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