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