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 ratio of the two strides cannot be represented as an int
1691     // if stride_con2 is min_int and stride_con is -1.
1692     if (stride_con2 == min_jint && stride_con == -1) {
1693       continue;
1694     }
1695 
1696     // The general case here gets a little tricky.  We want to find the
1697     // GCD of all possible parallel IV's and make a new IV using this
1698     // GCD for the loop.  Then all possible IVs are simple multiples of
1699     // the GCD.  In practice, this will cover very few extra loops.
1700     // Instead we require 'stride_con2' to be a multiple of 'stride_con',
1701     // where +/-1 is the common case, but other integer multiples are
1702     // also easy to handle.
1703     int ratio_con = stride_con2/stride_con;
1704 
1705     if ((ratio_con * stride_con) == stride_con2) { // Check for exact
1706 #ifndef PRODUCT
1707       if (TraceLoopOpts) {
1708         tty->print("Parallel IV: %d ", phi2->_idx);
1709         loop->dump_head();
1710       }
1711 #endif
1712       // Convert to using the trip counter.  The parallel induction
1713       // variable differs from the trip counter by a loop-invariant
1714       // amount, the difference between their respective initial values.
1715       // It is scaled by the 'ratio_con'.
1716       Node* ratio = _igvn.intcon(ratio_con);
1717       set_ctrl(ratio, C->root());
1718       Node* ratio_init = new MulINode(init, ratio);
1719       _igvn.register_new_node_with_optimizer(ratio_init, init);
1720       set_early_ctrl(ratio_init);
1721       Node* diff = new SubINode(init2, ratio_init);
1722       _igvn.register_new_node_with_optimizer(diff, init2);
1723       set_early_ctrl(diff);
1724       Node* ratio_idx = new MulINode(phi, ratio);
1725       _igvn.register_new_node_with_optimizer(ratio_idx, phi);
1726       set_ctrl(ratio_idx, cl);
1727       Node* add = new AddINode(ratio_idx, diff);
1728       _igvn.register_new_node_with_optimizer(add);
1729       set_ctrl(add, cl);
1730       _igvn.replace_node( phi2, add );
1731       // Sometimes an induction variable is unused
1732       if (add->outcnt() == 0) {
1733         _igvn.remove_dead_node(add);
1734       }
1735       --i; // deleted this phi; rescan starting with next position
1736       continue;
1737     }
1738   }
1739 }
1740 
1741 void IdealLoopTree::remove_safepoints(PhaseIdealLoop* phase, bool keep_one) {
1742   Node* keep = NULL;
1743   if (keep_one) {
1744     // Look for a safepoint on the idom-path.
1745     for (Node* i = tail(); i != _head; i = phase->idom(i)) {
1746       if (i->Opcode() == Op_SafePoint && phase->get_loop(i) == this) {
1747         keep = i;
1748         break; // Found one
1749       }
1750     }
1751   }
1752 
1753   // Don't remove any safepoints if it is requested to keep a single safepoint and
1754   // no safepoint was found on idom-path. It is not safe to remove any safepoint
1755   // in this case since there's no safepoint dominating all paths in the loop body.
1756   bool prune = !keep_one || keep != NULL;
1757 
1758   // Delete other safepoints in this loop.
1759   Node_List* sfpts = _safepts;
1760   if (prune && sfpts != NULL) {
1761     assert(keep == NULL || keep->Opcode() == Op_SafePoint, "not safepoint");
1762     for (uint i = 0; i < sfpts->size(); i++) {
1763       Node* n = sfpts->at(i);
1764       assert(phase->get_loop(n) == this, "");
1765       if (n != keep && phase->is_deleteable_safept(n)) {
1766         phase->lazy_replace(n, n->in(TypeFunc::Control));
1767       }
1768     }
1769   }
1770 }
1771 
1772 //------------------------------counted_loop-----------------------------------
1773 // Convert to counted loops where possible
1774 void IdealLoopTree::counted_loop( PhaseIdealLoop *phase ) {
1775 
1776   // For grins, set the inner-loop flag here
1777   if (!_child) {
1778     if (_head->is_Loop()) _head->as_Loop()->set_inner_loop();
1779   }
1780 
1781   if (_head->is_CountedLoop() ||
1782       phase->is_counted_loop(_head, this)) {
1783 
1784     if (!UseCountedLoopSafepoints) {
1785       // Indicate we do not need a safepoint here
1786       _has_sfpt = 1;
1787     }
1788 
1789     // Remove safepoints
1790     bool keep_one_sfpt = !(_has_call || _has_sfpt);
1791     remove_safepoints(phase, keep_one_sfpt);
1792 
1793     // Look for induction variables
1794     phase->replace_parallel_iv(this);
1795 
1796   } else if (_parent != NULL && !_irreducible) {
1797     // Not a counted loop. Keep one safepoint.
1798     bool keep_one_sfpt = true;
1799     remove_safepoints(phase, keep_one_sfpt);
1800   }
1801 
1802   // Recursively
1803   if (_child) _child->counted_loop( phase );
1804   if (_next)  _next ->counted_loop( phase );
1805 }
1806 
1807 #ifndef PRODUCT
1808 //------------------------------dump_head--------------------------------------
1809 // Dump 1 liner for loop header info
1810 void IdealLoopTree::dump_head( ) const {
1811   for (uint i=0; i<_nest; i++)
1812     tty->print("  ");
1813   tty->print("Loop: N%d/N%d ",_head->_idx,_tail->_idx);
1814   if (_irreducible) tty->print(" IRREDUCIBLE");
1815   Node* entry = _head->in(LoopNode::EntryControl);
1816   Node* predicate = PhaseIdealLoop::find_predicate_insertion_point(entry, Deoptimization::Reason_loop_limit_check);
1817   if (predicate != NULL ) {
1818     tty->print(" limit_check");
1819     entry = entry->in(0)->in(0);
1820   }
1821   if (UseLoopPredicate) {
1822     entry = PhaseIdealLoop::find_predicate_insertion_point(entry, Deoptimization::Reason_predicate);
1823     if (entry != NULL) {
1824       tty->print(" predicated");
1825     }
1826   }
1827   if (_head->is_CountedLoop()) {
1828     CountedLoopNode *cl = _head->as_CountedLoop();
1829     tty->print(" counted");
1830 
1831     Node* init_n = cl->init_trip();
1832     if (init_n  != NULL &&  init_n->is_Con())
1833       tty->print(" [%d,", cl->init_trip()->get_int());
1834     else
1835       tty->print(" [int,");
1836     Node* limit_n = cl->limit();
1837     if (limit_n  != NULL &&  limit_n->is_Con())
1838       tty->print("%d),", cl->limit()->get_int());
1839     else
1840       tty->print("int),");
1841     int stride_con  = cl->stride_con();
1842     if (stride_con > 0) tty->print("+");
1843     tty->print("%d", stride_con);
1844 
1845     tty->print(" (%0.f iters) ", cl->profile_trip_cnt());
1846 
1847     if (cl->is_pre_loop ()) tty->print(" pre" );
1848     if (cl->is_main_loop()) tty->print(" main");
1849     if (cl->is_post_loop()) tty->print(" post");
1850     if (cl->is_vectorized_loop()) tty->print(" vector");
1851     if (cl->range_checks_present()) tty->print(" rc ");
1852     if (cl->is_multiversioned()) tty->print(" multi ");
1853   }
1854   if (_has_call) tty->print(" has_call");
1855   if (_has_sfpt) tty->print(" has_sfpt");
1856   if (_rce_candidate) tty->print(" rce");
1857   if (_safepts != NULL && _safepts->size() > 0) {
1858     tty->print(" sfpts={"); _safepts->dump_simple(); tty->print(" }");
1859   }
1860   if (_required_safept != NULL && _required_safept->size() > 0) {
1861     tty->print(" req={"); _required_safept->dump_simple(); tty->print(" }");
1862   }
1863   tty->cr();
1864 }
1865 
1866 //------------------------------dump-------------------------------------------
1867 // Dump loops by loop tree
1868 void IdealLoopTree::dump( ) const {
1869   dump_head();
1870   if (_child) _child->dump();
1871   if (_next)  _next ->dump();
1872 }
1873 
1874 #endif
1875 
1876 static void log_loop_tree(IdealLoopTree* root, IdealLoopTree* loop, CompileLog* log) {
1877   if (loop == root) {
1878     if (loop->_child != NULL) {
1879       log->begin_head("loop_tree");
1880       log->end_head();
1881       if( loop->_child ) log_loop_tree(root, loop->_child, log);
1882       log->tail("loop_tree");
1883       assert(loop->_next == NULL, "what?");
1884     }
1885   } else {
1886     Node* head = loop->_head;
1887     log->begin_head("loop");
1888     log->print(" idx='%d' ", head->_idx);
1889     if (loop->_irreducible) log->print("irreducible='1' ");
1890     if (head->is_Loop()) {
1891       if (head->as_Loop()->is_inner_loop()) log->print("inner_loop='1' ");
1892       if (head->as_Loop()->is_partial_peel_loop()) log->print("partial_peel_loop='1' ");
1893     }
1894     if (head->is_CountedLoop()) {
1895       CountedLoopNode* cl = head->as_CountedLoop();
1896       if (cl->is_pre_loop())  log->print("pre_loop='%d' ",  cl->main_idx());
1897       if (cl->is_main_loop()) log->print("main_loop='%d' ", cl->_idx);
1898       if (cl->is_post_loop()) log->print("post_loop='%d' ",  cl->main_idx());
1899     }
1900     log->end_head();
1901     if( loop->_child ) log_loop_tree(root, loop->_child, log);
1902     log->tail("loop");
1903     if( loop->_next  ) log_loop_tree(root, loop->_next, log);
1904   }
1905 }
1906 
1907 //---------------------collect_potentially_useful_predicates-----------------------
1908 // Helper function to collect potentially useful predicates to prevent them from
1909 // being eliminated by PhaseIdealLoop::eliminate_useless_predicates
1910 void PhaseIdealLoop::collect_potentially_useful_predicates(
1911                          IdealLoopTree * loop, Unique_Node_List &useful_predicates) {
1912   if (loop->_child) { // child
1913     collect_potentially_useful_predicates(loop->_child, useful_predicates);
1914   }
1915 
1916   // self (only loops that we can apply loop predication may use their predicates)
1917   if (loop->_head->is_Loop() &&
1918       !loop->_irreducible    &&
1919       !loop->tail()->is_top()) {
1920     LoopNode* lpn = loop->_head->as_Loop();
1921     Node* entry = lpn->in(LoopNode::EntryControl);
1922     Node* predicate_proj = find_predicate(entry); // loop_limit_check first
1923     if (predicate_proj != NULL ) { // right pattern that can be used by loop predication
1924       assert(entry->in(0)->in(1)->in(1)->Opcode() == Op_Opaque1, "must be");
1925       useful_predicates.push(entry->in(0)->in(1)->in(1)); // good one
1926       entry = entry->in(0)->in(0);
1927     }
1928     predicate_proj = find_predicate(entry); // Predicate
1929     if (predicate_proj != NULL ) {
1930       useful_predicates.push(entry->in(0)->in(1)->in(1)); // good one
1931     }
1932   }
1933 
1934   if (loop->_next) { // sibling
1935     collect_potentially_useful_predicates(loop->_next, useful_predicates);
1936   }
1937 }
1938 
1939 //------------------------eliminate_useless_predicates-----------------------------
1940 // Eliminate all inserted predicates if they could not be used by loop predication.
1941 // Note: it will also eliminates loop limits check predicate since it also uses
1942 // Opaque1 node (see Parse::add_predicate()).
1943 void PhaseIdealLoop::eliminate_useless_predicates() {
1944   if (C->predicate_count() == 0)
1945     return; // no predicate left
1946 
1947   Unique_Node_List useful_predicates; // to store useful predicates
1948   if (C->has_loops()) {
1949     collect_potentially_useful_predicates(_ltree_root->_child, useful_predicates);
1950   }
1951 
1952   for (int i = C->predicate_count(); i > 0; i--) {
1953      Node * n = C->predicate_opaque1_node(i-1);
1954      assert(n->Opcode() == Op_Opaque1, "must be");
1955      if (!useful_predicates.member(n)) { // not in the useful list
1956        _igvn.replace_node(n, n->in(1));
1957      }
1958   }
1959 }
1960 
1961 //------------------------process_expensive_nodes-----------------------------
1962 // Expensive nodes have their control input set to prevent the GVN
1963 // from commoning them and as a result forcing the resulting node to
1964 // be in a more frequent path. Use CFG information here, to change the
1965 // control inputs so that some expensive nodes can be commoned while
1966 // not executed more frequently.
1967 bool PhaseIdealLoop::process_expensive_nodes() {
1968   assert(OptimizeExpensiveOps, "optimization off?");
1969 
1970   // Sort nodes to bring similar nodes together
1971   C->sort_expensive_nodes();
1972 
1973   bool progress = false;
1974 
1975   for (int i = 0; i < C->expensive_count(); ) {
1976     Node* n = C->expensive_node(i);
1977     int start = i;
1978     // Find nodes similar to n
1979     i++;
1980     for (; i < C->expensive_count() && Compile::cmp_expensive_nodes(n, C->expensive_node(i)) == 0; i++);
1981     int end = i;
1982     // And compare them two by two
1983     for (int j = start; j < end; j++) {
1984       Node* n1 = C->expensive_node(j);
1985       if (is_node_unreachable(n1)) {
1986         continue;
1987       }
1988       for (int k = j+1; k < end; k++) {
1989         Node* n2 = C->expensive_node(k);
1990         if (is_node_unreachable(n2)) {
1991           continue;
1992         }
1993 
1994         assert(n1 != n2, "should be pair of nodes");
1995 
1996         Node* c1 = n1->in(0);
1997         Node* c2 = n2->in(0);
1998 
1999         Node* parent_c1 = c1;
2000         Node* parent_c2 = c2;
2001 
2002         // The call to get_early_ctrl_for_expensive() moves the
2003         // expensive nodes up but stops at loops that are in a if
2004         // branch. See whether we can exit the loop and move above the
2005         // If.
2006         if (c1->is_Loop()) {
2007           parent_c1 = c1->in(1);
2008         }
2009         if (c2->is_Loop()) {
2010           parent_c2 = c2->in(1);
2011         }
2012 
2013         if (parent_c1 == parent_c2) {
2014           _igvn._worklist.push(n1);
2015           _igvn._worklist.push(n2);
2016           continue;
2017         }
2018 
2019         // Look for identical expensive node up the dominator chain.
2020         if (is_dominator(c1, c2)) {
2021           c2 = c1;
2022         } else if (is_dominator(c2, c1)) {
2023           c1 = c2;
2024         } else if (parent_c1->is_Proj() && parent_c1->in(0)->is_If() &&
2025                    parent_c2->is_Proj() && parent_c1->in(0) == parent_c2->in(0)) {
2026           // Both branches have the same expensive node so move it up
2027           // before the if.
2028           c1 = c2 = idom(parent_c1->in(0));
2029         }
2030         // Do the actual moves
2031         if (n1->in(0) != c1) {
2032           _igvn.hash_delete(n1);
2033           n1->set_req(0, c1);
2034           _igvn.hash_insert(n1);
2035           _igvn._worklist.push(n1);
2036           progress = true;
2037         }
2038         if (n2->in(0) != c2) {
2039           _igvn.hash_delete(n2);
2040           n2->set_req(0, c2);
2041           _igvn.hash_insert(n2);
2042           _igvn._worklist.push(n2);
2043           progress = true;
2044         }
2045       }
2046     }
2047   }
2048 
2049   return progress;
2050 }
2051 
2052 
2053 //=============================================================================
2054 //----------------------------build_and_optimize-------------------------------
2055 // Create a PhaseLoop.  Build the ideal Loop tree.  Map each Ideal Node to
2056 // its corresponding LoopNode.  If 'optimize' is true, do some loop cleanups.
2057 void PhaseIdealLoop::build_and_optimize(bool do_split_ifs, bool skip_loop_opts) {
2058   ResourceMark rm;
2059 
2060   int old_progress = C->major_progress();
2061   uint orig_worklist_size = _igvn._worklist.size();
2062 
2063   // Reset major-progress flag for the driver's heuristics
2064   C->clear_major_progress();
2065 
2066 #ifndef PRODUCT
2067   // Capture for later assert
2068   uint unique = C->unique();
2069   _loop_invokes++;
2070   _loop_work += unique;
2071 #endif
2072 
2073   // True if the method has at least 1 irreducible loop
2074   _has_irreducible_loops = false;
2075 
2076   _created_loop_node = false;
2077 
2078   Arena *a = Thread::current()->resource_area();
2079   VectorSet visited(a);
2080   // Pre-grow the mapping from Nodes to IdealLoopTrees.
2081   _nodes.map(C->unique(), NULL);
2082   memset(_nodes.adr(), 0, wordSize * C->unique());
2083 
2084   // Pre-build the top-level outermost loop tree entry
2085   _ltree_root = new IdealLoopTree( this, C->root(), C->root() );
2086   // Do not need a safepoint at the top level
2087   _ltree_root->_has_sfpt = 1;
2088 
2089   // Initialize Dominators.
2090   // Checked in clone_loop_predicate() during beautify_loops().
2091   _idom_size = 0;
2092   _idom      = NULL;
2093   _dom_depth = NULL;
2094   _dom_stk   = NULL;
2095 
2096   // Empty pre-order array
2097   allocate_preorders();
2098 
2099   // Build a loop tree on the fly.  Build a mapping from CFG nodes to
2100   // IdealLoopTree entries.  Data nodes are NOT walked.
2101   build_loop_tree();
2102   // Check for bailout, and return
2103   if (C->failing()) {
2104     return;
2105   }
2106 
2107   // No loops after all
2108   if( !_ltree_root->_child && !_verify_only ) C->set_has_loops(false);
2109 
2110   // There should always be an outer loop containing the Root and Return nodes.
2111   // If not, we have a degenerate empty program.  Bail out in this case.
2112   if (!has_node(C->root())) {
2113     if (!_verify_only) {
2114       C->clear_major_progress();
2115       C->record_method_not_compilable("empty program detected during loop optimization");
2116     }
2117     return;
2118   }
2119 
2120   // Nothing to do, so get out
2121   bool stop_early = !C->has_loops() && !skip_loop_opts && !do_split_ifs && !_verify_me && !_verify_only;
2122   bool do_expensive_nodes = C->should_optimize_expensive_nodes(_igvn);
2123   if (stop_early && !do_expensive_nodes) {
2124     _igvn.optimize();           // Cleanup NeverBranches
2125     return;
2126   }
2127 
2128   // Set loop nesting depth
2129   _ltree_root->set_nest( 0 );
2130 
2131   // Split shared headers and insert loop landing pads.
2132   // Do not bother doing this on the Root loop of course.
2133   if( !_verify_me && !_verify_only && _ltree_root->_child ) {
2134     C->print_method(PHASE_BEFORE_BEAUTIFY_LOOPS, 3);
2135     if( _ltree_root->_child->beautify_loops( this ) ) {
2136       // Re-build loop tree!
2137       _ltree_root->_child = NULL;
2138       _nodes.clear();
2139       reallocate_preorders();
2140       build_loop_tree();
2141       // Check for bailout, and return
2142       if (C->failing()) {
2143         return;
2144       }
2145       // Reset loop nesting depth
2146       _ltree_root->set_nest( 0 );
2147 
2148       C->print_method(PHASE_AFTER_BEAUTIFY_LOOPS, 3);
2149     }
2150   }
2151 
2152   // Build Dominators for elision of NULL checks & loop finding.
2153   // Since nodes do not have a slot for immediate dominator, make
2154   // a persistent side array for that info indexed on node->_idx.
2155   _idom_size = C->unique();
2156   _idom      = NEW_RESOURCE_ARRAY( Node*, _idom_size );
2157   _dom_depth = NEW_RESOURCE_ARRAY( uint,  _idom_size );
2158   _dom_stk   = NULL; // Allocated on demand in recompute_dom_depth
2159   memset( _dom_depth, 0, _idom_size * sizeof(uint) );
2160 
2161   Dominators();
2162 
2163   if (!_verify_only) {
2164     // As a side effect, Dominators removed any unreachable CFG paths
2165     // into RegionNodes.  It doesn't do this test against Root, so
2166     // we do it here.
2167     for( uint i = 1; i < C->root()->req(); i++ ) {
2168       if( !_nodes[C->root()->in(i)->_idx] ) {    // Dead path into Root?
2169         _igvn.delete_input_of(C->root(), i);
2170         i--;                      // Rerun same iteration on compressed edges
2171       }
2172     }
2173 
2174     // Given dominators, try to find inner loops with calls that must
2175     // always be executed (call dominates loop tail).  These loops do
2176     // not need a separate safepoint.
2177     Node_List cisstack(a);
2178     _ltree_root->check_safepts(visited, cisstack);
2179   }
2180 
2181   // Walk the DATA nodes and place into loops.  Find earliest control
2182   // node.  For CFG nodes, the _nodes array starts out and remains
2183   // holding the associated IdealLoopTree pointer.  For DATA nodes, the
2184   // _nodes array holds the earliest legal controlling CFG node.
2185 
2186   // Allocate stack with enough space to avoid frequent realloc
2187   int stack_size = (C->live_nodes() >> 1) + 16; // (live_nodes>>1)+16 from Java2D stats
2188   Node_Stack nstack( a, stack_size );
2189 
2190   visited.Clear();
2191   Node_List worklist(a);
2192   // Don't need C->root() on worklist since
2193   // it will be processed among C->top() inputs
2194   worklist.push( C->top() );
2195   visited.set( C->top()->_idx ); // Set C->top() as visited now
2196   build_loop_early( visited, worklist, nstack );
2197 
2198   // Given early legal placement, try finding counted loops.  This placement
2199   // is good enough to discover most loop invariants.
2200   if( !_verify_me && !_verify_only )
2201     _ltree_root->counted_loop( this );
2202 
2203   // Find latest loop placement.  Find ideal loop placement.
2204   visited.Clear();
2205   init_dom_lca_tags();
2206   // Need C->root() on worklist when processing outs
2207   worklist.push( C->root() );
2208   NOT_PRODUCT( C->verify_graph_edges(); )
2209   worklist.push( C->top() );
2210   build_loop_late( visited, worklist, nstack );
2211 
2212   if (_verify_only) {
2213     // restore major progress flag
2214     for (int i = 0; i < old_progress; i++)
2215       C->set_major_progress();
2216     assert(C->unique() == unique, "verification mode made Nodes? ? ?");
2217     assert(_igvn._worklist.size() == orig_worklist_size, "shouldn't push anything");
2218     return;
2219   }
2220 
2221   // clear out the dead code after build_loop_late
2222   while (_deadlist.size()) {
2223     _igvn.remove_globally_dead_node(_deadlist.pop());
2224   }
2225 
2226   if (stop_early) {
2227     assert(do_expensive_nodes, "why are we here?");
2228     if (process_expensive_nodes()) {
2229       // If we made some progress when processing expensive nodes then
2230       // the IGVN may modify the graph in a way that will allow us to
2231       // make some more progress: we need to try processing expensive
2232       // nodes again.
2233       C->set_major_progress();
2234     }
2235     _igvn.optimize();
2236     return;
2237   }
2238 
2239   // Some parser-inserted loop predicates could never be used by loop
2240   // predication or they were moved away from loop during some optimizations.
2241   // For example, peeling. Eliminate them before next loop optimizations.
2242   eliminate_useless_predicates();
2243 
2244 #ifndef PRODUCT
2245   C->verify_graph_edges();
2246   if (_verify_me) {             // Nested verify pass?
2247     // Check to see if the verify mode is broken
2248     assert(C->unique() == unique, "non-optimize mode made Nodes? ? ?");
2249     return;
2250   }
2251   if(VerifyLoopOptimizations) verify();
2252   if(TraceLoopOpts && C->has_loops()) {
2253     _ltree_root->dump();
2254   }
2255 #endif
2256 
2257   if (skip_loop_opts) {
2258     // restore major progress flag
2259     for (int i = 0; i < old_progress; i++) {
2260       C->set_major_progress();
2261     }
2262 
2263     // Cleanup any modified bits
2264     _igvn.optimize();
2265 
2266     if (C->log() != NULL) {
2267       log_loop_tree(_ltree_root, _ltree_root, C->log());
2268     }
2269     return;
2270   }
2271 
2272   if (ReassociateInvariants) {
2273     // Reassociate invariants and prep for split_thru_phi
2274     for (LoopTreeIterator iter(_ltree_root); !iter.done(); iter.next()) {
2275       IdealLoopTree* lpt = iter.current();
2276       bool is_counted = lpt->is_counted();
2277       if (!is_counted || !lpt->is_inner()) continue;
2278 
2279       // check for vectorized loops, any reassociation of invariants was already done
2280       if (is_counted && lpt->_head->as_CountedLoop()->do_unroll_only()) continue;
2281 
2282       lpt->reassociate_invariants(this);
2283 
2284       // Because RCE opportunities can be masked by split_thru_phi,
2285       // look for RCE candidates and inhibit split_thru_phi
2286       // on just their loop-phi's for this pass of loop opts
2287       if (SplitIfBlocks && do_split_ifs) {
2288         if (lpt->policy_range_check(this)) {
2289           lpt->_rce_candidate = 1; // = true
2290         }
2291       }
2292     }
2293   }
2294 
2295   // Check for aggressive application of split-if and other transforms
2296   // that require basic-block info (like cloning through Phi's)
2297   if( SplitIfBlocks && do_split_ifs ) {
2298     visited.Clear();
2299     split_if_with_blocks( visited, nstack );
2300     NOT_PRODUCT( if( VerifyLoopOptimizations ) verify(); );
2301   }
2302 
2303   if (!C->major_progress() && do_expensive_nodes && process_expensive_nodes()) {
2304     C->set_major_progress();
2305   }
2306 
2307   // Perform loop predication before iteration splitting
2308   if (C->has_loops() && !C->major_progress() && (C->predicate_count() > 0)) {
2309     _ltree_root->_child->loop_predication(this);
2310   }
2311 
2312   if (OptimizeFill && UseLoopPredicate && C->has_loops() && !C->major_progress()) {
2313     if (do_intrinsify_fill()) {
2314       C->set_major_progress();
2315     }
2316   }
2317 
2318   // Perform iteration-splitting on inner loops.  Split iterations to avoid
2319   // range checks or one-shot null checks.
2320 
2321   // If split-if's didn't hack the graph too bad (no CFG changes)
2322   // then do loop opts.
2323   if (C->has_loops() && !C->major_progress()) {
2324     memset( worklist.adr(), 0, worklist.Size()*sizeof(Node*) );
2325     _ltree_root->_child->iteration_split( this, worklist );
2326     // No verify after peeling!  GCM has hoisted code out of the loop.
2327     // After peeling, the hoisted code could sink inside the peeled area.
2328     // The peeling code does not try to recompute the best location for
2329     // all the code before the peeled area, so the verify pass will always
2330     // complain about it.
2331   }
2332   // Do verify graph edges in any case
2333   NOT_PRODUCT( C->verify_graph_edges(); );
2334 
2335   if (!do_split_ifs) {
2336     // We saw major progress in Split-If to get here.  We forced a
2337     // pass with unrolling and not split-if, however more split-if's
2338     // might make progress.  If the unrolling didn't make progress
2339     // then the major-progress flag got cleared and we won't try
2340     // another round of Split-If.  In particular the ever-common
2341     // instance-of/check-cast pattern requires at least 2 rounds of
2342     // Split-If to clear out.
2343     C->set_major_progress();
2344   }
2345 
2346   // Repeat loop optimizations if new loops were seen
2347   if (created_loop_node()) {
2348     C->set_major_progress();
2349   }
2350 
2351   // Keep loop predicates and perform optimizations with them
2352   // until no more loop optimizations could be done.
2353   // After that switch predicates off and do more loop optimizations.
2354   if (!C->major_progress() && (C->predicate_count() > 0)) {
2355      C->cleanup_loop_predicates(_igvn);
2356      if (TraceLoopOpts) {
2357        tty->print_cr("PredicatesOff");
2358      }
2359      C->set_major_progress();
2360   }
2361 
2362   // Convert scalar to superword operations at the end of all loop opts.
2363   if (UseSuperWord && C->has_loops() && !C->major_progress()) {
2364     // SuperWord transform
2365     SuperWord sw(this);
2366     for (LoopTreeIterator iter(_ltree_root); !iter.done(); iter.next()) {
2367       IdealLoopTree* lpt = iter.current();
2368       if (lpt->is_counted()) {
2369         CountedLoopNode *cl = lpt->_head->as_CountedLoop();
2370 
2371         if (PostLoopMultiversioning && cl->is_rce_post_loop() && !cl->is_vectorized_loop()) {
2372           // Check that the rce'd post loop is encountered first, multiversion after all
2373           // major main loop optimization are concluded
2374           if (!C->major_progress()) {
2375             IdealLoopTree *lpt_next = lpt->_next;
2376             if (lpt_next && lpt_next->is_counted()) {
2377               CountedLoopNode *cl = lpt_next->_head->as_CountedLoop();
2378               has_range_checks(lpt_next);
2379               if (cl->is_post_loop() && cl->range_checks_present()) {
2380                 if (!cl->is_multiversioned()) {
2381                   if (multi_version_post_loops(lpt, lpt_next) == false) {
2382                     // Cause the rce loop to be optimized away if we fail
2383                     cl->mark_is_multiversioned();
2384                     cl->set_slp_max_unroll(0);
2385                     poison_rce_post_loop(lpt);
2386                   }
2387                 }
2388               }
2389             }
2390             sw.transform_loop(lpt, true);
2391           }
2392         } else if (cl->is_main_loop()) {
2393           sw.transform_loop(lpt, true);
2394         }
2395       }
2396     }
2397   }
2398 
2399   // Cleanup any modified bits
2400   _igvn.optimize();
2401 
2402   // disable assert until issue with split_flow_path is resolved (6742111)
2403   // assert(!_has_irreducible_loops || C->parsed_irreducible_loop() || C->is_osr_compilation(),
2404   //        "shouldn't introduce irreducible loops");
2405 
2406   if (C->log() != NULL) {
2407     log_loop_tree(_ltree_root, _ltree_root, C->log());
2408   }
2409 }
2410 
2411 #ifndef PRODUCT
2412 //------------------------------print_statistics-------------------------------
2413 int PhaseIdealLoop::_loop_invokes=0;// Count of PhaseIdealLoop invokes
2414 int PhaseIdealLoop::_loop_work=0; // Sum of PhaseIdealLoop x unique
2415 void PhaseIdealLoop::print_statistics() {
2416   tty->print_cr("PhaseIdealLoop=%d, sum _unique=%d", _loop_invokes, _loop_work);
2417 }
2418 
2419 //------------------------------verify-----------------------------------------
2420 // Build a verify-only PhaseIdealLoop, and see that it agrees with me.
2421 static int fail;                // debug only, so its multi-thread dont care
2422 void PhaseIdealLoop::verify() const {
2423   int old_progress = C->major_progress();
2424   ResourceMark rm;
2425   PhaseIdealLoop loop_verify( _igvn, this );
2426   VectorSet visited(Thread::current()->resource_area());
2427 
2428   fail = 0;
2429   verify_compare( C->root(), &loop_verify, visited );
2430   assert( fail == 0, "verify loops failed" );
2431   // Verify loop structure is the same
2432   _ltree_root->verify_tree(loop_verify._ltree_root, NULL);
2433   // Reset major-progress.  It was cleared by creating a verify version of
2434   // PhaseIdealLoop.
2435   for( int i=0; i<old_progress; i++ )
2436     C->set_major_progress();
2437 }
2438 
2439 //------------------------------verify_compare---------------------------------
2440 // Make sure me and the given PhaseIdealLoop agree on key data structures
2441 void PhaseIdealLoop::verify_compare( Node *n, const PhaseIdealLoop *loop_verify, VectorSet &visited ) const {
2442   if( !n ) return;
2443   if( visited.test_set( n->_idx ) ) return;
2444   if( !_nodes[n->_idx] ) {      // Unreachable
2445     assert( !loop_verify->_nodes[n->_idx], "both should be unreachable" );
2446     return;
2447   }
2448 
2449   uint i;
2450   for( i = 0; i < n->req(); i++ )
2451     verify_compare( n->in(i), loop_verify, visited );
2452 
2453   // Check the '_nodes' block/loop structure
2454   i = n->_idx;
2455   if( has_ctrl(n) ) {           // We have control; verify has loop or ctrl
2456     if( _nodes[i] != loop_verify->_nodes[i] &&
2457         get_ctrl_no_update(n) != loop_verify->get_ctrl_no_update(n) ) {
2458       tty->print("Mismatched control setting for: ");
2459       n->dump();
2460       if( fail++ > 10 ) return;
2461       Node *c = get_ctrl_no_update(n);
2462       tty->print("We have it as: ");
2463       if( c->in(0) ) c->dump();
2464         else tty->print_cr("N%d",c->_idx);
2465       tty->print("Verify thinks: ");
2466       if( loop_verify->has_ctrl(n) )
2467         loop_verify->get_ctrl_no_update(n)->dump();
2468       else
2469         loop_verify->get_loop_idx(n)->dump();
2470       tty->cr();
2471     }
2472   } else {                    // We have a loop
2473     IdealLoopTree *us = get_loop_idx(n);
2474     if( loop_verify->has_ctrl(n) ) {
2475       tty->print("Mismatched loop setting for: ");
2476       n->dump();
2477       if( fail++ > 10 ) return;
2478       tty->print("We have it as: ");
2479       us->dump();
2480       tty->print("Verify thinks: ");
2481       loop_verify->get_ctrl_no_update(n)->dump();
2482       tty->cr();
2483     } else if (!C->major_progress()) {
2484       // Loop selection can be messed up if we did a major progress
2485       // operation, like split-if.  Do not verify in that case.
2486       IdealLoopTree *them = loop_verify->get_loop_idx(n);
2487       if( us->_head != them->_head ||  us->_tail != them->_tail ) {
2488         tty->print("Unequals loops for: ");
2489         n->dump();
2490         if( fail++ > 10 ) return;
2491         tty->print("We have it as: ");
2492         us->dump();
2493         tty->print("Verify thinks: ");
2494         them->dump();
2495         tty->cr();
2496       }
2497     }
2498   }
2499 
2500   // Check for immediate dominators being equal
2501   if( i >= _idom_size ) {
2502     if( !n->is_CFG() ) return;
2503     tty->print("CFG Node with no idom: ");
2504     n->dump();
2505     return;
2506   }
2507   if( !n->is_CFG() ) return;
2508   if( n == C->root() ) return; // No IDOM here
2509 
2510   assert(n->_idx == i, "sanity");
2511   Node *id = idom_no_update(n);
2512   if( id != loop_verify->idom_no_update(n) ) {
2513     tty->print("Unequals idoms for: ");
2514     n->dump();
2515     if( fail++ > 10 ) return;
2516     tty->print("We have it as: ");
2517     id->dump();
2518     tty->print("Verify thinks: ");
2519     loop_verify->idom_no_update(n)->dump();
2520     tty->cr();
2521   }
2522 
2523 }
2524 
2525 //------------------------------verify_tree------------------------------------
2526 // Verify that tree structures match.  Because the CFG can change, siblings
2527 // within the loop tree can be reordered.  We attempt to deal with that by
2528 // reordering the verify's loop tree if possible.
2529 void IdealLoopTree::verify_tree(IdealLoopTree *loop, const IdealLoopTree *parent) const {
2530   assert( _parent == parent, "Badly formed loop tree" );
2531 
2532   // Siblings not in same order?  Attempt to re-order.
2533   if( _head != loop->_head ) {
2534     // Find _next pointer to update
2535     IdealLoopTree **pp = &loop->_parent->_child;
2536     while( *pp != loop )
2537       pp = &((*pp)->_next);
2538     // Find proper sibling to be next
2539     IdealLoopTree **nn = &loop->_next;
2540     while( (*nn) && (*nn)->_head != _head )
2541       nn = &((*nn)->_next);
2542 
2543     // Check for no match.
2544     if( !(*nn) ) {
2545       // Annoyingly, irreducible loops can pick different headers
2546       // after a major_progress operation, so the rest of the loop
2547       // tree cannot be matched.
2548       if (_irreducible && Compile::current()->major_progress())  return;
2549       assert( 0, "failed to match loop tree" );
2550     }
2551 
2552     // Move (*nn) to (*pp)
2553     IdealLoopTree *hit = *nn;
2554     *nn = hit->_next;
2555     hit->_next = loop;
2556     *pp = loop;
2557     loop = hit;
2558     // Now try again to verify
2559   }
2560 
2561   assert( _head  == loop->_head , "mismatched loop head" );
2562   Node *tail = _tail;           // Inline a non-updating version of
2563   while( !tail->in(0) )         // the 'tail()' call.
2564     tail = tail->in(1);
2565   assert( tail == loop->_tail, "mismatched loop tail" );
2566 
2567   // Counted loops that are guarded should be able to find their guards
2568   if( _head->is_CountedLoop() && _head->as_CountedLoop()->is_main_loop() ) {
2569     CountedLoopNode *cl = _head->as_CountedLoop();
2570     Node *init = cl->init_trip();
2571     Node *ctrl = cl->in(LoopNode::EntryControl);
2572     assert( ctrl->Opcode() == Op_IfTrue || ctrl->Opcode() == Op_IfFalse, "" );
2573     Node *iff  = ctrl->in(0);
2574     assert( iff->Opcode() == Op_If, "" );
2575     Node *bol  = iff->in(1);
2576     assert( bol->Opcode() == Op_Bool, "" );
2577     Node *cmp  = bol->in(1);
2578     assert( cmp->Opcode() == Op_CmpI, "" );
2579     Node *add  = cmp->in(1);
2580     Node *opaq;
2581     if( add->Opcode() == Op_Opaque1 ) {
2582       opaq = add;
2583     } else {
2584       assert( add->Opcode() == Op_AddI || add->Opcode() == Op_ConI , "" );
2585       assert( add == init, "" );
2586       opaq = cmp->in(2);
2587     }
2588     assert( opaq->Opcode() == Op_Opaque1, "" );
2589 
2590   }
2591 
2592   if (_child != NULL)  _child->verify_tree(loop->_child, this);
2593   if (_next  != NULL)  _next ->verify_tree(loop->_next,  parent);
2594   // Innermost loops need to verify loop bodies,
2595   // but only if no 'major_progress'
2596   int fail = 0;
2597   if (!Compile::current()->major_progress() && _child == NULL) {
2598     for( uint i = 0; i < _body.size(); i++ ) {
2599       Node *n = _body.at(i);
2600       if (n->outcnt() == 0)  continue; // Ignore dead
2601       uint j;
2602       for( j = 0; j < loop->_body.size(); j++ )
2603         if( loop->_body.at(j) == n )
2604           break;
2605       if( j == loop->_body.size() ) { // Not found in loop body
2606         // Last ditch effort to avoid assertion: Its possible that we
2607         // have some users (so outcnt not zero) but are still dead.
2608         // Try to find from root.
2609         if (Compile::current()->root()->find(n->_idx)) {
2610           fail++;
2611           tty->print("We have that verify does not: ");
2612           n->dump();
2613         }
2614       }
2615     }
2616     for( uint i2 = 0; i2 < loop->_body.size(); i2++ ) {
2617       Node *n = loop->_body.at(i2);
2618       if (n->outcnt() == 0)  continue; // Ignore dead
2619       uint j;
2620       for( j = 0; j < _body.size(); j++ )
2621         if( _body.at(j) == n )
2622           break;
2623       if( j == _body.size() ) { // Not found in loop body
2624         // Last ditch effort to avoid assertion: Its possible that we
2625         // have some users (so outcnt not zero) but are still dead.
2626         // Try to find from root.
2627         if (Compile::current()->root()->find(n->_idx)) {
2628           fail++;
2629           tty->print("Verify has that we do not: ");
2630           n->dump();
2631         }
2632       }
2633     }
2634     assert( !fail, "loop body mismatch" );
2635   }
2636 }
2637 
2638 #endif
2639 
2640 //------------------------------set_idom---------------------------------------
2641 void PhaseIdealLoop::set_idom(Node* d, Node* n, uint dom_depth) {
2642   uint idx = d->_idx;
2643   if (idx >= _idom_size) {
2644     uint newsize = _idom_size<<1;
2645     while( idx >= newsize ) {
2646       newsize <<= 1;
2647     }
2648     _idom      = REALLOC_RESOURCE_ARRAY( Node*,     _idom,_idom_size,newsize);
2649     _dom_depth = REALLOC_RESOURCE_ARRAY( uint, _dom_depth,_idom_size,newsize);
2650     memset( _dom_depth + _idom_size, 0, (newsize - _idom_size) * sizeof(uint) );
2651     _idom_size = newsize;
2652   }
2653   _idom[idx] = n;
2654   _dom_depth[idx] = dom_depth;
2655 }
2656 
2657 //------------------------------recompute_dom_depth---------------------------------------
2658 // The dominator tree is constructed with only parent pointers.
2659 // This recomputes the depth in the tree by first tagging all
2660 // nodes as "no depth yet" marker.  The next pass then runs up
2661 // the dom tree from each node marked "no depth yet", and computes
2662 // the depth on the way back down.
2663 void PhaseIdealLoop::recompute_dom_depth() {
2664   uint no_depth_marker = C->unique();
2665   uint i;
2666   // Initialize depth to "no depth yet"
2667   for (i = 0; i < _idom_size; i++) {
2668     if (_dom_depth[i] > 0 && _idom[i] != NULL) {
2669      _dom_depth[i] = no_depth_marker;
2670     }
2671   }
2672   if (_dom_stk == NULL) {
2673     uint init_size = C->live_nodes() / 100; // Guess that 1/100 is a reasonable initial size.
2674     if (init_size < 10) init_size = 10;
2675     _dom_stk = new GrowableArray<uint>(init_size);
2676   }
2677   // Compute new depth for each node.
2678   for (i = 0; i < _idom_size; i++) {
2679     uint j = i;
2680     // Run up the dom tree to find a node with a depth
2681     while (_dom_depth[j] == no_depth_marker) {
2682       _dom_stk->push(j);
2683       j = _idom[j]->_idx;
2684     }
2685     // Compute the depth on the way back down this tree branch
2686     uint dd = _dom_depth[j] + 1;
2687     while (_dom_stk->length() > 0) {
2688       uint j = _dom_stk->pop();
2689       _dom_depth[j] = dd;
2690       dd++;
2691     }
2692   }
2693 }
2694 
2695 //------------------------------sort-------------------------------------------
2696 // Insert 'loop' into the existing loop tree.  'innermost' is a leaf of the
2697 // loop tree, not the root.
2698 IdealLoopTree *PhaseIdealLoop::sort( IdealLoopTree *loop, IdealLoopTree *innermost ) {
2699   if( !innermost ) return loop; // New innermost loop
2700 
2701   int loop_preorder = get_preorder(loop->_head); // Cache pre-order number
2702   assert( loop_preorder, "not yet post-walked loop" );
2703   IdealLoopTree **pp = &innermost;      // Pointer to previous next-pointer
2704   IdealLoopTree *l = *pp;               // Do I go before or after 'l'?
2705 
2706   // Insert at start of list
2707   while( l ) {                  // Insertion sort based on pre-order
2708     if( l == loop ) return innermost; // Already on list!
2709     int l_preorder = get_preorder(l->_head); // Cache pre-order number
2710     assert( l_preorder, "not yet post-walked l" );
2711     // Check header pre-order number to figure proper nesting
2712     if( loop_preorder > l_preorder )
2713       break;                    // End of insertion
2714     // If headers tie (e.g., shared headers) check tail pre-order numbers.
2715     // Since I split shared headers, you'd think this could not happen.
2716     // BUT: I must first do the preorder numbering before I can discover I
2717     // have shared headers, so the split headers all get the same preorder
2718     // number as the RegionNode they split from.
2719     if( loop_preorder == l_preorder &&
2720         get_preorder(loop->_tail) < get_preorder(l->_tail) )
2721       break;                    // Also check for shared headers (same pre#)
2722     pp = &l->_parent;           // Chain up list
2723     l = *pp;
2724   }
2725   // Link into list
2726   // Point predecessor to me
2727   *pp = loop;
2728   // Point me to successor
2729   IdealLoopTree *p = loop->_parent;
2730   loop->_parent = l;            // Point me to successor
2731   if( p ) sort( p, innermost ); // Insert my parents into list as well
2732   return innermost;
2733 }
2734 
2735 //------------------------------build_loop_tree--------------------------------
2736 // I use a modified Vick/Tarjan algorithm.  I need pre- and a post- visit
2737 // bits.  The _nodes[] array is mapped by Node index and holds a NULL for
2738 // not-yet-pre-walked, pre-order # for pre-but-not-post-walked and holds the
2739 // tightest enclosing IdealLoopTree for post-walked.
2740 //
2741 // During my forward walk I do a short 1-layer lookahead to see if I can find
2742 // a loop backedge with that doesn't have any work on the backedge.  This
2743 // helps me construct nested loops with shared headers better.
2744 //
2745 // Once I've done the forward recursion, I do the post-work.  For each child
2746 // I check to see if there is a backedge.  Backedges define a loop!  I
2747 // insert an IdealLoopTree at the target of the backedge.
2748 //
2749 // During the post-work I also check to see if I have several children
2750 // belonging to different loops.  If so, then this Node is a decision point
2751 // where control flow can choose to change loop nests.  It is at this
2752 // decision point where I can figure out how loops are nested.  At this
2753 // time I can properly order the different loop nests from my children.
2754 // Note that there may not be any backedges at the decision point!
2755 //
2756 // Since the decision point can be far removed from the backedges, I can't
2757 // order my loops at the time I discover them.  Thus at the decision point
2758 // I need to inspect loop header pre-order numbers to properly nest my
2759 // loops.  This means I need to sort my childrens' loops by pre-order.
2760 // The sort is of size number-of-control-children, which generally limits
2761 // it to size 2 (i.e., I just choose between my 2 target loops).
2762 void PhaseIdealLoop::build_loop_tree() {
2763   // Allocate stack of size C->live_nodes()/2 to avoid frequent realloc
2764   GrowableArray <Node *> bltstack(C->live_nodes() >> 1);
2765   Node *n = C->root();
2766   bltstack.push(n);
2767   int pre_order = 1;
2768   int stack_size;
2769 
2770   while ( ( stack_size = bltstack.length() ) != 0 ) {
2771     n = bltstack.top(); // Leave node on stack
2772     if ( !is_visited(n) ) {
2773       // ---- Pre-pass Work ----
2774       // Pre-walked but not post-walked nodes need a pre_order number.
2775 
2776       set_preorder_visited( n, pre_order ); // set as visited
2777 
2778       // ---- Scan over children ----
2779       // Scan first over control projections that lead to loop headers.
2780       // This helps us find inner-to-outer loops with shared headers better.
2781 
2782       // Scan children's children for loop headers.
2783       for ( int i = n->outcnt() - 1; i >= 0; --i ) {
2784         Node* m = n->raw_out(i);       // Child
2785         if( m->is_CFG() && !is_visited(m) ) { // Only for CFG children
2786           // Scan over children's children to find loop
2787           for (DUIterator_Fast jmax, j = m->fast_outs(jmax); j < jmax; j++) {
2788             Node* l = m->fast_out(j);
2789             if( is_visited(l) &&       // Been visited?
2790                 !is_postvisited(l) &&  // But not post-visited
2791                 get_preorder(l) < pre_order ) { // And smaller pre-order
2792               // Found!  Scan the DFS down this path before doing other paths
2793               bltstack.push(m);
2794               break;
2795             }
2796           }
2797         }
2798       }
2799       pre_order++;
2800     }
2801     else if ( !is_postvisited(n) ) {
2802       // Note: build_loop_tree_impl() adds out edges on rare occasions,
2803       // such as com.sun.rsasign.am::a.
2804       // For non-recursive version, first, process current children.
2805       // On next iteration, check if additional children were added.
2806       for ( int k = n->outcnt() - 1; k >= 0; --k ) {
2807         Node* u = n->raw_out(k);
2808         if ( u->is_CFG() && !is_visited(u) ) {
2809           bltstack.push(u);
2810         }
2811       }
2812       if ( bltstack.length() == stack_size ) {
2813         // There were no additional children, post visit node now
2814         (void)bltstack.pop(); // Remove node from stack
2815         pre_order = build_loop_tree_impl( n, pre_order );
2816         // Check for bailout
2817         if (C->failing()) {
2818           return;
2819         }
2820         // Check to grow _preorders[] array for the case when
2821         // build_loop_tree_impl() adds new nodes.
2822         check_grow_preorders();
2823       }
2824     }
2825     else {
2826       (void)bltstack.pop(); // Remove post-visited node from stack
2827     }
2828   }
2829 }
2830 
2831 //------------------------------build_loop_tree_impl---------------------------
2832 int PhaseIdealLoop::build_loop_tree_impl( Node *n, int pre_order ) {
2833   // ---- Post-pass Work ----
2834   // Pre-walked but not post-walked nodes need a pre_order number.
2835 
2836   // Tightest enclosing loop for this Node
2837   IdealLoopTree *innermost = NULL;
2838 
2839   // For all children, see if any edge is a backedge.  If so, make a loop
2840   // for it.  Then find the tightest enclosing loop for the self Node.
2841   for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
2842     Node* m = n->fast_out(i);   // Child
2843     if( n == m ) continue;      // Ignore control self-cycles
2844     if( !m->is_CFG() ) continue;// Ignore non-CFG edges
2845 
2846     IdealLoopTree *l;           // Child's loop
2847     if( !is_postvisited(m) ) {  // Child visited but not post-visited?
2848       // Found a backedge
2849       assert( get_preorder(m) < pre_order, "should be backedge" );
2850       // Check for the RootNode, which is already a LoopNode and is allowed
2851       // to have multiple "backedges".
2852       if( m == C->root()) {     // Found the root?
2853         l = _ltree_root;        // Root is the outermost LoopNode
2854       } else {                  // Else found a nested loop
2855         // Insert a LoopNode to mark this loop.
2856         l = new IdealLoopTree(this, m, n);
2857       } // End of Else found a nested loop
2858       if( !has_loop(m) )        // If 'm' does not already have a loop set
2859         set_loop(m, l);         // Set loop header to loop now
2860 
2861     } else {                    // Else not a nested loop
2862       if( !_nodes[m->_idx] ) continue; // Dead code has no loop
2863       l = get_loop(m);          // Get previously determined loop
2864       // If successor is header of a loop (nest), move up-loop till it
2865       // is a member of some outer enclosing loop.  Since there are no
2866       // shared headers (I've split them already) I only need to go up
2867       // at most 1 level.
2868       while( l && l->_head == m ) // Successor heads loop?
2869         l = l->_parent;         // Move up 1 for me
2870       // If this loop is not properly parented, then this loop
2871       // has no exit path out, i.e. its an infinite loop.
2872       if( !l ) {
2873         // Make loop "reachable" from root so the CFG is reachable.  Basically
2874         // insert a bogus loop exit that is never taken.  'm', the loop head,
2875         // points to 'n', one (of possibly many) fall-in paths.  There may be
2876         // many backedges as well.
2877 
2878         // Here I set the loop to be the root loop.  I could have, after
2879         // inserting a bogus loop exit, restarted the recursion and found my
2880         // new loop exit.  This would make the infinite loop a first-class
2881         // loop and it would then get properly optimized.  What's the use of
2882         // optimizing an infinite loop?
2883         l = _ltree_root;        // Oops, found infinite loop
2884 
2885         if (!_verify_only) {
2886           // Insert the NeverBranch between 'm' and it's control user.
2887           NeverBranchNode *iff = new NeverBranchNode( m );
2888           _igvn.register_new_node_with_optimizer(iff);
2889           set_loop(iff, l);
2890           Node *if_t = new CProjNode( iff, 0 );
2891           _igvn.register_new_node_with_optimizer(if_t);
2892           set_loop(if_t, l);
2893 
2894           Node* cfg = NULL;       // Find the One True Control User of m
2895           for (DUIterator_Fast jmax, j = m->fast_outs(jmax); j < jmax; j++) {
2896             Node* x = m->fast_out(j);
2897             if (x->is_CFG() && x != m && x != iff)
2898               { cfg = x; break; }
2899           }
2900           assert(cfg != NULL, "must find the control user of m");
2901           uint k = 0;             // Probably cfg->in(0)
2902           while( cfg->in(k) != m ) k++; // But check incase cfg is a Region
2903           cfg->set_req( k, if_t ); // Now point to NeverBranch
2904           _igvn._worklist.push(cfg);
2905 
2906           // Now create the never-taken loop exit
2907           Node *if_f = new CProjNode( iff, 1 );
2908           _igvn.register_new_node_with_optimizer(if_f);
2909           set_loop(if_f, l);
2910           // Find frame ptr for Halt.  Relies on the optimizer
2911           // V-N'ing.  Easier and quicker than searching through
2912           // the program structure.
2913           Node *frame = new ParmNode( C->start(), TypeFunc::FramePtr );
2914           _igvn.register_new_node_with_optimizer(frame);
2915           // Halt & Catch Fire
2916           Node *halt = new HaltNode( if_f, frame );
2917           _igvn.register_new_node_with_optimizer(halt);
2918           set_loop(halt, l);
2919           C->root()->add_req(halt);
2920         }
2921         set_loop(C->root(), _ltree_root);
2922       }
2923     }
2924     // Weeny check for irreducible.  This child was already visited (this
2925     // IS the post-work phase).  Is this child's loop header post-visited
2926     // as well?  If so, then I found another entry into the loop.
2927     if (!_verify_only) {
2928       while( is_postvisited(l->_head) ) {
2929         // found irreducible
2930         l->_irreducible = 1; // = true
2931         l = l->_parent;
2932         _has_irreducible_loops = true;
2933         // Check for bad CFG here to prevent crash, and bailout of compile
2934         if (l == NULL) {
2935           C->record_method_not_compilable("unhandled CFG detected during loop optimization");
2936           return pre_order;
2937         }
2938       }
2939       C->set_has_irreducible_loop(_has_irreducible_loops);
2940     }
2941 
2942     // This Node might be a decision point for loops.  It is only if
2943     // it's children belong to several different loops.  The sort call
2944     // does a trivial amount of work if there is only 1 child or all
2945     // children belong to the same loop.  If however, the children
2946     // belong to different loops, the sort call will properly set the
2947     // _parent pointers to show how the loops nest.
2948     //
2949     // In any case, it returns the tightest enclosing loop.
2950     innermost = sort( l, innermost );
2951   }
2952 
2953   // Def-use info will have some dead stuff; dead stuff will have no
2954   // loop decided on.
2955 
2956   // Am I a loop header?  If so fix up my parent's child and next ptrs.
2957   if( innermost && innermost->_head == n ) {
2958     assert( get_loop(n) == innermost, "" );
2959     IdealLoopTree *p = innermost->_parent;
2960     IdealLoopTree *l = innermost;
2961     while( p && l->_head == n ) {
2962       l->_next = p->_child;     // Put self on parents 'next child'
2963       p->_child = l;            // Make self as first child of parent
2964       l = p;                    // Now walk up the parent chain
2965       p = l->_parent;
2966     }
2967   } else {
2968     // Note that it is possible for a LoopNode to reach here, if the
2969     // backedge has been made unreachable (hence the LoopNode no longer
2970     // denotes a Loop, and will eventually be removed).
2971 
2972     // Record tightest enclosing loop for self.  Mark as post-visited.
2973     set_loop(n, innermost);
2974     // Also record has_call flag early on
2975     if( innermost ) {
2976       if( n->is_Call() && !n->is_CallLeaf() && !n->is_macro() ) {
2977         // Do not count uncommon calls
2978         if( !n->is_CallStaticJava() || !n->as_CallStaticJava()->_name ) {
2979           Node *iff = n->in(0)->in(0);
2980           // No any calls for vectorized loops.
2981           if( UseSuperWord || !iff->is_If() ||
2982               (n->in(0)->Opcode() == Op_IfFalse &&
2983                (1.0 - iff->as_If()->_prob) >= 0.01) ||
2984               (iff->as_If()->_prob >= 0.01) )
2985             innermost->_has_call = 1;
2986         }
2987       } else if( n->is_Allocate() && n->as_Allocate()->_is_scalar_replaceable ) {
2988         // Disable loop optimizations if the loop has a scalar replaceable
2989         // allocation. This disabling may cause a potential performance lost
2990         // if the allocation is not eliminated for some reason.
2991         innermost->_allow_optimizations = false;
2992         innermost->_has_call = 1; // = true
2993       } else if (n->Opcode() == Op_SafePoint) {
2994         // Record all safepoints in this loop.
2995         if (innermost->_safepts == NULL) innermost->_safepts = new Node_List();
2996         innermost->_safepts->push(n);
2997       }
2998     }
2999   }
3000 
3001   // Flag as post-visited now
3002   set_postvisited(n);
3003   return pre_order;
3004 }
3005 
3006 
3007 //------------------------------build_loop_early-------------------------------
3008 // Put Data nodes into some loop nest, by setting the _nodes[]->loop mapping.
3009 // First pass computes the earliest controlling node possible.  This is the
3010 // controlling input with the deepest dominating depth.
3011 void PhaseIdealLoop::build_loop_early( VectorSet &visited, Node_List &worklist, Node_Stack &nstack ) {
3012   while (worklist.size() != 0) {
3013     // Use local variables nstack_top_n & nstack_top_i to cache values
3014     // on nstack's top.
3015     Node *nstack_top_n = worklist.pop();
3016     uint  nstack_top_i = 0;
3017 //while_nstack_nonempty:
3018     while (true) {
3019       // Get parent node and next input's index from stack's top.
3020       Node  *n = nstack_top_n;
3021       uint   i = nstack_top_i;
3022       uint cnt = n->req(); // Count of inputs
3023       if (i == 0) {        // Pre-process the node.
3024         if( has_node(n) &&            // Have either loop or control already?
3025             !has_ctrl(n) ) {          // Have loop picked out already?
3026           // During "merge_many_backedges" we fold up several nested loops
3027           // into a single loop.  This makes the members of the original
3028           // loop bodies pointing to dead loops; they need to move up
3029           // to the new UNION'd larger loop.  I set the _head field of these
3030           // dead loops to NULL and the _parent field points to the owning
3031           // loop.  Shades of UNION-FIND algorithm.
3032           IdealLoopTree *ilt;
3033           while( !(ilt = get_loop(n))->_head ) {
3034             // Normally I would use a set_loop here.  But in this one special
3035             // case, it is legal (and expected) to change what loop a Node
3036             // belongs to.
3037             _nodes.map(n->_idx, (Node*)(ilt->_parent) );
3038           }
3039           // Remove safepoints ONLY if I've already seen I don't need one.
3040           // (the old code here would yank a 2nd safepoint after seeing a
3041           // first one, even though the 1st did not dominate in the loop body
3042           // and thus could be avoided indefinitely)
3043           if( !_verify_only && !_verify_me && ilt->_has_sfpt && n->Opcode() == Op_SafePoint &&
3044               is_deleteable_safept(n)) {
3045             Node *in = n->in(TypeFunc::Control);
3046             lazy_replace(n,in);       // Pull safepoint now
3047             if (ilt->_safepts != NULL) {
3048               ilt->_safepts->yank(n);
3049             }
3050             // Carry on with the recursion "as if" we are walking
3051             // only the control input
3052             if( !visited.test_set( in->_idx ) ) {
3053               worklist.push(in);      // Visit this guy later, using worklist
3054             }
3055             // Get next node from nstack:
3056             // - skip n's inputs processing by setting i > cnt;
3057             // - we also will not call set_early_ctrl(n) since
3058             //   has_node(n) == true (see the condition above).
3059             i = cnt + 1;
3060           }
3061         }
3062       } // if (i == 0)
3063 
3064       // Visit all inputs
3065       bool done = true;       // Assume all n's inputs will be processed
3066       while (i < cnt) {
3067         Node *in = n->in(i);
3068         ++i;
3069         if (in == NULL) continue;
3070         if (in->pinned() && !in->is_CFG())
3071           set_ctrl(in, in->in(0));
3072         int is_visited = visited.test_set( in->_idx );
3073         if (!has_node(in)) {  // No controlling input yet?
3074           assert( !in->is_CFG(), "CFG Node with no controlling input?" );
3075           assert( !is_visited, "visit only once" );
3076           nstack.push(n, i);  // Save parent node and next input's index.
3077           nstack_top_n = in;  // Process current input now.
3078           nstack_top_i = 0;
3079           done = false;       // Not all n's inputs processed.
3080           break; // continue while_nstack_nonempty;
3081         } else if (!is_visited) {
3082           // This guy has a location picked out for him, but has not yet
3083           // been visited.  Happens to all CFG nodes, for instance.
3084           // Visit him using the worklist instead of recursion, to break
3085           // cycles.  Since he has a location already we do not need to
3086           // find his location before proceeding with the current Node.
3087           worklist.push(in);  // Visit this guy later, using worklist
3088         }
3089       }
3090       if (done) {
3091         // All of n's inputs have been processed, complete post-processing.
3092 
3093         // Compute earliest point this Node can go.
3094         // CFG, Phi, pinned nodes already know their controlling input.
3095         if (!has_node(n)) {
3096           // Record earliest legal location
3097           set_early_ctrl( n );
3098         }
3099         if (nstack.is_empty()) {
3100           // Finished all nodes on stack.
3101           // Process next node on the worklist.
3102           break;
3103         }
3104         // Get saved parent node and next input's index.
3105         nstack_top_n = nstack.node();
3106         nstack_top_i = nstack.index();
3107         nstack.pop();
3108       }
3109     } // while (true)
3110   }
3111 }
3112 
3113 //------------------------------dom_lca_internal--------------------------------
3114 // Pair-wise LCA
3115 Node *PhaseIdealLoop::dom_lca_internal( Node *n1, Node *n2 ) const {
3116   if( !n1 ) return n2;          // Handle NULL original LCA
3117   assert( n1->is_CFG(), "" );
3118   assert( n2->is_CFG(), "" );
3119   // find LCA of all uses
3120   uint d1 = dom_depth(n1);
3121   uint d2 = dom_depth(n2);
3122   while (n1 != n2) {
3123     if (d1 > d2) {
3124       n1 =      idom(n1);
3125       d1 = dom_depth(n1);
3126     } else if (d1 < d2) {
3127       n2 =      idom(n2);
3128       d2 = dom_depth(n2);
3129     } else {
3130       // Here d1 == d2.  Due to edits of the dominator-tree, sections
3131       // of the tree might have the same depth.  These sections have
3132       // to be searched more carefully.
3133 
3134       // Scan up all the n1's with equal depth, looking for n2.
3135       Node *t1 = idom(n1);
3136       while (dom_depth(t1) == d1) {
3137         if (t1 == n2)  return n2;
3138         t1 = idom(t1);
3139       }
3140       // Scan up all the n2's with equal depth, looking for n1.
3141       Node *t2 = idom(n2);
3142       while (dom_depth(t2) == d2) {
3143         if (t2 == n1)  return n1;
3144         t2 = idom(t2);
3145       }
3146       // Move up to a new dominator-depth value as well as up the dom-tree.
3147       n1 = t1;
3148       n2 = t2;
3149       d1 = dom_depth(n1);
3150       d2 = dom_depth(n2);
3151     }
3152   }
3153   return n1;
3154 }
3155 
3156 //------------------------------compute_idom-----------------------------------
3157 // Locally compute IDOM using dom_lca call.  Correct only if the incoming
3158 // IDOMs are correct.
3159 Node *PhaseIdealLoop::compute_idom( Node *region ) const {
3160   assert( region->is_Region(), "" );
3161   Node *LCA = NULL;
3162   for( uint i = 1; i < region->req(); i++ ) {
3163     if( region->in(i) != C->top() )
3164       LCA = dom_lca( LCA, region->in(i) );
3165   }
3166   return LCA;
3167 }
3168 
3169 bool PhaseIdealLoop::verify_dominance(Node* n, Node* use, Node* LCA, Node* early) {
3170   bool had_error = false;
3171 #ifdef ASSERT
3172   if (early != C->root()) {
3173     // Make sure that there's a dominance path from LCA to early
3174     Node* d = LCA;
3175     while (d != early) {
3176       if (d == C->root()) {
3177         dump_bad_graph("Bad graph detected in compute_lca_of_uses", n, early, LCA);
3178         tty->print_cr("*** Use %d isn't dominated by def %d ***", use->_idx, n->_idx);
3179         had_error = true;
3180         break;
3181       }
3182       d = idom(d);
3183     }
3184   }
3185 #endif
3186   return had_error;
3187 }
3188 
3189 
3190 Node* PhaseIdealLoop::compute_lca_of_uses(Node* n, Node* early, bool verify) {
3191   // Compute LCA over list of uses
3192   bool had_error = false;
3193   Node *LCA = NULL;
3194   for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax && LCA != early; i++) {
3195     Node* c = n->fast_out(i);
3196     if (_nodes[c->_idx] == NULL)
3197       continue;                 // Skip the occasional dead node
3198     if( c->is_Phi() ) {         // For Phis, we must land above on the path
3199       for( uint j=1; j<c->req(); j++ ) {// For all inputs
3200         if( c->in(j) == n ) {   // Found matching input?
3201           Node *use = c->in(0)->in(j);
3202           if (_verify_only && use->is_top()) continue;
3203           LCA = dom_lca_for_get_late_ctrl( LCA, use, n );
3204           if (verify) had_error = verify_dominance(n, use, LCA, early) || had_error;
3205         }
3206       }
3207     } else {
3208       // For CFG data-users, use is in the block just prior
3209       Node *use = has_ctrl(c) ? get_ctrl(c) : c->in(0);
3210       LCA = dom_lca_for_get_late_ctrl( LCA, use, n );
3211       if (verify) had_error = verify_dominance(n, use, LCA, early) || had_error;
3212     }
3213   }
3214   assert(!had_error, "bad dominance");
3215   return LCA;
3216 }
3217 
3218 // Check the shape of the graph at the loop entry. In some cases,
3219 // the shape of the graph does not match the shape outlined below.
3220 // That is caused by the Opaque1 node "protecting" the shape of
3221 // the graph being removed by, for example, the IGVN performed
3222 // in PhaseIdealLoop::build_and_optimize().
3223 //
3224 // After the Opaque1 node has been removed, optimizations (e.g., split-if,
3225 // loop unswitching, and IGVN, or a combination of them) can freely change
3226 // the graph's shape. As a result, the graph shape outlined below cannot
3227 // be guaranteed anymore.
3228 bool PhaseIdealLoop::is_canonical_loop_entry(CountedLoopNode* cl) {
3229   if (!cl->is_main_loop() && !cl->is_post_loop()) {
3230     return false;
3231   }
3232   Node* ctrl = cl->in(LoopNode::EntryControl);
3233   if (ctrl == NULL || (!ctrl->is_IfTrue() && !ctrl->is_IfFalse())) {
3234     return false;
3235   }
3236   Node* iffm = ctrl->in(0);
3237   if (iffm == NULL || !iffm->is_If()) {
3238     return false;
3239   }
3240   Node* bolzm = iffm->in(1);
3241   if (bolzm == NULL || !bolzm->is_Bool()) {
3242     return false;
3243   }
3244   Node* cmpzm = bolzm->in(1);
3245   if (cmpzm == NULL || !cmpzm->is_Cmp()) {
3246     return false;
3247   }
3248   // compares can get conditionally flipped
3249   bool found_opaque = false;
3250   for (uint i = 1; i < cmpzm->req(); i++) {
3251     Node* opnd = cmpzm->in(i);
3252     if (opnd && opnd->Opcode() == Op_Opaque1) {
3253       found_opaque = true;
3254       break;
3255     }
3256   }
3257   if (!found_opaque) {
3258     return false;
3259   }
3260   return true;
3261 }
3262 
3263 //------------------------------get_late_ctrl----------------------------------
3264 // Compute latest legal control.
3265 Node *PhaseIdealLoop::get_late_ctrl( Node *n, Node *early ) {
3266   assert(early != NULL, "early control should not be NULL");
3267 
3268   Node* LCA = compute_lca_of_uses(n, early);
3269 #ifdef ASSERT
3270   if (LCA == C->root() && LCA != early) {
3271     // def doesn't dominate uses so print some useful debugging output
3272     compute_lca_of_uses(n, early, true);
3273   }
3274 #endif
3275 
3276   // if this is a load, check for anti-dependent stores
3277   // We use a conservative algorithm to identify potential interfering
3278   // instructions and for rescheduling the load.  The users of the memory
3279   // input of this load are examined.  Any use which is not a load and is
3280   // dominated by early is considered a potentially interfering store.
3281   // This can produce false positives.
3282   if (n->is_Load() && LCA != early) {
3283     Node_List worklist;
3284 
3285     Node *mem = n->in(MemNode::Memory);
3286     for (DUIterator_Fast imax, i = mem->fast_outs(imax); i < imax; i++) {
3287       Node* s = mem->fast_out(i);
3288       worklist.push(s);
3289     }
3290     while(worklist.size() != 0 && LCA != early) {
3291       Node* s = worklist.pop();
3292       if (s->is_Load()) {
3293         continue;
3294       } else if (s->is_MergeMem()) {
3295         for (DUIterator_Fast imax, i = s->fast_outs(imax); i < imax; i++) {
3296           Node* s1 = s->fast_out(i);
3297           worklist.push(s1);
3298         }
3299       } else {
3300         Node *sctrl = has_ctrl(s) ? get_ctrl(s) : s->in(0);
3301         assert(sctrl != NULL || s->outcnt() == 0, "must have control");
3302         if (sctrl != NULL && !sctrl->is_top() && is_dominator(early, sctrl)) {
3303           LCA = dom_lca_for_get_late_ctrl(LCA, sctrl, n);
3304         }
3305       }
3306     }
3307   }
3308 
3309   assert(LCA == find_non_split_ctrl(LCA), "unexpected late control");
3310   return LCA;
3311 }
3312 
3313 // true if CFG node d dominates CFG node n
3314 bool PhaseIdealLoop::is_dominator(Node *d, Node *n) {
3315   if (d == n)
3316     return true;
3317   assert(d->is_CFG() && n->is_CFG(), "must have CFG nodes");
3318   uint dd = dom_depth(d);
3319   while (dom_depth(n) >= dd) {
3320     if (n == d)
3321       return true;
3322     n = idom(n);
3323   }
3324   return false;
3325 }
3326 
3327 //------------------------------dom_lca_for_get_late_ctrl_internal-------------
3328 // Pair-wise LCA with tags.
3329 // Tag each index with the node 'tag' currently being processed
3330 // before advancing up the dominator chain using idom().
3331 // Later calls that find a match to 'tag' know that this path has already
3332 // been considered in the current LCA (which is input 'n1' by convention).
3333 // Since get_late_ctrl() is only called once for each node, the tag array
3334 // does not need to be cleared between calls to get_late_ctrl().
3335 // Algorithm trades a larger constant factor for better asymptotic behavior
3336 //
3337 Node *PhaseIdealLoop::dom_lca_for_get_late_ctrl_internal( Node *n1, Node *n2, Node *tag ) {
3338   uint d1 = dom_depth(n1);
3339   uint d2 = dom_depth(n2);
3340 
3341   do {
3342     if (d1 > d2) {
3343       // current lca is deeper than n2
3344       _dom_lca_tags.map(n1->_idx, tag);
3345       n1 =      idom(n1);
3346       d1 = dom_depth(n1);
3347     } else if (d1 < d2) {
3348       // n2 is deeper than current lca
3349       Node *memo = _dom_lca_tags[n2->_idx];
3350       if( memo == tag ) {
3351         return n1;    // Return the current LCA
3352       }
3353       _dom_lca_tags.map(n2->_idx, tag);
3354       n2 =      idom(n2);
3355       d2 = dom_depth(n2);
3356     } else {
3357       // Here d1 == d2.  Due to edits of the dominator-tree, sections
3358       // of the tree might have the same depth.  These sections have
3359       // to be searched more carefully.
3360 
3361       // Scan up all the n1's with equal depth, looking for n2.
3362       _dom_lca_tags.map(n1->_idx, tag);
3363       Node *t1 = idom(n1);
3364       while (dom_depth(t1) == d1) {
3365         if (t1 == n2)  return n2;
3366         _dom_lca_tags.map(t1->_idx, tag);
3367         t1 = idom(t1);
3368       }
3369       // Scan up all the n2's with equal depth, looking for n1.
3370       _dom_lca_tags.map(n2->_idx, tag);
3371       Node *t2 = idom(n2);
3372       while (dom_depth(t2) == d2) {
3373         if (t2 == n1)  return n1;
3374         _dom_lca_tags.map(t2->_idx, tag);
3375         t2 = idom(t2);
3376       }
3377       // Move up to a new dominator-depth value as well as up the dom-tree.
3378       n1 = t1;
3379       n2 = t2;
3380       d1 = dom_depth(n1);
3381       d2 = dom_depth(n2);
3382     }
3383   } while (n1 != n2);
3384   return n1;
3385 }
3386 
3387 //------------------------------init_dom_lca_tags------------------------------
3388 // Tag could be a node's integer index, 32bits instead of 64bits in some cases
3389 // Intended use does not involve any growth for the array, so it could
3390 // be of fixed size.
3391 void PhaseIdealLoop::init_dom_lca_tags() {
3392   uint limit = C->unique() + 1;
3393   _dom_lca_tags.map( limit, NULL );
3394 #ifdef ASSERT
3395   for( uint i = 0; i < limit; ++i ) {
3396     assert(_dom_lca_tags[i] == NULL, "Must be distinct from each node pointer");
3397   }
3398 #endif // ASSERT
3399 }
3400 
3401 //------------------------------clear_dom_lca_tags------------------------------
3402 // Tag could be a node's integer index, 32bits instead of 64bits in some cases
3403 // Intended use does not involve any growth for the array, so it could
3404 // be of fixed size.
3405 void PhaseIdealLoop::clear_dom_lca_tags() {
3406   uint limit = C->unique() + 1;
3407   _dom_lca_tags.map( limit, NULL );
3408   _dom_lca_tags.clear();
3409 #ifdef ASSERT
3410   for( uint i = 0; i < limit; ++i ) {
3411     assert(_dom_lca_tags[i] == NULL, "Must be distinct from each node pointer");
3412   }
3413 #endif // ASSERT
3414 }
3415 
3416 //------------------------------build_loop_late--------------------------------
3417 // Put Data nodes into some loop nest, by setting the _nodes[]->loop mapping.
3418 // Second pass finds latest legal placement, and ideal loop placement.
3419 void PhaseIdealLoop::build_loop_late( VectorSet &visited, Node_List &worklist, Node_Stack &nstack ) {
3420   while (worklist.size() != 0) {
3421     Node *n = worklist.pop();
3422     // Only visit once
3423     if (visited.test_set(n->_idx)) continue;
3424     uint cnt = n->outcnt();
3425     uint   i = 0;
3426     while (true) {
3427       assert( _nodes[n->_idx], "no dead nodes" );
3428       // Visit all children
3429       if (i < cnt) {
3430         Node* use = n->raw_out(i);
3431         ++i;
3432         // Check for dead uses.  Aggressively prune such junk.  It might be
3433         // dead in the global sense, but still have local uses so I cannot
3434         // easily call 'remove_dead_node'.
3435         if( _nodes[use->_idx] != NULL || use->is_top() ) { // Not dead?
3436           // Due to cycles, we might not hit the same fixed point in the verify
3437           // pass as we do in the regular pass.  Instead, visit such phis as
3438           // simple uses of the loop head.
3439           if( use->in(0) && (use->is_CFG() || use->is_Phi()) ) {
3440             if( !visited.test(use->_idx) )
3441               worklist.push(use);
3442           } else if( !visited.test_set(use->_idx) ) {
3443             nstack.push(n, i); // Save parent and next use's index.
3444             n   = use;         // Process all children of current use.
3445             cnt = use->outcnt();
3446             i   = 0;
3447           }
3448         } else {
3449           // Do not visit around the backedge of loops via data edges.
3450           // push dead code onto a worklist
3451           _deadlist.push(use);
3452         }
3453       } else {
3454         // All of n's children have been processed, complete post-processing.
3455         build_loop_late_post(n);
3456         if (nstack.is_empty()) {
3457           // Finished all nodes on stack.
3458           // Process next node on the worklist.
3459           break;
3460         }
3461         // Get saved parent node and next use's index. Visit the rest of uses.
3462         n   = nstack.node();
3463         cnt = n->outcnt();
3464         i   = nstack.index();
3465         nstack.pop();
3466       }
3467     }
3468   }
3469 }
3470 
3471 //------------------------------build_loop_late_post---------------------------
3472 // Put Data nodes into some loop nest, by setting the _nodes[]->loop mapping.
3473 // Second pass finds latest legal placement, and ideal loop placement.
3474 void PhaseIdealLoop::build_loop_late_post( Node *n ) {
3475 
3476   if (n->req() == 2 && (n->Opcode() == Op_ConvI2L || n->Opcode() == Op_CastII) && !C->major_progress() && !_verify_only) {
3477     _igvn._worklist.push(n);  // Maybe we'll normalize it, if no more loops.
3478   }
3479 
3480 #ifdef ASSERT
3481   if (_verify_only && !n->is_CFG()) {
3482     // Check def-use domination.
3483     compute_lca_of_uses(n, get_ctrl(n), true /* verify */);
3484   }
3485 #endif
3486 
3487   // CFG and pinned nodes already handled
3488   if( n->in(0) ) {
3489     if( n->in(0)->is_top() ) return; // Dead?
3490 
3491     // We'd like +VerifyLoopOptimizations to not believe that Mod's/Loads
3492     // _must_ be pinned (they have to observe their control edge of course).
3493     // Unlike Stores (which modify an unallocable resource, the memory
3494     // state), Mods/Loads can float around.  So free them up.
3495     bool pinned = true;
3496     switch( n->Opcode() ) {
3497     case Op_DivI:
3498     case Op_DivF:
3499     case Op_DivD:
3500     case Op_ModI:
3501     case Op_ModF:
3502     case Op_ModD:
3503     case Op_LoadB:              // Same with Loads; they can sink
3504     case Op_LoadUB:             // during loop optimizations.
3505     case Op_LoadUS:
3506     case Op_LoadD:
3507     case Op_LoadF:
3508     case Op_LoadI:
3509     case Op_LoadKlass:
3510     case Op_LoadNKlass:
3511     case Op_LoadL:
3512     case Op_LoadS:
3513     case Op_LoadP:
3514     case Op_LoadN:
3515     case Op_LoadRange:
3516     case Op_LoadD_unaligned:
3517     case Op_LoadL_unaligned:
3518     case Op_StrComp:            // Does a bunch of load-like effects
3519     case Op_StrEquals:
3520     case Op_StrIndexOf:
3521     case Op_StrIndexOfChar:
3522     case Op_AryEq:
3523     case Op_HasNegatives:
3524       pinned = false;
3525     }
3526     if( pinned ) {
3527       IdealLoopTree *chosen_loop = get_loop(n->is_CFG() ? n : get_ctrl(n));
3528       if( !chosen_loop->_child )       // Inner loop?
3529         chosen_loop->_body.push(n); // Collect inner loops
3530       return;
3531     }
3532   } else {                      // No slot zero
3533     if( n->is_CFG() ) {         // CFG with no slot 0 is dead
3534       _nodes.map(n->_idx,0);    // No block setting, it's globally dead
3535       return;
3536     }
3537     assert(!n->is_CFG() || n->outcnt() == 0, "");
3538   }
3539 
3540   // Do I have a "safe range" I can select over?
3541   Node *early = get_ctrl(n);// Early location already computed
3542 
3543   // Compute latest point this Node can go
3544   Node *LCA = get_late_ctrl( n, early );
3545   // LCA is NULL due to uses being dead
3546   if( LCA == NULL ) {
3547 #ifdef ASSERT
3548     for (DUIterator i1 = n->outs(); n->has_out(i1); i1++) {
3549       assert( _nodes[n->out(i1)->_idx] == NULL, "all uses must also be dead");
3550     }
3551 #endif
3552     _nodes.map(n->_idx, 0);     // This node is useless
3553     _deadlist.push(n);
3554     return;
3555   }
3556   assert(LCA != NULL && !LCA->is_top(), "no dead nodes");
3557 
3558   Node *legal = LCA;            // Walk 'legal' up the IDOM chain
3559   Node *least = legal;          // Best legal position so far
3560   while( early != legal ) {     // While not at earliest legal
3561 #ifdef ASSERT
3562     if (legal->is_Start() && !early->is_Root()) {
3563       // Bad graph. Print idom path and fail.
3564       dump_bad_graph("Bad graph detected in build_loop_late", n, early, LCA);
3565       assert(false, "Bad graph detected in build_loop_late");
3566     }
3567 #endif
3568     // Find least loop nesting depth
3569     legal = idom(legal);        // Bump up the IDOM tree
3570     // Check for lower nesting depth
3571     if( get_loop(legal)->_nest < get_loop(least)->_nest )
3572       least = legal;
3573   }
3574   assert(early == legal || legal != C->root(), "bad dominance of inputs");
3575 
3576   // Try not to place code on a loop entry projection
3577   // which can inhibit range check elimination.
3578   if (least != early) {
3579     Node* ctrl_out = least->unique_ctrl_out();
3580     if (ctrl_out && ctrl_out->is_CountedLoop() &&
3581         least == ctrl_out->in(LoopNode::EntryControl)) {
3582       Node* least_dom = idom(least);
3583       if (get_loop(least_dom)->is_member(get_loop(least))) {
3584         least = least_dom;
3585       }
3586     }
3587   }
3588 
3589 #ifdef ASSERT
3590   // If verifying, verify that 'verify_me' has a legal location
3591   // and choose it as our location.
3592   if( _verify_me ) {
3593     Node *v_ctrl = _verify_me->get_ctrl_no_update(n);
3594     Node *legal = LCA;
3595     while( early != legal ) {   // While not at earliest legal
3596       if( legal == v_ctrl ) break;  // Check for prior good location
3597       legal = idom(legal)      ;// Bump up the IDOM tree
3598     }
3599     // Check for prior good location
3600     if( legal == v_ctrl ) least = legal; // Keep prior if found
3601   }
3602 #endif
3603 
3604   // Assign discovered "here or above" point
3605   least = find_non_split_ctrl(least);
3606   set_ctrl(n, least);
3607 
3608   // Collect inner loop bodies
3609   IdealLoopTree *chosen_loop = get_loop(least);
3610   if( !chosen_loop->_child )   // Inner loop?
3611     chosen_loop->_body.push(n);// Collect inner loops
3612 }
3613 
3614 #ifdef ASSERT
3615 void PhaseIdealLoop::dump_bad_graph(const char* msg, Node* n, Node* early, Node* LCA) {
3616   tty->print_cr("%s", msg);
3617   tty->print("n: "); n->dump();
3618   tty->print("early(n): "); early->dump();
3619   if (n->in(0) != NULL  && !n->in(0)->is_top() &&
3620       n->in(0) != early && !n->in(0)->is_Root()) {
3621     tty->print("n->in(0): "); n->in(0)->dump();
3622   }
3623   for (uint i = 1; i < n->req(); i++) {
3624     Node* in1 = n->in(i);
3625     if (in1 != NULL && in1 != n && !in1->is_top()) {
3626       tty->print("n->in(%d): ", i); in1->dump();
3627       Node* in1_early = get_ctrl(in1);
3628       tty->print("early(n->in(%d)): ", i); in1_early->dump();
3629       if (in1->in(0) != NULL     && !in1->in(0)->is_top() &&
3630           in1->in(0) != in1_early && !in1->in(0)->is_Root()) {
3631         tty->print("n->in(%d)->in(0): ", i); in1->in(0)->dump();
3632       }
3633       for (uint j = 1; j < in1->req(); j++) {
3634         Node* in2 = in1->in(j);
3635         if (in2 != NULL && in2 != n && in2 != in1 && !in2->is_top()) {
3636           tty->print("n->in(%d)->in(%d): ", i, j); in2->dump();
3637           Node* in2_early = get_ctrl(in2);
3638           tty->print("early(n->in(%d)->in(%d)): ", i, j); in2_early->dump();
3639           if (in2->in(0) != NULL     && !in2->in(0)->is_top() &&
3640               in2->in(0) != in2_early && !in2->in(0)->is_Root()) {
3641             tty->print("n->in(%d)->in(%d)->in(0): ", i, j); in2->in(0)->dump();
3642           }
3643         }
3644       }
3645     }
3646   }
3647   tty->cr();
3648   tty->print("LCA(n): "); LCA->dump();
3649   for (uint i = 0; i < n->outcnt(); i++) {
3650     Node* u1 = n->raw_out(i);
3651     if (u1 == n)
3652       continue;
3653     tty->print("n->out(%d): ", i); u1->dump();
3654     if (u1->is_CFG()) {
3655       for (uint j = 0; j < u1->outcnt(); j++) {
3656         Node* u2 = u1->raw_out(j);
3657         if (u2 != u1 && u2 != n && u2->is_CFG()) {
3658           tty->print("n->out(%d)->out(%d): ", i, j); u2->dump();
3659         }
3660       }
3661     } else {
3662       Node* u1_later = get_ctrl(u1);
3663       tty->print("later(n->out(%d)): ", i); u1_later->dump();
3664       if (u1->in(0) != NULL     && !u1->in(0)->is_top() &&
3665           u1->in(0) != u1_later && !u1->in(0)->is_Root()) {
3666         tty->print("n->out(%d)->in(0): ", i); u1->in(0)->dump();
3667       }
3668       for (uint j = 0; j < u1->outcnt(); j++) {
3669         Node* u2 = u1->raw_out(j);
3670         if (u2 == n || u2 == u1)
3671           continue;
3672         tty->print("n->out(%d)->out(%d): ", i, j); u2->dump();
3673         if (!u2->is_CFG()) {
3674           Node* u2_later = get_ctrl(u2);
3675           tty->print("later(n->out(%d)->out(%d)): ", i, j); u2_later->dump();
3676           if (u2->in(0) != NULL     && !u2->in(0)->is_top() &&
3677               u2->in(0) != u2_later && !u2->in(0)->is_Root()) {
3678             tty->print("n->out(%d)->in(0): ", i); u2->in(0)->dump();
3679           }
3680         }
3681       }
3682     }
3683   }
3684   tty->cr();
3685   int ct = 0;
3686   Node *dbg_legal = LCA;
3687   while(!dbg_legal->is_Start() && ct < 100) {
3688     tty->print("idom[%d] ",ct); dbg_legal->dump();
3689     ct++;
3690     dbg_legal = idom(dbg_legal);
3691   }
3692   tty->cr();
3693 }
3694 #endif
3695 
3696 #ifndef PRODUCT
3697 //------------------------------dump-------------------------------------------
3698 void PhaseIdealLoop::dump( ) const {
3699   ResourceMark rm;
3700   Arena* arena = Thread::current()->resource_area();
3701   Node_Stack stack(arena, C->live_nodes() >> 2);
3702   Node_List rpo_list;
3703   VectorSet visited(arena);
3704   visited.set(C->top()->_idx);
3705   rpo( C->root(), stack, visited, rpo_list );
3706   // Dump root loop indexed by last element in PO order
3707   dump( _ltree_root, rpo_list.size(), rpo_list );
3708 }
3709 
3710 void PhaseIdealLoop::dump( IdealLoopTree *loop, uint idx, Node_List &rpo_list ) const {
3711   loop->dump_head();
3712 
3713   // Now scan for CFG nodes in the same loop
3714   for( uint j=idx; j > 0;  j-- ) {
3715     Node *n = rpo_list[j-1];
3716     if( !_nodes[n->_idx] )      // Skip dead nodes
3717       continue;
3718     if( get_loop(n) != loop ) { // Wrong loop nest
3719       if( get_loop(n)->_head == n &&    // Found nested loop?
3720           get_loop(n)->_parent == loop )
3721         dump(get_loop(n),rpo_list.size(),rpo_list);     // Print it nested-ly
3722       continue;
3723     }
3724 
3725     // Dump controlling node
3726     for( uint x = 0; x < loop->_nest; x++ )
3727       tty->print("  ");
3728     tty->print("C");
3729     if( n == C->root() ) {
3730       n->dump();
3731     } else {
3732       Node* cached_idom   = idom_no_update(n);
3733       Node *computed_idom = n->in(0);
3734       if( n->is_Region() ) {
3735         computed_idom = compute_idom(n);
3736         // computed_idom() will return n->in(0) when idom(n) is an IfNode (or
3737         // any MultiBranch ctrl node), so apply a similar transform to
3738         // the cached idom returned from idom_no_update.
3739         cached_idom = find_non_split_ctrl(cached_idom);
3740       }
3741       tty->print(" ID:%d",computed_idom->_idx);
3742       n->dump();
3743       if( cached_idom != computed_idom ) {
3744         tty->print_cr("*** BROKEN IDOM!  Computed as: %d, cached as: %d",
3745                       computed_idom->_idx, cached_idom->_idx);
3746       }
3747     }
3748     // Dump nodes it controls
3749     for( uint k = 0; k < _nodes.Size(); k++ ) {
3750       // (k < C->unique() && get_ctrl(find(k)) == n)
3751       if (k < C->unique() && _nodes[k] == (Node*)((intptr_t)n + 1)) {
3752         Node *m = C->root()->find(k);
3753         if( m && m->outcnt() > 0 ) {
3754           if (!(has_ctrl(m) && get_ctrl_no_update(m) == n)) {
3755             tty->print_cr("*** BROKEN CTRL ACCESSOR!  _nodes[k] is %p, ctrl is %p",
3756                           _nodes[k], has_ctrl(m) ? get_ctrl_no_update(m) : NULL);
3757           }
3758           for( uint j = 0; j < loop->_nest; j++ )
3759             tty->print("  ");
3760           tty->print(" ");
3761           m->dump();
3762         }
3763       }
3764     }
3765   }
3766 }
3767 
3768 // Collect a R-P-O for the whole CFG.
3769 // Result list is in post-order (scan backwards for RPO)
3770 void PhaseIdealLoop::rpo( Node *start, Node_Stack &stk, VectorSet &visited, Node_List &rpo_list ) const {
3771   stk.push(start, 0);
3772   visited.set(start->_idx);
3773 
3774   while (stk.is_nonempty()) {
3775     Node* m   = stk.node();
3776     uint  idx = stk.index();
3777     if (idx < m->outcnt()) {
3778       stk.set_index(idx + 1);
3779       Node* n = m->raw_out(idx);
3780       if (n->is_CFG() && !visited.test_set(n->_idx)) {
3781         stk.push(n, 0);
3782       }
3783     } else {
3784       rpo_list.push(m);
3785       stk.pop();
3786     }
3787   }
3788 }
3789 #endif
3790 
3791 
3792 //=============================================================================
3793 //------------------------------LoopTreeIterator-----------------------------------
3794 
3795 // Advance to next loop tree using a preorder, left-to-right traversal.
3796 void LoopTreeIterator::next() {
3797   assert(!done(), "must not be done.");
3798   if (_curnt->_child != NULL) {
3799     _curnt = _curnt->_child;
3800   } else if (_curnt->_next != NULL) {
3801     _curnt = _curnt->_next;
3802   } else {
3803     while (_curnt != _root && _curnt->_next == NULL) {
3804       _curnt = _curnt->_parent;
3805     }
3806     if (_curnt == _root) {
3807       _curnt = NULL;
3808       assert(done(), "must be done.");
3809     } else {
3810       assert(_curnt->_next != NULL, "must be more to do");
3811       _curnt = _curnt->_next;
3812     }
3813   }
3814 }