-
Notifications
You must be signed in to change notification settings - Fork 5.8k
/
Copy pathloopPredicate.cpp
1370 lines (1278 loc) · 55.3 KB
/
loopPredicate.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2011, 2025, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
#include "memory/allocation.hpp"
#include "opto/addnode.hpp"
#include "opto/callnode.hpp"
#include "opto/castnode.hpp"
#include "opto/connode.hpp"
#include "opto/convertnode.hpp"
#include "opto/loopnode.hpp"
#include "opto/matcher.hpp"
#include "opto/mulnode.hpp"
#include "opto/opaquenode.hpp"
#include "opto/predicates.hpp"
#include "opto/rootnode.hpp"
#include "opto/subnode.hpp"
#include <fenv.h>
#include <math.h>
/*
* The general idea of Loop Predication is to hoist a check inside a loop body by inserting a Hoisted Check Predicate with
* an uncommon trap on the entry path to the loop. The old check inside the loop can be eliminated. If the condition of
* the Hoisted Check Predicate fails at runtime, we'll execute the uncommon trap to avoid entering the loop which misses
* the check. Loop Predication can currently remove array range checks and loop invariant checks (such as null checks).
*
* On top of these predicates added by Loop Predication, there are other kinds of predicates. A detailed description
* about all predicates can be found in predicates.hpp.
*/
//-------------------------------register_control-------------------------
void PhaseIdealLoop::register_control(Node* n, IdealLoopTree *loop, Node* pred, bool update_body) {
assert(n->is_CFG(), "msust be control node");
_igvn.register_new_node_with_optimizer(n);
if (update_body) {
loop->_body.push(n);
}
set_loop(n, loop);
// When called from beautify_loops() idom is not constructed yet.
if (_idom != nullptr) {
set_idom(n, pred, dom_depth(pred));
}
}
//------------------------------create_new_if_for_predicate------------------------
// create a new if above the uct_if_pattern for the predicate to be promoted.
//
// before after
// ---------- ----------
// ctrl ctrl
// | |
// | |
// v v
// iff new_iff
// / \ / \
// / \ / \
// v v v v
// uncommon_proj cont_proj if_uct if_cont
// \ | | | |
// \ | | | |
// v v v | v
// rgn loop | iff
// | | / \
// | | / \
// v | v v
// uncommon_trap | uncommon_proj cont_proj
// \ \ | |
// \ \ | |
// v v v v
// rgn loop
// |
// |
// v
// uncommon_trap
//
//
// We will create a region to guard the uct call if there is no one there.
// The continuation projection (if_cont) of the new_iff is returned which
// is an IfTrue projection. This code is also used to clone predicates to
// cloned loops. 'rewire_uncommon_proj_phi_inputs' should be set to the
// non-default value 'true' when called for a false-path loop during
// Loop Unswitching.
IfTrueNode* PhaseIdealLoop::create_new_if_for_predicate(const ParsePredicateSuccessProj* parse_predicate_success_proj,
Node* new_entry, const Deoptimization::DeoptReason reason,
const int opcode, const bool rewire_uncommon_proj_phi_inputs) {
assert(parse_predicate_success_proj->is_uncommon_trap_if_pattern(reason), "must be a uct if pattern!");
ParsePredicateNode* parse_predicate = parse_predicate_success_proj->in(0)->as_ParsePredicate();
ParsePredicateUncommonProj* uncommon_proj = parse_predicate->uncommon_proj();
Node* uncommon_trap = parse_predicate->uncommon_trap();
uint proj_index = 1; // region's edge corresponding to uncommon_proj
if (!uncommon_trap->is_Region()) { // create a region to guard the call
assert(uncommon_trap->is_Call(), "must be call uct");
CallNode* call = uncommon_trap->as_Call();
IdealLoopTree* loop = get_loop(call);
uncommon_trap = new RegionNode(1);
Node* uncommon_proj_orig = uncommon_proj;
uncommon_proj = uncommon_proj->clone()->as_IfFalse();
register_control(uncommon_proj, loop, parse_predicate);
uncommon_trap->add_req(uncommon_proj);
register_control(uncommon_trap, loop, uncommon_proj);
_igvn.replace_input_of(call, 0, uncommon_trap);
// When called from beautify_loops() idom is not constructed yet.
if (_idom != nullptr) {
set_idom(call, uncommon_trap, dom_depth(uncommon_trap));
}
// Move nodes pinned on the projection or whose control is set to
// the projection to the region.
lazy_replace(uncommon_proj_orig, uncommon_trap);
} else {
// Find region's edge corresponding to uncommon_proj
for (; proj_index < uncommon_trap->req(); proj_index++)
if (uncommon_trap->in(proj_index) == uncommon_proj) break;
assert(proj_index < uncommon_trap->req(), "sanity");
}
Node* entry = parse_predicate->in(0);
if (new_entry != nullptr) {
// Cloning the predicate to new location.
entry = new_entry;
}
// Create new_iff
IdealLoopTree* lp = get_loop(entry);
IfNode* new_iff = nullptr;
switch (opcode) {
case Op_If:
new_iff = new IfNode(entry, parse_predicate->in(1), parse_predicate->_prob, parse_predicate->_fcnt);
break;
case Op_RangeCheck:
new_iff = new RangeCheckNode(entry, parse_predicate->in(1), parse_predicate->_prob, parse_predicate->_fcnt);
break;
case Op_ParsePredicate:
new_iff = new ParsePredicateNode(entry, reason, &_igvn);
break;
default:
fatal("no other If variant here");
}
register_control(new_iff, lp, entry);
IfTrueNode* if_cont = new IfTrueNode(new_iff);
IfFalseNode* if_uct = new IfFalseNode(new_iff);
register_control(if_cont, lp, new_iff);
register_control(if_uct, get_loop(uncommon_trap), new_iff);
_igvn.add_input_to(uncommon_trap, if_uct);
// If rgn has phis add new edges which has the same
// value as on original uncommon_proj pass.
assert(uncommon_trap->in(uncommon_trap->req() - 1) == if_uct, "new edge should be last");
bool has_phi = false;
for (DUIterator_Fast imax, i = uncommon_trap->fast_outs(imax); i < imax; i++) {
Node* use = uncommon_trap->fast_out(i);
if (use->is_Phi() && use->outcnt() > 0) {
assert(use->in(0) == uncommon_trap, "");
_igvn.rehash_node_delayed(use);
Node* phi_input = use->in(proj_index);
if (uncommon_proj->outcnt() > 1 && !phi_input->is_CFG() && !phi_input->is_Phi() && get_ctrl(phi_input) == uncommon_proj) {
// There are some control dependent nodes on the uncommon projection. We cannot simply reuse these data nodes.
// We either need to rewire them from the old uncommon projection to the newly created uncommon proj (if the old
// If is dying) or clone them and update their control (if the old If is not dying).
if (rewire_uncommon_proj_phi_inputs) {
// Replace phi input for the old uncommon projection with TOP as the If is dying anyways. Reuse the old data
// nodes by simply updating control inputs and ctrl.
_igvn.replace_input_of(use, proj_index, C->top());
set_ctrl_of_nodes_with_same_ctrl(phi_input, uncommon_proj, if_uct);
} else {
phi_input = clone_nodes_with_same_ctrl(phi_input, uncommon_proj, if_uct);
}
}
use->add_req(phi_input);
has_phi = true;
}
}
assert(!has_phi || uncommon_trap->req() > 3, "no phis when region is created");
if (new_entry == nullptr) {
// Attach if_cont to iff
_igvn.replace_input_of(parse_predicate, 0, if_cont);
if (_idom != nullptr) {
set_idom(parse_predicate, if_cont, dom_depth(parse_predicate));
}
}
// When called from beautify_loops() idom is not constructed yet.
if (_idom != nullptr) {
Node* ridom = idom(uncommon_trap);
Node* nrdom = dom_lca_internal(ridom, new_iff);
set_idom(uncommon_trap, nrdom, dom_depth(uncommon_trap));
}
return if_cont;
}
// Update ctrl and control inputs of all data nodes starting from 'node' to 'new_ctrl' which have 'old_ctrl' as
// current ctrl.
void PhaseIdealLoop::set_ctrl_of_nodes_with_same_ctrl(Node* start_node, ProjNode* old_uncommon_proj,
Node* new_uncommon_proj) {
ResourceMark rm;
const Unique_Node_List nodes_with_same_ctrl = find_nodes_with_same_ctrl(start_node, old_uncommon_proj);
for (uint i = 0; i < nodes_with_same_ctrl.size(); i++) {
Node* node = nodes_with_same_ctrl[i];
if (node->in(0) == old_uncommon_proj) {
_igvn.replace_input_of(node, 0, new_uncommon_proj);
}
set_ctrl(node, new_uncommon_proj);
}
}
// Recursively find all input nodes with the same ctrl.
Unique_Node_List PhaseIdealLoop::find_nodes_with_same_ctrl(Node* node, const ProjNode* ctrl) {
Unique_Node_List nodes_with_same_ctrl;
nodes_with_same_ctrl.push(node);
for (uint j = 0; j < nodes_with_same_ctrl.size(); j++) {
Node* next = nodes_with_same_ctrl[j];
for (uint k = 1; k < next->req(); k++) {
Node* in = next->in(k);
if (!in->is_Phi() && get_ctrl(in) == ctrl) {
nodes_with_same_ctrl.push(in);
}
}
}
return nodes_with_same_ctrl;
}
// Clone all data nodes with a ctrl to the old uncommon projection from `start_node' by following its inputs. Rewire the
// cloned nodes to the new uncommon projection. Returns the clone of the `start_node`.
Node* PhaseIdealLoop::clone_nodes_with_same_ctrl(Node* start_node, ProjNode* old_uncommon_proj, Node* new_uncommon_proj) {
ResourceMark rm;
DEBUG_ONLY(uint last_idx = C->unique();)
const Unique_Node_List nodes_with_same_ctrl = find_nodes_with_same_ctrl(start_node, old_uncommon_proj);
DataNodeGraph data_node_graph(nodes_with_same_ctrl, this);
const OrigToNewHashtable& orig_to_clone = data_node_graph.clone(new_uncommon_proj);
fix_cloned_data_node_controls(old_uncommon_proj, new_uncommon_proj, orig_to_clone);
Node** cloned_node_ptr = orig_to_clone.get(start_node);
assert(cloned_node_ptr != nullptr && (*cloned_node_ptr)->_idx >= last_idx, "must exist and be a proper clone");
return *cloned_node_ptr;
}
// All data nodes with a control input to the uncommon projection in the chain need to be rewired to the new uncommon
// projection (could not only be the last data node in the chain but also, for example, a pinned DivNode within the chain).
void PhaseIdealLoop::fix_cloned_data_node_controls(const ProjNode* old_uncommon_proj, Node* new_uncommon_proj,
const OrigToNewHashtable& orig_to_clone) {
auto orig_clone_action = [&](Node* orig, Node* clone) {
if (orig->in(0) == old_uncommon_proj) {
_igvn.replace_input_of(clone, 0, new_uncommon_proj);
set_ctrl(clone, new_uncommon_proj);
}
};
orig_to_clone.iterate_all(orig_clone_action);
}
// Put all OpaqueTemplateAssertionPredicate nodes on a list, starting at 'predicate' and going up in the tree.
void PhaseIdealLoop::get_opaque_template_assertion_predicate_nodes(ParsePredicateSuccessProj* parse_predicate_proj,
Unique_Node_List& list) {
Deoptimization::DeoptReason deopt_reason = parse_predicate_proj->in(0)->as_ParsePredicate()->deopt_reason();
PredicateBlockIterator predicate_iterator(parse_predicate_proj, deopt_reason);
OpaqueTemplateAssertionPredicateCollector opaque_template_assertion_predicate_collector(list);
predicate_iterator.for_each(opaque_template_assertion_predicate_collector);
}
//------------------------------Invariance-----------------------------------
// Helper class for loop_predication_impl to compute invariance on the fly and
// clone invariants.
class Invariance : public StackObj {
VectorSet _visited, _invariant;
Node_Stack _stack;
VectorSet _clone_visited;
Node_List _old_new; // map of old to new (clone)
IdealLoopTree* _lpt;
PhaseIdealLoop* _phase;
Node* _data_dependency_on; // The projection into the loop on which data nodes are dependent or null otherwise
// Helper function to set up the invariance for invariance computation
// If n is a known invariant, set up directly. Otherwise, look up the
// the possibility to push n onto the stack for further processing.
void visit(Node* use, Node* n) {
if (_lpt->is_invariant(n)) { // known invariant
_invariant.set(n->_idx);
} else if (!n->is_CFG()) {
Node *n_ctrl = _phase->ctrl_or_self(n);
Node *u_ctrl = _phase->ctrl_or_self(use); // self if use is a CFG
if (_phase->is_dominator(n_ctrl, u_ctrl)) {
_stack.push(n, n->in(0) == nullptr ? 1 : 0);
}
}
}
// Compute invariance for "the_node" and (possibly) all its inputs recursively
// on the fly
void compute_invariance(Node* n) {
assert(_visited.test(n->_idx), "must be");
visit(n, n);
while (_stack.is_nonempty()) {
Node* n = _stack.node();
uint idx = _stack.index();
if (idx == n->req()) { // all inputs are processed
_stack.pop();
// n is invariant if it's inputs are all invariant
bool all_inputs_invariant = true;
for (uint i = 0; i < n->req(); i++) {
Node* in = n->in(i);
if (in == nullptr) continue;
assert(_visited.test(in->_idx), "must have visited input");
if (!_invariant.test(in->_idx)) { // bad guy
all_inputs_invariant = false;
break;
}
}
if (all_inputs_invariant) {
// If n's control is a predicate that was moved out of the
// loop, it was marked invariant but n is only invariant if
// it depends only on that test. Otherwise, unless that test
// is out of the loop, it's not invariant.
if (n->is_CFG() || (n->depends_only_on_test() && _phase->igvn().no_dependent_zero_check(n)) || n->in(0) == nullptr || !_phase->is_member(_lpt, n->in(0))) {
_invariant.set(n->_idx); // I am a invariant too
}
}
} else { // process next input
_stack.set_index(idx + 1);
Node* m = n->in(idx);
if (m != nullptr && !_visited.test_set(m->_idx)) {
visit(n, m);
}
}
}
}
// Helper function to set up _old_new map for clone_nodes.
// If n is a known invariant, set up directly ("clone" of n == n).
// Otherwise, push n onto the stack for real cloning.
void clone_visit(Node* n) {
assert(_invariant.test(n->_idx), "must be invariant");
if (_lpt->is_invariant(n)) { // known invariant
_old_new.map(n->_idx, n);
} else { // to be cloned
assert(!n->is_CFG(), "should not see CFG here");
_stack.push(n, n->in(0) == nullptr ? 1 : 0);
}
}
// Clone "n" and (possibly) all its inputs recursively
void clone_nodes(Node* n, Node* ctrl) {
clone_visit(n);
while (_stack.is_nonempty()) {
Node* n = _stack.node();
uint idx = _stack.index();
if (idx == n->req()) { // all inputs processed, clone n!
_stack.pop();
// clone invariant node
Node* n_cl = n->clone();
_old_new.map(n->_idx, n_cl);
_phase->register_new_node(n_cl, ctrl);
for (uint i = 0; i < n->req(); i++) {
Node* in = n_cl->in(i);
if (in == nullptr) continue;
n_cl->set_req(i, _old_new[in->_idx]);
}
} else { // process next input
_stack.set_index(idx + 1);
Node* m = n->in(idx);
if (m != nullptr && !_clone_visited.test_set(m->_idx)) {
clone_visit(m); // visit the input
}
}
}
}
public:
Invariance(Arena* area, IdealLoopTree* lpt) :
_visited(area), _invariant(area),
_stack(area, 10 /* guess */),
_clone_visited(area), _old_new(area),
_lpt(lpt), _phase(lpt->_phase),
_data_dependency_on(nullptr)
{
LoopNode* head = _lpt->_head->as_Loop();
Node* entry = head->skip_strip_mined()->in(LoopNode::EntryControl);
if (entry->outcnt() != 1) {
// If a node is pinned between the predicates and the loop
// entry, we won't be able to move any node in the loop that
// depends on it above it in a predicate. Mark all those nodes
// as non-loop-invariant.
// Loop predication could create new nodes for which the below
// invariant information is missing. Mark the 'entry' node to
// later check again if a node needs to be treated as non-loop-
// invariant as well.
_data_dependency_on = entry;
Unique_Node_List wq;
wq.push(entry);
for (uint next = 0; next < wq.size(); ++next) {
Node *n = wq.at(next);
for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
Node* u = n->fast_out(i);
if (!u->is_CFG()) {
Node* c = _phase->get_ctrl(u);
if (_lpt->is_member(_phase->get_loop(c)) || _phase->is_dominator(c, head)) {
_visited.set(u->_idx);
wq.push(u);
}
}
}
}
}
}
// Did we explicitly mark some nodes non-loop-invariant? If so, return the entry node on which some data nodes
// are dependent that prevent loop predication. Otherwise, return null.
Node* data_dependency_on() {
return _data_dependency_on;
}
// Map old to n for invariance computation and clone
void map_ctrl(Node* old, Node* n) {
assert(old->is_CFG() && n->is_CFG(), "must be");
_old_new.map(old->_idx, n); // "clone" of old is n
_invariant.set(old->_idx); // old is invariant
_clone_visited.set(old->_idx);
}
// Driver function to compute invariance
bool is_invariant(Node* n) {
if (!_visited.test_set(n->_idx))
compute_invariance(n);
return (_invariant.test(n->_idx) != 0);
}
// Driver function to clone invariant
Node* clone(Node* n, Node* ctrl) {
assert(ctrl->is_CFG(), "must be");
assert(_invariant.test(n->_idx), "must be an invariant");
if (!_clone_visited.test(n->_idx))
clone_nodes(n, ctrl);
return _old_new[n->_idx];
}
};
//------------------------------is_range_check_if -----------------------------------
// Returns true if the predicate of iff is in "scale*iv + offset u< load_range(ptr)" format
// Note: this function is particularly designed for loop predication. We require load_range
// and offset to be loop invariant computed on the fly by "invar"
bool IdealLoopTree::is_range_check_if(IfProjNode* if_success_proj, PhaseIdealLoop *phase, BasicType bt, Node *iv, Node *&range,
Node *&offset, jlong &scale) const {
IfNode* iff = if_success_proj->in(0)->as_If();
if (!is_loop_exit(iff)) {
return false;
}
if (!iff->in(1)->is_Bool()) {
return false;
}
const BoolNode *bol = iff->in(1)->as_Bool();
if (bol->_test._test != BoolTest::lt || if_success_proj->is_IfFalse()) {
// We don't have the required range check pattern:
// if (scale*iv + offset <u limit) {
//
// } else {
// trap();
// }
//
// Having the trap on the true projection:
// if (scale*iv + offset <u limit) {
// trap();
// }
//
// is not correct. We would need to flip the test to get the expected "trap on false path" pattern:
// if (scale*iv + offset >=u limit) {
//
// } else {
// trap();
// }
//
// If we create a Range Check Predicate for this wrong pattern, it could succeed at runtime (i.e. true for the
// value of "scale*iv + offset" in the first loop iteration and true for the value of "scale*iv + offset" in the
// last loop iteration) while the check to be hoisted could fail in other loop iterations.
//
// Example:
// Loop: "for (int i = -1; i < 1000; i++)"
// init = "scale*iv + offset" in the first loop iteration = 1*-1 + 0 = -1
// last = "scale*iv + offset" in the last loop iteration = 1*999 + 0 = 999
// limit = 100
//
// Range Check Predicate is always true:
// init >=u limit && last >=u limit <=>
// -1 >=u 100 && 999 >= u 100
//
// But for 0 <= x < 100: x >=u 100 is false.
// We would wrongly skip the branch with the trap() and possibly miss to execute some other statements inside that
// trap() branch.
return false;
}
if (!bol->in(1)->is_Cmp()) {
return false;
}
const CmpNode *cmp = bol->in(1)->as_Cmp();
if (cmp->Opcode() != Op_Cmp_unsigned(bt)) {
return false;
}
range = cmp->in(2);
if (range->Opcode() != Op_LoadRange) {
const TypeInteger* tinteger = phase->_igvn.type(range)->isa_integer(bt);
if (tinteger == nullptr || tinteger->empty() || tinteger->lo_as_long() < 0) {
// Allow predication on positive values that aren't LoadRanges.
// This allows optimization of loops where the length of the
// array is a known value and doesn't need to be loaded back
// from the array.
return false;
}
} else {
assert(bt == T_INT, "no LoadRange for longs");
}
scale = 0;
offset = nullptr;
if (!phase->is_scaled_iv_plus_offset(cmp->in(1), iv, bt, &scale, &offset)) {
return false;
}
return true;
}
bool IdealLoopTree::is_range_check_if(IfProjNode* if_success_proj, PhaseIdealLoop *phase, Invariance& invar DEBUG_ONLY(COMMA ProjNode *predicate_proj)) const {
Node* range = nullptr;
Node* offset = nullptr;
jlong scale = 0;
Node* iv = _head->as_BaseCountedLoop()->phi();
Compile* C = Compile::current();
const uint old_unique_idx = C->unique();
if (!is_range_check_if(if_success_proj, phase, T_INT, iv, range, offset, scale)) {
return false;
}
if (!invar.is_invariant(range)) {
return false;
}
if (offset != nullptr) {
if (!invar.is_invariant(offset)) { // offset must be invariant
return false;
}
Node* data_dependency_on = invar.data_dependency_on();
if (data_dependency_on != nullptr && old_unique_idx < C->unique()) {
// 'offset' node was newly created in is_range_check_if(). Check that it does not depend on the entry projection
// into the loop. If it does, we cannot perform loop predication (see Invariant::Invariant()).
assert(!offset->is_CFG(), "offset must be a data node");
if (_phase->get_ctrl(offset) == data_dependency_on) {
return false;
}
}
}
#ifdef ASSERT
if (offset && phase->has_ctrl(offset)) {
Node* offset_ctrl = phase->get_ctrl(offset);
if (phase->get_loop(predicate_proj) == phase->get_loop(offset_ctrl) &&
phase->is_dominator(predicate_proj, offset_ctrl)) {
// If the control of offset is loop predication promoted by previous pass,
// then it will lead to cyclic dependency.
// Previously promoted loop predication is in the same loop of predication
// point.
// This situation can occur when pinning nodes too conservatively - can we do better?
assert(false, "cyclic dependency prevents range check elimination, idx: offset %d, offset_ctrl %d, predicate_proj %d",
offset->_idx, offset_ctrl->_idx, predicate_proj->_idx);
}
}
#endif
return true;
}
//------------------------------rc_predicate-----------------------------------
// Create a range check predicate
//
// for (i = init; i < limit; i += stride) {
// a[scale*i+offset]
// }
//
// Compute max(scale*i + offset) for init <= i < limit and build the predicate
// as "max(scale*i + offset) u< a.length".
//
// There are two cases for max(scale*i + offset):
// (1) stride*scale > 0
// max(scale*i + offset) = scale*(limit-stride) + offset
// (2) stride*scale < 0
// max(scale*i + offset) = scale*init + offset
BoolNode* PhaseIdealLoop::rc_predicate(Node* ctrl, const int scale, Node* offset, Node* init, Node* limit,
const jint stride, Node* range, const bool upper, bool& overflow) {
jint con_limit = (limit != nullptr && limit->is_Con()) ? limit->get_int() : 0;
jint con_init = init->is_Con() ? init->get_int() : 0;
jint con_offset = offset->is_Con() ? offset->get_int() : 0;
stringStream* predString = nullptr;
if (TraceLoopPredicate) {
predString = new (mtCompiler) stringStream();
predString->print("rc_predicate ");
}
overflow = false;
Node* max_idx_expr = nullptr;
const TypeInt* idx_type = TypeInt::INT;
// same signs and upper, or different signs and not upper.
if (((stride > 0) == (scale > 0)) == upper) {
guarantee(limit != nullptr, "sanity");
if (TraceLoopPredicate) {
if (limit->is_Con()) {
predString->print("(%d ", con_limit);
} else {
predString->print("(limit ");
}
predString->print("- %d) ", stride);
}
// Check if (limit - stride) may overflow
const TypeInt* limit_type = _igvn.type(limit)->isa_int();
jint limit_lo = limit_type->_lo;
jint limit_hi = limit_type->_hi;
if ((stride > 0 && (java_subtract(limit_lo, stride) < limit_lo)) ||
(stride < 0 && (java_subtract(limit_hi, stride) > limit_hi))) {
// No overflow possible
ConINode* con_stride = intcon(stride);
max_idx_expr = new SubINode(limit, con_stride);
idx_type = TypeInt::make(limit_lo - stride, limit_hi - stride, limit_type->_widen);
} else {
// May overflow
overflow = true;
limit = new ConvI2LNode(limit);
register_new_node(limit, ctrl);
ConLNode* con_stride = longcon(stride);
max_idx_expr = new SubLNode(limit, con_stride);
}
register_new_node(max_idx_expr, ctrl);
} else {
if (TraceLoopPredicate) {
if (init->is_Con()) {
predString->print("%d ", con_init);
} else {
predString->print("init ");
}
}
idx_type = _igvn.type(init)->isa_int();
max_idx_expr = init;
}
if (scale != 1) {
ConNode* con_scale = intcon(scale);
if (TraceLoopPredicate) {
predString->print("* %d ", scale);
}
// Check if (scale * max_idx_expr) may overflow
const TypeInt* scale_type = TypeInt::make(scale);
MulINode* mul = new MulINode(max_idx_expr, con_scale);
if (overflow || MulINode::does_overflow(idx_type, scale_type)) {
// May overflow
idx_type = TypeInt::INT;
mul->destruct(&_igvn);
if (!overflow) {
max_idx_expr = new ConvI2LNode(max_idx_expr);
register_new_node(max_idx_expr, ctrl);
}
overflow = true;
con_scale = longcon(scale);
max_idx_expr = new MulLNode(max_idx_expr, con_scale);
} else {
// No overflow possible
max_idx_expr = mul;
idx_type = (TypeInt*)mul->mul_ring(idx_type, scale_type);
}
register_new_node(max_idx_expr, ctrl);
}
if (offset && (!offset->is_Con() || con_offset != 0)){
if (TraceLoopPredicate) {
if (offset->is_Con()) {
predString->print("+ %d ", con_offset);
} else {
predString->print("+ offset");
}
}
// Check if (max_idx_expr + offset) may overflow
const TypeInt* offset_type = _igvn.type(offset)->isa_int();
jint lo = java_add(idx_type->_lo, offset_type->_lo);
jint hi = java_add(idx_type->_hi, offset_type->_hi);
if (overflow || (lo > hi) ||
((idx_type->_lo & offset_type->_lo) < 0 && lo >= 0) ||
((~(idx_type->_hi | offset_type->_hi)) < 0 && hi < 0)) {
// May overflow
if (!overflow) {
max_idx_expr = new ConvI2LNode(max_idx_expr);
register_new_node(max_idx_expr, ctrl);
}
overflow = true;
offset = new ConvI2LNode(offset);
register_new_node(offset, ctrl);
max_idx_expr = new AddLNode(max_idx_expr, offset);
} else {
// No overflow possible
max_idx_expr = new AddINode(max_idx_expr, offset);
}
register_new_node(max_idx_expr, ctrl);
}
CmpNode* cmp = nullptr;
if (overflow) {
// Integer expressions may overflow, do long comparison
range = new ConvI2LNode(range);
register_new_node(range, ctrl);
cmp = new CmpULNode(max_idx_expr, range);
} else {
cmp = new CmpUNode(max_idx_expr, range);
}
register_new_node(cmp, ctrl);
BoolNode* bol = new BoolNode(cmp, BoolTest::lt);
register_new_node(bol, ctrl);
if (TraceLoopPredicate) {
predString->print_cr("<u range");
tty->print("%s", predString->base());
delete predString;
}
return bol;
}
// Should loop predication look not only in the path from tail to head
// but also in branches of the loop body?
bool PhaseIdealLoop::loop_predication_should_follow_branches(IdealLoopTree* loop, float& loop_trip_cnt) {
if (!UseProfiledLoopPredicate) {
return false;
}
LoopNode* head = loop->_head->as_Loop();
bool follow_branches = true;
IdealLoopTree* l = loop->_child;
// For leaf loops and loops with a single inner loop
while (l != nullptr && follow_branches) {
IdealLoopTree* child = l;
if (child->_child != nullptr &&
child->_head->is_OuterStripMinedLoop()) {
assert(child->_child->_next == nullptr, "only one inner loop for strip mined loop");
assert(child->_child->_head->is_CountedLoop() && child->_child->_head->as_CountedLoop()->is_strip_mined(), "inner loop should be strip mined");
child = child->_child;
}
if (child->_child != nullptr || child->_irreducible) {
follow_branches = false;
}
l = l->_next;
}
if (follow_branches) {
loop->compute_profile_trip_cnt(this);
if (head->is_profile_trip_failed()) {
follow_branches = false;
} else {
loop_trip_cnt = head->profile_trip_cnt();
if (head->is_CountedLoop()) {
CountedLoopNode* cl = head->as_CountedLoop();
if (cl->phi() != nullptr) {
const TypeInt* t = _igvn.type(cl->phi())->is_int();
float worst_case_trip_cnt = ((float)t->_hi - t->_lo) / ABS((float)cl->stride_con());
if (worst_case_trip_cnt < loop_trip_cnt) {
loop_trip_cnt = worst_case_trip_cnt;
}
}
}
}
}
return follow_branches;
}
float PathFrequency::to(Node* n) {
// post order walk on the CFG graph from n to _dom
IdealLoopTree* loop = _phase->get_loop(_dom);
Node* c = n;
for (;;) {
assert(_phase->get_loop(c) == loop, "have to be in the same loop");
if (c == _dom || _freqs.at_grow(c->_idx, -1) >= 0) {
float f = c == _dom ? 1 : _freqs.at(c->_idx);
Node* prev = c;
while (_stack.size() > 0 && prev == c) {
Node* n = _stack.node();
if (!n->is_Region()) {
if (_phase->get_loop(n) != _phase->get_loop(n->in(0))) {
// Found an inner loop: compute frequency of reaching this
// exit from the loop head by looking at the number of
// times each loop exit was taken
IdealLoopTree* inner_loop = _phase->get_loop(n->in(0));
LoopNode* inner_head = inner_loop->_head->as_Loop();
assert(_phase->get_loop(n) == loop, "only 1 inner loop");
if (inner_head->is_OuterStripMinedLoop()) {
inner_head->verify_strip_mined(1);
if (n->in(0) == inner_head->in(LoopNode::LoopBackControl)->in(0)) {
n = n->in(0)->in(0)->in(0);
}
inner_loop = inner_loop->_child;
inner_head = inner_loop->_head->as_Loop();
inner_head->verify_strip_mined(1);
}
float loop_exit_cnt = 0.0f;
for (uint i = 0; i < inner_loop->_body.size(); i++) {
Node *n = inner_loop->_body[i];
float c = inner_loop->compute_profile_trip_cnt_helper(n);
loop_exit_cnt += c;
}
float cnt = -1;
if (n->in(0)->is_If()) {
IfNode* iff = n->in(0)->as_If();
float p = n->in(0)->as_If()->_prob;
if (n->Opcode() == Op_IfFalse) {
p = 1 - p;
}
if (p > PROB_MIN) {
cnt = p * iff->_fcnt;
} else {
cnt = 0;
}
} else {
assert(n->in(0)->is_Jump(), "unsupported node kind");
JumpNode* jmp = n->in(0)->as_Jump();
float p = n->in(0)->as_Jump()->_probs[n->as_JumpProj()->_con];
cnt = p * jmp->_fcnt;
}
float this_exit_f = cnt > 0 ? cnt / loop_exit_cnt : 0;
this_exit_f = check_and_truncate_frequency(this_exit_f);
f = f * this_exit_f;
f = check_and_truncate_frequency(f);
} else {
float p = -1;
if (n->in(0)->is_If()) {
p = n->in(0)->as_If()->_prob;
if (n->Opcode() == Op_IfFalse) {
p = 1 - p;
}
} else {
assert(n->in(0)->is_Jump(), "unsupported node kind");
p = n->in(0)->as_Jump()->_probs[n->as_JumpProj()->_con];
}
f = f * p;
f = check_and_truncate_frequency(f);
}
_freqs.at_put_grow(n->_idx, (float)f, -1);
_stack.pop();
} else {
float prev_f = _freqs_stack.pop();
float new_f = f;
f = new_f + prev_f;
f = check_and_truncate_frequency(f);
uint i = _stack.index();
if (i < n->req()) {
c = n->in(i);
_stack.set_index(i+1);
_freqs_stack.push(f);
} else {
_freqs.at_put_grow(n->_idx, f, -1);
_stack.pop();
}
}
}
if (_stack.size() == 0) {
return check_and_truncate_frequency(f);
}
} else if (c->is_Loop()) {
ShouldNotReachHere();
c = c->in(LoopNode::EntryControl);
} else if (c->is_Region()) {
_freqs_stack.push(0);
_stack.push(c, 2);
c = c->in(1);
} else {
if (c->is_IfProj()) {
IfNode* iff = c->in(0)->as_If();
if (iff->_prob == PROB_UNKNOWN) {
// assume never taken
_freqs.at_put_grow(c->_idx, 0, -1);
} else if (_phase->get_loop(c) != _phase->get_loop(iff)) {
if (iff->_fcnt == COUNT_UNKNOWN) {
// assume never taken
_freqs.at_put_grow(c->_idx, 0, -1);
} else {
// skip over loop
_stack.push(c, 1);
c = _phase->get_loop(c->in(0))->_head->as_Loop()->skip_strip_mined()->in(LoopNode::EntryControl);
}
} else {
_stack.push(c, 1);
c = iff;
}
} else if (c->is_JumpProj()) {
JumpNode* jmp = c->in(0)->as_Jump();
if (_phase->get_loop(c) != _phase->get_loop(jmp)) {
if (jmp->_fcnt == COUNT_UNKNOWN) {
// assume never taken
_freqs.at_put_grow(c->_idx, 0, -1);
} else {
// skip over loop
_stack.push(c, 1);
c = _phase->get_loop(c->in(0))->_head->as_Loop()->skip_strip_mined()->in(LoopNode::EntryControl);
}
} else {
_stack.push(c, 1);
c = jmp;
}
} else if (c->Opcode() == Op_CatchProj &&
c->in(0)->Opcode() == Op_Catch &&
c->in(0)->in(0)->is_Proj() &&
c->in(0)->in(0)->in(0)->is_Call()) {
// assume exceptions are never thrown
uint con = c->as_Proj()->_con;
if (con == CatchProjNode::fall_through_index) {
Node* call = c->in(0)->in(0)->in(0)->in(0);
if (_phase->get_loop(call) != _phase->get_loop(c)) {
_freqs.at_put_grow(c->_idx, 0, -1);
} else {
c = call;
}
} else {
assert(con >= CatchProjNode::catch_all_index, "what else?");
_freqs.at_put_grow(c->_idx, 0, -1);
}
} else if (c->unique_ctrl_out_or_null() == nullptr && !c->is_If() && !c->is_Jump()) {
ShouldNotReachHere();
} else {
c = c->in(0);
}
}
}
ShouldNotReachHere();
return -1;
}
void PhaseIdealLoop::loop_predication_follow_branches(Node *n, IdealLoopTree *loop, float loop_trip_cnt,
PathFrequency& pf, Node_Stack& stack, VectorSet& seen,
Node_List& if_proj_list) {
assert(n->is_Region(), "start from a region");
Node* tail = loop->tail();
stack.push(n, 1);
do {
Node* c = stack.node();
assert(c->is_Region() || c->is_IfProj(), "only region here");
uint i = stack.index();
if (i < c->req()) {
stack.set_index(i+1);
Node* in = c->in(i);
while (!is_dominator(in, tail) && !seen.test_set(in->_idx)) {
IdealLoopTree* in_loop = get_loop(in);
if (in_loop != loop) {
in = in_loop->_head->in(LoopNode::EntryControl);
} else if (in->is_Region()) {
stack.push(in, 1);
break;
} else if (in->is_IfProj() &&
in->as_Proj()->is_uncommon_trap_if_pattern() &&
(in->in(0)->Opcode() == Op_If ||
in->in(0)->Opcode() == Op_RangeCheck)) {
if (pf.to(in) * loop_trip_cnt >= 1) {
stack.push(in, 1);
}
in = in->in(0);
} else {
in = in->in(0);
}
}
} else {
if (c->is_IfProj()) {
if_proj_list.push(c);
}
stack.pop();
}
} while (stack.size() > 0);
}
bool PhaseIdealLoop::loop_predication_impl_helper(IdealLoopTree* loop, IfProjNode* if_success_proj,
ParsePredicateSuccessProj* parse_predicate_proj, CountedLoopNode* cl,
ConNode* zero, Invariance& invar,
Deoptimization::DeoptReason deopt_reason) {
// Following are changed to nonnull when a predicate can be hoisted
IfNode* iff = if_success_proj->in(0)->as_If();
Node* test = iff->in(1);
if (!test->is_Bool()) { //Conv2B, ...
return false;
}
BoolNode* bol = test->as_Bool();
bool range_check_predicate = false;
if (invar.is_invariant(bol)) {
C->print_method(PHASE_BEFORE_LOOP_PREDICATION_IC, 4, iff);
// Invariant test
IfProjNode* hoisted_check_predicate_proj = create_new_if_for_predicate(parse_predicate_proj, nullptr, deopt_reason,