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