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