1 /*
   2  * Copyright (c) 2000, 2017, 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   guarantee(main_end != NULL, "no loop exit node");
1021   assert( main_end->outcnt() == 2, "1 true, 1 false path only" );
1022 
1023   Node *pre_header= main_head->in(LoopNode::EntryControl);
1024   Node *init      = main_head->init_trip();
1025   Node *incr      = main_end ->incr();
1026   Node *limit     = main_end ->limit();
1027   Node *stride    = main_end ->stride();
1028   Node *cmp       = main_end ->cmp_node();
1029   BoolTest::mask b_test = main_end->test_trip();
1030 
1031   // Need only 1 user of 'bol' because I will be hacking the loop bounds.
1032   Node *bol = main_end->in(CountedLoopEndNode::TestValue);
1033   if( bol->outcnt() != 1 ) {
1034     bol = bol->clone();
1035     register_new_node(bol,main_end->in(CountedLoopEndNode::TestControl));
1036     _igvn.replace_input_of(main_end, CountedLoopEndNode::TestValue, bol);
1037   }
1038   // Need only 1 user of 'cmp' because I will be hacking the loop bounds.
1039   if( cmp->outcnt() != 1 ) {
1040     cmp = cmp->clone();
1041     register_new_node(cmp,main_end->in(CountedLoopEndNode::TestControl));
1042     _igvn.replace_input_of(bol, 1, cmp);
1043   }
1044 
1045   // Add the post loop
1046   CountedLoopNode *post_head = NULL;
1047   Node *main_exit = insert_post_loop(loop, old_new, main_head, main_end, incr, limit, post_head);
1048 
1049   //------------------------------
1050   // Step B: Create Pre-Loop.
1051 
1052   // Step B1: Clone the loop body.  The clone becomes the pre-loop.  The main
1053   // loop pre-header illegally has 2 control users (old & new loops).
1054   LoopNode* outer_main_head = main_head;
1055   IdealLoopTree* outer_loop = loop;
1056   if (main_head->is_strip_mined()) {
1057     main_head->verify_strip_mined(1);
1058     outer_main_head = main_head->outer_loop();
1059     outer_loop = loop->_parent;
1060     assert(outer_loop->_head == outer_main_head, "broken loop tree");
1061   }
1062   uint dd_main_head = dom_depth(outer_main_head);
1063   clone_loop(loop, old_new, dd_main_head, ControlAroundStripMined);
1064   CountedLoopNode*    pre_head = old_new[main_head->_idx]->as_CountedLoop();
1065   CountedLoopEndNode* pre_end  = old_new[main_end ->_idx]->as_CountedLoopEnd();
1066   pre_head->set_pre_loop(main_head);
1067   Node *pre_incr = old_new[incr->_idx];
1068 
1069   // Reduce the pre-loop trip count.
1070   pre_end->_prob = PROB_FAIR;
1071 
1072   // Find the pre-loop normal exit.
1073   Node* pre_exit = pre_end->proj_out(false);
1074   assert( pre_exit->Opcode() == Op_IfFalse, "" );
1075   IfFalseNode *new_pre_exit = new IfFalseNode(pre_end);
1076   _igvn.register_new_node_with_optimizer( new_pre_exit );
1077   set_idom(new_pre_exit, pre_end, dd_main_head);
1078   set_loop(new_pre_exit, outer_loop->_parent);
1079 
1080   // Step B2: Build a zero-trip guard for the main-loop.  After leaving the
1081   // pre-loop, the main-loop may not execute at all.  Later in life this
1082   // zero-trip guard will become the minimum-trip guard when we unroll
1083   // the main-loop.
1084   Node *min_opaq = new Opaque1Node(C, limit);
1085   Node *min_cmp  = new CmpINode( pre_incr, min_opaq );
1086   Node *min_bol  = new BoolNode( min_cmp, b_test );
1087   register_new_node( min_opaq, new_pre_exit );
1088   register_new_node( min_cmp , new_pre_exit );
1089   register_new_node( min_bol , new_pre_exit );
1090 
1091   // Build the IfNode (assume the main-loop is executed always).
1092   IfNode *min_iff = new IfNode( new_pre_exit, min_bol, PROB_ALWAYS, COUNT_UNKNOWN );
1093   _igvn.register_new_node_with_optimizer( min_iff );
1094   set_idom(min_iff, new_pre_exit, dd_main_head);
1095   set_loop(min_iff, outer_loop->_parent);
1096 
1097   // Plug in the false-path, taken if we need to skip main-loop
1098   _igvn.hash_delete( pre_exit );
1099   pre_exit->set_req(0, min_iff);
1100   set_idom(pre_exit, min_iff, dd_main_head);
1101   set_idom(pre_exit->unique_ctrl_out(), min_iff, dd_main_head);
1102   // Make the true-path, must enter the main loop
1103   Node *min_taken = new IfTrueNode( min_iff );
1104   _igvn.register_new_node_with_optimizer( min_taken );
1105   set_idom(min_taken, min_iff, dd_main_head);
1106   set_loop(min_taken, outer_loop->_parent);
1107   // Plug in the true path
1108   _igvn.hash_delete(outer_main_head);
1109   outer_main_head->set_req(LoopNode::EntryControl, min_taken);
1110   set_idom(outer_main_head, min_taken, dd_main_head);
1111 
1112   Arena *a = Thread::current()->resource_area();
1113   VectorSet visited(a);
1114   Node_Stack clones(a, main_head->back_control()->outcnt());
1115   // Step B3: Make the fall-in values to the main-loop come from the
1116   // fall-out values of the pre-loop.
1117   for (DUIterator_Fast i2max, i2 = main_head->fast_outs(i2max); i2 < i2max; i2++) {
1118     Node* main_phi = main_head->fast_out(i2);
1119     if( main_phi->is_Phi() && main_phi->in(0) == main_head && main_phi->outcnt() > 0 ) {
1120       Node *pre_phi = old_new[main_phi->_idx];
1121       Node *fallpre  = clone_up_backedge_goo(pre_head->back_control(),
1122                                              main_head->skip_strip_mined()->in(LoopNode::EntryControl),
1123                                              pre_phi->in(LoopNode::LoopBackControl),
1124                                              visited, clones);
1125       _igvn.hash_delete(main_phi);
1126       main_phi->set_req( LoopNode::EntryControl, fallpre );
1127     }
1128   }
1129 
1130   // Nodes inside the loop may be control dependent on a predicate
1131   // that was moved before the preloop. If the back branch of the main
1132   // or post loops becomes dead, those nodes won't be dependent on the
1133   // test that guards that loop nest anymore which could lead to an
1134   // incorrect array access because it executes independently of the
1135   // test that was guarding the loop nest. We add a special CastII on
1136   // the if branch that enters the loop, between the input induction
1137   // variable value and the induction variable Phi to preserve correct
1138   // dependencies.
1139 
1140   // CastII for the main loop:
1141   bool inserted = cast_incr_before_loop( pre_incr, min_taken, main_head );
1142   assert(inserted, "no castII inserted");
1143 
1144   // Step B4: Shorten the pre-loop to run only 1 iteration (for now).
1145   // RCE and alignment may change this later.
1146   Node *cmp_end = pre_end->cmp_node();
1147   assert( cmp_end->in(2) == limit, "" );
1148   Node *pre_limit = new AddINode( init, stride );
1149 
1150   // Save the original loop limit in this Opaque1 node for
1151   // use by range check elimination.
1152   Node *pre_opaq  = new Opaque1Node(C, pre_limit, limit);
1153 
1154   register_new_node( pre_limit, pre_head->in(0) );
1155   register_new_node( pre_opaq , pre_head->in(0) );
1156 
1157   // Since no other users of pre-loop compare, I can hack limit directly
1158   assert( cmp_end->outcnt() == 1, "no other users" );
1159   _igvn.hash_delete(cmp_end);
1160   cmp_end->set_req(2, peel_only ? pre_limit : pre_opaq);
1161 
1162   // Special case for not-equal loop bounds:
1163   // Change pre loop test, main loop test, and the
1164   // main loop guard test to use lt or gt depending on stride
1165   // direction:
1166   // positive stride use <
1167   // negative stride use >
1168   //
1169   // not-equal test is kept for post loop to handle case
1170   // when init > limit when stride > 0 (and reverse).
1171 
1172   if (pre_end->in(CountedLoopEndNode::TestValue)->as_Bool()->_test._test == BoolTest::ne) {
1173 
1174     BoolTest::mask new_test = (main_end->stride_con() > 0) ? BoolTest::lt : BoolTest::gt;
1175     // Modify pre loop end condition
1176     Node* pre_bol = pre_end->in(CountedLoopEndNode::TestValue)->as_Bool();
1177     BoolNode* new_bol0 = new BoolNode(pre_bol->in(1), new_test);
1178     register_new_node( new_bol0, pre_head->in(0) );
1179     _igvn.replace_input_of(pre_end, CountedLoopEndNode::TestValue, new_bol0);
1180     // Modify main loop guard condition
1181     assert(min_iff->in(CountedLoopEndNode::TestValue) == min_bol, "guard okay");
1182     BoolNode* new_bol1 = new BoolNode(min_bol->in(1), new_test);
1183     register_new_node( new_bol1, new_pre_exit );
1184     _igvn.hash_delete(min_iff);
1185     min_iff->set_req(CountedLoopEndNode::TestValue, new_bol1);
1186     // Modify main loop end condition
1187     BoolNode* main_bol = main_end->in(CountedLoopEndNode::TestValue)->as_Bool();
1188     BoolNode* new_bol2 = new BoolNode(main_bol->in(1), new_test);
1189     register_new_node( new_bol2, main_end->in(CountedLoopEndNode::TestControl) );
1190     _igvn.replace_input_of(main_end, CountedLoopEndNode::TestValue, new_bol2);
1191   }
1192 
1193   // Flag main loop
1194   main_head->set_main_loop();
1195   if( peel_only ) main_head->set_main_no_pre_loop();
1196 
1197   // Subtract a trip count for the pre-loop.
1198   main_head->set_trip_count(main_head->trip_count() - 1);
1199 
1200   // It's difficult to be precise about the trip-counts
1201   // for the pre/post loops.  They are usually very short,
1202   // so guess that 4 trips is a reasonable value.
1203   post_head->set_profile_trip_cnt(4.0);
1204   pre_head->set_profile_trip_cnt(4.0);
1205 
1206   // Now force out all loop-invariant dominating tests.  The optimizer
1207   // finds some, but we _know_ they are all useless.
1208   peeled_dom_test_elim(loop,old_new);
1209   loop->record_for_igvn();
1210 }
1211 
1212 //------------------------------insert_vector_post_loop------------------------
1213 // Insert a copy of the atomic unrolled vectorized main loop as a post loop,
1214 // unroll_policy has already informed us that more unrolling is about to happen to
1215 // the main loop.  The resultant post loop will serve as a vectorized drain loop.
1216 void PhaseIdealLoop::insert_vector_post_loop(IdealLoopTree *loop, Node_List &old_new) {
1217   if (!loop->_head->is_CountedLoop()) return;
1218 
1219   CountedLoopNode *cl = loop->_head->as_CountedLoop();
1220 
1221   // only process vectorized main loops
1222   if (!cl->is_vectorized_loop() || !cl->is_main_loop()) return;
1223 
1224   int slp_max_unroll_factor = cl->slp_max_unroll();
1225   int cur_unroll = cl->unrolled_count();
1226 
1227   if (slp_max_unroll_factor == 0) return;
1228 
1229   // only process atomic unroll vector loops (not super unrolled after vectorization)
1230   if (cur_unroll != slp_max_unroll_factor) return;
1231 
1232   // we only ever process this one time
1233   if (cl->has_atomic_post_loop()) return;
1234 
1235 #ifndef PRODUCT
1236   if (TraceLoopOpts) {
1237     tty->print("PostVector  ");
1238     loop->dump_head();
1239   }
1240 #endif
1241   C->set_major_progress();
1242 
1243   // Find common pieces of the loop being guarded with pre & post loops
1244   CountedLoopNode *main_head = loop->_head->as_CountedLoop();
1245   CountedLoopEndNode *main_end = main_head->loopexit();
1246   guarantee(main_end != NULL, "no loop exit node");
1247   // diagnostic to show loop end is not properly formed
1248   assert(main_end->outcnt() == 2, "1 true, 1 false path only");
1249 
1250   // mark this loop as processed
1251   main_head->mark_has_atomic_post_loop();
1252 
1253   Node *incr = main_end->incr();
1254   Node *limit = main_end->limit();
1255 
1256   // In this case we throw away the result as we are not using it to connect anything else.
1257   CountedLoopNode *post_head = NULL;
1258   insert_post_loop(loop, old_new, main_head, main_end, incr, limit, post_head);
1259 
1260   // It's difficult to be precise about the trip-counts
1261   // for post loops.  They are usually very short,
1262   // so guess that unit vector trips is a reasonable value.
1263   post_head->set_profile_trip_cnt(cur_unroll);
1264 
1265   // Now force out all loop-invariant dominating tests.  The optimizer
1266   // finds some, but we _know_ they are all useless.
1267   peeled_dom_test_elim(loop, old_new);
1268   loop->record_for_igvn();
1269 }
1270 
1271 
1272 //-------------------------insert_scalar_rced_post_loop------------------------
1273 // Insert a copy of the rce'd main loop as a post loop,
1274 // We have not unrolled the main loop, so this is the right time to inject this.
1275 // Later we will examine the partner of this post loop pair which still has range checks
1276 // to see inject code which tests at runtime if the range checks are applicable.
1277 void PhaseIdealLoop::insert_scalar_rced_post_loop(IdealLoopTree *loop, Node_List &old_new) {
1278   if (!loop->_head->is_CountedLoop()) return;
1279 
1280   CountedLoopNode *cl = loop->_head->as_CountedLoop();
1281 
1282   // only process RCE'd main loops
1283   if (!cl->is_main_loop() || cl->range_checks_present()) return;
1284 
1285 #ifndef PRODUCT
1286   if (TraceLoopOpts) {
1287     tty->print("PostScalarRce  ");
1288     loop->dump_head();
1289   }
1290 #endif
1291   C->set_major_progress();
1292 
1293   // Find common pieces of the loop being guarded with pre & post loops
1294   CountedLoopNode *main_head = loop->_head->as_CountedLoop();
1295   CountedLoopEndNode *main_end = main_head->loopexit();
1296   guarantee(main_end != NULL, "no loop exit node");
1297   // diagnostic to show loop end is not properly formed
1298   assert(main_end->outcnt() == 2, "1 true, 1 false path only");
1299 
1300   Node *incr = main_end->incr();
1301   Node *limit = main_end->limit();
1302 
1303   // In this case we throw away the result as we are not using it to connect anything else.
1304   CountedLoopNode *post_head = NULL;
1305   insert_post_loop(loop, old_new, main_head, main_end, incr, limit, post_head);
1306 
1307   // It's difficult to be precise about the trip-counts
1308   // for post loops.  They are usually very short,
1309   // so guess that unit vector trips is a reasonable value.
1310   post_head->set_profile_trip_cnt(4.0);
1311   post_head->set_is_rce_post_loop();
1312 
1313   // Now force out all loop-invariant dominating tests.  The optimizer
1314   // finds some, but we _know_ they are all useless.
1315   peeled_dom_test_elim(loop, old_new);
1316   loop->record_for_igvn();
1317 }
1318 
1319 
1320 //------------------------------insert_post_loop-------------------------------
1321 // Insert post loops.  Add a post loop to the given loop passed.
1322 Node *PhaseIdealLoop::insert_post_loop(IdealLoopTree *loop, Node_List &old_new,
1323                                        CountedLoopNode *main_head, CountedLoopEndNode *main_end,
1324                                        Node *incr, Node *limit, CountedLoopNode *&post_head) {
1325   IfNode* outer_main_end = main_end;
1326   IdealLoopTree* outer_loop = loop;
1327   if (main_head->is_strip_mined()) {
1328     main_head->verify_strip_mined(1);
1329     outer_main_end = main_head->outer_loop_end();
1330     outer_loop = loop->_parent;
1331     assert(outer_loop->_head == main_head->in(LoopNode::EntryControl), "broken loop tree");
1332   }
1333 
1334   //------------------------------
1335   // Step A: Create a new post-Loop.
1336   Node* main_exit = outer_main_end->proj_out(false);
1337   assert(main_exit->Opcode() == Op_IfFalse, "");
1338   int dd_main_exit = dom_depth(main_exit);
1339 
1340   // Step A1: Clone the loop body of main. The clone becomes the post-loop.
1341   // The main loop pre-header illegally has 2 control users (old & new loops).
1342   clone_loop(loop, old_new, dd_main_exit, ControlAroundStripMined);
1343   assert(old_new[main_end->_idx]->Opcode() == Op_CountedLoopEnd, "");
1344   post_head = old_new[main_head->_idx]->as_CountedLoop();
1345   post_head->set_normal_loop();
1346   post_head->set_post_loop(main_head);
1347 
1348   // Reduce the post-loop trip count.
1349   CountedLoopEndNode* post_end = old_new[main_end->_idx]->as_CountedLoopEnd();
1350   post_end->_prob = PROB_FAIR;
1351 
1352   // Build the main-loop normal exit.
1353   IfFalseNode *new_main_exit = new IfFalseNode(outer_main_end);
1354   _igvn.register_new_node_with_optimizer(new_main_exit);
1355   set_idom(new_main_exit, outer_main_end, dd_main_exit);
1356   set_loop(new_main_exit, outer_loop->_parent);
1357 
1358   // Step A2: Build a zero-trip guard for the post-loop.  After leaving the
1359   // main-loop, the post-loop may not execute at all.  We 'opaque' the incr
1360   // (the previous loop trip-counter exit value) because we will be changing
1361   // the exit value (via additional unrolling) so we cannot constant-fold away the zero
1362   // trip guard until all unrolling is done.
1363   Node *zer_opaq = new Opaque1Node(C, incr);
1364   Node *zer_cmp = new CmpINode(zer_opaq, limit);
1365   Node *zer_bol = new BoolNode(zer_cmp, main_end->test_trip());
1366   register_new_node(zer_opaq, new_main_exit);
1367   register_new_node(zer_cmp, new_main_exit);
1368   register_new_node(zer_bol, new_main_exit);
1369 
1370   // Build the IfNode
1371   IfNode *zer_iff = new IfNode(new_main_exit, zer_bol, PROB_FAIR, COUNT_UNKNOWN);
1372   _igvn.register_new_node_with_optimizer(zer_iff);
1373   set_idom(zer_iff, new_main_exit, dd_main_exit);
1374   set_loop(zer_iff, outer_loop->_parent);
1375 
1376   // Plug in the false-path, taken if we need to skip this post-loop
1377   _igvn.replace_input_of(main_exit, 0, zer_iff);
1378   set_idom(main_exit, zer_iff, dd_main_exit);
1379   set_idom(main_exit->unique_out(), zer_iff, dd_main_exit);
1380   // Make the true-path, must enter this post loop
1381   Node *zer_taken = new IfTrueNode(zer_iff);
1382   _igvn.register_new_node_with_optimizer(zer_taken);
1383   set_idom(zer_taken, zer_iff, dd_main_exit);
1384   set_loop(zer_taken, outer_loop->_parent);
1385   // Plug in the true path
1386   _igvn.hash_delete(post_head);
1387   post_head->set_req(LoopNode::EntryControl, zer_taken);
1388   set_idom(post_head, zer_taken, dd_main_exit);
1389 
1390   Arena *a = Thread::current()->resource_area();
1391   VectorSet visited(a);
1392   Node_Stack clones(a, main_head->back_control()->outcnt());
1393   // Step A3: Make the fall-in values to the post-loop come from the
1394   // fall-out values of the main-loop.
1395   for (DUIterator_Fast imax, i = main_head->fast_outs(imax); i < imax; i++) {
1396     Node* main_phi = main_head->fast_out(i);
1397     if (main_phi->is_Phi() && main_phi->in(0) == main_head && main_phi->outcnt() >0) {
1398       Node *cur_phi = old_new[main_phi->_idx];
1399       Node *fallnew = clone_up_backedge_goo(main_head->back_control(),
1400                                             post_head->init_control(),
1401                                             main_phi->in(LoopNode::LoopBackControl),
1402                                             visited, clones);
1403       _igvn.hash_delete(cur_phi);
1404       cur_phi->set_req(LoopNode::EntryControl, fallnew);
1405     }
1406   }
1407 
1408   // CastII for the new post loop:
1409   bool inserted = cast_incr_before_loop(zer_opaq->in(1), zer_taken, post_head);
1410   assert(inserted, "no castII inserted");
1411 
1412   return new_main_exit;
1413 }
1414 
1415 //------------------------------is_invariant-----------------------------
1416 // Return true if n is invariant
1417 bool IdealLoopTree::is_invariant(Node* n) const {
1418   Node *n_c = _phase->has_ctrl(n) ? _phase->get_ctrl(n) : n;
1419   if (n_c->is_top()) return false;
1420   return !is_member(_phase->get_loop(n_c));
1421 }
1422 
1423 
1424 //------------------------------do_unroll--------------------------------------
1425 // Unroll the loop body one step - make each trip do 2 iterations.
1426 void PhaseIdealLoop::do_unroll( IdealLoopTree *loop, Node_List &old_new, bool adjust_min_trip ) {
1427   assert(LoopUnrollLimit, "");
1428   CountedLoopNode *loop_head = loop->_head->as_CountedLoop();
1429   CountedLoopEndNode *loop_end = loop_head->loopexit();
1430   assert(loop_end, "");
1431 #ifndef PRODUCT
1432   if (PrintOpto && VerifyLoopOptimizations) {
1433     tty->print("Unrolling ");
1434     loop->dump_head();
1435   } else if (TraceLoopOpts) {
1436     if (loop_head->trip_count() < (uint)LoopUnrollLimit) {
1437       tty->print("Unroll %d(%2d) ", loop_head->unrolled_count()*2, loop_head->trip_count());
1438     } else {
1439       tty->print("Unroll %d     ", loop_head->unrolled_count()*2);
1440     }
1441     loop->dump_head();
1442   }
1443 
1444   if (C->do_vector_loop() && (PrintOpto && (VerifyLoopOptimizations || TraceLoopOpts))) {
1445     Arena* arena = Thread::current()->resource_area();
1446     Node_Stack stack(arena, C->live_nodes() >> 2);
1447     Node_List rpo_list;
1448     VectorSet visited(arena);
1449     visited.set(loop_head->_idx);
1450     rpo( loop_head, stack, visited, rpo_list );
1451     dump(loop, rpo_list.size(), rpo_list );
1452   }
1453 #endif
1454 
1455   // Remember loop node count before unrolling to detect
1456   // if rounds of unroll,optimize are making progress
1457   loop_head->set_node_count_before_unroll(loop->_body.size());
1458 
1459   Node *ctrl  = loop_head->skip_strip_mined()->in(LoopNode::EntryControl);
1460   Node *limit = loop_head->limit();
1461   Node *init  = loop_head->init_trip();
1462   Node *stride = loop_head->stride();
1463 
1464   Node *opaq = NULL;
1465   if (adjust_min_trip) {       // If not maximally unrolling, need adjustment
1466     // Search for zero-trip guard.
1467 
1468     // Check the shape of the graph at the loop entry. If an inappropriate
1469     // graph shape is encountered, the compiler bails out loop unrolling;
1470     // compilation of the method will still succeed.
1471     if (!is_canonical_loop_entry(loop_head)) {
1472       return;
1473     }
1474     opaq = ctrl->in(0)->in(1)->in(1)->in(2);
1475     // Zero-trip test uses an 'opaque' node which is not shared.
1476     assert(opaq->outcnt() == 1 && opaq->in(1) == limit, "");
1477   }
1478 
1479   C->set_major_progress();
1480 
1481   Node* new_limit = NULL;
1482   int stride_con = stride->get_int();
1483   int stride_p = (stride_con > 0) ? stride_con : -stride_con;
1484   uint old_trip_count = loop_head->trip_count();
1485   // Verify that unroll policy result is still valid.
1486   assert(old_trip_count > 1 &&
1487       (!adjust_min_trip || stride_p <= (1<<3)*loop_head->unrolled_count()), "sanity");
1488 
1489   // Adjust loop limit to keep valid iterations number after unroll.
1490   // Use (limit - stride) instead of (((limit - init)/stride) & (-2))*stride
1491   // which may overflow.
1492   if (!adjust_min_trip) {
1493     assert(old_trip_count > 1 && (old_trip_count & 1) == 0,
1494         "odd trip count for maximally unroll");
1495     // Don't need to adjust limit for maximally unroll since trip count is even.
1496   } else if (loop_head->has_exact_trip_count() && init->is_Con()) {
1497     // Loop's limit is constant. Loop's init could be constant when pre-loop
1498     // become peeled iteration.
1499     jlong init_con = init->get_int();
1500     // We can keep old loop limit if iterations count stays the same:
1501     //   old_trip_count == new_trip_count * 2
1502     // Note: since old_trip_count >= 2 then new_trip_count >= 1
1503     // so we also don't need to adjust zero trip test.
1504     jlong limit_con  = limit->get_int();
1505     // (stride_con*2) not overflow since stride_con <= 8.
1506     int new_stride_con = stride_con * 2;
1507     int stride_m    = new_stride_con - (stride_con > 0 ? 1 : -1);
1508     jlong trip_count = (limit_con - init_con + stride_m)/new_stride_con;
1509     // New trip count should satisfy next conditions.
1510     assert(trip_count > 0 && (julong)trip_count < (julong)max_juint/2, "sanity");
1511     uint new_trip_count = (uint)trip_count;
1512     adjust_min_trip = (old_trip_count != new_trip_count*2);
1513   }
1514 
1515   if (adjust_min_trip) {
1516     // Step 2: Adjust the trip limit if it is called for.
1517     // The adjustment amount is -stride. Need to make sure if the
1518     // adjustment underflows or overflows, then the main loop is skipped.
1519     Node* cmp = loop_end->cmp_node();
1520     assert(cmp->in(2) == limit, "sanity");
1521     assert(opaq != NULL && opaq->in(1) == limit, "sanity");
1522 
1523     // Verify that policy_unroll result is still valid.
1524     const TypeInt* limit_type = _igvn.type(limit)->is_int();
1525     assert(stride_con > 0 && ((limit_type->_hi - stride_con) < limit_type->_hi) ||
1526         stride_con < 0 && ((limit_type->_lo - stride_con) > limit_type->_lo), "sanity");
1527 
1528     if (limit->is_Con()) {
1529       // The check in policy_unroll and the assert above guarantee
1530       // no underflow if limit is constant.
1531       new_limit = _igvn.intcon(limit->get_int() - stride_con);
1532       set_ctrl(new_limit, C->root());
1533     } else {
1534       // Limit is not constant.
1535       if (loop_head->unrolled_count() == 1) { // only for first unroll
1536         // Separate limit by Opaque node in case it is an incremented
1537         // variable from previous loop to avoid using pre-incremented
1538         // value which could increase register pressure.
1539         // Otherwise reorg_offsets() optimization will create a separate
1540         // Opaque node for each use of trip-counter and as result
1541         // zero trip guard limit will be different from loop limit.
1542         assert(has_ctrl(opaq), "should have it");
1543         Node* opaq_ctrl = get_ctrl(opaq);
1544         limit = new Opaque2Node( C, limit );
1545         register_new_node( limit, opaq_ctrl );
1546       }
1547       if ((stride_con > 0 && (java_subtract(limit_type->_lo, stride_con) < limit_type->_lo)) ||
1548           (stride_con < 0 && (java_subtract(limit_type->_hi, stride_con) > limit_type->_hi))) {
1549         // No underflow.
1550         new_limit = new SubINode(limit, stride);
1551       } else {
1552         // (limit - stride) may underflow.
1553         // Clamp the adjustment value with MININT or MAXINT:
1554         //
1555         //   new_limit = limit-stride
1556         //   if (stride > 0)
1557         //     new_limit = (limit < new_limit) ? MININT : new_limit;
1558         //   else
1559         //     new_limit = (limit > new_limit) ? MAXINT : new_limit;
1560         //
1561         BoolTest::mask bt = loop_end->test_trip();
1562         assert(bt == BoolTest::lt || bt == BoolTest::gt, "canonical test is expected");
1563         Node* adj_max = _igvn.intcon((stride_con > 0) ? min_jint : max_jint);
1564         set_ctrl(adj_max, C->root());
1565         Node* old_limit = NULL;
1566         Node* adj_limit = NULL;
1567         Node* bol = limit->is_CMove() ? limit->in(CMoveNode::Condition) : NULL;
1568         if (loop_head->unrolled_count() > 1 &&
1569             limit->is_CMove() && limit->Opcode() == Op_CMoveI &&
1570             limit->in(CMoveNode::IfTrue) == adj_max &&
1571             bol->as_Bool()->_test._test == bt &&
1572             bol->in(1)->Opcode() == Op_CmpI &&
1573             bol->in(1)->in(2) == limit->in(CMoveNode::IfFalse)) {
1574           // Loop was unrolled before.
1575           // Optimize the limit to avoid nested CMove:
1576           // use original limit as old limit.
1577           old_limit = bol->in(1)->in(1);
1578           // Adjust previous adjusted limit.
1579           adj_limit = limit->in(CMoveNode::IfFalse);
1580           adj_limit = new SubINode(adj_limit, stride);
1581         } else {
1582           old_limit = limit;
1583           adj_limit = new SubINode(limit, stride);
1584         }
1585         assert(old_limit != NULL && adj_limit != NULL, "");
1586         register_new_node( adj_limit, ctrl ); // adjust amount
1587         Node* adj_cmp = new CmpINode(old_limit, adj_limit);
1588         register_new_node( adj_cmp, ctrl );
1589         Node* adj_bool = new BoolNode(adj_cmp, bt);
1590         register_new_node( adj_bool, ctrl );
1591         new_limit = new CMoveINode(adj_bool, adj_limit, adj_max, TypeInt::INT);
1592       }
1593       register_new_node(new_limit, ctrl);
1594     }
1595     assert(new_limit != NULL, "");
1596     // Replace in loop test.
1597     assert(loop_end->in(1)->in(1) == cmp, "sanity");
1598     if (cmp->outcnt() == 1 && loop_end->in(1)->outcnt() == 1) {
1599       // Don't need to create new test since only one user.
1600       _igvn.hash_delete(cmp);
1601       cmp->set_req(2, new_limit);
1602     } else {
1603       // Create new test since it is shared.
1604       Node* ctrl2 = loop_end->in(0);
1605       Node* cmp2  = cmp->clone();
1606       cmp2->set_req(2, new_limit);
1607       register_new_node(cmp2, ctrl2);
1608       Node* bol2 = loop_end->in(1)->clone();
1609       bol2->set_req(1, cmp2);
1610       register_new_node(bol2, ctrl2);
1611       _igvn.replace_input_of(loop_end, 1, bol2);
1612     }
1613     // Step 3: Find the min-trip test guaranteed before a 'main' loop.
1614     // Make it a 1-trip test (means at least 2 trips).
1615 
1616     // Guard test uses an 'opaque' node which is not shared.  Hence I
1617     // can edit it's inputs directly.  Hammer in the new limit for the
1618     // minimum-trip guard.
1619     assert(opaq->outcnt() == 1, "");
1620     _igvn.replace_input_of(opaq, 1, new_limit);
1621   }
1622 
1623   // Adjust max trip count. The trip count is intentionally rounded
1624   // down here (e.g. 15-> 7-> 3-> 1) because if we unwittingly over-unroll,
1625   // the main, unrolled, part of the loop will never execute as it is protected
1626   // by the min-trip test.  See bug 4834191 for a case where we over-unrolled
1627   // and later determined that part of the unrolled loop was dead.
1628   loop_head->set_trip_count(old_trip_count / 2);
1629 
1630   // Double the count of original iterations in the unrolled loop body.
1631   loop_head->double_unrolled_count();
1632 
1633   // ---------
1634   // Step 4: Clone the loop body.  Move it inside the loop.  This loop body
1635   // represents the odd iterations; since the loop trips an even number of
1636   // times its backedge is never taken.  Kill the backedge.
1637   uint dd = dom_depth(loop_head);
1638   clone_loop(loop, old_new, dd, IgnoreStripMined);
1639 
1640   // Make backedges of the clone equal to backedges of the original.
1641   // Make the fall-in from the original come from the fall-out of the clone.
1642   for (DUIterator_Fast jmax, j = loop_head->fast_outs(jmax); j < jmax; j++) {
1643     Node* phi = loop_head->fast_out(j);
1644     if( phi->is_Phi() && phi->in(0) == loop_head && phi->outcnt() > 0 ) {
1645       Node *newphi = old_new[phi->_idx];
1646       _igvn.hash_delete( phi );
1647       _igvn.hash_delete( newphi );
1648 
1649       phi   ->set_req(LoopNode::   EntryControl, newphi->in(LoopNode::LoopBackControl));
1650       newphi->set_req(LoopNode::LoopBackControl, phi   ->in(LoopNode::LoopBackControl));
1651       phi   ->set_req(LoopNode::LoopBackControl, C->top());
1652     }
1653   }
1654   Node *clone_head = old_new[loop_head->_idx];
1655   _igvn.hash_delete( clone_head );
1656   loop_head ->set_req(LoopNode::   EntryControl, clone_head->in(LoopNode::LoopBackControl));
1657   clone_head->set_req(LoopNode::LoopBackControl, loop_head ->in(LoopNode::LoopBackControl));
1658   loop_head ->set_req(LoopNode::LoopBackControl, C->top());
1659   loop->_head = clone_head;     // New loop header
1660 
1661   set_idom(loop_head,  loop_head ->in(LoopNode::EntryControl), dd);
1662   set_idom(clone_head, clone_head->in(LoopNode::EntryControl), dd);
1663 
1664   // Kill the clone's backedge
1665   Node *newcle = old_new[loop_end->_idx];
1666   _igvn.hash_delete( newcle );
1667   Node *one = _igvn.intcon(1);
1668   set_ctrl(one, C->root());
1669   newcle->set_req(1, one);
1670   // Force clone into same loop body
1671   uint max = loop->_body.size();
1672   for( uint k = 0; k < max; k++ ) {
1673     Node *old = loop->_body.at(k);
1674     Node *nnn = old_new[old->_idx];
1675     loop->_body.push(nnn);
1676     if (!has_ctrl(old))
1677       set_loop(nnn, loop);
1678   }
1679 
1680   loop->record_for_igvn();
1681   loop_head->clear_strip_mined();
1682 
1683 #ifndef PRODUCT
1684   if (C->do_vector_loop() && (PrintOpto && (VerifyLoopOptimizations || TraceLoopOpts))) {
1685     tty->print("\nnew loop after unroll\n");       loop->dump_head();
1686     for (uint i = 0; i < loop->_body.size(); i++) {
1687       loop->_body.at(i)->dump();
1688     }
1689     if(C->clone_map().is_debug()) {
1690       tty->print("\nCloneMap\n");
1691       Dict* dict = C->clone_map().dict();
1692       DictI i(dict);
1693       tty->print_cr("Dict@%p[%d] = ", dict, dict->Size());
1694       for (int ii = 0; i.test(); ++i, ++ii) {
1695         NodeCloneInfo cl((uint64_t)dict->operator[]((void*)i._key));
1696         tty->print("%d->%d:%d,", (int)(intptr_t)i._key, cl.idx(), cl.gen());
1697         if (ii % 10 == 9) {
1698           tty->print_cr(" ");
1699         }
1700       }
1701       tty->print_cr(" ");
1702     }
1703   }
1704 #endif
1705 
1706 }
1707 
1708 //------------------------------do_maximally_unroll----------------------------
1709 
1710 void PhaseIdealLoop::do_maximally_unroll( IdealLoopTree *loop, Node_List &old_new ) {
1711   CountedLoopNode *cl = loop->_head->as_CountedLoop();
1712   assert(cl->has_exact_trip_count(), "trip count is not exact");
1713   assert(cl->trip_count() > 0, "");
1714 #ifndef PRODUCT
1715   if (TraceLoopOpts) {
1716     tty->print("MaxUnroll  %d ", cl->trip_count());
1717     loop->dump_head();
1718   }
1719 #endif
1720 
1721   // If loop is tripping an odd number of times, peel odd iteration
1722   if ((cl->trip_count() & 1) == 1) {
1723     do_peeling(loop, old_new);
1724   }
1725 
1726   // Now its tripping an even number of times remaining.  Double loop body.
1727   // Do not adjust pre-guards; they are not needed and do not exist.
1728   if (cl->trip_count() > 0) {
1729     assert((cl->trip_count() & 1) == 0, "missed peeling");
1730     do_unroll(loop, old_new, false);
1731   }
1732 }
1733 
1734 void PhaseIdealLoop::mark_reductions(IdealLoopTree *loop) {
1735   if (SuperWordReductions == false) return;
1736 
1737   CountedLoopNode* loop_head = loop->_head->as_CountedLoop();
1738   if (loop_head->unrolled_count() > 1) {
1739     return;
1740   }
1741 
1742   Node* trip_phi = loop_head->phi();
1743   for (DUIterator_Fast imax, i = loop_head->fast_outs(imax); i < imax; i++) {
1744     Node* phi = loop_head->fast_out(i);
1745     if (phi->is_Phi() && phi->outcnt() > 0 && phi != trip_phi) {
1746       // For definitions which are loop inclusive and not tripcounts.
1747       Node* def_node = phi->in(LoopNode::LoopBackControl);
1748 
1749       if (def_node != NULL) {
1750         Node* n_ctrl = get_ctrl(def_node);
1751         if (n_ctrl != NULL && loop->is_member(get_loop(n_ctrl))) {
1752           // Now test it to see if it fits the standard pattern for a reduction operator.
1753           int opc = def_node->Opcode();
1754           if (opc != ReductionNode::opcode(opc, def_node->bottom_type()->basic_type())) {
1755             if (!def_node->is_reduction()) { // Not marked yet
1756               // To be a reduction, the arithmetic node must have the phi as input and provide a def to it
1757               bool ok = false;
1758               for (unsigned j = 1; j < def_node->req(); j++) {
1759                 Node* in = def_node->in(j);
1760                 if (in == phi) {
1761                   ok = true;
1762                   break;
1763                 }
1764               }
1765 
1766               // do nothing if we did not match the initial criteria
1767               if (ok == false) {
1768                 continue;
1769               }
1770 
1771               // The result of the reduction must not be used in the loop
1772               for (DUIterator_Fast imax, i = def_node->fast_outs(imax); i < imax && ok; i++) {
1773                 Node* u = def_node->fast_out(i);
1774                 if (!loop->is_member(get_loop(ctrl_or_self(u)))) {
1775                   continue;
1776                 }
1777                 if (u == phi) {
1778                   continue;
1779                 }
1780                 ok = false;
1781               }
1782 
1783               // iff the uses conform
1784               if (ok) {
1785                 def_node->add_flag(Node::Flag_is_reduction);
1786                 loop_head->mark_has_reductions();
1787               }
1788             }
1789           }
1790         }
1791       }
1792     }
1793   }
1794 }
1795 
1796 //------------------------------adjust_limit-----------------------------------
1797 // Helper function for add_constraint().
1798 Node* PhaseIdealLoop::adjust_limit(int stride_con, Node * scale, Node *offset, Node *rc_limit, Node *loop_limit, Node *pre_ctrl) {
1799   // Compute "I :: (limit-offset)/scale"
1800   Node *con = new SubINode(rc_limit, offset);
1801   register_new_node(con, pre_ctrl);
1802   Node *X = new DivINode(0, con, scale);
1803   register_new_node(X, pre_ctrl);
1804 
1805   // Adjust loop limit
1806   loop_limit = (stride_con > 0)
1807                ? (Node*)(new MinINode(loop_limit, X))
1808                : (Node*)(new MaxINode(loop_limit, X));
1809   register_new_node(loop_limit, pre_ctrl);
1810   return loop_limit;
1811 }
1812 
1813 //------------------------------add_constraint---------------------------------
1814 // Constrain the main loop iterations so the conditions:
1815 //    low_limit <= scale_con * I + offset  <  upper_limit
1816 // always holds true.  That is, either increase the number of iterations in
1817 // the pre-loop or the post-loop until the condition holds true in the main
1818 // loop.  Stride, scale, offset and limit are all loop invariant.  Further,
1819 // stride and scale are constants (offset and limit often are).
1820 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 ) {
1821   // For positive stride, the pre-loop limit always uses a MAX function
1822   // and the main loop a MIN function.  For negative stride these are
1823   // reversed.
1824 
1825   // Also for positive stride*scale the affine function is increasing, so the
1826   // pre-loop must check for underflow and the post-loop for overflow.
1827   // Negative stride*scale reverses this; pre-loop checks for overflow and
1828   // post-loop for underflow.
1829 
1830   Node *scale = _igvn.intcon(scale_con);
1831   set_ctrl(scale, C->root());
1832 
1833   if ((stride_con^scale_con) >= 0) { // Use XOR to avoid overflow
1834     // The overflow limit: scale*I+offset < upper_limit
1835     // For main-loop compute
1836     //   ( if (scale > 0) /* and stride > 0 */
1837     //       I < (upper_limit-offset)/scale
1838     //     else /* scale < 0 and stride < 0 */
1839     //       I > (upper_limit-offset)/scale
1840     //   )
1841     //
1842     // (upper_limit-offset) may overflow or underflow.
1843     // But it is fine since main loop will either have
1844     // less iterations or will be skipped in such case.
1845     *main_limit = adjust_limit(stride_con, scale, offset, upper_limit, *main_limit, pre_ctrl);
1846 
1847     // The underflow limit: low_limit <= scale*I+offset.
1848     // For pre-loop compute
1849     //   NOT(scale*I+offset >= low_limit)
1850     //   scale*I+offset < low_limit
1851     //   ( if (scale > 0) /* and stride > 0 */
1852     //       I < (low_limit-offset)/scale
1853     //     else /* scale < 0 and stride < 0 */
1854     //       I > (low_limit-offset)/scale
1855     //   )
1856 
1857     if (low_limit->get_int() == -max_jint) {
1858       // We need this guard when scale*pre_limit+offset >= limit
1859       // due to underflow. So we need execute pre-loop until
1860       // scale*I+offset >= min_int. But (min_int-offset) will
1861       // underflow when offset > 0 and X will be > original_limit
1862       // when stride > 0. To avoid it we replace positive offset with 0.
1863       //
1864       // Also (min_int+1 == -max_int) is used instead of min_int here
1865       // to avoid problem with scale == -1 (min_int/(-1) == min_int).
1866       Node* shift = _igvn.intcon(31);
1867       set_ctrl(shift, C->root());
1868       Node* sign = new RShiftINode(offset, shift);
1869       register_new_node(sign, pre_ctrl);
1870       offset = new AndINode(offset, sign);
1871       register_new_node(offset, pre_ctrl);
1872     } else {
1873       assert(low_limit->get_int() == 0, "wrong low limit for range check");
1874       // The only problem we have here when offset == min_int
1875       // since (0-min_int) == min_int. It may be fine for stride > 0
1876       // but for stride < 0 X will be < original_limit. To avoid it
1877       // max(pre_limit, original_limit) is used in do_range_check().
1878     }
1879     // Pass (-stride) to indicate pre_loop_cond = NOT(main_loop_cond);
1880     *pre_limit = adjust_limit((-stride_con), scale, offset, low_limit, *pre_limit, pre_ctrl);
1881 
1882   } else { // stride_con*scale_con < 0
1883     // For negative stride*scale pre-loop checks for overflow and
1884     // post-loop for underflow.
1885     //
1886     // The overflow limit: scale*I+offset < upper_limit
1887     // For pre-loop compute
1888     //   NOT(scale*I+offset < upper_limit)
1889     //   scale*I+offset >= upper_limit
1890     //   scale*I+offset+1 > upper_limit
1891     //   ( if (scale < 0) /* and stride > 0 */
1892     //       I < (upper_limit-(offset+1))/scale
1893     //     else /* scale > 0 and stride < 0 */
1894     //       I > (upper_limit-(offset+1))/scale
1895     //   )
1896     //
1897     // (upper_limit-offset-1) may underflow or overflow.
1898     // To avoid it min(pre_limit, original_limit) is used
1899     // in do_range_check() for stride > 0 and max() for < 0.
1900     Node *one  = _igvn.intcon(1);
1901     set_ctrl(one, C->root());
1902 
1903     Node *plus_one = new AddINode(offset, one);
1904     register_new_node( plus_one, pre_ctrl );
1905     // Pass (-stride) to indicate pre_loop_cond = NOT(main_loop_cond);
1906     *pre_limit = adjust_limit((-stride_con), scale, plus_one, upper_limit, *pre_limit, pre_ctrl);
1907 
1908     if (low_limit->get_int() == -max_jint) {
1909       // We need this guard when scale*main_limit+offset >= limit
1910       // due to underflow. So we need execute main-loop while
1911       // scale*I+offset+1 > min_int. But (min_int-offset-1) will
1912       // underflow when (offset+1) > 0 and X will be < main_limit
1913       // when scale < 0 (and stride > 0). To avoid it we replace
1914       // positive (offset+1) with 0.
1915       //
1916       // Also (min_int+1 == -max_int) is used instead of min_int here
1917       // to avoid problem with scale == -1 (min_int/(-1) == min_int).
1918       Node* shift = _igvn.intcon(31);
1919       set_ctrl(shift, C->root());
1920       Node* sign = new RShiftINode(plus_one, shift);
1921       register_new_node(sign, pre_ctrl);
1922       plus_one = new AndINode(plus_one, sign);
1923       register_new_node(plus_one, pre_ctrl);
1924     } else {
1925       assert(low_limit->get_int() == 0, "wrong low limit for range check");
1926       // The only problem we have here when offset == max_int
1927       // since (max_int+1) == min_int and (0-min_int) == min_int.
1928       // But it is fine since main loop will either have
1929       // less iterations or will be skipped in such case.
1930     }
1931     // The underflow limit: low_limit <= scale*I+offset.
1932     // For main-loop compute
1933     //   scale*I+offset+1 > low_limit
1934     //   ( if (scale < 0) /* and stride > 0 */
1935     //       I < (low_limit-(offset+1))/scale
1936     //     else /* scale > 0 and stride < 0 */
1937     //       I > (low_limit-(offset+1))/scale
1938     //   )
1939 
1940     *main_limit = adjust_limit(stride_con, scale, plus_one, low_limit, *main_limit, pre_ctrl);
1941   }
1942 }
1943 
1944 
1945 //------------------------------is_scaled_iv---------------------------------
1946 // Return true if exp is a constant times an induction var
1947 bool PhaseIdealLoop::is_scaled_iv(Node* exp, Node* iv, int* p_scale) {
1948   if (exp == iv) {
1949     if (p_scale != NULL) {
1950       *p_scale = 1;
1951     }
1952     return true;
1953   }
1954   int opc = exp->Opcode();
1955   if (opc == Op_MulI) {
1956     if (exp->in(1) == iv && exp->in(2)->is_Con()) {
1957       if (p_scale != NULL) {
1958         *p_scale = exp->in(2)->get_int();
1959       }
1960       return true;
1961     }
1962     if (exp->in(2) == iv && exp->in(1)->is_Con()) {
1963       if (p_scale != NULL) {
1964         *p_scale = exp->in(1)->get_int();
1965       }
1966       return true;
1967     }
1968   } else if (opc == Op_LShiftI) {
1969     if (exp->in(1) == iv && exp->in(2)->is_Con()) {
1970       if (p_scale != NULL) {
1971         *p_scale = 1 << exp->in(2)->get_int();
1972       }
1973       return true;
1974     }
1975   }
1976   return false;
1977 }
1978 
1979 //-----------------------------is_scaled_iv_plus_offset------------------------------
1980 // Return true if exp is a simple induction variable expression: k1*iv + (invar + k2)
1981 bool PhaseIdealLoop::is_scaled_iv_plus_offset(Node* exp, Node* iv, int* p_scale, Node** p_offset, int depth) {
1982   if (is_scaled_iv(exp, iv, p_scale)) {
1983     if (p_offset != NULL) {
1984       Node *zero = _igvn.intcon(0);
1985       set_ctrl(zero, C->root());
1986       *p_offset = zero;
1987     }
1988     return true;
1989   }
1990   int opc = exp->Opcode();
1991   if (opc == Op_AddI) {
1992     if (is_scaled_iv(exp->in(1), iv, p_scale)) {
1993       if (p_offset != NULL) {
1994         *p_offset = exp->in(2);
1995       }
1996       return true;
1997     }
1998     if (is_scaled_iv(exp->in(2), iv, p_scale)) {
1999       if (p_offset != NULL) {
2000         *p_offset = exp->in(1);
2001       }
2002       return true;
2003     }
2004     if (exp->in(2)->is_Con()) {
2005       Node* offset2 = NULL;
2006       if (depth < 2 &&
2007           is_scaled_iv_plus_offset(exp->in(1), iv, p_scale,
2008                                    p_offset != NULL ? &offset2 : NULL, depth+1)) {
2009         if (p_offset != NULL) {
2010           Node *ctrl_off2 = get_ctrl(offset2);
2011           Node* offset = new AddINode(offset2, exp->in(2));
2012           register_new_node(offset, ctrl_off2);
2013           *p_offset = offset;
2014         }
2015         return true;
2016       }
2017     }
2018   } else if (opc == Op_SubI) {
2019     if (is_scaled_iv(exp->in(1), iv, p_scale)) {
2020       if (p_offset != NULL) {
2021         Node *zero = _igvn.intcon(0);
2022         set_ctrl(zero, C->root());
2023         Node *ctrl_off = get_ctrl(exp->in(2));
2024         Node* offset = new SubINode(zero, exp->in(2));
2025         register_new_node(offset, ctrl_off);
2026         *p_offset = offset;
2027       }
2028       return true;
2029     }
2030     if (is_scaled_iv(exp->in(2), iv, p_scale)) {
2031       if (p_offset != NULL) {
2032         *p_scale *= -1;
2033         *p_offset = exp->in(1);
2034       }
2035       return true;
2036     }
2037   }
2038   return false;
2039 }
2040 
2041 //------------------------------do_range_check---------------------------------
2042 // Eliminate range-checks and other trip-counter vs loop-invariant tests.
2043 int PhaseIdealLoop::do_range_check( IdealLoopTree *loop, Node_List &old_new ) {
2044 #ifndef PRODUCT
2045   if (PrintOpto && VerifyLoopOptimizations) {
2046     tty->print("Range Check Elimination ");
2047     loop->dump_head();
2048   } else if (TraceLoopOpts) {
2049     tty->print("RangeCheck   ");
2050     loop->dump_head();
2051   }
2052 #endif
2053   assert(RangeCheckElimination, "");
2054   CountedLoopNode *cl = loop->_head->as_CountedLoop();
2055   // If we fail before trying to eliminate range checks, set multiversion state
2056   int closed_range_checks = 1;
2057 
2058   // protect against stride not being a constant
2059   if (!cl->stride_is_con())
2060     return closed_range_checks;
2061 
2062   // Find the trip counter; we are iteration splitting based on it
2063   Node *trip_counter = cl->phi();
2064   // Find the main loop limit; we will trim it's iterations
2065   // to not ever trip end tests
2066   Node *main_limit = cl->limit();
2067 
2068   // Check graph shape. Cannot optimize a loop if zero-trip
2069   // Opaque1 node is optimized away and then another round
2070   // of loop opts attempted.
2071   if (!is_canonical_loop_entry(cl)) {
2072     return closed_range_checks;
2073   }
2074 
2075   // Need to find the main-loop zero-trip guard
2076   Node *ctrl  = cl->skip_strip_mined()->in(LoopNode::EntryControl);
2077   Node *iffm = ctrl->in(0);
2078   Node *opqzm = iffm->in(1)->in(1)->in(2);
2079   assert(opqzm->in(1) == main_limit, "do not understand situation");
2080 
2081   // Find the pre-loop limit; we will expand its iterations to
2082   // not ever trip low tests.
2083   Node *p_f = iffm->in(0);
2084   // pre loop may have been optimized out
2085   if (p_f->Opcode() != Op_IfFalse) {
2086     return closed_range_checks;
2087   }
2088   CountedLoopEndNode *pre_end = p_f->in(0)->as_CountedLoopEnd();
2089   assert(pre_end->loopnode()->is_pre_loop(), "");
2090   Node *pre_opaq1 = pre_end->limit();
2091   // Occasionally it's possible for a pre-loop Opaque1 node to be
2092   // optimized away and then another round of loop opts attempted.
2093   // We can not optimize this particular loop in that case.
2094   if (pre_opaq1->Opcode() != Op_Opaque1)
2095     return closed_range_checks;
2096   Opaque1Node *pre_opaq = (Opaque1Node*)pre_opaq1;
2097   Node *pre_limit = pre_opaq->in(1);
2098 
2099   // Where do we put new limit calculations
2100   Node *pre_ctrl = pre_end->loopnode()->in(LoopNode::EntryControl);
2101 
2102   // Ensure the original loop limit is available from the
2103   // pre-loop Opaque1 node.
2104   Node *orig_limit = pre_opaq->original_loop_limit();
2105   if (orig_limit == NULL || _igvn.type(orig_limit) == Type::TOP)
2106     return closed_range_checks;
2107 
2108   // Must know if its a count-up or count-down loop
2109 
2110   int stride_con = cl->stride_con();
2111   Node *zero = _igvn.intcon(0);
2112   Node *one  = _igvn.intcon(1);
2113   // Use symmetrical int range [-max_jint,max_jint]
2114   Node *mini = _igvn.intcon(-max_jint);
2115   set_ctrl(zero, C->root());
2116   set_ctrl(one,  C->root());
2117   set_ctrl(mini, C->root());
2118 
2119   // Range checks that do not dominate the loop backedge (ie.
2120   // conditionally executed) can lengthen the pre loop limit beyond
2121   // the original loop limit. To prevent this, the pre limit is
2122   // (for stride > 0) MINed with the original loop limit (MAXed
2123   // stride < 0) when some range_check (rc) is conditionally
2124   // executed.
2125   bool conditional_rc = false;
2126 
2127   // Count number of range checks and reduce by load range limits, if zero,
2128   // the loop is in canonical form to multiversion.
2129   closed_range_checks = 0;
2130 
2131   // Check loop body for tests of trip-counter plus loop-invariant vs loop-variant.
2132   for( uint i = 0; i < loop->_body.size(); i++ ) {
2133     Node *iff = loop->_body[i];
2134     if (iff->Opcode() == Op_If ||
2135         iff->Opcode() == Op_RangeCheck) { // Test?
2136       // Test is an IfNode, has 2 projections.  If BOTH are in the loop
2137       // we need loop unswitching instead of iteration splitting.
2138       closed_range_checks++;
2139       Node *exit = loop->is_loop_exit(iff);
2140       if( !exit ) continue;
2141       int flip = (exit->Opcode() == Op_IfTrue) ? 1 : 0;
2142 
2143       // Get boolean condition to test
2144       Node *i1 = iff->in(1);
2145       if( !i1->is_Bool() ) continue;
2146       BoolNode *bol = i1->as_Bool();
2147       BoolTest b_test = bol->_test;
2148       // Flip sense of test if exit condition is flipped
2149       if( flip )
2150         b_test = b_test.negate();
2151 
2152       // Get compare
2153       Node *cmp = bol->in(1);
2154 
2155       // Look for trip_counter + offset vs limit
2156       Node *rc_exp = cmp->in(1);
2157       Node *limit  = cmp->in(2);
2158       int scale_con= 1;        // Assume trip counter not scaled
2159 
2160       Node *limit_c = get_ctrl(limit);
2161       if( loop->is_member(get_loop(limit_c) ) ) {
2162         // Compare might have operands swapped; commute them
2163         b_test = b_test.commute();
2164         rc_exp = cmp->in(2);
2165         limit  = cmp->in(1);
2166         limit_c = get_ctrl(limit);
2167         if( loop->is_member(get_loop(limit_c) ) )
2168           continue;             // Both inputs are loop varying; cannot RCE
2169       }
2170       // Here we know 'limit' is loop invariant
2171 
2172       // 'limit' maybe pinned below the zero trip test (probably from a
2173       // previous round of rce), in which case, it can't be used in the
2174       // zero trip test expression which must occur before the zero test's if.
2175       if( limit_c == ctrl ) {
2176         continue;  // Don't rce this check but continue looking for other candidates.
2177       }
2178 
2179       // Check for scaled induction variable plus an offset
2180       Node *offset = NULL;
2181 
2182       if (!is_scaled_iv_plus_offset(rc_exp, trip_counter, &scale_con, &offset)) {
2183         continue;
2184       }
2185 
2186       Node *offset_c = get_ctrl(offset);
2187       if( loop->is_member( get_loop(offset_c) ) )
2188         continue;               // Offset is not really loop invariant
2189       // Here we know 'offset' is loop invariant.
2190 
2191       // As above for the 'limit', the 'offset' maybe pinned below the
2192       // zero trip test.
2193       if( offset_c == ctrl ) {
2194         continue; // Don't rce this check but continue looking for other candidates.
2195       }
2196 #ifdef ASSERT
2197       if (TraceRangeLimitCheck) {
2198         tty->print_cr("RC bool node%s", flip ? " flipped:" : ":");
2199         bol->dump(2);
2200       }
2201 #endif
2202       // At this point we have the expression as:
2203       //   scale_con * trip_counter + offset :: limit
2204       // where scale_con, offset and limit are loop invariant.  Trip_counter
2205       // monotonically increases by stride_con, a constant.  Both (or either)
2206       // stride_con and scale_con can be negative which will flip about the
2207       // sense of the test.
2208 
2209       // Adjust pre and main loop limits to guard the correct iteration set
2210       if( cmp->Opcode() == Op_CmpU ) {// Unsigned compare is really 2 tests
2211         if( b_test._test == BoolTest::lt ) { // Range checks always use lt
2212           // The underflow and overflow limits: 0 <= scale*I+offset < limit
2213           add_constraint( stride_con, scale_con, offset, zero, limit, pre_ctrl, &pre_limit, &main_limit );
2214           // (0-offset)/scale could be outside of loop iterations range.
2215           conditional_rc = true;
2216         } else {
2217           if (PrintOpto) {
2218             tty->print_cr("missed RCE opportunity");
2219           }
2220           continue;             // In release mode, ignore it
2221         }
2222       } else {                  // Otherwise work on normal compares
2223         switch( b_test._test ) {
2224         case BoolTest::gt:
2225           // Fall into GE case
2226         case BoolTest::ge:
2227           // Convert (I*scale+offset) >= Limit to (I*(-scale)+(-offset)) <= -Limit
2228           scale_con = -scale_con;
2229           offset = new SubINode( zero, offset );
2230           register_new_node( offset, pre_ctrl );
2231           limit  = new SubINode( zero, limit );
2232           register_new_node( limit, pre_ctrl );
2233           // Fall into LE case
2234         case BoolTest::le:
2235           if (b_test._test != BoolTest::gt) {
2236             // Convert X <= Y to X < Y+1
2237             limit = new AddINode( limit, one );
2238             register_new_node( limit, pre_ctrl );
2239           }
2240           // Fall into LT case
2241         case BoolTest::lt:
2242           // The underflow and overflow limits: MIN_INT <= scale*I+offset < limit
2243           // Note: (MIN_INT+1 == -MAX_INT) is used instead of MIN_INT here
2244           // to avoid problem with scale == -1: MIN_INT/(-1) == MIN_INT.
2245           add_constraint( stride_con, scale_con, offset, mini, limit, pre_ctrl, &pre_limit, &main_limit );
2246           // ((MIN_INT+1)-offset)/scale could be outside of loop iterations range.
2247           // Note: negative offset is replaced with 0 but (MIN_INT+1)/scale could
2248           // still be outside of loop range.
2249           conditional_rc = true;
2250           break;
2251         default:
2252           if (PrintOpto) {
2253             tty->print_cr("missed RCE opportunity");
2254           }
2255           continue;             // Unhandled case
2256         }
2257       }
2258 
2259       // Kill the eliminated test
2260       C->set_major_progress();
2261       Node *kill_con = _igvn.intcon( 1-flip );
2262       set_ctrl(kill_con, C->root());
2263       _igvn.replace_input_of(iff, 1, kill_con);
2264       // Find surviving projection
2265       assert(iff->is_If(), "");
2266       ProjNode* dp = ((IfNode*)iff)->proj_out(1-flip);
2267       // Find loads off the surviving projection; remove their control edge
2268       for (DUIterator_Fast imax, i = dp->fast_outs(imax); i < imax; i++) {
2269         Node* cd = dp->fast_out(i); // Control-dependent node
2270         if (cd->is_Load() && cd->depends_only_on_test()) {   // Loads can now float around in the loop
2271           // Allow the load to float around in the loop, or before it
2272           // but NOT before the pre-loop.
2273           _igvn.replace_input_of(cd, 0, ctrl); // ctrl, not NULL
2274           --i;
2275           --imax;
2276         }
2277       }
2278       if (limit->Opcode() == Op_LoadRange) {
2279         closed_range_checks--;
2280       }
2281 
2282     } // End of is IF
2283 
2284   }
2285 
2286   // Update loop limits
2287   if (conditional_rc) {
2288     pre_limit = (stride_con > 0) ? (Node*)new MinINode(pre_limit, orig_limit)
2289                                  : (Node*)new MaxINode(pre_limit, orig_limit);
2290     register_new_node(pre_limit, pre_ctrl);
2291   }
2292   _igvn.replace_input_of(pre_opaq, 1, pre_limit);
2293 
2294   // Note:: we are making the main loop limit no longer precise;
2295   // need to round up based on stride.
2296   cl->set_nonexact_trip_count();
2297   Node *main_cle = cl->loopexit();
2298   Node *main_bol = main_cle->in(1);
2299   // Hacking loop bounds; need private copies of exit test
2300   if( main_bol->outcnt() > 1 ) {// BoolNode shared?
2301     main_bol = main_bol->clone();// Clone a private BoolNode
2302     register_new_node( main_bol, main_cle->in(0) );
2303     _igvn.replace_input_of(main_cle, 1, main_bol);
2304   }
2305   Node *main_cmp = main_bol->in(1);
2306   if( main_cmp->outcnt() > 1 ) { // CmpNode shared?
2307     main_cmp = main_cmp->clone();// Clone a private CmpNode
2308     register_new_node( main_cmp, main_cle->in(0) );
2309     _igvn.replace_input_of(main_bol, 1, main_cmp);
2310   }
2311   // Hack the now-private loop bounds
2312   _igvn.replace_input_of(main_cmp, 2, main_limit);
2313   // The OpaqueNode is unshared by design
2314   assert( opqzm->outcnt() == 1, "cannot hack shared node" );
2315   _igvn.replace_input_of(opqzm, 1, main_limit);
2316 
2317   return closed_range_checks;
2318 }
2319 
2320 //------------------------------has_range_checks-------------------------------
2321 // Check to see if RCE cleaned the current loop of range-checks.
2322 void PhaseIdealLoop::has_range_checks(IdealLoopTree *loop) {
2323   assert(RangeCheckElimination, "");
2324 
2325   // skip if not a counted loop
2326   if (!loop->is_counted()) return;
2327 
2328   CountedLoopNode *cl = loop->_head->as_CountedLoop();
2329 
2330   // skip this loop if it is already checked
2331   if (cl->has_been_range_checked()) return;
2332 
2333   // Now check for existence of range checks
2334   for (uint i = 0; i < loop->_body.size(); i++) {
2335     Node *iff = loop->_body[i];
2336     int iff_opc = iff->Opcode();
2337     if (iff_opc == Op_If || iff_opc == Op_RangeCheck) {
2338       cl->mark_has_range_checks();
2339       break;
2340     }
2341   }
2342   cl->set_has_been_range_checked();
2343 }
2344 
2345 //-------------------------multi_version_post_loops----------------------------
2346 // Check the range checks that remain, if simple, use the bounds to guard
2347 // which version to a post loop we execute, one with range checks or one without
2348 bool PhaseIdealLoop::multi_version_post_loops(IdealLoopTree *rce_loop, IdealLoopTree *legacy_loop) {
2349   bool multi_version_succeeded = false;
2350   assert(RangeCheckElimination, "");
2351   CountedLoopNode *legacy_cl = legacy_loop->_head->as_CountedLoop();
2352   assert(legacy_cl->is_post_loop(), "");
2353 
2354   // Check for existence of range checks using the unique instance to make a guard with
2355   Unique_Node_List worklist;
2356   for (uint i = 0; i < legacy_loop->_body.size(); i++) {
2357     Node *iff = legacy_loop->_body[i];
2358     int iff_opc = iff->Opcode();
2359     if (iff_opc == Op_If || iff_opc == Op_RangeCheck) {
2360       worklist.push(iff);
2361     }
2362   }
2363 
2364   // Find RCE'd post loop so that we can stage its guard.
2365   if (!is_canonical_loop_entry(legacy_cl)) return multi_version_succeeded;
2366   Node* ctrl = legacy_cl->in(LoopNode::EntryControl);
2367   Node* iffm = ctrl->in(0);
2368 
2369   // Now we test that both the post loops are connected
2370   Node* post_loop_region = iffm->in(0);
2371   if (post_loop_region == NULL) return multi_version_succeeded;
2372   if (!post_loop_region->is_Region()) return multi_version_succeeded;
2373   Node* covering_region = post_loop_region->in(RegionNode::Control+1);
2374   if (covering_region == NULL) return multi_version_succeeded;
2375   if (!covering_region->is_Region()) return multi_version_succeeded;
2376   Node* p_f = covering_region->in(RegionNode::Control);
2377   if (p_f == NULL) return multi_version_succeeded;
2378   if (!p_f->is_IfFalse()) return multi_version_succeeded;
2379   if (!p_f->in(0)->is_CountedLoopEnd()) return multi_version_succeeded;
2380   CountedLoopEndNode* rce_loop_end = p_f->in(0)->as_CountedLoopEnd();
2381   if (rce_loop_end == NULL) return multi_version_succeeded;
2382   CountedLoopNode* rce_cl = rce_loop_end->loopnode();
2383   if (rce_cl == NULL || !rce_cl->is_post_loop()) return multi_version_succeeded;
2384   CountedLoopNode *known_rce_cl = rce_loop->_head->as_CountedLoop();
2385   if (rce_cl != known_rce_cl) return multi_version_succeeded;
2386 
2387   // Then we fetch the cover entry test
2388   ctrl = rce_cl->in(LoopNode::EntryControl);
2389   if (!ctrl->is_IfTrue() && !ctrl->is_IfFalse()) return multi_version_succeeded;
2390 
2391 #ifndef PRODUCT
2392   if (TraceLoopOpts) {
2393     tty->print("PostMultiVersion\n");
2394     rce_loop->dump_head();
2395     legacy_loop->dump_head();
2396   }
2397 #endif
2398 
2399   // Now fetch the limit we want to compare against
2400   Node *limit = rce_cl->limit();
2401   bool first_time = true;
2402 
2403   // If we got this far, we identified the post loop which has been RCE'd and
2404   // we have a work list.  Now we will try to transform the if guard to cause
2405   // the loop pair to be multi version executed with the determination left to runtime
2406   // or the optimizer if full information is known about the given arrays at compile time.
2407   Node *last_min = NULL;
2408   multi_version_succeeded = true;
2409   while (worklist.size()) {
2410     Node* rc_iffm = worklist.pop();
2411     if (rc_iffm->is_If()) {
2412       Node *rc_bolzm = rc_iffm->in(1);
2413       if (rc_bolzm->is_Bool()) {
2414         Node *rc_cmpzm = rc_bolzm->in(1);
2415         if (rc_cmpzm->is_Cmp()) {
2416           Node *rc_left = rc_cmpzm->in(2);
2417           if (rc_left->Opcode() != Op_LoadRange) {
2418             multi_version_succeeded = false;
2419             break;
2420           }
2421           if (first_time) {
2422             last_min = rc_left;
2423             first_time = false;
2424           } else {
2425             Node *cur_min = new MinINode(last_min, rc_left);
2426             last_min = cur_min;
2427             _igvn.register_new_node_with_optimizer(last_min);
2428           }
2429         }
2430       }
2431     }
2432   }
2433 
2434   // All we have to do is update the limit of the rce loop
2435   // with the min of our expression and the current limit.
2436   // We will use this expression to replace the current limit.
2437   if (last_min && multi_version_succeeded) {
2438     Node *cur_min = new MinINode(last_min, limit);
2439     _igvn.register_new_node_with_optimizer(cur_min);
2440     Node *cmp_node = rce_loop_end->cmp_node();
2441     _igvn.replace_input_of(cmp_node, 2, cur_min);
2442     set_ctrl(cur_min, ctrl);
2443     set_loop(cur_min, rce_loop->_parent);
2444 
2445     legacy_cl->mark_is_multiversioned();
2446     rce_cl->mark_is_multiversioned();
2447     multi_version_succeeded = true;
2448 
2449     C->set_major_progress();
2450   }
2451 
2452   return multi_version_succeeded;
2453 }
2454 
2455 //-------------------------poison_rce_post_loop--------------------------------
2456 // Causes the rce'd post loop to be optimized away if multiversioning fails
2457 void PhaseIdealLoop::poison_rce_post_loop(IdealLoopTree *rce_loop) {
2458   CountedLoopNode *rce_cl = rce_loop->_head->as_CountedLoop();
2459   Node* ctrl = rce_cl->in(LoopNode::EntryControl);
2460   if (ctrl->is_IfTrue() || ctrl->is_IfFalse()) {
2461     Node* iffm = ctrl->in(0);
2462     if (iffm->is_If()) {
2463       Node* cur_bool = iffm->in(1);
2464       if (cur_bool->is_Bool()) {
2465         Node* cur_cmp = cur_bool->in(1);
2466         if (cur_cmp->is_Cmp()) {
2467           BoolTest::mask new_test = BoolTest::gt;
2468           BoolNode *new_bool = new BoolNode(cur_cmp, new_test);
2469           _igvn.replace_node(cur_bool, new_bool);
2470           _igvn._worklist.push(new_bool);
2471           Node* left_op = cur_cmp->in(1);
2472           _igvn.replace_input_of(cur_cmp, 2, left_op);
2473           C->set_major_progress();
2474         }
2475       }
2476     }
2477   }
2478 }
2479 
2480 //------------------------------DCE_loop_body----------------------------------
2481 // Remove simplistic dead code from loop body
2482 void IdealLoopTree::DCE_loop_body() {
2483   for( uint i = 0; i < _body.size(); i++ )
2484     if( _body.at(i)->outcnt() == 0 )
2485       _body.map( i--, _body.pop() );
2486 }
2487 
2488 
2489 //------------------------------adjust_loop_exit_prob--------------------------
2490 // Look for loop-exit tests with the 50/50 (or worse) guesses from the parsing stage.
2491 // Replace with a 1-in-10 exit guess.
2492 void IdealLoopTree::adjust_loop_exit_prob( PhaseIdealLoop *phase ) {
2493   Node *test = tail();
2494   while( test != _head ) {
2495     uint top = test->Opcode();
2496     if( top == Op_IfTrue || top == Op_IfFalse ) {
2497       int test_con = ((ProjNode*)test)->_con;
2498       assert(top == (uint)(test_con? Op_IfTrue: Op_IfFalse), "sanity");
2499       IfNode *iff = test->in(0)->as_If();
2500       if( iff->outcnt() == 2 ) {        // Ignore dead tests
2501         Node *bol = iff->in(1);
2502         if( bol && bol->req() > 1 && bol->in(1) &&
2503             ((bol->in(1)->Opcode() == Op_StorePConditional ) ||
2504              (bol->in(1)->Opcode() == Op_StoreIConditional ) ||
2505              (bol->in(1)->Opcode() == Op_StoreLConditional ) ||
2506              (bol->in(1)->Opcode() == Op_CompareAndExchangeB ) ||
2507              (bol->in(1)->Opcode() == Op_CompareAndExchangeS ) ||
2508              (bol->in(1)->Opcode() == Op_CompareAndExchangeI ) ||
2509              (bol->in(1)->Opcode() == Op_CompareAndExchangeL ) ||
2510              (bol->in(1)->Opcode() == Op_CompareAndExchangeP ) ||
2511              (bol->in(1)->Opcode() == Op_CompareAndExchangeN ) ||
2512              (bol->in(1)->Opcode() == Op_WeakCompareAndSwapB ) ||
2513              (bol->in(1)->Opcode() == Op_WeakCompareAndSwapS ) ||
2514              (bol->in(1)->Opcode() == Op_WeakCompareAndSwapI ) ||
2515              (bol->in(1)->Opcode() == Op_WeakCompareAndSwapL ) ||
2516              (bol->in(1)->Opcode() == Op_WeakCompareAndSwapP ) ||
2517              (bol->in(1)->Opcode() == Op_WeakCompareAndSwapN ) ||
2518              (bol->in(1)->Opcode() == Op_CompareAndSwapB ) ||
2519              (bol->in(1)->Opcode() == Op_CompareAndSwapS ) ||
2520              (bol->in(1)->Opcode() == Op_CompareAndSwapI ) ||
2521              (bol->in(1)->Opcode() == Op_CompareAndSwapL ) ||
2522              (bol->in(1)->Opcode() == Op_CompareAndSwapP ) ||
2523              (bol->in(1)->Opcode() == Op_CompareAndSwapN )))
2524           return;               // Allocation loops RARELY take backedge
2525         // Find the OTHER exit path from the IF
2526         Node* ex = iff->proj_out(1-test_con);
2527         float p = iff->_prob;
2528         if( !phase->is_member( this, ex ) && iff->_fcnt == COUNT_UNKNOWN ) {
2529           if( top == Op_IfTrue ) {
2530             if( p < (PROB_FAIR + PROB_UNLIKELY_MAG(3))) {
2531               iff->_prob = PROB_STATIC_FREQUENT;
2532             }
2533           } else {
2534             if( p > (PROB_FAIR - PROB_UNLIKELY_MAG(3))) {
2535               iff->_prob = PROB_STATIC_INFREQUENT;
2536             }
2537           }
2538         }
2539       }
2540     }
2541     test = phase->idom(test);
2542   }
2543 }
2544 
2545 #ifdef ASSERT
2546 static CountedLoopNode* locate_pre_from_main(CountedLoopNode *cl) {
2547   Node *ctrl  = cl->skip_strip_mined()->in(LoopNode::EntryControl);
2548   assert(ctrl->Opcode() == Op_IfTrue || ctrl->Opcode() == Op_IfFalse, "");
2549   Node *iffm = ctrl->in(0);
2550   assert(iffm->Opcode() == Op_If, "");
2551   Node *p_f = iffm->in(0);
2552   assert(p_f->Opcode() == Op_IfFalse, "");
2553   CountedLoopEndNode *pre_end = p_f->in(0)->as_CountedLoopEnd();
2554   assert(pre_end->loopnode()->is_pre_loop(), "");
2555   return pre_end->loopnode();
2556 }
2557 #endif
2558 
2559 // Remove the main and post loops and make the pre loop execute all
2560 // iterations. Useful when the pre loop is found empty.
2561 void IdealLoopTree::remove_main_post_loops(CountedLoopNode *cl, PhaseIdealLoop *phase) {
2562   CountedLoopEndNode* pre_end = cl->loopexit();
2563   Node* pre_cmp = pre_end->cmp_node();
2564   if (pre_cmp->in(2)->Opcode() != Op_Opaque1) {
2565     // Only safe to remove the main loop if the compiler optimized it
2566     // out based on an unknown number of iterations
2567     return;
2568   }
2569 
2570   // Can we find the main loop?
2571   if (_next == NULL) {
2572     return;
2573   }
2574 
2575   Node* next_head = _next->_head;
2576   if (!next_head->is_CountedLoop()) {
2577     return;
2578   }
2579 
2580   CountedLoopNode* main_head = next_head->as_CountedLoop();
2581   if (!main_head->is_main_loop()) {
2582     return;
2583   }
2584 
2585   assert(locate_pre_from_main(main_head) == cl, "bad main loop");
2586   Node* main_iff = main_head->skip_strip_mined()->in(LoopNode::EntryControl)->in(0);
2587 
2588   // Remove the Opaque1Node of the pre loop and make it execute all iterations
2589   phase->_igvn.replace_input_of(pre_cmp, 2, pre_cmp->in(2)->in(2));
2590   // Remove the Opaque1Node of the main loop so it can be optimized out
2591   Node* main_cmp = main_iff->in(1)->in(1);
2592   assert(main_cmp->in(2)->Opcode() == Op_Opaque1, "main loop has no opaque node?");
2593   phase->_igvn.replace_input_of(main_cmp, 2, main_cmp->in(2)->in(1));
2594 }
2595 
2596 //------------------------------policy_do_remove_empty_loop--------------------
2597 // Micro-benchmark spamming.  Policy is to always remove empty loops.
2598 // The 'DO' part is to replace the trip counter with the value it will
2599 // have on the last iteration.  This will break the loop.
2600 bool IdealLoopTree::policy_do_remove_empty_loop( PhaseIdealLoop *phase ) {
2601   // Minimum size must be empty loop
2602   if (_body.size() > EMPTY_LOOP_SIZE)
2603     return false;
2604 
2605   if (!_head->is_CountedLoop())
2606     return false;     // Dead loop
2607   CountedLoopNode *cl = _head->as_CountedLoop();
2608   if (!cl->is_valid_counted_loop())
2609     return false; // Malformed loop
2610   if (!phase->is_member(this, phase->get_ctrl(cl->loopexit()->in(CountedLoopEndNode::TestValue))))
2611     return false;             // Infinite loop
2612 
2613   if (cl->is_pre_loop()) {
2614     // If the loop we are removing is a pre-loop then the main and
2615     // post loop can be removed as well
2616     remove_main_post_loops(cl, phase);
2617   }
2618 
2619 #ifdef ASSERT
2620   // Ensure only one phi which is the iv.
2621   Node* iv = NULL;
2622   for (DUIterator_Fast imax, i = cl->fast_outs(imax); i < imax; i++) {
2623     Node* n = cl->fast_out(i);
2624     if (n->Opcode() == Op_Phi) {
2625       assert(iv == NULL, "Too many phis" );
2626       iv = n;
2627     }
2628   }
2629   assert(iv == cl->phi(), "Wrong phi" );
2630 #endif
2631 
2632   // main and post loops have explicitly created zero trip guard
2633   bool needs_guard = !cl->is_main_loop() && !cl->is_post_loop();
2634   if (needs_guard) {
2635     // Skip guard if values not overlap.
2636     const TypeInt* init_t = phase->_igvn.type(cl->init_trip())->is_int();
2637     const TypeInt* limit_t = phase->_igvn.type(cl->limit())->is_int();
2638     int  stride_con = cl->stride_con();
2639     if (stride_con > 0) {
2640       needs_guard = (init_t->_hi >= limit_t->_lo);
2641     } else {
2642       needs_guard = (init_t->_lo <= limit_t->_hi);
2643     }
2644   }
2645   if (needs_guard) {
2646     // Check for an obvious zero trip guard.
2647     Node* inctrl = PhaseIdealLoop::skip_loop_predicates(cl->skip_strip_mined()->in(LoopNode::EntryControl));
2648     if (inctrl->Opcode() == Op_IfTrue || inctrl->Opcode() == Op_IfFalse) {
2649       bool maybe_swapped = (inctrl->Opcode() == Op_IfFalse);
2650       // The test should look like just the backedge of a CountedLoop
2651       Node* iff = inctrl->in(0);
2652       if (iff->is_If()) {
2653         Node* bol = iff->in(1);
2654         if (bol->is_Bool()) {
2655           BoolTest test = bol->as_Bool()->_test;
2656           if (maybe_swapped) {
2657             test._test = test.commute();
2658             test._test = test.negate();
2659           }
2660           if (test._test == cl->loopexit()->test_trip()) {
2661             Node* cmp = bol->in(1);
2662             int init_idx = maybe_swapped ? 2 : 1;
2663             int limit_idx = maybe_swapped ? 1 : 2;
2664             if (cmp->is_Cmp() && cmp->in(init_idx) == cl->init_trip() && cmp->in(limit_idx) == cl->limit()) {
2665               needs_guard = false;
2666             }
2667           }
2668         }
2669       }
2670     }
2671   }
2672 
2673 #ifndef PRODUCT
2674   if (PrintOpto) {
2675     tty->print("Removing empty loop with%s zero trip guard", needs_guard ? "out" : "");
2676     this->dump_head();
2677   } else if (TraceLoopOpts) {
2678     tty->print("Empty with%s zero trip guard   ", needs_guard ? "out" : "");
2679     this->dump_head();
2680   }
2681 #endif
2682 
2683   if (needs_guard) {
2684     // Peel the loop to ensure there's a zero trip guard
2685     Node_List old_new;
2686     phase->do_peeling(this, old_new);
2687   }
2688 
2689   // Replace the phi at loop head with the final value of the last
2690   // iteration.  Then the CountedLoopEnd will collapse (backedge never
2691   // taken) and all loop-invariant uses of the exit values will be correct.
2692   Node *phi = cl->phi();
2693   Node *exact_limit = phase->exact_limit(this);
2694   if (exact_limit != cl->limit()) {
2695     // We also need to replace the original limit to collapse loop exit.
2696     Node* cmp = cl->loopexit()->cmp_node();
2697     assert(cl->limit() == cmp->in(2), "sanity");
2698     phase->_igvn._worklist.push(cmp->in(2)); // put limit on worklist
2699     phase->_igvn.replace_input_of(cmp, 2, exact_limit); // put cmp on worklist
2700   }
2701   // Note: the final value after increment should not overflow since
2702   // counted loop has limit check predicate.
2703   Node *final = new SubINode( exact_limit, cl->stride() );
2704   phase->register_new_node(final,cl->in(LoopNode::EntryControl));
2705   phase->_igvn.replace_node(phi,final);
2706   phase->C->set_major_progress();
2707   return true;
2708 }
2709 
2710 //------------------------------policy_do_one_iteration_loop-------------------
2711 // Convert one iteration loop into normal code.
2712 bool IdealLoopTree::policy_do_one_iteration_loop( PhaseIdealLoop *phase ) {
2713   if (!_head->as_Loop()->is_valid_counted_loop())
2714     return false; // Only for counted loop
2715 
2716   CountedLoopNode *cl = _head->as_CountedLoop();
2717   if (!cl->has_exact_trip_count() || cl->trip_count() != 1) {
2718     return false;
2719   }
2720 
2721 #ifndef PRODUCT
2722   if(TraceLoopOpts) {
2723     tty->print("OneIteration ");
2724     this->dump_head();
2725   }
2726 #endif
2727 
2728   Node *init_n = cl->init_trip();
2729 #ifdef ASSERT
2730   // Loop boundaries should be constant since trip count is exact.
2731   assert(init_n->get_int() + cl->stride_con() >= cl->limit()->get_int(), "should be one iteration");
2732 #endif
2733   // Replace the phi at loop head with the value of the init_trip.
2734   // Then the CountedLoopEnd will collapse (backedge will not be taken)
2735   // and all loop-invariant uses of the exit values will be correct.
2736   phase->_igvn.replace_node(cl->phi(), cl->init_trip());
2737   phase->C->set_major_progress();
2738   return true;
2739 }
2740 
2741 //=============================================================================
2742 //------------------------------iteration_split_impl---------------------------
2743 bool IdealLoopTree::iteration_split_impl( PhaseIdealLoop *phase, Node_List &old_new ) {
2744   // Compute loop trip count if possible.
2745   compute_trip_count(phase);
2746 
2747   // Convert one iteration loop into normal code.
2748   if (policy_do_one_iteration_loop(phase))
2749     return true;
2750 
2751   // Check and remove empty loops (spam micro-benchmarks)
2752   if (policy_do_remove_empty_loop(phase))
2753     return true;  // Here we removed an empty loop
2754 
2755   bool should_peel = policy_peeling(phase); // Should we peel?
2756 
2757   bool should_unswitch = policy_unswitching(phase);
2758 
2759   // Non-counted loops may be peeled; exactly 1 iteration is peeled.
2760   // This removes loop-invariant tests (usually null checks).
2761   if (!_head->is_CountedLoop()) { // Non-counted loop
2762     if (PartialPeelLoop && phase->partial_peel(this, old_new)) {
2763       // Partial peel succeeded so terminate this round of loop opts
2764       return false;
2765     }
2766     if (should_peel) {            // Should we peel?
2767       if (PrintOpto) { tty->print_cr("should_peel"); }
2768       phase->do_peeling(this,old_new);
2769     } else if (should_unswitch) {
2770       phase->do_unswitching(this, old_new);
2771     }
2772     return true;
2773   }
2774   CountedLoopNode *cl = _head->as_CountedLoop();
2775 
2776   if (!cl->is_valid_counted_loop()) return true; // Ignore various kinds of broken loops
2777 
2778   // Do nothing special to pre- and post- loops
2779   if (cl->is_pre_loop() || cl->is_post_loop()) return true;
2780 
2781   // Compute loop trip count from profile data
2782   compute_profile_trip_cnt(phase);
2783 
2784   // Before attempting fancy unrolling, RCE or alignment, see if we want
2785   // to completely unroll this loop or do loop unswitching.
2786   if (cl->is_normal_loop()) {
2787     if (should_unswitch) {
2788       phase->do_unswitching(this, old_new);
2789       return true;
2790     }
2791     bool should_maximally_unroll =  policy_maximally_unroll(phase);
2792     if (should_maximally_unroll) {
2793       // Here we did some unrolling and peeling.  Eventually we will
2794       // completely unroll this loop and it will no longer be a loop.
2795       phase->do_maximally_unroll(this,old_new);
2796       return true;
2797     }
2798   }
2799 
2800   // Skip next optimizations if running low on nodes. Note that
2801   // policy_unswitching and policy_maximally_unroll have this check.
2802   int nodes_left = phase->C->max_node_limit() - phase->C->live_nodes();
2803   if ((int)(2 * _body.size()) > nodes_left) {
2804     return true;
2805   }
2806 
2807   // Counted loops may be peeled, may need some iterations run up
2808   // front for RCE, and may want to align loop refs to a cache
2809   // line.  Thus we clone a full loop up front whose trip count is
2810   // at least 1 (if peeling), but may be several more.
2811 
2812   // The main loop will start cache-line aligned with at least 1
2813   // iteration of the unrolled body (zero-trip test required) and
2814   // will have some range checks removed.
2815 
2816   // A post-loop will finish any odd iterations (leftover after
2817   // unrolling), plus any needed for RCE purposes.
2818 
2819   bool should_unroll = policy_unroll(phase);
2820 
2821   bool should_rce = policy_range_check(phase);
2822 
2823   bool should_align = policy_align(phase);
2824 
2825   // If not RCE'ing (iteration splitting) or Aligning, then we do not
2826   // need a pre-loop.  We may still need to peel an initial iteration but
2827   // we will not be needing an unknown number of pre-iterations.
2828   //
2829   // Basically, if may_rce_align reports FALSE first time through,
2830   // we will not be able to later do RCE or Aligning on this loop.
2831   bool may_rce_align = !policy_peel_only(phase) || should_rce || should_align;
2832 
2833   // If we have any of these conditions (RCE, alignment, unrolling) met, then
2834   // we switch to the pre-/main-/post-loop model.  This model also covers
2835   // peeling.
2836   if (should_rce || should_align || should_unroll) {
2837     if (cl->is_normal_loop())  // Convert to 'pre/main/post' loops
2838       phase->insert_pre_post_loops(this,old_new, !may_rce_align);
2839 
2840     // Adjust the pre- and main-loop limits to let the pre and post loops run
2841     // with full checks, but the main-loop with no checks.  Remove said
2842     // checks from the main body.
2843     if (should_rce) {
2844       if (phase->do_range_check(this, old_new) != 0) {
2845         cl->mark_has_range_checks();
2846       }
2847     } else if (PostLoopMultiversioning) {
2848       phase->has_range_checks(this);
2849     }
2850 
2851     if (should_unroll && !should_peel && PostLoopMultiversioning) {
2852       // Try to setup multiversioning on main loops before they are unrolled
2853       if (cl->is_main_loop() && (cl->unrolled_count() == 1)) {
2854         phase->insert_scalar_rced_post_loop(this, old_new);
2855       }
2856     }
2857 
2858     // Double loop body for unrolling.  Adjust the minimum-trip test (will do
2859     // twice as many iterations as before) and the main body limit (only do
2860     // an even number of trips).  If we are peeling, we might enable some RCE
2861     // and we'd rather unroll the post-RCE'd loop SO... do not unroll if
2862     // peeling.
2863     if (should_unroll && !should_peel) {
2864       if (SuperWordLoopUnrollAnalysis) {
2865         phase->insert_vector_post_loop(this, old_new);
2866       }
2867       phase->do_unroll(this, old_new, true);
2868     }
2869 
2870     // Adjust the pre-loop limits to align the main body
2871     // iterations.
2872     if (should_align)
2873       Unimplemented();
2874 
2875   } else {                      // Else we have an unchanged counted loop
2876     if (should_peel)           // Might want to peel but do nothing else
2877       phase->do_peeling(this,old_new);
2878   }
2879   return true;
2880 }
2881 
2882 
2883 //=============================================================================
2884 //------------------------------iteration_split--------------------------------
2885 bool IdealLoopTree::iteration_split( PhaseIdealLoop *phase, Node_List &old_new ) {
2886   // Recursively iteration split nested loops
2887   if (_child && !_child->iteration_split(phase, old_new))
2888     return false;
2889 
2890   // Clean out prior deadwood
2891   DCE_loop_body();
2892 
2893 
2894   // Look for loop-exit tests with my 50/50 guesses from the Parsing stage.
2895   // Replace with a 1-in-10 exit guess.
2896   if (_parent /*not the root loop*/ &&
2897       !_irreducible &&
2898       // Also ignore the occasional dead backedge
2899       !tail()->is_top()) {
2900     adjust_loop_exit_prob(phase);
2901   }
2902 
2903   // Gate unrolling, RCE and peeling efforts.
2904   if (!_child &&                // If not an inner loop, do not split
2905       !_irreducible &&
2906       _allow_optimizations &&
2907       !tail()->is_top()) {     // Also ignore the occasional dead backedge
2908     if (!_has_call) {
2909         if (!iteration_split_impl(phase, old_new)) {
2910           return false;
2911         }
2912     } else if (policy_unswitching(phase)) {
2913       phase->do_unswitching(this, old_new);
2914     }
2915   }
2916 
2917   // Minor offset re-organization to remove loop-fallout uses of
2918   // trip counter when there was no major reshaping.
2919   phase->reorg_offsets(this);
2920 
2921   if (_next && !_next->iteration_split(phase, old_new))
2922     return false;
2923   return true;
2924 }
2925 
2926 
2927 //=============================================================================
2928 // Process all the loops in the loop tree and replace any fill
2929 // patterns with an intrinsic version.
2930 bool PhaseIdealLoop::do_intrinsify_fill() {
2931   bool changed = false;
2932   for (LoopTreeIterator iter(_ltree_root); !iter.done(); iter.next()) {
2933     IdealLoopTree* lpt = iter.current();
2934     changed |= intrinsify_fill(lpt);
2935   }
2936   return changed;
2937 }
2938 
2939 
2940 // Examine an inner loop looking for a a single store of an invariant
2941 // value in a unit stride loop,
2942 bool PhaseIdealLoop::match_fill_loop(IdealLoopTree* lpt, Node*& store, Node*& store_value,
2943                                      Node*& shift, Node*& con) {
2944   const char* msg = NULL;
2945   Node* msg_node = NULL;
2946 
2947   store_value = NULL;
2948   con = NULL;
2949   shift = NULL;
2950 
2951   // Process the loop looking for stores.  If there are multiple
2952   // stores or extra control flow give at this point.
2953   CountedLoopNode* head = lpt->_head->as_CountedLoop();
2954   for (uint i = 0; msg == NULL && i < lpt->_body.size(); i++) {
2955     Node* n = lpt->_body.at(i);
2956     if (n->outcnt() == 0) continue; // Ignore dead
2957     if (n->is_Store()) {
2958       if (store != NULL) {
2959         msg = "multiple stores";
2960         break;
2961       }
2962       int opc = n->Opcode();
2963       if (opc == Op_StoreP || opc == Op_StoreN || opc == Op_StoreNKlass || opc == Op_StoreCM) {
2964         msg = "oop fills not handled";
2965         break;
2966       }
2967       Node* value = n->in(MemNode::ValueIn);
2968       if (!lpt->is_invariant(value)) {
2969         msg  = "variant store value";
2970       } else if (!_igvn.type(n->in(MemNode::Address))->isa_aryptr()) {
2971         msg = "not array address";
2972       }
2973       store = n;
2974       store_value = value;
2975     } else if (n->is_If() && n != head->loopexit()) {
2976       msg = "extra control flow";
2977       msg_node = n;
2978     }
2979   }
2980 
2981   if (store == NULL) {
2982     // No store in loop
2983     return false;
2984   }
2985 
2986   if (msg == NULL && head->stride_con() != 1) {
2987     // could handle negative strides too
2988     if (head->stride_con() < 0) {
2989       msg = "negative stride";
2990     } else {
2991       msg = "non-unit stride";
2992     }
2993   }
2994 
2995   if (msg == NULL && !store->in(MemNode::Address)->is_AddP()) {
2996     msg = "can't handle store address";
2997     msg_node = store->in(MemNode::Address);
2998   }
2999 
3000   if (msg == NULL &&
3001       (!store->in(MemNode::Memory)->is_Phi() ||
3002        store->in(MemNode::Memory)->in(LoopNode::LoopBackControl) != store)) {
3003     msg = "store memory isn't proper phi";
3004     msg_node = store->in(MemNode::Memory);
3005   }
3006 
3007   // Make sure there is an appropriate fill routine
3008   BasicType t = store->as_Mem()->memory_type();
3009   const char* fill_name;
3010   if (msg == NULL &&
3011       StubRoutines::select_fill_function(t, false, fill_name) == NULL) {
3012     msg = "unsupported store";
3013     msg_node = store;
3014   }
3015 
3016   if (msg != NULL) {
3017 #ifndef PRODUCT
3018     if (TraceOptimizeFill) {
3019       tty->print_cr("not fill intrinsic candidate: %s", msg);
3020       if (msg_node != NULL) msg_node->dump();
3021     }
3022 #endif
3023     return false;
3024   }
3025 
3026   // Make sure the address expression can be handled.  It should be
3027   // head->phi * elsize + con.  head->phi might have a ConvI2L(CastII()).
3028   Node* elements[4];
3029   Node* cast = NULL;
3030   Node* conv = NULL;
3031   bool found_index = false;
3032   int count = store->in(MemNode::Address)->as_AddP()->unpack_offsets(elements, ARRAY_SIZE(elements));
3033   for (int e = 0; e < count; e++) {
3034     Node* n = elements[e];
3035     if (n->is_Con() && con == NULL) {
3036       con = n;
3037     } else if (n->Opcode() == Op_LShiftX && shift == NULL) {
3038       Node* value = n->in(1);
3039 #ifdef _LP64
3040       if (value->Opcode() == Op_ConvI2L) {
3041         conv = value;
3042         value = value->in(1);
3043       }
3044       if (value->Opcode() == Op_CastII &&
3045           value->as_CastII()->has_range_check()) {
3046         // Skip range check dependent CastII nodes
3047         cast = value;
3048         value = value->in(1);
3049       }
3050 #endif
3051       if (value != head->phi()) {
3052         msg = "unhandled shift in address";
3053       } else {
3054         if (type2aelembytes(store->as_Mem()->memory_type(), true) != (1 << n->in(2)->get_int())) {
3055           msg = "scale doesn't match";
3056         } else {
3057           found_index = true;
3058           shift = n;
3059         }
3060       }
3061     } else if (n->Opcode() == Op_ConvI2L && conv == NULL) {
3062       conv = n;
3063       n = n->in(1);
3064       if (n->Opcode() == Op_CastII &&
3065           n->as_CastII()->has_range_check()) {
3066         // Skip range check dependent CastII nodes
3067         cast = n;
3068         n = n->in(1);
3069       }
3070       if (n == head->phi()) {
3071         found_index = true;
3072       } else {
3073         msg = "unhandled input to ConvI2L";
3074       }
3075     } else if (n == head->phi()) {
3076       // no shift, check below for allowed cases
3077       found_index = true;
3078     } else {
3079       msg = "unhandled node in address";
3080       msg_node = n;
3081     }
3082   }
3083 
3084   if (count == -1) {
3085     msg = "malformed address expression";
3086     msg_node = store;
3087   }
3088 
3089   if (!found_index) {
3090     msg = "missing use of index";
3091   }
3092 
3093   // byte sized items won't have a shift
3094   if (msg == NULL && shift == NULL && t != T_BYTE && t != T_BOOLEAN) {
3095     msg = "can't find shift";
3096     msg_node = store;
3097   }
3098 
3099   if (msg != NULL) {
3100 #ifndef PRODUCT
3101     if (TraceOptimizeFill) {
3102       tty->print_cr("not fill intrinsic: %s", msg);
3103       if (msg_node != NULL) msg_node->dump();
3104     }
3105 #endif
3106     return false;
3107   }
3108 
3109   // No make sure all the other nodes in the loop can be handled
3110   VectorSet ok(Thread::current()->resource_area());
3111 
3112   // store related values are ok
3113   ok.set(store->_idx);
3114   ok.set(store->in(MemNode::Memory)->_idx);
3115 
3116   CountedLoopEndNode* loop_exit = head->loopexit();
3117   guarantee(loop_exit != NULL, "no loop exit node");
3118 
3119   // Loop structure is ok
3120   ok.set(head->_idx);
3121   ok.set(loop_exit->_idx);
3122   ok.set(head->phi()->_idx);
3123   ok.set(head->incr()->_idx);
3124   ok.set(loop_exit->cmp_node()->_idx);
3125   ok.set(loop_exit->in(1)->_idx);
3126 
3127   // Address elements are ok
3128   if (con)   ok.set(con->_idx);
3129   if (shift) ok.set(shift->_idx);
3130   if (cast)  ok.set(cast->_idx);
3131   if (conv)  ok.set(conv->_idx);
3132 
3133   for (uint i = 0; msg == NULL && i < lpt->_body.size(); i++) {
3134     Node* n = lpt->_body.at(i);
3135     if (n->outcnt() == 0) continue; // Ignore dead
3136     if (ok.test(n->_idx)) continue;
3137     // Backedge projection is ok
3138     if (n->is_IfTrue() && n->in(0) == loop_exit) continue;
3139     if (!n->is_AddP()) {
3140       msg = "unhandled node";
3141       msg_node = n;
3142       break;
3143     }
3144   }
3145 
3146   // Make sure no unexpected values are used outside the loop
3147   for (uint i = 0; msg == NULL && i < lpt->_body.size(); i++) {
3148     Node* n = lpt->_body.at(i);
3149     // These values can be replaced with other nodes if they are used
3150     // outside the loop.
3151     if (n == store || n == loop_exit || n == head->incr() || n == store->in(MemNode::Memory)) continue;
3152     for (SimpleDUIterator iter(n); iter.has_next(); iter.next()) {
3153       Node* use = iter.get();
3154       if (!lpt->_body.contains(use)) {
3155         msg = "node is used outside loop";
3156         // lpt->_body.dump();
3157         msg_node = n;
3158         break;
3159       }
3160     }
3161   }
3162 
3163 #ifdef ASSERT
3164   if (TraceOptimizeFill) {
3165     if (msg != NULL) {
3166       tty->print_cr("no fill intrinsic: %s", msg);
3167       if (msg_node != NULL) msg_node->dump();
3168     } else {
3169       tty->print_cr("fill intrinsic for:");
3170     }
3171     store->dump();
3172     if (Verbose) {
3173       lpt->_body.dump();
3174     }
3175   }
3176 #endif
3177 
3178   return msg == NULL;
3179 }
3180 
3181 
3182 
3183 bool PhaseIdealLoop::intrinsify_fill(IdealLoopTree* lpt) {
3184   // Only for counted inner loops
3185   if (!lpt->is_counted() || !lpt->is_inner()) {
3186     return false;
3187   }
3188 
3189   // Must have constant stride
3190   CountedLoopNode* head = lpt->_head->as_CountedLoop();
3191   if (!head->is_valid_counted_loop() || !head->is_normal_loop()) {
3192     return false;
3193   }
3194 
3195   head->verify_strip_mined(1);
3196 
3197   // Check that the body only contains a store of a loop invariant
3198   // value that is indexed by the loop phi.
3199   Node* store = NULL;
3200   Node* store_value = NULL;
3201   Node* shift = NULL;
3202   Node* offset = NULL;
3203   if (!match_fill_loop(lpt, store, store_value, shift, offset)) {
3204     return false;
3205   }
3206 
3207   Node* exit = head->loopexit()->proj_out(0);
3208   if (exit == NULL) {
3209     return false;
3210   }
3211 
3212 #ifndef PRODUCT
3213   if (TraceLoopOpts) {
3214     tty->print("ArrayFill    ");
3215     lpt->dump_head();
3216   }
3217 #endif
3218 
3219   // Now replace the whole loop body by a call to a fill routine that
3220   // covers the same region as the loop.
3221   Node* base = store->in(MemNode::Address)->as_AddP()->in(AddPNode::Base);
3222 
3223   // Build an expression for the beginning of the copy region
3224   Node* index = head->init_trip();
3225 #ifdef _LP64
3226   index = new ConvI2LNode(index);
3227   _igvn.register_new_node_with_optimizer(index);
3228 #endif
3229   if (shift != NULL) {
3230     // byte arrays don't require a shift but others do.
3231     index = new LShiftXNode(index, shift->in(2));
3232     _igvn.register_new_node_with_optimizer(index);
3233   }
3234   index = new AddPNode(base, base, index);
3235   _igvn.register_new_node_with_optimizer(index);
3236   Node* from = new AddPNode(base, index, offset);
3237   _igvn.register_new_node_with_optimizer(from);
3238   // Compute the number of elements to copy
3239   Node* len = new SubINode(head->limit(), head->init_trip());
3240   _igvn.register_new_node_with_optimizer(len);
3241 
3242   BasicType t = store->as_Mem()->memory_type();
3243   bool aligned = false;
3244   if (offset != NULL && head->init_trip()->is_Con()) {
3245     int element_size = type2aelembytes(t);
3246     aligned = (offset->find_intptr_t_type()->get_con() + head->init_trip()->get_int() * element_size) % HeapWordSize == 0;
3247   }
3248 
3249   // Build a call to the fill routine
3250   const char* fill_name;
3251   address fill = StubRoutines::select_fill_function(t, aligned, fill_name);
3252   assert(fill != NULL, "what?");
3253 
3254   // Convert float/double to int/long for fill routines
3255   if (t == T_FLOAT) {
3256     store_value = new MoveF2INode(store_value);
3257     _igvn.register_new_node_with_optimizer(store_value);
3258   } else if (t == T_DOUBLE) {
3259     store_value = new MoveD2LNode(store_value);
3260     _igvn.register_new_node_with_optimizer(store_value);
3261   }
3262 
3263   Node* mem_phi = store->in(MemNode::Memory);
3264   Node* result_ctrl;
3265   Node* result_mem;
3266   const TypeFunc* call_type = OptoRuntime::array_fill_Type();
3267   CallLeafNode *call = new CallLeafNoFPNode(call_type, fill,
3268                                             fill_name, TypeAryPtr::get_array_body_type(t));
3269   uint cnt = 0;
3270   call->init_req(TypeFunc::Parms + cnt++, from);
3271   call->init_req(TypeFunc::Parms + cnt++, store_value);
3272 #ifdef _LP64
3273   len = new ConvI2LNode(len);
3274   _igvn.register_new_node_with_optimizer(len);
3275 #endif
3276   call->init_req(TypeFunc::Parms + cnt++, len);
3277 #ifdef _LP64
3278   call->init_req(TypeFunc::Parms + cnt++, C->top());
3279 #endif
3280   call->init_req(TypeFunc::Control,   head->init_control());
3281   call->init_req(TypeFunc::I_O,       C->top());       // Does no I/O.
3282   call->init_req(TypeFunc::Memory,    mem_phi->in(LoopNode::EntryControl));
3283   call->init_req(TypeFunc::ReturnAdr, C->start()->proj_out(TypeFunc::ReturnAdr));
3284   call->init_req(TypeFunc::FramePtr,  C->start()->proj_out(TypeFunc::FramePtr));
3285   _igvn.register_new_node_with_optimizer(call);
3286   result_ctrl = new ProjNode(call,TypeFunc::Control);
3287   _igvn.register_new_node_with_optimizer(result_ctrl);
3288   result_mem = new ProjNode(call,TypeFunc::Memory);
3289   _igvn.register_new_node_with_optimizer(result_mem);
3290 
3291 /* Disable following optimization until proper fix (add missing checks).
3292 
3293   // If this fill is tightly coupled to an allocation and overwrites
3294   // the whole body, allow it to take over the zeroing.
3295   AllocateNode* alloc = AllocateNode::Ideal_allocation(base, this);
3296   if (alloc != NULL && alloc->is_AllocateArray()) {
3297     Node* length = alloc->as_AllocateArray()->Ideal_length();
3298     if (head->limit() == length &&
3299         head->init_trip() == _igvn.intcon(0)) {
3300       if (TraceOptimizeFill) {
3301         tty->print_cr("Eliminated zeroing in allocation");
3302       }
3303       alloc->maybe_set_complete(&_igvn);
3304     } else {
3305 #ifdef ASSERT
3306       if (TraceOptimizeFill) {
3307         tty->print_cr("filling array but bounds don't match");
3308         alloc->dump();
3309         head->init_trip()->dump();
3310         head->limit()->dump();
3311         length->dump();
3312       }
3313 #endif
3314     }
3315   }
3316 */
3317 
3318   if (head->is_strip_mined()) {
3319     // Inner strip mined loop goes away so get rid of outer strip
3320     // mined loop
3321     Node* outer_sfpt = head->outer_safepoint();
3322     Node* in = outer_sfpt->in(0);
3323     Node* outer_out = head->outer_loop_exit();
3324     lazy_replace(outer_out, in);
3325     _igvn.replace_input_of(outer_sfpt, 0, C->top());
3326   }
3327 
3328   // Redirect the old control and memory edges that are outside the loop.
3329   // Sometimes the memory phi of the head is used as the outgoing
3330   // state of the loop.  It's safe in this case to replace it with the
3331   // result_mem.
3332   _igvn.replace_node(store->in(MemNode::Memory), result_mem);
3333   lazy_replace(exit, result_ctrl);
3334   _igvn.replace_node(store, result_mem);
3335   // Any uses the increment outside of the loop become the loop limit.
3336   _igvn.replace_node(head->incr(), head->limit());
3337 
3338   // Disconnect the head from the loop.
3339   for (uint i = 0; i < lpt->_body.size(); i++) {
3340     Node* n = lpt->_body.at(i);
3341     _igvn.replace_node(n, C->top());
3342   }
3343 
3344   return true;
3345 }