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