1 /* 2 * Copyright (c) 2011, 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 "opto/loopnode.hpp" 27 #include "opto/addnode.hpp" 28 #include "opto/callnode.hpp" 29 #include "opto/connode.hpp" 30 #include "opto/convertnode.hpp" 31 #include "opto/loopnode.hpp" 32 #include "opto/matcher.hpp" 33 #include "opto/mulnode.hpp" 34 #include "opto/opaquenode.hpp" 35 #include "opto/rootnode.hpp" 36 #include "opto/subnode.hpp" 37 #include <fenv.h> 38 #include <math.h> 39 40 /* 41 * The general idea of Loop Predication is to insert a predicate on the entry 42 * path to a loop, and raise a uncommon trap if the check of the condition fails. 43 * The condition checks are promoted from inside the loop body, and thus 44 * the checks inside the loop could be eliminated. Currently, loop predication 45 * optimization has been applied to remove array range check and loop invariant 46 * checks (such as null checks). 47 */ 48 49 //-------------------------------register_control------------------------- 50 void PhaseIdealLoop::register_control(Node* n, IdealLoopTree *loop, Node* pred) { 51 assert(n->is_CFG(), "must be control node"); 52 _igvn.register_new_node_with_optimizer(n); 53 loop->_body.push(n); 54 set_loop(n, loop); 55 // When called from beautify_loops() idom is not constructed yet. 56 if (_idom != NULL) { 57 set_idom(n, pred, dom_depth(pred)); 58 } 59 } 60 61 //------------------------------create_new_if_for_predicate------------------------ 62 // create a new if above the uct_if_pattern for the predicate to be promoted. 63 // 64 // before after 65 // ---------- ---------- 66 // ctrl ctrl 67 // | | 68 // | | 69 // v v 70 // iff new_iff 71 // / \ / \ 72 // / \ / \ 73 // v v v v 74 // uncommon_proj cont_proj if_uct if_cont 75 // \ | | | | 76 // \ | | | | 77 // v v v | v 78 // rgn loop | iff 79 // | | / \ 80 // | | / \ 81 // v | v v 82 // uncommon_trap | uncommon_proj cont_proj 83 // \ \ | | 84 // \ \ | | 85 // v v v v 86 // rgn loop 87 // | 88 // | 89 // v 90 // uncommon_trap 91 // 92 // 93 // We will create a region to guard the uct call if there is no one there. 94 // The true projection (if_cont) of the new_iff is returned. 95 // This code is also used to clone predicates to cloned loops. 96 ProjNode* PhaseIdealLoop::create_new_if_for_predicate(ProjNode* cont_proj, Node* new_entry, 97 Deoptimization::DeoptReason reason, 98 int opcode) { 99 assert(cont_proj->is_uncommon_trap_if_pattern(reason), "must be a uct if pattern!"); 100 IfNode* iff = cont_proj->in(0)->as_If(); 101 102 ProjNode *uncommon_proj = iff->proj_out(1 - cont_proj->_con); 103 Node *rgn = uncommon_proj->unique_ctrl_out(); 104 assert(rgn->is_Region() || rgn->is_Call(), "must be a region or call uct"); 105 106 uint proj_index = 1; // region's edge corresponding to uncommon_proj 107 if (!rgn->is_Region()) { // create a region to guard the call 108 assert(rgn->is_Call(), "must be call uct"); 109 CallNode* call = rgn->as_Call(); 110 IdealLoopTree* loop = get_loop(call); 111 rgn = new RegionNode(1); 112 rgn->add_req(uncommon_proj); 113 register_control(rgn, loop, uncommon_proj); 114 _igvn.replace_input_of(call, 0, rgn); 115 // When called from beautify_loops() idom is not constructed yet. 116 if (_idom != NULL) { 117 set_idom(call, rgn, dom_depth(rgn)); 118 } 119 for (DUIterator_Fast imax, i = uncommon_proj->fast_outs(imax); i < imax; i++) { 120 Node* n = uncommon_proj->fast_out(i); 121 if (n->is_Load() || n->is_Store()) { 122 _igvn.replace_input_of(n, 0, rgn); 123 --i; --imax; 124 } 125 } 126 } else { 127 // Find region's edge corresponding to uncommon_proj 128 for (; proj_index < rgn->req(); proj_index++) 129 if (rgn->in(proj_index) == uncommon_proj) break; 130 assert(proj_index < rgn->req(), "sanity"); 131 } 132 133 Node* entry = iff->in(0); 134 if (new_entry != NULL) { 135 // Clonning the predicate to new location. 136 entry = new_entry; 137 } 138 // Create new_iff 139 IdealLoopTree* lp = get_loop(entry); 140 IfNode* new_iff = NULL; 141 if (opcode == Op_If) { 142 new_iff = new IfNode(entry, iff->in(1), iff->_prob, iff->_fcnt); 143 } else { 144 assert(opcode == Op_RangeCheck, "no other if variant here"); 145 new_iff = new RangeCheckNode(entry, iff->in(1), iff->_prob, iff->_fcnt); 146 } 147 register_control(new_iff, lp, entry); 148 Node *if_cont = new IfTrueNode(new_iff); 149 Node *if_uct = new IfFalseNode(new_iff); 150 if (cont_proj->is_IfFalse()) { 151 // Swap 152 Node* tmp = if_uct; if_uct = if_cont; if_cont = tmp; 153 } 154 register_control(if_cont, lp, new_iff); 155 register_control(if_uct, get_loop(rgn), new_iff); 156 157 // if_uct to rgn 158 _igvn.hash_delete(rgn); 159 rgn->add_req(if_uct); 160 // When called from beautify_loops() idom is not constructed yet. 161 if (_idom != NULL) { 162 Node* ridom = idom(rgn); 163 Node* nrdom = dom_lca(ridom, new_iff); 164 set_idom(rgn, nrdom, dom_depth(rgn)); 165 } 166 167 // If rgn has phis add new edges which has the same 168 // value as on original uncommon_proj pass. 169 assert(rgn->in(rgn->req() -1) == if_uct, "new edge should be last"); 170 bool has_phi = false; 171 for (DUIterator_Fast imax, i = rgn->fast_outs(imax); i < imax; i++) { 172 Node* use = rgn->fast_out(i); 173 if (use->is_Phi() && use->outcnt() > 0) { 174 assert(use->in(0) == rgn, ""); 175 _igvn.rehash_node_delayed(use); 176 use->add_req(use->in(proj_index)); 177 has_phi = true; 178 } 179 } 180 assert(!has_phi || rgn->req() > 3, "no phis when region is created"); 181 182 if (new_entry == NULL) { 183 // Attach if_cont to iff 184 _igvn.replace_input_of(iff, 0, if_cont); 185 if (_idom != NULL) { 186 set_idom(iff, if_cont, dom_depth(iff)); 187 } 188 } 189 return if_cont->as_Proj(); 190 } 191 192 //------------------------------create_new_if_for_predicate------------------------ 193 // Create a new if below new_entry for the predicate to be cloned (IGVN optimization) 194 ProjNode* PhaseIterGVN::create_new_if_for_predicate(ProjNode* cont_proj, Node* new_entry, 195 Deoptimization::DeoptReason reason, 196 int opcode) { 197 assert(new_entry != 0, "only used for clone predicate"); 198 assert(cont_proj->is_uncommon_trap_if_pattern(reason), "must be a uct if pattern!"); 199 IfNode* iff = cont_proj->in(0)->as_If(); 200 201 ProjNode *uncommon_proj = iff->proj_out(1 - cont_proj->_con); 202 Node *rgn = uncommon_proj->unique_ctrl_out(); 203 assert(rgn->is_Region() || rgn->is_Call(), "must be a region or call uct"); 204 205 uint proj_index = 1; // region's edge corresponding to uncommon_proj 206 if (!rgn->is_Region()) { // create a region to guard the call 207 assert(rgn->is_Call(), "must be call uct"); 208 CallNode* call = rgn->as_Call(); 209 rgn = new RegionNode(1); 210 register_new_node_with_optimizer(rgn); 211 rgn->add_req(uncommon_proj); 212 replace_input_of(call, 0, rgn); 213 } else { 214 // Find region's edge corresponding to uncommon_proj 215 for (; proj_index < rgn->req(); proj_index++) 216 if (rgn->in(proj_index) == uncommon_proj) break; 217 assert(proj_index < rgn->req(), "sanity"); 218 } 219 220 // Create new_iff in new location. 221 IfNode* new_iff = NULL; 222 if (opcode == Op_If) { 223 new_iff = new IfNode(new_entry, iff->in(1), iff->_prob, iff->_fcnt); 224 } else { 225 assert(opcode == Op_RangeCheck, "no other if variant here"); 226 new_iff = new RangeCheckNode(new_entry, iff->in(1), iff->_prob, iff->_fcnt); 227 } 228 229 register_new_node_with_optimizer(new_iff); 230 Node *if_cont = new IfTrueNode(new_iff); 231 Node *if_uct = new IfFalseNode(new_iff); 232 if (cont_proj->is_IfFalse()) { 233 // Swap 234 Node* tmp = if_uct; if_uct = if_cont; if_cont = tmp; 235 } 236 register_new_node_with_optimizer(if_cont); 237 register_new_node_with_optimizer(if_uct); 238 239 // if_uct to rgn 240 hash_delete(rgn); 241 rgn->add_req(if_uct); 242 243 // If rgn has phis add corresponding new edges which has the same 244 // value as on original uncommon_proj pass. 245 assert(rgn->in(rgn->req() -1) == if_uct, "new edge should be last"); 246 bool has_phi = false; 247 for (DUIterator_Fast imax, i = rgn->fast_outs(imax); i < imax; i++) { 248 Node* use = rgn->fast_out(i); 249 if (use->is_Phi() && use->outcnt() > 0) { 250 rehash_node_delayed(use); 251 use->add_req(use->in(proj_index)); 252 has_phi = true; 253 } 254 } 255 assert(!has_phi || rgn->req() > 3, "no phis when region is created"); 256 257 return if_cont->as_Proj(); 258 } 259 260 //--------------------------clone_predicate----------------------- 261 ProjNode* PhaseIdealLoop::clone_predicate(ProjNode* predicate_proj, Node* new_entry, 262 Deoptimization::DeoptReason reason, 263 PhaseIdealLoop* loop_phase, 264 PhaseIterGVN* igvn) { 265 ProjNode* new_predicate_proj; 266 if (loop_phase != NULL) { 267 new_predicate_proj = loop_phase->create_new_if_for_predicate(predicate_proj, new_entry, reason, Op_If); 268 } else { 269 new_predicate_proj = igvn->create_new_if_for_predicate(predicate_proj, new_entry, reason, Op_If); 270 } 271 IfNode* iff = new_predicate_proj->in(0)->as_If(); 272 Node* ctrl = iff->in(0); 273 274 // Match original condition since predicate's projections could be swapped. 275 assert(predicate_proj->in(0)->in(1)->in(1)->Opcode()==Op_Opaque1, "must be"); 276 Node* opq = new Opaque1Node(igvn->C, predicate_proj->in(0)->in(1)->in(1)->in(1)); 277 igvn->C->add_predicate_opaq(opq); 278 279 Node* bol = new Conv2BNode(opq); 280 if (loop_phase != NULL) { 281 loop_phase->register_new_node(opq, ctrl); 282 loop_phase->register_new_node(bol, ctrl); 283 } else { 284 igvn->register_new_node_with_optimizer(opq); 285 igvn->register_new_node_with_optimizer(bol); 286 } 287 igvn->hash_delete(iff); 288 iff->set_req(1, bol); 289 return new_predicate_proj; 290 } 291 292 293 //--------------------------clone_loop_predicates----------------------- 294 // Interface from IGVN 295 Node* PhaseIterGVN::clone_loop_predicates(Node* old_entry, Node* new_entry, bool clone_limit_check) { 296 return PhaseIdealLoop::clone_loop_predicates(old_entry, new_entry, clone_limit_check, NULL, this); 297 } 298 299 // Interface from PhaseIdealLoop 300 Node* PhaseIdealLoop::clone_loop_predicates(Node* old_entry, Node* new_entry, bool clone_limit_check) { 301 return clone_loop_predicates(old_entry, new_entry, clone_limit_check, this, &this->_igvn); 302 } 303 304 void PhaseIdealLoop::clone_loop_predicates_fix_mem(ProjNode* dom_proj , ProjNode* proj, 305 PhaseIdealLoop* loop_phase, 306 PhaseIterGVN* igvn) { 307 Compile* C = NULL; 308 if (loop_phase != NULL) { 309 igvn = &loop_phase->igvn(); 310 } 311 C = igvn->C; 312 ProjNode* other_dom_proj = dom_proj->in(0)->as_Multi()->proj_out(1-dom_proj->_con); 313 Node* dom_r = other_dom_proj->unique_ctrl_out(); 314 if (dom_r->is_Region()) { 315 assert(dom_r->unique_ctrl_out()->is_Call(), "unc expected"); 316 ProjNode* other_proj = proj->in(0)->as_Multi()->proj_out(1-proj->_con); 317 Node* r = other_proj->unique_ctrl_out(); 318 assert(r->is_Region() && r->unique_ctrl_out()->is_Call(), "cloned predicate should have caused region to be added"); 319 for (DUIterator_Fast imax, i = dom_r->fast_outs(imax); i < imax; i++) { 320 Node* dom_use = dom_r->fast_out(i); 321 if (dom_use->is_Phi() && dom_use->bottom_type() == Type::MEMORY) { 322 assert(dom_use->in(0) == dom_r, ""); 323 Node* phi = NULL; 324 for (DUIterator_Fast jmax, j = r->fast_outs(jmax); j < jmax; j++) { 325 Node* use = r->fast_out(j); 326 if (use->is_Phi() && use->bottom_type() == Type::MEMORY && 327 use->adr_type() == dom_use->adr_type()) { 328 assert(use->in(0) == r, ""); 329 assert(phi == NULL, "only one phi"); 330 phi = use; 331 } 332 } 333 if (phi == NULL) { 334 const TypePtr* adr_type = dom_use->adr_type(); 335 int alias = C->get_alias_index(adr_type); 336 Node* call = r->unique_ctrl_out(); 337 Node* mem = call->in(TypeFunc::Memory); 338 MergeMemNode* mm = NULL; 339 if (mem->is_MergeMem()) { 340 mm = mem->clone()->as_MergeMem(); 341 if (adr_type == TypePtr::BOTTOM) { 342 mem = mem->as_MergeMem()->base_memory(); 343 } else { 344 mem = mem->as_MergeMem()->memory_at(alias); 345 } 346 } else { 347 mm = MergeMemNode::make(mem); 348 } 349 phi = PhiNode::make(r, mem, Type::MEMORY, adr_type); 350 if (adr_type == TypePtr::BOTTOM) { 351 mm->set_base_memory(phi); 352 } else { 353 mm->set_memory_at(alias, phi); 354 } 355 if (loop_phase != NULL) { 356 loop_phase->register_new_node(mm, r); 357 loop_phase->register_new_node(phi, r); 358 } else { 359 igvn->register_new_node_with_optimizer(mm); 360 igvn->register_new_node_with_optimizer(phi); 361 } 362 igvn->replace_input_of(call, TypeFunc::Memory, mm); 363 } 364 igvn->replace_input_of(phi, r->find_edge(other_proj), dom_use->in(dom_r->find_edge(other_dom_proj))); 365 } 366 } 367 } 368 } 369 370 371 // Clone loop predicates to cloned loops (peeled, unswitched, split_if). 372 Node* PhaseIdealLoop::clone_loop_predicates(Node* old_entry, Node* new_entry, 373 bool clone_limit_check, 374 PhaseIdealLoop* loop_phase, 375 PhaseIterGVN* igvn) { 376 #ifdef ASSERT 377 if (new_entry == NULL || !(new_entry->is_Proj() || new_entry->is_Region() || new_entry->is_SafePoint())) { 378 if (new_entry != NULL) 379 new_entry->dump(); 380 assert(false, "not IfTrue, IfFalse, Region or SafePoint"); 381 } 382 #endif 383 // Search original predicates 384 Node* entry = old_entry; 385 ProjNode* limit_check_proj = NULL; 386 limit_check_proj = find_predicate_insertion_point(entry, Deoptimization::Reason_loop_limit_check); 387 if (limit_check_proj != NULL) { 388 entry = skip_loop_predicates(entry); 389 } 390 ProjNode* profile_predicate_proj = NULL; 391 ProjNode* predicate_proj = NULL; 392 if (UseProfiledLoopPredicate) { 393 profile_predicate_proj = find_predicate_insertion_point(entry, Deoptimization::Reason_profile_predicate); 394 if (profile_predicate_proj != NULL) { 395 entry = skip_loop_predicates(entry); 396 } 397 } 398 if (UseLoopPredicate) { 399 predicate_proj = find_predicate_insertion_point(entry, Deoptimization::Reason_predicate); 400 } 401 if (predicate_proj != NULL) { // right pattern that can be used by loop predication 402 // clone predicate 403 ProjNode* proj = clone_predicate(predicate_proj, new_entry, 404 Deoptimization::Reason_predicate, 405 loop_phase, igvn); 406 assert(proj != NULL, "IfTrue or IfFalse after clone predicate"); 407 new_entry = proj; 408 if (TraceLoopPredicate) { 409 tty->print("Loop Predicate cloned: "); 410 debug_only( new_entry->in(0)->dump(); ); 411 } 412 if (profile_predicate_proj != NULL) { 413 // A node that produces memory may be out of loop and depend on 414 // a profiled predicates. In that case the memory state at the 415 // end of profiled predicates and at the end of predicates are 416 // not the same. The cloned predicates are dominated by the 417 // profiled predicates but may have the wrong memory 418 // state. Update it. 419 clone_loop_predicates_fix_mem(profile_predicate_proj, proj, loop_phase, igvn); 420 } 421 } 422 if (profile_predicate_proj != NULL) { // right pattern that can be used by loop predication 423 // clone predicate 424 new_entry = clone_predicate(profile_predicate_proj, new_entry, 425 Deoptimization::Reason_profile_predicate, 426 loop_phase, igvn); 427 assert(new_entry != NULL && new_entry->is_Proj(), "IfTrue or IfFalse after clone predicate"); 428 if (TraceLoopPredicate) { 429 tty->print("Loop Predicate cloned: "); 430 debug_only( new_entry->in(0)->dump(); ); 431 } 432 } 433 if (limit_check_proj != NULL && clone_limit_check) { 434 // Clone loop limit check last to insert it before loop. 435 // Don't clone a limit check which was already finalized 436 // for this counted loop (only one limit check is needed). 437 new_entry = clone_predicate(limit_check_proj, new_entry, 438 Deoptimization::Reason_loop_limit_check, 439 loop_phase, igvn); 440 assert(new_entry != NULL && new_entry->is_Proj(), "IfTrue or IfFalse after clone limit check"); 441 if (TraceLoopLimitCheck) { 442 tty->print("Loop Limit Check cloned: "); 443 debug_only( new_entry->in(0)->dump(); ) 444 } 445 } 446 return new_entry; 447 } 448 449 //--------------------------skip_loop_predicates------------------------------ 450 // Skip related predicates. 451 Node* PhaseIdealLoop::skip_loop_predicates(Node* entry) { 452 IfNode* iff = entry->in(0)->as_If(); 453 ProjNode* uncommon_proj = iff->proj_out(1 - entry->as_Proj()->_con); 454 Node* rgn = uncommon_proj->unique_ctrl_out(); 455 assert(rgn->is_Region() || rgn->is_Call(), "must be a region or call uct"); 456 entry = entry->in(0)->in(0); 457 while (entry != NULL && entry->is_Proj() && entry->in(0)->is_If()) { 458 uncommon_proj = entry->in(0)->as_If()->proj_out(1 - entry->as_Proj()->_con); 459 if (uncommon_proj->unique_ctrl_out() != rgn) 460 break; 461 entry = entry->in(0)->in(0); 462 } 463 return entry; 464 } 465 466 Node* PhaseIdealLoop::skip_all_loop_predicates(Node* entry) { 467 Node* predicate = NULL; 468 predicate = find_predicate_insertion_point(entry, Deoptimization::Reason_loop_limit_check); 469 if (predicate != NULL) { 470 entry = skip_loop_predicates(entry); 471 } 472 if (UseProfiledLoopPredicate) { 473 predicate = find_predicate_insertion_point(entry, Deoptimization::Reason_profile_predicate); 474 if (predicate != NULL) { // right pattern that can be used by loop predication 475 entry = skip_loop_predicates(entry); 476 } 477 } 478 if (UseLoopPredicate) { 479 predicate = find_predicate_insertion_point(entry, Deoptimization::Reason_predicate); 480 if (predicate != NULL) { // right pattern that can be used by loop predication 481 entry = skip_loop_predicates(entry); 482 } 483 } 484 return entry; 485 } 486 487 //--------------------------find_predicate_insertion_point------------------- 488 // Find a good location to insert a predicate 489 ProjNode* PhaseIdealLoop::find_predicate_insertion_point(Node* start_c, Deoptimization::DeoptReason reason) { 490 if (start_c == NULL || !start_c->is_Proj()) 491 return NULL; 492 if (start_c->as_Proj()->is_uncommon_trap_if_pattern(reason)) { 493 return start_c->as_Proj(); 494 } 495 return NULL; 496 } 497 498 //--------------------------find_predicate------------------------------------ 499 // Find a predicate 500 Node* PhaseIdealLoop::find_predicate(Node* entry) { 501 Node* predicate = NULL; 502 predicate = find_predicate_insertion_point(entry, Deoptimization::Reason_loop_limit_check); 503 if (predicate != NULL) { // right pattern that can be used by loop predication 504 return entry; 505 } 506 if (UseLoopPredicate) { 507 predicate = find_predicate_insertion_point(entry, Deoptimization::Reason_predicate); 508 if (predicate != NULL) { // right pattern that can be used by loop predication 509 return entry; 510 } 511 } 512 if (UseProfiledLoopPredicate) { 513 predicate = find_predicate_insertion_point(entry, Deoptimization::Reason_profile_predicate); 514 if (predicate != NULL) { // right pattern that can be used by loop predication 515 return entry; 516 } 517 } 518 return NULL; 519 } 520 521 //------------------------------Invariance----------------------------------- 522 // Helper class for loop_predication_impl to compute invariance on the fly and 523 // clone invariants. 524 class Invariance : public StackObj { 525 VectorSet _visited, _invariant; 526 Node_Stack _stack; 527 VectorSet _clone_visited; 528 Node_List _old_new; // map of old to new (clone) 529 IdealLoopTree* _lpt; 530 PhaseIdealLoop* _phase; 531 532 // Helper function to set up the invariance for invariance computation 533 // If n is a known invariant, set up directly. Otherwise, look up the 534 // the possibility to push n onto the stack for further processing. 535 void visit(Node* use, Node* n) { 536 if (_lpt->is_invariant(n)) { // known invariant 537 _invariant.set(n->_idx); 538 } else if (!n->is_CFG()) { 539 if (n->Opcode() == Op_ShenandoahWriteBarrier) { 540 return; 541 } 542 Node *n_ctrl = _phase->ctrl_or_self(n); 543 Node *u_ctrl = _phase->ctrl_or_self(use); // self if use is a CFG 544 if (_phase->is_dominator(n_ctrl, u_ctrl)) { 545 _stack.push(n, n->in(0) == NULL ? 1 : 0); 546 } 547 } 548 } 549 550 // Compute invariance for "the_node" and (possibly) all its inputs recursively 551 // on the fly 552 void compute_invariance(Node* n) { 553 assert(_visited.test(n->_idx), "must be"); 554 visit(n, n); 555 while (_stack.is_nonempty()) { 556 Node* n = _stack.node(); 557 uint idx = _stack.index(); 558 if (idx == n->req()) { // all inputs are processed 559 _stack.pop(); 560 // n is invariant if it's inputs are all invariant 561 bool all_inputs_invariant = true; 562 for (uint i = 0; i < n->req(); i++) { 563 Node* in = n->in(i); 564 if (in == NULL) continue; 565 assert(_visited.test(in->_idx), "must have visited input"); 566 if (!_invariant.test(in->_idx)) { // bad guy 567 all_inputs_invariant = false; 568 break; 569 } 570 } 571 if (all_inputs_invariant) { 572 // If n's control is a predicate that was moved out of the 573 // loop, it was marked invariant but n is only invariant if 574 // it depends only on that test. Otherwise, unless that test 575 // is out of the loop, it's not invariant. 576 if (n->is_CFG() || n->depends_only_on_test() || n->in(0) == NULL || !_phase->is_member(_lpt, n->in(0))) { 577 _invariant.set(n->_idx); // I am a invariant too 578 } 579 } 580 } else { // process next input 581 _stack.set_index(idx + 1); 582 Node* m = n->in(idx); 583 if (m != NULL && !_visited.test_set(m->_idx)) { 584 visit(n, m); 585 } 586 } 587 } 588 } 589 590 // Helper function to set up _old_new map for clone_nodes. 591 // If n is a known invariant, set up directly ("clone" of n == n). 592 // Otherwise, push n onto the stack for real cloning. 593 void clone_visit(Node* n) { 594 assert(_invariant.test(n->_idx), "must be invariant"); 595 if (_lpt->is_invariant(n)) { // known invariant 596 _old_new.map(n->_idx, n); 597 } else { // to be cloned 598 assert(!n->is_CFG(), "should not see CFG here"); 599 _stack.push(n, n->in(0) == NULL ? 1 : 0); 600 } 601 } 602 603 // Clone "n" and (possibly) all its inputs recursively 604 void clone_nodes(Node* n, Node* ctrl) { 605 clone_visit(n); 606 while (_stack.is_nonempty()) { 607 Node* n = _stack.node(); 608 uint idx = _stack.index(); 609 if (idx == n->req()) { // all inputs processed, clone n! 610 _stack.pop(); 611 // clone invariant node 612 Node* n_cl = n->clone(); 613 _old_new.map(n->_idx, n_cl); 614 _phase->register_new_node(n_cl, ctrl); 615 for (uint i = 0; i < n->req(); i++) { 616 Node* in = n_cl->in(i); 617 if (in == NULL) continue; 618 n_cl->set_req(i, _old_new[in->_idx]); 619 } 620 } else { // process next input 621 _stack.set_index(idx + 1); 622 Node* m = n->in(idx); 623 if (m != NULL && !_clone_visited.test_set(m->_idx)) { 624 clone_visit(m); // visit the input 625 } 626 } 627 } 628 } 629 630 public: 631 Invariance(Arena* area, IdealLoopTree* lpt) : 632 _visited(area), _invariant(area), 633 _stack(area, 10 /* guess */), 634 _clone_visited(area), _old_new(area), 635 _lpt(lpt), _phase(lpt->_phase) 636 { 637 LoopNode* head = _lpt->_head->as_Loop(); 638 Node* entry = head->skip_strip_mined()->in(LoopNode::EntryControl); 639 if (entry->outcnt() != 1) { 640 // If a node is pinned between the predicates and the loop 641 // entry, we won't be able to move any node in the loop that 642 // depends on it above it in a predicate. Mark all those nodes 643 // as non loop invariatnt. 644 Unique_Node_List wq; 645 wq.push(entry); 646 for (uint next = 0; next < wq.size(); ++next) { 647 Node *n = wq.at(next); 648 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) { 649 Node* u = n->fast_out(i); 650 if (!u->is_CFG()) { 651 Node* c = _phase->get_ctrl(u); 652 if (_lpt->is_member(_phase->get_loop(c)) || _phase->is_dominator(c, head)) { 653 _visited.set(u->_idx); 654 wq.push(u); 655 } 656 } 657 } 658 } 659 } 660 } 661 662 // Map old to n for invariance computation and clone 663 void map_ctrl(Node* old, Node* n) { 664 assert(old->is_CFG() && n->is_CFG(), "must be"); 665 _old_new.map(old->_idx, n); // "clone" of old is n 666 _invariant.set(old->_idx); // old is invariant 667 _clone_visited.set(old->_idx); 668 } 669 670 // Driver function to compute invariance 671 bool is_invariant(Node* n) { 672 if (!_visited.test_set(n->_idx)) 673 compute_invariance(n); 674 return (_invariant.test(n->_idx) != 0); 675 } 676 677 // Driver function to clone invariant 678 Node* clone(Node* n, Node* ctrl) { 679 assert(ctrl->is_CFG(), "must be"); 680 assert(_invariant.test(n->_idx), "must be an invariant"); 681 if (!_clone_visited.test(n->_idx)) 682 clone_nodes(n, ctrl); 683 return _old_new[n->_idx]; 684 } 685 }; 686 687 //------------------------------is_range_check_if ----------------------------------- 688 // Returns true if the predicate of iff is in "scale*iv + offset u< load_range(ptr)" format 689 // Note: this function is particularly designed for loop predication. We require load_range 690 // and offset to be loop invariant computed on the fly by "invar" 691 bool IdealLoopTree::is_range_check_if(IfNode *iff, PhaseIdealLoop *phase, Invariance& invar) const { 692 if (!is_loop_exit(iff)) { 693 return false; 694 } 695 if (!iff->in(1)->is_Bool()) { 696 return false; 697 } 698 const BoolNode *bol = iff->in(1)->as_Bool(); 699 if (bol->_test._test != BoolTest::lt) { 700 return false; 701 } 702 if (!bol->in(1)->is_Cmp()) { 703 return false; 704 } 705 const CmpNode *cmp = bol->in(1)->as_Cmp(); 706 if (cmp->Opcode() != Op_CmpU) { 707 return false; 708 } 709 Node* range = cmp->in(2); 710 if (range->Opcode() != Op_LoadRange && !iff->is_RangeCheck()) { 711 const TypeInt* tint = phase->_igvn.type(range)->isa_int(); 712 if (tint == NULL || tint->empty() || tint->_lo < 0) { 713 // Allow predication on positive values that aren't LoadRanges. 714 // This allows optimization of loops where the length of the 715 // array is a known value and doesn't need to be loaded back 716 // from the array. 717 return false; 718 } 719 } 720 if (!invar.is_invariant(range)) { 721 return false; 722 } 723 Node *iv = _head->as_CountedLoop()->phi(); 724 int scale = 0; 725 Node *offset = NULL; 726 if (!phase->is_scaled_iv_plus_offset(cmp->in(1), iv, &scale, &offset)) { 727 return false; 728 } 729 if (offset && !invar.is_invariant(offset)) { // offset must be invariant 730 return false; 731 } 732 return true; 733 } 734 735 //------------------------------rc_predicate----------------------------------- 736 // Create a range check predicate 737 // 738 // for (i = init; i < limit; i += stride) { 739 // a[scale*i+offset] 740 // } 741 // 742 // Compute max(scale*i + offset) for init <= i < limit and build the predicate 743 // as "max(scale*i + offset) u< a.length". 744 // 745 // There are two cases for max(scale*i + offset): 746 // (1) stride*scale > 0 747 // max(scale*i + offset) = scale*(limit-stride) + offset 748 // (2) stride*scale < 0 749 // max(scale*i + offset) = scale*init + offset 750 BoolNode* PhaseIdealLoop::rc_predicate(IdealLoopTree *loop, Node* ctrl, 751 int scale, Node* offset, 752 Node* init, Node* limit, jint stride, 753 Node* range, bool upper, bool &overflow) { 754 jint con_limit = (limit != NULL && limit->is_Con()) ? limit->get_int() : 0; 755 jint con_init = init->is_Con() ? init->get_int() : 0; 756 jint con_offset = offset->is_Con() ? offset->get_int() : 0; 757 758 stringStream* predString = NULL; 759 if (TraceLoopPredicate) { 760 predString = new stringStream(); 761 predString->print("rc_predicate "); 762 } 763 764 overflow = false; 765 Node* max_idx_expr = NULL; 766 const TypeInt* idx_type = TypeInt::INT; 767 if ((stride > 0) == (scale > 0) == upper) { 768 guarantee(limit != NULL, "sanity"); 769 if (TraceLoopPredicate) { 770 if (limit->is_Con()) { 771 predString->print("(%d ", con_limit); 772 } else { 773 predString->print("(limit "); 774 } 775 predString->print("- %d) ", stride); 776 } 777 // Check if (limit - stride) may overflow 778 const TypeInt* limit_type = _igvn.type(limit)->isa_int(); 779 jint limit_lo = limit_type->_lo; 780 jint limit_hi = limit_type->_hi; 781 if ((stride > 0 && (java_subtract(limit_lo, stride) < limit_lo)) || 782 (stride < 0 && (java_subtract(limit_hi, stride) > limit_hi))) { 783 // No overflow possible 784 ConINode* con_stride = _igvn.intcon(stride); 785 set_ctrl(con_stride, C->root()); 786 max_idx_expr = new SubINode(limit, con_stride); 787 idx_type = TypeInt::make(limit_lo - stride, limit_hi - stride, limit_type->_widen); 788 } else { 789 // May overflow 790 overflow = true; 791 limit = new ConvI2LNode(limit); 792 register_new_node(limit, ctrl); 793 ConLNode* con_stride = _igvn.longcon(stride); 794 set_ctrl(con_stride, C->root()); 795 max_idx_expr = new SubLNode(limit, con_stride); 796 } 797 register_new_node(max_idx_expr, ctrl); 798 } else { 799 if (TraceLoopPredicate) { 800 if (init->is_Con()) { 801 predString->print("%d ", con_init); 802 } else { 803 predString->print("init "); 804 } 805 } 806 idx_type = _igvn.type(init)->isa_int(); 807 max_idx_expr = init; 808 } 809 810 if (scale != 1) { 811 ConNode* con_scale = _igvn.intcon(scale); 812 set_ctrl(con_scale, C->root()); 813 if (TraceLoopPredicate) { 814 predString->print("* %d ", scale); 815 } 816 // Check if (scale * max_idx_expr) may overflow 817 const TypeInt* scale_type = TypeInt::make(scale); 818 MulINode* mul = new MulINode(max_idx_expr, con_scale); 819 idx_type = (TypeInt*)mul->mul_ring(idx_type, scale_type); 820 if (overflow || TypeInt::INT->higher_equal(idx_type)) { 821 // May overflow 822 mul->destruct(); 823 if (!overflow) { 824 max_idx_expr = new ConvI2LNode(max_idx_expr); 825 register_new_node(max_idx_expr, ctrl); 826 } 827 overflow = true; 828 con_scale = _igvn.longcon(scale); 829 set_ctrl(con_scale, C->root()); 830 max_idx_expr = new MulLNode(max_idx_expr, con_scale); 831 } else { 832 // No overflow possible 833 max_idx_expr = mul; 834 } 835 register_new_node(max_idx_expr, ctrl); 836 } 837 838 if (offset && (!offset->is_Con() || con_offset != 0)){ 839 if (TraceLoopPredicate) { 840 if (offset->is_Con()) { 841 predString->print("+ %d ", con_offset); 842 } else { 843 predString->print("+ offset"); 844 } 845 } 846 // Check if (max_idx_expr + offset) may overflow 847 const TypeInt* offset_type = _igvn.type(offset)->isa_int(); 848 jint lo = java_add(idx_type->_lo, offset_type->_lo); 849 jint hi = java_add(idx_type->_hi, offset_type->_hi); 850 if (overflow || (lo > hi) || 851 ((idx_type->_lo & offset_type->_lo) < 0 && lo >= 0) || 852 ((~(idx_type->_hi | offset_type->_hi)) < 0 && hi < 0)) { 853 // May overflow 854 if (!overflow) { 855 max_idx_expr = new ConvI2LNode(max_idx_expr); 856 register_new_node(max_idx_expr, ctrl); 857 } 858 overflow = true; 859 offset = new ConvI2LNode(offset); 860 register_new_node(offset, ctrl); 861 max_idx_expr = new AddLNode(max_idx_expr, offset); 862 } else { 863 // No overflow possible 864 max_idx_expr = new AddINode(max_idx_expr, offset); 865 } 866 register_new_node(max_idx_expr, ctrl); 867 if (TraceLoopPredicate) { 868 if (offset->is_Con()) { 869 predString->print("+ %d ", offset->get_int()); 870 } else { 871 predString->print("+ offset "); 872 } 873 } 874 } 875 876 CmpNode* cmp = NULL; 877 if (overflow) { 878 // Integer expressions may overflow, do long comparison 879 range = new ConvI2LNode(range); 880 register_new_node(range, ctrl); 881 cmp = new CmpULNode(max_idx_expr, range); 882 } else { 883 cmp = new CmpUNode(max_idx_expr, range); 884 } 885 register_new_node(cmp, ctrl); 886 BoolNode* bol = new BoolNode(cmp, BoolTest::lt); 887 register_new_node(bol, ctrl); 888 889 if (TraceLoopPredicate) { 890 predString->print_cr("<u range"); 891 tty->print("%s", predString->as_string()); 892 } 893 return bol; 894 } 895 896 // Should loop predication look not only in the path from tail to head 897 // but also in branches of the loop body? 898 bool PhaseIdealLoop::loop_predication_should_follow_branches(IdealLoopTree *loop, ProjNode *predicate_proj, float& loop_trip_cnt) { 899 if (!UseProfiledLoopPredicate) { 900 return false; 901 } 902 903 if (predicate_proj == NULL) { 904 return false; 905 } 906 907 LoopNode* head = loop->_head->as_Loop(); 908 bool follow_branches = true; 909 IdealLoopTree* l = loop->_child; 910 // For leaf loops and loops with a single inner loop 911 while (l != NULL && follow_branches) { 912 IdealLoopTree* child = l; 913 if (child->_child != NULL && 914 child->_head->is_OuterStripMinedLoop()) { 915 assert(child->_child->_next == NULL, "only one inner loop for strip mined loop"); 916 assert(child->_child->_head->is_CountedLoop() && child->_child->_head->as_CountedLoop()->is_strip_mined(), "inner loop should be strip mined"); 917 child = child->_child; 918 } 919 if (child->_child != NULL || child->_irreducible) { 920 follow_branches = false; 921 } 922 l = l->_next; 923 } 924 if (follow_branches) { 925 loop->compute_profile_trip_cnt(this); 926 if (head->is_profile_trip_failed()) { 927 follow_branches = false; 928 } else { 929 loop_trip_cnt = head->profile_trip_cnt(); 930 if (head->is_CountedLoop()) { 931 CountedLoopNode* cl = head->as_CountedLoop(); 932 if (cl->phi() != NULL) { 933 const TypeInt* t = _igvn.type(cl->phi())->is_int(); 934 float worst_case_trip_cnt = ((float)t->_hi - t->_lo) / ABS(cl->stride_con()); 935 if (worst_case_trip_cnt < loop_trip_cnt) { 936 loop_trip_cnt = worst_case_trip_cnt; 937 } 938 } 939 } 940 } 941 } 942 return follow_branches; 943 } 944 945 // Compute probability of reaching some CFG node from a fixed 946 // dominating CFG node 947 class PathFrequency { 948 private: 949 Node* _dom; // frequencies are computed relative to this node 950 Node_Stack _stack; 951 GrowableArray<float> _freqs_stack; // keep track of intermediate result at regions 952 GrowableArray<float> _freqs; // cache frequencies 953 PhaseIdealLoop* _phase; 954 955 void set_rounding(int mode) { 956 // fesetround is broken on windows 957 NOT_WINDOWS(fesetround(mode);) 958 } 959 960 void check_frequency(float f) { 961 NOT_WINDOWS(assert(f <= 1 && f >= 0, "Incorrect frequency");) 962 } 963 964 public: 965 PathFrequency(Node* dom, PhaseIdealLoop* phase) 966 : _dom(dom), _stack(0), _phase(phase) { 967 } 968 969 float to(Node* n) { 970 // post order walk on the CFG graph from n to _dom 971 set_rounding(FE_TOWARDZERO); // make sure rounding doesn't push frequency above 1 972 IdealLoopTree* loop = _phase->get_loop(_dom); 973 Node* c = n; 974 for (;;) { 975 assert(_phase->get_loop(c) == loop, "have to be in the same loop"); 976 if (c == _dom || _freqs.at_grow(c->_idx, -1) >= 0) { 977 float f = c == _dom ? 1 : _freqs.at(c->_idx); 978 Node* prev = c; 979 while (_stack.size() > 0 && prev == c) { 980 Node* n = _stack.node(); 981 if (!n->is_Region()) { 982 if (_phase->get_loop(n) != _phase->get_loop(n->in(0))) { 983 // Found an inner loop: compute frequency of reaching this 984 // exit from the loop head by looking at the number of 985 // times each loop exit was taken 986 IdealLoopTree* inner_loop = _phase->get_loop(n->in(0)); 987 LoopNode* inner_head = inner_loop->_head->as_Loop(); 988 assert(_phase->get_loop(n) == loop, "only 1 inner loop"); 989 if (inner_head->is_OuterStripMinedLoop()) { 990 inner_head->verify_strip_mined(1); 991 if (n->in(0) == inner_head->in(LoopNode::LoopBackControl)->in(0)) { 992 n = n->in(0)->in(0)->in(0); 993 } 994 inner_loop = inner_loop->_child; 995 inner_head = inner_loop->_head->as_Loop(); 996 inner_head->verify_strip_mined(1); 997 } 998 set_rounding(FE_UPWARD); // make sure rounding doesn't push frequency above 1 999 float loop_exit_cnt = 0.0f; 1000 for (uint i = 0; i < inner_loop->_body.size(); i++) { 1001 Node *n = inner_loop->_body[i]; 1002 float c = inner_loop->compute_profile_trip_cnt_helper(n); 1003 loop_exit_cnt += c; 1004 } 1005 set_rounding(FE_TOWARDZERO); 1006 float cnt = -1; 1007 if (n->in(0)->is_If()) { 1008 IfNode* iff = n->in(0)->as_If(); 1009 float p = n->in(0)->as_If()->_prob; 1010 if (n->Opcode() == Op_IfFalse) { 1011 p = 1 - p; 1012 } 1013 if (p > PROB_MIN) { 1014 cnt = p * iff->_fcnt; 1015 } else { 1016 cnt = 0; 1017 } 1018 } else { 1019 assert(n->in(0)->is_Jump(), "unsupported node kind"); 1020 JumpNode* jmp = n->in(0)->as_Jump(); 1021 float p = n->in(0)->as_Jump()->_probs[n->as_JumpProj()->_con]; 1022 cnt = p * jmp->_fcnt; 1023 } 1024 float this_exit_f = cnt > 0 ? cnt / loop_exit_cnt : 0; 1025 check_frequency(this_exit_f); 1026 f = f * this_exit_f; 1027 check_frequency(f); 1028 } else { 1029 float p = -1; 1030 if (n->in(0)->is_If()) { 1031 p = n->in(0)->as_If()->_prob; 1032 if (n->Opcode() == Op_IfFalse) { 1033 p = 1 - p; 1034 } 1035 } else { 1036 assert(n->in(0)->is_Jump(), "unsupported node kind"); 1037 p = n->in(0)->as_Jump()->_probs[n->as_JumpProj()->_con]; 1038 } 1039 f = f * p; 1040 check_frequency(f); 1041 } 1042 _freqs.at_put_grow(n->_idx, (float)f, -1); 1043 _stack.pop(); 1044 } else { 1045 float prev_f = _freqs_stack.pop(); 1046 float new_f = f; 1047 f = new_f + prev_f; 1048 check_frequency(f); 1049 uint i = _stack.index(); 1050 if (i < n->req()) { 1051 c = n->in(i); 1052 _stack.set_index(i+1); 1053 _freqs_stack.push(f); 1054 } else { 1055 _freqs.at_put_grow(n->_idx, f, -1); 1056 _stack.pop(); 1057 } 1058 } 1059 } 1060 if (_stack.size() == 0) { 1061 set_rounding(FE_TONEAREST); 1062 check_frequency(f); 1063 return f; 1064 } 1065 } else if (c->is_Loop()) { 1066 ShouldNotReachHere(); 1067 c = c->in(LoopNode::EntryControl); 1068 } else if (c->is_Region()) { 1069 _freqs_stack.push(0); 1070 _stack.push(c, 2); 1071 c = c->in(1); 1072 } else { 1073 if (c->is_IfProj()) { 1074 IfNode* iff = c->in(0)->as_If(); 1075 if (iff->_prob == PROB_UNKNOWN) { 1076 // assume never taken 1077 _freqs.at_put_grow(c->_idx, 0, -1); 1078 } else if (_phase->get_loop(c) != _phase->get_loop(iff)) { 1079 if (iff->_fcnt == COUNT_UNKNOWN) { 1080 // assume never taken 1081 _freqs.at_put_grow(c->_idx, 0, -1); 1082 } else { 1083 // skip over loop 1084 _stack.push(c, 1); 1085 c = _phase->get_loop(c->in(0))->_head->as_Loop()->skip_strip_mined()->in(LoopNode::EntryControl); 1086 } 1087 } else { 1088 _stack.push(c, 1); 1089 c = iff; 1090 } 1091 } else if (c->is_JumpProj()) { 1092 JumpNode* jmp = c->in(0)->as_Jump(); 1093 if (_phase->get_loop(c) != _phase->get_loop(jmp)) { 1094 if (jmp->_fcnt == COUNT_UNKNOWN) { 1095 // assume never taken 1096 _freqs.at_put_grow(c->_idx, 0, -1); 1097 } else { 1098 // skip over loop 1099 _stack.push(c, 1); 1100 c = _phase->get_loop(c->in(0))->_head->as_Loop()->skip_strip_mined()->in(LoopNode::EntryControl); 1101 } 1102 } else { 1103 _stack.push(c, 1); 1104 c = jmp; 1105 } 1106 } else if (c->Opcode() == Op_CatchProj && 1107 c->in(0)->Opcode() == Op_Catch && 1108 c->in(0)->in(0)->is_Proj() && 1109 c->in(0)->in(0)->in(0)->is_Call()) { 1110 // assume exceptions are never thrown 1111 uint con = c->as_Proj()->_con; 1112 if (con == CatchProjNode::fall_through_index) { 1113 Node* call = c->in(0)->in(0)->in(0)->in(0); 1114 if (_phase->get_loop(call) != _phase->get_loop(c)) { 1115 _freqs.at_put_grow(c->_idx, 0, -1); 1116 } else { 1117 c = call; 1118 } 1119 } else { 1120 assert(con >= CatchProjNode::catch_all_index, "what else?"); 1121 _freqs.at_put_grow(c->_idx, 0, -1); 1122 } 1123 } else if (c->unique_ctrl_out() == NULL && !c->is_If() && !c->is_Jump()) { 1124 ShouldNotReachHere(); 1125 } else { 1126 c = c->in(0); 1127 } 1128 } 1129 } 1130 ShouldNotReachHere(); 1131 return -1; 1132 } 1133 }; 1134 1135 void PhaseIdealLoop::loop_predication_follow_branches(Node *n, IdealLoopTree *loop, float loop_trip_cnt, 1136 PathFrequency& pf, Node_Stack& stack, VectorSet& seen, 1137 Node_List& if_proj_list) { 1138 assert(n->is_Region(), "start from a region"); 1139 Node* tail = loop->tail(); 1140 stack.push(n, 1); 1141 do { 1142 Node* c = stack.node(); 1143 assert(c->is_Region() || c->is_IfProj(), "only region here"); 1144 uint i = stack.index(); 1145 1146 if (i < c->req()) { 1147 stack.set_index(i+1); 1148 Node* in = c->in(i); 1149 while (!is_dominator(in, tail) && !seen.test_set(in->_idx)) { 1150 IdealLoopTree* in_loop = get_loop(in); 1151 if (in_loop != loop) { 1152 in = in_loop->_head->in(LoopNode::EntryControl); 1153 } else if (in->is_Region()) { 1154 stack.push(in, 1); 1155 break; 1156 } else if (in->is_IfProj() && 1157 in->as_Proj()->is_uncommon_trap_if_pattern(Deoptimization::Reason_none) && 1158 (in->in(0)->Opcode() == Op_If || 1159 in->in(0)->Opcode() == Op_RangeCheck)) { 1160 if (pf.to(in) * loop_trip_cnt >= 1) { 1161 stack.push(in, 1); 1162 } 1163 in = in->in(0); 1164 } else { 1165 in = in->in(0); 1166 } 1167 } 1168 } else { 1169 if (c->is_IfProj()) { 1170 if_proj_list.push(c); 1171 } 1172 stack.pop(); 1173 } 1174 1175 } while (stack.size() > 0); 1176 } 1177 1178 1179 bool PhaseIdealLoop::loop_predication_impl_helper(IdealLoopTree *loop, ProjNode* proj, ProjNode *predicate_proj, 1180 CountedLoopNode *cl, ConNode* zero, Invariance& invar, 1181 Deoptimization::DeoptReason reason) { 1182 // Following are changed to nonnull when a predicate can be hoisted 1183 ProjNode* new_predicate_proj = NULL; 1184 IfNode* iff = proj->in(0)->as_If(); 1185 Node* test = iff->in(1); 1186 if (!test->is_Bool()){ //Conv2B, ... 1187 return false; 1188 } 1189 BoolNode* bol = test->as_Bool(); 1190 if (invar.is_invariant(bol)) { 1191 // Invariant test 1192 new_predicate_proj = create_new_if_for_predicate(predicate_proj, NULL, 1193 reason, 1194 iff->Opcode()); 1195 Node* ctrl = new_predicate_proj->in(0)->as_If()->in(0); 1196 BoolNode* new_predicate_bol = invar.clone(bol, ctrl)->as_Bool(); 1197 1198 // Negate test if necessary 1199 bool negated = false; 1200 if (proj->_con != predicate_proj->_con) { 1201 new_predicate_bol = new BoolNode(new_predicate_bol->in(1), new_predicate_bol->_test.negate()); 1202 register_new_node(new_predicate_bol, ctrl); 1203 negated = true; 1204 } 1205 IfNode* new_predicate_iff = new_predicate_proj->in(0)->as_If(); 1206 _igvn.hash_delete(new_predicate_iff); 1207 new_predicate_iff->set_req(1, new_predicate_bol); 1208 #ifndef PRODUCT 1209 if (TraceLoopPredicate) { 1210 tty->print("Predicate invariant if%s: %d ", negated ? " negated" : "", new_predicate_iff->_idx); 1211 loop->dump_head(); 1212 } else if (TraceLoopOpts) { 1213 tty->print("Predicate IC "); 1214 loop->dump_head(); 1215 } 1216 #endif 1217 } else if (cl != NULL && loop->is_range_check_if(iff, this, invar)) { 1218 // Range check for counted loops 1219 const Node* cmp = bol->in(1)->as_Cmp(); 1220 Node* idx = cmp->in(1); 1221 assert(!invar.is_invariant(idx), "index is variant"); 1222 Node* rng = cmp->in(2); 1223 assert(rng->Opcode() == Op_LoadRange || iff->is_RangeCheck() || _igvn.type(rng)->is_int()->_lo >= 0, "must be"); 1224 assert(invar.is_invariant(rng), "range must be invariant"); 1225 int scale = 1; 1226 Node* offset = zero; 1227 bool ok = is_scaled_iv_plus_offset(idx, cl->phi(), &scale, &offset); 1228 assert(ok, "must be index expression"); 1229 1230 Node* init = cl->init_trip(); 1231 // Limit is not exact. 1232 // Calculate exact limit here. 1233 // Note, counted loop's test is '<' or '>'. 1234 Node* limit = exact_limit(loop); 1235 int stride = cl->stride()->get_int(); 1236 1237 // Build if's for the upper and lower bound tests. The 1238 // lower_bound test will dominate the upper bound test and all 1239 // cloned or created nodes will use the lower bound test as 1240 // their declared control. 1241 1242 // Perform cloning to keep Invariance state correct since the 1243 // late schedule will place invariant things in the loop. 1244 Node *ctrl = predicate_proj->in(0)->as_If()->in(0); 1245 rng = invar.clone(rng, ctrl); 1246 if (offset && offset != zero) { 1247 assert(invar.is_invariant(offset), "offset must be loop invariant"); 1248 offset = invar.clone(offset, ctrl); 1249 } 1250 // If predicate expressions may overflow in the integer range, longs are used. 1251 bool overflow = false; 1252 1253 // Test the lower bound 1254 BoolNode* lower_bound_bol = rc_predicate(loop, ctrl, scale, offset, init, limit, stride, rng, false, overflow); 1255 // Negate test if necessary 1256 bool negated = false; 1257 if (proj->_con != predicate_proj->_con) { 1258 lower_bound_bol = new BoolNode(lower_bound_bol->in(1), lower_bound_bol->_test.negate()); 1259 register_new_node(lower_bound_bol, ctrl); 1260 negated = true; 1261 } 1262 ProjNode* lower_bound_proj = create_new_if_for_predicate(predicate_proj, NULL, reason, overflow ? Op_If : iff->Opcode()); 1263 IfNode* lower_bound_iff = lower_bound_proj->in(0)->as_If(); 1264 _igvn.hash_delete(lower_bound_iff); 1265 lower_bound_iff->set_req(1, lower_bound_bol); 1266 if (TraceLoopPredicate) tty->print_cr("lower bound check if: %s %d ", negated ? " negated" : "", lower_bound_iff->_idx); 1267 1268 // Test the upper bound 1269 BoolNode* upper_bound_bol = rc_predicate(loop, lower_bound_proj, scale, offset, init, limit, stride, rng, true, overflow); 1270 negated = false; 1271 if (proj->_con != predicate_proj->_con) { 1272 upper_bound_bol = new BoolNode(upper_bound_bol->in(1), upper_bound_bol->_test.negate()); 1273 register_new_node(upper_bound_bol, ctrl); 1274 negated = true; 1275 } 1276 ProjNode* upper_bound_proj = create_new_if_for_predicate(predicate_proj, NULL, reason, overflow ? Op_If : iff->Opcode()); 1277 assert(upper_bound_proj->in(0)->as_If()->in(0) == lower_bound_proj, "should dominate"); 1278 IfNode* upper_bound_iff = upper_bound_proj->in(0)->as_If(); 1279 _igvn.hash_delete(upper_bound_iff); 1280 upper_bound_iff->set_req(1, upper_bound_bol); 1281 if (TraceLoopPredicate) tty->print_cr("upper bound check if: %s %d ", negated ? " negated" : "", lower_bound_iff->_idx); 1282 1283 // Fall through into rest of the clean up code which will move 1284 // any dependent nodes onto the upper bound test. 1285 new_predicate_proj = upper_bound_proj; 1286 1287 if (iff->is_RangeCheck()) { 1288 new_predicate_proj = insert_skeleton_predicate(iff, loop, proj, predicate_proj, upper_bound_proj, scale, offset, init, limit, stride, rng, overflow, reason); 1289 } 1290 1291 #ifndef PRODUCT 1292 if (TraceLoopOpts && !TraceLoopPredicate) { 1293 tty->print("Predicate RC "); 1294 loop->dump_head(); 1295 } 1296 #endif 1297 } else { 1298 // Loop variant check (for example, range check in non-counted loop) 1299 // with uncommon trap. 1300 return false; 1301 } 1302 assert(new_predicate_proj != NULL, "sanity"); 1303 // Success - attach condition (new_predicate_bol) to predicate if 1304 invar.map_ctrl(proj, new_predicate_proj); // so that invariance test can be appropriate 1305 1306 // Eliminate the old If in the loop body 1307 dominated_by( new_predicate_proj, iff, proj->_con != new_predicate_proj->_con ); 1308 1309 C->set_major_progress(); 1310 return true; 1311 } 1312 1313 1314 // After pre/main/post loops are created, we'll put a copy of some 1315 // range checks between the pre and main loop to validate the value 1316 // of the main loop induction variable. Make a copy of the predicates 1317 // here with an opaque node as a place holder for the value (will be 1318 // updated by PhaseIdealLoop::update_skeleton_predicate()). 1319 ProjNode* PhaseIdealLoop::insert_skeleton_predicate(IfNode* iff, IdealLoopTree *loop, 1320 ProjNode* proj, ProjNode *predicate_proj, 1321 ProjNode* upper_bound_proj, 1322 int scale, Node* offset, 1323 Node* init, Node* limit, jint stride, 1324 Node* rng, bool &overflow, 1325 Deoptimization::DeoptReason reason) { 1326 assert(proj->_con && predicate_proj->_con, "not a range check?"); 1327 Node* opaque_init = new Opaque1Node(C, init); 1328 register_new_node(opaque_init, upper_bound_proj); 1329 BoolNode* bol = rc_predicate(loop, upper_bound_proj, scale, offset, opaque_init, limit, stride, rng, (stride > 0) != (scale > 0), overflow); 1330 Node* opaque_bol = new Opaque4Node(C, bol, _igvn.intcon(1)); // This will go away once loop opts are over 1331 register_new_node(opaque_bol, upper_bound_proj); 1332 ProjNode* new_proj = create_new_if_for_predicate(predicate_proj, NULL, reason, overflow ? Op_If : iff->Opcode()); 1333 _igvn.replace_input_of(new_proj->in(0), 1, opaque_bol); 1334 assert(opaque_init->outcnt() > 0, "should be used"); 1335 return new_proj; 1336 } 1337 1338 //------------------------------ loop_predication_impl-------------------------- 1339 // Insert loop predicates for null checks and range checks 1340 bool PhaseIdealLoop::loop_predication_impl(IdealLoopTree *loop) { 1341 if (!UseLoopPredicate) return false; 1342 1343 if (!loop->_head->is_Loop()) { 1344 // Could be a simple region when irreducible loops are present. 1345 return false; 1346 } 1347 LoopNode* head = loop->_head->as_Loop(); 1348 1349 if (head->unique_ctrl_out()->Opcode() == Op_NeverBranch) { 1350 // do nothing for infinite loops 1351 return false; 1352 } 1353 1354 if (head->is_OuterStripMinedLoop()) { 1355 return false; 1356 } 1357 1358 CountedLoopNode *cl = NULL; 1359 if (head->is_valid_counted_loop()) { 1360 cl = head->as_CountedLoop(); 1361 // do nothing for iteration-splitted loops 1362 if (!cl->is_normal_loop()) return false; 1363 // Avoid RCE if Counted loop's test is '!='. 1364 BoolTest::mask bt = cl->loopexit()->test_trip(); 1365 if (bt != BoolTest::lt && bt != BoolTest::gt) 1366 cl = NULL; 1367 } 1368 1369 Node* entry = head->skip_strip_mined()->in(LoopNode::EntryControl); 1370 ProjNode *loop_limit_proj = NULL; 1371 ProjNode *predicate_proj = NULL; 1372 ProjNode *profile_predicate_proj = NULL; 1373 // Loop limit check predicate should be near the loop. 1374 loop_limit_proj = find_predicate_insertion_point(entry, Deoptimization::Reason_loop_limit_check); 1375 if (loop_limit_proj != NULL) { 1376 entry = skip_loop_predicates(loop_limit_proj); 1377 } 1378 bool has_profile_predicates = false; 1379 profile_predicate_proj = find_predicate_insertion_point(entry, Deoptimization::Reason_profile_predicate); 1380 if (profile_predicate_proj != NULL) { 1381 Node* n = skip_loop_predicates(entry); 1382 // Check if predicates were already added to the profile predicate 1383 // block 1384 if (n != entry->in(0)->in(0) || n->outcnt() != 1) { 1385 has_profile_predicates = true; 1386 } 1387 entry = n; 1388 } 1389 predicate_proj = find_predicate_insertion_point(entry, Deoptimization::Reason_predicate); 1390 1391 float loop_trip_cnt = -1; 1392 bool follow_branches = loop_predication_should_follow_branches(loop, profile_predicate_proj, loop_trip_cnt); 1393 assert(!follow_branches || loop_trip_cnt >= 0, "negative trip count?"); 1394 1395 if (predicate_proj == NULL && !follow_branches) { 1396 #ifndef PRODUCT 1397 if (TraceLoopPredicate) { 1398 tty->print("missing predicate:"); 1399 loop->dump_head(); 1400 head->dump(1); 1401 } 1402 #endif 1403 return false; 1404 } 1405 ConNode* zero = _igvn.intcon(0); 1406 set_ctrl(zero, C->root()); 1407 1408 ResourceArea *area = Thread::current()->resource_area(); 1409 Invariance invar(area, loop); 1410 1411 // Create list of if-projs such that a newer proj dominates all older 1412 // projs in the list, and they all dominate loop->tail() 1413 Node_List if_proj_list(area); 1414 Node_List regions(area); 1415 Node *current_proj = loop->tail(); //start from tail 1416 1417 1418 Node_List controls(area); 1419 while (current_proj != head) { 1420 if (loop == get_loop(current_proj) && // still in the loop ? 1421 current_proj->is_Proj() && // is a projection ? 1422 (current_proj->in(0)->Opcode() == Op_If || 1423 current_proj->in(0)->Opcode() == Op_RangeCheck)) { // is a if projection ? 1424 if_proj_list.push(current_proj); 1425 } 1426 if (follow_branches && 1427 current_proj->Opcode() == Op_Region && 1428 loop == get_loop(current_proj)) { 1429 regions.push(current_proj); 1430 } 1431 current_proj = idom(current_proj); 1432 } 1433 1434 bool hoisted = false; // true if at least one proj is promoted 1435 1436 if (!has_profile_predicates) { 1437 while (if_proj_list.size() > 0) { 1438 Node* n = if_proj_list.pop(); 1439 1440 ProjNode* proj = n->as_Proj(); 1441 IfNode* iff = proj->in(0)->as_If(); 1442 1443 CallStaticJavaNode* call = proj->is_uncommon_trap_if_pattern(Deoptimization::Reason_none); 1444 if (call == NULL) { 1445 if (loop->is_loop_exit(iff)) { 1446 // stop processing the remaining projs in the list because the execution of them 1447 // depends on the condition of "iff" (iff->in(1)). 1448 break; 1449 } else { 1450 // Both arms are inside the loop. There are two cases: 1451 // (1) there is one backward branch. In this case, any remaining proj 1452 // in the if_proj list post-dominates "iff". So, the condition of "iff" 1453 // does not determine the execution the remining projs directly, and we 1454 // can safely continue. 1455 // (2) both arms are forwarded, i.e. a diamond shape. In this case, "proj" 1456 // does not dominate loop->tail(), so it can not be in the if_proj list. 1457 continue; 1458 } 1459 } 1460 Deoptimization::DeoptReason reason = Deoptimization::trap_request_reason(call->uncommon_trap_request()); 1461 if (reason == Deoptimization::Reason_predicate) { 1462 break; 1463 } 1464 1465 if (predicate_proj != NULL) { 1466 hoisted = loop_predication_impl_helper(loop, proj, predicate_proj, cl, zero, invar, Deoptimization::Reason_predicate) | hoisted; 1467 } 1468 } // end while 1469 } 1470 1471 Node_List if_proj_list_freq(area); 1472 if (follow_branches) { 1473 PathFrequency pf(loop->_head, this); 1474 1475 // Some projections were skipped by regular predicates because of 1476 // an early loop exit. Try them with profile data. 1477 while (if_proj_list.size() > 0) { 1478 Node* proj = if_proj_list.pop(); 1479 float f = pf.to(proj); 1480 if (proj->as_Proj()->is_uncommon_trap_if_pattern(Deoptimization::Reason_none) && 1481 f * loop_trip_cnt >= 1) { 1482 hoisted = loop_predication_impl_helper(loop, proj->as_Proj(), profile_predicate_proj, cl, zero, invar, Deoptimization::Reason_profile_predicate) | hoisted; 1483 } 1484 } 1485 1486 // And look into all branches 1487 Node_Stack stack(0); 1488 VectorSet seen(Thread::current()->resource_area()); 1489 while (regions.size() > 0) { 1490 Node* c = regions.pop(); 1491 loop_predication_follow_branches(c, loop, loop_trip_cnt, pf, stack, seen, if_proj_list_freq); 1492 } 1493 1494 for (uint i = 0; i < if_proj_list_freq.size(); i++) { 1495 ProjNode* proj = if_proj_list_freq.at(i)->as_Proj(); 1496 hoisted = loop_predication_impl_helper(loop, proj, profile_predicate_proj, cl, zero, invar, Deoptimization::Reason_profile_predicate) | hoisted; 1497 } 1498 } 1499 1500 #ifndef PRODUCT 1501 // report that the loop predication has been actually performed 1502 // for this loop 1503 if (TraceLoopPredicate && hoisted) { 1504 tty->print("Loop Predication Performed:"); 1505 loop->dump_head(); 1506 } 1507 #endif 1508 1509 head->verify_strip_mined(1); 1510 1511 return hoisted; 1512 } 1513 1514 //------------------------------loop_predication-------------------------------- 1515 // driver routine for loop predication optimization 1516 bool IdealLoopTree::loop_predication( PhaseIdealLoop *phase) { 1517 bool hoisted = false; 1518 // Recursively promote predicates 1519 if (_child) { 1520 hoisted = _child->loop_predication( phase); 1521 } 1522 1523 // self 1524 if (!_irreducible && !tail()->is_top()) { 1525 hoisted |= phase->loop_predication_impl(this); 1526 } 1527 1528 if (_next) { //sibling 1529 hoisted |= _next->loop_predication( phase); 1530 } 1531 1532 return hoisted; 1533 }