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