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