comparison src/share/vm/opto/loopPredicate.cpp @ 2445:08eb13460b3a

7004535: Clone loop predicate during loop unswitch Summary: Clone loop predicate for clonned loops Reviewed-by: never
author kvn
date Sat, 02 Apr 2011 10:54:15 -0700
parents
children 2e038ad0c1d0
comparison
equal deleted inserted replaced
2444:07acc51c1d2a 2445:08eb13460b3a
1 /*
2 * Copyright (c) 2011, 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 "precompiled.hpp"
26 #include "opto/loopnode.hpp"
27 #include "opto/addnode.hpp"
28 #include "opto/callnode.hpp"
29 #include "opto/connode.hpp"
30 #include "opto/loopnode.hpp"
31 #include "opto/mulnode.hpp"
32 #include "opto/rootnode.hpp"
33 #include "opto/subnode.hpp"
34
35 /*
36 * The general idea of Loop Predication is to insert a predicate on the entry
37 * path to a loop, and raise a uncommon trap if the check of the condition fails.
38 * The condition checks are promoted from inside the loop body, and thus
39 * the checks inside the loop could be eliminated. Currently, loop predication
40 * optimization has been applied to remove array range check and loop invariant
41 * checks (such as null checks).
42 */
43
44 //-------------------------------is_uncommon_trap_proj----------------------------
45 // Return true if proj is the form of "proj->[region->..]call_uct"
46 bool PhaseIdealLoop::is_uncommon_trap_proj(ProjNode* proj, Deoptimization::DeoptReason reason) {
47 int path_limit = 10;
48 assert(proj, "invalid argument");
49 Node* out = proj;
50 for (int ct = 0; ct < path_limit; ct++) {
51 out = out->unique_ctrl_out();
52 if (out == NULL)
53 return false;
54 if (out->is_CallStaticJava()) {
55 int req = out->as_CallStaticJava()->uncommon_trap_request();
56 if (req != 0) {
57 Deoptimization::DeoptReason trap_reason = Deoptimization::trap_request_reason(req);
58 if (trap_reason == reason || reason == Deoptimization::Reason_none) {
59 return true;
60 }
61 }
62 return false; // don't do further after call
63 }
64 if (out->Opcode() != Op_Region)
65 return false;
66 }
67 return false;
68 }
69
70 //-------------------------------is_uncommon_trap_if_pattern-------------------------
71 // Return true for "if(test)-> proj -> ...
72 // |
73 // V
74 // other_proj->[region->..]call_uct"
75 //
76 // "must_reason_predicate" means the uct reason must be Reason_predicate
77 bool PhaseIdealLoop::is_uncommon_trap_if_pattern(ProjNode *proj, Deoptimization::DeoptReason reason) {
78 Node *in0 = proj->in(0);
79 if (!in0->is_If()) return false;
80 // Variation of a dead If node.
81 if (in0->outcnt() < 2) return false;
82 IfNode* iff = in0->as_If();
83
84 // we need "If(Conv2B(Opaque1(...)))" pattern for reason_predicate
85 if (reason != Deoptimization::Reason_none) {
86 if (iff->in(1)->Opcode() != Op_Conv2B ||
87 iff->in(1)->in(1)->Opcode() != Op_Opaque1) {
88 return false;
89 }
90 }
91
92 ProjNode* other_proj = iff->proj_out(1-proj->_con)->as_Proj();
93 if (is_uncommon_trap_proj(other_proj, reason)) {
94 assert(reason == Deoptimization::Reason_none ||
95 Compile::current()->is_predicate_opaq(iff->in(1)->in(1)), "should be on the list");
96 return true;
97 }
98 return false;
99 }
100
101 //-------------------------------register_control-------------------------
102 void PhaseIdealLoop::register_control(Node* n, IdealLoopTree *loop, Node* pred) {
103 assert(n->is_CFG(), "must be control node");
104 _igvn.register_new_node_with_optimizer(n);
105 loop->_body.push(n);
106 set_loop(n, loop);
107 // When called from beautify_loops() idom is not constructed yet.
108 if (_idom != NULL) {
109 set_idom(n, pred, dom_depth(pred));
110 }
111 }
112
113 //------------------------------create_new_if_for_predicate------------------------
114 // create a new if above the uct_if_pattern for the predicate to be promoted.
115 //
116 // before after
117 // ---------- ----------
118 // ctrl ctrl
119 // | |
120 // | |
121 // v v
122 // iff new_iff
123 // / \ / \
124 // / \ / \
125 // v v v v
126 // uncommon_proj cont_proj if_uct if_cont
127 // \ | | | |
128 // \ | | | |
129 // v v v | v
130 // rgn loop | iff
131 // | | / \
132 // | | / \
133 // v | v v
134 // uncommon_trap | uncommon_proj cont_proj
135 // \ \ | |
136 // \ \ | |
137 // v v v v
138 // rgn loop
139 // |
140 // |
141 // v
142 // uncommon_trap
143 //
144 //
145 // We will create a region to guard the uct call if there is no one there.
146 // The true projecttion (if_cont) of the new_iff is returned.
147 // This code is also used to clone predicates to clonned loops.
148 ProjNode* PhaseIdealLoop::create_new_if_for_predicate(ProjNode* cont_proj, Node* new_entry,
149 Deoptimization::DeoptReason reason) {
150 assert(is_uncommon_trap_if_pattern(cont_proj, reason), "must be a uct if pattern!");
151 IfNode* iff = cont_proj->in(0)->as_If();
152
153 ProjNode *uncommon_proj = iff->proj_out(1 - cont_proj->_con);
154 Node *rgn = uncommon_proj->unique_ctrl_out();
155 assert(rgn->is_Region() || rgn->is_Call(), "must be a region or call uct");
156
157 uint proj_index = 1; // region's edge corresponding to uncommon_proj
158 if (!rgn->is_Region()) { // create a region to guard the call
159 assert(rgn->is_Call(), "must be call uct");
160 CallNode* call = rgn->as_Call();
161 IdealLoopTree* loop = get_loop(call);
162 rgn = new (C, 1) RegionNode(1);
163 rgn->add_req(uncommon_proj);
164 register_control(rgn, loop, uncommon_proj);
165 _igvn.hash_delete(call);
166 call->set_req(0, rgn);
167 // When called from beautify_loops() idom is not constructed yet.
168 if (_idom != NULL) {
169 set_idom(call, rgn, dom_depth(rgn));
170 }
171 } else {
172 // Find region's edge corresponding to uncommon_proj
173 for (; proj_index < rgn->req(); proj_index++)
174 if (rgn->in(proj_index) == uncommon_proj) break;
175 assert(proj_index < rgn->req(), "sanity");
176 }
177
178 Node* entry = iff->in(0);
179 if (new_entry != NULL) {
180 // Clonning the predicate to new location.
181 entry = new_entry;
182 }
183 // Create new_iff
184 IdealLoopTree* lp = get_loop(entry);
185 IfNode *new_iff = iff->clone()->as_If();
186 new_iff->set_req(0, entry);
187 register_control(new_iff, lp, entry);
188 Node *if_cont = new (C, 1) IfTrueNode(new_iff);
189 Node *if_uct = new (C, 1) IfFalseNode(new_iff);
190 if (cont_proj->is_IfFalse()) {
191 // Swap
192 Node* tmp = if_uct; if_uct = if_cont; if_cont = tmp;
193 }
194 register_control(if_cont, lp, new_iff);
195 register_control(if_uct, get_loop(rgn), new_iff);
196
197 // if_uct to rgn
198 _igvn.hash_delete(rgn);
199 rgn->add_req(if_uct);
200 // When called from beautify_loops() idom is not constructed yet.
201 if (_idom != NULL) {
202 Node* ridom = idom(rgn);
203 Node* nrdom = dom_lca(ridom, new_iff);
204 set_idom(rgn, nrdom, dom_depth(rgn));
205 }
206
207 // If rgn has phis add new edges which has the same
208 // value as on original uncommon_proj pass.
209 assert(rgn->in(rgn->req() -1) == if_uct, "new edge should be last");
210 bool has_phi = false;
211 for (DUIterator_Fast imax, i = rgn->fast_outs(imax); i < imax; i++) {
212 Node* use = rgn->fast_out(i);
213 if (use->is_Phi() && use->outcnt() > 0) {
214 assert(use->in(0) == rgn, "");
215 _igvn.hash_delete(use);
216 use->add_req(use->in(proj_index));
217 _igvn._worklist.push(use);
218 has_phi = true;
219 }
220 }
221 assert(!has_phi || rgn->req() > 3, "no phis when region is created");
222
223 if (new_entry == NULL) {
224 // Attach if_cont to iff
225 _igvn.hash_delete(iff);
226 iff->set_req(0, if_cont);
227 if (_idom != NULL) {
228 set_idom(iff, if_cont, dom_depth(iff));
229 }
230 }
231 return if_cont->as_Proj();
232 }
233
234 //------------------------------create_new_if_for_predicate------------------------
235 // Create a new if below new_entry for the predicate to be cloned (IGVN optimization)
236 ProjNode* PhaseIterGVN::create_new_if_for_predicate(ProjNode* cont_proj, Node* new_entry,
237 Deoptimization::DeoptReason reason) {
238 assert(new_entry != 0, "only used for clone predicate");
239 assert(PhaseIdealLoop::is_uncommon_trap_if_pattern(cont_proj, reason), "must be a uct if pattern!");
240 IfNode* iff = cont_proj->in(0)->as_If();
241
242 ProjNode *uncommon_proj = iff->proj_out(1 - cont_proj->_con);
243 Node *rgn = uncommon_proj->unique_ctrl_out();
244 assert(rgn->is_Region() || rgn->is_Call(), "must be a region or call uct");
245
246 uint proj_index = 1; // region's edge corresponding to uncommon_proj
247 if (!rgn->is_Region()) { // create a region to guard the call
248 assert(rgn->is_Call(), "must be call uct");
249 CallNode* call = rgn->as_Call();
250 rgn = new (C, 1) RegionNode(1);
251 register_new_node_with_optimizer(rgn);
252 rgn->add_req(uncommon_proj);
253 hash_delete(call);
254 call->set_req(0, rgn);
255 } else {
256 // Find region's edge corresponding to uncommon_proj
257 for (; proj_index < rgn->req(); proj_index++)
258 if (rgn->in(proj_index) == uncommon_proj) break;
259 assert(proj_index < rgn->req(), "sanity");
260 }
261
262 // Create new_iff in new location.
263 IfNode *new_iff = iff->clone()->as_If();
264 new_iff->set_req(0, new_entry);
265
266 register_new_node_with_optimizer(new_iff);
267 Node *if_cont = new (C, 1) IfTrueNode(new_iff);
268 Node *if_uct = new (C, 1) IfFalseNode(new_iff);
269 if (cont_proj->is_IfFalse()) {
270 // Swap
271 Node* tmp = if_uct; if_uct = if_cont; if_cont = tmp;
272 }
273 register_new_node_with_optimizer(if_cont);
274 register_new_node_with_optimizer(if_uct);
275
276 // if_uct to rgn
277 hash_delete(rgn);
278 rgn->add_req(if_uct);
279
280 // If rgn has phis add corresponding new edges which has the same
281 // value as on original uncommon_proj pass.
282 assert(rgn->in(rgn->req() -1) == if_uct, "new edge should be last");
283 bool has_phi = false;
284 for (DUIterator_Fast imax, i = rgn->fast_outs(imax); i < imax; i++) {
285 Node* use = rgn->fast_out(i);
286 if (use->is_Phi() && use->outcnt() > 0) {
287 hash_delete(use);
288 use->add_req(use->in(proj_index));
289 _worklist.push(use);
290 has_phi = true;
291 }
292 }
293 assert(!has_phi || rgn->req() > 3, "no phis when region is created");
294
295 return if_cont->as_Proj();
296 }
297
298 //--------------------------clone_predicate-----------------------
299 ProjNode* PhaseIdealLoop::clone_predicate(ProjNode* predicate_proj, Node* new_entry,
300 Deoptimization::DeoptReason reason,
301 PhaseIdealLoop* loop_phase,
302 PhaseIterGVN* igvn) {
303 ProjNode* new_predicate_proj;
304 if (loop_phase != NULL) {
305 new_predicate_proj = loop_phase->create_new_if_for_predicate(predicate_proj, new_entry, reason);
306 } else {
307 new_predicate_proj = igvn->create_new_if_for_predicate(predicate_proj, new_entry, reason);
308 }
309 IfNode* iff = new_predicate_proj->in(0)->as_If();
310 Node* ctrl = iff->in(0);
311
312 // Match original condition since predicate's projections could be swapped.
313 assert(predicate_proj->in(0)->in(1)->in(1)->Opcode()==Op_Opaque1, "must be");
314 Node* opq = new (igvn->C, 2) Opaque1Node(igvn->C, predicate_proj->in(0)->in(1)->in(1)->in(1));
315 igvn->C->add_predicate_opaq(opq);
316
317 Node* bol = new (igvn->C, 2) Conv2BNode(opq);
318 if (loop_phase != NULL) {
319 loop_phase->register_new_node(opq, ctrl);
320 loop_phase->register_new_node(bol, ctrl);
321 } else {
322 igvn->register_new_node_with_optimizer(opq);
323 igvn->register_new_node_with_optimizer(bol);
324 }
325 igvn->hash_delete(iff);
326 iff->set_req(1, bol);
327 return new_predicate_proj;
328 }
329
330 //--------------------------move_predicate-----------------------
331 // Cut predicate from old place and move it to new.
332 ProjNode* PhaseIdealLoop::move_predicate(ProjNode* predicate_proj, Node* new_entry,
333 Deoptimization::DeoptReason reason,
334 PhaseIdealLoop* loop_phase,
335 PhaseIterGVN* igvn) {
336 assert(new_entry != NULL, "must be");
337 assert(predicate_proj->in(0)->in(1)->in(1)->Opcode()==Op_Opaque1, "must be");
338 IfNode* iff = predicate_proj->in(0)->as_If();
339 Node* old_entry = iff->in(0);
340
341 // Cut predicate from old place.
342 Node* old = predicate_proj;
343 igvn->_worklist.push(old);
344 for (DUIterator_Last imin, i = old->last_outs(imin); i >= imin; ) {
345 Node* use = old->last_out(i); // for each use...
346 igvn->hash_delete(use);
347 igvn->_worklist.push(use);
348 // Update use-def info
349 uint uses_found = 0;
350 for (uint j = 0; j < use->req(); j++) {
351 if (use->in(j) == old) {
352 use->set_req(j, old_entry);
353 uses_found++;
354 if (loop_phase != NULL) {
355 if (use->is_CFG()) {
356 // When called from beautify_loops() idom is not constructed yet.
357 if (loop_phase->_idom != NULL)
358 loop_phase->set_idom(use, old_entry, loop_phase->dom_depth(use));
359 } else {
360 loop_phase->set_ctrl(use, old_entry);
361 }
362 }
363 }
364 }
365 i -= uses_found; // we deleted 1 or more copies of this edge
366 }
367
368 // Move predicate.
369 igvn->hash_delete(iff);
370 iff->set_req(0, new_entry);
371 igvn->_worklist.push(iff);
372
373 if (loop_phase != NULL) {
374 // Fix up idom and ctrl.
375 loop_phase->set_ctrl(iff->in(1), new_entry);
376 loop_phase->set_ctrl(iff->in(1)->in(1), new_entry);
377 // When called from beautify_loops() idom is not constructed yet.
378 if (loop_phase->_idom != NULL)
379 loop_phase->set_idom(iff, new_entry, loop_phase->dom_depth(iff));
380 }
381
382 return predicate_proj;
383 }
384
385 //--------------------------clone_loop_predicates-----------------------
386 // Interface from IGVN
387 Node* PhaseIterGVN::clone_loop_predicates(Node* old_entry, Node* new_entry) {
388 return PhaseIdealLoop::clone_loop_predicates(old_entry, new_entry, false, NULL, this);
389 }
390 Node* PhaseIterGVN::move_loop_predicates(Node* old_entry, Node* new_entry) {
391 return PhaseIdealLoop::clone_loop_predicates(old_entry, new_entry, true, NULL, this);
392 }
393
394 // Interface from PhaseIdealLoop
395 Node* PhaseIdealLoop::clone_loop_predicates(Node* old_entry, Node* new_entry) {
396 return clone_loop_predicates(old_entry, new_entry, false, this, &this->_igvn);
397 }
398 Node* PhaseIdealLoop::move_loop_predicates(Node* old_entry, Node* new_entry) {
399 return clone_loop_predicates(old_entry, new_entry, true, this, &this->_igvn);
400 }
401
402 // Clone loop predicates to cloned loops (peeled, unswitched, split_if).
403 Node* PhaseIdealLoop::clone_loop_predicates(Node* old_entry, Node* new_entry,
404 bool move_predicates,
405 PhaseIdealLoop* loop_phase,
406 PhaseIterGVN* igvn) {
407 #ifdef ASSERT
408 if (new_entry == NULL || !(new_entry->is_Proj() || new_entry->is_Region() || new_entry->is_SafePoint())) {
409 if (new_entry != NULL)
410 new_entry->dump();
411 assert(false, "not IfTrue, IfFalse, Region or SafePoint");
412 }
413 #endif
414 // Search original predicates
415 Node* entry = old_entry;
416 if (UseLoopPredicate) {
417 ProjNode* predicate_proj = find_predicate_insertion_point(entry, Deoptimization::Reason_predicate);
418 if (predicate_proj != NULL) { // right pattern that can be used by loop predication
419 assert(entry->in(0)->in(1)->in(1)->Opcode()==Op_Opaque1, "must be");
420 if (move_predicates) {
421 new_entry = move_predicate(predicate_proj, new_entry,
422 Deoptimization::Reason_predicate,
423 loop_phase, igvn);
424 assert(new_entry == predicate_proj, "old predicate fall through projection");
425 } else {
426 // clone predicate
427 new_entry = clone_predicate(predicate_proj, new_entry,
428 Deoptimization::Reason_predicate,
429 loop_phase, igvn);
430 assert(new_entry != NULL && new_entry->is_Proj(), "IfTrue or IfFalse after clone predicate");
431 }
432 if (TraceLoopPredicate) {
433 tty->print_cr("Loop Predicate %s: ", move_predicates ? "moved" : "cloned");
434 debug_only( new_entry->in(0)->dump(); )
435 }
436 }
437 }
438 return new_entry;
439 }
440
441 //--------------------------eliminate_loop_predicates-----------------------
442 void PhaseIdealLoop::eliminate_loop_predicates(Node* entry) {
443 if (UseLoopPredicate) {
444 ProjNode* predicate_proj = find_predicate_insertion_point(entry, Deoptimization::Reason_predicate);
445 if (predicate_proj != NULL) { // right pattern that can be used by loop predication
446 Node* n = entry->in(0)->in(1)->in(1);
447 assert(n->Opcode()==Op_Opaque1, "must be");
448 // Remove Opaque1 node from predicates list.
449 // IGVN will remove this predicate check.
450 _igvn.replace_node(n, n->in(1));
451 }
452 }
453 }
454
455 //--------------------------skip_loop_predicates------------------------------
456 // Skip related predicates.
457 Node* PhaseIdealLoop::skip_loop_predicates(Node* entry) {
458 Node* predicate = NULL;
459 if (UseLoopPredicate) {
460 predicate = find_predicate_insertion_point(entry, Deoptimization::Reason_predicate);
461 if (predicate != NULL) { // right pattern that can be used by loop predication
462 assert(entry->is_Proj() && entry->in(0)->in(1)->in(1)->Opcode()==Op_Opaque1, "must be");
463 IfNode* iff = entry->in(0)->as_If();
464 ProjNode* uncommon_proj = iff->proj_out(1 - entry->as_Proj()->_con);
465 Node* rgn = uncommon_proj->unique_ctrl_out();
466 assert(rgn->is_Region() || rgn->is_Call(), "must be a region or call uct");
467 entry = entry->in(0)->in(0);
468 while (entry != NULL && entry->is_Proj() && entry->in(0)->is_If()) {
469 uncommon_proj = entry->in(0)->as_If()->proj_out(1 - entry->as_Proj()->_con);
470 if (uncommon_proj->unique_ctrl_out() != rgn)
471 break;
472 entry = entry->in(0)->in(0);
473 }
474 }
475 }
476 return entry;
477 }
478
479 //--------------------------find_predicate_insertion_point-------------------
480 // Find a good location to insert a predicate
481 ProjNode* PhaseIdealLoop::find_predicate_insertion_point(Node* start_c, Deoptimization::DeoptReason reason) {
482 if (start_c == NULL || !start_c->is_Proj())
483 return NULL;
484 if (is_uncommon_trap_if_pattern(start_c->as_Proj(), reason)) {
485 return start_c->as_Proj();
486 }
487 return NULL;
488 }
489
490 //--------------------------find_predicate------------------------------------
491 // Find a predicate
492 Node* PhaseIdealLoop::find_predicate(Node* entry) {
493 Node* predicate = NULL;
494 if (UseLoopPredicate) {
495 predicate = find_predicate_insertion_point(entry, Deoptimization::Reason_predicate);
496 if (predicate != NULL) { // right pattern that can be used by loop predication
497 assert(entry->in(0)->in(1)->in(1)->Opcode()==Op_Opaque1, "must be");
498 return entry;
499 }
500 }
501 return NULL;
502 }
503
504 //------------------------------Invariance-----------------------------------
505 // Helper class for loop_predication_impl to compute invariance on the fly and
506 // clone invariants.
507 class Invariance : public StackObj {
508 VectorSet _visited, _invariant;
509 Node_Stack _stack;
510 VectorSet _clone_visited;
511 Node_List _old_new; // map of old to new (clone)
512 IdealLoopTree* _lpt;
513 PhaseIdealLoop* _phase;
514
515 // Helper function to set up the invariance for invariance computation
516 // If n is a known invariant, set up directly. Otherwise, look up the
517 // the possibility to push n onto the stack for further processing.
518 void visit(Node* use, Node* n) {
519 if (_lpt->is_invariant(n)) { // known invariant
520 _invariant.set(n->_idx);
521 } else if (!n->is_CFG()) {
522 Node *n_ctrl = _phase->ctrl_or_self(n);
523 Node *u_ctrl = _phase->ctrl_or_self(use); // self if use is a CFG
524 if (_phase->is_dominator(n_ctrl, u_ctrl)) {
525 _stack.push(n, n->in(0) == NULL ? 1 : 0);
526 }
527 }
528 }
529
530 // Compute invariance for "the_node" and (possibly) all its inputs recursively
531 // on the fly
532 void compute_invariance(Node* n) {
533 assert(_visited.test(n->_idx), "must be");
534 visit(n, n);
535 while (_stack.is_nonempty()) {
536 Node* n = _stack.node();
537 uint idx = _stack.index();
538 if (idx == n->req()) { // all inputs are processed
539 _stack.pop();
540 // n is invariant if it's inputs are all invariant
541 bool all_inputs_invariant = true;
542 for (uint i = 0; i < n->req(); i++) {
543 Node* in = n->in(i);
544 if (in == NULL) continue;
545 assert(_visited.test(in->_idx), "must have visited input");
546 if (!_invariant.test(in->_idx)) { // bad guy
547 all_inputs_invariant = false;
548 break;
549 }
550 }
551 if (all_inputs_invariant) {
552 _invariant.set(n->_idx); // I am a invariant too
553 }
554 } else { // process next input
555 _stack.set_index(idx + 1);
556 Node* m = n->in(idx);
557 if (m != NULL && !_visited.test_set(m->_idx)) {
558 visit(n, m);
559 }
560 }
561 }
562 }
563
564 // Helper function to set up _old_new map for clone_nodes.
565 // If n is a known invariant, set up directly ("clone" of n == n).
566 // Otherwise, push n onto the stack for real cloning.
567 void clone_visit(Node* n) {
568 assert(_invariant.test(n->_idx), "must be invariant");
569 if (_lpt->is_invariant(n)) { // known invariant
570 _old_new.map(n->_idx, n);
571 } else { // to be cloned
572 assert(!n->is_CFG(), "should not see CFG here");
573 _stack.push(n, n->in(0) == NULL ? 1 : 0);
574 }
575 }
576
577 // Clone "n" and (possibly) all its inputs recursively
578 void clone_nodes(Node* n, Node* ctrl) {
579 clone_visit(n);
580 while (_stack.is_nonempty()) {
581 Node* n = _stack.node();
582 uint idx = _stack.index();
583 if (idx == n->req()) { // all inputs processed, clone n!
584 _stack.pop();
585 // clone invariant node
586 Node* n_cl = n->clone();
587 _old_new.map(n->_idx, n_cl);
588 _phase->register_new_node(n_cl, ctrl);
589 for (uint i = 0; i < n->req(); i++) {
590 Node* in = n_cl->in(i);
591 if (in == NULL) continue;
592 n_cl->set_req(i, _old_new[in->_idx]);
593 }
594 } else { // process next input
595 _stack.set_index(idx + 1);
596 Node* m = n->in(idx);
597 if (m != NULL && !_clone_visited.test_set(m->_idx)) {
598 clone_visit(m); // visit the input
599 }
600 }
601 }
602 }
603
604 public:
605 Invariance(Arena* area, IdealLoopTree* lpt) :
606 _lpt(lpt), _phase(lpt->_phase),
607 _visited(area), _invariant(area), _stack(area, 10 /* guess */),
608 _clone_visited(area), _old_new(area)
609 {}
610
611 // Map old to n for invariance computation and clone
612 void map_ctrl(Node* old, Node* n) {
613 assert(old->is_CFG() && n->is_CFG(), "must be");
614 _old_new.map(old->_idx, n); // "clone" of old is n
615 _invariant.set(old->_idx); // old is invariant
616 _clone_visited.set(old->_idx);
617 }
618
619 // Driver function to compute invariance
620 bool is_invariant(Node* n) {
621 if (!_visited.test_set(n->_idx))
622 compute_invariance(n);
623 return (_invariant.test(n->_idx) != 0);
624 }
625
626 // Driver function to clone invariant
627 Node* clone(Node* n, Node* ctrl) {
628 assert(ctrl->is_CFG(), "must be");
629 assert(_invariant.test(n->_idx), "must be an invariant");
630 if (!_clone_visited.test(n->_idx))
631 clone_nodes(n, ctrl);
632 return _old_new[n->_idx];
633 }
634 };
635
636 //------------------------------is_range_check_if -----------------------------------
637 // Returns true if the predicate of iff is in "scale*iv + offset u< load_range(ptr)" format
638 // Note: this function is particularly designed for loop predication. We require load_range
639 // and offset to be loop invariant computed on the fly by "invar"
640 bool IdealLoopTree::is_range_check_if(IfNode *iff, PhaseIdealLoop *phase, Invariance& invar) const {
641 if (!is_loop_exit(iff)) {
642 return false;
643 }
644 if (!iff->in(1)->is_Bool()) {
645 return false;
646 }
647 const BoolNode *bol = iff->in(1)->as_Bool();
648 if (bol->_test._test != BoolTest::lt) {
649 return false;
650 }
651 if (!bol->in(1)->is_Cmp()) {
652 return false;
653 }
654 const CmpNode *cmp = bol->in(1)->as_Cmp();
655 if (cmp->Opcode() != Op_CmpU) {
656 return false;
657 }
658 Node* range = cmp->in(2);
659 if (range->Opcode() != Op_LoadRange) {
660 const TypeInt* tint = phase->_igvn.type(range)->isa_int();
661 if (!OptimizeFill || tint == NULL || tint->empty() || tint->_lo < 0) {
662 // Allow predication on positive values that aren't LoadRanges.
663 // This allows optimization of loops where the length of the
664 // array is a known value and doesn't need to be loaded back
665 // from the array.
666 return false;
667 }
668 }
669 if (!invar.is_invariant(range)) {
670 return false;
671 }
672 Node *iv = _head->as_CountedLoop()->phi();
673 int scale = 0;
674 Node *offset = NULL;
675 if (!phase->is_scaled_iv_plus_offset(cmp->in(1), iv, &scale, &offset)) {
676 return false;
677 }
678 if (offset && !invar.is_invariant(offset)) { // offset must be invariant
679 return false;
680 }
681 return true;
682 }
683
684 //------------------------------rc_predicate-----------------------------------
685 // Create a range check predicate
686 //
687 // for (i = init; i < limit; i += stride) {
688 // a[scale*i+offset]
689 // }
690 //
691 // Compute max(scale*i + offset) for init <= i < limit and build the predicate
692 // as "max(scale*i + offset) u< a.length".
693 //
694 // There are two cases for max(scale*i + offset):
695 // (1) stride*scale > 0
696 // max(scale*i + offset) = scale*(limit-stride) + offset
697 // (2) stride*scale < 0
698 // max(scale*i + offset) = scale*init + offset
699 BoolNode* PhaseIdealLoop::rc_predicate(Node* ctrl,
700 int scale, Node* offset,
701 Node* init, Node* limit, Node* stride,
702 Node* range, bool upper) {
703 DEBUG_ONLY(ttyLocker ttyl);
704 if (TraceLoopPredicate) tty->print("rc_predicate ");
705
706 Node* max_idx_expr = init;
707 int stride_con = stride->get_int();
708 if ((stride_con > 0) == (scale > 0) == upper) {
709 max_idx_expr = new (C, 3) SubINode(limit, stride);
710 register_new_node(max_idx_expr, ctrl);
711 if (TraceLoopPredicate) tty->print("(limit - stride) ");
712 } else {
713 if (TraceLoopPredicate) tty->print("init ");
714 }
715
716 if (scale != 1) {
717 ConNode* con_scale = _igvn.intcon(scale);
718 max_idx_expr = new (C, 3) MulINode(max_idx_expr, con_scale);
719 register_new_node(max_idx_expr, ctrl);
720 if (TraceLoopPredicate) tty->print("* %d ", scale);
721 }
722
723 if (offset && (!offset->is_Con() || offset->get_int() != 0)){
724 max_idx_expr = new (C, 3) AddINode(max_idx_expr, offset);
725 register_new_node(max_idx_expr, ctrl);
726 if (TraceLoopPredicate)
727 if (offset->is_Con()) tty->print("+ %d ", offset->get_int());
728 else tty->print("+ offset ");
729 }
730
731 CmpUNode* cmp = new (C, 3) CmpUNode(max_idx_expr, range);
732 register_new_node(cmp, ctrl);
733 BoolNode* bol = new (C, 2) BoolNode(cmp, BoolTest::lt);
734 register_new_node(bol, ctrl);
735
736 if (TraceLoopPredicate) tty->print_cr("<u range");
737 return bol;
738 }
739
740 //------------------------------ loop_predication_impl--------------------------
741 // Insert loop predicates for null checks and range checks
742 bool PhaseIdealLoop::loop_predication_impl(IdealLoopTree *loop) {
743 if (!UseLoopPredicate) return false;
744
745 if (!loop->_head->is_Loop()) {
746 // Could be a simple region when irreducible loops are present.
747 return false;
748 }
749
750 if (loop->_head->unique_ctrl_out()->Opcode() == Op_NeverBranch) {
751 // do nothing for infinite loops
752 return false;
753 }
754
755 CountedLoopNode *cl = NULL;
756 if (loop->_head->is_CountedLoop()) {
757 cl = loop->_head->as_CountedLoop();
758 // do nothing for iteration-splitted loops
759 if (!cl->is_normal_loop()) return false;
760 }
761
762 LoopNode *lpn = loop->_head->as_Loop();
763 Node* entry = lpn->in(LoopNode::EntryControl);
764
765 ProjNode *predicate_proj = find_predicate_insertion_point(entry, Deoptimization::Reason_predicate);
766 if (!predicate_proj) {
767 #ifndef PRODUCT
768 if (TraceLoopPredicate) {
769 tty->print("missing predicate:");
770 loop->dump_head();
771 lpn->dump(1);
772 }
773 #endif
774 return false;
775 }
776 ConNode* zero = _igvn.intcon(0);
777 set_ctrl(zero, C->root());
778
779 ResourceArea *area = Thread::current()->resource_area();
780 Invariance invar(area, loop);
781
782 // Create list of if-projs such that a newer proj dominates all older
783 // projs in the list, and they all dominate loop->tail()
784 Node_List if_proj_list(area);
785 LoopNode *head = loop->_head->as_Loop();
786 Node *current_proj = loop->tail(); //start from tail
787 while (current_proj != head) {
788 if (loop == get_loop(current_proj) && // still in the loop ?
789 current_proj->is_Proj() && // is a projection ?
790 current_proj->in(0)->Opcode() == Op_If) { // is a if projection ?
791 if_proj_list.push(current_proj);
792 }
793 current_proj = idom(current_proj);
794 }
795
796 bool hoisted = false; // true if at least one proj is promoted
797 while (if_proj_list.size() > 0) {
798 // Following are changed to nonnull when a predicate can be hoisted
799 ProjNode* new_predicate_proj = NULL;
800
801 ProjNode* proj = if_proj_list.pop()->as_Proj();
802 IfNode* iff = proj->in(0)->as_If();
803
804 if (!is_uncommon_trap_if_pattern(proj, Deoptimization::Reason_none)) {
805 if (loop->is_loop_exit(iff)) {
806 // stop processing the remaining projs in the list because the execution of them
807 // depends on the condition of "iff" (iff->in(1)).
808 break;
809 } else {
810 // Both arms are inside the loop. There are two cases:
811 // (1) there is one backward branch. In this case, any remaining proj
812 // in the if_proj list post-dominates "iff". So, the condition of "iff"
813 // does not determine the execution the remining projs directly, and we
814 // can safely continue.
815 // (2) both arms are forwarded, i.e. a diamond shape. In this case, "proj"
816 // does not dominate loop->tail(), so it can not be in the if_proj list.
817 continue;
818 }
819 }
820
821 Node* test = iff->in(1);
822 if (!test->is_Bool()){ //Conv2B, ...
823 continue;
824 }
825 BoolNode* bol = test->as_Bool();
826 if (invar.is_invariant(bol)) {
827 // Invariant test
828 new_predicate_proj = create_new_if_for_predicate(predicate_proj, NULL,
829 Deoptimization::Reason_predicate);
830 Node* ctrl = new_predicate_proj->in(0)->as_If()->in(0);
831 BoolNode* new_predicate_bol = invar.clone(bol, ctrl)->as_Bool();
832
833 // Negate test if necessary
834 bool negated = false;
835 if (proj->_con != predicate_proj->_con) {
836 new_predicate_bol = new (C, 2) BoolNode(new_predicate_bol->in(1), new_predicate_bol->_test.negate());
837 register_new_node(new_predicate_bol, ctrl);
838 negated = true;
839 }
840 IfNode* new_predicate_iff = new_predicate_proj->in(0)->as_If();
841 _igvn.hash_delete(new_predicate_iff);
842 new_predicate_iff->set_req(1, new_predicate_bol);
843 #ifndef PRODUCT
844 if (TraceLoopPredicate) {
845 tty->print("Predicate invariant if%s: %d ", negated ? " negated" : "", new_predicate_iff->_idx);
846 loop->dump_head();
847 } else if (TraceLoopOpts) {
848 tty->print("Predicate IC ");
849 loop->dump_head();
850 }
851 #endif
852 } else if (cl != NULL && loop->is_range_check_if(iff, this, invar)) {
853 assert(proj->_con == predicate_proj->_con, "must match");
854
855 // Range check for counted loops
856 const Node* cmp = bol->in(1)->as_Cmp();
857 Node* idx = cmp->in(1);
858 assert(!invar.is_invariant(idx), "index is variant");
859 assert(cmp->in(2)->Opcode() == Op_LoadRange || OptimizeFill, "must be");
860 Node* rng = cmp->in(2);
861 assert(invar.is_invariant(rng), "range must be invariant");
862 int scale = 1;
863 Node* offset = zero;
864 bool ok = is_scaled_iv_plus_offset(idx, cl->phi(), &scale, &offset);
865 assert(ok, "must be index expression");
866
867 Node* init = cl->init_trip();
868 Node* limit = cl->limit();
869 Node* stride = cl->stride();
870
871 // Build if's for the upper and lower bound tests. The
872 // lower_bound test will dominate the upper bound test and all
873 // cloned or created nodes will use the lower bound test as
874 // their declared control.
875 ProjNode* lower_bound_proj = create_new_if_for_predicate(predicate_proj, NULL, Deoptimization::Reason_predicate);
876 ProjNode* upper_bound_proj = create_new_if_for_predicate(predicate_proj, NULL, Deoptimization::Reason_predicate);
877 assert(upper_bound_proj->in(0)->as_If()->in(0) == lower_bound_proj, "should dominate");
878 Node *ctrl = lower_bound_proj->in(0)->as_If()->in(0);
879
880 // Perform cloning to keep Invariance state correct since the
881 // late schedule will place invariant things in the loop.
882 rng = invar.clone(rng, ctrl);
883 if (offset && offset != zero) {
884 assert(invar.is_invariant(offset), "offset must be loop invariant");
885 offset = invar.clone(offset, ctrl);
886 }
887
888 // Test the lower bound
889 Node* lower_bound_bol = rc_predicate(ctrl, scale, offset, init, limit, stride, rng, false);
890 IfNode* lower_bound_iff = lower_bound_proj->in(0)->as_If();
891 _igvn.hash_delete(lower_bound_iff);
892 lower_bound_iff->set_req(1, lower_bound_bol);
893 if (TraceLoopPredicate) tty->print_cr("lower bound check if: %d", lower_bound_iff->_idx);
894
895 // Test the upper bound
896 Node* upper_bound_bol = rc_predicate(ctrl, scale, offset, init, limit, stride, rng, true);
897 IfNode* upper_bound_iff = upper_bound_proj->in(0)->as_If();
898 _igvn.hash_delete(upper_bound_iff);
899 upper_bound_iff->set_req(1, upper_bound_bol);
900 if (TraceLoopPredicate) tty->print_cr("upper bound check if: %d", lower_bound_iff->_idx);
901
902 // Fall through into rest of the clean up code which will move
903 // any dependent nodes onto the upper bound test.
904 new_predicate_proj = upper_bound_proj;
905
906 #ifndef PRODUCT
907 if (TraceLoopOpts && !TraceLoopPredicate) {
908 tty->print("Predicate RC ");
909 loop->dump_head();
910 }
911 #endif
912 } else {
913 // Loop variant check (for example, range check in non-counted loop)
914 // with uncommon trap.
915 continue;
916 }
917 assert(new_predicate_proj != NULL, "sanity");
918 // Success - attach condition (new_predicate_bol) to predicate if
919 invar.map_ctrl(proj, new_predicate_proj); // so that invariance test can be appropriate
920
921 // Eliminate the old If in the loop body
922 dominated_by( new_predicate_proj, iff, proj->_con != new_predicate_proj->_con );
923
924 hoisted = true;
925 C->set_major_progress();
926 } // end while
927
928 #ifndef PRODUCT
929 // report that the loop predication has been actually performed
930 // for this loop
931 if (TraceLoopPredicate && hoisted) {
932 tty->print("Loop Predication Performed:");
933 loop->dump_head();
934 }
935 #endif
936
937 return hoisted;
938 }
939
940 //------------------------------loop_predication--------------------------------
941 // driver routine for loop predication optimization
942 bool IdealLoopTree::loop_predication( PhaseIdealLoop *phase) {
943 bool hoisted = false;
944 // Recursively promote predicates
945 if (_child) {
946 hoisted = _child->loop_predication( phase);
947 }
948
949 // self
950 if (!_irreducible && !tail()->is_top()) {
951 hoisted |= phase->loop_predication_impl(this);
952 }
953
954 if (_next) { //sibling
955 hoisted |= _next->loop_predication( phase);
956 }
957
958 return hoisted;
959 }
960