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