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