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