1 /* 2 * Copyright (c) 1998, 2018, 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 "ci/ciMethodData.hpp" 27 #include "compiler/compileLog.hpp" 28 #include "libadt/vectset.hpp" 29 #include "memory/allocation.inline.hpp" 30 #include "memory/resourceArea.hpp" 31 #include "opto/addnode.hpp" 32 #include "opto/callnode.hpp" 33 #include "opto/connode.hpp" 34 #include "opto/convertnode.hpp" 35 #include "opto/divnode.hpp" 36 #include "opto/idealGraphPrinter.hpp" 37 #include "opto/loopnode.hpp" 38 #include "opto/mulnode.hpp" 39 #include "opto/rootnode.hpp" 40 #include "opto/superword.hpp" 41 42 //============================================================================= 43 //------------------------------is_loop_iv------------------------------------- 44 // Determine if a node is Counted loop induction variable. 45 // The method is declared in node.hpp. 46 const Node* Node::is_loop_iv() const { 47 if (this->is_Phi() && !this->as_Phi()->is_copy() && 48 this->as_Phi()->region()->is_CountedLoop() && 49 this->as_Phi()->region()->as_CountedLoop()->phi() == this) { 50 return this; 51 } else { 52 return NULL; 53 } 54 } 55 56 //============================================================================= 57 //------------------------------dump_spec-------------------------------------- 58 // Dump special per-node info 59 #ifndef PRODUCT 60 void LoopNode::dump_spec(outputStream *st) const { 61 if (is_inner_loop()) st->print( "inner " ); 62 if (is_partial_peel_loop()) st->print( "partial_peel " ); 63 if (partial_peel_has_failed()) st->print( "partial_peel_failed " ); 64 } 65 #endif 66 67 //------------------------------is_valid_counted_loop------------------------- 68 bool LoopNode::is_valid_counted_loop() const { 69 if (is_CountedLoop()) { 70 CountedLoopNode* l = as_CountedLoop(); 71 CountedLoopEndNode* le = l->loopexit_or_null(); 72 if (le != NULL && 73 le->proj_out_or_null(1 /* true */) == l->in(LoopNode::LoopBackControl)) { 74 Node* phi = l->phi(); 75 Node* exit = le->proj_out_or_null(0 /* false */); 76 if (exit != NULL && exit->Opcode() == Op_IfFalse && 77 phi != NULL && phi->is_Phi() && 78 phi->in(LoopNode::LoopBackControl) == l->incr() && 79 le->loopnode() == l && le->stride_is_con()) { 80 return true; 81 } 82 } 83 } 84 return false; 85 } 86 87 //------------------------------get_early_ctrl--------------------------------- 88 // Compute earliest legal control 89 Node *PhaseIdealLoop::get_early_ctrl( Node *n ) { 90 assert( !n->is_Phi() && !n->is_CFG(), "this code only handles data nodes" ); 91 uint i; 92 Node *early; 93 if (n->in(0) && !n->is_expensive()) { 94 early = n->in(0); 95 if (!early->is_CFG()) // Might be a non-CFG multi-def 96 early = get_ctrl(early); // So treat input as a straight data input 97 i = 1; 98 } else { 99 early = get_ctrl(n->in(1)); 100 i = 2; 101 } 102 uint e_d = dom_depth(early); 103 assert( early, "" ); 104 for (; i < n->req(); i++) { 105 Node *cin = get_ctrl(n->in(i)); 106 assert( cin, "" ); 107 // Keep deepest dominator depth 108 uint c_d = dom_depth(cin); 109 if (c_d > e_d) { // Deeper guy? 110 early = cin; // Keep deepest found so far 111 e_d = c_d; 112 } else if (c_d == e_d && // Same depth? 113 early != cin) { // If not equal, must use slower algorithm 114 // If same depth but not equal, one _must_ dominate the other 115 // and we want the deeper (i.e., dominated) guy. 116 Node *n1 = early; 117 Node *n2 = cin; 118 while (1) { 119 n1 = idom(n1); // Walk up until break cycle 120 n2 = idom(n2); 121 if (n1 == cin || // Walked early up to cin 122 dom_depth(n2) < c_d) 123 break; // early is deeper; keep him 124 if (n2 == early || // Walked cin up to early 125 dom_depth(n1) < c_d) { 126 early = cin; // cin is deeper; keep him 127 break; 128 } 129 } 130 e_d = dom_depth(early); // Reset depth register cache 131 } 132 } 133 134 // Return earliest legal location 135 assert(early == find_non_split_ctrl(early), "unexpected early control"); 136 137 if (n->is_expensive() && !_verify_only && !_verify_me) { 138 assert(n->in(0), "should have control input"); 139 early = get_early_ctrl_for_expensive(n, early); 140 } 141 142 return early; 143 } 144 145 //------------------------------get_early_ctrl_for_expensive--------------------------------- 146 // Move node up the dominator tree as high as legal while still beneficial 147 Node *PhaseIdealLoop::get_early_ctrl_for_expensive(Node *n, Node* earliest) { 148 assert(n->in(0) && n->is_expensive(), "expensive node with control input here"); 149 assert(OptimizeExpensiveOps, "optimization off?"); 150 151 Node* ctl = n->in(0); 152 assert(ctl->is_CFG(), "expensive input 0 must be cfg"); 153 uint min_dom_depth = dom_depth(earliest); 154 #ifdef ASSERT 155 if (!is_dominator(ctl, earliest) && !is_dominator(earliest, ctl)) { 156 dump_bad_graph("Bad graph detected in get_early_ctrl_for_expensive", n, earliest, ctl); 157 assert(false, "Bad graph detected in get_early_ctrl_for_expensive"); 158 } 159 #endif 160 if (dom_depth(ctl) < min_dom_depth) { 161 return earliest; 162 } 163 164 while (1) { 165 Node *next = ctl; 166 // Moving the node out of a loop on the projection of a If 167 // confuses loop predication. So once we hit a Loop in a If branch 168 // that doesn't branch to an UNC, we stop. The code that process 169 // expensive nodes will notice the loop and skip over it to try to 170 // move the node further up. 171 if (ctl->is_CountedLoop() && ctl->in(1) != NULL && ctl->in(1)->in(0) != NULL && ctl->in(1)->in(0)->is_If()) { 172 if (!ctl->in(1)->as_Proj()->is_uncommon_trap_if_pattern(Deoptimization::Reason_none)) { 173 break; 174 } 175 next = idom(ctl->in(1)->in(0)); 176 } else if (ctl->is_Proj()) { 177 // We only move it up along a projection if the projection is 178 // the single control projection for its parent: same code path, 179 // if it's a If with UNC or fallthrough of a call. 180 Node* parent_ctl = ctl->in(0); 181 if (parent_ctl == NULL) { 182 break; 183 } else if (parent_ctl->is_CountedLoopEnd() && parent_ctl->as_CountedLoopEnd()->loopnode() != NULL) { 184 next = parent_ctl->as_CountedLoopEnd()->loopnode()->init_control(); 185 } else if (parent_ctl->is_If()) { 186 if (!ctl->as_Proj()->is_uncommon_trap_if_pattern(Deoptimization::Reason_none)) { 187 break; 188 } 189 assert(idom(ctl) == parent_ctl, "strange"); 190 next = idom(parent_ctl); 191 } else if (ctl->is_CatchProj()) { 192 if (ctl->as_Proj()->_con != CatchProjNode::fall_through_index) { 193 break; 194 } 195 assert(parent_ctl->in(0)->in(0)->is_Call(), "strange graph"); 196 next = parent_ctl->in(0)->in(0)->in(0); 197 } else { 198 // Check if parent control has a single projection (this 199 // control is the only possible successor of the parent 200 // control). If so, we can try to move the node above the 201 // parent control. 202 int nb_ctl_proj = 0; 203 for (DUIterator_Fast imax, i = parent_ctl->fast_outs(imax); i < imax; i++) { 204 Node *p = parent_ctl->fast_out(i); 205 if (p->is_Proj() && p->is_CFG()) { 206 nb_ctl_proj++; 207 if (nb_ctl_proj > 1) { 208 break; 209 } 210 } 211 } 212 213 if (nb_ctl_proj > 1) { 214 break; 215 } 216 assert(parent_ctl->is_Start() || parent_ctl->is_MemBar() || parent_ctl->is_Call(), "unexpected node"); 217 assert(idom(ctl) == parent_ctl, "strange"); 218 next = idom(parent_ctl); 219 } 220 } else { 221 next = idom(ctl); 222 } 223 if (next->is_Root() || next->is_Start() || dom_depth(next) < min_dom_depth) { 224 break; 225 } 226 ctl = next; 227 } 228 229 if (ctl != n->in(0)) { 230 _igvn.replace_input_of(n, 0, ctl); 231 _igvn.hash_insert(n); 232 } 233 234 return ctl; 235 } 236 237 238 //------------------------------set_early_ctrl--------------------------------- 239 // Set earliest legal control 240 void PhaseIdealLoop::set_early_ctrl( Node *n ) { 241 Node *early = get_early_ctrl(n); 242 243 // Record earliest legal location 244 set_ctrl(n, early); 245 } 246 247 //------------------------------set_subtree_ctrl------------------------------- 248 // set missing _ctrl entries on new nodes 249 void PhaseIdealLoop::set_subtree_ctrl( Node *n ) { 250 // Already set? Get out. 251 if( _nodes[n->_idx] ) return; 252 // Recursively set _nodes array to indicate where the Node goes 253 uint i; 254 for( i = 0; i < n->req(); ++i ) { 255 Node *m = n->in(i); 256 if( m && m != C->root() ) 257 set_subtree_ctrl( m ); 258 } 259 260 // Fixup self 261 set_early_ctrl( n ); 262 } 263 264 // Create a skeleton strip mined outer loop: a Loop head before the 265 // inner strip mined loop, a safepoint and an exit condition guarded 266 // by an opaque node after the inner strip mined loop with a backedge 267 // to the loop head. The inner strip mined loop is left as it is. Only 268 // once loop optimizations are over, do we adjust the inner loop exit 269 // condition to limit its number of iterations, set the outer loop 270 // exit condition and add Phis to the outer loop head. Some loop 271 // optimizations that operate on the inner strip mined loop need to be 272 // aware of the outer strip mined loop: loop unswitching needs to 273 // clone the outer loop as well as the inner, unrolling needs to only 274 // clone the inner loop etc. No optimizations need to change the outer 275 // strip mined loop as it is only a skeleton. 276 IdealLoopTree* PhaseIdealLoop::create_outer_strip_mined_loop(BoolNode *test, Node *cmp, Node *init_control, 277 IdealLoopTree* loop, float cl_prob, float le_fcnt, 278 Node*& entry_control, Node*& iffalse) { 279 Node* outer_test = _igvn.intcon(0); 280 set_ctrl(outer_test, C->root()); 281 Node *orig = iffalse; 282 iffalse = iffalse->clone(); 283 _igvn.register_new_node_with_optimizer(iffalse); 284 set_idom(iffalse, idom(orig), dom_depth(orig)); 285 286 IfNode *outer_le = new OuterStripMinedLoopEndNode(iffalse, outer_test, cl_prob, le_fcnt); 287 Node *outer_ift = new IfTrueNode (outer_le); 288 Node* outer_iff = orig; 289 _igvn.replace_input_of(outer_iff, 0, outer_le); 290 291 LoopNode *outer_l = new OuterStripMinedLoopNode(C, init_control, outer_ift); 292 entry_control = outer_l; 293 294 IdealLoopTree* outer_ilt = new IdealLoopTree(this, outer_l, outer_ift); 295 IdealLoopTree* parent = loop->_parent; 296 IdealLoopTree* sibling = parent->_child; 297 if (sibling == loop) { 298 parent->_child = outer_ilt; 299 } else { 300 while (sibling->_next != loop) { 301 sibling = sibling->_next; 302 } 303 sibling->_next = outer_ilt; 304 } 305 outer_ilt->_next = loop->_next; 306 outer_ilt->_parent = parent; 307 outer_ilt->_child = loop; 308 outer_ilt->_nest = loop->_nest; 309 loop->_parent = outer_ilt; 310 loop->_next = NULL; 311 loop->_nest++; 312 313 set_loop(iffalse, outer_ilt); 314 register_control(outer_le, outer_ilt, iffalse); 315 register_control(outer_ift, outer_ilt, outer_le); 316 set_idom(outer_iff, outer_le, dom_depth(outer_le)); 317 _igvn.register_new_node_with_optimizer(outer_l); 318 set_loop(outer_l, outer_ilt); 319 set_idom(outer_l, init_control, dom_depth(init_control)+1); 320 321 return outer_ilt; 322 } 323 324 //------------------------------is_counted_loop-------------------------------- 325 bool PhaseIdealLoop::is_counted_loop(Node* x, IdealLoopTree*& loop) { 326 PhaseGVN *gvn = &_igvn; 327 328 // Counted loop head must be a good RegionNode with only 3 not NULL 329 // control input edges: Self, Entry, LoopBack. 330 if (x->in(LoopNode::Self) == NULL || x->req() != 3 || loop->_irreducible) { 331 return false; 332 } 333 Node *init_control = x->in(LoopNode::EntryControl); 334 Node *back_control = x->in(LoopNode::LoopBackControl); 335 if (init_control == NULL || back_control == NULL) // Partially dead 336 return false; 337 // Must also check for TOP when looking for a dead loop 338 if (init_control->is_top() || back_control->is_top()) 339 return false; 340 341 // Allow funny placement of Safepoint 342 if (back_control->Opcode() == Op_SafePoint) { 343 if (LoopStripMiningIter != 0) { 344 // Leaving the safepoint on the backedge and creating a 345 // CountedLoop will confuse optimizations. We can't move the 346 // safepoint around because its jvm state wouldn't match a new 347 // location. Give up on that loop. 348 return false; 349 } 350 back_control = back_control->in(TypeFunc::Control); 351 } 352 353 // Controlling test for loop 354 Node *iftrue = back_control; 355 uint iftrue_op = iftrue->Opcode(); 356 if (iftrue_op != Op_IfTrue && 357 iftrue_op != Op_IfFalse) 358 // I have a weird back-control. Probably the loop-exit test is in 359 // the middle of the loop and I am looking at some trailing control-flow 360 // merge point. To fix this I would have to partially peel the loop. 361 return false; // Obscure back-control 362 363 // Get boolean guarding loop-back test 364 Node *iff = iftrue->in(0); 365 if (get_loop(iff) != loop || !iff->in(1)->is_Bool()) 366 return false; 367 BoolNode *test = iff->in(1)->as_Bool(); 368 BoolTest::mask bt = test->_test._test; 369 float cl_prob = iff->as_If()->_prob; 370 if (iftrue_op == Op_IfFalse) { 371 bt = BoolTest(bt).negate(); 372 cl_prob = 1.0 - cl_prob; 373 } 374 // Get backedge compare 375 Node *cmp = test->in(1); 376 int cmp_op = cmp->Opcode(); 377 if (cmp_op != Op_CmpI) 378 return false; // Avoid pointer & float compares 379 380 // Find the trip-counter increment & limit. Limit must be loop invariant. 381 Node *incr = cmp->in(1); 382 Node *limit = cmp->in(2); 383 384 // --------- 385 // need 'loop()' test to tell if limit is loop invariant 386 // --------- 387 388 if (!is_member(loop, get_ctrl(incr))) { // Swapped trip counter and limit? 389 Node *tmp = incr; // Then reverse order into the CmpI 390 incr = limit; 391 limit = tmp; 392 bt = BoolTest(bt).commute(); // And commute the exit test 393 } 394 if (is_member(loop, get_ctrl(limit))) // Limit must be loop-invariant 395 return false; 396 if (!is_member(loop, get_ctrl(incr))) // Trip counter must be loop-variant 397 return false; 398 399 Node* phi_incr = NULL; 400 // Trip-counter increment must be commutative & associative. 401 if (incr->Opcode() == Op_CastII) { 402 incr = incr->in(1); 403 } 404 if (incr->is_Phi()) { 405 if (incr->as_Phi()->region() != x || incr->req() != 3) 406 return false; // Not simple trip counter expression 407 phi_incr = incr; 408 incr = phi_incr->in(LoopNode::LoopBackControl); // Assume incr is on backedge of Phi 409 if (!is_member(loop, get_ctrl(incr))) // Trip counter must be loop-variant 410 return false; 411 } 412 413 Node* trunc1 = NULL; 414 Node* trunc2 = NULL; 415 const TypeInt* iv_trunc_t = NULL; 416 Node* orig_incr = incr; 417 if (!(incr = CountedLoopNode::match_incr_with_optional_truncation(incr, &trunc1, &trunc2, &iv_trunc_t))) { 418 return false; // Funny increment opcode 419 } 420 assert(incr->Opcode() == Op_AddI, "wrong increment code"); 421 422 const TypeInt* limit_t = gvn->type(limit)->is_int(); 423 if (trunc1 != NULL) { 424 // When there is a truncation, we must be sure that after the truncation 425 // the trip counter will end up higher than the limit, otherwise we are looking 426 // at an endless loop. Can happen with range checks. 427 428 // Example: 429 // int i = 0; 430 // while (true) 431 // sum + = array[i]; 432 // i++; 433 // i = i && 0x7fff; 434 // } 435 // 436 // If the array is shorter than 0x8000 this exits through a AIOOB 437 // - Counted loop transformation is ok 438 // If the array is longer then this is an endless loop 439 // - No transformation can be done. 440 441 const TypeInt* incr_t = gvn->type(orig_incr)->is_int(); 442 if (limit_t->_hi > incr_t->_hi) { 443 // if the limit can have a higher value than the increment (before the phi) 444 return false; 445 } 446 } 447 448 // Get merge point 449 Node *xphi = incr->in(1); 450 Node *stride = incr->in(2); 451 if (!stride->is_Con()) { // Oops, swap these 452 if (!xphi->is_Con()) // Is the other guy a constant? 453 return false; // Nope, unknown stride, bail out 454 Node *tmp = xphi; // 'incr' is commutative, so ok to swap 455 xphi = stride; 456 stride = tmp; 457 } 458 if (xphi->Opcode() == Op_CastII) { 459 xphi = xphi->in(1); 460 } 461 // Stride must be constant 462 int stride_con = stride->get_int(); 463 if (stride_con == 0) 464 return false; // missed some peephole opt 465 466 if (!xphi->is_Phi()) 467 return false; // Too much math on the trip counter 468 if (phi_incr != NULL && phi_incr != xphi) 469 return false; 470 PhiNode *phi = xphi->as_Phi(); 471 472 // Phi must be of loop header; backedge must wrap to increment 473 if (phi->region() != x) 474 return false; 475 if ((trunc1 == NULL && phi->in(LoopNode::LoopBackControl) != incr) || 476 (trunc1 != NULL && phi->in(LoopNode::LoopBackControl) != trunc1)) { 477 return false; 478 } 479 Node *init_trip = phi->in(LoopNode::EntryControl); 480 481 // If iv trunc type is smaller than int, check for possible wrap. 482 if (!TypeInt::INT->higher_equal(iv_trunc_t)) { 483 assert(trunc1 != NULL, "must have found some truncation"); 484 485 // Get a better type for the phi (filtered thru if's) 486 const TypeInt* phi_ft = filtered_type(phi); 487 488 // Can iv take on a value that will wrap? 489 // 490 // Ensure iv's limit is not within "stride" of the wrap value. 491 // 492 // Example for "short" type 493 // Truncation ensures value is in the range -32768..32767 (iv_trunc_t) 494 // If the stride is +10, then the last value of the induction 495 // variable before the increment (phi_ft->_hi) must be 496 // <= 32767 - 10 and (phi_ft->_lo) must be >= -32768 to 497 // ensure no truncation occurs after the increment. 498 499 if (stride_con > 0) { 500 if (iv_trunc_t->_hi - phi_ft->_hi < stride_con || 501 iv_trunc_t->_lo > phi_ft->_lo) { 502 return false; // truncation may occur 503 } 504 } else if (stride_con < 0) { 505 if (iv_trunc_t->_lo - phi_ft->_lo > stride_con || 506 iv_trunc_t->_hi < phi_ft->_hi) { 507 return false; // truncation may occur 508 } 509 } 510 // No possibility of wrap so truncation can be discarded 511 // Promote iv type to Int 512 } else { 513 assert(trunc1 == NULL && trunc2 == NULL, "no truncation for int"); 514 } 515 516 // If the condition is inverted and we will be rolling 517 // through MININT to MAXINT, then bail out. 518 if (bt == BoolTest::eq || // Bail out, but this loop trips at most twice! 519 // Odd stride 520 (bt == BoolTest::ne && stride_con != 1 && stride_con != -1) || 521 // Count down loop rolls through MAXINT 522 ((bt == BoolTest::le || bt == BoolTest::lt) && stride_con < 0) || 523 // Count up loop rolls through MININT 524 ((bt == BoolTest::ge || bt == BoolTest::gt) && stride_con > 0)) { 525 return false; // Bail out 526 } 527 528 const TypeInt* init_t = gvn->type(init_trip)->is_int(); 529 530 if (stride_con > 0) { 531 jlong init_p = (jlong)init_t->_lo + stride_con; 532 if (init_p > (jlong)max_jint || init_p > (jlong)limit_t->_hi) 533 return false; // cyclic loop or this loop trips only once 534 } else { 535 jlong init_p = (jlong)init_t->_hi + stride_con; 536 if (init_p < (jlong)min_jint || init_p < (jlong)limit_t->_lo) 537 return false; // cyclic loop or this loop trips only once 538 } 539 540 if (phi_incr != NULL) { 541 // check if there is a possiblity of IV overflowing after the first increment 542 if (stride_con > 0) { 543 if (init_t->_hi > max_jint - stride_con) { 544 return false; 545 } 546 } else { 547 if (init_t->_lo < min_jint - stride_con) { 548 return false; 549 } 550 } 551 } 552 553 // ================================================= 554 // ---- SUCCESS! Found A Trip-Counted Loop! ----- 555 // 556 assert(x->Opcode() == Op_Loop, "regular loops only"); 557 C->print_method(PHASE_BEFORE_CLOOPS, 3); 558 559 Node *hook = new Node(6); 560 561 // =================================================== 562 // Generate loop limit check to avoid integer overflow 563 // in cases like next (cyclic loops): 564 // 565 // for (i=0; i <= max_jint; i++) {} 566 // for (i=0; i < max_jint; i+=2) {} 567 // 568 // 569 // Limit check predicate depends on the loop test: 570 // 571 // for(;i != limit; i++) --> limit <= (max_jint) 572 // for(;i < limit; i+=stride) --> limit <= (max_jint - stride + 1) 573 // for(;i <= limit; i+=stride) --> limit <= (max_jint - stride ) 574 // 575 576 // Check if limit is excluded to do more precise int overflow check. 577 bool incl_limit = (bt == BoolTest::le || bt == BoolTest::ge); 578 int stride_m = stride_con - (incl_limit ? 0 : (stride_con > 0 ? 1 : -1)); 579 580 // If compare points directly to the phi we need to adjust 581 // the compare so that it points to the incr. Limit have 582 // to be adjusted to keep trip count the same and the 583 // adjusted limit should be checked for int overflow. 584 if (phi_incr != NULL) { 585 stride_m += stride_con; 586 } 587 588 if (limit->is_Con()) { 589 int limit_con = limit->get_int(); 590 if ((stride_con > 0 && limit_con > (max_jint - stride_m)) || 591 (stride_con < 0 && limit_con < (min_jint - stride_m))) { 592 // Bailout: it could be integer overflow. 593 return false; 594 } 595 } else if ((stride_con > 0 && limit_t->_hi <= (max_jint - stride_m)) || 596 (stride_con < 0 && limit_t->_lo >= (min_jint - stride_m))) { 597 // Limit's type may satisfy the condition, for example, 598 // when it is an array length. 599 } else { 600 // Generate loop's limit check. 601 // Loop limit check predicate should be near the loop. 602 ProjNode *limit_check_proj = find_predicate_insertion_point(init_control, Deoptimization::Reason_loop_limit_check); 603 if (!limit_check_proj) { 604 // The limit check predicate is not generated if this method trapped here before. 605 #ifdef ASSERT 606 if (TraceLoopLimitCheck) { 607 tty->print("missing loop limit check:"); 608 loop->dump_head(); 609 x->dump(1); 610 } 611 #endif 612 return false; 613 } 614 615 IfNode* check_iff = limit_check_proj->in(0)->as_If(); 616 Node* cmp_limit; 617 Node* bol; 618 619 if (stride_con > 0) { 620 cmp_limit = new CmpINode(limit, _igvn.intcon(max_jint - stride_m)); 621 bol = new BoolNode(cmp_limit, BoolTest::le); 622 } else { 623 cmp_limit = new CmpINode(limit, _igvn.intcon(min_jint - stride_m)); 624 bol = new BoolNode(cmp_limit, BoolTest::ge); 625 } 626 cmp_limit = _igvn.register_new_node_with_optimizer(cmp_limit); 627 bol = _igvn.register_new_node_with_optimizer(bol); 628 set_subtree_ctrl(bol); 629 630 // Replace condition in original predicate but preserve Opaque node 631 // so that previous predicates could be found. 632 assert(check_iff->in(1)->Opcode() == Op_Conv2B && 633 check_iff->in(1)->in(1)->Opcode() == Op_Opaque1, ""); 634 Node* opq = check_iff->in(1)->in(1); 635 _igvn.replace_input_of(opq, 1, bol); 636 // Update ctrl. 637 set_ctrl(opq, check_iff->in(0)); 638 set_ctrl(check_iff->in(1), check_iff->in(0)); 639 640 #ifndef PRODUCT 641 // report that the loop predication has been actually performed 642 // for this loop 643 if (TraceLoopLimitCheck) { 644 tty->print_cr("Counted Loop Limit Check generated:"); 645 debug_only( bol->dump(2); ) 646 } 647 #endif 648 } 649 650 if (phi_incr != NULL) { 651 // If compare points directly to the phi we need to adjust 652 // the compare so that it points to the incr. Limit have 653 // to be adjusted to keep trip count the same and we 654 // should avoid int overflow. 655 // 656 // i = init; do {} while(i++ < limit); 657 // is converted to 658 // i = init; do {} while(++i < limit+1); 659 // 660 limit = gvn->transform(new AddINode(limit, stride)); 661 } 662 663 // Now we need to canonicalize loop condition. 664 if (bt == BoolTest::ne) { 665 assert(stride_con == 1 || stride_con == -1, "simple increment only"); 666 // 'ne' can be replaced with 'lt' only when init < limit. 667 if (stride_con > 0 && init_t->_hi < limit_t->_lo) 668 bt = BoolTest::lt; 669 // 'ne' can be replaced with 'gt' only when init > limit. 670 if (stride_con < 0 && init_t->_lo > limit_t->_hi) 671 bt = BoolTest::gt; 672 } 673 674 if (incl_limit) { 675 // The limit check guaranties that 'limit <= (max_jint - stride)' so 676 // we can convert 'i <= limit' to 'i < limit+1' since stride != 0. 677 // 678 Node* one = (stride_con > 0) ? gvn->intcon( 1) : gvn->intcon(-1); 679 limit = gvn->transform(new AddINode(limit, one)); 680 if (bt == BoolTest::le) 681 bt = BoolTest::lt; 682 else if (bt == BoolTest::ge) 683 bt = BoolTest::gt; 684 else 685 ShouldNotReachHere(); 686 } 687 set_subtree_ctrl( limit ); 688 689 if (LoopStripMiningIter == 0) { 690 // Check for SafePoint on backedge and remove 691 Node *sfpt = x->in(LoopNode::LoopBackControl); 692 if (sfpt->Opcode() == Op_SafePoint && is_deleteable_safept(sfpt)) { 693 lazy_replace( sfpt, iftrue ); 694 if (loop->_safepts != NULL) { 695 loop->_safepts->yank(sfpt); 696 } 697 loop->_tail = iftrue; 698 } 699 } 700 701 // Build a canonical trip test. 702 // Clone code, as old values may be in use. 703 incr = incr->clone(); 704 incr->set_req(1,phi); 705 incr->set_req(2,stride); 706 incr = _igvn.register_new_node_with_optimizer(incr); 707 set_early_ctrl( incr ); 708 _igvn.rehash_node_delayed(phi); 709 phi->set_req_X( LoopNode::LoopBackControl, incr, &_igvn ); 710 711 // If phi type is more restrictive than Int, raise to 712 // Int to prevent (almost) infinite recursion in igvn 713 // which can only handle integer types for constants or minint..maxint. 714 if (!TypeInt::INT->higher_equal(phi->bottom_type())) { 715 Node* nphi = PhiNode::make(phi->in(0), phi->in(LoopNode::EntryControl), TypeInt::INT); 716 nphi->set_req(LoopNode::LoopBackControl, phi->in(LoopNode::LoopBackControl)); 717 nphi = _igvn.register_new_node_with_optimizer(nphi); 718 set_ctrl(nphi, get_ctrl(phi)); 719 _igvn.replace_node(phi, nphi); 720 phi = nphi->as_Phi(); 721 } 722 cmp = cmp->clone(); 723 cmp->set_req(1,incr); 724 cmp->set_req(2,limit); 725 cmp = _igvn.register_new_node_with_optimizer(cmp); 726 set_ctrl(cmp, iff->in(0)); 727 728 test = test->clone()->as_Bool(); 729 (*(BoolTest*)&test->_test)._test = bt; 730 test->set_req(1,cmp); 731 _igvn.register_new_node_with_optimizer(test); 732 set_ctrl(test, iff->in(0)); 733 734 // Replace the old IfNode with a new LoopEndNode 735 Node *lex = _igvn.register_new_node_with_optimizer(new CountedLoopEndNode( iff->in(0), test, cl_prob, iff->as_If()->_fcnt )); 736 IfNode *le = lex->as_If(); 737 uint dd = dom_depth(iff); 738 set_idom(le, le->in(0), dd); // Update dominance for loop exit 739 set_loop(le, loop); 740 741 // Get the loop-exit control 742 Node *iffalse = iff->as_If()->proj_out(!(iftrue_op == Op_IfTrue)); 743 744 // Need to swap loop-exit and loop-back control? 745 if (iftrue_op == Op_IfFalse) { 746 Node *ift2=_igvn.register_new_node_with_optimizer(new IfTrueNode (le)); 747 Node *iff2=_igvn.register_new_node_with_optimizer(new IfFalseNode(le)); 748 749 loop->_tail = back_control = ift2; 750 set_loop(ift2, loop); 751 set_loop(iff2, get_loop(iffalse)); 752 753 // Lazy update of 'get_ctrl' mechanism. 754 lazy_replace(iffalse, iff2); 755 lazy_replace(iftrue, ift2); 756 757 // Swap names 758 iffalse = iff2; 759 iftrue = ift2; 760 } else { 761 _igvn.rehash_node_delayed(iffalse); 762 _igvn.rehash_node_delayed(iftrue); 763 iffalse->set_req_X( 0, le, &_igvn ); 764 iftrue ->set_req_X( 0, le, &_igvn ); 765 } 766 767 set_idom(iftrue, le, dd+1); 768 set_idom(iffalse, le, dd+1); 769 assert(iff->outcnt() == 0, "should be dead now"); 770 lazy_replace( iff, le ); // fix 'get_ctrl' 771 772 Node *sfpt2 = le->in(0); 773 774 Node* entry_control = init_control; 775 bool strip_mine_loop = LoopStripMiningIter > 1 && loop->_child == NULL && 776 sfpt2->Opcode() == Op_SafePoint && !loop->_has_call; 777 IdealLoopTree* outer_ilt = NULL; 778 if (strip_mine_loop) { 779 outer_ilt = create_outer_strip_mined_loop(test, cmp, init_control, loop, 780 cl_prob, le->_fcnt, entry_control, 781 iffalse); 782 } 783 784 // Now setup a new CountedLoopNode to replace the existing LoopNode 785 CountedLoopNode *l = new CountedLoopNode(entry_control, back_control); 786 l->set_unswitch_count(x->as_Loop()->unswitch_count()); // Preserve 787 // The following assert is approximately true, and defines the intention 788 // of can_be_counted_loop. It fails, however, because phase->type 789 // is not yet initialized for this loop and its parts. 790 //assert(l->can_be_counted_loop(this), "sanity"); 791 _igvn.register_new_node_with_optimizer(l); 792 set_loop(l, loop); 793 loop->_head = l; 794 // Fix all data nodes placed at the old loop head. 795 // Uses the lazy-update mechanism of 'get_ctrl'. 796 lazy_replace( x, l ); 797 set_idom(l, entry_control, dom_depth(entry_control) + 1); 798 799 if (LoopStripMiningIter == 0 || strip_mine_loop) { 800 // Check for immediately preceding SafePoint and remove 801 if (sfpt2->Opcode() == Op_SafePoint && (LoopStripMiningIter != 0 || is_deleteable_safept(sfpt2))) { 802 if (strip_mine_loop) { 803 Node* outer_le = outer_ilt->_tail->in(0); 804 Node* sfpt = sfpt2->clone(); 805 sfpt->set_req(0, iffalse); 806 outer_le->set_req(0, sfpt); 807 register_control(sfpt, outer_ilt, iffalse); 808 set_idom(outer_le, sfpt, dom_depth(sfpt)); 809 } 810 lazy_replace( sfpt2, sfpt2->in(TypeFunc::Control)); 811 if (loop->_safepts != NULL) { 812 loop->_safepts->yank(sfpt2); 813 } 814 } 815 } 816 817 // Free up intermediate goo 818 _igvn.remove_dead_node(hook); 819 820 #ifdef ASSERT 821 assert(l->is_valid_counted_loop(), "counted loop shape is messed up"); 822 assert(l == loop->_head && l->phi() == phi && l->loopexit_or_null() == lex, "" ); 823 #endif 824 #ifndef PRODUCT 825 if (TraceLoopOpts) { 826 tty->print("Counted "); 827 loop->dump_head(); 828 } 829 #endif 830 831 C->print_method(PHASE_AFTER_CLOOPS, 3); 832 833 // Capture bounds of the loop in the induction variable Phi before 834 // subsequent transformation (iteration splitting) obscures the 835 // bounds 836 l->phi()->as_Phi()->set_type(l->phi()->Value(&_igvn)); 837 838 if (strip_mine_loop) { 839 l->mark_strip_mined(); 840 l->verify_strip_mined(1); 841 outer_ilt->_head->as_Loop()->verify_strip_mined(1); 842 loop = outer_ilt; 843 } 844 845 return true; 846 } 847 848 //----------------------exact_limit------------------------------------------- 849 Node* PhaseIdealLoop::exact_limit( IdealLoopTree *loop ) { 850 assert(loop->_head->is_CountedLoop(), ""); 851 CountedLoopNode *cl = loop->_head->as_CountedLoop(); 852 assert(cl->is_valid_counted_loop(), ""); 853 854 if (ABS(cl->stride_con()) == 1 || 855 cl->limit()->Opcode() == Op_LoopLimit) { 856 // Old code has exact limit (it could be incorrect in case of int overflow). 857 // Loop limit is exact with stride == 1. And loop may already have exact limit. 858 return cl->limit(); 859 } 860 Node *limit = NULL; 861 #ifdef ASSERT 862 BoolTest::mask bt = cl->loopexit()->test_trip(); 863 assert(bt == BoolTest::lt || bt == BoolTest::gt, "canonical test is expected"); 864 #endif 865 if (cl->has_exact_trip_count()) { 866 // Simple case: loop has constant boundaries. 867 // Use jlongs to avoid integer overflow. 868 int stride_con = cl->stride_con(); 869 jlong init_con = cl->init_trip()->get_int(); 870 jlong limit_con = cl->limit()->get_int(); 871 julong trip_cnt = cl->trip_count(); 872 jlong final_con = init_con + trip_cnt*stride_con; 873 int final_int = (int)final_con; 874 // The final value should be in integer range since the loop 875 // is counted and the limit was checked for overflow. 876 assert(final_con == (jlong)final_int, "final value should be integer"); 877 limit = _igvn.intcon(final_int); 878 } else { 879 // Create new LoopLimit node to get exact limit (final iv value). 880 limit = new LoopLimitNode(C, cl->init_trip(), cl->limit(), cl->stride()); 881 register_new_node(limit, cl->in(LoopNode::EntryControl)); 882 } 883 assert(limit != NULL, "sanity"); 884 return limit; 885 } 886 887 //------------------------------Ideal------------------------------------------ 888 // Return a node which is more "ideal" than the current node. 889 // Attempt to convert into a counted-loop. 890 Node *LoopNode::Ideal(PhaseGVN *phase, bool can_reshape) { 891 if (!can_be_counted_loop(phase) && !is_OuterStripMinedLoop()) { 892 phase->C->set_major_progress(); 893 } 894 return RegionNode::Ideal(phase, can_reshape); 895 } 896 897 void LoopNode::verify_strip_mined(int expect_skeleton) const { 898 #ifdef ASSERT 899 const OuterStripMinedLoopNode* outer = NULL; 900 const CountedLoopNode* inner = NULL; 901 if (is_strip_mined()) { 902 assert(is_CountedLoop(), "no Loop should be marked strip mined"); 903 inner = as_CountedLoop(); 904 outer = inner->in(LoopNode::EntryControl)->as_OuterStripMinedLoop(); 905 } else if (is_OuterStripMinedLoop()) { 906 outer = this->as_OuterStripMinedLoop(); 907 inner = outer->unique_ctrl_out()->as_CountedLoop(); 908 assert(!is_strip_mined(), "outer loop shouldn't be marked strip mined"); 909 } 910 if (inner != NULL || outer != NULL) { 911 assert(inner != NULL && outer != NULL, "missing loop in strip mined nest"); 912 Node* outer_tail = outer->in(LoopNode::LoopBackControl); 913 Node* outer_le = outer_tail->in(0); 914 assert(outer_le->Opcode() == Op_OuterStripMinedLoopEnd, "tail of outer loop should be an If"); 915 Node* sfpt = outer_le->in(0); 916 assert(sfpt->Opcode() == Op_SafePoint, "where's the safepoint?"); 917 Node* inner_out = sfpt->in(0); 918 if (inner_out->outcnt() != 1) { 919 ResourceMark rm; 920 Unique_Node_List wq; 921 922 for (DUIterator_Fast imax, i = inner_out->fast_outs(imax); i < imax; i++) { 923 Node* u = inner_out->fast_out(i); 924 if (u == sfpt) { 925 continue; 926 } 927 wq.clear(); 928 wq.push(u); 929 bool found_sfpt = false; 930 for (uint next = 0; next < wq.size() && !found_sfpt; next++) { 931 Node *n = wq.at(next); 932 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax && !found_sfpt; i++) { 933 Node* u = n->fast_out(i); 934 if (u == sfpt) { 935 found_sfpt = true; 936 } 937 if (!u->is_CFG()) { 938 wq.push(u); 939 } 940 } 941 } 942 assert(found_sfpt, "no node in loop that's not input to safepoint"); 943 } 944 } 945 CountedLoopEndNode* cle = inner_out->in(0)->as_CountedLoopEnd(); 946 assert(cle == inner->loopexit_or_null(), "mismatch"); 947 bool has_skeleton = outer_le->in(1)->bottom_type()->singleton() && outer_le->in(1)->bottom_type()->is_int()->get_con() == 0; 948 if (has_skeleton) { 949 assert(expect_skeleton == 1 || expect_skeleton == -1, "unexpected skeleton node"); 950 assert(outer->outcnt() == 2, "only phis"); 951 } else { 952 assert(expect_skeleton == 0 || expect_skeleton == -1, "no skeleton node?"); 953 uint phis = 0; 954 for (DUIterator_Fast imax, i = inner->fast_outs(imax); i < imax; i++) { 955 Node* u = inner->fast_out(i); 956 if (u->is_Phi()) { 957 phis++; 958 } 959 } 960 for (DUIterator_Fast imax, i = outer->fast_outs(imax); i < imax; i++) { 961 Node* u = outer->fast_out(i); 962 assert(u == outer || u == inner || u->is_Phi(), "nothing between inner and outer loop"); 963 } 964 uint stores = 0; 965 for (DUIterator_Fast imax, i = inner_out->fast_outs(imax); i < imax; i++) { 966 Node* u = inner_out->fast_out(i); 967 if (u->is_Store()) { 968 stores++; 969 } 970 } 971 assert(outer->outcnt() >= phis + 2 && outer->outcnt() <= phis + 2 + stores + 1, "only phis"); 972 } 973 assert(sfpt->outcnt() == 1, "no data node"); 974 assert(outer_tail->outcnt() == 1 || !has_skeleton, "no data node"); 975 } 976 #endif 977 } 978 979 //============================================================================= 980 //------------------------------Ideal------------------------------------------ 981 // Return a node which is more "ideal" than the current node. 982 // Attempt to convert into a counted-loop. 983 Node *CountedLoopNode::Ideal(PhaseGVN *phase, bool can_reshape) { 984 return RegionNode::Ideal(phase, can_reshape); 985 } 986 987 //------------------------------dump_spec-------------------------------------- 988 // Dump special per-node info 989 #ifndef PRODUCT 990 void CountedLoopNode::dump_spec(outputStream *st) const { 991 LoopNode::dump_spec(st); 992 if (stride_is_con()) { 993 st->print("stride: %d ",stride_con()); 994 } 995 if (is_pre_loop ()) st->print("pre of N%d" , _main_idx); 996 if (is_main_loop()) st->print("main of N%d", _idx); 997 if (is_post_loop()) st->print("post of N%d", _main_idx); 998 if (is_strip_mined()) st->print(" strip mined"); 999 } 1000 #endif 1001 1002 //============================================================================= 1003 int CountedLoopEndNode::stride_con() const { 1004 return stride()->bottom_type()->is_int()->get_con(); 1005 } 1006 1007 //============================================================================= 1008 //------------------------------Value----------------------------------------- 1009 const Type* LoopLimitNode::Value(PhaseGVN* phase) const { 1010 const Type* init_t = phase->type(in(Init)); 1011 const Type* limit_t = phase->type(in(Limit)); 1012 const Type* stride_t = phase->type(in(Stride)); 1013 // Either input is TOP ==> the result is TOP 1014 if (init_t == Type::TOP) return Type::TOP; 1015 if (limit_t == Type::TOP) return Type::TOP; 1016 if (stride_t == Type::TOP) return Type::TOP; 1017 1018 int stride_con = stride_t->is_int()->get_con(); 1019 if (stride_con == 1) 1020 return NULL; // Identity 1021 1022 if (init_t->is_int()->is_con() && limit_t->is_int()->is_con()) { 1023 // Use jlongs to avoid integer overflow. 1024 jlong init_con = init_t->is_int()->get_con(); 1025 jlong limit_con = limit_t->is_int()->get_con(); 1026 int stride_m = stride_con - (stride_con > 0 ? 1 : -1); 1027 jlong trip_count = (limit_con - init_con + stride_m)/stride_con; 1028 jlong final_con = init_con + stride_con*trip_count; 1029 int final_int = (int)final_con; 1030 // The final value should be in integer range since the loop 1031 // is counted and the limit was checked for overflow. 1032 assert(final_con == (jlong)final_int, "final value should be integer"); 1033 return TypeInt::make(final_int); 1034 } 1035 1036 return bottom_type(); // TypeInt::INT 1037 } 1038 1039 //------------------------------Ideal------------------------------------------ 1040 // Return a node which is more "ideal" than the current node. 1041 Node *LoopLimitNode::Ideal(PhaseGVN *phase, bool can_reshape) { 1042 if (phase->type(in(Init)) == Type::TOP || 1043 phase->type(in(Limit)) == Type::TOP || 1044 phase->type(in(Stride)) == Type::TOP) 1045 return NULL; // Dead 1046 1047 int stride_con = phase->type(in(Stride))->is_int()->get_con(); 1048 if (stride_con == 1) 1049 return NULL; // Identity 1050 1051 if (in(Init)->is_Con() && in(Limit)->is_Con()) 1052 return NULL; // Value 1053 1054 // Delay following optimizations until all loop optimizations 1055 // done to keep Ideal graph simple. 1056 if (!can_reshape || phase->C->major_progress()) 1057 return NULL; 1058 1059 const TypeInt* init_t = phase->type(in(Init) )->is_int(); 1060 const TypeInt* limit_t = phase->type(in(Limit))->is_int(); 1061 int stride_p; 1062 jlong lim, ini; 1063 julong max; 1064 if (stride_con > 0) { 1065 stride_p = stride_con; 1066 lim = limit_t->_hi; 1067 ini = init_t->_lo; 1068 max = (julong)max_jint; 1069 } else { 1070 stride_p = -stride_con; 1071 lim = init_t->_hi; 1072 ini = limit_t->_lo; 1073 max = (julong)min_jint; 1074 } 1075 julong range = lim - ini + stride_p; 1076 if (range <= max) { 1077 // Convert to integer expression if it is not overflow. 1078 Node* stride_m = phase->intcon(stride_con - (stride_con > 0 ? 1 : -1)); 1079 Node *range = phase->transform(new SubINode(in(Limit), in(Init))); 1080 Node *bias = phase->transform(new AddINode(range, stride_m)); 1081 Node *trip = phase->transform(new DivINode(0, bias, in(Stride))); 1082 Node *span = phase->transform(new MulINode(trip, in(Stride))); 1083 return new AddINode(span, in(Init)); // exact limit 1084 } 1085 1086 if (is_power_of_2(stride_p) || // divisor is 2^n 1087 !Matcher::has_match_rule(Op_LoopLimit)) { // or no specialized Mach node? 1088 // Convert to long expression to avoid integer overflow 1089 // and let igvn optimizer convert this division. 1090 // 1091 Node* init = phase->transform( new ConvI2LNode(in(Init))); 1092 Node* limit = phase->transform( new ConvI2LNode(in(Limit))); 1093 Node* stride = phase->longcon(stride_con); 1094 Node* stride_m = phase->longcon(stride_con - (stride_con > 0 ? 1 : -1)); 1095 1096 Node *range = phase->transform(new SubLNode(limit, init)); 1097 Node *bias = phase->transform(new AddLNode(range, stride_m)); 1098 Node *span; 1099 if (stride_con > 0 && is_power_of_2(stride_p)) { 1100 // bias >= 0 if stride >0, so if stride is 2^n we can use &(-stride) 1101 // and avoid generating rounding for division. Zero trip guard should 1102 // guarantee that init < limit but sometimes the guard is missing and 1103 // we can get situation when init > limit. Note, for the empty loop 1104 // optimization zero trip guard is generated explicitly which leaves 1105 // only RCE predicate where exact limit is used and the predicate 1106 // will simply fail forcing recompilation. 1107 Node* neg_stride = phase->longcon(-stride_con); 1108 span = phase->transform(new AndLNode(bias, neg_stride)); 1109 } else { 1110 Node *trip = phase->transform(new DivLNode(0, bias, stride)); 1111 span = phase->transform(new MulLNode(trip, stride)); 1112 } 1113 // Convert back to int 1114 Node *span_int = phase->transform(new ConvL2INode(span)); 1115 return new AddINode(span_int, in(Init)); // exact limit 1116 } 1117 1118 return NULL; // No progress 1119 } 1120 1121 //------------------------------Identity--------------------------------------- 1122 // If stride == 1 return limit node. 1123 Node* LoopLimitNode::Identity(PhaseGVN* phase) { 1124 int stride_con = phase->type(in(Stride))->is_int()->get_con(); 1125 if (stride_con == 1 || stride_con == -1) 1126 return in(Limit); 1127 return this; 1128 } 1129 1130 //============================================================================= 1131 //----------------------match_incr_with_optional_truncation-------------------- 1132 // Match increment with optional truncation: 1133 // CHAR: (i+1)&0x7fff, BYTE: ((i+1)<<8)>>8, or SHORT: ((i+1)<<16)>>16 1134 // Return NULL for failure. Success returns the increment node. 1135 Node* CountedLoopNode::match_incr_with_optional_truncation( 1136 Node* expr, Node** trunc1, Node** trunc2, const TypeInt** trunc_type) { 1137 // Quick cutouts: 1138 if (expr == NULL || expr->req() != 3) return NULL; 1139 1140 Node *t1 = NULL; 1141 Node *t2 = NULL; 1142 const TypeInt* trunc_t = TypeInt::INT; 1143 Node* n1 = expr; 1144 int n1op = n1->Opcode(); 1145 1146 // Try to strip (n1 & M) or (n1 << N >> N) from n1. 1147 if (n1op == Op_AndI && 1148 n1->in(2)->is_Con() && 1149 n1->in(2)->bottom_type()->is_int()->get_con() == 0x7fff) { 1150 // %%% This check should match any mask of 2**K-1. 1151 t1 = n1; 1152 n1 = t1->in(1); 1153 n1op = n1->Opcode(); 1154 trunc_t = TypeInt::CHAR; 1155 } else if (n1op == Op_RShiftI && 1156 n1->in(1) != NULL && 1157 n1->in(1)->Opcode() == Op_LShiftI && 1158 n1->in(2) == n1->in(1)->in(2) && 1159 n1->in(2)->is_Con()) { 1160 jint shift = n1->in(2)->bottom_type()->is_int()->get_con(); 1161 // %%% This check should match any shift in [1..31]. 1162 if (shift == 16 || shift == 8) { 1163 t1 = n1; 1164 t2 = t1->in(1); 1165 n1 = t2->in(1); 1166 n1op = n1->Opcode(); 1167 if (shift == 16) { 1168 trunc_t = TypeInt::SHORT; 1169 } else if (shift == 8) { 1170 trunc_t = TypeInt::BYTE; 1171 } 1172 } 1173 } 1174 1175 // If (maybe after stripping) it is an AddI, we won: 1176 if (n1op == Op_AddI) { 1177 *trunc1 = t1; 1178 *trunc2 = t2; 1179 *trunc_type = trunc_t; 1180 return n1; 1181 } 1182 1183 // failed 1184 return NULL; 1185 } 1186 1187 LoopNode* CountedLoopNode::skip_strip_mined(int expect_skeleton) { 1188 if (is_strip_mined()) { 1189 verify_strip_mined(expect_skeleton); 1190 return in(EntryControl)->as_Loop(); 1191 } 1192 return this; 1193 } 1194 1195 OuterStripMinedLoopNode* CountedLoopNode::outer_loop() const { 1196 assert(is_strip_mined(), "not a strip mined loop"); 1197 Node* c = in(EntryControl); 1198 if (c == NULL || c->is_top() || !c->is_OuterStripMinedLoop()) { 1199 return NULL; 1200 } 1201 return c->as_OuterStripMinedLoop(); 1202 } 1203 1204 IfTrueNode* OuterStripMinedLoopNode::outer_loop_tail() const { 1205 Node* c = in(LoopBackControl); 1206 if (c == NULL || c->is_top()) { 1207 return NULL; 1208 } 1209 return c->as_IfTrue(); 1210 } 1211 1212 IfTrueNode* CountedLoopNode::outer_loop_tail() const { 1213 LoopNode* l = outer_loop(); 1214 if (l == NULL) { 1215 return NULL; 1216 } 1217 return l->outer_loop_tail(); 1218 } 1219 1220 OuterStripMinedLoopEndNode* OuterStripMinedLoopNode::outer_loop_end() const { 1221 IfTrueNode* proj = outer_loop_tail(); 1222 if (proj == NULL) { 1223 return NULL; 1224 } 1225 Node* c = proj->in(0); 1226 if (c == NULL || c->is_top() || c->outcnt() != 2) { 1227 return NULL; 1228 } 1229 return c->as_OuterStripMinedLoopEnd(); 1230 } 1231 1232 OuterStripMinedLoopEndNode* CountedLoopNode::outer_loop_end() const { 1233 LoopNode* l = outer_loop(); 1234 if (l == NULL) { 1235 return NULL; 1236 } 1237 return l->outer_loop_end(); 1238 } 1239 1240 IfFalseNode* OuterStripMinedLoopNode::outer_loop_exit() const { 1241 IfNode* le = outer_loop_end(); 1242 if (le == NULL) { 1243 return NULL; 1244 } 1245 Node* c = le->proj_out_or_null(false); 1246 if (c == NULL) { 1247 return NULL; 1248 } 1249 return c->as_IfFalse(); 1250 } 1251 1252 IfFalseNode* CountedLoopNode::outer_loop_exit() const { 1253 LoopNode* l = outer_loop(); 1254 if (l == NULL) { 1255 return NULL; 1256 } 1257 return l->outer_loop_exit(); 1258 } 1259 1260 SafePointNode* OuterStripMinedLoopNode::outer_safepoint() const { 1261 IfNode* le = outer_loop_end(); 1262 if (le == NULL) { 1263 return NULL; 1264 } 1265 Node* c = le->in(0); 1266 if (c == NULL || c->is_top()) { 1267 return NULL; 1268 } 1269 assert(c->Opcode() == Op_SafePoint, "broken outer loop"); 1270 return c->as_SafePoint(); 1271 } 1272 1273 SafePointNode* CountedLoopNode::outer_safepoint() const { 1274 LoopNode* l = outer_loop(); 1275 if (l == NULL) { 1276 return NULL; 1277 } 1278 return l->outer_safepoint(); 1279 } 1280 1281 Node* CountedLoopNode::skip_predicates() { 1282 if (is_main_loop()) { 1283 Node* ctrl = skip_strip_mined()->in(LoopNode::EntryControl); 1284 while (ctrl != NULL && ctrl->is_Proj() && ctrl->in(0)->is_If() && 1285 ctrl->in(0)->as_If()->proj_out(1-ctrl->as_Proj()->_con)->outcnt() == 1 && 1286 ctrl->in(0)->as_If()->proj_out(1-ctrl->as_Proj()->_con)->unique_out()->Opcode() == Op_Halt) { 1287 ctrl = ctrl->in(0)->in(0); 1288 } 1289 1290 return ctrl; 1291 } 1292 return in(LoopNode::EntryControl); 1293 } 1294 1295 void OuterStripMinedLoopNode::adjust_strip_mined_loop(PhaseIterGVN* igvn) { 1296 // Look for the outer & inner strip mined loop, reduce number of 1297 // iterations of the inner loop, set exit condition of outer loop, 1298 // construct required phi nodes for outer loop. 1299 CountedLoopNode* inner_cl = unique_ctrl_out()->as_CountedLoop(); 1300 assert(inner_cl->is_strip_mined(), "inner loop should be strip mined"); 1301 Node* inner_iv_phi = inner_cl->phi(); 1302 if (inner_iv_phi == NULL) { 1303 IfNode* outer_le = outer_loop_end(); 1304 Node* iff = igvn->transform(new IfNode(outer_le->in(0), outer_le->in(1), outer_le->_prob, outer_le->_fcnt)); 1305 igvn->replace_node(outer_le, iff); 1306 inner_cl->clear_strip_mined(); 1307 return; 1308 } 1309 CountedLoopEndNode* inner_cle = inner_cl->loopexit(); 1310 1311 int stride = inner_cl->stride_con(); 1312 jlong scaled_iters_long = ((jlong)LoopStripMiningIter) * ABS(stride); 1313 int scaled_iters = (int)scaled_iters_long; 1314 int short_scaled_iters = LoopStripMiningIterShortLoop* ABS(stride); 1315 const TypeInt* inner_iv_t = igvn->type(inner_iv_phi)->is_int(); 1316 jlong iter_estimate = (jlong)inner_iv_t->_hi - (jlong)inner_iv_t->_lo; 1317 assert(iter_estimate > 0, "broken"); 1318 if ((jlong)scaled_iters != scaled_iters_long || iter_estimate <= short_scaled_iters) { 1319 // Remove outer loop and safepoint (too few iterations) 1320 Node* outer_sfpt = outer_safepoint(); 1321 Node* outer_out = outer_loop_exit(); 1322 igvn->replace_node(outer_out, outer_sfpt->in(0)); 1323 igvn->replace_input_of(outer_sfpt, 0, igvn->C->top()); 1324 inner_cl->clear_strip_mined(); 1325 return; 1326 } 1327 if (iter_estimate <= scaled_iters_long) { 1328 // We would only go through one iteration of 1329 // the outer loop: drop the outer loop but 1330 // keep the safepoint so we don't run for 1331 // too long without a safepoint 1332 IfNode* outer_le = outer_loop_end(); 1333 Node* iff = igvn->transform(new IfNode(outer_le->in(0), outer_le->in(1), outer_le->_prob, outer_le->_fcnt)); 1334 igvn->replace_node(outer_le, iff); 1335 inner_cl->clear_strip_mined(); 1336 return; 1337 } 1338 1339 Node* cle_tail = inner_cle->proj_out(true); 1340 ResourceMark rm; 1341 Node_List old_new; 1342 if (cle_tail->outcnt() > 1) { 1343 // Look for nodes on backedge of inner loop and clone them 1344 Unique_Node_List backedge_nodes; 1345 for (DUIterator_Fast imax, i = cle_tail->fast_outs(imax); i < imax; i++) { 1346 Node* u = cle_tail->fast_out(i); 1347 if (u != inner_cl) { 1348 assert(!u->is_CFG(), "control flow on the backedge?"); 1349 backedge_nodes.push(u); 1350 } 1351 } 1352 uint last = igvn->C->unique(); 1353 for (uint next = 0; next < backedge_nodes.size(); next++) { 1354 Node* n = backedge_nodes.at(next); 1355 old_new.map(n->_idx, n->clone()); 1356 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) { 1357 Node* u = n->fast_out(i); 1358 assert(!u->is_CFG(), "broken"); 1359 if (u->_idx >= last) { 1360 continue; 1361 } 1362 if (!u->is_Phi()) { 1363 backedge_nodes.push(u); 1364 } else { 1365 assert(u->in(0) == inner_cl, "strange phi on the backedge"); 1366 } 1367 } 1368 } 1369 // Put the clones on the outer loop backedge 1370 Node* le_tail = outer_loop_tail(); 1371 for (uint next = 0; next < backedge_nodes.size(); next++) { 1372 Node *n = old_new[backedge_nodes.at(next)->_idx]; 1373 for (uint i = 1; i < n->req(); i++) { 1374 if (n->in(i) != NULL && old_new[n->in(i)->_idx] != NULL) { 1375 n->set_req(i, old_new[n->in(i)->_idx]); 1376 } 1377 } 1378 if (n->in(0) != NULL && n->in(0) == cle_tail) { 1379 n->set_req(0, le_tail); 1380 } 1381 igvn->register_new_node_with_optimizer(n); 1382 } 1383 } 1384 1385 Node* iv_phi = NULL; 1386 // Make a clone of each phi in the inner loop 1387 // for the outer loop 1388 for (uint i = 0; i < inner_cl->outcnt(); i++) { 1389 Node* u = inner_cl->raw_out(i); 1390 if (u->is_Phi()) { 1391 assert(u->in(0) == inner_cl, "inconsistent"); 1392 Node* phi = u->clone(); 1393 phi->set_req(0, this); 1394 Node* be = old_new[phi->in(LoopNode::LoopBackControl)->_idx]; 1395 if (be != NULL) { 1396 phi->set_req(LoopNode::LoopBackControl, be); 1397 } 1398 phi = igvn->transform(phi); 1399 igvn->replace_input_of(u, LoopNode::EntryControl, phi); 1400 if (u == inner_iv_phi) { 1401 iv_phi = phi; 1402 } 1403 } 1404 } 1405 Node* cle_out = inner_cle->proj_out(false); 1406 if (cle_out->outcnt() > 1) { 1407 // Look for chains of stores that were sunk 1408 // out of the inner loop and are in the outer loop 1409 for (DUIterator_Fast imax, i = cle_out->fast_outs(imax); i < imax; i++) { 1410 Node* u = cle_out->fast_out(i); 1411 if (u->is_Store()) { 1412 Node* first = u; 1413 for(;;) { 1414 Node* next = first->in(MemNode::Memory); 1415 if (!next->is_Store() || next->in(0) != cle_out) { 1416 break; 1417 } 1418 first = next; 1419 } 1420 Node* last = u; 1421 for(;;) { 1422 Node* next = NULL; 1423 for (DUIterator_Fast jmax, j = last->fast_outs(jmax); j < jmax; j++) { 1424 Node* uu = last->fast_out(j); 1425 if (uu->is_Store() && uu->in(0) == cle_out) { 1426 assert(next == NULL, "only one in the outer loop"); 1427 next = uu; 1428 } 1429 } 1430 if (next == NULL) { 1431 break; 1432 } 1433 last = next; 1434 } 1435 Node* phi = NULL; 1436 for (DUIterator_Fast jmax, j = fast_outs(jmax); j < jmax; j++) { 1437 Node* uu = fast_out(j); 1438 if (uu->is_Phi()) { 1439 Node* be = uu->in(LoopNode::LoopBackControl); 1440 if (be->is_Store() && old_new[be->_idx] != NULL) { 1441 assert(false, "store on the backedge + sunk stores: unsupported"); 1442 // drop outer loop 1443 IfNode* outer_le = outer_loop_end(); 1444 Node* iff = igvn->transform(new IfNode(outer_le->in(0), outer_le->in(1), outer_le->_prob, outer_le->_fcnt)); 1445 igvn->replace_node(outer_le, iff); 1446 inner_cl->clear_strip_mined(); 1447 return; 1448 } 1449 if (be == last || be == first->in(MemNode::Memory)) { 1450 assert(phi == NULL, "only one phi"); 1451 phi = uu; 1452 } 1453 } 1454 } 1455 #ifdef ASSERT 1456 for (DUIterator_Fast jmax, j = fast_outs(jmax); j < jmax; j++) { 1457 Node* uu = fast_out(j); 1458 if (uu->is_Phi() && uu->bottom_type() == Type::MEMORY) { 1459 if (uu->adr_type() == igvn->C->get_adr_type(igvn->C->get_alias_index(u->adr_type()))) { 1460 assert(phi == uu, "what's that phi?"); 1461 } else if (uu->adr_type() == TypePtr::BOTTOM) { 1462 Node* n = uu->in(LoopNode::LoopBackControl); 1463 uint limit = igvn->C->live_nodes(); 1464 uint i = 0; 1465 while (n != uu) { 1466 i++; 1467 assert(i < limit, "infinite loop"); 1468 if (n->is_Proj()) { 1469 n = n->in(0); 1470 } else if (n->is_SafePoint() || n->is_MemBar()) { 1471 n = n->in(TypeFunc::Memory); 1472 } else if (n->is_Phi()) { 1473 n = n->in(1); 1474 } else if (n->is_MergeMem()) { 1475 n = n->as_MergeMem()->memory_at(igvn->C->get_alias_index(u->adr_type())); 1476 } else if (n->is_Store() || n->is_LoadStore() || n->is_ClearArray()) { 1477 n = n->in(MemNode::Memory); 1478 } else { 1479 n->dump(); 1480 ShouldNotReachHere(); 1481 } 1482 } 1483 } 1484 } 1485 } 1486 #endif 1487 if (phi == NULL) { 1488 // If the an entire chains was sunk, the 1489 // inner loop has no phi for that memory 1490 // slice, create one for the outer loop 1491 phi = PhiNode::make(this, first->in(MemNode::Memory), Type::MEMORY, 1492 igvn->C->get_adr_type(igvn->C->get_alias_index(u->adr_type()))); 1493 phi->set_req(LoopNode::LoopBackControl, last); 1494 phi = igvn->transform(phi); 1495 igvn->replace_input_of(first, MemNode::Memory, phi); 1496 } else { 1497 // Or fix the outer loop fix to include 1498 // that chain of stores. 1499 Node* be = phi->in(LoopNode::LoopBackControl); 1500 assert(!(be->is_Store() && old_new[be->_idx] != NULL), "store on the backedge + sunk stores: unsupported"); 1501 if (be == first->in(MemNode::Memory)) { 1502 if (be == phi->in(LoopNode::LoopBackControl)) { 1503 igvn->replace_input_of(phi, LoopNode::LoopBackControl, last); 1504 } else { 1505 igvn->replace_input_of(be, MemNode::Memory, last); 1506 } 1507 } else { 1508 #ifdef ASSERT 1509 if (be == phi->in(LoopNode::LoopBackControl)) { 1510 assert(phi->in(LoopNode::LoopBackControl) == last, ""); 1511 } else { 1512 assert(be->in(MemNode::Memory) == last, ""); 1513 } 1514 #endif 1515 } 1516 } 1517 } 1518 } 1519 } 1520 1521 if (iv_phi != NULL) { 1522 // Now adjust the inner loop's exit condition 1523 Node* limit = inner_cl->limit(); 1524 Node* sub = NULL; 1525 if (stride > 0) { 1526 sub = igvn->transform(new SubINode(limit, iv_phi)); 1527 } else { 1528 sub = igvn->transform(new SubINode(iv_phi, limit)); 1529 } 1530 Node* min = igvn->transform(new MinINode(sub, igvn->intcon(scaled_iters))); 1531 Node* new_limit = NULL; 1532 if (stride > 0) { 1533 new_limit = igvn->transform(new AddINode(min, iv_phi)); 1534 } else { 1535 new_limit = igvn->transform(new SubINode(iv_phi, min)); 1536 } 1537 Node* cmp = inner_cle->cmp_node()->clone(); 1538 igvn->replace_input_of(cmp, 2, new_limit); 1539 Node* bol = inner_cle->in(CountedLoopEndNode::TestValue)->clone(); 1540 cmp->set_req(2, limit); 1541 bol->set_req(1, igvn->transform(cmp)); 1542 igvn->replace_input_of(outer_loop_end(), 1, igvn->transform(bol)); 1543 } else { 1544 assert(false, "should be able to adjust outer loop"); 1545 IfNode* outer_le = outer_loop_end(); 1546 Node* iff = igvn->transform(new IfNode(outer_le->in(0), outer_le->in(1), outer_le->_prob, outer_le->_fcnt)); 1547 igvn->replace_node(outer_le, iff); 1548 inner_cl->clear_strip_mined(); 1549 } 1550 } 1551 1552 const Type* OuterStripMinedLoopEndNode::Value(PhaseGVN* phase) const { 1553 if (!in(0)) return Type::TOP; 1554 if (phase->type(in(0)) == Type::TOP) 1555 return Type::TOP; 1556 1557 return TypeTuple::IFBOTH; 1558 } 1559 1560 Node *OuterStripMinedLoopEndNode::Ideal(PhaseGVN *phase, bool can_reshape) { 1561 if (remove_dead_region(phase, can_reshape)) return this; 1562 1563 return NULL; 1564 } 1565 1566 //------------------------------filtered_type-------------------------------- 1567 // Return a type based on condition control flow 1568 // A successful return will be a type that is restricted due 1569 // to a series of dominating if-tests, such as: 1570 // if (i < 10) { 1571 // if (i > 0) { 1572 // here: "i" type is [1..10) 1573 // } 1574 // } 1575 // or a control flow merge 1576 // if (i < 10) { 1577 // do { 1578 // phi( , ) -- at top of loop type is [min_int..10) 1579 // i = ? 1580 // } while ( i < 10) 1581 // 1582 const TypeInt* PhaseIdealLoop::filtered_type( Node *n, Node* n_ctrl) { 1583 assert(n && n->bottom_type()->is_int(), "must be int"); 1584 const TypeInt* filtered_t = NULL; 1585 if (!n->is_Phi()) { 1586 assert(n_ctrl != NULL || n_ctrl == C->top(), "valid control"); 1587 filtered_t = filtered_type_from_dominators(n, n_ctrl); 1588 1589 } else { 1590 Node* phi = n->as_Phi(); 1591 Node* region = phi->in(0); 1592 assert(n_ctrl == NULL || n_ctrl == region, "ctrl parameter must be region"); 1593 if (region && region != C->top()) { 1594 for (uint i = 1; i < phi->req(); i++) { 1595 Node* val = phi->in(i); 1596 Node* use_c = region->in(i); 1597 const TypeInt* val_t = filtered_type_from_dominators(val, use_c); 1598 if (val_t != NULL) { 1599 if (filtered_t == NULL) { 1600 filtered_t = val_t; 1601 } else { 1602 filtered_t = filtered_t->meet(val_t)->is_int(); 1603 } 1604 } 1605 } 1606 } 1607 } 1608 const TypeInt* n_t = _igvn.type(n)->is_int(); 1609 if (filtered_t != NULL) { 1610 n_t = n_t->join(filtered_t)->is_int(); 1611 } 1612 return n_t; 1613 } 1614 1615 1616 //------------------------------filtered_type_from_dominators-------------------------------- 1617 // Return a possibly more restrictive type for val based on condition control flow of dominators 1618 const TypeInt* PhaseIdealLoop::filtered_type_from_dominators( Node* val, Node *use_ctrl) { 1619 if (val->is_Con()) { 1620 return val->bottom_type()->is_int(); 1621 } 1622 uint if_limit = 10; // Max number of dominating if's visited 1623 const TypeInt* rtn_t = NULL; 1624 1625 if (use_ctrl && use_ctrl != C->top()) { 1626 Node* val_ctrl = get_ctrl(val); 1627 uint val_dom_depth = dom_depth(val_ctrl); 1628 Node* pred = use_ctrl; 1629 uint if_cnt = 0; 1630 while (if_cnt < if_limit) { 1631 if ((pred->Opcode() == Op_IfTrue || pred->Opcode() == Op_IfFalse)) { 1632 if_cnt++; 1633 const TypeInt* if_t = IfNode::filtered_int_type(&_igvn, val, pred); 1634 if (if_t != NULL) { 1635 if (rtn_t == NULL) { 1636 rtn_t = if_t; 1637 } else { 1638 rtn_t = rtn_t->join(if_t)->is_int(); 1639 } 1640 } 1641 } 1642 pred = idom(pred); 1643 if (pred == NULL || pred == C->top()) { 1644 break; 1645 } 1646 // Stop if going beyond definition block of val 1647 if (dom_depth(pred) < val_dom_depth) { 1648 break; 1649 } 1650 } 1651 } 1652 return rtn_t; 1653 } 1654 1655 1656 //------------------------------dump_spec-------------------------------------- 1657 // Dump special per-node info 1658 #ifndef PRODUCT 1659 void CountedLoopEndNode::dump_spec(outputStream *st) const { 1660 if( in(TestValue) != NULL && in(TestValue)->is_Bool() ) { 1661 BoolTest bt( test_trip()); // Added this for g++. 1662 1663 st->print("["); 1664 bt.dump_on(st); 1665 st->print("]"); 1666 } 1667 st->print(" "); 1668 IfNode::dump_spec(st); 1669 } 1670 #endif 1671 1672 //============================================================================= 1673 //------------------------------is_member-------------------------------------- 1674 // Is 'l' a member of 'this'? 1675 bool IdealLoopTree::is_member(const IdealLoopTree *l) const { 1676 while( l->_nest > _nest ) l = l->_parent; 1677 return l == this; 1678 } 1679 1680 //------------------------------set_nest--------------------------------------- 1681 // Set loop tree nesting depth. Accumulate _has_call bits. 1682 int IdealLoopTree::set_nest( uint depth ) { 1683 _nest = depth; 1684 int bits = _has_call; 1685 if( _child ) bits |= _child->set_nest(depth+1); 1686 if( bits ) _has_call = 1; 1687 if( _next ) bits |= _next ->set_nest(depth ); 1688 return bits; 1689 } 1690 1691 //------------------------------split_fall_in---------------------------------- 1692 // Split out multiple fall-in edges from the loop header. Move them to a 1693 // private RegionNode before the loop. This becomes the loop landing pad. 1694 void IdealLoopTree::split_fall_in( PhaseIdealLoop *phase, int fall_in_cnt ) { 1695 PhaseIterGVN &igvn = phase->_igvn; 1696 uint i; 1697 1698 // Make a new RegionNode to be the landing pad. 1699 Node *landing_pad = new RegionNode( fall_in_cnt+1 ); 1700 phase->set_loop(landing_pad,_parent); 1701 // Gather all the fall-in control paths into the landing pad 1702 uint icnt = fall_in_cnt; 1703 uint oreq = _head->req(); 1704 for( i = oreq-1; i>0; i-- ) 1705 if( !phase->is_member( this, _head->in(i) ) ) 1706 landing_pad->set_req(icnt--,_head->in(i)); 1707 1708 // Peel off PhiNode edges as well 1709 for (DUIterator_Fast jmax, j = _head->fast_outs(jmax); j < jmax; j++) { 1710 Node *oj = _head->fast_out(j); 1711 if( oj->is_Phi() ) { 1712 PhiNode* old_phi = oj->as_Phi(); 1713 assert( old_phi->region() == _head, "" ); 1714 igvn.hash_delete(old_phi); // Yank from hash before hacking edges 1715 Node *p = PhiNode::make_blank(landing_pad, old_phi); 1716 uint icnt = fall_in_cnt; 1717 for( i = oreq-1; i>0; i-- ) { 1718 if( !phase->is_member( this, _head->in(i) ) ) { 1719 p->init_req(icnt--, old_phi->in(i)); 1720 // Go ahead and clean out old edges from old phi 1721 old_phi->del_req(i); 1722 } 1723 } 1724 // Search for CSE's here, because ZKM.jar does a lot of 1725 // loop hackery and we need to be a little incremental 1726 // with the CSE to avoid O(N^2) node blow-up. 1727 Node *p2 = igvn.hash_find_insert(p); // Look for a CSE 1728 if( p2 ) { // Found CSE 1729 p->destruct(); // Recover useless new node 1730 p = p2; // Use old node 1731 } else { 1732 igvn.register_new_node_with_optimizer(p, old_phi); 1733 } 1734 // Make old Phi refer to new Phi. 1735 old_phi->add_req(p); 1736 // Check for the special case of making the old phi useless and 1737 // disappear it. In JavaGrande I have a case where this useless 1738 // Phi is the loop limit and prevents recognizing a CountedLoop 1739 // which in turn prevents removing an empty loop. 1740 Node *id_old_phi = old_phi->Identity( &igvn ); 1741 if( id_old_phi != old_phi ) { // Found a simple identity? 1742 // Note that I cannot call 'replace_node' here, because 1743 // that will yank the edge from old_phi to the Region and 1744 // I'm mid-iteration over the Region's uses. 1745 for (DUIterator_Last imin, i = old_phi->last_outs(imin); i >= imin; ) { 1746 Node* use = old_phi->last_out(i); 1747 igvn.rehash_node_delayed(use); 1748 uint uses_found = 0; 1749 for (uint j = 0; j < use->len(); j++) { 1750 if (use->in(j) == old_phi) { 1751 if (j < use->req()) use->set_req (j, id_old_phi); 1752 else use->set_prec(j, id_old_phi); 1753 uses_found++; 1754 } 1755 } 1756 i -= uses_found; // we deleted 1 or more copies of this edge 1757 } 1758 } 1759 igvn._worklist.push(old_phi); 1760 } 1761 } 1762 // Finally clean out the fall-in edges from the RegionNode 1763 for( i = oreq-1; i>0; i-- ) { 1764 if( !phase->is_member( this, _head->in(i) ) ) { 1765 _head->del_req(i); 1766 } 1767 } 1768 igvn.rehash_node_delayed(_head); 1769 // Transform landing pad 1770 igvn.register_new_node_with_optimizer(landing_pad, _head); 1771 // Insert landing pad into the header 1772 _head->add_req(landing_pad); 1773 } 1774 1775 //------------------------------split_outer_loop------------------------------- 1776 // Split out the outermost loop from this shared header. 1777 void IdealLoopTree::split_outer_loop( PhaseIdealLoop *phase ) { 1778 PhaseIterGVN &igvn = phase->_igvn; 1779 1780 // Find index of outermost loop; it should also be my tail. 1781 uint outer_idx = 1; 1782 while( _head->in(outer_idx) != _tail ) outer_idx++; 1783 1784 // Make a LoopNode for the outermost loop. 1785 Node *ctl = _head->in(LoopNode::EntryControl); 1786 Node *outer = new LoopNode( ctl, _head->in(outer_idx) ); 1787 outer = igvn.register_new_node_with_optimizer(outer, _head); 1788 phase->set_created_loop_node(); 1789 1790 // Outermost loop falls into '_head' loop 1791 _head->set_req(LoopNode::EntryControl, outer); 1792 _head->del_req(outer_idx); 1793 // Split all the Phis up between '_head' loop and 'outer' loop. 1794 for (DUIterator_Fast jmax, j = _head->fast_outs(jmax); j < jmax; j++) { 1795 Node *out = _head->fast_out(j); 1796 if( out->is_Phi() ) { 1797 PhiNode *old_phi = out->as_Phi(); 1798 assert( old_phi->region() == _head, "" ); 1799 Node *phi = PhiNode::make_blank(outer, old_phi); 1800 phi->init_req(LoopNode::EntryControl, old_phi->in(LoopNode::EntryControl)); 1801 phi->init_req(LoopNode::LoopBackControl, old_phi->in(outer_idx)); 1802 phi = igvn.register_new_node_with_optimizer(phi, old_phi); 1803 // Make old Phi point to new Phi on the fall-in path 1804 igvn.replace_input_of(old_phi, LoopNode::EntryControl, phi); 1805 old_phi->del_req(outer_idx); 1806 } 1807 } 1808 1809 // Use the new loop head instead of the old shared one 1810 _head = outer; 1811 phase->set_loop(_head, this); 1812 } 1813 1814 //------------------------------fix_parent------------------------------------- 1815 static void fix_parent( IdealLoopTree *loop, IdealLoopTree *parent ) { 1816 loop->_parent = parent; 1817 if( loop->_child ) fix_parent( loop->_child, loop ); 1818 if( loop->_next ) fix_parent( loop->_next , parent ); 1819 } 1820 1821 //------------------------------estimate_path_freq----------------------------- 1822 static float estimate_path_freq( Node *n ) { 1823 // Try to extract some path frequency info 1824 IfNode *iff; 1825 for( int i = 0; i < 50; i++ ) { // Skip through a bunch of uncommon tests 1826 uint nop = n->Opcode(); 1827 if( nop == Op_SafePoint ) { // Skip any safepoint 1828 n = n->in(0); 1829 continue; 1830 } 1831 if( nop == Op_CatchProj ) { // Get count from a prior call 1832 // Assume call does not always throw exceptions: means the call-site 1833 // count is also the frequency of the fall-through path. 1834 assert( n->is_CatchProj(), "" ); 1835 if( ((CatchProjNode*)n)->_con != CatchProjNode::fall_through_index ) 1836 return 0.0f; // Assume call exception path is rare 1837 Node *call = n->in(0)->in(0)->in(0); 1838 assert( call->is_Call(), "expect a call here" ); 1839 const JVMState *jvms = ((CallNode*)call)->jvms(); 1840 ciMethodData* methodData = jvms->method()->method_data(); 1841 if (!methodData->is_mature()) return 0.0f; // No call-site data 1842 ciProfileData* data = methodData->bci_to_data(jvms->bci()); 1843 if ((data == NULL) || !data->is_CounterData()) { 1844 // no call profile available, try call's control input 1845 n = n->in(0); 1846 continue; 1847 } 1848 return data->as_CounterData()->count()/FreqCountInvocations; 1849 } 1850 // See if there's a gating IF test 1851 Node *n_c = n->in(0); 1852 if( !n_c->is_If() ) break; // No estimate available 1853 iff = n_c->as_If(); 1854 if( iff->_fcnt != COUNT_UNKNOWN ) // Have a valid count? 1855 // Compute how much count comes on this path 1856 return ((nop == Op_IfTrue) ? iff->_prob : 1.0f - iff->_prob) * iff->_fcnt; 1857 // Have no count info. Skip dull uncommon-trap like branches. 1858 if( (nop == Op_IfTrue && iff->_prob < PROB_LIKELY_MAG(5)) || 1859 (nop == Op_IfFalse && iff->_prob > PROB_UNLIKELY_MAG(5)) ) 1860 break; 1861 // Skip through never-taken branch; look for a real loop exit. 1862 n = iff->in(0); 1863 } 1864 return 0.0f; // No estimate available 1865 } 1866 1867 //------------------------------merge_many_backedges--------------------------- 1868 // Merge all the backedges from the shared header into a private Region. 1869 // Feed that region as the one backedge to this loop. 1870 void IdealLoopTree::merge_many_backedges( PhaseIdealLoop *phase ) { 1871 uint i; 1872 1873 // Scan for the top 2 hottest backedges 1874 float hotcnt = 0.0f; 1875 float warmcnt = 0.0f; 1876 uint hot_idx = 0; 1877 // Loop starts at 2 because slot 1 is the fall-in path 1878 for( i = 2; i < _head->req(); i++ ) { 1879 float cnt = estimate_path_freq(_head->in(i)); 1880 if( cnt > hotcnt ) { // Grab hottest path 1881 warmcnt = hotcnt; 1882 hotcnt = cnt; 1883 hot_idx = i; 1884 } else if( cnt > warmcnt ) { // And 2nd hottest path 1885 warmcnt = cnt; 1886 } 1887 } 1888 1889 // See if the hottest backedge is worthy of being an inner loop 1890 // by being much hotter than the next hottest backedge. 1891 if( hotcnt <= 0.0001 || 1892 hotcnt < 2.0*warmcnt ) hot_idx = 0;// No hot backedge 1893 1894 // Peel out the backedges into a private merge point; peel 1895 // them all except optionally hot_idx. 1896 PhaseIterGVN &igvn = phase->_igvn; 1897 1898 Node *hot_tail = NULL; 1899 // Make a Region for the merge point 1900 Node *r = new RegionNode(1); 1901 for( i = 2; i < _head->req(); i++ ) { 1902 if( i != hot_idx ) 1903 r->add_req( _head->in(i) ); 1904 else hot_tail = _head->in(i); 1905 } 1906 igvn.register_new_node_with_optimizer(r, _head); 1907 // Plug region into end of loop _head, followed by hot_tail 1908 while( _head->req() > 3 ) _head->del_req( _head->req()-1 ); 1909 igvn.replace_input_of(_head, 2, r); 1910 if( hot_idx ) _head->add_req(hot_tail); 1911 1912 // Split all the Phis up between '_head' loop and the Region 'r' 1913 for (DUIterator_Fast jmax, j = _head->fast_outs(jmax); j < jmax; j++) { 1914 Node *out = _head->fast_out(j); 1915 if( out->is_Phi() ) { 1916 PhiNode* n = out->as_Phi(); 1917 igvn.hash_delete(n); // Delete from hash before hacking edges 1918 Node *hot_phi = NULL; 1919 Node *phi = new PhiNode(r, n->type(), n->adr_type()); 1920 // Check all inputs for the ones to peel out 1921 uint j = 1; 1922 for( uint i = 2; i < n->req(); i++ ) { 1923 if( i != hot_idx ) 1924 phi->set_req( j++, n->in(i) ); 1925 else hot_phi = n->in(i); 1926 } 1927 // Register the phi but do not transform until whole place transforms 1928 igvn.register_new_node_with_optimizer(phi, n); 1929 // Add the merge phi to the old Phi 1930 while( n->req() > 3 ) n->del_req( n->req()-1 ); 1931 igvn.replace_input_of(n, 2, phi); 1932 if( hot_idx ) n->add_req(hot_phi); 1933 } 1934 } 1935 1936 1937 // Insert a new IdealLoopTree inserted below me. Turn it into a clone 1938 // of self loop tree. Turn self into a loop headed by _head and with 1939 // tail being the new merge point. 1940 IdealLoopTree *ilt = new IdealLoopTree( phase, _head, _tail ); 1941 phase->set_loop(_tail,ilt); // Adjust tail 1942 _tail = r; // Self's tail is new merge point 1943 phase->set_loop(r,this); 1944 ilt->_child = _child; // New guy has my children 1945 _child = ilt; // Self has new guy as only child 1946 ilt->_parent = this; // new guy has self for parent 1947 ilt->_nest = _nest; // Same nesting depth (for now) 1948 1949 // Starting with 'ilt', look for child loop trees using the same shared 1950 // header. Flatten these out; they will no longer be loops in the end. 1951 IdealLoopTree **pilt = &_child; 1952 while( ilt ) { 1953 if( ilt->_head == _head ) { 1954 uint i; 1955 for( i = 2; i < _head->req(); i++ ) 1956 if( _head->in(i) == ilt->_tail ) 1957 break; // Still a loop 1958 if( i == _head->req() ) { // No longer a loop 1959 // Flatten ilt. Hang ilt's "_next" list from the end of 1960 // ilt's '_child' list. Move the ilt's _child up to replace ilt. 1961 IdealLoopTree **cp = &ilt->_child; 1962 while( *cp ) cp = &(*cp)->_next; // Find end of child list 1963 *cp = ilt->_next; // Hang next list at end of child list 1964 *pilt = ilt->_child; // Move child up to replace ilt 1965 ilt->_head = NULL; // Flag as a loop UNIONED into parent 1966 ilt = ilt->_child; // Repeat using new ilt 1967 continue; // do not advance over ilt->_child 1968 } 1969 assert( ilt->_tail == hot_tail, "expected to only find the hot inner loop here" ); 1970 phase->set_loop(_head,ilt); 1971 } 1972 pilt = &ilt->_child; // Advance to next 1973 ilt = *pilt; 1974 } 1975 1976 if( _child ) fix_parent( _child, this ); 1977 } 1978 1979 //------------------------------beautify_loops--------------------------------- 1980 // Split shared headers and insert loop landing pads. 1981 // Insert a LoopNode to replace the RegionNode. 1982 // Return TRUE if loop tree is structurally changed. 1983 bool IdealLoopTree::beautify_loops( PhaseIdealLoop *phase ) { 1984 bool result = false; 1985 // Cache parts in locals for easy 1986 PhaseIterGVN &igvn = phase->_igvn; 1987 1988 igvn.hash_delete(_head); // Yank from hash before hacking edges 1989 1990 // Check for multiple fall-in paths. Peel off a landing pad if need be. 1991 int fall_in_cnt = 0; 1992 for( uint i = 1; i < _head->req(); i++ ) 1993 if( !phase->is_member( this, _head->in(i) ) ) 1994 fall_in_cnt++; 1995 assert( fall_in_cnt, "at least 1 fall-in path" ); 1996 if( fall_in_cnt > 1 ) // Need a loop landing pad to merge fall-ins 1997 split_fall_in( phase, fall_in_cnt ); 1998 1999 // Swap inputs to the _head and all Phis to move the fall-in edge to 2000 // the left. 2001 fall_in_cnt = 1; 2002 while( phase->is_member( this, _head->in(fall_in_cnt) ) ) 2003 fall_in_cnt++; 2004 if( fall_in_cnt > 1 ) { 2005 // Since I am just swapping inputs I do not need to update def-use info 2006 Node *tmp = _head->in(1); 2007 igvn.rehash_node_delayed(_head); 2008 _head->set_req( 1, _head->in(fall_in_cnt) ); 2009 _head->set_req( fall_in_cnt, tmp ); 2010 // Swap also all Phis 2011 for (DUIterator_Fast imax, i = _head->fast_outs(imax); i < imax; i++) { 2012 Node* phi = _head->fast_out(i); 2013 if( phi->is_Phi() ) { 2014 igvn.rehash_node_delayed(phi); // Yank from hash before hacking edges 2015 tmp = phi->in(1); 2016 phi->set_req( 1, phi->in(fall_in_cnt) ); 2017 phi->set_req( fall_in_cnt, tmp ); 2018 } 2019 } 2020 } 2021 assert( !phase->is_member( this, _head->in(1) ), "left edge is fall-in" ); 2022 assert( phase->is_member( this, _head->in(2) ), "right edge is loop" ); 2023 2024 // If I am a shared header (multiple backedges), peel off the many 2025 // backedges into a private merge point and use the merge point as 2026 // the one true backedge. 2027 if( _head->req() > 3 ) { 2028 // Merge the many backedges into a single backedge but leave 2029 // the hottest backedge as separate edge for the following peel. 2030 merge_many_backedges( phase ); 2031 result = true; 2032 } 2033 2034 // If I have one hot backedge, peel off myself loop. 2035 // I better be the outermost loop. 2036 if (_head->req() > 3 && !_irreducible) { 2037 split_outer_loop( phase ); 2038 result = true; 2039 2040 } else if (!_head->is_Loop() && !_irreducible) { 2041 // Make a new LoopNode to replace the old loop head 2042 Node *l = new LoopNode( _head->in(1), _head->in(2) ); 2043 l = igvn.register_new_node_with_optimizer(l, _head); 2044 phase->set_created_loop_node(); 2045 // Go ahead and replace _head 2046 phase->_igvn.replace_node( _head, l ); 2047 _head = l; 2048 phase->set_loop(_head, this); 2049 } 2050 2051 // Now recursively beautify nested loops 2052 if( _child ) result |= _child->beautify_loops( phase ); 2053 if( _next ) result |= _next ->beautify_loops( phase ); 2054 return result; 2055 } 2056 2057 //------------------------------allpaths_check_safepts---------------------------- 2058 // Allpaths backwards scan from loop tail, terminating each path at first safepoint 2059 // encountered. Helper for check_safepts. 2060 void IdealLoopTree::allpaths_check_safepts(VectorSet &visited, Node_List &stack) { 2061 assert(stack.size() == 0, "empty stack"); 2062 stack.push(_tail); 2063 visited.Clear(); 2064 visited.set(_tail->_idx); 2065 while (stack.size() > 0) { 2066 Node* n = stack.pop(); 2067 if (n->is_Call() && n->as_Call()->guaranteed_safepoint()) { 2068 // Terminate this path 2069 } else if (n->Opcode() == Op_SafePoint) { 2070 if (_phase->get_loop(n) != this) { 2071 if (_required_safept == NULL) _required_safept = new Node_List(); 2072 _required_safept->push(n); // save the one closest to the tail 2073 } 2074 // Terminate this path 2075 } else { 2076 uint start = n->is_Region() ? 1 : 0; 2077 uint end = n->is_Region() && !n->is_Loop() ? n->req() : start + 1; 2078 for (uint i = start; i < end; i++) { 2079 Node* in = n->in(i); 2080 assert(in->is_CFG(), "must be"); 2081 if (!visited.test_set(in->_idx) && is_member(_phase->get_loop(in))) { 2082 stack.push(in); 2083 } 2084 } 2085 } 2086 } 2087 } 2088 2089 //------------------------------check_safepts---------------------------- 2090 // Given dominators, try to find loops with calls that must always be 2091 // executed (call dominates loop tail). These loops do not need non-call 2092 // safepoints (ncsfpt). 2093 // 2094 // A complication is that a safepoint in a inner loop may be needed 2095 // by an outer loop. In the following, the inner loop sees it has a 2096 // call (block 3) on every path from the head (block 2) to the 2097 // backedge (arc 3->2). So it deletes the ncsfpt (non-call safepoint) 2098 // in block 2, _but_ this leaves the outer loop without a safepoint. 2099 // 2100 // entry 0 2101 // | 2102 // v 2103 // outer 1,2 +->1 2104 // | | 2105 // | v 2106 // | 2<---+ ncsfpt in 2 2107 // |_/|\ | 2108 // | v | 2109 // inner 2,3 / 3 | call in 3 2110 // / | | 2111 // v +--+ 2112 // exit 4 2113 // 2114 // 2115 // This method creates a list (_required_safept) of ncsfpt nodes that must 2116 // be protected is created for each loop. When a ncsfpt maybe deleted, it 2117 // is first looked for in the lists for the outer loops of the current loop. 2118 // 2119 // The insights into the problem: 2120 // A) counted loops are okay 2121 // B) innermost loops are okay (only an inner loop can delete 2122 // a ncsfpt needed by an outer loop) 2123 // C) a loop is immune from an inner loop deleting a safepoint 2124 // if the loop has a call on the idom-path 2125 // D) a loop is also immune if it has a ncsfpt (non-call safepoint) on the 2126 // idom-path that is not in a nested loop 2127 // E) otherwise, an ncsfpt on the idom-path that is nested in an inner 2128 // loop needs to be prevented from deletion by an inner loop 2129 // 2130 // There are two analyses: 2131 // 1) The first, and cheaper one, scans the loop body from 2132 // tail to head following the idom (immediate dominator) 2133 // chain, looking for the cases (C,D,E) above. 2134 // Since inner loops are scanned before outer loops, there is summary 2135 // information about inner loops. Inner loops can be skipped over 2136 // when the tail of an inner loop is encountered. 2137 // 2138 // 2) The second, invoked if the first fails to find a call or ncsfpt on 2139 // the idom path (which is rare), scans all predecessor control paths 2140 // from the tail to the head, terminating a path when a call or sfpt 2141 // is encountered, to find the ncsfpt's that are closest to the tail. 2142 // 2143 void IdealLoopTree::check_safepts(VectorSet &visited, Node_List &stack) { 2144 // Bottom up traversal 2145 IdealLoopTree* ch = _child; 2146 if (_child) _child->check_safepts(visited, stack); 2147 if (_next) _next ->check_safepts(visited, stack); 2148 2149 if (!_head->is_CountedLoop() && !_has_sfpt && _parent != NULL && !_irreducible) { 2150 bool has_call = false; // call on dom-path 2151 bool has_local_ncsfpt = false; // ncsfpt on dom-path at this loop depth 2152 Node* nonlocal_ncsfpt = NULL; // ncsfpt on dom-path at a deeper depth 2153 // Scan the dom-path nodes from tail to head 2154 for (Node* n = tail(); n != _head; n = _phase->idom(n)) { 2155 if (n->is_Call() && n->as_Call()->guaranteed_safepoint()) { 2156 has_call = true; 2157 _has_sfpt = 1; // Then no need for a safept! 2158 break; 2159 } else if (n->Opcode() == Op_SafePoint) { 2160 if (_phase->get_loop(n) == this) { 2161 has_local_ncsfpt = true; 2162 break; 2163 } 2164 if (nonlocal_ncsfpt == NULL) { 2165 nonlocal_ncsfpt = n; // save the one closest to the tail 2166 } 2167 } else { 2168 IdealLoopTree* nlpt = _phase->get_loop(n); 2169 if (this != nlpt) { 2170 // If at an inner loop tail, see if the inner loop has already 2171 // recorded seeing a call on the dom-path (and stop.) If not, 2172 // jump to the head of the inner loop. 2173 assert(is_member(nlpt), "nested loop"); 2174 Node* tail = nlpt->_tail; 2175 if (tail->in(0)->is_If()) tail = tail->in(0); 2176 if (n == tail) { 2177 // If inner loop has call on dom-path, so does outer loop 2178 if (nlpt->_has_sfpt) { 2179 has_call = true; 2180 _has_sfpt = 1; 2181 break; 2182 } 2183 // Skip to head of inner loop 2184 assert(_phase->is_dominator(_head, nlpt->_head), "inner head dominated by outer head"); 2185 n = nlpt->_head; 2186 } 2187 } 2188 } 2189 } 2190 // Record safept's that this loop needs preserved when an 2191 // inner loop attempts to delete it's safepoints. 2192 if (_child != NULL && !has_call && !has_local_ncsfpt) { 2193 if (nonlocal_ncsfpt != NULL) { 2194 if (_required_safept == NULL) _required_safept = new Node_List(); 2195 _required_safept->push(nonlocal_ncsfpt); 2196 } else { 2197 // Failed to find a suitable safept on the dom-path. Now use 2198 // an all paths walk from tail to head, looking for safepoints to preserve. 2199 allpaths_check_safepts(visited, stack); 2200 } 2201 } 2202 } 2203 } 2204 2205 //---------------------------is_deleteable_safept---------------------------- 2206 // Is safept not required by an outer loop? 2207 bool PhaseIdealLoop::is_deleteable_safept(Node* sfpt) { 2208 assert(sfpt->Opcode() == Op_SafePoint, ""); 2209 IdealLoopTree* lp = get_loop(sfpt)->_parent; 2210 while (lp != NULL) { 2211 Node_List* sfpts = lp->_required_safept; 2212 if (sfpts != NULL) { 2213 for (uint i = 0; i < sfpts->size(); i++) { 2214 if (sfpt == sfpts->at(i)) 2215 return false; 2216 } 2217 } 2218 lp = lp->_parent; 2219 } 2220 return true; 2221 } 2222 2223 //---------------------------replace_parallel_iv------------------------------- 2224 // Replace parallel induction variable (parallel to trip counter) 2225 void PhaseIdealLoop::replace_parallel_iv(IdealLoopTree *loop) { 2226 assert(loop->_head->is_CountedLoop(), ""); 2227 CountedLoopNode *cl = loop->_head->as_CountedLoop(); 2228 if (!cl->is_valid_counted_loop()) 2229 return; // skip malformed counted loop 2230 Node *incr = cl->incr(); 2231 if (incr == NULL) 2232 return; // Dead loop? 2233 Node *init = cl->init_trip(); 2234 Node *phi = cl->phi(); 2235 int stride_con = cl->stride_con(); 2236 2237 // Visit all children, looking for Phis 2238 for (DUIterator i = cl->outs(); cl->has_out(i); i++) { 2239 Node *out = cl->out(i); 2240 // Look for other phis (secondary IVs). Skip dead ones 2241 if (!out->is_Phi() || out == phi || !has_node(out)) 2242 continue; 2243 PhiNode* phi2 = out->as_Phi(); 2244 Node *incr2 = phi2->in( LoopNode::LoopBackControl ); 2245 // Look for induction variables of the form: X += constant 2246 if (phi2->region() != loop->_head || 2247 incr2->req() != 3 || 2248 incr2->in(1) != phi2 || 2249 incr2 == incr || 2250 incr2->Opcode() != Op_AddI || 2251 !incr2->in(2)->is_Con()) 2252 continue; 2253 2254 // Check for parallel induction variable (parallel to trip counter) 2255 // via an affine function. In particular, count-down loops with 2256 // count-up array indices are common. We only RCE references off 2257 // the trip-counter, so we need to convert all these to trip-counter 2258 // expressions. 2259 Node *init2 = phi2->in( LoopNode::EntryControl ); 2260 int stride_con2 = incr2->in(2)->get_int(); 2261 2262 // The ratio of the two strides cannot be represented as an int 2263 // if stride_con2 is min_int and stride_con is -1. 2264 if (stride_con2 == min_jint && stride_con == -1) { 2265 continue; 2266 } 2267 2268 // The general case here gets a little tricky. We want to find the 2269 // GCD of all possible parallel IV's and make a new IV using this 2270 // GCD for the loop. Then all possible IVs are simple multiples of 2271 // the GCD. In practice, this will cover very few extra loops. 2272 // Instead we require 'stride_con2' to be a multiple of 'stride_con', 2273 // where +/-1 is the common case, but other integer multiples are 2274 // also easy to handle. 2275 int ratio_con = stride_con2/stride_con; 2276 2277 if ((ratio_con * stride_con) == stride_con2) { // Check for exact 2278 #ifndef PRODUCT 2279 if (TraceLoopOpts) { 2280 tty->print("Parallel IV: %d ", phi2->_idx); 2281 loop->dump_head(); 2282 } 2283 #endif 2284 // Convert to using the trip counter. The parallel induction 2285 // variable differs from the trip counter by a loop-invariant 2286 // amount, the difference between their respective initial values. 2287 // It is scaled by the 'ratio_con'. 2288 Node* ratio = _igvn.intcon(ratio_con); 2289 set_ctrl(ratio, C->root()); 2290 Node* ratio_init = new MulINode(init, ratio); 2291 _igvn.register_new_node_with_optimizer(ratio_init, init); 2292 set_early_ctrl(ratio_init); 2293 Node* diff = new SubINode(init2, ratio_init); 2294 _igvn.register_new_node_with_optimizer(diff, init2); 2295 set_early_ctrl(diff); 2296 Node* ratio_idx = new MulINode(phi, ratio); 2297 _igvn.register_new_node_with_optimizer(ratio_idx, phi); 2298 set_ctrl(ratio_idx, cl); 2299 Node* add = new AddINode(ratio_idx, diff); 2300 _igvn.register_new_node_with_optimizer(add); 2301 set_ctrl(add, cl); 2302 _igvn.replace_node( phi2, add ); 2303 // Sometimes an induction variable is unused 2304 if (add->outcnt() == 0) { 2305 _igvn.remove_dead_node(add); 2306 } 2307 --i; // deleted this phi; rescan starting with next position 2308 continue; 2309 } 2310 } 2311 } 2312 2313 void IdealLoopTree::remove_safepoints(PhaseIdealLoop* phase, bool keep_one) { 2314 Node* keep = NULL; 2315 if (keep_one) { 2316 // Look for a safepoint on the idom-path. 2317 for (Node* i = tail(); i != _head; i = phase->idom(i)) { 2318 if (i->Opcode() == Op_SafePoint && phase->get_loop(i) == this) { 2319 keep = i; 2320 break; // Found one 2321 } 2322 } 2323 } 2324 2325 // Don't remove any safepoints if it is requested to keep a single safepoint and 2326 // no safepoint was found on idom-path. It is not safe to remove any safepoint 2327 // in this case since there's no safepoint dominating all paths in the loop body. 2328 bool prune = !keep_one || keep != NULL; 2329 2330 // Delete other safepoints in this loop. 2331 Node_List* sfpts = _safepts; 2332 if (prune && sfpts != NULL) { 2333 assert(keep == NULL || keep->Opcode() == Op_SafePoint, "not safepoint"); 2334 for (uint i = 0; i < sfpts->size(); i++) { 2335 Node* n = sfpts->at(i); 2336 assert(phase->get_loop(n) == this, ""); 2337 if (n != keep && phase->is_deleteable_safept(n)) { 2338 phase->lazy_replace(n, n->in(TypeFunc::Control)); 2339 } 2340 } 2341 } 2342 } 2343 2344 //------------------------------counted_loop----------------------------------- 2345 // Convert to counted loops where possible 2346 void IdealLoopTree::counted_loop( PhaseIdealLoop *phase ) { 2347 2348 // For grins, set the inner-loop flag here 2349 if (!_child) { 2350 if (_head->is_Loop()) _head->as_Loop()->set_inner_loop(); 2351 } 2352 2353 IdealLoopTree* loop = this; 2354 if (_head->is_CountedLoop() || 2355 phase->is_counted_loop(_head, loop)) { 2356 2357 if (LoopStripMiningIter == 0 || (LoopStripMiningIter > 1 && _child == NULL)) { 2358 // Indicate we do not need a safepoint here 2359 _has_sfpt = 1; 2360 } 2361 2362 // Remove safepoints 2363 bool keep_one_sfpt = !(_has_call || _has_sfpt); 2364 remove_safepoints(phase, keep_one_sfpt); 2365 2366 // Look for induction variables 2367 phase->replace_parallel_iv(this); 2368 2369 } else if (_parent != NULL && !_irreducible) { 2370 // Not a counted loop. Keep one safepoint. 2371 bool keep_one_sfpt = true; 2372 remove_safepoints(phase, keep_one_sfpt); 2373 } 2374 2375 // Recursively 2376 assert(loop->_child != this || (loop->_head->as_Loop()->is_OuterStripMinedLoop() && _head->as_CountedLoop()->is_strip_mined()), "what kind of loop was added?"); 2377 assert(loop->_child != this || (loop->_child->_child == NULL && loop->_child->_next == NULL), "would miss some loops"); 2378 if (loop->_child && loop->_child != this) loop->_child->counted_loop(phase); 2379 if (loop->_next) loop->_next ->counted_loop(phase); 2380 } 2381 2382 #ifndef PRODUCT 2383 //------------------------------dump_head-------------------------------------- 2384 // Dump 1 liner for loop header info 2385 void IdealLoopTree::dump_head( ) const { 2386 for (uint i=0; i<_nest; i++) 2387 tty->print(" "); 2388 tty->print("Loop: N%d/N%d ",_head->_idx,_tail->_idx); 2389 if (_irreducible) tty->print(" IRREDUCIBLE"); 2390 Node* entry = _head->is_Loop() ? _head->as_Loop()->skip_strip_mined(-1)->in(LoopNode::EntryControl) : _head->in(LoopNode::EntryControl); 2391 Node* predicate = PhaseIdealLoop::find_predicate_insertion_point(entry, Deoptimization::Reason_loop_limit_check); 2392 if (predicate != NULL ) { 2393 tty->print(" limit_check"); 2394 entry = entry->in(0)->in(0); 2395 } 2396 if (UseLoopPredicate) { 2397 entry = PhaseIdealLoop::find_predicate_insertion_point(entry, Deoptimization::Reason_predicate); 2398 if (entry != NULL) { 2399 tty->print(" predicated"); 2400 } 2401 } 2402 if (_head->is_CountedLoop()) { 2403 CountedLoopNode *cl = _head->as_CountedLoop(); 2404 tty->print(" counted"); 2405 2406 Node* init_n = cl->init_trip(); 2407 if (init_n != NULL && init_n->is_Con()) 2408 tty->print(" [%d,", cl->init_trip()->get_int()); 2409 else 2410 tty->print(" [int,"); 2411 Node* limit_n = cl->limit(); 2412 if (limit_n != NULL && limit_n->is_Con()) 2413 tty->print("%d),", cl->limit()->get_int()); 2414 else 2415 tty->print("int),"); 2416 int stride_con = cl->stride_con(); 2417 if (stride_con > 0) tty->print("+"); 2418 tty->print("%d", stride_con); 2419 2420 tty->print(" (%0.f iters) ", cl->profile_trip_cnt()); 2421 2422 if (cl->is_pre_loop ()) tty->print(" pre" ); 2423 if (cl->is_main_loop()) tty->print(" main"); 2424 if (cl->is_post_loop()) tty->print(" post"); 2425 if (cl->is_vectorized_loop()) tty->print(" vector"); 2426 if (cl->range_checks_present()) tty->print(" rc "); 2427 if (cl->is_multiversioned()) tty->print(" multi "); 2428 } 2429 if (_has_call) tty->print(" has_call"); 2430 if (_has_sfpt) tty->print(" has_sfpt"); 2431 if (_rce_candidate) tty->print(" rce"); 2432 if (_safepts != NULL && _safepts->size() > 0) { 2433 tty->print(" sfpts={"); _safepts->dump_simple(); tty->print(" }"); 2434 } 2435 if (_required_safept != NULL && _required_safept->size() > 0) { 2436 tty->print(" req={"); _required_safept->dump_simple(); tty->print(" }"); 2437 } 2438 if (Verbose) { 2439 tty->print(" body={"); _body.dump_simple(); tty->print(" }"); 2440 } 2441 if (_head->is_Loop() && _head->as_Loop()->is_strip_mined()) { 2442 tty->print(" strip_mined"); 2443 } 2444 tty->cr(); 2445 } 2446 2447 //------------------------------dump------------------------------------------- 2448 // Dump loops by loop tree 2449 void IdealLoopTree::dump( ) const { 2450 dump_head(); 2451 if (_child) _child->dump(); 2452 if (_next) _next ->dump(); 2453 } 2454 2455 #endif 2456 2457 static void log_loop_tree(IdealLoopTree* root, IdealLoopTree* loop, CompileLog* log) { 2458 if (loop == root) { 2459 if (loop->_child != NULL) { 2460 log->begin_head("loop_tree"); 2461 log->end_head(); 2462 if( loop->_child ) log_loop_tree(root, loop->_child, log); 2463 log->tail("loop_tree"); 2464 assert(loop->_next == NULL, "what?"); 2465 } 2466 } else { 2467 Node* head = loop->_head; 2468 log->begin_head("loop"); 2469 log->print(" idx='%d' ", head->_idx); 2470 if (loop->_irreducible) log->print("irreducible='1' "); 2471 if (head->is_Loop()) { 2472 if (head->as_Loop()->is_inner_loop()) log->print("inner_loop='1' "); 2473 if (head->as_Loop()->is_partial_peel_loop()) log->print("partial_peel_loop='1' "); 2474 } 2475 if (head->is_CountedLoop()) { 2476 CountedLoopNode* cl = head->as_CountedLoop(); 2477 if (cl->is_pre_loop()) log->print("pre_loop='%d' ", cl->main_idx()); 2478 if (cl->is_main_loop()) log->print("main_loop='%d' ", cl->_idx); 2479 if (cl->is_post_loop()) log->print("post_loop='%d' ", cl->main_idx()); 2480 } 2481 log->end_head(); 2482 if( loop->_child ) log_loop_tree(root, loop->_child, log); 2483 log->tail("loop"); 2484 if( loop->_next ) log_loop_tree(root, loop->_next, log); 2485 } 2486 } 2487 2488 //---------------------collect_potentially_useful_predicates----------------------- 2489 // Helper function to collect potentially useful predicates to prevent them from 2490 // being eliminated by PhaseIdealLoop::eliminate_useless_predicates 2491 void PhaseIdealLoop::collect_potentially_useful_predicates( 2492 IdealLoopTree * loop, Unique_Node_List &useful_predicates) { 2493 if (loop->_child) { // child 2494 collect_potentially_useful_predicates(loop->_child, useful_predicates); 2495 } 2496 2497 // self (only loops that we can apply loop predication may use their predicates) 2498 if (loop->_head->is_Loop() && 2499 !loop->_irreducible && 2500 !loop->tail()->is_top()) { 2501 LoopNode* lpn = loop->_head->as_Loop(); 2502 Node* entry = lpn->in(LoopNode::EntryControl); 2503 Node* predicate_proj = find_predicate(entry); // loop_limit_check first 2504 if (predicate_proj != NULL ) { // right pattern that can be used by loop predication 2505 assert(entry->in(0)->in(1)->in(1)->Opcode() == Op_Opaque1, "must be"); 2506 useful_predicates.push(entry->in(0)->in(1)->in(1)); // good one 2507 entry = entry->in(0)->in(0); 2508 } 2509 predicate_proj = find_predicate(entry); // Predicate 2510 if (predicate_proj != NULL ) { 2511 useful_predicates.push(entry->in(0)->in(1)->in(1)); // good one 2512 } 2513 } 2514 2515 if (loop->_next) { // sibling 2516 collect_potentially_useful_predicates(loop->_next, useful_predicates); 2517 } 2518 } 2519 2520 //------------------------eliminate_useless_predicates----------------------------- 2521 // Eliminate all inserted predicates if they could not be used by loop predication. 2522 // Note: it will also eliminates loop limits check predicate since it also uses 2523 // Opaque1 node (see Parse::add_predicate()). 2524 void PhaseIdealLoop::eliminate_useless_predicates() { 2525 if (C->predicate_count() == 0) 2526 return; // no predicate left 2527 2528 Unique_Node_List useful_predicates; // to store useful predicates 2529 if (C->has_loops()) { 2530 collect_potentially_useful_predicates(_ltree_root->_child, useful_predicates); 2531 } 2532 2533 for (int i = C->predicate_count(); i > 0; i--) { 2534 Node * n = C->predicate_opaque1_node(i-1); 2535 assert(n->Opcode() == Op_Opaque1, "must be"); 2536 if (!useful_predicates.member(n)) { // not in the useful list 2537 _igvn.replace_node(n, n->in(1)); 2538 } 2539 } 2540 } 2541 2542 //------------------------process_expensive_nodes----------------------------- 2543 // Expensive nodes have their control input set to prevent the GVN 2544 // from commoning them and as a result forcing the resulting node to 2545 // be in a more frequent path. Use CFG information here, to change the 2546 // control inputs so that some expensive nodes can be commoned while 2547 // not executed more frequently. 2548 bool PhaseIdealLoop::process_expensive_nodes() { 2549 assert(OptimizeExpensiveOps, "optimization off?"); 2550 2551 // Sort nodes to bring similar nodes together 2552 C->sort_expensive_nodes(); 2553 2554 bool progress = false; 2555 2556 for (int i = 0; i < C->expensive_count(); ) { 2557 Node* n = C->expensive_node(i); 2558 int start = i; 2559 // Find nodes similar to n 2560 i++; 2561 for (; i < C->expensive_count() && Compile::cmp_expensive_nodes(n, C->expensive_node(i)) == 0; i++); 2562 int end = i; 2563 // And compare them two by two 2564 for (int j = start; j < end; j++) { 2565 Node* n1 = C->expensive_node(j); 2566 if (is_node_unreachable(n1)) { 2567 continue; 2568 } 2569 for (int k = j+1; k < end; k++) { 2570 Node* n2 = C->expensive_node(k); 2571 if (is_node_unreachable(n2)) { 2572 continue; 2573 } 2574 2575 assert(n1 != n2, "should be pair of nodes"); 2576 2577 Node* c1 = n1->in(0); 2578 Node* c2 = n2->in(0); 2579 2580 Node* parent_c1 = c1; 2581 Node* parent_c2 = c2; 2582 2583 // The call to get_early_ctrl_for_expensive() moves the 2584 // expensive nodes up but stops at loops that are in a if 2585 // branch. See whether we can exit the loop and move above the 2586 // If. 2587 if (c1->is_Loop()) { 2588 parent_c1 = c1->in(1); 2589 } 2590 if (c2->is_Loop()) { 2591 parent_c2 = c2->in(1); 2592 } 2593 2594 if (parent_c1 == parent_c2) { 2595 _igvn._worklist.push(n1); 2596 _igvn._worklist.push(n2); 2597 continue; 2598 } 2599 2600 // Look for identical expensive node up the dominator chain. 2601 if (is_dominator(c1, c2)) { 2602 c2 = c1; 2603 } else if (is_dominator(c2, c1)) { 2604 c1 = c2; 2605 } else if (parent_c1->is_Proj() && parent_c1->in(0)->is_If() && 2606 parent_c2->is_Proj() && parent_c1->in(0) == parent_c2->in(0)) { 2607 // Both branches have the same expensive node so move it up 2608 // before the if. 2609 c1 = c2 = idom(parent_c1->in(0)); 2610 } 2611 // Do the actual moves 2612 if (n1->in(0) != c1) { 2613 _igvn.hash_delete(n1); 2614 n1->set_req(0, c1); 2615 _igvn.hash_insert(n1); 2616 _igvn._worklist.push(n1); 2617 progress = true; 2618 } 2619 if (n2->in(0) != c2) { 2620 _igvn.hash_delete(n2); 2621 n2->set_req(0, c2); 2622 _igvn.hash_insert(n2); 2623 _igvn._worklist.push(n2); 2624 progress = true; 2625 } 2626 } 2627 } 2628 } 2629 2630 return progress; 2631 } 2632 2633 2634 //============================================================================= 2635 //----------------------------build_and_optimize------------------------------- 2636 // Create a PhaseLoop. Build the ideal Loop tree. Map each Ideal Node to 2637 // its corresponding LoopNode. If 'optimize' is true, do some loop cleanups. 2638 void PhaseIdealLoop::build_and_optimize(bool do_split_ifs, bool skip_loop_opts) { 2639 ResourceMark rm; 2640 2641 int old_progress = C->major_progress(); 2642 uint orig_worklist_size = _igvn._worklist.size(); 2643 2644 #ifndef PRODUCT 2645 // Capture for later assert 2646 uint unique = C->unique(); 2647 _loop_invokes++; 2648 _loop_work += unique; 2649 #endif 2650 2651 // True if the method has at least 1 irreducible loop 2652 _has_irreducible_loops = false; 2653 2654 _created_loop_node = false; 2655 2656 Arena *a = Thread::current()->resource_area(); 2657 VectorSet visited(a); 2658 // Pre-grow the mapping from Nodes to IdealLoopTrees. 2659 _nodes.map(C->unique(), NULL); 2660 memset(_nodes.adr(), 0, wordSize * C->unique()); 2661 2662 // Pre-build the top-level outermost loop tree entry 2663 _ltree_root = new IdealLoopTree( this, C->root(), C->root() ); 2664 // Do not need a safepoint at the top level 2665 _ltree_root->_has_sfpt = 1; 2666 2667 // Initialize Dominators. 2668 // Checked in clone_loop_predicate() during beautify_loops(). 2669 _idom_size = 0; 2670 _idom = NULL; 2671 _dom_depth = NULL; 2672 _dom_stk = NULL; 2673 2674 // Empty pre-order array 2675 allocate_preorders(); 2676 2677 // Build a loop tree on the fly. Build a mapping from CFG nodes to 2678 // IdealLoopTree entries. Data nodes are NOT walked. 2679 build_loop_tree(); 2680 // Check for bailout, and return 2681 if (C->failing()) { 2682 return; 2683 } 2684 2685 // No loops after all 2686 if( !_ltree_root->_child && !_verify_only ) C->set_has_loops(false); 2687 2688 // There should always be an outer loop containing the Root and Return nodes. 2689 // If not, we have a degenerate empty program. Bail out in this case. 2690 if (!has_node(C->root())) { 2691 if (!_verify_only) { 2692 C->clear_major_progress(); 2693 C->record_method_not_compilable("empty program detected during loop optimization"); 2694 } 2695 return; 2696 } 2697 2698 // Nothing to do, so get out 2699 bool stop_early = !C->has_loops() && !skip_loop_opts && !do_split_ifs && !_verify_me && !_verify_only; 2700 bool do_expensive_nodes = C->should_optimize_expensive_nodes(_igvn); 2701 if (stop_early && !do_expensive_nodes) { 2702 _igvn.optimize(); // Cleanup NeverBranches 2703 return; 2704 } 2705 2706 // Set loop nesting depth 2707 _ltree_root->set_nest( 0 ); 2708 2709 // Split shared headers and insert loop landing pads. 2710 // Do not bother doing this on the Root loop of course. 2711 if( !_verify_me && !_verify_only && _ltree_root->_child ) { 2712 C->print_method(PHASE_BEFORE_BEAUTIFY_LOOPS, 3); 2713 if( _ltree_root->_child->beautify_loops( this ) ) { 2714 // IdealLoopTree::split_outer_loop may produce phi-nodes with a single in edge. 2715 // Transform them away. 2716 _igvn.optimize(); 2717 2718 // Re-build loop tree! 2719 _ltree_root->_child = NULL; 2720 _nodes.clear(); 2721 reallocate_preorders(); 2722 build_loop_tree(); 2723 2724 // Check for bailout, and return 2725 if (C->failing()) { 2726 return; 2727 } 2728 // Reset loop nesting depth 2729 _ltree_root->set_nest( 0 ); 2730 2731 C->print_method(PHASE_AFTER_BEAUTIFY_LOOPS, 3); 2732 } 2733 } 2734 2735 // Reset major-progress flag for the driver's heuristics 2736 C->clear_major_progress(); 2737 2738 // Build Dominators for elision of NULL checks & loop finding. 2739 // Since nodes do not have a slot for immediate dominator, make 2740 // a persistent side array for that info indexed on node->_idx. 2741 _idom_size = C->unique(); 2742 _idom = NEW_RESOURCE_ARRAY( Node*, _idom_size ); 2743 _dom_depth = NEW_RESOURCE_ARRAY( uint, _idom_size ); 2744 _dom_stk = NULL; // Allocated on demand in recompute_dom_depth 2745 memset( _dom_depth, 0, _idom_size * sizeof(uint) ); 2746 2747 Dominators(); 2748 2749 if (!_verify_only) { 2750 // As a side effect, Dominators removed any unreachable CFG paths 2751 // into RegionNodes. It doesn't do this test against Root, so 2752 // we do it here. 2753 for( uint i = 1; i < C->root()->req(); i++ ) { 2754 if( !_nodes[C->root()->in(i)->_idx] ) { // Dead path into Root? 2755 _igvn.delete_input_of(C->root(), i); 2756 i--; // Rerun same iteration on compressed edges 2757 } 2758 } 2759 2760 // Given dominators, try to find inner loops with calls that must 2761 // always be executed (call dominates loop tail). These loops do 2762 // not need a separate safepoint. 2763 Node_List cisstack(a); 2764 _ltree_root->check_safepts(visited, cisstack); 2765 } 2766 2767 // Walk the DATA nodes and place into loops. Find earliest control 2768 // node. For CFG nodes, the _nodes array starts out and remains 2769 // holding the associated IdealLoopTree pointer. For DATA nodes, the 2770 // _nodes array holds the earliest legal controlling CFG node. 2771 2772 // Allocate stack with enough space to avoid frequent realloc 2773 int stack_size = (C->live_nodes() >> 1) + 16; // (live_nodes>>1)+16 from Java2D stats 2774 Node_Stack nstack( a, stack_size ); 2775 2776 visited.Clear(); 2777 Node_List worklist(a); 2778 // Don't need C->root() on worklist since 2779 // it will be processed among C->top() inputs 2780 worklist.push( C->top() ); 2781 visited.set( C->top()->_idx ); // Set C->top() as visited now 2782 build_loop_early( visited, worklist, nstack ); 2783 2784 // Given early legal placement, try finding counted loops. This placement 2785 // is good enough to discover most loop invariants. 2786 if( !_verify_me && !_verify_only ) 2787 _ltree_root->counted_loop( this ); 2788 2789 // Find latest loop placement. Find ideal loop placement. 2790 visited.Clear(); 2791 init_dom_lca_tags(); 2792 // Need C->root() on worklist when processing outs 2793 worklist.push( C->root() ); 2794 NOT_PRODUCT( C->verify_graph_edges(); ) 2795 worklist.push( C->top() ); 2796 build_loop_late( visited, worklist, nstack ); 2797 2798 if (_verify_only) { 2799 // restore major progress flag 2800 for (int i = 0; i < old_progress; i++) 2801 C->set_major_progress(); 2802 assert(C->unique() == unique, "verification mode made Nodes? ? ?"); 2803 assert(_igvn._worklist.size() == orig_worklist_size, "shouldn't push anything"); 2804 return; 2805 } 2806 2807 // clear out the dead code after build_loop_late 2808 while (_deadlist.size()) { 2809 _igvn.remove_globally_dead_node(_deadlist.pop()); 2810 } 2811 2812 if (stop_early) { 2813 assert(do_expensive_nodes, "why are we here?"); 2814 if (process_expensive_nodes()) { 2815 // If we made some progress when processing expensive nodes then 2816 // the IGVN may modify the graph in a way that will allow us to 2817 // make some more progress: we need to try processing expensive 2818 // nodes again. 2819 C->set_major_progress(); 2820 } 2821 _igvn.optimize(); 2822 return; 2823 } 2824 2825 // Some parser-inserted loop predicates could never be used by loop 2826 // predication or they were moved away from loop during some optimizations. 2827 // For example, peeling. Eliminate them before next loop optimizations. 2828 eliminate_useless_predicates(); 2829 2830 #ifndef PRODUCT 2831 C->verify_graph_edges(); 2832 if (_verify_me) { // Nested verify pass? 2833 // Check to see if the verify mode is broken 2834 assert(C->unique() == unique, "non-optimize mode made Nodes? ? ?"); 2835 return; 2836 } 2837 if(VerifyLoopOptimizations) verify(); 2838 if(TraceLoopOpts && C->has_loops()) { 2839 _ltree_root->dump(); 2840 } 2841 #endif 2842 2843 if (skip_loop_opts) { 2844 // restore major progress flag 2845 for (int i = 0; i < old_progress; i++) { 2846 C->set_major_progress(); 2847 } 2848 2849 // Cleanup any modified bits 2850 _igvn.optimize(); 2851 2852 if (C->log() != NULL) { 2853 log_loop_tree(_ltree_root, _ltree_root, C->log()); 2854 } 2855 return; 2856 } 2857 2858 if (ReassociateInvariants) { 2859 // Reassociate invariants and prep for split_thru_phi 2860 for (LoopTreeIterator iter(_ltree_root); !iter.done(); iter.next()) { 2861 IdealLoopTree* lpt = iter.current(); 2862 bool is_counted = lpt->is_counted(); 2863 if (!is_counted || !lpt->is_inner()) continue; 2864 2865 // check for vectorized loops, any reassociation of invariants was already done 2866 if (is_counted && lpt->_head->as_CountedLoop()->do_unroll_only()) continue; 2867 2868 lpt->reassociate_invariants(this); 2869 2870 // Because RCE opportunities can be masked by split_thru_phi, 2871 // look for RCE candidates and inhibit split_thru_phi 2872 // on just their loop-phi's for this pass of loop opts 2873 if (SplitIfBlocks && do_split_ifs) { 2874 if (lpt->policy_range_check(this)) { 2875 lpt->_rce_candidate = 1; // = true 2876 } 2877 } 2878 } 2879 } 2880 2881 // Check for aggressive application of split-if and other transforms 2882 // that require basic-block info (like cloning through Phi's) 2883 if( SplitIfBlocks && do_split_ifs ) { 2884 visited.Clear(); 2885 split_if_with_blocks( visited, nstack ); 2886 NOT_PRODUCT( if( VerifyLoopOptimizations ) verify(); ); 2887 } 2888 2889 if (!C->major_progress() && do_expensive_nodes && process_expensive_nodes()) { 2890 C->set_major_progress(); 2891 } 2892 2893 // Perform loop predication before iteration splitting 2894 if (C->has_loops() && !C->major_progress() && (C->predicate_count() > 0)) { 2895 _ltree_root->_child->loop_predication(this); 2896 } 2897 2898 if (OptimizeFill && UseLoopPredicate && C->has_loops() && !C->major_progress()) { 2899 if (do_intrinsify_fill()) { 2900 C->set_major_progress(); 2901 } 2902 } 2903 2904 // Perform iteration-splitting on inner loops. Split iterations to avoid 2905 // range checks or one-shot null checks. 2906 2907 // If split-if's didn't hack the graph too bad (no CFG changes) 2908 // then do loop opts. 2909 if (C->has_loops() && !C->major_progress()) { 2910 memset( worklist.adr(), 0, worklist.Size()*sizeof(Node*) ); 2911 _ltree_root->_child->iteration_split( this, worklist ); 2912 // No verify after peeling! GCM has hoisted code out of the loop. 2913 // After peeling, the hoisted code could sink inside the peeled area. 2914 // The peeling code does not try to recompute the best location for 2915 // all the code before the peeled area, so the verify pass will always 2916 // complain about it. 2917 } 2918 // Do verify graph edges in any case 2919 NOT_PRODUCT( C->verify_graph_edges(); ); 2920 2921 if (!do_split_ifs) { 2922 // We saw major progress in Split-If to get here. We forced a 2923 // pass with unrolling and not split-if, however more split-if's 2924 // might make progress. If the unrolling didn't make progress 2925 // then the major-progress flag got cleared and we won't try 2926 // another round of Split-If. In particular the ever-common 2927 // instance-of/check-cast pattern requires at least 2 rounds of 2928 // Split-If to clear out. 2929 C->set_major_progress(); 2930 } 2931 2932 // Repeat loop optimizations if new loops were seen 2933 if (created_loop_node()) { 2934 C->set_major_progress(); 2935 } 2936 2937 // Keep loop predicates and perform optimizations with them 2938 // until no more loop optimizations could be done. 2939 // After that switch predicates off and do more loop optimizations. 2940 if (!C->major_progress() && (C->predicate_count() > 0)) { 2941 C->cleanup_loop_predicates(_igvn); 2942 if (TraceLoopOpts) { 2943 tty->print_cr("PredicatesOff"); 2944 } 2945 C->set_major_progress(); 2946 } 2947 2948 // Convert scalar to superword operations at the end of all loop opts. 2949 if (UseSuperWord && C->has_loops() && !C->major_progress()) { 2950 // SuperWord transform 2951 SuperWord sw(this); 2952 for (LoopTreeIterator iter(_ltree_root); !iter.done(); iter.next()) { 2953 IdealLoopTree* lpt = iter.current(); 2954 if (lpt->is_counted()) { 2955 CountedLoopNode *cl = lpt->_head->as_CountedLoop(); 2956 2957 if (PostLoopMultiversioning && cl->is_rce_post_loop() && !cl->is_vectorized_loop()) { 2958 // Check that the rce'd post loop is encountered first, multiversion after all 2959 // major main loop optimization are concluded 2960 if (!C->major_progress()) { 2961 IdealLoopTree *lpt_next = lpt->_next; 2962 if (lpt_next && lpt_next->is_counted()) { 2963 CountedLoopNode *cl = lpt_next->_head->as_CountedLoop(); 2964 has_range_checks(lpt_next); 2965 if (cl->is_post_loop() && cl->range_checks_present()) { 2966 if (!cl->is_multiversioned()) { 2967 if (multi_version_post_loops(lpt, lpt_next) == false) { 2968 // Cause the rce loop to be optimized away if we fail 2969 cl->mark_is_multiversioned(); 2970 cl->set_slp_max_unroll(0); 2971 poison_rce_post_loop(lpt); 2972 } 2973 } 2974 } 2975 } 2976 sw.transform_loop(lpt, true); 2977 } 2978 } else if (cl->is_main_loop()) { 2979 sw.transform_loop(lpt, true); 2980 } 2981 } 2982 } 2983 } 2984 2985 // Cleanup any modified bits 2986 _igvn.optimize(); 2987 2988 // disable assert until issue with split_flow_path is resolved (6742111) 2989 // assert(!_has_irreducible_loops || C->parsed_irreducible_loop() || C->is_osr_compilation(), 2990 // "shouldn't introduce irreducible loops"); 2991 2992 if (C->log() != NULL) { 2993 log_loop_tree(_ltree_root, _ltree_root, C->log()); 2994 } 2995 } 2996 2997 #ifndef PRODUCT 2998 //------------------------------print_statistics------------------------------- 2999 int PhaseIdealLoop::_loop_invokes=0;// Count of PhaseIdealLoop invokes 3000 int PhaseIdealLoop::_loop_work=0; // Sum of PhaseIdealLoop x unique 3001 void PhaseIdealLoop::print_statistics() { 3002 tty->print_cr("PhaseIdealLoop=%d, sum _unique=%d", _loop_invokes, _loop_work); 3003 } 3004 3005 //------------------------------verify----------------------------------------- 3006 // Build a verify-only PhaseIdealLoop, and see that it agrees with me. 3007 static int fail; // debug only, so its multi-thread dont care 3008 void PhaseIdealLoop::verify() const { 3009 int old_progress = C->major_progress(); 3010 ResourceMark rm; 3011 PhaseIdealLoop loop_verify( _igvn, this ); 3012 VectorSet visited(Thread::current()->resource_area()); 3013 3014 fail = 0; 3015 verify_compare( C->root(), &loop_verify, visited ); 3016 assert( fail == 0, "verify loops failed" ); 3017 // Verify loop structure is the same 3018 _ltree_root->verify_tree(loop_verify._ltree_root, NULL); 3019 // Reset major-progress. It was cleared by creating a verify version of 3020 // PhaseIdealLoop. 3021 for( int i=0; i<old_progress; i++ ) 3022 C->set_major_progress(); 3023 } 3024 3025 //------------------------------verify_compare--------------------------------- 3026 // Make sure me and the given PhaseIdealLoop agree on key data structures 3027 void PhaseIdealLoop::verify_compare( Node *n, const PhaseIdealLoop *loop_verify, VectorSet &visited ) const { 3028 if( !n ) return; 3029 if( visited.test_set( n->_idx ) ) return; 3030 if( !_nodes[n->_idx] ) { // Unreachable 3031 assert( !loop_verify->_nodes[n->_idx], "both should be unreachable" ); 3032 return; 3033 } 3034 3035 uint i; 3036 for( i = 0; i < n->req(); i++ ) 3037 verify_compare( n->in(i), loop_verify, visited ); 3038 3039 // Check the '_nodes' block/loop structure 3040 i = n->_idx; 3041 if( has_ctrl(n) ) { // We have control; verify has loop or ctrl 3042 if( _nodes[i] != loop_verify->_nodes[i] && 3043 get_ctrl_no_update(n) != loop_verify->get_ctrl_no_update(n) ) { 3044 tty->print("Mismatched control setting for: "); 3045 n->dump(); 3046 if( fail++ > 10 ) return; 3047 Node *c = get_ctrl_no_update(n); 3048 tty->print("We have it as: "); 3049 if( c->in(0) ) c->dump(); 3050 else tty->print_cr("N%d",c->_idx); 3051 tty->print("Verify thinks: "); 3052 if( loop_verify->has_ctrl(n) ) 3053 loop_verify->get_ctrl_no_update(n)->dump(); 3054 else 3055 loop_verify->get_loop_idx(n)->dump(); 3056 tty->cr(); 3057 } 3058 } else { // We have a loop 3059 IdealLoopTree *us = get_loop_idx(n); 3060 if( loop_verify->has_ctrl(n) ) { 3061 tty->print("Mismatched loop setting for: "); 3062 n->dump(); 3063 if( fail++ > 10 ) return; 3064 tty->print("We have it as: "); 3065 us->dump(); 3066 tty->print("Verify thinks: "); 3067 loop_verify->get_ctrl_no_update(n)->dump(); 3068 tty->cr(); 3069 } else if (!C->major_progress()) { 3070 // Loop selection can be messed up if we did a major progress 3071 // operation, like split-if. Do not verify in that case. 3072 IdealLoopTree *them = loop_verify->get_loop_idx(n); 3073 if( us->_head != them->_head || us->_tail != them->_tail ) { 3074 tty->print("Unequals loops for: "); 3075 n->dump(); 3076 if( fail++ > 10 ) return; 3077 tty->print("We have it as: "); 3078 us->dump(); 3079 tty->print("Verify thinks: "); 3080 them->dump(); 3081 tty->cr(); 3082 } 3083 } 3084 } 3085 3086 // Check for immediate dominators being equal 3087 if( i >= _idom_size ) { 3088 if( !n->is_CFG() ) return; 3089 tty->print("CFG Node with no idom: "); 3090 n->dump(); 3091 return; 3092 } 3093 if( !n->is_CFG() ) return; 3094 if( n == C->root() ) return; // No IDOM here 3095 3096 assert(n->_idx == i, "sanity"); 3097 Node *id = idom_no_update(n); 3098 if( id != loop_verify->idom_no_update(n) ) { 3099 tty->print("Unequals idoms for: "); 3100 n->dump(); 3101 if( fail++ > 10 ) return; 3102 tty->print("We have it as: "); 3103 id->dump(); 3104 tty->print("Verify thinks: "); 3105 loop_verify->idom_no_update(n)->dump(); 3106 tty->cr(); 3107 } 3108 3109 } 3110 3111 //------------------------------verify_tree------------------------------------ 3112 // Verify that tree structures match. Because the CFG can change, siblings 3113 // within the loop tree can be reordered. We attempt to deal with that by 3114 // reordering the verify's loop tree if possible. 3115 void IdealLoopTree::verify_tree(IdealLoopTree *loop, const IdealLoopTree *parent) const { 3116 assert( _parent == parent, "Badly formed loop tree" ); 3117 3118 // Siblings not in same order? Attempt to re-order. 3119 if( _head != loop->_head ) { 3120 // Find _next pointer to update 3121 IdealLoopTree **pp = &loop->_parent->_child; 3122 while( *pp != loop ) 3123 pp = &((*pp)->_next); 3124 // Find proper sibling to be next 3125 IdealLoopTree **nn = &loop->_next; 3126 while( (*nn) && (*nn)->_head != _head ) 3127 nn = &((*nn)->_next); 3128 3129 // Check for no match. 3130 if( !(*nn) ) { 3131 // Annoyingly, irreducible loops can pick different headers 3132 // after a major_progress operation, so the rest of the loop 3133 // tree cannot be matched. 3134 if (_irreducible && Compile::current()->major_progress()) return; 3135 assert( 0, "failed to match loop tree" ); 3136 } 3137 3138 // Move (*nn) to (*pp) 3139 IdealLoopTree *hit = *nn; 3140 *nn = hit->_next; 3141 hit->_next = loop; 3142 *pp = loop; 3143 loop = hit; 3144 // Now try again to verify 3145 } 3146 3147 assert( _head == loop->_head , "mismatched loop head" ); 3148 Node *tail = _tail; // Inline a non-updating version of 3149 while( !tail->in(0) ) // the 'tail()' call. 3150 tail = tail->in(1); 3151 assert( tail == loop->_tail, "mismatched loop tail" ); 3152 3153 // Counted loops that are guarded should be able to find their guards 3154 if( _head->is_CountedLoop() && _head->as_CountedLoop()->is_main_loop() ) { 3155 CountedLoopNode *cl = _head->as_CountedLoop(); 3156 Node *init = cl->init_trip(); 3157 Node *ctrl = cl->in(LoopNode::EntryControl); 3158 assert( ctrl->Opcode() == Op_IfTrue || ctrl->Opcode() == Op_IfFalse, "" ); 3159 Node *iff = ctrl->in(0); 3160 assert( iff->Opcode() == Op_If, "" ); 3161 Node *bol = iff->in(1); 3162 assert( bol->Opcode() == Op_Bool, "" ); 3163 Node *cmp = bol->in(1); 3164 assert( cmp->Opcode() == Op_CmpI, "" ); 3165 Node *add = cmp->in(1); 3166 Node *opaq; 3167 if( add->Opcode() == Op_Opaque1 ) { 3168 opaq = add; 3169 } else { 3170 assert( add->Opcode() == Op_AddI || add->Opcode() == Op_ConI , "" ); 3171 assert( add == init, "" ); 3172 opaq = cmp->in(2); 3173 } 3174 assert( opaq->Opcode() == Op_Opaque1, "" ); 3175 3176 } 3177 3178 if (_child != NULL) _child->verify_tree(loop->_child, this); 3179 if (_next != NULL) _next ->verify_tree(loop->_next, parent); 3180 // Innermost loops need to verify loop bodies, 3181 // but only if no 'major_progress' 3182 int fail = 0; 3183 if (!Compile::current()->major_progress() && _child == NULL) { 3184 for( uint i = 0; i < _body.size(); i++ ) { 3185 Node *n = _body.at(i); 3186 if (n->outcnt() == 0) continue; // Ignore dead 3187 uint j; 3188 for( j = 0; j < loop->_body.size(); j++ ) 3189 if( loop->_body.at(j) == n ) 3190 break; 3191 if( j == loop->_body.size() ) { // Not found in loop body 3192 // Last ditch effort to avoid assertion: Its possible that we 3193 // have some users (so outcnt not zero) but are still dead. 3194 // Try to find from root. 3195 if (Compile::current()->root()->find(n->_idx)) { 3196 fail++; 3197 tty->print("We have that verify does not: "); 3198 n->dump(); 3199 } 3200 } 3201 } 3202 for( uint i2 = 0; i2 < loop->_body.size(); i2++ ) { 3203 Node *n = loop->_body.at(i2); 3204 if (n->outcnt() == 0) continue; // Ignore dead 3205 uint j; 3206 for( j = 0; j < _body.size(); j++ ) 3207 if( _body.at(j) == n ) 3208 break; 3209 if( j == _body.size() ) { // Not found in loop body 3210 // Last ditch effort to avoid assertion: Its possible that we 3211 // have some users (so outcnt not zero) but are still dead. 3212 // Try to find from root. 3213 if (Compile::current()->root()->find(n->_idx)) { 3214 fail++; 3215 tty->print("Verify has that we do not: "); 3216 n->dump(); 3217 } 3218 } 3219 } 3220 assert( !fail, "loop body mismatch" ); 3221 } 3222 } 3223 3224 #endif 3225 3226 //------------------------------set_idom--------------------------------------- 3227 void PhaseIdealLoop::set_idom(Node* d, Node* n, uint dom_depth) { 3228 uint idx = d->_idx; 3229 if (idx >= _idom_size) { 3230 uint newsize = _idom_size<<1; 3231 while( idx >= newsize ) { 3232 newsize <<= 1; 3233 } 3234 _idom = REALLOC_RESOURCE_ARRAY( Node*, _idom,_idom_size,newsize); 3235 _dom_depth = REALLOC_RESOURCE_ARRAY( uint, _dom_depth,_idom_size,newsize); 3236 memset( _dom_depth + _idom_size, 0, (newsize - _idom_size) * sizeof(uint) ); 3237 _idom_size = newsize; 3238 } 3239 _idom[idx] = n; 3240 _dom_depth[idx] = dom_depth; 3241 } 3242 3243 //------------------------------recompute_dom_depth--------------------------------------- 3244 // The dominator tree is constructed with only parent pointers. 3245 // This recomputes the depth in the tree by first tagging all 3246 // nodes as "no depth yet" marker. The next pass then runs up 3247 // the dom tree from each node marked "no depth yet", and computes 3248 // the depth on the way back down. 3249 void PhaseIdealLoop::recompute_dom_depth() { 3250 uint no_depth_marker = C->unique(); 3251 uint i; 3252 // Initialize depth to "no depth yet" and realize all lazy updates 3253 for (i = 0; i < _idom_size; i++) { 3254 // Only indices with a _dom_depth has a Node* or NULL (otherwise uninitalized). 3255 if (_dom_depth[i] > 0 && _idom[i] != NULL) { 3256 _dom_depth[i] = no_depth_marker; 3257 3258 // heal _idom if it has a fwd mapping in _nodes 3259 if (_idom[i]->in(0) == NULL) { 3260 idom(i); 3261 } 3262 } 3263 } 3264 if (_dom_stk == NULL) { 3265 uint init_size = C->live_nodes() / 100; // Guess that 1/100 is a reasonable initial size. 3266 if (init_size < 10) init_size = 10; 3267 _dom_stk = new GrowableArray<uint>(init_size); 3268 } 3269 // Compute new depth for each node. 3270 for (i = 0; i < _idom_size; i++) { 3271 uint j = i; 3272 // Run up the dom tree to find a node with a depth 3273 while (_dom_depth[j] == no_depth_marker) { 3274 _dom_stk->push(j); 3275 j = _idom[j]->_idx; 3276 } 3277 // Compute the depth on the way back down this tree branch 3278 uint dd = _dom_depth[j] + 1; 3279 while (_dom_stk->length() > 0) { 3280 uint j = _dom_stk->pop(); 3281 _dom_depth[j] = dd; 3282 dd++; 3283 } 3284 } 3285 } 3286 3287 //------------------------------sort------------------------------------------- 3288 // Insert 'loop' into the existing loop tree. 'innermost' is a leaf of the 3289 // loop tree, not the root. 3290 IdealLoopTree *PhaseIdealLoop::sort( IdealLoopTree *loop, IdealLoopTree *innermost ) { 3291 if( !innermost ) return loop; // New innermost loop 3292 3293 int loop_preorder = get_preorder(loop->_head); // Cache pre-order number 3294 assert( loop_preorder, "not yet post-walked loop" ); 3295 IdealLoopTree **pp = &innermost; // Pointer to previous next-pointer 3296 IdealLoopTree *l = *pp; // Do I go before or after 'l'? 3297 3298 // Insert at start of list 3299 while( l ) { // Insertion sort based on pre-order 3300 if( l == loop ) return innermost; // Already on list! 3301 int l_preorder = get_preorder(l->_head); // Cache pre-order number 3302 assert( l_preorder, "not yet post-walked l" ); 3303 // Check header pre-order number to figure proper nesting 3304 if( loop_preorder > l_preorder ) 3305 break; // End of insertion 3306 // If headers tie (e.g., shared headers) check tail pre-order numbers. 3307 // Since I split shared headers, you'd think this could not happen. 3308 // BUT: I must first do the preorder numbering before I can discover I 3309 // have shared headers, so the split headers all get the same preorder 3310 // number as the RegionNode they split from. 3311 if( loop_preorder == l_preorder && 3312 get_preorder(loop->_tail) < get_preorder(l->_tail) ) 3313 break; // Also check for shared headers (same pre#) 3314 pp = &l->_parent; // Chain up list 3315 l = *pp; 3316 } 3317 // Link into list 3318 // Point predecessor to me 3319 *pp = loop; 3320 // Point me to successor 3321 IdealLoopTree *p = loop->_parent; 3322 loop->_parent = l; // Point me to successor 3323 if( p ) sort( p, innermost ); // Insert my parents into list as well 3324 return innermost; 3325 } 3326 3327 //------------------------------build_loop_tree-------------------------------- 3328 // I use a modified Vick/Tarjan algorithm. I need pre- and a post- visit 3329 // bits. The _nodes[] array is mapped by Node index and holds a NULL for 3330 // not-yet-pre-walked, pre-order # for pre-but-not-post-walked and holds the 3331 // tightest enclosing IdealLoopTree for post-walked. 3332 // 3333 // During my forward walk I do a short 1-layer lookahead to see if I can find 3334 // a loop backedge with that doesn't have any work on the backedge. This 3335 // helps me construct nested loops with shared headers better. 3336 // 3337 // Once I've done the forward recursion, I do the post-work. For each child 3338 // I check to see if there is a backedge. Backedges define a loop! I 3339 // insert an IdealLoopTree at the target of the backedge. 3340 // 3341 // During the post-work I also check to see if I have several children 3342 // belonging to different loops. If so, then this Node is a decision point 3343 // where control flow can choose to change loop nests. It is at this 3344 // decision point where I can figure out how loops are nested. At this 3345 // time I can properly order the different loop nests from my children. 3346 // Note that there may not be any backedges at the decision point! 3347 // 3348 // Since the decision point can be far removed from the backedges, I can't 3349 // order my loops at the time I discover them. Thus at the decision point 3350 // I need to inspect loop header pre-order numbers to properly nest my 3351 // loops. This means I need to sort my childrens' loops by pre-order. 3352 // The sort is of size number-of-control-children, which generally limits 3353 // it to size 2 (i.e., I just choose between my 2 target loops). 3354 void PhaseIdealLoop::build_loop_tree() { 3355 // Allocate stack of size C->live_nodes()/2 to avoid frequent realloc 3356 GrowableArray <Node *> bltstack(C->live_nodes() >> 1); 3357 Node *n = C->root(); 3358 bltstack.push(n); 3359 int pre_order = 1; 3360 int stack_size; 3361 3362 while ( ( stack_size = bltstack.length() ) != 0 ) { 3363 n = bltstack.top(); // Leave node on stack 3364 if ( !is_visited(n) ) { 3365 // ---- Pre-pass Work ---- 3366 // Pre-walked but not post-walked nodes need a pre_order number. 3367 3368 set_preorder_visited( n, pre_order ); // set as visited 3369 3370 // ---- Scan over children ---- 3371 // Scan first over control projections that lead to loop headers. 3372 // This helps us find inner-to-outer loops with shared headers better. 3373 3374 // Scan children's children for loop headers. 3375 for ( int i = n->outcnt() - 1; i >= 0; --i ) { 3376 Node* m = n->raw_out(i); // Child 3377 if( m->is_CFG() && !is_visited(m) ) { // Only for CFG children 3378 // Scan over children's children to find loop 3379 for (DUIterator_Fast jmax, j = m->fast_outs(jmax); j < jmax; j++) { 3380 Node* l = m->fast_out(j); 3381 if( is_visited(l) && // Been visited? 3382 !is_postvisited(l) && // But not post-visited 3383 get_preorder(l) < pre_order ) { // And smaller pre-order 3384 // Found! Scan the DFS down this path before doing other paths 3385 bltstack.push(m); 3386 break; 3387 } 3388 } 3389 } 3390 } 3391 pre_order++; 3392 } 3393 else if ( !is_postvisited(n) ) { 3394 // Note: build_loop_tree_impl() adds out edges on rare occasions, 3395 // such as com.sun.rsasign.am::a. 3396 // For non-recursive version, first, process current children. 3397 // On next iteration, check if additional children were added. 3398 for ( int k = n->outcnt() - 1; k >= 0; --k ) { 3399 Node* u = n->raw_out(k); 3400 if ( u->is_CFG() && !is_visited(u) ) { 3401 bltstack.push(u); 3402 } 3403 } 3404 if ( bltstack.length() == stack_size ) { 3405 // There were no additional children, post visit node now 3406 (void)bltstack.pop(); // Remove node from stack 3407 pre_order = build_loop_tree_impl( n, pre_order ); 3408 // Check for bailout 3409 if (C->failing()) { 3410 return; 3411 } 3412 // Check to grow _preorders[] array for the case when 3413 // build_loop_tree_impl() adds new nodes. 3414 check_grow_preorders(); 3415 } 3416 } 3417 else { 3418 (void)bltstack.pop(); // Remove post-visited node from stack 3419 } 3420 } 3421 } 3422 3423 //------------------------------build_loop_tree_impl--------------------------- 3424 int PhaseIdealLoop::build_loop_tree_impl( Node *n, int pre_order ) { 3425 // ---- Post-pass Work ---- 3426 // Pre-walked but not post-walked nodes need a pre_order number. 3427 3428 // Tightest enclosing loop for this Node 3429 IdealLoopTree *innermost = NULL; 3430 3431 // For all children, see if any edge is a backedge. If so, make a loop 3432 // for it. Then find the tightest enclosing loop for the self Node. 3433 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) { 3434 Node* m = n->fast_out(i); // Child 3435 if( n == m ) continue; // Ignore control self-cycles 3436 if( !m->is_CFG() ) continue;// Ignore non-CFG edges 3437 3438 IdealLoopTree *l; // Child's loop 3439 if( !is_postvisited(m) ) { // Child visited but not post-visited? 3440 // Found a backedge 3441 assert( get_preorder(m) < pre_order, "should be backedge" ); 3442 // Check for the RootNode, which is already a LoopNode and is allowed 3443 // to have multiple "backedges". 3444 if( m == C->root()) { // Found the root? 3445 l = _ltree_root; // Root is the outermost LoopNode 3446 } else { // Else found a nested loop 3447 // Insert a LoopNode to mark this loop. 3448 l = new IdealLoopTree(this, m, n); 3449 } // End of Else found a nested loop 3450 if( !has_loop(m) ) // If 'm' does not already have a loop set 3451 set_loop(m, l); // Set loop header to loop now 3452 3453 } else { // Else not a nested loop 3454 if( !_nodes[m->_idx] ) continue; // Dead code has no loop 3455 l = get_loop(m); // Get previously determined loop 3456 // If successor is header of a loop (nest), move up-loop till it 3457 // is a member of some outer enclosing loop. Since there are no 3458 // shared headers (I've split them already) I only need to go up 3459 // at most 1 level. 3460 while( l && l->_head == m ) // Successor heads loop? 3461 l = l->_parent; // Move up 1 for me 3462 // If this loop is not properly parented, then this loop 3463 // has no exit path out, i.e. its an infinite loop. 3464 if( !l ) { 3465 // Make loop "reachable" from root so the CFG is reachable. Basically 3466 // insert a bogus loop exit that is never taken. 'm', the loop head, 3467 // points to 'n', one (of possibly many) fall-in paths. There may be 3468 // many backedges as well. 3469 3470 // Here I set the loop to be the root loop. I could have, after 3471 // inserting a bogus loop exit, restarted the recursion and found my 3472 // new loop exit. This would make the infinite loop a first-class 3473 // loop and it would then get properly optimized. What's the use of 3474 // optimizing an infinite loop? 3475 l = _ltree_root; // Oops, found infinite loop 3476 3477 if (!_verify_only) { 3478 // Insert the NeverBranch between 'm' and it's control user. 3479 NeverBranchNode *iff = new NeverBranchNode( m ); 3480 _igvn.register_new_node_with_optimizer(iff); 3481 set_loop(iff, l); 3482 Node *if_t = new CProjNode( iff, 0 ); 3483 _igvn.register_new_node_with_optimizer(if_t); 3484 set_loop(if_t, l); 3485 3486 Node* cfg = NULL; // Find the One True Control User of m 3487 for (DUIterator_Fast jmax, j = m->fast_outs(jmax); j < jmax; j++) { 3488 Node* x = m->fast_out(j); 3489 if (x->is_CFG() && x != m && x != iff) 3490 { cfg = x; break; } 3491 } 3492 assert(cfg != NULL, "must find the control user of m"); 3493 uint k = 0; // Probably cfg->in(0) 3494 while( cfg->in(k) != m ) k++; // But check incase cfg is a Region 3495 cfg->set_req( k, if_t ); // Now point to NeverBranch 3496 _igvn._worklist.push(cfg); 3497 3498 // Now create the never-taken loop exit 3499 Node *if_f = new CProjNode( iff, 1 ); 3500 _igvn.register_new_node_with_optimizer(if_f); 3501 set_loop(if_f, l); 3502 // Find frame ptr for Halt. Relies on the optimizer 3503 // V-N'ing. Easier and quicker than searching through 3504 // the program structure. 3505 Node *frame = new ParmNode( C->start(), TypeFunc::FramePtr ); 3506 _igvn.register_new_node_with_optimizer(frame); 3507 // Halt & Catch Fire 3508 Node *halt = new HaltNode( if_f, frame ); 3509 _igvn.register_new_node_with_optimizer(halt); 3510 set_loop(halt, l); 3511 C->root()->add_req(halt); 3512 } 3513 set_loop(C->root(), _ltree_root); 3514 } 3515 } 3516 // Weeny check for irreducible. This child was already visited (this 3517 // IS the post-work phase). Is this child's loop header post-visited 3518 // as well? If so, then I found another entry into the loop. 3519 if (!_verify_only) { 3520 while( is_postvisited(l->_head) ) { 3521 // found irreducible 3522 l->_irreducible = 1; // = true 3523 l = l->_parent; 3524 _has_irreducible_loops = true; 3525 // Check for bad CFG here to prevent crash, and bailout of compile 3526 if (l == NULL) { 3527 C->record_method_not_compilable("unhandled CFG detected during loop optimization"); 3528 return pre_order; 3529 } 3530 } 3531 C->set_has_irreducible_loop(_has_irreducible_loops); 3532 } 3533 3534 // This Node might be a decision point for loops. It is only if 3535 // it's children belong to several different loops. The sort call 3536 // does a trivial amount of work if there is only 1 child or all 3537 // children belong to the same loop. If however, the children 3538 // belong to different loops, the sort call will properly set the 3539 // _parent pointers to show how the loops nest. 3540 // 3541 // In any case, it returns the tightest enclosing loop. 3542 innermost = sort( l, innermost ); 3543 } 3544 3545 // Def-use info will have some dead stuff; dead stuff will have no 3546 // loop decided on. 3547 3548 // Am I a loop header? If so fix up my parent's child and next ptrs. 3549 if( innermost && innermost->_head == n ) { 3550 assert( get_loop(n) == innermost, "" ); 3551 IdealLoopTree *p = innermost->_parent; 3552 IdealLoopTree *l = innermost; 3553 while( p && l->_head == n ) { 3554 l->_next = p->_child; // Put self on parents 'next child' 3555 p->_child = l; // Make self as first child of parent 3556 l = p; // Now walk up the parent chain 3557 p = l->_parent; 3558 } 3559 } else { 3560 // Note that it is possible for a LoopNode to reach here, if the 3561 // backedge has been made unreachable (hence the LoopNode no longer 3562 // denotes a Loop, and will eventually be removed). 3563 3564 // Record tightest enclosing loop for self. Mark as post-visited. 3565 set_loop(n, innermost); 3566 // Also record has_call flag early on 3567 if( innermost ) { 3568 if( n->is_Call() && !n->is_CallLeaf() && !n->is_macro() ) { 3569 // Do not count uncommon calls 3570 if( !n->is_CallStaticJava() || !n->as_CallStaticJava()->_name ) { 3571 Node *iff = n->in(0)->in(0); 3572 // No any calls for vectorized loops. 3573 if( UseSuperWord || !iff->is_If() || 3574 (n->in(0)->Opcode() == Op_IfFalse && 3575 (1.0 - iff->as_If()->_prob) >= 0.01) || 3576 (iff->as_If()->_prob >= 0.01) ) 3577 innermost->_has_call = 1; 3578 } 3579 } else if( n->is_Allocate() && n->as_Allocate()->_is_scalar_replaceable ) { 3580 // Disable loop optimizations if the loop has a scalar replaceable 3581 // allocation. This disabling may cause a potential performance lost 3582 // if the allocation is not eliminated for some reason. 3583 innermost->_allow_optimizations = false; 3584 innermost->_has_call = 1; // = true 3585 } else if (n->Opcode() == Op_SafePoint) { 3586 // Record all safepoints in this loop. 3587 if (innermost->_safepts == NULL) innermost->_safepts = new Node_List(); 3588 innermost->_safepts->push(n); 3589 } 3590 } 3591 } 3592 3593 // Flag as post-visited now 3594 set_postvisited(n); 3595 return pre_order; 3596 } 3597 3598 3599 //------------------------------build_loop_early------------------------------- 3600 // Put Data nodes into some loop nest, by setting the _nodes[]->loop mapping. 3601 // First pass computes the earliest controlling node possible. This is the 3602 // controlling input with the deepest dominating depth. 3603 void PhaseIdealLoop::build_loop_early( VectorSet &visited, Node_List &worklist, Node_Stack &nstack ) { 3604 while (worklist.size() != 0) { 3605 // Use local variables nstack_top_n & nstack_top_i to cache values 3606 // on nstack's top. 3607 Node *nstack_top_n = worklist.pop(); 3608 uint nstack_top_i = 0; 3609 //while_nstack_nonempty: 3610 while (true) { 3611 // Get parent node and next input's index from stack's top. 3612 Node *n = nstack_top_n; 3613 uint i = nstack_top_i; 3614 uint cnt = n->req(); // Count of inputs 3615 if (i == 0) { // Pre-process the node. 3616 if( has_node(n) && // Have either loop or control already? 3617 !has_ctrl(n) ) { // Have loop picked out already? 3618 // During "merge_many_backedges" we fold up several nested loops 3619 // into a single loop. This makes the members of the original 3620 // loop bodies pointing to dead loops; they need to move up 3621 // to the new UNION'd larger loop. I set the _head field of these 3622 // dead loops to NULL and the _parent field points to the owning 3623 // loop. Shades of UNION-FIND algorithm. 3624 IdealLoopTree *ilt; 3625 while( !(ilt = get_loop(n))->_head ) { 3626 // Normally I would use a set_loop here. But in this one special 3627 // case, it is legal (and expected) to change what loop a Node 3628 // belongs to. 3629 _nodes.map(n->_idx, (Node*)(ilt->_parent) ); 3630 } 3631 // Remove safepoints ONLY if I've already seen I don't need one. 3632 // (the old code here would yank a 2nd safepoint after seeing a 3633 // first one, even though the 1st did not dominate in the loop body 3634 // and thus could be avoided indefinitely) 3635 if( !_verify_only && !_verify_me && ilt->_has_sfpt && n->Opcode() == Op_SafePoint && 3636 is_deleteable_safept(n)) { 3637 Node *in = n->in(TypeFunc::Control); 3638 lazy_replace(n,in); // Pull safepoint now 3639 if (ilt->_safepts != NULL) { 3640 ilt->_safepts->yank(n); 3641 } 3642 // Carry on with the recursion "as if" we are walking 3643 // only the control input 3644 if( !visited.test_set( in->_idx ) ) { 3645 worklist.push(in); // Visit this guy later, using worklist 3646 } 3647 // Get next node from nstack: 3648 // - skip n's inputs processing by setting i > cnt; 3649 // - we also will not call set_early_ctrl(n) since 3650 // has_node(n) == true (see the condition above). 3651 i = cnt + 1; 3652 } 3653 } 3654 } // if (i == 0) 3655 3656 // Visit all inputs 3657 bool done = true; // Assume all n's inputs will be processed 3658 while (i < cnt) { 3659 Node *in = n->in(i); 3660 ++i; 3661 if (in == NULL) continue; 3662 if (in->pinned() && !in->is_CFG()) 3663 set_ctrl(in, in->in(0)); 3664 int is_visited = visited.test_set( in->_idx ); 3665 if (!has_node(in)) { // No controlling input yet? 3666 assert( !in->is_CFG(), "CFG Node with no controlling input?" ); 3667 assert( !is_visited, "visit only once" ); 3668 nstack.push(n, i); // Save parent node and next input's index. 3669 nstack_top_n = in; // Process current input now. 3670 nstack_top_i = 0; 3671 done = false; // Not all n's inputs processed. 3672 break; // continue while_nstack_nonempty; 3673 } else if (!is_visited) { 3674 // This guy has a location picked out for him, but has not yet 3675 // been visited. Happens to all CFG nodes, for instance. 3676 // Visit him using the worklist instead of recursion, to break 3677 // cycles. Since he has a location already we do not need to 3678 // find his location before proceeding with the current Node. 3679 worklist.push(in); // Visit this guy later, using worklist 3680 } 3681 } 3682 if (done) { 3683 // All of n's inputs have been processed, complete post-processing. 3684 3685 // Compute earliest point this Node can go. 3686 // CFG, Phi, pinned nodes already know their controlling input. 3687 if (!has_node(n)) { 3688 // Record earliest legal location 3689 set_early_ctrl( n ); 3690 } 3691 if (nstack.is_empty()) { 3692 // Finished all nodes on stack. 3693 // Process next node on the worklist. 3694 break; 3695 } 3696 // Get saved parent node and next input's index. 3697 nstack_top_n = nstack.node(); 3698 nstack_top_i = nstack.index(); 3699 nstack.pop(); 3700 } 3701 } // while (true) 3702 } 3703 } 3704 3705 //------------------------------dom_lca_internal-------------------------------- 3706 // Pair-wise LCA 3707 Node *PhaseIdealLoop::dom_lca_internal( Node *n1, Node *n2 ) const { 3708 if( !n1 ) return n2; // Handle NULL original LCA 3709 assert( n1->is_CFG(), "" ); 3710 assert( n2->is_CFG(), "" ); 3711 // find LCA of all uses 3712 uint d1 = dom_depth(n1); 3713 uint d2 = dom_depth(n2); 3714 while (n1 != n2) { 3715 if (d1 > d2) { 3716 n1 = idom(n1); 3717 d1 = dom_depth(n1); 3718 } else if (d1 < d2) { 3719 n2 = idom(n2); 3720 d2 = dom_depth(n2); 3721 } else { 3722 // Here d1 == d2. Due to edits of the dominator-tree, sections 3723 // of the tree might have the same depth. These sections have 3724 // to be searched more carefully. 3725 3726 // Scan up all the n1's with equal depth, looking for n2. 3727 Node *t1 = idom(n1); 3728 while (dom_depth(t1) == d1) { 3729 if (t1 == n2) return n2; 3730 t1 = idom(t1); 3731 } 3732 // Scan up all the n2's with equal depth, looking for n1. 3733 Node *t2 = idom(n2); 3734 while (dom_depth(t2) == d2) { 3735 if (t2 == n1) return n1; 3736 t2 = idom(t2); 3737 } 3738 // Move up to a new dominator-depth value as well as up the dom-tree. 3739 n1 = t1; 3740 n2 = t2; 3741 d1 = dom_depth(n1); 3742 d2 = dom_depth(n2); 3743 } 3744 } 3745 return n1; 3746 } 3747 3748 //------------------------------compute_idom----------------------------------- 3749 // Locally compute IDOM using dom_lca call. Correct only if the incoming 3750 // IDOMs are correct. 3751 Node *PhaseIdealLoop::compute_idom( Node *region ) const { 3752 assert( region->is_Region(), "" ); 3753 Node *LCA = NULL; 3754 for( uint i = 1; i < region->req(); i++ ) { 3755 if( region->in(i) != C->top() ) 3756 LCA = dom_lca( LCA, region->in(i) ); 3757 } 3758 return LCA; 3759 } 3760 3761 bool PhaseIdealLoop::verify_dominance(Node* n, Node* use, Node* LCA, Node* early) { 3762 bool had_error = false; 3763 #ifdef ASSERT 3764 if (early != C->root()) { 3765 // Make sure that there's a dominance path from LCA to early 3766 Node* d = LCA; 3767 while (d != early) { 3768 if (d == C->root()) { 3769 dump_bad_graph("Bad graph detected in compute_lca_of_uses", n, early, LCA); 3770 tty->print_cr("*** Use %d isn't dominated by def %d ***", use->_idx, n->_idx); 3771 had_error = true; 3772 break; 3773 } 3774 d = idom(d); 3775 } 3776 } 3777 #endif 3778 return had_error; 3779 } 3780 3781 3782 Node* PhaseIdealLoop::compute_lca_of_uses(Node* n, Node* early, bool verify) { 3783 // Compute LCA over list of uses 3784 bool had_error = false; 3785 Node *LCA = NULL; 3786 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax && LCA != early; i++) { 3787 Node* c = n->fast_out(i); 3788 if (_nodes[c->_idx] == NULL) 3789 continue; // Skip the occasional dead node 3790 if( c->is_Phi() ) { // For Phis, we must land above on the path 3791 for( uint j=1; j<c->req(); j++ ) {// For all inputs 3792 if( c->in(j) == n ) { // Found matching input? 3793 Node *use = c->in(0)->in(j); 3794 if (_verify_only && use->is_top()) continue; 3795 LCA = dom_lca_for_get_late_ctrl( LCA, use, n ); 3796 if (verify) had_error = verify_dominance(n, use, LCA, early) || had_error; 3797 } 3798 } 3799 } else { 3800 // For CFG data-users, use is in the block just prior 3801 Node *use = has_ctrl(c) ? get_ctrl(c) : c->in(0); 3802 LCA = dom_lca_for_get_late_ctrl( LCA, use, n ); 3803 if (verify) had_error = verify_dominance(n, use, LCA, early) || had_error; 3804 } 3805 } 3806 assert(!had_error, "bad dominance"); 3807 return LCA; 3808 } 3809 3810 // Check the shape of the graph at the loop entry. In some cases, 3811 // the shape of the graph does not match the shape outlined below. 3812 // That is caused by the Opaque1 node "protecting" the shape of 3813 // the graph being removed by, for example, the IGVN performed 3814 // in PhaseIdealLoop::build_and_optimize(). 3815 // 3816 // After the Opaque1 node has been removed, optimizations (e.g., split-if, 3817 // loop unswitching, and IGVN, or a combination of them) can freely change 3818 // the graph's shape. As a result, the graph shape outlined below cannot 3819 // be guaranteed anymore. 3820 bool PhaseIdealLoop::is_canonical_loop_entry(CountedLoopNode* cl) { 3821 if (!cl->is_main_loop() && !cl->is_post_loop()) { 3822 return false; 3823 } 3824 Node* ctrl = cl->skip_predicates(); 3825 3826 if (ctrl == NULL || (!ctrl->is_IfTrue() && !ctrl->is_IfFalse())) { 3827 return false; 3828 } 3829 Node* iffm = ctrl->in(0); 3830 if (iffm == NULL || !iffm->is_If()) { 3831 return false; 3832 } 3833 Node* bolzm = iffm->in(1); 3834 if (bolzm == NULL || !bolzm->is_Bool()) { 3835 return false; 3836 } 3837 Node* cmpzm = bolzm->in(1); 3838 if (cmpzm == NULL || !cmpzm->is_Cmp()) { 3839 return false; 3840 } 3841 // compares can get conditionally flipped 3842 bool found_opaque = false; 3843 for (uint i = 1; i < cmpzm->req(); i++) { 3844 Node* opnd = cmpzm->in(i); 3845 if (opnd && opnd->Opcode() == Op_Opaque1) { 3846 found_opaque = true; 3847 break; 3848 } 3849 } 3850 if (!found_opaque) { 3851 return false; 3852 } 3853 return true; 3854 } 3855 3856 //------------------------------get_late_ctrl---------------------------------- 3857 // Compute latest legal control. 3858 Node *PhaseIdealLoop::get_late_ctrl( Node *n, Node *early ) { 3859 assert(early != NULL, "early control should not be NULL"); 3860 3861 Node* LCA = compute_lca_of_uses(n, early); 3862 #ifdef ASSERT 3863 if (LCA == C->root() && LCA != early) { 3864 // def doesn't dominate uses so print some useful debugging output 3865 compute_lca_of_uses(n, early, true); 3866 } 3867 #endif 3868 3869 // if this is a load, check for anti-dependent stores 3870 // We use a conservative algorithm to identify potential interfering 3871 // instructions and for rescheduling the load. The users of the memory 3872 // input of this load are examined. Any use which is not a load and is 3873 // dominated by early is considered a potentially interfering store. 3874 // This can produce false positives. 3875 if (n->is_Load() && LCA != early) { 3876 Node_List worklist; 3877 3878 Node *mem = n->in(MemNode::Memory); 3879 for (DUIterator_Fast imax, i = mem->fast_outs(imax); i < imax; i++) { 3880 Node* s = mem->fast_out(i); 3881 worklist.push(s); 3882 } 3883 while(worklist.size() != 0 && LCA != early) { 3884 Node* s = worklist.pop(); 3885 if (s->is_Load() || s->Opcode() == Op_SafePoint) { 3886 continue; 3887 } else if (s->is_MergeMem()) { 3888 for (DUIterator_Fast imax, i = s->fast_outs(imax); i < imax; i++) { 3889 Node* s1 = s->fast_out(i); 3890 worklist.push(s1); 3891 } 3892 } else { 3893 Node *sctrl = has_ctrl(s) ? get_ctrl(s) : s->in(0); 3894 assert(sctrl != NULL || s->outcnt() == 0, "must have control"); 3895 if (sctrl != NULL && !sctrl->is_top() && is_dominator(early, sctrl)) { 3896 LCA = dom_lca_for_get_late_ctrl(LCA, sctrl, n); 3897 } 3898 } 3899 } 3900 } 3901 3902 assert(LCA == find_non_split_ctrl(LCA), "unexpected late control"); 3903 return LCA; 3904 } 3905 3906 // true if CFG node d dominates CFG node n 3907 bool PhaseIdealLoop::is_dominator(Node *d, Node *n) { 3908 if (d == n) 3909 return true; 3910 assert(d->is_CFG() && n->is_CFG(), "must have CFG nodes"); 3911 uint dd = dom_depth(d); 3912 while (dom_depth(n) >= dd) { 3913 if (n == d) 3914 return true; 3915 n = idom(n); 3916 } 3917 return false; 3918 } 3919 3920 //------------------------------dom_lca_for_get_late_ctrl_internal------------- 3921 // Pair-wise LCA with tags. 3922 // Tag each index with the node 'tag' currently being processed 3923 // before advancing up the dominator chain using idom(). 3924 // Later calls that find a match to 'tag' know that this path has already 3925 // been considered in the current LCA (which is input 'n1' by convention). 3926 // Since get_late_ctrl() is only called once for each node, the tag array 3927 // does not need to be cleared between calls to get_late_ctrl(). 3928 // Algorithm trades a larger constant factor for better asymptotic behavior 3929 // 3930 Node *PhaseIdealLoop::dom_lca_for_get_late_ctrl_internal( Node *n1, Node *n2, Node *tag ) { 3931 uint d1 = dom_depth(n1); 3932 uint d2 = dom_depth(n2); 3933 3934 do { 3935 if (d1 > d2) { 3936 // current lca is deeper than n2 3937 _dom_lca_tags.map(n1->_idx, tag); 3938 n1 = idom(n1); 3939 d1 = dom_depth(n1); 3940 } else if (d1 < d2) { 3941 // n2 is deeper than current lca 3942 Node *memo = _dom_lca_tags[n2->_idx]; 3943 if( memo == tag ) { 3944 return n1; // Return the current LCA 3945 } 3946 _dom_lca_tags.map(n2->_idx, tag); 3947 n2 = idom(n2); 3948 d2 = dom_depth(n2); 3949 } else { 3950 // Here d1 == d2. Due to edits of the dominator-tree, sections 3951 // of the tree might have the same depth. These sections have 3952 // to be searched more carefully. 3953 3954 // Scan up all the n1's with equal depth, looking for n2. 3955 _dom_lca_tags.map(n1->_idx, tag); 3956 Node *t1 = idom(n1); 3957 while (dom_depth(t1) == d1) { 3958 if (t1 == n2) return n2; 3959 _dom_lca_tags.map(t1->_idx, tag); 3960 t1 = idom(t1); 3961 } 3962 // Scan up all the n2's with equal depth, looking for n1. 3963 _dom_lca_tags.map(n2->_idx, tag); 3964 Node *t2 = idom(n2); 3965 while (dom_depth(t2) == d2) { 3966 if (t2 == n1) return n1; 3967 _dom_lca_tags.map(t2->_idx, tag); 3968 t2 = idom(t2); 3969 } 3970 // Move up to a new dominator-depth value as well as up the dom-tree. 3971 n1 = t1; 3972 n2 = t2; 3973 d1 = dom_depth(n1); 3974 d2 = dom_depth(n2); 3975 } 3976 } while (n1 != n2); 3977 return n1; 3978 } 3979 3980 //------------------------------init_dom_lca_tags------------------------------ 3981 // Tag could be a node's integer index, 32bits instead of 64bits in some cases 3982 // Intended use does not involve any growth for the array, so it could 3983 // be of fixed size. 3984 void PhaseIdealLoop::init_dom_lca_tags() { 3985 uint limit = C->unique() + 1; 3986 _dom_lca_tags.map( limit, NULL ); 3987 #ifdef ASSERT 3988 for( uint i = 0; i < limit; ++i ) { 3989 assert(_dom_lca_tags[i] == NULL, "Must be distinct from each node pointer"); 3990 } 3991 #endif // ASSERT 3992 } 3993 3994 //------------------------------clear_dom_lca_tags------------------------------ 3995 // Tag could be a node's integer index, 32bits instead of 64bits in some cases 3996 // Intended use does not involve any growth for the array, so it could 3997 // be of fixed size. 3998 void PhaseIdealLoop::clear_dom_lca_tags() { 3999 uint limit = C->unique() + 1; 4000 _dom_lca_tags.map( limit, NULL ); 4001 _dom_lca_tags.clear(); 4002 #ifdef ASSERT 4003 for( uint i = 0; i < limit; ++i ) { 4004 assert(_dom_lca_tags[i] == NULL, "Must be distinct from each node pointer"); 4005 } 4006 #endif // ASSERT 4007 } 4008 4009 //------------------------------build_loop_late-------------------------------- 4010 // Put Data nodes into some loop nest, by setting the _nodes[]->loop mapping. 4011 // Second pass finds latest legal placement, and ideal loop placement. 4012 void PhaseIdealLoop::build_loop_late( VectorSet &visited, Node_List &worklist, Node_Stack &nstack ) { 4013 while (worklist.size() != 0) { 4014 Node *n = worklist.pop(); 4015 // Only visit once 4016 if (visited.test_set(n->_idx)) continue; 4017 uint cnt = n->outcnt(); 4018 uint i = 0; 4019 while (true) { 4020 assert( _nodes[n->_idx], "no dead nodes" ); 4021 // Visit all children 4022 if (i < cnt) { 4023 Node* use = n->raw_out(i); 4024 ++i; 4025 // Check for dead uses. Aggressively prune such junk. It might be 4026 // dead in the global sense, but still have local uses so I cannot 4027 // easily call 'remove_dead_node'. 4028 if( _nodes[use->_idx] != NULL || use->is_top() ) { // Not dead? 4029 // Due to cycles, we might not hit the same fixed point in the verify 4030 // pass as we do in the regular pass. Instead, visit such phis as 4031 // simple uses of the loop head. 4032 if( use->in(0) && (use->is_CFG() || use->is_Phi()) ) { 4033 if( !visited.test(use->_idx) ) 4034 worklist.push(use); 4035 } else if( !visited.test_set(use->_idx) ) { 4036 nstack.push(n, i); // Save parent and next use's index. 4037 n = use; // Process all children of current use. 4038 cnt = use->outcnt(); 4039 i = 0; 4040 } 4041 } else { 4042 // Do not visit around the backedge of loops via data edges. 4043 // push dead code onto a worklist 4044 _deadlist.push(use); 4045 } 4046 } else { 4047 // All of n's children have been processed, complete post-processing. 4048 build_loop_late_post(n); 4049 if (nstack.is_empty()) { 4050 // Finished all nodes on stack. 4051 // Process next node on the worklist. 4052 break; 4053 } 4054 // Get saved parent node and next use's index. Visit the rest of uses. 4055 n = nstack.node(); 4056 cnt = n->outcnt(); 4057 i = nstack.index(); 4058 nstack.pop(); 4059 } 4060 } 4061 } 4062 } 4063 4064 // Verify that no data node is schedules in the outer loop of a strip 4065 // mined loop. 4066 void PhaseIdealLoop::verify_strip_mined_scheduling(Node *n, Node* least) { 4067 #ifdef ASSERT 4068 if (get_loop(least)->_nest == 0) { 4069 return; 4070 } 4071 IdealLoopTree* loop = get_loop(least); 4072 Node* head = loop->_head; 4073 if (head->is_OuterStripMinedLoop()) { 4074 Node* sfpt = head->as_Loop()->outer_safepoint(); 4075 ResourceMark rm; 4076 Unique_Node_List wq; 4077 wq.push(sfpt); 4078 for (uint i = 0; i < wq.size(); i++) { 4079 Node *m = wq.at(i); 4080 for (uint i = 1; i < m->req(); i++) { 4081 Node* nn = m->in(i); 4082 if (nn == n) { 4083 return; 4084 } 4085 if (nn != NULL && has_ctrl(nn) && get_loop(get_ctrl(nn)) == loop) { 4086 wq.push(nn); 4087 } 4088 } 4089 } 4090 ShouldNotReachHere(); 4091 } 4092 #endif 4093 } 4094 4095 4096 //------------------------------build_loop_late_post--------------------------- 4097 // Put Data nodes into some loop nest, by setting the _nodes[]->loop mapping. 4098 // Second pass finds latest legal placement, and ideal loop placement. 4099 void PhaseIdealLoop::build_loop_late_post( Node *n ) { 4100 4101 if (n->req() == 2 && (n->Opcode() == Op_ConvI2L || n->Opcode() == Op_CastII) && !C->major_progress() && !_verify_only) { 4102 _igvn._worklist.push(n); // Maybe we'll normalize it, if no more loops. 4103 } 4104 4105 #ifdef ASSERT 4106 if (_verify_only && !n->is_CFG()) { 4107 // Check def-use domination. 4108 compute_lca_of_uses(n, get_ctrl(n), true /* verify */); 4109 } 4110 #endif 4111 4112 // CFG and pinned nodes already handled 4113 if( n->in(0) ) { 4114 if( n->in(0)->is_top() ) return; // Dead? 4115 4116 // We'd like +VerifyLoopOptimizations to not believe that Mod's/Loads 4117 // _must_ be pinned (they have to observe their control edge of course). 4118 // Unlike Stores (which modify an unallocable resource, the memory 4119 // state), Mods/Loads can float around. So free them up. 4120 bool pinned = true; 4121 switch( n->Opcode() ) { 4122 case Op_DivI: 4123 case Op_DivF: 4124 case Op_DivD: 4125 case Op_ModI: 4126 case Op_ModF: 4127 case Op_ModD: 4128 case Op_LoadB: // Same with Loads; they can sink 4129 case Op_LoadUB: // during loop optimizations. 4130 case Op_LoadUS: 4131 case Op_LoadD: 4132 case Op_LoadF: 4133 case Op_LoadI: 4134 case Op_LoadKlass: 4135 case Op_LoadNKlass: 4136 case Op_LoadL: 4137 case Op_LoadS: 4138 case Op_LoadP: 4139 case Op_LoadN: 4140 case Op_LoadRange: 4141 case Op_LoadD_unaligned: 4142 case Op_LoadL_unaligned: 4143 case Op_StrComp: // Does a bunch of load-like effects 4144 case Op_StrEquals: 4145 case Op_StrIndexOf: 4146 case Op_StrIndexOfChar: 4147 case Op_AryEq: 4148 case Op_HasNegatives: 4149 pinned = false; 4150 } 4151 if( pinned ) { 4152 IdealLoopTree *chosen_loop = get_loop(n->is_CFG() ? n : get_ctrl(n)); 4153 if( !chosen_loop->_child ) // Inner loop? 4154 chosen_loop->_body.push(n); // Collect inner loops 4155 return; 4156 } 4157 } else { // No slot zero 4158 if( n->is_CFG() ) { // CFG with no slot 0 is dead 4159 _nodes.map(n->_idx,0); // No block setting, it's globally dead 4160 return; 4161 } 4162 assert(!n->is_CFG() || n->outcnt() == 0, ""); 4163 } 4164 4165 // Do I have a "safe range" I can select over? 4166 Node *early = get_ctrl(n);// Early location already computed 4167 4168 // Compute latest point this Node can go 4169 Node *LCA = get_late_ctrl( n, early ); 4170 // LCA is NULL due to uses being dead 4171 if( LCA == NULL ) { 4172 #ifdef ASSERT 4173 for (DUIterator i1 = n->outs(); n->has_out(i1); i1++) { 4174 assert( _nodes[n->out(i1)->_idx] == NULL, "all uses must also be dead"); 4175 } 4176 #endif 4177 _nodes.map(n->_idx, 0); // This node is useless 4178 _deadlist.push(n); 4179 return; 4180 } 4181 assert(LCA != NULL && !LCA->is_top(), "no dead nodes"); 4182 4183 Node *legal = LCA; // Walk 'legal' up the IDOM chain 4184 Node *least = legal; // Best legal position so far 4185 while( early != legal ) { // While not at earliest legal 4186 #ifdef ASSERT 4187 if (legal->is_Start() && !early->is_Root()) { 4188 // Bad graph. Print idom path and fail. 4189 dump_bad_graph("Bad graph detected in build_loop_late", n, early, LCA); 4190 assert(false, "Bad graph detected in build_loop_late"); 4191 } 4192 #endif 4193 // Find least loop nesting depth 4194 legal = idom(legal); // Bump up the IDOM tree 4195 // Check for lower nesting depth 4196 if( get_loop(legal)->_nest < get_loop(least)->_nest ) 4197 least = legal; 4198 } 4199 assert(early == legal || legal != C->root(), "bad dominance of inputs"); 4200 4201 // Try not to place code on a loop entry projection 4202 // which can inhibit range check elimination. 4203 if (least != early) { 4204 Node* ctrl_out = least->unique_ctrl_out(); 4205 if (ctrl_out && ctrl_out->is_Loop() && 4206 least == ctrl_out->in(LoopNode::EntryControl) && 4207 (ctrl_out->is_CountedLoop() || ctrl_out->is_OuterStripMinedLoop())) { 4208 Node* least_dom = idom(least); 4209 if (get_loop(least_dom)->is_member(get_loop(least))) { 4210 least = least_dom; 4211 } 4212 } 4213 } 4214 4215 #ifdef ASSERT 4216 // If verifying, verify that 'verify_me' has a legal location 4217 // and choose it as our location. 4218 if( _verify_me ) { 4219 Node *v_ctrl = _verify_me->get_ctrl_no_update(n); 4220 Node *legal = LCA; 4221 while( early != legal ) { // While not at earliest legal 4222 if( legal == v_ctrl ) break; // Check for prior good location 4223 legal = idom(legal) ;// Bump up the IDOM tree 4224 } 4225 // Check for prior good location 4226 if( legal == v_ctrl ) least = legal; // Keep prior if found 4227 } 4228 #endif 4229 4230 // Assign discovered "here or above" point 4231 least = find_non_split_ctrl(least); 4232 verify_strip_mined_scheduling(n, least); 4233 set_ctrl(n, least); 4234 4235 // Collect inner loop bodies 4236 IdealLoopTree *chosen_loop = get_loop(least); 4237 if( !chosen_loop->_child ) // Inner loop? 4238 chosen_loop->_body.push(n);// Collect inner loops 4239 } 4240 4241 #ifdef ASSERT 4242 void PhaseIdealLoop::dump_bad_graph(const char* msg, Node* n, Node* early, Node* LCA) { 4243 tty->print_cr("%s", msg); 4244 tty->print("n: "); n->dump(); 4245 tty->print("early(n): "); early->dump(); 4246 if (n->in(0) != NULL && !n->in(0)->is_top() && 4247 n->in(0) != early && !n->in(0)->is_Root()) { 4248 tty->print("n->in(0): "); n->in(0)->dump(); 4249 } 4250 for (uint i = 1; i < n->req(); i++) { 4251 Node* in1 = n->in(i); 4252 if (in1 != NULL && in1 != n && !in1->is_top()) { 4253 tty->print("n->in(%d): ", i); in1->dump(); 4254 Node* in1_early = get_ctrl(in1); 4255 tty->print("early(n->in(%d)): ", i); in1_early->dump(); 4256 if (in1->in(0) != NULL && !in1->in(0)->is_top() && 4257 in1->in(0) != in1_early && !in1->in(0)->is_Root()) { 4258 tty->print("n->in(%d)->in(0): ", i); in1->in(0)->dump(); 4259 } 4260 for (uint j = 1; j < in1->req(); j++) { 4261 Node* in2 = in1->in(j); 4262 if (in2 != NULL && in2 != n && in2 != in1 && !in2->is_top()) { 4263 tty->print("n->in(%d)->in(%d): ", i, j); in2->dump(); 4264 Node* in2_early = get_ctrl(in2); 4265 tty->print("early(n->in(%d)->in(%d)): ", i, j); in2_early->dump(); 4266 if (in2->in(0) != NULL && !in2->in(0)->is_top() && 4267 in2->in(0) != in2_early && !in2->in(0)->is_Root()) { 4268 tty->print("n->in(%d)->in(%d)->in(0): ", i, j); in2->in(0)->dump(); 4269 } 4270 } 4271 } 4272 } 4273 } 4274 tty->cr(); 4275 tty->print("LCA(n): "); LCA->dump(); 4276 for (uint i = 0; i < n->outcnt(); i++) { 4277 Node* u1 = n->raw_out(i); 4278 if (u1 == n) 4279 continue; 4280 tty->print("n->out(%d): ", i); u1->dump(); 4281 if (u1->is_CFG()) { 4282 for (uint j = 0; j < u1->outcnt(); j++) { 4283 Node* u2 = u1->raw_out(j); 4284 if (u2 != u1 && u2 != n && u2->is_CFG()) { 4285 tty->print("n->out(%d)->out(%d): ", i, j); u2->dump(); 4286 } 4287 } 4288 } else { 4289 Node* u1_later = get_ctrl(u1); 4290 tty->print("later(n->out(%d)): ", i); u1_later->dump(); 4291 if (u1->in(0) != NULL && !u1->in(0)->is_top() && 4292 u1->in(0) != u1_later && !u1->in(0)->is_Root()) { 4293 tty->print("n->out(%d)->in(0): ", i); u1->in(0)->dump(); 4294 } 4295 for (uint j = 0; j < u1->outcnt(); j++) { 4296 Node* u2 = u1->raw_out(j); 4297 if (u2 == n || u2 == u1) 4298 continue; 4299 tty->print("n->out(%d)->out(%d): ", i, j); u2->dump(); 4300 if (!u2->is_CFG()) { 4301 Node* u2_later = get_ctrl(u2); 4302 tty->print("later(n->out(%d)->out(%d)): ", i, j); u2_later->dump(); 4303 if (u2->in(0) != NULL && !u2->in(0)->is_top() && 4304 u2->in(0) != u2_later && !u2->in(0)->is_Root()) { 4305 tty->print("n->out(%d)->in(0): ", i); u2->in(0)->dump(); 4306 } 4307 } 4308 } 4309 } 4310 } 4311 tty->cr(); 4312 int ct = 0; 4313 Node *dbg_legal = LCA; 4314 while(!dbg_legal->is_Start() && ct < 100) { 4315 tty->print("idom[%d] ",ct); dbg_legal->dump(); 4316 ct++; 4317 dbg_legal = idom(dbg_legal); 4318 } 4319 tty->cr(); 4320 } 4321 #endif 4322 4323 #ifndef PRODUCT 4324 //------------------------------dump------------------------------------------- 4325 void PhaseIdealLoop::dump( ) const { 4326 ResourceMark rm; 4327 Arena* arena = Thread::current()->resource_area(); 4328 Node_Stack stack(arena, C->live_nodes() >> 2); 4329 Node_List rpo_list; 4330 VectorSet visited(arena); 4331 visited.set(C->top()->_idx); 4332 rpo( C->root(), stack, visited, rpo_list ); 4333 // Dump root loop indexed by last element in PO order 4334 dump( _ltree_root, rpo_list.size(), rpo_list ); 4335 } 4336 4337 void PhaseIdealLoop::dump( IdealLoopTree *loop, uint idx, Node_List &rpo_list ) const { 4338 loop->dump_head(); 4339 4340 // Now scan for CFG nodes in the same loop 4341 for( uint j=idx; j > 0; j-- ) { 4342 Node *n = rpo_list[j-1]; 4343 if( !_nodes[n->_idx] ) // Skip dead nodes 4344 continue; 4345 if( get_loop(n) != loop ) { // Wrong loop nest 4346 if( get_loop(n)->_head == n && // Found nested loop? 4347 get_loop(n)->_parent == loop ) 4348 dump(get_loop(n),rpo_list.size(),rpo_list); // Print it nested-ly 4349 continue; 4350 } 4351 4352 // Dump controlling node 4353 for( uint x = 0; x < loop->_nest; x++ ) 4354 tty->print(" "); 4355 tty->print("C"); 4356 if( n == C->root() ) { 4357 n->dump(); 4358 } else { 4359 Node* cached_idom = idom_no_update(n); 4360 Node *computed_idom = n->in(0); 4361 if( n->is_Region() ) { 4362 computed_idom = compute_idom(n); 4363 // computed_idom() will return n->in(0) when idom(n) is an IfNode (or 4364 // any MultiBranch ctrl node), so apply a similar transform to 4365 // the cached idom returned from idom_no_update. 4366 cached_idom = find_non_split_ctrl(cached_idom); 4367 } 4368 tty->print(" ID:%d",computed_idom->_idx); 4369 n->dump(); 4370 if( cached_idom != computed_idom ) { 4371 tty->print_cr("*** BROKEN IDOM! Computed as: %d, cached as: %d", 4372 computed_idom->_idx, cached_idom->_idx); 4373 } 4374 } 4375 // Dump nodes it controls 4376 for( uint k = 0; k < _nodes.Size(); k++ ) { 4377 // (k < C->unique() && get_ctrl(find(k)) == n) 4378 if (k < C->unique() && _nodes[k] == (Node*)((intptr_t)n + 1)) { 4379 Node *m = C->root()->find(k); 4380 if( m && m->outcnt() > 0 ) { 4381 if (!(has_ctrl(m) && get_ctrl_no_update(m) == n)) { 4382 tty->print_cr("*** BROKEN CTRL ACCESSOR! _nodes[k] is %p, ctrl is %p", 4383 _nodes[k], has_ctrl(m) ? get_ctrl_no_update(m) : NULL); 4384 } 4385 for( uint j = 0; j < loop->_nest; j++ ) 4386 tty->print(" "); 4387 tty->print(" "); 4388 m->dump(); 4389 } 4390 } 4391 } 4392 } 4393 } 4394 4395 // Collect a R-P-O for the whole CFG. 4396 // Result list is in post-order (scan backwards for RPO) 4397 void PhaseIdealLoop::rpo( Node *start, Node_Stack &stk, VectorSet &visited, Node_List &rpo_list ) const { 4398 stk.push(start, 0); 4399 visited.set(start->_idx); 4400 4401 while (stk.is_nonempty()) { 4402 Node* m = stk.node(); 4403 uint idx = stk.index(); 4404 if (idx < m->outcnt()) { 4405 stk.set_index(idx + 1); 4406 Node* n = m->raw_out(idx); 4407 if (n->is_CFG() && !visited.test_set(n->_idx)) { 4408 stk.push(n, 0); 4409 } 4410 } else { 4411 rpo_list.push(m); 4412 stk.pop(); 4413 } 4414 } 4415 } 4416 #endif 4417 4418 4419 //============================================================================= 4420 //------------------------------LoopTreeIterator----------------------------------- 4421 4422 // Advance to next loop tree using a preorder, left-to-right traversal. 4423 void LoopTreeIterator::next() { 4424 assert(!done(), "must not be done."); 4425 if (_curnt->_child != NULL) { 4426 _curnt = _curnt->_child; 4427 } else if (_curnt->_next != NULL) { 4428 _curnt = _curnt->_next; 4429 } else { 4430 while (_curnt != _root && _curnt->_next == NULL) { 4431 _curnt = _curnt->_parent; 4432 } 4433 if (_curnt == _root) { 4434 _curnt = NULL; 4435 assert(done(), "must be done."); 4436 } else { 4437 assert(_curnt->_next != NULL, "must be more to do"); 4438 _curnt = _curnt->_next; 4439 } 4440 } 4441 }