1 /*
   2  * Copyright (c) 1998, 2016, 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 "ci/ciMethodData.hpp"
  27 #include "compiler/compileLog.hpp"
  28 #include "libadt/vectset.hpp"
  29 #include "memory/allocation.inline.hpp"
  30 #include "memory/resourceArea.hpp"
  31 #include "opto/addnode.hpp"
  32 #include "opto/callnode.hpp"
  33 #include "opto/connode.hpp"
  34 #include "opto/convertnode.hpp"
  35 #include "opto/divnode.hpp"
  36 #include "opto/idealGraphPrinter.hpp"
  37 #include "opto/loopnode.hpp"
  38 #include "opto/mulnode.hpp"
  39 #include "opto/rootnode.hpp"
  40 #include "opto/superword.hpp"
  41 
  42 //=============================================================================
  43 //------------------------------is_loop_iv-------------------------------------
  44 // Determine if a node is Counted loop induction variable.
  45 // The method is declared in node.hpp.
  46 const Node* Node::is_loop_iv() const {
  47   if (this->is_Phi() && !this->as_Phi()->is_copy() &&
  48       this->as_Phi()->region()->is_CountedLoop() &&
  49       this->as_Phi()->region()->as_CountedLoop()->phi() == this) {
  50     return this;
  51   } else {
  52     return NULL;
  53   }
  54 }
  55 
  56 //=============================================================================
  57 //------------------------------dump_spec--------------------------------------
  58 // Dump special per-node info
  59 #ifndef PRODUCT
  60 void LoopNode::dump_spec(outputStream *st) const {
  61   if (is_inner_loop()) st->print( "inner " );
  62   if (is_partial_peel_loop()) st->print( "partial_peel " );
  63   if (partial_peel_has_failed()) st->print( "partial_peel_failed " );
  64 }
  65 #endif
  66 
  67 //------------------------------is_valid_counted_loop-------------------------
  68 bool LoopNode::is_valid_counted_loop() const {
  69   if (is_CountedLoop()) {
  70     CountedLoopNode*    l  = as_CountedLoop();
  71     CountedLoopEndNode* le = l->loopexit();
  72     if (le != NULL &&
  73         le->proj_out(1 /* true */) == l->in(LoopNode::LoopBackControl)) {
  74       Node* phi  = l->phi();
  75       Node* exit = le->proj_out(0 /* false */);
  76       if (exit != NULL && exit->Opcode() == Op_IfFalse &&
  77           phi != NULL && phi->is_Phi() &&
  78           phi->in(LoopNode::LoopBackControl) == l->incr() &&
  79           le->loopnode() == l && le->stride_is_con()) {
  80         return true;
  81       }
  82     }
  83   }
  84   return false;
  85 }
  86 
  87 //------------------------------get_early_ctrl---------------------------------
  88 // Compute earliest legal control
  89 Node *PhaseIdealLoop::get_early_ctrl( Node *n ) {
  90   assert( !n->is_Phi() && !n->is_CFG(), "this code only handles data nodes" );
  91   uint i;
  92   Node *early;
  93   if (n->in(0) && !n->is_expensive()) {
  94     early = n->in(0);
  95     if (!early->is_CFG()) // Might be a non-CFG multi-def
  96       early = get_ctrl(early);        // So treat input as a straight data input
  97     i = 1;
  98   } else {
  99     early = get_ctrl(n->in(1));
 100     i = 2;
 101   }
 102   uint e_d = dom_depth(early);
 103   assert( early, "" );
 104   for (; i < n->req(); i++) {
 105     Node *cin = get_ctrl(n->in(i));
 106     assert( cin, "" );
 107     // Keep deepest dominator depth
 108     uint c_d = dom_depth(cin);
 109     if (c_d > e_d) {           // Deeper guy?
 110       early = cin;              // Keep deepest found so far
 111       e_d = c_d;
 112     } else if (c_d == e_d &&    // Same depth?
 113                early != cin) { // If not equal, must use slower algorithm
 114       // If same depth but not equal, one _must_ dominate the other
 115       // and we want the deeper (i.e., dominated) guy.
 116       Node *n1 = early;
 117       Node *n2 = cin;
 118       while (1) {
 119         n1 = idom(n1);          // Walk up until break cycle
 120         n2 = idom(n2);
 121         if (n1 == cin ||        // Walked early up to cin
 122             dom_depth(n2) < c_d)
 123           break;                // early is deeper; keep him
 124         if (n2 == early ||      // Walked cin up to early
 125             dom_depth(n1) < c_d) {
 126           early = cin;          // cin is deeper; keep him
 127           break;
 128         }
 129       }
 130       e_d = dom_depth(early);   // Reset depth register cache
 131     }
 132   }
 133 
 134   // Return earliest legal location
 135   assert(early == find_non_split_ctrl(early), "unexpected early control");
 136 
 137   if (n->is_expensive() && !_verify_only && !_verify_me) {
 138     assert(n->in(0), "should have control input");
 139     early = get_early_ctrl_for_expensive(n, early);
 140   }
 141 
 142   return early;
 143 }
 144 
 145 //------------------------------get_early_ctrl_for_expensive---------------------------------
 146 // Move node up the dominator tree as high as legal while still beneficial
 147 Node *PhaseIdealLoop::get_early_ctrl_for_expensive(Node *n, Node* earliest) {
 148   assert(n->in(0) && n->is_expensive(), "expensive node with control input here");
 149   assert(OptimizeExpensiveOps, "optimization off?");
 150 
 151   Node* ctl = n->in(0);
 152   assert(ctl->is_CFG(), "expensive input 0 must be cfg");
 153   uint min_dom_depth = dom_depth(earliest);
 154 #ifdef ASSERT
 155   if (!is_dominator(ctl, earliest) && !is_dominator(earliest, ctl)) {
 156     dump_bad_graph("Bad graph detected in get_early_ctrl_for_expensive", n, earliest, ctl);
 157     assert(false, "Bad graph detected in get_early_ctrl_for_expensive");
 158   }
 159 #endif
 160   if (dom_depth(ctl) < min_dom_depth) {
 161     return earliest;
 162   }
 163 
 164   while (1) {
 165     Node *next = ctl;
 166     // Moving the node out of a loop on the projection of a If
 167     // confuses loop predication. So once we hit a Loop in a If branch
 168     // that doesn't branch to an UNC, we stop. The code that process
 169     // expensive nodes will notice the loop and skip over it to try to
 170     // move the node further up.
 171     if (ctl->is_CountedLoop() && ctl->in(1) != NULL && ctl->in(1)->in(0) != NULL && ctl->in(1)->in(0)->is_If()) {
 172       if (!ctl->in(1)->as_Proj()->is_uncommon_trap_if_pattern(Deoptimization::Reason_none)) {
 173         break;
 174       }
 175       next = idom(ctl->in(1)->in(0));
 176     } else if (ctl->is_Proj()) {
 177       // We only move it up along a projection if the projection is
 178       // the single control projection for its parent: same code path,
 179       // if it's a If with UNC or fallthrough of a call.
 180       Node* parent_ctl = ctl->in(0);
 181       if (parent_ctl == NULL) {
 182         break;
 183       } else if (parent_ctl->is_CountedLoopEnd() && parent_ctl->as_CountedLoopEnd()->loopnode() != NULL) {
 184         next = parent_ctl->as_CountedLoopEnd()->loopnode()->init_control();
 185       } else if (parent_ctl->is_If()) {
 186         if (!ctl->as_Proj()->is_uncommon_trap_if_pattern(Deoptimization::Reason_none)) {
 187           break;
 188         }
 189         assert(idom(ctl) == parent_ctl, "strange");
 190         next = idom(parent_ctl);
 191       } else if (ctl->is_CatchProj()) {
 192         if (ctl->as_Proj()->_con != CatchProjNode::fall_through_index) {
 193           break;
 194         }
 195         assert(parent_ctl->in(0)->in(0)->is_Call(), "strange graph");
 196         next = parent_ctl->in(0)->in(0)->in(0);
 197       } else {
 198         // Check if parent control has a single projection (this
 199         // control is the only possible successor of the parent
 200         // control). If so, we can try to move the node above the
 201         // parent control.
 202         int nb_ctl_proj = 0;
 203         for (DUIterator_Fast imax, i = parent_ctl->fast_outs(imax); i < imax; i++) {
 204           Node *p = parent_ctl->fast_out(i);
 205           if (p->is_Proj() && p->is_CFG()) {
 206             nb_ctl_proj++;
 207             if (nb_ctl_proj > 1) {
 208               break;
 209             }
 210           }
 211         }
 212 
 213         if (nb_ctl_proj > 1) {
 214           break;
 215         }
 216         assert(parent_ctl->is_Start() || parent_ctl->is_MemBar() || parent_ctl->is_Call(), "unexpected node");
 217         assert(idom(ctl) == parent_ctl, "strange");
 218         next = idom(parent_ctl);
 219       }
 220     } else {
 221       next = idom(ctl);
 222     }
 223     if (next->is_Root() || next->is_Start() || dom_depth(next) < min_dom_depth) {
 224       break;
 225     }
 226     ctl = next;
 227   }
 228 
 229   if (ctl != n->in(0)) {
 230     _igvn.replace_input_of(n, 0, ctl);
 231     _igvn.hash_insert(n);
 232   }
 233 
 234   return ctl;
 235 }
 236 
 237 
 238 //------------------------------set_early_ctrl---------------------------------
 239 // Set earliest legal control
 240 void PhaseIdealLoop::set_early_ctrl( Node *n ) {
 241   Node *early = get_early_ctrl(n);
 242 
 243   // Record earliest legal location
 244   set_ctrl(n, early);
 245 }
 246 
 247 //------------------------------set_subtree_ctrl-------------------------------
 248 // set missing _ctrl entries on new nodes
 249 void PhaseIdealLoop::set_subtree_ctrl( Node *n ) {
 250   // Already set?  Get out.
 251   if( _nodes[n->_idx] ) return;
 252   // Recursively set _nodes array to indicate where the Node goes
 253   uint i;
 254   for( i = 0; i < n->req(); ++i ) {
 255     Node *m = n->in(i);
 256     if( m && m != C->root() )
 257       set_subtree_ctrl( m );
 258   }
 259 
 260   // Fixup self
 261   set_early_ctrl( n );
 262 }
 263 
 264 //------------------------------is_counted_loop--------------------------------
 265 bool PhaseIdealLoop::is_counted_loop( Node *x, IdealLoopTree *loop ) {
 266   PhaseGVN *gvn = &_igvn;
 267 
 268   // Counted loop head must be a good RegionNode with only 3 not NULL
 269   // control input edges: Self, Entry, LoopBack.
 270   if (x->in(LoopNode::Self) == NULL || x->req() != 3 || loop->_irreducible) {
 271     return false;
 272   }
 273   Node *init_control = x->in(LoopNode::EntryControl);
 274   Node *back_control = x->in(LoopNode::LoopBackControl);
 275   if (init_control == NULL || back_control == NULL)    // Partially dead
 276     return false;
 277   // Must also check for TOP when looking for a dead loop
 278   if (init_control->is_top() || back_control->is_top())
 279     return false;
 280 
 281   // Allow funny placement of Safepoint
 282   if (back_control->Opcode() == Op_SafePoint) {
 283     if (UseCountedLoopSafepoints) {
 284       // Leaving the safepoint on the backedge and creating a
 285       // CountedLoop will confuse optimizations. We can't move the
 286       // safepoint around because its jvm state wouldn't match a new
 287       // location. Give up on that loop.
 288       return false;
 289     }
 290     back_control = back_control->in(TypeFunc::Control);
 291   }
 292 
 293   // Controlling test for loop
 294   Node *iftrue = back_control;
 295   uint iftrue_op = iftrue->Opcode();
 296   if (iftrue_op != Op_IfTrue &&
 297       iftrue_op != Op_IfFalse)
 298     // I have a weird back-control.  Probably the loop-exit test is in
 299     // the middle of the loop and I am looking at some trailing control-flow
 300     // merge point.  To fix this I would have to partially peel the loop.
 301     return false; // Obscure back-control
 302 
 303   // Get boolean guarding loop-back test
 304   Node *iff = iftrue->in(0);
 305   if (get_loop(iff) != loop || !iff->in(1)->is_Bool())
 306     return false;
 307   BoolNode *test = iff->in(1)->as_Bool();
 308   BoolTest::mask bt = test->_test._test;
 309   float cl_prob = iff->as_If()->_prob;
 310   if (iftrue_op == Op_IfFalse) {
 311     bt = BoolTest(bt).negate();
 312     cl_prob = 1.0 - cl_prob;
 313   }
 314   // Get backedge compare
 315   Node *cmp = test->in(1);
 316   int cmp_op = cmp->Opcode();
 317   if (cmp_op != Op_CmpI)
 318     return false;                // Avoid pointer & float compares
 319 
 320   // Find the trip-counter increment & limit.  Limit must be loop invariant.
 321   Node *incr  = cmp->in(1);
 322   Node *limit = cmp->in(2);
 323 
 324   // ---------
 325   // need 'loop()' test to tell if limit is loop invariant
 326   // ---------
 327 
 328   if (!is_member(loop, get_ctrl(incr))) { // Swapped trip counter and limit?
 329     Node *tmp = incr;            // Then reverse order into the CmpI
 330     incr = limit;
 331     limit = tmp;
 332     bt = BoolTest(bt).commute(); // And commute the exit test
 333   }
 334   if (is_member(loop, get_ctrl(limit))) // Limit must be loop-invariant
 335     return false;
 336   if (!is_member(loop, get_ctrl(incr))) // Trip counter must be loop-variant
 337     return false;
 338 
 339   Node* phi_incr = NULL;
 340   // Trip-counter increment must be commutative & associative.
 341   if (incr->Opcode() == Op_CastII) {
 342     incr = incr->in(1);
 343   }
 344   if (incr->is_Phi()) {
 345     if (incr->as_Phi()->region() != x || incr->req() != 3)
 346       return false; // Not simple trip counter expression
 347     phi_incr = incr;
 348     incr = phi_incr->in(LoopNode::LoopBackControl); // Assume incr is on backedge of Phi
 349     if (!is_member(loop, get_ctrl(incr))) // Trip counter must be loop-variant
 350       return false;
 351   }
 352 
 353   Node* trunc1 = NULL;
 354   Node* trunc2 = NULL;
 355   const TypeInt* iv_trunc_t = NULL;
 356   if (!(incr = CountedLoopNode::match_incr_with_optional_truncation(incr, &trunc1, &trunc2, &iv_trunc_t))) {
 357     return false; // Funny increment opcode
 358   }
 359   assert(incr->Opcode() == Op_AddI, "wrong increment code");
 360 
 361   // Get merge point
 362   Node *xphi = incr->in(1);
 363   Node *stride = incr->in(2);
 364   if (!stride->is_Con()) {     // Oops, swap these
 365     if (!xphi->is_Con())       // Is the other guy a constant?
 366       return false;             // Nope, unknown stride, bail out
 367     Node *tmp = xphi;           // 'incr' is commutative, so ok to swap
 368     xphi = stride;
 369     stride = tmp;
 370   }
 371   if (xphi->Opcode() == Op_CastII) {
 372     xphi = xphi->in(1);
 373   }
 374   // Stride must be constant
 375   int stride_con = stride->get_int();
 376   if (stride_con == 0)
 377     return false; // missed some peephole opt
 378 
 379   if (!xphi->is_Phi())
 380     return false; // Too much math on the trip counter
 381   if (phi_incr != NULL && phi_incr != xphi)
 382     return false;
 383   PhiNode *phi = xphi->as_Phi();
 384 
 385   // Phi must be of loop header; backedge must wrap to increment
 386   if (phi->region() != x)
 387     return false;
 388   if (trunc1 == NULL && phi->in(LoopNode::LoopBackControl) != incr ||
 389       trunc1 != NULL && phi->in(LoopNode::LoopBackControl) != trunc1) {
 390     return false;
 391   }
 392   Node *init_trip = phi->in(LoopNode::EntryControl);
 393 
 394   // If iv trunc type is smaller than int, check for possible wrap.
 395   if (!TypeInt::INT->higher_equal(iv_trunc_t)) {
 396     assert(trunc1 != NULL, "must have found some truncation");
 397 
 398     // Get a better type for the phi (filtered thru if's)
 399     const TypeInt* phi_ft = filtered_type(phi);
 400 
 401     // Can iv take on a value that will wrap?
 402     //
 403     // Ensure iv's limit is not within "stride" of the wrap value.
 404     //
 405     // Example for "short" type
 406     //    Truncation ensures value is in the range -32768..32767 (iv_trunc_t)
 407     //    If the stride is +10, then the last value of the induction
 408     //    variable before the increment (phi_ft->_hi) must be
 409     //    <= 32767 - 10 and (phi_ft->_lo) must be >= -32768 to
 410     //    ensure no truncation occurs after the increment.
 411 
 412     if (stride_con > 0) {
 413       if (iv_trunc_t->_hi - phi_ft->_hi < stride_con ||
 414           iv_trunc_t->_lo > phi_ft->_lo) {
 415         return false;  // truncation may occur
 416       }
 417     } else if (stride_con < 0) {
 418       if (iv_trunc_t->_lo - phi_ft->_lo > stride_con ||
 419           iv_trunc_t->_hi < phi_ft->_hi) {
 420         return false;  // truncation may occur
 421       }
 422     }
 423     // No possibility of wrap so truncation can be discarded
 424     // Promote iv type to Int
 425   } else {
 426     assert(trunc1 == NULL && trunc2 == NULL, "no truncation for int");
 427   }
 428 
 429   // If the condition is inverted and we will be rolling
 430   // through MININT to MAXINT, then bail out.
 431   if (bt == BoolTest::eq || // Bail out, but this loop trips at most twice!
 432       // Odd stride
 433       bt == BoolTest::ne && stride_con != 1 && stride_con != -1 ||
 434       // Count down loop rolls through MAXINT
 435       (bt == BoolTest::le || bt == BoolTest::lt) && stride_con < 0 ||
 436       // Count up loop rolls through MININT
 437       (bt == BoolTest::ge || bt == BoolTest::gt) && stride_con > 0) {
 438     return false; // Bail out
 439   }
 440 
 441   const TypeInt* init_t = gvn->type(init_trip)->is_int();
 442   const TypeInt* limit_t = gvn->type(limit)->is_int();
 443 
 444   if (stride_con > 0) {
 445     jlong init_p = (jlong)init_t->_lo + stride_con;
 446     if (init_p > (jlong)max_jint || init_p > (jlong)limit_t->_hi)
 447       return false; // cyclic loop or this loop trips only once
 448   } else {
 449     jlong init_p = (jlong)init_t->_hi + stride_con;
 450     if (init_p < (jlong)min_jint || init_p < (jlong)limit_t->_lo)
 451       return false; // cyclic loop or this loop trips only once
 452   }
 453 
 454   if (phi_incr != NULL) {
 455     // check if there is a possiblity of IV overflowing after the first increment
 456     if (stride_con > 0) {
 457       if (init_t->_hi > max_jint - stride_con) {
 458         return false;
 459       }
 460     } else {
 461       if (init_t->_lo < min_jint - stride_con) {
 462         return false;
 463       }
 464     }
 465   }
 466 
 467   // =================================================
 468   // ---- SUCCESS!   Found A Trip-Counted Loop!  -----
 469   //
 470   assert(x->Opcode() == Op_Loop, "regular loops only");
 471   C->print_method(PHASE_BEFORE_CLOOPS, 3);
 472 
 473   Node *hook = new Node(6);
 474 
 475   // ===================================================
 476   // Generate loop limit check to avoid integer overflow
 477   // in cases like next (cyclic loops):
 478   //
 479   // for (i=0; i <= max_jint; i++) {}
 480   // for (i=0; i <  max_jint; i+=2) {}
 481   //
 482   //
 483   // Limit check predicate depends on the loop test:
 484   //
 485   // for(;i != limit; i++)       --> limit <= (max_jint)
 486   // for(;i <  limit; i+=stride) --> limit <= (max_jint - stride + 1)
 487   // for(;i <= limit; i+=stride) --> limit <= (max_jint - stride    )
 488   //
 489 
 490   // Check if limit is excluded to do more precise int overflow check.
 491   bool incl_limit = (bt == BoolTest::le || bt == BoolTest::ge);
 492   int stride_m  = stride_con - (incl_limit ? 0 : (stride_con > 0 ? 1 : -1));
 493 
 494   // If compare points directly to the phi we need to adjust
 495   // the compare so that it points to the incr. Limit have
 496   // to be adjusted to keep trip count the same and the
 497   // adjusted limit should be checked for int overflow.
 498   if (phi_incr != NULL) {
 499     stride_m  += stride_con;
 500   }
 501 
 502   if (limit->is_Con()) {
 503     int limit_con = limit->get_int();
 504     if ((stride_con > 0 && limit_con > (max_jint - stride_m)) ||
 505         (stride_con < 0 && limit_con < (min_jint - stride_m))) {
 506       // Bailout: it could be integer overflow.
 507       return false;
 508     }
 509   } else if ((stride_con > 0 && limit_t->_hi <= (max_jint - stride_m)) ||
 510              (stride_con < 0 && limit_t->_lo >= (min_jint - stride_m))) {
 511       // Limit's type may satisfy the condition, for example,
 512       // when it is an array length.
 513   } else {
 514     // Generate loop's limit check.
 515     // Loop limit check predicate should be near the loop.
 516     ProjNode *limit_check_proj = find_predicate_insertion_point(init_control, Deoptimization::Reason_loop_limit_check);
 517     if (!limit_check_proj) {
 518       // The limit check predicate is not generated if this method trapped here before.
 519 #ifdef ASSERT
 520       if (TraceLoopLimitCheck) {
 521         tty->print("missing loop limit check:");
 522         loop->dump_head();
 523         x->dump(1);
 524       }
 525 #endif
 526       return false;
 527     }
 528 
 529     IfNode* check_iff = limit_check_proj->in(0)->as_If();
 530     Node* cmp_limit;
 531     Node* bol;
 532 
 533     if (stride_con > 0) {
 534       cmp_limit = new CmpINode(limit, _igvn.intcon(max_jint - stride_m));
 535       bol = new BoolNode(cmp_limit, BoolTest::le);
 536     } else {
 537       cmp_limit = new CmpINode(limit, _igvn.intcon(min_jint - stride_m));
 538       bol = new BoolNode(cmp_limit, BoolTest::ge);
 539     }
 540     cmp_limit = _igvn.register_new_node_with_optimizer(cmp_limit);
 541     bol = _igvn.register_new_node_with_optimizer(bol);
 542     set_subtree_ctrl(bol);
 543 
 544     // Replace condition in original predicate but preserve Opaque node
 545     // so that previous predicates could be found.
 546     assert(check_iff->in(1)->Opcode() == Op_Conv2B &&
 547            check_iff->in(1)->in(1)->Opcode() == Op_Opaque1, "");
 548     Node* opq = check_iff->in(1)->in(1);
 549     _igvn.replace_input_of(opq, 1, bol);
 550     // Update ctrl.
 551     set_ctrl(opq, check_iff->in(0));
 552     set_ctrl(check_iff->in(1), check_iff->in(0));
 553 
 554 #ifndef PRODUCT
 555     // report that the loop predication has been actually performed
 556     // for this loop
 557     if (TraceLoopLimitCheck) {
 558       tty->print_cr("Counted Loop Limit Check generated:");
 559       debug_only( bol->dump(2); )
 560     }
 561 #endif
 562   }
 563 
 564   if (phi_incr != NULL) {
 565     // If compare points directly to the phi we need to adjust
 566     // the compare so that it points to the incr. Limit have
 567     // to be adjusted to keep trip count the same and we
 568     // should avoid int overflow.
 569     //
 570     //   i = init; do {} while(i++ < limit);
 571     // is converted to
 572     //   i = init; do {} while(++i < limit+1);
 573     //
 574     limit = gvn->transform(new AddINode(limit, stride));
 575   }
 576 
 577   // Now we need to canonicalize loop condition.
 578   if (bt == BoolTest::ne) {
 579     assert(stride_con == 1 || stride_con == -1, "simple increment only");
 580     // 'ne' can be replaced with 'lt' only when init < limit.
 581     if (stride_con > 0 && init_t->_hi < limit_t->_lo)
 582       bt = BoolTest::lt;
 583     // 'ne' can be replaced with 'gt' only when init > limit.
 584     if (stride_con < 0 && init_t->_lo > limit_t->_hi)
 585       bt = BoolTest::gt;
 586   }
 587 
 588   if (incl_limit) {
 589     // The limit check guaranties that 'limit <= (max_jint - stride)' so
 590     // we can convert 'i <= limit' to 'i < limit+1' since stride != 0.
 591     //
 592     Node* one = (stride_con > 0) ? gvn->intcon( 1) : gvn->intcon(-1);
 593     limit = gvn->transform(new AddINode(limit, one));
 594     if (bt == BoolTest::le)
 595       bt = BoolTest::lt;
 596     else if (bt == BoolTest::ge)
 597       bt = BoolTest::gt;
 598     else
 599       ShouldNotReachHere();
 600   }
 601   set_subtree_ctrl( limit );
 602 
 603   if (!UseCountedLoopSafepoints) {
 604     // Check for SafePoint on backedge and remove
 605     Node *sfpt = x->in(LoopNode::LoopBackControl);
 606     if (sfpt->Opcode() == Op_SafePoint && is_deleteable_safept(sfpt)) {
 607       lazy_replace( sfpt, iftrue );
 608       if (loop->_safepts != NULL) {
 609         loop->_safepts->yank(sfpt);
 610       }
 611       loop->_tail = iftrue;
 612     }
 613   }
 614 
 615   // Build a canonical trip test.
 616   // Clone code, as old values may be in use.
 617   incr = incr->clone();
 618   incr->set_req(1,phi);
 619   incr->set_req(2,stride);
 620   incr = _igvn.register_new_node_with_optimizer(incr);
 621   set_early_ctrl( incr );
 622   _igvn.rehash_node_delayed(phi);
 623   phi->set_req_X( LoopNode::LoopBackControl, incr, &_igvn );
 624 
 625   // If phi type is more restrictive than Int, raise to
 626   // Int to prevent (almost) infinite recursion in igvn
 627   // which can only handle integer types for constants or minint..maxint.
 628   if (!TypeInt::INT->higher_equal(phi->bottom_type())) {
 629     Node* nphi = PhiNode::make(phi->in(0), phi->in(LoopNode::EntryControl), TypeInt::INT);
 630     nphi->set_req(LoopNode::LoopBackControl, phi->in(LoopNode::LoopBackControl));
 631     nphi = _igvn.register_new_node_with_optimizer(nphi);
 632     set_ctrl(nphi, get_ctrl(phi));
 633     _igvn.replace_node(phi, nphi);
 634     phi = nphi->as_Phi();
 635   }
 636   cmp = cmp->clone();
 637   cmp->set_req(1,incr);
 638   cmp->set_req(2,limit);
 639   cmp = _igvn.register_new_node_with_optimizer(cmp);
 640   set_ctrl(cmp, iff->in(0));
 641 
 642   test = test->clone()->as_Bool();
 643   (*(BoolTest*)&test->_test)._test = bt;
 644   test->set_req(1,cmp);
 645   _igvn.register_new_node_with_optimizer(test);
 646   set_ctrl(test, iff->in(0));
 647 
 648   // Replace the old IfNode with a new LoopEndNode
 649   Node *lex = _igvn.register_new_node_with_optimizer(new CountedLoopEndNode( iff->in(0), test, cl_prob, iff->as_If()->_fcnt ));
 650   IfNode *le = lex->as_If();
 651   uint dd = dom_depth(iff);
 652   set_idom(le, le->in(0), dd); // Update dominance for loop exit
 653   set_loop(le, loop);
 654 
 655   // Get the loop-exit control
 656   Node *iffalse = iff->as_If()->proj_out(!(iftrue_op == Op_IfTrue));
 657 
 658   // Need to swap loop-exit and loop-back control?
 659   if (iftrue_op == Op_IfFalse) {
 660     Node *ift2=_igvn.register_new_node_with_optimizer(new IfTrueNode (le));
 661     Node *iff2=_igvn.register_new_node_with_optimizer(new IfFalseNode(le));
 662 
 663     loop->_tail = back_control = ift2;
 664     set_loop(ift2, loop);
 665     set_loop(iff2, get_loop(iffalse));
 666 
 667     // Lazy update of 'get_ctrl' mechanism.
 668     lazy_replace(iffalse, iff2);
 669     lazy_replace(iftrue,  ift2);
 670 
 671     // Swap names
 672     iffalse = iff2;
 673     iftrue  = ift2;
 674   } else {
 675     _igvn.rehash_node_delayed(iffalse);
 676     _igvn.rehash_node_delayed(iftrue);
 677     iffalse->set_req_X( 0, le, &_igvn );
 678     iftrue ->set_req_X( 0, le, &_igvn );
 679   }
 680 
 681   set_idom(iftrue,  le, dd+1);
 682   set_idom(iffalse, le, dd+1);
 683   assert(iff->outcnt() == 0, "should be dead now");
 684   lazy_replace( iff, le ); // fix 'get_ctrl'
 685 
 686   // Now setup a new CountedLoopNode to replace the existing LoopNode
 687   CountedLoopNode *l = new CountedLoopNode(init_control, back_control);
 688   l->set_unswitch_count(x->as_Loop()->unswitch_count()); // Preserve
 689   // The following assert is approximately true, and defines the intention
 690   // of can_be_counted_loop.  It fails, however, because phase->type
 691   // is not yet initialized for this loop and its parts.
 692   //assert(l->can_be_counted_loop(this), "sanity");
 693   _igvn.register_new_node_with_optimizer(l);
 694   set_loop(l, loop);
 695   loop->_head = l;
 696   // Fix all data nodes placed at the old loop head.
 697   // Uses the lazy-update mechanism of 'get_ctrl'.
 698   lazy_replace( x, l );
 699   set_idom(l, init_control, dom_depth(x));
 700 
 701   if (!UseCountedLoopSafepoints) {
 702     // Check for immediately preceding SafePoint and remove
 703     Node *sfpt2 = le->in(0);
 704     if (sfpt2->Opcode() == Op_SafePoint && is_deleteable_safept(sfpt2)) {
 705       lazy_replace( sfpt2, sfpt2->in(TypeFunc::Control));
 706       if (loop->_safepts != NULL) {
 707         loop->_safepts->yank(sfpt2);
 708       }
 709     }
 710   }
 711 
 712   // Free up intermediate goo
 713   _igvn.remove_dead_node(hook);
 714 
 715 #ifdef ASSERT
 716   assert(l->is_valid_counted_loop(), "counted loop shape is messed up");
 717   assert(l == loop->_head && l->phi() == phi && l->loopexit() == lex, "" );
 718 #endif
 719 #ifndef PRODUCT
 720   if (TraceLoopOpts) {
 721     tty->print("Counted      ");
 722     loop->dump_head();
 723   }
 724 #endif
 725 
 726   C->print_method(PHASE_AFTER_CLOOPS, 3);
 727 
 728   // Capture bounds of the loop in the induction variable Phi before
 729   // subsequent transformation (iteration splitting) obscures the
 730   // bounds
 731   l->phi()->as_Phi()->set_type(l->phi()->Value(&_igvn));
 732 
 733   return true;
 734 }
 735 
 736 //----------------------exact_limit-------------------------------------------
 737 Node* PhaseIdealLoop::exact_limit( IdealLoopTree *loop ) {
 738   assert(loop->_head->is_CountedLoop(), "");
 739   CountedLoopNode *cl = loop->_head->as_CountedLoop();
 740   assert(cl->is_valid_counted_loop(), "");
 741 
 742   if (ABS(cl->stride_con()) == 1 ||
 743       cl->limit()->Opcode() == Op_LoopLimit) {
 744     // Old code has exact limit (it could be incorrect in case of int overflow).
 745     // Loop limit is exact with stride == 1. And loop may already have exact limit.
 746     return cl->limit();
 747   }
 748   Node *limit = NULL;
 749 #ifdef ASSERT
 750   BoolTest::mask bt = cl->loopexit()->test_trip();
 751   assert(bt == BoolTest::lt || bt == BoolTest::gt, "canonical test is expected");
 752 #endif
 753   if (cl->has_exact_trip_count()) {
 754     // Simple case: loop has constant boundaries.
 755     // Use jlongs to avoid integer overflow.
 756     int stride_con = cl->stride_con();
 757     jlong  init_con = cl->init_trip()->get_int();
 758     jlong limit_con = cl->limit()->get_int();
 759     julong trip_cnt = cl->trip_count();
 760     jlong final_con = init_con + trip_cnt*stride_con;
 761     int final_int = (int)final_con;
 762     // The final value should be in integer range since the loop
 763     // is counted and the limit was checked for overflow.
 764     assert(final_con == (jlong)final_int, "final value should be integer");
 765     limit = _igvn.intcon(final_int);
 766   } else {
 767     // Create new LoopLimit node to get exact limit (final iv value).
 768     limit = new LoopLimitNode(C, cl->init_trip(), cl->limit(), cl->stride());
 769     register_new_node(limit, cl->in(LoopNode::EntryControl));
 770   }
 771   assert(limit != NULL, "sanity");
 772   return limit;
 773 }
 774 
 775 //------------------------------Ideal------------------------------------------
 776 // Return a node which is more "ideal" than the current node.
 777 // Attempt to convert into a counted-loop.
 778 Node *LoopNode::Ideal(PhaseGVN *phase, bool can_reshape) {
 779   if (!can_be_counted_loop(phase)) {
 780     phase->C->set_major_progress();
 781   }
 782   return RegionNode::Ideal(phase, can_reshape);
 783 }
 784 
 785 
 786 //=============================================================================
 787 //------------------------------Ideal------------------------------------------
 788 // Return a node which is more "ideal" than the current node.
 789 // Attempt to convert into a counted-loop.
 790 Node *CountedLoopNode::Ideal(PhaseGVN *phase, bool can_reshape) {
 791   return RegionNode::Ideal(phase, can_reshape);
 792 }
 793 
 794 //------------------------------dump_spec--------------------------------------
 795 // Dump special per-node info
 796 #ifndef PRODUCT
 797 void CountedLoopNode::dump_spec(outputStream *st) const {
 798   LoopNode::dump_spec(st);
 799   if (stride_is_con()) {
 800     st->print("stride: %d ",stride_con());
 801   }
 802   if (is_pre_loop ()) st->print("pre of N%d" , _main_idx);
 803   if (is_main_loop()) st->print("main of N%d", _idx);
 804   if (is_post_loop()) st->print("post of N%d", _main_idx);
 805 }
 806 #endif
 807 
 808 //=============================================================================
 809 int CountedLoopEndNode::stride_con() const {
 810   return stride()->bottom_type()->is_int()->get_con();
 811 }
 812 
 813 //=============================================================================
 814 //------------------------------Value-----------------------------------------
 815 const Type* LoopLimitNode::Value(PhaseGVN* phase) const {
 816   const Type* init_t   = phase->type(in(Init));
 817   const Type* limit_t  = phase->type(in(Limit));
 818   const Type* stride_t = phase->type(in(Stride));
 819   // Either input is TOP ==> the result is TOP
 820   if (init_t   == Type::TOP) return Type::TOP;
 821   if (limit_t  == Type::TOP) return Type::TOP;
 822   if (stride_t == Type::TOP) return Type::TOP;
 823 
 824   int stride_con = stride_t->is_int()->get_con();
 825   if (stride_con == 1)
 826     return NULL;  // Identity
 827 
 828   if (init_t->is_int()->is_con() && limit_t->is_int()->is_con()) {
 829     // Use jlongs to avoid integer overflow.
 830     jlong init_con   =  init_t->is_int()->get_con();
 831     jlong limit_con  = limit_t->is_int()->get_con();
 832     int  stride_m   = stride_con - (stride_con > 0 ? 1 : -1);
 833     jlong trip_count = (limit_con - init_con + stride_m)/stride_con;
 834     jlong final_con  = init_con + stride_con*trip_count;
 835     int final_int = (int)final_con;
 836     // The final value should be in integer range since the loop
 837     // is counted and the limit was checked for overflow.
 838     assert(final_con == (jlong)final_int, "final value should be integer");
 839     return TypeInt::make(final_int);
 840   }
 841 
 842   return bottom_type(); // TypeInt::INT
 843 }
 844 
 845 //------------------------------Ideal------------------------------------------
 846 // Return a node which is more "ideal" than the current node.
 847 Node *LoopLimitNode::Ideal(PhaseGVN *phase, bool can_reshape) {
 848   if (phase->type(in(Init))   == Type::TOP ||
 849       phase->type(in(Limit))  == Type::TOP ||
 850       phase->type(in(Stride)) == Type::TOP)
 851     return NULL;  // Dead
 852 
 853   int stride_con = phase->type(in(Stride))->is_int()->get_con();
 854   if (stride_con == 1)
 855     return NULL;  // Identity
 856 
 857   if (in(Init)->is_Con() && in(Limit)->is_Con())
 858     return NULL;  // Value
 859 
 860   // Delay following optimizations until all loop optimizations
 861   // done to keep Ideal graph simple.
 862   if (!can_reshape || phase->C->major_progress())
 863     return NULL;
 864 
 865   const TypeInt* init_t  = phase->type(in(Init) )->is_int();
 866   const TypeInt* limit_t = phase->type(in(Limit))->is_int();
 867   int stride_p;
 868   jlong lim, ini;
 869   julong max;
 870   if (stride_con > 0) {
 871     stride_p = stride_con;
 872     lim = limit_t->_hi;
 873     ini = init_t->_lo;
 874     max = (julong)max_jint;
 875   } else {
 876     stride_p = -stride_con;
 877     lim = init_t->_hi;
 878     ini = limit_t->_lo;
 879     max = (julong)min_jint;
 880   }
 881   julong range = lim - ini + stride_p;
 882   if (range <= max) {
 883     // Convert to integer expression if it is not overflow.
 884     Node* stride_m = phase->intcon(stride_con - (stride_con > 0 ? 1 : -1));
 885     Node *range = phase->transform(new SubINode(in(Limit), in(Init)));
 886     Node *bias  = phase->transform(new AddINode(range, stride_m));
 887     Node *trip  = phase->transform(new DivINode(0, bias, in(Stride)));
 888     Node *span  = phase->transform(new MulINode(trip, in(Stride)));
 889     return new AddINode(span, in(Init)); // exact limit
 890   }
 891 
 892   if (is_power_of_2(stride_p) ||                // divisor is 2^n
 893       !Matcher::has_match_rule(Op_LoopLimit)) { // or no specialized Mach node?
 894     // Convert to long expression to avoid integer overflow
 895     // and let igvn optimizer convert this division.
 896     //
 897     Node*   init   = phase->transform( new ConvI2LNode(in(Init)));
 898     Node*  limit   = phase->transform( new ConvI2LNode(in(Limit)));
 899     Node* stride   = phase->longcon(stride_con);
 900     Node* stride_m = phase->longcon(stride_con - (stride_con > 0 ? 1 : -1));
 901 
 902     Node *range = phase->transform(new SubLNode(limit, init));
 903     Node *bias  = phase->transform(new AddLNode(range, stride_m));
 904     Node *span;
 905     if (stride_con > 0 && is_power_of_2(stride_p)) {
 906       // bias >= 0 if stride >0, so if stride is 2^n we can use &(-stride)
 907       // and avoid generating rounding for division. Zero trip guard should
 908       // guarantee that init < limit but sometimes the guard is missing and
 909       // we can get situation when init > limit. Note, for the empty loop
 910       // optimization zero trip guard is generated explicitly which leaves
 911       // only RCE predicate where exact limit is used and the predicate
 912       // will simply fail forcing recompilation.
 913       Node* neg_stride   = phase->longcon(-stride_con);
 914       span = phase->transform(new AndLNode(bias, neg_stride));
 915     } else {
 916       Node *trip  = phase->transform(new DivLNode(0, bias, stride));
 917       span = phase->transform(new MulLNode(trip, stride));
 918     }
 919     // Convert back to int
 920     Node *span_int = phase->transform(new ConvL2INode(span));
 921     return new AddINode(span_int, in(Init)); // exact limit
 922   }
 923 
 924   return NULL;    // No progress
 925 }
 926 
 927 //------------------------------Identity---------------------------------------
 928 // If stride == 1 return limit node.
 929 Node* LoopLimitNode::Identity(PhaseGVN* phase) {
 930   int stride_con = phase->type(in(Stride))->is_int()->get_con();
 931   if (stride_con == 1 || stride_con == -1)
 932     return in(Limit);
 933   return this;
 934 }
 935 
 936 //=============================================================================
 937 //----------------------match_incr_with_optional_truncation--------------------
 938 // Match increment with optional truncation:
 939 // CHAR: (i+1)&0x7fff, BYTE: ((i+1)<<8)>>8, or SHORT: ((i+1)<<16)>>16
 940 // Return NULL for failure. Success returns the increment node.
 941 Node* CountedLoopNode::match_incr_with_optional_truncation(
 942                       Node* expr, Node** trunc1, Node** trunc2, const TypeInt** trunc_type) {
 943   // Quick cutouts:
 944   if (expr == NULL || expr->req() != 3)  return NULL;
 945 
 946   Node *t1 = NULL;
 947   Node *t2 = NULL;
 948   const TypeInt* trunc_t = TypeInt::INT;
 949   Node* n1 = expr;
 950   int   n1op = n1->Opcode();
 951 
 952   // Try to strip (n1 & M) or (n1 << N >> N) from n1.
 953   if (n1op == Op_AndI &&
 954       n1->in(2)->is_Con() &&
 955       n1->in(2)->bottom_type()->is_int()->get_con() == 0x7fff) {
 956     // %%% This check should match any mask of 2**K-1.
 957     t1 = n1;
 958     n1 = t1->in(1);
 959     n1op = n1->Opcode();
 960     trunc_t = TypeInt::CHAR;
 961   } else if (n1op == Op_RShiftI &&
 962              n1->in(1) != NULL &&
 963              n1->in(1)->Opcode() == Op_LShiftI &&
 964              n1->in(2) == n1->in(1)->in(2) &&
 965              n1->in(2)->is_Con()) {
 966     jint shift = n1->in(2)->bottom_type()->is_int()->get_con();
 967     // %%% This check should match any shift in [1..31].
 968     if (shift == 16 || shift == 8) {
 969       t1 = n1;
 970       t2 = t1->in(1);
 971       n1 = t2->in(1);
 972       n1op = n1->Opcode();
 973       if (shift == 16) {
 974         trunc_t = TypeInt::SHORT;
 975       } else if (shift == 8) {
 976         trunc_t = TypeInt::BYTE;
 977       }
 978     }
 979   }
 980 
 981   // If (maybe after stripping) it is an AddI, we won:
 982   if (n1op == Op_AddI) {
 983     *trunc1 = t1;
 984     *trunc2 = t2;
 985     *trunc_type = trunc_t;
 986     return n1;
 987   }
 988 
 989   // failed
 990   return NULL;
 991 }
 992 
 993 
 994 //------------------------------filtered_type--------------------------------
 995 // Return a type based on condition control flow
 996 // A successful return will be a type that is restricted due
 997 // to a series of dominating if-tests, such as:
 998 //    if (i < 10) {
 999 //       if (i > 0) {
