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