1 /* 2 * Copyright (c) 1999, 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 "gc/shared/barrierSet.hpp" 26 #include "gc/shared/c2/barrierSetC2.hpp" 27 #include "memory/allocation.inline.hpp" 28 #include "memory/resourceArea.hpp" 29 #include "opto/addnode.hpp" 30 #include "opto/callnode.hpp" 31 #include "opto/castnode.hpp" 32 #include "opto/connode.hpp" 33 #include "opto/divnode.hpp" 34 #include "opto/inlinetypenode.hpp" 35 #include "opto/loopnode.hpp" 36 #include "opto/matcher.hpp" 37 #include "opto/movenode.hpp" 38 #include "opto/mulnode.hpp" 39 #include "opto/opaquenode.hpp" 40 #include "opto/rootnode.hpp" 41 #include "opto/subnode.hpp" 42 #include "opto/subtypenode.hpp" 43 #include "opto/superword.hpp" 44 #include "opto/vectornode.hpp" 45 #include "utilities/checkedCast.hpp" 46 #include "utilities/macros.hpp" 47 48 //============================================================================= 49 //------------------------------split_thru_phi--------------------------------- 50 // Split Node 'n' through merge point if there is enough win. 51 Node* PhaseIdealLoop::split_thru_phi(Node* n, Node* region, int policy) { 52 if ((n->Opcode() == Op_ConvI2L && n->bottom_type() != TypeLong::LONG) || 53 (n->Opcode() == Op_ConvL2I && n->bottom_type() != TypeInt::INT)) { 54 // ConvI2L/ConvL2I may have type information on it which is unsafe to push up 55 // so disable this for now 56 return nullptr; 57 } 58 59 // Splitting range check CastIIs through a loop induction Phi can 60 // cause new Phis to be created that are left unrelated to the loop 61 // induction Phi and prevent optimizations (vectorization) 62 if (n->Opcode() == Op_CastII && region->is_CountedLoop() && 63 n->in(1) == region->as_CountedLoop()->phi()) { 64 return nullptr; 65 } 66 67 // Inline types should not be split through Phis because they cannot be merged 68 // through Phi nodes but each value input needs to be merged individually. 69 if (n->is_InlineType()) { 70 return nullptr; 71 } 72 73 if (cannot_split_division(n, region)) { 74 return nullptr; 75 } 76 77 SplitThruPhiWins wins(region); 78 assert(!n->is_CFG(), ""); 79 assert(region->is_Region(), ""); 80 81 const Type* type = n->bottom_type(); 82 const TypeOopPtr* t_oop = _igvn.type(n)->isa_oopptr(); 83 Node* phi; 84 if (t_oop != nullptr && t_oop->is_known_instance_field()) { 85 int iid = t_oop->instance_id(); 86 int index = C->get_alias_index(t_oop); 87 int offset = t_oop->offset(); 88 phi = new PhiNode(region, type, nullptr, iid, index, offset); 89 } else { 90 phi = PhiNode::make_blank(region, n); 91 } 92 uint old_unique = C->unique(); 93 for (uint i = 1; i < region->req(); i++) { 94 Node* x; 95 Node* the_clone = nullptr; 96 if (region->in(i) == C->top()) { 97 x = C->top(); // Dead path? Use a dead data op 98 } else { 99 x = n->clone(); // Else clone up the data op 100 the_clone = x; // Remember for possible deletion. 101 // Alter data node to use pre-phi inputs 102 if (n->in(0) == region) 103 x->set_req( 0, region->in(i) ); 104 for (uint j = 1; j < n->req(); j++) { 105 Node* in = n->in(j); 106 if (in->is_Phi() && in->in(0) == region) 107 x->set_req(j, in->in(i)); // Use pre-Phi input for the clone 108 } 109 } 110 // Check for a 'win' on some paths 111 const Type* t = x->Value(&_igvn); 112 113 bool singleton = t->singleton(); 114 115 // A TOP singleton indicates that there are no possible values incoming 116 // along a particular edge. In most cases, this is OK, and the Phi will 117 // be eliminated later in an Ideal call. However, we can't allow this to 118 // happen if the singleton occurs on loop entry, as the elimination of 119 // the PhiNode may cause the resulting node to migrate back to a previous 120 // loop iteration. 121 if (singleton && t == Type::TOP) { 122 // Is_Loop() == false does not confirm the absence of a loop (e.g., an 123 // irreducible loop may not be indicated by an affirmative is_Loop()); 124 // therefore, the only top we can split thru a phi is on a backedge of 125 // a loop. 126 singleton &= region->is_Loop() && (i != LoopNode::EntryControl); 127 } 128 129 if (singleton) { 130 wins.add_win(i); 131 x = makecon(t); 132 } else { 133 // We now call Identity to try to simplify the cloned node. 134 // Note that some Identity methods call phase->type(this). 135 // Make sure that the type array is big enough for 136 // our new node, even though we may throw the node away. 137 // (Note: This tweaking with igvn only works because x is a new node.) 138 _igvn.set_type(x, t); 139 // If x is a TypeNode, capture any more-precise type permanently into Node 140 // otherwise it will be not updated during igvn->transform since 141 // igvn->type(x) is set to x->Value() already. 142 x->raise_bottom_type(t); 143 Node* y = x->Identity(&_igvn); 144 if (y != x) { 145 wins.add_win(i); 146 x = y; 147 } else { 148 y = _igvn.hash_find(x); 149 if (y == nullptr) { 150 y = similar_subtype_check(x, region->in(i)); 151 } 152 if (y) { 153 wins.add_win(i); 154 x = y; 155 } else { 156 // Else x is a new node we are keeping 157 // We do not need register_new_node_with_optimizer 158 // because set_type has already been called. 159 _igvn._worklist.push(x); 160 } 161 } 162 } 163 164 phi->set_req( i, x ); 165 166 if (the_clone == nullptr) { 167 continue; 168 } 169 170 if (the_clone != x) { 171 _igvn.remove_dead_node(the_clone); 172 } else if (region->is_Loop() && i == LoopNode::LoopBackControl && 173 n->is_Load() && can_move_to_inner_loop(n, region->as_Loop(), x)) { 174 // it is not a win if 'x' moved from an outer to an inner loop 175 // this edge case can only happen for Load nodes 176 wins.reset(); 177 break; 178 } 179 } 180 // Too few wins? 181 if (!wins.profitable(policy)) { 182 _igvn.remove_dead_node(phi); 183 return nullptr; 184 } 185 186 // Record Phi 187 register_new_node( phi, region ); 188 189 for (uint i2 = 1; i2 < phi->req(); i2++) { 190 Node *x = phi->in(i2); 191 // If we commoned up the cloned 'x' with another existing Node, 192 // the existing Node picks up a new use. We need to make the 193 // existing Node occur higher up so it dominates its uses. 194 Node *old_ctrl; 195 IdealLoopTree *old_loop; 196 197 if (x->is_Con()) { 198 assert(get_ctrl(x) == C->root(), "constant control is not root"); 199 continue; 200 } 201 // The occasional new node 202 if (x->_idx >= old_unique) { // Found a new, unplaced node? 203 old_ctrl = nullptr; 204 old_loop = nullptr; // Not in any prior loop 205 } else { 206 old_ctrl = get_ctrl(x); 207 old_loop = get_loop(old_ctrl); // Get prior loop 208 } 209 // New late point must dominate new use 210 Node *new_ctrl = dom_lca(old_ctrl, region->in(i2)); 211 if (new_ctrl == old_ctrl) // Nothing is changed 212 continue; 213 214 IdealLoopTree *new_loop = get_loop(new_ctrl); 215 216 // Don't move x into a loop if its uses are 217 // outside of loop. Otherwise x will be cloned 218 // for each use outside of this loop. 219 IdealLoopTree *use_loop = get_loop(region); 220 if (!new_loop->is_member(use_loop) && 221 (old_loop == nullptr || !new_loop->is_member(old_loop))) { 222 // Take early control, later control will be recalculated 223 // during next iteration of loop optimizations. 224 new_ctrl = get_early_ctrl(x); 225 new_loop = get_loop(new_ctrl); 226 } 227 // Set new location 228 set_ctrl(x, new_ctrl); 229 // If changing loop bodies, see if we need to collect into new body 230 if (old_loop != new_loop) { 231 if (old_loop && !old_loop->_child) 232 old_loop->_body.yank(x); 233 if (!new_loop->_child) 234 new_loop->_body.push(x); // Collect body info 235 } 236 } 237 238 #ifndef PRODUCT 239 if (TraceLoopOpts) { 240 tty->print("Split %d %s through %d Phi in %d %s", 241 n->_idx, n->Name(), phi->_idx, region->_idx, region->Name()); 242 } 243 #endif // !PRODUCT 244 245 return phi; 246 } 247 248 // Test whether node 'x' can move into an inner loop relative to node 'n'. 249 // Note: The test is not exact. Returns true if 'x' COULD end up in an inner loop, 250 // BUT it can also return true and 'x' is in the outer loop 251 bool PhaseIdealLoop::can_move_to_inner_loop(Node* n, LoopNode* n_loop, Node* x) { 252 IdealLoopTree* n_loop_tree = get_loop(n_loop); 253 IdealLoopTree* x_loop_tree = get_loop(get_early_ctrl(x)); 254 // x_loop_tree should be outer or same loop as n_loop_tree 255 return !x_loop_tree->is_member(n_loop_tree); 256 } 257 258 // Subtype checks that carry profile data don't common so look for a replacement by following edges 259 Node* PhaseIdealLoop::similar_subtype_check(const Node* x, Node* r_in) { 260 if (x->is_SubTypeCheck()) { 261 Node* in1 = x->in(1); 262 for (DUIterator_Fast imax, i = in1->fast_outs(imax); i < imax; i++) { 263 Node* u = in1->fast_out(i); 264 if (u != x && u->is_SubTypeCheck() && u->in(1) == x->in(1) && u->in(2) == x->in(2)) { 265 for (DUIterator_Fast jmax, j = u->fast_outs(jmax); j < jmax; j++) { 266 Node* bol = u->fast_out(j); 267 for (DUIterator_Fast kmax, k = bol->fast_outs(kmax); k < kmax; k++) { 268 Node* iff = bol->fast_out(k); 269 // Only dominating subtype checks are interesting: otherwise we risk replacing a subtype check by another with 270 // unrelated profile 271 if (iff->is_If() && is_dominator(iff, r_in)) { 272 return u; 273 } 274 } 275 } 276 } 277 } 278 } 279 return nullptr; 280 } 281 282 // Return true if 'n' is a Div or Mod node (without zero check If node which was removed earlier) with a loop phi divisor 283 // of a trip-counted (integer or long) loop with a backedge input that could be zero (include zero in its type range). In 284 // this case, we cannot split the division to the backedge as it could freely float above the loop exit check resulting in 285 // a division by zero. This situation is possible because the type of an increment node of an iv phi (trip-counter) could 286 // include zero while the iv phi does not (see PhiNode::Value() for trip-counted loops where we improve types of iv phis). 287 // We also need to check other loop phis as they could have been created in the same split-if pass when applying 288 // PhaseIdealLoop::split_thru_phi() to split nodes through an iv phi. 289 bool PhaseIdealLoop::cannot_split_division(const Node* n, const Node* region) const { 290 const Type* zero; 291 switch (n->Opcode()) { 292 case Op_DivI: 293 case Op_ModI: 294 case Op_UDivI: 295 case Op_UModI: 296 zero = TypeInt::ZERO; 297 break; 298 case Op_DivL: 299 case Op_ModL: 300 case Op_UDivL: 301 case Op_UModL: 302 zero = TypeLong::ZERO; 303 break; 304 default: 305 return false; 306 } 307 308 if (n->in(0) != nullptr) { 309 // Cannot split through phi if Div or Mod node has a control dependency to a zero check. 310 return true; 311 } 312 313 Node* divisor = n->in(2); 314 return is_divisor_loop_phi(divisor, region) && 315 loop_phi_backedge_type_contains_zero(divisor, zero); 316 } 317 318 bool PhaseIdealLoop::is_divisor_loop_phi(const Node* divisor, const Node* loop) { 319 return loop->is_Loop() && divisor->is_Phi() && divisor->in(0) == loop; 320 } 321 322 bool PhaseIdealLoop::loop_phi_backedge_type_contains_zero(const Node* phi_divisor, const Type* zero) const { 323 return _igvn.type(phi_divisor->in(LoopNode::LoopBackControl))->filter_speculative(zero) != Type::TOP; 324 } 325 326 //------------------------------dominated_by------------------------------------ 327 // Replace the dominated test with an obvious true or false. Place it on the 328 // IGVN worklist for later cleanup. Move control-dependent data Nodes on the 329 // live path up to the dominating control. 330 void PhaseIdealLoop::dominated_by(IfProjNode* prevdom, IfNode* iff, bool flip, bool pin_array_access_nodes) { 331 if (VerifyLoopOptimizations && PrintOpto) { tty->print_cr("dominating test"); } 332 333 // prevdom is the dominating projection of the dominating test. 334 assert(iff->Opcode() == Op_If || 335 iff->Opcode() == Op_CountedLoopEnd || 336 iff->Opcode() == Op_LongCountedLoopEnd || 337 iff->Opcode() == Op_RangeCheck || 338 iff->Opcode() == Op_ParsePredicate, 339 "Check this code when new subtype is added"); 340 341 int pop = prevdom->Opcode(); 342 assert( pop == Op_IfFalse || pop == Op_IfTrue, "" ); 343 if (flip) { 344 if (pop == Op_IfTrue) 345 pop = Op_IfFalse; 346 else 347 pop = Op_IfTrue; 348 } 349 // 'con' is set to true or false to kill the dominated test. 350 Node* con = makecon(pop == Op_IfTrue ? TypeInt::ONE : TypeInt::ZERO); 351 // Hack the dominated test 352 _igvn.replace_input_of(iff, 1, con); 353 354 // If I don't have a reachable TRUE and FALSE path following the IfNode then 355 // I can assume this path reaches an infinite loop. In this case it's not 356 // important to optimize the data Nodes - either the whole compilation will 357 // be tossed or this path (and all data Nodes) will go dead. 358 if (iff->outcnt() != 2) { 359 return; 360 } 361 362 // Make control-dependent data Nodes on the live path (path that will remain 363 // once the dominated IF is removed) become control-dependent on the 364 // dominating projection. 365 Node* dp = iff->proj_out_or_null(pop == Op_IfTrue); 366 367 if (dp == nullptr) { 368 return; 369 } 370 371 rewire_safe_outputs_to_dominator(dp, prevdom, pin_array_access_nodes); 372 } 373 374 void PhaseIdealLoop::rewire_safe_outputs_to_dominator(Node* source, Node* dominator, const bool pin_array_access_nodes) { 375 IdealLoopTree* old_loop = get_loop(source); 376 377 for (DUIterator_Fast imax, i = source->fast_outs(imax); i < imax; i++) { 378 Node* out = source->fast_out(i); // Control-dependent node 379 // Do not rewire Div and Mod nodes which could have a zero divisor to avoid skipping their zero check. 380 if (out->depends_only_on_test() && _igvn.no_dependent_zero_check(out)) { 381 assert(out->in(0) == source, "must be control dependent on source"); 382 _igvn.replace_input_of(out, 0, dominator); 383 if (pin_array_access_nodes) { 384 // Because of Loop Predication, Loads and range check Cast nodes that are control dependent on this range 385 // check (that is about to be removed) now depend on multiple dominating Hoisted Check Predicates. After the 386 // removal of this range check, these control dependent nodes end up at the lowest/nearest dominating predicate 387 // in the graph. To ensure that these Loads/Casts do not float above any of the dominating checks (even when the 388 // lowest dominating check is later replaced by yet another dominating check), we need to pin them at the lowest 389 // dominating check. 390 Node* clone = out->pin_array_access_node(); 391 if (clone != nullptr) { 392 clone = _igvn.register_new_node_with_optimizer(clone, out); 393 _igvn.replace_node(out, clone); 394 out = clone; 395 } 396 } 397 set_early_ctrl(out, false); 398 IdealLoopTree* new_loop = get_loop(get_ctrl(out)); 399 if (old_loop != new_loop) { 400 if (!old_loop->_child) { 401 old_loop->_body.yank(out); 402 } 403 if (!new_loop->_child) { 404 new_loop->_body.push(out); 405 } 406 } 407 --i; 408 --imax; 409 } 410 } 411 } 412 413 //------------------------------has_local_phi_input---------------------------- 414 // Return TRUE if 'n' has Phi inputs from its local block and no other 415 // block-local inputs (all non-local-phi inputs come from earlier blocks) 416 Node *PhaseIdealLoop::has_local_phi_input( Node *n ) { 417 Node *n_ctrl = get_ctrl(n); 418 // See if some inputs come from a Phi in this block, or from before 419 // this block. 420 uint i; 421 for( i = 1; i < n->req(); i++ ) { 422 Node *phi = n->in(i); 423 if( phi->is_Phi() && phi->in(0) == n_ctrl ) 424 break; 425 } 426 if( i >= n->req() ) 427 return nullptr; // No Phi inputs; nowhere to clone thru 428 429 // Check for inputs created between 'n' and the Phi input. These 430 // must split as well; they have already been given the chance 431 // (courtesy of a post-order visit) and since they did not we must 432 // recover the 'cost' of splitting them by being very profitable 433 // when splitting 'n'. Since this is unlikely we simply give up. 434 for( i = 1; i < n->req(); i++ ) { 435 Node *m = n->in(i); 436 if( get_ctrl(m) == n_ctrl && !m->is_Phi() ) { 437 // We allow the special case of AddP's with no local inputs. 438 // This allows us to split-up address expressions. 439 if (m->is_AddP() && 440 get_ctrl(m->in(AddPNode::Base)) != n_ctrl && 441 get_ctrl(m->in(AddPNode::Address)) != n_ctrl && 442 get_ctrl(m->in(AddPNode::Offset)) != n_ctrl) { 443 // Move the AddP up to the dominating point. That's fine because control of m's inputs 444 // must dominate get_ctrl(m) == n_ctrl and we just checked that the input controls are != n_ctrl. 445 Node* c = find_non_split_ctrl(idom(n_ctrl)); 446 if (c->is_OuterStripMinedLoop()) { 447 c->as_Loop()->verify_strip_mined(1); 448 c = c->in(LoopNode::EntryControl); 449 } 450 set_ctrl_and_loop(m, c); 451 continue; 452 } 453 return nullptr; 454 } 455 assert(n->is_Phi() || m->is_Phi() || is_dominator(get_ctrl(m), n_ctrl), "m has strange control"); 456 } 457 458 return n_ctrl; 459 } 460 461 // Replace expressions like ((V+I) << 2) with (V<<2 + I<<2). 462 Node* PhaseIdealLoop::remix_address_expressions_add_left_shift(Node* n, IdealLoopTree* n_loop, Node* n_ctrl, BasicType bt) { 463 assert(bt == T_INT || bt == T_LONG, "only for integers"); 464 int n_op = n->Opcode(); 465 466 if (n_op == Op_LShift(bt)) { 467 // Scale is loop invariant 468 Node* scale = n->in(2); 469 Node* scale_ctrl = get_ctrl(scale); 470 IdealLoopTree* scale_loop = get_loop(scale_ctrl); 471 if (n_loop == scale_loop || !scale_loop->is_member(n_loop)) { 472 return nullptr; 473 } 474 const TypeInt* scale_t = scale->bottom_type()->isa_int(); 475 if (scale_t != nullptr && scale_t->is_con() && scale_t->get_con() >= 16) { 476 return nullptr; // Dont bother with byte/short masking 477 } 478 // Add must vary with loop (else shift would be loop-invariant) 479 Node* add = n->in(1); 480 Node* add_ctrl = get_ctrl(add); 481 IdealLoopTree* add_loop = get_loop(add_ctrl); 482 if (n_loop != add_loop) { 483 return nullptr; // happens w/ evil ZKM loops 484 } 485 486 // Convert I-V into I+ (0-V); same for V-I 487 if (add->Opcode() == Op_Sub(bt) && 488 _igvn.type(add->in(1)) != TypeInteger::zero(bt)) { 489 assert(add->Opcode() == Op_SubI || add->Opcode() == Op_SubL, ""); 490 Node* zero = integercon(0, bt); 491 Node* neg = SubNode::make(zero, add->in(2), bt); 492 register_new_node_with_ctrl_of(neg, add->in(2)); 493 add = AddNode::make(add->in(1), neg, bt); 494 register_new_node(add, add_ctrl); 495 } 496 if (add->Opcode() != Op_Add(bt)) return nullptr; 497 assert(add->Opcode() == Op_AddI || add->Opcode() == Op_AddL, ""); 498 // See if one add input is loop invariant 499 Node* add_var = add->in(1); 500 Node* add_var_ctrl = get_ctrl(add_var); 501 IdealLoopTree* add_var_loop = get_loop(add_var_ctrl); 502 Node* add_invar = add->in(2); 503 Node* add_invar_ctrl = get_ctrl(add_invar); 504 IdealLoopTree* add_invar_loop = get_loop(add_invar_ctrl); 505 if (add_invar_loop == n_loop) { 506 // Swap to find the invariant part 507 add_invar = add_var; 508 add_invar_ctrl = add_var_ctrl; 509 add_invar_loop = add_var_loop; 510 add_var = add->in(2); 511 } else if (add_var_loop != n_loop) { // Else neither input is loop invariant 512 return nullptr; 513 } 514 if (n_loop == add_invar_loop || !add_invar_loop->is_member(n_loop)) { 515 return nullptr; // No invariant part of the add? 516 } 517 518 // Yes! Reshape address expression! 519 Node* inv_scale = LShiftNode::make(add_invar, scale, bt); 520 Node* inv_scale_ctrl = 521 dom_depth(add_invar_ctrl) > dom_depth(scale_ctrl) ? 522 add_invar_ctrl : scale_ctrl; 523 register_new_node(inv_scale, inv_scale_ctrl); 524 Node* var_scale = LShiftNode::make(add_var, scale, bt); 525 register_new_node(var_scale, n_ctrl); 526 Node* var_add = AddNode::make(var_scale, inv_scale, bt); 527 register_new_node(var_add, n_ctrl); 528 _igvn.replace_node(n, var_add); 529 return var_add; 530 } 531 return nullptr; 532 } 533 534 //------------------------------remix_address_expressions---------------------- 535 // Rework addressing expressions to get the most loop-invariant stuff 536 // moved out. We'd like to do all associative operators, but it's especially 537 // important (common) to do address expressions. 538 Node* PhaseIdealLoop::remix_address_expressions(Node* n) { 539 if (!has_ctrl(n)) return nullptr; 540 Node* n_ctrl = get_ctrl(n); 541 IdealLoopTree* n_loop = get_loop(n_ctrl); 542 543 // See if 'n' mixes loop-varying and loop-invariant inputs and 544 // itself is loop-varying. 545 546 // Only interested in binary ops (and AddP) 547 if (n->req() < 3 || n->req() > 4) return nullptr; 548 549 Node* n1_ctrl = get_ctrl(n->in( 1)); 550 Node* n2_ctrl = get_ctrl(n->in( 2)); 551 Node* n3_ctrl = get_ctrl(n->in(n->req() == 3 ? 2 : 3)); 552 IdealLoopTree* n1_loop = get_loop(n1_ctrl); 553 IdealLoopTree* n2_loop = get_loop(n2_ctrl); 554 IdealLoopTree* n3_loop = get_loop(n3_ctrl); 555 556 // Does one of my inputs spin in a tighter loop than self? 557 if ((n_loop->is_member(n1_loop) && n_loop != n1_loop) || 558 (n_loop->is_member(n2_loop) && n_loop != n2_loop) || 559 (n_loop->is_member(n3_loop) && n_loop != n3_loop)) { 560 return nullptr; // Leave well enough alone 561 } 562 563 // Is at least one of my inputs loop-invariant? 564 if (n1_loop == n_loop && 565 n2_loop == n_loop && 566 n3_loop == n_loop) { 567 return nullptr; // No loop-invariant inputs 568 } 569 570 Node* res = remix_address_expressions_add_left_shift(n, n_loop, n_ctrl, T_INT); 571 if (res != nullptr) { 572 return res; 573 } 574 res = remix_address_expressions_add_left_shift(n, n_loop, n_ctrl, T_LONG); 575 if (res != nullptr) { 576 return res; 577 } 578 579 int n_op = n->Opcode(); 580 // Replace (I+V) with (V+I) 581 if (n_op == Op_AddI || 582 n_op == Op_AddL || 583 n_op == Op_AddF || 584 n_op == Op_AddD || 585 n_op == Op_MulI || 586 n_op == Op_MulL || 587 n_op == Op_MulF || 588 n_op == Op_MulD) { 589 if (n2_loop == n_loop) { 590 assert(n1_loop != n_loop, ""); 591 n->swap_edges(1, 2); 592 } 593 } 594 595 // Replace ((I1 +p V) +p I2) with ((I1 +p I2) +p V), 596 // but not if I2 is a constant. Skip for irreducible loops. 597 if (n_op == Op_AddP && n_loop->_head->is_Loop()) { 598 if (n2_loop == n_loop && n3_loop != n_loop) { 599 if (n->in(2)->Opcode() == Op_AddP && !n->in(3)->is_Con()) { 600 Node* n22_ctrl = get_ctrl(n->in(2)->in(2)); 601 Node* n23_ctrl = get_ctrl(n->in(2)->in(3)); 602 IdealLoopTree* n22loop = get_loop(n22_ctrl); 603 IdealLoopTree* n23_loop = get_loop(n23_ctrl); 604 if (n22loop != n_loop && n22loop->is_member(n_loop) && 605 n23_loop == n_loop) { 606 Node* add1 = new AddPNode(n->in(1), n->in(2)->in(2), n->in(3)); 607 // Stuff new AddP in the loop preheader 608 register_new_node(add1, n_loop->_head->as_Loop()->skip_strip_mined(1)->in(LoopNode::EntryControl)); 609 Node* add2 = new AddPNode(n->in(1), add1, n->in(2)->in(3)); 610 register_new_node(add2, n_ctrl); 611 _igvn.replace_node(n, add2); 612 return add2; 613 } 614 } 615 } 616 617 // Replace (I1 +p (I2 + V)) with ((I1 +p I2) +p V) 618 if (n2_loop != n_loop && n3_loop == n_loop) { 619 if (n->in(3)->Opcode() == Op_AddX) { 620 Node* V = n->in(3)->in(1); 621 Node* I = n->in(3)->in(2); 622 if (is_member(n_loop,get_ctrl(V))) { 623 } else { 624 Node *tmp = V; V = I; I = tmp; 625 } 626 if (!is_member(n_loop,get_ctrl(I))) { 627 Node* add1 = new AddPNode(n->in(1), n->in(2), I); 628 // Stuff new AddP in the loop preheader 629 register_new_node(add1, n_loop->_head->as_Loop()->skip_strip_mined(1)->in(LoopNode::EntryControl)); 630 Node* add2 = new AddPNode(n->in(1), add1, V); 631 register_new_node(add2, n_ctrl); 632 _igvn.replace_node(n, add2); 633 return add2; 634 } 635 } 636 } 637 } 638 639 return nullptr; 640 } 641 642 // Optimize ((in1[2*i] * in2[2*i]) + (in1[2*i+1] * in2[2*i+1])) 643 Node *PhaseIdealLoop::convert_add_to_muladd(Node* n) { 644 assert(n->Opcode() == Op_AddI, "sanity"); 645 Node * nn = nullptr; 646 Node * in1 = n->in(1); 647 Node * in2 = n->in(2); 648 if (in1->Opcode() == Op_MulI && in2->Opcode() == Op_MulI) { 649 IdealLoopTree* loop_n = get_loop(get_ctrl(n)); 650 if (loop_n->is_counted() && 651 loop_n->_head->as_Loop()->is_valid_counted_loop(T_INT) && 652 Matcher::match_rule_supported(Op_MulAddVS2VI) && 653 Matcher::match_rule_supported(Op_MulAddS2I)) { 654 Node* mul_in1 = in1->in(1); 655 Node* mul_in2 = in1->in(2); 656 Node* mul_in3 = in2->in(1); 657 Node* mul_in4 = in2->in(2); 658 if (mul_in1->Opcode() == Op_LoadS && 659 mul_in2->Opcode() == Op_LoadS && 660 mul_in3->Opcode() == Op_LoadS && 661 mul_in4->Opcode() == Op_LoadS) { 662 IdealLoopTree* loop1 = get_loop(get_ctrl(mul_in1)); 663 IdealLoopTree* loop2 = get_loop(get_ctrl(mul_in2)); 664 IdealLoopTree* loop3 = get_loop(get_ctrl(mul_in3)); 665 IdealLoopTree* loop4 = get_loop(get_ctrl(mul_in4)); 666 IdealLoopTree* loop5 = get_loop(get_ctrl(in1)); 667 IdealLoopTree* loop6 = get_loop(get_ctrl(in2)); 668 // All nodes should be in the same counted loop. 669 if (loop_n == loop1 && loop_n == loop2 && loop_n == loop3 && 670 loop_n == loop4 && loop_n == loop5 && loop_n == loop6) { 671 Node* adr1 = mul_in1->in(MemNode::Address); 672 Node* adr2 = mul_in2->in(MemNode::Address); 673 Node* adr3 = mul_in3->in(MemNode::Address); 674 Node* adr4 = mul_in4->in(MemNode::Address); 675 if (adr1->is_AddP() && adr2->is_AddP() && adr3->is_AddP() && adr4->is_AddP()) { 676 if ((adr1->in(AddPNode::Base) == adr3->in(AddPNode::Base)) && 677 (adr2->in(AddPNode::Base) == adr4->in(AddPNode::Base))) { 678 nn = new MulAddS2INode(mul_in1, mul_in2, mul_in3, mul_in4); 679 register_new_node_with_ctrl_of(nn, n); 680 _igvn.replace_node(n, nn); 681 return nn; 682 } else if ((adr1->in(AddPNode::Base) == adr4->in(AddPNode::Base)) && 683 (adr2->in(AddPNode::Base) == adr3->in(AddPNode::Base))) { 684 nn = new MulAddS2INode(mul_in1, mul_in2, mul_in4, mul_in3); 685 register_new_node_with_ctrl_of(nn, n); 686 _igvn.replace_node(n, nn); 687 return nn; 688 } 689 } 690 } 691 } 692 } 693 } 694 return nn; 695 } 696 697 //------------------------------conditional_move------------------------------- 698 // Attempt to replace a Phi with a conditional move. We have some pretty 699 // strict profitability requirements. All Phis at the merge point must 700 // be converted, so we can remove the control flow. We need to limit the 701 // number of c-moves to a small handful. All code that was in the side-arms 702 // of the CFG diamond is now speculatively executed. This code has to be 703 // "cheap enough". We are pretty much limited to CFG diamonds that merge 704 // 1 or 2 items with a total of 1 or 2 ops executed speculatively. 705 Node *PhaseIdealLoop::conditional_move( Node *region ) { 706 707 assert(region->is_Region(), "sanity check"); 708 if (region->req() != 3) return nullptr; 709 710 // Check for CFG diamond 711 Node *lp = region->in(1); 712 Node *rp = region->in(2); 713 if (!lp || !rp) return nullptr; 714 Node *lp_c = lp->in(0); 715 if (lp_c == nullptr || lp_c != rp->in(0) || !lp_c->is_If()) return nullptr; 716 IfNode *iff = lp_c->as_If(); 717 718 // Check for ops pinned in an arm of the diamond. 719 // Can't remove the control flow in this case 720 if (lp->outcnt() > 1) return nullptr; 721 if (rp->outcnt() > 1) return nullptr; 722 723 IdealLoopTree* r_loop = get_loop(region); 724 assert(r_loop == get_loop(iff), "sanity"); 725 // Always convert to CMOVE if all results are used only outside this loop. 726 bool used_inside_loop = (r_loop == _ltree_root); 727 728 // Check profitability 729 int cost = 0; 730 int phis = 0; 731 for (DUIterator_Fast imax, i = region->fast_outs(imax); i < imax; i++) { 732 Node *out = region->fast_out(i); 733 if (!out->is_Phi()) continue; // Ignore other control edges, etc 734 phis++; 735 PhiNode* phi = out->as_Phi(); 736 BasicType bt = phi->type()->basic_type(); 737 switch (bt) { 738 case T_DOUBLE: 739 case T_FLOAT: 740 if (C->use_cmove()) { 741 continue; //TODO: maybe we want to add some cost 742 } 743 cost += Matcher::float_cmove_cost(); // Could be very expensive 744 break; 745 case T_LONG: { 746 cost += Matcher::long_cmove_cost(); // May encodes as 2 CMOV's 747 } 748 case T_INT: // These all CMOV fine 749 case T_ADDRESS: { // (RawPtr) 750 cost++; 751 break; 752 } 753 case T_NARROWOOP: // Fall through 754 case T_OBJECT: { // Base oops are OK, but not derived oops 755 const TypeOopPtr *tp = phi->type()->make_ptr()->isa_oopptr(); 756 // Derived pointers are Bad (tm): what's the Base (for GC purposes) of a 757 // CMOVE'd derived pointer? It's a CMOVE'd derived base. Thus 758 // CMOVE'ing a derived pointer requires we also CMOVE the base. If we 759 // have a Phi for the base here that we convert to a CMOVE all is well 760 // and good. But if the base is dead, we'll not make a CMOVE. Later 761 // the allocator will have to produce a base by creating a CMOVE of the 762 // relevant bases. This puts the allocator in the business of 763 // manufacturing expensive instructions, generally a bad plan. 764 // Just Say No to Conditionally-Moved Derived Pointers. 765 if (tp && tp->offset() != 0) 766 return nullptr; 767 cost++; 768 break; 769 } 770 default: 771 return nullptr; // In particular, can't do memory or I/O 772 } 773 // Add in cost any speculative ops 774 for (uint j = 1; j < region->req(); j++) { 775 Node *proj = region->in(j); 776 Node *inp = phi->in(j); 777 if (inp->isa_InlineType()) { 778 // TODO 8302217 This prevents PhiNode::push_inline_types_through 779 return nullptr; 780 } 781 if (get_ctrl(inp) == proj) { // Found local op 782 cost++; 783 // Check for a chain of dependent ops; these will all become 784 // speculative in a CMOV. 785 for (uint k = 1; k < inp->req(); k++) 786 if (get_ctrl(inp->in(k)) == proj) 787 cost += ConditionalMoveLimit; // Too much speculative goo 788 } 789 } 790 // See if the Phi is used by a Cmp or Narrow oop Decode/Encode. 791 // This will likely Split-If, a higher-payoff operation. 792 for (DUIterator_Fast kmax, k = phi->fast_outs(kmax); k < kmax; k++) { 793 Node* use = phi->fast_out(k); 794 if (use->is_Cmp() || use->is_DecodeNarrowPtr() || use->is_EncodeNarrowPtr()) 795 cost += ConditionalMoveLimit; 796 // Is there a use inside the loop? 797 // Note: check only basic types since CMoveP is pinned. 798 if (!used_inside_loop && is_java_primitive(bt)) { 799 IdealLoopTree* u_loop = get_loop(has_ctrl(use) ? get_ctrl(use) : use); 800 if (r_loop == u_loop || r_loop->is_member(u_loop)) { 801 used_inside_loop = true; 802 } 803 } 804 } 805 }//for 806 Node* bol = iff->in(1); 807 assert(!bol->is_OpaqueInitializedAssertionPredicate(), "Initialized Assertion Predicates cannot form a diamond with Halt"); 808 if (bol->is_OpaqueTemplateAssertionPredicate()) { 809 // Ignore Template Assertion Predicates with OpaqueTemplateAssertionPredicate nodes. 810 return nullptr; 811 } 812 if (bol->is_OpaqueMultiversioning()) { 813 assert(bol->as_OpaqueMultiversioning()->is_useless(), "Must be useless, i.e. fast main loop has already disappeared."); 814 // Ignore multiversion_if that just lost its loops. The OpaqueMultiversioning is marked useless, 815 // and will make the multiversion_if constant fold in the next IGVN round. 816 return nullptr; 817 } 818 if (!bol->is_Bool()) { 819 assert(false, "Expected Bool, but got %s", NodeClassNames[bol->Opcode()]); 820 return nullptr; 821 } 822 int cmp_op = bol->in(1)->Opcode(); 823 if (cmp_op == Op_SubTypeCheck) { // SubTypeCheck expansion expects an IfNode 824 return nullptr; 825 } 826 // It is expensive to generate flags from a float compare. 827 // Avoid duplicated float compare. 828 if (phis > 1 && (cmp_op == Op_CmpF || cmp_op == Op_CmpD)) return nullptr; 829 830 float infrequent_prob = PROB_UNLIKELY_MAG(3); 831 // Ignore cost and blocks frequency if CMOVE can be moved outside the loop. 832 if (used_inside_loop) { 833 if (cost >= ConditionalMoveLimit) return nullptr; // Too much goo 834 835 // BlockLayoutByFrequency optimization moves infrequent branch 836 // from hot path. No point in CMOV'ing in such case (110 is used 837 // instead of 100 to take into account not exactness of float value). 838 if (BlockLayoutByFrequency) { 839 infrequent_prob = MAX2(infrequent_prob, (float)BlockLayoutMinDiamondPercentage/110.0f); 840 } 841 } 842 // Check for highly predictable branch. No point in CMOV'ing if 843 // we are going to predict accurately all the time. 844 if (C->use_cmove() && (cmp_op == Op_CmpF || cmp_op == Op_CmpD)) { 845 //keep going 846 } else if (iff->_prob < infrequent_prob || 847 iff->_prob > (1.0f - infrequent_prob)) 848 return nullptr; 849 850 // -------------- 851 // Now replace all Phis with CMOV's 852 Node *cmov_ctrl = iff->in(0); 853 uint flip = (lp->Opcode() == Op_IfTrue); 854 Node_List wq; 855 while (1) { 856 PhiNode* phi = nullptr; 857 for (DUIterator_Fast imax, i = region->fast_outs(imax); i < imax; i++) { 858 Node *out = region->fast_out(i); 859 if (out->is_Phi()) { 860 phi = out->as_Phi(); 861 break; 862 } 863 } 864 if (phi == nullptr || _igvn.type(phi) == Type::TOP || !CMoveNode::supported(_igvn.type(phi))) { 865 break; 866 } 867 // Move speculative ops 868 wq.push(phi); 869 while (wq.size() > 0) { 870 Node *n = wq.pop(); 871 for (uint j = 1; j < n->req(); j++) { 872 Node* m = n->in(j); 873 if (m != nullptr && !is_dominator(get_ctrl(m), cmov_ctrl)) { 874 set_ctrl(m, cmov_ctrl); 875 wq.push(m); 876 } 877 } 878 } 879 Node* cmov = CMoveNode::make(iff->in(1), phi->in(1+flip), phi->in(2-flip), _igvn.type(phi)); 880 register_new_node(cmov, cmov_ctrl); 881 _igvn.replace_node(phi, cmov); 882 #ifndef PRODUCT 883 if (TraceLoopOpts) { 884 tty->print("CMOV "); 885 r_loop->dump_head(); 886 if (Verbose) { 887 bol->in(1)->dump(1); 888 cmov->dump(1); 889 } 890 } 891 DEBUG_ONLY( if (VerifyLoopOptimizations) { verify(); } ); 892 #endif 893 } 894 895 // The useless CFG diamond will fold up later; see the optimization in 896 // RegionNode::Ideal. 897 _igvn._worklist.push(region); 898 899 return iff->in(1); 900 } 901 902 static void enqueue_cfg_uses(Node* m, Unique_Node_List& wq) { 903 for (DUIterator_Fast imax, i = m->fast_outs(imax); i < imax; i++) { 904 Node* u = m->fast_out(i); 905 if (u->is_CFG()) { 906 if (u->is_NeverBranch()) { 907 u = u->as_NeverBranch()->proj_out(0); 908 enqueue_cfg_uses(u, wq); 909 } else { 910 wq.push(u); 911 } 912 } 913 } 914 } 915 916 // Try moving a store out of a loop, right before the loop 917 Node* PhaseIdealLoop::try_move_store_before_loop(Node* n, Node *n_ctrl) { 918 // Store has to be first in the loop body 919 IdealLoopTree *n_loop = get_loop(n_ctrl); 920 if (n->is_Store() && n_loop != _ltree_root && 921 n_loop->is_loop() && n_loop->_head->is_Loop() && 922 n->in(0) != nullptr) { 923 Node* address = n->in(MemNode::Address); 924 Node* value = n->in(MemNode::ValueIn); 925 Node* mem = n->in(MemNode::Memory); 926 IdealLoopTree* address_loop = get_loop(get_ctrl(address)); 927 IdealLoopTree* value_loop = get_loop(get_ctrl(value)); 928 929 // - address and value must be loop invariant 930 // - memory must be a memory Phi for the loop 931 // - Store must be the only store on this memory slice in the 932 // loop: if there's another store following this one then value 933 // written at iteration i by the second store could be overwritten 934 // at iteration i+n by the first store: it's not safe to move the 935 // first store out of the loop 936 // - nothing must observe the memory Phi: it guarantees no read 937 // before the store, we are also guaranteed the store post 938 // dominates the loop head (ignoring a possible early 939 // exit). Otherwise there would be extra Phi involved between the 940 // loop's Phi and the store. 941 // - there must be no early exit from the loop before the Store 942 // (such an exit most of the time would be an extra use of the 943 // memory Phi but sometimes is a bottom memory Phi that takes the 944 // store as input). 945 946 if (!n_loop->is_member(address_loop) && 947 !n_loop->is_member(value_loop) && 948 mem->is_Phi() && mem->in(0) == n_loop->_head && 949 mem->outcnt() == 1 && 950 mem->in(LoopNode::LoopBackControl) == n) { 951 952 assert(n_loop->_tail != nullptr, "need a tail"); 953 assert(is_dominator(n_ctrl, n_loop->_tail), "store control must not be in a branch in the loop"); 954 955 // Verify that there's no early exit of the loop before the store. 956 bool ctrl_ok = false; 957 { 958 // Follow control from loop head until n, we exit the loop or 959 // we reach the tail 960 ResourceMark rm; 961 Unique_Node_List wq; 962 wq.push(n_loop->_head); 963 964 for (uint next = 0; next < wq.size(); ++next) { 965 Node *m = wq.at(next); 966 if (m == n->in(0)) { 967 ctrl_ok = true; 968 continue; 969 } 970 assert(!has_ctrl(m), "should be CFG"); 971 if (!n_loop->is_member(get_loop(m)) || m == n_loop->_tail) { 972 ctrl_ok = false; 973 break; 974 } 975 enqueue_cfg_uses(m, wq); 976 if (wq.size() > 10) { 977 ctrl_ok = false; 978 break; 979 } 980 } 981 } 982 if (ctrl_ok) { 983 // move the Store 984 _igvn.replace_input_of(mem, LoopNode::LoopBackControl, mem); 985 _igvn.replace_input_of(n, 0, n_loop->_head->as_Loop()->skip_strip_mined()->in(LoopNode::EntryControl)); 986 _igvn.replace_input_of(n, MemNode::Memory, mem->in(LoopNode::EntryControl)); 987 // Disconnect the phi now. An empty phi can confuse other 988 // optimizations in this pass of loop opts. 989 _igvn.replace_node(mem, mem->in(LoopNode::EntryControl)); 990 n_loop->_body.yank(mem); 991 992 set_ctrl_and_loop(n, n->in(0)); 993 994 return n; 995 } 996 } 997 } 998 return nullptr; 999 } 1000 1001 // Try moving a store out of a loop, right after the loop 1002 void PhaseIdealLoop::try_move_store_after_loop(Node* n) { 1003 if (n->is_Store() && n->in(0) != nullptr) { 1004 Node *n_ctrl = get_ctrl(n); 1005 IdealLoopTree *n_loop = get_loop(n_ctrl); 1006 // Store must be in a loop 1007 if (n_loop != _ltree_root && !n_loop->_irreducible) { 1008 Node* address = n->in(MemNode::Address); 1009 Node* value = n->in(MemNode::ValueIn); 1010 IdealLoopTree* address_loop = get_loop(get_ctrl(address)); 1011 // address must be loop invariant 1012 if (!n_loop->is_member(address_loop)) { 1013 // Store must be last on this memory slice in the loop and 1014 // nothing in the loop must observe it 1015 Node* phi = nullptr; 1016 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) { 1017 Node* u = n->fast_out(i); 1018 if (has_ctrl(u)) { // control use? 1019 IdealLoopTree *u_loop = get_loop(get_ctrl(u)); 1020 if (!n_loop->is_member(u_loop)) { 1021 continue; 1022 } 1023 if (u->is_Phi() && u->in(0) == n_loop->_head) { 1024 assert(_igvn.type(u) == Type::MEMORY, "bad phi"); 1025 // multiple phis on the same slice are possible 1026 if (phi != nullptr) { 1027 return; 1028 } 1029 phi = u; 1030 continue; 1031 } 1032 } 1033 return; 1034 } 1035 if (phi != nullptr) { 1036 // Nothing in the loop before the store (next iteration) 1037 // must observe the stored value 1038 bool mem_ok = true; 1039 { 1040 ResourceMark rm; 1041 Unique_Node_List wq; 1042 wq.push(phi); 1043 for (uint next = 0; next < wq.size() && mem_ok; ++next) { 1044 Node *m = wq.at(next); 1045 for (DUIterator_Fast imax, i = m->fast_outs(imax); i < imax && mem_ok; i++) { 1046 Node* u = m->fast_out(i); 1047 if (u->is_Store() || u->is_Phi()) { 1048 if (u != n) { 1049 wq.push(u); 1050 mem_ok = (wq.size() <= 10); 1051 } 1052 } else { 1053 mem_ok = false; 1054 break; 1055 } 1056 } 1057 } 1058 } 1059 if (mem_ok) { 1060 // Move the store out of the loop if the LCA of all 1061 // users (except for the phi) is outside the loop. 1062 Node* hook = new Node(1); 1063 hook->init_req(0, n_ctrl); // Add an input to prevent hook from being dead 1064 _igvn.rehash_node_delayed(phi); 1065 int count = phi->replace_edge(n, hook, &_igvn); 1066 assert(count > 0, "inconsistent phi"); 1067 1068 // Compute latest point this store can go 1069 Node* lca = get_late_ctrl(n, get_ctrl(n)); 1070 if (lca->is_OuterStripMinedLoop()) { 1071 lca = lca->in(LoopNode::EntryControl); 1072 } 1073 if (n_loop->is_member(get_loop(lca))) { 1074 // LCA is in the loop - bail out 1075 _igvn.replace_node(hook, n); 1076 return; 1077 } 1078 #ifdef ASSERT 1079 if (n_loop->_head->is_Loop() && n_loop->_head->as_Loop()->is_strip_mined()) { 1080 assert(n_loop->_head->Opcode() == Op_CountedLoop, "outer loop is a strip mined"); 1081 n_loop->_head->as_Loop()->verify_strip_mined(1); 1082 Node* outer = n_loop->_head->as_CountedLoop()->outer_loop(); 1083 IdealLoopTree* outer_loop = get_loop(outer); 1084 assert(n_loop->_parent == outer_loop, "broken loop tree"); 1085 assert(get_loop(lca) == outer_loop, "safepoint in outer loop consume all memory state"); 1086 } 1087 #endif 1088 lca = place_outside_loop(lca, n_loop); 1089 assert(!n_loop->is_member(get_loop(lca)), "control must not be back in the loop"); 1090 assert(get_loop(lca)->_nest < n_loop->_nest || get_loop(lca)->_head->as_Loop()->is_in_infinite_subgraph(), "must not be moved into inner loop"); 1091 1092 // Move store out of the loop 1093 _igvn.replace_node(hook, n->in(MemNode::Memory)); 1094 _igvn.replace_input_of(n, 0, lca); 1095 set_ctrl_and_loop(n, lca); 1096 1097 // Disconnect the phi now. An empty phi can confuse other 1098 // optimizations in this pass of loop opts.. 1099 if (phi->in(LoopNode::LoopBackControl) == phi) { 1100 _igvn.replace_node(phi, phi->in(LoopNode::EntryControl)); 1101 n_loop->_body.yank(phi); 1102 } 1103 } 1104 } 1105 } 1106 } 1107 } 1108 } 1109 1110 // We can't use immutable memory for the flat array check because we are loading the mark word which is 1111 // mutable. Although the bits we are interested in are immutable (we check for markWord::unlocked_value), 1112 // we need to use raw memory to not break anti dependency analysis. Below code will attempt to still move 1113 // flat array checks out of loops, mainly to enable loop unswitching. 1114 void PhaseIdealLoop::move_flat_array_check_out_of_loop(Node* n) { 1115 // Skip checks for more than one array 1116 if (n->req() > 3) { 1117 return; 1118 } 1119 Node* mem = n->in(FlatArrayCheckNode::Memory); 1120 Node* array = n->in(FlatArrayCheckNode::ArrayOrKlass)->uncast(); 1121 IdealLoopTree* check_loop = get_loop(get_ctrl(n)); 1122 IdealLoopTree* ary_loop = get_loop(get_ctrl(array)); 1123 1124 // Check if array is loop invariant 1125 if (!check_loop->is_member(ary_loop)) { 1126 // Walk up memory graph from the check until we leave the loop 1127 VectorSet wq; 1128 wq.set(mem->_idx); 1129 while (check_loop->is_member(get_loop(ctrl_or_self(mem)))) { 1130 if (mem->is_Phi()) { 1131 mem = mem->in(1); 1132 } else if (mem->is_MergeMem()) { 1133 mem = mem->as_MergeMem()->memory_at(Compile::AliasIdxRaw); 1134 } else if (mem->is_Proj()) { 1135 mem = mem->in(0); 1136 } else if (mem->is_MemBar() || mem->is_SafePoint()) { 1137 mem = mem->in(TypeFunc::Memory); 1138 } else if (mem->is_Store() || mem->is_LoadStore() || mem->is_ClearArray()) { 1139 mem = mem->in(MemNode::Memory); 1140 } else { 1141 #ifdef ASSERT 1142 mem->dump(); 1143 #endif 1144 ShouldNotReachHere(); 1145 } 1146 if (wq.test_set(mem->_idx)) { 1147 return; 1148 } 1149 } 1150 // Replace memory input and re-compute ctrl to move the check out of the loop 1151 _igvn.replace_input_of(n, 1, mem); 1152 set_ctrl_and_loop(n, get_early_ctrl(n)); 1153 Node* bol = n->unique_out(); 1154 set_ctrl_and_loop(bol, get_early_ctrl(bol)); 1155 } 1156 } 1157 1158 //------------------------------split_if_with_blocks_pre----------------------- 1159 // Do the real work in a non-recursive function. Data nodes want to be 1160 // cloned in the pre-order so they can feed each other nicely. 1161 Node *PhaseIdealLoop::split_if_with_blocks_pre( Node *n ) { 1162 // Cloning these guys is unlikely to win 1163 int n_op = n->Opcode(); 1164 if (n_op == Op_MergeMem) { 1165 return n; 1166 } 1167 if (n->is_Proj()) { 1168 return n; 1169 } 1170 1171 if (n->isa_FlatArrayCheck()) { 1172 move_flat_array_check_out_of_loop(n); 1173 return n; 1174 } 1175 1176 // Do not clone-up CmpFXXX variations, as these are always 1177 // followed by a CmpI 1178 if (n->is_Cmp()) { 1179 return n; 1180 } 1181 // Attempt to use a conditional move instead of a phi/branch 1182 if (ConditionalMoveLimit > 0 && n_op == Op_Region) { 1183 Node *cmov = conditional_move( n ); 1184 if (cmov) { 1185 return cmov; 1186 } 1187 } 1188 if (n->is_CFG() || n->is_LoadStore()) { 1189 return n; 1190 } 1191 if (n->is_Opaque1()) { // Opaque nodes cannot be mod'd 1192 if (!C->major_progress()) { // If chance of no more loop opts... 1193 _igvn._worklist.push(n); // maybe we'll remove them 1194 } 1195 return n; 1196 } 1197 1198 if (n->is_Con()) { 1199 return n; // No cloning for Con nodes 1200 } 1201 1202 Node *n_ctrl = get_ctrl(n); 1203 if (!n_ctrl) { 1204 return n; // Dead node 1205 } 1206 1207 Node* res = try_move_store_before_loop(n, n_ctrl); 1208 if (res != nullptr) { 1209 return n; 1210 } 1211 1212 // Attempt to remix address expressions for loop invariants 1213 Node *m = remix_address_expressions( n ); 1214 if( m ) return m; 1215 1216 if (n_op == Op_AddI) { 1217 Node *nn = convert_add_to_muladd( n ); 1218 if ( nn ) return nn; 1219 } 1220 1221 if (n->is_ConstraintCast()) { 1222 Node* dom_cast = n->as_ConstraintCast()->dominating_cast(&_igvn, this); 1223 // ConstraintCastNode::dominating_cast() uses node control input to determine domination. 1224 // Node control inputs don't necessarily agree with loop control info (due to 1225 // transformations happened in between), thus additional dominance check is needed 1226 // to keep loop info valid. 1227 if (dom_cast != nullptr && is_dominator(get_ctrl(dom_cast), get_ctrl(n))) { 1228 _igvn.replace_node(n, dom_cast); 1229 return dom_cast; 1230 } 1231 } 1232 1233 // Determine if the Node has inputs from some local Phi. 1234 // Returns the block to clone thru. 1235 Node *n_blk = has_local_phi_input( n ); 1236 if( !n_blk ) return n; 1237 1238 // Do not clone the trip counter through on a CountedLoop 1239 // (messes up the canonical shape). 1240 if (((n_blk->is_CountedLoop() || (n_blk->is_Loop() && n_blk->as_Loop()->is_loop_nest_inner_loop())) && n->Opcode() == Op_AddI) || 1241 (n_blk->is_LongCountedLoop() && n->Opcode() == Op_AddL)) { 1242 return n; 1243 } 1244 // Pushing a shift through the iv Phi can get in the way of addressing optimizations or range check elimination 1245 if (n_blk->is_BaseCountedLoop() && n->Opcode() == Op_LShift(n_blk->as_BaseCountedLoop()->bt()) && 1246 n->in(1) == n_blk->as_BaseCountedLoop()->phi()) { 1247 return n; 1248 } 1249 1250 // Check for having no control input; not pinned. Allow 1251 // dominating control. 1252 if (n->in(0)) { 1253 Node *dom = idom(n_blk); 1254 if (dom_lca(n->in(0), dom) != n->in(0)) { 1255 return n; 1256 } 1257 } 1258 // Policy: when is it profitable. You must get more wins than 1259 // policy before it is considered profitable. Policy is usually 0, 1260 // so 1 win is considered profitable. Big merges will require big 1261 // cloning, so get a larger policy. 1262 int policy = n_blk->req() >> 2; 1263 1264 // If the loop is a candidate for range check elimination, 1265 // delay splitting through it's phi until a later loop optimization 1266 if (n_blk->is_BaseCountedLoop()) { 1267 IdealLoopTree *lp = get_loop(n_blk); 1268 if (lp && lp->_rce_candidate) { 1269 return n; 1270 } 1271 } 1272 1273 if (must_throttle_split_if()) return n; 1274 1275 // Split 'n' through the merge point if it is profitable 1276 Node *phi = split_thru_phi( n, n_blk, policy ); 1277 if (!phi) return n; 1278 1279 // Found a Phi to split thru! 1280 // Replace 'n' with the new phi 1281 _igvn.replace_node( n, phi ); 1282 // Moved a load around the loop, 'en-registering' something. 1283 if (n_blk->is_Loop() && n->is_Load() && 1284 !phi->in(LoopNode::LoopBackControl)->is_Load()) 1285 C->set_major_progress(); 1286 1287 return phi; 1288 } 1289 1290 static bool merge_point_too_heavy(Compile* C, Node* region) { 1291 // Bail out if the region and its phis have too many users. 1292 int weight = 0; 1293 for (DUIterator_Fast imax, i = region->fast_outs(imax); i < imax; i++) { 1294 weight += region->fast_out(i)->outcnt(); 1295 } 1296 int nodes_left = C->max_node_limit() - C->live_nodes(); 1297 if (weight * 8 > nodes_left) { 1298 if (PrintOpto) { 1299 tty->print_cr("*** Split-if bails out: %d nodes, region weight %d", C->unique(), weight); 1300 } 1301 return true; 1302 } else { 1303 return false; 1304 } 1305 } 1306 1307 static bool merge_point_safe(Node* region) { 1308 // 4799512: Stop split_if_with_blocks from splitting a block with a ConvI2LNode 1309 // having a PhiNode input. This sidesteps the dangerous case where the split 1310 // ConvI2LNode may become TOP if the input Value() does not 1311 // overlap the ConvI2L range, leaving a node which may not dominate its 1312 // uses. 1313 // A better fix for this problem can be found in the BugTraq entry, but 1314 // expediency for Mantis demands this hack. 1315 #ifdef _LP64 1316 for (DUIterator_Fast imax, i = region->fast_outs(imax); i < imax; i++) { 1317 Node* n = region->fast_out(i); 1318 if (n->is_Phi()) { 1319 for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++) { 1320 Node* m = n->fast_out(j); 1321 if (m->Opcode() == Op_ConvI2L) 1322 return false; 1323 if (m->is_CastII()) { 1324 return false; 1325 } 1326 } 1327 } 1328 } 1329 #endif 1330 return true; 1331 } 1332 1333 1334 //------------------------------place_outside_loop--------------------------------- 1335 // Place some computation outside of this loop on the path to the use passed as argument 1336 Node* PhaseIdealLoop::place_outside_loop(Node* useblock, IdealLoopTree* loop) const { 1337 Node* head = loop->_head; 1338 assert(!loop->is_member(get_loop(useblock)), "must be outside loop"); 1339 if (head->is_Loop() && head->as_Loop()->is_strip_mined()) { 1340 loop = loop->_parent; 1341 assert(loop->_head->is_OuterStripMinedLoop(), "malformed strip mined loop"); 1342 } 1343 1344 // Pick control right outside the loop 1345 for (;;) { 1346 Node* dom = idom(useblock); 1347 if (loop->is_member(get_loop(dom))) { 1348 break; 1349 } 1350 useblock = dom; 1351 } 1352 assert(find_non_split_ctrl(useblock) == useblock, "should be non split control"); 1353 return useblock; 1354 } 1355 1356 1357 bool PhaseIdealLoop::identical_backtoback_ifs(Node *n) { 1358 if (!n->is_If() || n->is_BaseCountedLoopEnd()) { 1359 return false; 1360 } 1361 if (!n->in(0)->is_Region()) { 1362 return false; 1363 } 1364 1365 Node* region = n->in(0); 1366 Node* dom = idom(region); 1367 if (!dom->is_If() || !n->as_If()->same_condition(dom, &_igvn)) { 1368 return false; 1369 } 1370 IfNode* dom_if = dom->as_If(); 1371 Node* proj_true = dom_if->proj_out(1); 1372 Node* proj_false = dom_if->proj_out(0); 1373 1374 for (uint i = 1; i < region->req(); i++) { 1375 if (is_dominator(proj_true, region->in(i))) { 1376 continue; 1377 } 1378 if (is_dominator(proj_false, region->in(i))) { 1379 continue; 1380 } 1381 return false; 1382 } 1383 1384 return true; 1385 } 1386 1387 1388 bool PhaseIdealLoop::can_split_if(Node* n_ctrl) { 1389 if (must_throttle_split_if()) { 1390 return false; 1391 } 1392 1393 // Do not do 'split-if' if irreducible loops are present. 1394 if (_has_irreducible_loops) { 1395 return false; 1396 } 1397 1398 if (merge_point_too_heavy(C, n_ctrl)) { 1399 return false; 1400 } 1401 1402 // Do not do 'split-if' if some paths are dead. First do dead code 1403 // elimination and then see if its still profitable. 1404 for (uint i = 1; i < n_ctrl->req(); i++) { 1405 if (n_ctrl->in(i) == C->top()) { 1406 return false; 1407 } 1408 } 1409 1410 // If trying to do a 'Split-If' at the loop head, it is only 1411 // profitable if the cmp folds up on BOTH paths. Otherwise we 1412 // risk peeling a loop forever. 1413 1414 // CNC - Disabled for now. Requires careful handling of loop 1415 // body selection for the cloned code. Also, make sure we check 1416 // for any input path not being in the same loop as n_ctrl. For 1417 // irreducible loops we cannot check for 'n_ctrl->is_Loop()' 1418 // because the alternative loop entry points won't be converted 1419 // into LoopNodes. 1420 IdealLoopTree *n_loop = get_loop(n_ctrl); 1421 for (uint j = 1; j < n_ctrl->req(); j++) { 1422 if (get_loop(n_ctrl->in(j)) != n_loop) { 1423 return false; 1424 } 1425 } 1426 1427 // Check for safety of the merge point. 1428 if (!merge_point_safe(n_ctrl)) { 1429 return false; 1430 } 1431 1432 return true; 1433 } 1434 1435 // Detect if the node is the inner strip-mined loop 1436 // Return: null if it's not the case, or the exit of outer strip-mined loop 1437 static Node* is_inner_of_stripmined_loop(const Node* out) { 1438 Node* out_le = nullptr; 1439 1440 if (out->is_CountedLoopEnd()) { 1441 const CountedLoopNode* loop = out->as_CountedLoopEnd()->loopnode(); 1442 1443 if (loop != nullptr && loop->is_strip_mined()) { 1444 out_le = loop->in(LoopNode::EntryControl)->as_OuterStripMinedLoop()->outer_loop_exit(); 1445 } 1446 } 1447 1448 return out_le; 1449 } 1450 1451 bool PhaseIdealLoop::flat_array_element_type_check(Node *n) { 1452 // If the CmpP is a subtype check for a value that has just been 1453 // loaded from an array, the subtype check guarantees the value 1454 // can't be stored in a flat array and the load of the value 1455 // happens with a flat array check then: push the type check 1456 // through the phi of the flat array check. This needs special 1457 // logic because the subtype check's input is not a phi but a 1458 // LoadKlass that must first be cloned through the phi. 1459 if (n->Opcode() != Op_CmpP) { 1460 return false; 1461 } 1462 1463 Node* klassptr = n->in(1); 1464 Node* klasscon = n->in(2); 1465 1466 if (klassptr->is_DecodeNarrowPtr()) { 1467 klassptr = klassptr->in(1); 1468 } 1469 1470 if (klassptr->Opcode() != Op_LoadKlass && klassptr->Opcode() != Op_LoadNKlass) { 1471 return false; 1472 } 1473 1474 if (!klasscon->is_Con()) { 1475 return false; 1476 } 1477 1478 Node* addr = klassptr->in(MemNode::Address); 1479 1480 if (!addr->is_AddP()) { 1481 return false; 1482 } 1483 1484 intptr_t offset; 1485 Node* obj = AddPNode::Ideal_base_and_offset(addr, &_igvn, offset); 1486 1487 if (obj == nullptr) { 1488 return false; 1489 } 1490 1491 assert(obj != nullptr && addr->in(AddPNode::Base) == addr->in(AddPNode::Address), "malformed AddP?"); 1492 if (obj->Opcode() == Op_CastPP) { 1493 obj = obj->in(1); 1494 } 1495 1496 if (!obj->is_Phi()) { 1497 return false; 1498 } 1499 1500 Node* region = obj->in(0); 1501 1502 Node* phi = PhiNode::make_blank(region, n->in(1)); 1503 for (uint i = 1; i < region->req(); i++) { 1504 Node* in = obj->in(i); 1505 Node* ctrl = region->in(i); 1506 if (addr->in(AddPNode::Base) != obj) { 1507 Node* cast = addr->in(AddPNode::Base); 1508 assert(cast->Opcode() == Op_CastPP && cast->in(0) != nullptr, "inconsistent subgraph"); 1509 Node* cast_clone = cast->clone(); 1510 cast_clone->set_req(0, ctrl); 1511 cast_clone->set_req(1, in); 1512 register_new_node(cast_clone, ctrl); 1513 const Type* tcast = cast_clone->Value(&_igvn); 1514 _igvn.set_type(cast_clone, tcast); 1515 cast_clone->as_Type()->set_type(tcast); 1516 in = cast_clone; 1517 } 1518 Node* addr_clone = addr->clone(); 1519 addr_clone->set_req(AddPNode::Base, in); 1520 addr_clone->set_req(AddPNode::Address, in); 1521 register_new_node(addr_clone, ctrl); 1522 _igvn.set_type(addr_clone, addr_clone->Value(&_igvn)); 1523 Node* klassptr_clone = klassptr->clone(); 1524 klassptr_clone->set_req(2, addr_clone); 1525 register_new_node(klassptr_clone, ctrl); 1526 _igvn.set_type(klassptr_clone, klassptr_clone->Value(&_igvn)); 1527 if (klassptr != n->in(1)) { 1528 Node* decode = n->in(1); 1529 assert(decode->is_DecodeNarrowPtr(), "inconsistent subgraph"); 1530 Node* decode_clone = decode->clone(); 1531 decode_clone->set_req(1, klassptr_clone); 1532 register_new_node(decode_clone, ctrl); 1533 _igvn.set_type(decode_clone, decode_clone->Value(&_igvn)); 1534 klassptr_clone = decode_clone; 1535 } 1536 phi->set_req(i, klassptr_clone); 1537 } 1538 register_new_node(phi, region); 1539 Node* orig = n->in(1); 1540 _igvn.replace_input_of(n, 1, phi); 1541 split_if_with_blocks_post(n); 1542 if (n->outcnt() != 0) { 1543 _igvn.replace_input_of(n, 1, orig); 1544 _igvn.remove_dead_node(phi); 1545 } 1546 return true; 1547 } 1548 1549 //------------------------------split_if_with_blocks_post---------------------- 1550 // Do the real work in a non-recursive function. CFG hackery wants to be 1551 // in the post-order, so it can dirty the I-DOM info and not use the dirtied 1552 // info. 1553 void PhaseIdealLoop::split_if_with_blocks_post(Node *n) { 1554 1555 if (flat_array_element_type_check(n)) { 1556 return; 1557 } 1558 1559 // Cloning Cmp through Phi's involves the split-if transform. 1560 // FastLock is not used by an If 1561 if (n->is_Cmp() && !n->is_FastLock()) { 1562 Node *n_ctrl = get_ctrl(n); 1563 // Determine if the Node has inputs from some local Phi. 1564 // Returns the block to clone thru. 1565 Node *n_blk = has_local_phi_input(n); 1566 if (n_blk != n_ctrl) { 1567 return; 1568 } 1569 1570 if (!can_split_if(n_ctrl)) { 1571 return; 1572 } 1573 1574 if (n->outcnt() != 1) { 1575 return; // Multiple bool's from 1 compare? 1576 } 1577 Node *bol = n->unique_out(); 1578 assert(bol->is_Bool(), "expect a bool here"); 1579 if (bol->outcnt() != 1) { 1580 return;// Multiple branches from 1 compare? 1581 } 1582 Node *iff = bol->unique_out(); 1583 1584 // Check some safety conditions 1585 if (iff->is_If()) { // Classic split-if? 1586 if (iff->in(0) != n_ctrl) { 1587 return; // Compare must be in same blk as if 1588 } 1589 } else if (iff->is_CMove()) { // Trying to split-up a CMOVE 1590 // Can't split CMove with different control. 1591 if (get_ctrl(iff) != n_ctrl) { 1592 return; 1593 } 1594 if (get_ctrl(iff->in(2)) == n_ctrl || 1595 get_ctrl(iff->in(3)) == n_ctrl) { 1596 return; // Inputs not yet split-up 1597 } 1598 if (get_loop(n_ctrl) != get_loop(get_ctrl(iff))) { 1599 return; // Loop-invar test gates loop-varying CMOVE 1600 } 1601 } else { 1602 return; // some other kind of node, such as an Allocate 1603 } 1604 1605 // When is split-if profitable? Every 'win' on means some control flow 1606 // goes dead, so it's almost always a win. 1607 int policy = 0; 1608 // Split compare 'n' through the merge point if it is profitable 1609 Node *phi = split_thru_phi( n, n_ctrl, policy); 1610 if (!phi) { 1611 return; 1612 } 1613 1614 // Found a Phi to split thru! 1615 // Replace 'n' with the new phi 1616 _igvn.replace_node(n, phi); 1617 1618 // Now split the bool up thru the phi 1619 Node *bolphi = split_thru_phi(bol, n_ctrl, -1); 1620 guarantee(bolphi != nullptr, "null boolean phi node"); 1621 1622 _igvn.replace_node(bol, bolphi); 1623 assert(iff->in(1) == bolphi, ""); 1624 1625 if (bolphi->Value(&_igvn)->singleton()) { 1626 return; 1627 } 1628 1629 // Conditional-move? Must split up now 1630 if (!iff->is_If()) { 1631 Node *cmovphi = split_thru_phi(iff, n_ctrl, -1); 1632 _igvn.replace_node(iff, cmovphi); 1633 return; 1634 } 1635 1636 // Now split the IF 1637 C->print_method(PHASE_BEFORE_SPLIT_IF, 4, iff); 1638 if (TraceLoopOpts) { 1639 tty->print_cr("Split-If"); 1640 } 1641 do_split_if(iff); 1642 C->print_method(PHASE_AFTER_SPLIT_IF, 4, iff); 1643 return; 1644 } 1645 1646 // Two identical ifs back to back can be merged 1647 if (try_merge_identical_ifs(n)) { 1648 return; 1649 } 1650 1651 // Check for an IF ready to split; one that has its 1652 // condition codes input coming from a Phi at the block start. 1653 int n_op = n->Opcode(); 1654 1655 // Check for an IF being dominated by another IF same test 1656 if (n_op == Op_If || 1657 n_op == Op_RangeCheck) { 1658 Node *bol = n->in(1); 1659 uint max = bol->outcnt(); 1660 // Check for same test used more than once? 1661 if (bol->is_Bool() && (max > 1 || bol->in(1)->is_SubTypeCheck())) { 1662 // Search up IDOMs to see if this IF is dominated. 1663 Node* cmp = bol->in(1); 1664 Node *cutoff = cmp->is_SubTypeCheck() ? dom_lca(get_ctrl(cmp->in(1)), get_ctrl(cmp->in(2))) : get_ctrl(bol); 1665 1666 // Now search up IDOMs till cutoff, looking for a dominating test 1667 Node *prevdom = n; 1668 Node *dom = idom(prevdom); 1669 while (dom != cutoff) { 1670 if (dom->req() > 1 && n->as_If()->same_condition(dom, &_igvn) && prevdom->in(0) == dom && 1671 safe_for_if_replacement(dom)) { 1672 // It's invalid to move control dependent data nodes in the inner 1673 // strip-mined loop, because: 1674 // 1) break validation of LoopNode::verify_strip_mined() 1675 // 2) move code with side-effect in strip-mined loop 1676 // Move to the exit of outer strip-mined loop in that case. 1677 Node* out_le = is_inner_of_stripmined_loop(dom); 1678 if (out_le != nullptr) { 1679 prevdom = out_le; 1680 } 1681 // Replace the dominated test with an obvious true or false. 1682 // Place it on the IGVN worklist for later cleanup. 1683 C->set_major_progress(); 1684 // Split if: pin array accesses that are control dependent on a range check and moved to a regular if, 1685 // to prevent an array load from floating above its range check. There are three cases: 1686 // 1. Move from RangeCheck "a" to RangeCheck "b": don't need to pin. If we ever remove b, then we pin 1687 // all its array accesses at that point. 1688 // 2. We move from RangeCheck "a" to regular if "b": need to pin. If we ever remove b, then its array 1689 // accesses would start to float, since we don't pin at that point. 1690 // 3. If we move from regular if: don't pin. All array accesses are already assumed to be pinned. 1691 bool pin_array_access_nodes = n->Opcode() == Op_RangeCheck && 1692 prevdom->in(0)->Opcode() != Op_RangeCheck; 1693 dominated_by(prevdom->as_IfProj(), n->as_If(), false, pin_array_access_nodes); 1694 DEBUG_ONLY( if (VerifyLoopOptimizations) { verify(); } ); 1695 return; 1696 } 1697 prevdom = dom; 1698 dom = idom(prevdom); 1699 } 1700 } 1701 } 1702 1703 try_sink_out_of_loop(n); 1704 if (C->failing()) { 1705 return; 1706 } 1707 1708 try_move_store_after_loop(n); 1709 1710 // Remove multiple allocations of the same inline type 1711 if (n->is_InlineType()) { 1712 n->as_InlineType()->remove_redundant_allocations(this); 1713 } 1714 } 1715 1716 // Transform: 1717 // 1718 // if (some_condition) { 1719 // // body 1 1720 // } else { 1721 // // body 2 1722 // } 1723 // if (some_condition) { 1724 // // body 3 1725 // } else { 1726 // // body 4 1727 // } 1728 // 1729 // into: 1730 // 1731 // 1732 // if (some_condition) { 1733 // // body 1 1734 // // body 3 1735 // } else { 1736 // // body 2 1737 // // body 4 1738 // } 1739 bool PhaseIdealLoop::try_merge_identical_ifs(Node* n) { 1740 if (identical_backtoback_ifs(n) && can_split_if(n->in(0))) { 1741 Node *n_ctrl = n->in(0); 1742 IfNode* dom_if = idom(n_ctrl)->as_If(); 1743 if (n->in(1) != dom_if->in(1)) { 1744 assert(n->in(1)->in(1)->is_SubTypeCheck() && 1745 (n->in(1)->in(1)->as_SubTypeCheck()->method() != nullptr || 1746 dom_if->in(1)->in(1)->as_SubTypeCheck()->method() != nullptr), "only for subtype checks with profile data attached"); 1747 _igvn.replace_input_of(n, 1, dom_if->in(1)); 1748 } 1749 ProjNode* dom_proj_true = dom_if->proj_out(1); 1750 ProjNode* dom_proj_false = dom_if->proj_out(0); 1751 1752 // Now split the IF 1753 RegionNode* new_false_region; 1754 RegionNode* new_true_region; 1755 do_split_if(n, &new_false_region, &new_true_region); 1756 assert(new_false_region->req() == new_true_region->req(), ""); 1757 #ifdef ASSERT 1758 for (uint i = 1; i < new_false_region->req(); ++i) { 1759 assert(new_false_region->in(i)->in(0) == new_true_region->in(i)->in(0), "unexpected shape following split if"); 1760 assert(i == new_false_region->req() - 1 || new_false_region->in(i)->in(0)->in(1) == new_false_region->in(i + 1)->in(0)->in(1), "unexpected shape following split if"); 1761 } 1762 #endif 1763 assert(new_false_region->in(1)->in(0)->in(1) == dom_if->in(1), "dominating if and dominated if after split must share test"); 1764 1765 // We now have: 1766 // if (some_condition) { 1767 // // body 1 1768 // if (some_condition) { 1769 // body3: // new_true_region 1770 // // body3 1771 // } else { 1772 // goto body4; 1773 // } 1774 // } else { 1775 // // body 2 1776 // if (some_condition) { 1777 // goto body3; 1778 // } else { 1779 // body4: // new_false_region 1780 // // body4; 1781 // } 1782 // } 1783 // 1784 1785 // clone pinned nodes thru the resulting regions 1786 push_pinned_nodes_thru_region(dom_if, new_true_region); 1787 push_pinned_nodes_thru_region(dom_if, new_false_region); 1788 1789 // Optimize out the cloned ifs. Because pinned nodes were cloned, this also allows a CastPP that would be dependent 1790 // on a projection of n to have the dom_if as a control dependency. We don't want the CastPP to end up with an 1791 // unrelated control dependency. 1792 for (uint i = 1; i < new_false_region->req(); i++) { 1793 if (is_dominator(dom_proj_true, new_false_region->in(i))) { 1794 dominated_by(dom_proj_true->as_IfProj(), new_false_region->in(i)->in(0)->as_If()); 1795 } else { 1796 assert(is_dominator(dom_proj_false, new_false_region->in(i)), "bad if"); 1797 dominated_by(dom_proj_false->as_IfProj(), new_false_region->in(i)->in(0)->as_If()); 1798 } 1799 } 1800 return true; 1801 } 1802 return false; 1803 } 1804 1805 void PhaseIdealLoop::push_pinned_nodes_thru_region(IfNode* dom_if, Node* region) { 1806 for (DUIterator i = region->outs(); region->has_out(i); i++) { 1807 Node* u = region->out(i); 1808 if (!has_ctrl(u) || u->is_Phi() || !u->depends_only_on_test() || !_igvn.no_dependent_zero_check(u)) { 1809 continue; 1810 } 1811 assert(u->in(0) == region, "not a control dependent node?"); 1812 uint j = 1; 1813 for (; j < u->req(); ++j) { 1814 Node* in = u->in(j); 1815 if (!is_dominator(ctrl_or_self(in), dom_if)) { 1816 break; 1817 } 1818 } 1819 if (j == u->req()) { 1820 Node *phi = PhiNode::make_blank(region, u); 1821 for (uint k = 1; k < region->req(); ++k) { 1822 Node* clone = u->clone(); 1823 clone->set_req(0, region->in(k)); 1824 register_new_node(clone, region->in(k)); 1825 phi->init_req(k, clone); 1826 } 1827 register_new_node(phi, region); 1828 _igvn.replace_node(u, phi); 1829 --i; 1830 } 1831 } 1832 } 1833 1834 bool PhaseIdealLoop::safe_for_if_replacement(const Node* dom) const { 1835 if (!dom->is_CountedLoopEnd()) { 1836 return true; 1837 } 1838 CountedLoopEndNode* le = dom->as_CountedLoopEnd(); 1839 CountedLoopNode* cl = le->loopnode(); 1840 if (cl == nullptr) { 1841 return true; 1842 } 1843 if (!cl->is_main_loop()) { 1844 return true; 1845 } 1846 if (cl->is_canonical_loop_entry() == nullptr) { 1847 return true; 1848 } 1849 // Further unrolling is possible so loop exit condition might change 1850 return false; 1851 } 1852 1853 // See if a shared loop-varying computation has no loop-varying uses. 1854 // Happens if something is only used for JVM state in uncommon trap exits, 1855 // like various versions of induction variable+offset. Clone the 1856 // computation per usage to allow it to sink out of the loop. 1857 void PhaseIdealLoop::try_sink_out_of_loop(Node* n) { 1858 bool is_raw_to_oop_cast = n->is_ConstraintCast() && 1859 n->in(1)->bottom_type()->isa_rawptr() && 1860 !n->bottom_type()->isa_rawptr(); 1861 1862 if (has_ctrl(n) && 1863 !n->is_Phi() && 1864 !n->is_Bool() && 1865 !n->is_Proj() && 1866 !n->is_MergeMem() && 1867 !n->is_CMove() && 1868 !n->is_OpaqueNotNull() && 1869 !n->is_OpaqueInitializedAssertionPredicate() && 1870 !n->is_OpaqueTemplateAssertionPredicate() && 1871 !is_raw_to_oop_cast && // don't extend live ranges of raw oops 1872 (KillPathsReachableByDeadTypeNode || !n->is_Type()) 1873 ) { 1874 Node *n_ctrl = get_ctrl(n); 1875 IdealLoopTree *n_loop = get_loop(n_ctrl); 1876 1877 if (n->in(0) != nullptr) { 1878 IdealLoopTree* loop_ctrl = get_loop(n->in(0)); 1879 if (n_loop != loop_ctrl && n_loop->is_member(loop_ctrl)) { 1880 // n has a control input inside a loop but get_ctrl() is member of an outer loop. This could happen, for example, 1881 // for Div nodes inside a loop (control input inside loop) without a use except for an UCT (outside the loop). 1882 // Rewire control of n to right outside of the loop, regardless if its input(s) are later sunk or not. 1883 Node* maybe_pinned_n = n; 1884 Node* outside_ctrl = place_outside_loop(n_ctrl, loop_ctrl); 1885 if (n->depends_only_on_test()) { 1886 Node* pinned_clone = n->pin_array_access_node(); 1887 if (pinned_clone != nullptr) { 1888 // Pin array access nodes: if this is an array load, it's going to be dependent on a condition that's not a 1889 // range check for that access. If that condition is replaced by an identical dominating one, then an 1890 // unpinned load would risk floating above its range check. 1891 register_new_node(pinned_clone, n_ctrl); 1892 maybe_pinned_n = pinned_clone; 1893 _igvn.replace_node(n, pinned_clone); 1894 } 1895 } 1896 _igvn.replace_input_of(maybe_pinned_n, 0, outside_ctrl); 1897 } 1898 } 1899 if (n_loop != _ltree_root && n->outcnt() > 1) { 1900 // Compute early control: needed for anti-dependence analysis. It's also possible that as a result of 1901 // previous transformations in this loop opts round, the node can be hoisted now: early control will tell us. 1902 Node* early_ctrl = compute_early_ctrl(n, n_ctrl); 1903 if (n_loop->is_member(get_loop(early_ctrl)) && // check that this one can't be hoisted now 1904 ctrl_of_all_uses_out_of_loop(n, early_ctrl, n_loop)) { // All uses in outer loops! 1905 if (n->is_Store() || n->is_LoadStore()) { 1906 assert(false, "no node with a side effect"); 1907 C->record_failure("no node with a side effect"); 1908 return; 1909 } 1910 Node* outer_loop_clone = nullptr; 1911 for (DUIterator_Last jmin, j = n->last_outs(jmin); j >= jmin;) { 1912 Node* u = n->last_out(j); // Clone private computation per use 1913 _igvn.rehash_node_delayed(u); 1914 Node* x = nullptr; 1915 if (n->depends_only_on_test()) { 1916 // Pin array access nodes: if this is an array load, it's going to be dependent on a condition that's not a 1917 // range check for that access. If that condition is replaced by an identical dominating one, then an 1918 // unpinned load would risk floating above its range check. 1919 x = n->pin_array_access_node(); 1920 } 1921 if (x == nullptr) { 1922 x = n->clone(); 1923 } 1924 Node* x_ctrl = nullptr; 1925 if (u->is_Phi()) { 1926 // Replace all uses of normal nodes. Replace Phi uses 1927 // individually, so the separate Nodes can sink down 1928 // different paths. 1929 uint k = 1; 1930 while (u->in(k) != n) k++; 1931 u->set_req(k, x); 1932 // x goes next to Phi input path 1933 x_ctrl = u->in(0)->in(k); 1934 // Find control for 'x' next to use but not inside inner loops. 1935 x_ctrl = place_outside_loop(x_ctrl, n_loop); 1936 --j; 1937 } else { // Normal use 1938 if (has_ctrl(u)) { 1939 x_ctrl = get_ctrl(u); 1940 } else { 1941 x_ctrl = u->in(0); 1942 } 1943 // Find control for 'x' next to use but not inside inner loops. 1944 x_ctrl = place_outside_loop(x_ctrl, n_loop); 1945 // Replace all uses 1946 if (u->is_ConstraintCast() && _igvn.type(n)->higher_equal(u->bottom_type()) && u->in(0) == x_ctrl) { 1947 // If we're sinking a chain of data nodes, we might have inserted a cast to pin the use which is not necessary 1948 // anymore now that we're going to pin n as well 1949 _igvn.replace_node(u, x); 1950 --j; 1951 } else { 1952 int nb = u->replace_edge(n, x, &_igvn); 1953 j -= nb; 1954 } 1955 } 1956 1957 if (n->is_Load()) { 1958 // For loads, add a control edge to a CFG node outside of the loop 1959 // to force them to not combine and return back inside the loop 1960 // during GVN optimization (4641526). 1961 assert(x_ctrl == get_late_ctrl_with_anti_dep(x->as_Load(), early_ctrl, x_ctrl), "anti-dependences were already checked"); 1962 1963 IdealLoopTree* x_loop = get_loop(x_ctrl); 1964 Node* x_head = x_loop->_head; 1965 if (x_head->is_Loop() && x_head->is_OuterStripMinedLoop()) { 1966 // Do not add duplicate LoadNodes to the outer strip mined loop 1967 if (outer_loop_clone != nullptr) { 1968 _igvn.replace_node(x, outer_loop_clone); 1969 continue; 1970 } 1971 outer_loop_clone = x; 1972 } 1973 x->set_req(0, x_ctrl); 1974 } else if (n->in(0) != nullptr){ 1975 x->set_req(0, x_ctrl); 1976 } 1977 assert(dom_depth(n_ctrl) <= dom_depth(x_ctrl), "n is later than its clone"); 1978 assert(!n_loop->is_member(get_loop(x_ctrl)), "should have moved out of loop"); 1979 register_new_node(x, x_ctrl); 1980 1981 // Chain of AddP nodes: (AddP base (AddP base (AddP base ))) 1982 // All AddP nodes must keep the same base after sinking so: 1983 // 1- We don't add a CastPP here until the last one of the chain is sunk: if part of the chain is not sunk, 1984 // their bases remain the same. 1985 // (see 2- below) 1986 assert(!x->is_AddP() || !x->in(AddPNode::Address)->is_AddP() || 1987 x->in(AddPNode::Address)->in(AddPNode::Base) == x->in(AddPNode::Base) || 1988 !x->in(AddPNode::Address)->in(AddPNode::Base)->eqv_uncast(x->in(AddPNode::Base)), "unexpected AddP shape"); 1989 if (x->in(0) == nullptr && !x->is_DecodeNarrowPtr() && 1990 !(x->is_AddP() && x->in(AddPNode::Address)->is_AddP() && x->in(AddPNode::Address)->in(AddPNode::Base) == x->in(AddPNode::Base))) { 1991 assert(!x->is_Load(), "load should be pinned"); 1992 // Use a cast node to pin clone out of loop 1993 Node* cast = nullptr; 1994 for (uint k = 0; k < x->req(); k++) { 1995 Node* in = x->in(k); 1996 if (in != nullptr && n_loop->is_member(get_loop(get_ctrl(in)))) { 1997 const Type* in_t = _igvn.type(in); 1998 cast = ConstraintCastNode::make_cast_for_type(x_ctrl, in, in_t, 1999 ConstraintCastNode::UnconditionalDependency, nullptr); 2000 } 2001 if (cast != nullptr) { 2002 Node* prev = _igvn.hash_find_insert(cast); 2003 if (prev != nullptr && get_ctrl(prev) == x_ctrl) { 2004 cast->destruct(&_igvn); 2005 cast = prev; 2006 } else { 2007 register_new_node(cast, x_ctrl); 2008 } 2009 x->replace_edge(in, cast); 2010 // Chain of AddP nodes: 2011 // 2- A CastPP of the base is only added now that all AddP nodes are sunk 2012 if (x->is_AddP() && k == AddPNode::Base) { 2013 update_addp_chain_base(x, n->in(AddPNode::Base), cast); 2014 } 2015 break; 2016 } 2017 } 2018 assert(cast != nullptr, "must have added a cast to pin the node"); 2019 } 2020 } 2021 _igvn.remove_dead_node(n); 2022 } 2023 _dom_lca_tags_round = 0; 2024 } 2025 } 2026 } 2027 2028 void PhaseIdealLoop::update_addp_chain_base(Node* x, Node* old_base, Node* new_base) { 2029 ResourceMark rm; 2030 Node_List wq; 2031 wq.push(x); 2032 while (wq.size() != 0) { 2033 Node* n = wq.pop(); 2034 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) { 2035 Node* u = n->fast_out(i); 2036 if (u->is_AddP() && u->in(AddPNode::Base) == old_base) { 2037 _igvn.replace_input_of(u, AddPNode::Base, new_base); 2038 wq.push(u); 2039 } 2040 } 2041 } 2042 } 2043 2044 // Compute the early control of a node by following its inputs until we reach 2045 // nodes that are pinned. Then compute the LCA of the control of all pinned nodes. 2046 Node* PhaseIdealLoop::compute_early_ctrl(Node* n, Node* n_ctrl) { 2047 Node* early_ctrl = nullptr; 2048 ResourceMark rm; 2049 Unique_Node_List wq; 2050 wq.push(n); 2051 for (uint i = 0; i < wq.size(); i++) { 2052 Node* m = wq.at(i); 2053 Node* c = nullptr; 2054 if (m->is_CFG()) { 2055 c = m; 2056 } else if (m->pinned()) { 2057 c = m->in(0); 2058 } else { 2059 for (uint j = 0; j < m->req(); j++) { 2060 Node* in = m->in(j); 2061 if (in != nullptr) { 2062 wq.push(in); 2063 } 2064 } 2065 } 2066 if (c != nullptr) { 2067 assert(is_dominator(c, n_ctrl), "control input must dominate current control"); 2068 if (early_ctrl == nullptr || is_dominator(early_ctrl, c)) { 2069 early_ctrl = c; 2070 } 2071 } 2072 } 2073 assert(is_dominator(early_ctrl, n_ctrl), "early control must dominate current control"); 2074 return early_ctrl; 2075 } 2076 2077 bool PhaseIdealLoop::ctrl_of_all_uses_out_of_loop(const Node* n, Node* n_ctrl, IdealLoopTree* n_loop) { 2078 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) { 2079 Node* u = n->fast_out(i); 2080 if (u->is_Opaque1()) { 2081 return false; // Found loop limit, bugfix for 4677003 2082 } 2083 // We can't reuse tags in PhaseIdealLoop::dom_lca_for_get_late_ctrl_internal() so make sure calls to 2084 // get_late_ctrl_with_anti_dep() use their own tag 2085 _dom_lca_tags_round++; 2086 assert(_dom_lca_tags_round != 0, "shouldn't wrap around"); 2087 2088 if (u->is_Phi()) { 2089 for (uint j = 1; j < u->req(); ++j) { 2090 if (u->in(j) == n && !ctrl_of_use_out_of_loop(n, n_ctrl, n_loop, u->in(0)->in(j))) { 2091 return false; 2092 } 2093 } 2094 } else { 2095 Node* ctrl = has_ctrl(u) ? get_ctrl(u) : u->in(0); 2096 if (!ctrl_of_use_out_of_loop(n, n_ctrl, n_loop, ctrl)) { 2097 return false; 2098 } 2099 } 2100 } 2101 return true; 2102 } 2103 2104 bool PhaseIdealLoop::ctrl_of_use_out_of_loop(const Node* n, Node* n_ctrl, IdealLoopTree* n_loop, Node* ctrl) { 2105 if (n->is_Load()) { 2106 ctrl = get_late_ctrl_with_anti_dep(n->as_Load(), n_ctrl, ctrl); 2107 } 2108 IdealLoopTree *u_loop = get_loop(ctrl); 2109 if (u_loop == n_loop) { 2110 return false; // Found loop-varying use 2111 } 2112 if (n_loop->is_member(u_loop)) { 2113 return false; // Found use in inner loop 2114 } 2115 // Sinking a node from a pre loop to its main loop pins the node between the pre and main loops. If that node is input 2116 // to a check that's eliminated by range check elimination, it becomes input to an expression that feeds into the exit 2117 // test of the pre loop above the point in the graph where it's pinned. 2118 if (n_loop->_head->is_CountedLoop() && n_loop->_head->as_CountedLoop()->is_pre_loop()) { 2119 CountedLoopNode* pre_loop = n_loop->_head->as_CountedLoop(); 2120 if (is_dominator(pre_loop->loopexit(), ctrl)) { 2121 return false; 2122 } 2123 } 2124 return true; 2125 } 2126 2127 //------------------------------split_if_with_blocks--------------------------- 2128 // Check for aggressive application of 'split-if' optimization, 2129 // using basic block level info. 2130 void PhaseIdealLoop::split_if_with_blocks(VectorSet &visited, Node_Stack &nstack) { 2131 Node* root = C->root(); 2132 visited.set(root->_idx); // first, mark root as visited 2133 // Do pre-visit work for root 2134 Node* n = split_if_with_blocks_pre(root); 2135 uint cnt = n->outcnt(); 2136 uint i = 0; 2137 2138 while (true) { 2139 // Visit all children 2140 if (i < cnt) { 2141 Node* use = n->raw_out(i); 2142 ++i; 2143 if (use->outcnt() != 0 && !visited.test_set(use->_idx)) { 2144 // Now do pre-visit work for this use 2145 use = split_if_with_blocks_pre(use); 2146 nstack.push(n, i); // Save parent and next use's index. 2147 n = use; // Process all children of current use. 2148 cnt = use->outcnt(); 2149 i = 0; 2150 } 2151 } 2152 else { 2153 // All of n's children have been processed, complete post-processing. 2154 if (cnt != 0 && !n->is_Con()) { 2155 assert(has_node(n), "no dead nodes"); 2156 split_if_with_blocks_post(n); 2157 if (C->failing()) { 2158 return; 2159 } 2160 } 2161 if (must_throttle_split_if()) { 2162 nstack.clear(); 2163 } 2164 if (nstack.is_empty()) { 2165 // Finished all nodes on stack. 2166 break; 2167 } 2168 // Get saved parent node and next use's index. Visit the rest of uses. 2169 n = nstack.node(); 2170 cnt = n->outcnt(); 2171 i = nstack.index(); 2172 nstack.pop(); 2173 } 2174 } 2175 } 2176 2177 2178 //============================================================================= 2179 // 2180 // C L O N E A L O O P B O D Y 2181 // 2182 2183 //------------------------------clone_iff-------------------------------------- 2184 // Passed in a Phi merging (recursively) some nearly equivalent Bool/Cmps. 2185 // "Nearly" because all Nodes have been cloned from the original in the loop, 2186 // but the fall-in edges to the Cmp are different. Clone bool/Cmp pairs 2187 // through the Phi recursively, and return a Bool. 2188 Node* PhaseIdealLoop::clone_iff(PhiNode* phi) { 2189 2190 // Convert this Phi into a Phi merging Bools 2191 uint i; 2192 for (i = 1; i < phi->req(); i++) { 2193 Node* b = phi->in(i); 2194 if (b->is_Phi()) { 2195 _igvn.replace_input_of(phi, i, clone_iff(b->as_Phi())); 2196 } else { 2197 assert(b->is_Bool() || b->is_OpaqueNotNull() || b->is_OpaqueInitializedAssertionPredicate(), 2198 "bool, non-null check with OpaqueNotNull or Initialized Assertion Predicate with its Opaque node"); 2199 } 2200 } 2201 Node* n = phi->in(1); 2202 Node* sample_opaque = nullptr; 2203 Node *sample_bool = nullptr; 2204 if (n->is_OpaqueNotNull() || n->is_OpaqueInitializedAssertionPredicate()) { 2205 sample_opaque = n; 2206 sample_bool = n->in(1); 2207 assert(sample_bool->is_Bool(), "wrong type"); 2208 } else { 2209 sample_bool = n; 2210 } 2211 Node* sample_cmp = sample_bool->in(1); 2212 const Type* t = Type::TOP; 2213 const TypePtr* at = nullptr; 2214 if (sample_cmp->is_FlatArrayCheck()) { 2215 // Left input of a FlatArrayCheckNode is memory, set the (adr) type of the phi accordingly 2216 assert(sample_cmp->in(1)->bottom_type() == Type::MEMORY, "unexpected input type"); 2217 t = Type::MEMORY; 2218 at = TypeRawPtr::BOTTOM; 2219 } 2220 2221 // Make Phis to merge the Cmp's inputs. 2222 PhiNode *phi1 = new PhiNode(phi->in(0), t, at); 2223 PhiNode *phi2 = new PhiNode(phi->in(0), Type::TOP); 2224 for (i = 1; i < phi->req(); i++) { 2225 Node *n1 = sample_opaque == nullptr ? phi->in(i)->in(1)->in(1) : phi->in(i)->in(1)->in(1)->in(1); 2226 Node *n2 = sample_opaque == nullptr ? phi->in(i)->in(1)->in(2) : phi->in(i)->in(1)->in(1)->in(2); 2227 phi1->set_req(i, n1); 2228 phi2->set_req(i, n2); 2229 phi1->set_type(phi1->type()->meet_speculative(n1->bottom_type())); 2230 phi2->set_type(phi2->type()->meet_speculative(n2->bottom_type())); 2231 } 2232 // See if these Phis have been made before. 2233 // Register with optimizer 2234 Node *hit1 = _igvn.hash_find_insert(phi1); 2235 if (hit1) { // Hit, toss just made Phi 2236 _igvn.remove_dead_node(phi1); // Remove new phi 2237 assert(hit1->is_Phi(), "" ); 2238 phi1 = (PhiNode*)hit1; // Use existing phi 2239 } else { // Miss 2240 _igvn.register_new_node_with_optimizer(phi1); 2241 } 2242 Node *hit2 = _igvn.hash_find_insert(phi2); 2243 if (hit2) { // Hit, toss just made Phi 2244 _igvn.remove_dead_node(phi2); // Remove new phi 2245 assert(hit2->is_Phi(), "" ); 2246 phi2 = (PhiNode*)hit2; // Use existing phi 2247 } else { // Miss 2248 _igvn.register_new_node_with_optimizer(phi2); 2249 } 2250 // Register Phis with loop/block info 2251 set_ctrl(phi1, phi->in(0)); 2252 set_ctrl(phi2, phi->in(0)); 2253 // Make a new Cmp 2254 Node *cmp = sample_cmp->clone(); 2255 cmp->set_req(1, phi1); 2256 cmp->set_req(2, phi2); 2257 _igvn.register_new_node_with_optimizer(cmp); 2258 set_ctrl(cmp, phi->in(0)); 2259 2260 // Make a new Bool 2261 Node *b = sample_bool->clone(); 2262 b->set_req(1,cmp); 2263 _igvn.register_new_node_with_optimizer(b); 2264 set_ctrl(b, phi->in(0)); 2265 2266 if (sample_opaque != nullptr) { 2267 Node* opaque = sample_opaque->clone(); 2268 opaque->set_req(1, b); 2269 _igvn.register_new_node_with_optimizer(opaque); 2270 set_ctrl(opaque, phi->in(0)); 2271 return opaque; 2272 } 2273 2274 assert(b->is_Bool(), ""); 2275 return b; 2276 } 2277 2278 //------------------------------clone_bool------------------------------------- 2279 // Passed in a Phi merging (recursively) some nearly equivalent Bool/Cmps. 2280 // "Nearly" because all Nodes have been cloned from the original in the loop, 2281 // but the fall-in edges to the Cmp are different. Clone bool/Cmp pairs 2282 // through the Phi recursively, and return a Bool. 2283 CmpNode*PhaseIdealLoop::clone_bool(PhiNode* phi) { 2284 uint i; 2285 // Convert this Phi into a Phi merging Bools 2286 for( i = 1; i < phi->req(); i++ ) { 2287 Node *b = phi->in(i); 2288 if( b->is_Phi() ) { 2289 _igvn.replace_input_of(phi, i, clone_bool(b->as_Phi())); 2290 } else { 2291 assert( b->is_Cmp() || b->is_top(), "inputs are all Cmp or TOP" ); 2292 } 2293 } 2294 2295 Node *sample_cmp = phi->in(1); 2296 2297 // Make Phis to merge the Cmp's inputs. 2298 PhiNode *phi1 = new PhiNode( phi->in(0), Type::TOP ); 2299 PhiNode *phi2 = new PhiNode( phi->in(0), Type::TOP ); 2300 for( uint j = 1; j < phi->req(); j++ ) { 2301 Node *cmp_top = phi->in(j); // Inputs are all Cmp or TOP 2302 Node *n1, *n2; 2303 if( cmp_top->is_Cmp() ) { 2304 n1 = cmp_top->in(1); 2305 n2 = cmp_top->in(2); 2306 } else { 2307 n1 = n2 = cmp_top; 2308 } 2309 phi1->set_req( j, n1 ); 2310 phi2->set_req( j, n2 ); 2311 phi1->set_type(phi1->type()->meet_speculative(n1->bottom_type())); 2312 phi2->set_type(phi2->type()->meet_speculative(n2->bottom_type())); 2313 } 2314 2315 // See if these Phis have been made before. 2316 // Register with optimizer 2317 Node *hit1 = _igvn.hash_find_insert(phi1); 2318 if( hit1 ) { // Hit, toss just made Phi 2319 _igvn.remove_dead_node(phi1); // Remove new phi 2320 assert( hit1->is_Phi(), "" ); 2321 phi1 = (PhiNode*)hit1; // Use existing phi 2322 } else { // Miss 2323 _igvn.register_new_node_with_optimizer(phi1); 2324 } 2325 Node *hit2 = _igvn.hash_find_insert(phi2); 2326 if( hit2 ) { // Hit, toss just made Phi 2327 _igvn.remove_dead_node(phi2); // Remove new phi 2328 assert( hit2->is_Phi(), "" ); 2329 phi2 = (PhiNode*)hit2; // Use existing phi 2330 } else { // Miss 2331 _igvn.register_new_node_with_optimizer(phi2); 2332 } 2333 // Register Phis with loop/block info 2334 set_ctrl(phi1, phi->in(0)); 2335 set_ctrl(phi2, phi->in(0)); 2336 // Make a new Cmp 2337 Node *cmp = sample_cmp->clone(); 2338 cmp->set_req( 1, phi1 ); 2339 cmp->set_req( 2, phi2 ); 2340 _igvn.register_new_node_with_optimizer(cmp); 2341 set_ctrl(cmp, phi->in(0)); 2342 2343 assert( cmp->is_Cmp(), "" ); 2344 return (CmpNode*)cmp; 2345 } 2346 2347 void PhaseIdealLoop::clone_loop_handle_data_uses(Node* old, Node_List &old_new, 2348 IdealLoopTree* loop, IdealLoopTree* outer_loop, 2349 Node_List*& split_if_set, Node_List*& split_bool_set, 2350 Node_List*& split_cex_set, Node_List& worklist, 2351 uint new_counter, CloneLoopMode mode) { 2352 Node* nnn = old_new[old->_idx]; 2353 // Copy uses to a worklist, so I can munge the def-use info 2354 // with impunity. 2355 for (DUIterator_Fast jmax, j = old->fast_outs(jmax); j < jmax; j++) 2356 worklist.push(old->fast_out(j)); 2357 2358 while( worklist.size() ) { 2359 Node *use = worklist.pop(); 2360 if (!has_node(use)) continue; // Ignore dead nodes 2361 if (use->in(0) == C->top()) continue; 2362 IdealLoopTree *use_loop = get_loop( has_ctrl(use) ? get_ctrl(use) : use ); 2363 // Check for data-use outside of loop - at least one of OLD or USE 2364 // must not be a CFG node. 2365 #ifdef ASSERT 2366 if (loop->_head->as_Loop()->is_strip_mined() && outer_loop->is_member(use_loop) && !loop->is_member(use_loop) && old_new[use->_idx] == nullptr) { 2367 Node* sfpt = loop->_head->as_CountedLoop()->outer_safepoint(); 2368 assert(mode != IgnoreStripMined, "incorrect cloning mode"); 2369 assert((mode == ControlAroundStripMined && use == sfpt) || !use->is_reachable_from_root(), "missed a node"); 2370 } 2371 #endif 2372 if (!loop->is_member(use_loop) && !outer_loop->is_member(use_loop) && (!old->is_CFG() || !use->is_CFG())) { 2373 2374 // If the Data use is an IF, that means we have an IF outside the 2375 // loop that is switching on a condition that is set inside the 2376 // loop. Happens if people set a loop-exit flag; then test the flag 2377 // in the loop to break the loop, then test is again outside the 2378 // loop to determine which way the loop exited. 2379 // 2380 // For several uses we need to make sure that there is no phi between, 2381 // the use and the Bool/Cmp. We therefore clone the Bool/Cmp down here 2382 // to avoid such a phi in between. 2383 // For example, it is unexpected that there is a Phi between an 2384 // AllocateArray node and its ValidLengthTest input that could cause 2385 // split if to break. 2386 assert(!use->is_OpaqueTemplateAssertionPredicate(), 2387 "should not clone a Template Assertion Predicate which should be removed once it's useless"); 2388 if (use->is_If() || use->is_CMove() || use->is_OpaqueNotNull() || use->is_OpaqueInitializedAssertionPredicate() || 2389 (use->Opcode() == Op_AllocateArray && use->in(AllocateNode::ValidLengthTest) == old)) { 2390 // Since this code is highly unlikely, we lazily build the worklist 2391 // of such Nodes to go split. 2392 if (!split_if_set) { 2393 split_if_set = new Node_List(); 2394 } 2395 split_if_set->push(use); 2396 } 2397 if (use->is_Bool()) { 2398 if (!split_bool_set) { 2399 split_bool_set = new Node_List(); 2400 } 2401 split_bool_set->push(use); 2402 } 2403 if (use->Opcode() == Op_CreateEx) { 2404 if (!split_cex_set) { 2405 split_cex_set = new Node_List(); 2406 } 2407 split_cex_set->push(use); 2408 } 2409 2410 2411 // Get "block" use is in 2412 uint idx = 0; 2413 while( use->in(idx) != old ) idx++; 2414 Node *prev = use->is_CFG() ? use : get_ctrl(use); 2415 assert(!loop->is_member(get_loop(prev)) && !outer_loop->is_member(get_loop(prev)), "" ); 2416 Node* cfg = (prev->_idx >= new_counter && prev->is_Region()) 2417 ? prev->in(2) 2418 : idom(prev); 2419 if( use->is_Phi() ) // Phi use is in prior block 2420 cfg = prev->in(idx); // NOT in block of Phi itself 2421 if (cfg->is_top()) { // Use is dead? 2422 _igvn.replace_input_of(use, idx, C->top()); 2423 continue; 2424 } 2425 2426 // If use is referenced through control edge... (idx == 0) 2427 if (mode == IgnoreStripMined && idx == 0) { 2428 LoopNode *head = loop->_head->as_Loop(); 2429 if (head->is_strip_mined() && is_dominator(head->outer_loop_exit(), prev)) { 2430 // That node is outside the inner loop, leave it outside the 2431 // outer loop as well to not confuse verification code. 2432 assert(!loop->_parent->is_member(use_loop), "should be out of the outer loop"); 2433 _igvn.replace_input_of(use, 0, head->outer_loop_exit()); 2434 continue; 2435 } 2436 } 2437 2438 while(!outer_loop->is_member(get_loop(cfg))) { 2439 prev = cfg; 2440 cfg = (cfg->_idx >= new_counter && cfg->is_Region()) ? cfg->in(2) : idom(cfg); 2441 } 2442 // If the use occurs after merging several exits from the loop, then 2443 // old value must have dominated all those exits. Since the same old 2444 // value was used on all those exits we did not need a Phi at this 2445 // merge point. NOW we do need a Phi here. Each loop exit value 2446 // is now merged with the peeled body exit; each exit gets its own 2447 // private Phi and those Phis need to be merged here. 2448 Node *phi; 2449 if( prev->is_Region() ) { 2450 if( idx == 0 ) { // Updating control edge? 2451 phi = prev; // Just use existing control 2452 } else { // Else need a new Phi 2453 phi = PhiNode::make( prev, old ); 2454 // Now recursively fix up the new uses of old! 2455 for( uint i = 1; i < prev->req(); i++ ) { 2456 worklist.push(phi); // Onto worklist once for each 'old' input 2457 } 2458 } 2459 } else { 2460 // Get new RegionNode merging old and new loop exits 2461 prev = old_new[prev->_idx]; 2462 assert( prev, "just made this in step 7" ); 2463 if( idx == 0) { // Updating control edge? 2464 phi = prev; // Just use existing control 2465 } else { // Else need a new Phi 2466 // Make a new Phi merging data values properly 2467 phi = PhiNode::make( prev, old ); 2468 phi->set_req( 1, nnn ); 2469 } 2470 } 2471 // If inserting a new Phi, check for prior hits 2472 if( idx != 0 ) { 2473 Node *hit = _igvn.hash_find_insert(phi); 2474 if( hit == nullptr ) { 2475 _igvn.register_new_node_with_optimizer(phi); // Register new phi 2476 } else { // or 2477 // Remove the new phi from the graph and use the hit 2478 _igvn.remove_dead_node(phi); 2479 phi = hit; // Use existing phi 2480 } 2481 set_ctrl(phi, prev); 2482 } 2483 // Make 'use' use the Phi instead of the old loop body exit value 2484 assert(use->in(idx) == old, "old is still input of use"); 2485 // We notify all uses of old, including use, and the indirect uses, 2486 // that may now be optimized because we have replaced old with phi. 2487 _igvn.add_users_to_worklist(old); 2488 if (idx == 0 && 2489 use->depends_only_on_test()) { 2490 Node* pinned_clone = use->pin_array_access_node(); 2491 if (pinned_clone != nullptr) { 2492 // Pin array access nodes: control is updated here to a region. If, after some transformations, only one path 2493 // into the region is left, an array load could become dependent on a condition that's not a range check for 2494 // that access. If that condition is replaced by an identical dominating one, then an unpinned load would risk 2495 // floating above its range check. 2496 pinned_clone->set_req(0, phi); 2497 register_new_node_with_ctrl_of(pinned_clone, use); 2498 _igvn.replace_node(use, pinned_clone); 2499 continue; 2500 } 2501 } 2502 _igvn.replace_input_of(use, idx, phi); 2503 if( use->_idx >= new_counter ) { // If updating new phis 2504 // Not needed for correctness, but prevents a weak assert 2505 // in AddPNode from tripping (when we end up with different 2506 // base & derived Phis that will become the same after 2507 // IGVN does CSE). 2508 Node *hit = _igvn.hash_find_insert(use); 2509 if( hit ) // Go ahead and re-hash for hits. 2510 _igvn.replace_node( use, hit ); 2511 } 2512 } 2513 } 2514 } 2515 2516 static void collect_nodes_in_outer_loop_not_reachable_from_sfpt(Node* n, const IdealLoopTree *loop, const IdealLoopTree* outer_loop, 2517 const Node_List &old_new, Unique_Node_List& wq, PhaseIdealLoop* phase, 2518 bool check_old_new) { 2519 for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++) { 2520 Node* u = n->fast_out(j); 2521 assert(check_old_new || old_new[u->_idx] == nullptr, "shouldn't have been cloned"); 2522 if (!u->is_CFG() && (!check_old_new || old_new[u->_idx] == nullptr)) { 2523 Node* c = phase->get_ctrl(u); 2524 IdealLoopTree* u_loop = phase->get_loop(c); 2525 assert(!loop->is_member(u_loop) || !loop->_body.contains(u), "can be in outer loop or out of both loops only"); 2526 if (!loop->is_member(u_loop)) { 2527 if (outer_loop->is_member(u_loop)) { 2528 wq.push(u); 2529 } else { 2530 // nodes pinned with control in the outer loop but not referenced from the safepoint must be moved out of 2531 // the outer loop too 2532 Node* u_c = u->in(0); 2533 if (u_c != nullptr) { 2534 IdealLoopTree* u_c_loop = phase->get_loop(u_c); 2535 if (outer_loop->is_member(u_c_loop) && !loop->is_member(u_c_loop)) { 2536 wq.push(u); 2537 } 2538 } 2539 } 2540 } 2541 } 2542 } 2543 } 2544 2545 void PhaseIdealLoop::clone_outer_loop(LoopNode* head, CloneLoopMode mode, IdealLoopTree *loop, 2546 IdealLoopTree* outer_loop, int dd, Node_List &old_new, 2547 Node_List& extra_data_nodes) { 2548 if (head->is_strip_mined() && mode != IgnoreStripMined) { 2549 CountedLoopNode* cl = head->as_CountedLoop(); 2550 Node* l = cl->outer_loop(); 2551 Node* tail = cl->outer_loop_tail(); 2552 IfNode* le = cl->outer_loop_end(); 2553 Node* sfpt = cl->outer_safepoint(); 2554 CountedLoopEndNode* cle = cl->loopexit(); 2555 CountedLoopNode* new_cl = old_new[cl->_idx]->as_CountedLoop(); 2556 CountedLoopEndNode* new_cle = new_cl->as_CountedLoop()->loopexit_or_null(); 2557 Node* cle_out = cle->proj_out(false); 2558 2559 Node* new_sfpt = nullptr; 2560 Node* new_cle_out = cle_out->clone(); 2561 old_new.map(cle_out->_idx, new_cle_out); 2562 if (mode == CloneIncludesStripMined) { 2563 // clone outer loop body 2564 Node* new_l = l->clone(); 2565 Node* new_tail = tail->clone(); 2566 IfNode* new_le = le->clone()->as_If(); 2567 new_sfpt = sfpt->clone(); 2568 2569 set_loop(new_l, outer_loop->_parent); 2570 set_idom(new_l, new_l->in(LoopNode::EntryControl), dd); 2571 set_loop(new_cle_out, outer_loop->_parent); 2572 set_idom(new_cle_out, new_cle, dd); 2573 set_loop(new_sfpt, outer_loop->_parent); 2574 set_idom(new_sfpt, new_cle_out, dd); 2575 set_loop(new_le, outer_loop->_parent); 2576 set_idom(new_le, new_sfpt, dd); 2577 set_loop(new_tail, outer_loop->_parent); 2578 set_idom(new_tail, new_le, dd); 2579 set_idom(new_cl, new_l, dd); 2580 2581 old_new.map(l->_idx, new_l); 2582 old_new.map(tail->_idx, new_tail); 2583 old_new.map(le->_idx, new_le); 2584 old_new.map(sfpt->_idx, new_sfpt); 2585 2586 new_l->set_req(LoopNode::LoopBackControl, new_tail); 2587 new_l->set_req(0, new_l); 2588 new_tail->set_req(0, new_le); 2589 new_le->set_req(0, new_sfpt); 2590 new_sfpt->set_req(0, new_cle_out); 2591 new_cle_out->set_req(0, new_cle); 2592 new_cl->set_req(LoopNode::EntryControl, new_l); 2593 2594 _igvn.register_new_node_with_optimizer(new_l); 2595 _igvn.register_new_node_with_optimizer(new_tail); 2596 _igvn.register_new_node_with_optimizer(new_le); 2597 } else { 2598 Node *newhead = old_new[loop->_head->_idx]; 2599 newhead->as_Loop()->clear_strip_mined(); 2600 _igvn.replace_input_of(newhead, LoopNode::EntryControl, newhead->in(LoopNode::EntryControl)->in(LoopNode::EntryControl)); 2601 set_idom(newhead, newhead->in(LoopNode::EntryControl), dd); 2602 } 2603 // Look at data node that were assigned a control in the outer 2604 // loop: they are kept in the outer loop by the safepoint so start 2605 // from the safepoint node's inputs. 2606 IdealLoopTree* outer_loop = get_loop(l); 2607 Node_Stack stack(2); 2608 stack.push(sfpt, 1); 2609 uint new_counter = C->unique(); 2610 while (stack.size() > 0) { 2611 Node* n = stack.node(); 2612 uint i = stack.index(); 2613 while (i < n->req() && 2614 (n->in(i) == nullptr || 2615 !has_ctrl(n->in(i)) || 2616 get_loop(get_ctrl(n->in(i))) != outer_loop || 2617 (old_new[n->in(i)->_idx] != nullptr && old_new[n->in(i)->_idx]->_idx >= new_counter))) { 2618 i++; 2619 } 2620 if (i < n->req()) { 2621 stack.set_index(i+1); 2622 stack.push(n->in(i), 0); 2623 } else { 2624 assert(old_new[n->_idx] == nullptr || n == sfpt || old_new[n->_idx]->_idx < new_counter, "no clone yet"); 2625 Node* m = n == sfpt ? new_sfpt : n->clone(); 2626 if (m != nullptr) { 2627 for (uint i = 0; i < n->req(); i++) { 2628 if (m->in(i) != nullptr && old_new[m->in(i)->_idx] != nullptr) { 2629 m->set_req(i, old_new[m->in(i)->_idx]); 2630 } 2631 } 2632 } else { 2633 assert(n == sfpt && mode != CloneIncludesStripMined, "where's the safepoint clone?"); 2634 } 2635 if (n != sfpt) { 2636 extra_data_nodes.push(n); 2637 _igvn.register_new_node_with_optimizer(m); 2638 assert(get_ctrl(n) == cle_out, "what other control?"); 2639 set_ctrl(m, new_cle_out); 2640 old_new.map(n->_idx, m); 2641 } 2642 stack.pop(); 2643 } 2644 } 2645 if (mode == CloneIncludesStripMined) { 2646 _igvn.register_new_node_with_optimizer(new_sfpt); 2647 _igvn.register_new_node_with_optimizer(new_cle_out); 2648 } 2649 // Some other transformation may have pessimistically assigned some 2650 // data nodes to the outer loop. Set their control so they are out 2651 // of the outer loop. 2652 ResourceMark rm; 2653 Unique_Node_List wq; 2654 for (uint i = 0; i < extra_data_nodes.size(); i++) { 2655 Node* old = extra_data_nodes.at(i); 2656 collect_nodes_in_outer_loop_not_reachable_from_sfpt(old, loop, outer_loop, old_new, wq, this, true); 2657 } 2658 2659 for (uint i = 0; i < loop->_body.size(); i++) { 2660 Node* old = loop->_body.at(i); 2661 collect_nodes_in_outer_loop_not_reachable_from_sfpt(old, loop, outer_loop, old_new, wq, this, true); 2662 } 2663 2664 Node* inner_out = sfpt->in(0); 2665 if (inner_out->outcnt() > 1) { 2666 collect_nodes_in_outer_loop_not_reachable_from_sfpt(inner_out, loop, outer_loop, old_new, wq, this, true); 2667 } 2668 2669 Node* new_ctrl = cl->outer_loop_exit(); 2670 assert(get_loop(new_ctrl) != outer_loop, "must be out of the loop nest"); 2671 for (uint i = 0; i < wq.size(); i++) { 2672 Node* n = wq.at(i); 2673 set_ctrl(n, new_ctrl); 2674 if (n->in(0) != nullptr) { 2675 _igvn.replace_input_of(n, 0, new_ctrl); 2676 } 2677 collect_nodes_in_outer_loop_not_reachable_from_sfpt(n, loop, outer_loop, old_new, wq, this, false); 2678 } 2679 } else { 2680 Node *newhead = old_new[loop->_head->_idx]; 2681 set_idom(newhead, newhead->in(LoopNode::EntryControl), dd); 2682 } 2683 } 2684 2685 //------------------------------clone_loop------------------------------------- 2686 // 2687 // C L O N E A L O O P B O D Y 2688 // 2689 // This is the basic building block of the loop optimizations. It clones an 2690 // entire loop body. It makes an old_new loop body mapping; with this mapping 2691 // you can find the new-loop equivalent to an old-loop node. All new-loop 2692 // nodes are exactly equal to their old-loop counterparts, all edges are the 2693 // same. All exits from the old-loop now have a RegionNode that merges the 2694 // equivalent new-loop path. This is true even for the normal "loop-exit" 2695 // condition. All uses of loop-invariant old-loop values now come from (one 2696 // or more) Phis that merge their new-loop equivalents. 2697 // 2698 // This operation leaves the graph in an illegal state: there are two valid 2699 // control edges coming from the loop pre-header to both loop bodies. I'll 2700 // definitely have to hack the graph after running this transform. 2701 // 2702 // From this building block I will further edit edges to perform loop peeling 2703 // or loop unrolling or iteration splitting (Range-Check-Elimination), etc. 2704 // 2705 // Parameter side_by_size_idom: 2706 // When side_by_size_idom is null, the dominator tree is constructed for 2707 // the clone loop to dominate the original. Used in construction of 2708 // pre-main-post loop sequence. 2709 // When nonnull, the clone and original are side-by-side, both are 2710 // dominated by the side_by_side_idom node. Used in construction of 2711 // unswitched loops. 2712 void PhaseIdealLoop::clone_loop( IdealLoopTree *loop, Node_List &old_new, int dd, 2713 CloneLoopMode mode, Node* side_by_side_idom) { 2714 2715 LoopNode* head = loop->_head->as_Loop(); 2716 head->verify_strip_mined(1); 2717 2718 if (C->do_vector_loop() && PrintOpto) { 2719 const char* mname = C->method()->name()->as_quoted_ascii(); 2720 if (mname != nullptr) { 2721 tty->print("PhaseIdealLoop::clone_loop: for vectorize method %s\n", mname); 2722 } 2723 } 2724 2725 CloneMap& cm = C->clone_map(); 2726 if (C->do_vector_loop()) { 2727 cm.set_clone_idx(cm.max_gen()+1); 2728 #ifndef PRODUCT 2729 if (PrintOpto) { 2730 tty->print_cr("PhaseIdealLoop::clone_loop: _clone_idx %d", cm.clone_idx()); 2731 loop->dump_head(); 2732 } 2733 #endif 2734 } 2735 2736 // Step 1: Clone the loop body. Make the old->new mapping. 2737 clone_loop_body(loop->_body, old_new, &cm); 2738 2739 IdealLoopTree* outer_loop = (head->is_strip_mined() && mode != IgnoreStripMined) ? get_loop(head->as_CountedLoop()->outer_loop()) : loop; 2740 2741 // Step 2: Fix the edges in the new body. If the old input is outside the 2742 // loop use it. If the old input is INside the loop, use the corresponding 2743 // new node instead. 2744 fix_body_edges(loop->_body, loop, old_new, dd, outer_loop->_parent, false); 2745 2746 Node_List extra_data_nodes; // data nodes in the outer strip mined loop 2747 clone_outer_loop(head, mode, loop, outer_loop, dd, old_new, extra_data_nodes); 2748 2749 // Step 3: Now fix control uses. Loop varying control uses have already 2750 // been fixed up (as part of all input edges in Step 2). Loop invariant 2751 // control uses must be either an IfFalse or an IfTrue. Make a merge 2752 // point to merge the old and new IfFalse/IfTrue nodes; make the use 2753 // refer to this. 2754 Node_List worklist; 2755 uint new_counter = C->unique(); 2756 fix_ctrl_uses(loop->_body, loop, old_new, mode, side_by_side_idom, &cm, worklist); 2757 2758 // Step 4: If loop-invariant use is not control, it must be dominated by a 2759 // loop exit IfFalse/IfTrue. Find "proper" loop exit. Make a Region 2760 // there if needed. Make a Phi there merging old and new used values. 2761 Node_List *split_if_set = nullptr; 2762 Node_List *split_bool_set = nullptr; 2763 Node_List *split_cex_set = nullptr; 2764 fix_data_uses(loop->_body, loop, mode, outer_loop, new_counter, old_new, worklist, split_if_set, split_bool_set, split_cex_set); 2765 2766 for (uint i = 0; i < extra_data_nodes.size(); i++) { 2767 Node* old = extra_data_nodes.at(i); 2768 clone_loop_handle_data_uses(old, old_new, loop, outer_loop, split_if_set, 2769 split_bool_set, split_cex_set, worklist, new_counter, 2770 mode); 2771 } 2772 2773 // Check for IFs that need splitting/cloning. Happens if an IF outside of 2774 // the loop uses a condition set in the loop. The original IF probably 2775 // takes control from one or more OLD Regions (which in turn get from NEW 2776 // Regions). In any case, there will be a set of Phis for each merge point 2777 // from the IF up to where the original BOOL def exists the loop. 2778 finish_clone_loop(split_if_set, split_bool_set, split_cex_set); 2779 2780 } 2781 2782 void PhaseIdealLoop::finish_clone_loop(Node_List* split_if_set, Node_List* split_bool_set, Node_List* split_cex_set) { 2783 if (split_if_set) { 2784 while (split_if_set->size()) { 2785 Node *iff = split_if_set->pop(); 2786 uint input = iff->Opcode() == Op_AllocateArray ? AllocateNode::ValidLengthTest : 1; 2787 if (iff->in(input)->is_Phi()) { 2788 Node *b = clone_iff(iff->in(input)->as_Phi()); 2789 _igvn.replace_input_of(iff, input, b); 2790 } 2791 } 2792 } 2793 if (split_bool_set) { 2794 while (split_bool_set->size()) { 2795 Node *b = split_bool_set->pop(); 2796 Node *phi = b->in(1); 2797 assert(phi->is_Phi(), ""); 2798 CmpNode *cmp = clone_bool((PhiNode*) phi); 2799 _igvn.replace_input_of(b, 1, cmp); 2800 } 2801 } 2802 if (split_cex_set) { 2803 while (split_cex_set->size()) { 2804 Node *b = split_cex_set->pop(); 2805 assert(b->in(0)->is_Region(), ""); 2806 assert(b->in(1)->is_Phi(), ""); 2807 assert(b->in(0)->in(0) == b->in(1)->in(0), ""); 2808 split_up(b, b->in(0), nullptr); 2809 } 2810 } 2811 } 2812 2813 void PhaseIdealLoop::fix_data_uses(Node_List& body, IdealLoopTree* loop, CloneLoopMode mode, IdealLoopTree* outer_loop, 2814 uint new_counter, Node_List &old_new, Node_List &worklist, Node_List*& split_if_set, 2815 Node_List*& split_bool_set, Node_List*& split_cex_set) { 2816 for(uint i = 0; i < body.size(); i++ ) { 2817 Node* old = body.at(i); 2818 clone_loop_handle_data_uses(old, old_new, loop, outer_loop, split_if_set, 2819 split_bool_set, split_cex_set, worklist, new_counter, 2820 mode); 2821 } 2822 } 2823 2824 void PhaseIdealLoop::fix_ctrl_uses(const Node_List& body, const IdealLoopTree* loop, Node_List &old_new, CloneLoopMode mode, 2825 Node* side_by_side_idom, CloneMap* cm, Node_List &worklist) { 2826 LoopNode* head = loop->_head->as_Loop(); 2827 for(uint i = 0; i < body.size(); i++ ) { 2828 Node* old = body.at(i); 2829 if( !old->is_CFG() ) continue; 2830 2831 // Copy uses to a worklist, so I can munge the def-use info 2832 // with impunity. 2833 for (DUIterator_Fast jmax, j = old->fast_outs(jmax); j < jmax; j++) { 2834 worklist.push(old->fast_out(j)); 2835 } 2836 2837 while (worklist.size()) { // Visit all uses 2838 Node *use = worklist.pop(); 2839 if (!has_node(use)) continue; // Ignore dead nodes 2840 IdealLoopTree *use_loop = get_loop(has_ctrl(use) ? get_ctrl(use) : use ); 2841 if (!loop->is_member(use_loop) && use->is_CFG()) { 2842 // Both OLD and USE are CFG nodes here. 2843 assert(use->is_Proj(), "" ); 2844 Node* nnn = old_new[old->_idx]; 2845 2846 Node* newuse = nullptr; 2847 if (head->is_strip_mined() && mode != IgnoreStripMined) { 2848 CountedLoopNode* cl = head->as_CountedLoop(); 2849 CountedLoopEndNode* cle = cl->loopexit(); 2850 Node* cle_out = cle->proj_out_or_null(false); 2851 if (use == cle_out) { 2852 IfNode* le = cl->outer_loop_end(); 2853 use = le->proj_out(false); 2854 use_loop = get_loop(use); 2855 if (mode == CloneIncludesStripMined) { 2856 nnn = old_new[le->_idx]; 2857 } else { 2858 newuse = old_new[cle_out->_idx]; 2859 } 2860 } 2861 } 2862 if (newuse == nullptr) { 2863 newuse = use->clone(); 2864 } 2865 2866 // Clone the loop exit control projection 2867 if (C->do_vector_loop() && cm != nullptr) { 2868 cm->verify_insert_and_clone(use, newuse, cm->clone_idx()); 2869 } 2870 newuse->set_req(0,nnn); 2871 _igvn.register_new_node_with_optimizer(newuse); 2872 set_loop(newuse, use_loop); 2873 set_idom(newuse, nnn, dom_depth(nnn) + 1 ); 2874 2875 // We need a Region to merge the exit from the peeled body and the 2876 // exit from the old loop body. 2877 RegionNode *r = new RegionNode(3); 2878 uint dd_r = MIN2(dom_depth(newuse), dom_depth(use)); 2879 assert(dd_r >= dom_depth(dom_lca(newuse, use)), "" ); 2880 2881 // The original user of 'use' uses 'r' instead. 2882 for (DUIterator_Last lmin, l = use->last_outs(lmin); l >= lmin;) { 2883 Node* useuse = use->last_out(l); 2884 _igvn.rehash_node_delayed(useuse); 2885 uint uses_found = 0; 2886 if (useuse->in(0) == use) { 2887 useuse->set_req(0, r); 2888 uses_found++; 2889 if (useuse->is_CFG()) { 2890 // This is not a dom_depth > dd_r because when new 2891 // control flow is constructed by a loop opt, a node and 2892 // its dominator can end up at the same dom_depth 2893 assert(dom_depth(useuse) >= dd_r, ""); 2894 set_idom(useuse, r, dom_depth(useuse)); 2895 } 2896 } 2897 for (uint k = 1; k < useuse->req(); k++) { 2898 if( useuse->in(k) == use ) { 2899 useuse->set_req(k, r); 2900 uses_found++; 2901 if (useuse->is_Loop() && k == LoopNode::EntryControl) { 2902 // This is not a dom_depth > dd_r because when new 2903 // control flow is constructed by a loop opt, a node 2904 // and its dominator can end up at the same dom_depth 2905 assert(dom_depth(useuse) >= dd_r , ""); 2906 set_idom(useuse, r, dom_depth(useuse)); 2907 } 2908 } 2909 } 2910 l -= uses_found; // we deleted 1 or more copies of this edge 2911 } 2912 2913 assert(use->is_Proj(), "loop exit should be projection"); 2914 // lazy_replace() below moves all nodes that are: 2915 // - control dependent on the loop exit or 2916 // - have control set to the loop exit 2917 // below the post-loop merge point. lazy_replace() takes a dead control as first input. To make it 2918 // possible to use it, the loop exit projection is cloned and becomes the new exit projection. The initial one 2919 // becomes dead and is "replaced" by the region. 2920 Node* use_clone = use->clone(); 2921 register_control(use_clone, use_loop, idom(use), dom_depth(use)); 2922 // Now finish up 'r' 2923 r->set_req(1, newuse); 2924 r->set_req(2, use_clone); 2925 _igvn.register_new_node_with_optimizer(r); 2926 set_loop(r, use_loop); 2927 set_idom(r, (side_by_side_idom == nullptr) ? newuse->in(0) : side_by_side_idom, dd_r); 2928 lazy_replace(use, r); 2929 // Map the (cloned) old use to the new merge point 2930 old_new.map(use_clone->_idx, r); 2931 } // End of if a loop-exit test 2932 } 2933 } 2934 } 2935 2936 void PhaseIdealLoop::fix_body_edges(const Node_List &body, IdealLoopTree* loop, const Node_List &old_new, int dd, 2937 IdealLoopTree* parent, bool partial) { 2938 for(uint i = 0; i < body.size(); i++ ) { 2939 Node *old = body.at(i); 2940 Node *nnn = old_new[old->_idx]; 2941 // Fix CFG/Loop controlling the new node 2942 if (has_ctrl(old)) { 2943 set_ctrl(nnn, old_new[get_ctrl(old)->_idx]); 2944 } else { 2945 set_loop(nnn, parent); 2946 if (old->outcnt() > 0) { 2947 Node* dom = idom(old); 2948 if (old_new[dom->_idx] != nullptr) { 2949 dom = old_new[dom->_idx]; 2950 set_idom(nnn, dom, dd ); 2951 } 2952 } 2953 } 2954 // Correct edges to the new node 2955 for (uint j = 0; j < nnn->req(); j++) { 2956 Node *n = nnn->in(j); 2957 if (n != nullptr) { 2958 IdealLoopTree *old_in_loop = get_loop(has_ctrl(n) ? get_ctrl(n) : n); 2959 if (loop->is_member(old_in_loop)) { 2960 if (old_new[n->_idx] != nullptr) { 2961 nnn->set_req(j, old_new[n->_idx]); 2962 } else { 2963 assert(!body.contains(n), ""); 2964 assert(partial, "node not cloned"); 2965 } 2966 } 2967 } 2968 } 2969 _igvn.hash_find_insert(nnn); 2970 } 2971 } 2972 2973 void PhaseIdealLoop::clone_loop_body(const Node_List& body, Node_List &old_new, CloneMap* cm) { 2974 for (uint i = 0; i < body.size(); i++) { 2975 Node* old = body.at(i); 2976 Node* nnn = old->clone(); 2977 old_new.map(old->_idx, nnn); 2978 if (C->do_vector_loop() && cm != nullptr) { 2979 cm->verify_insert_and_clone(old, nnn, cm->clone_idx()); 2980 } 2981 _igvn.register_new_node_with_optimizer(nnn); 2982 } 2983 } 2984 2985 2986 //---------------------- stride_of_possible_iv ------------------------------------- 2987 // Looks for an iff/bool/comp with one operand of the compare 2988 // being a cycle involving an add and a phi, 2989 // with an optional truncation (left-shift followed by a right-shift) 2990 // of the add. Returns zero if not an iv. 2991 int PhaseIdealLoop::stride_of_possible_iv(Node* iff) { 2992 Node* trunc1 = nullptr; 2993 Node* trunc2 = nullptr; 2994 const TypeInteger* ttype = nullptr; 2995 if (!iff->is_If() || iff->in(1) == nullptr || !iff->in(1)->is_Bool()) { 2996 return 0; 2997 } 2998 BoolNode* bl = iff->in(1)->as_Bool(); 2999 Node* cmp = bl->in(1); 3000 if (!cmp || (cmp->Opcode() != Op_CmpI && cmp->Opcode() != Op_CmpU)) { 3001 return 0; 3002 } 3003 // Must have an invariant operand 3004 if (is_member(get_loop(iff), get_ctrl(cmp->in(2)))) { 3005 return 0; 3006 } 3007 Node* add2 = nullptr; 3008 Node* cmp1 = cmp->in(1); 3009 if (cmp1->is_Phi()) { 3010 // (If (Bool (CmpX phi:(Phi ...(Optional-trunc(AddI phi add2))) ))) 3011 Node* phi = cmp1; 3012 for (uint i = 1; i < phi->req(); i++) { 3013 Node* in = phi->in(i); 3014 Node* add = CountedLoopNode::match_incr_with_optional_truncation(in, 3015 &trunc1, &trunc2, &ttype, T_INT); 3016 if (add && add->in(1) == phi) { 3017 add2 = add->in(2); 3018 break; 3019 } 3020 } 3021 } else { 3022 // (If (Bool (CmpX addtrunc:(Optional-trunc((AddI (Phi ...addtrunc...) add2)) ))) 3023 Node* addtrunc = cmp1; 3024 Node* add = CountedLoopNode::match_incr_with_optional_truncation(addtrunc, 3025 &trunc1, &trunc2, &ttype, T_INT); 3026 if (add && add->in(1)->is_Phi()) { 3027 Node* phi = add->in(1); 3028 for (uint i = 1; i < phi->req(); i++) { 3029 if (phi->in(i) == addtrunc) { 3030 add2 = add->in(2); 3031 break; 3032 } 3033 } 3034 } 3035 } 3036 if (add2 != nullptr) { 3037 const TypeInt* add2t = _igvn.type(add2)->is_int(); 3038 if (add2t->is_con()) { 3039 return add2t->get_con(); 3040 } 3041 } 3042 return 0; 3043 } 3044 3045 3046 //---------------------- stay_in_loop ------------------------------------- 3047 // Return the (unique) control output node that's in the loop (if it exists.) 3048 Node* PhaseIdealLoop::stay_in_loop( Node* n, IdealLoopTree *loop) { 3049 Node* unique = nullptr; 3050 if (!n) return nullptr; 3051 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) { 3052 Node* use = n->fast_out(i); 3053 if (!has_ctrl(use) && loop->is_member(get_loop(use))) { 3054 if (unique != nullptr) { 3055 return nullptr; 3056 } 3057 unique = use; 3058 } 3059 } 3060 return unique; 3061 } 3062 3063 //------------------------------ register_node ------------------------------------- 3064 // Utility to register node "n" with PhaseIdealLoop 3065 void PhaseIdealLoop::register_node(Node* n, IdealLoopTree* loop, Node* pred, uint ddepth) { 3066 _igvn.register_new_node_with_optimizer(n); 3067 loop->_body.push(n); 3068 if (n->is_CFG()) { 3069 set_loop(n, loop); 3070 set_idom(n, pred, ddepth); 3071 } else { 3072 set_ctrl(n, pred); 3073 } 3074 } 3075 3076 //------------------------------ proj_clone ------------------------------------- 3077 // Utility to create an if-projection 3078 ProjNode* PhaseIdealLoop::proj_clone(ProjNode* p, IfNode* iff) { 3079 ProjNode* c = p->clone()->as_Proj(); 3080 c->set_req(0, iff); 3081 return c; 3082 } 3083 3084 //------------------------------ short_circuit_if ------------------------------------- 3085 // Force the iff control output to be the live_proj 3086 Node* PhaseIdealLoop::short_circuit_if(IfNode* iff, ProjNode* live_proj) { 3087 guarantee(live_proj != nullptr, "null projection"); 3088 int proj_con = live_proj->_con; 3089 assert(proj_con == 0 || proj_con == 1, "false or true projection"); 3090 Node* con = intcon(proj_con); 3091 if (iff) { 3092 iff->set_req(1, con); 3093 } 3094 return con; 3095 } 3096 3097 //------------------------------ insert_if_before_proj ------------------------------------- 3098 // Insert a new if before an if projection (* - new node) 3099 // 3100 // before 3101 // if(test) 3102 // / \ 3103 // v v 3104 // other-proj proj (arg) 3105 // 3106 // after 3107 // if(test) 3108 // / \ 3109 // / v 3110 // | * proj-clone 3111 // v | 3112 // other-proj v 3113 // * new_if(relop(cmp[IU](left,right))) 3114 // / \ 3115 // v v 3116 // * new-proj proj 3117 // (returned) 3118 // 3119 ProjNode* PhaseIdealLoop::insert_if_before_proj(Node* left, bool Signed, BoolTest::mask relop, Node* right, ProjNode* proj) { 3120 IfNode* iff = proj->in(0)->as_If(); 3121 IdealLoopTree *loop = get_loop(proj); 3122 ProjNode *other_proj = iff->proj_out(!proj->is_IfTrue())->as_Proj(); 3123 uint ddepth = dom_depth(proj); 3124 3125 _igvn.rehash_node_delayed(iff); 3126 _igvn.rehash_node_delayed(proj); 3127 3128 proj->set_req(0, nullptr); // temporary disconnect 3129 ProjNode* proj2 = proj_clone(proj, iff); 3130 register_node(proj2, loop, iff, ddepth); 3131 3132 Node* cmp = Signed ? (Node*) new CmpINode(left, right) : (Node*) new CmpUNode(left, right); 3133 register_node(cmp, loop, proj2, ddepth); 3134 3135 BoolNode* bol = new BoolNode(cmp, relop); 3136 register_node(bol, loop, proj2, ddepth); 3137 3138 int opcode = iff->Opcode(); 3139 assert(opcode == Op_If || opcode == Op_RangeCheck, "unexpected opcode"); 3140 IfNode* new_if = IfNode::make_with_same_profile(iff, proj2, bol); 3141 register_node(new_if, loop, proj2, ddepth); 3142 3143 proj->set_req(0, new_if); // reattach 3144 set_idom(proj, new_if, ddepth); 3145 3146 ProjNode* new_exit = proj_clone(other_proj, new_if)->as_Proj(); 3147 guarantee(new_exit != nullptr, "null exit node"); 3148 register_node(new_exit, get_loop(other_proj), new_if, ddepth); 3149 3150 return new_exit; 3151 } 3152 3153 //------------------------------ insert_region_before_proj ------------------------------------- 3154 // Insert a region before an if projection (* - new node) 3155 // 3156 // before 3157 // if(test) 3158 // / | 3159 // v | 3160 // proj v 3161 // other-proj 3162 // 3163 // after 3164 // if(test) 3165 // / | 3166 // v | 3167 // * proj-clone v 3168 // | other-proj 3169 // v 3170 // * new-region 3171 // | 3172 // v 3173 // * dum_if 3174 // / \ 3175 // v \ 3176 // * dum-proj v 3177 // proj 3178 // 3179 RegionNode* PhaseIdealLoop::insert_region_before_proj(ProjNode* proj) { 3180 IfNode* iff = proj->in(0)->as_If(); 3181 IdealLoopTree *loop = get_loop(proj); 3182 ProjNode *other_proj = iff->proj_out(!proj->is_IfTrue())->as_Proj(); 3183 uint ddepth = dom_depth(proj); 3184 3185 _igvn.rehash_node_delayed(iff); 3186 _igvn.rehash_node_delayed(proj); 3187 3188 proj->set_req(0, nullptr); // temporary disconnect 3189 ProjNode* proj2 = proj_clone(proj, iff); 3190 register_node(proj2, loop, iff, ddepth); 3191 3192 RegionNode* reg = new RegionNode(2); 3193 reg->set_req(1, proj2); 3194 register_node(reg, loop, iff, ddepth); 3195 3196 IfNode* dum_if = new IfNode(reg, short_circuit_if(nullptr, proj), iff->_prob, iff->_fcnt); 3197 register_node(dum_if, loop, reg, ddepth); 3198 3199 proj->set_req(0, dum_if); // reattach 3200 set_idom(proj, dum_if, ddepth); 3201 3202 ProjNode* dum_proj = proj_clone(other_proj, dum_if); 3203 register_node(dum_proj, loop, dum_if, ddepth); 3204 3205 return reg; 3206 } 3207 3208 // Idea 3209 // ---- 3210 // Partial Peeling tries to rotate the loop in such a way that it can later be turned into a counted loop. Counted loops 3211 // require a signed loop exit test. When calling this method, we've only found a suitable unsigned test to partial peel 3212 // with. Therefore, we try to split off a signed loop exit test from the unsigned test such that it can be used as new 3213 // loop exit while keeping the unsigned test unchanged and preserving the same behavior as if we've used the unsigned 3214 // test alone instead: 3215 // 3216 // Before Partial Peeling: 3217 // Loop: 3218 // <peeled section> 3219 // Split off signed loop exit test 3220 // <-- CUT HERE --> 3221 // Unchanged unsigned loop exit test 3222 // <rest of unpeeled section> 3223 // goto Loop 3224 // 3225 // After Partial Peeling: 3226 // <cloned peeled section> 3227 // Cloned split off signed loop exit test 3228 // Loop: 3229 // Unchanged unsigned loop exit test 3230 // <rest of unpeeled section> 3231 // <peeled section> 3232 // Split off signed loop exit test 3233 // goto Loop 3234 // 3235 // Details 3236 // ------- 3237 // Before: 3238 // if (i <u limit) Unsigned loop exit condition 3239 // / | 3240 // v v 3241 // exit-proj stay-in-loop-proj 3242 // 3243 // Split off a signed loop exit test (i.e. with CmpI) from an unsigned loop exit test (i.e. with CmpU) and insert it 3244 // before the CmpU on the stay-in-loop path and keep both tests: 3245 // 3246 // if (i <u limit) Signed loop exit test 3247 // / | 3248 // / if (i <u limit) Unsigned loop exit test 3249 // / / | 3250 // v v v 3251 // exit-region stay-in-loop-proj 3252 // 3253 // Implementation 3254 // -------------- 3255 // We need to make sure that the new signed loop exit test is properly inserted into the graph such that the unsigned 3256 // loop exit test still dominates the same set of control nodes, the ctrl() relation from data nodes to both loop 3257 // exit tests is preserved, and their loop nesting is correct. 3258 // 3259 // To achieve that, we clone the unsigned loop exit test completely (leave it unchanged), insert the signed loop exit 3260 // test above it and kill the original unsigned loop exit test by setting it's condition to a constant 3261 // (i.e. stay-in-loop-const in graph below) such that IGVN can fold it later: 3262 // 3263 // if (stay-in-loop-const) Killed original unsigned loop exit test 3264 // / | 3265 // / v 3266 // / if (i < limit) Split off signed loop exit test 3267 // / / | 3268 // / / v 3269 // / / if (i <u limit) Cloned unsigned loop exit test 3270 // / / / | 3271 // v v v | 3272 // exit-region | 3273 // | | 3274 // dummy-if | 3275 // / | | 3276 // dead | | 3277 // v v 3278 // exit-proj stay-in-loop-proj 3279 // 3280 // Note: The dummy-if is inserted to create a region to merge the loop exits between the original to be killed unsigned 3281 // loop exit test and its exit projection while keeping the exit projection (also see insert_region_before_proj()). 3282 // 3283 // Requirements 3284 // ------------ 3285 // Note that we can only split off a signed loop exit test from the unsigned loop exit test when the behavior is exactly 3286 // the same as before with only a single unsigned test. This is only possible if certain requirements are met. 3287 // Otherwise, we need to bail out (see comments in the code below). 3288 IfNode* PhaseIdealLoop::insert_cmpi_loop_exit(IfNode* if_cmpu, IdealLoopTree* loop) { 3289 const bool Signed = true; 3290 const bool Unsigned = false; 3291 3292 BoolNode* bol = if_cmpu->in(1)->as_Bool(); 3293 if (bol->_test._test != BoolTest::lt) { 3294 return nullptr; 3295 } 3296 CmpNode* cmpu = bol->in(1)->as_Cmp(); 3297 assert(cmpu->Opcode() == Op_CmpU, "must be unsigned comparison"); 3298 3299 int stride = stride_of_possible_iv(if_cmpu); 3300 if (stride == 0) { 3301 return nullptr; 3302 } 3303 3304 Node* lp_proj = stay_in_loop(if_cmpu, loop); 3305 guarantee(lp_proj != nullptr, "null loop node"); 3306 3307 ProjNode* lp_continue = lp_proj->as_Proj(); 3308 ProjNode* lp_exit = if_cmpu->proj_out(!lp_continue->is_IfTrue())->as_Proj(); 3309 if (!lp_exit->is_IfFalse()) { 3310 // The loop exit condition is (i <u limit) ==> (i >= 0 && i < limit). 3311 // We therefore can't add a single exit condition. 3312 return nullptr; 3313 } 3314 // The unsigned loop exit condition is 3315 // !(i <u limit) 3316 // = i >=u limit 3317 // 3318 // First, we note that for any x for which 3319 // 0 <= x <= INT_MAX 3320 // we can convert x to an unsigned int and still get the same guarantee: 3321 // 0 <= (uint) x <= INT_MAX = (uint) INT_MAX 3322 // 0 <=u (uint) x <=u INT_MAX = (uint) INT_MAX (LEMMA) 3323 // 3324 // With that in mind, if 3325 // limit >= 0 (COND) 3326 // then the unsigned loop exit condition 3327 // i >=u limit (ULE) 3328 // is equivalent to 3329 // i < 0 || i >= limit (SLE-full) 3330 // because either i is negative and therefore always greater than MAX_INT when converting to unsigned 3331 // (uint) i >=u MAX_INT >= limit >= 0 3332 // or otherwise 3333 // i >= limit >= 0 3334 // holds due to (LEMMA). 3335 // 3336 // For completeness, a counterexample with limit < 0: 3337 // Assume i = -3 and limit = -2: 3338 // i < 0 3339 // -2 < 0 3340 // is true and thus also "i < 0 || i >= limit". But 3341 // i >=u limit 3342 // -3 >=u -2 3343 // is false. 3344 Node* limit = cmpu->in(2); 3345 const TypeInt* type_limit = _igvn.type(limit)->is_int(); 3346 if (type_limit->_lo < 0) { 3347 return nullptr; 3348 } 3349 3350 // We prove below that we can extract a single signed loop exit condition from (SLE-full), depending on the stride: 3351 // stride < 0: 3352 // i < 0 (SLE = SLE-negative) 3353 // stride > 0: 3354 // i >= limit (SLE = SLE-positive) 3355 // such that we have the following graph before Partial Peeling with stride > 0 (similar for stride < 0): 3356 // 3357 // Loop: 3358 // <peeled section> 3359 // i >= limit (SLE-positive) 3360 // <-- CUT HERE --> 3361 // i >=u limit (ULE) 3362 // <rest of unpeeled section> 3363 // goto Loop 3364 // 3365 // We exit the loop if: 3366 // (SLE) is true OR (ULE) is true 3367 // However, if (SLE) is true then (ULE) also needs to be true to ensure the exact same behavior. Otherwise, we wrongly 3368 // exit a loop that should not have been exited if we did not apply Partial Peeling. More formally, we need to ensure: 3369 // (SLE) IMPLIES (ULE) 3370 // This indeed holds when (COND) is given: 3371 // - stride > 0: 3372 // i >= limit // (SLE = SLE-positive) 3373 // i >= limit >= 0 // (COND) 3374 // i >=u limit >= 0 // (LEMMA) 3375 // which is the unsigned loop exit condition (ULE). 3376 // - stride < 0: 3377 // i < 0 // (SLE = SLE-negative) 3378 // (uint) i >u MAX_INT // (NEG) all negative values are greater than MAX_INT when converted to unsigned 3379 // MAX_INT >= limit >= 0 // (COND) 3380 // MAX_INT >=u limit >= 0 // (LEMMA) 3381 // and thus from (NEG) and (LEMMA): 3382 // i >=u limit 3383 // which is the unsigned loop exit condition (ULE). 3384 // 3385 // 3386 // After Partial Peeling, we have the following structure for stride > 0 (similar for stride < 0): 3387 // <cloned peeled section> 3388 // i >= limit (SLE-positive) 3389 // Loop: 3390 // i >=u limit (ULE) 3391 // <rest of unpeeled section> 3392 // <peeled section> 3393 // i >= limit (SLE-positive) 3394 // goto Loop 3395 Node* rhs_cmpi; 3396 if (stride > 0) { 3397 rhs_cmpi = limit; // For i >= limit 3398 } else { 3399 rhs_cmpi = makecon(TypeInt::ZERO); // For i < 0 3400 } 3401 // Create a new region on the exit path 3402 RegionNode* reg = insert_region_before_proj(lp_exit); 3403 guarantee(reg != nullptr, "null region node"); 3404 3405 // Clone the if-cmpu-true-false using a signed compare 3406 BoolTest::mask rel_i = stride > 0 ? bol->_test._test : BoolTest::ge; 3407 ProjNode* cmpi_exit = insert_if_before_proj(cmpu->in(1), Signed, rel_i, rhs_cmpi, lp_continue); 3408 reg->add_req(cmpi_exit); 3409 3410 // Clone the if-cmpu-true-false 3411 BoolTest::mask rel_u = bol->_test._test; 3412 ProjNode* cmpu_exit = insert_if_before_proj(cmpu->in(1), Unsigned, rel_u, cmpu->in(2), lp_continue); 3413 reg->add_req(cmpu_exit); 3414 3415 // Force original if to stay in loop. 3416 short_circuit_if(if_cmpu, lp_continue); 3417 3418 return cmpi_exit->in(0)->as_If(); 3419 } 3420 3421 //------------------------------ remove_cmpi_loop_exit ------------------------------------- 3422 // Remove a previously inserted signed compare loop exit. 3423 void PhaseIdealLoop::remove_cmpi_loop_exit(IfNode* if_cmp, IdealLoopTree *loop) { 3424 Node* lp_proj = stay_in_loop(if_cmp, loop); 3425 assert(if_cmp->in(1)->in(1)->Opcode() == Op_CmpI && 3426 stay_in_loop(lp_proj, loop)->is_If() && 3427 stay_in_loop(lp_proj, loop)->in(1)->in(1)->Opcode() == Op_CmpU, "inserted cmpi before cmpu"); 3428 Node* con = makecon(lp_proj->is_IfTrue() ? TypeInt::ONE : TypeInt::ZERO); 3429 if_cmp->set_req(1, con); 3430 } 3431 3432 //------------------------------ scheduled_nodelist ------------------------------------- 3433 // Create a post order schedule of nodes that are in the 3434 // "member" set. The list is returned in "sched". 3435 // The first node in "sched" is the loop head, followed by 3436 // nodes which have no inputs in the "member" set, and then 3437 // followed by the nodes that have an immediate input dependence 3438 // on a node in "sched". 3439 void PhaseIdealLoop::scheduled_nodelist( IdealLoopTree *loop, VectorSet& member, Node_List &sched ) { 3440 3441 assert(member.test(loop->_head->_idx), "loop head must be in member set"); 3442 VectorSet visited; 3443 Node_Stack nstack(loop->_body.size()); 3444 3445 Node* n = loop->_head; // top of stack is cached in "n" 3446 uint idx = 0; 3447 visited.set(n->_idx); 3448 3449 // Initially push all with no inputs from within member set 3450 for(uint i = 0; i < loop->_body.size(); i++ ) { 3451 Node *elt = loop->_body.at(i); 3452 if (member.test(elt->_idx)) { 3453 bool found = false; 3454 for (uint j = 0; j < elt->req(); j++) { 3455 Node* def = elt->in(j); 3456 if (def && member.test(def->_idx) && def != elt) { 3457 found = true; 3458 break; 3459 } 3460 } 3461 if (!found && elt != loop->_head) { 3462 nstack.push(n, idx); 3463 n = elt; 3464 assert(!visited.test(n->_idx), "not seen yet"); 3465 visited.set(n->_idx); 3466 } 3467 } 3468 } 3469 3470 // traverse out's that are in the member set 3471 while (true) { 3472 if (idx < n->outcnt()) { 3473 Node* use = n->raw_out(idx); 3474 idx++; 3475 if (!visited.test_set(use->_idx)) { 3476 if (member.test(use->_idx)) { 3477 nstack.push(n, idx); 3478 n = use; 3479 idx = 0; 3480 } 3481 } 3482 } else { 3483 // All outputs processed 3484 sched.push(n); 3485 if (nstack.is_empty()) break; 3486 n = nstack.node(); 3487 idx = nstack.index(); 3488 nstack.pop(); 3489 } 3490 } 3491 } 3492 3493 3494 //------------------------------ has_use_in_set ------------------------------------- 3495 // Has a use in the vector set 3496 bool PhaseIdealLoop::has_use_in_set( Node* n, VectorSet& vset ) { 3497 for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++) { 3498 Node* use = n->fast_out(j); 3499 if (vset.test(use->_idx)) { 3500 return true; 3501 } 3502 } 3503 return false; 3504 } 3505 3506 3507 //------------------------------ has_use_internal_to_set ------------------------------------- 3508 // Has use internal to the vector set (ie. not in a phi at the loop head) 3509 bool PhaseIdealLoop::has_use_internal_to_set( Node* n, VectorSet& vset, IdealLoopTree *loop ) { 3510 Node* head = loop->_head; 3511 for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++) { 3512 Node* use = n->fast_out(j); 3513 if (vset.test(use->_idx) && !(use->is_Phi() && use->in(0) == head)) { 3514 return true; 3515 } 3516 } 3517 return false; 3518 } 3519 3520 3521 //------------------------------ clone_for_use_outside_loop ------------------------------------- 3522 // clone "n" for uses that are outside of loop 3523 int PhaseIdealLoop::clone_for_use_outside_loop( IdealLoopTree *loop, Node* n, Node_List& worklist ) { 3524 int cloned = 0; 3525 assert(worklist.size() == 0, "should be empty"); 3526 for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++) { 3527 Node* use = n->fast_out(j); 3528 if( !loop->is_member(get_loop(has_ctrl(use) ? get_ctrl(use) : use)) ) { 3529 worklist.push(use); 3530 } 3531 } 3532 3533 if (C->check_node_count(worklist.size() + NodeLimitFudgeFactor, 3534 "Too many clones required in clone_for_use_outside_loop in partial peeling")) { 3535 return -1; 3536 } 3537 3538 while( worklist.size() ) { 3539 Node *use = worklist.pop(); 3540 if (!has_node(use) || use->in(0) == C->top()) continue; 3541 uint j; 3542 for (j = 0; j < use->req(); j++) { 3543 if (use->in(j) == n) break; 3544 } 3545 assert(j < use->req(), "must be there"); 3546 3547 // clone "n" and insert it between the inputs of "n" and the use outside the loop 3548 Node* n_clone = n->clone(); 3549 _igvn.replace_input_of(use, j, n_clone); 3550 cloned++; 3551 Node* use_c; 3552 if (!use->is_Phi()) { 3553 use_c = has_ctrl(use) ? get_ctrl(use) : use->in(0); 3554 } else { 3555 // Use in a phi is considered a use in the associated predecessor block 3556 use_c = use->in(0)->in(j); 3557 } 3558 set_ctrl(n_clone, use_c); 3559 assert(!loop->is_member(get_loop(use_c)), "should be outside loop"); 3560 get_loop(use_c)->_body.push(n_clone); 3561 _igvn.register_new_node_with_optimizer(n_clone); 3562 #ifndef PRODUCT 3563 if (TracePartialPeeling) { 3564 tty->print_cr("loop exit cloning old: %d new: %d newbb: %d", n->_idx, n_clone->_idx, get_ctrl(n_clone)->_idx); 3565 } 3566 #endif 3567 } 3568 return cloned; 3569 } 3570 3571 3572 //------------------------------ clone_for_special_use_inside_loop ------------------------------------- 3573 // clone "n" for special uses that are in the not_peeled region. 3574 // If these def-uses occur in separate blocks, the code generator 3575 // marks the method as not compilable. For example, if a "BoolNode" 3576 // is in a different basic block than the "IfNode" that uses it, then 3577 // the compilation is aborted in the code generator. 3578 void PhaseIdealLoop::clone_for_special_use_inside_loop( IdealLoopTree *loop, Node* n, 3579 VectorSet& not_peel, Node_List& sink_list, Node_List& worklist ) { 3580 if (n->is_Phi() || n->is_Load()) { 3581 return; 3582 } 3583 assert(worklist.size() == 0, "should be empty"); 3584 for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++) { 3585 Node* use = n->fast_out(j); 3586 if ( not_peel.test(use->_idx) && 3587 (use->is_If() || use->is_CMove() || use->is_Bool() || use->is_OpaqueInitializedAssertionPredicate()) && 3588 use->in(1) == n) { 3589 worklist.push(use); 3590 } 3591 } 3592 if (worklist.size() > 0) { 3593 // clone "n" and insert it between inputs of "n" and the use 3594 Node* n_clone = n->clone(); 3595 loop->_body.push(n_clone); 3596 _igvn.register_new_node_with_optimizer(n_clone); 3597 set_ctrl(n_clone, get_ctrl(n)); 3598 sink_list.push(n_clone); 3599 not_peel.set(n_clone->_idx); 3600 #ifndef PRODUCT 3601 if (TracePartialPeeling) { 3602 tty->print_cr("special not_peeled cloning old: %d new: %d", n->_idx, n_clone->_idx); 3603 } 3604 #endif 3605 while( worklist.size() ) { 3606 Node *use = worklist.pop(); 3607 _igvn.rehash_node_delayed(use); 3608 for (uint j = 1; j < use->req(); j++) { 3609 if (use->in(j) == n) { 3610 use->set_req(j, n_clone); 3611 } 3612 } 3613 } 3614 } 3615 } 3616 3617 3618 //------------------------------ insert_phi_for_loop ------------------------------------- 3619 // Insert phi(lp_entry_val, back_edge_val) at use->in(idx) for loop lp if phi does not already exist 3620 void PhaseIdealLoop::insert_phi_for_loop( Node* use, uint idx, Node* lp_entry_val, Node* back_edge_val, LoopNode* lp ) { 3621 Node *phi = PhiNode::make(lp, back_edge_val); 3622 phi->set_req(LoopNode::EntryControl, lp_entry_val); 3623 // Use existing phi if it already exists 3624 Node *hit = _igvn.hash_find_insert(phi); 3625 if( hit == nullptr ) { 3626 _igvn.register_new_node_with_optimizer(phi); 3627 set_ctrl(phi, lp); 3628 } else { 3629 // Remove the new phi from the graph and use the hit 3630 _igvn.remove_dead_node(phi); 3631 phi = hit; 3632 } 3633 _igvn.replace_input_of(use, idx, phi); 3634 } 3635 3636 #ifdef ASSERT 3637 //------------------------------ is_valid_loop_partition ------------------------------------- 3638 // Validate the loop partition sets: peel and not_peel 3639 bool PhaseIdealLoop::is_valid_loop_partition( IdealLoopTree *loop, VectorSet& peel, Node_List& peel_list, 3640 VectorSet& not_peel ) { 3641 uint i; 3642 // Check that peel_list entries are in the peel set 3643 for (i = 0; i < peel_list.size(); i++) { 3644 if (!peel.test(peel_list.at(i)->_idx)) { 3645 return false; 3646 } 3647 } 3648 // Check at loop members are in one of peel set or not_peel set 3649 for (i = 0; i < loop->_body.size(); i++ ) { 3650 Node *def = loop->_body.at(i); 3651 uint di = def->_idx; 3652 // Check that peel set elements are in peel_list 3653 if (peel.test(di)) { 3654 if (not_peel.test(di)) { 3655 return false; 3656 } 3657 // Must be in peel_list also 3658 bool found = false; 3659 for (uint j = 0; j < peel_list.size(); j++) { 3660 if (peel_list.at(j)->_idx == di) { 3661 found = true; 3662 break; 3663 } 3664 } 3665 if (!found) { 3666 return false; 3667 } 3668 } else if (not_peel.test(di)) { 3669 if (peel.test(di)) { 3670 return false; 3671 } 3672 } else { 3673 return false; 3674 } 3675 } 3676 return true; 3677 } 3678 3679 //------------------------------ is_valid_clone_loop_exit_use ------------------------------------- 3680 // Ensure a use outside of loop is of the right form 3681 bool PhaseIdealLoop::is_valid_clone_loop_exit_use( IdealLoopTree *loop, Node* use, uint exit_idx) { 3682 Node *use_c = has_ctrl(use) ? get_ctrl(use) : use; 3683 return (use->is_Phi() && 3684 use_c->is_Region() && use_c->req() == 3 && 3685 (use_c->in(exit_idx)->Opcode() == Op_IfTrue || 3686 use_c->in(exit_idx)->Opcode() == Op_IfFalse || 3687 use_c->in(exit_idx)->Opcode() == Op_JumpProj) && 3688 loop->is_member( get_loop( use_c->in(exit_idx)->in(0) ) ) ); 3689 } 3690 3691 //------------------------------ is_valid_clone_loop_form ------------------------------------- 3692 // Ensure that all uses outside of loop are of the right form 3693 bool PhaseIdealLoop::is_valid_clone_loop_form( IdealLoopTree *loop, Node_List& peel_list, 3694 uint orig_exit_idx, uint clone_exit_idx) { 3695 uint len = peel_list.size(); 3696 for (uint i = 0; i < len; i++) { 3697 Node *def = peel_list.at(i); 3698 3699 for (DUIterator_Fast jmax, j = def->fast_outs(jmax); j < jmax; j++) { 3700 Node *use = def->fast_out(j); 3701 Node *use_c = has_ctrl(use) ? get_ctrl(use) : use; 3702 if (!loop->is_member(get_loop(use_c))) { 3703 // use is not in the loop, check for correct structure 3704 if (use->in(0) == def) { 3705 // Okay 3706 } else if (!is_valid_clone_loop_exit_use(loop, use, orig_exit_idx)) { 3707 return false; 3708 } 3709 } 3710 } 3711 } 3712 return true; 3713 } 3714 #endif 3715 3716 //------------------------------ partial_peel ------------------------------------- 3717 // Partially peel (aka loop rotation) the top portion of a loop (called 3718 // the peel section below) by cloning it and placing one copy just before 3719 // the new loop head and the other copy at the bottom of the new loop. 3720 // 3721 // before after where it came from 3722 // 3723 // stmt1 stmt1 3724 // loop: stmt2 clone 3725 // stmt2 if condA goto exitA clone 3726 // if condA goto exitA new_loop: new 3727 // stmt3 stmt3 clone 3728 // if !condB goto loop if condB goto exitB clone 3729 // exitB: stmt2 orig 3730 // stmt4 if !condA goto new_loop orig 3731 // exitA: goto exitA 3732 // exitB: 3733 // stmt4 3734 // exitA: 3735 // 3736 // Step 1: find the cut point: an exit test on probable 3737 // induction variable. 3738 // Step 2: schedule (with cloning) operations in the peel 3739 // section that can be executed after the cut into 3740 // the section that is not peeled. This may need 3741 // to clone operations into exit blocks. For 3742 // instance, a reference to A[i] in the not-peel 3743 // section and a reference to B[i] in an exit block 3744 // may cause a left-shift of i by 2 to be placed 3745 // in the peel block. This step will clone the left 3746 // shift into the exit block and sink the left shift 3747 // from the peel to the not-peel section. 3748 // Step 3: clone the loop, retarget the control, and insert 3749 // phis for values that are live across the new loop 3750 // head. This is very dependent on the graph structure 3751 // from clone_loop. It creates region nodes for 3752 // exit control and associated phi nodes for values 3753 // flow out of the loop through that exit. The region 3754 // node is dominated by the clone's control projection. 3755 // So the clone's peel section is placed before the 3756 // new loop head, and the clone's not-peel section is 3757 // forms the top part of the new loop. The original 3758 // peel section forms the tail of the new loop. 3759 // Step 4: update the dominator tree and recompute the 3760 // dominator depth. 3761 // 3762 // orig 3763 // 3764 // stmt1 3765 // | 3766 // v 3767 // predicates 3768 // | 3769 // v 3770 // loop<----+ 3771 // | | 3772 // stmt2 | 3773 // | | 3774 // v | 3775 // ifA | 3776 // / | | 3777 // v v | 3778 // false true ^ <-- last_peel 3779 // / | | 3780 // / ===|==cut | 3781 // / stmt3 | <-- first_not_peel 3782 // / | | 3783 // | v | 3784 // v ifB | 3785 // exitA: / \ | 3786 // / \ | 3787 // v v | 3788 // false true | 3789 // / \ | 3790 // / ----+ 3791 // | 3792 // v 3793 // exitB: 3794 // stmt4 3795 // 3796 // 3797 // after clone loop 3798 // 3799 // stmt1 3800 // | 3801 // v 3802 // predicates 3803 // / \ 3804 // clone / \ orig 3805 // / \ 3806 // / \ 3807 // v v 3808 // +---->loop loop<----+ 3809 // | | | | 3810 // | stmt2 stmt2 | 3811 // | | | | 3812 // | v v | 3813 // | ifA ifA | 3814 // | | \ / | | 3815 // | v v v v | 3816 // ^ true false false true ^ <-- last_peel 3817 // | | ^ \ / | | 3818 // | cut==|== \ \ / ===|==cut | 3819 // | stmt3 \ \ / stmt3 | <-- first_not_peel 3820 // | | dom | | | | 3821 // | v \ 1v v2 v | 3822 // | ifB regionA ifB | 3823 // | / \ | / \ | 3824 // | / \ v / \ | 3825 // | v v exitA: v v | 3826 // | true false false true | 3827 // | / ^ \ / \ | 3828 // +---- \ \ / ----+ 3829 // dom \ / 3830 // \ 1v v2 3831 // regionB 3832 // | 3833 // v 3834 // exitB: 3835 // stmt4 3836 // 3837 // 3838 // after partial peel 3839 // 3840 // stmt1 3841 // | 3842 // v 3843 // predicates 3844 // / 3845 // clone / orig 3846 // / TOP 3847 // / \ 3848 // v v 3849 // TOP->loop loop----+ 3850 // | | | 3851 // stmt2 stmt2 | 3852 // | | | 3853 // v v | 3854 // ifA ifA | 3855 // | \ / | | 3856 // v v v v | 3857 // true false false true | <-- last_peel 3858 // | ^ \ / +------|---+ 3859 // +->newloop \ \ / === ==cut | | 3860 // | stmt3 \ \ / TOP | | 3861 // | | dom | | stmt3 | | <-- first_not_peel 3862 // | v \ 1v v2 v | | 3863 // | ifB regionA ifB ^ v 3864 // | / \ | / \ | | 3865 // | / \ v / \ | | 3866 // | v v exitA: v v | | 3867 // | true false false true | | 3868 // | / ^ \ / \ | | 3869 // | | \ \ / v | | 3870 // | | dom \ / TOP | | 3871 // | | \ 1v v2 | | 3872 // ^ v regionB | | 3873 // | | | | | 3874 // | | v ^ v 3875 // | | exitB: | | 3876 // | | stmt4 | | 3877 // | +------------>-----------------+ | 3878 // | | 3879 // +-----------------<---------------------+ 3880 // 3881 // 3882 // final graph 3883 // 3884 // stmt1 3885 // | 3886 // v 3887 // predicates 3888 // | 3889 // v 3890 // stmt2 clone 3891 // | 3892 // v 3893 // ........> ifA clone 3894 // : / | 3895 // dom / | 3896 // : v v 3897 // : false true 3898 // : | | 3899 // : | v 3900 // : | newloop<-----+ 3901 // : | | | 3902 // : | stmt3 clone | 3903 // : | | | 3904 // : | v | 3905 // : | ifB | 3906 // : | / \ | 3907 // : | v v | 3908 // : | false true | 3909 // : | | | | 3910 // : | v stmt2 | 3911 // : | exitB: | | 3912 // : | stmt4 v | 3913 // : | ifA orig | 3914 // : | / \ | 3915 // : | / \ | 3916 // : | v v | 3917 // : | false true | 3918 // : | / \ | 3919 // : v v -----+ 3920 // RegionA 3921 // | 3922 // v 3923 // exitA 3924 // 3925 bool PhaseIdealLoop::partial_peel( IdealLoopTree *loop, Node_List &old_new ) { 3926 3927 assert(!loop->_head->is_CountedLoop(), "Non-counted loop only"); 3928 if (!loop->_head->is_Loop()) { 3929 return false; 3930 } 3931 LoopNode *head = loop->_head->as_Loop(); 3932 3933 if (head->is_partial_peel_loop() || head->partial_peel_has_failed()) { 3934 return false; 3935 } 3936 3937 // Check for complex exit control 3938 for (uint ii = 0; ii < loop->_body.size(); ii++) { 3939 Node *n = loop->_body.at(ii); 3940 int opc = n->Opcode(); 3941 if (n->is_Call() || 3942 opc == Op_Catch || 3943 opc == Op_CatchProj || 3944 opc == Op_Jump || 3945 opc == Op_JumpProj) { 3946 #ifndef PRODUCT 3947 if (TracePartialPeeling) { 3948 tty->print_cr("\nExit control too complex: lp: %d", head->_idx); 3949 } 3950 #endif 3951 return false; 3952 } 3953 } 3954 3955 int dd = dom_depth(head); 3956 3957 // Step 1: find cut point 3958 3959 // Walk up dominators to loop head looking for first loop exit 3960 // which is executed on every path thru loop. 3961 IfNode *peel_if = nullptr; 3962 IfNode *peel_if_cmpu = nullptr; 3963 3964 Node *iff = loop->tail(); 3965 while (iff != head) { 3966 if (iff->is_If()) { 3967 Node *ctrl = get_ctrl(iff->in(1)); 3968 if (ctrl->is_top()) return false; // Dead test on live IF. 3969 // If loop-varying exit-test, check for induction variable 3970 if (loop->is_member(get_loop(ctrl)) && 3971 loop->is_loop_exit(iff) && 3972 is_possible_iv_test(iff)) { 3973 Node* cmp = iff->in(1)->in(1); 3974 if (cmp->Opcode() == Op_CmpI) { 3975 peel_if = iff->as_If(); 3976 } else { 3977 assert(cmp->Opcode() == Op_CmpU, "must be CmpI or CmpU"); 3978 peel_if_cmpu = iff->as_If(); 3979 } 3980 } 3981 } 3982 iff = idom(iff); 3983 } 3984 3985 // Prefer signed compare over unsigned compare. 3986 IfNode* new_peel_if = nullptr; 3987 if (peel_if == nullptr) { 3988 if (!PartialPeelAtUnsignedTests || peel_if_cmpu == nullptr) { 3989 return false; // No peel point found 3990 } 3991 new_peel_if = insert_cmpi_loop_exit(peel_if_cmpu, loop); 3992 if (new_peel_if == nullptr) { 3993 return false; // No peel point found 3994 } 3995 peel_if = new_peel_if; 3996 } 3997 Node* last_peel = stay_in_loop(peel_if, loop); 3998 Node* first_not_peeled = stay_in_loop(last_peel, loop); 3999 if (first_not_peeled == nullptr || first_not_peeled == head) { 4000 return false; 4001 } 4002 4003 #ifndef PRODUCT 4004 if (TraceLoopOpts) { 4005 tty->print("PartialPeel "); 4006 loop->dump_head(); 4007 } 4008 4009 if (TracePartialPeeling) { 4010 tty->print_cr("before partial peel one iteration"); 4011 Node_List wl; 4012 Node* t = head->in(2); 4013 while (true) { 4014 wl.push(t); 4015 if (t == head) break; 4016 t = idom(t); 4017 } 4018 while (wl.size() > 0) { 4019 Node* tt = wl.pop(); 4020 tt->dump(); 4021 if (tt == last_peel) tty->print_cr("-- cut --"); 4022 } 4023 } 4024 #endif 4025 4026 C->print_method(PHASE_BEFORE_PARTIAL_PEELING, 4, head); 4027 4028 VectorSet peel; 4029 VectorSet not_peel; 4030 Node_List peel_list; 4031 Node_List worklist; 4032 Node_List sink_list; 4033 4034 uint estimate = loop->est_loop_clone_sz(1); 4035 if (exceeding_node_budget(estimate)) { 4036 return false; 4037 } 4038 4039 // Set of cfg nodes to peel are those that are executable from 4040 // the head through last_peel. 4041 assert(worklist.size() == 0, "should be empty"); 4042 worklist.push(head); 4043 peel.set(head->_idx); 4044 while (worklist.size() > 0) { 4045 Node *n = worklist.pop(); 4046 if (n != last_peel) { 4047 for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++) { 4048 Node* use = n->fast_out(j); 4049 if (use->is_CFG() && 4050 loop->is_member(get_loop(use)) && 4051 !peel.test_set(use->_idx)) { 4052 worklist.push(use); 4053 } 4054 } 4055 } 4056 } 4057 4058 // Set of non-cfg nodes to peel are those that are control 4059 // dependent on the cfg nodes. 4060 for (uint i = 0; i < loop->_body.size(); i++) { 4061 Node *n = loop->_body.at(i); 4062 Node *n_c = has_ctrl(n) ? get_ctrl(n) : n; 4063 if (peel.test(n_c->_idx)) { 4064 peel.set(n->_idx); 4065 } else { 4066 not_peel.set(n->_idx); 4067 } 4068 } 4069 4070 // Step 2: move operations from the peeled section down into the 4071 // not-peeled section 4072 4073 // Get a post order schedule of nodes in the peel region 4074 // Result in right-most operand. 4075 scheduled_nodelist(loop, peel, peel_list); 4076 4077 assert(is_valid_loop_partition(loop, peel, peel_list, not_peel), "bad partition"); 4078 4079 // For future check for too many new phis 4080 uint old_phi_cnt = 0; 4081 for (DUIterator_Fast jmax, j = head->fast_outs(jmax); j < jmax; j++) { 4082 Node* use = head->fast_out(j); 4083 if (use->is_Phi()) old_phi_cnt++; 4084 } 4085 4086 #ifndef PRODUCT 4087 if (TracePartialPeeling) { 4088 tty->print_cr("\npeeled list"); 4089 } 4090 #endif 4091 4092 // Evacuate nodes in peel region into the not_peeled region if possible 4093 bool too_many_clones = false; 4094 uint new_phi_cnt = 0; 4095 uint cloned_for_outside_use = 0; 4096 for (uint i = 0; i < peel_list.size();) { 4097 Node* n = peel_list.at(i); 4098 #ifndef PRODUCT 4099 if (TracePartialPeeling) n->dump(); 4100 #endif 4101 bool incr = true; 4102 if (!n->is_CFG()) { 4103 if (has_use_in_set(n, not_peel)) { 4104 // If not used internal to the peeled region, 4105 // move "n" from peeled to not_peeled region. 4106 if (!has_use_internal_to_set(n, peel, loop)) { 4107 // if not pinned and not a load (which maybe anti-dependent on a store) 4108 // and not a CMove (Matcher expects only bool->cmove). 4109 if (n->in(0) == nullptr && !n->is_Load() && !n->is_CMove()) { 4110 int new_clones = clone_for_use_outside_loop(loop, n, worklist); 4111 if (C->failing()) return false; 4112 if (new_clones == -1) { 4113 too_many_clones = true; 4114 break; 4115 } 4116 cloned_for_outside_use += new_clones; 4117 sink_list.push(n); 4118 peel.remove(n->_idx); 4119 not_peel.set(n->_idx); 4120 peel_list.remove(i); 4121 incr = false; 4122 #ifndef PRODUCT 4123 if (TracePartialPeeling) { 4124 tty->print_cr("sink to not_peeled region: %d newbb: %d", 4125 n->_idx, get_ctrl(n)->_idx); 4126 } 4127 #endif 4128 } 4129 } else { 4130 // Otherwise check for special def-use cases that span 4131 // the peel/not_peel boundary such as bool->if 4132 clone_for_special_use_inside_loop(loop, n, not_peel, sink_list, worklist); 4133 new_phi_cnt++; 4134 } 4135 } 4136 } 4137 if (incr) i++; 4138 } 4139 4140 estimate += cloned_for_outside_use + new_phi_cnt; 4141 bool exceed_node_budget = !may_require_nodes(estimate); 4142 bool exceed_phi_limit = new_phi_cnt > old_phi_cnt + PartialPeelNewPhiDelta; 4143 4144 if (too_many_clones || exceed_node_budget || exceed_phi_limit) { 4145 #ifndef PRODUCT 4146 if (TracePartialPeeling && exceed_phi_limit) { 4147 tty->print_cr("\nToo many new phis: %d old %d new cmpi: %c", 4148 new_phi_cnt, old_phi_cnt, new_peel_if != nullptr?'T':'F'); 4149 } 4150 #endif 4151 if (new_peel_if != nullptr) { 4152 remove_cmpi_loop_exit(new_peel_if, loop); 4153 } 4154 // Inhibit more partial peeling on this loop 4155 assert(!head->is_partial_peel_loop(), "not partial peeled"); 4156 head->mark_partial_peel_failed(); 4157 if (cloned_for_outside_use > 0) { 4158 // Terminate this round of loop opts because 4159 // the graph outside this loop was changed. 4160 C->set_major_progress(); 4161 return true; 4162 } 4163 return false; 4164 } 4165 4166 // Step 3: clone loop, retarget control, and insert new phis 4167 4168 // Create new loop head for new phis and to hang 4169 // the nodes being moved (sinked) from the peel region. 4170 LoopNode* new_head = new LoopNode(last_peel, last_peel); 4171 new_head->set_unswitch_count(head->unswitch_count()); // Preserve 4172 _igvn.register_new_node_with_optimizer(new_head); 4173 assert(first_not_peeled->in(0) == last_peel, "last_peel <- first_not_peeled"); 4174 _igvn.replace_input_of(first_not_peeled, 0, new_head); 4175 set_loop(new_head, loop); 4176 loop->_body.push(new_head); 4177 not_peel.set(new_head->_idx); 4178 set_idom(new_head, last_peel, dom_depth(first_not_peeled)); 4179 set_idom(first_not_peeled, new_head, dom_depth(first_not_peeled)); 4180 4181 while (sink_list.size() > 0) { 4182 Node* n = sink_list.pop(); 4183 set_ctrl(n, new_head); 4184 } 4185 4186 assert(is_valid_loop_partition(loop, peel, peel_list, not_peel), "bad partition"); 4187 4188 clone_loop(loop, old_new, dd, IgnoreStripMined); 4189 4190 const uint clone_exit_idx = 1; 4191 const uint orig_exit_idx = 2; 4192 assert(is_valid_clone_loop_form(loop, peel_list, orig_exit_idx, clone_exit_idx), "bad clone loop"); 4193 4194 Node* head_clone = old_new[head->_idx]; 4195 LoopNode* new_head_clone = old_new[new_head->_idx]->as_Loop(); 4196 Node* orig_tail_clone = head_clone->in(2); 4197 4198 // Add phi if "def" node is in peel set and "use" is not 4199 4200 for (uint i = 0; i < peel_list.size(); i++) { 4201 Node *def = peel_list.at(i); 4202 if (!def->is_CFG()) { 4203 for (DUIterator_Fast jmax, j = def->fast_outs(jmax); j < jmax; j++) { 4204 Node *use = def->fast_out(j); 4205 if (has_node(use) && use->in(0) != C->top() && 4206 (!peel.test(use->_idx) || 4207 (use->is_Phi() && use->in(0) == head)) ) { 4208 worklist.push(use); 4209 } 4210 } 4211 while( worklist.size() ) { 4212 Node *use = worklist.pop(); 4213 for (uint j = 1; j < use->req(); j++) { 4214 Node* n = use->in(j); 4215 if (n == def) { 4216 4217 // "def" is in peel set, "use" is not in peel set 4218 // or "use" is in the entry boundary (a phi) of the peel set 4219 4220 Node* use_c = has_ctrl(use) ? get_ctrl(use) : use; 4221 4222 if ( loop->is_member(get_loop( use_c )) ) { 4223 // use is in loop 4224 if (old_new[use->_idx] != nullptr) { // null for dead code 4225 Node* use_clone = old_new[use->_idx]; 4226 _igvn.replace_input_of(use, j, C->top()); 4227 insert_phi_for_loop( use_clone, j, old_new[def->_idx], def, new_head_clone ); 4228 } 4229 } else { 4230 assert(is_valid_clone_loop_exit_use(loop, use, orig_exit_idx), "clone loop format"); 4231 // use is not in the loop, check if the live range includes the cut 4232 Node* lp_if = use_c->in(orig_exit_idx)->in(0); 4233 if (not_peel.test(lp_if->_idx)) { 4234 assert(j == orig_exit_idx, "use from original loop"); 4235 insert_phi_for_loop( use, clone_exit_idx, old_new[def->_idx], def, new_head_clone ); 4236 } 4237 } 4238 } 4239 } 4240 } 4241 } 4242 } 4243 4244 // Step 3b: retarget control 4245 4246 // Redirect control to the new loop head if a cloned node in 4247 // the not_peeled region has control that points into the peeled region. 4248 // This necessary because the cloned peeled region will be outside 4249 // the loop. 4250 // from to 4251 // cloned-peeled <---+ 4252 // new_head_clone: | <--+ 4253 // cloned-not_peeled in(0) in(0) 4254 // orig-peeled 4255 4256 for (uint i = 0; i < loop->_body.size(); i++) { 4257 Node *n = loop->_body.at(i); 4258 if (!n->is_CFG() && n->in(0) != nullptr && 4259 not_peel.test(n->_idx) && peel.test(n->in(0)->_idx)) { 4260 Node* n_clone = old_new[n->_idx]; 4261 if (n_clone->depends_only_on_test()) { 4262 // Pin array access nodes: control is updated here to the loop head. If, after some transformations, the 4263 // backedge is removed, an array load could become dependent on a condition that's not a range check for that 4264 // access. If that condition is replaced by an identical dominating one, then an unpinned load would risk 4265 // floating above its range check. 4266 Node* pinned_clone = n_clone->pin_array_access_node(); 4267 if (pinned_clone != nullptr) { 4268 register_new_node_with_ctrl_of(pinned_clone, n_clone); 4269 old_new.map(n->_idx, pinned_clone); 4270 _igvn.replace_node(n_clone, pinned_clone); 4271 n_clone = pinned_clone; 4272 } 4273 } 4274 _igvn.replace_input_of(n_clone, 0, new_head_clone); 4275 } 4276 } 4277 4278 // Backedge of the surviving new_head (the clone) is original last_peel 4279 _igvn.replace_input_of(new_head_clone, LoopNode::LoopBackControl, last_peel); 4280 4281 // Cut first node in original not_peel set 4282 _igvn.rehash_node_delayed(new_head); // Multiple edge updates: 4283 new_head->set_req(LoopNode::EntryControl, C->top()); // use rehash_node_delayed / set_req instead of 4284 new_head->set_req(LoopNode::LoopBackControl, C->top()); // multiple replace_input_of calls 4285 4286 // Copy head_clone back-branch info to original head 4287 // and remove original head's loop entry and 4288 // clone head's back-branch 4289 _igvn.rehash_node_delayed(head); // Multiple edge updates 4290 head->set_req(LoopNode::EntryControl, head_clone->in(LoopNode::LoopBackControl)); 4291 head->set_req(LoopNode::LoopBackControl, C->top()); 4292 _igvn.replace_input_of(head_clone, LoopNode::LoopBackControl, C->top()); 4293 4294 // Similarly modify the phis 4295 for (DUIterator_Fast kmax, k = head->fast_outs(kmax); k < kmax; k++) { 4296 Node* use = head->fast_out(k); 4297 if (use->is_Phi() && use->outcnt() > 0) { 4298 Node* use_clone = old_new[use->_idx]; 4299 _igvn.rehash_node_delayed(use); // Multiple edge updates 4300 use->set_req(LoopNode::EntryControl, use_clone->in(LoopNode::LoopBackControl)); 4301 use->set_req(LoopNode::LoopBackControl, C->top()); 4302 _igvn.replace_input_of(use_clone, LoopNode::LoopBackControl, C->top()); 4303 } 4304 } 4305 4306 // Step 4: update dominator tree and dominator depth 4307 4308 set_idom(head, orig_tail_clone, dd); 4309 recompute_dom_depth(); 4310 4311 // Inhibit more partial peeling on this loop 4312 new_head_clone->set_partial_peel_loop(); 4313 C->set_major_progress(); 4314 loop->record_for_igvn(); 4315 4316 #ifndef PRODUCT 4317 if (TracePartialPeeling) { 4318 tty->print_cr("\nafter partial peel one iteration"); 4319 Node_List wl; 4320 Node* t = last_peel; 4321 while (true) { 4322 wl.push(t); 4323 if (t == head_clone) break; 4324 t = idom(t); 4325 } 4326 while (wl.size() > 0) { 4327 Node* tt = wl.pop(); 4328 if (tt == head) tty->print_cr("orig head"); 4329 else if (tt == new_head_clone) tty->print_cr("new head"); 4330 else if (tt == head_clone) tty->print_cr("clone head"); 4331 tt->dump(); 4332 } 4333 } 4334 #endif 4335 4336 C->print_method(PHASE_AFTER_PARTIAL_PEELING, 4, new_head_clone); 4337 4338 return true; 4339 } 4340 4341 // Transform: 4342 // 4343 // loop<-----------------+ 4344 // | | 4345 // stmt1 stmt2 .. stmtn | 4346 // | | | | 4347 // \ | / | 4348 // v v v | 4349 // region | 4350 // | | 4351 // shared_stmt | 4352 // | | 4353 // v | 4354 // if | 4355 // / \ | 4356 // | -----------+ 4357 // v 4358 // 4359 // into: 4360 // 4361 // loop<-------------------+ 4362 // | | 4363 // v | 4364 // +->loop | 4365 // | | | 4366 // | stmt1 stmt2 .. stmtn | 4367 // | | | | | 4368 // | | \ / | 4369 // | | v v | 4370 // | | region1 | 4371 // | | | | 4372 // | shared_stmt shared_stmt | 4373 // | | | | 4374 // | v v | 4375 // | if if | 4376 // | /\ / \ | 4377 // +-- | | -------+ 4378 // \ / 4379 // v v 4380 // region2 4381 // 4382 // (region2 is shown to merge mirrored projections of the loop exit 4383 // ifs to make the diagram clearer but they really merge the same 4384 // projection) 4385 // 4386 // Conditions for this transformation to trigger: 4387 // - the path through stmt1 is frequent enough 4388 // - the inner loop will be turned into a counted loop after transformation 4389 bool PhaseIdealLoop::duplicate_loop_backedge(IdealLoopTree *loop, Node_List &old_new) { 4390 if (!DuplicateBackedge) { 4391 return false; 4392 } 4393 assert(!loop->_head->is_CountedLoop() || StressDuplicateBackedge, "Non-counted loop only"); 4394 if (!loop->_head->is_Loop()) { 4395 return false; 4396 } 4397 4398 uint estimate = loop->est_loop_clone_sz(1); 4399 if (exceeding_node_budget(estimate)) { 4400 return false; 4401 } 4402 4403 LoopNode *head = loop->_head->as_Loop(); 4404 4405 Node* region = nullptr; 4406 IfNode* exit_test = nullptr; 4407 uint inner; 4408 float f; 4409 if (StressDuplicateBackedge) { 4410 if (head->is_strip_mined()) { 4411 return false; 4412 } 4413 Node* c = head->in(LoopNode::LoopBackControl); 4414 4415 while (c != head) { 4416 if (c->is_Region()) { 4417 region = c; 4418 } 4419 c = idom(c); 4420 } 4421 4422 if (region == nullptr) { 4423 return false; 4424 } 4425 4426 inner = 1; 4427 } else { 4428 // Is the shape of the loop that of a counted loop... 4429 Node* back_control = loop_exit_control(head, loop); 4430 if (back_control == nullptr) { 4431 return false; 4432 } 4433 4434 BoolTest::mask bt = BoolTest::illegal; 4435 float cl_prob = 0; 4436 Node* incr = nullptr; 4437 Node* limit = nullptr; 4438 Node* cmp = loop_exit_test(back_control, loop, incr, limit, bt, cl_prob); 4439 if (cmp == nullptr || cmp->Opcode() != Op_CmpI) { 4440 return false; 4441 } 4442 4443 // With an extra phi for the candidate iv? 4444 // Or the region node is the loop head 4445 if (!incr->is_Phi() || incr->in(0) == head) { 4446 return false; 4447 } 4448 4449 PathFrequency pf(head, this); 4450 region = incr->in(0); 4451 4452 // Go over all paths for the extra phi's region and see if that 4453 // path is frequent enough and would match the expected iv shape 4454 // if the extra phi is removed 4455 inner = 0; 4456 for (uint i = 1; i < incr->req(); ++i) { 4457 Node* in = incr->in(i); 4458 Node* trunc1 = nullptr; 4459 Node* trunc2 = nullptr; 4460 const TypeInteger* iv_trunc_t = nullptr; 4461 Node* orig_in = in; 4462 if (!(in = CountedLoopNode::match_incr_with_optional_truncation(in, &trunc1, &trunc2, &iv_trunc_t, T_INT))) { 4463 continue; 4464 } 4465 assert(in->Opcode() == Op_AddI, "wrong increment code"); 4466 Node* xphi = nullptr; 4467 Node* stride = loop_iv_stride(in, xphi); 4468 4469 if (stride == nullptr) { 4470 continue; 4471 } 4472 4473 PhiNode* phi = loop_iv_phi(xphi, nullptr, head); 4474 if (phi == nullptr || 4475 (trunc1 == nullptr && phi->in(LoopNode::LoopBackControl) != incr) || 4476 (trunc1 != nullptr && phi->in(LoopNode::LoopBackControl) != trunc1)) { 4477 return false; 4478 } 4479 4480 f = pf.to(region->in(i)); 4481 if (f > 0.5) { 4482 inner = i; 4483 break; 4484 } 4485 } 4486 4487 if (inner == 0) { 4488 return false; 4489 } 4490 4491 exit_test = back_control->in(0)->as_If(); 4492 } 4493 4494 if (idom(region)->is_Catch()) { 4495 return false; 4496 } 4497 4498 // Collect all control nodes that need to be cloned (shared_stmt in the diagram) 4499 Unique_Node_List wq; 4500 wq.push(head->in(LoopNode::LoopBackControl)); 4501 for (uint i = 0; i < wq.size(); i++) { 4502 Node* c = wq.at(i); 4503 assert(get_loop(c) == loop, "not in the right loop?"); 4504 if (c->is_Region()) { 4505 if (c != region) { 4506 for (uint j = 1; j < c->req(); ++j) { 4507 wq.push(c->in(j)); 4508 } 4509 } 4510 } else { 4511 wq.push(c->in(0)); 4512 } 4513 assert(!is_strict_dominator(c, region), "shouldn't go above region"); 4514 } 4515 4516 Node* region_dom = idom(region); 4517 4518 // Can't do the transformation if this would cause a membar pair to 4519 // be split 4520 for (uint i = 0; i < wq.size(); i++) { 4521 Node* c = wq.at(i); 4522 if (c->is_MemBar() && (c->as_MemBar()->trailing_store() || c->as_MemBar()->trailing_load_store())) { 4523 assert(c->as_MemBar()->leading_membar()->trailing_membar() == c, "bad membar pair"); 4524 if (!wq.member(c->as_MemBar()->leading_membar())) { 4525 return false; 4526 } 4527 } 4528 } 4529 C->print_method(PHASE_BEFORE_DUPLICATE_LOOP_BACKEDGE, 4, head); 4530 4531 // Collect data nodes that need to be clones as well 4532 int dd = dom_depth(head); 4533 4534 for (uint i = 0; i < loop->_body.size(); ++i) { 4535 Node* n = loop->_body.at(i); 4536 if (has_ctrl(n)) { 4537 Node* c = get_ctrl(n); 4538 if (wq.member(c)) { 4539 wq.push(n); 4540 } 4541 } else { 4542 set_idom(n, idom(n), dd); 4543 } 4544 } 4545 4546 // clone shared_stmt 4547 clone_loop_body(wq, old_new, nullptr); 4548 4549 Node* region_clone = old_new[region->_idx]; 4550 region_clone->set_req(inner, C->top()); 4551 set_idom(region, region->in(inner), dd); 4552 4553 // Prepare the outer loop 4554 Node* outer_head = new LoopNode(head->in(LoopNode::EntryControl), old_new[head->in(LoopNode::LoopBackControl)->_idx]); 4555 register_control(outer_head, loop->_parent, outer_head->in(LoopNode::EntryControl)); 4556 _igvn.replace_input_of(head, LoopNode::EntryControl, outer_head); 4557 set_idom(head, outer_head, dd); 4558 4559 fix_body_edges(wq, loop, old_new, dd, loop->_parent, true); 4560 4561 // Make one of the shared_stmt copies only reachable from stmt1, the 4562 // other only from stmt2..stmtn. 4563 Node* dom = nullptr; 4564 for (uint i = 1; i < region->req(); ++i) { 4565 if (i != inner) { 4566 _igvn.replace_input_of(region, i, C->top()); 4567 } 4568 Node* in = region_clone->in(i); 4569 if (in->is_top()) { 4570 continue; 4571 } 4572 if (dom == nullptr) { 4573 dom = in; 4574 } else { 4575 dom = dom_lca(dom, in); 4576 } 4577 } 4578 4579 set_idom(region_clone, dom, dd); 4580 4581 // Set up the outer loop 4582 for (uint i = 0; i < head->outcnt(); i++) { 4583 Node* u = head->raw_out(i); 4584 if (u->is_Phi()) { 4585 Node* outer_phi = u->clone(); 4586 outer_phi->set_req(0, outer_head); 4587 Node* backedge = old_new[u->in(LoopNode::LoopBackControl)->_idx]; 4588 if (backedge == nullptr) { 4589 backedge = u->in(LoopNode::LoopBackControl); 4590 } 4591 outer_phi->set_req(LoopNode::LoopBackControl, backedge); 4592 register_new_node(outer_phi, outer_head); 4593 _igvn.replace_input_of(u, LoopNode::EntryControl, outer_phi); 4594 } 4595 } 4596 4597 // create control and data nodes for out of loop uses (including region2) 4598 Node_List worklist; 4599 uint new_counter = C->unique(); 4600 fix_ctrl_uses(wq, loop, old_new, ControlAroundStripMined, outer_head, nullptr, worklist); 4601 4602 Node_List *split_if_set = nullptr; 4603 Node_List *split_bool_set = nullptr; 4604 Node_List *split_cex_set = nullptr; 4605 fix_data_uses(wq, loop, ControlAroundStripMined, loop->skip_strip_mined(), new_counter, old_new, worklist, 4606 split_if_set, split_bool_set, split_cex_set); 4607 4608 finish_clone_loop(split_if_set, split_bool_set, split_cex_set); 4609 4610 if (exit_test != nullptr) { 4611 float cnt = exit_test->_fcnt; 4612 if (cnt != COUNT_UNKNOWN) { 4613 exit_test->_fcnt = cnt * f; 4614 old_new[exit_test->_idx]->as_If()->_fcnt = cnt * (1 - f); 4615 } 4616 } 4617 4618 C->set_major_progress(); 4619 4620 C->print_method(PHASE_AFTER_DUPLICATE_LOOP_BACKEDGE, 4, outer_head); 4621 4622 return true; 4623 } 4624 4625 // AutoVectorize the loop: replace scalar ops with vector ops. 4626 PhaseIdealLoop::AutoVectorizeStatus 4627 PhaseIdealLoop::auto_vectorize(IdealLoopTree* lpt, VSharedData &vshared) { 4628 // Counted loop only 4629 if (!lpt->is_counted()) { 4630 return AutoVectorizeStatus::Impossible; 4631 } 4632 4633 // Main-loop only 4634 CountedLoopNode* cl = lpt->_head->as_CountedLoop(); 4635 if (!cl->is_main_loop()) { 4636 return AutoVectorizeStatus::Impossible; 4637 } 4638 4639 VLoop vloop(lpt, false); 4640 if (!vloop.check_preconditions()) { 4641 return AutoVectorizeStatus::TriedAndFailed; 4642 } 4643 4644 // Ensure the shared data is cleared before each use 4645 vshared.clear(); 4646 4647 const VLoopAnalyzer vloop_analyzer(vloop, vshared); 4648 if (!vloop_analyzer.success()) { 4649 return AutoVectorizeStatus::TriedAndFailed; 4650 } 4651 4652 SuperWord sw(vloop_analyzer); 4653 if (!sw.transform_loop()) { 4654 return AutoVectorizeStatus::TriedAndFailed; 4655 } 4656 4657 return AutoVectorizeStatus::Success; 4658 } 4659 4660 // Just before insert_pre_post_loops, we can multiversion the loop: 4661 // 4662 // multiversion_if 4663 // | | 4664 // fast_loop slow_loop 4665 // 4666 // In the fast_loop we can make speculative assumptions, and put the 4667 // conditions into the multiversion_if. If the conditions hold at runtime, 4668 // we enter the fast_loop, if the conditions fail, we take the slow_loop 4669 // instead which does not make any of the speculative assumptions. 4670 // 4671 // Note: we only multiversion the loop if the loop does not have any 4672 // auto vectorization check Predicate. If we have that predicate, 4673 // then we can simply add the speculative assumption checks to 4674 // that Predicate. This means we do not need to duplicate the 4675 // loop - we have a smaller graph and save compile time. Should 4676 // the conditions ever fail, then we deopt / trap at the Predicate 4677 // and recompile without that Predicate. At that point we will 4678 // multiversion the loop, so that we can still have speculative 4679 // runtime checks. 4680 // 4681 // We perform the multiversioning when the loop is still in its single 4682 // iteration form, even before we insert pre and post loops. This makes 4683 // the cloning much simpler. However, this means that both the fast 4684 // and the slow loop have to be optimized independently (adding pre 4685 // and post loops, unrolling the main loop, auto-vectorize etc.). And 4686 // we may end up not needing any speculative assumptions in the fast_loop 4687 // and then rejecting the slow_loop by constant folding the multiversion_if. 4688 // 4689 // Therefore, we "delay" the optimization of the slow_loop until we add 4690 // at least one speculative assumption for the fast_loop. If we never 4691 // add such a speculative runtime check, the OpaqueMultiversioningNode 4692 // of the multiversion_if constant folds to true after loop opts, and the 4693 // multiversion_if folds away the "delayed" slow_loop. If we add any 4694 // speculative assumption, then we notify the OpaqueMultiversioningNode 4695 // with "notify_slow_loop_that_it_can_resume_optimizations". 4696 // 4697 // Note: new runtime checks can be added to the multiversion_if with 4698 // PhaseIdealLoop::create_new_if_for_multiversion 4699 void PhaseIdealLoop::maybe_multiversion_for_auto_vectorization_runtime_checks(IdealLoopTree* lpt, Node_List& old_new) { 4700 CountedLoopNode* cl = lpt->_head->as_CountedLoop(); 4701 LoopNode* outer_loop = cl->skip_strip_mined(); 4702 Node* entry = outer_loop->in(LoopNode::EntryControl); 4703 4704 // Check we have multiversioning enabled, and are not already multiversioned. 4705 if (!LoopMultiversioning || cl->is_multiversion()) { return; } 4706 4707 // Check that we do not have a parse-predicate where we can add the runtime checks 4708 // during auto-vectorization. 4709 const Predicates predicates(entry); 4710 const PredicateBlock* predicate_block = predicates.auto_vectorization_check_block(); 4711 if (predicate_block->has_parse_predicate()) { return; } 4712 4713 // Check node budget. 4714 uint estimate = lpt->est_loop_clone_sz(2); 4715 if (!may_require_nodes(estimate)) { return; } 4716 4717 do_multiversioning(lpt, old_new); 4718 } 4719 4720 // Returns true if the Reduction node is unordered. 4721 static bool is_unordered_reduction(Node* n) { 4722 return n->is_Reduction() && !n->as_Reduction()->requires_strict_order(); 4723 } 4724 4725 // Having ReductionNodes in the loop is expensive. They need to recursively 4726 // fold together the vector values, for every vectorized loop iteration. If 4727 // we encounter the following pattern, we can vector accumulate the values 4728 // inside the loop, and only have a single UnorderedReduction after the loop. 4729 // 4730 // Note: UnorderedReduction represents a ReductionNode which does not require 4731 // calculating in strict order. 4732 // 4733 // CountedLoop init 4734 // | | 4735 // +------+ | +-----------------------+ 4736 // | | | | 4737 // PhiNode (s) | 4738 // | | 4739 // | Vector | 4740 // | | | 4741 // UnorderedReduction (first_ur) | 4742 // | | 4743 // ... Vector | 4744 // | | | 4745 // UnorderedReduction (last_ur) | 4746 // | | 4747 // +---------------------+ 4748 // 4749 // We patch the graph to look like this: 4750 // 4751 // CountedLoop identity_vector 4752 // | | 4753 // +-------+ | +---------------+ 4754 // | | | | 4755 // PhiNode (v) | 4756 // | | 4757 // | Vector | 4758 // | | | 4759 // VectorAccumulator | 4760 // | | 4761 // ... Vector | 4762 // | | | 4763 // init VectorAccumulator | 4764 // | | | | 4765 // UnorderedReduction +-----------+ 4766 // 4767 // We turned the scalar (s) Phi into a vectorized one (v). In the loop, we 4768 // use vector_accumulators, which do the same reductions, but only element 4769 // wise. This is a single operation per vector_accumulator, rather than many 4770 // for a UnorderedReduction. We can then reduce the last vector_accumulator 4771 // after the loop, and also reduce the init value into it. 4772 // 4773 // We can not do this with all reductions. Some reductions do not allow the 4774 // reordering of operations (for example float addition/multiplication require 4775 // strict order). 4776 void PhaseIdealLoop::move_unordered_reduction_out_of_loop(IdealLoopTree* loop) { 4777 assert(!C->major_progress() && loop->is_counted() && loop->is_innermost(), "sanity"); 4778 4779 // Find all Phi nodes with an unordered Reduction on backedge. 4780 CountedLoopNode* cl = loop->_head->as_CountedLoop(); 4781 for (DUIterator_Fast jmax, j = cl->fast_outs(jmax); j < jmax; j++) { 4782 Node* phi = cl->fast_out(j); 4783 // We have a phi with a single use, and an unordered Reduction on the backedge. 4784 if (!phi->is_Phi() || phi->outcnt() != 1 || !is_unordered_reduction(phi->in(2))) { 4785 continue; 4786 } 4787 4788 ReductionNode* last_ur = phi->in(2)->as_Reduction(); 4789 assert(!last_ur->requires_strict_order(), "must be"); 4790 4791 // Determine types 4792 const TypeVect* vec_t = last_ur->vect_type(); 4793 uint vector_length = vec_t->length(); 4794 BasicType bt = vec_t->element_basic_type(); 4795 4796 // Convert opcode from vector-reduction -> scalar -> normal-vector-op 4797 const int sopc = VectorNode::scalar_opcode(last_ur->Opcode(), bt); 4798 const int vopc = VectorNode::opcode(sopc, bt); 4799 if (!Matcher::match_rule_supported_vector(vopc, vector_length, bt)) { 4800 DEBUG_ONLY( last_ur->dump(); ) 4801 assert(false, "do not have normal vector op for this reduction"); 4802 continue; // not implemented -> fails 4803 } 4804 4805 // Traverse up the chain of unordered Reductions, checking that it loops back to 4806 // the phi. Check that all unordered Reductions only have a single use, except for 4807 // the last (last_ur), which only has phi as a use in the loop, and all other uses 4808 // are outside the loop. 4809 ReductionNode* current = last_ur; 4810 ReductionNode* first_ur = nullptr; 4811 while (true) { 4812 assert(!current->requires_strict_order(), "sanity"); 4813 4814 // Expect no ctrl and a vector_input from within the loop. 4815 Node* ctrl = current->in(0); 4816 Node* vector_input = current->in(2); 4817 if (ctrl != nullptr || get_ctrl(vector_input) != cl) { 4818 DEBUG_ONLY( current->dump(1); ) 4819 assert(false, "reduction has ctrl or bad vector_input"); 4820 break; // Chain traversal fails. 4821 } 4822 4823 assert(current->vect_type() != nullptr, "must have vector type"); 4824 if (current->vect_type() != last_ur->vect_type()) { 4825 // Reductions do not have the same vector type (length and element type). 4826 break; // Chain traversal fails. 4827 } 4828 4829 // Expect single use of an unordered Reduction, except for last_ur. 4830 if (current == last_ur) { 4831 // Expect all uses to be outside the loop, except phi. 4832 for (DUIterator_Fast kmax, k = current->fast_outs(kmax); k < kmax; k++) { 4833 Node* use = current->fast_out(k); 4834 if (use != phi && ctrl_or_self(use) == cl) { 4835 DEBUG_ONLY( current->dump(-1); ) 4836 assert(false, "reduction has use inside loop"); 4837 // Should not be allowed by SuperWord::mark_reductions 4838 return; // bail out of optimization 4839 } 4840 } 4841 } else { 4842 if (current->outcnt() != 1) { 4843 break; // Chain traversal fails. 4844 } 4845 } 4846 4847 // Expect another unordered Reduction or phi as the scalar input. 4848 Node* scalar_input = current->in(1); 4849 if (is_unordered_reduction(scalar_input) && 4850 scalar_input->Opcode() == current->Opcode()) { 4851 // Move up the unordered Reduction chain. 4852 current = scalar_input->as_Reduction(); 4853 assert(!current->requires_strict_order(), "must be"); 4854 } else if (scalar_input == phi) { 4855 // Chain terminates at phi. 4856 first_ur = current; 4857 current = nullptr; 4858 break; // Success. 4859 } else { 4860 // scalar_input is neither phi nor a matching reduction 4861 // Can for example be scalar reduction when we have 4862 // partial vectorization. 4863 break; // Chain traversal fails. 4864 } 4865 } 4866 if (current != nullptr) { 4867 // Chain traversal was not successful. 4868 continue; 4869 } 4870 assert(first_ur != nullptr, "must have successfully terminated chain traversal"); 4871 4872 Node* identity_scalar = ReductionNode::make_identity_con_scalar(_igvn, sopc, bt); 4873 set_root_as_ctrl(identity_scalar); 4874 VectorNode* identity_vector = VectorNode::scalar2vector(identity_scalar, vector_length, bt); 4875 register_new_node(identity_vector, C->root()); 4876 assert(vec_t == identity_vector->vect_type(), "matching vector type"); 4877 VectorNode::trace_new_vector(identity_vector, "Unordered Reduction"); 4878 4879 // Turn the scalar phi into a vector phi. 4880 _igvn.rehash_node_delayed(phi); 4881 Node* init = phi->in(1); // Remember init before replacing it. 4882 phi->set_req_X(1, identity_vector, &_igvn); 4883 phi->as_Type()->set_type(vec_t); 4884 _igvn.set_type(phi, vec_t); 4885 4886 // Traverse down the chain of unordered Reductions, and replace them with vector_accumulators. 4887 current = first_ur; 4888 while (true) { 4889 // Create vector_accumulator to replace current. 4890 Node* last_vector_accumulator = current->in(1); 4891 Node* vector_input = current->in(2); 4892 VectorNode* vector_accumulator = VectorNode::make(vopc, last_vector_accumulator, vector_input, vec_t); 4893 register_new_node(vector_accumulator, cl); 4894 _igvn.replace_node(current, vector_accumulator); 4895 VectorNode::trace_new_vector(vector_accumulator, "Unordered Reduction"); 4896 if (current == last_ur) { 4897 break; 4898 } 4899 current = vector_accumulator->unique_out()->as_Reduction(); 4900 assert(!current->requires_strict_order(), "must be"); 4901 } 4902 4903 // Create post-loop reduction. 4904 Node* last_accumulator = phi->in(2); 4905 Node* post_loop_reduction = ReductionNode::make(sopc, nullptr, init, last_accumulator, bt); 4906 4907 // Take over uses of last_accumulator that are not in the loop. 4908 for (DUIterator i = last_accumulator->outs(); last_accumulator->has_out(i); i++) { 4909 Node* use = last_accumulator->out(i); 4910 if (use != phi && use != post_loop_reduction) { 4911 assert(ctrl_or_self(use) != cl, "use must be outside loop"); 4912 use->replace_edge(last_accumulator, post_loop_reduction, &_igvn); 4913 --i; 4914 } 4915 } 4916 register_new_node(post_loop_reduction, get_late_ctrl(post_loop_reduction, cl)); 4917 VectorNode::trace_new_vector(post_loop_reduction, "Unordered Reduction"); 4918 4919 assert(last_accumulator->outcnt() == 2, "last_accumulator has 2 uses: phi and post_loop_reduction"); 4920 assert(post_loop_reduction->outcnt() > 0, "should have taken over all non loop uses of last_accumulator"); 4921 assert(phi->outcnt() == 1, "accumulator is the only use of phi"); 4922 } 4923 } 4924 4925 void DataNodeGraph::clone_data_nodes(Node* new_ctrl) { 4926 for (uint i = 0; i < _data_nodes.size(); i++) { 4927 clone(_data_nodes[i], new_ctrl); 4928 } 4929 } 4930 4931 // Clone the given node and set it up properly. Set 'new_ctrl' as ctrl. 4932 void DataNodeGraph::clone(Node* node, Node* new_ctrl) { 4933 Node* clone = node->clone(); 4934 _phase->igvn().register_new_node_with_optimizer(clone); 4935 _orig_to_new.put(node, clone); 4936 _phase->set_ctrl(clone, new_ctrl); 4937 if (node->is_CastII()) { 4938 clone->set_req(0, new_ctrl); 4939 } 4940 } 4941 4942 // Rewire the data inputs of all (unprocessed) cloned nodes, whose inputs are still pointing to the same inputs as their 4943 // corresponding orig nodes, to the newly cloned inputs to create a separate cloned graph. 4944 void DataNodeGraph::rewire_clones_to_cloned_inputs() { 4945 _orig_to_new.iterate_all([&](Node* node, Node* clone) { 4946 for (uint i = 1; i < node->req(); i++) { 4947 Node** cloned_input = _orig_to_new.get(node->in(i)); 4948 if (cloned_input != nullptr) { 4949 // Input was also cloned -> rewire clone to the cloned input. 4950 _phase->igvn().replace_input_of(clone, i, *cloned_input); 4951 } 4952 } 4953 }); 4954 } 4955 4956 // Clone all non-OpaqueLoop* nodes and apply the provided transformation strategy for OpaqueLoop* nodes. 4957 // Set 'new_ctrl' as ctrl for all cloned non-OpaqueLoop* nodes. 4958 void DataNodeGraph::clone_data_nodes_and_transform_opaque_loop_nodes( 4959 const TransformStrategyForOpaqueLoopNodes& transform_strategy, 4960 Node* new_ctrl) { 4961 for (uint i = 0; i < _data_nodes.size(); i++) { 4962 Node* data_node = _data_nodes[i]; 4963 if (data_node->is_Opaque1()) { 4964 transform_opaque_node(transform_strategy, data_node); 4965 } else { 4966 clone(data_node, new_ctrl); 4967 } 4968 } 4969 } 4970 4971 void DataNodeGraph::transform_opaque_node(const TransformStrategyForOpaqueLoopNodes& transform_strategy, Node* node) { 4972 Node* transformed_node; 4973 if (node->is_OpaqueLoopInit()) { 4974 transformed_node = transform_strategy.transform_opaque_init(node->as_OpaqueLoopInit()); 4975 } else { 4976 assert(node->is_OpaqueLoopStride(), "must be OpaqueLoopStrideNode"); 4977 transformed_node = transform_strategy.transform_opaque_stride(node->as_OpaqueLoopStride()); 4978 } 4979 // Add an orig->new mapping to correctly update the inputs of the copied graph in rewire_clones_to_cloned_inputs(). 4980 _orig_to_new.put(node, transformed_node); 4981 }