1 /*
   2  * Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "compiler/compileLog.hpp"
  27 #include "memory/allocation.inline.hpp"
  28 #include "opto/addnode.hpp"
  29 #include "opto/callnode.hpp"
  30 #include "opto/castnode.hpp"
  31 #include "opto/connode.hpp"
  32 #include "opto/convertnode.hpp"
  33 #include "opto/divnode.hpp"
  34 #include "opto/loopnode.hpp"
  35 #include "opto/mulnode.hpp"
  36 #include "opto/movenode.hpp"
  37 #include "opto/opaquenode.hpp"
  38 #include "opto/rootnode.hpp"
  39 #include "opto/runtime.hpp"
  40 #include "opto/subnode.hpp"
  41 #include "opto/superword.hpp"
  42 #include "opto/vectornode.hpp"
  43 
  44 //------------------------------is_loop_exit-----------------------------------
  45 // Given an IfNode, return the loop-exiting projection or NULL if both
  46 // arms remain in the loop.
  47 Node *IdealLoopTree::is_loop_exit(Node *iff) const {
  48   if( iff->outcnt() != 2 ) return NULL; // Ignore partially dead tests
  49   PhaseIdealLoop *phase = _phase;
  50   // Test is an IfNode, has 2 projections.  If BOTH are in the loop
  51   // we need loop unswitching instead of peeling.
  52   if( !is_member(phase->get_loop( iff->raw_out(0) )) )
  53     return iff->raw_out(0);
  54   if( !is_member(phase->get_loop( iff->raw_out(1) )) )
  55     return iff->raw_out(1);
  56   return NULL;
  57 }
  58 
  59 
  60 //=============================================================================
  61 
  62 
  63 //------------------------------record_for_igvn----------------------------
  64 // Put loop body on igvn work list
  65 void IdealLoopTree::record_for_igvn() {
  66   for( uint i = 0; i < _body.size(); i++ ) {
  67     Node *n = _body.at(i);
  68     _phase->_igvn._worklist.push(n);
  69   }
  70   // put body of outer strip mined loop on igvn work list as well
  71   if (_head->is_CountedLoop() && _head->as_Loop()->is_strip_mined()) {
  72     CountedLoopNode* l = _head->as_CountedLoop();
  73     _phase->_igvn._worklist.push(l->outer_loop());
  74     _phase->_igvn._worklist.push(l->outer_loop_tail());
  75     _phase->_igvn._worklist.push(l->outer_loop_end());
  76     _phase->_igvn._worklist.push(l->outer_safepoint());
  77     Node* cle_out = _head->as_CountedLoop()->loopexit()->proj_out(false);
  78     _phase->_igvn._worklist.push(cle_out);
  79   }
  80 }
  81 
  82 //------------------------------compute_exact_trip_count-----------------------
  83 // Compute loop trip count if possible. Do not recalculate trip count for
  84 // split loops (pre-main-post) which have their limits and inits behind Opaque node.
  85 void IdealLoopTree::compute_trip_count(PhaseIdealLoop* phase) {
  86   if (!_head->as_Loop()->is_valid_counted_loop()) {
  87     return;
  88   }
  89   CountedLoopNode* cl = _head->as_CountedLoop();
  90   // Trip count may become nonexact for iteration split loops since
  91   // RCE modifies limits. Note, _trip_count value is not reset since
  92   // it is used to limit unrolling of main loop.
  93   cl->set_nonexact_trip_count();
  94 
  95   // Loop's test should be part of loop.
  96   if (!phase->is_member(this, phase->get_ctrl(cl->loopexit()->in(CountedLoopEndNode::TestValue))))
  97     return; // Infinite loop
  98 
  99 #ifdef ASSERT
 100   BoolTest::mask bt = cl->loopexit()->test_trip();
 101   assert(bt == BoolTest::lt || bt == BoolTest::gt ||
 102          bt == BoolTest::ne, "canonical test is expected");
 103 #endif
 104 
 105   Node* init_n = cl->init_trip();
 106   Node* limit_n = cl->limit();
 107   if (init_n != NULL && limit_n != NULL) {
 108     // Use longs to avoid integer overflow.
 109     int stride_con = cl->stride_con();
 110     jlong init_con = phase->_igvn.type(init_n)->is_int()->_lo;
 111     jlong limit_con = phase->_igvn.type(limit_n)->is_int()->_hi;
 112     int stride_m   = stride_con - (stride_con > 0 ? 1 : -1);
 113     jlong trip_count = (limit_con - init_con + stride_m)/stride_con;
 114     if (trip_count > 0 && (julong)trip_count < (julong)max_juint) {
 115       if (init_n->is_Con() && limit_n->is_Con()) {
 116         // Set exact trip count.
 117         cl->set_exact_trip_count((uint)trip_count);
 118       } else if (cl->unrolled_count() == 1) {
 119         // Set maximum trip count before unrolling.
 120         cl->set_trip_count((uint)trip_count);
 121       }
 122     }
 123   }
 124 }
 125 
 126 //------------------------------compute_profile_trip_cnt----------------------------
 127 // Compute loop trip count from profile data as
 128 //    (backedge_count + loop_exit_count) / loop_exit_count
 129 void IdealLoopTree::compute_profile_trip_cnt( PhaseIdealLoop *phase ) {
 130   if (!_head->is_CountedLoop()) {
 131     return;
 132   }
 133   CountedLoopNode* head = _head->as_CountedLoop();
 134   if (head->profile_trip_cnt() != COUNT_UNKNOWN) {
 135     return; // Already computed
 136   }
 137   float trip_cnt = (float)max_jint; // default is big
 138 
 139   Node* back = head->in(LoopNode::LoopBackControl);
 140   while (back != head) {
 141     if ((back->Opcode() == Op_IfTrue || back->Opcode() == Op_IfFalse) &&
 142         back->in(0) &&
 143         back->in(0)->is_If() &&
 144         back->in(0)->as_If()->_fcnt != COUNT_UNKNOWN &&
 145         back->in(0)->as_If()->_prob != PROB_UNKNOWN) {
 146       break;
 147     }
 148     back = phase->idom(back);
 149   }
 150   if (back != head) {
 151     assert((back->Opcode() == Op_IfTrue || back->Opcode() == Op_IfFalse) &&
 152            back->in(0), "if-projection exists");
 153     IfNode* back_if = back->in(0)->as_If();
 154     float loop_back_cnt = back_if->_fcnt * back_if->_prob;
 155 
 156     // Now compute a loop exit count
 157     float loop_exit_cnt = 0.0f;
 158     for( uint i = 0; i < _body.size(); i++ ) {
 159       Node *n = _body[i];
 160       if( n->is_If() ) {
 161         IfNode *iff = n->as_If();
 162         if( iff->_fcnt != COUNT_UNKNOWN && iff->_prob != PROB_UNKNOWN ) {
 163           Node *exit = is_loop_exit(iff);
 164           if( exit ) {
 165             float exit_prob = iff->_prob;
 166             if (exit->Opcode() == Op_IfFalse) exit_prob = 1.0 - exit_prob;
 167             if (exit_prob > PROB_MIN) {
 168               float exit_cnt = iff->_fcnt * exit_prob;
 169               loop_exit_cnt += exit_cnt;
 170             }
 171           }
 172         }
 173       }
 174     }
 175     if (loop_exit_cnt > 0.0f) {
 176       trip_cnt = (loop_back_cnt + loop_exit_cnt) / loop_exit_cnt;
 177     } else {
 178       // No exit count so use
 179       trip_cnt = loop_back_cnt;
 180     }
 181   }
 182 #ifndef PRODUCT
 183   if (TraceProfileTripCount) {
 184     tty->print_cr("compute_profile_trip_cnt  lp: %d cnt: %f\n", head->_idx, trip_cnt);
 185   }
 186 #endif
 187   head->set_profile_trip_cnt(trip_cnt);
 188 }
 189 
 190 //---------------------is_invariant_addition-----------------------------
 191 // Return nonzero index of invariant operand for an Add or Sub
 192 // of (nonconstant) invariant and variant values. Helper for reassociate_invariants.
 193 int IdealLoopTree::is_invariant_addition(Node* n, PhaseIdealLoop *phase) {
 194   int op = n->Opcode();
 195   if (op == Op_AddI || op == Op_SubI) {
 196     bool in1_invar = this->is_invariant(n->in(1));
 197     bool in2_invar = this->is_invariant(n->in(2));
 198     if (in1_invar && !in2_invar) return 1;
 199     if (!in1_invar && in2_invar) return 2;
 200   }
 201   return 0;
 202 }
 203 
 204 //---------------------reassociate_add_sub-----------------------------
 205 // Reassociate invariant add and subtract expressions:
 206 //
 207 // inv1 + (x + inv2)  =>  ( inv1 + inv2) + x
 208 // (x + inv2) + inv1  =>  ( inv1 + inv2) + x
 209 // inv1 + (x - inv2)  =>  ( inv1 - inv2) + x
 210 // inv1 - (inv2 - x)  =>  ( inv1 - inv2) + x
 211 // (x + inv2) - inv1  =>  (-inv1 + inv2) + x
 212 // (x - inv2) + inv1  =>  ( inv1 - inv2) + x
 213 // (x - inv2) - inv1  =>  (-inv1 - inv2) + x
 214 // inv1 + (inv2 - x)  =>  ( inv1 + inv2) - x
 215 // inv1 - (x - inv2)  =>  ( inv1 + inv2) - x
 216 // (inv2 - x) + inv1  =>  ( inv1 + inv2) - x
 217 // (inv2 - x) - inv1  =>  (-inv1 + inv2) - x
 218 // inv1 - (x + inv2)  =>  ( inv1 - inv2) - x
 219 //
 220 Node* IdealLoopTree::reassociate_add_sub(Node* n1, PhaseIdealLoop *phase) {
 221   if ((!n1->is_Add() && !n1->is_Sub()) || n1->outcnt() == 0) return NULL;
 222   if (is_invariant(n1)) return NULL;
 223   int inv1_idx = is_invariant_addition(n1, phase);
 224   if (!inv1_idx) return NULL;
 225   // Don't mess with add of constant (igvn moves them to expression tree root.)
 226   if (n1->is_Add() && n1->in(2)->is_Con()) return NULL;
 227   Node* inv1 = n1->in(inv1_idx);
 228   Node* n2 = n1->in(3 - inv1_idx);
 229   int inv2_idx = is_invariant_addition(n2, phase);
 230   if (!inv2_idx) return NULL;
 231   Node* x    = n2->in(3 - inv2_idx);
 232   Node* inv2 = n2->in(inv2_idx);
 233 
 234   bool neg_x    = n2->is_Sub() && inv2_idx == 1;
 235   bool neg_inv2 = n2->is_Sub() && inv2_idx == 2;
 236   bool neg_inv1 = n1->is_Sub() && inv1_idx == 2;
 237   if (n1->is_Sub() && inv1_idx == 1) {
 238     neg_x    = !neg_x;
 239     neg_inv2 = !neg_inv2;
 240   }
 241   Node* inv1_c = phase->get_ctrl(inv1);
 242   Node* inv2_c = phase->get_ctrl(inv2);
 243   Node* n_inv1;
 244   if (neg_inv1) {
 245     Node *zero = phase->_igvn.intcon(0);
 246     phase->set_ctrl(zero, phase->C->root());
 247     n_inv1 = new SubINode(zero, inv1);
 248     phase->register_new_node(n_inv1, inv1_c);
 249   } else {
 250     n_inv1 = inv1;
 251   }
 252   Node* inv;
 253   if (neg_inv2) {
 254     inv = new SubINode(n_inv1, inv2);
 255   } else {
 256     inv = new AddINode(n_inv1, inv2);
 257   }
 258   phase->register_new_node(inv, phase->get_early_ctrl(inv));
 259 
 260   Node* addx;
 261   if (neg_x) {
 262     addx = new SubINode(inv, x);
 263   } else {
 264     addx = new AddINode(x, inv);
 265   }
 266   phase->register_new_node(addx, phase->get_ctrl(x));
 267   phase->_igvn.replace_node(n1, addx);
 268   assert(phase->get_loop(phase->get_ctrl(n1)) == this, "");
 269   _body.yank(n1);
 270   return addx;
 271 }
 272 
 273 //---------------------reassociate_invariants-----------------------------
 274 // Reassociate invariant expressions:
 275 void IdealLoopTree::reassociate_invariants(PhaseIdealLoop *phase) {
 276   for (int i = _body.size() - 1; i >= 0; i--) {
 277     Node *n = _body.at(i);
 278     for (int j = 0; j < 5; j++) {
 279       Node* nn = reassociate_add_sub(n, phase);
 280       if (nn == NULL) break;
 281       n = nn; // again
 282     };
 283   }
 284 }
 285 
 286 //------------------------------policy_peeling---------------------------------
 287 // Return TRUE or FALSE if the loop should be peeled or not.  Peel if we can
 288 // make some loop-invariant test (usually a null-check) happen before the loop.
 289 bool IdealLoopTree::policy_peeling( PhaseIdealLoop *phase ) const {
 290   Node *test = ((IdealLoopTree*)this)->tail();
 291   int  body_size = ((IdealLoopTree*)this)->_body.size();
 292   // Peeling does loop cloning which can result in O(N^2) node construction
 293   if( body_size > 255 /* Prevent overflow for large body_size */
 294       || (body_size * body_size + phase->C->live_nodes()) > phase->C->max_node_limit() ) {
 295     return false;           // too large to safely clone
 296   }
 297 
 298   // check for vectorized loops, any peeling done was already applied
 299   if (_head->is_CountedLoop() && _head->as_CountedLoop()->do_unroll_only()) return false;
 300 
 301   while( test != _head ) {      // Scan till run off top of loop
 302     if( test->is_If() ) {       // Test?
 303       Node *ctrl = phase->get_ctrl(test->in(1));
 304       if (ctrl->is_top())
 305         return false;           // Found dead test on live IF?  No peeling!
 306       // Standard IF only has one input value to check for loop invariance
 307       assert(test->Opcode() == Op_If || test->Opcode() == Op_CountedLoopEnd || test->Opcode() == Op_RangeCheck, "Check this code when new subtype is added");
 308       // Condition is not a member of this loop?
 309       if( !is_member(phase->get_loop(ctrl)) &&
 310           is_loop_exit(test) )
 311         return true;            // Found reason to peel!
 312     }
 313     // Walk up dominators to loop _head looking for test which is
 314     // executed on every path thru loop.
 315     test = phase->idom(test);
 316   }
 317   return false;
 318 }
 319 
 320 //------------------------------peeled_dom_test_elim---------------------------
 321 // If we got the effect of peeling, either by actually peeling or by making
 322 // a pre-loop which must execute at least once, we can remove all
 323 // loop-invariant dominated tests in the main body.
 324 void PhaseIdealLoop::peeled_dom_test_elim( IdealLoopTree *loop, Node_List &old_new ) {
 325   bool progress = true;
 326   while( progress ) {
 327     progress = false;           // Reset for next iteration
 328     Node *prev = loop->_head->in(LoopNode::LoopBackControl);//loop->tail();
 329     Node *test = prev->in(0);
 330     while( test != loop->_head ) { // Scan till run off top of loop
 331 
 332       int p_op = prev->Opcode();
 333       if( (p_op == Op_IfFalse || p_op == Op_IfTrue) &&
 334           test->is_If() &&      // Test?
 335           !test->in(1)->is_Con() && // And not already obvious?
 336           // Condition is not a member of this loop?
 337           !loop->is_member(get_loop(get_ctrl(test->in(1))))){
 338         // Walk loop body looking for instances of this test
 339         for( uint i = 0; i < loop->_body.size(); i++ ) {
 340           Node *n = loop->_body.at(i);
 341           if( n->is_If() && n->in(1) == test->in(1) /*&& n != loop->tail()->in(0)*/ ) {
 342             // IfNode was dominated by version in peeled loop body
 343             progress = true;
 344             dominated_by( old_new[prev->_idx], n );
 345           }
 346         }
 347       }
 348       prev = test;
 349       test = idom(test);
 350     } // End of scan tests in loop
 351 
 352   } // End of while( progress )
 353 }
 354 
 355 //------------------------------do_peeling-------------------------------------
 356 // Peel the first iteration of the given loop.
 357 // Step 1: Clone the loop body.  The clone becomes the peeled iteration.
 358 //         The pre-loop illegally has 2 control users (old & new loops).
 359 // Step 2: Make the old-loop fall-in edges point to the peeled iteration.
 360 //         Do this by making the old-loop fall-in edges act as if they came
 361 //         around the loopback from the prior iteration (follow the old-loop
 362 //         backedges) and then map to the new peeled iteration.  This leaves
 363 //         the pre-loop with only 1 user (the new peeled iteration), but the
 364 //         peeled-loop backedge has 2 users.
 365 // Step 3: Cut the backedge on the clone (so its not a loop) and remove the
 366 //         extra backedge user.
 367 //
 368 //                   orig
 369 //
 370 //                  stmt1
 371 //                    |
 372 //                    v
 373 //              loop predicate
 374 //                    |
 375 //                    v
 376 //                   loop<----+
 377 //                     |      |
 378 //                   stmt2    |
 379 //                     |      |
 380 //                     v      |
 381 //                    if      ^
 382 //                   / \      |
 383 //                  /   \     |
 384 //                 v     v    |
 385 //               false true   |
 386 //               /       \    |
 387 //              /         ----+
 388 //             |
 389 //             v
 390 //           exit
 391 //
 392 //
 393 //            after clone loop
 394 //
 395 //                   stmt1
 396 //                     |
 397 //                     v
 398 //               loop predicate
 399 //                 /       \
 400 //        clone   /         \   orig
 401 //               /           \
 402 //              /             \
 403 //             v               v
 404 //   +---->loop clone          loop<----+
 405 //   |      |                    |      |
 406 //   |    stmt2 clone          stmt2    |
 407 //   |      |                    |      |
 408 //   |      v                    v      |
 409 //   ^      if clone            If      ^
 410 //   |      / \                / \      |
 411 //   |     /   \              /   \     |
 412 //   |    v     v            v     v    |
 413 //   |    true  false      false true   |
 414 //   |    /         \      /       \    |
 415 //   +----           \    /         ----+
 416 //                    \  /
 417 //                    1v v2
 418 //                  region
 419 //                     |
 420 //                     v
 421 //                   exit
 422 //
 423 //
 424 //         after peel and predicate move
 425 //
 426 //                   stmt1
 427 //                    /
 428 //                   /
 429 //        clone     /            orig
 430 //                 /
 431 //                /              +----------+
 432 //               /               |          |
 433 //              /          loop predicate   |
 434 //             /                 |          |
 435 //            v                  v          |
 436 //   TOP-->loop clone          loop<----+   |
 437 //          |                    |      |   |
 438 //        stmt2 clone          stmt2    |   |
 439 //          |                    |      |   ^
 440 //          v                    v      |   |
 441 //          if clone            If      ^   |
 442 //          / \                / \      |   |
 443 //         /   \              /   \     |   |
 444 //        v     v            v     v    |   |
 445 //      true   false      false  true   |   |
 446 //        |         \      /       \    |   |
 447 //        |          \    /         ----+   ^
 448 //        |           \  /                  |
 449 //        |           1v v2                 |
 450 //        v         region                  |
 451 //        |            |                    |
 452 //        |            v                    |
 453 //        |          exit                   |
 454 //        |                                 |
 455 //        +--------------->-----------------+
 456 //
 457 //
 458 //              final graph
 459 //
 460 //                  stmt1
 461 //                    |
 462 //                    v
 463 //                  stmt2 clone
 464 //                    |
 465 //                    v
 466 //                   if clone
 467 //                  / |
 468 //                 /  |
 469 //                v   v
 470 //            false  true
 471 //             |      |
 472 //             |      v
 473 //             | loop predicate
 474 //             |      |
 475 //             |      v
 476 //             |     loop<----+
 477 //             |      |       |
 478 //             |    stmt2     |
 479 //             |      |       |
 480 //             |      v       |
 481 //             v      if      ^
 482 //             |     /  \     |
 483 //             |    /    \    |
 484 //             |   v     v    |
 485 //             | false  true  |
 486 //             |  |        \  |
 487 //             v  v         --+
 488 //            region
 489 //              |
 490 //              v
 491 //             exit
 492 //
 493 void PhaseIdealLoop::do_peeling( IdealLoopTree *loop, Node_List &old_new ) {
 494 
 495   C->set_major_progress();
 496   // Peeling a 'main' loop in a pre/main/post situation obfuscates the
 497   // 'pre' loop from the main and the 'pre' can no longer have its
 498   // iterations adjusted.  Therefore, we need to declare this loop as
 499   // no longer a 'main' loop; it will need new pre and post loops before
 500   // we can do further RCE.
 501 #ifndef PRODUCT
 502   if (TraceLoopOpts) {
 503     tty->print("Peel         ");
 504     loop->dump_head();
 505   }
 506 #endif
 507   LoopNode* head = loop->_head->as_Loop();
 508   bool counted_loop = head->is_CountedLoop();
 509   if (counted_loop) {
 510     CountedLoopNode *cl = head->as_CountedLoop();
 511     assert(cl->trip_count() > 0, "peeling a fully unrolled loop");
 512     cl->set_trip_count(cl->trip_count() - 1);
 513     if (cl->is_main_loop()) {
 514       cl->set_normal_loop();
 515 #ifndef PRODUCT
 516       if (PrintOpto && VerifyLoopOptimizations) {
 517         tty->print("Peeling a 'main' loop; resetting to 'normal' ");
 518         loop->dump_head();
 519       }
 520 #endif
 521     }
 522   }
 523   Node* entry = head->in(LoopNode::EntryControl);
 524 
 525   // Step 1: Clone the loop body.  The clone becomes the peeled iteration.
 526   //         The pre-loop illegally has 2 control users (old & new loops).
 527   clone_loop(loop, old_new, dom_depth(head->skip_strip_mined()), ControlAroundStripMined);
 528 
 529   // Step 2: Make the old-loop fall-in edges point to the peeled iteration.
 530   //         Do this by making the old-loop fall-in edges act as if they came
 531   //         around the loopback from the prior iteration (follow the old-loop
 532   //         backedges) and then map to the new peeled iteration.  This leaves
 533   //         the pre-loop with only 1 user (the new peeled iteration), but the
 534   //         peeled-loop backedge has 2 users.
 535   Node* new_entry = old_new[head->in(LoopNode::LoopBackControl)->_idx];
 536   _igvn.hash_delete(head->skip_strip_mined());
 537   head->skip_strip_mined()->set_req(LoopNode::EntryControl, new_entry);
 538   for (DUIterator_Fast jmax, j = head->fast_outs(jmax); j < jmax; j++) {
 539     Node* old = head->fast_out(j);
 540     if (old->in(0) == loop->_head && old->req() == 3 && old->is_Phi()) {
 541       Node* new_exit_value = old_new[old->in(LoopNode::LoopBackControl)->_idx];
 542       if (!new_exit_value )     // Backedge value is ALSO loop invariant?
 543         // Then loop body backedge value remains the same.
 544         new_exit_value = old->in(LoopNode::LoopBackControl);
 545       _igvn.hash_delete(old);
 546       old->set_req(LoopNode::EntryControl, new_exit_value);
 547     }
 548   }
 549 
 550 
 551   // Step 3: Cut the backedge on the clone (so its not a loop) and remove the
 552   //         extra backedge user.
 553   Node* new_head = old_new[head->_idx];
 554   _igvn.hash_delete(new_head);
 555   new_head->set_req(LoopNode::LoopBackControl, C->top());
 556   for (DUIterator_Fast j2max, j2 = new_head->fast_outs(j2max); j2 < j2max; j2++) {
 557     Node* use = new_head->fast_out(j2);
 558     if (use->in(0) == new_head && use->req() == 3 && use->is_Phi()) {
 559       _igvn.hash_delete(use);
 560       use->set_req(LoopNode::LoopBackControl, C->top());
 561     }
 562   }
 563 
 564 
 565   // Step 4: Correct dom-depth info.  Set to loop-head depth.
 566   int dd = dom_depth(head);
 567   set_idom(head, head->in(1), dd);
 568   for (uint j3 = 0; j3 < loop->_body.size(); j3++) {
 569     Node *old = loop->_body.at(j3);
 570     Node *nnn = old_new[old->_idx];
 571     if (!has_ctrl(nnn))
 572       set_idom(nnn, idom(nnn), dd-1);
 573   }
 574 
 575   // Now force out all loop-invariant dominating tests.  The optimizer
 576   // finds some, but we _know_ they are all useless.
 577   peeled_dom_test_elim(loop,old_new);
 578 
 579   loop->record_for_igvn();
 580 }
 581 
 582 #define EMPTY_LOOP_SIZE 7 // number of nodes in an empty loop
 583 
 584 //------------------------------policy_maximally_unroll------------------------
 585 // Calculate exact loop trip count and return true if loop can be maximally
 586 // unrolled.
 587 bool IdealLoopTree::policy_maximally_unroll( PhaseIdealLoop *phase ) const {
 588   CountedLoopNode *cl = _head->as_CountedLoop();
 589   assert(cl->is_normal_loop(), "");
 590   if (!cl->is_valid_counted_loop())
 591     return false; // Malformed counted loop
 592 
 593   if (!cl->has_exact_trip_count()) {
 594     // Trip count is not exact.
 595     return false;
 596   }
 597 
 598   uint trip_count = cl->trip_count();
 599   // Note, max_juint is used to indicate unknown trip count.
 600   assert(trip_count > 1, "one iteration loop should be optimized out already");
 601   assert(trip_count < max_juint, "exact trip_count should be less than max_uint.");
 602 
 603   // Real policy: if we maximally unroll, does it get too big?
 604   // Allow the unrolled mess to get larger than standard loop
 605   // size.  After all, it will no longer be a loop.
 606   uint body_size    = _body.size();
 607   uint unroll_limit = (uint)LoopUnrollLimit * 4;
 608   assert( (intx)unroll_limit == LoopUnrollLimit * 4, "LoopUnrollLimit must fit in 32bits");
 609   if (trip_count > unroll_limit || body_size > unroll_limit) {
 610     return false;
 611   }
 612 
 613   // Fully unroll a loop with few iterations regardless next
 614   // conditions since following loop optimizations will split
 615   // such loop anyway (pre-main-post).
 616   if (trip_count <= 3)
 617     return true;
 618 
 619   // Take into account that after unroll conjoined heads and tails will fold,
 620   // otherwise policy_unroll() may allow more unrolling than max unrolling.
 621   uint new_body_size = EMPTY_LOOP_SIZE + (body_size - EMPTY_LOOP_SIZE) * trip_count;
 622   uint tst_body_size = (new_body_size - EMPTY_LOOP_SIZE) / trip_count + EMPTY_LOOP_SIZE;
 623   if (body_size != tst_body_size) // Check for int overflow
 624     return false;
 625   if (new_body_size > unroll_limit ||
 626       // Unrolling can result in a large amount of node construction
 627       new_body_size >= phase->C->max_node_limit() - phase->C->live_nodes()) {
 628     return false;
 629   }
 630 
 631   // Do not unroll a loop with String intrinsics code.
 632   // String intrinsics are large and have loops.
 633   for (uint k = 0; k < _body.size(); k++) {
 634     Node* n = _body.at(k);
 635     switch (n->Opcode()) {
 636       case Op_StrComp:
 637       case Op_StrEquals:
 638       case Op_StrIndexOf:
 639       case Op_StrIndexOfChar:
 640       case Op_EncodeISOArray:
 641       case Op_AryEq:
 642       case Op_HasNegatives: {
 643         return false;
 644       }
 645 #if INCLUDE_RTM_OPT
 646       case Op_FastLock:
 647       case Op_FastUnlock: {
 648         // Don't unroll RTM locking code because it is large.
 649         if (UseRTMLocking) {
 650           return false;
 651         }
 652       }
 653 #endif
 654     } // switch
 655   }
 656 
 657   return true; // Do maximally unroll
 658 }
 659 
 660 
 661 //------------------------------policy_unroll----------------------------------
 662 // Return TRUE or FALSE if the loop should be unrolled or not.  Unroll if
 663 // the loop is a CountedLoop and the body is small enough.
 664 bool IdealLoopTree::policy_unroll(PhaseIdealLoop *phase) {
 665 
 666   CountedLoopNode *cl = _head->as_CountedLoop();
 667   assert(cl->is_normal_loop() || cl->is_main_loop(), "");
 668 
 669   if (!cl->is_valid_counted_loop())
 670     return false; // Malformed counted loop
 671 
 672   // Protect against over-unrolling.
 673   // After split at least one iteration will be executed in pre-loop.
 674   if (cl->trip_count() <= (uint)(cl->is_normal_loop() ? 2 : 1)) return false;
 675 
 676   _local_loop_unroll_limit = LoopUnrollLimit;
 677   _local_loop_unroll_factor = 4;
 678   int future_unroll_ct = cl->unrolled_count() * 2;
 679   if (!cl->is_vectorized_loop()) {
 680     if (future_unroll_ct > LoopMaxUnroll) return false;
 681   } else {
 682     // obey user constraints on vector mapped loops with additional unrolling applied
 683     int unroll_constraint = (cl->slp_max_unroll()) ? cl->slp_max_unroll() : 1;
 684     if ((future_unroll_ct / unroll_constraint) > LoopMaxUnroll) return false;
 685   }
 686 
 687   // Check for initial stride being a small enough constant
 688   if (abs(cl->stride_con()) > (1<<2)*future_unroll_ct) return false;
 689 
 690   // Don't unroll if the next round of unrolling would push us
 691   // over the expected trip count of the loop.  One is subtracted
 692   // from the expected trip count because the pre-loop normally
 693   // executes 1 iteration.
 694   if (UnrollLimitForProfileCheck > 0 &&
 695       cl->profile_trip_cnt() != COUNT_UNKNOWN &&
 696       future_unroll_ct        > UnrollLimitForProfileCheck &&
 697       (float)future_unroll_ct > cl->profile_trip_cnt() - 1.0) {
 698     return false;
 699   }
 700 
 701   // When unroll count is greater than LoopUnrollMin, don't unroll if:
 702   //   the residual iterations are more than 10% of the trip count
 703   //   and rounds of "unroll,optimize" are not making significant progress
 704   //   Progress defined as current size less than 20% larger than previous size.
 705   if (UseSuperWord && cl->node_count_before_unroll() > 0 &&
 706       future_unroll_ct > LoopUnrollMin &&
 707       (future_unroll_ct - 1) * (100 / LoopPercentProfileLimit) > cl->profile_trip_cnt() &&
 708       1.2 * cl->node_count_before_unroll() < (double)_body.size()) {
 709     return false;
 710   }
 711 
 712   Node *init_n = cl->init_trip();
 713   Node *limit_n = cl->limit();
 714   int stride_con = cl->stride_con();
 715   // Non-constant bounds.
 716   // Protect against over-unrolling when init or/and limit are not constant
 717   // (so that trip_count's init value is maxint) but iv range is known.
 718   if (init_n   == NULL || !init_n->is_Con()  ||
 719       limit_n  == NULL || !limit_n->is_Con()) {
 720     Node* phi = cl->phi();
 721     if (phi != NULL) {
 722       assert(phi->is_Phi() && phi->in(0) == _head, "Counted loop should have iv phi.");
 723       const TypeInt* iv_type = phase->_igvn.type(phi)->is_int();
 724       int next_stride = stride_con * 2; // stride after this unroll
 725       if (next_stride > 0) {
 726         if (iv_type->_lo + next_stride <= iv_type->_lo || // overflow
 727             iv_type->_lo + next_stride >  iv_type->_hi) {
 728           return false;  // over-unrolling
 729         }
 730       } else if (next_stride < 0) {
 731         if (iv_type->_hi + next_stride >= iv_type->_hi || // overflow
 732             iv_type->_hi + next_stride <  iv_type->_lo) {
 733           return false;  // over-unrolling
 734         }
 735       }
 736     }
 737   }
 738 
 739   // After unroll limit will be adjusted: new_limit = limit-stride.
 740   // Bailout if adjustment overflow.
 741   const TypeInt* limit_type = phase->_igvn.type(limit_n)->is_int();
 742   if ((stride_con > 0 && ((limit_type->_hi - stride_con) >= limit_type->_hi)) ||
 743       (stride_con < 0 && ((limit_type->_lo - stride_con) <= limit_type->_lo)))
 744     return false;  // overflow
 745 
 746   // Adjust body_size to determine if we unroll or not
 747   uint body_size = _body.size();
 748   // Key test to unroll loop in CRC32 java code
 749   int xors_in_loop = 0;
 750   // Also count ModL, DivL and MulL which expand mightly
 751   for (uint k = 0; k < _body.size(); k++) {
 752     Node* n = _body.at(k);
 753     switch (n->Opcode()) {
 754       case Op_XorI: xors_in_loop++; break; // CRC32 java code
 755       case Op_ModL: body_size += 30; break;
 756       case Op_DivL: body_size += 30; break;
 757       case Op_MulL: body_size += 10; break;
 758       case Op_StrComp:
 759       case Op_StrEquals:
 760       case Op_StrIndexOf:
 761       case Op_StrIndexOfChar:
 762       case Op_EncodeISOArray:
 763       case Op_AryEq:
 764       case Op_HasNegatives: {
 765         // Do not unroll a loop with String intrinsics code.
 766         // String intrinsics are large and have loops.
 767         return false;
 768       }
 769 #if INCLUDE_RTM_OPT
 770       case Op_FastLock:
 771       case Op_FastUnlock: {
 772         // Don't unroll RTM locking code because it is large.
 773         if (UseRTMLocking) {
 774           return false;
 775         }
 776       }
 777 #endif
 778     } // switch
 779   }
 780 
 781   if (UseSuperWord) {
 782     if (!cl->is_reduction_loop()) {
 783       phase->mark_reductions(this);
 784     }
 785 
 786     // Only attempt slp analysis when user controls do not prohibit it
 787     if (LoopMaxUnroll > _local_loop_unroll_factor) {
 788       // Once policy_slp_analysis succeeds, mark the loop with the
 789       // maximal unroll factor so that we minimize analysis passes
 790       if (future_unroll_ct >= _local_loop_unroll_factor) {
 791         policy_unroll_slp_analysis(cl, phase, future_unroll_ct);
 792       }
 793     }
 794   }
 795 
 796   int slp_max_unroll_factor = cl->slp_max_unroll();
 797   if ((LoopMaxUnroll < slp_max_unroll_factor) && FLAG_IS_DEFAULT(LoopMaxUnroll) && UseSubwordForMaxVector) {
 798     LoopMaxUnroll = slp_max_unroll_factor;
 799   }
 800   if (cl->has_passed_slp()) {
 801     if (slp_max_unroll_factor >= future_unroll_ct) return true;
 802     // Normal case: loop too big
 803     return false;
 804   }
 805 
 806   // Check for being too big
 807   if (body_size > (uint)_local_loop_unroll_limit) {
 808     if ((UseSubwordForMaxVector || xors_in_loop >= 4) && body_size < (uint)LoopUnrollLimit * 4) return true;
 809     // Normal case: loop too big
 810     return false;
 811   }
 812 
 813   if (cl->do_unroll_only()) {
 814     if (TraceSuperWordLoopUnrollAnalysis) {
 815       tty->print_cr("policy_unroll passed vector loop(vlen=%d,factor = %d)\n", slp_max_unroll_factor, future_unroll_ct);
 816     }
 817   }
 818 
 819   // Unroll once!  (Each trip will soon do double iterations)
 820   return true;
 821 }
 822 
 823 void IdealLoopTree::policy_unroll_slp_analysis(CountedLoopNode *cl, PhaseIdealLoop *phase, int future_unroll_ct) {
 824   // Enable this functionality target by target as needed
 825   if (SuperWordLoopUnrollAnalysis) {
 826     if (!cl->was_slp_analyzed()) {
 827       SuperWord sw(phase);
 828       sw.transform_loop(this, false);
 829 
 830       // If the loop is slp canonical analyze it
 831       if (sw.early_return() == false) {
 832         sw.unrolling_analysis(_local_loop_unroll_factor);
 833       }
 834     }
 835 
 836     if (cl->has_passed_slp()) {
 837       int slp_max_unroll_factor = cl->slp_max_unroll();
 838       if (slp_max_unroll_factor >= future_unroll_ct) {
 839         int new_limit = cl->node_count_before_unroll() * slp_max_unroll_factor;
 840         if (new_limit > LoopUnrollLimit) {
 841           if (TraceSuperWordLoopUnrollAnalysis) {
 842             tty->print_cr("slp analysis unroll=%d, default limit=%d\n", new_limit, _local_loop_unroll_limit);
 843           }
 844           _local_loop_unroll_limit = new_limit;
 845         }
 846       }
 847     }
 848   }
 849 }
 850 
 851 //------------------------------policy_align-----------------------------------
 852 // Return TRUE or FALSE if the loop should be cache-line aligned.  Gather the
 853 // expression that does the alignment.  Note that only one array base can be
 854 // aligned in a loop (unless the VM guarantees mutual alignment).  Note that
 855 // if we vectorize short memory ops into longer memory ops, we may want to
 856 // increase alignment.
 857 bool IdealLoopTree::policy_align( PhaseIdealLoop *phase ) const {
 858   return false;
 859 }
 860 
 861 //------------------------------policy_range_check-----------------------------
 862 // Return TRUE or FALSE if the loop should be range-check-eliminated.
 863 // Actually we do iteration-splitting, a more powerful form of RCE.
 864 bool IdealLoopTree::policy_range_check( PhaseIdealLoop *phase ) const {
 865   if (!RangeCheckElimination) return false;
 866 
 867   CountedLoopNode *cl = _head->as_CountedLoop();
 868   // If we unrolled with no intention of doing RCE and we later
 869   // changed our minds, we got no pre-loop.  Either we need to
 870   // make a new pre-loop, or we gotta disallow RCE.
 871   if (cl->is_main_no_pre_loop()) return false; // Disallowed for now.
 872   Node *trip_counter = cl->phi();
 873 
 874   // check for vectorized loops, some opts are no longer needed
 875   if (cl->do_unroll_only()) return false;
 876 
 877   // Check loop body for tests of trip-counter plus loop-invariant vs
 878   // loop-invariant.
 879   for (uint i = 0; i < _body.size(); i++) {
 880     Node *iff = _body[i];
 881     if (iff->Opcode() == Op_If ||
 882         iff->Opcode() == Op_RangeCheck) { // Test?
 883 
 884       // Comparing trip+off vs limit
 885       Node *bol = iff->in(1);
 886       if (bol->req() != 2) continue; // dead constant test
 887       if (!bol->is_Bool()) {
 888         assert(bol->Opcode() == Op_Conv2B, "predicate check only");
 889         continue;
 890       }
 891       if (bol->as_Bool()->_test._test == BoolTest::ne)
 892         continue; // not RC
 893 
 894       Node *cmp = bol->in(1);
 895       Node *rc_exp = cmp->in(1);
 896       Node *limit = cmp->in(2);
 897 
 898       Node *limit_c = phase->get_ctrl(limit);
 899       if( limit_c == phase->C->top() )
 900         return false;           // Found dead test on live IF?  No RCE!
 901       if( is_member(phase->get_loop(limit_c) ) ) {
 902         // Compare might have operands swapped; commute them
 903         rc_exp = cmp->in(2);
 904         limit  = cmp->in(1);
 905         limit_c = phase->get_ctrl(limit);
 906         if( is_member(phase->get_loop(limit_c) ) )
 907           continue;             // Both inputs are loop varying; cannot RCE
 908       }
 909 
 910       if (!phase->is_scaled_iv_plus_offset(rc_exp, trip_counter, NULL, NULL)) {
 911         continue;
 912       }
 913       // Yeah!  Found a test like 'trip+off vs limit'
 914       // Test is an IfNode, has 2 projections.  If BOTH are in the loop
 915       // we need loop unswitching instead of iteration splitting.
 916       if( is_loop_exit(iff) )
 917         return true;            // Found reason to split iterations
 918     } // End of is IF
 919   }
 920 
 921   return false;
 922 }
 923 
 924 //------------------------------policy_peel_only-------------------------------
 925 // Return TRUE or FALSE if the loop should NEVER be RCE'd or aligned.  Useful
 926 // for unrolling loops with NO array accesses.
 927 bool IdealLoopTree::policy_peel_only( PhaseIdealLoop *phase ) const {
 928   // check for vectorized loops, any peeling done was already applied
 929   if (_head->is_CountedLoop() && _head->as_CountedLoop()->do_unroll_only()) return false;
 930 
 931   for( uint i = 0; i < _body.size(); i++ )
 932     if( _body[i]->is_Mem() )
 933       return false;
 934 
 935   // No memory accesses at all!
 936   return true;
 937 }
 938 
 939 //------------------------------clone_up_backedge_goo--------------------------
 940 // If Node n lives in the back_ctrl block and cannot float, we clone a private
 941 // version of n in preheader_ctrl block and return that, otherwise return n.
 942 Node *PhaseIdealLoop::clone_up_backedge_goo( Node *back_ctrl, Node *preheader_ctrl, Node *n, VectorSet &visited, Node_Stack &clones ) {
 943   if( get_ctrl(n) != back_ctrl ) return n;
 944 
 945   // Only visit once
 946   if (visited.test_set(n->_idx)) {
 947     Node *x = clones.find(n->_idx);
 948     if (x != NULL)
 949       return x;
 950     return n;
 951   }
 952 
 953   Node *x = NULL;               // If required, a clone of 'n'
 954   // Check for 'n' being pinned in the backedge.
 955   if( n->in(0) && n->in(0) == back_ctrl ) {
 956     assert(clones.find(n->_idx) == NULL, "dead loop");
 957     x = n->clone();             // Clone a copy of 'n' to preheader
 958     clones.push(x, n->_idx);
 959     x->set_req( 0, preheader_ctrl ); // Fix x's control input to preheader
 960   }
 961 
 962   // Recursive fixup any other input edges into x.
 963   // If there are no changes we can just return 'n', otherwise
 964   // we need to clone a private copy and change it.
 965   for( uint i = 1; i < n->req(); i++ ) {
 966     Node *g = clone_up_backedge_goo( back_ctrl, preheader_ctrl, n->in(i), visited, clones );
 967     if( g != n->in(i) ) {
 968       if( !x ) {
 969         assert(clones.find(n->_idx) == NULL, "dead loop");
 970         x = n->clone();
 971         clones.push(x, n->_idx);
 972       }
 973       x->set_req(i, g);
 974     }
 975   }
 976   if( x ) {                     // x can legally float to pre-header location
 977     register_new_node( x, preheader_ctrl );
 978     return x;
 979   } else {                      // raise n to cover LCA of uses
 980     set_ctrl( n, find_non_split_ctrl(back_ctrl->in(0)) );
 981   }
 982   return n;
 983 }
 984 
 985 bool PhaseIdealLoop::cast_incr_before_loop(Node* incr, Node* ctrl, Node* loop) {
 986   Node* castii = new CastIINode(incr, TypeInt::INT, true);
 987   castii->set_req(0, ctrl);
 988   register_new_node(castii, ctrl);
 989   for (DUIterator_Fast imax, i = incr->fast_outs(imax); i < imax; i++) {
 990     Node* n = incr->fast_out(i);
 991     if (n->is_Phi() && n->in(0) == loop) {
 992       int nrep = n->replace_edge(incr, castii);
 993       return true;
 994     }
 995   }
 996   return false;
 997 }
 998 
 999 //------------------------------insert_pre_post_loops--------------------------
