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