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