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