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