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