1 /*
2 * Copyright (c) 2000, 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 #include "compiler/compileLog.hpp"
26 #include "gc/shared/barrierSet.hpp"
27 #include "gc/shared/c2/barrierSetC2.hpp"
28 #include "memory/allocation.inline.hpp"
29 #include "opto/addnode.hpp"
30 #include "opto/callnode.hpp"
31 #include "opto/castnode.hpp"
32 #include "opto/connode.hpp"
33 #include "opto/convertnode.hpp"
34 #include "opto/divnode.hpp"
35 #include "opto/loopnode.hpp"
36 #include "opto/movenode.hpp"
37 #include "opto/mulnode.hpp"
38 #include "opto/node.hpp"
39 #include "opto/opaquenode.hpp"
40 #include "opto/opcodes.hpp"
41 #include "opto/phase.hpp"
42 #include "opto/predicates.hpp"
43 #include "opto/rootnode.hpp"
44 #include "opto/runtime.hpp"
45 #include "opto/subnode.hpp"
46 #include "opto/superword.hpp"
47 #include "opto/vectornode.hpp"
48 #include "runtime/globals_extension.hpp"
49 #include "runtime/stubRoutines.hpp"
50
51 //------------------------------is_loop_exit-----------------------------------
52 // Given an IfNode, return the loop-exiting projection or null if both
53 // arms remain in the loop.
54 Node *IdealLoopTree::is_loop_exit(Node *iff) const {
55 assert(iff->is_If(), "not an If: %s", iff->Name());
56 assert(is_member(_phase->get_loop(iff)), "not related");
57
58 if (iff->outcnt() != 2) {
59 return nullptr; // Ignore partially dead tests
60 }
61 // Test is an IfNode, has 2 projections. If BOTH are in the loop
62 // we need loop unswitching instead of peeling.
63 if (!is_member(_phase->get_loop(iff->raw_out(0)))) {
64 return iff->raw_out(0);
65 }
66 if (!is_member(_phase->get_loop(iff->raw_out(1)))) {
67 return iff->raw_out(1);
68 }
69 return nullptr;
70 }
71
72 //------------------------------unique_loop_exit_or_null----------------------
73 // Return the loop-exit projection if loop exit is unique.
74 IfFalseNode* IdealLoopTree::unique_loop_exit_proj_or_null() {
75 if (is_loop() && head()->is_BaseCountedLoop()) {
76 IfNode* loop_end = head()->as_BaseCountedLoop()->loopexit_or_null();
77 if (loop_end == nullptr) {
78 return nullptr; // malformed loop shape
79 }
80 // Look for other loop exits.
81 assert(_phase->is_dominator(head(), tail()), "sanity");
82 for (Node* ctrl = tail(); ctrl != head(); ctrl = ctrl->in(0)) {
83 assert(is_member(_phase->get_loop(ctrl)), "sanity");
84 if (ctrl->is_If()) {
85 if (!is_loop_exit(ctrl->as_If())) {
86 continue; // local branch
87 } else if (ctrl != loop_end) {
88 return nullptr; // multiple loop exits
89 }
90 } else if (ctrl->is_Region()) {
91 return nullptr; // give up on control flow merges
92 } else if (ctrl->is_ReachabilityFence() ||
93 ctrl->is_SafePoint() ||
94 ctrl->is_MemBar() ||
95 ctrl->Opcode() == Op_Blackhole) {
96 continue; // skip
97 } else if (ctrl->is_Proj()) {
98 if (ctrl->is_IfProj() ||
99 ctrl->Opcode() == Op_SCMemProj ||
100 ctrl->Opcode() == Op_Proj) {
101 continue; // skip simple control projections
102 } else if (ctrl->is_CatchProj() ||
103 ctrl->is_JumpProj()) {
104 return nullptr; // give up on control flow splits
105 } else {
106 assert(false, "unknown control projection: %s", ctrl->Name());
107 return nullptr; // stop on unknown control node
108 }
109 } else {
110 assert(false, "unknown CFG node: %s", ctrl->Name());
111 return nullptr; // stop on unknown control node
112 }
113 }
114 assert(is_loop_exit(loop_end), "not a loop exit?");
115 return loop_end->false_proj_or_null();
116 }
117 return nullptr; // not found or multiple loop exits
118 }
119
120 //=============================================================================
121
122
123 //------------------------------record_for_igvn----------------------------
124 // Put loop body on igvn work list
125 void IdealLoopTree::record_for_igvn() {
126 for (uint i = 0; i < _body.size(); i++) {
127 Node *n = _body.at(i);
128 _phase->_igvn._worklist.push(n);
129 }
130 // put body of outer strip mined loop on igvn work list as well
131 if (_head->is_CountedLoop() && _head->as_Loop()->is_strip_mined()) {
132 CountedLoopNode* l = _head->as_CountedLoop();
133 Node* outer_loop = l->outer_loop();
134 assert(outer_loop != nullptr, "missing piece of strip mined loop");
135 _phase->_igvn._worklist.push(outer_loop);
136 Node* outer_loop_tail = l->outer_loop_tail();
137 assert(outer_loop_tail != nullptr, "missing piece of strip mined loop");
138 _phase->_igvn._worklist.push(outer_loop_tail);
139 Node* outer_loop_end = l->outer_loop_end();
140 assert(outer_loop_end != nullptr, "missing piece of strip mined loop");
141 _phase->_igvn._worklist.push(outer_loop_end);
142 Node* outer_safepoint = l->outer_safepoint();
143 assert(outer_safepoint != nullptr, "missing piece of strip mined loop");
144 _phase->_igvn._worklist.push(outer_safepoint);
145 IfFalseNode* cle_out = _head->as_CountedLoop()->loopexit()->false_proj();
146 assert(cle_out != nullptr, "missing piece of strip mined loop");
147 _phase->_igvn._worklist.push(cle_out);
148 }
149 }
150
151 //------------------------------compute_exact_trip_count-----------------------
152 // Compute loop trip count if possible. Do not recalculate trip count for
153 // split loops (pre-main-post) which have their limits and inits behind Opaque node.
154 void IdealLoopTree::compute_trip_count(PhaseIdealLoop* phase, BasicType loop_bt) {
155 if (!_head->as_Loop()->is_valid_counted_loop(loop_bt)) {
156 return;
157 }
158 BaseCountedLoopNode* cl = _head->as_BaseCountedLoop();
159 // Trip count may become nonexact for iteration split loops since
160 // RCE modifies limits. Note, _trip_count value is not reset since
161 // it is used to limit unrolling of main loop.
162 cl->set_nonexact_trip_count();
163
164 // Loop's test should be part of loop.
165 if (!phase->ctrl_is_member(this, cl->loopexit()->in(CountedLoopEndNode::TestValue)))
166 return; // Infinite loop
167
168 #ifdef ASSERT
169 BoolTest::mask bt = cl->loopexit()->test_trip();
170 assert(bt == BoolTest::lt || bt == BoolTest::gt ||
171 bt == BoolTest::ne, "canonical test is expected");
172 #endif
173
174 Node* init_n = cl->init_trip();
175 Node* limit_n = cl->limit();
176 if (init_n != nullptr && limit_n != nullptr) {
177 jlong stride_con = cl->stride_con();
178 const TypeInteger* init_type = phase->_igvn.type(init_n)->is_integer(loop_bt);
179 const TypeInteger* limit_type = phase->_igvn.type(limit_n)->is_integer(loop_bt);
180
181 // compute trip count
182 // It used to be computed as:
183 // max(1, limit_con - init_con + stride_m) / stride_con
184 // with stride_m = stride_con - (stride_con > 0 ? 1 : -1)
185 // for int counted loops only and by promoting all values to long to avoid overflow
186 // This implements the computation for int and long counted loops in a way that promotion to the next larger integer
187 // type is not needed to protect against overflow.
188 //
189 // Use unsigned longs to avoid overflow: number of iteration is a positive number but can be really large for
190 // instance if init_con = min_jint, limit_con = max_jint
191 jlong init_con = (stride_con > 0) ? init_type->lo_as_long() : init_type->hi_as_long();
192 julong uinit_con = init_con;
193 jlong limit_con = (stride_con > 0) ? limit_type->hi_as_long() : limit_type->lo_as_long();
194 julong ulimit_con = limit_con;
195 // The loop body is always executed at least once even if init >= limit (for stride_con > 0) or
196 // init <= limit (for stride_con < 0).
197 julong udiff = 1;
198 if (stride_con > 0 && limit_con > init_con) {
199 udiff = ulimit_con - uinit_con;
200 } else if (stride_con < 0 && limit_con < init_con) {
201 udiff = uinit_con - ulimit_con;
202 }
203 // The loop runs for one more iteration if the limit is (stride > 0 in this example):
204 // init + k * stride + small_value, 0 < small_value < stride
205 julong utrip_count = udiff / ABS(stride_con);
206 if (utrip_count * ABS(stride_con) != udiff) {
207 // Guaranteed to not overflow because it can only happen for ABS(stride) > 1 in which case, utrip_count can't be
208 // max_juint/max_julong
209 utrip_count++;
210 }
211
212 #ifdef ASSERT
213 if (loop_bt == T_INT) {
214 // Use longs to avoid integer overflow.
215 jlong init_con = (stride_con > 0) ? init_type->is_int()->_lo : init_type->is_int()->_hi;
216 jlong limit_con = (stride_con > 0) ? limit_type->is_int()->_hi : limit_type->is_int()->_lo;
217 int stride_m = stride_con - (stride_con > 0 ? 1 : -1);
218 jlong trip_count = (limit_con - init_con + stride_m) / stride_con;
219 // The loop body is always executed at least once even if init >= limit (for stride_con > 0) or
220 // init <= limit (for stride_con < 0).
221 trip_count = MAX2(trip_count, (jlong)1);
222 assert(checked_cast<juint>(trip_count) == checked_cast<juint>(utrip_count), "incorrect trip count computation");
223 }
224 #endif
225
226 if (utrip_count < max_unsigned_integer(loop_bt)) {
227 if (init_n->is_Con() && limit_n->is_Con()) {
228 // Set exact trip count.
229 cl->set_exact_trip_count(utrip_count);
230 } else if (loop_bt == T_LONG || cl->as_CountedLoop()->unrolled_count() == 1) {
231 // Set maximum trip count before unrolling.
232 cl->set_trip_count(utrip_count);
233 }
234 }
235 }
236 }
237
238 //------------------------------compute_profile_trip_cnt----------------------------
239 // Compute loop trip count from profile data as
240 // (backedge_count + loop_exit_count) / loop_exit_count
241
242 float IdealLoopTree::compute_profile_trip_cnt_helper(Node* n) {
243 if (n->is_If()) {
244 IfNode *iff = n->as_If();
245 if (iff->_fcnt != COUNT_UNKNOWN && iff->_prob != PROB_UNKNOWN) {
246 Node *exit = is_loop_exit(iff);
247 if (exit) {
248 float exit_prob = iff->_prob;
249 if (exit->Opcode() == Op_IfFalse) {
250 exit_prob = 1.0 - exit_prob;
251 }
252 if (exit_prob > PROB_MIN) {
253 float exit_cnt = iff->_fcnt * exit_prob;
254 return exit_cnt;
255 }
256 }
257 }
258 }
259 if (n->is_Jump()) {
260 JumpNode *jmp = n->as_Jump();
261 if (jmp->_fcnt != COUNT_UNKNOWN) {
262 float* probs = jmp->_probs;
263 float exit_prob = 0;
264 PhaseIdealLoop *phase = _phase;
265 for (DUIterator_Fast imax, i = jmp->fast_outs(imax); i < imax; i++) {
266 JumpProjNode* u = jmp->fast_out(i)->as_JumpProj();
267 if (!is_member(_phase->get_loop(u))) {
268 exit_prob += probs[u->_con];
269 }
270 }
271 return exit_prob * jmp->_fcnt;
272 }
273 }
274 return 0;
275 }
276
277 void IdealLoopTree::compute_profile_trip_cnt(PhaseIdealLoop *phase) {
278 if (!_head->is_Loop()) {
279 return;
280 }
281 LoopNode* head = _head->as_Loop();
282 if (head->profile_trip_cnt() != COUNT_UNKNOWN) {
283 return; // Already computed
284 }
285 float trip_cnt = (float)max_jint; // default is big
286
287 Node* back = head->in(LoopNode::LoopBackControl);
288 while (back != head) {
289 if ((back->Opcode() == Op_IfTrue || back->Opcode() == Op_IfFalse) &&
290 back->in(0) &&
291 back->in(0)->is_If() &&
292 back->in(0)->as_If()->_fcnt != COUNT_UNKNOWN &&
293 back->in(0)->as_If()->_prob != PROB_UNKNOWN &&
294 (back->Opcode() == Op_IfTrue ? 1-back->in(0)->as_If()->_prob : back->in(0)->as_If()->_prob) > PROB_MIN) {
295 break;
296 }
297 back = phase->idom(back);
298 }
299 if (back != head) {
300 assert((back->Opcode() == Op_IfTrue || back->Opcode() == Op_IfFalse) &&
301 back->in(0), "if-projection exists");
302 IfNode* back_if = back->in(0)->as_If();
303 float loop_back_cnt = back_if->_fcnt * (back->Opcode() == Op_IfTrue ? back_if->_prob : (1 - back_if->_prob));
304
305 // Now compute a loop exit count
306 float loop_exit_cnt = 0.0f;
307 if (_child == nullptr) {
308 for (uint i = 0; i < _body.size(); i++) {
309 Node *n = _body[i];
310 loop_exit_cnt += compute_profile_trip_cnt_helper(n);
311 }
312 } else {
313 ResourceMark rm;
314 Unique_Node_List wq;
315 wq.push(back);
316 for (uint i = 0; i < wq.size(); i++) {
317 Node *n = wq.at(i);
318 assert(n->is_CFG(), "only control nodes");
319 if (n != head) {
320 if (n->is_Region()) {
321 for (uint j = 1; j < n->req(); j++) {
322 wq.push(n->in(j));
323 }
324 } else {
325 loop_exit_cnt += compute_profile_trip_cnt_helper(n);
326 wq.push(n->in(0));
327 }
328 }
329 }
330
331 }
332 if (loop_exit_cnt > 0.0f) {
333 trip_cnt = (loop_back_cnt + loop_exit_cnt) / loop_exit_cnt;
334 } else {
335 // No exit count so use
336 trip_cnt = loop_back_cnt;
337 }
338 } else {
339 head->mark_profile_trip_failed();
340 }
341 #ifndef PRODUCT
342 if (TraceProfileTripCount) {
343 tty->print_cr("compute_profile_trip_cnt lp: %d cnt: %f\n", head->_idx, trip_cnt);
344 }
345 #endif
346 head->set_profile_trip_cnt(trip_cnt);
347 }
348
349 // Return nonzero index of invariant operand for an associative
350 // binary operation of (nonconstant) invariant and variant values.
351 // Helper for reassociate_invariants.
352 int IdealLoopTree::find_invariant(Node* n, PhaseIdealLoop* phase) {
353 bool in1_invar = this->is_invariant(n->in(1));
354 bool in2_invar = this->is_invariant(n->in(2));
355 if (in1_invar && !in2_invar) return 1;
356 if (!in1_invar && in2_invar) return 2;
357 return 0;
358 }
359
360 // Return TRUE if "n" is an associative cmp node. A cmp node is
361 // associative if it is only used for equals or not-equals
362 // comparisons of integers or longs. We cannot reassociate
363 // non-equality comparisons due to possibility of overflow.
364 bool IdealLoopTree::is_associative_cmp(Node* n) {
365 if (n->Opcode() != Op_CmpI && n->Opcode() != Op_CmpL) {
366 return false;
367 }
368 for (DUIterator i = n->outs(); n->has_out(i); i++) {
369 BoolNode* bool_out = n->out(i)->isa_Bool();
370 if (bool_out == nullptr || !(bool_out->_test._test == BoolTest::eq ||
371 bool_out->_test._test == BoolTest::ne)) {
372 return false;
373 }
374 }
375 return true;
376 }
377
378 // Return TRUE if "n" is an associative binary node. If "base" is
379 // not null, "n" must be re-associative with it.
380 bool IdealLoopTree::is_associative(Node* n, Node* base) {
381 int op = n->Opcode();
382 if (base != nullptr) {
383 assert(is_associative(base), "Base node should be associative");
384 int base_op = base->Opcode();
385 if (base_op == Op_AddI || base_op == Op_SubI || base_op == Op_CmpI) {
386 return op == Op_AddI || op == Op_SubI;
387 }
388 if (base_op == Op_AddL || base_op == Op_SubL || base_op == Op_CmpL) {
389 return op == Op_AddL || op == Op_SubL;
390 }
391 return op == base_op;
392 } else {
393 // Integer "add/sub/mul/and/or/xor" operations are associative. Integer
394 // "cmp" operations are associative if it is an equality comparison.
395 return op == Op_AddI || op == Op_AddL
396 || op == Op_SubI || op == Op_SubL
397 || op == Op_MulI || op == Op_MulL
398 || op == Op_AndI || op == Op_AndL
399 || op == Op_OrI || op == Op_OrL
400 || op == Op_XorI || op == Op_XorL
401 || is_associative_cmp(n);
402 }
403 }
404
405 // Reassociate invariant add and subtract expressions:
406 //
407 // inv1 + (x + inv2) => ( inv1 + inv2) + x
408 // (x + inv2) + inv1 => ( inv1 + inv2) + x
409 // inv1 + (x - inv2) => ( inv1 - inv2) + x
410 // inv1 - (inv2 - x) => ( inv1 - inv2) + x
411 // (x + inv2) - inv1 => (-inv1 + inv2) + x
412 // (x - inv2) + inv1 => ( inv1 - inv2) + x
413 // (x - inv2) - inv1 => (-inv1 - inv2) + x
414 // inv1 + (inv2 - x) => ( inv1 + inv2) - x
415 // inv1 - (x - inv2) => ( inv1 + inv2) - x
416 // (inv2 - x) + inv1 => ( inv1 + inv2) - x
417 // (inv2 - x) - inv1 => (-inv1 + inv2) - x
418 // inv1 - (x + inv2) => ( inv1 - inv2) - x
419 //
420 // Apply the same transformations to == and !=
421 // inv1 == (x + inv2) => ( inv1 - inv2 ) == x
422 // inv1 == (x - inv2) => ( inv1 + inv2 ) == x
423 // inv1 == (inv2 - x) => (-inv1 + inv2 ) == x
424 Node* IdealLoopTree::reassociate_add_sub_cmp(Node* n1, int inv1_idx, int inv2_idx, PhaseIdealLoop* phase) {
425 Node* n2 = n1->in(3 - inv1_idx);
426 bool n1_is_sub = n1->is_Sub() && !n1->is_Cmp();
427 bool n1_is_cmp = n1->is_Cmp();
428 bool n2_is_sub = n2->is_Sub();
429 assert(n1->is_Add() || n1_is_sub || n1_is_cmp, "Target node should be add, subtract, or compare");
430 assert(n2->is_Add() || (n2_is_sub && !n2->is_Cmp()), "Child node should be add or subtract");
431 Node* inv1 = n1->in(inv1_idx);
432 Node* inv2 = n2->in(inv2_idx);
433 Node* x = n2->in(3 - inv2_idx);
434
435 // Determine whether x, inv1, or inv2 should be negative in the transformed
436 // expression
437 bool neg_x = n2_is_sub && inv2_idx == 1;
438 bool neg_inv2 = (n2_is_sub && !n1_is_cmp && inv2_idx == 2) || (n1_is_cmp && !n2_is_sub);
439 bool neg_inv1 = (n1_is_sub && inv1_idx == 2) || (n1_is_cmp && inv2_idx == 1 && n2_is_sub);
440 if (n1_is_sub && inv1_idx == 1) {
441 neg_x = !neg_x;
442 neg_inv2 = !neg_inv2;
443 }
444
445 bool is_int = n2->bottom_type()->isa_int() != nullptr;
446 Node* inv1_c = phase->get_ctrl(inv1);
447 Node* n_inv1;
448 if (neg_inv1) {
449 if (is_int) {
450 n_inv1 = new SubINode(phase->intcon(0), inv1);
451 } else {
452 n_inv1 = new SubLNode(phase->longcon(0L), inv1);
453 }
454 phase->register_new_node(n_inv1, inv1_c);
455 } else {
456 n_inv1 = inv1;
457 }
458
459 Node* inv;
460 if (is_int) {
461 if (neg_inv2) {
462 inv = new SubINode(n_inv1, inv2);
463 } else {
464 inv = new AddINode(n_inv1, inv2);
465 }
466 phase->register_new_node(inv, phase->get_early_ctrl(inv));
467 if (n1_is_cmp) {
468 return new CmpINode(x, inv);
469 }
470 if (neg_x) {
471 return new SubINode(inv, x);
472 } else {
473 return new AddINode(x, inv);
474 }
475 } else {
476 if (neg_inv2) {
477 inv = new SubLNode(n_inv1, inv2);
478 } else {
479 inv = new AddLNode(n_inv1, inv2);
480 }
481 phase->register_new_node(inv, phase->get_early_ctrl(inv));
482 if (n1_is_cmp) {
483 return new CmpLNode(x, inv);
484 }
485 if (neg_x) {
486 return new SubLNode(inv, x);
487 } else {
488 return new AddLNode(x, inv);
489 }
490 }
491 }
492
493 // Reassociate invariant binary expressions with add/sub/mul/
494 // and/or/xor/cmp operators.
495 // For add/sub/cmp expressions: see "reassociate_add_sub_cmp"
496 //
497 // For mul/and/or/xor expressions:
498 //
499 // inv1 op (x op inv2) => (inv1 op inv2) op x
500 //
501 Node* IdealLoopTree::reassociate(Node* n1, PhaseIdealLoop *phase) {
502 if (!is_associative(n1) || n1->outcnt() == 0) return nullptr;
503 if (is_invariant(n1)) return nullptr;
504 // Don't mess with add of constant (igvn moves them to expression tree root.)
505 if (n1->is_Add() && n1->in(2)->is_Con()) return nullptr;
506
507 int inv1_idx = find_invariant(n1, phase);
508 if (!inv1_idx) return nullptr;
509 Node* n2 = n1->in(3 - inv1_idx);
510 if (!is_associative(n2, n1)) return nullptr;
511 int inv2_idx = find_invariant(n2, phase);
512 if (!inv2_idx) return nullptr;
513
514 if (!phase->may_require_nodes(10, 10)) return nullptr;
515
516 Node* result = nullptr;
517 switch (n1->Opcode()) {
518 case Op_AddI:
519 case Op_AddL:
520 case Op_SubI:
521 case Op_SubL:
522 case Op_CmpI:
523 case Op_CmpL:
524 result = reassociate_add_sub_cmp(n1, inv1_idx, inv2_idx, phase);
525 break;
526 case Op_MulI:
527 case Op_MulL:
528 case Op_AndI:
529 case Op_AndL:
530 case Op_OrI:
531 case Op_OrL:
532 case Op_XorI:
533 case Op_XorL: {
534 Node* inv1 = n1->in(inv1_idx);
535 Node* inv2 = n2->in(inv2_idx);
536 Node* x = n2->in(3 - inv2_idx);
537 Node* inv = n2->clone_with_data_edge(inv1, inv2);
538 phase->register_new_node(inv, phase->get_early_ctrl(inv));
539 result = n1->clone_with_data_edge(x, inv);
540 break;
541 }
542 default:
543 ShouldNotReachHere();
544 }
545
546 assert(result != nullptr, "");
547 phase->register_new_node_with_ctrl_of(result, n1);
548 phase->_igvn.replace_node(n1, result);
549 assert(phase->get_loop(phase->get_ctrl(n1)) == this, "");
550 _body.yank(n1);
551 return result;
552 }
553
554 //---------------------reassociate_invariants-----------------------------
555 // Reassociate invariant expressions:
556 void IdealLoopTree::reassociate_invariants(PhaseIdealLoop *phase) {
557 for (int i = _body.size() - 1; i >= 0; i--) {
558 Node *n = _body.at(i);
559 for (int j = 0; j < 5; j++) {
560 Node* nn = reassociate(n, phase);
561 if (nn == nullptr) break;
562 n = nn; // again
563 }
564 }
565 }
566
567 //------------------------------policy_peeling---------------------------------
568 // Return TRUE if the loop should be peeled, otherwise return FALSE. Peeling
569 // is applicable if we can make a loop-invariant test (usually a null-check)
570 // execute before we enter the loop. When TRUE, the estimated node budget is
571 // also requested.
572 bool IdealLoopTree::policy_peeling(PhaseIdealLoop *phase) {
573 uint estimate = estimate_peeling(phase);
574
575 return estimate == 0 ? false : phase->may_require_nodes(estimate);
576 }
577
578 // Perform actual policy and size estimate for the loop peeling transform, and
579 // return the estimated loop size if peeling is applicable, otherwise return
580 // zero. No node budget is allocated.
581 uint IdealLoopTree::estimate_peeling(PhaseIdealLoop *phase) {
582 if (LoopPeeling != 1) {
583 return 0;
584 }
585
586 // If nodes are depleted, some transform has miscalculated its needs.
587 assert(!phase->exceeding_node_budget(), "sanity");
588
589 // Peeling does loop cloning which can result in O(N^2) node construction.
590 if (_body.size() > 255 && !StressLoopPeeling) {
591 return 0; // Suppress too large body size.
592 }
593 // Optimistic estimate that approximates loop body complexity via data and
594 // control flow fan-out (instead of using the more pessimistic: BodySize^2).
595 uint estimate = est_loop_clone_sz(2);
596
597 if (phase->exceeding_node_budget(estimate)) {
598 return 0; // Too large to safely clone.
599 }
600
601 // Check for vectorized loops, any peeling done was already applied.
602 if (_head->is_CountedLoop()) {
603 CountedLoopNode* cl = _head->as_CountedLoop();
604 if (cl->is_unroll_only() || cl->trip_count() == 1) {
605 // Peeling is not legal here (cf. assert in do_peeling), we don't even stress peel!
606 return 0;
607 }
608 }
609
610 #ifndef PRODUCT
611 // It is now safe to peel or not.
612 if (StressLoopPeeling) {
613 LoopNode* loop_head = _head->as_Loop();
614 static constexpr uint max_peeling_opportunities = 5;
615 if (loop_head->_stress_peeling_attempts < max_peeling_opportunities) {
616 loop_head->_stress_peeling_attempts++;
617 // In case of stress, let's just pick randomly...
618 return ((phase->C->random() % 2) == 0) ? estimate : 0;
619 }
620 return 0;
621 }
622 // ...otherwise, let's apply our heuristic.
623 #endif
624
625 Node* test = tail();
626
627 while (test != _head) { // Scan till run off top of loop
628 if (test->is_If()) { // Test?
629 Node *ctrl = phase->get_ctrl(test->in(1));
630 if (ctrl->is_top()) {
631 return 0; // Found dead test on live IF? No peeling!
632 }
633 // Standard IF only has one input value to check for loop invariance.
634 assert(test->Opcode() == Op_If ||
635 test->Opcode() == Op_CountedLoopEnd ||
636 test->Opcode() == Op_LongCountedLoopEnd ||
637 test->Opcode() == Op_RangeCheck ||
638 test->Opcode() == Op_ParsePredicate,
639 "Check this code when new subtype is added");
640 // Condition is not a member of this loop?
641 if (!is_member(phase->get_loop(ctrl)) && is_loop_exit(test)) {
642 return estimate; // Found reason to peel!
643 }
644 }
645 // Walk up dominators to loop _head looking for test which is executed on
646 // every path through the loop.
647 test = phase->idom(test);
648 }
649 return 0;
650 }
651
652 //------------------------------peeled_dom_test_elim---------------------------
653 // If we got the effect of peeling, either by actually peeling or by making
654 // a pre-loop which must execute at least once, we can remove all
655 // loop-invariant dominated tests in the main body.
656 void PhaseIdealLoop::peeled_dom_test_elim(IdealLoopTree* loop, Node_List& old_new) {
657 bool progress = true;
658 while (progress) {
659 progress = false; // Reset for next iteration
660 Node* prev = loop->_head->in(LoopNode::LoopBackControl); // loop->tail();
661 Node* test = prev->in(0);
662 while (test != loop->_head) { // Scan till run off top of loop
663 int p_op = prev->Opcode();
664 assert(test != nullptr, "test cannot be null");
665 Node* test_cond = nullptr;
666 if ((p_op == Op_IfFalse || p_op == Op_IfTrue) && test->is_If()) {
667 test_cond = test->in(1);
668 }
669 if (test_cond != nullptr && // Test?
670 !test_cond->is_Con() && // And not already obvious?
671 // And condition is not a member of this loop?
672 !ctrl_is_member(loop, test_cond)) {
673 // Walk loop body looking for instances of this test
674 for (uint i = 0; i < loop->_body.size(); i++) {
675 Node* n = loop->_body.at(i);
676 // Check against cached test condition because dominated_by()
677 // replaces the test condition with a constant.
678 if (n->is_If() && n->in(1) == test_cond) {
679 // IfNode was dominated by version in peeled loop body
680 progress = true;
681 dominated_by(old_new[prev->_idx]->as_IfProj(), n->as_If());
682 }
683 }
684 }
685 prev = test;
686 test = idom(test);
687 } // End of scan tests in loop
688 } // End of while (progress)
689 }
690
691 //------------------------------do_peeling-------------------------------------
692 // Peel the first iteration of the given loop.
693 // Step 1: Clone the loop body. The clone becomes the peeled iteration.
694 // The pre-loop illegally has 2 control users (old & new loops).
695 // Step 2: Make the old-loop fall-in edges point to the peeled iteration.
696 // Do this by making the old-loop fall-in edges act as if they came
697 // around the loopback from the prior iteration (follow the old-loop
698 // backedges) and then map to the new peeled iteration. This leaves
699 // the pre-loop with only 1 user (the new peeled iteration), but the
700 // peeled-loop backedge has 2 users.
701 // Step 3: Cut the backedge on the clone (so its not a loop) and remove the
702 // extra backedge user.
703 //
704 // orig
705 //
706 // stmt1
707 // |
708 // v
709 // predicates
710 // |
711 // v
712 // loop<----+
713 // | |
714 // stmt2 |
715 // | |
716 // v |
717 // if ^
718 // / \ |
719 // / \ |
720 // v v |
721 // false true |
722 // / \ |
723 // / ----+
724 // |
725 // v
726 // exit
727 //
728 //
729 // after clone loop
730 //
731 // stmt1
732 // |
733 // v
734 // predicates
735 // / \
736 // clone / \ orig
737 // / \
738 // / \
739 // v v
740 // +---->loop clone loop<----+
741 // | | | |
742 // | stmt2 clone stmt2 |
743 // | | | |
744 // | v v |
745 // ^ if clone If ^
746 // | / \ / \ |
747 // | / \ / \ |
748 // | v v v v |
749 // | true false false true |
750 // | / \ / \ |
751 // +---- \ / ----+
752 // \ /
753 // 1v v2
754 // region
755 // |
756 // v
757 // exit
758 //
759 //
760 // after peel and predicate move
761 //
762 // stmt1
763 // |
764 // v
765 // predicates
766 // /
767 // /
768 // clone / orig
769 // /
770 // / +----------+
771 // / | |
772 // / | |
773 // / | |
774 // v v |
775 // TOP-->loop clone loop<----+ |
776 // | | | |
777 // stmt2 clone stmt2 | |
778 // | | | ^
779 // v v | |
780 // if clone If ^ |
781 // / \ / \ | |
782 // / \ / \ | |
783 // v v v v | |
784 // true false false true | |
785 // | \ / \ | |
786 // | \ / ----+ ^
787 // | \ / |
788 // | 1v v2 |
789 // v region |
790 // | | |
791 // | v |
792 // | exit |
793 // | |
794 // +--------------->-----------------+
795 //
796 //
797 // final graph
798 //
799 // stmt1
800 // |
801 // v
802 // predicates
803 // |
804 // v
805 // stmt2 clone
806 // |
807 // v
808 // if clone
809 // / |
810 // / |
811 // v v
812 // false true
813 // | |
814 // | v
815 // | Initialized Assertion Predicates
816 // | |
817 // | v
818 // | loop<----+
819 // | | |
820 // | stmt2 |
821 // | | |
822 // | v |
823 // v if ^
824 // | / \ |
825 // | / \ |
826 // | v v |
827 // | false true |
828 // | | \ |
829 // v v --+
830 // region
831 // |
832 // v
833 // exit
834 //
835 void PhaseIdealLoop::do_peeling(IdealLoopTree *loop, Node_List &old_new) {
836 assert(LoopPeeling != 0, "do_peeling called with loop peeling always disabled");
837
838 C->set_major_progress();
839 // Peeling a 'main' loop in a pre/main/post situation obfuscates the
840 // 'pre' loop from the main and the 'pre' can no longer have its
841 // iterations adjusted. Therefore, we need to declare this loop as
842 // no longer a 'main' loop; it will need new pre and post loops before
843 // we can do further RCE.
844 #ifndef PRODUCT
845 if (TraceLoopOpts) {
846 tty->print("Peel ");
847 loop->dump_head();
848 }
849 #endif
850 LoopNode* head = loop->_head->as_Loop();
851
852 C->print_method(PHASE_BEFORE_LOOP_PEELING, 4, head);
853
854 bool counted_loop = head->is_CountedLoop();
855 if (counted_loop) {
856 CountedLoopNode *cl = head->as_CountedLoop();
857 assert(cl->trip_count() > 0, "peeling a fully unrolled loop");
858 cl->set_trip_count(cl->trip_count() - 1);
859 if (cl->is_main_loop()) {
860 cl->set_normal_loop();
861 if (cl->is_multiversion()) {
862 // Peeling also destroys the connection of the main loop
863 // to the multiversion_if.
864 cl->set_no_multiversion();
865 }
866 #ifndef PRODUCT
867 if (TraceLoopOpts) {
868 tty->print("Peeling a 'main' loop; resetting to 'normal' ");
869 }
870 #endif
871 }
872 }
873
874 // Step 1: Clone the loop body. The clone becomes the peeled iteration.
875 // The pre-loop illegally has 2 control users (old & new loops).
876 const uint first_node_index_in_post_loop_body = Compile::current()->unique();
877 LoopNode* outer_loop_head = head->skip_strip_mined();
878 clone_loop(loop, old_new, dom_depth(outer_loop_head), ControlAroundStripMined);
879
880 // Step 2: Make the old-loop fall-in edges point to the peeled iteration.
881 // Do this by making the old-loop fall-in edges act as if they came
882 // around the loopback from the prior iteration (follow the old-loop
883 // backedges) and then map to the new peeled iteration. This leaves
884 // the pre-loop with only 1 user (the new peeled iteration), but the
885 // peeled-loop backedge has 2 users.
886 Node* new_entry = old_new[head->in(LoopNode::LoopBackControl)->_idx];
887 _igvn.hash_delete(outer_loop_head);
888 outer_loop_head->set_req(LoopNode::EntryControl, new_entry);
889 for (DUIterator_Fast jmax, j = head->fast_outs(jmax); j < jmax; j++) {
890 Node* old = head->fast_out(j);
891 if (old->in(0) == loop->_head && old->req() == 3 && old->is_Phi()) {
892 Node* new_exit_value = old_new[old->in(LoopNode::LoopBackControl)->_idx];
893 if (!new_exit_value) // Backedge value is ALSO loop invariant?
894 // Then loop body backedge value remains the same.
895 new_exit_value = old->in(LoopNode::LoopBackControl);
896 _igvn.hash_delete(old);
897 old->set_req(LoopNode::EntryControl, new_exit_value);
898 }
899 }
900
901
902 // Step 3: Cut the backedge on the clone (so its not a loop) and remove the
903 // extra backedge user.
904 Node* new_head = old_new[head->_idx];
905 _igvn.hash_delete(new_head);
906 new_head->set_req(LoopNode::LoopBackControl, C->top());
907 for (DUIterator_Fast j2max, j2 = new_head->fast_outs(j2max); j2 < j2max; j2++) {
908 Node* use = new_head->fast_out(j2);
909 if (use->in(0) == new_head && use->req() == 3 && use->is_Phi()) {
910 _igvn.hash_delete(use);
911 use->set_req(LoopNode::LoopBackControl, C->top());
912 }
913 }
914
915 // Step 4: Correct dom-depth info. Set to loop-head depth.
916
917 int dd_outer_loop_head = dom_depth(outer_loop_head);
918 set_idom(outer_loop_head, outer_loop_head->in(LoopNode::EntryControl), dd_outer_loop_head);
919 for (uint j3 = 0; j3 < loop->_body.size(); j3++) {
920 Node *old = loop->_body.at(j3);
921 Node *nnn = old_new[old->_idx];
922 if (!has_ctrl(nnn)) {
923 set_idom(nnn, idom(nnn), dd_outer_loop_head-1);
924 }
925 }
926
927 // Step 5: Assertion Predicates initialization
928 if (counted_loop) {
929 CountedLoopNode* cl = head->as_CountedLoop();
930 Node* init = cl->init_trip();
931 Node* init_ctrl = cl->skip_strip_mined()->in(LoopNode::EntryControl);
932 initialize_assertion_predicates_for_peeled_loop(new_head->as_CountedLoop(), cl,
933 first_node_index_in_post_loop_body, old_new);
934 cast_incr_before_loop(init, init_ctrl, cl);
935 }
936
937 // Now force out all loop-invariant dominating tests. The optimizer
938 // finds some, but we _know_ they are all useless.
939 peeled_dom_test_elim(loop,old_new);
940
941 loop->record_for_igvn();
942
943 C->print_method(PHASE_AFTER_LOOP_PEELING, 4, new_head);
944 }
945
946 //------------------------------policy_maximally_unroll------------------------
947 // Calculate the exact loop trip-count and return TRUE if loop can be fully,
948 // i.e. maximally, unrolled, otherwise return FALSE. When TRUE, the estimated
949 // node budget is also requested.
950 bool IdealLoopTree::policy_maximally_unroll(PhaseIdealLoop* phase) const {
951 CountedLoopNode* cl = _head->as_CountedLoop();
952 assert(cl->is_normal_loop(), "");
953 if (!cl->is_valid_counted_loop(T_INT)) {
954 return false; // Malformed counted loop.
955 }
956 if (!cl->has_exact_trip_count()) {
957 return false; // Trip count is not exact.
958 }
959
960 uint trip_count = cl->trip_count();
961 // Note, max_juint is used to indicate unknown trip count.
962 assert(trip_count > 1, "one-iteration loop should be optimized out already");
963 assert(trip_count < max_juint, "exact trip_count should be less than max_juint.");
964
965 // If nodes are depleted, some transform has miscalculated its needs.
966 assert(!phase->exceeding_node_budget(), "sanity");
967
968 // Allow the unrolled body to get larger than the standard loop size limit.
969 uint unroll_limit = (uint)LoopUnrollLimit * 4;
970 assert((intx)unroll_limit == LoopUnrollLimit * 4, "LoopUnrollLimit must fit in 32bits");
971 if (trip_count > unroll_limit || _body.size() > unroll_limit) {
972 return false;
973 }
974
975 uint new_body_size = est_loop_unroll_sz(trip_count);
976
977 if (new_body_size == UINT_MAX) { // Check for bad estimate (overflow).
978 return false;
979 }
980
981 // Fully unroll a loop with few iterations, regardless of other conditions,
982 // since the following (general) loop optimizations will split such loop in
983 // any case (into pre-main-post).
984 if (trip_count <= 3) {
985 return phase->may_require_nodes(new_body_size);
986 }
987
988 // Reject if unrolling will result in too much node construction.
989 if (new_body_size > unroll_limit || phase->exceeding_node_budget(new_body_size)) {
990 return false;
991 }
992
993 // Do not unroll a loop with String intrinsics code.
994 // String intrinsics are large and have loops.
995 for (uint k = 0; k < _body.size(); k++) {
996 Node* n = _body.at(k);
997 switch (n->Opcode()) {
998 case Op_StrComp:
999 case Op_StrEquals:
1000 case Op_VectorizedHashCode:
1001 case Op_StrIndexOf:
1002 case Op_StrIndexOfChar:
1003 case Op_EncodeISOArray:
1004 case Op_AryEq:
1005 case Op_CountPositives: {
1006 return false;
1007 }
1008 } // switch
1009 }
1010
1011 return phase->may_require_nodes(new_body_size);
1012 }
1013
1014
1015 //------------------------------policy_unroll----------------------------------
1016 // Return TRUE or FALSE if the loop should be unrolled or not. Apply unroll if
1017 // the loop is a counted loop and the loop body is small enough. When TRUE,
1018 // the estimated node budget is also requested.
1019 bool IdealLoopTree::policy_unroll(PhaseIdealLoop *phase) {
1020
1021 CountedLoopNode *cl = _head->as_CountedLoop();
1022 assert(cl->is_normal_loop() || cl->is_main_loop(), "");
1023
1024 if (!cl->is_valid_counted_loop(T_INT)) {
1025 return false; // Malformed counted loop
1026 }
1027
1028 // If nodes are depleted, some transform has miscalculated its needs.
1029 assert(!phase->exceeding_node_budget(), "sanity");
1030
1031 // Protect against over-unrolling.
1032 // After split at least one iteration will be executed in pre-loop.
1033 if (cl->trip_count() <= (cl->is_normal_loop() ? 2u : 1u)) {
1034 return false;
1035 }
1036 _local_loop_unroll_limit = LoopUnrollLimit;
1037 _local_loop_unroll_factor = 4;
1038 int future_unroll_cnt = cl->unrolled_count() * 2;
1039 if (!cl->is_vectorized_loop()) {
1040 if (future_unroll_cnt > LoopMaxUnroll) return false;
1041 } else {
1042 // obey user constraints on vector mapped loops with additional unrolling applied
1043 int unroll_constraint = (cl->slp_max_unroll()) ? cl->slp_max_unroll() : 1;
1044 if ((future_unroll_cnt / unroll_constraint) > LoopMaxUnroll) return false;
1045 }
1046
1047 const int stride_con = cl->stride_con();
1048
1049 // Check for initial stride being a small enough constant
1050 const int initial_stride_sz = MAX2(1<<2, Matcher::max_vector_size(T_BYTE) / 2);
1051 // Maximum stride size should protect against overflow, when doubling stride unroll_count times
1052 const int max_stride_size = MIN2<int>(max_jint / 2 - 2, initial_stride_sz * future_unroll_cnt);
1053 // No abs() use; abs(min_jint) = min_jint
1054 if (stride_con < -max_stride_size || stride_con > max_stride_size) return false;
1055
1056 // Don't unroll if the next round of unrolling would push us
1057 // over the expected trip count of the loop. One is subtracted
1058 // from the expected trip count because the pre-loop normally
1059 // executes 1 iteration.
1060 if (UnrollLimitForProfileCheck > 0 &&
1061 cl->profile_trip_cnt() != COUNT_UNKNOWN &&
1062 future_unroll_cnt > UnrollLimitForProfileCheck &&
1063 (float)future_unroll_cnt > cl->profile_trip_cnt() - 1.0) {
1064 return false;
1065 }
1066
1067 bool should_unroll = true;
1068
1069 // When unroll count is greater than LoopUnrollMin, don't unroll if:
1070 // the residual iterations are more than 10% of the trip count
1071 // and rounds of "unroll,optimize" are not making significant progress
1072 // Progress defined as current size less than 20% larger than previous size.
1073 if (phase->C->do_superword() &&
1074 cl->node_count_before_unroll() > 0 &&
1075 future_unroll_cnt > LoopUnrollMin &&
1076 is_residual_iters_large(future_unroll_cnt, cl) &&
1077 1.2 * cl->node_count_before_unroll() < (double)_body.size()) {
1078 if ((cl->slp_max_unroll() == 0) && !is_residual_iters_large(cl->unrolled_count(), cl)) {
1079 // cl->slp_max_unroll() = 0 means that the previous slp analysis never passed.
1080 // slp analysis may fail due to the loop IR is too complicated especially during the early stage
1081 // of loop unrolling analysis. But after several rounds of loop unrolling and other optimizations,
1082 // it's possible that the loop IR becomes simple enough to pass the slp analysis.
1083 // So we don't return immediately in hoping that the next slp analysis can succeed.
1084 should_unroll = false;
1085 future_unroll_cnt = cl->unrolled_count();
1086 } else {
1087 return false;
1088 }
1089 }
1090
1091 Node *init_n = cl->init_trip();
1092 Node *limit_n = cl->limit();
1093 if (limit_n == nullptr) return false; // We will dereference it below.
1094
1095 // Non-constant bounds.
1096 // Protect against over-unrolling when init or/and limit are not constant
1097 // (so that trip_count's init value is maxint) but iv range is known.
1098 if (init_n == nullptr || !init_n->is_Con() || !limit_n->is_Con()) {
1099 Node* phi = cl->phi();
1100 if (phi != nullptr) {
1101 assert(phi->is_Phi() && phi->in(0) == _head, "Counted loop should have iv phi.");
1102 const TypeInt* iv_type = phase->_igvn.type(phi)->is_int();
1103 int next_stride = stride_con * 2; // stride after this unroll
1104 if (next_stride > 0) {
1105 if (iv_type->_lo > max_jint - next_stride || // overflow
1106 iv_type->_lo + next_stride > iv_type->_hi) {
1107 return false; // over-unrolling
1108 }
1109 } else if (next_stride < 0) {
1110 if (iv_type->_hi < min_jint - next_stride || // overflow
1111 iv_type->_hi + next_stride < iv_type->_lo) {
1112 return false; // over-unrolling
1113 }
1114 }
1115 }
1116 }
1117
1118 // After unroll limit will be adjusted: new_limit = limit-stride.
1119 // Bailout if adjustment overflow.
1120 const TypeInt* limit_type = phase->_igvn.type(limit_n)->is_int();
1121 if ((stride_con > 0 && ((min_jint + stride_con) > limit_type->_hi)) ||
1122 (stride_con < 0 && ((max_jint + stride_con) < limit_type->_lo)))
1123 return false; // overflow
1124
1125 // Rudimentary cost model to estimate loop unrolling
1126 // factor.
1127 // Adjust body_size to determine if we unroll or not
1128 uint body_size = _body.size();
1129 // Key test to unroll loop in CRC32 java code
1130 int xors_in_loop = 0;
1131 // Also count ModL, DivL, MulL, and other nodes that expand mightly
1132 for (uint k = 0; k < _body.size(); k++) {
1133 Node* n = _body.at(k);
1134 if (MemNode::barrier_data(n) != 0) {
1135 body_size += BarrierSet::barrier_set()->barrier_set_c2()->estimated_barrier_size(n);
1136 }
1137 switch (n->Opcode()) {
1138 case Op_XorI: xors_in_loop++; break; // CRC32 java code
1139 case Op_ModL: body_size += 30; break;
1140 case Op_DivL: body_size += 30; break;
1141 case Op_MulL: body_size += 10; break;
1142 case Op_RoundF:
1143 case Op_RoundD: {
1144 body_size += Matcher::scalar_op_pre_select_sz_estimate(n->Opcode(), n->bottom_type()->basic_type());
1145 } break;
1146 case Op_CountTrailingZerosV:
1147 case Op_CountLeadingZerosV:
1148 case Op_LoadVectorGather:
1149 case Op_LoadVectorGatherMasked:
1150 case Op_ReverseV:
1151 case Op_RoundVF:
1152 case Op_RoundVD:
1153 case Op_VectorCastD2X:
1154 case Op_VectorCastF2X:
1155 case Op_PopCountVI:
1156 case Op_PopCountVL: {
1157 const TypeVect* vt = n->bottom_type()->is_vect();
1158 body_size += Matcher::vector_op_pre_select_sz_estimate(n->Opcode(), vt->element_basic_type(), vt->length());
1159 } break;
1160 case Op_StrComp:
1161 case Op_StrEquals:
1162 case Op_StrIndexOf:
1163 case Op_StrIndexOfChar:
1164 case Op_EncodeISOArray:
1165 case Op_AryEq:
1166 case Op_VectorizedHashCode:
1167 case Op_CountPositives: {
1168 // Do not unroll a loop with String intrinsics code.
1169 // String intrinsics are large and have loops.
1170 return false;
1171 }
1172 } // switch
1173 }
1174
1175 if (phase->C->do_superword()) {
1176 // Only attempt slp analysis when user controls do not prohibit it
1177 if (!range_checks_present() && (LoopMaxUnroll > _local_loop_unroll_factor)) {
1178 // Once policy_slp_analysis succeeds, mark the loop with the
1179 // maximal unroll factor so that we minimize analysis passes
1180 if (future_unroll_cnt >= _local_loop_unroll_factor) {
1181 policy_unroll_slp_analysis(cl, phase, future_unroll_cnt);
1182 }
1183 }
1184 }
1185
1186 int slp_max_unroll_factor = cl->slp_max_unroll();
1187 if ((LoopMaxUnroll < slp_max_unroll_factor) && FLAG_IS_DEFAULT(LoopMaxUnroll) && UseSubwordForMaxVector) {
1188 LoopMaxUnroll = slp_max_unroll_factor;
1189 }
1190
1191 uint estimate = est_loop_clone_sz(2);
1192
1193 if (cl->has_passed_slp()) {
1194 if (slp_max_unroll_factor >= future_unroll_cnt) {
1195 return should_unroll && phase->may_require_nodes(estimate);
1196 }
1197 return false; // Loop too big.
1198 }
1199
1200 // Check for being too big
1201 if (body_size > (uint)_local_loop_unroll_limit) {
1202 if ((cl->is_subword_loop() || xors_in_loop >= 4) && body_size < 4u * LoopUnrollLimit) {
1203 return should_unroll && phase->may_require_nodes(estimate);
1204 }
1205 return false; // Loop too big.
1206 }
1207
1208 if (cl->is_unroll_only()) {
1209 if (TraceSuperWordLoopUnrollAnalysis) {
1210 tty->print_cr("policy_unroll passed vector loop(vlen=%d, factor=%d)\n",
1211 slp_max_unroll_factor, future_unroll_cnt);
1212 }
1213 }
1214
1215 // Unroll once! (Each trip will soon do double iterations)
1216 return should_unroll && phase->may_require_nodes(estimate);
1217 }
1218
1219 void IdealLoopTree::policy_unroll_slp_analysis(CountedLoopNode *cl, PhaseIdealLoop *phase, int future_unroll_cnt) {
1220
1221 // If nodes are depleted, some transform has miscalculated its needs.
1222 assert(!phase->exceeding_node_budget(), "sanity");
1223
1224 // Enable this functionality target by target as needed
1225 if (SuperWordLoopUnrollAnalysis) {
1226 if (!cl->was_slp_analyzed()) {
1227 Compile::TracePhase tp(Phase::_t_autoVectorize);
1228
1229 VLoop vloop(this, true);
1230 if (vloop.check_preconditions()) {
1231 SuperWord::unrolling_analysis(vloop, _local_loop_unroll_factor);
1232 }
1233 }
1234
1235 if (cl->has_passed_slp()) {
1236 int slp_max_unroll_factor = cl->slp_max_unroll();
1237 if (slp_max_unroll_factor >= future_unroll_cnt) {
1238 int new_limit = cl->node_count_before_unroll() * slp_max_unroll_factor;
1239 if (new_limit > LoopUnrollLimit) {
1240 if (TraceSuperWordLoopUnrollAnalysis) {
1241 tty->print_cr("slp analysis unroll=%d, default limit=%d\n", new_limit, _local_loop_unroll_limit);
1242 }
1243 _local_loop_unroll_limit = new_limit;
1244 }
1245 }
1246 }
1247 }
1248 }
1249
1250
1251 //------------------------------policy_range_check-----------------------------
1252 // Return TRUE or FALSE if the loop should be range-check-eliminated or not.
1253 // When TRUE, the estimated node budget is also requested.
1254 //
1255 // We will actually perform iteration-splitting, a more powerful form of RCE.
1256 bool IdealLoopTree::policy_range_check(PhaseIdealLoop* phase, bool provisional, BasicType bt) const {
1257 if (!provisional && !RangeCheckElimination) return false;
1258
1259 // If nodes are depleted, some transform has miscalculated its needs.
1260 assert(provisional || !phase->exceeding_node_budget(), "sanity");
1261
1262 if (_head->is_CountedLoop()) {
1263 CountedLoopNode *cl = _head->as_CountedLoop();
1264 // If we unrolled with no intention of doing RCE and we later changed our
1265 // minds, we got no pre-loop. Either we need to make a new pre-loop, or we
1266 // have to disallow RCE.
1267 if (cl->is_main_no_pre_loop()) return false; // Disallowed for now.
1268
1269 // check for vectorized loops, some opts are no longer needed
1270 // RCE needs pre/main/post loops. Don't apply it on a single iteration loop.
1271 if (cl->is_unroll_only() || (cl->is_normal_loop() && cl->trip_count() == 1)) return false;
1272 } else {
1273 assert(provisional, "no long counted loop expected");
1274 }
1275
1276 BaseCountedLoopNode* cl = _head->as_BaseCountedLoop();
1277 Node *trip_counter = cl->phi();
1278 assert(!cl->is_LongCountedLoop() || bt == T_LONG, "only long range checks in long counted loops");
1279 assert(cl->is_valid_counted_loop(cl->bt()), "only for well formed loops");
1280
1281 // Check loop body for tests of trip-counter plus loop-invariant vs
1282 // loop-invariant.
1283 for (uint i = 0; i < _body.size(); i++) {
1284 Node *iff = _body[i];
1285 if (iff->Opcode() == Op_If ||
1286 iff->Opcode() == Op_RangeCheck) { // Test?
1287
1288 // Comparing trip+off vs limit
1289 Node* bol = iff->in(1);
1290 if (bol->req() != 2) {
1291 // Could be a dead constant test or another dead variant (e.g. a Phi with 2 inputs created with split_thru_phi).
1292 // Either way, skip this test.
1293 continue;
1294 }
1295 if (!bol->is_Bool()) {
1296 assert(bol->is_OpaqueConstantBool() ||
1297 bol->is_OpaqueTemplateAssertionPredicate() ||
1298 bol->is_OpaqueInitializedAssertionPredicate() ||
1299 bol->is_OpaqueMultiversioning(),
1300 "Opaque node of a non-null-check or an Assertion Predicate or Multiversioning");
1301 continue;
1302 }
1303 if (bol->as_Bool()->_test._test == BoolTest::ne) {
1304 continue; // not RC
1305 }
1306 Node *cmp = bol->in(1);
1307
1308 if (provisional) {
1309 // Try to pattern match with either cmp inputs, do not check
1310 // whether one of the inputs is loop independent as it may not
1311 // have had a chance to be hoisted yet.
1312 if (!phase->is_scaled_iv_plus_offset(cmp->in(1), trip_counter, bt, nullptr, nullptr) &&
1313 !phase->is_scaled_iv_plus_offset(cmp->in(2), trip_counter, bt, nullptr, nullptr)) {
1314 continue;
1315 }
1316 } else {
1317 Node *rc_exp = cmp->in(1);
1318 Node *limit = cmp->in(2);
1319 Node *limit_c = phase->get_ctrl(limit);
1320 if (limit_c == phase->C->top()) {
1321 return false; // Found dead test on live IF? No RCE!
1322 }
1323 if (is_member(phase->get_loop(limit_c))) {
1324 // Compare might have operands swapped; commute them
1325 rc_exp = cmp->in(2);
1326 limit = cmp->in(1);
1327 limit_c = phase->get_ctrl(limit);
1328 if (is_member(phase->get_loop(limit_c))) {
1329 continue; // Both inputs are loop varying; cannot RCE
1330 }
1331 }
1332
1333 if (!phase->is_scaled_iv_plus_offset(rc_exp, trip_counter, bt, nullptr, nullptr)) {
1334 continue;
1335 }
1336 }
1337 // Found a test like 'trip+off vs limit'. Test is an IfNode, has two (2)
1338 // projections. If BOTH are in the loop we need loop unswitching instead
1339 // of iteration splitting.
1340 if (is_loop_exit(iff)) {
1341 // Found valid reason to split iterations (if there is room).
1342 // NOTE: Usually a gross overestimate.
1343 // Long range checks cause the loop to be transformed in a loop nest which only causes a fixed number of nodes
1344 // to be added
1345 return provisional || bt == T_LONG || phase->may_require_nodes(est_loop_clone_sz(2));
1346 }
1347 } // End of is IF
1348 }
1349
1350 return false;
1351 }
1352
1353 //------------------------------policy_peel_only-------------------------------
1354 // Return TRUE or FALSE if the loop should NEVER be RCE'd or aligned. Useful
1355 // for unrolling loops with NO array accesses.
1356 bool IdealLoopTree::policy_peel_only(PhaseIdealLoop *phase) const {
1357
1358 // If nodes are depleted, some transform has miscalculated its needs.
1359 assert(!phase->exceeding_node_budget(), "sanity");
1360
1361 // check for vectorized loops, any peeling done was already applied
1362 if (_head->is_CountedLoop() && _head->as_CountedLoop()->is_unroll_only()) {
1363 return false;
1364 }
1365
1366 for (uint i = 0; i < _body.size(); i++) {
1367 if (_body[i]->is_Mem()) {
1368 return false;
1369 }
1370 }
1371 // No memory accesses at all!
1372 return true;
1373 }
1374
1375 //------------------------------clone_up_backedge_goo--------------------------
1376 // If Node n lives in the back_ctrl block and cannot float, we clone a private
1377 // version of n in preheader_ctrl block and return that, otherwise return n.
1378 Node *PhaseIdealLoop::clone_up_backedge_goo(Node *back_ctrl, Node *preheader_ctrl, Node *n, VectorSet &visited, Node_Stack &clones) {
1379 if (get_ctrl(n) != back_ctrl) return n;
1380
1381 // Only visit once
1382 if (visited.test_set(n->_idx)) {
1383 Node *x = clones.find(n->_idx);
1384 return (x != nullptr) ? x : n;
1385 }
1386
1387 Node *x = nullptr; // If required, a clone of 'n'
1388 // Check for 'n' being pinned in the backedge.
1389 if (n->in(0) && n->in(0) == back_ctrl) {
1390 assert(clones.find(n->_idx) == nullptr, "dead loop");
1391 x = n->clone(); // Clone a copy of 'n' to preheader
1392 clones.push(x, n->_idx);
1393 x->set_req(0, preheader_ctrl); // Fix x's control input to preheader
1394 }
1395
1396 // Recursive fixup any other input edges into x.
1397 // If there are no changes we can just return 'n', otherwise
1398 // we need to clone a private copy and change it.
1399 for (uint i = 1; i < n->req(); i++) {
1400 Node *g = clone_up_backedge_goo(back_ctrl, preheader_ctrl, n->in(i), visited, clones);
1401 if (g != n->in(i)) {
1402 if (!x) {
1403 assert(clones.find(n->_idx) == nullptr, "dead loop");
1404 x = n->clone();
1405 clones.push(x, n->_idx);
1406 }
1407 x->set_req(i, g);
1408 }
1409 }
1410 if (x) { // x can legally float to pre-header location
1411 register_new_node(x, preheader_ctrl);
1412 return x;
1413 } else { // raise n to cover LCA of uses
1414 set_ctrl(n, find_non_split_ctrl(back_ctrl->in(0)));
1415 }
1416 return n;
1417 }
1418
1419 // When a counted loop is created, the loop phi type may be narrowed down. As a consequence, the control input of some
1420 // nodes may be cleared: in particular in the case of a division by the loop iv, the Div node would lose its control
1421 // dependency if the loop phi is never zero. After pre/main/post loops are created (and possibly unrolling), the
1422 // loop phi type is only correct if the loop is indeed reachable: there's an implicit dependency between the loop phi
1423 // type and the zero trip guard for the main or post loop and as a consequence a dependency between the Div node and the
1424 // zero trip guard. This makes the dependency explicit by adding a CastII for the loop entry input of the loop phi. If
1425 // the backedge of the main or post loop is removed, a Div node won't be able to float above the zero trip guard of the
1426 // loop and can't execute even if the loop is not reached.
1427 void PhaseIdealLoop::cast_incr_before_loop(Node* incr, Node* ctrl, CountedLoopNode* loop) {
1428 Node* castii = new CastIINode(ctrl, incr, TypeInt::INT, ConstraintCastNode::DependencyType::NonFloatingNonNarrowing);
1429 register_new_node(castii, ctrl);
1430 Node* phi = loop->phi();
1431 assert(phi->in(LoopNode::EntryControl) == incr, "replacing wrong input?");
1432 _igvn.replace_input_of(phi, LoopNode::EntryControl, castii);
1433 }
1434
1435 #ifdef ASSERT
1436 void PhaseIdealLoop::ensure_zero_trip_guard_proj(Node* node, bool is_main_loop) {
1437 assert(node->is_IfProj(), "must be the zero trip guard If node");
1438 Node* zer_bol = node->in(0)->in(1);
1439 assert(zer_bol != nullptr && zer_bol->is_Bool(), "must be Bool");
1440 Node* zer_cmp = zer_bol->in(1);
1441 assert(zer_cmp != nullptr && zer_cmp->Opcode() == Op_CmpI, "must be CmpI");
1442 // For the main loop, the opaque node is the second input to zer_cmp, for the post loop it's the first input node
1443 Node* zer_opaq = zer_cmp->in(is_main_loop ? 2 : 1);
1444 assert(zer_opaq != nullptr && zer_opaq->Opcode() == Op_OpaqueZeroTripGuard, "must be OpaqueZeroTripGuard");
1445 }
1446 #endif
1447
1448 //------------------------------insert_pre_post_loops--------------------------
1449 // Insert pre and post loops. If peel_only is set, the pre-loop can not have
1450 // more iterations added. It acts as a 'peel' only, no lower-bound RCE, no
1451 // alignment. Useful to unroll loops that do no array accesses.
1452 void PhaseIdealLoop::insert_pre_post_loops(IdealLoopTree *loop, Node_List &old_new, bool peel_only) {
1453
1454 #ifndef PRODUCT
1455 if (TraceLoopOpts) {
1456 if (peel_only)
1457 tty->print("PeelMainPost ");
1458 else
1459 tty->print("PreMainPost ");
1460 loop->dump_head();
1461 }
1462 #endif
1463 C->set_major_progress();
1464
1465 // Find common pieces of the loop being guarded with pre & post loops
1466 CountedLoopNode *main_head = loop->_head->as_CountedLoop();
1467 assert(main_head->is_normal_loop(), "");
1468 CountedLoopEndNode *main_end = main_head->loopexit();
1469 assert(main_end->outcnt() == 2, "1 true, 1 false path only");
1470
1471 C->print_method(PHASE_BEFORE_PRE_MAIN_POST, 4, main_head);
1472
1473 Node *init = main_head->init_trip();
1474 Node *incr = main_end ->incr();
1475 Node *limit = main_end ->limit();
1476 Node *stride = main_end ->stride();
1477 Node *cmp = main_end ->cmp_node();
1478 BoolTest::mask b_test = main_end->test_trip();
1479
1480 // Need only 1 user of 'bol' because I will be hacking the loop bounds.
1481 Node *bol = main_end->in(CountedLoopEndNode::TestValue);
1482 if (bol->outcnt() != 1) {
1483 bol = bol->clone();
1484 register_new_node(bol,main_end->in(CountedLoopEndNode::TestControl));
1485 _igvn.replace_input_of(main_end, CountedLoopEndNode::TestValue, bol);
1486 }
1487 // Need only 1 user of 'cmp' because I will be hacking the loop bounds.
1488 if (cmp->outcnt() != 1) {
1489 cmp = cmp->clone();
1490 register_new_node(cmp,main_end->in(CountedLoopEndNode::TestControl));
1491 _igvn.replace_input_of(bol, 1, cmp);
1492 }
1493
1494 // Add the post loop
1495 CountedLoopNode *post_head = nullptr;
1496 Node* post_incr = incr;
1497 Node* main_exit = insert_post_loop(loop, old_new, main_head, main_end, post_incr, limit, post_head);
1498 C->print_method(PHASE_AFTER_POST_LOOP, 4, post_head);
1499
1500 //------------------------------
1501 // Step B: Create Pre-Loop.
1502
1503 // Step B1: Clone the loop body. The clone becomes the pre-loop. The main
1504 // loop pre-header illegally has 2 control users (old & new loops).
1505 LoopNode* outer_main_head = main_head;
1506 IdealLoopTree* outer_loop = loop;
1507 if (main_head->is_strip_mined()) {
1508 main_head->verify_strip_mined(1);
1509 outer_main_head = main_head->outer_loop();
1510 outer_loop = loop->_parent;
1511 assert(outer_loop->_head == outer_main_head, "broken loop tree");
1512 }
1513
1514 const uint first_node_index_in_pre_loop_body = Compile::current()->unique();
1515 uint dd_main_head = dom_depth(outer_main_head);
1516 clone_loop(loop, old_new, dd_main_head, ControlAroundStripMined);
1517 CountedLoopNode* pre_head = old_new[main_head->_idx]->as_CountedLoop();
1518 CountedLoopEndNode* pre_end = old_new[main_end ->_idx]->as_CountedLoopEnd();
1519 pre_head->set_pre_loop(main_head);
1520 Node *pre_incr = old_new[incr->_idx];
1521
1522 // Reduce the pre-loop trip count.
1523 pre_end->_prob = PROB_FAIR;
1524
1525 // Find the pre-loop normal exit.
1526 IfFalseNode* pre_exit = pre_end->false_proj();
1527 IfFalseNode* new_pre_exit = new IfFalseNode(pre_end);
1528 _igvn.register_new_node_with_optimizer(new_pre_exit);
1529 set_idom(new_pre_exit, pre_end, dd_main_head);
1530 set_loop(new_pre_exit, outer_loop->_parent);
1531
1532 // Step B2: Build a zero-trip guard for the main-loop. After leaving the
1533 // pre-loop, the main-loop may not execute at all. Later in life this
1534 // zero-trip guard will become the minimum-trip guard when we unroll
1535 // the main-loop.
1536 Node *min_opaq = new OpaqueZeroTripGuardNode(C, limit, b_test);
1537 Node *min_cmp = new CmpINode(pre_incr, min_opaq);
1538 Node *min_bol = new BoolNode(min_cmp, b_test);
1539 register_new_node(min_opaq, new_pre_exit);
1540 register_new_node(min_cmp , new_pre_exit);
1541 register_new_node(min_bol , new_pre_exit);
1542
1543 // Build the IfNode (assume the main-loop is executed always).
1544 IfNode *min_iff = new IfNode(new_pre_exit, min_bol, PROB_ALWAYS, COUNT_UNKNOWN);
1545 _igvn.register_new_node_with_optimizer(min_iff);
1546 set_idom(min_iff, new_pre_exit, dd_main_head);
1547 set_loop(min_iff, outer_loop->_parent);
1548
1549 // Plug in the false-path, taken if we need to skip main-loop
1550 _igvn.hash_delete(pre_exit);
1551 pre_exit->set_req(0, min_iff);
1552 set_idom(pre_exit, min_iff, dd_main_head);
1553 set_idom(pre_exit->unique_ctrl_out(), min_iff, dd_main_head);
1554 // Make the true-path, must enter the main loop
1555 Node *min_taken = new IfTrueNode(min_iff);
1556 _igvn.register_new_node_with_optimizer(min_taken);
1557 set_idom(min_taken, min_iff, dd_main_head);
1558 set_loop(min_taken, outer_loop->_parent);
1559 // Plug in the true path
1560 _igvn.hash_delete(outer_main_head);
1561 outer_main_head->set_req(LoopNode::EntryControl, min_taken);
1562 set_idom(outer_main_head, min_taken, dd_main_head);
1563 assert(post_head->in(1)->is_IfProj(), "must be zero-trip guard If node projection of the post loop");
1564
1565 VectorSet visited;
1566 Node_Stack clones(main_head->back_control()->outcnt());
1567 // Step B3: Make the fall-in values to the main-loop come from the
1568 // fall-out values of the pre-loop.
1569 const uint last_node_index_in_pre_loop_body = Compile::current()->unique() - 1;
1570 for (DUIterator i2 = main_head->outs(); main_head->has_out(i2); i2++) {
1571 Node* main_phi = main_head->out(i2);
1572 if (main_phi->is_Phi() && main_phi->in(0) == main_head && main_phi->outcnt() > 0) {
1573 Node* pre_phi = old_new[main_phi->_idx];
1574 Node* fallpre = clone_up_backedge_goo(pre_head->back_control(),
1575 main_head->skip_strip_mined()->in(LoopNode::EntryControl),
1576 pre_phi->in(LoopNode::LoopBackControl),
1577 visited, clones);
1578 _igvn.hash_delete(main_phi);
1579 main_phi->set_req(LoopNode::EntryControl, fallpre);
1580 }
1581 }
1582 DEBUG_ONLY(const uint last_node_index_from_backedge_goo = Compile::current()->unique() - 1);
1583
1584 DEBUG_ONLY(ensure_zero_trip_guard_proj(outer_main_head->in(LoopNode::EntryControl), true);)
1585 initialize_assertion_predicates_for_main_loop(pre_head, main_head, first_node_index_in_pre_loop_body,
1586 last_node_index_in_pre_loop_body,
1587 DEBUG_ONLY(last_node_index_from_backedge_goo COMMA) old_new);
1588 // CastII for the main loop:
1589 cast_incr_before_loop(pre_incr, min_taken, main_head);
1590
1591 // Step B4: Shorten the pre-loop to run only 1 iteration (for now).
1592 // RCE and alignment may change this later.
1593 Node *cmp_end = pre_end->cmp_node();
1594 assert(cmp_end->in(2) == limit, "");
1595 Node *pre_limit = new AddINode(init, stride);
1596
1597 // Save the original loop limit in this Opaque1 node for
1598 // use by range check elimination.
1599 Node *pre_opaq = new Opaque1Node(C, pre_limit, limit);
1600
1601 register_new_node(pre_limit, pre_head->in(LoopNode::EntryControl));
1602 register_new_node(pre_opaq , pre_head->in(LoopNode::EntryControl));
1603
1604 // Since no other users of pre-loop compare, I can hack limit directly
1605 assert(cmp_end->outcnt() == 1, "no other users");
1606 _igvn.hash_delete(cmp_end);
1607 cmp_end->set_req(2, peel_only ? pre_limit : pre_opaq);
1608
1609 // Special case for not-equal loop bounds:
1610 // Change pre loop test, main loop test, and the
1611 // main loop guard test to use lt or gt depending on stride
1612 // direction:
1613 // positive stride use <
1614 // negative stride use >
1615 //
1616 // not-equal test is kept for post loop to handle case
1617 // when init > limit when stride > 0 (and reverse).
1618
1619 if (pre_end->in(CountedLoopEndNode::TestValue)->as_Bool()->_test._test == BoolTest::ne) {
1620
1621 BoolTest::mask new_test = (main_end->stride_con() > 0) ? BoolTest::lt : BoolTest::gt;
1622 // Modify pre loop end condition
1623 Node* pre_bol = pre_end->in(CountedLoopEndNode::TestValue)->as_Bool();
1624 BoolNode* new_bol0 = new BoolNode(pre_bol->in(1), new_test);
1625 register_new_node(new_bol0, pre_head->in(0));
1626 _igvn.replace_input_of(pre_end, CountedLoopEndNode::TestValue, new_bol0);
1627 // Modify main loop guard condition
1628 assert(min_iff->in(CountedLoopEndNode::TestValue) == min_bol, "guard okay");
1629 BoolNode* new_bol1 = new BoolNode(min_bol->in(1), new_test);
1630 register_new_node(new_bol1, new_pre_exit);
1631 _igvn.hash_delete(min_iff);
1632 min_iff->set_req(CountedLoopEndNode::TestValue, new_bol1);
1633 // Modify main loop end condition
1634 BoolNode* main_bol = main_end->in(CountedLoopEndNode::TestValue)->as_Bool();
1635 BoolNode* new_bol2 = new BoolNode(main_bol->in(1), new_test);
1636 register_new_node(new_bol2, main_end->in(CountedLoopEndNode::TestControl));
1637 _igvn.replace_input_of(main_end, CountedLoopEndNode::TestValue, new_bol2);
1638 }
1639
1640 // Flag main loop
1641 main_head->set_main_loop();
1642 if (peel_only) {
1643 main_head->set_main_no_pre_loop();
1644 }
1645
1646 // Subtract a trip count for the pre-loop.
1647 main_head->set_trip_count(main_head->trip_count() - 1);
1648
1649 // It's difficult to be precise about the trip-counts
1650 // for the pre/post loops. They are usually very short,
1651 // so guess that 4 trips is a reasonable value.
1652 post_head->set_profile_trip_cnt(4.0);
1653 pre_head->set_profile_trip_cnt(4.0);
1654
1655 // Now force out all loop-invariant dominating tests. The optimizer
1656 // finds some, but we _know_ they are all useless.
1657 peeled_dom_test_elim(loop,old_new);
1658 loop->record_for_igvn();
1659
1660 C->print_method(PHASE_AFTER_PRE_MAIN_POST, 4, main_head);
1661 }
1662
1663 //------------------------------insert_vector_post_loop------------------------
1664 // Insert a copy of the atomic unrolled vectorized main loop as a post loop,
1665 // unroll_policy has already informed us that more unrolling is about to
1666 // happen to the main loop. The resultant post loop will serve as a
1667 // vectorized drain loop.
1668 void PhaseIdealLoop::insert_vector_post_loop(IdealLoopTree *loop, Node_List &old_new) {
1669 if (!loop->_head->is_CountedLoop()) return;
1670
1671 CountedLoopNode *cl = loop->_head->as_CountedLoop();
1672
1673 // only process vectorized main loops
1674 if (!cl->is_vectorized_loop() || !cl->is_main_loop()) return;
1675
1676 int slp_max_unroll_factor = cl->slp_max_unroll();
1677 int cur_unroll = cl->unrolled_count();
1678
1679 if (slp_max_unroll_factor == 0) return;
1680
1681 // only process atomic unroll vector loops (not super unrolled after vectorization)
1682 if (cur_unroll != slp_max_unroll_factor) return;
1683
1684 // we only ever process this one time
1685 if (cl->has_atomic_post_loop()) return;
1686
1687 if (!may_require_nodes(loop->est_loop_clone_sz(2))) {
1688 return;
1689 }
1690
1691 #ifndef PRODUCT
1692 if (TraceLoopOpts) {
1693 tty->print("PostVector ");
1694 loop->dump_head();
1695 }
1696 #endif
1697 C->set_major_progress();
1698
1699 // Find common pieces of the loop being guarded with pre & post loops
1700 CountedLoopNode *main_head = loop->_head->as_CountedLoop();
1701 CountedLoopEndNode *main_end = main_head->loopexit();
1702 // diagnostic to show loop end is not properly formed
1703 assert(main_end->outcnt() == 2, "1 true, 1 false path only");
1704
1705 // mark this loop as processed
1706 main_head->mark_has_atomic_post_loop();
1707
1708 Node *incr = main_end->incr();
1709 Node *limit = main_end->limit();
1710
1711 // In this case we throw away the result as we are not using it to connect anything else.
1712 C->print_method(PHASE_BEFORE_POST_LOOP, 4, main_head);
1713 CountedLoopNode *post_head = nullptr;
1714 insert_post_loop(loop, old_new, main_head, main_end, incr, limit, post_head);
1715 C->print_method(PHASE_AFTER_POST_LOOP, 4, post_head);
1716
1717 // It's difficult to be precise about the trip-counts
1718 // for post loops. They are usually very short,
1719 // so guess that unit vector trips is a reasonable value.
1720 post_head->set_profile_trip_cnt(cur_unroll);
1721
1722 // Now force out all loop-invariant dominating tests. The optimizer
1723 // finds some, but we _know_ they are all useless.
1724 peeled_dom_test_elim(loop, old_new);
1725 loop->record_for_igvn();
1726 }
1727
1728 Node* PhaseIdealLoop::find_last_store_in_outer_loop(Node* store, const IdealLoopTree* outer_loop) {
1729 assert(store != nullptr && store->is_Store(), "starting point should be a store node");
1730 // Follow the memory uses until we get out of the loop.
1731 // Store nodes in the outer loop body were moved by PhaseIdealLoop::try_move_store_after_loop.
1732 // Because of the conditions in try_move_store_after_loop (no other usage in the loop body
1733 // except for the phi node associated with the loop head), we have the guarantee of a
1734 // linear memory subgraph within the outer loop body.
1735 Node* last = store;
1736 Node* unique_next = store;
1737 do {
1738 last = unique_next;
1739 for (DUIterator_Fast imax, l = last->fast_outs(imax); l < imax; l++) {
1740 Node* use = last->fast_out(l);
1741 if (use->is_Store() && use->in(MemNode::Memory) == last) {
1742 if (ctrl_is_member(outer_loop, use)) {
1743 assert(unique_next == last, "memory node should only have one usage in the loop body");
1744 unique_next = use;
1745 }
1746 }
1747 }
1748 } while (last != unique_next);
1749 return last;
1750 }
1751
1752 //------------------------------insert_post_loop-------------------------------
1753 // Insert post loops. Add a post loop to the given loop passed.
1754 Node *PhaseIdealLoop::insert_post_loop(IdealLoopTree* loop, Node_List& old_new,
1755 CountedLoopNode* main_head, CountedLoopEndNode* main_end,
1756 Node* incr, Node* limit, CountedLoopNode*& post_head) {
1757 IfNode* outer_main_end = main_end;
1758 IdealLoopTree* outer_loop = loop;
1759 if (main_head->is_strip_mined()) {
1760 main_head->verify_strip_mined(1);
1761 outer_main_end = main_head->outer_loop_end();
1762 outer_loop = loop->_parent;
1763 assert(outer_loop->_head == main_head->in(LoopNode::EntryControl), "broken loop tree");
1764 }
1765
1766 //------------------------------
1767 // Step A: Create a new post-Loop.
1768 IfFalseNode* main_exit = outer_main_end->false_proj();
1769 int dd_main_exit = dom_depth(main_exit);
1770
1771 // Step A1: Clone the loop body of main. The clone becomes the post-loop.
1772 // The main loop pre-header illegally has 2 control users (old & new loops).
1773 const uint first_node_index_in_cloned_loop_body = C->unique();
1774 clone_loop(loop, old_new, dd_main_exit, ControlAroundStripMined);
1775 assert(old_new[main_end->_idx]->Opcode() == Op_CountedLoopEnd, "");
1776 post_head = old_new[main_head->_idx]->as_CountedLoop();
1777 post_head->set_normal_loop();
1778 post_head->set_post_loop(main_head);
1779
1780 // clone_loop() above changes the exit projection
1781 main_exit = outer_main_end->false_proj();
1782
1783 // Reduce the post-loop trip count.
1784 CountedLoopEndNode* post_end = old_new[main_end->_idx]->as_CountedLoopEnd();
1785 post_end->_prob = PROB_FAIR;
1786
1787 // Build the main-loop normal exit.
1788 IfFalseNode *new_main_exit = new IfFalseNode(outer_main_end);
1789 _igvn.register_new_node_with_optimizer(new_main_exit);
1790 set_idom(new_main_exit, outer_main_end, dd_main_exit);
1791 set_loop(new_main_exit, outer_loop->_parent);
1792
1793 // Step A2: Build a zero-trip guard for the post-loop. After leaving the
1794 // main-loop, the post-loop may not execute at all. We 'opaque' the incr
1795 // (the previous loop trip-counter exit value) because we will be changing
1796 // the exit value (via additional unrolling) so we cannot constant-fold away the zero
1797 // trip guard until all unrolling is done.
1798 Node *zer_opaq = new OpaqueZeroTripGuardNode(C, incr, main_end->test_trip());
1799 Node *zer_cmp = new CmpINode(zer_opaq, limit);
1800 Node *zer_bol = new BoolNode(zer_cmp, main_end->test_trip());
1801 register_new_node(zer_opaq, new_main_exit);
1802 register_new_node(zer_cmp, new_main_exit);
1803 register_new_node(zer_bol, new_main_exit);
1804
1805 // Build the IfNode
1806 IfNode *zer_iff = new IfNode(new_main_exit, zer_bol, PROB_FAIR, COUNT_UNKNOWN);
1807 _igvn.register_new_node_with_optimizer(zer_iff);
1808 set_idom(zer_iff, new_main_exit, dd_main_exit);
1809 set_loop(zer_iff, outer_loop->_parent);
1810
1811 // Plug in the false-path, taken if we need to skip this post-loop
1812 _igvn.replace_input_of(main_exit, 0, zer_iff);
1813 set_idom(main_exit, zer_iff, dd_main_exit);
1814 set_idom(main_exit->unique_out(), zer_iff, dd_main_exit);
1815 // Make the true-path, must enter this post loop
1816 Node *zer_taken = new IfTrueNode(zer_iff);
1817 _igvn.register_new_node_with_optimizer(zer_taken);
1818 set_idom(zer_taken, zer_iff, dd_main_exit);
1819 set_loop(zer_taken, outer_loop->_parent);
1820 // Plug in the true path
1821 _igvn.hash_delete(post_head);
1822 post_head->set_req(LoopNode::EntryControl, zer_taken);
1823 set_idom(post_head, zer_taken, dd_main_exit);
1824
1825 VectorSet visited;
1826 Node_Stack clones(main_head->back_control()->outcnt());
1827 // Step A3: Make the fall-in values to the post-loop come from the
1828 // fall-out values of the main-loop.
1829 for (DUIterator i = main_head->outs(); main_head->has_out(i); i++) {
1830 Node* main_phi = main_head->out(i);
1831 if (main_phi->is_Phi() && main_phi->in(0) == main_head && main_phi->outcnt() > 0) {
1832 Node* post_phi = old_new[main_phi->_idx];
1833 Node* loopback_input = main_phi->in(LoopNode::LoopBackControl);
1834 Node* fallnew = clone_up_backedge_goo(main_head->back_control(),
1835 post_head->init_control(),
1836 loopback_input,
1837 visited, clones);
1838 // Technically, the entry value of post_phi must be the loop back input of the corresponding
1839 // Phi of the outer loop, not the Phi of the inner loop (i.e. main_phi). However, we have not
1840 // constructed the Phis for the OuterStripMinedLoop yet, so the input must be inferred from
1841 // the loop back input of main_phi.
1842 // - If post_phi is a data Phi, then we can use the loop back input of main_phi.
1843 // - If post_phi is a memory Phi, since Stores can be sunk below the inner loop, but still
1844 // inside the outer loop, we have 2 cases:
1845 // + If the loop back input of main_phi is on the backedge, then the entry input of
1846 // post_phi is the clone of the node on the entry of post_head, similar to when post_phi
1847 // is a data Phi.
1848 // + If the loop back input of main_phi is not on the backedge, we need to find whether
1849 // there is a sunk Store corresponding to post_phi, if there is any, the latest such
1850 // store will be the entry input of post_phi. Fortunately, the safepoint at the exit of
1851 // the outer loop captures all memory states, so we can use it as the entry input of
1852 // post_phi.
1853 // Another way to see it is that, the memory phi should capture the latest state at the
1854 // post-loop entry. If loopback_input is cloned by clone_up_backedge_goo, it is pinned at
1855 // the post-loop entry, and is surely the latest state. Otherwise, the latest memory state
1856 // corresponding to post_phi is the memory state at the exit of the outer main-loop, which
1857 // is captured by the safepoint there.
1858 if (main_head->is_strip_mined() && fallnew == loopback_input && post_phi->is_memory_phi()) {
1859 SafePointNode* main_safepoint = main_head->outer_safepoint();
1860 assert(main_safepoint != nullptr, "outer loop must have a safepoint");
1861 fallnew = main_safepoint->memory();
1862 }
1863 _igvn.hash_delete(post_phi);
1864 post_phi->set_req(LoopNode::EntryControl, fallnew);
1865 }
1866 }
1867 // Store nodes that were moved to the outer loop by PhaseIdealLoop::try_move_store_after_loop
1868 // do not have an associated Phi node. Such nodes are attached to the false projection of the CountedLoopEnd node,
1869 // right after the execution of the inner CountedLoop.
1870 // We have to make sure that such stores in the post loop have the right memory inputs from the main loop
1871 // The moved store node is always attached right after the inner loop exit, and just before the safepoint
1872 const IfFalseNode* if_false = main_end->false_proj();
1873 for (DUIterator j = if_false->outs(); if_false->has_out(j); j++) {
1874 Node* store = if_false->out(j);
1875 if (store->is_Store()) {
1876 // We only make changes if the memory input of the store is outside the outer loop body,
1877 // as this is when we would normally expect a Phi as input. If the memory input
1878 // is in the loop body as well, then we can safely assume it is still correct as the entire
1879 // body was cloned as a unit
1880 if (!ctrl_is_member(outer_loop, store->in(MemNode::Memory))) {
1881 Node* mem_out = find_last_store_in_outer_loop(store, outer_loop);
1882 Node* store_new = old_new[store->_idx];
1883 store_new->set_req(MemNode::Memory, mem_out);
1884 }
1885 }
1886 }
1887
1888 DEBUG_ONLY(ensure_zero_trip_guard_proj(post_head->in(LoopNode::EntryControl), false);)
1889 initialize_assertion_predicates_for_post_loop(main_head, post_head, first_node_index_in_cloned_loop_body);
1890 cast_incr_before_loop(zer_opaq->in(1), zer_taken, post_head);
1891 return new_main_exit;
1892 }
1893
1894 //------------------------------is_invariant-----------------------------
1895 // Return true if n is invariant
1896 bool IdealLoopTree::is_invariant(Node* n) const {
1897 Node *n_c = _phase->has_ctrl(n) ? _phase->get_ctrl(n) : n;
1898 if (n_c->is_top()) return false;
1899 return !is_member(_phase->get_loop(n_c));
1900 }
1901
1902 // Search the Assertion Predicates added by loop predication and/or range check elimination and update them according
1903 // to the new stride.
1904 void PhaseIdealLoop::update_main_loop_assertion_predicates(CountedLoopNode* new_main_loop_head,
1905 const int stride_con_before_unroll) {
1906 // Compute the value of the loop induction variable at the end of the
1907 // first iteration of the unrolled loop: init + new_stride_con - init_inc
1908 int unrolled_stride_con = stride_con_before_unroll * 2;
1909 Node* unrolled_stride = intcon(unrolled_stride_con);
1910
1911 Node* loop_entry = new_main_loop_head->skip_strip_mined()->in(LoopNode::EntryControl);
1912 PredicateIterator predicate_iterator(loop_entry);
1913 UpdateStrideForAssertionPredicates update_stride_for_assertion_predicates(unrolled_stride, new_main_loop_head, this);
1914 predicate_iterator.for_each(update_stride_for_assertion_predicates);
1915 }
1916
1917 // Source Loop: Cloned - peeled_loop_head
1918 // Target Loop: Original - remaining_loop_head
1919 void PhaseIdealLoop::initialize_assertion_predicates_for_peeled_loop(CountedLoopNode* peeled_loop_head,
1920 CountedLoopNode* remaining_loop_head,
1921 const uint first_node_index_in_cloned_loop_body,
1922 const Node_List& old_new) {
1923 const NodeInOriginalLoopBody node_in_original_loop_body(first_node_index_in_cloned_loop_body, old_new);
1924 create_assertion_predicates_at_loop(peeled_loop_head, remaining_loop_head, node_in_original_loop_body, true);
1925 }
1926
1927 // Source Loop: Cloned - pre_loop_head
1928 // Target Loop: Original - main_loop_head
1929 void PhaseIdealLoop::initialize_assertion_predicates_for_main_loop(CountedLoopNode* pre_loop_head,
1930 CountedLoopNode* main_loop_head,
1931 const uint first_node_index_in_pre_loop_body,
1932 const uint last_node_index_in_pre_loop_body,
1933 DEBUG_ONLY(const uint last_node_index_from_backedge_goo COMMA)
1934 const Node_List& old_new) {
1935 assert(first_node_index_in_pre_loop_body < last_node_index_in_pre_loop_body, "cloned some nodes");
1936 const NodeInMainLoopBody node_in_main_loop_body(first_node_index_in_pre_loop_body,
1937 last_node_index_in_pre_loop_body,
1938 DEBUG_ONLY(last_node_index_from_backedge_goo COMMA) old_new);
1939 create_assertion_predicates_at_main_or_post_loop(pre_loop_head, main_loop_head, node_in_main_loop_body, true);
1940 }
1941
1942 // Source Loop: Original - main_loop_head
1943 // Target Loop: Cloned - post_loop_head
1944 //
1945 // The post loop is cloned before the pre loop. Do not kill the old Template Assertion Predicates, yet. We need to clone
1946 // from them when creating the pre loop. Only then we can kill them.
1947 void PhaseIdealLoop::initialize_assertion_predicates_for_post_loop(CountedLoopNode* main_loop_head,
1948 CountedLoopNode* post_loop_head,
1949 const uint first_node_index_in_cloned_loop_body) {
1950 const NodeInClonedLoopBody node_in_cloned_loop_body(first_node_index_in_cloned_loop_body);
1951 create_assertion_predicates_at_main_or_post_loop(main_loop_head, post_loop_head, node_in_cloned_loop_body, false);
1952 }
1953
1954 void PhaseIdealLoop::create_assertion_predicates_at_loop(CountedLoopNode* source_loop_head,
1955 CountedLoopNode* target_loop_head,
1956 const NodeInLoopBody& _node_in_loop_body,
1957 const bool kill_old_template) {
1958 CreateAssertionPredicatesVisitor create_assertion_predicates_visitor(target_loop_head, this, _node_in_loop_body,
1959 kill_old_template);
1960 Node* source_loop_entry = source_loop_head->skip_strip_mined()->in(LoopNode::EntryControl);
1961 PredicateIterator predicate_iterator(source_loop_entry);
1962 predicate_iterator.for_each(create_assertion_predicates_visitor);
1963 }
1964
1965 void PhaseIdealLoop::create_assertion_predicates_at_main_or_post_loop(CountedLoopNode* source_loop_head,
1966 CountedLoopNode* target_loop_head,
1967 const NodeInLoopBody& _node_in_loop_body,
1968 const bool kill_old_template) {
1969 Node* old_target_loop_head_entry = target_loop_head->skip_strip_mined()->in(LoopNode::EntryControl);
1970 const uint node_index_before_new_assertion_predicate_nodes = C->unique();
1971 const bool need_to_rewire_old_target_loop_entry_dependencies = old_target_loop_head_entry->outcnt() > 1;
1972 create_assertion_predicates_at_loop(source_loop_head, target_loop_head, _node_in_loop_body, kill_old_template);
1973 if (need_to_rewire_old_target_loop_entry_dependencies) {
1974 rewire_old_target_loop_entry_dependency_to_new_entry(target_loop_head, old_target_loop_head_entry,
1975 node_index_before_new_assertion_predicate_nodes);
1976 }
1977 }
1978
1979 // Rewire any control dependent nodes on the old target loop entry before adding Assertion Predicate related nodes.
1980 // These have been added by PhaseIdealLoop::clone_up_backedge_goo() and assume to be ending up at the target loop entry
1981 // which is no longer the case when adding additional Assertion Predicates. Fix this by rewiring these nodes to the new
1982 // target loop entry which corresponds to the tail of the last Assertion Predicate before the target loop. This is safe
1983 // to do because these control dependent nodes on the old target loop entry created by clone_up_backedge_goo() were
1984 // pinned on the loop backedge before. The Assertion Predicates are not control dependent on these nodes in any way.
1985 void PhaseIdealLoop::rewire_old_target_loop_entry_dependency_to_new_entry(
1986 CountedLoopNode* target_loop_head, const Node* old_target_loop_entry,
1987 const uint node_index_before_new_assertion_predicate_nodes) {
1988 Node* new_main_loop_entry = target_loop_head->skip_strip_mined()->in(LoopNode::EntryControl);
1989 if (new_main_loop_entry == old_target_loop_entry) {
1990 // No Assertion Predicates added.
1991 return;
1992 }
1993
1994 for (DUIterator_Fast imax, i = old_target_loop_entry->fast_outs(imax); i < imax; i++) {
1995 Node* out = old_target_loop_entry->fast_out(i);
1996 if (!out->is_CFG() && out->_idx < node_index_before_new_assertion_predicate_nodes) {
1997 assert(out != target_loop_head->init_trip(), "CastII on loop entry?");
1998 _igvn.replace_input_of(out, 0, new_main_loop_entry);
1999 set_ctrl(out, new_main_loop_entry);
2000 --i;
2001 --imax;
2002 }
2003 }
2004 }
2005
2006 //------------------------------do_unroll--------------------------------------
2007 // Unroll the loop body one step - make each trip do 2 iterations.
2008 void PhaseIdealLoop::do_unroll(IdealLoopTree *loop, Node_List &old_new, bool adjust_min_trip) {
2009 assert(LoopUnrollLimit, "");
2010 CountedLoopNode *loop_head = loop->_head->as_CountedLoop();
2011 CountedLoopEndNode *loop_end = loop_head->loopexit();
2012
2013 C->print_method(PHASE_BEFORE_LOOP_UNROLLING, 4, loop_head);
2014
2015 #ifndef PRODUCT
2016 if (TraceLoopOpts) {
2017 if (loop_head->trip_count() < (uint)LoopUnrollLimit) {
2018 tty->print("Unroll %d(" JULONG_FORMAT_W(2) ") ", loop_head->unrolled_count()*2, loop_head->trip_count());
2019 } else {
2020 tty->print("Unroll %d ", loop_head->unrolled_count()*2);
2021 }
2022 loop->dump_head();
2023 }
2024
2025 if (C->do_vector_loop() && (PrintOpto && (VerifyLoopOptimizations || TraceLoopOpts))) {
2026 Node_Stack stack(C->live_nodes() >> 2);
2027 Node_List rpo_list;
2028 VectorSet visited;
2029 visited.set(loop_head->_idx);
2030 rpo(loop_head, stack, visited, rpo_list);
2031 dump(loop, rpo_list.size(), rpo_list);
2032 }
2033 #endif
2034
2035 // Remember loop node count before unrolling to detect
2036 // if rounds of unroll,optimize are making progress
2037 loop_head->set_node_count_before_unroll(loop->_body.size());
2038
2039 Node *ctrl = loop_head->skip_strip_mined()->in(LoopNode::EntryControl);
2040 Node *limit = loop_head->limit();
2041 Node *init = loop_head->init_trip();
2042 Node *stride = loop_head->stride();
2043
2044 Node *opaq = nullptr;
2045 if (adjust_min_trip) { // If not maximally unrolling, need adjustment
2046 // Search for zero-trip guard.
2047
2048 // Check the shape of the graph at the loop entry. If an inappropriate
2049 // graph shape is encountered, the compiler bails out loop unrolling;
2050 // compilation of the method will still succeed.
2051 opaq = loop_head->is_canonical_loop_entry();
2052 if (opaq == nullptr) {
2053 return;
2054 }
2055 // Zero-trip test uses an 'opaque' node which is not shared, otherwise bail out.
2056 if (opaq->outcnt() != 1 || opaq->in(1) != limit) {
2057 #ifdef ASSERT
2058 // In rare cases, loop cloning (as for peeling, for instance) can break this by replacing
2059 // limit and the input of opaq by equivalent but distinct phis.
2060 // Next IGVN should clean it up. Let's try to detect we are in such a case.
2061 Unique_Node_List& worklist = loop->_phase->_igvn._worklist;
2062 assert(C->major_progress(), "The operation that replaced limit and opaq->in(1) (e.g. peeling) should have set major_progress");
2063 assert(opaq->in(1)->is_Phi() && limit->is_Phi(), "Nodes limit and opaq->in(1) should have been replaced by PhiNodes by fix_data_uses from clone_loop.");
2064 assert(worklist.member(opaq->in(1)) && worklist.member(limit), "Nodes limit and opaq->in(1) differ and should have been recorded for IGVN.");
2065 #endif
2066 return;
2067 }
2068 }
2069
2070 C->set_major_progress();
2071
2072 Node* new_limit = nullptr;
2073 const int stride_con = stride->get_int();
2074 int stride_p = (stride_con > 0) ? stride_con : -stride_con;
2075 uint old_trip_count = loop_head->trip_count();
2076 // Verify that unroll policy result is still valid.
2077 assert(old_trip_count > 1 && (!adjust_min_trip || stride_p <=
2078 MIN2<int>(max_jint / 2 - 2, MAX2(1<<3, Matcher::max_vector_size(T_BYTE)) * loop_head->unrolled_count())), "sanity");
2079
2080 // Adjust loop limit to keep valid iterations number after unroll.
2081 // Use (limit - stride) instead of (((limit - init)/stride) & (-2))*stride
2082 // which may overflow.
2083 if (!adjust_min_trip) {
2084 assert(old_trip_count > 1 && (old_trip_count & 1) == 0,
2085 "odd trip count for maximally unroll");
2086 // Don't need to adjust limit for maximally unroll since trip count is even.
2087 } else if (loop_head->has_exact_trip_count() && init->is_Con()) {
2088 // The trip count being exact means it has been set (using CountedLoopNode::set_exact_trip_count in compute_trip_count)
2089 assert(old_trip_count < max_juint, "sanity");
2090 // Loop's limit is constant. Loop's init could be constant when pre-loop
2091 // become peeled iteration.
2092 jlong init_con = init->get_int();
2093 // We can keep old loop limit if iterations count stays the same:
2094 // old_trip_count == new_trip_count * 2
2095 // Note: since old_trip_count >= 2 then new_trip_count >= 1
2096 // so we also don't need to adjust zero trip test.
2097 jlong limit_con = limit->get_int();
2098 // (stride_con*2) not overflow since stride_con <= 8.
2099 int new_stride_con = stride_con * 2;
2100 int stride_m = new_stride_con - (stride_con > 0 ? 1 : -1);
2101 jlong trip_count = (limit_con - init_con + stride_m)/new_stride_con;
2102 // New trip count should satisfy next conditions.
2103 assert(trip_count > 0 && (julong)trip_count <= (julong)max_juint/2, "sanity");
2104 uint new_trip_count = (uint)trip_count;
2105 // Since old_trip_count has been set to < max_juint (that is at most 2^32-2),
2106 // new_trip_count is lower than or equal to 2^31-1 and the multiplication cannot overflow.
2107 adjust_min_trip = (old_trip_count != new_trip_count*2);
2108 }
2109
2110 if (adjust_min_trip) {
2111 // Step 2: Adjust the trip limit if it is called for.
2112 // The adjustment amount is -stride. Need to make sure if the
2113 // adjustment underflows or overflows, then the main loop is skipped.
2114 Node* cmp = loop_end->cmp_node();
2115 assert(cmp->in(2) == limit, "sanity");
2116 assert(opaq != nullptr && opaq->in(1) == limit, "sanity");
2117
2118 // Verify that policy_unroll result is still valid.
2119 const TypeInt* limit_type = _igvn.type(limit)->is_int();
2120 assert((stride_con > 0 && ((min_jint + stride_con) <= limit_type->_hi)) ||
2121 (stride_con < 0 && ((max_jint + stride_con) >= limit_type->_lo)),
2122 "sanity");
2123
2124 if (limit->is_Con()) {
2125 // The check in policy_unroll and the assert above guarantee
2126 // no underflow if limit is constant.
2127 new_limit = intcon(limit->get_int() - stride_con);
2128 } else {
2129 // Limit is not constant. Int subtraction could lead to underflow.
2130 // (1) Convert to long.
2131 Node* limit_l = new ConvI2LNode(limit);
2132 register_new_node_with_ctrl_of(limit_l, limit);
2133 Node* stride_l = longcon(stride_con);
2134
2135 // (2) Subtract: compute in long, to prevent underflow.
2136 Node* new_limit_l = new SubLNode(limit_l, stride_l);
2137 register_new_node(new_limit_l, ctrl);
2138
2139 // (3) Clamp to int range, in case we had subtraction underflow.
2140 Node* underflow_clamp_l = longcon((stride_con > 0) ? min_jint : max_jint);
2141 Node* new_limit_no_underflow_l = nullptr;
2142 if (stride_con > 0) {
2143 // limit = MaxL(limit - stride, min_jint)
2144 new_limit_no_underflow_l = new MaxLNode(C, new_limit_l, underflow_clamp_l);
2145 } else {
2146 // limit = MinL(limit - stride, max_jint)
2147 new_limit_no_underflow_l = new MinLNode(C, new_limit_l, underflow_clamp_l);
2148 }
2149 register_new_node(new_limit_no_underflow_l, ctrl);
2150
2151 // (4) Convert back to int.
2152 new_limit = new ConvL2INode(new_limit_no_underflow_l);
2153 register_new_node(new_limit, ctrl);
2154 }
2155
2156 assert(new_limit != nullptr, "");
2157 // Replace in loop test.
2158 assert(loop_end->in(1)->in(1) == cmp, "sanity");
2159 if (cmp->outcnt() == 1 && loop_end->in(1)->outcnt() == 1) {
2160 // Don't need to create new test since only one user.
2161 _igvn.hash_delete(cmp);
2162 cmp->set_req(2, new_limit);
2163 } else {
2164 // Create new test since it is shared.
2165 Node* ctrl2 = loop_end->in(0);
2166 Node* cmp2 = cmp->clone();
2167 cmp2->set_req(2, new_limit);
2168 register_new_node(cmp2, ctrl2);
2169 Node* bol2 = loop_end->in(1)->clone();
2170 bol2->set_req(1, cmp2);
2171 register_new_node(bol2, ctrl2);
2172 _igvn.replace_input_of(loop_end, 1, bol2);
2173 }
2174 // Step 3: Find the min-trip test guaranteed before a 'main' loop.
2175 // Make it a 1-trip test (means at least 2 trips).
2176
2177 // Guard test uses an 'opaque' node which is not shared. Hence I
2178 // can edit it's inputs directly. Hammer in the new limit for the
2179 // minimum-trip guard.
2180 assert(opaq->outcnt() == 1, "");
2181 // Notify limit -> opaq -> CmpI, it may constant fold.
2182 _igvn.add_users_to_worklist(opaq->in(1));
2183 _igvn.replace_input_of(opaq, 1, new_limit);
2184 }
2185
2186 // Adjust max trip count. The trip count is intentionally rounded
2187 // down here (e.g. 15-> 7-> 3-> 1) because if we unwittingly over-unroll,
2188 // the main, unrolled, part of the loop will never execute as it is protected
2189 // by the min-trip test. See bug 4834191 for a case where we over-unrolled
2190 // and later determined that part of the unrolled loop was dead.
2191 loop_head->set_trip_count(old_trip_count / 2);
2192
2193 // Double the count of original iterations in the unrolled loop body.
2194 loop_head->double_unrolled_count();
2195
2196 // ---------
2197 // Step 4: Clone the loop body. Move it inside the loop. This loop body
2198 // represents the odd iterations; since the loop trips an even number of
2199 // times its backedge is never taken. Kill the backedge.
2200 uint dd = dom_depth(loop_head);
2201 clone_loop(loop, old_new, dd, IgnoreStripMined);
2202
2203 // Make backedges of the clone equal to backedges of the original.
2204 // Make the fall-in from the original come from the fall-out of the clone.
2205 for (DUIterator_Fast jmax, j = loop_head->fast_outs(jmax); j < jmax; j++) {
2206 Node* phi = loop_head->fast_out(j);
2207 if (phi->is_Phi() && phi->in(0) == loop_head && phi->outcnt() > 0) {
2208 Node *newphi = old_new[phi->_idx];
2209 _igvn.hash_delete(phi);
2210 _igvn.hash_delete(newphi);
2211
2212 phi ->set_req(LoopNode:: EntryControl, newphi->in(LoopNode::LoopBackControl));
2213 newphi->set_req(LoopNode::LoopBackControl, phi ->in(LoopNode::LoopBackControl));
2214 phi ->set_req(LoopNode::LoopBackControl, C->top());
2215 }
2216 }
2217 CountedLoopNode* clone_head = old_new[loop_head->_idx]->as_CountedLoop();
2218 _igvn.hash_delete(clone_head);
2219 loop_head ->set_req(LoopNode:: EntryControl, clone_head->in(LoopNode::LoopBackControl));
2220 clone_head->set_req(LoopNode::LoopBackControl, loop_head ->in(LoopNode::LoopBackControl));
2221 loop_head ->set_req(LoopNode::LoopBackControl, C->top());
2222 loop->_head = clone_head; // New loop header
2223
2224 set_idom(loop_head, loop_head ->in(LoopNode::EntryControl), dd);
2225 set_idom(clone_head, clone_head->in(LoopNode::EntryControl), dd);
2226
2227 // Kill the clone's backedge
2228 Node *newcle = old_new[loop_end->_idx];
2229 _igvn.hash_delete(newcle);
2230 Node* one = intcon(1);
2231 newcle->set_req(1, one);
2232 // Force clone into same loop body
2233 uint max = loop->_body.size();
2234 for (uint k = 0; k < max; k++) {
2235 Node *old = loop->_body.at(k);
2236 Node *nnn = old_new[old->_idx];
2237 loop->_body.push(nnn);
2238 if (!has_ctrl(old)) {
2239 set_loop(nnn, loop);
2240 }
2241 }
2242
2243 loop->record_for_igvn();
2244 loop_head->clear_strip_mined();
2245
2246 update_main_loop_assertion_predicates(clone_head, stride_con);
2247
2248 #ifndef PRODUCT
2249 if (C->do_vector_loop() && (PrintOpto && (VerifyLoopOptimizations || TraceLoopOpts))) {
2250 tty->print("\nnew loop after unroll\n"); loop->dump_head();
2251 for (uint i = 0; i < loop->_body.size(); i++) {
2252 loop->_body.at(i)->dump();
2253 }
2254 if (C->clone_map().is_debug()) {
2255 tty->print("\nCloneMap\n");
2256 Dict* dict = C->clone_map().dict();
2257 DictI i(dict);
2258 tty->print_cr("Dict@%p[%d] = ", dict, dict->Size());
2259 for (int ii = 0; i.test(); ++i, ++ii) {
2260 NodeCloneInfo cl((uint64_t)dict->operator[]((void*)i._key));
2261 tty->print("%d->%d:%d,", (int)(intptr_t)i._key, cl.idx(), cl.gen());
2262 if (ii % 10 == 9) {
2263 tty->print_cr(" ");
2264 }
2265 }
2266 tty->print_cr(" ");
2267 }
2268 }
2269 #endif
2270
2271 C->print_method(PHASE_AFTER_LOOP_UNROLLING, 4, clone_head);
2272 }
2273
2274 //------------------------------do_maximally_unroll----------------------------
2275
2276 void PhaseIdealLoop::do_maximally_unroll(IdealLoopTree *loop, Node_List &old_new) {
2277 CountedLoopNode *cl = loop->_head->as_CountedLoop();
2278 assert(cl->has_exact_trip_count(), "trip count is not exact");
2279 assert(cl->trip_count() > 0, "");
2280 #ifndef PRODUCT
2281 if (TraceLoopOpts) {
2282 tty->print("MaxUnroll " JULONG_FORMAT " ", cl->trip_count());
2283 loop->dump_head();
2284 }
2285 #endif
2286
2287 // If loop is tripping an odd number of times, peel odd iteration
2288 if ((cl->trip_count() & 1) == 1) {
2289 if (LoopPeeling == 0) {
2290 #ifndef PRODUCT
2291 if (TraceLoopOpts) {
2292 tty->print("MaxUnroll cancelled since LoopPeeling is always disabled");
2293 loop->dump_head();
2294 }
2295 #endif
2296 return;
2297 }
2298 do_peeling(loop, old_new);
2299 }
2300
2301 // Now its tripping an even number of times remaining. Double loop body.
2302 // Do not adjust pre-guards; they are not needed and do not exist.
2303 if (cl->trip_count() > 0) {
2304 assert((cl->trip_count() & 1) == 0, "missed peeling");
2305 do_unroll(loop, old_new, false);
2306 }
2307 }
2308
2309 //------------------------------adjust_limit-----------------------------------
2310 // Helper function that computes new loop limit as (rc_limit-offset)/scale
2311 Node* PhaseIdealLoop::adjust_limit(bool is_positive_stride, Node* scale, Node* offset, Node* rc_limit, Node* old_limit, Node* pre_ctrl, bool round) {
2312 Node* old_limit_long = new ConvI2LNode(old_limit);
2313 register_new_node(old_limit_long, pre_ctrl);
2314
2315 Node* sub = new SubLNode(rc_limit, offset);
2316 register_new_node(sub, pre_ctrl);
2317 Node* limit = new DivLNode(nullptr, sub, scale);
2318 register_new_node(limit, pre_ctrl);
2319
2320 // When the absolute value of scale is greater than one, the division
2321 // may round limit down/up, so add/sub one to/from the limit.
2322 if (round) {
2323 limit = new AddLNode(limit, _igvn.longcon(is_positive_stride ? -1 : 1));
2324 register_new_node(limit, pre_ctrl);
2325 }
2326
2327 // Clamp the limit to handle integer under-/overflows by using long values.
2328 // We only convert the limit back to int when we handled under-/overflows.
2329 // Note that all values are longs in the following computations.
2330 // When reducing the limit, clamp to [min_jint, old_limit]:
2331 // INT(MINL(old_limit, MAXL(limit, min_jint)))
2332 // - integer underflow of limit: MAXL chooses min_jint.
2333 // - integer overflow of limit: MINL chooses old_limit (<= MAX_INT < limit)
2334 // When increasing the limit, clamp to [old_limit, max_jint]:
2335 // INT(MAXL(old_limit, MINL(limit, max_jint)))
2336 // - integer overflow of limit: MINL chooses max_jint.
2337 // - integer underflow of limit: MAXL chooses old_limit (>= MIN_INT > limit)
2338 // INT() is finally converting the limit back to an integer value.
2339
2340 Node* inner_result_long = nullptr;
2341 Node* outer_result_long = nullptr;
2342 if (is_positive_stride) {
2343 inner_result_long = new MaxLNode(C, limit, _igvn.longcon(min_jint));
2344 outer_result_long = new MinLNode(C, inner_result_long, old_limit_long);
2345 } else {
2346 inner_result_long = new MinLNode(C, limit, _igvn.longcon(max_jint));
2347 outer_result_long = new MaxLNode(C, inner_result_long, old_limit_long);
2348 }
2349 register_new_node(inner_result_long, pre_ctrl);
2350 register_new_node(outer_result_long, pre_ctrl);
2351
2352 limit = new ConvL2INode(outer_result_long);
2353 register_new_node(limit, pre_ctrl);
2354 return limit;
2355 }
2356
2357 //------------------------------add_constraint---------------------------------
2358 // Constrain the main loop iterations so the conditions:
2359 // low_limit <= scale_con*I + offset < upper_limit
2360 // always hold true. That is, either increase the number of iterations in the
2361 // pre-loop or reduce the number of iterations in the main-loop until the condition
2362 // holds true in the main-loop. Stride, scale, offset and limit are all loop
2363 // invariant. Further, stride and scale are constants (offset and limit often are).
2364 void PhaseIdealLoop::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) {
2365 assert(_igvn.type(offset)->isa_long() != nullptr && _igvn.type(low_limit)->isa_long() != nullptr &&
2366 _igvn.type(upper_limit)->isa_long() != nullptr, "arguments should be long values");
2367
2368 // For a positive stride, we need to reduce the main-loop limit and
2369 // increase the pre-loop limit. This is reversed for a negative stride.
2370 bool is_positive_stride = (stride_con > 0);
2371
2372 // If the absolute scale value is greater one, division in 'adjust_limit' may require
2373 // rounding. Make sure the ABS method correctly handles min_jint.
2374 // Only do this for the pre-loop, one less iteration of the main loop doesn't hurt.
2375 bool round = ABS(scale_con) > 1;
2376
2377 Node* scale = longcon(scale_con);
2378
2379 if ((stride_con^scale_con) >= 0) { // Use XOR to avoid overflow
2380 // Positive stride*scale: the affine function is increasing,
2381 // the pre-loop checks for underflow and the post-loop for overflow.
2382
2383 // The overflow limit: scale*I+offset < upper_limit
2384 // For the main-loop limit compute:
2385 // ( if (scale > 0) /* and stride > 0 */
2386 // I < (upper_limit-offset)/scale
2387 // else /* scale < 0 and stride < 0 */
2388 // I > (upper_limit-offset)/scale
2389 // )
2390 *main_limit = adjust_limit(is_positive_stride, scale, offset, upper_limit, *main_limit, pre_ctrl, false);
2391
2392 // The underflow limit: low_limit <= scale*I+offset
2393 // For the pre-loop limit compute:
2394 // NOT(scale*I+offset >= low_limit)
2395 // scale*I+offset < low_limit
2396 // ( if (scale > 0) /* and stride > 0 */
2397 // I < (low_limit-offset)/scale
2398 // else /* scale < 0 and stride < 0 */
2399 // I > (low_limit-offset)/scale
2400 // )
2401 *pre_limit = adjust_limit(!is_positive_stride, scale, offset, low_limit, *pre_limit, pre_ctrl, round);
2402 } else {
2403 // Negative stride*scale: the affine function is decreasing,
2404 // the pre-loop checks for overflow and the post-loop for underflow.
2405
2406 // The overflow limit: scale*I+offset < upper_limit
2407 // For the pre-loop limit compute:
2408 // NOT(scale*I+offset < upper_limit)
2409 // scale*I+offset >= upper_limit
2410 // scale*I+offset+1 > upper_limit
2411 // ( if (scale < 0) /* and stride > 0 */
2412 // I < (upper_limit-(offset+1))/scale
2413 // else /* scale > 0 and stride < 0 */
2414 // I > (upper_limit-(offset+1))/scale
2415 // )
2416 Node* one = longcon(1);
2417 Node* plus_one = new AddLNode(offset, one);
2418 register_new_node(plus_one, pre_ctrl);
2419 *pre_limit = adjust_limit(!is_positive_stride, scale, plus_one, upper_limit, *pre_limit, pre_ctrl, round);
2420
2421 // The underflow limit: low_limit <= scale*I+offset
2422 // For the main-loop limit compute:
2423 // scale*I+offset+1 > low_limit
2424 // ( if (scale < 0) /* and stride > 0 */
2425 // I < (low_limit-(offset+1))/scale
2426 // else /* scale > 0 and stride < 0 */
2427 // I > (low_limit-(offset+1))/scale
2428 // )
2429 *main_limit = adjust_limit(is_positive_stride, scale, plus_one, low_limit, *main_limit, pre_ctrl, false);
2430 }
2431 }
2432
2433 //----------------------------------is_iv------------------------------------
2434 // Return true if exp is the value (of type bt) of the given induction var.
2435 // This grammar of cases is recognized, where X is I|L according to bt:
2436 // VIV[iv] = iv | (CastXX VIV[iv]) | (ConvI2X VIV[iv])
2437 bool PhaseIdealLoop::is_iv(Node* exp, Node* iv, BasicType bt) {
2438 exp = exp->uncast();
2439 if (exp == iv && iv->bottom_type()->isa_integer(bt)) {
2440 return true;
2441 }
2442
2443 if (bt == T_LONG && iv->bottom_type()->isa_int() && exp->Opcode() == Op_ConvI2L && exp->in(1)->uncast() == iv) {
2444 return true;
2445 }
2446 return false;
2447 }
2448
2449 //------------------------------is_scaled_iv---------------------------------
2450 // Return true if exp is a constant times the given induction var (of type bt).
2451 // The multiplication is either done in full precision (exactly of type bt),
2452 // or else bt is T_LONG but iv is scaled using 32-bit arithmetic followed by a ConvI2L.
2453 // This grammar of cases is recognized, where X is I|L according to bt:
2454 // SIV[iv] = VIV[iv] | (CastXX SIV[iv])
2455 // | (MulX VIV[iv] ConX) | (MulX ConX VIV[iv])
2456 // | (LShiftX VIV[iv] ConI)
2457 // | (ConvI2L SIV[iv]) -- a "short-scale" can occur here; note recursion
2458 // | (SubX 0 SIV[iv]) -- same as MulX(iv, -scale); note recursion
2459 // | (AddX SIV[iv] SIV[iv]) -- sum of two scaled iv; note recursion
2460 // | (SubX SIV[iv] SIV[iv]) -- difference of two scaled iv; note recursion
2461 // VIV[iv] = [either iv or its value converted; see is_iv() above]
2462 // On success, the constant scale value is stored back to *p_scale.
2463 // The value (*p_short_scale) reports if such a ConvI2L conversion was present.
2464 bool PhaseIdealLoop::is_scaled_iv(Node* exp, Node* iv, BasicType bt, jlong* p_scale, bool* p_short_scale, int depth) {
2465 BasicType exp_bt = bt;
2466 exp = exp->uncast(); //strip casts
2467 assert(exp_bt == T_INT || exp_bt == T_LONG, "unexpected int type");
2468 if (is_iv(exp, iv, exp_bt)) {
2469 if (p_scale != nullptr) {
2470 *p_scale = 1;
2471 }
2472 if (p_short_scale != nullptr) {
2473 *p_short_scale = false;
2474 }
2475 return true;
2476 }
2477 if (exp_bt == T_LONG && iv->bottom_type()->isa_int() && exp->Opcode() == Op_ConvI2L) {
2478 exp = exp->in(1);
2479 exp_bt = T_INT;
2480 }
2481 int opc = exp->Opcode();
2482 int which = 0; // this is which subexpression we find the iv in
2483 // Can't use is_Mul() here as it's true for AndI and AndL
2484 if (opc == Op_Mul(exp_bt)) {
2485 if ((is_iv(exp->in(which = 1), iv, exp_bt) && exp->in(2)->is_Con()) ||
2486 (is_iv(exp->in(which = 2), iv, exp_bt) && exp->in(1)->is_Con())) {
2487 Node* factor = exp->in(which == 1 ? 2 : 1); // the other argument
2488 jlong scale = factor->find_integer_as_long(exp_bt, 0);
2489 if (scale == 0) {
2490 return false; // might be top
2491 }
2492 if (p_scale != nullptr) {
2493 *p_scale = scale;
2494 }
2495 if (p_short_scale != nullptr) {
2496 // (ConvI2L (MulI iv K)) can be 64-bit linear if iv is kept small enough...
2497 *p_short_scale = (exp_bt != bt && scale != 1);
2498 }
2499 return true;
2500 }
2501 } else if (opc == Op_LShift(exp_bt)) {
2502 if (is_iv(exp->in(1), iv, exp_bt) && exp->in(2)->is_Con()) {
2503 jint shift_amount = exp->in(2)->find_int_con(min_jint);
2504 if (shift_amount == min_jint) {
2505 return false; // might be top
2506 }
2507 jlong scale;
2508 if (exp_bt == T_INT) {
2509 scale = java_shift_left((jint)1, (juint)shift_amount);
2510 } else if (exp_bt == T_LONG) {
2511 scale = java_shift_left((jlong)1, (julong)shift_amount);
2512 }
2513 if (p_scale != nullptr) {
2514 *p_scale = scale;
2515 }
2516 if (p_short_scale != nullptr) {
2517 // (ConvI2L (MulI iv K)) can be 64-bit linear if iv is kept small enough...
2518 *p_short_scale = (exp_bt != bt && scale != 1);
2519 }
2520 return true;
2521 }
2522 } else if (opc == Op_Add(exp_bt)) {
2523 jlong scale_l = 0;
2524 jlong scale_r = 0;
2525 bool short_scale_l = false;
2526 bool short_scale_r = false;
2527 if (depth == 0 &&
2528 is_scaled_iv(exp->in(1), iv, exp_bt, &scale_l, &short_scale_l, depth + 1) &&
2529 is_scaled_iv(exp->in(2), iv, exp_bt, &scale_r, &short_scale_r, depth + 1)) {
2530 // AddX(iv*K1, iv*K2) => iv*(K1+K2)
2531 jlong scale_sum = java_add(scale_l, scale_r);
2532 if (scale_sum > max_signed_integer(exp_bt) || scale_sum <= min_signed_integer(exp_bt)) {
2533 // This logic is shared by int and long. For int, the result may overflow
2534 // as we use jlong to compute so do the check here. Long result may also
2535 // overflow but that's fine because result wraps.
2536 return false;
2537 }
2538 if (p_scale != nullptr) {
2539 *p_scale = scale_sum;
2540 }
2541 if (p_short_scale != nullptr) {
2542 *p_short_scale = short_scale_l && short_scale_r;
2543 }
2544 return true;
2545 }
2546 } else if (opc == Op_Sub(exp_bt)) {
2547 if (exp->in(1)->find_integer_as_long(exp_bt, -1) == 0) {
2548 jlong scale = 0;
2549 if (depth == 0 && is_scaled_iv(exp->in(2), iv, exp_bt, &scale, p_short_scale, depth + 1)) {
2550 // SubX(0, iv*K) => iv*(-K)
2551 if (scale == min_signed_integer(exp_bt)) {
2552 // This should work even if -K overflows, but let's not.
2553 return false;
2554 }
2555 scale = java_multiply(scale, (jlong)-1);
2556 if (p_scale != nullptr) {
2557 *p_scale = scale;
2558 }
2559 if (p_short_scale != nullptr) {
2560 // (ConvI2L (MulI iv K)) can be 64-bit linear if iv is kept small enough...
2561 *p_short_scale = *p_short_scale || (exp_bt != bt && scale != 1);
2562 }
2563 return true;
2564 }
2565 } else {
2566 jlong scale_l = 0;
2567 jlong scale_r = 0;
2568 bool short_scale_l = false;
2569 bool short_scale_r = false;
2570 if (depth == 0 &&
2571 is_scaled_iv(exp->in(1), iv, exp_bt, &scale_l, &short_scale_l, depth + 1) &&
2572 is_scaled_iv(exp->in(2), iv, exp_bt, &scale_r, &short_scale_r, depth + 1)) {
2573 // SubX(iv*K1, iv*K2) => iv*(K1-K2)
2574 jlong scale_diff = java_subtract(scale_l, scale_r);
2575 if (scale_diff > max_signed_integer(exp_bt) || scale_diff <= min_signed_integer(exp_bt)) {
2576 // This logic is shared by int and long. For int, the result may
2577 // overflow as we use jlong to compute so do the check here. Long
2578 // result may also overflow but that's fine because result wraps.
2579 return false;
2580 }
2581 if (p_scale != nullptr) {
2582 *p_scale = scale_diff;
2583 }
2584 if (p_short_scale != nullptr) {
2585 *p_short_scale = short_scale_l && short_scale_r;
2586 }
2587 return true;
2588 }
2589 }
2590 }
2591 // We could also recognize (iv*K1)*K2, even with overflow, but let's not.
2592 return false;
2593 }
2594
2595 //-------------------------is_scaled_iv_plus_offset--------------------------
2596 // Return true if exp is a simple linear transform of the given induction var.
2597 // The scale must be constant and the addition tree (if any) must be simple.
2598 // This grammar of cases is recognized, where X is I|L according to bt:
2599 //
2600 // OIV[iv] = SIV[iv] | (CastXX OIV[iv])
2601 // | (AddX SIV[iv] E) | (AddX E SIV[iv])
2602 // | (SubX SIV[iv] E) | (SubX E SIV[iv])
2603 // SSIV[iv] = (ConvI2X SIV[iv]) -- a "short scale" might occur here
2604 // SIV[iv] = [a possibly scaled value of iv; see is_scaled_iv() above]
2605 //
2606 // On success, the constant scale value is stored back to *p_scale unless null.
2607 // Likewise, the addend (perhaps a synthetic AddX node) is stored to *p_offset.
2608 // Also, (*p_short_scale) reports if a ConvI2L conversion was seen after a MulI,
2609 // meaning bt is T_LONG but iv was scaled using 32-bit arithmetic.
2610 // To avoid looping, the match is depth-limited, and so may fail to match the grammar to complex expressions.
2611 bool PhaseIdealLoop::is_scaled_iv_plus_offset(Node* exp, Node* iv, BasicType bt, jlong* p_scale, Node** p_offset, bool* p_short_scale, int depth) {
2612 assert(bt == T_INT || bt == T_LONG, "unexpected int type");
2613 jlong scale = 0; // to catch result from is_scaled_iv()
2614 BasicType exp_bt = bt;
2615 exp = exp->uncast();
2616 if (is_scaled_iv(exp, iv, exp_bt, &scale, p_short_scale)) {
2617 if (p_scale != nullptr) {
2618 *p_scale = scale;
2619 }
2620 if (p_offset != nullptr) {
2621 Node* zero = zerocon(bt);
2622 *p_offset = zero;
2623 }
2624 return true;
2625 }
2626 if (exp_bt != bt) {
2627 // We would now be matching inputs like (ConvI2L exp:(AddI (MulI iv S) E)).
2628 // It's hard to make 32-bit arithmetic linear if it overflows. Although we do
2629 // cope with overflowing multiplication by S, it would be even more work to
2630 // handle overflowing addition of E. So we bail out here on ConvI2L input.
2631 return false;
2632 }
2633 int opc = exp->Opcode();
2634 int which = 0; // this is which subexpression we find the iv in
2635 Node* offset = nullptr;
2636 if (opc == Op_Add(exp_bt)) {
2637 // Check for a scaled IV in (AddX (MulX iv S) E) or (AddX E (MulX iv S)).
2638 if (is_scaled_iv(exp->in(which = 1), iv, bt, &scale, p_short_scale) ||
2639 is_scaled_iv(exp->in(which = 2), iv, bt, &scale, p_short_scale)) {
2640 offset = exp->in(which == 1 ? 2 : 1); // the other argument
2641 if (p_scale != nullptr) {
2642 *p_scale = scale;
2643 }
2644 if (p_offset != nullptr) {
2645 *p_offset = offset;
2646 }
2647 return true;
2648 }
2649 // Check for more addends, like (AddX (AddX (MulX iv S) E1) E2), etc.
2650 if (is_scaled_iv_plus_extra_offset(exp->in(1), exp->in(2), iv, bt, p_scale, p_offset, p_short_scale, depth) ||
2651 is_scaled_iv_plus_extra_offset(exp->in(2), exp->in(1), iv, bt, p_scale, p_offset, p_short_scale, depth)) {
2652 return true;
2653 }
2654 } else if (opc == Op_Sub(exp_bt)) {
2655 if (is_scaled_iv(exp->in(which = 1), iv, bt, &scale, p_short_scale) ||
2656 is_scaled_iv(exp->in(which = 2), iv, bt, &scale, p_short_scale)) {
2657 // Match (SubX SIV[iv] E) as if (AddX SIV[iv] (SubX 0 E)), and
2658 // match (SubX E SIV[iv]) as if (AddX E (SubX 0 SIV[iv])).
2659 offset = exp->in(which == 1 ? 2 : 1); // the other argument
2660 if (which == 2) {
2661 // We can't handle a scale of min_jint (or min_jlong) here as -1 * min_jint = min_jint
2662 if (scale == min_signed_integer(bt)) {
2663 return false; // cannot negate the scale of the iv
2664 }
2665 scale = java_multiply(scale, (jlong)-1);
2666 }
2667 if (p_scale != nullptr) {
2668 *p_scale = scale;
2669 }
2670 if (p_offset != nullptr) {
2671 if (which == 1) { // must negate the extracted offset
2672 Node* zero = integercon(0, exp_bt);
2673 Node *ctrl_off = get_ctrl(offset);
2674 offset = SubNode::make(zero, offset, exp_bt);
2675 register_new_node(offset, ctrl_off);
2676 }
2677 *p_offset = offset;
2678 }
2679 return true;
2680 }
2681 }
2682 return false;
2683 }
2684
2685 // Helper for is_scaled_iv_plus_offset(), not called separately.
2686 // The caller encountered (AddX exp1 offset3) or (AddX offset3 exp1).
2687 // Here, exp1 is inspected to see if it is a simple linear transform of iv.
2688 // If so, the offset3 is combined with any other offset2 from inside exp1.
2689 bool PhaseIdealLoop::is_scaled_iv_plus_extra_offset(Node* exp1, Node* offset3, Node* iv,
2690 BasicType bt,
2691 jlong* p_scale, Node** p_offset,
2692 bool* p_short_scale, int depth) {
2693 // By the time we reach here, it is unlikely that exp1 is a simple iv*K.
2694 // If is a linear iv transform, it is probably an add or subtract.
2695 // Let's collect the internal offset2 from it.
2696 Node* offset2 = nullptr;
2697 if (offset3->is_Con() &&
2698 depth < 2 &&
2699 is_scaled_iv_plus_offset(exp1, iv, bt, p_scale,
2700 &offset2, p_short_scale, depth+1)) {
2701 if (p_offset != nullptr) {
2702 Node* ctrl_off2 = get_ctrl(offset2);
2703 Node* offset = AddNode::make(offset2, offset3, bt);
2704 register_new_node(offset, ctrl_off2);
2705 *p_offset = offset;
2706 }
2707 return true;
2708 }
2709 return false;
2710 }
2711
2712 //------------------------------do_range_check---------------------------------
2713 // Eliminate range-checks and other trip-counter vs loop-invariant tests.
2714 void PhaseIdealLoop::do_range_check(IdealLoopTree* loop) {
2715 #ifndef PRODUCT
2716 if (TraceLoopOpts) {
2717 tty->print("RangeCheck ");
2718 loop->dump_head();
2719 }
2720 #endif
2721
2722 assert(RangeCheckElimination, "");
2723 CountedLoopNode *cl = loop->_head->as_CountedLoop();
2724
2725 // protect against stride not being a constant
2726 if (!cl->stride_is_con()) {
2727 return;
2728 }
2729 // Find the trip counter; we are iteration splitting based on it
2730 Node *trip_counter = cl->phi();
2731 // Find the main loop limit; we will trim it's iterations
2732 // to not ever trip end tests
2733 Node *main_limit = cl->limit();
2734 Node* main_limit_ctrl = get_ctrl(main_limit);
2735
2736 // Check graph shape. Cannot optimize a loop if zero-trip
2737 // Opaque1 node is optimized away and then another round
2738 // of loop opts attempted.
2739 if (cl->is_canonical_loop_entry() == nullptr) {
2740 return;
2741 }
2742
2743 // Need to find the main-loop zero-trip guard
2744 Node *ctrl = cl->skip_assertion_predicates_with_halt();
2745 Node *iffm = ctrl->in(0);
2746 Node *opqzm = iffm->in(1)->in(1)->in(2);
2747 assert(opqzm->in(1) == main_limit, "do not understand situation");
2748
2749 // Find the pre-loop limit; we will expand its iterations to
2750 // not ever trip low tests.
2751 Node *p_f = iffm->in(0);
2752 // pre loop may have been optimized out
2753 if (p_f->Opcode() != Op_IfFalse) {
2754 return;
2755 }
2756 CountedLoopEndNode *pre_end = p_f->in(0)->as_CountedLoopEnd();
2757 assert(pre_end->loopnode()->is_pre_loop(), "");
2758 Node *pre_opaq1 = pre_end->limit();
2759 // Occasionally it's possible for a pre-loop Opaque1 node to be
2760 // optimized away and then another round of loop opts attempted.
2761 // We can not optimize this particular loop in that case.
2762 if (pre_opaq1->Opcode() != Op_Opaque1) {
2763 return;
2764 }
2765 Opaque1Node *pre_opaq = (Opaque1Node*)pre_opaq1;
2766 Node *pre_limit = pre_opaq->in(1);
2767 Node* pre_limit_ctrl = get_ctrl(pre_limit);
2768
2769 // Where do we put new limit calculations
2770 Node* pre_ctrl = pre_end->loopnode()->in(LoopNode::EntryControl);
2771 // Range check elimination optimizes out conditions whose parameters are loop invariant in the main loop. They usually
2772 // have control above the pre loop, but there's no guarantee that they do. There's no guarantee either that the pre
2773 // loop limit has control that's out of loop (a previous round of range check elimination could have set a limit that's
2774 // not loop invariant). new_limit_ctrl is used for both the pre and main loops. Early control for the main limit may be
2775 // below the pre loop entry and the pre limit and must be taken into account when initializing new_limit_ctrl.
2776 Node* new_limit_ctrl = dominated_node(pre_ctrl, pre_limit_ctrl, compute_early_ctrl(main_limit, main_limit_ctrl));
2777
2778 // Ensure the original loop limit is available from the
2779 // pre-loop Opaque1 node.
2780 Node *orig_limit = pre_opaq->original_loop_limit();
2781 if (orig_limit == nullptr || _igvn.type(orig_limit) == Type::TOP) {
2782 return;
2783 }
2784 // Must know if its a count-up or count-down loop
2785
2786 int stride_con = cl->stride_con();
2787 bool abs_stride_is_one = stride_con == 1 || stride_con == -1;
2788 Node* zero = longcon(0);
2789 Node* one = longcon(1);
2790 // Use symmetrical int range [-max_jint,max_jint]
2791 Node* mini = longcon(-max_jint);
2792
2793 Node* loop_entry = cl->skip_strip_mined()->in(LoopNode::EntryControl);
2794 assert(loop_entry->is_Proj() && loop_entry->in(0)->is_If(), "if projection only");
2795
2796 // if abs(stride) == 1, an Assertion Predicate for the final iv value is added. We don't know the final iv value until
2797 // we're done with range check elimination so use a place holder.
2798 Node* final_iv_placeholder = nullptr;
2799 if (abs_stride_is_one) {
2800 final_iv_placeholder = new Node(1);
2801 _igvn.set_type(final_iv_placeholder, TypeInt::INT);
2802 final_iv_placeholder->init_req(0, loop_entry);
2803 }
2804
2805 // Check loop body for tests of trip-counter plus loop-invariant vs loop-variant.
2806 for (uint i = 0; i < loop->_body.size(); i++) {
2807 Node *iff = loop->_body[i];
2808 if (iff->Opcode() == Op_If ||
2809 iff->Opcode() == Op_RangeCheck) { // Test?
2810 // Test is an IfNode, has 2 projections. If BOTH are in the loop
2811 // we need loop unswitching instead of iteration splitting.
2812 Node *exit = loop->is_loop_exit(iff);
2813 if (!exit) continue;
2814 int flip = (exit->Opcode() == Op_IfTrue) ? 1 : 0;
2815
2816 // Get boolean condition to test
2817 Node *i1 = iff->in(1);
2818 if (!i1->is_Bool()) continue;
2819 BoolNode *bol = i1->as_Bool();
2820 BoolTest b_test = bol->_test;
2821 // Flip sense of test if exit condition is flipped
2822 if (flip) {
2823 b_test = b_test.negate();
2824 }
2825 // Get compare
2826 Node *cmp = bol->in(1);
2827
2828 // Look for trip_counter + offset vs limit
2829 Node *rc_exp = cmp->in(1);
2830 Node *limit = cmp->in(2);
2831 int scale_con= 1; // Assume trip counter not scaled
2832
2833 Node* limit_ctrl = get_ctrl(limit);
2834 if (loop->is_member(get_loop(limit_ctrl))) {
2835 // Compare might have operands swapped; commute them
2836 b_test = b_test.commute();
2837 rc_exp = cmp->in(2);
2838 limit = cmp->in(1);
2839 limit_ctrl = get_ctrl(limit);
2840 if (loop->is_member(get_loop(limit_ctrl))) {
2841 continue; // Both inputs are loop varying; cannot RCE
2842 }
2843 }
2844 // Here we know 'limit' is loop invariant
2845
2846 // 'limit' maybe pinned below the zero trip test (probably from a
2847 // previous round of rce), in which case, it can't be used in the
2848 // zero trip test expression which must occur before the zero test's if.
2849 if (is_dominator(ctrl, limit_ctrl)) {
2850 continue; // Don't rce this check but continue looking for other candidates.
2851 }
2852
2853 assert(is_dominator(compute_early_ctrl(limit, limit_ctrl), pre_end), "node pinned on loop exit test?");
2854
2855 // Check for scaled induction variable plus an offset
2856 Node *offset = nullptr;
2857
2858 if (!is_scaled_iv_plus_offset(rc_exp, trip_counter, &scale_con, &offset)) {
2859 continue;
2860 }
2861
2862 Node* offset_ctrl = get_ctrl(offset);
2863 if (loop->is_member(get_loop(offset_ctrl))) {
2864 continue; // Offset is not really loop invariant
2865 }
2866 // Here we know 'offset' is loop invariant.
2867
2868 // As above for the 'limit', the 'offset' maybe pinned below the
2869 // zero trip test.
2870 if (is_dominator(ctrl, offset_ctrl)) {
2871 continue; // Don't rce this check but continue looking for other candidates.
2872 }
2873
2874 // offset and limit can have control set below the pre loop when they are not loop invariant in the pre loop.
2875 // Update their control (and the control of inputs as needed) to be above pre_end
2876 offset_ctrl = ensure_node_and_inputs_are_above_pre_end(pre_end, offset);
2877 limit_ctrl = ensure_node_and_inputs_are_above_pre_end(pre_end, limit);
2878
2879 // offset and limit could have control below new_limit_ctrl if they are not loop invariant in the pre loop.
2880 Node* next_limit_ctrl = dominated_node(new_limit_ctrl, offset_ctrl, limit_ctrl);
2881
2882 #ifdef ASSERT
2883 if (TraceRangeLimitCheck) {
2884 tty->print_cr("RC bool node%s", flip ? " flipped:" : ":");
2885 bol->dump(2);
2886 }
2887 #endif
2888 // At this point we have the expression as:
2889 // scale_con * trip_counter + offset :: limit
2890 // where scale_con, offset and limit are loop invariant. Trip_counter
2891 // monotonically increases by stride_con, a constant. Both (or either)
2892 // stride_con and scale_con can be negative which will flip about the
2893 // sense of the test.
2894
2895 C->print_method(PHASE_BEFORE_RANGE_CHECK_ELIMINATION, 4, iff);
2896
2897 // Perform the limit computations in jlong to avoid overflow
2898 jlong lscale_con = scale_con;
2899 Node* int_offset = offset;
2900 offset = new ConvI2LNode(offset);
2901 register_new_node(offset, next_limit_ctrl);
2902 Node* int_limit = limit;
2903 limit = new ConvI2LNode(limit);
2904 register_new_node(limit, next_limit_ctrl);
2905
2906 // Adjust pre and main loop limits to guard the correct iteration set
2907 if (cmp->Opcode() == Op_CmpU) { // Unsigned compare is really 2 tests
2908 if (b_test._test == BoolTest::lt) { // Range checks always use lt
2909 // The underflow and overflow limits: 0 <= scale*I+offset < limit
2910 add_constraint(stride_con, lscale_con, offset, zero, limit, next_limit_ctrl, &pre_limit, &main_limit);
2911 Node* init = cl->uncasted_init_trip(true);
2912
2913 Node* opaque_init = new OpaqueLoopInitNode(C, init);
2914 register_new_node(opaque_init, loop_entry);
2915
2916 InitializedAssertionPredicateCreator initialized_assertion_predicate_creator(this);
2917 if (abs_stride_is_one) {
2918 // If the main loop becomes empty and the array access for this range check is sunk out of the loop, the index
2919 // for the array access will be set to the index value of the final iteration which could be out of loop.
2920 // Add an Initialized Assertion Predicate for that corner case. The final iv is computed from LoopLimit which
2921 // is the LoopNode::limit() only if abs(stride) == 1 otherwise the computation depends on LoopNode::init_trip()
2922 // as well. When LoopLimit only depends on LoopNode::limit(), there are cases where the zero trip guard for
2923 // the main loop doesn't constant fold after range check elimination but, the array access for the final
2924 // iteration of the main loop is out of bound and the index for that access is out of range for the range
2925 // check CastII.
2926 // Note that we do not need to emit a Template Assertion Predicate to update this predicate. When further
2927 // splitting this loop, the final IV will still be the same. When unrolling the loop, we will remove a
2928 // previously added Initialized Assertion Predicate here. But then abs(stride) is greater than 1, and we
2929 // cannot remove an empty loop with a constant limit when init is not a constant as well. We will use
2930 // a LoopLimitCheck node that can only be folded if the zero grip guard is also foldable.
2931 loop_entry = initialized_assertion_predicate_creator.create(final_iv_placeholder, loop_entry, stride_con,
2932 scale_con, int_offset, int_limit,
2933 AssertionPredicateType::FinalIv);
2934 }
2935
2936 // Add two Template Assertion Predicates to create new Initialized Assertion Predicates from when either
2937 // unrolling or splitting this main-loop further.
2938 TemplateAssertionPredicateCreator template_assertion_predicate_creator(cl, scale_con , int_offset, int_limit,
2939 this);
2940 loop_entry = template_assertion_predicate_creator.create(loop_entry);
2941
2942 // Initialized Assertion Predicate for the value of the initial main-loop.
2943 loop_entry = initialized_assertion_predicate_creator.create(init, loop_entry, stride_con, scale_con,
2944 int_offset, int_limit,
2945 AssertionPredicateType::InitValue);
2946
2947 } else {
2948 if (PrintOpto) {
2949 tty->print_cr("missed RCE opportunity");
2950 }
2951 continue; // In release mode, ignore it
2952 }
2953 } else { // Otherwise work on normal compares
2954 switch(b_test._test) {
2955 case BoolTest::gt:
2956 // Fall into GE case
2957 case BoolTest::ge:
2958 // Convert (I*scale+offset) >= Limit to (I*(-scale)+(-offset)) <= -Limit
2959 lscale_con = -lscale_con;
2960 offset = new SubLNode(zero, offset);
2961 register_new_node(offset, next_limit_ctrl);
2962 limit = new SubLNode(zero, limit);
2963 register_new_node(limit, next_limit_ctrl);
2964 // Fall into LE case
2965 case BoolTest::le:
2966 if (b_test._test != BoolTest::gt) {
2967 // Convert X <= Y to X < Y+1
2968 limit = new AddLNode(limit, one);
2969 register_new_node(limit, next_limit_ctrl);
2970 }
2971 // Fall into LT case
2972 case BoolTest::lt:
2973 // The underflow and overflow limits: MIN_INT <= scale*I+offset < limit
2974 // Note: (MIN_INT+1 == -MAX_INT) is used instead of MIN_INT here
2975 // to avoid problem with scale == -1: MIN_INT/(-1) == MIN_INT.
2976 add_constraint(stride_con, lscale_con, offset, mini, limit, next_limit_ctrl, &pre_limit, &main_limit);
2977 break;
2978 default:
2979 if (PrintOpto) {
2980 tty->print_cr("missed RCE opportunity");
2981 }
2982 continue; // Unhandled case
2983 }
2984 }
2985 // Only update variable tracking control for new nodes if it's indeed a range check that can be eliminated (and
2986 // limits are updated)
2987 new_limit_ctrl = next_limit_ctrl;
2988
2989 // Kill the eliminated test
2990 C->set_major_progress();
2991 Node* kill_con = intcon(1-flip);
2992 _igvn.replace_input_of(iff, 1, kill_con);
2993 // Find surviving projection
2994 assert(iff->is_If(), "");
2995 ProjNode* dp = ((IfNode*)iff)->proj_out(1-flip);
2996 // Find loads off the surviving projection; remove their control edge
2997 for (DUIterator_Fast imax, i = dp->fast_outs(imax); i < imax; i++) {
2998 Node* cd = dp->fast_out(i); // Control-dependent node
2999 if (cd->is_Load() && cd->depends_only_on_test()) { // Loads can now float around in the loop
3000 // Allow the load to float around in the loop, or before it
3001 // but NOT before the pre-loop.
3002 _igvn.replace_input_of(cd, 0, ctrl); // ctrl, not null
3003 --i;
3004 --imax;
3005 }
3006 }
3007 } // End of is IF
3008 }
3009 if (loop_entry != cl->skip_strip_mined()->in(LoopNode::EntryControl)) {
3010 _igvn.replace_input_of(cl->skip_strip_mined(), LoopNode::EntryControl, loop_entry);
3011 set_idom(cl->skip_strip_mined(), loop_entry, dom_depth(cl->skip_strip_mined()));
3012 }
3013
3014 // Update loop limits
3015 if (pre_limit != orig_limit) {
3016 // Computed pre-loop limit can be outside of loop iterations range.
3017 pre_limit = (stride_con > 0) ? (Node*)new MinINode(pre_limit, orig_limit)
3018 : (Node*)new MaxINode(pre_limit, orig_limit);
3019 register_new_node(pre_limit, new_limit_ctrl);
3020 }
3021 // new pre_limit can push Bool/Cmp/Opaque nodes down (when one of the eliminated condition has parameters that are not
3022 // loop invariant in the pre loop.
3023 set_ctrl(pre_opaq, new_limit_ctrl);
3024 // Can't use new_limit_ctrl for Bool/Cmp because it can be out of loop while they are loop variant. Conservatively set
3025 // control to latest possible one.
3026 set_ctrl(pre_end->cmp_node(), pre_end->in(0));
3027 set_ctrl(pre_end->in(1), pre_end->in(0));
3028
3029 _igvn.replace_input_of(pre_opaq, 1, pre_limit);
3030
3031 // Note:: we are making the main loop limit no longer precise;
3032 // need to round up based on stride.
3033 cl->set_nonexact_trip_count();
3034 Node *main_cle = cl->loopexit();
3035 Node *main_bol = main_cle->in(1);
3036 // Hacking loop bounds; need private copies of exit test
3037 if (main_bol->outcnt() > 1) { // BoolNode shared?
3038 main_bol = main_bol->clone(); // Clone a private BoolNode
3039 register_new_node(main_bol, main_cle->in(0));
3040 _igvn.replace_input_of(main_cle, 1, main_bol);
3041 }
3042 Node *main_cmp = main_bol->in(1);
3043 if (main_cmp->outcnt() > 1) { // CmpNode shared?
3044 main_cmp = main_cmp->clone(); // Clone a private CmpNode
3045 register_new_node(main_cmp, main_cle->in(0));
3046 _igvn.replace_input_of(main_bol, 1, main_cmp);
3047 }
3048 assert(main_limit == cl->limit() || get_ctrl(main_limit) == new_limit_ctrl, "wrong control for added limit");
3049 const TypeInt* orig_limit_t = _igvn.type(orig_limit)->is_int();
3050 bool upward = cl->stride_con() > 0;
3051 // The new loop limit is <= (for an upward loop) >= (for a downward loop) than the orig limit.
3052 // The expression that computes the new limit may be too complicated and the computed type of the new limit
3053 // may be too pessimistic. A CastII here guarantees it's not lost.
3054 main_limit = new CastIINode(pre_ctrl, main_limit, TypeInt::make(upward ? min_jint : orig_limit_t->_lo,
3055 upward ? orig_limit_t->_hi : max_jint, Type::WidenMax));
3056 register_new_node(main_limit, new_limit_ctrl);
3057 // Hack the now-private loop bounds
3058 _igvn.replace_input_of(main_cmp, 2, main_limit);
3059 if (abs_stride_is_one) {
3060 Node* final_iv = new SubINode(main_limit, cl->stride());
3061 register_new_node(final_iv, loop_entry);
3062 _igvn.replace_node(final_iv_placeholder, final_iv);
3063 }
3064 // The OpaqueNode is unshared by design
3065 assert(opqzm->outcnt() == 1, "cannot hack shared node");
3066 _igvn.replace_input_of(opqzm, 1, main_limit);
3067 // new main_limit can push opaque node for zero trip guard down (when one of the eliminated condition has parameters
3068 // that are not loop invariant in the pre loop).
3069 set_ctrl(opqzm, new_limit_ctrl);
3070 // Bool/Cmp nodes for zero trip guard should have been assigned control between the main and pre loop (because zero
3071 // trip guard depends on induction variable value out of pre loop) so shouldn't need to be adjusted
3072 assert(is_dominator(new_limit_ctrl, get_ctrl(iffm->in(1)->in(1))), "control of cmp should be below control of updated input");
3073
3074 C->print_method(PHASE_AFTER_RANGE_CHECK_ELIMINATION, 4, cl);
3075 }
3076
3077 // Adjust control for node and its inputs (and inputs of its inputs) to be above the pre end
3078 Node* PhaseIdealLoop::ensure_node_and_inputs_are_above_pre_end(CountedLoopEndNode* pre_end, Node* node) {
3079 Node* control = get_ctrl(node);
3080 assert(is_dominator(compute_early_ctrl(node, control), pre_end), "node pinned on loop exit test?");
3081
3082 if (is_dominator(control, pre_end)) {
3083 return control;
3084 }
3085 control = pre_end->in(0);
3086 ResourceMark rm;
3087 Unique_Node_List wq;
3088 wq.push(node);
3089 for (uint i = 0; i < wq.size(); i++) {
3090 Node* n = wq.at(i);
3091 assert(is_dominator(compute_early_ctrl(n, get_ctrl(n)), pre_end), "node pinned on loop exit test?");
3092 set_ctrl(n, control);
3093 for (uint j = 0; j < n->req(); j++) {
3094 Node* in = n->in(j);
3095 if (in != nullptr && has_ctrl(in) && !is_dominator(get_ctrl(in), pre_end)) {
3096 wq.push(in);
3097 }
3098 }
3099 }
3100 return control;
3101 }
3102
3103 bool IdealLoopTree::compute_has_range_checks() const {
3104 assert(_head->is_CountedLoop(), "");
3105 for (uint i = 0; i < _body.size(); i++) {
3106 Node *iff = _body[i];
3107 int iff_opc = iff->Opcode();
3108 if (iff_opc == Op_If || iff_opc == Op_RangeCheck) {
3109 return true;
3110 }
3111 }
3112 return false;
3113 }
3114
3115 //------------------------------DCE_loop_body----------------------------------
3116 // Remove simplistic dead code from loop body
3117 void IdealLoopTree::DCE_loop_body() {
3118 for (uint i = 0; i < _body.size(); i++) {
3119 if (_body.at(i)->outcnt() == 0) {
3120 _body.map(i, _body.pop());
3121 i--; // Ensure we revisit the updated index.
3122 }
3123 }
3124 }
3125
3126
3127 //------------------------------adjust_loop_exit_prob--------------------------
3128 // Look for loop-exit tests with the 50/50 (or worse) guesses from the parsing stage.
3129 // Replace with a 1-in-10 exit guess.
3130 void IdealLoopTree::adjust_loop_exit_prob(PhaseIdealLoop *phase) {
3131 Node *test = tail();
3132 while (test != _head) {
3133 uint top = test->Opcode();
3134 if (top == Op_IfTrue || top == Op_IfFalse) {
3135 int test_con = ((ProjNode*)test)->_con;
3136 assert(top == (uint)(test_con? Op_IfTrue: Op_IfFalse), "sanity");
3137 IfNode *iff = test->in(0)->as_If();
3138 if (iff->outcnt() == 2) { // Ignore dead tests
3139 Node *bol = iff->in(1);
3140 if (bol && bol->req() > 1 && bol->in(1) &&
3141 ((bol->in(1)->Opcode() == Op_CompareAndExchangeB) ||
3142 (bol->in(1)->Opcode() == Op_CompareAndExchangeS) ||
3143 (bol->in(1)->Opcode() == Op_CompareAndExchangeI) ||
3144 (bol->in(1)->Opcode() == Op_CompareAndExchangeL) ||
3145 (bol->in(1)->Opcode() == Op_CompareAndExchangeP) ||
3146 (bol->in(1)->Opcode() == Op_CompareAndExchangeN) ||
3147 (bol->in(1)->Opcode() == Op_WeakCompareAndSwapB) ||
3148 (bol->in(1)->Opcode() == Op_WeakCompareAndSwapS) ||
3149 (bol->in(1)->Opcode() == Op_WeakCompareAndSwapI) ||
3150 (bol->in(1)->Opcode() == Op_WeakCompareAndSwapL) ||
3151 (bol->in(1)->Opcode() == Op_WeakCompareAndSwapP) ||
3152 (bol->in(1)->Opcode() == Op_WeakCompareAndSwapN) ||
3153 (bol->in(1)->Opcode() == Op_CompareAndSwapB) ||
3154 (bol->in(1)->Opcode() == Op_CompareAndSwapS) ||
3155 (bol->in(1)->Opcode() == Op_CompareAndSwapI) ||
3156 (bol->in(1)->Opcode() == Op_CompareAndSwapL) ||
3157 (bol->in(1)->Opcode() == Op_CompareAndSwapP) ||
3158 (bol->in(1)->Opcode() == Op_CompareAndSwapN)))
3159 return; // Allocation loops RARELY take backedge
3160 // Find the OTHER exit path from the IF
3161 Node* ex = iff->proj_out(1-test_con);
3162 float p = iff->_prob;
3163 if (!phase->is_member(this, ex) && iff->_fcnt == COUNT_UNKNOWN) {
3164 if (top == Op_IfTrue) {
3165 if (p < (PROB_FAIR + PROB_UNLIKELY_MAG(3))) {
3166 iff->_prob = PROB_STATIC_FREQUENT;
3167 }
3168 } else {
3169 if (p > (PROB_FAIR - PROB_UNLIKELY_MAG(3))) {
3170 iff->_prob = PROB_STATIC_INFREQUENT;
3171 }
3172 }
3173 }
3174 }
3175 }
3176 test = phase->idom(test);
3177 }
3178 }
3179
3180 static CountedLoopNode* locate_pre_from_main(CountedLoopNode* main_loop) {
3181 assert(!main_loop->is_main_no_pre_loop(), "Does not have a pre loop");
3182 Node* ctrl = main_loop->skip_assertion_predicates_with_halt();
3183 assert(ctrl->Opcode() == Op_IfTrue || ctrl->Opcode() == Op_IfFalse, "");
3184 Node* iffm = ctrl->in(0);
3185 assert(iffm->Opcode() == Op_If, "%s", iffm->Name());
3186 Node* p_f = iffm->in(0);
3187 // Skip ReachabilityFences hoisted out of pre-loop.
3188 while (p_f->is_ReachabilityFence()) {
3189 p_f = p_f->in(0);
3190 }
3191 assert(p_f->Opcode() == Op_IfFalse, "%s", p_f->Name());
3192 CountedLoopNode* pre_loop = p_f->in(0)->as_CountedLoopEnd()->loopnode();
3193 assert(pre_loop->is_pre_loop(), "No pre loop found");
3194 return pre_loop;
3195 }
3196
3197 // Remove the main and post loops and make the pre loop execute all
3198 // iterations. Useful when the pre loop is found empty.
3199 void IdealLoopTree::remove_main_post_loops(CountedLoopNode *cl, PhaseIdealLoop *phase) {
3200 CountedLoopEndNode* pre_end = cl->loopexit();
3201 Node* pre_cmp = pre_end->cmp_node();
3202 if (pre_cmp->in(2)->Opcode() != Op_Opaque1) {
3203 // Only safe to remove the main loop if the compiler optimized it
3204 // out based on an unknown number of iterations
3205 return;
3206 }
3207
3208 // Can we find the main loop?
3209 if (_next == nullptr) {
3210 return;
3211 }
3212
3213 Node* next_head = _next->_head;
3214 if (!next_head->is_CountedLoop()) {
3215 return;
3216 }
3217
3218 CountedLoopNode* main_head = next_head->as_CountedLoop();
3219 if (!main_head->is_main_loop() || main_head->is_main_no_pre_loop()) {
3220 return;
3221 }
3222
3223 // We found a main-loop after this pre-loop, but they might not belong together.
3224 if (locate_pre_from_main(main_head) != cl) {
3225 return;
3226 }
3227
3228 Node* main_iff = main_head->skip_assertion_predicates_with_halt()->in(0);
3229
3230 // Remove the Opaque1Node of the pre loop and make it execute all iterations
3231 phase->_igvn.replace_input_of(pre_cmp, 2, pre_cmp->in(2)->in(2));
3232 // Remove the OpaqueZeroTripGuardNode of the main loop so it can be optimized out
3233 Node* main_cmp = main_iff->in(1)->in(1);
3234 assert(main_cmp->in(2)->Opcode() == Op_OpaqueZeroTripGuard, "main loop has no opaque node?");
3235 phase->_igvn.replace_input_of(main_cmp, 2, main_cmp->in(2)->in(1));
3236 }
3237
3238 //------------------------------do_remove_empty_loop---------------------------
3239 // We always attempt remove empty loops. The approach is to replace the trip
3240 // counter with the value it will have on the last iteration. This will break
3241 // the loop.
3242 bool IdealLoopTree::do_remove_empty_loop(PhaseIdealLoop *phase) {
3243 if (!_head->is_CountedLoop()) {
3244 return false; // Dead loop
3245 }
3246 if (!empty_loop_candidate(phase)) {
3247 return false;
3248 }
3249 CountedLoopNode *cl = _head->as_CountedLoop();
3250 #ifdef ASSERT
3251 // Call collect_loop_core_nodes to exercise the assert that checks that it finds the right number of nodes
3252 if (empty_loop_with_extra_nodes_candidate(phase)) {
3253 Unique_Node_List wq;
3254 collect_loop_core_nodes(phase, wq);
3255 }
3256 #endif
3257 // Minimum size must be empty loop
3258 if (_body.size() > EMPTY_LOOP_SIZE) {
3259 // This loop has more nodes than an empty loop but, maybe they are only kept alive by the outer strip mined loop's
3260 // safepoint. If they go away once the safepoint is removed, that loop is empty.
3261 if (!empty_loop_with_data_nodes(phase)) {
3262 return false;
3263 }
3264 }
3265 phase->C->print_method(PHASE_BEFORE_REMOVE_EMPTY_LOOP, 4, cl);
3266 if (cl->is_pre_loop()) {
3267 // If the loop we are removing is a pre-loop then the main and post loop
3268 // can be removed as well.
3269 remove_main_post_loops(cl, phase);
3270 }
3271
3272 #ifdef ASSERT
3273 // Ensure at most one used phi exists, which is the iv.
3274 Node* iv = nullptr;
3275 for (DUIterator_Fast imax, i = cl->fast_outs(imax); i < imax; i++) {
3276 Node* n = cl->fast_out(i);
3277 if ((n->Opcode() == Op_Phi) && (n->outcnt() > 0)) {
3278 assert(iv == nullptr, "Too many phis");
3279 iv = n;
3280 }
3281 }
3282 assert(iv == cl->phi(), "Wrong phi");
3283 #endif
3284
3285 // main and post loops have explicitly created zero trip guard
3286 bool needs_guard = !cl->is_main_loop() && !cl->is_post_loop();
3287 if (needs_guard) {
3288 // Skip guard if values not overlap.
3289 const TypeInt* init_t = phase->_igvn.type(cl->init_trip())->is_int();
3290 const TypeInt* limit_t = phase->_igvn.type(cl->limit())->is_int();
3291 int stride_con = cl->stride_con();
3292 if (stride_con > 0) {
3293 needs_guard = (init_t->_hi >= limit_t->_lo);
3294 } else {
3295 needs_guard = (init_t->_lo <= limit_t->_hi);
3296 }
3297 }
3298 if (needs_guard) {
3299 // Check for an obvious zero trip guard.
3300 Predicates predicates(cl->skip_strip_mined()->in(LoopNode::EntryControl));
3301 Node* in_ctrl = predicates.entry();
3302 if (in_ctrl->Opcode() == Op_IfTrue || in_ctrl->Opcode() == Op_IfFalse) {
3303 bool maybe_swapped = (in_ctrl->Opcode() == Op_IfFalse);
3304 // The test should look like just the backedge of a CountedLoop
3305 Node* iff = in_ctrl->in(0);
3306 if (iff->is_If()) {
3307 Node* bol = iff->in(1);
3308 if (bol->is_Bool()) {
3309 BoolTest test = bol->as_Bool()->_test;
3310 if (maybe_swapped) {
3311 test._test = test.commute();
3312 test._test = test.negate();
3313 }
3314 if (test._test == cl->loopexit()->test_trip()) {
3315 Node* cmp = bol->in(1);
3316 int init_idx = maybe_swapped ? 2 : 1;
3317 int limit_idx = maybe_swapped ? 1 : 2;
3318 if (cmp->is_Cmp() && cmp->in(init_idx) == cl->init_trip() && cmp->in(limit_idx) == cl->limit()) {
3319 needs_guard = false;
3320 }
3321 }
3322 }
3323 }
3324 }
3325 }
3326
3327 #ifndef PRODUCT
3328 if (PrintOpto) {
3329 tty->print("Removing empty loop with%s zero trip guard", needs_guard ? "out" : "");
3330 this->dump_head();
3331 } else if (TraceLoopOpts) {
3332 tty->print("Empty with%s zero trip guard ", needs_guard ? "out" : "");
3333 this->dump_head();
3334 }
3335 #endif
3336
3337 if (needs_guard) {
3338 if (LoopPeeling == 0) {
3339 #ifndef PRODUCT
3340 if (TraceLoopOpts) {
3341 tty->print("Empty loop not removed since LoopPeeling is always disabled");
3342 this->dump_head();
3343 }
3344 #endif
3345 return false;
3346 }
3347 // Peel the loop to ensure there's a zero trip guard
3348 Node_List old_new;
3349 phase->do_peeling(this, old_new);
3350 }
3351
3352 // Replace the phi at loop head with the final value of the last
3353 // iteration (exact_limit - stride), to make sure the loop exit value
3354 // is correct, for any users after the loop.
3355 // Note: the final value after increment should not overflow since
3356 // counted loop has limit check predicate.
3357 Node* phi = cl->phi();
3358 Node* exact_limit = phase->exact_limit(this);
3359
3360 // We need to pin the exact limit to prevent it from floating above the zero trip guard.
3361 Node* cast_ii = ConstraintCastNode::make_cast_for_basic_type(
3362 cl->in(LoopNode::EntryControl), exact_limit,
3363 phase->_igvn.type(exact_limit),
3364 ConstraintCastNode::DependencyType::NonFloatingNonNarrowing, T_INT);
3365 phase->register_new_node(cast_ii, cl->in(LoopNode::EntryControl));
3366
3367 Node* final_iv = new SubINode(cast_ii, cl->stride());
3368 phase->register_new_node(final_iv, cl->in(LoopNode::EntryControl));
3369 phase->_igvn.replace_node(phi, final_iv);
3370
3371 // Set loop-exit condition to false. Then the CountedLoopEnd will collapse,
3372 // because the back edge is never taken.
3373 Node* zero = phase->_igvn.intcon(0);
3374 phase->_igvn.replace_input_of(cl->loopexit(), CountedLoopEndNode::TestValue, zero);
3375
3376 phase->C->set_major_progress();
3377 phase->C->print_method(PHASE_AFTER_REMOVE_EMPTY_LOOP, 4, final_iv);
3378 return true;
3379 }
3380
3381 bool IdealLoopTree::empty_loop_candidate(PhaseIdealLoop* phase) const {
3382 CountedLoopNode *cl = _head->as_CountedLoop();
3383 if (!cl->is_valid_counted_loop(T_INT)) {
3384 return false; // Malformed loop
3385 }
3386 if (!phase->ctrl_is_member(this, cl->loopexit()->in(CountedLoopEndNode::TestValue))) {
3387 return false; // Infinite loop
3388 }
3389 return true;
3390 }
3391
3392 bool IdealLoopTree::empty_loop_with_data_nodes(PhaseIdealLoop* phase) const {
3393 CountedLoopNode* cl = _head->as_CountedLoop();
3394 if (!cl->is_strip_mined() || !empty_loop_with_extra_nodes_candidate(phase)) {
3395 return false;
3396 }
3397 Unique_Node_List empty_loop_nodes;
3398 Unique_Node_List wq;
3399
3400 // Start from all data nodes in the loop body that are not one of the EMPTY_LOOP_SIZE nodes expected in an empty body
3401 enqueue_data_nodes(phase, empty_loop_nodes, wq);
3402 // and now follow uses
3403 for (uint i = 0; i < wq.size(); ++i) {
3404 Node* n = wq.at(i);
3405 for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++) {
3406 Node* u = n->fast_out(j);
3407 if (u->Opcode() == Op_SafePoint) {
3408 // found a safepoint. Maybe this loop's safepoint or another loop safepoint.
3409 if (!process_safepoint(phase, empty_loop_nodes, wq, u)) {
3410 return false;
3411 }
3412 } else {
3413 const Type* u_t = phase->_igvn.type(u);
3414 if (u_t == Type::CONTROL || u_t == Type::MEMORY || u_t == Type::ABIO) {
3415 // found a side effect
3416 return false;
3417 }
3418 wq.push(u);
3419 }
3420 }
3421 }
3422 // Nodes (ignoring the EMPTY_LOOP_SIZE nodes of the "core" of the loop) are kept alive by otherwise empty loops'
3423 // safepoints: kill them.
3424 for (uint i = 0; i < wq.size(); ++i) {
3425 Node* n = wq.at(i);
3426 phase->_igvn.replace_node(n, phase->C->top());
3427 }
3428
3429 #ifdef ASSERT
3430 for (uint i = 0; i < _body.size(); ++i) {
3431 Node* n = _body.at(i);
3432 assert(wq.member(n) || empty_loop_nodes.member(n), "missed a node in the body?");
3433 }
3434 #endif
3435
3436 return true;
3437 }
3438
3439 bool IdealLoopTree::process_safepoint(PhaseIdealLoop* phase, Unique_Node_List& empty_loop_nodes, Unique_Node_List& wq,
3440 Node* sfpt) const {
3441 CountedLoopNode* cl = _head->as_CountedLoop();
3442 if (cl->outer_safepoint() == sfpt) {
3443 // the current loop's safepoint
3444 return true;
3445 }
3446
3447 // Some other loop's safepoint. Maybe that loop is empty too.
3448 IdealLoopTree* sfpt_loop = phase->get_loop(sfpt);
3449 if (!sfpt_loop->_head->is_OuterStripMinedLoop()) {
3450 return false;
3451 }
3452 IdealLoopTree* sfpt_inner_loop = sfpt_loop->_child;
3453 CountedLoopNode* sfpt_cl = sfpt_inner_loop->_head->as_CountedLoop();
3454 assert(sfpt_cl->is_strip_mined(), "inconsistent");
3455
3456 if (empty_loop_nodes.member(sfpt_cl)) {
3457 // already taken care of
3458 return true;
3459 }
3460
3461 if (!sfpt_inner_loop->empty_loop_candidate(phase) || !sfpt_inner_loop->empty_loop_with_extra_nodes_candidate(phase)) {
3462 return false;
3463 }
3464
3465 // Enqueue the nodes of that loop for processing too
3466 sfpt_inner_loop->enqueue_data_nodes(phase, empty_loop_nodes, wq);
3467 return true;
3468 }
3469
3470 bool IdealLoopTree::empty_loop_with_extra_nodes_candidate(PhaseIdealLoop* phase) const {
3471 CountedLoopNode *cl = _head->as_CountedLoop();
3472 // No other control flow node in the loop body
3473 if (cl->loopexit()->in(0) != cl) {
3474 return false;
3475 }
3476
3477 if (phase->ctrl_is_member(this, cl->limit())) {
3478 return false;
3479 }
3480 return true;
3481 }
3482
3483 void IdealLoopTree::enqueue_data_nodes(PhaseIdealLoop* phase, Unique_Node_List& empty_loop_nodes,
3484 Unique_Node_List& wq) const {
3485 collect_loop_core_nodes(phase, empty_loop_nodes);
3486 for (uint i = 0; i < _body.size(); ++i) {
3487 Node* n = _body.at(i);
3488 if (!empty_loop_nodes.member(n)) {
3489 wq.push(n);
3490 }
3491 }
3492 }
3493
3494 // This collects the node that would be left if this body was empty
3495 void IdealLoopTree::collect_loop_core_nodes(PhaseIdealLoop* phase, Unique_Node_List& wq) const {
3496 uint before = wq.size();
3497 wq.push(_head->in(LoopNode::LoopBackControl));
3498 for (uint i = before; i < wq.size(); ++i) {
3499 Node* n = wq.at(i);
3500 for (uint j = 0; j < n->req(); ++j) {
3501 Node* in = n->in(j);
3502 if (in != nullptr) {
3503 if (phase->get_loop(phase->ctrl_or_self(in)) == this) {
3504 wq.push(in);
3505 }
3506 }
3507 }
3508 }
3509 assert(wq.size() - before == EMPTY_LOOP_SIZE, "expect the EMPTY_LOOP_SIZE nodes of this body if empty");
3510 }
3511
3512 //------------------------------do_one_iteration_loop--------------------------
3513 // Convert one-iteration loop into normal code.
3514 bool IdealLoopTree::do_one_iteration_loop(PhaseIdealLoop *phase) {
3515 if (!_head->as_Loop()->is_valid_counted_loop(T_INT)) {
3516 return false; // Only for counted loop
3517 }
3518 CountedLoopNode *cl = _head->as_CountedLoop();
3519 if (!cl->has_exact_trip_count() || cl->trip_count() != 1) {
3520 return false;
3521 }
3522
3523 #ifndef PRODUCT
3524 if (TraceLoopOpts) {
3525 tty->print("OneIteration ");
3526 this->dump_head();
3527 }
3528 #endif
3529
3530 phase->C->print_method(PHASE_BEFORE_ONE_ITERATION_LOOP, 4, cl);
3531 Node *init_n = cl->init_trip();
3532 // Loop boundaries should be constant since trip count is exact.
3533 assert((cl->stride_con() > 0 && init_n->get_int() + cl->stride_con() >= cl->limit()->get_int()) ||
3534 (cl->stride_con() < 0 && init_n->get_int() + cl->stride_con() <= cl->limit()->get_int()), "should be one iteration");
3535 // Replace the phi at loop head with the value of the init_trip.
3536 // Then the CountedLoopEnd will collapse (backedge will not be taken)
3537 // and all loop-invariant uses of the exit values will be correct.
3538 phase->_igvn.replace_node(cl->phi(), cl->init_trip());
3539 phase->C->set_major_progress();
3540 phase->C->print_method(PHASE_AFTER_ONE_ITERATION_LOOP, 4, init_n);
3541 return true;
3542 }
3543
3544 //=============================================================================
3545 //------------------------------iteration_split_impl---------------------------
3546 bool IdealLoopTree::iteration_split_impl(PhaseIdealLoop *phase, Node_List &old_new) {
3547 if (!_head->is_Loop()) {
3548 // Head could be a region with a NeverBranch that was added in beautify loops but the region was not
3549 // yet transformed into a LoopNode. Bail out and wait until beautify loops turns it into a Loop node.
3550 return false;
3551 }
3552 // Compute loop trip count if possible.
3553 compute_trip_count(phase, T_INT);
3554
3555 // Convert one-iteration loop into normal code.
3556 if (do_one_iteration_loop(phase)) {
3557 return true;
3558 }
3559 // Check and remove empty loops (spam micro-benchmarks)
3560 if (do_remove_empty_loop(phase)) {
3561 return true; // Here we removed an empty loop
3562 }
3563
3564 AutoNodeBudget node_budget(phase);
3565
3566 // Non-counted loops may be peeled; exactly 1 iteration is peeled.
3567 // This removes loop-invariant tests (usually null checks).
3568 if (!_head->is_CountedLoop()) { // Non-counted loop
3569 if (PartialPeelLoop) {
3570 bool rc = phase->partial_peel(this, old_new);
3571 if (Compile::current()->failing()) { return false; }
3572 if (rc) {
3573 // Partial peel succeeded so terminate this round of loop opts
3574 return false;
3575 }
3576 }
3577 if (policy_peeling(phase)) { // Should we peel?
3578 if (PrintOpto) { tty->print_cr("should_peel"); }
3579 phase->do_peeling(this, old_new);
3580 } else if (policy_unswitching(phase)) {
3581 phase->do_unswitching(this, old_new);
3582 return false; // need to recalculate idom data
3583 } else if (phase->duplicate_loop_backedge(this, old_new)) {
3584 return false;
3585 } else if (_head->is_LongCountedLoop()) {
3586 phase->create_loop_nest(this, old_new);
3587 }
3588 return true;
3589 }
3590 CountedLoopNode *cl = _head->as_CountedLoop();
3591
3592 if (!cl->is_valid_counted_loop(T_INT)) return true; // Ignore various kinds of broken loops
3593
3594 // Do nothing special to pre- and post- loops
3595 if (cl->is_pre_loop() || cl->is_post_loop()) return true;
3596
3597 // With multiversioning, we create a fast_loop and a slow_loop, and a multiversion_if that
3598 // decides which loop is taken at runtime. At first, the multiversion_if always takes the
3599 // fast_loop, and we only optimize the fast_loop. Since we are not sure if we will ever use
3600 // the slow_loop, we delay optimizations for it, so we do not waste compile time and code
3601 // size. If we never change the condition of the multiversion_if, the slow_loop is eventually
3602 // folded away after loop-opts. While optimizing the fast_loop, we may want to perform some
3603 // speculative optimization, for which we need a runtime-check. We add this runtime-check
3604 // condition to the multiversion_if. Now, it becomes possible to execute the slow_loop at
3605 // runtime, and we resume optimizations for slow_loop ("un-delay" it).
3606 // TLDR: If the slow_loop is still in "delay" mode, check if the multiversion_if was changed
3607 // and we should now resume optimizations for it.
3608 if (cl->is_multiversion_delayed_slow_loop() &&
3609 !phase->try_resume_optimizations_for_delayed_slow_loop(this)) {
3610 // We are still delayed, so wait with further loop-opts.
3611 return true;
3612 }
3613
3614 // Compute loop trip count from profile data
3615 compute_profile_trip_cnt(phase);
3616
3617 // Before attempting fancy unrolling, RCE or alignment, see if we want
3618 // to completely unroll this loop or do loop unswitching.
3619 if (cl->is_normal_loop()) {
3620 if (policy_unswitching(phase)) {
3621 phase->do_unswitching(this, old_new);
3622 return false; // need to recalculate idom data
3623 }
3624 if (policy_maximally_unroll(phase)) {
3625 // Here we did some unrolling and peeling. Eventually we will
3626 // completely unroll this loop and it will no longer be a loop.
3627 phase->do_maximally_unroll(this, old_new);
3628 return true;
3629 }
3630 if (StressDuplicateBackedge && phase->duplicate_loop_backedge(this, old_new)) {
3631 return false;
3632 }
3633 }
3634
3635 uint est_peeling = estimate_peeling(phase);
3636 bool should_peel = 0 < est_peeling;
3637
3638 // Counted loops may be peeled, or may need some iterations run up
3639 // front for RCE. Thus we clone a full loop up front whose trip count is
3640 // at least 1 (if peeling), but may be several more.
3641
3642 // The main loop will start cache-line aligned with at least 1
3643 // iteration of the unrolled body (zero-trip test required) and
3644 // will have some range checks removed.
3645
3646 // A post-loop will finish any odd iterations (leftover after
3647 // unrolling), plus any needed for RCE purposes.
3648
3649 bool should_unroll = policy_unroll(phase);
3650 bool should_rce = policy_range_check(phase, false, T_INT);
3651 bool should_rce_long = policy_range_check(phase, false, T_LONG);
3652
3653 // If not RCE'ing (iteration splitting), then we do not need a pre-loop.
3654 // We may still need to peel an initial iteration but we will not
3655 // be needing an unknown number of pre-iterations.
3656 //
3657 // Basically, if peel_only reports TRUE first time through, we will not
3658 // be able to later do RCE on this loop.
3659 bool peel_only = policy_peel_only(phase) && !should_rce;
3660
3661 // If we have any of these conditions (RCE, unrolling) met, then
3662 // we switch to the pre-/main-/post-loop model. This model also covers
3663 // peeling.
3664 if (should_rce || should_unroll) {
3665 if (cl->is_normal_loop()) { // Convert to 'pre/main/post' loops
3666 if (should_rce_long && phase->create_loop_nest(this, old_new)) {
3667 return true;
3668 }
3669 uint estimate = est_loop_clone_sz(3);
3670 if (!phase->may_require_nodes(estimate)) {
3671 return false;
3672 }
3673
3674 if (!peel_only) {
3675 // We are going to add pre-loop and post-loop (PreMainPost).
3676 // But should we also multiversion for auto-vectorization speculative
3677 // checks, i.e. fast and slow-paths?
3678 // Note: Just PeelMainPost is not sufficient, as we could never find the
3679 // multiversion_if again from the main loop: we need a nicely structured
3680 // pre-loop, a peeled iteration cannot easily be parsed through.
3681 phase->maybe_multiversion_for_auto_vectorization_runtime_checks(this, old_new);
3682 }
3683
3684 phase->insert_pre_post_loops(this, old_new, peel_only);
3685 }
3686 // Adjust the pre- and main-loop limits to let the pre and post loops run
3687 // with full checks, but the main-loop with no checks. Remove said checks
3688 // from the main body.
3689 if (should_rce) {
3690 phase->do_range_check(this);
3691 }
3692
3693 // Double loop body for unrolling. Adjust the minimum-trip test (will do
3694 // twice as many iterations as before) and the main body limit (only do
3695 // an even number of trips). If we are peeling, we might enable some RCE
3696 // and we'd rather unroll the post-RCE'd loop SO... do not unroll if
3697 // peeling.
3698 if (should_unroll && !should_peel) {
3699 if (SuperWordLoopUnrollAnalysis) {
3700 phase->insert_vector_post_loop(this, old_new);
3701 }
3702 phase->do_unroll(this, old_new, true);
3703 }
3704 } else { // Else we have an unchanged counted loop
3705 if (should_peel) { // Might want to peel but do nothing else
3706 if (phase->may_require_nodes(est_peeling)) {
3707 phase->do_peeling(this, old_new);
3708 }
3709 }
3710 if (should_rce_long) {
3711 phase->create_loop_nest(this, old_new);
3712 }
3713 }
3714 return true;
3715 }
3716
3717
3718 //=============================================================================
3719 //------------------------------iteration_split--------------------------------
3720 bool IdealLoopTree::iteration_split(PhaseIdealLoop* phase, Node_List &old_new) {
3721 // Recursively iteration split nested loops
3722 if (_child && !_child->iteration_split(phase, old_new)) {
3723 return false;
3724 }
3725
3726 // Clean out prior deadwood
3727 DCE_loop_body();
3728
3729 // Look for loop-exit tests with my 50/50 guesses from the Parsing stage.
3730 // Replace with a 1-in-10 exit guess.
3731 if (!is_root() && is_loop()) {
3732 adjust_loop_exit_prob(phase);
3733 }
3734
3735 // Unrolling, RCE and peeling efforts, iff innermost loop.
3736 if (_allow_optimizations && is_innermost()) {
3737 if (!_has_call) {
3738 if (!iteration_split_impl(phase, old_new)) {
3739 return false;
3740 }
3741 } else {
3742 AutoNodeBudget node_budget(phase);
3743 if (policy_unswitching(phase)) {
3744 phase->do_unswitching(this, old_new);
3745 return false; // need to recalculate idom data
3746 }
3747 }
3748 }
3749
3750 if (_next && !_next->iteration_split(phase, old_new)) {
3751 return false;
3752 }
3753 return true;
3754 }
3755
3756
3757 //=============================================================================
3758 // Process all the loops in the loop tree and replace any fill
3759 // patterns with an intrinsic version.
3760 bool PhaseIdealLoop::do_intrinsify_fill() {
3761 bool changed = false;
3762 for (LoopTreeIterator iter(_ltree_root); !iter.done(); iter.next()) {
3763 IdealLoopTree* lpt = iter.current();
3764 changed |= intrinsify_fill(lpt);
3765 }
3766 return changed;
3767 }
3768
3769
3770 // Examine an inner loop looking for a single store of an invariant
3771 // value in a unit stride loop,
3772 bool PhaseIdealLoop::match_fill_loop(IdealLoopTree* lpt, Node*& store, Node*& store_value,
3773 Node*& shift, Node*& con) {
3774 const char* msg = nullptr;
3775 Node* msg_node = nullptr;
3776
3777 store_value = nullptr;
3778 con = nullptr;
3779 shift = nullptr;
3780
3781 // Process the loop looking for stores. If there are multiple
3782 // stores or extra control flow give at this point.
3783 CountedLoopNode* head = lpt->_head->as_CountedLoop();
3784 for (uint i = 0; msg == nullptr && i < lpt->_body.size(); i++) {
3785 Node* n = lpt->_body.at(i);
3786 if (n->outcnt() == 0) continue; // Ignore dead
3787 if (n->is_Store()) {
3788 if (store != nullptr) {
3789 msg = "multiple stores";
3790 break;
3791 }
3792 int opc = n->Opcode();
3793 if (opc == Op_StoreP || opc == Op_StoreN || opc == Op_StoreNKlass) {
3794 msg = "oop fills not handled";
3795 break;
3796 }
3797 Node* value = n->in(MemNode::ValueIn);
3798 if (!lpt->is_invariant(value)) {
3799 msg = "variant store value";
3800 } else if (!_igvn.type(n->in(MemNode::Address))->isa_aryptr()) {
3801 msg = "not array address";
3802 }
3803 store = n;
3804 store_value = value;
3805 } else if (n->is_If() && n != head->loopexit_or_null()) {
3806 msg = "extra control flow";
3807 msg_node = n;
3808 }
3809 }
3810
3811 if (store == nullptr) {
3812 // No store in loop
3813 return false;
3814 }
3815
3816 if (msg == nullptr && store->as_Mem()->is_mismatched_access()) {
3817 // This optimization does not currently support mismatched stores, where the
3818 // type of the value to be stored differs from the element type of the
3819 // destination array. Such patterns arise for example from memory segment
3820 // initialization. This limitation could be overcome by extending this
3821 // function's address matching logic and ensuring that the fill intrinsic
3822 // implementations support mismatched array filling.
3823 msg = "mismatched store";
3824 }
3825
3826 if (msg == nullptr && head->stride_con() != 1) {
3827 // could handle negative strides too
3828 if (head->stride_con() < 0) {
3829 msg = "negative stride";
3830 } else {
3831 msg = "non-unit stride";
3832 }
3833 }
3834
3835 if (msg == nullptr && !store->in(MemNode::Address)->is_AddP()) {
3836 msg = "can't handle store address";
3837 msg_node = store->in(MemNode::Address);
3838 }
3839
3840 if (msg == nullptr &&
3841 (!store->in(MemNode::Memory)->is_Phi() ||
3842 store->in(MemNode::Memory)->in(LoopNode::LoopBackControl) != store)) {
3843 msg = "store memory isn't proper phi";
3844 msg_node = store->in(MemNode::Memory);
3845 }
3846
3847 // Make sure there is an appropriate fill routine
3848 BasicType t = msg == nullptr ?
3849 store->adr_type()->isa_aryptr()->elem()->array_element_basic_type() : T_VOID;
3850 const char* fill_name;
3851 if (msg == nullptr &&
3852 StubRoutines::select_fill_function(t, false, fill_name) == nullptr) {
3853 msg = "unsupported store";
3854 msg_node = store;
3855 }
3856
3857 if (msg != nullptr) {
3858 #ifndef PRODUCT
3859 if (TraceOptimizeFill) {
3860 tty->print_cr("not fill intrinsic candidate: %s", msg);
3861 if (msg_node != nullptr) msg_node->dump();
3862 }
3863 #endif
3864 return false;
3865 }
3866
3867 // Make sure the address expression can be handled. It should be
3868 // head->phi * elsize + con. head->phi might have a ConvI2L(CastII()).
3869 Node* elements[4];
3870 Node* cast = nullptr;
3871 Node* conv = nullptr;
3872 bool found_index = false;
3873 int count = store->in(MemNode::Address)->as_AddP()->unpack_offsets(elements, ARRAY_SIZE(elements));
3874 for (int e = 0; e < count; e++) {
3875 Node* n = elements[e];
3876 if (n->is_Con() && con == nullptr) {
3877 con = n;
3878 } else if (n->Opcode() == Op_LShiftX && shift == nullptr) {
3879 Node* value = n->in(1);
3880 #ifdef _LP64
3881 if (value->Opcode() == Op_ConvI2L) {
3882 conv = value;
3883 value = value->in(1);
3884 }
3885 if (value->Opcode() == Op_CastII &&
3886 value->as_CastII()->has_range_check()) {
3887 // Skip range check dependent CastII nodes
3888 cast = value;
3889 value = value->in(1);
3890 }
3891 #endif
3892 if (value != head->phi()) {
3893 msg = "unhandled shift in address";
3894 } else {
3895 if (type2aelembytes(t, true) != (1 << n->in(2)->get_int())) {
3896 msg = "scale doesn't match";
3897 } else {
3898 found_index = true;
3899 shift = n;
3900 }
3901 }
3902 } else if (n->Opcode() == Op_ConvI2L && conv == nullptr) {
3903 conv = n;
3904 n = n->in(1);
3905 if (n->Opcode() == Op_CastII &&
3906 n->as_CastII()->has_range_check()) {
3907 // Skip range check dependent CastII nodes
3908 cast = n;
3909 n = n->in(1);
3910 }
3911 if (n == head->phi()) {
3912 found_index = true;
3913 } else {
3914 msg = "unhandled input to ConvI2L";
3915 }
3916 } else if (n == head->phi()) {
3917 // no shift, check below for allowed cases
3918 found_index = true;
3919 } else {
3920 msg = "unhandled node in address";
3921 msg_node = n;
3922 }
3923 }
3924
3925 if (count == -1) {
3926 msg = "malformed address expression";
3927 msg_node = store;
3928 }
3929
3930 if (!found_index) {
3931 msg = "missing use of index";
3932 }
3933
3934 // byte sized items won't have a shift
3935 if (msg == nullptr && shift == nullptr && t != T_BYTE && t != T_BOOLEAN) {
3936 msg = "can't find shift";
3937 msg_node = store;
3938 }
3939
3940 if (msg != nullptr) {
3941 #ifndef PRODUCT
3942 if (TraceOptimizeFill) {
3943 tty->print_cr("not fill intrinsic: %s", msg);
3944 if (msg_node != nullptr) msg_node->dump();
3945 }
3946 #endif
3947 return false;
3948 }
3949
3950 // No make sure all the other nodes in the loop can be handled
3951 VectorSet ok;
3952
3953 // store related values are ok
3954 ok.set(store->_idx);
3955 ok.set(store->in(MemNode::Memory)->_idx);
3956
3957 CountedLoopEndNode* loop_exit = head->loopexit();
3958
3959 // Loop structure is ok
3960 ok.set(head->_idx);
3961 ok.set(loop_exit->_idx);
3962 ok.set(head->phi()->_idx);
3963 ok.set(head->incr()->_idx);
3964 ok.set(loop_exit->cmp_node()->_idx);
3965 ok.set(loop_exit->in(1)->_idx);
3966
3967 // Address elements are ok
3968 if (con) ok.set(con->_idx);
3969 if (shift) ok.set(shift->_idx);
3970 if (cast) ok.set(cast->_idx);
3971 if (conv) ok.set(conv->_idx);
3972
3973 for (uint i = 0; msg == nullptr && i < lpt->_body.size(); i++) {
3974 Node* n = lpt->_body.at(i);
3975 if (n->outcnt() == 0) continue; // Ignore dead
3976 if (ok.test(n->_idx)) continue;
3977 // Backedge projection is ok
3978 if (n->is_IfTrue() && n->in(0) == loop_exit) continue;
3979 if (!n->is_AddP()) {
3980 msg = "unhandled node";
3981 msg_node = n;
3982 break;
3983 }
3984 }
3985
3986 // Make sure no unexpected values are used outside the loop
3987 for (uint i = 0; msg == nullptr && i < lpt->_body.size(); i++) {
3988 Node* n = lpt->_body.at(i);
3989 // These values can be replaced with other nodes if they are used
3990 // outside the loop.
3991 if (n == store || n == loop_exit || n == head->incr() || n == store->in(MemNode::Memory)) continue;
3992 for (SimpleDUIterator iter(n); iter.has_next(); iter.next()) {
3993 Node* use = iter.get();
3994 if (!lpt->_body.contains(use)) {
3995 msg = "node is used outside loop";
3996 msg_node = n;
3997 break;
3998 }
3999 }
4000 }
4001
4002 #ifdef ASSERT
4003 if (TraceOptimizeFill) {
4004 if (msg != nullptr) {
4005 tty->print_cr("no fill intrinsic: %s", msg);
4006 if (msg_node != nullptr) msg_node->dump();
4007 } else {
4008 tty->print_cr("fill intrinsic for:");
4009 }
4010 store->dump();
4011 if (Verbose) {
4012 lpt->_body.dump();
4013 }
4014 }
4015 #endif
4016
4017 return msg == nullptr;
4018 }
4019
4020
4021
4022 bool PhaseIdealLoop::intrinsify_fill(IdealLoopTree* lpt) {
4023 // Only for counted inner loops
4024 if (!lpt->is_counted() || !lpt->is_innermost()) {
4025 return false;
4026 }
4027
4028 // Must have constant stride
4029 CountedLoopNode* head = lpt->_head->as_CountedLoop();
4030 if (!head->is_valid_counted_loop(T_INT) || !head->is_normal_loop()) {
4031 return false;
4032 }
4033
4034 head->verify_strip_mined(1);
4035
4036 // Check that the body only contains a store of a loop invariant
4037 // value that is indexed by the loop phi.
4038 Node* store = nullptr;
4039 Node* store_value = nullptr;
4040 Node* shift = nullptr;
4041 Node* offset = nullptr;
4042 if (!match_fill_loop(lpt, store, store_value, shift, offset)) {
4043 return false;
4044 }
4045
4046 IfFalseNode* exit = head->loopexit()->false_proj_or_null();
4047 if (exit == nullptr) {
4048 return false;
4049 }
4050
4051 #ifndef PRODUCT
4052 if (TraceLoopOpts) {
4053 tty->print("ArrayFill ");
4054 lpt->dump_head();
4055 }
4056 #endif
4057
4058 // Now replace the whole loop body by a call to a fill routine that
4059 // covers the same region as the loop.
4060 Node* base = store->in(MemNode::Address)->as_AddP()->in(AddPNode::Base);
4061
4062 // Build an expression for the beginning of the copy region
4063 Node* index = head->init_trip();
4064 #ifdef _LP64
4065 index = new ConvI2LNode(index);
4066 _igvn.register_new_node_with_optimizer(index);
4067 #endif
4068 if (shift != nullptr) {
4069 // byte arrays don't require a shift but others do.
4070 index = new LShiftXNode(index, shift->in(2));
4071 _igvn.register_new_node_with_optimizer(index);
4072 }
4073 Node* from = AddPNode::make_with_base(base, index);
4074 _igvn.register_new_node_with_optimizer(from);
4075 // For normal array fills, C2 uses two AddP nodes for array element
4076 // addressing. But for array fills with Unsafe call, there's only one
4077 // AddP node adding an absolute offset, so we do a null check here.
4078 assert(offset != nullptr || C->has_unsafe_access(),
4079 "Only array fills with unsafe have no extra offset");
4080 if (offset != nullptr) {
4081 from = AddPNode::make_with_base(base, from, offset);
4082 _igvn.register_new_node_with_optimizer(from);
4083 }
4084 // Compute the number of elements to copy
4085 Node* len = new SubINode(head->limit(), head->init_trip());
4086 _igvn.register_new_node_with_optimizer(len);
4087
4088 // If the store is on the backedge, it is not executed in the last
4089 // iteration, and we must subtract 1 from the len.
4090 IfTrueNode* backedge = head->loopexit()->true_proj();
4091 if (store->in(0) == backedge) {
4092 len = new SubINode(len, _igvn.intcon(1));
4093 _igvn.register_new_node_with_optimizer(len);
4094 #ifndef PRODUCT
4095 if (TraceOptimizeFill) {
4096 tty->print_cr("ArrayFill store on backedge, subtract 1 from len.");
4097 }
4098 #endif
4099 }
4100
4101 BasicType t = store->adr_type()->isa_aryptr()->elem()->array_element_basic_type();
4102 bool aligned = false;
4103 if (offset != nullptr && head->init_trip()->is_Con()) {
4104 int element_size = type2aelembytes(t);
4105 aligned = (offset->find_intptr_t_type()->get_con() + head->init_trip()->get_int() * element_size) % HeapWordSize == 0;
4106 }
4107
4108 // Build a call to the fill routine
4109 const char* fill_name;
4110 address fill = StubRoutines::select_fill_function(t, aligned, fill_name);
4111 assert(fill != nullptr, "what?");
4112
4113 // Convert float/double to int/long for fill routines
4114 if (t == T_FLOAT) {
4115 store_value = new MoveF2INode(store_value);
4116 _igvn.register_new_node_with_optimizer(store_value);
4117 } else if (t == T_DOUBLE) {
4118 store_value = new MoveD2LNode(store_value);
4119 _igvn.register_new_node_with_optimizer(store_value);
4120 }
4121
4122 Node* mem_phi = store->in(MemNode::Memory);
4123 Node* result_ctrl;
4124 Node* result_mem;
4125 const TypeFunc* call_type = OptoRuntime::array_fill_Type();
4126 CallLeafNode *call = new CallLeafNoFPNode(call_type, fill,
4127 fill_name, TypeAryPtr::get_array_body_type(t));
4128 uint cnt = 0;
4129 call->init_req(TypeFunc::Parms + cnt++, from);
4130 call->init_req(TypeFunc::Parms + cnt++, store_value);
4131 #ifdef _LP64
4132 len = new ConvI2LNode(len);
4133 _igvn.register_new_node_with_optimizer(len);
4134 #endif
4135 call->init_req(TypeFunc::Parms + cnt++, len);
4136 #ifdef _LP64
4137 call->init_req(TypeFunc::Parms + cnt++, C->top());
4138 #endif
4139 call->init_req(TypeFunc::Control, head->init_control());
4140 call->init_req(TypeFunc::I_O, C->top()); // Does no I/O.
4141 call->init_req(TypeFunc::Memory, mem_phi->in(LoopNode::EntryControl));
4142 call->init_req(TypeFunc::ReturnAdr, C->top());
4143 Node* frame = new ParmNode(C->start(), TypeFunc::FramePtr);
4144 _igvn.register_new_node_with_optimizer(frame);
4145 call->init_req(TypeFunc::FramePtr, frame);
4146 _igvn.register_new_node_with_optimizer(call);
4147 result_ctrl = new ProjNode(call,TypeFunc::Control);
4148 _igvn.register_new_node_with_optimizer(result_ctrl);
4149 result_mem = new ProjNode(call,TypeFunc::Memory);
4150 _igvn.register_new_node_with_optimizer(result_mem);
4151
4152 /* Disable following optimization until proper fix (add missing checks).
4153
4154 // If this fill is tightly coupled to an allocation and overwrites
4155 // the whole body, allow it to take over the zeroing.
4156 AllocateNode* alloc = AllocateNode::Ideal_allocation(base, this);
4157 if (alloc != nullptr && alloc->is_AllocateArray()) {
4158 Node* length = alloc->as_AllocateArray()->Ideal_length();
4159 if (head->limit() == length &&
4160 head->init_trip() == _igvn.intcon(0)) {
4161 if (TraceOptimizeFill) {
4162 tty->print_cr("Eliminated zeroing in allocation");
4163 }
4164 alloc->maybe_set_complete(&_igvn);
4165 } else {
4166 #ifdef ASSERT
4167 if (TraceOptimizeFill) {
4168 tty->print_cr("filling array but bounds don't match");
4169 alloc->dump();
4170 head->init_trip()->dump();
4171 head->limit()->dump();
4172 length->dump();
4173 }
4174 #endif
4175 }
4176 }
4177 */
4178
4179 if (head->is_strip_mined()) {
4180 // Inner strip mined loop goes away so get rid of outer strip
4181 // mined loop
4182 Node* outer_sfpt = head->outer_safepoint();
4183 Node* in = outer_sfpt->in(0);
4184 Node* outer_out = head->outer_loop_exit();
4185 replace_node_and_forward_ctrl(outer_out, in);
4186 _igvn.replace_input_of(outer_sfpt, 0, C->top());
4187 }
4188
4189 // Redirect the old control and memory edges that are outside the loop.
4190 // Sometimes the memory phi of the head is used as the outgoing
4191 // state of the loop. It's safe in this case to replace it with the
4192 // result_mem.
4193 _igvn.replace_node(store->in(MemNode::Memory), result_mem);
4194 replace_node_and_forward_ctrl(exit, result_ctrl);
4195 _igvn.replace_node(store, result_mem);
4196 // Any uses the increment outside of the loop become the loop limit.
4197 _igvn.replace_node(head->incr(), head->limit());
4198
4199 // Disconnect the head from the loop.
4200 for (uint i = 0; i < lpt->_body.size(); i++) {
4201 Node* n = lpt->_body.at(i);
4202 _igvn.replace_node(n, C->top());
4203 }
4204
4205 #ifndef PRODUCT
4206 if (TraceOptimizeFill) {
4207 tty->print("ArrayFill call ");
4208 call->dump();
4209 }
4210 #endif
4211
4212 return true;
4213 }