1 /* 2 * Copyright (c) 1998, 2025, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. 8 * 9 * This code is distributed in the hope that it will be useful, but WITHOUT 10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 12 * version 2 for more details (a copy is included in the LICENSE file that 13 * accompanied this code). 14 * 15 * You should have received a copy of the GNU General Public License version 16 * 2 along with this work; if not, write to the Free Software Foundation, 17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 18 * 19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 20 * or visit www.oracle.com if you need additional information or have any 21 * questions. 22 * 23 */ 24 25 #ifndef SHARE_OPTO_LOOPNODE_HPP 26 #define SHARE_OPTO_LOOPNODE_HPP 27 28 #include "opto/cfgnode.hpp" 29 #include "opto/multnode.hpp" 30 #include "opto/phaseX.hpp" 31 #include "opto/predicates.hpp" 32 #include "opto/subnode.hpp" 33 #include "opto/type.hpp" 34 #include "utilities/checkedCast.hpp" 35 36 class CmpNode; 37 class BaseCountedLoopEndNode; 38 class CountedLoopNode; 39 class IdealLoopTree; 40 class LoopNode; 41 class Node; 42 class OuterStripMinedLoopEndNode; 43 class PredicateBlock; 44 class PathFrequency; 45 class PhaseIdealLoop; 46 class LoopSelector; 47 class UnswitchedLoopSelector; 48 class VectorSet; 49 class VSharedData; 50 class Invariance; 51 struct small_cache; 52 53 // 54 // I D E A L I Z E D L O O P S 55 // 56 // Idealized loops are the set of loops I perform more interesting 57 // transformations on, beyond simple hoisting. 58 59 //------------------------------LoopNode--------------------------------------- 60 // Simple loop header. Fall in path on left, loop-back path on right. 61 class LoopNode : public RegionNode { 62 // Size is bigger to hold the flags. However, the flags do not change 63 // the semantics so it does not appear in the hash & cmp functions. 64 virtual uint size_of() const { return sizeof(*this); } 65 protected: 66 uint _loop_flags; 67 // Names for flag bitfields 68 enum { Normal=0, Pre=1, Main=2, Post=3, PreMainPostFlagsMask=3, 69 MainHasNoPreLoop = 1<<2, 70 HasExactTripCount = 1<<3, 71 InnerLoop = 1<<4, 72 PartialPeelLoop = 1<<5, 73 PartialPeelFailed = 1<<6, 74 WasSlpAnalyzed = 1<<7, 75 PassedSlpAnalysis = 1<<8, 76 DoUnrollOnly = 1<<9, 77 VectorizedLoop = 1<<10, 78 HasAtomicPostLoop = 1<<11, 79 StripMined = 1<<12, 80 SubwordLoop = 1<<13, 81 ProfileTripFailed = 1<<14, 82 LoopNestInnerLoop = 1<<15, 83 LoopNestLongOuterLoop = 1<<16, 84 MultiversionFastLoop = 1<<17, 85 MultiversionSlowLoop = 2<<17, 86 MultiversionDelayedSlowLoop = 3<<17, 87 MultiversionFlagsMask = 3<<17, 88 }; 89 char _unswitch_count; 90 enum { _unswitch_max=3 }; 91 92 // Expected trip count from profile data 93 float _profile_trip_cnt; 94 95 public: 96 // Names for edge indices 97 enum { Self=0, EntryControl, LoopBackControl }; 98 99 bool is_inner_loop() const { return _loop_flags & InnerLoop; } 100 void set_inner_loop() { _loop_flags |= InnerLoop; } 101 102 bool is_vectorized_loop() const { return _loop_flags & VectorizedLoop; } 103 bool is_partial_peel_loop() const { return _loop_flags & PartialPeelLoop; } 104 void set_partial_peel_loop() { _loop_flags |= PartialPeelLoop; } 105 bool partial_peel_has_failed() const { return _loop_flags & PartialPeelFailed; } 106 bool is_strip_mined() const { return _loop_flags & StripMined; } 107 bool is_profile_trip_failed() const { return _loop_flags & ProfileTripFailed; } 108 bool is_subword_loop() const { return _loop_flags & SubwordLoop; } 109 bool is_loop_nest_inner_loop() const { return _loop_flags & LoopNestInnerLoop; } 110 bool is_loop_nest_outer_loop() const { return _loop_flags & LoopNestLongOuterLoop; } 111 112 void mark_partial_peel_failed() { _loop_flags |= PartialPeelFailed; } 113 void mark_was_slp() { _loop_flags |= WasSlpAnalyzed; } 114 void mark_passed_slp() { _loop_flags |= PassedSlpAnalysis; } 115 void mark_do_unroll_only() { _loop_flags |= DoUnrollOnly; } 116 void mark_loop_vectorized() { _loop_flags |= VectorizedLoop; } 117 void mark_has_atomic_post_loop() { _loop_flags |= HasAtomicPostLoop; } 118 void mark_strip_mined() { _loop_flags |= StripMined; } 119 void clear_strip_mined() { _loop_flags &= ~StripMined; } 120 void mark_profile_trip_failed() { _loop_flags |= ProfileTripFailed; } 121 void mark_subword_loop() { _loop_flags |= SubwordLoop; } 122 void mark_loop_nest_inner_loop() { _loop_flags |= LoopNestInnerLoop; } 123 void mark_loop_nest_outer_loop() { _loop_flags |= LoopNestLongOuterLoop; } 124 125 int unswitch_max() { return _unswitch_max; } 126 int unswitch_count() { return _unswitch_count; } 127 128 void set_unswitch_count(int val) { 129 assert (val <= unswitch_max(), "too many unswitches"); 130 _unswitch_count = val; 131 } 132 133 void set_profile_trip_cnt(float ptc) { _profile_trip_cnt = ptc; } 134 float profile_trip_cnt() { return _profile_trip_cnt; } 135 136 LoopNode(Node *entry, Node *backedge) 137 : RegionNode(3), _loop_flags(0), _unswitch_count(0), 138 _profile_trip_cnt(COUNT_UNKNOWN) { 139 init_class_id(Class_Loop); 140 init_req(EntryControl, entry); 141 init_req(LoopBackControl, backedge); 142 } 143 144 virtual Node *Ideal(PhaseGVN *phase, bool can_reshape); 145 virtual int Opcode() const; 146 bool can_be_counted_loop(PhaseValues* phase) const { 147 return req() == 3 && in(0) != nullptr && 148 in(1) != nullptr && phase->type(in(1)) != Type::TOP && 149 in(2) != nullptr && phase->type(in(2)) != Type::TOP; 150 } 151 bool is_valid_counted_loop(BasicType bt) const; 152 #ifndef PRODUCT 153 virtual void dump_spec(outputStream *st) const; 154 #endif 155 156 void verify_strip_mined(int expect_skeleton) const NOT_DEBUG_RETURN; 157 virtual LoopNode* skip_strip_mined(int expect_skeleton = 1) { return this; } 158 virtual IfTrueNode* outer_loop_tail() const { ShouldNotReachHere(); return nullptr; } 159 virtual OuterStripMinedLoopEndNode* outer_loop_end() const { ShouldNotReachHere(); return nullptr; } 160 virtual IfFalseNode* outer_loop_exit() const { ShouldNotReachHere(); return nullptr; } 161 virtual SafePointNode* outer_safepoint() const { ShouldNotReachHere(); return nullptr; } 162 }; 163 164 //------------------------------Counted Loops---------------------------------- 165 // Counted loops are all trip-counted loops, with exactly 1 trip-counter exit 166 // path (and maybe some other exit paths). The trip-counter exit is always 167 // last in the loop. The trip-counter have to stride by a constant; 168 // the exit value is also loop invariant. 169 170 // CountedLoopNodes and CountedLoopEndNodes come in matched pairs. The 171 // CountedLoopNode has the incoming loop control and the loop-back-control 172 // which is always the IfTrue before the matching CountedLoopEndNode. The 173 // CountedLoopEndNode has an incoming control (possibly not the 174 // CountedLoopNode if there is control flow in the loop), the post-increment 175 // trip-counter value, and the limit. The trip-counter value is always of 176 // the form (Op old-trip-counter stride). The old-trip-counter is produced 177 // by a Phi connected to the CountedLoopNode. The stride is constant. 178 // The Op is any commutable opcode, including Add, Mul, Xor. The 179 // CountedLoopEndNode also takes in the loop-invariant limit value. 180 181 // From a CountedLoopNode I can reach the matching CountedLoopEndNode via the 182 // loop-back control. From CountedLoopEndNodes I can reach CountedLoopNodes 183 // via the old-trip-counter from the Op node. 184 185 //------------------------------CountedLoopNode-------------------------------- 186 // CountedLoopNodes head simple counted loops. CountedLoopNodes have as 187 // inputs the incoming loop-start control and the loop-back control, so they 188 // act like RegionNodes. They also take in the initial trip counter, the 189 // loop-invariant stride and the loop-invariant limit value. CountedLoopNodes 190 // produce a loop-body control and the trip counter value. Since 191 // CountedLoopNodes behave like RegionNodes I still have a standard CFG model. 192 193 class BaseCountedLoopNode : public LoopNode { 194 public: 195 BaseCountedLoopNode(Node *entry, Node *backedge) 196 : LoopNode(entry, backedge) { 197 } 198 199 Node *init_control() const { return in(EntryControl); } 200 Node *back_control() const { return in(LoopBackControl); } 201 202 Node* init_trip() const; 203 Node* stride() const; 204 bool stride_is_con() const; 205 Node* limit() const; 206 Node* incr() const; 207 Node* phi() const; 208 209 BaseCountedLoopEndNode* loopexit_or_null() const; 210 BaseCountedLoopEndNode* loopexit() const; 211 212 virtual BasicType bt() const = 0; 213 214 jlong stride_con() const; 215 216 static BaseCountedLoopNode* make(Node* entry, Node* backedge, BasicType bt); 217 }; 218 219 220 class CountedLoopNode : public BaseCountedLoopNode { 221 // Size is bigger to hold _main_idx. However, _main_idx does not change 222 // the semantics so it does not appear in the hash & cmp functions. 223 virtual uint size_of() const { return sizeof(*this); } 224 225 // For Pre- and Post-loops during debugging ONLY, this holds the index of 226 // the Main CountedLoop. Used to assert that we understand the graph shape. 227 node_idx_t _main_idx; 228 229 // Known trip count calculated by compute_exact_trip_count() 230 uint _trip_count; 231 232 // Log2 of original loop bodies in unrolled loop 233 int _unrolled_count_log2; 234 235 // Node count prior to last unrolling - used to decide if 236 // unroll,optimize,unroll,optimize,... is making progress 237 int _node_count_before_unroll; 238 239 // If slp analysis is performed we record the maximum 240 // vector mapped unroll factor here 241 int _slp_maximum_unroll_factor; 242 243 public: 244 CountedLoopNode(Node *entry, Node *backedge) 245 : BaseCountedLoopNode(entry, backedge), _main_idx(0), _trip_count(max_juint), 246 _unrolled_count_log2(0), _node_count_before_unroll(0), 247 _slp_maximum_unroll_factor(0) { 248 init_class_id(Class_CountedLoop); 249 // Initialize _trip_count to the largest possible value. 250 // Will be reset (lower) if the loop's trip count is known. 251 } 252 253 virtual int Opcode() const; 254 virtual Node *Ideal(PhaseGVN *phase, bool can_reshape); 255 256 CountedLoopEndNode* loopexit_or_null() const { return (CountedLoopEndNode*) BaseCountedLoopNode::loopexit_or_null(); } 257 CountedLoopEndNode* loopexit() const { return (CountedLoopEndNode*) BaseCountedLoopNode::loopexit(); } 258 int stride_con() const; 259 260 // Match increment with optional truncation 261 static Node* 262 match_incr_with_optional_truncation(Node* expr, Node** trunc1, Node** trunc2, const TypeInteger** trunc_type, 263 BasicType bt); 264 265 // A 'main' loop has a pre-loop and a post-loop. The 'main' loop 266 // can run short a few iterations and may start a few iterations in. 267 // It will be RCE'd and unrolled and aligned. 268 269 // A following 'post' loop will run any remaining iterations. Used 270 // during Range Check Elimination, the 'post' loop will do any final 271 // iterations with full checks. Also used by Loop Unrolling, where 272 // the 'post' loop will do any epilog iterations needed. Basically, 273 // a 'post' loop can not profitably be further unrolled or RCE'd. 274 275 // A preceding 'pre' loop will run at least 1 iteration (to do peeling), 276 // it may do under-flow checks for RCE and may do alignment iterations 277 // so the following main loop 'knows' that it is striding down cache 278 // lines. 279 280 // A 'main' loop that is ONLY unrolled or peeled, never RCE'd or 281 // Aligned, may be missing it's pre-loop. 282 bool is_normal_loop () const { return (_loop_flags&PreMainPostFlagsMask) == Normal; } 283 bool is_pre_loop () const { return (_loop_flags&PreMainPostFlagsMask) == Pre; } 284 bool is_main_loop () const { return (_loop_flags&PreMainPostFlagsMask) == Main; } 285 bool is_post_loop () const { return (_loop_flags&PreMainPostFlagsMask) == Post; } 286 bool was_slp_analyzed () const { return (_loop_flags&WasSlpAnalyzed) == WasSlpAnalyzed; } 287 bool has_passed_slp () const { return (_loop_flags&PassedSlpAnalysis) == PassedSlpAnalysis; } 288 bool is_unroll_only () const { return (_loop_flags&DoUnrollOnly) == DoUnrollOnly; } 289 bool is_main_no_pre_loop() const { return _loop_flags & MainHasNoPreLoop; } 290 bool has_atomic_post_loop () const { return (_loop_flags & HasAtomicPostLoop) == HasAtomicPostLoop; } 291 void set_main_no_pre_loop() { _loop_flags |= MainHasNoPreLoop; } 292 293 IfNode* find_multiversion_if_from_multiversion_fast_main_loop(); 294 295 int main_idx() const { return _main_idx; } 296 297 298 void set_pre_loop (CountedLoopNode *main) { assert(is_normal_loop(),""); _loop_flags |= Pre ; _main_idx = main->_idx; } 299 void set_main_loop ( ) { assert(is_normal_loop(),""); _loop_flags |= Main; } 300 void set_post_loop (CountedLoopNode *main) { assert(is_normal_loop(),""); _loop_flags |= Post; _main_idx = main->_idx; } 301 void set_normal_loop( ) { _loop_flags &= ~PreMainPostFlagsMask; } 302 303 void set_trip_count(uint tc) { _trip_count = tc; } 304 uint trip_count() { return _trip_count; } 305 306 bool has_exact_trip_count() const { return (_loop_flags & HasExactTripCount) != 0; } 307 void set_exact_trip_count(uint tc) { 308 _trip_count = tc; 309 _loop_flags |= HasExactTripCount; 310 } 311 void set_nonexact_trip_count() { 312 _loop_flags &= ~HasExactTripCount; 313 } 314 void set_notpassed_slp() { 315 _loop_flags &= ~PassedSlpAnalysis; 316 } 317 318 void double_unrolled_count() { _unrolled_count_log2++; } 319 int unrolled_count() { return 1 << MIN2(_unrolled_count_log2, BitsPerInt-3); } 320 321 void set_node_count_before_unroll(int ct) { _node_count_before_unroll = ct; } 322 int node_count_before_unroll() { return _node_count_before_unroll; } 323 void set_slp_max_unroll(int unroll_factor) { _slp_maximum_unroll_factor = unroll_factor; } 324 int slp_max_unroll() const { return _slp_maximum_unroll_factor; } 325 326 // Multiversioning allows us to duplicate a CountedLoop, and have two versions, and the multiversion_if 327 // decides which one is taken: 328 // (1) fast_loop: We enter this loop by default, by default the multiversion_if has its condition set to 329 // "true", guarded by a OpaqueMultiversioning. If we want to make a speculative assumption 330 // for an optimization, we can add the runtime-check to the multiversion_if, and if the 331 // assumption fails we take the slow_loop instead, where we do not make the same speculative 332 // assumption. 333 // We call it the "fast_loop" because it has more optimizations, enabled by the speculative 334 // runtime-checks at the multiversion_if, and we expect the fast_loop to execute faster. 335 // (2) slow_loop: By default, it is not taken, until a runtime-check is added to the multiversion_if while 336 // optimizing the fast_looop. If such a runtime-check is never added, then after loop-opts 337 // the multiversion_if constant folds to true, and the slow_loop is folded away. To save 338 // compile time, we delay the optimization of the slow_loop until a runtime-check is added 339 // to the multiversion_if, at which point we resume optimizations for the slow_loop. 340 // We call it the "slow_loop" because it has fewer optimizations, since this is the fall-back 341 // loop where we do not make any of the speculative assumptions we make for the fast_loop. 342 // Hence, we expect the slow_loop to execute slower. 343 bool is_multiversion() const { return (_loop_flags & MultiversionFlagsMask) != Normal; } 344 bool is_multiversion_fast_loop() const { return (_loop_flags & MultiversionFlagsMask) == MultiversionFastLoop; } 345 bool is_multiversion_slow_loop() const { return (_loop_flags & MultiversionFlagsMask) == MultiversionSlowLoop; } 346 bool is_multiversion_delayed_slow_loop() const { return (_loop_flags & MultiversionFlagsMask) == MultiversionDelayedSlowLoop; } 347 void set_multiversion_fast_loop() { assert(!is_multiversion(), ""); _loop_flags |= MultiversionFastLoop; } 348 void set_multiversion_slow_loop() { assert(!is_multiversion(), ""); _loop_flags |= MultiversionSlowLoop; } 349 void set_multiversion_delayed_slow_loop() { assert(!is_multiversion(), ""); _loop_flags |= MultiversionDelayedSlowLoop; } 350 void set_no_multiversion() { assert( is_multiversion(), ""); _loop_flags &= ~MultiversionFlagsMask; } 351 352 virtual LoopNode* skip_strip_mined(int expect_skeleton = 1); 353 OuterStripMinedLoopNode* outer_loop() const; 354 virtual IfTrueNode* outer_loop_tail() const; 355 virtual OuterStripMinedLoopEndNode* outer_loop_end() const; 356 virtual IfFalseNode* outer_loop_exit() const; 357 virtual SafePointNode* outer_safepoint() const; 358 359 Node* skip_assertion_predicates_with_halt(); 360 361 virtual BasicType bt() const { 362 return T_INT; 363 } 364 365 Node* is_canonical_loop_entry(); 366 CountedLoopEndNode* find_pre_loop_end(); 367 368 Node* uncasted_init_trip(bool uncasted); 369 370 #ifndef PRODUCT 371 virtual void dump_spec(outputStream *st) const; 372 #endif 373 }; 374 375 class LongCountedLoopNode : public BaseCountedLoopNode { 376 public: 377 LongCountedLoopNode(Node *entry, Node *backedge) 378 : BaseCountedLoopNode(entry, backedge) { 379 init_class_id(Class_LongCountedLoop); 380 } 381 382 virtual int Opcode() const; 383 384 virtual BasicType bt() const { 385 return T_LONG; 386 } 387 388 LongCountedLoopEndNode* loopexit_or_null() const { return (LongCountedLoopEndNode*) BaseCountedLoopNode::loopexit_or_null(); } 389 LongCountedLoopEndNode* loopexit() const { return (LongCountedLoopEndNode*) BaseCountedLoopNode::loopexit(); } 390 }; 391 392 393 //------------------------------CountedLoopEndNode----------------------------- 394 // CountedLoopEndNodes end simple trip counted loops. They act much like 395 // IfNodes. 396 397 class BaseCountedLoopEndNode : public IfNode { 398 public: 399 enum { TestControl, TestValue }; 400 BaseCountedLoopEndNode(Node *control, Node *test, float prob, float cnt) 401 : IfNode(control, test, prob, cnt) { 402 init_class_id(Class_BaseCountedLoopEnd); 403 } 404 405 Node *cmp_node() const { return (in(TestValue)->req() >=2) ? in(TestValue)->in(1) : nullptr; } 406 Node* incr() const { Node* tmp = cmp_node(); return (tmp && tmp->req() == 3) ? tmp->in(1) : nullptr; } 407 Node* limit() const { Node* tmp = cmp_node(); return (tmp && tmp->req() == 3) ? tmp->in(2) : nullptr; } 408 Node* stride() const { Node* tmp = incr(); return (tmp && tmp->req() == 3) ? tmp->in(2) : nullptr; } 409 Node* init_trip() const { Node* tmp = phi(); return (tmp && tmp->req() == 3) ? tmp->in(1) : nullptr; } 410 bool stride_is_con() const { Node *tmp = stride(); return (tmp != nullptr && tmp->is_Con()); } 411 412 PhiNode* phi() const { 413 Node* tmp = incr(); 414 if (tmp && tmp->req() == 3) { 415 Node* phi = tmp->in(1); 416 if (phi->is_Phi()) { 417 return phi->as_Phi(); 418 } 419 } 420 return nullptr; 421 } 422 423 BaseCountedLoopNode* loopnode() const { 424 // The CountedLoopNode that goes with this CountedLoopEndNode may 425 // have been optimized out by the IGVN so be cautious with the 426 // pattern matching on the graph 427 PhiNode* iv_phi = phi(); 428 if (iv_phi == nullptr) { 429 return nullptr; 430 } 431 Node* ln = iv_phi->in(0); 432 if (!ln->is_BaseCountedLoop() || ln->as_BaseCountedLoop()->loopexit_or_null() != this) { 433 return nullptr; 434 } 435 if (ln->as_BaseCountedLoop()->bt() != bt()) { 436 return nullptr; 437 } 438 return ln->as_BaseCountedLoop(); 439 } 440 441 BoolTest::mask test_trip() const { return in(TestValue)->as_Bool()->_test._test; } 442 443 jlong stride_con() const; 444 virtual BasicType bt() const = 0; 445 446 static BaseCountedLoopEndNode* make(Node* control, Node* test, float prob, float cnt, BasicType bt); 447 }; 448 449 class CountedLoopEndNode : public BaseCountedLoopEndNode { 450 public: 451 452 CountedLoopEndNode(Node *control, Node *test, float prob, float cnt) 453 : BaseCountedLoopEndNode(control, test, prob, cnt) { 454 init_class_id(Class_CountedLoopEnd); 455 } 456 virtual int Opcode() const; 457 458 CountedLoopNode* loopnode() const { 459 return (CountedLoopNode*) BaseCountedLoopEndNode::loopnode(); 460 } 461 462 virtual BasicType bt() const { 463 return T_INT; 464 } 465 466 #ifndef PRODUCT 467 virtual void dump_spec(outputStream *st) const; 468 #endif 469 }; 470 471 class LongCountedLoopEndNode : public BaseCountedLoopEndNode { 472 public: 473 LongCountedLoopEndNode(Node *control, Node *test, float prob, float cnt) 474 : BaseCountedLoopEndNode(control, test, prob, cnt) { 475 init_class_id(Class_LongCountedLoopEnd); 476 } 477 478 LongCountedLoopNode* loopnode() const { 479 return (LongCountedLoopNode*) BaseCountedLoopEndNode::loopnode(); 480 } 481 482 virtual int Opcode() const; 483 484 virtual BasicType bt() const { 485 return T_LONG; 486 } 487 }; 488 489 490 inline BaseCountedLoopEndNode* BaseCountedLoopNode::loopexit_or_null() const { 491 Node* bctrl = back_control(); 492 if (bctrl == nullptr) return nullptr; 493 494 Node* lexit = bctrl->in(0); 495 if (!lexit->is_BaseCountedLoopEnd()) { 496 return nullptr; 497 } 498 BaseCountedLoopEndNode* result = lexit->as_BaseCountedLoopEnd(); 499 if (result->bt() != bt()) { 500 return nullptr; 501 } 502 return result; 503 } 504 505 inline BaseCountedLoopEndNode* BaseCountedLoopNode::loopexit() const { 506 BaseCountedLoopEndNode* cle = loopexit_or_null(); 507 assert(cle != nullptr, "loopexit is null"); 508 return cle; 509 } 510 511 inline Node* BaseCountedLoopNode::init_trip() const { 512 BaseCountedLoopEndNode* cle = loopexit_or_null(); 513 return cle != nullptr ? cle->init_trip() : nullptr; 514 } 515 inline Node* BaseCountedLoopNode::stride() const { 516 BaseCountedLoopEndNode* cle = loopexit_or_null(); 517 return cle != nullptr ? cle->stride() : nullptr; 518 } 519 520 inline bool BaseCountedLoopNode::stride_is_con() const { 521 BaseCountedLoopEndNode* cle = loopexit_or_null(); 522 return cle != nullptr && cle->stride_is_con(); 523 } 524 inline Node* BaseCountedLoopNode::limit() const { 525 BaseCountedLoopEndNode* cle = loopexit_or_null(); 526 return cle != nullptr ? cle->limit() : nullptr; 527 } 528 inline Node* BaseCountedLoopNode::incr() const { 529 BaseCountedLoopEndNode* cle = loopexit_or_null(); 530 return cle != nullptr ? cle->incr() : nullptr; 531 } 532 inline Node* BaseCountedLoopNode::phi() const { 533 BaseCountedLoopEndNode* cle = loopexit_or_null(); 534 return cle != nullptr ? cle->phi() : nullptr; 535 } 536 537 inline jlong BaseCountedLoopNode::stride_con() const { 538 BaseCountedLoopEndNode* cle = loopexit_or_null(); 539 return cle != nullptr ? cle->stride_con() : 0; 540 } 541 542 543 //------------------------------LoopLimitNode----------------------------- 544 // Counted Loop limit node which represents exact final iterator value: 545 // trip_count = (limit - init_trip + stride - 1)/stride 546 // final_value= trip_count * stride + init_trip. 547 // Use HW instructions to calculate it when it can overflow in integer. 548 // Note, final_value should fit into integer since counted loop has 549 // limit check: limit <= max_int-stride. 550 class LoopLimitNode : public Node { 551 enum { Init=1, Limit=2, Stride=3 }; 552 public: 553 LoopLimitNode( Compile* C, Node *init, Node *limit, Node *stride ) : Node(nullptr,init,limit,stride) { 554 // Put it on the Macro nodes list to optimize during macro nodes expansion. 555 init_flags(Flag_is_macro); 556 C->add_macro_node(this); 557 } 558 virtual int Opcode() const; 559 virtual const Type *bottom_type() const { return TypeInt::INT; } 560 virtual uint ideal_reg() const { return Op_RegI; } 561 virtual const Type* Value(PhaseGVN* phase) const; 562 virtual Node *Ideal(PhaseGVN *phase, bool can_reshape); 563 virtual Node* Identity(PhaseGVN* phase); 564 }; 565 566 // Support for strip mining 567 class OuterStripMinedLoopNode : public LoopNode { 568 private: 569 static void fix_sunk_stores(CountedLoopEndNode* inner_cle, LoopNode* inner_cl, PhaseIterGVN* igvn, PhaseIdealLoop* iloop); 570 571 public: 572 OuterStripMinedLoopNode(Compile* C, Node *entry, Node *backedge) 573 : LoopNode(entry, backedge) { 574 init_class_id(Class_OuterStripMinedLoop); 575 init_flags(Flag_is_macro); 576 C->add_macro_node(this); 577 } 578 579 virtual int Opcode() const; 580 581 virtual IfTrueNode* outer_loop_tail() const; 582 virtual OuterStripMinedLoopEndNode* outer_loop_end() const; 583 virtual IfFalseNode* outer_loop_exit() const; 584 virtual SafePointNode* outer_safepoint() const; 585 void adjust_strip_mined_loop(PhaseIterGVN* igvn); 586 587 void remove_outer_loop_and_safepoint(PhaseIterGVN* igvn) const; 588 589 void transform_to_counted_loop(PhaseIterGVN* igvn, PhaseIdealLoop* iloop); 590 591 static Node* register_new_node(Node* node, LoopNode* ctrl, PhaseIterGVN* igvn, PhaseIdealLoop* iloop); 592 593 Node* register_control(Node* node, Node* loop, Node* idom, PhaseIterGVN* igvn, 594 PhaseIdealLoop* iloop); 595 }; 596 597 class OuterStripMinedLoopEndNode : public IfNode { 598 public: 599 OuterStripMinedLoopEndNode(Node *control, Node *test, float prob, float cnt) 600 : IfNode(control, test, prob, cnt) { 601 init_class_id(Class_OuterStripMinedLoopEnd); 602 } 603 604 virtual int Opcode() const; 605 606 virtual const Type* Value(PhaseGVN* phase) const; 607 virtual Node *Ideal(PhaseGVN *phase, bool can_reshape); 608 609 bool is_expanded(PhaseGVN *phase) const; 610 }; 611 612 // -----------------------------IdealLoopTree---------------------------------- 613 class IdealLoopTree : public ResourceObj { 614 public: 615 IdealLoopTree *_parent; // Parent in loop tree 616 IdealLoopTree *_next; // Next sibling in loop tree 617 IdealLoopTree *_child; // First child in loop tree 618 619 // The head-tail backedge defines the loop. 620 // If a loop has multiple backedges, this is addressed during cleanup where 621 // we peel off the multiple backedges, merging all edges at the bottom and 622 // ensuring that one proper backedge flow into the loop. 623 Node *_head; // Head of loop 624 Node *_tail; // Tail of loop 625 inline Node *tail(); // Handle lazy update of _tail field 626 inline Node *head(); // Handle lazy update of _head field 627 PhaseIdealLoop* _phase; 628 int _local_loop_unroll_limit; 629 int _local_loop_unroll_factor; 630 631 Node_List _body; // Loop body for inner loops 632 633 uint16_t _nest; // Nesting depth 634 uint8_t _irreducible:1, // True if irreducible 635 _has_call:1, // True if has call safepoint 636 _has_sfpt:1, // True if has non-call safepoint 637 _rce_candidate:1, // True if candidate for range check elimination 638 _has_range_checks:1, 639 _has_range_checks_computed:1; 640 641 Node_List* _safepts; // List of safepoints in this loop 642 Node_List* _required_safept; // A inner loop cannot delete these safepts; 643 bool _allow_optimizations; // Allow loop optimizations 644 645 IdealLoopTree( PhaseIdealLoop* phase, Node *head, Node *tail ) 646 : _parent(nullptr), _next(nullptr), _child(nullptr), 647 _head(head), _tail(tail), 648 _phase(phase), 649 _local_loop_unroll_limit(0), _local_loop_unroll_factor(0), 650 _body(Compile::current()->comp_arena()), 651 _nest(0), _irreducible(0), _has_call(0), _has_sfpt(0), _rce_candidate(0), 652 _has_range_checks(0), _has_range_checks_computed(0), 653 _safepts(nullptr), 654 _required_safept(nullptr), 655 _allow_optimizations(true) 656 { 657 precond(_head != nullptr); 658 precond(_tail != nullptr); 659 } 660 661 // Is 'l' a member of 'this'? 662 bool is_member(const IdealLoopTree *l) const; // Test for nested membership 663 664 // Set loop nesting depth. Accumulate has_call bits. 665 int set_nest( uint depth ); 666 667 // Split out multiple fall-in edges from the loop header. Move them to a 668 // private RegionNode before the loop. This becomes the loop landing pad. 669 void split_fall_in( PhaseIdealLoop *phase, int fall_in_cnt ); 670 671 // Split out the outermost loop from this shared header. 672 void split_outer_loop( PhaseIdealLoop *phase ); 673 674 // Merge all the backedges from the shared header into a private Region. 675 // Feed that region as the one backedge to this loop. 676 void merge_many_backedges( PhaseIdealLoop *phase ); 677 678 // Split shared headers and insert loop landing pads. 679 // Insert a LoopNode to replace the RegionNode. 680 // Returns TRUE if loop tree is structurally changed. 681 bool beautify_loops( PhaseIdealLoop *phase ); 682 683 // Perform optimization to use the loop predicates for null checks and range checks. 684 // Applies to any loop level (not just the innermost one) 685 bool loop_predication( PhaseIdealLoop *phase); 686 bool can_apply_loop_predication(); 687 688 // Perform iteration-splitting on inner loops. Split iterations to 689 // avoid range checks or one-shot null checks. Returns false if the 690 // current round of loop opts should stop. 691 bool iteration_split( PhaseIdealLoop *phase, Node_List &old_new ); 692 693 // Driver for various flavors of iteration splitting. Returns false 694 // if the current round of loop opts should stop. 695 bool iteration_split_impl( PhaseIdealLoop *phase, Node_List &old_new ); 696 697 // Given dominators, try to find loops with calls that must always be 698 // executed (call dominates loop tail). These loops do not need non-call 699 // safepoints (ncsfpt). 700 void check_safepts(VectorSet &visited, Node_List &stack); 701 702 // Allpaths backwards scan from loop tail, terminating each path at first safepoint 703 // encountered. 704 void allpaths_check_safepts(VectorSet &visited, Node_List &stack); 705 706 // Remove safepoints from loop. Optionally keeping one. 707 void remove_safepoints(PhaseIdealLoop* phase, bool keep_one); 708 709 // Convert to counted loops where possible 710 void counted_loop( PhaseIdealLoop *phase ); 711 712 // Check for Node being a loop-breaking test 713 Node *is_loop_exit(Node *iff) const; 714 715 // Remove simplistic dead code from loop body 716 void DCE_loop_body(); 717 718 // Look for loop-exit tests with my 50/50 guesses from the Parsing stage. 719 // Replace with a 1-in-10 exit guess. 720 void adjust_loop_exit_prob( PhaseIdealLoop *phase ); 721 722 // Return TRUE or FALSE if the loop should never be RCE'd or aligned. 723 // Useful for unrolling loops with NO array accesses. 724 bool policy_peel_only( PhaseIdealLoop *phase ) const; 725 726 // Return TRUE or FALSE if the loop should be unswitched -- clone 727 // loop with an invariant test 728 bool policy_unswitching( PhaseIdealLoop *phase ) const; 729 730 // Micro-benchmark spamming. Remove empty loops. 731 bool do_remove_empty_loop( PhaseIdealLoop *phase ); 732 733 // Convert one iteration loop into normal code. 734 bool do_one_iteration_loop( PhaseIdealLoop *phase ); 735 736 // Return TRUE or FALSE if the loop should be peeled or not. Peel if we can 737 // move some loop-invariant test (usually a null-check) before the loop. 738 bool policy_peeling(PhaseIdealLoop *phase); 739 740 uint estimate_peeling(PhaseIdealLoop *phase); 741 742 // Return TRUE or FALSE if the loop should be maximally unrolled. Stash any 743 // known trip count in the counted loop node. 744 bool policy_maximally_unroll(PhaseIdealLoop *phase) const; 745 746 // Return TRUE or FALSE if the loop should be unrolled or not. Apply unroll 747 // if the loop is a counted loop and the loop body is small enough. 748 bool policy_unroll(PhaseIdealLoop *phase); 749 750 // Loop analyses to map to a maximal superword unrolling for vectorization. 751 void policy_unroll_slp_analysis(CountedLoopNode *cl, PhaseIdealLoop *phase, int future_unroll_ct); 752 753 // Return TRUE or FALSE if the loop should be range-check-eliminated. 754 // Gather a list of IF tests that are dominated by iteration splitting; 755 // also gather the end of the first split and the start of the 2nd split. 756 bool policy_range_check(PhaseIdealLoop* phase, bool provisional, BasicType bt) const; 757 758 // Return TRUE if "iff" is a range check. 759 bool is_range_check_if(IfProjNode* if_success_proj, PhaseIdealLoop* phase, Invariance& invar DEBUG_ONLY(COMMA ProjNode* predicate_proj)) const; 760 bool is_range_check_if(IfProjNode* if_success_proj, PhaseIdealLoop* phase, BasicType bt, Node* iv, Node*& range, Node*& offset, 761 jlong& scale) const; 762 763 // Estimate the number of nodes required when cloning a loop (body). 764 uint est_loop_clone_sz(uint factor) const; 765 // Estimate the number of nodes required when unrolling a loop (body). 766 uint est_loop_unroll_sz(uint factor) const; 767 768 // Compute loop trip count if possible 769 void compute_trip_count(PhaseIdealLoop* phase); 770 771 // Compute loop trip count from profile data 772 float compute_profile_trip_cnt_helper(Node* n); 773 void compute_profile_trip_cnt( PhaseIdealLoop *phase ); 774 775 // Reassociate invariant expressions. 776 void reassociate_invariants(PhaseIdealLoop *phase); 777 // Reassociate invariant binary expressions. 778 Node* reassociate(Node* n1, PhaseIdealLoop *phase); 779 // Reassociate invariant add, subtract, and compare expressions. 780 Node* reassociate_add_sub_cmp(Node* n1, int inv1_idx, int inv2_idx, PhaseIdealLoop* phase); 781 // Return nonzero index of invariant operand if invariant and variant 782 // are combined with an associative binary. Helper for reassociate_invariants. 783 int find_invariant(Node* n, PhaseIdealLoop *phase); 784 // Return TRUE if "n" is associative. 785 bool is_associative(Node* n, Node* base=nullptr); 786 // Return TRUE if "n" is an associative cmp node. 787 bool is_associative_cmp(Node* n); 788 789 // Return true if n is invariant 790 bool is_invariant(Node* n) const; 791 792 // Put loop body on igvn work list 793 void record_for_igvn(); 794 795 bool is_root() { return _parent == nullptr; } 796 // A proper/reducible loop w/o any (occasional) dead back-edge. 797 bool is_loop() { return !_irreducible && !tail()->is_top(); } 798 bool is_counted() { return is_loop() && _head->is_CountedLoop(); } 799 bool is_innermost() { return is_loop() && _child == nullptr; } 800 801 void remove_main_post_loops(CountedLoopNode *cl, PhaseIdealLoop *phase); 802 803 bool compute_has_range_checks() const; 804 bool range_checks_present() { 805 if (!_has_range_checks_computed) { 806 if (compute_has_range_checks()) { 807 _has_range_checks = 1; 808 } 809 _has_range_checks_computed = 1; 810 } 811 return _has_range_checks; 812 } 813 814 // Return the parent's IdealLoopTree for a strip mined loop which is the outer strip mined loop. 815 // In all other cases, return this. 816 IdealLoopTree* skip_strip_mined() { 817 return _head->as_Loop()->is_strip_mined() ? _parent : this; 818 } 819 820 #ifndef PRODUCT 821 void dump_head(); // Dump loop head only 822 void dump(); // Dump this loop recursively 823 #endif 824 825 #ifdef ASSERT 826 GrowableArray<IdealLoopTree*> collect_sorted_children() const; 827 bool verify_tree(IdealLoopTree* loop_verify) const; 828 #endif 829 830 private: 831 enum { EMPTY_LOOP_SIZE = 7 }; // Number of nodes in an empty loop. 832 833 // Estimate the number of nodes resulting from control and data flow merge. 834 uint est_loop_flow_merge_sz() const; 835 836 // Check if the number of residual iterations is large with unroll_cnt. 837 // Return true if the residual iterations are more than 10% of the trip count. 838 bool is_residual_iters_large(int unroll_cnt, CountedLoopNode *cl) const { 839 return (unroll_cnt - 1) * (100.0 / LoopPercentProfileLimit) > cl->profile_trip_cnt(); 840 } 841 842 void collect_loop_core_nodes(PhaseIdealLoop* phase, Unique_Node_List& wq) const; 843 844 bool empty_loop_with_data_nodes(PhaseIdealLoop* phase) const; 845 846 void enqueue_data_nodes(PhaseIdealLoop* phase, Unique_Node_List& empty_loop_nodes, Unique_Node_List& wq) const; 847 848 bool process_safepoint(PhaseIdealLoop* phase, Unique_Node_List& empty_loop_nodes, Unique_Node_List& wq, 849 Node* sfpt) const; 850 851 bool empty_loop_candidate(PhaseIdealLoop* phase) const; 852 853 bool empty_loop_with_extra_nodes_candidate(PhaseIdealLoop* phase) const; 854 }; 855 856 // -----------------------------PhaseIdealLoop--------------------------------- 857 // Computes the mapping from Nodes to IdealLoopTrees. Organizes IdealLoopTrees 858 // into a loop tree. Drives the loop-based transformations on the ideal graph. 859 class PhaseIdealLoop : public PhaseTransform { 860 friend class IdealLoopTree; 861 friend class SuperWord; 862 friend class ShenandoahBarrierC2Support; 863 friend class AutoNodeBudget; 864 865 // Map loop membership for CFG nodes, and ctrl for non-CFG nodes. 866 Node_List _loop_or_ctrl; 867 868 // Pre-computed def-use info 869 PhaseIterGVN &_igvn; 870 871 // Head of loop tree 872 IdealLoopTree* _ltree_root; 873 874 // Array of pre-order numbers, plus post-visited bit. 875 // ZERO for not pre-visited. EVEN for pre-visited but not post-visited. 876 // ODD for post-visited. Other bits are the pre-order number. 877 uint *_preorders; 878 uint _max_preorder; 879 880 ReallocMark _nesting; // Safety checks for arena reallocation 881 882 const PhaseIdealLoop* _verify_me; 883 bool _verify_only; 884 885 // Allocate _preorders[] array 886 void allocate_preorders() { 887 _max_preorder = C->unique()+8; 888 _preorders = NEW_RESOURCE_ARRAY(uint, _max_preorder); 889 memset(_preorders, 0, sizeof(uint) * _max_preorder); 890 } 891 892 // Allocate _preorders[] array 893 void reallocate_preorders() { 894 _nesting.check(); // Check if a potential re-allocation in the resource arena is safe 895 if ( _max_preorder < C->unique() ) { 896 _preorders = REALLOC_RESOURCE_ARRAY(uint, _preorders, _max_preorder, C->unique()); 897 _max_preorder = C->unique(); 898 } 899 memset(_preorders, 0, sizeof(uint) * _max_preorder); 900 } 901 902 // Check to grow _preorders[] array for the case when build_loop_tree_impl() 903 // adds new nodes. 904 void check_grow_preorders( ) { 905 _nesting.check(); // Check if a potential re-allocation in the resource arena is safe 906 if ( _max_preorder < C->unique() ) { 907 uint newsize = _max_preorder<<1; // double size of array 908 _preorders = REALLOC_RESOURCE_ARRAY(uint, _preorders, _max_preorder, newsize); 909 memset(&_preorders[_max_preorder],0,sizeof(uint)*(newsize-_max_preorder)); 910 _max_preorder = newsize; 911 } 912 } 913 // Check for pre-visited. Zero for NOT visited; non-zero for visited. 914 int is_visited( Node *n ) const { return _preorders[n->_idx]; } 915 // Pre-order numbers are written to the Nodes array as low-bit-set values. 916 void set_preorder_visited( Node *n, int pre_order ) { 917 assert( !is_visited( n ), "already set" ); 918 _preorders[n->_idx] = (pre_order<<1); 919 }; 920 // Return pre-order number. 921 int get_preorder( Node *n ) const { assert( is_visited(n), "" ); return _preorders[n->_idx]>>1; } 922 923 // Check for being post-visited. 924 // Should be previsited already (checked with assert(is_visited(n))). 925 int is_postvisited( Node *n ) const { assert( is_visited(n), "" ); return _preorders[n->_idx]&1; } 926 927 // Mark as post visited 928 void set_postvisited( Node *n ) { assert( !is_postvisited( n ), "" ); _preorders[n->_idx] |= 1; } 929 930 public: 931 // Set/get control node out. Set lower bit to distinguish from IdealLoopTree 932 // Returns true if "n" is a data node, false if it's a control node. 933 bool has_ctrl(const Node* n) const { return ((intptr_t)_loop_or_ctrl[n->_idx]) & 1; } 934 935 private: 936 // clear out dead code after build_loop_late 937 Node_List _deadlist; 938 Node_List _zero_trip_guard_opaque_nodes; 939 Node_List _multiversion_opaque_nodes; 940 941 // Support for faster execution of get_late_ctrl()/dom_lca() 942 // when a node has many uses and dominator depth is deep. 943 GrowableArray<jlong> _dom_lca_tags; 944 uint _dom_lca_tags_round; 945 void init_dom_lca_tags(); 946 947 // Helper for debugging bad dominance relationships 948 bool verify_dominance(Node* n, Node* use, Node* LCA, Node* early); 949 950 Node* compute_lca_of_uses(Node* n, Node* early, bool verify = false); 951 952 // Inline wrapper for frequent cases: 953 // 1) only one use 954 // 2) a use is the same as the current LCA passed as 'n1' 955 Node *dom_lca_for_get_late_ctrl( Node *lca, Node *n, Node *tag ) { 956 assert( n->is_CFG(), "" ); 957 // Fast-path null lca 958 if( lca != nullptr && lca != n ) { 959 assert( lca->is_CFG(), "" ); 960 // find LCA of all uses 961 n = dom_lca_for_get_late_ctrl_internal( lca, n, tag ); 962 } 963 return find_non_split_ctrl(n); 964 } 965 Node *dom_lca_for_get_late_ctrl_internal( Node *lca, Node *n, Node *tag ); 966 967 // Helper function for directing control inputs away from CFG split points. 968 Node *find_non_split_ctrl( Node *ctrl ) const { 969 if (ctrl != nullptr) { 970 if (ctrl->is_MultiBranch()) { 971 ctrl = ctrl->in(0); 972 } 973 assert(ctrl->is_CFG(), "CFG"); 974 } 975 return ctrl; 976 } 977 978 void cast_incr_before_loop(Node* incr, Node* ctrl, CountedLoopNode* loop); 979 980 #ifdef ASSERT 981 static void ensure_zero_trip_guard_proj(Node* node, bool is_main_loop); 982 #endif 983 private: 984 static void get_opaque_template_assertion_predicate_nodes(ParsePredicateSuccessProj* parse_predicate_proj, 985 Unique_Node_List& list); 986 void update_main_loop_assertion_predicates(CountedLoopNode* new_main_loop_head, int stride_con_before_unroll); 987 void initialize_assertion_predicates_for_peeled_loop(CountedLoopNode* peeled_loop_head, 988 CountedLoopNode* remaining_loop_head, 989 uint first_node_index_in_cloned_loop_body, 990 const Node_List& old_new); 991 void initialize_assertion_predicates_for_main_loop(CountedLoopNode* pre_loop_head, 992 CountedLoopNode* main_loop_head, 993 uint first_node_index_in_pre_loop_body, 994 uint last_node_index_in_pre_loop_body, 995 DEBUG_ONLY(uint last_node_index_from_backedge_goo COMMA) 996 const Node_List& old_new); 997 void initialize_assertion_predicates_for_post_loop(CountedLoopNode* main_loop_head, CountedLoopNode* post_loop_head, 998 uint first_node_index_in_cloned_loop_body); 999 void create_assertion_predicates_at_loop(CountedLoopNode* source_loop_head, CountedLoopNode* target_loop_head, 1000 const NodeInLoopBody& _node_in_loop_body, bool kill_old_template); 1001 void create_assertion_predicates_at_main_or_post_loop(CountedLoopNode* source_loop_head, 1002 CountedLoopNode* target_loop_head, 1003 const NodeInLoopBody& _node_in_loop_body, 1004 bool kill_old_template); 1005 void rewire_old_target_loop_entry_dependency_to_new_entry(CountedLoopNode* target_loop_head, 1006 const Node* old_target_loop_entry, 1007 uint node_index_before_new_assertion_predicate_nodes); 1008 void insert_loop_limit_check_predicate(ParsePredicateSuccessProj* loop_limit_check_parse_proj, Node* cmp_limit, 1009 Node* bol); 1010 void log_loop_tree(); 1011 1012 public: 1013 1014 PhaseIterGVN &igvn() const { return _igvn; } 1015 1016 bool has_node(const Node* n) const { 1017 guarantee(n != nullptr, "No Node."); 1018 return _loop_or_ctrl[n->_idx] != nullptr; 1019 } 1020 // check if transform created new nodes that need _ctrl recorded 1021 Node *get_late_ctrl( Node *n, Node *early ); 1022 Node *get_early_ctrl( Node *n ); 1023 Node *get_early_ctrl_for_expensive(Node *n, Node* earliest); 1024 void set_early_ctrl(Node* n, bool update_body); 1025 void set_subtree_ctrl(Node* n, bool update_body); 1026 void set_ctrl( Node *n, Node *ctrl ) { 1027 assert( !has_node(n) || has_ctrl(n), "" ); 1028 assert( ctrl->in(0), "cannot set dead control node" ); 1029 assert( ctrl == find_non_split_ctrl(ctrl), "must set legal crtl" ); 1030 _loop_or_ctrl.map(n->_idx, (Node*)((intptr_t)ctrl + 1)); 1031 } 1032 void set_root_as_ctrl(Node* n) { 1033 assert(!has_node(n) || has_ctrl(n), ""); 1034 _loop_or_ctrl.map(n->_idx, (Node*)((intptr_t)C->root() + 1)); 1035 } 1036 // Set control and update loop membership 1037 void set_ctrl_and_loop(Node* n, Node* ctrl) { 1038 IdealLoopTree* old_loop = get_loop(get_ctrl(n)); 1039 IdealLoopTree* new_loop = get_loop(ctrl); 1040 if (old_loop != new_loop) { 1041 if (old_loop->_child == nullptr) old_loop->_body.yank(n); 1042 if (new_loop->_child == nullptr) new_loop->_body.push(n); 1043 } 1044 set_ctrl(n, ctrl); 1045 } 1046 // Control nodes can be replaced or subsumed. During this pass they 1047 // get their replacement Node in slot 1. Instead of updating the block 1048 // location of all Nodes in the subsumed block, we lazily do it. As we 1049 // pull such a subsumed block out of the array, we write back the final 1050 // correct block. 1051 Node* get_ctrl(const Node* i) { 1052 assert(has_node(i), ""); 1053 Node *n = get_ctrl_no_update(i); 1054 _loop_or_ctrl.map(i->_idx, (Node*)((intptr_t)n + 1)); 1055 assert(has_node(i) && has_ctrl(i), ""); 1056 assert(n == find_non_split_ctrl(n), "must return legal ctrl" ); 1057 return n; 1058 } 1059 1060 bool is_dominator(Node* dominator, Node* n); 1061 bool is_strict_dominator(Node* dominator, Node* n); 1062 1063 // return get_ctrl for a data node and self(n) for a CFG node 1064 Node* ctrl_or_self(Node* n) { 1065 if (has_ctrl(n)) 1066 return get_ctrl(n); 1067 else { 1068 assert (n->is_CFG(), "must be a CFG node"); 1069 return n; 1070 } 1071 } 1072 1073 Node* get_ctrl_no_update_helper(const Node* i) const { 1074 assert(has_ctrl(i), "should be control, not loop"); 1075 return (Node*)(((intptr_t)_loop_or_ctrl[i->_idx]) & ~1); 1076 } 1077 1078 Node* get_ctrl_no_update(const Node* i) const { 1079 assert( has_ctrl(i), "" ); 1080 Node *n = get_ctrl_no_update_helper(i); 1081 if (!n->in(0)) { 1082 // Skip dead CFG nodes 1083 do { 1084 n = get_ctrl_no_update_helper(n); 1085 } while (!n->in(0)); 1086 n = find_non_split_ctrl(n); 1087 } 1088 return n; 1089 } 1090 1091 // Check for loop being set 1092 // "n" must be a control node. Returns true if "n" is known to be in a loop. 1093 bool has_loop( Node *n ) const { 1094 assert(!has_node(n) || !has_ctrl(n), ""); 1095 return has_node(n); 1096 } 1097 // Set loop 1098 void set_loop( Node *n, IdealLoopTree *loop ) { 1099 _loop_or_ctrl.map(n->_idx, (Node*)loop); 1100 } 1101 // Lazy-dazy update of 'get_ctrl' and 'idom_at' mechanisms. Replace 1102 // the 'old_node' with 'new_node'. Kill old-node. Add a reference 1103 // from old_node to new_node to support the lazy update. Reference 1104 // replaces loop reference, since that is not needed for dead node. 1105 void lazy_update(Node *old_node, Node *new_node) { 1106 assert(old_node != new_node, "no cycles please"); 1107 // Re-use the side array slot for this node to provide the 1108 // forwarding pointer. 1109 _loop_or_ctrl.map(old_node->_idx, (Node*)((intptr_t)new_node + 1)); 1110 } 1111 void lazy_replace(Node *old_node, Node *new_node) { 1112 _igvn.replace_node(old_node, new_node); 1113 lazy_update(old_node, new_node); 1114 } 1115 1116 private: 1117 1118 // Place 'n' in some loop nest, where 'n' is a CFG node 1119 void build_loop_tree(); 1120 int build_loop_tree_impl(Node* n, int pre_order); 1121 // Insert loop into the existing loop tree. 'innermost' is a leaf of the 1122 // loop tree, not the root. 1123 IdealLoopTree *sort( IdealLoopTree *loop, IdealLoopTree *innermost ); 1124 1125 #ifdef ASSERT 1126 // verify that regions in irreducible loops are marked is_in_irreducible_loop 1127 void verify_regions_in_irreducible_loops(); 1128 bool is_in_irreducible_loop(RegionNode* region); 1129 #endif 1130 1131 // Place Data nodes in some loop nest 1132 void build_loop_early( VectorSet &visited, Node_List &worklist, Node_Stack &nstack ); 1133 void build_loop_late ( VectorSet &visited, Node_List &worklist, Node_Stack &nstack ); 1134 void build_loop_late_post_work(Node* n, bool pinned); 1135 void build_loop_late_post(Node* n); 1136 void verify_strip_mined_scheduling(Node *n, Node* least); 1137 1138 // Array of immediate dominance info for each CFG node indexed by node idx 1139 private: 1140 uint _idom_size; 1141 Node **_idom; // Array of immediate dominators 1142 uint *_dom_depth; // Used for fast LCA test 1143 GrowableArray<uint>* _dom_stk; // For recomputation of dom depth 1144 LoopOptsMode _mode; 1145 1146 // build the loop tree and perform any requested optimizations 1147 void build_and_optimize(); 1148 1149 // Dominators for the sea of nodes 1150 void Dominators(); 1151 1152 // Compute the Ideal Node to Loop mapping 1153 PhaseIdealLoop(PhaseIterGVN& igvn, LoopOptsMode mode) : 1154 PhaseTransform(Ideal_Loop), 1155 _loop_or_ctrl(igvn.C->comp_arena()), 1156 _igvn(igvn), 1157 _verify_me(nullptr), 1158 _verify_only(false), 1159 _mode(mode), 1160 _nodes_required(UINT_MAX) { 1161 assert(mode != LoopOptsVerify, "wrong constructor to verify IdealLoop"); 1162 build_and_optimize(); 1163 } 1164 1165 #ifndef PRODUCT 1166 // Verify that verify_me made the same decisions as a fresh run 1167 // or only verify that the graph is valid if verify_me is null. 1168 PhaseIdealLoop(PhaseIterGVN& igvn, const PhaseIdealLoop* verify_me = nullptr) : 1169 PhaseTransform(Ideal_Loop), 1170 _loop_or_ctrl(igvn.C->comp_arena()), 1171 _igvn(igvn), 1172 _verify_me(verify_me), 1173 _verify_only(verify_me == nullptr), 1174 _mode(LoopOptsVerify), 1175 _nodes_required(UINT_MAX) { 1176 DEBUG_ONLY(C->set_phase_verify_ideal_loop();) 1177 build_and_optimize(); 1178 DEBUG_ONLY(C->reset_phase_verify_ideal_loop();) 1179 } 1180 #endif 1181 1182 Node* insert_convert_node_if_needed(BasicType target, Node* input); 1183 1184 public: 1185 Node* idom_no_update(Node* d) const { 1186 return idom_no_update(d->_idx); 1187 } 1188 1189 Node* idom_no_update(uint didx) const { 1190 assert(didx < _idom_size, "oob"); 1191 Node* n = _idom[didx]; 1192 assert(n != nullptr,"Bad immediate dominator info."); 1193 while (n->in(0) == nullptr) { // Skip dead CFG nodes 1194 n = (Node*)(((intptr_t)_loop_or_ctrl[n->_idx]) & ~1); 1195 assert(n != nullptr,"Bad immediate dominator info."); 1196 } 1197 return n; 1198 } 1199 1200 Node *idom(Node* d) const { 1201 return idom(d->_idx); 1202 } 1203 1204 Node *idom(uint didx) const { 1205 Node *n = idom_no_update(didx); 1206 _idom[didx] = n; // Lazily remove dead CFG nodes from table. 1207 return n; 1208 } 1209 1210 uint dom_depth(Node* d) const { 1211 guarantee(d != nullptr, "Null dominator info."); 1212 guarantee(d->_idx < _idom_size, ""); 1213 return _dom_depth[d->_idx]; 1214 } 1215 void set_idom(Node* d, Node* n, uint dom_depth); 1216 // Locally compute IDOM using dom_lca call 1217 Node *compute_idom( Node *region ) const; 1218 // Recompute dom_depth 1219 void recompute_dom_depth(); 1220 1221 // Is safept not required by an outer loop? 1222 bool is_deleteable_safept(Node* sfpt); 1223 1224 // Replace parallel induction variable (parallel to trip counter) 1225 void replace_parallel_iv(IdealLoopTree *loop); 1226 1227 Node *dom_lca( Node *n1, Node *n2 ) const { 1228 return find_non_split_ctrl(dom_lca_internal(n1, n2)); 1229 } 1230 Node *dom_lca_internal( Node *n1, Node *n2 ) const; 1231 1232 Node* dominated_node(Node* c1, Node* c2) { 1233 assert(is_dominator(c1, c2) || is_dominator(c2, c1), "nodes must be related"); 1234 return is_dominator(c1, c2) ? c2 : c1; 1235 } 1236 1237 // Return control node that's dominated by the 2 others 1238 Node* dominated_node(Node* c1, Node* c2, Node* c3) { 1239 return dominated_node(c1, dominated_node(c2, c3)); 1240 } 1241 1242 // Build and verify the loop tree without modifying the graph. This 1243 // is useful to verify that all inputs properly dominate their uses. 1244 static void verify(PhaseIterGVN& igvn) { 1245 #ifdef ASSERT 1246 ResourceMark rm; 1247 Compile::TracePhase tp(_t_idealLoopVerify); 1248 PhaseIdealLoop v(igvn); 1249 #endif 1250 } 1251 1252 // Recommended way to use PhaseIdealLoop. 1253 // Run PhaseIdealLoop in some mode and allocates a local scope for memory allocations. 1254 static void optimize(PhaseIterGVN &igvn, LoopOptsMode mode) { 1255 ResourceMark rm; 1256 PhaseIdealLoop v(igvn, mode); 1257 1258 Compile* C = Compile::current(); 1259 if (!C->failing()) { 1260 // Cleanup any modified bits 1261 igvn.optimize(); 1262 if (C->failing()) { return; } 1263 v.log_loop_tree(); 1264 } 1265 } 1266 1267 // True if the method has at least 1 irreducible loop 1268 bool _has_irreducible_loops; 1269 1270 // Per-Node transform 1271 virtual Node* transform(Node* n) { return nullptr; } 1272 1273 Node* loop_exit_control(Node* x, IdealLoopTree* loop); 1274 Node* loop_exit_test(Node* back_control, IdealLoopTree* loop, Node*& incr, Node*& limit, BoolTest::mask& bt, float& cl_prob); 1275 Node* loop_iv_incr(Node* incr, Node* x, IdealLoopTree* loop, Node*& phi_incr); 1276 Node* loop_iv_stride(Node* incr, IdealLoopTree* loop, Node*& xphi); 1277 PhiNode* loop_iv_phi(Node* xphi, Node* phi_incr, Node* x, IdealLoopTree* loop); 1278 1279 bool is_counted_loop(Node* x, IdealLoopTree*&loop, BasicType iv_bt); 1280 1281 Node* loop_nest_replace_iv(Node* iv_to_replace, Node* inner_iv, Node* outer_phi, Node* inner_head, BasicType bt); 1282 bool create_loop_nest(IdealLoopTree* loop, Node_List &old_new); 1283 #ifdef ASSERT 1284 bool convert_to_long_loop(Node* cmp, Node* phi, IdealLoopTree* loop); 1285 #endif 1286 void add_parse_predicate(Deoptimization::DeoptReason reason, Node* inner_head, IdealLoopTree* loop, SafePointNode* sfpt); 1287 SafePointNode* find_safepoint(Node* back_control, Node* x, IdealLoopTree* loop); 1288 IdealLoopTree* insert_outer_loop(IdealLoopTree* loop, LoopNode* outer_l, Node* outer_ift); 1289 IdealLoopTree* create_outer_strip_mined_loop(BoolNode *test, Node *cmp, Node *init_control, 1290 IdealLoopTree* loop, float cl_prob, float le_fcnt, 1291 Node*& entry_control, Node*& iffalse); 1292 1293 Node* exact_limit( IdealLoopTree *loop ); 1294 1295 // Return a post-walked LoopNode 1296 IdealLoopTree *get_loop( Node *n ) const { 1297 // Dead nodes have no loop, so return the top level loop instead 1298 if (!has_node(n)) return _ltree_root; 1299 assert(!has_ctrl(n), ""); 1300 return (IdealLoopTree*)_loop_or_ctrl[n->_idx]; 1301 } 1302 1303 IdealLoopTree* ltree_root() const { return _ltree_root; } 1304 1305 // Is 'n' a (nested) member of 'loop'? 1306 int is_member( const IdealLoopTree *loop, Node *n ) const { 1307 return loop->is_member(get_loop(n)); } 1308 1309 // This is the basic building block of the loop optimizations. It clones an 1310 // entire loop body. It makes an old_new loop body mapping; with this 1311 // mapping you can find the new-loop equivalent to an old-loop node. All 1312 // new-loop nodes are exactly equal to their old-loop counterparts, all 1313 // edges are the same. All exits from the old-loop now have a RegionNode 1314 // that merges the equivalent new-loop path. This is true even for the 1315 // normal "loop-exit" condition. All uses of loop-invariant old-loop values 1316 // now come from (one or more) Phis that merge their new-loop equivalents. 1317 // Parameter side_by_side_idom: 1318 // When side_by_size_idom is null, the dominator tree is constructed for 1319 // the clone loop to dominate the original. Used in construction of 1320 // pre-main-post loop sequence. 1321 // When nonnull, the clone and original are side-by-side, both are 1322 // dominated by the passed in side_by_side_idom node. Used in 1323 // construction of unswitched loops. 1324 enum CloneLoopMode { 1325 IgnoreStripMined = 0, // Only clone inner strip mined loop 1326 CloneIncludesStripMined = 1, // clone both inner and outer strip mined loops 1327 ControlAroundStripMined = 2 // Only clone inner strip mined loop, 1328 // result control flow branches 1329 // either to inner clone or outer 1330 // strip mined loop. 1331 }; 1332 void clone_loop( IdealLoopTree *loop, Node_List &old_new, int dom_depth, 1333 CloneLoopMode mode, Node* side_by_side_idom = nullptr); 1334 void clone_loop_handle_data_uses(Node* old, Node_List &old_new, 1335 IdealLoopTree* loop, IdealLoopTree* companion_loop, 1336 Node_List*& split_if_set, Node_List*& split_bool_set, 1337 Node_List*& split_cex_set, Node_List& worklist, 1338 uint new_counter, CloneLoopMode mode); 1339 void clone_outer_loop(LoopNode* head, CloneLoopMode mode, IdealLoopTree *loop, 1340 IdealLoopTree* outer_loop, int dd, Node_List &old_new, 1341 Node_List& extra_data_nodes); 1342 1343 // If we got the effect of peeling, either by actually peeling or by 1344 // making a pre-loop which must execute at least once, we can remove 1345 // all loop-invariant dominated tests in the main body. 1346 void peeled_dom_test_elim( IdealLoopTree *loop, Node_List &old_new ); 1347 1348 // Generate code to do a loop peel for the given loop (and body). 1349 // old_new is a temp array. 1350 void do_peeling( IdealLoopTree *loop, Node_List &old_new ); 1351 1352 // Add pre and post loops around the given loop. These loops are used 1353 // during RCE, unrolling and aligning loops. 1354 void insert_pre_post_loops( IdealLoopTree *loop, Node_List &old_new, bool peel_only ); 1355 1356 // Add post loop after the given loop. 1357 Node *insert_post_loop(IdealLoopTree* loop, Node_List& old_new, 1358 CountedLoopNode* main_head, CountedLoopEndNode* main_end, 1359 Node* incr, Node* limit, CountedLoopNode*& post_head); 1360 1361 // Add a vector post loop between a vector main loop and the current post loop 1362 void insert_vector_post_loop(IdealLoopTree *loop, Node_List &old_new); 1363 // If Node n lives in the back_ctrl block, we clone a private version of n 1364 // in preheader_ctrl block and return that, otherwise return n. 1365 Node *clone_up_backedge_goo( Node *back_ctrl, Node *preheader_ctrl, Node *n, VectorSet &visited, Node_Stack &clones ); 1366 1367 // Take steps to maximally unroll the loop. Peel any odd iterations, then 1368 // unroll to do double iterations. The next round of major loop transforms 1369 // will repeat till the doubled loop body does all remaining iterations in 1 1370 // pass. 1371 void do_maximally_unroll( IdealLoopTree *loop, Node_List &old_new ); 1372 1373 // Unroll the loop body one step - make each trip do 2 iterations. 1374 void do_unroll( IdealLoopTree *loop, Node_List &old_new, bool adjust_min_trip ); 1375 1376 // Return true if exp is a constant times an induction var 1377 bool is_scaled_iv(Node* exp, Node* iv, BasicType bt, jlong* p_scale, bool* p_short_scale, int depth = 0); 1378 1379 bool is_iv(Node* exp, Node* iv, BasicType bt); 1380 1381 // Return true if exp is a scaled induction var plus (or minus) constant 1382 bool is_scaled_iv_plus_offset(Node* exp, Node* iv, BasicType bt, jlong* p_scale, Node** p_offset, bool* p_short_scale = nullptr, int depth = 0); 1383 bool is_scaled_iv_plus_offset(Node* exp, Node* iv, int* p_scale, Node** p_offset) { 1384 jlong long_scale; 1385 if (is_scaled_iv_plus_offset(exp, iv, T_INT, &long_scale, p_offset)) { 1386 int int_scale = checked_cast<int>(long_scale); 1387 if (p_scale != nullptr) { 1388 *p_scale = int_scale; 1389 } 1390 return true; 1391 } 1392 return false; 1393 } 1394 // Helper for finding more complex matches to is_scaled_iv_plus_offset. 1395 bool is_scaled_iv_plus_extra_offset(Node* exp1, Node* offset2, Node* iv, 1396 BasicType bt, 1397 jlong* p_scale, Node** p_offset, 1398 bool* p_short_scale, int depth); 1399 1400 // Create a new if above the uncommon_trap_if_pattern for the predicate to be promoted 1401 IfTrueNode* create_new_if_for_predicate(const ParsePredicateSuccessProj* parse_predicate_proj, Node* new_entry, 1402 Deoptimization::DeoptReason reason, int opcode, 1403 bool rewire_uncommon_proj_phi_inputs = false); 1404 1405 private: 1406 // Helper functions for create_new_if_for_predicate() 1407 void set_ctrl_of_nodes_with_same_ctrl(Node* start_node, ProjNode* old_uncommon_proj, Node* new_uncommon_proj); 1408 Unique_Node_List find_nodes_with_same_ctrl(Node* node, const ProjNode* ctrl); 1409 Node* clone_nodes_with_same_ctrl(Node* start_node, ProjNode* old_uncommon_proj, Node* new_uncommon_proj); 1410 void fix_cloned_data_node_controls(const ProjNode* orig, Node* new_uncommon_proj, 1411 const OrigToNewHashtable& orig_to_clone); 1412 bool has_dominating_loop_limit_check(Node* init_trip, Node* limit, jlong stride_con, BasicType iv_bt, 1413 Node* loop_entry); 1414 1415 public: 1416 void register_control(Node* n, IdealLoopTree *loop, Node* pred, bool update_body = true); 1417 1418 // Replace the control input of 'node' with 'new_control' and set the dom depth to the one of 'new_control'. 1419 void replace_control(Node* node, Node* new_control) { 1420 _igvn.replace_input_of(node, 0, new_control); 1421 set_idom(node, new_control, dom_depth(new_control)); 1422 } 1423 1424 void replace_loop_entry(LoopNode* loop_head, Node* new_entry) { 1425 _igvn.replace_input_of(loop_head, LoopNode::EntryControl, new_entry); 1426 set_idom(loop_head, new_entry, dom_depth(new_entry)); 1427 } 1428 1429 // Construct a range check for a predicate if 1430 BoolNode* rc_predicate(Node* ctrl, int scale, Node* offset, Node* init, Node* limit, 1431 jint stride, Node* range, bool upper, bool& overflow); 1432 1433 // Implementation of the loop predication to promote checks outside the loop 1434 bool loop_predication_impl(IdealLoopTree *loop); 1435 1436 private: 1437 bool loop_predication_impl_helper(IdealLoopTree* loop, IfProjNode* if_success_proj, 1438 ParsePredicateSuccessProj* parse_predicate_proj, CountedLoopNode* cl, ConNode* zero, 1439 Invariance& invar, Deoptimization::DeoptReason deopt_reason); 1440 bool can_create_loop_predicates(const PredicateBlock* profiled_loop_predicate_block) const; 1441 bool loop_predication_should_follow_branches(IdealLoopTree* loop, float& loop_trip_cnt); 1442 void loop_predication_follow_branches(Node *c, IdealLoopTree *loop, float loop_trip_cnt, 1443 PathFrequency& pf, Node_Stack& stack, VectorSet& seen, 1444 Node_List& if_proj_list); 1445 IfTrueNode* create_template_assertion_predicate(CountedLoopNode* loop_head, ParsePredicateNode* parse_predicate, 1446 IfProjNode* new_control, int scale, Node* offset, Node* range); 1447 void eliminate_hoisted_range_check(IfTrueNode* hoisted_check_proj, IfTrueNode* template_assertion_predicate_proj); 1448 1449 // Helper function to collect predicate for eliminating the useless ones 1450 void eliminate_useless_predicates() const; 1451 1452 void eliminate_useless_zero_trip_guard(); 1453 void eliminate_useless_multiversion_if(); 1454 1455 public: 1456 // Change the control input of expensive nodes to allow commoning by 1457 // IGVN when it is guaranteed to not result in a more frequent 1458 // execution of the expensive node. Return true if progress. 1459 bool process_expensive_nodes(); 1460 1461 // Check whether node has become unreachable 1462 bool is_node_unreachable(Node *n) const { 1463 return !has_node(n) || n->is_unreachable(_igvn); 1464 } 1465 1466 // Eliminate range-checks and other trip-counter vs loop-invariant tests. 1467 void do_range_check(IdealLoopTree* loop); 1468 1469 // Clone loop with an invariant test (that does not exit) and 1470 // insert a clone of the test that selects which version to 1471 // execute. 1472 void do_unswitching(IdealLoopTree* loop, Node_List& old_new); 1473 1474 IfNode* find_unswitch_candidate(const IdealLoopTree* loop) const; 1475 1476 private: 1477 static bool has_control_dependencies_from_predicates(LoopNode* head); 1478 static void revert_to_normal_loop(const LoopNode* loop_head); 1479 1480 void hoist_invariant_check_casts(const IdealLoopTree* loop, const Node_List& old_new, 1481 const UnswitchedLoopSelector& unswitched_loop_selector); 1482 void add_unswitched_loop_version_bodies_to_igvn(IdealLoopTree* loop, const Node_List& old_new); 1483 static void increment_unswitch_counts(LoopNode* original_head, LoopNode* new_head); 1484 void remove_unswitch_candidate_from_loops(const Node_List& old_new, const UnswitchedLoopSelector& unswitched_loop_selector); 1485 #ifndef PRODUCT 1486 static void trace_loop_unswitching_count(IdealLoopTree* loop, LoopNode* original_head); 1487 static void trace_loop_unswitching_impossible(const LoopNode* original_head); 1488 static void trace_loop_unswitching_result(const UnswitchedLoopSelector& unswitched_loop_selector, 1489 const LoopNode* original_head, const LoopNode* new_head); 1490 static void trace_loop_multiversioning_result(const LoopSelector& loop_selector, 1491 const LoopNode* original_head, const LoopNode* new_head); 1492 #endif 1493 1494 public: 1495 1496 // Range Check Elimination uses this function! 1497 // Constrain the main loop iterations so the affine function: 1498 // low_limit <= scale_con * I + offset < upper_limit 1499 // always holds true. That is, either increase the number of iterations in 1500 // the pre-loop or the post-loop until the condition holds true in the main 1501 // loop. Scale_con, offset and limit are all loop invariant. 1502 void add_constraint(jlong stride_con, jlong scale_con, Node* offset, Node* low_limit, Node* upper_limit, Node* pre_ctrl, Node** pre_limit, Node** main_limit); 1503 // Helper function for add_constraint(). 1504 Node* adjust_limit(bool reduce, Node* scale, Node* offset, Node* rc_limit, Node* old_limit, Node* pre_ctrl, bool round); 1505 1506 // Partially peel loop up through last_peel node. 1507 bool partial_peel( IdealLoopTree *loop, Node_List &old_new ); 1508 bool duplicate_loop_backedge(IdealLoopTree *loop, Node_List &old_new); 1509 1510 // AutoVectorize the loop: replace scalar ops with vector ops. 1511 enum AutoVectorizeStatus { 1512 Impossible, // This loop has the wrong shape to even try vectorization. 1513 Success, // We just successfully vectorized the loop. 1514 TriedAndFailed, // We tried to vectorize, but failed. 1515 }; 1516 AutoVectorizeStatus auto_vectorize(IdealLoopTree* lpt, VSharedData &vshared); 1517 1518 void maybe_multiversion_for_auto_vectorization_runtime_checks(IdealLoopTree* lpt, Node_List& old_new); 1519 void do_multiversioning(IdealLoopTree* lpt, Node_List& old_new); 1520 IfTrueNode* create_new_if_for_multiversion(IfTrueNode* multiversioning_fast_proj); 1521 bool try_resume_optimizations_for_delayed_slow_loop(IdealLoopTree* lpt); 1522 1523 // Move an unordered Reduction out of loop if possible 1524 void move_unordered_reduction_out_of_loop(IdealLoopTree* loop); 1525 1526 // Create a scheduled list of nodes control dependent on ctrl set. 1527 void scheduled_nodelist( IdealLoopTree *loop, VectorSet& ctrl, Node_List &sched ); 1528 // Has a use in the vector set 1529 bool has_use_in_set( Node* n, VectorSet& vset ); 1530 // Has use internal to the vector set (ie. not in a phi at the loop head) 1531 bool has_use_internal_to_set( Node* n, VectorSet& vset, IdealLoopTree *loop ); 1532 // clone "n" for uses that are outside of loop 1533 int clone_for_use_outside_loop( IdealLoopTree *loop, Node* n, Node_List& worklist ); 1534 // clone "n" for special uses that are in the not_peeled region 1535 void clone_for_special_use_inside_loop( IdealLoopTree *loop, Node* n, 1536 VectorSet& not_peel, Node_List& sink_list, Node_List& worklist ); 1537 // Insert phi(lp_entry_val, back_edge_val) at use->in(idx) for loop lp if phi does not already exist 1538 void insert_phi_for_loop( Node* use, uint idx, Node* lp_entry_val, Node* back_edge_val, LoopNode* lp ); 1539 #ifdef ASSERT 1540 // Validate the loop partition sets: peel and not_peel 1541 bool is_valid_loop_partition( IdealLoopTree *loop, VectorSet& peel, Node_List& peel_list, VectorSet& not_peel ); 1542 // Ensure that uses outside of loop are of the right form 1543 bool is_valid_clone_loop_form( IdealLoopTree *loop, Node_List& peel_list, 1544 uint orig_exit_idx, uint clone_exit_idx); 1545 bool is_valid_clone_loop_exit_use( IdealLoopTree *loop, Node* use, uint exit_idx); 1546 #endif 1547 1548 // Returns nonzero constant stride if-node is a possible iv test (otherwise returns zero.) 1549 int stride_of_possible_iv( Node* iff ); 1550 bool is_possible_iv_test( Node* iff ) { return stride_of_possible_iv(iff) != 0; } 1551 // Return the (unique) control output node that's in the loop (if it exists.) 1552 Node* stay_in_loop( Node* n, IdealLoopTree *loop); 1553 // Insert a signed compare loop exit cloned from an unsigned compare. 1554 IfNode* insert_cmpi_loop_exit(IfNode* if_cmpu, IdealLoopTree *loop); 1555 void remove_cmpi_loop_exit(IfNode* if_cmp, IdealLoopTree *loop); 1556 // Utility to register node "n" with PhaseIdealLoop 1557 void register_node(Node* n, IdealLoopTree* loop, Node* pred, uint ddepth); 1558 // Utility to create an if-projection 1559 ProjNode* proj_clone(ProjNode* p, IfNode* iff); 1560 // Force the iff control output to be the live_proj 1561 Node* short_circuit_if(IfNode* iff, ProjNode* live_proj); 1562 // Insert a region before an if projection 1563 RegionNode* insert_region_before_proj(ProjNode* proj); 1564 // Insert a new if before an if projection 1565 ProjNode* insert_if_before_proj(Node* left, bool Signed, BoolTest::mask relop, Node* right, ProjNode* proj); 1566 1567 // Passed in a Phi merging (recursively) some nearly equivalent Bool/Cmps. 1568 // "Nearly" because all Nodes have been cloned from the original in the loop, 1569 // but the fall-in edges to the Cmp are different. Clone bool/Cmp pairs 1570 // through the Phi recursively, and return a Bool. 1571 Node* clone_iff(PhiNode* phi); 1572 CmpNode* clone_bool(PhiNode* phi); 1573 1574 1575 // Rework addressing expressions to get the most loop-invariant stuff 1576 // moved out. We'd like to do all associative operators, but it's especially 1577 // important (common) to do address expressions. 1578 Node* remix_address_expressions(Node* n); 1579 Node* remix_address_expressions_add_left_shift(Node* n, IdealLoopTree* n_loop, Node* n_ctrl, BasicType bt); 1580 1581 // Convert add to muladd to generate MuladdS2I under certain criteria 1582 Node * convert_add_to_muladd(Node * n); 1583 1584 // Attempt to use a conditional move instead of a phi/branch 1585 Node *conditional_move( Node *n ); 1586 1587 // Check for aggressive application of 'split-if' optimization, 1588 // using basic block level info. 1589 void split_if_with_blocks ( VectorSet &visited, Node_Stack &nstack); 1590 Node *split_if_with_blocks_pre ( Node *n ); 1591 void split_if_with_blocks_post( Node *n ); 1592 Node *has_local_phi_input( Node *n ); 1593 // Mark an IfNode as being dominated by a prior test, 1594 // without actually altering the CFG (and hence IDOM info). 1595 void dominated_by(IfProjNode* prevdom, IfNode* iff, bool flip = false, bool pin_array_access_nodes = false); 1596 void rewire_safe_outputs_to_dominator(Node* source, Node* dominator, bool pin_array_access_nodes); 1597 1598 // Split Node 'n' through merge point 1599 RegionNode* split_thru_region(Node* n, RegionNode* region); 1600 // Split Node 'n' through merge point if there is enough win. 1601 Node *split_thru_phi( Node *n, Node *region, int policy ); 1602 // Found an If getting its condition-code input from a Phi in the 1603 // same block. Split thru the Region. 1604 void do_split_if(Node *iff, RegionNode** new_false_region = nullptr, RegionNode** new_true_region = nullptr); 1605 1606 // Conversion of fill/copy patterns into intrinsic versions 1607 bool do_intrinsify_fill(); 1608 bool intrinsify_fill(IdealLoopTree* lpt); 1609 bool match_fill_loop(IdealLoopTree* lpt, Node*& store, Node*& store_value, 1610 Node*& shift, Node*& offset); 1611 1612 private: 1613 // Return a type based on condition control flow 1614 const TypeInt* filtered_type( Node *n, Node* n_ctrl); 1615 const TypeInt* filtered_type( Node *n ) { return filtered_type(n, nullptr); } 1616 // Helpers for filtered type 1617 const TypeInt* filtered_type_from_dominators( Node* val, Node *val_ctrl); 1618 1619 // Helper functions 1620 Node *spinup( Node *iff, Node *new_false, Node *new_true, Node *region, Node *phi, small_cache *cache ); 1621 Node *find_use_block( Node *use, Node *def, Node *old_false, Node *new_false, Node *old_true, Node *new_true ); 1622 void handle_use( Node *use, Node *def, small_cache *cache, Node *region_dom, Node *new_false, Node *new_true, Node *old_false, Node *old_true ); 1623 bool split_up( Node *n, Node *blk1, Node *blk2 ); 1624 1625 Node* place_outside_loop(Node* useblock, IdealLoopTree* loop) const; 1626 Node* try_move_store_before_loop(Node* n, Node *n_ctrl); 1627 void try_move_store_after_loop(Node* n); 1628 bool identical_backtoback_ifs(Node *n); 1629 bool can_split_if(Node *n_ctrl); 1630 bool cannot_split_division(const Node* n, const Node* region) const; 1631 static bool is_divisor_loop_phi(const Node* divisor, const Node* loop); 1632 bool loop_phi_backedge_type_contains_zero(const Node* phi_divisor, const Type* zero) const; 1633 1634 // Determine if a method is too big for a/another round of split-if, based on 1635 // a magic (approximate) ratio derived from the equally magic constant 35000, 1636 // previously used for this purpose (but without relating to the node limit). 1637 bool must_throttle_split_if() { 1638 uint threshold = C->max_node_limit() * 2 / 5; 1639 return C->live_nodes() > threshold; 1640 } 1641 1642 // A simplistic node request tracking mechanism, where 1643 // = UINT_MAX Request not valid or made final. 1644 // < UINT_MAX Nodes currently requested (estimate). 1645 uint _nodes_required; 1646 1647 enum { REQUIRE_MIN = 70 }; 1648 1649 uint nodes_required() const { return _nodes_required; } 1650 1651 // Given the _currently_ available number of nodes, check whether there is 1652 // "room" for an additional request or not, considering the already required 1653 // number of nodes. Return TRUE if the new request is exceeding the node 1654 // budget limit, otherwise return FALSE. Note that this interpretation will 1655 // act pessimistic on additional requests when new nodes have already been 1656 // generated since the 'begin'. This behaviour fits with the intention that 1657 // node estimates/requests should be made upfront. 1658 bool exceeding_node_budget(uint required = 0) { 1659 assert(C->live_nodes() < C->max_node_limit(), "sanity"); 1660 uint available = C->max_node_limit() - C->live_nodes(); 1661 return available < required + _nodes_required + REQUIRE_MIN; 1662 } 1663 1664 uint require_nodes(uint require, uint minreq = REQUIRE_MIN) { 1665 precond(require > 0); 1666 _nodes_required += MAX2(require, minreq); 1667 return _nodes_required; 1668 } 1669 1670 bool may_require_nodes(uint require, uint minreq = REQUIRE_MIN) { 1671 return !exceeding_node_budget(require) && require_nodes(require, minreq) > 0; 1672 } 1673 1674 uint require_nodes_begin() { 1675 assert(_nodes_required == UINT_MAX, "Bad state (begin)."); 1676 _nodes_required = 0; 1677 return C->live_nodes(); 1678 } 1679 1680 // When a node request is final, optionally check that the requested number 1681 // of nodes was reasonably correct with respect to the number of new nodes 1682 // introduced since the last 'begin'. Always check that we have not exceeded 1683 // the maximum node limit. 1684 void require_nodes_final(uint live_at_begin, bool check_estimate) { 1685 assert(_nodes_required < UINT_MAX, "Bad state (final)."); 1686 1687 #ifdef ASSERT 1688 if (check_estimate) { 1689 // Check that the node budget request was not off by too much (x2). 1690 // Should this be the case we _surely_ need to improve the estimates 1691 // used in our budget calculations. 1692 if (C->live_nodes() - live_at_begin > 2 * _nodes_required) { 1693 log_info(compilation)("Bad node estimate: actual = %d >> request = %d", 1694 C->live_nodes() - live_at_begin, _nodes_required); 1695 } 1696 } 1697 #endif 1698 // Assert that we have stayed within the node budget limit. 1699 assert(C->live_nodes() < C->max_node_limit(), 1700 "Exceeding node budget limit: %d + %d > %d (request = %d)", 1701 C->live_nodes() - live_at_begin, live_at_begin, 1702 C->max_node_limit(), _nodes_required); 1703 1704 _nodes_required = UINT_MAX; 1705 } 1706 1707 private: 1708 1709 bool _created_loop_node; 1710 DEBUG_ONLY(void dump_idoms(Node* early, Node* wrong_lca);) 1711 NOT_PRODUCT(void dump_idoms_in_reverse(const Node* n, const Node_List& idom_list) const;) 1712 1713 public: 1714 void set_created_loop_node() { _created_loop_node = true; } 1715 bool created_loop_node() { return _created_loop_node; } 1716 void register_new_node(Node* n, Node* blk); 1717 void register_new_node_with_ctrl_of(Node* new_node, Node* ctrl_of) { 1718 register_new_node(new_node, get_ctrl(ctrl_of)); 1719 } 1720 1721 Node* clone_and_register(Node* n, Node* ctrl) { 1722 n = n->clone(); 1723 register_new_node(n, ctrl); 1724 return n; 1725 } 1726 1727 #ifdef ASSERT 1728 void dump_bad_graph(const char* msg, Node* n, Node* early, Node* LCA); 1729 #endif 1730 1731 #ifndef PRODUCT 1732 void dump() const; 1733 void dump_idom(Node* n) const { dump_idom(n, 1000); } // For debugging 1734 void dump_idom(Node* n, uint count) const; 1735 void get_idoms(Node* n, uint count, Unique_Node_List& idoms) const; 1736 void dump(IdealLoopTree* loop, uint rpo_idx, Node_List &rpo_list) const; 1737 IdealLoopTree* get_loop_idx(Node* n) const { 1738 // Dead nodes have no loop, so return the top level loop instead 1739 return _loop_or_ctrl[n->_idx] ? (IdealLoopTree*)_loop_or_ctrl[n->_idx] : _ltree_root; 1740 } 1741 // Print some stats 1742 static void print_statistics(); 1743 static int _loop_invokes; // Count of PhaseIdealLoop invokes 1744 static int _loop_work; // Sum of PhaseIdealLoop x _unique 1745 static volatile int _long_loop_candidates; 1746 static volatile int _long_loop_nests; 1747 static volatile int _long_loop_counted_loops; 1748 #endif 1749 1750 #ifdef ASSERT 1751 void verify() const; 1752 bool verify_idom_and_nodes(Node* root, const PhaseIdealLoop* phase_verify) const; 1753 bool verify_idom(Node* n, const PhaseIdealLoop* phase_verify) const; 1754 bool verify_loop_ctrl(Node* n, const PhaseIdealLoop* phase_verify) const; 1755 #endif 1756 1757 void rpo(Node* start, Node_Stack &stk, VectorSet &visited, Node_List &rpo_list) const; 1758 1759 void check_counted_loop_shape(IdealLoopTree* loop, Node* x, BasicType bt) NOT_DEBUG_RETURN; 1760 1761 LoopNode* create_inner_head(IdealLoopTree* loop, BaseCountedLoopNode* head, IfNode* exit_test); 1762 1763 1764 int extract_long_range_checks(const IdealLoopTree* loop, jint stride_con, int iters_limit, PhiNode* phi, 1765 Node_List &range_checks); 1766 1767 void transform_long_range_checks(int stride_con, const Node_List &range_checks, Node* outer_phi, 1768 Node* inner_iters_actual_int, Node* inner_phi, 1769 Node* iv_add, LoopNode* inner_head); 1770 1771 Node* get_late_ctrl_with_anti_dep(LoadNode* n, Node* early, Node* LCA); 1772 1773 bool ctrl_of_use_out_of_loop(const Node* n, Node* n_ctrl, IdealLoopTree* n_loop, Node* ctrl); 1774 1775 bool ctrl_of_all_uses_out_of_loop(const Node* n, Node* n_ctrl, IdealLoopTree* n_loop); 1776 1777 Node* compute_early_ctrl(Node* n, Node* n_ctrl); 1778 1779 void try_sink_out_of_loop(Node* n); 1780 1781 Node* clamp(Node* R, Node* L, Node* H); 1782 1783 bool safe_for_if_replacement(const Node* dom) const; 1784 1785 void push_pinned_nodes_thru_region(IfNode* dom_if, Node* region); 1786 1787 bool try_merge_identical_ifs(Node* n); 1788 1789 void clone_loop_body(const Node_List& body, Node_List &old_new, CloneMap* cm); 1790 1791 void fix_body_edges(const Node_List &body, IdealLoopTree* loop, const Node_List &old_new, int dd, 1792 IdealLoopTree* parent, bool partial); 1793 1794 void fix_ctrl_uses(const Node_List& body, const IdealLoopTree* loop, Node_List &old_new, CloneLoopMode mode, 1795 Node* side_by_side_idom, CloneMap* cm, Node_List &worklist); 1796 1797 void fix_data_uses(Node_List& body, IdealLoopTree* loop, CloneLoopMode mode, IdealLoopTree* outer_loop, 1798 uint new_counter, Node_List& old_new, Node_List& worklist, Node_List*& split_if_set, 1799 Node_List*& split_bool_set, Node_List*& split_cex_set); 1800 1801 void finish_clone_loop(Node_List* split_if_set, Node_List* split_bool_set, Node_List* split_cex_set); 1802 1803 bool at_relevant_ctrl(Node* n, const Node* blk1, const Node* blk2); 1804 1805 bool clone_cmp_loadklass_down(Node* n, const Node* blk1, const Node* blk2); 1806 void clone_loadklass_nodes_at_cmp_index(const Node* n, Node* cmp, int i); 1807 bool clone_cmp_down(Node* n, const Node* blk1, const Node* blk2); 1808 void clone_template_assertion_expression_down(Node* node); 1809 1810 Node* similar_subtype_check(const Node* x, Node* r_in); 1811 1812 void update_addp_chain_base(Node* x, Node* old_base, Node* new_base); 1813 1814 bool can_move_to_inner_loop(Node* n, LoopNode* n_loop, Node* x); 1815 1816 void pin_array_access_nodes_dependent_on(Node* ctrl); 1817 1818 Node* ensure_node_and_inputs_are_above_pre_end(CountedLoopEndNode* pre_end, Node* node); 1819 1820 ConINode* intcon(jint i); 1821 1822 ConLNode* longcon(jlong i); 1823 1824 ConNode* makecon(const Type* t); 1825 1826 ConNode* integercon(jlong l, BasicType bt); 1827 1828 ConNode* zerocon(BasicType bt); 1829 }; 1830 1831 1832 class AutoNodeBudget : public StackObj 1833 { 1834 public: 1835 enum budget_check_t { BUDGET_CHECK, NO_BUDGET_CHECK }; 1836 1837 AutoNodeBudget(PhaseIdealLoop* phase, budget_check_t chk = BUDGET_CHECK) 1838 : _phase(phase), 1839 _check_at_final(chk == BUDGET_CHECK), 1840 _nodes_at_begin(0) 1841 { 1842 precond(_phase != nullptr); 1843 1844 _nodes_at_begin = _phase->require_nodes_begin(); 1845 } 1846 1847 ~AutoNodeBudget() { 1848 #ifndef PRODUCT 1849 if (TraceLoopOpts) { 1850 uint request = _phase->nodes_required(); 1851 uint delta = _phase->C->live_nodes() - _nodes_at_begin; 1852 1853 if (request < delta) { 1854 tty->print_cr("Exceeding node budget: %d < %d", request, delta); 1855 } else { 1856 uint const REQUIRE_MIN = PhaseIdealLoop::REQUIRE_MIN; 1857 // Identify the worst estimates as "poor" ones. 1858 if (request > REQUIRE_MIN && delta > 0) { 1859 if ((delta > REQUIRE_MIN && request > 3 * delta) || 1860 (delta <= REQUIRE_MIN && request > 10 * delta)) { 1861 tty->print_cr("Poor node estimate: %d >> %d", request, delta); 1862 } 1863 } 1864 } 1865 } 1866 #endif // PRODUCT 1867 _phase->require_nodes_final(_nodes_at_begin, _check_at_final); 1868 } 1869 1870 private: 1871 PhaseIdealLoop* _phase; 1872 bool _check_at_final; 1873 uint _nodes_at_begin; 1874 }; 1875 1876 inline Node* IdealLoopTree::tail() { 1877 // Handle lazy update of _tail field. 1878 if (_tail->in(0) == nullptr) { 1879 _tail = _phase->get_ctrl(_tail); 1880 } 1881 return _tail; 1882 } 1883 1884 inline Node* IdealLoopTree::head() { 1885 // Handle lazy update of _head field. 1886 if (_head->in(0) == nullptr) { 1887 _head = _phase->get_ctrl(_head); 1888 } 1889 return _head; 1890 } 1891 1892 // Iterate over the loop tree using a preorder, left-to-right traversal. 1893 // 1894 // Example that visits all counted loops from within PhaseIdealLoop 1895 // 1896 // for (LoopTreeIterator iter(_ltree_root); !iter.done(); iter.next()) { 1897 // IdealLoopTree* lpt = iter.current(); 1898 // if (!lpt->is_counted()) continue; 1899 // ... 1900 class LoopTreeIterator : public StackObj { 1901 private: 1902 IdealLoopTree* _root; 1903 IdealLoopTree* _curnt; 1904 1905 public: 1906 LoopTreeIterator(IdealLoopTree* root) : _root(root), _curnt(root) {} 1907 1908 bool done() { return _curnt == nullptr; } // Finished iterating? 1909 1910 void next(); // Advance to next loop tree 1911 1912 IdealLoopTree* current() { return _curnt; } // Return current value of iterator. 1913 }; 1914 1915 // Compute probability of reaching some CFG node from a fixed 1916 // dominating CFG node 1917 class PathFrequency { 1918 private: 1919 Node* _dom; // frequencies are computed relative to this node 1920 Node_Stack _stack; 1921 GrowableArray<float> _freqs_stack; // keep track of intermediate result at regions 1922 GrowableArray<float> _freqs; // cache frequencies 1923 PhaseIdealLoop* _phase; 1924 1925 float check_and_truncate_frequency(float f) { 1926 assert(f >= 0, "Incorrect frequency"); 1927 // We do not perform an exact (f <= 1) check 1928 // this would be error prone with rounding of floats. 1929 // Performing a check like (f <= 1+eps) would be of benefit, 1930 // however, it is not evident how to determine such an eps, 1931 // given that an arbitrary number of add/mul operations 1932 // are performed on these frequencies. 1933 return (f > 1) ? 1 : f; 1934 } 1935 1936 public: 1937 PathFrequency(Node* dom, PhaseIdealLoop* phase) 1938 : _dom(dom), _stack(0), _phase(phase) { 1939 } 1940 1941 float to(Node* n); 1942 }; 1943 1944 // Class to clone a data node graph by taking a list of data nodes. This is done in 2 steps: 1945 // 1. Clone the data nodes 1946 // 2. Fix the cloned data inputs pointing to the old nodes to the cloned inputs by using an old->new mapping. 1947 class DataNodeGraph : public StackObj { 1948 PhaseIdealLoop* const _phase; 1949 const Unique_Node_List& _data_nodes; 1950 OrigToNewHashtable _orig_to_new; 1951 1952 public: 1953 DataNodeGraph(const Unique_Node_List& data_nodes, PhaseIdealLoop* phase) 1954 : _phase(phase), 1955 _data_nodes(data_nodes), 1956 // Use 107 as best guess which is the first resize value in ResizeableResourceHashtable::large_table_sizes. 1957 _orig_to_new(107, MaxNodeLimit) 1958 { 1959 #ifdef ASSERT 1960 for (uint i = 0; i < data_nodes.size(); i++) { 1961 assert(!data_nodes[i]->is_CFG(), "only data nodes"); 1962 } 1963 #endif 1964 } 1965 NONCOPYABLE(DataNodeGraph); 1966 1967 private: 1968 void clone(Node* node, Node* new_ctrl); 1969 void clone_data_nodes(Node* new_ctrl); 1970 void clone_data_nodes_and_transform_opaque_loop_nodes(const TransformStrategyForOpaqueLoopNodes& transform_strategy, 1971 Node* new_ctrl); 1972 void rewire_clones_to_cloned_inputs(); 1973 void transform_opaque_node(const TransformStrategyForOpaqueLoopNodes& transform_strategy, Node* node); 1974 1975 public: 1976 // Clone the provided data node collection and rewire the clones in such a way to create an identical graph copy. 1977 // Set 'new_ctrl' as ctrl for the cloned nodes. 1978 const OrigToNewHashtable& clone(Node* new_ctrl) { 1979 assert(_orig_to_new.number_of_entries() == 0, "should not call this method twice in a row"); 1980 clone_data_nodes(new_ctrl); 1981 rewire_clones_to_cloned_inputs(); 1982 return _orig_to_new; 1983 } 1984 1985 // Create a copy of the data nodes provided to the constructor by doing the following: 1986 // Clone all non-OpaqueLoop* nodes and rewire them to create an identical subgraph copy. For the OpaqueLoop* nodes, 1987 // apply the provided transformation strategy and include the transformed node into the subgraph copy to get a complete 1988 // "cloned-and-transformed" graph copy. For all newly cloned nodes (which could also be new OpaqueLoop* nodes), set 1989 // `new_ctrl` as ctrl. 1990 const OrigToNewHashtable& clone_with_opaque_loop_transform_strategy( 1991 const TransformStrategyForOpaqueLoopNodes& transform_strategy, 1992 Node* new_ctrl) { 1993 clone_data_nodes_and_transform_opaque_loop_nodes(transform_strategy, new_ctrl); 1994 rewire_clones_to_cloned_inputs(); 1995 return _orig_to_new; 1996 } 1997 }; 1998 #endif // SHARE_OPTO_LOOPNODE_HPP