1000 // Insert pre and post loops.  If peel_only is set, the pre-loop can not have
1001 // more iterations added.  It acts as a 'peel' only, no lower-bound RCE, no
1002 // alignment.  Useful to unroll loops that do no array accesses.
1003 void PhaseIdealLoop::insert_pre_post_loops( IdealLoopTree *loop, Node_List &old_new, bool peel_only ) {
1004 
1005 #ifndef PRODUCT
1006   if (TraceLoopOpts) {
1007     if (peel_only)
1008       tty->print("PeelMainPost ");
1009     else
1010       tty->print("PreMainPost  ");
1011     loop->dump_head();
1012   }
1013 #endif
1014   C->set_major_progress();
1015 
1016   // Find common pieces of the loop being guarded with pre & post loops
1017   CountedLoopNode *main_head = loop->_head->as_CountedLoop();
1018   assert( main_head->is_normal_loop(), "" );
1019   CountedLoopEndNode *main_end = main_head->loopexit();
1020   assert( main_end->outcnt() == 2, "1 true, 1 false path only" );
1021 
1022   Node *pre_header= main_head->in(LoopNode::EntryControl);
1023   Node *init      = main_head->init_trip();
1024   Node *incr      = main_end ->incr();
1025   Node *limit     = main_end ->limit();
1026   Node *stride    = main_end ->stride();
1027   Node *cmp       = main_end ->cmp_node();
1028   BoolTest::mask b_test = main_end->test_trip();
1029 
1030   // Need only 1 user of 'bol' because I will be hacking the loop bounds.
1031   Node *bol = main_end->in(CountedLoopEndNode::TestValue);
1032   if( bol->outcnt() != 1 ) {
1033     bol = bol->clone();
1034     register_new_node(bol,main_end->in(CountedLoopEndNode::TestControl));
1035     _igvn.replace_input_of(main_end, CountedLoopEndNode::TestValue, bol);
1036   }
1037   // Need only 1 user of 'cmp' because I will be hacking the loop bounds.
1038   if( cmp->outcnt() != 1 ) {
1039     cmp = cmp->clone();
1040     register_new_node(cmp,main_end->in(CountedLoopEndNode::TestControl));
1041     _igvn.replace_input_of(bol, 1, cmp);
1042   }
1043 
1044   // Add the post loop
1045   CountedLoopNode *post_head = NULL;
1046   Node *main_exit = insert_post_loop(loop, old_new, main_head, main_end, incr, limit, post_head);
1047 
1048   //------------------------------
1049   // Step B: Create Pre-Loop.
1050 
1051   // Step B1: Clone the loop body.  The clone becomes the pre-loop.  The main
1052   // loop pre-header illegally has 2 control users (old & new loops).
1053   LoopNode* outer_main_head = main_head;
1054   IdealLoopTree* outer_loop = loop;
1055   if (main_head->is_strip_mined()) {
1056     main_head->verify_strip_mined(1);
1057     outer_main_head = main_head->outer_loop();
1058     outer_loop = loop->_parent;
1059     assert(outer_loop->_head == outer_main_head, "broken loop tree");
1060   }
1061   uint dd_main_head = dom_depth(outer_main_head);
1062   clone_loop(loop, old_new, dd_main_head, ControlAroundStripMined);
1063   CountedLoopNode*    pre_head = old_new[main_head->_idx]->as_CountedLoop();
1064   CountedLoopEndNode* pre_end  = old_new[main_end ->_idx]->as_CountedLoopEnd();
1065   pre_head->set_pre_loop(main_head);
1066   Node *pre_incr = old_new[incr->_idx];
1067 
1068   // Reduce the pre-loop trip count.
1069   pre_end->_prob = PROB_FAIR;
1070 
1071   // Find the pre-loop normal exit.
1072   Node* pre_exit = pre_end->proj_out(false);
1073   assert( pre_exit->Opcode() == Op_IfFalse, "" );
1074   IfFalseNode *new_pre_exit = new IfFalseNode(pre_end);
1075   _igvn.register_new_node_with_optimizer( new_pre_exit );
1076   set_idom(new_pre_exit, pre_end, dd_main_head);
1077   set_loop(new_pre_exit, outer_loop->_parent);
1078 
1079   // Step B2: Build a zero-trip guard for the main-loop.  After leaving the
1080   // pre-loop, the main-loop may not execute at all.  Later in life this
1081   // zero-trip guard will become the minimum-trip guard when we unroll
1082   // the main-loop.
1083   Node *min_opaq = new Opaque1Node(C, limit);
1084   Node *min_cmp  = new CmpINode( pre_incr, min_opaq );
1085   Node *min_bol  = new BoolNode( min_cmp, b_test );
1086   register_new_node( min_opaq, new_pre_exit );
1087   register_new_node( min_cmp , new_pre_exit );
1088   register_new_node( min_bol , new_pre_exit );
1089 
1090   // Build the IfNode (assume the main-loop is executed always).
1091   IfNode *min_iff = new IfNode( new_pre_exit, min_bol, PROB_ALWAYS, COUNT_UNKNOWN );
1092   _igvn.register_new_node_with_optimizer( min_iff );
1093   set_idom(min_iff, new_pre_exit, dd_main_head);
1094   set_loop(min_iff, outer_loop->_parent);
1095 
1096   // Plug in the false-path, taken if we need to skip main-loop
1097   _igvn.hash_delete( pre_exit );
1098   pre_exit->set_req(0, min_iff);
1099   set_idom(pre_exit, min_iff, dd_main_head);
1100   set_idom(pre_exit->unique_ctrl_out(), min_iff, dd_main_head);
1101   // Make the true-path, must enter the main loop
1102   Node *min_taken = new IfTrueNode( min_iff );
1103   _igvn.register_new_node_with_optimizer( min_taken );
1104   set_idom(min_taken, min_iff, dd_main_head);
1105   set_loop(min_taken, outer_loop->_parent);
1106   // Plug in the true path
1107   _igvn.hash_delete(outer_main_head);
1108   outer_main_head->set_req(LoopNode::EntryControl, min_taken);
1109   set_idom(outer_main_head, min_taken, dd_main_head);
1110 
1111   Arena *a = Thread::current()->resource_area();
1112   VectorSet visited(a);
1113   Node_Stack clones(a, main_head->back_control()->outcnt());
1114   // Step B3: Make the fall-in values to the main-loop come from the
1115   // fall-out values of the pre-loop.
1116   for (DUIterator_Fast i2max, i2 = main_head->fast_outs(i2max); i2 < i2max; i2++) {
1117     Node* main_phi = main_head->fast_out(i2);
1118     if( main_phi->is_Phi() && main_phi->in(0) == main_head && main_phi->outcnt() > 0 ) {
1119       Node *pre_phi = old_new[main_phi->_idx];
1120       Node *fallpre  = clone_up_backedge_goo(pre_head->back_control(),
1121                                              main_head->skip_strip_mined()->in(LoopNode::EntryControl),
1122                                              pre_phi->in(LoopNode::LoopBackControl),
1123                                              visited, clones);
1124       _igvn.hash_delete(main_phi);
1125       main_phi->set_req( LoopNode::EntryControl, fallpre );
1126     }
1127   }
1128 
1129   // Nodes inside the loop may be control dependent on a predicate
1130   // that was moved before the preloop. If the back branch of the main
1131   // or post loops becomes dead, those nodes won't be dependent on the
1132   // test that guards that loop nest anymore which could lead to an
1133   // incorrect array access because it executes independently of the
1134   // test that was guarding the loop nest. We add a special CastII on
1135   // the if branch that enters the loop, between the input induction
1136   // variable value and the induction variable Phi to preserve correct
1137   // dependencies.
1138 
1139   // CastII for the main loop:
1140   bool inserted = cast_incr_before_loop( pre_incr, min_taken, main_head );
1141   assert(inserted, "no castII inserted");
1142 
1143   // Step B4: Shorten the pre-loop to run only 1 iteration (for now).
1144   // RCE and alignment may change this later.
1145   Node *cmp_end = pre_end->cmp_node();
1146   assert( cmp_end->in(2) == limit, "" );
1147   Node *pre_limit = new AddINode( init, stride );
1148 
1149   // Save the original loop limit in this Opaque1 node for
1150   // use by range check elimination.
1151   Node *pre_opaq  = new Opaque1Node(C, pre_limit, limit);
1152 
1153   register_new_node( pre_limit, pre_head->in(0) );
1154   register_new_node( pre_opaq , pre_head->in(0) );
1155 
1156   // Since no other users of pre-loop compare, I can hack limit directly
1157   assert( cmp_end->outcnt() == 1, "no other users" );
1158   _igvn.hash_delete(cmp_end);
1159   cmp_end->set_req(2, peel_only ? pre_limit : pre_opaq);
1160 
1161   // Special case for not-equal loop bounds:
1162   // Change pre loop test, main loop test, and the
1163   // main loop guard test to use lt or gt depending on stride
1164   // direction:
1165   // positive stride use <
1166   // negative stride use >
1167   //
1168   // not-equal test is kept for post loop to handle case
1169   // when init > limit when stride > 0 (and reverse).
1170 
1171   if (pre_end->in(CountedLoopEndNode::TestValue)->as_Bool()->_test._test == BoolTest::ne) {
1172 
1173     BoolTest::mask new_test = (main_end->stride_con() > 0) ? BoolTest::lt : BoolTest::gt;
1174     // Modify pre loop end condition
1175     Node* pre_bol = pre_end->in(CountedLoopEndNode::TestValue)->as_Bool();
1176     BoolNode* new_bol0 = new BoolNode(pre_bol->in(1), new_test);
1177     register_new_node( new_bol0, pre_head->in(0) );
1178     _igvn.replace_input_of(pre_end, CountedLoopEndNode::TestValue, new_bol0);
1179     // Modify main loop guard condition
1180     assert(min_iff->in(CountedLoopEndNode::TestValue) == min_bol, "guard okay");
1181     BoolNode* new_bol1 = new BoolNode(min_bol->in(1), new_test);
1182     register_new_node( new_bol1, new_pre_exit );
1183     _igvn.hash_delete(min_iff);
1184     min_iff->set_req(CountedLoopEndNode::TestValue, new_bol1);
1185     // Modify main loop end condition
1186     BoolNode* main_bol = main_end->in(CountedLoopEndNode::TestValue)->as_Bool();
1187     BoolNode* new_bol2 = new BoolNode(main_bol->in(1), new_test);
1188     register_new_node( new_bol2, main_end->in(CountedLoopEndNode::TestControl) );
1189     _igvn.replace_input_of(main_end, CountedLoopEndNode::TestValue, new_bol2);
1190   }
1191 
1192   // Flag main loop
1193   main_head->set_main_loop();
1194   if( peel_only ) main_head->set_main_no_pre_loop();
1195 
1196   // Subtract a trip count for the pre-loop.
1197   main_head->set_trip_count(main_head->trip_count() - 1);
1198 
1199   // It's difficult to be precise about the trip-counts
1200   // for the pre/post loops.  They are usually very short,
1201   // so guess that 4 trips is a reasonable value.
1202   post_head->set_profile_trip_cnt(4.0);
1203   pre_head->set_profile_trip_cnt(4.0);
1204 
1205   // Now force out all loop-invariant dominating tests.  The optimizer
1206   // finds some, but we _know_ they are all useless.
1207   peeled_dom_test_elim(loop,old_new);
1208   loop->record_for_igvn();
1209 }
1210 
1211 //------------------------------insert_vector_post_loop------------------------
1212 // Insert a copy of the atomic unrolled vectorized main loop as a post loop,
1213 // unroll_policy has already informed us that more unrolling is about to happen to
1214 // the main loop.  The resultant post loop will serve as a vectorized drain loop.
1215 void PhaseIdealLoop::insert_vector_post_loop(IdealLoopTree *loop, Node_List &old_new) {
1216   if (!loop->_head->is_CountedLoop()) return;
1217 
1218   CountedLoopNode *cl = loop->_head->as_CountedLoop();
1219 
1220   // only process vectorized main loops
1221   if (!cl->is_vectorized_loop() || !cl->is_main_loop()) return;
1222 
1223   int slp_max_unroll_factor = cl->slp_max_unroll();
1224   int cur_unroll = cl->unrolled_count();
1225 
1226   if (slp_max_unroll_factor == 0) return;
1227 
1228   // only process atomic unroll vector loops (not super unrolled after vectorization)
1229   if (cur_unroll != slp_max_unroll_factor) return;
1230 
1231   // we only ever process this one time
1232   if (cl->has_atomic_post_loop()) return;
1233 
1234 #ifndef PRODUCT
1235   if (TraceLoopOpts) {
1236     tty->print("PostVector  ");
1237     loop->dump_head();
1238   }
1239 #endif
1240   C->set_major_progress();
1241 
1242   // Find common pieces of the loop being guarded with pre & post loops
1243   CountedLoopNode *main_head = loop->_head->as_CountedLoop();
1244   CountedLoopEndNode *main_end = main_head->loopexit();
1245   // diagnostic to show loop end is not properly formed
1246   assert(main_end->outcnt() == 2, "1 true, 1 false path only");
1247 
1248   // mark this loop as processed
1249   main_head->mark_has_atomic_post_loop();
1250 
1251   Node *incr = main_end->incr();
1252   Node *limit = main_end->limit();
1253 
1254   // In this case we throw away the result as we are not using it to connect anything else.
1255   CountedLoopNode *post_head = NULL;
1256   insert_post_loop(loop, old_new, main_head, main_end, incr, limit, post_head);
1257 
1258   // It's difficult to be precise about the trip-counts
1259   // for post loops.  They are usually very short,
1260   // so guess that unit vector trips is a reasonable value.
1261   post_head->set_profile_trip_cnt(cur_unroll);
1262 
1263   // Now force out all loop-invariant dominating tests.  The optimizer
1264   // finds some, but we _know_ they are all useless.
1265   peeled_dom_test_elim(loop, old_new);
1266   loop->record_for_igvn();
1267 }
1268 
1269 
1270 //-------------------------insert_scalar_rced_post_loop------------------------
1271 // Insert a copy of the rce'd main loop as a post loop,
1272 // We have not unrolled the main loop, so this is the right time to inject this.
1273 // Later we will examine the partner of this post loop pair which still has range checks
1274 // to see inject code which tests at runtime if the range checks are applicable.
1275 void PhaseIdealLoop::insert_scalar_rced_post_loop(IdealLoopTree *loop, Node_List &old_new) {
1276   if (!loop->_head->is_CountedLoop()) return;
1277 
1278   CountedLoopNode *cl = loop->_head->as_CountedLoop();
1279 
1280   // only process RCE'd main loops
1281   if (!cl->is_main_loop() || cl->range_checks_present()) return;
1282 
1283 #ifndef PRODUCT
1284   if (TraceLoopOpts) {
1285     tty->print("PostScalarRce  ");
1286     loop->dump_head();
1287   }
1288 #endif
1289   C->set_major_progress();
1290 
1291   // Find common pieces of the loop being guarded with pre & post loops
1292   CountedLoopNode *main_head = loop->_head->as_CountedLoop();
1293   CountedLoopEndNode *main_end = main_head->loopexit();
1294   // diagnostic to show loop end is not properly formed
1295   assert(main_end->outcnt() == 2, "1 true, 1 false path only");
1296 
1297   Node *incr = main_end->incr();
1298   Node *limit = main_end->limit();
1299 
1300   // In this case we throw away the result as we are not using it to connect anything else.
1301   CountedLoopNode *post_head = NULL;
1302   insert_post_loop(loop, old_new, main_head, main_end, incr, limit, post_head);
1303 
1304   // It's difficult to be precise about the trip-counts
1305   // for post loops.  They are usually very short,
1306   // so guess that unit vector trips is a reasonable value.
1307   post_head->set_profile_trip_cnt(4.0);
1308   post_head->set_is_rce_post_loop();
1309 
1310   // Now force out all loop-invariant dominating tests.  The optimizer
1311   // finds some, but we _know_ they are all useless.
1312   peeled_dom_test_elim(loop, old_new);
1313   loop->record_for_igvn();
1314 }
1315 
1316 
1317 //------------------------------insert_post_loop-------------------------------
1318 // Insert post loops.  Add a post loop to the given loop passed.
1319 Node *PhaseIdealLoop::insert_post_loop(IdealLoopTree *loop, Node_List &old_new,
1320                                        CountedLoopNode *main_head, CountedLoopEndNode *main_end,
1321                                        Node *incr, Node *limit, CountedLoopNode *&post_head) {
1322   IfNode* outer_main_end = main_end;
1323   IdealLoopTree* outer_loop = loop;
1324   if (main_head->is_strip_mined()) {
1325     main_head->verify_strip_mined(1);
1326     outer_main_end = main_head->outer_loop_end();
1327     outer_loop = loop->_parent;
1328     assert(outer_loop->_head == main_head->in(LoopNode::EntryControl), "broken loop tree");
1329   }
1330 
1331   //------------------------------
1332   // Step A: Create a new post-Loop.
1333   Node* main_exit = outer_main_end->proj_out(false);
1334   assert(main_exit->Opcode() == Op_IfFalse, "");
1335   int dd_main_exit = dom_depth(main_exit);
1336 
1337   // Step A1: Clone the loop body of main. The clone becomes the post-loop.
1338   // The main loop pre-header illegally has 2 control users (old & new loops).
1339   clone_loop(loop, old_new, dd_main_exit, ControlAroundStripMined);
1340   assert(old_new[main_end->_idx]->Opcode() == Op_CountedLoopEnd, "");
1341   post_head = old_new[main_head->_idx]->as_CountedLoop();
1342   post_head->set_normal_loop();
1343   post_head->set_post_loop(main_head);
1344 
1345   // Reduce the post-loop trip count.
1346   CountedLoopEndNode* post_end = old_new[main_end->_idx]->as_CountedLoopEnd();
1347   post_end->_prob = PROB_FAIR;
1348 
1349   // Build the main-loop normal exit.
1350   IfFalseNode *new_main_exit = new IfFalseNode(outer_main_end);
1351   _igvn.register_new_node_with_optimizer(new_main_exit);
1352   set_idom(new_main_exit, outer_main_end, dd_main_exit);
1353   set_loop(new_main_exit, outer_loop->_parent);
1354 
1355   // Step A2: Build a zero-trip guard for the post-loop.  After leaving the
1356   // main-loop, the post-loop may not execute at all.  We 'opaque' the incr
1357   // (the previous loop trip-counter exit value) because we will be changing
1358   // the exit value (via additional unrolling) so we cannot constant-fold away the zero
1359   // trip guard until all unrolling is done.
1360   Node *zer_opaq = new Opaque1Node(C, incr);
1361   Node *zer_cmp = new CmpINode(zer_opaq, limit);
1362   Node *zer_bol = new BoolNode(zer_cmp, main_end->test_trip());
1363   register_new_node(zer_opaq, new_main_exit);
1364   register_new_node(zer_cmp, new_main_exit);
1365   register_new_node(zer_bol, new_main_exit);
1366 
1367   // Build the IfNode
1368   IfNode *zer_iff = new IfNode(new_main_exit, zer_bol, PROB_FAIR, COUNT_UNKNOWN);
1369   _igvn.register_new_node_with_optimizer(zer_iff);
1370   set_idom(zer_iff, new_main_exit, dd_main_exit);
1371   set_loop(zer_iff, outer_loop->_parent);
1372 
1373   // Plug in the false-path, taken if we need to skip this post-loop
1374   _igvn.replace_input_of(main_exit, 0, zer_iff);
1375   set_idom(main_exit, zer_iff, dd_main_exit);
1376   set_idom(main_exit->unique_out(), zer_iff, dd_main_exit);
1377   // Make the true-path, must enter this post loop
1378   Node *zer_taken = new IfTrueNode(zer_iff);
1379   _igvn.register_new_node_with_optimizer(zer_taken);
1380   set_idom(zer_taken, zer_iff, dd_main_exit);
1381   set_loop(zer_taken, outer_loop->_parent);
1382   // Plug in the true path
1383   _igvn.hash_delete(post_head);
1384   post_head->set_req(LoopNode::EntryControl, zer_taken);
1385   set_idom(post_head, zer_taken, dd_main_exit);
1386 
1387   Arena *a = Thread::current()->resource_area();
1388   VectorSet visited(a);
1389   Node_Stack clones(a, main_head->back_control()->outcnt());
1390   // Step A3: Make the fall-in values to the post-loop come from the
1391   // fall-out values of the main-loop.
1392   for (DUIterator_Fast imax, i = main_head->fast_outs(imax); i < imax; i++) {
1393     Node* main_phi = main_head->fast_out(i);
1394     if (main_phi->is_Phi() && main_phi->in(0) == main_head && main_phi->outcnt() >0) {
1395       Node *cur_phi = old_new[main_phi->_idx];
1396       Node *fallnew = clone_up_backedge_goo(main_head->back_control(),
1397                                             post_head->init_control(),
1398                                             main_phi->in(LoopNode::LoopBackControl),
1399                                             visited, clones);
1400       _igvn.hash_delete(cur_phi);
1401       cur_phi->set_req(LoopNode::EntryControl, fallnew);
1402     }
1403   }
1404 
1405   // CastII for the new post loop:
1406   bool inserted = cast_incr_before_loop(zer_opaq->in(1), zer_taken, post_head);
1407   assert(inserted, "no castII inserted");
1408 
1409   return new_main_exit;
1410 }
1411 
1412 //------------------------------is_invariant-----------------------------
1413 // Return true if n is invariant
1414 bool IdealLoopTree::is_invariant(Node* n) const {
1415   Node *n_c = _phase->has_ctrl(n) ? _phase->get_ctrl(n) : n;
1416   if (n_c->is_top()) return false;
1417   return !is_member(_phase->get_loop(n_c));
1418 }
1419 
1420 
1421 //------------------------------do_unroll--------------------------------------
1422 // Unroll the loop body one step - make each trip do 2 iterations.
1423 void PhaseIdealLoop::do_unroll( IdealLoopTree *loop, Node_List &old_new, bool adjust_min_trip ) {
1424   assert(LoopUnrollLimit, "");
1425   CountedLoopNode *loop_head = loop->_head->as_CountedLoop();
1426   CountedLoopEndNode *loop_end = loop_head->loopexit();
1427 #ifndef PRODUCT
1428   if (PrintOpto && VerifyLoopOptimizations) {
1429     tty->print("Unrolling ");
1430     loop->dump_head();
1431   } else if (TraceLoopOpts) {
1432     if (loop_head->trip_count() < (uint)LoopUnrollLimit) {
1433       tty->print("Unroll %d(%2d) ", loop_head->unrolled_count()*2, loop_head->trip_count());
1434     } else {
1435       tty->print("Unroll %d     ", loop_head->unrolled_count()*2);
1436     }
1437     loop->dump_head();
1438   }
1439 
1440   if (C->do_vector_loop() && (PrintOpto && (VerifyLoopOptimizations || TraceLoopOpts))) {
1441     Arena* arena = Thread::current()->resource_area();
1442     Node_Stack stack(arena, C->live_nodes() >> 2);
1443     Node_List rpo_list;
1444     VectorSet visited(arena);
1445     visited.set(loop_head->_idx);
1446     rpo( loop_head, stack, visited, rpo_list );
1447     dump(loop, rpo_list.size(), rpo_list );
1448   }
1449 #endif
1450 
1451   // Remember loop node count before unrolling to detect
1452   // if rounds of unroll,optimize are making progress
1453   loop_head->set_node_count_before_unroll(loop->_body.size());
1454 
1455   Node *ctrl  = loop_head->skip_strip_mined()->in(LoopNode::EntryControl);
1456   Node *limit = loop_head->limit();
1457   Node *init  = loop_head->init_trip();
1458   Node *stride = loop_head->stride();
1459 
1460   Node *opaq = NULL;
1461   if (adjust_min_trip) {       // If not maximally unrolling, need adjustment
1462     // Search for zero-trip guard.
1463 
1464     // Check the shape of the graph at the loop entry. If an inappropriate
1465     // graph shape is encountered, the compiler bails out loop unrolling;
1466     // compilation of the method will still succeed.
1467     if (!is_canonical_loop_entry(loop_head)) {
1468       return;
1469     }
1470     opaq = ctrl->in(0)->in(1)->in(1)->in(2);
1471     // Zero-trip test uses an 'opaque' node which is not shared.
1472     assert(opaq->outcnt() == 1 && opaq->in(1) == limit, "");
1473   }
1474 
1475   C->set_major_progress();
1476 
1477   Node* new_limit = NULL;
1478   int stride_con = stride->get_int();
1479   int stride_p = (stride_con > 0) ? stride_con : -stride_con;
1480   uint old_trip_count = loop_head->trip_count();
1481   // Verify that unroll policy result is still valid.
1482   assert(old_trip_count > 1 &&
1483       (!adjust_min_trip || stride_p <= (1<<3)*loop_head->unrolled_count()), "sanity");
1484 
1485   // Adjust loop limit to keep valid iterations number after unroll.
1486   // Use (limit - stride) instead of (((limit - init)/stride) & (-2))*stride
1487   // which may overflow.
1488   if (!adjust_min_trip) {
1489     assert(old_trip_count > 1 && (old_trip_count & 1) == 0,
1490         "odd trip count for maximally unroll");
1491     // Don't need to adjust limit for maximally unroll since trip count is even.
1492   } else if (loop_head->has_exact_trip_count() && init->is_Con()) {
1493     // Loop's limit is constant. Loop's init could be constant when pre-loop
1494     // become peeled iteration.
1495     jlong init_con = init->get_int();
1496     // We can keep old loop limit if iterations count stays the same:
1497     //   old_trip_count == new_trip_count * 2
1498     // Note: since old_trip_count >= 2 then new_trip_count >= 1
1499     // so we also don't need to adjust zero trip test.
1500     jlong limit_con  = limit->get_int();
1501     // (stride_con*2) not overflow since stride_con <= 8.
1502     int new_stride_con = stride_con * 2;
1503     int stride_m    = new_stride_con - (stride_con > 0 ? 1 : -1);
1504     jlong trip_count = (limit_con - init_con + stride_m)/new_stride_con;
1505     // New trip count should satisfy next conditions.
1506     assert(trip_count > 0 && (julong)trip_count < (julong)max_juint/2, "sanity");
1507     uint new_trip_count = (uint)trip_count;
1508     adjust_min_trip = (old_trip_count != new_trip_count*2);
1509   }
1510 
1511   if (adjust_min_trip) {
1512     // Step 2: Adjust the trip limit if it is called for.
1513     // The adjustment amount is -stride. Need to make sure if the
1514     // adjustment underflows or overflows, then the main loop is skipped.
1515     Node* cmp = loop_end->cmp_node();
1516     assert(cmp->in(2) == limit, "sanity");
1517     assert(opaq != NULL && opaq->in(1) == limit, "sanity");
1518 
1519     // Verify that policy_unroll result is still valid.
1520     const TypeInt* limit_type = _igvn.type(limit)->is_int();
1521     assert(stride_con > 0 && ((limit_type->_hi - stride_con) < limit_type->_hi) ||
1522         stride_con < 0 && ((limit_type->_lo - stride_con) > limit_type->_lo), "sanity");
1523 
1524     if (limit->is_Con()) {
1525       // The check in policy_unroll and the assert above guarantee
1526       // no underflow if limit is constant.
1527       new_limit = _igvn.intcon(limit->get_int() - stride_con);
1528       set_ctrl(new_limit, C->root());
1529     } else {
1530       // Limit is not constant.
1531       if (loop_head->unrolled_count() == 1) { // only for first unroll
1532         // Separate limit by Opaque node in case it is an incremented
1533         // variable from previous loop to avoid using pre-incremented
1534         // value which could increase register pressure.
1535         // Otherwise reorg_offsets() optimization will create a separate
1536         // Opaque node for each use of trip-counter and as result
1537         // zero trip guard limit will be different from loop limit.
1538         assert(has_ctrl(opaq), "should have it");
1539         Node* opaq_ctrl = get_ctrl(opaq);
1540         limit = new Opaque2Node( C, limit );
1541         register_new_node( limit, opaq_ctrl );
1542       }
1543       if ((stride_con > 0 && (java_subtract(limit_type->_lo, stride_con) < limit_type->_lo)) ||
1544           (stride_con < 0 && (java_subtract(limit_type->_hi, stride_con) > limit_type->_hi))) {
1545         // No underflow.
1546         new_limit = new SubINode(limit, stride);
1547       } else {
1548         // (limit - stride) may underflow.
1549         // Clamp the adjustment value with MININT or MAXINT:
1550         //
1551         //   new_limit = limit-stride
1552         //   if (stride > 0)
1553         //     new_limit = (limit < new_limit) ? MININT : new_limit;
1554         //   else
1555         //     new_limit = (limit > new_limit) ? MAXINT : new_limit;
1556         //
1557         BoolTest::mask bt = loop_end->test_trip();
1558         assert(bt == BoolTest::lt || bt == BoolTest::gt, "canonical test is expected");
1559         Node* adj_max = _igvn.intcon((stride_con > 0) ? min_jint : max_jint);
1560         set_ctrl(adj_max, C->root());
1561         Node* old_limit = NULL;
1562         Node* adj_limit = NULL;
1563         Node* bol = limit->is_CMove() ? limit->in(CMoveNode::Condition) : NULL;
1564         if (loop_head->unrolled_count() > 1 &&
1565             limit->is_CMove() && limit->Opcode() == Op_CMoveI &&
1566             limit->in(CMoveNode::IfTrue) == adj_max &&
1567             bol->as_Bool()->_test._test == bt &&
1568             bol->in(1)->Opcode() == Op_CmpI &&
1569             bol->in(1)->in(2) == limit->in(CMoveNode::IfFalse)) {
1570           // Loop was unrolled before.
1571           // Optimize the limit to avoid nested CMove:
1572           // use original limit as old limit.
1573           old_limit = bol->in(1)->in(1);
1574           // Adjust previous adjusted limit.
1575           adj_limit = limit->in(CMoveNode::IfFalse);
1576           adj_limit = new SubINode(adj_limit, stride);
1577         } else {
1578           old_limit = limit;
1579           adj_limit = new SubINode(limit, stride);
1580         }
1581         assert(old_limit != NULL && adj_limit != NULL, "");
1582         register_new_node( adj_limit, ctrl ); // adjust amount
1583         Node* adj_cmp = new CmpINode(old_limit, adj_limit);
1584         register_new_node( adj_cmp, ctrl );
1585         Node* adj_bool = new BoolNode(adj_cmp, bt);
1586         register_new_node( adj_bool, ctrl );
1587         new_limit = new CMoveINode(adj_bool, adj_limit, adj_max, TypeInt::INT);
1588       }
1589       register_new_node(new_limit, ctrl);
1590     }
1591     assert(new_limit != NULL, "");
1592     // Replace in loop test.
1593     assert(loop_end->in(1)->in(1) == cmp, "sanity");
1594     if (cmp->outcnt() == 1 && loop_end->in(1)->outcnt() == 1) {
1595       // Don't need to create new test since only one user.
1596       _igvn.hash_delete(cmp);
1597       cmp->set_req(2, new_limit);
1598     } else {
1599       // Create new test since it is shared.
1600       Node* ctrl2 = loop_end->in(0);
1601       Node* cmp2  = cmp->clone();
1602       cmp2->set_req(2, new_limit);
1603       register_new_node(cmp2, ctrl2);
1604       Node* bol2 = loop_end->in(1)->clone();
1605       bol2->set_req(1, cmp2);
1606       register_new_node(bol2, ctrl2);
1607       _igvn.replace_input_of(loop_end, 1, bol2);
1608     }
1609     // Step 3: Find the min-trip test guaranteed before a 'main' loop.
1610     // Make it a 1-trip test (means at least 2 trips).
1611 
1612     // Guard test uses an 'opaque' node which is not shared.  Hence I
1613     // can edit it's inputs directly.  Hammer in the new limit for the
1614     // minimum-trip guard.
1615     assert(opaq->outcnt() == 1, "");
1616     _igvn.replace_input_of(opaq, 1, new_limit);
1617   }
1618 
1619   // Adjust max trip count. The trip count is intentionally rounded
1620   // down here (e.g. 15-> 7-> 3-> 1) because if we unwittingly over-unroll,
1621   // the main, unrolled, part of the loop will never execute as it is protected
1622   // by the min-trip test.  See bug 4834191 for a case where we over-unrolled
1623   // and later determined that part of the unrolled loop was dead.
1624   loop_head->set_trip_count(old_trip_count / 2);
1625 
1626   // Double the count of original iterations in the unrolled loop body.
1627   loop_head->double_unrolled_count();
1628 
1629   // ---------
1630   // Step 4: Clone the loop body.  Move it inside the loop.  This loop body
1631   // represents the odd iterations; since the loop trips an even number of
1632   // times its backedge is never taken.  Kill the backedge.
1633   uint dd = dom_depth(loop_head);
1634   clone_loop(loop, old_new, dd, IgnoreStripMined);
1635 
1636   // Make backedges of the clone equal to backedges of the original.
1637   // Make the fall-in from the original come from the fall-out of the clone.
1638   for (DUIterator_Fast jmax, j = loop_head->fast_outs(jmax); j < jmax; j++) {
1639     Node* phi = loop_head->fast_out(j);
1640     if( phi->is_Phi() && phi->in(0) == loop_head && phi->outcnt() > 0 ) {
1641       Node *newphi = old_new[phi->_idx];
1642       _igvn.hash_delete( phi );
1643       _igvn.hash_delete( newphi );
1644 
1645       phi   ->set_req(LoopNode::   EntryControl, newphi->in(LoopNode::LoopBackControl));
1646       newphi->set_req(LoopNode::LoopBackControl, phi   ->in(LoopNode::LoopBackControl));
1647       phi   ->set_req(LoopNode::LoopBackControl, C->top());
1648     }
1649   }
1650   Node *clone_head = old_new[loop_head->_idx];
1651   _igvn.hash_delete( clone_head );
1652   loop_head ->set_req(LoopNode::   EntryControl, clone_head->in(LoopNode::LoopBackControl));
1653   clone_head->set_req(LoopNode::LoopBackControl, loop_head ->in(LoopNode::LoopBackControl));
1654   loop_head ->set_req(LoopNode::LoopBackControl, C->top());
1655   loop->_head = clone_head;     // New loop header
1656 
1657   set_idom(loop_head,  loop_head ->in(LoopNode::EntryControl), dd);
1658   set_idom(clone_head, clone_head->in(LoopNode::EntryControl), dd);
1659 
1660   // Kill the clone's backedge
1661   Node *newcle = old_new[loop_end->_idx];
1662   _igvn.hash_delete( newcle );
1663   Node *one = _igvn.intcon(1);
1664   set_ctrl(one, C->root());
1665   newcle->set_req(1, one);
1666   // Force clone into same loop body
1667   uint max = loop->_body.size();
1668   for( uint k = 0; k < max; k++ ) {
1669     Node *old = loop->_body.at(k);
1670     Node *nnn = old_new[old->_idx];
1671     loop->_body.push(nnn);
1672     if (!has_ctrl(old))
1673       set_loop(nnn, loop);
1674   }
1675 
1676   loop->record_for_igvn();
1677   loop_head->clear_strip_mined();
1678 
1679 #ifndef PRODUCT
1680   if (C->do_vector_loop() && (PrintOpto && (VerifyLoopOptimizations || TraceLoopOpts))) {
1681     tty->print("\nnew loop after unroll\n");       loop->dump_head();
1682     for (uint i = 0; i < loop->_body.size(); i++) {
1683       loop->_body.at(i)->dump();
1684     }
1685     if(C->clone_map().is_debug()) {
1686       tty->print("\nCloneMap\n");
1687       Dict* dict = C->clone_map().dict();
1688       DictI i(dict);
1689       tty->print_cr("Dict@%p[%d] = ", dict, dict->Size());
1690       for (int ii = 0; i.test(); ++i, ++ii) {
1691         NodeCloneInfo cl((uint64_t)dict->operator[]((void*)i._key));
1692         tty->print("%d->%d:%d,", (int)(intptr_t)i._key, cl.idx(), cl.gen());
1693         if (ii % 10 == 9) {
1694           tty->print_cr(" ");
1695         }
1696       }
1697       tty->print_cr(" ");
1698     }
1699   }
1700 #endif
1701 
1702 }
1703 
1704 //------------------------------do_maximally_unroll----------------------------
1705 
1706 void PhaseIdealLoop::do_maximally_unroll( IdealLoopTree *loop, Node_List &old_new ) {
1707   CountedLoopNode *cl = loop->_head->as_CountedLoop();
1708   assert(cl->has_exact_trip_count(), "trip count is not exact");
1709   assert(cl->trip_count() > 0, "");
1710 #ifndef PRODUCT
1711   if (TraceLoopOpts) {
1712     tty->print("MaxUnroll  %d ", cl->trip_count());
1713     loop->dump_head();
1714   }
1715 #endif
1716 
1717   // If loop is tripping an odd number of times, peel odd iteration
1718   if ((cl->trip_count() & 1) == 1) {
1719     do_peeling(loop, old_new);
1720   }
1721 
1722   // Now its tripping an even number of times remaining.  Double loop body.
1723   // Do not adjust pre-guards; they are not needed and do not exist.
1724   if (cl->trip_count() > 0) {
1725     assert((cl->trip_count() & 1) == 0, "missed peeling");
1726     do_unroll(loop, old_new, false);
1727   }
1728 }
1729 
1730 void PhaseIdealLoop::mark_reductions(IdealLoopTree *loop) {
1731   if (SuperWordReductions == false) return;
1732 
1733   CountedLoopNode* loop_head = loop->_head->as_CountedLoop();
1734   if (loop_head->unrolled_count() > 1) {
1735     return;
1736   }
1737 
1738   Node* trip_phi = loop_head->phi();
1739   for (DUIterator_Fast imax, i = loop_head->fast_outs(imax); i < imax; i++) {
1740     Node* phi = loop_head->fast_out(i);
1741     if (phi->is_Phi() && phi->outcnt() > 0 && phi != trip_phi) {
1742       // For definitions which are loop inclusive and not tripcounts.
1743       Node* def_node = phi->in(LoopNode::LoopBackControl);
1744 
1745       if (def_node != NULL) {
1746         Node* n_ctrl = get_ctrl(def_node);
1747         if (n_ctrl != NULL && loop->is_member(get_loop(n_ctrl))) {
1748           // Now test it to see if it fits the standard pattern for a reduction operator.
1749           int opc = def_node->Opcode();
1750           if (opc != ReductionNode::opcode(opc, def_node->bottom_type()->basic_type())) {
1751             if (!def_node->is_reduction()) { // Not marked yet
1752               // To be a reduction, the arithmetic node must have the phi as input and provide a def to it
1753               bool ok = false;
1754               for (unsigned j = 1; j < def_node->req(); j++) {
1755                 Node* in = def_node->in(j);
1756                 if (in == phi) {
1757                   ok = true;
1758                   break;
1759                 }
1760               }
1761 
1762               // do nothing if we did not match the initial criteria
1763               if (ok == false) {
1764                 continue;
1765               }
1766 
1767               // The result of the reduction must not be used in the loop
1768               for (DUIterator_Fast imax, i = def_node->fast_outs(imax); i < imax && ok; i++) {
1769                 Node* u = def_node->fast_out(i);
1770                 if (!loop->is_member(get_loop(ctrl_or_self(u)))) {
1771                   continue;
1772                 }
1773                 if (u == phi) {
1774                   continue;
1775                 }
1776                 ok = false;
1777               }
1778 
1779               // iff the uses conform
1780               if (ok) {
1781                 def_node->add_flag(Node::Flag_is_reduction);
1782                 loop_head->mark_has_reductions();
1783               }
1784             }
1785           }
1786         }
1787       }
1788     }
1789   }
1790 }
1791 
1792 //------------------------------adjust_limit-----------------------------------
1793 // Helper function for add_constraint().
1794 Node* PhaseIdealLoop::adjust_limit(int stride_con, Node * scale, Node *offset, Node *rc_limit, Node *loop_limit, Node *pre_ctrl) {
1795   // Compute "I :: (limit-offset)/scale"
1796   Node *con = new SubINode(rc_limit, offset);
1797   register_new_node(con, pre_ctrl);
1798   Node *X = new DivINode(0, con, scale);
1799   register_new_node(X, pre_ctrl);
1800 
1801   // Adjust loop limit
1802   loop_limit = (stride_con > 0)
1803                ? (Node*)(new MinINode(loop_limit, X))
1804                : (Node*)(new MaxINode(loop_limit, X));
1805   register_new_node(loop_limit, pre_ctrl);
1806   return loop_limit;
1807 }
1808 
1809 //------------------------------add_constraint---------------------------------
1810 // Constrain the main loop iterations so the conditions:
1811 //    low_limit <= scale_con * I + offset  <  upper_limit
1812 // always holds true.  That is, either increase the number of iterations in
1813 // the pre-loop or the post-loop until the condition holds true in the main
1814 // loop.  Stride, scale, offset and limit are all loop invariant.  Further,
1815 // stride and scale are constants (offset and limit often are).
1816 void PhaseIdealLoop::add_constraint( int stride_con, int scale_con, Node *offset, Node *low_limit, Node *upper_limit, Node *pre_ctrl, Node **pre_limit, Node **main_limit ) {
1817   // For positive stride, the pre-loop limit always uses a MAX function
1818   // and the main loop a MIN function.  For negative stride these are
1819   // reversed.
1820 
1821   // Also for positive stride*scale the affine function is increasing, so the
1822   // pre-loop must check for underflow and the post-loop for overflow.
1823   // Negative stride*scale reverses this; pre-loop checks for overflow and
1824   // post-loop for underflow.
1825 
1826   Node *scale = _igvn.intcon(scale_con);
1827   set_ctrl(scale, C->root());
1828 
1829   if ((stride_con^scale_con) >= 0) { // Use XOR to avoid overflow
1830     // The overflow limit: scale*I+offset < upper_limit
1831     // For main-loop compute
1832     //   ( if (scale > 0) /* and stride > 0 */
1833     //       I < (upper_limit-offset)/scale
1834     //     else /* scale < 0 and stride < 0 */
1835     //       I > (upper_limit-offset)/scale
1836     //   )
1837     //
1838     // (upper_limit-offset) may overflow or underflow.
1839     // But it is fine since main loop will either have
1840     // less iterations or will be skipped in such case.
1841     *main_limit = adjust_limit(stride_con, scale, offset, upper_limit, *main_limit, pre_ctrl);
1842 
1843     // The underflow limit: low_limit <= scale*I+offset.
1844     // For pre-loop compute
1845     //   NOT(scale*I+offset >= low_limit)
1846     //   scale*I+offset < low_limit
1847     //   ( if (scale > 0) /* and stride > 0 */
1848     //       I < (low_limit-offset)/scale
1849     //     else /* scale < 0 and stride < 0 */
1850     //       I > (low_limit-offset)/scale
1851     //   )
1852 
1853     if (low_limit->get_int() == -max_jint) {
1854       // We need this guard when scale*pre_limit+offset >= limit
1855       // due to underflow. So we need execute pre-loop until
1856       // scale*I+offset >= min_int. But (min_int-offset) will
1857       // underflow when offset > 0 and X will be > original_limit
1858       // when stride > 0. To avoid it we replace positive offset with 0.
1859       //
1860       // Also (min_int+1 == -max_int) is used instead of min_int here
1861       // to avoid problem with scale == -1 (min_int/(-1) == min_int).
1862       Node* shift = _igvn.intcon(31);
1863       set_ctrl(shift, C->root());
1864       Node* sign = new RShiftINode(offset, shift);
1865       register_new_node(sign, pre_ctrl);
1866       offset = new AndINode(offset, sign);
1867       register_new_node(offset, pre_ctrl);
1868     } else {
1869       assert(low_limit->get_int() == 0, "wrong low limit for range check");
1870       // The only problem we have here when offset == min_int
1871       // since (0-min_int) == min_int. It may be fine for stride > 0
1872       // but for stride < 0 X will be < original_limit. To avoid it
1873       // max(pre_limit, original_limit) is used in do_range_check().
1874     }
1875     // Pass (-stride) to indicate pre_loop_cond = NOT(main_loop_cond);
1876     *pre_limit = adjust_limit((-stride_con), scale, offset, low_limit, *pre_limit, pre_ctrl);
1877 
1878   } else { // stride_con*scale_con < 0
1879     // For negative stride*scale pre-loop checks for overflow and
1880     // post-loop for underflow.
1881     //
1882     // The overflow limit: scale*I+offset < upper_limit
1883     // For pre-loop compute
1884     //   NOT(scale*I+offset < upper_limit)
1885     //   scale*I+offset >= upper_limit
1886     //   scale*I+offset+1 > upper_limit
1887     //   ( if (scale < 0) /* and stride > 0 */
1888     //       I < (upper_limit-(offset+1))/scale
1889     //     else /* scale > 0 and stride < 0 */
1890     //       I > (upper_limit-(offset+1))/scale
1891     //   )
1892     //
1893     // (upper_limit-offset-1) may underflow or overflow.
1894     // To avoid it min(pre_limit, original_limit) is used
1895     // in do_range_check() for stride > 0 and max() for < 0.
1896     Node *one  = _igvn.intcon(1);
1897     set_ctrl(one, C->root());
1898 
1899     Node *plus_one = new AddINode(offset, one);
1900     register_new_node( plus_one, pre_ctrl );
1901     // Pass (-stride) to indicate pre_loop_cond = NOT(main_loop_cond);
1902     *pre_limit = adjust_limit((-stride_con), scale, plus_one, upper_limit, *pre_limit, pre_ctrl);
1903 
1904     if (low_limit->get_int() == -max_jint) {
1905       // We need this guard when scale*main_limit+offset >= limit
1906       // due to underflow. So we need execute main-loop while
1907       // scale*I+offset+1 > min_int. But (min_int-offset-1) will
1908       // underflow when (offset+1) > 0 and X will be < main_limit
1909       // when scale < 0 (and stride > 0). To avoid it we replace
1910       // positive (offset+1) with 0.
1911       //
1912       // Also (min_int+1 == -max_int) is used instead of min_int here
1913       // to avoid problem with scale == -1 (min_int/(-1) == min_int).
1914       Node* shift = _igvn.intcon(31);
1915       set_ctrl(shift, C->root());
1916       Node* sign = new RShiftINode(plus_one, shift);
1917       register_new_node(sign, pre_ctrl);
1918       plus_one = new AndINode(plus_one, sign);
1919       register_new_node(plus_one, pre_ctrl);
1920     } else {
1921       assert(low_limit->get_int() == 0, "wrong low limit for range check");
1922       // The only problem we have here when offset == max_int
1923       // since (max_int+1) == min_int and (0-min_int) == min_int.
1924       // But it is fine since main loop will either have
1925       // less iterations or will be skipped in such case.
1926     }
1927     // The underflow limit: low_limit <= scale*I+offset.
1928     // For main-loop compute
1929     //   scale*I+offset+1 > low_limit
1930     //   ( if (scale < 0) /* and stride > 0 */
1931     //       I < (low_limit-(offset+1))/scale
1932     //     else /* scale > 0 and stride < 0 */
1933     //       I > (low_limit-(offset+1))/scale
1934     //   )
1935 
1936     *main_limit = adjust_limit(stride_con, scale, plus_one, low_limit, *main_limit, pre_ctrl);
1937   }
1938 }
1939 
1940 
1941 //------------------------------is_scaled_iv---------------------------------
1942 // Return true if exp is a constant times an induction var
1943 bool PhaseIdealLoop::is_scaled_iv(Node* exp, Node* iv, int* p_scale) {
1944   if (exp == iv) {
1945     if (p_scale != NULL) {
1946       *p_scale = 1;
1947     }
1948     return true;
1949   }
1950   int opc = exp->Opcode();
1951   if (opc == Op_MulI) {
1952     if (exp->in(1) == iv && exp->in(2)->is_Con()) {
1953       if (p_scale != NULL) {
1954         *p_scale = exp->in(2)->get_int();
1955       }
1956       return true;
1957     }
1958     if (exp->in(2) == iv && exp->in(1)->is_Con()) {
1959       if (p_scale != NULL) {
1960         *p_scale = exp->in(1)->get_int();
1961       }
1962       return true;
1963     }
1964   } else if (opc == Op_LShiftI) {
1965     if (exp->in(1) == iv && exp->in(2)->is_Con()) {
1966       if (p_scale != NULL) {
1967         *p_scale = 1 << exp->in(2)->get_int();
1968       }
1969       return true;
1970     }
1971   }
1972   return false;
1973 }
1974 
1975 //-----------------------------is_scaled_iv_plus_offset------------------------------
1976 // Return true if exp is a simple induction variable expression: k1*iv + (invar + k2)
1977 bool PhaseIdealLoop::is_scaled_iv_plus_offset(Node* exp, Node* iv, int* p_scale, Node** p_offset, int depth) {
1978   if (is_scaled_iv(exp, iv, p_scale)) {
1979     if (p_offset != NULL) {
1980       Node *zero = _igvn.intcon(0);
1981       set_ctrl(zero, C->root());
1982       *p_offset = zero;
1983     }
1984     return true;
1985   }
1986   int opc = exp->Opcode();
1987   if (opc == Op_AddI) {
1988     if (is_scaled_iv(exp->in(1), iv, p_scale)) {
1989       if (p_offset != NULL) {
1990         *p_offset = exp->in(2);
1991       }
1992       return true;
1993     }
1994     if (is_scaled_iv(exp->in(2), iv, p_scale)) {
1995       if (p_offset != NULL) {
1996         *p_offset = exp->in(1);
1997       }
1998       return true;
1999     }
2000     if (exp->in(2)->is_Con()) {
2001       Node* offset2 = NULL;
2002       if (depth < 2 &&
2003           is_scaled_iv_plus_offset(exp->in(1), iv, p_scale,
2004                                    p_offset != NULL ? &offset2 : NULL, depth+1)) {
2005         if (p_offset != NULL) {
2006           Node *ctrl_off2 = get_ctrl(offset2);
2007           Node* offset = new AddINode(offset2, exp->in(2));
2008           register_new_node(offset, ctrl_off2);
2009           *p_offset = offset;
2010         }
2011         return true;
2012       }
2013     }
2014   } else if (opc == Op_SubI) {
2015     if (is_scaled_iv(exp->in(1), iv, p_scale)) {
2016       if (p_offset != NULL) {
2017         Node *zero = _igvn.intcon(0);
2018         set_ctrl(zero, C->root());
2019         Node *ctrl_off = get_ctrl(exp->in(2));
2020         Node* offset = new SubINode(zero, exp->in(2));
2021         register_new_node(offset, ctrl_off);
2022         *p_offset = offset;
2023       }
2024       return true;
2025     }
2026     if (is_scaled_iv(exp->in(2), iv, p_scale)) {
2027       if (p_offset != NULL) {
2028         *p_scale *= -1;
2029         *p_offset = exp->in(1);
2030       }
2031       return true;
2032     }
2033   }
2034   return false;
2035 }
2036 
2037 //------------------------------do_range_check---------------------------------
2038 // Eliminate range-checks and other trip-counter vs loop-invariant tests.
2039 int PhaseIdealLoop::do_range_check( IdealLoopTree *loop, Node_List &old_new ) {
2040 #ifndef PRODUCT
2041   if (PrintOpto && VerifyLoopOptimizations) {
2042     tty->print("Range Check Elimination ");
2043     loop->dump_head();
2044   } else if (TraceLoopOpts) {
2045     tty->print("RangeCheck   ");
2046     loop->dump_head();
2047   }
2048 #endif
2049   assert(RangeCheckElimination, "");
2050   CountedLoopNode *cl = loop->_head->as_CountedLoop();
2051   // If we fail before trying to eliminate range checks, set multiversion state
2052   int closed_range_checks = 1;
2053 
2054   // protect against stride not being a constant
2055   if (!cl->stride_is_con())
2056     return closed_range_checks;
2057 
2058   // Find the trip counter; we are iteration splitting based on it
2059   Node *trip_counter = cl->phi();
2060   // Find the main loop limit; we will trim it's iterations
2061   // to not ever trip end tests
2062   Node *main_limit = cl->limit();
2063 
2064   // Check graph shape. Cannot optimize a loop if zero-trip
2065   // Opaque1 node is optimized away and then another round
2066   // of loop opts attempted.
2067   if (!is_canonical_loop_entry(cl)) {
2068     return closed_range_checks;
2069   }
2070 
2071   // Need to find the main-loop zero-trip guard
2072   Node *ctrl  = cl->skip_strip_mined()->in(LoopNode::EntryControl);
2073   Node *iffm = ctrl->in(0);
2074   Node *opqzm = iffm->in(1)->in(1)->in(2);
2075   assert(opqzm->in(1) == main_limit, "do not understand situation");
2076 
2077   // Find the pre-loop limit; we will expand its iterations to
2078   // not ever trip low tests.
2079   Node *p_f = iffm->in(0);
2080   // pre loop may have been optimized out
2081   if (p_f->Opcode() != Op_IfFalse) {
2082     return closed_range_checks;
2083   }
2084   CountedLoopEndNode *pre_end = p_f->in(0)->as_CountedLoopEnd();
2085   assert(pre_end->loopnode()->is_pre_loop(), "");
2086   Node *pre_opaq1 = pre_end->limit();
2087   // Occasionally it's possible for a pre-loop Opaque1 node to be
2088   // optimized away and then another round of loop opts attempted.
2089   // We can not optimize this particular loop in that case.
2090   if (pre_opaq1->Opcode() != Op_Opaque1)
2091     return closed_range_checks;
2092   Opaque1Node *pre_opaq = (Opaque1Node*)pre_opaq1;
2093   Node *pre_limit = pre_opaq->in(1);
2094 
2095   // Where do we put new limit calculations
2096   Node *pre_ctrl = pre_end->loopnode()->in(LoopNode::EntryControl);
2097 
2098   // Ensure the original loop limit is available from the
2099   // pre-loop Opaque1 node.
2100   Node *orig_limit = pre_opaq->original_loop_limit();
2101   if (orig_limit == NULL || _igvn.type(orig_limit) == Type::TOP)
2102     return closed_range_checks;
2103 
2104   // Must know if its a count-up or count-down loop
2105 
2106   int stride_con = cl->stride_con();
2107   Node *zero = _igvn.intcon(0);
2108   Node *one  = _igvn.intcon(1);
2109   // Use symmetrical int range [-max_jint,max_jint]
2110   Node *mini = _igvn.intcon(-max_jint);
2111   set_ctrl(zero, C->root());
2112   set_ctrl(one,  C->root());
2113   set_ctrl(mini, C->root());
2114 
2115   // Range checks that do not dominate the loop backedge (ie.
2116   // conditionally executed) can lengthen the pre loop limit beyond
2117   // the original loop limit. To prevent this, the pre limit is
2118   // (for stride > 0) MINed with the original loop limit (MAXed
2119   // stride < 0) when some range_check (rc) is conditionally
2120   // executed.
2121   bool conditional_rc = false;
2122 
2123   // Count number of range checks and reduce by load range limits, if zero,
2124   // the loop is in canonical form to multiversion.
2125   closed_range_checks = 0;
2126 
2127   // Check loop body for tests of trip-counter plus loop-invariant vs loop-variant.
2128   for( uint i = 0; i < loop->_body.size(); i++ ) {
2129     Node *iff = loop->_body[i];
2130     if (iff->Opcode() == Op_If ||
2131         iff->Opcode() == Op_RangeCheck) { // Test?
2132       // Test is an IfNode, has 2 projections.  If BOTH are in the loop
2133       // we need loop unswitching instead of iteration splitting.
2134       closed_range_checks++;
2135       Node *exit = loop->is_loop_exit(iff);
2136       if( !exit ) continue;
2137       int flip = (exit->Opcode() == Op_IfTrue) ? 1 : 0;
2138 
2139       // Get boolean condition to test
2140       Node *i1 = iff->in(1);
2141       if( !i1->is_Bool() ) continue;
2142       BoolNode *bol = i1->as_Bool();
2143       BoolTest b_test = bol->_test;
2144       // Flip sense of test if exit condition is flipped
2145       if( flip )
2146         b_test = b_test.negate();
2147 
2148       // Get compare
2149       Node *cmp = bol->in(1);
2150 
2151       // Look for trip_counter + offset vs limit
2152       Node *rc_exp = cmp->in(1);
2153       Node *limit  = cmp->in(2);
2154       int scale_con= 1;        // Assume trip counter not scaled
2155 
2156       Node *limit_c = get_ctrl(limit);
2157       if( loop->is_member(get_loop(limit_c) ) ) {
2158         // Compare might have operands swapped; commute them
2159         b_test = b_test.commute();
2160         rc_exp = cmp->in(2);
2161         limit  = cmp->in(1);
2162         limit_c = get_ctrl(limit);
2163         if( loop->is_member(get_loop(limit_c) ) )
2164           continue;             // Both inputs are loop varying; cannot RCE
2165       }
2166       // Here we know 'limit' is loop invariant
2167 
2168       // 'limit' maybe pinned below the zero trip test (probably from a
2169       // previous round of rce), in which case, it can't be used in the
2170       // zero trip test expression which must occur before the zero test's if.
2171       if( limit_c == ctrl ) {
2172         continue;  // Don't rce this check but continue looking for other candidates.
2173       }
2174 
2175       // Check for scaled induction variable plus an offset
2176       Node *offset = NULL;
2177 
2178       if (!is_scaled_iv_plus_offset(rc_exp, trip_counter, &scale_con, &offset)) {
2179         continue;
2180       }
2181 
2182       Node *offset_c = get_ctrl(offset);
2183       if( loop->is_member( get_loop(offset_c) ) )
2184         continue;               // Offset is not really loop invariant
2185       // Here we know 'offset' is loop invariant.
2186 
2187       // As above for the 'limit', the 'offset' maybe pinned below the
2188       // zero trip test.
2189       if( offset_c == ctrl ) {
2190         continue; // Don't rce this check but continue looking for other candidates.
2191       }
2192 #ifdef ASSERT
2193       if (TraceRangeLimitCheck) {
2194         tty->print_cr("RC bool node%s", flip ? " flipped:" : ":");
2195         bol->dump(2);
2196       }
2197 #endif
2198       // At this point we have the expression as:
2199       //   scale_con * trip_counter + offset :: limit
2200       // where scale_con, offset and limit are loop invariant.  Trip_counter
2201       // monotonically increases by stride_con, a constant.  Both (or either)
2202       // stride_con and scale_con can be negative which will flip about the
2203       // sense of the test.
2204 
2205       // Adjust pre and main loop limits to guard the correct iteration set
2206       if( cmp->Opcode() == Op_CmpU ) {// Unsigned compare is really 2 tests
2207         if( b_test._test == BoolTest::lt ) { // Range checks always use lt
2208           // The underflow and overflow limits: 0 <= scale*I+offset < limit
2209           add_constraint( stride_con, scale_con, offset, zero, limit, pre_ctrl, &pre_limit, &main_limit );
2210           // (0-offset)/scale could be outside of loop iterations range.
2211           conditional_rc = true;
2212         } else {
2213           if (PrintOpto) {
2214             tty->print_cr("missed RCE opportunity");
2215           }
2216           continue;             // In release mode, ignore it
2217         }
2218       } else {                  // Otherwise work on normal compares
2219         switch( b_test._test ) {
2220         case BoolTest::gt:
2221           // Fall into GE case
2222         case BoolTest::ge:
2223           // Convert (I*scale+offset) >= Limit to (I*(-scale)+(-offset)) <= -Limit
2224           scale_con = -scale_con;
2225           offset = new SubINode( zero, offset );
2226           register_new_node( offset, pre_ctrl );
2227           limit  = new SubINode( zero, limit );
2228           register_new_node( limit, pre_ctrl );
2229           // Fall into LE case
2230         case BoolTest::le:
2231           if (b_test._test != BoolTest::gt) {
2232             // Convert X <= Y to X < Y+1
2233             limit = new AddINode( limit, one );
2234             register_new_node( limit, pre_ctrl );
2235           }
2236           // Fall into LT case
2237         case BoolTest::lt:
2238           // The underflow and overflow limits: MIN_INT <= scale*I+offset < limit
2239           // Note: (MIN_INT+1 == -MAX_INT) is used instead of MIN_INT here
2240           // to avoid problem with scale == -1: MIN_INT/(-1) == MIN_INT.
2241           add_constraint( stride_con, scale_con, offset, mini, limit, pre_ctrl, &pre_limit, &main_limit );
2242           // ((MIN_INT+1)-offset)/scale could be outside of loop iterations range.
2243           // Note: negative offset is replaced with 0 but (MIN_INT+1)/scale could
2244           // still be outside of loop range.
2245           conditional_rc = true;
2246           break;
2247         default:
2248           if (PrintOpto) {
2249             tty->print_cr("missed RCE opportunity");
2250           }
2251           continue;             // Unhandled case
2252         }
2253       }
2254 
2255       // Kill the eliminated test
2256       C->set_major_progress();
2257       Node *kill_con = _igvn.intcon( 1-flip );
2258       set_ctrl(kill_con, C->root());
2259       _igvn.replace_input_of(iff, 1, kill_con);
2260       // Find surviving projection
2261       assert(iff->is_If(), "");
2262       ProjNode* dp = ((IfNode*)iff)->proj_out(1-flip);
2263       // Find loads off the surviving projection; remove their control edge
2264       for (DUIterator_Fast imax, i = dp->fast_outs(imax); i < imax; i++) {
2265         Node* cd = dp->fast_out(i); // Control-dependent node
2266         if (cd->is_Load() && cd->depends_only_on_test()) {   // Loads can now float around in the loop
2267           // Allow the load to float around in the loop, or before it
2268           // but NOT before the pre-loop.
2269           _igvn.replace_input_of(cd, 0, ctrl); // ctrl, not NULL
2270           --i;
2271           --imax;
2272         }
2273       }
2274       if (limit->Opcode() == Op_LoadRange) {
2275         closed_range_checks--;
2276       }
2277 
2278     } // End of is IF
2279 
2280   }
2281 
2282   // Update loop limits
2283   if (conditional_rc) {
2284     pre_limit = (stride_con > 0) ? (Node*)new MinINode(pre_limit, orig_limit)
2285                                  : (Node*)new MaxINode(pre_limit, orig_limit);
2286     register_new_node(pre_limit, pre_ctrl);
2287   }
2288   _igvn.replace_input_of(pre_opaq, 1, pre_limit);
2289 
2290   // Note:: we are making the main loop limit no longer precise;
2291   // need to round up based on stride.
2292   cl->set_nonexact_trip_count();
2293   Node *main_cle = cl->loopexit();
2294   Node *main_bol = main_cle->in(1);
2295   // Hacking loop bounds; need private copies of exit test
2296   if( main_bol->outcnt() > 1 ) {// BoolNode shared?
2297     main_bol = main_bol->clone();// Clone a private BoolNode
2298     register_new_node( main_bol, main_cle->in(0) );
2299     _igvn.replace_input_of(main_cle, 1, main_bol);
2300   }
2301   Node *main_cmp = main_bol->in(1);
2302   if( main_cmp->outcnt() > 1 ) { // CmpNode shared?
2303     main_cmp = main_cmp->clone();// Clone a private CmpNode
2304     register_new_node( main_cmp, main_cle->in(0) );
2305     _igvn.replace_input_of(main_bol, 1, main_cmp);
2306   }
2307   // Hack the now-private loop bounds
2308   _igvn.replace_input_of(main_cmp, 2, main_limit);
2309   // The OpaqueNode is unshared by design
2310   assert( opqzm->outcnt() == 1, "cannot hack shared node" );
2311   _igvn.replace_input_of(opqzm, 1, main_limit);
2312 
2313   return closed_range_checks;
2314 }
2315 
2316 //------------------------------has_range_checks-------------------------------
2317 // Check to see if RCE cleaned the current loop of range-checks.
2318 void PhaseIdealLoop::has_range_checks(IdealLoopTree *loop) {
2319   assert(RangeCheckElimination, "");
2320 
2321   // skip if not a counted loop
2322   if (!loop->is_counted()) return;
2323 
2324   CountedLoopNode *cl = loop->_head->as_CountedLoop();
2325 
2326   // skip this loop if it is already checked
2327   if (cl->has_been_range_checked()) return;
2328 
2329   // Now check for existence of range checks
2330   for (uint i = 0; i < loop->_body.size(); i++) {
2331     Node *iff = loop->_body[i];
2332     int iff_opc = iff->Opcode();
2333     if (iff_opc == Op_If || iff_opc == Op_RangeCheck) {
2334       cl->mark_has_range_checks();
2335       break;
2336     }
2337   }
2338   cl->set_has_been_range_checked();
2339 }
2340 
2341 //-------------------------multi_version_post_loops----------------------------
2342 // Check the range checks that remain, if simple, use the bounds to guard
2343 // which version to a post loop we execute, one with range checks or one without
2344 bool PhaseIdealLoop::multi_version_post_loops(IdealLoopTree *rce_loop, IdealLoopTree *legacy_loop) {
2345   bool multi_version_succeeded = false;
2346   assert(RangeCheckElimination, "");
2347   CountedLoopNode *legacy_cl = legacy_loop->_head->as_CountedLoop();
2348   assert(legacy_cl->is_post_loop(), "");
2349 
2350   // Check for existence of range checks using the unique instance to make a guard with
2351   Unique_Node_List worklist;
2352   for (uint i = 0; i < legacy_loop->_body.size(); i++) {
2353     Node *iff = legacy_loop->_body[i];
2354     int iff_opc = iff->Opcode();
2355     if (iff_opc == Op_If || iff_opc == Op_RangeCheck) {
2356       worklist.push(iff);
2357     }
2358   }
2359 
2360   // Find RCE'd post loop so that we can stage its guard.
2361   if (!is_canonical_loop_entry(legacy_cl)) return multi_version_succeeded;
2362   Node* ctrl = legacy_cl->in(LoopNode::EntryControl);
2363   Node* iffm = ctrl->in(0);
2364 
2365   // Now we test that both the post loops are connected
2366   Node* post_loop_region = iffm->in(0);
2367   if (post_loop_region == NULL) return multi_version_succeeded;
2368   if (!post_loop_region->is_Region()) return multi_version_succeeded;
2369   Node* covering_region = post_loop_region->in(RegionNode::Control+1);
2370   if (covering_region == NULL) return multi_version_succeeded;
2371   if (!covering_region->is_Region()) return multi_version_succeeded;
2372   Node* p_f = covering_region->in(RegionNode::Control);
2373   if (p_f == NULL) return multi_version_succeeded;
2374   if (!p_f->is_IfFalse()) return multi_version_succeeded;
2375   if (!p_f->in(0)->is_CountedLoopEnd()) return multi_version_succeeded;
2376   CountedLoopEndNode* rce_loop_end = p_f->in(0)->as_CountedLoopEnd();
2377   if (rce_loop_end == NULL) return multi_version_succeeded;
2378   CountedLoopNode* rce_cl = rce_loop_end->loopnode();
2379   if (rce_cl == NULL || !rce_cl->is_post_loop()) return multi_version_succeeded;
2380   CountedLoopNode *known_rce_cl = rce_loop->_head->as_CountedLoop();
2381   if (rce_cl != known_rce_cl) return multi_version_succeeded;
2382 
2383   // Then we fetch the cover entry test
2384   ctrl = rce_cl->in(LoopNode::EntryControl);
2385   if (!ctrl->is_IfTrue() && !ctrl->is_IfFalse()) return multi_version_succeeded;
2386 
2387 #ifndef PRODUCT
2388   if (TraceLoopOpts) {
2389     tty->print("PostMultiVersion\n");
2390     rce_loop->dump_head();
2391     legacy_loop->dump_head();
2392   }
2393 #endif
2394 
2395   // Now fetch the limit we want to compare against
2396   Node *limit = rce_cl->limit();
2397   bool first_time = true;
2398 
2399   // If we got this far, we identified the post loop which has been RCE'd and
2400   // we have a work list.  Now we will try to transform the if guard to cause
2401   // the loop pair to be multi version executed with the determination left to runtime
2402   // or the optimizer if full information is known about the given arrays at compile time.
2403   Node *last_min = NULL;
2404   multi_version_succeeded = true;
2405   while (worklist.size()) {
2406     Node* rc_iffm = worklist.pop();
2407     if (rc_iffm->is_If()) {
2408       Node *rc_bolzm = rc_iffm->in(1);
2409       if (rc_bolzm->is_Bool()) {
2410         Node *rc_cmpzm = rc_bolzm->in(1);
2411         if (rc_cmpzm->is_Cmp()) {
2412           Node *rc_left = rc_cmpzm->in(2);
2413           if (rc_left->Opcode() != Op_LoadRange) {
2414             multi_version_succeeded = false;
2415             break;
2416           }
2417           if (first_time) {
2418             last_min = rc_left;
2419             first_time = false;
2420           } else {
2421             Node *cur_min = new MinINode(last_min, rc_left);
2422             last_min = cur_min;
2423             _igvn.register_new_node_with_optimizer(last_min);
2424           }
2425         }
2426       }
2427     }
2428   }
2429 
2430   // All we have to do is update the limit of the rce loop
2431   // with the min of our expression and the current limit.
2432   // We will use this expression to replace the current limit.
2433   if (last_min && multi_version_succeeded) {
2434     Node *cur_min = new MinINode(last_min, limit);
2435     _igvn.register_new_node_with_optimizer(cur_min);
2436     Node *cmp_node = rce_loop_end->cmp_node();
2437     _igvn.replace_input_of(cmp_node, 2, cur_min);
2438     set_ctrl(cur_min, ctrl);
2439     set_loop(cur_min, rce_loop->_parent);
2440 
2441     legacy_cl->mark_is_multiversioned();
2442     rce_cl->mark_is_multiversioned();
2443     multi_version_succeeded = true;
2444 
2445     C->set_major_progress();
2446   }
2447 
2448   return multi_version_succeeded;
2449 }
2450 
2451 //-------------------------poison_rce_post_loop--------------------------------
2452 // Causes the rce'd post loop to be optimized away if multiversioning fails
2453 void PhaseIdealLoop::poison_rce_post_loop(IdealLoopTree *rce_loop) {
2454   CountedLoopNode *rce_cl = rce_loop->_head->as_CountedLoop();
2455   Node* ctrl = rce_cl->in(LoopNode::EntryControl);
2456   if (ctrl->is_IfTrue() || ctrl->is_IfFalse()) {
2457     Node* iffm = ctrl->in(0);
2458     if (iffm->is_If()) {
2459       Node* cur_bool = iffm->in(1);
2460       if (cur_bool->is_Bool()) {
2461         Node* cur_cmp = cur_bool->in(1);
2462         if (cur_cmp->is_Cmp()) {
2463           BoolTest::mask new_test = BoolTest::gt;
2464           BoolNode *new_bool = new BoolNode(cur_cmp, new_test);
2465           _igvn.replace_node(cur_bool, new_bool);
2466           _igvn._worklist.push(new_bool);
2467           Node* left_op = cur_cmp->in(1);
2468           _igvn.replace_input_of(cur_cmp, 2, left_op);
2469           C->set_major_progress();
2470         }
2471       }
2472     }
2473   }
2474 }
2475 
2476 //------------------------------DCE_loop_body----------------------------------
2477 // Remove simplistic dead code from loop body
2478 void IdealLoopTree::DCE_loop_body() {
2479   for( uint i = 0; i < _body.size(); i++ )
2480     if( _body.at(i)->outcnt() == 0 )
2481       _body.map( i--, _body.pop() );
2482 }
2483 
2484 
2485 //------------------------------adjust_loop_exit_prob--------------------------
2486 // Look for loop-exit tests with the 50/50 (or worse) guesses from the parsing stage.
2487 // Replace with a 1-in-10 exit guess.
2488 void IdealLoopTree::adjust_loop_exit_prob( PhaseIdealLoop *phase ) {
2489   Node *test = tail();
2490   while( test != _head ) {
2491     uint top = test->Opcode();
2492     if( top == Op_IfTrue || top == Op_IfFalse ) {
2493       int test_con = ((ProjNode*)test)->_con;
2494       assert(top == (uint)(test_con? Op_IfTrue: Op_IfFalse), "sanity");
2495       IfNode *iff = test->in(0)->as_If();
2496       if( iff->outcnt() == 2 ) {        // Ignore dead tests
2497         Node *bol = iff->in(1);
2498         if( bol && bol->req() > 1 && bol->in(1) &&
2499             ((bol->in(1)->Opcode() == Op_StorePConditional ) ||
2500              (bol->in(1)->Opcode() == Op_StoreIConditional ) ||
2501              (bol->in(1)->Opcode() == Op_StoreLConditional ) ||
2502              (bol->in(1)->Opcode() == Op_CompareAndExchangeB ) ||
2503              (bol->in(1)->Opcode() == Op_CompareAndExchangeS ) ||
2504              (bol->in(1)->Opcode() == Op_CompareAndExchangeI ) ||
2505              (bol->in(1)->Opcode() == Op_CompareAndExchangeL ) ||
2506              (bol->in(1)->Opcode() == Op_CompareAndExchangeP ) ||
2507              (bol->in(1)->Opcode() == Op_CompareAndExchangeN ) ||
2508              (bol->in(1)->Opcode() == Op_WeakCompareAndSwapB ) ||
2509              (bol->in(1)->Opcode() == Op_WeakCompareAndSwapS ) ||
2510              (bol->in(1)->Opcode() == Op_WeakCompareAndSwapI ) ||
2511              (bol->in(1)->Opcode() == Op_WeakCompareAndSwapL ) ||
2512              (bol->in(1)->Opcode() == Op_WeakCompareAndSwapP ) ||
2513              (bol->in(1)->Opcode() == Op_WeakCompareAndSwapN ) ||
2514              (bol->in(1)->Opcode() == Op_CompareAndSwapB ) ||
2515              (bol->in(1)->Opcode() == Op_CompareAndSwapS ) ||
2516              (bol->in(1)->Opcode() == Op_CompareAndSwapI ) ||
2517              (bol->in(1)->Opcode() == Op_CompareAndSwapL ) ||
2518              (bol->in(1)->Opcode() == Op_CompareAndSwapP ) ||
2519              (bol->in(1)->Opcode() == Op_CompareAndSwapN )))
2520           return;               // Allocation loops RARELY take backedge
2521         // Find the OTHER exit path from the IF
2522         Node* ex = iff->proj_out(1-test_con);
2523         float p = iff->_prob;
2524         if( !phase->is_member( this, ex ) && iff->_fcnt == COUNT_UNKNOWN ) {
2525           if( top == Op_IfTrue ) {
2526             if( p < (PROB_FAIR + PROB_UNLIKELY_MAG(3))) {
2527               iff->_prob = PROB_STATIC_FREQUENT;
2528             }
2529           } else {
2530             if( p > (PROB_FAIR - PROB_UNLIKELY_MAG(3))) {
2531               iff->_prob = PROB_STATIC_INFREQUENT;
2532             }
2533           }
2534         }
2535       }
2536     }
2537     test = phase->idom(test);
2538   }
2539 }
2540 
2541 #ifdef ASSERT
2542 static CountedLoopNode* locate_pre_from_main(CountedLoopNode *cl) {
2543   Node *ctrl  = cl->skip_strip_mined()->in(LoopNode::EntryControl);
2544   assert(ctrl->Opcode() == Op_IfTrue || ctrl->Opcode() == Op_IfFalse, "");
2545   Node *iffm = ctrl->in(0);
2546   assert(iffm->Opcode() == Op_If, "");
2547   Node *p_f = iffm->in(0);
2548   assert(p_f->Opcode() == Op_IfFalse, "");
2549   CountedLoopEndNode *pre_end = p_f->in(0)->as_CountedLoopEnd();
2550   assert(pre_end->loopnode()->is_pre_loop(), "");
2551   return pre_end->loopnode();
2552 }
2553 #endif
2554 
2555 // Remove the main and post loops and make the pre loop execute all
2556 // iterations. Useful when the pre loop is found empty.
2557 void IdealLoopTree::remove_main_post_loops(CountedLoopNode *cl, PhaseIdealLoop *phase) {
2558   CountedLoopEndNode* pre_end = cl->loopexit();
2559   Node* pre_cmp = pre_end->cmp_node();
2560   if (pre_cmp->in(2)->Opcode() != Op_Opaque1) {
2561     // Only safe to remove the main loop if the compiler optimized it
2562     // out based on an unknown number of iterations
2563     return;
2564   }
2565 
2566   // Can we find the main loop?
2567   if (_next == NULL) {
2568     return;
2569   }
2570 
2571   Node* next_head = _next->_head;
2572   if (!next_head->is_CountedLoop()) {
2573     return;
2574   }
2575 
2576   CountedLoopNode* main_head = next_head->as_CountedLoop();
2577   if (!main_head->is_main_loop()) {
2578     return;
2579   }
2580 
2581   assert(locate_pre_from_main(main_head) == cl, "bad main loop");
2582   Node* main_iff = main_head->skip_strip_mined()->in(LoopNode::EntryControl)->in(0);
2583 
2584   // Remove the Opaque1Node of the pre loop and make it execute all iterations
2585   phase->_igvn.replace_input_of(pre_cmp, 2, pre_cmp->in(2)->in(2));
2586   // Remove the Opaque1Node of the main loop so it can be optimized out
2587   Node* main_cmp = main_iff->in(1)->in(1);
2588   assert(main_cmp->in(2)->Opcode() == Op_Opaque1, "main loop has no opaque node?");
2589   phase->_igvn.replace_input_of(main_cmp, 2, main_cmp->in(2)->in(1));
2590 }
2591 
2592 //------------------------------policy_do_remove_empty_loop--------------------
2593 // Micro-benchmark spamming.  Policy is to always remove empty loops.
2594 // The 'DO' part is to replace the trip counter with the value it will
2595 // have on the last iteration.  This will break the loop.
2596 bool IdealLoopTree::policy_do_remove_empty_loop( PhaseIdealLoop *phase ) {
2597   // Minimum size must be empty loop
2598   if (_body.size() > EMPTY_LOOP_SIZE)
2599     return false;
2600 
2601   if (!_head->is_CountedLoop())
2602     return false;     // Dead loop
2603   CountedLoopNode *cl = _head->as_CountedLoop();
2604   if (!cl->is_valid_counted_loop())
2605     return false; // Malformed loop
2606   if (!phase->is_member(this, phase->get_ctrl(cl->loopexit()->in(CountedLoopEndNode::TestValue))))
2607     return false;             // Infinite loop
2608 
2609   if (cl->is_pre_loop()) {
2610     // If the loop we are removing is a pre-loop then the main and
2611     // post loop can be removed as well
2612     remove_main_post_loops(cl, phase);
2613   }
2614 
2615 #ifdef ASSERT
2616   // Ensure only one phi which is the iv.
2617   Node* iv = NULL;
2618   for (DUIterator_Fast imax, i = cl->fast_outs(imax); i < imax; i++) {
2619     Node* n = cl->fast_out(i);
2620     if (n->Opcode() == Op_Phi) {
2621       assert(iv == NULL, "Too many phis" );
2622       iv = n;
2623     }
2624   }
2625   assert(iv == cl->phi(), "Wrong phi" );
2626 #endif
2627 
2628   // main and post loops have explicitly created zero trip guard
2629   bool needs_guard = !cl->is_main_loop() && !cl->is_post_loop();
2630   if (needs_guard) {
2631     // Skip guard if values not overlap.
2632     const TypeInt* init_t = phase->_igvn.type(cl->init_trip())->is_int();
2633     const TypeInt* limit_t = phase->_igvn.type(cl->limit())->is_int();
2634     int  stride_con = cl->stride_con();
2635     if (stride_con > 0) {
2636       needs_guard = (init_t->_hi >= limit_t->_lo);
2637     } else {
2638       needs_guard = (init_t->_lo <= limit_t->_hi);
2639     }
2640   }
2641   if (needs_guard) {
2642     // Check for an obvious zero trip guard.
2643     Node* inctrl = PhaseIdealLoop::skip_loop_predicates(cl->skip_strip_mined()->in(LoopNode::EntryControl));
2644     if (inctrl->Opcode() == Op_IfTrue || inctrl->Opcode() == Op_IfFalse) {
2645       bool maybe_swapped = (inctrl->Opcode() == Op_IfFalse);
2646       // The test should look like just the backedge of a CountedLoop
2647       Node* iff = inctrl->in(0);
2648       if (iff->is_If()) {
2649         Node* bol = iff->in(1);
2650         if (bol->is_Bool()) {
2651           BoolTest test = bol->as_Bool()->_test;
2652           if (maybe_swapped) {
2653             test._test = test.commute();
2654             test._test = test.negate();
2655           }
2656           if (test._test == cl->loopexit()->test_trip()) {
2657             Node* cmp = bol->in(1);
2658             int init_idx = maybe_swapped ? 2 : 1;
2659             int limit_idx = maybe_swapped ? 1 : 2;
2660             if (cmp->is_Cmp() && cmp->in(init_idx) == cl->init_trip() && cmp->in(limit_idx) == cl->limit()) {
2661               needs_guard = false;
2662             }
2663           }
2664         }
2665       }
2666     }
2667   }
2668 
2669 #ifndef PRODUCT
2670   if (PrintOpto) {
2671     tty->print("Removing empty loop with%s zero trip guard", needs_guard ? "out" : "");
2672     this->dump_head();
2673   } else if (TraceLoopOpts) {
2674     tty->print("Empty with%s zero trip guard   ", needs_guard ? "out" : "");
2675     this->dump_head();
2676   }
2677 #endif
2678 
2679   if (needs_guard) {
2680     // Peel the loop to ensure there's a zero trip guard
2681     Node_List old_new;
2682     phase->do_peeling(this, old_new);
2683   }
2684 
2685   // Replace the phi at loop head with the final value of the last
2686   // iteration.  Then the CountedLoopEnd will collapse (backedge never
2687   // taken) and all loop-invariant uses of the exit values will be correct.
2688   Node *phi = cl->phi();
2689   Node *exact_limit = phase->exact_limit(this);
2690   if (exact_limit != cl->limit()) {
2691     // We also need to replace the original limit to collapse loop exit.
2692     Node* cmp = cl->loopexit()->cmp_node();
2693     assert(cl->limit() == cmp->in(2), "sanity");
2694     phase->_igvn._worklist.push(cmp->in(2)); // put limit on worklist
2695     phase->_igvn.replace_input_of(cmp, 2, exact_limit); // put cmp on worklist
2696   }
2697   // Note: the final value after increment should not overflow since
2698   // counted loop has limit check predicate.
2699   Node *final = new SubINode( exact_limit, cl->stride() );
2700   phase->register_new_node(final,cl->in(LoopNode::EntryControl));
2701   phase->_igvn.replace_node(phi,final);
2702   phase->C->set_major_progress();
2703   return true;
2704 }
2705 
2706 //------------------------------policy_do_one_iteration_loop-------------------
2707 // Convert one iteration loop into normal code.
2708 bool IdealLoopTree::policy_do_one_iteration_loop( PhaseIdealLoop *phase ) {
2709   if (!_head->as_Loop()->is_valid_counted_loop())
2710     return false; // Only for counted loop
2711 
2712   CountedLoopNode *cl = _head->as_CountedLoop();
2713   if (!cl->has_exact_trip_count() || cl->trip_count() != 1) {
2714     return false;
2715   }
2716 
2717 #ifndef PRODUCT
2718   if(TraceLoopOpts) {
2719     tty->print("OneIteration ");
2720     this->dump_head();
2721   }
2722 #endif
2723 
2724   Node *init_n = cl->init_trip();
2725 #ifdef ASSERT
2726   // Loop boundaries should be constant since trip count is exact.
2727   assert(init_n->get_int() + cl->stride_con() >= cl->limit()->get_int(), "should be one iteration");
2728 #endif
2729   // Replace the phi at loop head with the value of the init_trip.
2730   // Then the CountedLoopEnd will collapse (backedge will not be taken)
2731   // and all loop-invariant uses of the exit values will be correct.
2732   phase->_igvn.replace_node(cl->phi(), cl->init_trip());
2733   phase->C->set_major_progress();
2734   return true;
2735 }
2736 
2737 //=============================================================================
2738 //------------------------------iteration_split_impl---------------------------
2739 bool IdealLoopTree::iteration_split_impl( PhaseIdealLoop *phase, Node_List &old_new ) {
2740   // Compute loop trip count if possible.
2741   compute_trip_count(phase);
2742 
2743   // Convert one iteration loop into normal code.
2744   if (policy_do_one_iteration_loop(phase))
2745     return true;
2746 
2747   // Check and remove empty loops (spam micro-benchmarks)
2748   if (policy_do_remove_empty_loop(phase))
2749     return true;  // Here we removed an empty loop
2750 
2751   bool should_peel = policy_peeling(phase); // Should we peel?
2752 
2753   bool should_unswitch = policy_unswitching(phase);
2754 
2755   // Non-counted loops may be peeled; exactly 1 iteration is peeled.
2756   // This removes loop-invariant tests (usually null checks).
2757   if (!_head->is_CountedLoop()) { // Non-counted loop
2758     if (PartialPeelLoop && phase->partial_peel(this, old_new)) {
2759       // Partial peel succeeded so terminate this round of loop opts
2760       return false;
2761     }
2762     if (should_peel) {            // Should we peel?
2763       if (PrintOpto) { tty->print_cr("should_peel"); }
2764       phase->do_peeling(this,old_new);
2765     } else if (should_unswitch) {
2766       phase->do_unswitching(this, old_new);
2767     }
2768     return true;
2769   }
2770   CountedLoopNode *cl = _head->as_CountedLoop();
2771 
2772   if (!cl->is_valid_counted_loop()) return true; // Ignore various kinds of broken loops
2773 
2774   // Do nothing special to pre- and post- loops
2775   if (cl->is_pre_loop() || cl->is_post_loop()) return true;
2776 
2777   // Compute loop trip count from profile data
2778   compute_profile_trip_cnt(phase);
2779 
2780   // Before attempting fancy unrolling, RCE or alignment, see if we want
2781   // to completely unroll this loop or do loop unswitching.
2782   if (cl->is_normal_loop()) {
2783     if (should_unswitch) {
2784       phase->do_unswitching(this, old_new);
2785       return true;
2786     }
2787     bool should_maximally_unroll =  policy_maximally_unroll(phase);
2788     if (should_maximally_unroll) {
2789       // Here we did some unrolling and peeling.  Eventually we will
2790       // completely unroll this loop and it will no longer be a loop.
2791       phase->do_maximally_unroll(this,old_new);
2792       return true;
2793     }
2794   }
2795 
2796   // Skip next optimizations if running low on nodes. Note that
2797   // policy_unswitching and policy_maximally_unroll have this check.
2798   int nodes_left = phase->C->max_node_limit() - phase->C->live_nodes();
2799   if ((int)(2 * _body.size()) > nodes_left) {
2800     return true;
2801   }
2802 
2803   // Counted loops may be peeled, may need some iterations run up
2804   // front for RCE, and may want to align loop refs to a cache
2805   // line.  Thus we clone a full loop up front whose trip count is
2806   // at least 1 (if peeling), but may be several more.
2807 
2808   // The main loop will start cache-line aligned with at least 1
2809   // iteration of the unrolled body (zero-trip test required) and
2810   // will have some range checks removed.
2811 
2812   // A post-loop will finish any odd iterations (leftover after
2813   // unrolling), plus any needed for RCE purposes.
2814 
2815   bool should_unroll = policy_unroll(phase);
2816 
2817   bool should_rce = policy_range_check(phase);
2818 
2819   bool should_align = policy_align(phase);
2820 
2821   // If not RCE'ing (iteration splitting) or Aligning, then we do not
2822   // need a pre-loop.  We may still need to peel an initial iteration but
2823   // we will not be needing an unknown number of pre-iterations.
2824   //
2825   // Basically, if may_rce_align reports FALSE first time through,
2826   // we will not be able to later do RCE or Aligning on this loop.
2827   bool may_rce_align = !policy_peel_only(phase) || should_rce || should_align;
2828 
2829   // If we have any of these conditions (RCE, alignment, unrolling) met, then
2830   // we switch to the pre-/main-/post-loop model.  This model also covers
2831   // peeling.
2832   if (should_rce || should_align || should_unroll) {
2833     if (cl->is_normal_loop())  // Convert to 'pre/main/post' loops
2834       phase->insert_pre_post_loops(this,old_new, !may_rce_align);
2835 
2836     // Adjust the pre- and main-loop limits to let the pre and post loops run
2837     // with full checks, but the main-loop with no checks.  Remove said
2838     // checks from the main body.
2839     if (should_rce) {
2840       if (phase->do_range_check(this, old_new) != 0) {
2841         cl->mark_has_range_checks();
2842       }
2843     } else if (PostLoopMultiversioning) {
2844       phase->has_range_checks(this);
2845     }
2846 
2847     if (should_unroll && !should_peel && PostLoopMultiversioning) {
2848       // Try to setup multiversioning on main loops before they are unrolled
2849       if (cl->is_main_loop() && (cl->unrolled_count() == 1)) {
2850         phase->insert_scalar_rced_post_loop(this, old_new);
2851       }
2852     }
2853 
2854     // Double loop body for unrolling.  Adjust the minimum-trip test (will do
2855     // twice as many iterations as before) and the main body limit (only do
2856     // an even number of trips).  If we are peeling, we might enable some RCE
2857     // and we'd rather unroll the post-RCE'd loop SO... do not unroll if
2858     // peeling.
2859     if (should_unroll && !should_peel) {
2860       if (SuperWordLoopUnrollAnalysis) {
2861         phase->insert_vector_post_loop(this, old_new);
2862       }
2863       phase->do_unroll(this, old_new, true);
2864     }
2865 
2866     // Adjust the pre-loop limits to align the main body
2867     // iterations.
2868     if (should_align)
2869       Unimplemented();
2870 
2871   } else {                      // Else we have an unchanged counted loop
2872     if (should_peel)           // Might want to peel but do nothing else
2873       phase->do_peeling(this,old_new);
2874   }
2875   return true;
2876 }
2877 
2878 
2879 //=============================================================================
2880 //------------------------------iteration_split--------------------------------
2881 bool IdealLoopTree::iteration_split( PhaseIdealLoop *phase, Node_List &old_new ) {
2882   // Recursively iteration split nested loops
2883   if (_child && !_child->iteration_split(phase, old_new))
2884     return false;
2885 
2886   // Clean out prior deadwood
2887   DCE_loop_body();
2888 
2889 
2890   // Look for loop-exit tests with my 50/50 guesses from the Parsing stage.
2891   // Replace with a 1-in-10 exit guess.
2892   if (_parent /*not the root loop*/ &&
2893       !_irreducible &&
2894       // Also ignore the occasional dead backedge
2895       !tail()->is_top()) {
2896     adjust_loop_exit_prob(phase);
2897   }
2898 
2899   // Gate unrolling, RCE and peeling efforts.
2900   if (!_child &&                // If not an inner loop, do not split
2901       !_irreducible &&
2902       _allow_optimizations &&
2903       !tail()->is_top()) {     // Also ignore the occasional dead backedge
2904     if (!_has_call) {
2905         if (!iteration_split_impl(phase, old_new)) {
2906           return false;
2907         }
2908     } else if (policy_unswitching(phase)) {
2909       phase->do_unswitching(this, old_new);
2910     }
2911   }
2912 
2913   // Minor offset re-organization to remove loop-fallout uses of
2914   // trip counter when there was no major reshaping.
2915   phase->reorg_offsets(this);
2916 
2917   if (_next && !_next->iteration_split(phase, old_new))
2918     return false;
2919   return true;
2920 }
2921 
2922 
2923 //=============================================================================
2924 // Process all the loops in the loop tree and replace any fill
2925 // patterns with an intrinsic version.
2926 bool PhaseIdealLoop::do_intrinsify_fill() {
2927   bool changed = false;
2928   for (LoopTreeIterator iter(_ltree_root); !iter.done(); iter.next()) {
2929     IdealLoopTree* lpt = iter.current();
2930     changed |= intrinsify_fill(lpt);
2931   }
2932   return changed;
2933 }
2934 
2935 
2936 // Examine an inner loop looking for a a single store of an invariant
2937 // value in a unit stride loop,
2938 bool PhaseIdealLoop::match_fill_loop(IdealLoopTree* lpt, Node*& store, Node*& store_value,
2939                                      Node*& shift, Node*& con) {
2940   const char* msg = NULL;
2941   Node* msg_node = NULL;
2942 
2943   store_value = NULL;
2944   con = NULL;
2945   shift = NULL;
2946 
2947   // Process the loop looking for stores.  If there are multiple
2948   // stores or extra control flow give at this point.
2949   CountedLoopNode* head = lpt->_head->as_CountedLoop();
2950   for (uint i = 0; msg == NULL && i < lpt->_body.size(); i++) {
2951     Node* n = lpt->_body.at(i);
2952     if (n->outcnt() == 0) continue; // Ignore dead
2953     if (n->is_Store()) {
2954       if (store != NULL) {
2955         msg = "multiple stores";
2956         break;
2957       }
2958       int opc = n->Opcode();
2959       if (opc == Op_StoreP || opc == Op_StoreN || opc == Op_StoreNKlass || opc == Op_StoreCM) {
2960         msg = "oop fills not handled";
2961         break;
2962       }
2963       Node* value = n->in(MemNode::ValueIn);
2964       if (!lpt->is_invariant(value)) {
2965         msg  = "variant store value";
2966       } else if (!_igvn.type(n->in(MemNode::Address))->isa_aryptr()) {
2967         msg = "not array address";
2968       }
2969       store = n;
2970       store_value = value;
2971     } else if (n->is_If() && n != head->loopexit_or_null()) {
2972       msg = "extra control flow";
2973       msg_node = n;
2974     }
2975   }
2976 
2977   if (store == NULL) {
2978     // No store in loop
2979     return false;
2980   }
2981 
2982   if (msg == NULL && head->stride_con() != 1) {
2983     // could handle negative strides too
2984     if (head->stride_con() < 0) {
2985       msg = "negative stride";
2986     } else {
2987       msg = "non-unit stride";
2988     }
2989   }
2990 
2991   if (msg == NULL && !store->in(MemNode::Address)->is_AddP()) {
2992     msg = "can't handle store address";
2993     msg_node = store->in(MemNode::Address);
2994   }
2995 
2996   if (msg == NULL &&
2997       (!store->in(MemNode::Memory)->is_Phi() ||
2998        store->in(MemNode::Memory)->in(LoopNode::LoopBackControl) != store)) {
2999     msg = "store memory isn't proper phi";
3000     msg_node = store->in(MemNode::Memory);
3001   }
3002 
3003   // Make sure there is an appropriate fill routine
3004   BasicType t = store->as_Mem()->memory_type();
3005   const char* fill_name;
3006   if (msg == NULL &&
3007       StubRoutines::select_fill_function(t, false, fill_name) == NULL) {
3008     msg = "unsupported store";
3009     msg_node = store;
3010   }
3011 
3012   if (msg != NULL) {
3013 #ifndef PRODUCT
3014     if (TraceOptimizeFill) {
3015       tty->print_cr("not fill intrinsic candidate: %s", msg);
3016       if (msg_node != NULL) msg_node->dump();
3017     }
3018 #endif
3019     return false;
3020   }
3021 
3022   // Make sure the address expression can be handled.  It should be
3023   // head->phi * elsize + con.  head->phi might have a ConvI2L(CastII()).
3024   Node* elements[4];
3025   Node* cast = NULL;
3026   Node* conv = NULL;
3027   bool found_index = false;
3028   int count = store->in(MemNode::Address)->as_AddP()->unpack_offsets(elements, ARRAY_SIZE(elements));
3029   for (int e = 0; e < count; e++) {
3030     Node* n = elements[e];
3031     if (n->is_Con() && con == NULL) {
3032       con = n;
3033     } else if (n->Opcode() == Op_LShiftX && shift == NULL) {
3034       Node* value = n->in(1);
3035 #ifdef _LP64
3036       if (value->Opcode() == Op_ConvI2L) {
3037         conv = value;
3038         value = value->in(1);
3039       }
3040       if (value->Opcode() == Op_CastII &&
3041           value->as_CastII()->has_range_check()) {
3042         // Skip range check dependent CastII nodes
3043         cast = value;
3044         value = value->in(1);
3045       }
3046 #endif
3047       if (value != head->phi()) {
3048         msg = "unhandled shift in address";
3049       } else {
3050         if (type2aelembytes(store->as_Mem()->memory_type(), true) != (1 << n->in(2)->get_int())) {
3051           msg = "scale doesn't match";
3052         } else {
3053           found_index = true;
3054           shift = n;
3055         }
3056       }
3057     } else if (n->Opcode() == Op_ConvI2L && conv == NULL) {
3058       conv = n;
3059       n = n->in(1);
3060       if (n->Opcode() == Op_CastII &&
3061           n->as_CastII()->has_range_check()) {
3062         // Skip range check dependent CastII nodes
3063         cast = n;
3064         n = n->in(1);
3065       }
3066       if (n == head->phi()) {
3067         found_index = true;
3068       } else {
3069         msg = "unhandled input to ConvI2L";
3070       }
3071     } else if (n == head->phi()) {
3072       // no shift, check below for allowed cases
3073       found_index = true;
3074     } else {
3075       msg = "unhandled node in address";
3076       msg_node = n;
3077     }
3078   }
3079 
3080   if (count == -1) {
3081     msg = "malformed address expression";
3082     msg_node = store;
3083   }
3084 
3085   if (!found_index) {
3086     msg = "missing use of index";
3087   }
3088 
3089   // byte sized items won't have a shift
3090   if (msg == NULL && shift == NULL && t != T_BYTE && t != T_BOOLEAN) {
3091     msg = "can't find shift";
3092     msg_node = store;
3093   }
3094 
3095   if (msg != NULL) {
3096 #ifndef PRODUCT
3097     if (TraceOptimizeFill) {
3098       tty->print_cr("not fill intrinsic: %s", msg);
3099       if (msg_node != NULL) msg_node->dump();
3100     }
3101 #endif
3102     return false;
3103   }
3104 
3105   // No make sure all the other nodes in the loop can be handled
3106   VectorSet ok(Thread::current()->resource_area());
3107 
3108   // store related values are ok
3109   ok.set(store->_idx);
3110   ok.set(store->in(MemNode::Memory)->_idx);
3111 
3112   CountedLoopEndNode* loop_exit = head->loopexit();
3113 
3114   // Loop structure is ok
3115   ok.set(head->_idx);
3116   ok.set(loop_exit->_idx);
3117   ok.set(head->phi()->_idx);
3118   ok.set(head->incr()->_idx);
3119   ok.set(loop_exit->cmp_node()->_idx);
3120   ok.set(loop_exit->in(1)->_idx);
3121 
3122   // Address elements are ok
3123   if (con)   ok.set(con->_idx);
3124   if (shift) ok.set(shift->_idx);
3125   if (cast)  ok.set(cast->_idx);
3126   if (conv)  ok.set(conv->_idx);
3127 
3128   for (uint i = 0; msg == NULL && i < lpt->_body.size(); i++) {
3129     Node* n = lpt->_body.at(i);
3130     if (n->outcnt() == 0) continue; // Ignore dead
3131     if (ok.test(n->_idx)) continue;
3132     // Backedge projection is ok
3133     if (n->is_IfTrue() && n->in(0) == loop_exit) continue;
3134     if (!n->is_AddP()) {
3135       msg = "unhandled node";
3136       msg_node = n;
3137       break;
3138     }
3139   }
3140 
3141   // Make sure no unexpected values are used outside the loop
3142   for (uint i = 0; msg == NULL && i < lpt->_body.size(); i++) {
3143     Node* n = lpt->_body.at(i);
3144     // These values can be replaced with other nodes if they are used
3145     // outside the loop.
3146     if (n == store || n == loop_exit || n == head->incr() || n == store->in(MemNode::Memory)) continue;
3147     for (SimpleDUIterator iter(n); iter.has_next(); iter.next()) {
3148       Node* use = iter.get();
3149       if (!lpt->_body.contains(use)) {
3150         msg = "node is used outside loop";
3151         // lpt->_body.dump();
3152         msg_node = n;
3153         break;
3154       }
3155     }
3156   }
3157 
3158 #ifdef ASSERT
3159   if (TraceOptimizeFill) {
3160     if (msg != NULL) {
3161       tty->print_cr("no fill intrinsic: %s", msg);
3162       if (msg_node != NULL) msg_node->dump();
3163     } else {
3164       tty->print_cr("fill intrinsic for:");
3165     }
3166     store->dump();
3167     if (Verbose) {
3168       lpt->_body.dump();
3169     }
3170   }
3171 #endif
3172 
3173   return msg == NULL;
3174 }
3175 
3176 
3177 
3178 bool PhaseIdealLoop::intrinsify_fill(IdealLoopTree* lpt) {
3179   // Only for counted inner loops
3180   if (!lpt->is_counted() || !lpt->is_inner()) {
3181     return false;
3182   }
3183 
3184   // Must have constant stride
3185   CountedLoopNode* head = lpt->_head->as_CountedLoop();
3186   if (!head->is_valid_counted_loop() || !head->is_normal_loop()) {
3187     return false;
3188   }
3189 
3190   head->verify_strip_mined(1);
3191 
3192   // Check that the body only contains a store of a loop invariant
3193   // value that is indexed by the loop phi.
3194   Node* store = NULL;
3195   Node* store_value = NULL;
3196   Node* shift = NULL;
3197   Node* offset = NULL;
3198   if (!match_fill_loop(lpt, store, store_value, shift, offset)) {
3199     return false;
3200   }
3201 
3202   Node* exit = head->loopexit()->proj_out_or_null(0);
3203   if (exit == NULL) {
3204     return false;
3205   }
3206 
3207 #ifndef PRODUCT
3208   if (TraceLoopOpts) {
3209     tty->print("ArrayFill    ");
3210     lpt->dump_head();
3211   }
3212 #endif
3213 
3214   // Now replace the whole loop body by a call to a fill routine that
3215   // covers the same region as the loop.
3216   Node* base = store->in(MemNode::Address)->as_AddP()->in(AddPNode::Base);
3217 
3218   // Build an expression for the beginning of the copy region
3219   Node* index = head->init_trip();
3220 #ifdef _LP64
3221   index = new ConvI2LNode(index);
3222   _igvn.register_new_node_with_optimizer(index);
3223 #endif
3224   if (shift != NULL) {
3225     // byte arrays don't require a shift but others do.
3226     index = new LShiftXNode(index, shift->in(2));
3227     _igvn.register_new_node_with_optimizer(index);
3228   }
3229   index = new AddPNode(base, base, index);
3230   _igvn.register_new_node_with_optimizer(index);
3231   Node* from = new AddPNode(base, index, offset);
3232   _igvn.register_new_node_with_optimizer(from);
3233   // Compute the number of elements to copy
3234   Node* len = new SubINode(head->limit(), head->init_trip());
3235   _igvn.register_new_node_with_optimizer(len);
3236 
3237   BasicType t = store->as_Mem()->memory_type();
3238   bool aligned = false;
3239   if (offset != NULL && head->init_trip()->is_Con()) {
3240     int element_size = type2aelembytes(t);
3241     aligned = (offset->find_intptr_t_type()->get_con() + head->init_trip()->get_int() * element_size) % HeapWordSize == 0;
3242   }
3243 
3244   // Build a call to the fill routine
3245   const char* fill_name;
3246   address fill = StubRoutines::select_fill_function(t, aligned, fill_name);
3247   assert(fill != NULL, "what?");
3248 
3249   // Convert float/double to int/long for fill routines
3250   if (t == T_FLOAT) {
3251     store_value = new MoveF2INode(store_value);
3252     _igvn.register_new_node_with_optimizer(store_value);
3253   } else if (t == T_DOUBLE) {
3254     store_value = new MoveD2LNode(store_value);
3255     _igvn.register_new_node_with_optimizer(store_value);
3256   }
3257 
3258   Node* mem_phi = store->in(MemNode::Memory);
3259   Node* result_ctrl;
3260   Node* result_mem;
3261   const TypeFunc* call_type = OptoRuntime::array_fill_Type();
3262   CallLeafNode *call = new CallLeafNoFPNode(call_type, fill,
3263                                             fill_name, TypeAryPtr::get_array_body_type(t));
3264   uint cnt = 0;
3265   call->init_req(TypeFunc::Parms + cnt++, from);
3266   call->init_req(TypeFunc::Parms + cnt++, store_value);
3267 #ifdef _LP64
3268   len = new ConvI2LNode(len);
3269   _igvn.register_new_node_with_optimizer(len);
3270 #endif
3271   call->init_req(TypeFunc::Parms + cnt++, len);
3272 #ifdef _LP64
3273   call->init_req(TypeFunc::Parms + cnt++, C->top());
3274 #endif
3275   call->init_req(TypeFunc::Control,   head->init_control());
3276   call->init_req(TypeFunc::I_O,       C->top());       // Does no I/O.
3277   call->init_req(TypeFunc::Memory,    mem_phi->in(LoopNode::EntryControl));
3278   call->init_req(TypeFunc::ReturnAdr, C->start()->proj_out_or_null(TypeFunc::ReturnAdr));
3279   call->init_req(TypeFunc::FramePtr,  C->start()->proj_out_or_null(TypeFunc::FramePtr));
3280   _igvn.register_new_node_with_optimizer(call);
3281   result_ctrl = new ProjNode(call,TypeFunc::Control);
3282   _igvn.register_new_node_with_optimizer(result_ctrl);
3283   result_mem = new ProjNode(call,TypeFunc::Memory);
3284   _igvn.register_new_node_with_optimizer(result_mem);
3285 
3286 /* Disable following optimization until proper fix (add missing checks).
3287 
3288   // If this fill is tightly coupled to an allocation and overwrites
3289   // the whole body, allow it to take over the zeroing.
3290   AllocateNode* alloc = AllocateNode::Ideal_allocation(base, this);
3291   if (alloc != NULL && alloc->is_AllocateArray()) {
3292     Node* length = alloc->as_AllocateArray()->Ideal_length();
3293     if (head->limit() == length &&
3294         head->init_trip() == _igvn.intcon(0)) {
3295       if (TraceOptimizeFill) {
3296         tty->print_cr("Eliminated zeroing in allocation");
3297       }
3298       alloc->maybe_set_complete(&_igvn);
3299     } else {
3300 #ifdef ASSERT
3301       if (TraceOptimizeFill) {
3302         tty->print_cr("filling array but bounds don't match");
3303         alloc->dump();
3304         head->init_trip()->dump();
3305         head->limit()->dump();
3306         length->dump();
3307       }
3308 #endif
3309     }
3310   }
3311 */
3312 
3313   if (head->is_strip_mined()) {
3314     // Inner strip mined loop goes away so get rid of outer strip
3315     // mined loop
3316     Node* outer_sfpt = head->outer_safepoint();
3317     Node* in = outer_sfpt->in(0);
3318     Node* outer_out = head->outer_loop_exit();
3319     lazy_replace(outer_out, in);
3320     _igvn.replace_input_of(outer_sfpt, 0, C->top());
3321   }
3322 
3323   // Redirect the old control and memory edges that are outside the loop.
3324   // Sometimes the memory phi of the head is used as the outgoing
3325   // state of the loop.  It's safe in this case to replace it with the
3326   // result_mem.
3327   _igvn.replace_node(store->in(MemNode::Memory), result_mem);
3328   lazy_replace(exit, result_ctrl);
3329   _igvn.replace_node(store, result_mem);
3330   // Any uses the increment outside of the loop become the loop limit.
3331   _igvn.replace_node(head->incr(), head->limit());
3332 
3333   // Disconnect the head from the loop.
3334   for (uint i = 0; i < lpt->_body.size(); i++) {
3335     Node* n = lpt->_body.at(i);
3336     _igvn.replace_node(n, C->top());
3337   }
3338 
3339   return true;
3340 }