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