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