1000 //          here: "i" type is [1..10)
1001 //       }
1002 //    }
1003 // or a control flow merge
1004 //    if (i < 10) {
1005 //       do {
1006 //          phi( , ) -- at top of loop type is [min_int..10)
1007 //         i = ?
1008 //       } while ( i < 10)
1009 //
1010 const TypeInt* PhaseIdealLoop::filtered_type( Node *n, Node* n_ctrl) {
1011   assert(n && n->bottom_type()->is_int(), "must be int");
1012   const TypeInt* filtered_t = NULL;
1013   if (!n->is_Phi()) {
1014     assert(n_ctrl != NULL || n_ctrl == C->top(), "valid control");
1015     filtered_t = filtered_type_from_dominators(n, n_ctrl);
1016 
1017   } else {
1018     Node* phi    = n->as_Phi();
1019     Node* region = phi->in(0);
1020     assert(n_ctrl == NULL || n_ctrl == region, "ctrl parameter must be region");
1021     if (region && region != C->top()) {
1022       for (uint i = 1; i < phi->req(); i++) {
1023         Node* val   = phi->in(i);
1024         Node* use_c = region->in(i);
1025         const TypeInt* val_t = filtered_type_from_dominators(val, use_c);
1026         if (val_t != NULL) {
1027           if (filtered_t == NULL) {
1028             filtered_t = val_t;
1029           } else {
1030             filtered_t = filtered_t->meet(val_t)->is_int();
1031           }
1032         }
1033       }
1034     }
1035   }
1036   const TypeInt* n_t = _igvn.type(n)->is_int();
1037   if (filtered_t != NULL) {
1038     n_t = n_t->join(filtered_t)->is_int();
1039   }
1040   return n_t;
1041 }
1042 
1043 
1044 //------------------------------filtered_type_from_dominators--------------------------------
1045 // Return a possibly more restrictive type for val based on condition control flow of dominators
1046 const TypeInt* PhaseIdealLoop::filtered_type_from_dominators( Node* val, Node *use_ctrl) {
1047   if (val->is_Con()) {
1048      return val->bottom_type()->is_int();
1049   }
1050   uint if_limit = 10; // Max number of dominating if's visited
1051   const TypeInt* rtn_t = NULL;
1052 
1053   if (use_ctrl && use_ctrl != C->top()) {
1054     Node* val_ctrl = get_ctrl(val);
1055     uint val_dom_depth = dom_depth(val_ctrl);
1056     Node* pred = use_ctrl;
1057     uint if_cnt = 0;
1058     while (if_cnt < if_limit) {
1059       if ((pred->Opcode() == Op_IfTrue || pred->Opcode() == Op_IfFalse)) {
1060         if_cnt++;
1061         const TypeInt* if_t = IfNode::filtered_int_type(&_igvn, val, pred);
1062         if (if_t != NULL) {
1063           if (rtn_t == NULL) {
1064             rtn_t = if_t;
1065           } else {
1066             rtn_t = rtn_t->join(if_t)->is_int();
1067           }
1068         }
1069       }
1070       pred = idom(pred);
1071       if (pred == NULL || pred == C->top()) {
1072         break;
1073       }
1074       // Stop if going beyond definition block of val
1075       if (dom_depth(pred) < val_dom_depth) {
1076         break;
1077       }
1078     }
1079   }
1080   return rtn_t;
1081 }
1082 
1083 
1084 //------------------------------dump_spec--------------------------------------
1085 // Dump special per-node info
1086 #ifndef PRODUCT
1087 void CountedLoopEndNode::dump_spec(outputStream *st) const {
1088   if( in(TestValue) != NULL && in(TestValue)->is_Bool() ) {
1089     BoolTest bt( test_trip()); // Added this for g++.
1090 
1091     st->print("[");
1092     bt.dump_on(st);
1093     st->print("]");
1094   }
1095   st->print(" ");
1096   IfNode::dump_spec(st);
1097 }
1098 #endif
1099 
1100 //=============================================================================
1101 //------------------------------is_member--------------------------------------
1102 // Is 'l' a member of 'this'?
1103 bool IdealLoopTree::is_member(const IdealLoopTree *l) const {
1104   while( l->_nest > _nest ) l = l->_parent;
1105   return l == this;
1106 }
1107 
1108 //------------------------------set_nest---------------------------------------
1109 // Set loop tree nesting depth.  Accumulate _has_call bits.
1110 int IdealLoopTree::set_nest( uint depth ) {
1111   _nest = depth;
1112   int bits = _has_call;
1113   if( _child ) bits |= _child->set_nest(depth+1);
1114   if( bits ) _has_call = 1;
1115   if( _next  ) bits |= _next ->set_nest(depth  );
1116   return bits;
1117 }
1118 
1119 //------------------------------split_fall_in----------------------------------
1120 // Split out multiple fall-in edges from the loop header.  Move them to a
1121 // private RegionNode before the loop.  This becomes the loop landing pad.
1122 void IdealLoopTree::split_fall_in( PhaseIdealLoop *phase, int fall_in_cnt ) {
1123   PhaseIterGVN &igvn = phase->_igvn;
1124   uint i;
1125 
1126   // Make a new RegionNode to be the landing pad.
1127   Node *landing_pad = new RegionNode( fall_in_cnt+1 );
1128   phase->set_loop(landing_pad,_parent);
1129   // Gather all the fall-in control paths into the landing pad
1130   uint icnt = fall_in_cnt;
1131   uint oreq = _head->req();
1132   for( i = oreq-1; i>0; i-- )
1133     if( !phase->is_member( this, _head->in(i) ) )
1134       landing_pad->set_req(icnt--,_head->in(i));
1135 
1136   // Peel off PhiNode edges as well
1137   for (DUIterator_Fast jmax, j = _head->fast_outs(jmax); j < jmax; j++) {
1138     Node *oj = _head->fast_out(j);
1139     if( oj->is_Phi() ) {
1140       PhiNode* old_phi = oj->as_Phi();
1141       assert( old_phi->region() == _head, "" );
1142       igvn.hash_delete(old_phi);   // Yank from hash before hacking edges
1143       Node *p = PhiNode::make_blank(landing_pad, old_phi);
1144       uint icnt = fall_in_cnt;
1145       for( i = oreq-1; i>0; i-- ) {
1146         if( !phase->is_member( this, _head->in(i) ) ) {
1147           p->init_req(icnt--, old_phi->in(i));
1148           // Go ahead and clean out old edges from old phi
1149           old_phi->del_req(i);
1150         }
1151       }
1152       // Search for CSE's here, because ZKM.jar does a lot of
1153       // loop hackery and we need to be a little incremental
1154       // with the CSE to avoid O(N^2) node blow-up.
1155       Node *p2 = igvn.hash_find_insert(p); // Look for a CSE
1156       if( p2 ) {                // Found CSE
1157         p->destruct();          // Recover useless new node
1158         p = p2;                 // Use old node
1159       } else {
1160         igvn.register_new_node_with_optimizer(p, old_phi);
1161       }
1162       // Make old Phi refer to new Phi.
1163       old_phi->add_req(p);
1164       // Check for the special case of making the old phi useless and
1165       // disappear it.  In JavaGrande I have a case where this useless
1166       // Phi is the loop limit and prevents recognizing a CountedLoop
1167       // which in turn prevents removing an empty loop.
1168       Node *id_old_phi = old_phi->Identity( &igvn );
1169       if( id_old_phi != old_phi ) { // Found a simple identity?
1170         // Note that I cannot call 'replace_node' here, because
1171         // that will yank the edge from old_phi to the Region and
1172         // I'm mid-iteration over the Region's uses.
1173         for (DUIterator_Last imin, i = old_phi->last_outs(imin); i >= imin; ) {
1174           Node* use = old_phi->last_out(i);
1175           igvn.rehash_node_delayed(use);
1176           uint uses_found = 0;
1177           for (uint j = 0; j < use->len(); j++) {
1178             if (use->in(j) == old_phi) {
1179               if (j < use->req()) use->set_req (j, id_old_phi);
1180               else                use->set_prec(j, id_old_phi);
1181               uses_found++;
1182             }
1183           }
1184           i -= uses_found;    // we deleted 1 or more copies of this edge
1185         }
1186       }
1187       igvn._worklist.push(old_phi);
1188     }
1189   }
1190   // Finally clean out the fall-in edges from the RegionNode
1191   for( i = oreq-1; i>0; i-- ) {
1192     if( !phase->is_member( this, _head->in(i) ) ) {
1193       _head->del_req(i);
1194     }
1195   }
1196   igvn.rehash_node_delayed(_head);
1197   // Transform landing pad
1198   igvn.register_new_node_with_optimizer(landing_pad, _head);
1199   // Insert landing pad into the header
1200   _head->add_req(landing_pad);
1201 }
1202 
1203 //------------------------------split_outer_loop-------------------------------
1204 // Split out the outermost loop from this shared header.
1205 void IdealLoopTree::split_outer_loop( PhaseIdealLoop *phase ) {
1206   PhaseIterGVN &igvn = phase->_igvn;
1207 
1208   // Find index of outermost loop; it should also be my tail.
1209   uint outer_idx = 1;
1210   while( _head->in(outer_idx) != _tail ) outer_idx++;
1211 
1212   // Make a LoopNode for the outermost loop.
1213   Node *ctl = _head->in(LoopNode::EntryControl);
1214   Node *outer = new LoopNode( ctl, _head->in(outer_idx) );
1215   outer = igvn.register_new_node_with_optimizer(outer, _head);
1216   phase->set_created_loop_node();
1217 
1218   // Outermost loop falls into '_head' loop
1219   _head->set_req(LoopNode::EntryControl, outer);
1220   _head->del_req(outer_idx);
1221   // Split all the Phis up between '_head' loop and 'outer' loop.
1222   for (DUIterator_Fast jmax, j = _head->fast_outs(jmax); j < jmax; j++) {
1223     Node *out = _head->fast_out(j);
1224     if( out->is_Phi() ) {
1225       PhiNode *old_phi = out->as_Phi();
1226       assert( old_phi->region() == _head, "" );
1227       Node *phi = PhiNode::make_blank(outer, old_phi);
1228       phi->init_req(LoopNode::EntryControl,    old_phi->in(LoopNode::EntryControl));
1229       phi->init_req(LoopNode::LoopBackControl, old_phi->in(outer_idx));
1230       phi = igvn.register_new_node_with_optimizer(phi, old_phi);
1231       // Make old Phi point to new Phi on the fall-in path
1232       igvn.replace_input_of(old_phi, LoopNode::EntryControl, phi);
1233       old_phi->del_req(outer_idx);
1234     }
1235   }
1236 
1237   // Use the new loop head instead of the old shared one
1238   _head = outer;
1239   phase->set_loop(_head, this);
1240 }
1241 
1242 //------------------------------fix_parent-------------------------------------
1243 static void fix_parent( IdealLoopTree *loop, IdealLoopTree *parent ) {
1244   loop->_parent = parent;
1245   if( loop->_child ) fix_parent( loop->_child, loop   );
1246   if( loop->_next  ) fix_parent( loop->_next , parent );
1247 }
1248 
1249 //------------------------------estimate_path_freq-----------------------------
1250 static float estimate_path_freq( Node *n ) {
1251   // Try to extract some path frequency info
1252   IfNode *iff;
1253   for( int i = 0; i < 50; i++ ) { // Skip through a bunch of uncommon tests
1254     uint nop = n->Opcode();
1255     if( nop == Op_SafePoint ) {   // Skip any safepoint
1256       n = n->in(0);
1257       continue;
1258     }
1259     if( nop == Op_CatchProj ) {   // Get count from a prior call
1260       // Assume call does not always throw exceptions: means the call-site
1261       // count is also the frequency of the fall-through path.
1262       assert( n->is_CatchProj(), "" );
1263       if( ((CatchProjNode*)n)->_con != CatchProjNode::fall_through_index )
1264         return 0.0f;            // Assume call exception path is rare
1265       Node *call = n->in(0)->in(0)->in(0);
1266       assert( call->is_Call(), "expect a call here" );
1267       const JVMState *jvms = ((CallNode*)call)->jvms();
1268       ciMethodData* methodData = jvms->method()->method_data();
1269       if (!methodData->is_mature())  return 0.0f; // No call-site data
1270       ciProfileData* data = methodData->bci_to_data(jvms->bci());
1271       if ((data == NULL) || !data->is_CounterData()) {
1272         // no call profile available, try call's control input
1273         n = n->in(0);
1274         continue;
1275       }
1276       return data->as_CounterData()->count()/FreqCountInvocations;
1277     }
1278     // See if there's a gating IF test
1279     Node *n_c = n->in(0);
1280     if( !n_c->is_If() ) break;       // No estimate available
1281     iff = n_c->as_If();
1282     if( iff->_fcnt != COUNT_UNKNOWN )   // Have a valid count?
1283       // Compute how much count comes on this path
1284       return ((nop == Op_IfTrue) ? iff->_prob : 1.0f - iff->_prob) * iff->_fcnt;
1285     // Have no count info.  Skip dull uncommon-trap like branches.
1286     if( (nop == Op_IfTrue  && iff->_prob < PROB_LIKELY_MAG(5)) ||
1287         (nop == Op_IfFalse && iff->_prob > PROB_UNLIKELY_MAG(5)) )
1288       break;
1289     // Skip through never-taken branch; look for a real loop exit.
1290     n = iff->in(0);
1291   }
1292   return 0.0f;                  // No estimate available
1293 }
1294 
1295 //------------------------------merge_many_backedges---------------------------
1296 // Merge all the backedges from the shared header into a private Region.
1297 // Feed that region as the one backedge to this loop.
1298 void IdealLoopTree::merge_many_backedges( PhaseIdealLoop *phase ) {
1299   uint i;
1300 
1301   // Scan for the top 2 hottest backedges
1302   float hotcnt = 0.0f;
1303   float warmcnt = 0.0f;
1304   uint hot_idx = 0;
1305   // Loop starts at 2 because slot 1 is the fall-in path
1306   for( i = 2; i < _head->req(); i++ ) {
1307     float cnt = estimate_path_freq(_head->in(i));
1308     if( cnt > hotcnt ) {       // Grab hottest path
1309       warmcnt = hotcnt;
1310       hotcnt = cnt;
1311       hot_idx = i;
1312     } else if( cnt > warmcnt ) { // And 2nd hottest path
1313       warmcnt = cnt;
1314     }
1315   }
1316 
1317   // See if the hottest backedge is worthy of being an inner loop
1318   // by being much hotter than the next hottest backedge.
1319   if( hotcnt <= 0.0001 ||
1320       hotcnt < 2.0*warmcnt ) hot_idx = 0;// No hot backedge
1321 
1322   // Peel out the backedges into a private merge point; peel
1323   // them all except optionally hot_idx.
1324   PhaseIterGVN &igvn = phase->_igvn;
1325 
1326   Node *hot_tail = NULL;
1327   // Make a Region for the merge point
1328   Node *r = new RegionNode(1);
1329   for( i = 2; i < _head->req(); i++ ) {
1330     if( i != hot_idx )
1331       r->add_req( _head->in(i) );
1332     else hot_tail = _head->in(i);
1333   }
1334   igvn.register_new_node_with_optimizer(r, _head);
1335   // Plug region into end of loop _head, followed by hot_tail
1336   while( _head->req() > 3 ) _head->del_req( _head->req()-1 );
1337   igvn.replace_input_of(_head, 2, r);
1338   if( hot_idx ) _head->add_req(hot_tail);
1339 
1340   // Split all the Phis up between '_head' loop and the Region 'r'
1341   for (DUIterator_Fast jmax, j = _head->fast_outs(jmax); j < jmax; j++) {
1342     Node *out = _head->fast_out(j);
1343     if( out->is_Phi() ) {
1344       PhiNode* n = out->as_Phi();
1345       igvn.hash_delete(n);      // Delete from hash before hacking edges
1346       Node *hot_phi = NULL;
1347       Node *phi = new PhiNode(r, n->type(), n->adr_type());
1348       // Check all inputs for the ones to peel out
1349       uint j = 1;
1350       for( uint i = 2; i < n->req(); i++ ) {
1351         if( i != hot_idx )
1352           phi->set_req( j++, n->in(i) );
1353         else hot_phi = n->in(i);
1354       }
1355       // Register the phi but do not transform until whole place transforms
1356       igvn.register_new_node_with_optimizer(phi, n);
1357       // Add the merge phi to the old Phi
1358       while( n->req() > 3 ) n->del_req( n->req()-1 );
1359       igvn.replace_input_of(n, 2, phi);
1360       if( hot_idx ) n->add_req(hot_phi);
1361     }
1362   }
1363 
1364 
1365   // Insert a new IdealLoopTree inserted below me.  Turn it into a clone
1366   // of self loop tree.  Turn self into a loop headed by _head and with
1367   // tail being the new merge point.
1368   IdealLoopTree *ilt = new IdealLoopTree( phase, _head, _tail );
1369   phase->set_loop(_tail,ilt);   // Adjust tail
1370   _tail = r;                    // Self's tail is new merge point
1371   phase->set_loop(r,this);
1372   ilt->_child = _child;         // New guy has my children
1373   _child = ilt;                 // Self has new guy as only child
1374   ilt->_parent = this;          // new guy has self for parent
1375   ilt->_nest = _nest;           // Same nesting depth (for now)
1376 
1377   // Starting with 'ilt', look for child loop trees using the same shared
1378   // header.  Flatten these out; they will no longer be loops in the end.
1379   IdealLoopTree **pilt = &_child;
1380   while( ilt ) {
1381     if( ilt->_head == _head ) {
1382       uint i;
1383       for( i = 2; i < _head->req(); i++ )
1384         if( _head->in(i) == ilt->_tail )
1385           break;                // Still a loop
1386       if( i == _head->req() ) { // No longer a loop
1387         // Flatten ilt.  Hang ilt's "_next" list from the end of
1388         // ilt's '_child' list.  Move the ilt's _child up to replace ilt.
1389         IdealLoopTree **cp = &ilt->_child;
1390         while( *cp ) cp = &(*cp)->_next;   // Find end of child list
1391         *cp = ilt->_next;       // Hang next list at end of child list
1392         *pilt = ilt->_child;    // Move child up to replace ilt
1393         ilt->_head = NULL;      // Flag as a loop UNIONED into parent
1394         ilt = ilt->_child;      // Repeat using new ilt
1395         continue;               // do not advance over ilt->_child
1396       }
1397       assert( ilt->_tail == hot_tail, "expected to only find the hot inner loop here" );
1398       phase->set_loop(_head,ilt);
1399     }
1400     pilt = &ilt->_child;        // Advance to next
1401     ilt = *pilt;
1402   }
1403 
1404   if( _child ) fix_parent( _child, this );
1405 }
1406 
1407 //------------------------------beautify_loops---------------------------------
1408 // Split shared headers and insert loop landing pads.
1409 // Insert a LoopNode to replace the RegionNode.
1410 // Return TRUE if loop tree is structurally changed.
1411 bool IdealLoopTree::beautify_loops( PhaseIdealLoop *phase ) {
1412   bool result = false;
1413   // Cache parts in locals for easy
1414   PhaseIterGVN &igvn = phase->_igvn;
1415 
1416   igvn.hash_delete(_head);      // Yank from hash before hacking edges
1417 
1418   // Check for multiple fall-in paths.  Peel off a landing pad if need be.
1419   int fall_in_cnt = 0;
1420   for( uint i = 1; i < _head->req(); i++ )
1421     if( !phase->is_member( this, _head->in(i) ) )
1422       fall_in_cnt++;
1423   assert( fall_in_cnt, "at least 1 fall-in path" );
1424   if( fall_in_cnt > 1 )         // Need a loop landing pad to merge fall-ins
1425     split_fall_in( phase, fall_in_cnt );
1426 
1427   // Swap inputs to the _head and all Phis to move the fall-in edge to
1428   // the left.
1429   fall_in_cnt = 1;
1430   while( phase->is_member( this, _head->in(fall_in_cnt) ) )
1431     fall_in_cnt++;
1432   if( fall_in_cnt > 1 ) {
1433     // Since I am just swapping inputs I do not need to update def-use info
1434     Node *tmp = _head->in(1);
1435     igvn.rehash_node_delayed(_head);
1436     _head->set_req( 1, _head->in(fall_in_cnt) );
1437     _head->set_req( fall_in_cnt, tmp );
1438     // Swap also all Phis
1439     for (DUIterator_Fast imax, i = _head->fast_outs(imax); i < imax; i++) {
1440       Node* phi = _head->fast_out(i);
1441       if( phi->is_Phi() ) {
1442         igvn.rehash_node_delayed(phi); // Yank from hash before hacking edges
1443         tmp = phi->in(1);
1444         phi->set_req( 1, phi->in(fall_in_cnt) );
1445         phi->set_req( fall_in_cnt, tmp );
1446       }
1447     }
1448   }
1449   assert( !phase->is_member( this, _head->in(1) ), "left edge is fall-in" );
1450   assert(  phase->is_member( this, _head->in(2) ), "right edge is loop" );
1451 
1452   // If I am a shared header (multiple backedges), peel off the many
1453   // backedges into a private merge point and use the merge point as
1454   // the one true backedge.
1455   if( _head->req() > 3 ) {
1456     // Merge the many backedges into a single backedge but leave
1457     // the hottest backedge as separate edge for the following peel.
1458     merge_many_backedges( phase );
1459     result = true;
1460   }
1461 
1462   // If I have one hot backedge, peel off myself loop.
1463   // I better be the outermost loop.
1464   if (_head->req() > 3 && !_irreducible) {
1465     split_outer_loop( phase );
1466     result = true;
1467 
1468   } else if (!_head->is_Loop() && !_irreducible) {
1469     // Make a new LoopNode to replace the old loop head
1470     Node *l = new LoopNode( _head->in(1), _head->in(2) );
1471     l = igvn.register_new_node_with_optimizer(l, _head);
1472     phase->set_created_loop_node();
1473     // Go ahead and replace _head
1474     phase->_igvn.replace_node( _head, l );
1475     _head = l;
1476     phase->set_loop(_head, this);
1477   }
1478 
1479   // Now recursively beautify nested loops
1480   if( _child ) result |= _child->beautify_loops( phase );
1481   if( _next  ) result |= _next ->beautify_loops( phase );
1482   return result;
1483 }
1484 
1485 //------------------------------allpaths_check_safepts----------------------------
1486 // Allpaths backwards scan from loop tail, terminating each path at first safepoint
1487 // encountered.  Helper for check_safepts.
1488 void IdealLoopTree::allpaths_check_safepts(VectorSet &visited, Node_List &stack) {
1489   assert(stack.size() == 0, "empty stack");
1490   stack.push(_tail);
1491   visited.Clear();
1492   visited.set(_tail->_idx);
1493   while (stack.size() > 0) {
1494     Node* n = stack.pop();
1495     if (n->is_Call() && n->as_Call()->guaranteed_safepoint()) {
1496       // Terminate this path
1497     } else if (n->Opcode() == Op_SafePoint) {
1498       if (_phase->get_loop(n) != this) {
1499         if (_required_safept == NULL) _required_safept = new Node_List();
1500         _required_safept->push(n);  // save the one closest to the tail
1501       }
1502       // Terminate this path
1503     } else {
1504       uint start = n->is_Region() ? 1 : 0;
1505       uint end   = n->is_Region() && !n->is_Loop() ? n->req() : start + 1;
1506       for (uint i = start; i < end; i++) {
1507         Node* in = n->in(i);
1508         assert(in->is_CFG(), "must be");
1509         if (!visited.test_set(in->_idx) && is_member(_phase->get_loop(in))) {
1510           stack.push(in);
1511         }
1512       }
1513     }
1514   }
1515 }
1516 
1517 //------------------------------check_safepts----------------------------
1518 // Given dominators, try to find loops with calls that must always be
1519 // executed (call dominates loop tail).  These loops do not need non-call
1520 // safepoints (ncsfpt).
1521 //
1522 // A complication is that a safepoint in a inner loop may be needed
1523 // by an outer loop. In the following, the inner loop sees it has a
1524 // call (block 3) on every path from the head (block 2) to the
1525 // backedge (arc 3->2).  So it deletes the ncsfpt (non-call safepoint)
1526 // in block 2, _but_ this leaves the outer loop without a safepoint.
1527 //
1528 //          entry  0
1529 //                 |
1530 //                 v
1531 // outer 1,2    +->1
1532 //              |  |
1533 //              |  v
1534 //              |  2<---+  ncsfpt in 2
1535 //              |_/|\   |
1536 //                 | v  |
1537 // inner 2,3      /  3  |  call in 3
1538 //               /   |  |
1539 //              v    +--+
1540 //        exit  4
1541 //
1542 //
1543 // This method creates a list (_required_safept) of ncsfpt nodes that must
1544 // be protected is created for each loop. When a ncsfpt maybe deleted, it
1545 // is first looked for in the lists for the outer loops of the current loop.
1546 //
1547 // The insights into the problem:
1548 //  A) counted loops are okay
1549 //  B) innermost loops are okay (only an inner loop can delete
1550 //     a ncsfpt needed by an outer loop)
1551 //  C) a loop is immune from an inner loop deleting a safepoint
1552 //     if the loop has a call on the idom-path
1553 //  D) a loop is also immune if it has a ncsfpt (non-call safepoint) on the
1554 //     idom-path that is not in a nested loop
1555 //  E) otherwise, an ncsfpt on the idom-path that is nested in an inner
1556 //     loop needs to be prevented from deletion by an inner loop
1557 //
1558 // There are two analyses:
1559 //  1) The first, and cheaper one, scans the loop body from
1560 //     tail to head following the idom (immediate dominator)
1561 //     chain, looking for the cases (C,D,E) above.
1562 //     Since inner loops are scanned before outer loops, there is summary
1563 //     information about inner loops.  Inner loops can be skipped over
1564 //     when the tail of an inner loop is encountered.
1565 //
1566 //  2) The second, invoked if the first fails to find a call or ncsfpt on
1567 //     the idom path (which is rare), scans all predecessor control paths
1568 //     from the tail to the head, terminating a path when a call or sfpt
1569 //     is encountered, to find the ncsfpt's that are closest to the tail.
1570 //
1571 void IdealLoopTree::check_safepts(VectorSet &visited, Node_List &stack) {
1572   // Bottom up traversal
1573   IdealLoopTree* ch = _child;
1574   if (_child) _child->check_safepts(visited, stack);
1575   if (_next)  _next ->check_safepts(visited, stack);
1576 
1577   if (!_head->is_CountedLoop() && !_has_sfpt && _parent != NULL && !_irreducible) {
1578     bool  has_call         = false; // call on dom-path
1579     bool  has_local_ncsfpt = false; // ncsfpt on dom-path at this loop depth
1580     Node* nonlocal_ncsfpt  = NULL;  // ncsfpt on dom-path at a deeper depth
1581     // Scan the dom-path nodes from tail to head
1582     for (Node* n = tail(); n != _head; n = _phase->idom(n)) {
1583       if (n->is_Call() && n->as_Call()->guaranteed_safepoint()) {
1584         has_call = true;
1585         _has_sfpt = 1;          // Then no need for a safept!
1586         break;
1587       } else if (n->Opcode() == Op_SafePoint) {
1588         if (_phase->get_loop(n) == this) {
1589           has_local_ncsfpt = true;
1590           break;
1591         }
1592         if (nonlocal_ncsfpt == NULL) {
1593           nonlocal_ncsfpt = n; // save the one closest to the tail
1594         }
1595       } else {
1596         IdealLoopTree* nlpt = _phase->get_loop(n);
1597         if (this != nlpt) {
1598           // If at an inner loop tail, see if the inner loop has already
1599           // recorded seeing a call on the dom-path (and stop.)  If not,
1600           // jump to the head of the inner loop.
1601           assert(is_member(nlpt), "nested loop");
1602           Node* tail = nlpt->_tail;
1603           if (tail->in(0)->is_If()) tail = tail->in(0);
1604           if (n == tail) {
1605             // If inner loop has call on dom-path, so does outer loop
1606             if (nlpt->_has_sfpt) {
1607               has_call = true;
1608               _has_sfpt = 1;
1609               break;
1610             }
1611             // Skip to head of inner loop
1612             assert(_phase->is_dominator(_head, nlpt->_head), "inner head dominated by outer head");
1613             n = nlpt->_head;
1614           }
1615         }
1616       }
1617     }
1618     // Record safept's that this loop needs preserved when an
1619     // inner loop attempts to delete it's safepoints.
1620     if (_child != NULL && !has_call && !has_local_ncsfpt) {
1621       if (nonlocal_ncsfpt != NULL) {
1622         if (_required_safept == NULL) _required_safept = new Node_List();
1623         _required_safept->push(nonlocal_ncsfpt);
1624       } else {
1625         // Failed to find a suitable safept on the dom-path.  Now use
1626         // an all paths walk from tail to head, looking for safepoints to preserve.
1627         allpaths_check_safepts(visited, stack);
1628       }
1629     }
1630   }
1631 }
1632 
1633 //---------------------------is_deleteable_safept----------------------------
1634 // Is safept not required by an outer loop?
1635 bool PhaseIdealLoop::is_deleteable_safept(Node* sfpt) {
1636   assert(sfpt->Opcode() == Op_SafePoint, "");
1637   IdealLoopTree* lp = get_loop(sfpt)->_parent;
1638   while (lp != NULL) {
1639     Node_List* sfpts = lp->_required_safept;
1640     if (sfpts != NULL) {
1641       for (uint i = 0; i < sfpts->size(); i++) {
1642         if (sfpt == sfpts->at(i))
1643           return false;
1644       }
1645     }
1646     lp = lp->_parent;
1647   }
1648   return true;
1649 }
1650 
1651 //---------------------------replace_parallel_iv-------------------------------
1652 // Replace parallel induction variable (parallel to trip counter)
1653 void PhaseIdealLoop::replace_parallel_iv(IdealLoopTree *loop) {
1654   assert(loop->_head->is_CountedLoop(), "");
1655   CountedLoopNode *cl = loop->_head->as_CountedLoop();
1656   if (!cl->is_valid_counted_loop())
1657     return;         // skip malformed counted loop
1658   Node *incr = cl->incr();
1659   if (incr == NULL)
1660     return;         // Dead loop?
1661   Node *init = cl->init_trip();
1662   Node *phi  = cl->phi();
1663   int stride_con = cl->stride_con();
1664 
1665   // Visit all children, looking for Phis
1666   for (DUIterator i = cl->outs(); cl->has_out(i); i++) {
1667     Node *out = cl->out(i);
1668     // Look for other phis (secondary IVs). Skip dead ones
1669     if (!out->is_Phi() || out == phi || !has_node(out))
1670       continue;
1671     PhiNode* phi2 = out->as_Phi();
1672     Node *incr2 = phi2->in( LoopNode::LoopBackControl );
1673     // Look for induction variables of the form:  X += constant
1674     if (phi2->region() != loop->_head ||
1675         incr2->req() != 3 ||
1676         incr2->in(1) != phi2 ||
1677         incr2 == incr ||
1678         incr2->Opcode() != Op_AddI ||
1679         !incr2->in(2)->is_Con())
1680       continue;
1681 
1682     // Check for parallel induction variable (parallel to trip counter)
1683     // via an affine function.  In particular, count-down loops with
1684     // count-up array indices are common. We only RCE references off
1685     // the trip-counter, so we need to convert all these to trip-counter
1686     // expressions.
1687     Node *init2 = phi2->in( LoopNode::EntryControl );
1688     int stride_con2 = incr2->in(2)->get_int();
1689 
1690     // The general case here gets a little tricky.  We want to find the
1691     // GCD of all possible parallel IV's and make a new IV using this
1692     // GCD for the loop.  Then all possible IVs are simple multiples of
1693     // the GCD.  In practice, this will cover very few extra loops.
1694     // Instead we require 'stride_con2' to be a multiple of 'stride_con',
1695     // where +/-1 is the common case, but other integer multiples are
1696     // also easy to handle.
1697     int ratio_con = stride_con2/stride_con;
1698 
1699     if ((ratio_con * stride_con) == stride_con2) { // Check for exact
1700 #ifndef PRODUCT
1701       if (TraceLoopOpts) {
1702         tty->print("Parallel IV: %d ", phi2->_idx);
1703         loop->dump_head();
1704       }
1705 #endif
1706       // Convert to using the trip counter.  The parallel induction
1707       // variable differs from the trip counter by a loop-invariant
1708       // amount, the difference between their respective initial values.
1709       // It is scaled by the 'ratio_con'.
1710       Node* ratio = _igvn.intcon(ratio_con);
1711       set_ctrl(ratio, C->root());
1712       Node* ratio_init = new MulINode(init, ratio);
1713       _igvn.register_new_node_with_optimizer(ratio_init, init);
1714       set_early_ctrl(ratio_init);
1715       Node* diff = new SubINode(init2, ratio_init);
1716       _igvn.register_new_node_with_optimizer(diff, init2);
1717       set_early_ctrl(diff);
1718       Node* ratio_idx = new MulINode(phi, ratio);
1719       _igvn.register_new_node_with_optimizer(ratio_idx, phi);
1720       set_ctrl(ratio_idx, cl);
1721       Node* add = new AddINode(ratio_idx, diff);
1722       _igvn.register_new_node_with_optimizer(add);
1723       set_ctrl(add, cl);
1724       _igvn.replace_node( phi2, add );
1725       // Sometimes an induction variable is unused
1726       if (add->outcnt() == 0) {
1727         _igvn.remove_dead_node(add);
1728       }
1729       --i; // deleted this phi; rescan starting with next position
1730       continue;
1731     }
1732   }
1733 }
1734 
1735 void IdealLoopTree::remove_safepoints(PhaseIdealLoop* phase, bool keep_one) {
1736   Node* keep = NULL;
1737   if (keep_one) {
1738     // Look for a safepoint on the idom-path.
1739     for (Node* i = tail(); i != _head; i = phase->idom(i)) {
1740       if (i->Opcode() == Op_SafePoint && phase->get_loop(i) == this) {
1741         keep = i;
1742         break; // Found one
1743       }
1744     }
1745   }
1746 
1747   // Don't remove any safepoints if it is requested to keep a single safepoint and
1748   // no safepoint was found on idom-path. It is not safe to remove any safepoint
1749   // in this case since there's no safepoint dominating all paths in the loop body.
1750   bool prune = !keep_one || keep != NULL;
1751 
1752   // Delete other safepoints in this loop.
1753   Node_List* sfpts = _safepts;
1754   if (prune && sfpts != NULL) {
1755     assert(keep == NULL || keep->Opcode() == Op_SafePoint, "not safepoint");
1756     for (uint i = 0; i < sfpts->size(); i++) {
1757       Node* n = sfpts->at(i);
1758       assert(phase->get_loop(n) == this, "");
1759       if (n != keep && phase->is_deleteable_safept(n)) {
1760         phase->lazy_replace(n, n->in(TypeFunc::Control));
1761       }
1762     }
1763   }
1764 }
1765 
1766 //------------------------------counted_loop-----------------------------------
1767 // Convert to counted loops where possible
1768 void IdealLoopTree::counted_loop( PhaseIdealLoop *phase ) {
1769 
1770   // For grins, set the inner-loop flag here
1771   if (!_child) {
1772     if (_head->is_Loop()) _head->as_Loop()->set_inner_loop();
1773   }
1774 
1775   if (_head->is_CountedLoop() ||
1776       phase->is_counted_loop(_head, this)) {
1777 
1778     if (!UseCountedLoopSafepoints) {
1779       // Indicate we do not need a safepoint here
1780       _has_sfpt = 1;
1781     }
1782 
1783     // Remove safepoints
1784     bool keep_one_sfpt = !(_has_call || _has_sfpt);
1785     remove_safepoints(phase, keep_one_sfpt);
1786 
1787     // Look for induction variables
1788     phase->replace_parallel_iv(this);
1789 
1790   } else if (_parent != NULL && !_irreducible) {
1791     // Not a counted loop. Keep one safepoint.
1792     bool keep_one_sfpt = true;
1793     remove_safepoints(phase, keep_one_sfpt);
1794   }
1795 
1796   // Recursively
1797   if (_child) _child->counted_loop( phase );
1798   if (_next)  _next ->counted_loop( phase );
1799 }
1800 
1801 #ifndef PRODUCT
1802 //------------------------------dump_head--------------------------------------
1803 // Dump 1 liner for loop header info
1804 void IdealLoopTree::dump_head( ) const {
1805   for (uint i=0; i<_nest; i++)
1806     tty->print("  ");
1807   tty->print("Loop: N%d/N%d ",_head->_idx,_tail->_idx);
1808   if (_irreducible) tty->print(" IRREDUCIBLE");
1809   Node* entry = _head->in(LoopNode::EntryControl);
1810   Node* predicate = PhaseIdealLoop::find_predicate_insertion_point(entry, Deoptimization::Reason_loop_limit_check);
1811   if (predicate != NULL ) {
1812     tty->print(" limit_check");
1813     entry = entry->in(0)->in(0);
1814   }
1815   if (UseLoopPredicate) {
1816     entry = PhaseIdealLoop::find_predicate_insertion_point(entry, Deoptimization::Reason_predicate);
1817     if (entry != NULL) {
1818       tty->print(" predicated");
1819     }
1820   }
1821   if (_head->is_CountedLoop()) {
1822     CountedLoopNode *cl = _head->as_CountedLoop();
1823     tty->print(" counted");
1824 
1825     Node* init_n = cl->init_trip();
1826     if (init_n  != NULL &&  init_n->is_Con())
1827       tty->print(" [%d,", cl->init_trip()->get_int());
1828     else
1829       tty->print(" [int,");
1830     Node* limit_n = cl->limit();
1831     if (limit_n  != NULL &&  limit_n->is_Con())
1832       tty->print("%d),", cl->limit()->get_int());
1833     else
1834       tty->print("int),");
1835     int stride_con  = cl->stride_con();
1836     if (stride_con > 0) tty->print("+");
1837     tty->print("%d", stride_con);
1838 
1839     tty->print(" (%0.f iters) ", cl->profile_trip_cnt());
1840 
1841     if (cl->is_pre_loop ()) tty->print(" pre" );
1842     if (cl->is_main_loop()) tty->print(" main");
1843     if (cl->is_post_loop()) tty->print(" post");
1844     if (cl->is_vectorized_loop()) tty->print(" vector");
1845     if (cl->range_checks_present()) tty->print(" rc ");
1846     if (cl->is_multiversioned()) tty->print(" multi ");
1847   }
1848   if (_has_call) tty->print(" has_call");
1849   if (_has_sfpt) tty->print(" has_sfpt");
1850   if (_rce_candidate) tty->print(" rce");
1851   if (_safepts != NULL && _safepts->size() > 0) {
1852     tty->print(" sfpts={"); _safepts->dump_simple(); tty->print(" }");
1853   }
1854   if (_required_safept != NULL && _required_safept->size() > 0) {
1855     tty->print(" req={"); _required_safept->dump_simple(); tty->print(" }");
1856   }
1857   tty->cr();
1858 }
1859 
1860 //------------------------------dump-------------------------------------------
1861 // Dump loops by loop tree
1862 void IdealLoopTree::dump( ) const {
1863   dump_head();
1864   if (_child) _child->dump();
1865   if (_next)  _next ->dump();
1866 }
1867 
1868 #endif
1869 
1870 static void log_loop_tree(IdealLoopTree* root, IdealLoopTree* loop, CompileLog* log) {
1871   if (loop == root) {
1872     if (loop->_child != NULL) {
1873       log->begin_head("loop_tree");
1874       log->end_head();
1875       if( loop->_child ) log_loop_tree(root, loop->_child, log);
1876       log->tail("loop_tree");
1877       assert(loop->_next == NULL, "what?");
1878     }
1879   } else {
1880     Node* head = loop->_head;
1881     log->begin_head("loop");
1882     log->print(" idx='%d' ", head->_idx);
1883     if (loop->_irreducible) log->print("irreducible='1' ");
1884     if (head->is_Loop()) {
1885       if (head->as_Loop()->is_inner_loop()) log->print("inner_loop='1' ");
1886       if (head->as_Loop()->is_partial_peel_loop()) log->print("partial_peel_loop='1' ");
1887     }
1888     if (head->is_CountedLoop()) {
1889       CountedLoopNode* cl = head->as_CountedLoop();
1890       if (cl->is_pre_loop())  log->print("pre_loop='%d' ",  cl->main_idx());
1891       if (cl->is_main_loop()) log->print("main_loop='%d' ", cl->_idx);
1892       if (cl->is_post_loop()) log->print("post_loop='%d' ",  cl->main_idx());
1893     }
1894     log->end_head();
1895     if( loop->_child ) log_loop_tree(root, loop->_child, log);
1896     log->tail("loop");
1897     if( loop->_next  ) log_loop_tree(root, loop->_next, log);
1898   }
1899 }
1900 
1901 //---------------------collect_potentially_useful_predicates-----------------------
1902 // Helper function to collect potentially useful predicates to prevent them from
1903 // being eliminated by PhaseIdealLoop::eliminate_useless_predicates
1904 void PhaseIdealLoop::collect_potentially_useful_predicates(
1905                          IdealLoopTree * loop, Unique_Node_List &useful_predicates) {
1906   if (loop->_child) { // child
1907     collect_potentially_useful_predicates(loop->_child, useful_predicates);
1908   }
1909 
1910   // self (only loops that we can apply loop predication may use their predicates)
1911   if (loop->_head->is_Loop() &&
1912       !loop->_irreducible    &&
1913       !loop->tail()->is_top()) {
1914     LoopNode* lpn = loop->_head->as_Loop();
1915     Node* entry = lpn->in(LoopNode::EntryControl);
1916     Node* predicate_proj = find_predicate(entry); // loop_limit_check first
1917     if (predicate_proj != NULL ) { // right pattern that can be used by loop predication
1918       assert(entry->in(0)->in(1)->in(1)->Opcode() == Op_Opaque1, "must be");
1919       useful_predicates.push(entry->in(0)->in(1)->in(1)); // good one
1920       entry = entry->in(0)->in(0);
1921     }
1922     predicate_proj = find_predicate(entry); // Predicate
1923     if (predicate_proj != NULL ) {
1924       useful_predicates.push(entry->in(0)->in(1)->in(1)); // good one
1925     }
1926   }
1927 
1928   if (loop->_next) { // sibling
1929     collect_potentially_useful_predicates(loop->_next, useful_predicates);
1930   }
1931 }
1932 
1933 //------------------------eliminate_useless_predicates-----------------------------
1934 // Eliminate all inserted predicates if they could not be used by loop predication.
1935 // Note: it will also eliminates loop limits check predicate since it also uses
1936 // Opaque1 node (see Parse::add_predicate()).
1937 void PhaseIdealLoop::eliminate_useless_predicates() {
1938   if (C->predicate_count() == 0)
1939     return; // no predicate left
1940 
1941   Unique_Node_List useful_predicates; // to store useful predicates
1942   if (C->has_loops()) {
1943     collect_potentially_useful_predicates(_ltree_root->_child, useful_predicates);
1944   }
1945 
1946   for (int i = C->predicate_count(); i > 0; i--) {
1947      Node * n = C->predicate_opaque1_node(i-1);
1948      assert(n->Opcode() == Op_Opaque1, "must be");
1949      if (!useful_predicates.member(n)) { // not in the useful list
1950        _igvn.replace_node(n, n->in(1));
1951      }
1952   }
1953 }
1954 
1955 //------------------------process_expensive_nodes-----------------------------
1956 // Expensive nodes have their control input set to prevent the GVN
1957 // from commoning them and as a result forcing the resulting node to
1958 // be in a more frequent path. Use CFG information here, to change the
1959 // control inputs so that some expensive nodes can be commoned while
1960 // not executed more frequently.
1961 bool PhaseIdealLoop::process_expensive_nodes() {
1962   assert(OptimizeExpensiveOps, "optimization off?");
1963 
1964   // Sort nodes to bring similar nodes together
1965   C->sort_expensive_nodes();
1966 
1967   bool progress = false;
1968 
1969   for (int i = 0; i < C->expensive_count(); ) {
1970     Node* n = C->expensive_node(i);
1971     int start = i;
1972     // Find nodes similar to n
1973     i++;
1974     for (; i < C->expensive_count() && Compile::cmp_expensive_nodes(n, C->expensive_node(i)) == 0; i++);
1975     int end = i;
1976     // And compare them two by two
1977     for (int j = start; j < end; j++) {
1978       Node* n1 = C->expensive_node(j);
1979       if (is_node_unreachable(n1)) {
1980         continue;
1981       }
1982       for (int k = j+1; k < end; k++) {
1983         Node* n2 = C->expensive_node(k);
1984         if (is_node_unreachable(n2)) {
1985           continue;
1986         }
1987 
1988         assert(n1 != n2, "should be pair of nodes");
1989 
1990         Node* c1 = n1->in(0);
1991         Node* c2 = n2->in(0);
1992 
1993         Node* parent_c1 = c1;
1994         Node* parent_c2 = c2;
1995 
1996         // The call to get_early_ctrl_for_expensive() moves the
1997         // expensive nodes up but stops at loops that are in a if
1998         // branch. See whether we can exit the loop and move above the
1999         // If.
2000         if (c1->is_Loop()) {
2001           parent_c1 = c1->in(1);
2002         }
2003         if (c2->is_Loop()) {
2004           parent_c2 = c2->in(1);
2005         }
2006 
2007         if (parent_c1 == parent_c2) {
2008           _igvn._worklist.push(n1);
2009           _igvn._worklist.push(n2);
2010           continue;
2011         }
2012 
2013         // Look for identical expensive node up the dominator chain.
2014         if (is_dominator(c1, c2)) {
2015           c2 = c1;
2016         } else if (is_dominator(c2, c1)) {
2017           c1 = c2;
2018         } else if (parent_c1->is_Proj() && parent_c1->in(0)->is_If() &&
2019                    parent_c2->is_Proj() && parent_c1->in(0) == parent_c2->in(0)) {
2020           // Both branches have the same expensive node so move it up
2021           // before the if.
2022           c1 = c2 = idom(parent_c1->in(0));
2023         }
2024         // Do the actual moves
2025         if (n1->in(0) != c1) {
2026           _igvn.hash_delete(n1);
2027           n1->set_req(0, c1);
2028           _igvn.hash_insert(n1);
2029           _igvn._worklist.push(n1);
2030           progress = true;
2031         }
2032         if (n2->in(0) != c2) {
2033           _igvn.hash_delete(n2);
2034           n2->set_req(0, c2);
2035           _igvn.hash_insert(n2);
2036           _igvn._worklist.push(n2);
2037           progress = true;
2038         }
2039       }
2040     }
2041   }
2042 
2043   return progress;
2044 }
2045 
2046 
2047 //=============================================================================
2048 //----------------------------build_and_optimize-------------------------------
2049 // Create a PhaseLoop.  Build the ideal Loop tree.  Map each Ideal Node to
2050 // its corresponding LoopNode.  If 'optimize' is true, do some loop cleanups.
2051 void PhaseIdealLoop::build_and_optimize(bool do_split_ifs, bool skip_loop_opts) {
2052   ResourceMark rm;
2053 
2054   int old_progress = C->major_progress();
2055   uint orig_worklist_size = _igvn._worklist.size();
2056 
2057   // Reset major-progress flag for the driver's heuristics
2058   C->clear_major_progress();
2059 
2060 #ifndef PRODUCT
2061   // Capture for later assert
2062   uint unique = C->unique();
2063   _loop_invokes++;
2064   _loop_work += unique;
2065 #endif
2066 
2067   // True if the method has at least 1 irreducible loop
2068   _has_irreducible_loops = false;
2069 
2070   _created_loop_node = false;
2071 
2072   Arena *a = Thread::current()->resource_area();
2073   VectorSet visited(a);
2074   // Pre-grow the mapping from Nodes to IdealLoopTrees.
2075   _nodes.map(C->unique(), NULL);
2076   memset(_nodes.adr(), 0, wordSize * C->unique());
2077 
2078   // Pre-build the top-level outermost loop tree entry
2079   _ltree_root = new IdealLoopTree( this, C->root(), C->root() );
2080   // Do not need a safepoint at the top level
2081   _ltree_root->_has_sfpt = 1;
2082 
2083   // Initialize Dominators.
2084   // Checked in clone_loop_predicate() during beautify_loops().
2085   _idom_size = 0;
2086   _idom      = NULL;
2087   _dom_depth = NULL;
2088   _dom_stk   = NULL;
2089 
2090   // Empty pre-order array
2091   allocate_preorders();
2092 
2093   // Build a loop tree on the fly.  Build a mapping from CFG nodes to
2094   // IdealLoopTree entries.  Data nodes are NOT walked.
2095   build_loop_tree();
2096   // Check for bailout, and return
2097   if (C->failing()) {
2098     return;
2099   }
2100 
2101   // No loops after all
2102   if( !_ltree_root->_child && !_verify_only ) C->set_has_loops(false);
2103 
2104   // There should always be an outer loop containing the Root and Return nodes.
2105   // If not, we have a degenerate empty program.  Bail out in this case.
2106   if (!has_node(C->root())) {
2107     if (!_verify_only) {
2108       C->clear_major_progress();
2109       C->record_method_not_compilable("empty program detected during loop optimization");
2110     }
2111     return;
2112   }
2113 
2114   // Nothing to do, so get out
2115   bool stop_early = !C->has_loops() && !skip_loop_opts && !do_split_ifs && !_verify_me && !_verify_only;
2116   bool do_expensive_nodes = C->should_optimize_expensive_nodes(_igvn);
2117   if (stop_early && !do_expensive_nodes) {
2118     _igvn.optimize();           // Cleanup NeverBranches
2119     return;
2120   }
2121 
2122   // Set loop nesting depth
2123   _ltree_root->set_nest( 0 );
2124 
2125   // Split shared headers and insert loop landing pads.
2126   // Do not bother doing this on the Root loop of course.
2127   if( !_verify_me && !_verify_only && _ltree_root->_child ) {
2128     C->print_method(PHASE_BEFORE_BEAUTIFY_LOOPS, 3);
2129     if( _ltree_root->_child->beautify_loops( this ) ) {
2130       // Re-build loop tree!
2131       _ltree_root->_child = NULL;
2132       _nodes.clear();
2133       reallocate_preorders();
2134       build_loop_tree();
2135       // Check for bailout, and return
2136       if (C->failing()) {
2137         return;
2138       }
2139       // Reset loop nesting depth
2140       _ltree_root->set_nest( 0 );
2141 
2142       C->print_method(PHASE_AFTER_BEAUTIFY_LOOPS, 3);
2143     }
2144   }
2145 
2146   // Build Dominators for elision of NULL checks & loop finding.
2147   // Since nodes do not have a slot for immediate dominator, make
2148   // a persistent side array for that info indexed on node->_idx.
2149   _idom_size = C->unique();
2150   _idom      = NEW_RESOURCE_ARRAY( Node*, _idom_size );
2151   _dom_depth = NEW_RESOURCE_ARRAY( uint,  _idom_size );
2152   _dom_stk   = NULL; // Allocated on demand in recompute_dom_depth
2153   memset( _dom_depth, 0, _idom_size * sizeof(uint) );
2154 
2155   Dominators();
2156 
2157   if (!_verify_only) {
2158     // As a side effect, Dominators removed any unreachable CFG paths
2159     // into RegionNodes.  It doesn't do this test against Root, so
2160     // we do it here.
2161     for( uint i = 1; i < C->root()->req(); i++ ) {
2162       if( !_nodes[C->root()->in(i)->_idx] ) {    // Dead path into Root?
2163         _igvn.delete_input_of(C->root(), i);
2164         i--;                      // Rerun same iteration on compressed edges
2165       }
2166     }
2167 
2168     // Given dominators, try to find inner loops with calls that must
2169     // always be executed (call dominates loop tail).  These loops do
2170     // not need a separate safepoint.
2171     Node_List cisstack(a);
2172     _ltree_root->check_safepts(visited, cisstack);
2173   }
2174 
2175   // Walk the DATA nodes and place into loops.  Find earliest control
2176   // node.  For CFG nodes, the _nodes array starts out and remains
2177   // holding the associated IdealLoopTree pointer.  For DATA nodes, the
2178   // _nodes array holds the earliest legal controlling CFG node.
2179 
2180   // Allocate stack with enough space to avoid frequent realloc
2181   int stack_size = (C->live_nodes() >> 1) + 16; // (live_nodes>>1)+16 from Java2D stats
2182   Node_Stack nstack( a, stack_size );
2183 
2184   visited.Clear();
2185   Node_List worklist(a);
2186   // Don't need C->root() on worklist since
2187   // it will be processed among C->top() inputs
2188   worklist.push( C->top() );
2189   visited.set( C->top()->_idx ); // Set C->top() as visited now
2190   build_loop_early( visited, worklist, nstack );
2191 
2192   // Given early legal placement, try finding counted loops.  This placement
2193   // is good enough to discover most loop invariants.
2194   if( !_verify_me && !_verify_only )
2195     _ltree_root->counted_loop( this );
2196 
2197   // Find latest loop placement.  Find ideal loop placement.
2198   visited.Clear();
2199   init_dom_lca_tags();
2200   // Need C->root() on worklist when processing outs
2201   worklist.push( C->root() );
2202   NOT_PRODUCT( C->verify_graph_edges(); )
2203   worklist.push( C->top() );
2204   build_loop_late( visited, worklist, nstack );
2205 
2206   if (_verify_only) {
2207     // restore major progress flag
2208     for (int i = 0; i < old_progress; i++)
2209       C->set_major_progress();
2210     assert(C->unique() == unique, "verification mode made Nodes? ? ?");
2211     assert(_igvn._worklist.size() == orig_worklist_size, "shouldn't push anything");
2212     return;
2213   }
2214 
2215   // clear out the dead code after build_loop_late
2216   while (_deadlist.size()) {
2217     _igvn.remove_globally_dead_node(_deadlist.pop());
2218   }
2219 
2220   if (stop_early) {
2221     assert(do_expensive_nodes, "why are we here?");
2222     if (process_expensive_nodes()) {
2223       // If we made some progress when processing expensive nodes then
2224       // the IGVN may modify the graph in a way that will allow us to
2225       // make some more progress: we need to try processing expensive
2226       // nodes again.
2227       C->set_major_progress();
2228     }
2229     _igvn.optimize();
2230     return;
2231   }
2232 
2233   // Some parser-inserted loop predicates could never be used by loop
2234   // predication or they were moved away from loop during some optimizations.
2235   // For example, peeling. Eliminate them before next loop optimizations.
2236   eliminate_useless_predicates();
2237 
2238 #ifndef PRODUCT
2239   C->verify_graph_edges();
2240   if (_verify_me) {             // Nested verify pass?
2241     // Check to see if the verify mode is broken
2242     assert(C->unique() == unique, "non-optimize mode made Nodes? ? ?");
2243     return;
2244   }
2245   if(VerifyLoopOptimizations) verify();
2246   if(TraceLoopOpts && C->has_loops()) {
2247     _ltree_root->dump();
2248   }
2249 #endif
2250 
2251   if (skip_loop_opts) {
2252     // restore major progress flag
2253     for (int i = 0; i < old_progress; i++) {
2254       C->set_major_progress();
2255     }
2256 
2257     // Cleanup any modified bits
2258     _igvn.optimize();
2259 
2260     if (C->log() != NULL) {
2261       log_loop_tree(_ltree_root, _ltree_root, C->log());
2262     }
2263     return;
2264   }
2265 
2266   if (ReassociateInvariants) {
2267     // Reassociate invariants and prep for split_thru_phi
2268     for (LoopTreeIterator iter(_ltree_root); !iter.done(); iter.next()) {
2269       IdealLoopTree* lpt = iter.current();
2270       bool is_counted = lpt->is_counted();
2271       if (!is_counted || !lpt->is_inner()) continue;
2272 
2273       // check for vectorized loops, any reassociation of invariants was already done
2274       if (is_counted && lpt->_head->as_CountedLoop()->do_unroll_only()) continue;
2275 
2276       lpt->reassociate_invariants(this);
2277 
2278       // Because RCE opportunities can be masked by split_thru_phi,
2279       // look for RCE candidates and inhibit split_thru_phi
2280       // on just their loop-phi's for this pass of loop opts
2281       if (SplitIfBlocks && do_split_ifs) {
2282         if (lpt->policy_range_check(this)) {
2283           lpt->_rce_candidate = 1; // = true
2284         }
2285       }
2286     }
2287   }
2288 
2289   // Check for aggressive application of split-if and other transforms
2290   // that require basic-block info (like cloning through Phi's)
2291   if( SplitIfBlocks && do_split_ifs ) {
2292     visited.Clear();
2293     split_if_with_blocks( visited, nstack );
2294     NOT_PRODUCT( if( VerifyLoopOptimizations ) verify(); );
2295   }
2296 
2297   if (!C->major_progress() && do_expensive_nodes && process_expensive_nodes()) {
2298     C->set_major_progress();
2299   }
2300 
2301   // Perform loop predication before iteration splitting
2302   if (C->has_loops() && !C->major_progress() && (C->predicate_count() > 0)) {
2303     _ltree_root->_child->loop_predication(this);
2304   }
2305 
2306   if (OptimizeFill && UseLoopPredicate && C->has_loops() && !C->major_progress()) {
2307     if (do_intrinsify_fill()) {
2308       C->set_major_progress();
2309     }
2310   }
2311 
2312   // Perform iteration-splitting on inner loops.  Split iterations to avoid
2313   // range checks or one-shot null checks.
2314 
2315   // If split-if's didn't hack the graph too bad (no CFG changes)
2316   // then do loop opts.
2317   if (C->has_loops() && !C->major_progress()) {
2318     memset( worklist.adr(), 0, worklist.Size()*sizeof(Node*) );
2319     _ltree_root->_child->iteration_split( this, worklist );
2320     // No verify after peeling!  GCM has hoisted code out of the loop.
2321     // After peeling, the hoisted code could sink inside the peeled area.
2322     // The peeling code does not try to recompute the best location for
2323     // all the code before the peeled area, so the verify pass will always
2324     // complain about it.
2325   }
2326   // Do verify graph edges in any case
2327   NOT_PRODUCT( C->verify_graph_edges(); );
2328 
2329   if (!do_split_ifs) {
2330     // We saw major progress in Split-If to get here.  We forced a
2331     // pass with unrolling and not split-if, however more split-if's
2332     // might make progress.  If the unrolling didn't make progress
2333     // then the major-progress flag got cleared and we won't try
2334     // another round of Split-If.  In particular the ever-common
2335     // instance-of/check-cast pattern requires at least 2 rounds of
2336     // Split-If to clear out.
2337     C->set_major_progress();
2338   }
2339 
2340   // Repeat loop optimizations if new loops were seen
2341   if (created_loop_node()) {
2342     C->set_major_progress();
2343   }
2344 
2345   // Keep loop predicates and perform optimizations with them
2346   // until no more loop optimizations could be done.
2347   // After that switch predicates off and do more loop optimizations.
2348   if (!C->major_progress() && (C->predicate_count() > 0)) {
2349      C->cleanup_loop_predicates(_igvn);
2350      if (TraceLoopOpts) {
2351        tty->print_cr("PredicatesOff");
2352      }
2353      C->set_major_progress();
2354   }
2355 
2356   // Convert scalar to superword operations at the end of all loop opts.
2357   if (UseSuperWord && C->has_loops() && !C->major_progress()) {
2358     // SuperWord transform
2359     SuperWord sw(this);
2360     for (LoopTreeIterator iter(_ltree_root); !iter.done(); iter.next()) {
2361       IdealLoopTree* lpt = iter.current();
2362       if (lpt->is_counted()) {
2363         CountedLoopNode *cl = lpt->_head->as_CountedLoop();
2364 
2365         if (PostLoopMultiversioning && cl->is_rce_post_loop() && !cl->is_vectorized_loop()) {
2366           // Check that the rce'd post loop is encountered first, multiversion after all
2367           // major main loop optimization are concluded
2368           if (!C->major_progress()) {
2369             IdealLoopTree *lpt_next = lpt->_next;
2370             if (lpt_next && lpt_next->is_counted()) {
2371               CountedLoopNode *cl = lpt_next->_head->as_CountedLoop();
2372               has_range_checks(lpt_next);
2373               if (cl->is_post_loop() && cl->range_checks_present()) {
2374                 if (!cl->is_multiversioned()) {
2375                   if (multi_version_post_loops(lpt, lpt_next) == false) {
2376                     // Cause the rce loop to be optimized away if we fail
2377                     cl->mark_is_multiversioned();
2378                     cl->set_slp_max_unroll(0);
2379                     poison_rce_post_loop(lpt);
2380                   }
2381                 }
2382               }
2383             }
2384             sw.transform_loop(lpt, true);
2385           }
2386         } else if (cl->is_main_loop()) {
2387           sw.transform_loop(lpt, true);
2388         }
2389       }
2390     }
2391   }
2392 
2393   // Cleanup any modified bits
2394   _igvn.optimize();
2395 
2396   // disable assert until issue with split_flow_path is resolved (6742111)
2397   // assert(!_has_irreducible_loops || C->parsed_irreducible_loop() || C->is_osr_compilation(),
2398   //        "shouldn't introduce irreducible loops");
2399 
2400   if (C->log() != NULL) {
2401     log_loop_tree(_ltree_root, _ltree_root, C->log());
2402   }
2403 }
2404 
2405 #ifndef PRODUCT
2406 //------------------------------print_statistics-------------------------------
2407 int PhaseIdealLoop::_loop_invokes=0;// Count of PhaseIdealLoop invokes
2408 int PhaseIdealLoop::_loop_work=0; // Sum of PhaseIdealLoop x unique
2409 void PhaseIdealLoop::print_statistics() {
2410   tty->print_cr("PhaseIdealLoop=%d, sum _unique=%d", _loop_invokes, _loop_work);
2411 }
2412 
2413 //------------------------------verify-----------------------------------------
2414 // Build a verify-only PhaseIdealLoop, and see that it agrees with me.
2415 static int fail;                // debug only, so its multi-thread dont care
2416 void PhaseIdealLoop::verify() const {
2417   int old_progress = C->major_progress();
2418   ResourceMark rm;
2419   PhaseIdealLoop loop_verify( _igvn, this );
2420   VectorSet visited(Thread::current()->resource_area());
2421 
2422   fail = 0;
2423   verify_compare( C->root(), &loop_verify, visited );
2424   assert( fail == 0, "verify loops failed" );
2425   // Verify loop structure is the same
2426   _ltree_root->verify_tree(loop_verify._ltree_root, NULL);
2427   // Reset major-progress.  It was cleared by creating a verify version of
2428   // PhaseIdealLoop.
2429   for( int i=0; i<old_progress; i++ )
2430     C->set_major_progress();
2431 }
2432 
2433 //------------------------------verify_compare---------------------------------
2434 // Make sure me and the given PhaseIdealLoop agree on key data structures
2435 void PhaseIdealLoop::verify_compare( Node *n, const PhaseIdealLoop *loop_verify, VectorSet &visited ) const {
2436   if( !n ) return;
2437   if( visited.test_set( n->_idx ) ) return;
2438   if( !_nodes[n->_idx] ) {      // Unreachable
2439     assert( !loop_verify->_nodes[n->_idx], "both should be unreachable" );
2440     return;
2441   }
2442 
2443   uint i;
2444   for( i = 0; i < n->req(); i++ )
2445     verify_compare( n->in(i), loop_verify, visited );
2446 
2447   // Check the '_nodes' block/loop structure
2448   i = n->_idx;
2449   if( has_ctrl(n) ) {           // We have control; verify has loop or ctrl
2450     if( _nodes[i] != loop_verify->_nodes[i] &&
2451         get_ctrl_no_update(n) != loop_verify->get_ctrl_no_update(n) ) {
2452       tty->print("Mismatched control setting for: ");
2453       n->dump();
2454       if( fail++ > 10 ) return;
2455       Node *c = get_ctrl_no_update(n);
2456       tty->print("We have it as: ");
2457       if( c->in(0) ) c->dump();
2458         else tty->print_cr("N%d",c->_idx);
2459       tty->print("Verify thinks: ");
2460       if( loop_verify->has_ctrl(n) )
2461         loop_verify->get_ctrl_no_update(n)->dump();
2462       else
2463         loop_verify->get_loop_idx(n)->dump();
2464       tty->cr();
2465     }
2466   } else {                    // We have a loop
2467     IdealLoopTree *us = get_loop_idx(n);
2468     if( loop_verify->has_ctrl(n) ) {
2469       tty->print("Mismatched loop setting for: ");
2470       n->dump();
2471       if( fail++ > 10 ) return;
2472       tty->print("We have it as: ");
2473       us->dump();
2474       tty->print("Verify thinks: ");
2475       loop_verify->get_ctrl_no_update(n)->dump();
2476       tty->cr();
2477     } else if (!C->major_progress()) {
2478       // Loop selection can be messed up if we did a major progress
2479       // operation, like split-if.  Do not verify in that case.
2480       IdealLoopTree *them = loop_verify->get_loop_idx(n);
2481       if( us->_head != them->_head ||  us->_tail != them->_tail ) {
2482         tty->print("Unequals loops for: ");
2483         n->dump();
2484         if( fail++ > 10 ) return;
2485         tty->print("We have it as: ");
2486         us->dump();
2487         tty->print("Verify thinks: ");
2488         them->dump();
2489         tty->cr();
2490       }
2491     }
2492   }
2493 
2494   // Check for immediate dominators being equal
2495   if( i >= _idom_size ) {
2496     if( !n->is_CFG() ) return;
2497     tty->print("CFG Node with no idom: ");
2498     n->dump();
2499     return;
2500   }
2501   if( !n->is_CFG() ) return;
2502   if( n == C->root() ) return; // No IDOM here
2503 
2504   assert(n->_idx == i, "sanity");
2505   Node *id = idom_no_update(n);
2506   if( id != loop_verify->idom_no_update(n) ) {
2507     tty->print("Unequals idoms for: ");
2508     n->dump();
2509     if( fail++ > 10 ) return;
2510     tty->print("We have it as: ");
2511     id->dump();
2512     tty->print("Verify thinks: ");
2513     loop_verify->idom_no_update(n)->dump();
2514     tty->cr();
2515   }
2516 
2517 }
2518 
2519 //------------------------------verify_tree------------------------------------
2520 // Verify that tree structures match.  Because the CFG can change, siblings
2521 // within the loop tree can be reordered.  We attempt to deal with that by
2522 // reordering the verify's loop tree if possible.
2523 void IdealLoopTree::verify_tree(IdealLoopTree *loop, const IdealLoopTree *parent) const {
2524   assert( _parent == parent, "Badly formed loop tree" );
2525 
2526   // Siblings not in same order?  Attempt to re-order.
2527   if( _head != loop->_head ) {
2528     // Find _next pointer to update
2529     IdealLoopTree **pp = &loop->_parent->_child;
2530     while( *pp != loop )
2531       pp = &((*pp)->_next);
2532     // Find proper sibling to be next
2533     IdealLoopTree **nn = &loop->_next;
2534     while( (*nn) && (*nn)->_head != _head )
2535       nn = &((*nn)->_next);
2536 
2537     // Check for no match.
2538     if( !(*nn) ) {
2539       // Annoyingly, irreducible loops can pick different headers
2540       // after a major_progress operation, so the rest of the loop
2541       // tree cannot be matched.
2542       if (_irreducible && Compile::current()->major_progress())  return;
2543       assert( 0, "failed to match loop tree" );
2544     }
2545 
2546     // Move (*nn) to (*pp)
2547     IdealLoopTree *hit = *nn;
2548     *nn = hit->_next;
2549     hit->_next = loop;
2550     *pp = loop;
2551     loop = hit;
2552     // Now try again to verify
2553   }
2554 
2555   assert( _head  == loop->_head , "mismatched loop head" );
2556   Node *tail = _tail;           // Inline a non-updating version of
2557   while( !tail->in(0) )         // the 'tail()' call.
2558     tail = tail->in(1);
2559   assert( tail == loop->_tail, "mismatched loop tail" );
2560 
2561   // Counted loops that are guarded should be able to find their guards
2562   if( _head->is_CountedLoop() && _head->as_CountedLoop()->is_main_loop() ) {
2563     CountedLoopNode *cl = _head->as_CountedLoop();
2564     Node *init = cl->init_trip();
2565     Node *ctrl = cl->in(LoopNode::EntryControl);
2566     assert( ctrl->Opcode() == Op_IfTrue || ctrl->Opcode() == Op_IfFalse, "" );
2567     Node *iff  = ctrl->in(0);
2568     assert( iff->Opcode() == Op_If, "" );
2569     Node *bol  = iff->in(1);
2570     assert( bol->Opcode() == Op_Bool, "" );
2571     Node *cmp  = bol->in(1);
2572     assert( cmp->Opcode() == Op_CmpI, "" );
2573     Node *add  = cmp->in(1);
2574     Node *opaq;
2575     if( add->Opcode() == Op_Opaque1 ) {
2576       opaq = add;
2577     } else {
2578       assert( add->Opcode() == Op_AddI || add->Opcode() == Op_ConI , "" );
2579       assert( add == init, "" );
2580       opaq = cmp->in(2);
2581     }
2582     assert( opaq->Opcode() == Op_Opaque1, "" );
2583 
2584   }
2585 
2586   if (_child != NULL)  _child->verify_tree(loop->_child, this);
2587   if (_next  != NULL)  _next ->verify_tree(loop->_next,  parent);
2588   // Innermost loops need to verify loop bodies,
2589   // but only if no 'major_progress'
2590   int fail = 0;
2591   if (!Compile::current()->major_progress() && _child == NULL) {
2592     for( uint i = 0; i < _body.size(); i++ ) {
2593       Node *n = _body.at(i);
2594       if (n->outcnt() == 0)  continue; // Ignore dead
2595       uint j;
2596       for( j = 0; j < loop->_body.size(); j++ )
2597         if( loop->_body.at(j) == n )
2598           break;
2599       if( j == loop->_body.size() ) { // Not found in loop body
2600         // Last ditch effort to avoid assertion: Its possible that we
2601         // have some users (so outcnt not zero) but are still dead.
2602         // Try to find from root.
2603         if (Compile::current()->root()->find(n->_idx)) {
2604           fail++;
2605           tty->print("We have that verify does not: ");
2606           n->dump();
2607         }
2608       }
2609     }
2610     for( uint i2 = 0; i2 < loop->_body.size(); i2++ ) {
2611       Node *n = loop->_body.at(i2);
2612       if (n->outcnt() == 0)  continue; // Ignore dead
2613       uint j;
2614       for( j = 0; j < _body.size(); j++ )
2615         if( _body.at(j) == n )
2616           break;
2617       if( j == _body.size() ) { // Not found in loop body
2618         // Last ditch effort to avoid assertion: Its possible that we
2619         // have some users (so outcnt not zero) but are still dead.
2620         // Try to find from root.
2621         if (Compile::current()->root()->find(n->_idx)) {
2622           fail++;
2623           tty->print("Verify has that we do not: ");
2624           n->dump();
2625         }
2626       }
2627     }
2628     assert( !fail, "loop body mismatch" );
2629   }
2630 }
2631 
2632 #endif
2633 
2634 //------------------------------set_idom---------------------------------------
2635 void PhaseIdealLoop::set_idom(Node* d, Node* n, uint dom_depth) {
2636   uint idx = d->_idx;
2637   if (idx >= _idom_size) {
2638     uint newsize = _idom_size<<1;
2639     while( idx >= newsize ) {
2640       newsize <<= 1;
2641     }
2642     _idom      = REALLOC_RESOURCE_ARRAY( Node*,     _idom,_idom_size,newsize);
2643     _dom_depth = REALLOC_RESOURCE_ARRAY( uint, _dom_depth,_idom_size,newsize);
2644     memset( _dom_depth + _idom_size, 0, (newsize - _idom_size) * sizeof(uint) );
2645     _idom_size = newsize;
2646   }
2647   _idom[idx] = n;
2648   _dom_depth[idx] = dom_depth;
2649 }
2650 
2651 //------------------------------recompute_dom_depth---------------------------------------
2652 // The dominator tree is constructed with only parent pointers.
2653 // This recomputes the depth in the tree by first tagging all
2654 // nodes as "no depth yet" marker.  The next pass then runs up
2655 // the dom tree from each node marked "no depth yet", and computes
2656 // the depth on the way back down.
2657 void PhaseIdealLoop::recompute_dom_depth() {
2658   uint no_depth_marker = C->unique();
2659   uint i;
2660   // Initialize depth to "no depth yet"
2661   for (i = 0; i < _idom_size; i++) {
2662     if (_dom_depth[i] > 0 && _idom[i] != NULL) {
2663      _dom_depth[i] = no_depth_marker;
2664     }
2665   }
2666   if (_dom_stk == NULL) {
2667     uint init_size = C->live_nodes() / 100; // Guess that 1/100 is a reasonable initial size.
2668     if (init_size < 10) init_size = 10;
2669     _dom_stk = new GrowableArray<uint>(init_size);
2670   }
2671   // Compute new depth for each node.
2672   for (i = 0; i < _idom_size; i++) {
2673     uint j = i;
2674     // Run up the dom tree to find a node with a depth
2675     while (_dom_depth[j] == no_depth_marker) {
2676       _dom_stk->push(j);
2677       j = _idom[j]->_idx;
2678     }
2679     // Compute the depth on the way back down this tree branch
2680     uint dd = _dom_depth[j] + 1;
2681     while (_dom_stk->length() > 0) {
2682       uint j = _dom_stk->pop();
2683       _dom_depth[j] = dd;
2684       dd++;
2685     }
2686   }
2687 }
2688 
2689 //------------------------------sort-------------------------------------------
2690 // Insert 'loop' into the existing loop tree.  'innermost' is a leaf of the
2691 // loop tree, not the root.
2692 IdealLoopTree *PhaseIdealLoop::sort( IdealLoopTree *loop, IdealLoopTree *innermost ) {
2693   if( !innermost ) return loop; // New innermost loop
2694 
2695   int loop_preorder = get_preorder(loop->_head); // Cache pre-order number
2696   assert( loop_preorder, "not yet post-walked loop" );
2697   IdealLoopTree **pp = &innermost;      // Pointer to previous next-pointer
2698   IdealLoopTree *l = *pp;               // Do I go before or after 'l'?
2699 
2700   // Insert at start of list
2701   while( l ) {                  // Insertion sort based on pre-order
2702     if( l == loop ) return innermost; // Already on list!
2703     int l_preorder = get_preorder(l->_head); // Cache pre-order number
2704     assert( l_preorder, "not yet post-walked l" );
2705     // Check header pre-order number to figure proper nesting
2706     if( loop_preorder > l_preorder )
2707       break;                    // End of insertion
2708     // If headers tie (e.g., shared headers) check tail pre-order numbers.
2709     // Since I split shared headers, you'd think this could not happen.
2710     // BUT: I must first do the preorder numbering before I can discover I
2711     // have shared headers, so the split headers all get the same preorder
2712     // number as the RegionNode they split from.
2713     if( loop_preorder == l_preorder &&
2714         get_preorder(loop->_tail) < get_preorder(l->_tail) )
2715       break;                    // Also check for shared headers (same pre#)
2716     pp = &l->_parent;           // Chain up list
2717     l = *pp;
2718   }
2719   // Link into list
2720   // Point predecessor to me
2721   *pp = loop;
2722   // Point me to successor
2723   IdealLoopTree *p = loop->_parent;
2724   loop->_parent = l;            // Point me to successor
2725   if( p ) sort( p, innermost ); // Insert my parents into list as well
2726   return innermost;
2727 }
2728 
2729 //------------------------------build_loop_tree--------------------------------
2730 // I use a modified Vick/Tarjan algorithm.  I need pre- and a post- visit
2731 // bits.  The _nodes[] array is mapped by Node index and holds a NULL for
2732 // not-yet-pre-walked, pre-order # for pre-but-not-post-walked and holds the
2733 // tightest enclosing IdealLoopTree for post-walked.
2734 //
2735 // During my forward walk I do a short 1-layer lookahead to see if I can find
2736 // a loop backedge with that doesn't have any work on the backedge.  This
2737 // helps me construct nested loops with shared headers better.
2738 //
2739 // Once I've done the forward recursion, I do the post-work.  For each child
2740 // I check to see if there is a backedge.  Backedges define a loop!  I
2741 // insert an IdealLoopTree at the target of the backedge.
2742 //
2743 // During the post-work I also check to see if I have several children
2744 // belonging to different loops.  If so, then this Node is a decision point
2745 // where control flow can choose to change loop nests.  It is at this
2746 // decision point where I can figure out how loops are nested.  At this
2747 // time I can properly order the different loop nests from my children.
2748 // Note that there may not be any backedges at the decision point!
2749 //
2750 // Since the decision point can be far removed from the backedges, I can't
2751 // order my loops at the time I discover them.  Thus at the decision point
2752 // I need to inspect loop header pre-order numbers to properly nest my
2753 // loops.  This means I need to sort my childrens' loops by pre-order.
2754 // The sort is of size number-of-control-children, which generally limits
2755 // it to size 2 (i.e., I just choose between my 2 target loops).
2756 void PhaseIdealLoop::build_loop_tree() {
2757   // Allocate stack of size C->live_nodes()/2 to avoid frequent realloc
2758   GrowableArray <Node *> bltstack(C->live_nodes() >> 1);
2759   Node *n = C->root();
2760   bltstack.push(n);
2761   int pre_order = 1;
2762   int stack_size;
2763 
2764   while ( ( stack_size = bltstack.length() ) != 0 ) {
2765     n = bltstack.top(); // Leave node on stack
2766     if ( !is_visited(n) ) {
2767       // ---- Pre-pass Work ----
2768       // Pre-walked but not post-walked nodes need a pre_order number.
2769 
2770       set_preorder_visited( n, pre_order ); // set as visited
2771 
2772       // ---- Scan over children ----
2773       // Scan first over control projections that lead to loop headers.
2774       // This helps us find inner-to-outer loops with shared headers better.
2775 
2776       // Scan children's children for loop headers.
2777       for ( int i = n->outcnt() - 1; i >= 0; --i ) {
2778         Node* m = n->raw_out(i);       // Child
2779         if( m->is_CFG() && !is_visited(m) ) { // Only for CFG children
2780           // Scan over children's children to find loop
2781           for (DUIterator_Fast jmax, j = m->fast_outs(jmax); j < jmax; j++) {
2782             Node* l = m->fast_out(j);
2783             if( is_visited(l) &&       // Been visited?
2784                 !is_postvisited(l) &&  // But not post-visited
2785                 get_preorder(l) < pre_order ) { // And smaller pre-order
2786               // Found!  Scan the DFS down this path before doing other paths
2787               bltstack.push(m);
2788               break;
2789             }
2790           }
2791         }
2792       }
2793       pre_order++;
2794     }
2795     else if ( !is_postvisited(n) ) {
2796       // Note: build_loop_tree_impl() adds out edges on rare occasions,
2797       // such as com.sun.rsasign.am::a.
2798       // For non-recursive version, first, process current children.
2799       // On next iteration, check if additional children were added.
2800       for ( int k = n->outcnt() - 1; k >= 0; --k ) {
2801         Node* u = n->raw_out(k);
2802         if ( u->is_CFG() && !is_visited(u) ) {
2803           bltstack.push(u);
2804         }
2805       }
2806       if ( bltstack.length() == stack_size ) {
2807         // There were no additional children, post visit node now
2808         (void)bltstack.pop(); // Remove node from stack
2809         pre_order = build_loop_tree_impl( n, pre_order );
2810         // Check for bailout
2811         if (C->failing()) {
2812           return;
2813         }
2814         // Check to grow _preorders[] array for the case when
2815         // build_loop_tree_impl() adds new nodes.
2816         check_grow_preorders();
2817       }
2818     }
2819     else {
2820       (void)bltstack.pop(); // Remove post-visited node from stack
2821     }
2822   }
2823 }
2824 
2825 //------------------------------build_loop_tree_impl---------------------------
2826 int PhaseIdealLoop::build_loop_tree_impl( Node *n, int pre_order ) {
2827   // ---- Post-pass Work ----
2828   // Pre-walked but not post-walked nodes need a pre_order number.
2829 
2830   // Tightest enclosing loop for this Node
2831   IdealLoopTree *innermost = NULL;
2832 
2833   // For all children, see if any edge is a backedge.  If so, make a loop
2834   // for it.  Then find the tightest enclosing loop for the self Node.
2835   for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
2836     Node* m = n->fast_out(i);   // Child
2837     if( n == m ) continue;      // Ignore control self-cycles
2838     if( !m->is_CFG() ) continue;// Ignore non-CFG edges
2839 
2840     IdealLoopTree *l;           // Child's loop
2841     if( !is_postvisited(m) ) {  // Child visited but not post-visited?
2842       // Found a backedge
2843       assert( get_preorder(m) < pre_order, "should be backedge" );
2844       // Check for the RootNode, which is already a LoopNode and is allowed
2845       // to have multiple "backedges".
2846       if( m == C->root()) {     // Found the root?
2847         l = _ltree_root;        // Root is the outermost LoopNode
2848       } else {                  // Else found a nested loop
2849         // Insert a LoopNode to mark this loop.
2850         l = new IdealLoopTree(this, m, n);
2851       } // End of Else found a nested loop
2852       if( !has_loop(m) )        // If 'm' does not already have a loop set
2853         set_loop(m, l);         // Set loop header to loop now
2854 
2855     } else {                    // Else not a nested loop
2856       if( !_nodes[m->_idx] ) continue; // Dead code has no loop
2857       l = get_loop(m);          // Get previously determined loop
2858       // If successor is header of a loop (nest), move up-loop till it
2859       // is a member of some outer enclosing loop.  Since there are no
2860       // shared headers (I've split them already) I only need to go up
2861       // at most 1 level.
2862       while( l && l->_head == m ) // Successor heads loop?
2863         l = l->_parent;         // Move up 1 for me
2864       // If this loop is not properly parented, then this loop
2865       // has no exit path out, i.e. its an infinite loop.
2866       if( !l ) {
2867         // Make loop "reachable" from root so the CFG is reachable.  Basically
2868         // insert a bogus loop exit that is never taken.  'm', the loop head,
2869         // points to 'n', one (of possibly many) fall-in paths.  There may be
2870         // many backedges as well.
2871 
2872         // Here I set the loop to be the root loop.  I could have, after
2873         // inserting a bogus loop exit, restarted the recursion and found my
2874         // new loop exit.  This would make the infinite loop a first-class
2875         // loop and it would then get properly optimized.  What's the use of
2876         // optimizing an infinite loop?
2877         l = _ltree_root;        // Oops, found infinite loop
2878 
2879         if (!_verify_only) {
2880           // Insert the NeverBranch between 'm' and it's control user.
2881           NeverBranchNode *iff = new NeverBranchNode( m );
2882           _igvn.register_new_node_with_optimizer(iff);
2883           set_loop(iff, l);
2884           Node *if_t = new CProjNode( iff, 0 );
2885           _igvn.register_new_node_with_optimizer(if_t);
2886           set_loop(if_t, l);
2887 
2888           Node* cfg = NULL;       // Find the One True Control User of m
2889           for (DUIterator_Fast jmax, j = m->fast_outs(jmax); j < jmax; j++) {
2890             Node* x = m->fast_out(j);
2891             if (x->is_CFG() && x != m && x != iff)
2892               { cfg = x; break; }
2893           }
2894           assert(cfg != NULL, "must find the control user of m");
2895           uint k = 0;             // Probably cfg->in(0)
2896           while( cfg->in(k) != m ) k++; // But check incase cfg is a Region
2897           cfg->set_req( k, if_t ); // Now point to NeverBranch
2898           _igvn._worklist.push(cfg);
2899 
2900           // Now create the never-taken loop exit
2901           Node *if_f = new CProjNode( iff, 1 );
2902           _igvn.register_new_node_with_optimizer(if_f);
2903           set_loop(if_f, l);
2904           // Find frame ptr for Halt.  Relies on the optimizer
2905           // V-N'ing.  Easier and quicker than searching through
2906           // the program structure.
2907           Node *frame = new ParmNode( C->start(), TypeFunc::FramePtr );
2908           _igvn.register_new_node_with_optimizer(frame);
2909           // Halt & Catch Fire
2910           Node *halt = new HaltNode( if_f, frame );
2911           _igvn.register_new_node_with_optimizer(halt);
2912           set_loop(halt, l);
2913           C->root()->add_req(halt);
2914         }
2915         set_loop(C->root(), _ltree_root);
2916       }
2917     }
2918     // Weeny check for irreducible.  This child was already visited (this
2919     // IS the post-work phase).  Is this child's loop header post-visited
2920     // as well?  If so, then I found another entry into the loop.
2921     if (!_verify_only) {
2922       while( is_postvisited(l->_head) ) {
2923         // found irreducible
2924         l->_irreducible = 1; // = true
2925         l = l->_parent;
2926         _has_irreducible_loops = true;
2927         // Check for bad CFG here to prevent crash, and bailout of compile
2928         if (l == NULL) {
2929           C->record_method_not_compilable("unhandled CFG detected during loop optimization");
2930           return pre_order;
2931         }
2932       }
2933       C->set_has_irreducible_loop(_has_irreducible_loops);
2934     }
2935 
2936     // This Node might be a decision point for loops.  It is only if
2937     // it's children belong to several different loops.  The sort call
2938     // does a trivial amount of work if there is only 1 child or all
2939     // children belong to the same loop.  If however, the children
2940     // belong to different loops, the sort call will properly set the
2941     // _parent pointers to show how the loops nest.
2942     //
2943     // In any case, it returns the tightest enclosing loop.
2944     innermost = sort( l, innermost );
2945   }
2946 
2947   // Def-use info will have some dead stuff; dead stuff will have no
2948   // loop decided on.
2949 
2950   // Am I a loop header?  If so fix up my parent's child and next ptrs.
2951   if( innermost && innermost->_head == n ) {
2952     assert( get_loop(n) == innermost, "" );
2953     IdealLoopTree *p = innermost->_parent;
2954     IdealLoopTree *l = innermost;
2955     while( p && l->_head == n ) {
2956       l->_next = p->_child;     // Put self on parents 'next child'
2957       p->_child = l;            // Make self as first child of parent
2958       l = p;                    // Now walk up the parent chain
2959       p = l->_parent;
2960     }
2961   } else {
2962     // Note that it is possible for a LoopNode to reach here, if the
2963     // backedge has been made unreachable (hence the LoopNode no longer
2964     // denotes a Loop, and will eventually be removed).
2965 
2966     // Record tightest enclosing loop for self.  Mark as post-visited.
2967     set_loop(n, innermost);
2968     // Also record has_call flag early on
2969     if( innermost ) {
2970       if( n->is_Call() && !n->is_CallLeaf() && !n->is_macro() ) {
2971         // Do not count uncommon calls
2972         if( !n->is_CallStaticJava() || !n->as_CallStaticJava()->_name ) {
2973           Node *iff = n->in(0)->in(0);
2974           // No any calls for vectorized loops.
2975           if( UseSuperWord || !iff->is_If() ||
2976               (n->in(0)->Opcode() == Op_IfFalse &&
2977                (1.0 - iff->as_If()->_prob) >= 0.01) ||
2978               (iff->as_If()->_prob >= 0.01) )
2979             innermost->_has_call = 1;
2980         }
2981       } else if( n->is_Allocate() && n->as_Allocate()->_is_scalar_replaceable ) {
2982         // Disable loop optimizations if the loop has a scalar replaceable
2983         // allocation. This disabling may cause a potential performance lost
2984         // if the allocation is not eliminated for some reason.
2985         innermost->_allow_optimizations = false;
2986         innermost->_has_call = 1; // = true
2987       } else if (n->Opcode() == Op_SafePoint) {
2988         // Record all safepoints in this loop.
2989         if (innermost->_safepts == NULL) innermost->_safepts = new Node_List();
2990         innermost->_safepts->push(n);
2991       }
2992     }
2993   }
2994 
2995   // Flag as post-visited now
2996   set_postvisited(n);
2997   return pre_order;
2998 }
2999 
3000 
3001 //------------------------------build_loop_early-------------------------------
3002 // Put Data nodes into some loop nest, by setting the _nodes[]->loop mapping.
3003 // First pass computes the earliest controlling node possible.  This is the
3004 // controlling input with the deepest dominating depth.
3005 void PhaseIdealLoop::build_loop_early( VectorSet &visited, Node_List &worklist, Node_Stack &nstack ) {
3006   while (worklist.size() != 0) {
3007     // Use local variables nstack_top_n & nstack_top_i to cache values
3008     // on nstack's top.
3009     Node *nstack_top_n = worklist.pop();
3010     uint  nstack_top_i = 0;
3011 //while_nstack_nonempty:
3012     while (true) {
3013       // Get parent node and next input's index from stack's top.
3014       Node  *n = nstack_top_n;
3015       uint   i = nstack_top_i;
3016       uint cnt = n->req(); // Count of inputs
3017       if (i == 0) {        // Pre-process the node.
3018         if( has_node(n) &&            // Have either loop or control already?
3019             !has_ctrl(n) ) {          // Have loop picked out already?
3020           // During "merge_many_backedges" we fold up several nested loops
3021           // into a single loop.  This makes the members of the original
3022           // loop bodies pointing to dead loops; they need to move up
3023           // to the new UNION'd larger loop.  I set the _head field of these
3024           // dead loops to NULL and the _parent field points to the owning
3025           // loop.  Shades of UNION-FIND algorithm.
3026           IdealLoopTree *ilt;
3027           while( !(ilt = get_loop(n))->_head ) {
3028             // Normally I would use a set_loop here.  But in this one special
3029             // case, it is legal (and expected) to change what loop a Node
3030             // belongs to.
3031             _nodes.map(n->_idx, (Node*)(ilt->_parent) );
3032           }
3033           // Remove safepoints ONLY if I've already seen I don't need one.
3034           // (the old code here would yank a 2nd safepoint after seeing a
3035           // first one, even though the 1st did not dominate in the loop body
3036           // and thus could be avoided indefinitely)
3037           if( !_verify_only && !_verify_me && ilt->_has_sfpt && n->Opcode() == Op_SafePoint &&
3038               is_deleteable_safept(n)) {
3039             Node *in = n->in(TypeFunc::Control);
3040             lazy_replace(n,in);       // Pull safepoint now
3041             if (ilt->_safepts != NULL) {
3042               ilt->_safepts->yank(n);
3043             }
3044             // Carry on with the recursion "as if" we are walking
3045             // only the control input
3046             if( !visited.test_set( in->_idx ) ) {
3047               worklist.push(in);      // Visit this guy later, using worklist
3048             }
3049             // Get next node from nstack:
3050             // - skip n's inputs processing by setting i > cnt;
3051             // - we also will not call set_early_ctrl(n) since
3052             //   has_node(n) == true (see the condition above).
3053             i = cnt + 1;
3054           }
3055         }
3056       } // if (i == 0)
3057 
3058       // Visit all inputs
3059       bool done = true;       // Assume all n's inputs will be processed
3060       while (i < cnt) {
3061         Node *in = n->in(i);
3062         ++i;
3063         if (in == NULL) continue;
3064         if (in->pinned() && !in->is_CFG())
3065           set_ctrl(in, in->in(0));
3066         int is_visited = visited.test_set( in->_idx );
3067         if (!has_node(in)) {  // No controlling input yet?
3068           assert( !in->is_CFG(), "CFG Node with no controlling input?" );
3069           assert( !is_visited, "visit only once" );
3070           nstack.push(n, i);  // Save parent node and next input's index.
3071           nstack_top_n = in;  // Process current input now.
3072           nstack_top_i = 0;
3073           done = false;       // Not all n's inputs processed.
3074           break; // continue while_nstack_nonempty;
3075         } else if (!is_visited) {
3076           // This guy has a location picked out for him, but has not yet
3077           // been visited.  Happens to all CFG nodes, for instance.
3078           // Visit him using the worklist instead of recursion, to break
3079           // cycles.  Since he has a location already we do not need to
3080           // find his location before proceeding with the current Node.
3081           worklist.push(in);  // Visit this guy later, using worklist
3082         }
3083       }
3084       if (done) {
3085         // All of n's inputs have been processed, complete post-processing.
3086 
3087         // Compute earliest point this Node can go.
3088         // CFG, Phi, pinned nodes already know their controlling input.
3089         if (!has_node(n)) {
3090           // Record earliest legal location
3091           set_early_ctrl( n );
3092         }
3093         if (nstack.is_empty()) {
3094           // Finished all nodes on stack.
3095           // Process next node on the worklist.
3096           break;
3097         }
3098         // Get saved parent node and next input's index.
3099         nstack_top_n = nstack.node();
3100         nstack_top_i = nstack.index();
3101         nstack.pop();
3102       }
3103     } // while (true)
3104   }
3105 }
3106 
3107 //------------------------------dom_lca_internal--------------------------------
3108 // Pair-wise LCA
3109 Node *PhaseIdealLoop::dom_lca_internal( Node *n1, Node *n2 ) const {
3110   if( !n1 ) return n2;          // Handle NULL original LCA
3111   assert( n1->is_CFG(), "" );
3112   assert( n2->is_CFG(), "" );
3113   // find LCA of all uses
3114   uint d1 = dom_depth(n1);
3115   uint d2 = dom_depth(n2);
3116   while (n1 != n2) {
3117     if (d1 > d2) {
3118       n1 =      idom(n1);
3119       d1 = dom_depth(n1);
3120     } else if (d1 < d2) {
3121       n2 =      idom(n2);
3122       d2 = dom_depth(n2);
3123     } else {
3124       // Here d1 == d2.  Due to edits of the dominator-tree, sections
3125       // of the tree might have the same depth.  These sections have
3126       // to be searched more carefully.
3127 
3128       // Scan up all the n1's with equal depth, looking for n2.
3129       Node *t1 = idom(n1);
3130       while (dom_depth(t1) == d1) {
3131         if (t1 == n2)  return n2;
3132         t1 = idom(t1);
3133       }
3134       // Scan up all the n2's with equal depth, looking for n1.
3135       Node *t2 = idom(n2);
3136       while (dom_depth(t2) == d2) {
3137         if (t2 == n1)  return n1;
3138         t2 = idom(t2);
3139       }
3140       // Move up to a new dominator-depth value as well as up the dom-tree.
3141       n1 = t1;
3142       n2 = t2;
3143       d1 = dom_depth(n1);
3144       d2 = dom_depth(n2);
3145     }
3146   }
3147   return n1;
3148 }
3149 
3150 //------------------------------compute_idom-----------------------------------
3151 // Locally compute IDOM using dom_lca call.  Correct only if the incoming
3152 // IDOMs are correct.
3153 Node *PhaseIdealLoop::compute_idom( Node *region ) const {
3154   assert( region->is_Region(), "" );
3155   Node *LCA = NULL;
3156   for( uint i = 1; i < region->req(); i++ ) {
3157     if( region->in(i) != C->top() )
3158       LCA = dom_lca( LCA, region->in(i) );
3159   }
3160   return LCA;
3161 }
3162 
3163 bool PhaseIdealLoop::verify_dominance(Node* n, Node* use, Node* LCA, Node* early) {
3164   bool had_error = false;
3165 #ifdef ASSERT
3166   if (early != C->root()) {
3167     // Make sure that there's a dominance path from LCA to early
3168     Node* d = LCA;
3169     while (d != early) {
3170       if (d == C->root()) {
3171         dump_bad_graph("Bad graph detected in compute_lca_of_uses", n, early, LCA);
3172         tty->print_cr("*** Use %d isn't dominated by def %d ***", use->_idx, n->_idx);
3173         had_error = true;
3174         break;
3175       }
3176       d = idom(d);
3177     }
3178   }
3179 #endif
3180   return had_error;
3181 }
3182 
3183 
3184 Node* PhaseIdealLoop::compute_lca_of_uses(Node* n, Node* early, bool verify) {
3185   // Compute LCA over list of uses
3186   bool had_error = false;
3187   Node *LCA = NULL;
3188   for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax && LCA != early; i++) {
3189     Node* c = n->fast_out(i);
3190     if (_nodes[c->_idx] == NULL)
3191       continue;                 // Skip the occasional dead node
3192     if( c->is_Phi() ) {         // For Phis, we must land above on the path
3193       for( uint j=1; j<c->req(); j++ ) {// For all inputs
3194         if( c->in(j) == n ) {   // Found matching input?
3195           Node *use = c->in(0)->in(j);
3196           if (_verify_only && use->is_top()) continue;
3197           LCA = dom_lca_for_get_late_ctrl( LCA, use, n );
3198           if (verify) had_error = verify_dominance(n, use, LCA, early) || had_error;
3199         }
3200       }
3201     } else {
3202       // For CFG data-users, use is in the block just prior
3203       Node *use = has_ctrl(c) ? get_ctrl(c) : c->in(0);
3204       LCA = dom_lca_for_get_late_ctrl( LCA, use, n );
3205       if (verify) had_error = verify_dominance(n, use, LCA, early) || had_error;
3206     }
3207   }
3208   assert(!had_error, "bad dominance");
3209   return LCA;
3210 }
3211 
3212 // Check the shape of the graph at the loop entry. In some cases,
3213 // the shape of the graph does not match the shape outlined below.
3214 // That is caused by the Opaque1 node "protecting" the shape of
3215 // the graph being removed by, for example, the IGVN performed
3216 // in PhaseIdealLoop::build_and_optimize().
3217 //
3218 // After the Opaque1 node has been removed, optimizations (e.g., split-if,
3219 // loop unswitching, and IGVN, or a combination of them) can freely change
3220 // the graph's shape. As a result, the graph shape outlined below cannot
3221 // be guaranteed anymore.
3222 bool PhaseIdealLoop::is_canonical_loop_entry(CountedLoopNode* cl) {
3223   if (!cl->is_main_loop() && !cl->is_post_loop()) {
3224     return false;
3225   }
3226   Node* ctrl = cl->in(LoopNode::EntryControl);
3227   if (ctrl == NULL || (!ctrl->is_IfTrue() && !ctrl->is_IfFalse())) {
3228     return false;
3229   }
3230   Node* iffm = ctrl->in(0);
3231   if (iffm == NULL || !iffm->is_If()) {
3232     return false;
3233   }
3234   Node* bolzm = iffm->in(1);
3235   if (bolzm == NULL || !bolzm->is_Bool()) {
3236     return false;
3237   }
3238   Node* cmpzm = bolzm->in(1);
3239   if (cmpzm == NULL || !cmpzm->is_Cmp()) {
3240     return false;
3241   }
3242   // compares can get conditionally flipped
3243   bool found_opaque = false;
3244   for (uint i = 1; i < cmpzm->req(); i++) {
3245     Node* opnd = cmpzm->in(i);
3246     if (opnd && opnd->Opcode() == Op_Opaque1) {
3247       found_opaque = true;
3248       break;
3249     }
3250   }
3251   if (!found_opaque) {
3252     return false;
3253   }
3254   return true;
3255 }
3256 
3257 //------------------------------get_late_ctrl----------------------------------
3258 // Compute latest legal control.
3259 Node *PhaseIdealLoop::get_late_ctrl( Node *n, Node *early ) {
3260   assert(early != NULL, "early control should not be NULL");
3261 
3262   Node* LCA = compute_lca_of_uses(n, early);
3263 #ifdef ASSERT
3264   if (LCA == C->root() && LCA != early) {
3265     // def doesn't dominate uses so print some useful debugging output
3266     compute_lca_of_uses(n, early, true);
3267   }
3268 #endif
3269 
3270   // if this is a load, check for anti-dependent stores
3271   // We use a conservative algorithm to identify potential interfering
3272   // instructions and for rescheduling the load.  The users of the memory
3273   // input of this load are examined.  Any use which is not a load and is
3274   // dominated by early is considered a potentially interfering store.
3275   // This can produce false positives.
3276   if (n->is_Load() && LCA != early) {
3277     Node_List worklist;
3278 
3279     Node *mem = n->in(MemNode::Memory);
3280     for (DUIterator_Fast imax, i = mem->fast_outs(imax); i < imax; i++) {
3281       Node* s = mem->fast_out(i);
3282       worklist.push(s);
3283     }
3284     while(worklist.size() != 0 && LCA != early) {
3285       Node* s = worklist.pop();
3286       if (s->is_Load()) {
3287         continue;
3288       } else if (s->is_MergeMem()) {
3289         for (DUIterator_Fast imax, i = s->fast_outs(imax); i < imax; i++) {
3290           Node* s1 = s->fast_out(i);
3291           worklist.push(s1);
3292         }
3293       } else {
3294         Node *sctrl = has_ctrl(s) ? get_ctrl(s) : s->in(0);
3295         assert(sctrl != NULL || s->outcnt() == 0, "must have control");
3296         if (sctrl != NULL && !sctrl->is_top() && is_dominator(early, sctrl)) {
3297           LCA = dom_lca_for_get_late_ctrl(LCA, sctrl, n);
3298         }
3299       }
3300     }
3301   }
3302 
3303   assert(LCA == find_non_split_ctrl(LCA), "unexpected late control");
3304   return LCA;
3305 }
3306 
3307 // true if CFG node d dominates CFG node n
3308 bool PhaseIdealLoop::is_dominator(Node *d, Node *n) {
3309   if (d == n)
3310     return true;
3311   assert(d->is_CFG() && n->is_CFG(), "must have CFG nodes");
3312   uint dd = dom_depth(d);
3313   while (dom_depth(n) >= dd) {
3314     if (n == d)
3315       return true;
3316     n = idom(n);
3317   }
3318   return false;
3319 }
3320 
3321 //------------------------------dom_lca_for_get_late_ctrl_internal-------------
3322 // Pair-wise LCA with tags.
3323 // Tag each index with the node 'tag' currently being processed
3324 // before advancing up the dominator chain using idom().
3325 // Later calls that find a match to 'tag' know that this path has already
3326 // been considered in the current LCA (which is input 'n1' by convention).
3327 // Since get_late_ctrl() is only called once for each node, the tag array
3328 // does not need to be cleared between calls to get_late_ctrl().
3329 // Algorithm trades a larger constant factor for better asymptotic behavior
3330 //
3331 Node *PhaseIdealLoop::dom_lca_for_get_late_ctrl_internal( Node *n1, Node *n2, Node *tag ) {
3332   uint d1 = dom_depth(n1);
3333   uint d2 = dom_depth(n2);
3334 
3335   do {
3336     if (d1 > d2) {
3337       // current lca is deeper than n2
3338       _dom_lca_tags.map(n1->_idx, tag);
3339       n1 =      idom(n1);
3340       d1 = dom_depth(n1);
3341     } else if (d1 < d2) {
3342       // n2 is deeper than current lca
3343       Node *memo = _dom_lca_tags[n2->_idx];
3344       if( memo == tag ) {
3345         return n1;    // Return the current LCA
3346       }
3347       _dom_lca_tags.map(n2->_idx, tag);
3348       n2 =      idom(n2);
3349       d2 = dom_depth(n2);
3350     } else {
3351       // Here d1 == d2.  Due to edits of the dominator-tree, sections
3352       // of the tree might have the same depth.  These sections have
3353       // to be searched more carefully.
3354 
3355       // Scan up all the n1's with equal depth, looking for n2.
3356       _dom_lca_tags.map(n1->_idx, tag);
3357       Node *t1 = idom(n1);
3358       while (dom_depth(t1) == d1) {
3359         if (t1 == n2)  return n2;
3360         _dom_lca_tags.map(t1->_idx, tag);
3361         t1 = idom(t1);
3362       }
3363       // Scan up all the n2's with equal depth, looking for n1.
3364       _dom_lca_tags.map(n2->_idx, tag);
3365       Node *t2 = idom(n2);
3366       while (dom_depth(t2) == d2) {
3367         if (t2 == n1)  return n1;
3368         _dom_lca_tags.map(t2->_idx, tag);
3369         t2 = idom(t2);
3370       }
3371       // Move up to a new dominator-depth value as well as up the dom-tree.
3372       n1 = t1;
3373       n2 = t2;
3374       d1 = dom_depth(n1);
3375       d2 = dom_depth(n2);
3376     }
3377   } while (n1 != n2);
3378   return n1;
3379 }
3380 
3381 //------------------------------init_dom_lca_tags------------------------------
3382 // Tag could be a node's integer index, 32bits instead of 64bits in some cases
3383 // Intended use does not involve any growth for the array, so it could
3384 // be of fixed size.
3385 void PhaseIdealLoop::init_dom_lca_tags() {
3386   uint limit = C->unique() + 1;
3387   _dom_lca_tags.map( limit, NULL );
3388 #ifdef ASSERT
3389   for( uint i = 0; i < limit; ++i ) {
3390     assert(_dom_lca_tags[i] == NULL, "Must be distinct from each node pointer");
3391   }
3392 #endif // ASSERT
3393 }
3394 
3395 //------------------------------clear_dom_lca_tags------------------------------
3396 // Tag could be a node's integer index, 32bits instead of 64bits in some cases
3397 // Intended use does not involve any growth for the array, so it could
3398 // be of fixed size.
3399 void PhaseIdealLoop::clear_dom_lca_tags() {
3400   uint limit = C->unique() + 1;
3401   _dom_lca_tags.map( limit, NULL );
3402   _dom_lca_tags.clear();
3403 #ifdef ASSERT
3404   for( uint i = 0; i < limit; ++i ) {
3405     assert(_dom_lca_tags[i] == NULL, "Must be distinct from each node pointer");
3406   }
3407 #endif // ASSERT
3408 }
3409 
3410 //------------------------------build_loop_late--------------------------------
3411 // Put Data nodes into some loop nest, by setting the _nodes[]->loop mapping.
3412 // Second pass finds latest legal placement, and ideal loop placement.
3413 void PhaseIdealLoop::build_loop_late( VectorSet &visited, Node_List &worklist, Node_Stack &nstack ) {
3414   while (worklist.size() != 0) {
3415     Node *n = worklist.pop();
3416     // Only visit once
3417     if (visited.test_set(n->_idx)) continue;
3418     uint cnt = n->outcnt();
3419     uint   i = 0;
3420     while (true) {
3421       assert( _nodes[n->_idx], "no dead nodes" );
3422       // Visit all children
3423       if (i < cnt) {
3424         Node* use = n->raw_out(i);
3425         ++i;
3426         // Check for dead uses.  Aggressively prune such junk.  It might be
3427         // dead in the global sense, but still have local uses so I cannot
3428         // easily call 'remove_dead_node'.
3429         if( _nodes[use->_idx] != NULL || use->is_top() ) { // Not dead?
3430           // Due to cycles, we might not hit the same fixed point in the verify
3431           // pass as we do in the regular pass.  Instead, visit such phis as
3432           // simple uses of the loop head.
3433           if( use->in(0) && (use->is_CFG() || use->is_Phi()) ) {
3434             if( !visited.test(use->_idx) )
3435               worklist.push(use);
3436           } else if( !visited.test_set(use->_idx) ) {
3437             nstack.push(n, i); // Save parent and next use's index.
3438             n   = use;         // Process all children of current use.
3439             cnt = use->outcnt();
3440             i   = 0;
3441           }
3442         } else {
3443           // Do not visit around the backedge of loops via data edges.
3444           // push dead code onto a worklist
3445           _deadlist.push(use);
3446         }
3447       } else {
3448         // All of n's children have been processed, complete post-processing.
3449         build_loop_late_post(n);
3450         if (nstack.is_empty()) {
3451           // Finished all nodes on stack.
3452           // Process next node on the worklist.
3453           break;
3454         }
3455         // Get saved parent node and next use's index. Visit the rest of uses.
3456         n   = nstack.node();
3457         cnt = n->outcnt();
3458         i   = nstack.index();
3459         nstack.pop();
3460       }
3461     }
3462   }
3463 }
3464 
3465 //------------------------------build_loop_late_post---------------------------
3466 // Put Data nodes into some loop nest, by setting the _nodes[]->loop mapping.
3467 // Second pass finds latest legal placement, and ideal loop placement.
3468 void PhaseIdealLoop::build_loop_late_post( Node *n ) {
3469 
3470   if (n->req() == 2 && (n->Opcode() == Op_ConvI2L || n->Opcode() == Op_CastII) && !C->major_progress() && !_verify_only) {
3471     _igvn._worklist.push(n);  // Maybe we'll normalize it, if no more loops.
3472   }
3473 
3474 #ifdef ASSERT
3475   if (_verify_only && !n->is_CFG()) {
3476     // Check def-use domination.
3477     compute_lca_of_uses(n, get_ctrl(n), true /* verify */);
3478   }
3479 #endif
3480 
3481   // CFG and pinned nodes already handled
3482   if( n->in(0) ) {
3483     if( n->in(0)->is_top() ) return; // Dead?
3484 
3485     // We'd like +VerifyLoopOptimizations to not believe that Mod's/Loads
3486     // _must_ be pinned (they have to observe their control edge of course).
3487     // Unlike Stores (which modify an unallocable resource, the memory
3488     // state), Mods/Loads can float around.  So free them up.
3489     bool pinned = true;
3490     switch( n->Opcode() ) {
3491     case Op_DivI:
3492     case Op_DivF:
3493     case Op_DivD:
3494     case Op_ModI:
3495     case Op_ModF:
3496     case Op_ModD:
3497     case Op_LoadB:              // Same with Loads; they can sink
3498     case Op_LoadUB:             // during loop optimizations.
3499     case Op_LoadUS:
3500     case Op_LoadD:
3501     case Op_LoadF:
3502     case Op_LoadI:
3503     case Op_LoadKlass:
3504     case Op_LoadNKlass:
3505     case Op_LoadL:
3506     case Op_LoadS:
3507     case Op_LoadP:
3508     case Op_LoadN:
3509     case Op_LoadRange:
3510     case Op_LoadD_unaligned:
3511     case Op_LoadL_unaligned:
3512     case Op_StrComp:            // Does a bunch of load-like effects
3513     case Op_StrEquals:
3514     case Op_StrIndexOf:
3515     case Op_StrIndexOfChar:
3516     case Op_AryEq:
3517     case Op_HasNegatives:
3518       pinned = false;
3519     }
3520     if( pinned ) {
3521       IdealLoopTree *chosen_loop = get_loop(n->is_CFG() ? n : get_ctrl(n));
3522       if( !chosen_loop->_child )       // Inner loop?
3523         chosen_loop->_body.push(n); // Collect inner loops
3524       return;
3525     }
3526   } else {                      // No slot zero
3527     if( n->is_CFG() ) {         // CFG with no slot 0 is dead
3528       _nodes.map(n->_idx,0);    // No block setting, it's globally dead
3529       return;
3530     }
3531     assert(!n->is_CFG() || n->outcnt() == 0, "");
3532   }
3533 
3534   // Do I have a "safe range" I can select over?
3535   Node *early = get_ctrl(n);// Early location already computed
3536 
3537   // Compute latest point this Node can go
3538   Node *LCA = get_late_ctrl( n, early );
3539   // LCA is NULL due to uses being dead
3540   if( LCA == NULL ) {
3541 #ifdef ASSERT
3542     for (DUIterator i1 = n->outs(); n->has_out(i1); i1++) {
3543       assert( _nodes[n->out(i1)->_idx] == NULL, "all uses must also be dead");
3544     }
3545 #endif
3546     _nodes.map(n->_idx, 0);     // This node is useless
3547     _deadlist.push(n);
3548     return;
3549   }
3550   assert(LCA != NULL && !LCA->is_top(), "no dead nodes");
3551 
3552   Node *legal = LCA;            // Walk 'legal' up the IDOM chain
3553   Node *least = legal;          // Best legal position so far
3554   while( early != legal ) {     // While not at earliest legal
3555 #ifdef ASSERT
3556     if (legal->is_Start() && !early->is_Root()) {
3557       // Bad graph. Print idom path and fail.
3558       dump_bad_graph("Bad graph detected in build_loop_late", n, early, LCA);
3559       assert(false, "Bad graph detected in build_loop_late");
3560     }
3561 #endif
3562     // Find least loop nesting depth
3563     legal = idom(legal);        // Bump up the IDOM tree
3564     // Check for lower nesting depth
3565     if( get_loop(legal)->_nest < get_loop(least)->_nest )
3566       least = legal;
3567   }
3568   assert(early == legal || legal != C->root(), "bad dominance of inputs");
3569 
3570   // Try not to place code on a loop entry projection
3571   // which can inhibit range check elimination.
3572   if (least != early) {
3573     Node* ctrl_out = least->unique_ctrl_out();
3574     if (ctrl_out && ctrl_out->is_CountedLoop() &&
3575         least == ctrl_out->in(LoopNode::EntryControl)) {
3576       Node* least_dom = idom(least);
3577       if (get_loop(least_dom)->is_member(get_loop(least))) {
3578         least = least_dom;
3579       }
3580     }
3581   }
3582 
3583 #ifdef ASSERT
3584   // If verifying, verify that 'verify_me' has a legal location
3585   // and choose it as our location.
3586   if( _verify_me ) {
3587     Node *v_ctrl = _verify_me->get_ctrl_no_update(n);
3588     Node *legal = LCA;
3589     while( early != legal ) {   // While not at earliest legal
3590       if( legal == v_ctrl ) break;  // Check for prior good location
3591       legal = idom(legal)      ;// Bump up the IDOM tree
3592     }
3593     // Check for prior good location
3594     if( legal == v_ctrl ) least = legal; // Keep prior if found
3595   }
3596 #endif
3597 
3598   // Assign discovered "here or above" point
3599   least = find_non_split_ctrl(least);
3600   set_ctrl(n, least);
3601 
3602   // Collect inner loop bodies
3603   IdealLoopTree *chosen_loop = get_loop(least);
3604   if( !chosen_loop->_child )   // Inner loop?
3605     chosen_loop->_body.push(n);// Collect inner loops
3606 }
3607 
3608 #ifdef ASSERT
3609 void PhaseIdealLoop::dump_bad_graph(const char* msg, Node* n, Node* early, Node* LCA) {
3610   tty->print_cr("%s", msg);
3611   tty->print("n: "); n->dump();
3612   tty->print("early(n): "); early->dump();
3613   if (n->in(0) != NULL  && !n->in(0)->is_top() &&
3614       n->in(0) != early && !n->in(0)->is_Root()) {
3615     tty->print("n->in(0): "); n->in(0)->dump();
3616   }
3617   for (uint i = 1; i < n->req(); i++) {
3618     Node* in1 = n->in(i);
3619     if (in1 != NULL && in1 != n && !in1->is_top()) {
3620       tty->print("n->in(%d): ", i); in1->dump();
3621       Node* in1_early = get_ctrl(in1);
3622       tty->print("early(n->in(%d)): ", i); in1_early->dump();
3623       if (in1->in(0) != NULL     && !in1->in(0)->is_top() &&
3624           in1->in(0) != in1_early && !in1->in(0)->is_Root()) {
3625         tty->print("n->in(%d)->in(0): ", i); in1->in(0)->dump();
3626       }
3627       for (uint j = 1; j < in1->req(); j++) {
3628         Node* in2 = in1->in(j);
3629         if (in2 != NULL && in2 != n && in2 != in1 && !in2->is_top()) {
3630           tty->print("n->in(%d)->in(%d): ", i, j); in2->dump();
3631           Node* in2_early = get_ctrl(in2);
3632           tty->print("early(n->in(%d)->in(%d)): ", i, j); in2_early->dump();
3633           if (in2->in(0) != NULL     && !in2->in(0)->is_top() &&
3634               in2->in(0) != in2_early && !in2->in(0)->is_Root()) {
3635             tty->print("n->in(%d)->in(%d)->in(0): ", i, j); in2->in(0)->dump();
3636           }
3637         }
3638       }
3639     }
3640   }
3641   tty->cr();
3642   tty->print("LCA(n): "); LCA->dump();
3643   for (uint i = 0; i < n->outcnt(); i++) {
3644     Node* u1 = n->raw_out(i);
3645     if (u1 == n)
3646       continue;
3647     tty->print("n->out(%d): ", i); u1->dump();
3648     if (u1->is_CFG()) {
3649       for (uint j = 0; j < u1->outcnt(); j++) {
3650         Node* u2 = u1->raw_out(j);
3651         if (u2 != u1 && u2 != n && u2->is_CFG()) {
3652           tty->print("n->out(%d)->out(%d): ", i, j); u2->dump();
3653         }
3654       }
3655     } else {
3656       Node* u1_later = get_ctrl(u1);
3657       tty->print("later(n->out(%d)): ", i); u1_later->dump();
3658       if (u1->in(0) != NULL     && !u1->in(0)->is_top() &&
3659           u1->in(0) != u1_later && !u1->in(0)->is_Root()) {
3660         tty->print("n->out(%d)->in(0): ", i); u1->in(0)->dump();
3661       }
3662       for (uint j = 0; j < u1->outcnt(); j++) {
3663         Node* u2 = u1->raw_out(j);
3664         if (u2 == n || u2 == u1)
3665           continue;
3666         tty->print("n->out(%d)->out(%d): ", i, j); u2->dump();
3667         if (!u2->is_CFG()) {
3668           Node* u2_later = get_ctrl(u2);
3669           tty->print("later(n->out(%d)->out(%d)): ", i, j); u2_later->dump();
3670           if (u2->in(0) != NULL     && !u2->in(0)->is_top() &&
3671               u2->in(0) != u2_later && !u2->in(0)->is_Root()) {
3672             tty->print("n->out(%d)->in(0): ", i); u2->in(0)->dump();
3673           }
3674         }
3675       }
3676     }
3677   }
3678   tty->cr();
3679   int ct = 0;
3680   Node *dbg_legal = LCA;
3681   while(!dbg_legal->is_Start() && ct < 100) {
3682     tty->print("idom[%d] ",ct); dbg_legal->dump();
3683     ct++;
3684     dbg_legal = idom(dbg_legal);
3685   }
3686   tty->cr();
3687 }
3688 #endif
3689 
3690 #ifndef PRODUCT
3691 //------------------------------dump-------------------------------------------
3692 void PhaseIdealLoop::dump( ) const {
3693   ResourceMark rm;
3694   Arena* arena = Thread::current()->resource_area();
3695   Node_Stack stack(arena, C->live_nodes() >> 2);
3696   Node_List rpo_list;
3697   VectorSet visited(arena);
3698   visited.set(C->top()->_idx);
3699   rpo( C->root(), stack, visited, rpo_list );
3700   // Dump root loop indexed by last element in PO order
3701   dump( _ltree_root, rpo_list.size(), rpo_list );
3702 }
3703 
3704 void PhaseIdealLoop::dump( IdealLoopTree *loop, uint idx, Node_List &rpo_list ) const {
3705   loop->dump_head();
3706 
3707   // Now scan for CFG nodes in the same loop
3708   for( uint j=idx; j > 0;  j-- ) {
3709     Node *n = rpo_list[j-1];
3710     if( !_nodes[n->_idx] )      // Skip dead nodes
3711       continue;
3712     if( get_loop(n) != loop ) { // Wrong loop nest
3713       if( get_loop(n)->_head == n &&    // Found nested loop?
3714           get_loop(n)->_parent == loop )
3715         dump(get_loop(n),rpo_list.size(),rpo_list);     // Print it nested-ly
3716       continue;
3717     }
3718 
3719     // Dump controlling node
3720     for( uint x = 0; x < loop->_nest; x++ )
3721       tty->print("  ");
3722     tty->print("C");
3723     if( n == C->root() ) {
3724       n->dump();
3725     } else {
3726       Node* cached_idom   = idom_no_update(n);
3727       Node *computed_idom = n->in(0);
3728       if( n->is_Region() ) {
3729         computed_idom = compute_idom(n);
3730         // computed_idom() will return n->in(0) when idom(n) is an IfNode (or
3731         // any MultiBranch ctrl node), so apply a similar transform to
3732         // the cached idom returned from idom_no_update.
3733         cached_idom = find_non_split_ctrl(cached_idom);
3734       }
3735       tty->print(" ID:%d",computed_idom->_idx);
3736       n->dump();
3737       if( cached_idom != computed_idom ) {
3738         tty->print_cr("*** BROKEN IDOM!  Computed as: %d, cached as: %d",
3739                       computed_idom->_idx, cached_idom->_idx);
3740       }
3741     }
3742     // Dump nodes it controls
3743     for( uint k = 0; k < _nodes.Size(); k++ ) {
3744       // (k < C->unique() && get_ctrl(find(k)) == n)
3745       if (k < C->unique() && _nodes[k] == (Node*)((intptr_t)n + 1)) {
3746         Node *m = C->root()->find(k);
3747         if( m && m->outcnt() > 0 ) {
3748           if (!(has_ctrl(m) && get_ctrl_no_update(m) == n)) {
3749             tty->print_cr("*** BROKEN CTRL ACCESSOR!  _nodes[k] is %p, ctrl is %p",
3750                           _nodes[k], has_ctrl(m) ? get_ctrl_no_update(m) : NULL);
3751           }
3752           for( uint j = 0; j < loop->_nest; j++ )
3753             tty->print("  ");
3754           tty->print(" ");
3755           m->dump();
3756         }
3757       }
3758     }
3759   }
3760 }
3761 
3762 // Collect a R-P-O for the whole CFG.
3763 // Result list is in post-order (scan backwards for RPO)
3764 void PhaseIdealLoop::rpo( Node *start, Node_Stack &stk, VectorSet &visited, Node_List &rpo_list ) const {
3765   stk.push(start, 0);
3766   visited.set(start->_idx);
3767 
3768   while (stk.is_nonempty()) {
3769     Node* m   = stk.node();
3770     uint  idx = stk.index();
3771     if (idx < m->outcnt()) {
3772       stk.set_index(idx + 1);
3773       Node* n = m->raw_out(idx);
3774       if (n->is_CFG() && !visited.test_set(n->_idx)) {
3775         stk.push(n, 0);
3776       }
3777     } else {
3778       rpo_list.push(m);
3779       stk.pop();
3780     }
3781   }
3782 }
3783 #endif
3784 
3785 
3786 //=============================================================================
3787 //------------------------------LoopTreeIterator-----------------------------------
3788 
3789 // Advance to next loop tree using a preorder, left-to-right traversal.
3790 void LoopTreeIterator::next() {
3791   assert(!done(), "must not be done.");
3792   if (_curnt->_child != NULL) {
3793     _curnt = _curnt->_child;
3794   } else if (_curnt->_next != NULL) {
3795     _curnt = _curnt->_next;
3796   } else {
3797     while (_curnt != _root && _curnt->_next == NULL) {
3798       _curnt = _curnt->_parent;
3799     }
3800     if (_curnt == _root) {
3801       _curnt = NULL;
3802       assert(done(), "must be done.");
3803     } else {
3804       assert(_curnt->_next != NULL, "must be more to do");
3805       _curnt = _curnt->_next;
3806     }
3807   }
3808 }