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