1 /*
2 * Copyright (c) 1998, 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 "ci/ciMethodData.hpp"
26 #include "classfile/vmSymbols.hpp"
27 #include "compiler/compileLog.hpp"
28 #include "interpreter/linkResolver.hpp"
29 #include "jvm_io.h"
30 #include "memory/resourceArea.hpp"
31 #include "memory/universe.hpp"
32 #include "oops/oop.inline.hpp"
33 #include "opto/addnode.hpp"
34 #include "opto/castnode.hpp"
35 #include "opto/convertnode.hpp"
36 #include "opto/divnode.hpp"
37 #include "opto/idealGraphPrinter.hpp"
38 #include "opto/matcher.hpp"
39 #include "opto/memnode.hpp"
40 #include "opto/mulnode.hpp"
41 #include "opto/opaquenode.hpp"
42 #include "opto/parse.hpp"
43 #include "opto/runtime.hpp"
44 #include "runtime/deoptimization.hpp"
45 #include "runtime/sharedRuntime.hpp"
46
47 #ifndef PRODUCT
48 extern uint explicit_null_checks_inserted,
49 explicit_null_checks_elided;
50 #endif
51
52 //---------------------------------array_load----------------------------------
53 void Parse::array_load(BasicType bt) {
54 const Type* elemtype = Type::TOP;
55 bool big_val = bt == T_DOUBLE || bt == T_LONG;
56 Node* adr = array_addressing(bt, 0, elemtype);
57 if (stopped()) return; // guaranteed null or range check
58
59 pop(); // index (already used)
60 Node* array = pop(); // the array itself
61
62 if (elemtype == TypeInt::BOOL) {
63 bt = T_BOOLEAN;
64 }
65 const TypeAryPtr* adr_type = TypeAryPtr::get_array_body_type(bt);
66
67 Node* ld = access_load_at(array, adr, adr_type, elemtype, bt,
68 IN_HEAP | IS_ARRAY | C2_CONTROL_DEPENDENT_LOAD);
69 if (big_val) {
70 push_pair(ld);
71 } else {
72 push(ld);
73 }
74 }
75
76
77 //--------------------------------array_store----------------------------------
78 void Parse::array_store(BasicType bt) {
79 const Type* elemtype = Type::TOP;
80 bool big_val = bt == T_DOUBLE || bt == T_LONG;
81 Node* adr = array_addressing(bt, big_val ? 2 : 1, elemtype);
82 if (stopped()) return; // guaranteed null or range check
83 if (bt == T_OBJECT) {
84 array_store_check();
85 if (stopped()) {
86 return;
87 }
88 }
89 Node* val; // Oop to store
90 if (big_val) {
91 val = pop_pair();
92 } else {
93 val = pop();
94 }
95 pop(); // index (already used)
96 Node* array = pop(); // the array itself
97
98 if (elemtype == TypeInt::BOOL) {
99 bt = T_BOOLEAN;
100 }
101 const TypeAryPtr* adr_type = TypeAryPtr::get_array_body_type(bt);
102
103 access_store_at(array, adr, adr_type, val, elemtype, bt, MO_UNORDERED | IN_HEAP | IS_ARRAY);
104 }
105
106
107 //------------------------------array_addressing-------------------------------
108 // Pull array and index from the stack. Compute pointer-to-element.
109 Node* Parse::array_addressing(BasicType type, int vals, const Type*& elemtype) {
110 Node *idx = peek(0+vals); // Get from stack without popping
111 Node *ary = peek(1+vals); // in case of exception
112
113 // Null check the array base, with correct stack contents
114 ary = null_check(ary, T_ARRAY);
115 // Compile-time detect of null-exception?
116 if (stopped()) return top();
117
118 const TypeAryPtr* arytype = _gvn.type(ary)->is_aryptr();
119 const TypeInt* sizetype = arytype->size();
120 elemtype = arytype->elem();
121
122 if (UseUniqueSubclasses) {
123 const Type* el = elemtype->make_ptr();
124 if (el && el->isa_instptr()) {
125 const TypeInstPtr* toop = el->is_instptr();
126 if (toop->instance_klass()->unique_concrete_subklass()) {
127 // If we load from "AbstractClass[]" we must see "ConcreteSubClass".
128 const Type* subklass = Type::get_const_type(toop->instance_klass());
129 elemtype = subklass->join_speculative(el);
130 }
131 }
132 }
133
134 // Check for big class initializers with all constant offsets
135 // feeding into a known-size array.
136 const TypeInt* idxtype = _gvn.type(idx)->is_int();
137 // See if the highest idx value is less than the lowest array bound,
138 // and if the idx value cannot be negative:
139 bool need_range_check = true;
140 if (idxtype->_hi < sizetype->_lo && idxtype->_lo >= 0) {
141 need_range_check = false;
142 if (C->log() != nullptr) C->log()->elem("observe that='!need_range_check'");
143 }
144
145 if (!arytype->is_loaded()) {
146 // Only fails for some -Xcomp runs
147 // The class is unloaded. We have to run this bytecode in the interpreter.
148 ciKlass* klass = arytype->unloaded_klass();
149
150 uncommon_trap(Deoptimization::Reason_unloaded,
151 Deoptimization::Action_reinterpret,
152 klass, "!loaded array");
153 return top();
154 }
155
156 // Do the range check
157 if (need_range_check) {
158 Node* tst;
159 if (sizetype->_hi <= 0) {
160 // The greatest array bound is negative, so we can conclude that we're
161 // compiling unreachable code, but the unsigned compare trick used below
162 // only works with non-negative lengths. Instead, hack "tst" to be zero so
163 // the uncommon_trap path will always be taken.
164 tst = _gvn.intcon(0);
165 } else {
166 // Range is constant in array-oop, so we can use the original state of mem
167 Node* len = load_array_length(ary);
168
169 // Test length vs index (standard trick using unsigned compare)
170 Node* chk = _gvn.transform( new CmpUNode(idx, len) );
171 BoolTest::mask btest = BoolTest::lt;
172 tst = _gvn.transform( new BoolNode(chk, btest) );
173 }
174 RangeCheckNode* rc = new RangeCheckNode(control(), tst, PROB_MAX, COUNT_UNKNOWN);
175 _gvn.set_type(rc, rc->Value(&_gvn));
176 if (!tst->is_Con()) {
177 record_for_igvn(rc);
178 }
179 set_control(_gvn.transform(new IfTrueNode(rc)));
180 // Branch to failure if out of bounds
181 {
182 PreserveJVMState pjvms(this);
183 set_control(_gvn.transform(new IfFalseNode(rc)));
184 if (C->allow_range_check_smearing()) {
185 // Do not use builtin_throw, since range checks are sometimes
186 // made more stringent by an optimistic transformation.
187 // This creates "tentative" range checks at this point,
188 // which are not guaranteed to throw exceptions.
189 // See IfNode::Ideal, is_range_check, adjust_check.
190 uncommon_trap(Deoptimization::Reason_range_check,
191 Deoptimization::Action_make_not_entrant,
192 nullptr, "range_check");
193 } else {
194 // If we have already recompiled with the range-check-widening
195 // heroic optimization turned off, then we must really be throwing
196 // range check exceptions.
197 builtin_throw(Deoptimization::Reason_range_check);
198 }
199 }
200 }
201 // Check for always knowing you are throwing a range-check exception
202 if (stopped()) return top();
203
204 // Make array address computation control dependent to prevent it
205 // from floating above the range check during loop optimizations.
206 Node* ptr = array_element_address(ary, idx, type, sizetype, control());
207 assert(ptr != top(), "top should go hand-in-hand with stopped");
208
209 return ptr;
210 }
211
212
213 // returns IfNode
214 IfNode* Parse::jump_if_fork_int(Node* a, Node* b, BoolTest::mask mask, float prob, float cnt) {
215 Node *cmp = _gvn.transform(new CmpINode(a, b)); // two cases: shiftcount > 32 and shiftcount <= 32
216 Node *tst = _gvn.transform(new BoolNode(cmp, mask));
217 IfNode *iff = create_and_map_if(control(), tst, prob, cnt);
218 return iff;
219 }
220
221
222 // sentinel value for the target bci to mark never taken branches
223 // (according to profiling)
224 static const int never_reached = INT_MAX;
225
226 //------------------------------helper for tableswitch-------------------------
227 void Parse::jump_if_true_fork(IfNode *iff, int dest_bci_if_true, bool unc) {
228 // True branch, use existing map info
229 { PreserveJVMState pjvms(this);
230 Node *iftrue = _gvn.transform( new IfTrueNode (iff) );
231 set_control( iftrue );
232 if (unc) {
233 repush_if_args();
234 uncommon_trap(Deoptimization::Reason_unstable_if,
235 Deoptimization::Action_reinterpret,
236 nullptr,
237 "taken always");
238 } else {
239 assert(dest_bci_if_true != never_reached, "inconsistent dest");
240 merge_new_path(dest_bci_if_true);
241 }
242 }
243
244 // False branch
245 Node *iffalse = _gvn.transform( new IfFalseNode(iff) );
246 set_control( iffalse );
247 }
248
249 void Parse::jump_if_false_fork(IfNode *iff, int dest_bci_if_true, bool unc) {
250 // True branch, use existing map info
251 { PreserveJVMState pjvms(this);
252 Node *iffalse = _gvn.transform( new IfFalseNode (iff) );
253 set_control( iffalse );
254 if (unc) {
255 repush_if_args();
256 uncommon_trap(Deoptimization::Reason_unstable_if,
257 Deoptimization::Action_reinterpret,
258 nullptr,
259 "taken never");
260 } else {
261 assert(dest_bci_if_true != never_reached, "inconsistent dest");
262 merge_new_path(dest_bci_if_true);
263 }
264 }
265
266 // False branch
267 Node *iftrue = _gvn.transform( new IfTrueNode(iff) );
268 set_control( iftrue );
269 }
270
271 void Parse::jump_if_always_fork(int dest_bci, bool unc) {
272 // False branch, use existing map and control()
273 if (unc) {
274 repush_if_args();
275 uncommon_trap(Deoptimization::Reason_unstable_if,
276 Deoptimization::Action_reinterpret,
277 nullptr,
278 "taken never");
279 } else {
280 assert(dest_bci != never_reached, "inconsistent dest");
281 merge_new_path(dest_bci);
282 }
283 }
284
285
286 extern "C" {
287 static int jint_cmp(const void *i, const void *j) {
288 int a = *(jint *)i;
289 int b = *(jint *)j;
290 return a > b ? 1 : a < b ? -1 : 0;
291 }
292 }
293
294
295 class SwitchRange : public StackObj {
296 // a range of integers coupled with a bci destination
297 jint _lo; // inclusive lower limit
298 jint _hi; // inclusive upper limit
299 int _dest;
300 float _cnt; // how many times this range was hit according to profiling
301
302 public:
303 jint lo() const { return _lo; }
304 jint hi() const { return _hi; }
305 int dest() const { return _dest; }
306 bool is_singleton() const { return _lo == _hi; }
307 float cnt() const { return _cnt; }
308
309 void setRange(jint lo, jint hi, int dest, float cnt) {
310 assert(lo <= hi, "must be a non-empty range");
311 _lo = lo, _hi = hi; _dest = dest; _cnt = cnt;
312 assert(_cnt >= 0, "");
313 }
314 bool adjoinRange(jint lo, jint hi, int dest, float cnt, bool trim_ranges) {
315 assert(lo <= hi, "must be a non-empty range");
316 if (lo == _hi+1) {
317 // see merge_ranges() comment below
318 if (trim_ranges) {
319 if (cnt == 0) {
320 if (_cnt != 0) {
321 return false;
322 }
323 if (dest != _dest) {
324 _dest = never_reached;
325 }
326 } else {
327 if (_cnt == 0) {
328 return false;
329 }
330 if (dest != _dest) {
331 return false;
332 }
333 }
334 } else {
335 if (dest != _dest) {
336 return false;
337 }
338 }
339 _hi = hi;
340 _cnt += cnt;
341 return true;
342 }
343 return false;
344 }
345
346 void set (jint value, int dest, float cnt) {
347 setRange(value, value, dest, cnt);
348 }
349 bool adjoin(jint value, int dest, float cnt, bool trim_ranges) {
350 return adjoinRange(value, value, dest, cnt, trim_ranges);
351 }
352 bool adjoin(SwitchRange& other) {
353 return adjoinRange(other._lo, other._hi, other._dest, other._cnt, false);
354 }
355
356 void print() {
357 if (is_singleton())
358 tty->print(" {%d}=>%d (cnt=%f)", lo(), dest(), cnt());
359 else if (lo() == min_jint)
360 tty->print(" {..%d}=>%d (cnt=%f)", hi(), dest(), cnt());
361 else if (hi() == max_jint)
362 tty->print(" {%d..}=>%d (cnt=%f)", lo(), dest(), cnt());
363 else
364 tty->print(" {%d..%d}=>%d (cnt=%f)", lo(), hi(), dest(), cnt());
365 }
366 };
367
368 // We try to minimize the number of ranges and the size of the taken
369 // ones using profiling data. When ranges are created,
370 // SwitchRange::adjoinRange() only allows 2 adjoining ranges to merge
371 // if both were never hit or both were hit to build longer unreached
372 // ranges. Here, we now merge adjoining ranges with the same
373 // destination and finally set destination of unreached ranges to the
374 // special value never_reached because it can help minimize the number
375 // of tests that are necessary.
376 //
377 // For instance:
378 // [0, 1] to target1 sometimes taken
379 // [1, 2] to target1 never taken
380 // [2, 3] to target2 never taken
381 // would lead to:
382 // [0, 1] to target1 sometimes taken
383 // [1, 3] never taken
384 //
385 // (first 2 ranges to target1 are not merged)
386 static void merge_ranges(SwitchRange* ranges, int& rp) {
387 if (rp == 0) {
388 return;
389 }
390 int shift = 0;
391 for (int j = 0; j < rp; j++) {
392 SwitchRange& r1 = ranges[j-shift];
393 SwitchRange& r2 = ranges[j+1];
394 if (r1.adjoin(r2)) {
395 shift++;
396 } else if (shift > 0) {
397 ranges[j+1-shift] = r2;
398 }
399 }
400 rp -= shift;
401 for (int j = 0; j <= rp; j++) {
402 SwitchRange& r = ranges[j];
403 if (r.cnt() == 0 && r.dest() != never_reached) {
404 r.setRange(r.lo(), r.hi(), never_reached, r.cnt());
405 }
406 }
407 }
408
409 //-------------------------------do_tableswitch--------------------------------
410 void Parse::do_tableswitch() {
411 // Get information about tableswitch
412 int default_dest = iter().get_dest_table(0);
413 jint lo_index = iter().get_int_table(1);
414 jint hi_index = iter().get_int_table(2);
415 int len = hi_index - lo_index + 1;
416
417 if (len < 1) {
418 // If this is a backward branch, add safepoint
419 maybe_add_safepoint(default_dest);
420 pop(); // the effect of the instruction execution on the operand stack
421 merge(default_dest);
422 return;
423 }
424
425 ciMethodData* methodData = method()->method_data();
426 ciMultiBranchData* profile = nullptr;
427 if (methodData->is_mature() && UseSwitchProfiling) {
428 ciProfileData* data = methodData->bci_to_data(bci());
429 if (data != nullptr && data->is_MultiBranchData()) {
430 profile = (ciMultiBranchData*)data;
431 }
432 }
433 bool trim_ranges = !C->too_many_traps(method(), bci(), Deoptimization::Reason_unstable_if);
434
435 // generate decision tree, using trichotomy when possible
436 int rnum = len+2;
437 bool makes_backward_branch = (default_dest <= bci());
438 SwitchRange* ranges = NEW_RESOURCE_ARRAY(SwitchRange, rnum);
439 int rp = -1;
440 if (lo_index != min_jint) {
441 float cnt = 1.0F;
442 if (profile != nullptr) {
443 cnt = (float)profile->default_count() / (hi_index != max_jint ? 2.0F : 1.0F);
444 }
445 ranges[++rp].setRange(min_jint, lo_index-1, default_dest, cnt);
446 }
447 for (int j = 0; j < len; j++) {
448 jint match_int = lo_index+j;
449 int dest = iter().get_dest_table(j+3);
450 makes_backward_branch |= (dest <= bci());
451 float cnt = 1.0F;
452 if (profile != nullptr) {
453 cnt = (float)profile->count_at(j);
454 }
455 if (rp < 0 || !ranges[rp].adjoin(match_int, dest, cnt, trim_ranges)) {
456 ranges[++rp].set(match_int, dest, cnt);
457 }
458 }
459 jint highest = lo_index+(len-1);
460 assert(ranges[rp].hi() == highest, "");
461 if (highest != max_jint) {
462 float cnt = 1.0F;
463 if (profile != nullptr) {
464 cnt = (float)profile->default_count() / (lo_index != min_jint ? 2.0F : 1.0F);
465 }
466 if (!ranges[rp].adjoinRange(highest+1, max_jint, default_dest, cnt, trim_ranges)) {
467 ranges[++rp].setRange(highest+1, max_jint, default_dest, cnt);
468 }
469 }
470 assert(rp < len+2, "not too many ranges");
471
472 if (trim_ranges) {
473 merge_ranges(ranges, rp);
474 }
475
476 // Safepoint in case if backward branch observed
477 if (makes_backward_branch) {
478 add_safepoint();
479 }
480
481 Node* lookup = pop(); // lookup value
482 jump_switch_ranges(lookup, &ranges[0], &ranges[rp]);
483 }
484
485
486 //------------------------------do_lookupswitch--------------------------------
487 void Parse::do_lookupswitch() {
488 // Get information about lookupswitch
489 int default_dest = iter().get_dest_table(0);
490 jint len = iter().get_int_table(1);
491
492 if (len < 1) { // If this is a backward branch, add safepoint
493 maybe_add_safepoint(default_dest);
494 pop(); // the effect of the instruction execution on the operand stack
495 merge(default_dest);
496 return;
497 }
498
499 ciMethodData* methodData = method()->method_data();
500 ciMultiBranchData* profile = nullptr;
501 if (methodData->is_mature() && UseSwitchProfiling) {
502 ciProfileData* data = methodData->bci_to_data(bci());
503 if (data != nullptr && data->is_MultiBranchData()) {
504 profile = (ciMultiBranchData*)data;
505 }
506 }
507 bool trim_ranges = !C->too_many_traps(method(), bci(), Deoptimization::Reason_unstable_if);
508
509 // generate decision tree, using trichotomy when possible
510 jint* table = NEW_RESOURCE_ARRAY(jint, len*3);
511 {
512 for (int j = 0; j < len; j++) {
513 table[3*j+0] = iter().get_int_table(2+2*j);
514 table[3*j+1] = iter().get_dest_table(2+2*j+1);
515 // Handle overflow when converting from uint to jint
516 table[3*j+2] = (profile == nullptr) ? 1 : (jint)MIN2<uint>((uint)max_jint, profile->count_at(j));
517 }
518 qsort(table, len, 3*sizeof(table[0]), jint_cmp);
519 }
520
521 float default_cnt = 1.0F;
522 if (profile != nullptr) {
523 juint defaults = max_juint - len;
524 default_cnt = (float)profile->default_count()/(float)defaults;
525 }
526
527 int rnum = len*2+1;
528 bool makes_backward_branch = (default_dest <= bci());
529 SwitchRange* ranges = NEW_RESOURCE_ARRAY(SwitchRange, rnum);
530 int rp = -1;
531 for (int j = 0; j < len; j++) {
532 jint match_int = table[3*j+0];
533 jint dest = table[3*j+1];
534 jint cnt = table[3*j+2];
535 jint next_lo = rp < 0 ? min_jint : ranges[rp].hi()+1;
536 makes_backward_branch |= (dest <= bci());
537 float c = default_cnt * ((float)match_int - (float)next_lo);
538 if (match_int != next_lo && (rp < 0 || !ranges[rp].adjoinRange(next_lo, match_int-1, default_dest, c, trim_ranges))) {
539 assert(default_dest != never_reached, "sentinel value for dead destinations");
540 ranges[++rp].setRange(next_lo, match_int-1, default_dest, c);
541 }
542 if (rp < 0 || !ranges[rp].adjoin(match_int, dest, (float)cnt, trim_ranges)) {
543 assert(dest != never_reached, "sentinel value for dead destinations");
544 ranges[++rp].set(match_int, dest, (float)cnt);
545 }
546 }
547 jint highest = table[3*(len-1)];
548 assert(ranges[rp].hi() == highest, "");
549 if (highest != max_jint &&
550 !ranges[rp].adjoinRange(highest+1, max_jint, default_dest, default_cnt * ((float)max_jint - (float)highest), trim_ranges)) {
551 ranges[++rp].setRange(highest+1, max_jint, default_dest, default_cnt * ((float)max_jint - (float)highest));
552 }
553 assert(rp < rnum, "not too many ranges");
554
555 if (trim_ranges) {
556 merge_ranges(ranges, rp);
557 }
558
559 // Safepoint in case backward branch observed
560 if (makes_backward_branch) {
561 add_safepoint();
562 }
563
564 Node *lookup = pop(); // lookup value
565 jump_switch_ranges(lookup, &ranges[0], &ranges[rp]);
566 }
567
568 static float if_prob(float taken_cnt, float total_cnt) {
569 assert(taken_cnt <= total_cnt, "");
570 if (total_cnt == 0) {
571 return PROB_FAIR;
572 }
573 float p = taken_cnt / total_cnt;
574 return clamp(p, PROB_MIN, PROB_MAX);
575 }
576
577 static float if_cnt(float cnt) {
578 if (cnt == 0) {
579 return COUNT_UNKNOWN;
580 }
581 return cnt;
582 }
583
584 static float sum_of_cnts(SwitchRange *lo, SwitchRange *hi) {
585 float total_cnt = 0;
586 for (SwitchRange* sr = lo; sr <= hi; sr++) {
587 total_cnt += sr->cnt();
588 }
589 return total_cnt;
590 }
591
592 class SwitchRanges : public ResourceObj {
593 public:
594 SwitchRange* _lo;
595 SwitchRange* _hi;
596 SwitchRange* _mid;
597 float _cost;
598
599 enum {
600 Start,
601 LeftDone,
602 RightDone,
603 Done
604 } _state;
605
606 SwitchRanges(SwitchRange *lo, SwitchRange *hi)
607 : _lo(lo), _hi(hi), _mid(nullptr),
608 _cost(0), _state(Start) {
609 }
610
611 SwitchRanges()
612 : _lo(nullptr), _hi(nullptr), _mid(nullptr),
613 _cost(0), _state(Start) {}
614 };
615
616 // Estimate cost of performing a binary search on lo..hi
617 static float compute_tree_cost(SwitchRange *lo, SwitchRange *hi, float total_cnt) {
618 GrowableArray<SwitchRanges> tree;
619 SwitchRanges root(lo, hi);
620 tree.push(root);
621
622 float cost = 0;
623 do {
624 SwitchRanges& r = *tree.adr_at(tree.length()-1);
625 if (r._hi != r._lo) {
626 if (r._mid == nullptr) {
627 float r_cnt = sum_of_cnts(r._lo, r._hi);
628
629 if (r_cnt == 0) {
630 tree.pop();
631 cost = 0;
632 continue;
633 }
634
635 SwitchRange* mid = nullptr;
636 mid = r._lo;
637 for (float cnt = 0; ; ) {
638 assert(mid <= r._hi, "out of bounds");
639 cnt += mid->cnt();
640 if (cnt > r_cnt / 2) {
641 break;
642 }
643 mid++;
644 }
645 assert(mid <= r._hi, "out of bounds");
646 r._mid = mid;
647 r._cost = r_cnt / total_cnt;
648 }
649 r._cost += cost;
650 if (r._state < SwitchRanges::LeftDone && r._mid > r._lo) {
651 cost = 0;
652 r._state = SwitchRanges::LeftDone;
653 tree.push(SwitchRanges(r._lo, r._mid-1));
654 } else if (r._state < SwitchRanges::RightDone) {
655 cost = 0;
656 r._state = SwitchRanges::RightDone;
657 tree.push(SwitchRanges(r._mid == r._lo ? r._mid+1 : r._mid, r._hi));
658 } else {
659 tree.pop();
660 cost = r._cost;
661 }
662 } else {
663 tree.pop();
664 cost = r._cost;
665 }
666 } while (tree.length() > 0);
667
668
669 return cost;
670 }
671
672 // It sometimes pays off to test most common ranges before the binary search
673 void Parse::linear_search_switch_ranges(Node* key_val, SwitchRange*& lo, SwitchRange*& hi) {
674 uint nr = hi - lo + 1;
675 float total_cnt = sum_of_cnts(lo, hi);
676
677 float min = compute_tree_cost(lo, hi, total_cnt);
678 float extra = 1;
679 float sub = 0;
680
681 SwitchRange* array1 = lo;
682 SwitchRange* array2 = NEW_RESOURCE_ARRAY(SwitchRange, nr);
683
684 SwitchRange* ranges = nullptr;
685
686 while (nr >= 2) {
687 assert(lo == array1 || lo == array2, "one the 2 already allocated arrays");
688 ranges = (lo == array1) ? array2 : array1;
689
690 // Find highest frequency range
691 SwitchRange* candidate = lo;
692 for (SwitchRange* sr = lo+1; sr <= hi; sr++) {
693 if (sr->cnt() > candidate->cnt()) {
694 candidate = sr;
695 }
696 }
697 SwitchRange most_freq = *candidate;
698 if (most_freq.cnt() == 0) {
699 break;
700 }
701
702 // Copy remaining ranges into another array
703 int shift = 0;
704 for (uint i = 0; i < nr; i++) {
705 SwitchRange* sr = &lo[i];
706 if (sr != candidate) {
707 ranges[i-shift] = *sr;
708 } else {
709 shift++;
710 if (i > 0 && i < nr-1) {
711 SwitchRange prev = lo[i-1];
712 prev.setRange(prev.lo(), sr->hi(), prev.dest(), prev.cnt());
713 if (prev.adjoin(lo[i+1])) {
714 shift++;
715 i++;
716 }
717 ranges[i-shift] = prev;
718 }
719 }
720 }
721 nr -= shift;
722
723 // Evaluate cost of testing the most common range and performing a
724 // binary search on the other ranges
725 float cost = extra + compute_tree_cost(&ranges[0], &ranges[nr-1], total_cnt);
726 if (cost >= min) {
727 break;
728 }
729 // swap arrays
730 lo = &ranges[0];
731 hi = &ranges[nr-1];
732
733 // It pays off: emit the test for the most common range
734 assert(most_freq.cnt() > 0, "must be taken");
735 Node* val = _gvn.transform(new SubINode(key_val, _gvn.intcon(most_freq.lo())));
736 Node* cmp = _gvn.transform(new CmpUNode(val, _gvn.intcon(java_subtract(most_freq.hi(), most_freq.lo()))));
737 Node* tst = _gvn.transform(new BoolNode(cmp, BoolTest::le));
738 IfNode* iff = create_and_map_if(control(), tst, if_prob(most_freq.cnt(), total_cnt), if_cnt(most_freq.cnt()));
739 jump_if_true_fork(iff, most_freq.dest(), false);
740
741 sub += most_freq.cnt() / total_cnt;
742 extra += 1 - sub;
743 min = cost;
744 }
745 }
746
747 //----------------------------create_jump_tables-------------------------------
748 bool Parse::create_jump_tables(Node* key_val, SwitchRange* lo, SwitchRange* hi) {
749 // Are jumptables enabled
750 if (!UseJumpTables) return false;
751
752 // Are jumptables supported
753 if (!Matcher::has_match_rule(Op_Jump)) return false;
754
755 bool trim_ranges = !C->too_many_traps(method(), bci(), Deoptimization::Reason_unstable_if);
756
757 // Decide if a guard is needed to lop off big ranges at either (or
758 // both) end(s) of the input set. We'll call this the default target
759 // even though we can't be sure that it is the true "default".
760
761 bool needs_guard = false;
762 int default_dest;
763 int64_t total_outlier_size = 0;
764 int64_t hi_size = ((int64_t)hi->hi()) - ((int64_t)hi->lo()) + 1;
765 int64_t lo_size = ((int64_t)lo->hi()) - ((int64_t)lo->lo()) + 1;
766
767 if (lo->dest() == hi->dest()) {
768 total_outlier_size = hi_size + lo_size;
769 default_dest = lo->dest();
770 } else if (lo_size > hi_size) {
771 total_outlier_size = lo_size;
772 default_dest = lo->dest();
773 } else {
774 total_outlier_size = hi_size;
775 default_dest = hi->dest();
776 }
777
778 float total = sum_of_cnts(lo, hi);
779 float cost = compute_tree_cost(lo, hi, total);
780
781 // If a guard test will eliminate very sparse end ranges, then
782 // it is worth the cost of an extra jump.
783 float trimmed_cnt = 0;
784 if (total_outlier_size > (MaxJumpTableSparseness * 4)) {
785 needs_guard = true;
786 if (default_dest == lo->dest()) {
787 trimmed_cnt += lo->cnt();
788 lo++;
789 }
790 if (default_dest == hi->dest()) {
791 trimmed_cnt += hi->cnt();
792 hi--;
793 }
794 }
795
796 // Find the total number of cases and ranges
797 int64_t num_cases = ((int64_t)hi->hi()) - ((int64_t)lo->lo()) + 1;
798 int num_range = hi - lo + 1;
799
800 // Don't create table if: too large, too small, or too sparse.
801 if (num_cases > MaxJumpTableSize)
802 return false;
803 if (UseSwitchProfiling) {
804 // MinJumpTableSize is set so with a well balanced binary tree,
805 // when the number of ranges is MinJumpTableSize, it's cheaper to
806 // go through a JumpNode that a tree of IfNodes. Average cost of a
807 // tree of IfNodes with MinJumpTableSize is
808 // log2f(MinJumpTableSize) comparisons. So if the cost computed
809 // from profile data is less than log2f(MinJumpTableSize) then
810 // going with the binary search is cheaper.
811 if (cost < log2f(MinJumpTableSize)) {
812 return false;
813 }
814 } else {
815 if (num_cases < MinJumpTableSize)
816 return false;
817 }
818 if (num_cases > (MaxJumpTableSparseness * num_range))
819 return false;
820
821 // Normalize table lookups to zero
822 int lowval = lo->lo();
823 key_val = _gvn.transform( new SubINode(key_val, _gvn.intcon(lowval)) );
824
825 // Generate a guard to protect against input keyvals that aren't
826 // in the switch domain.
827 if (needs_guard) {
828 Node* size = _gvn.intcon(num_cases);
829 Node* cmp = _gvn.transform(new CmpUNode(key_val, size));
830 Node* tst = _gvn.transform(new BoolNode(cmp, BoolTest::ge));
831 IfNode* iff = create_and_map_if(control(), tst, if_prob(trimmed_cnt, total), if_cnt(trimmed_cnt));
832 jump_if_true_fork(iff, default_dest, trim_ranges && trimmed_cnt == 0);
833
834 total -= trimmed_cnt;
835 }
836
837 // Create an ideal node JumpTable that has projections
838 // of all possible ranges for a switch statement
839 // The key_val input must be converted to a pointer offset and scaled.
840 // Compare Parse::array_addressing above.
841
842 // Clean the 32-bit int into a real 64-bit offset.
843 // Otherwise, the jint value 0 might turn into an offset of 0x0800000000.
844 // Make I2L conversion control dependent to prevent it from
845 // floating above the range check during loop optimizations.
846 // Do not use a narrow int type here to prevent the data path from dying
847 // while the control path is not removed. This can happen if the type of key_val
848 // is later known to be out of bounds of [0, num_cases] and therefore a narrow cast
849 // would be replaced by TOP while C2 is not able to fold the corresponding range checks.
850 // Set _carry_dependency for the cast to avoid being removed by IGVN.
851 #ifdef _LP64
852 key_val = C->constrained_convI2L(&_gvn, key_val, TypeInt::INT, control(), true /* carry_dependency */);
853 #endif
854
855 // Shift the value by wordsize so we have an index into the table, rather
856 // than a switch value
857 Node *shiftWord = _gvn.MakeConX(wordSize);
858 key_val = _gvn.transform( new MulXNode( key_val, shiftWord));
859
860 // Create the JumpNode
861 Arena* arena = C->comp_arena();
862 float* probs = (float*)arena->Amalloc(sizeof(float)*num_cases);
863 int i = 0;
864 if (total == 0) {
865 for (SwitchRange* r = lo; r <= hi; r++) {
866 for (int64_t j = r->lo(); j <= r->hi(); j++, i++) {
867 probs[i] = 1.0F / num_cases;
868 }
869 }
870 } else {
871 for (SwitchRange* r = lo; r <= hi; r++) {
872 float prob = r->cnt()/total;
873 for (int64_t j = r->lo(); j <= r->hi(); j++, i++) {
874 probs[i] = prob / (r->hi() - r->lo() + 1);
875 }
876 }
877 }
878
879 ciMethodData* methodData = method()->method_data();
880 ciMultiBranchData* profile = nullptr;
881 if (methodData->is_mature()) {
882 ciProfileData* data = methodData->bci_to_data(bci());
883 if (data != nullptr && data->is_MultiBranchData()) {
884 profile = (ciMultiBranchData*)data;
885 }
886 }
887
888 Node* jtn = _gvn.transform(new JumpNode(control(), key_val, num_cases, probs, profile == nullptr ? COUNT_UNKNOWN : total));
889
890 // These are the switch destinations hanging off the jumpnode
891 i = 0;
892 for (SwitchRange* r = lo; r <= hi; r++) {
893 for (int64_t j = r->lo(); j <= r->hi(); j++, i++) {
894 Node* input = _gvn.transform(new JumpProjNode(jtn, i, r->dest(), (int)(j - lowval)));
895 {
896 PreserveJVMState pjvms(this);
897 set_control(input);
898 jump_if_always_fork(r->dest(), trim_ranges && r->cnt() == 0);
899 }
900 }
901 }
902 assert(i == num_cases, "miscount of cases");
903 stop_and_kill_map(); // no more uses for this JVMS
904 return true;
905 }
906
907 //----------------------------jump_switch_ranges-------------------------------
908 void Parse::jump_switch_ranges(Node* key_val, SwitchRange *lo, SwitchRange *hi, int switch_depth) {
909 Block* switch_block = block();
910 bool trim_ranges = !C->too_many_traps(method(), bci(), Deoptimization::Reason_unstable_if);
911
912 if (switch_depth == 0) {
913 // Do special processing for the top-level call.
914 assert(lo->lo() == min_jint, "initial range must exhaust Type::INT");
915 assert(hi->hi() == max_jint, "initial range must exhaust Type::INT");
916
917 // Decrement pred-numbers for the unique set of nodes.
918 #ifdef ASSERT
919 if (!trim_ranges) {
920 // Ensure that the block's successors are a (duplicate-free) set.
921 int successors_counted = 0; // block occurrences in [hi..lo]
922 int unique_successors = switch_block->num_successors();
923 for (int i = 0; i < unique_successors; i++) {
924 Block* target = switch_block->successor_at(i);
925
926 // Check that the set of successors is the same in both places.
927 int successors_found = 0;
928 for (SwitchRange* p = lo; p <= hi; p++) {
929 if (p->dest() == target->start()) successors_found++;
930 }
931 assert(successors_found > 0, "successor must be known");
932 successors_counted += successors_found;
933 }
934 assert(successors_counted == (hi-lo)+1, "no unexpected successors");
935 }
936 #endif
937
938 // Maybe prune the inputs, based on the type of key_val.
939 jint min_val = min_jint;
940 jint max_val = max_jint;
941 const TypeInt* ti = key_val->bottom_type()->isa_int();
942 if (ti != nullptr) {
943 min_val = ti->_lo;
944 max_val = ti->_hi;
945 assert(min_val <= max_val, "invalid int type");
946 }
947 while (lo->hi() < min_val) {
948 lo++;
949 }
950 if (lo->lo() < min_val) {
951 lo->setRange(min_val, lo->hi(), lo->dest(), lo->cnt());
952 }
953 while (hi->lo() > max_val) {
954 hi--;
955 }
956 if (hi->hi() > max_val) {
957 hi->setRange(hi->lo(), max_val, hi->dest(), hi->cnt());
958 }
959
960 linear_search_switch_ranges(key_val, lo, hi);
961 }
962
963 #ifndef PRODUCT
964 if (switch_depth == 0) {
965 _max_switch_depth = 0;
966 _est_switch_depth = log2i_graceful((hi - lo + 1) - 1) + 1;
967 }
968 #endif
969
970 assert(lo <= hi, "must be a non-empty set of ranges");
971 if (lo == hi) {
972 jump_if_always_fork(lo->dest(), trim_ranges && lo->cnt() == 0);
973 } else {
974 assert(lo->hi() == (lo+1)->lo()-1, "contiguous ranges");
975 assert(hi->lo() == (hi-1)->hi()+1, "contiguous ranges");
976
977 if (create_jump_tables(key_val, lo, hi)) return;
978
979 SwitchRange* mid = nullptr;
980 float total_cnt = sum_of_cnts(lo, hi);
981
982 int nr = hi - lo + 1;
983 if (UseSwitchProfiling) {
984 // Don't keep the binary search tree balanced: pick up mid point
985 // that split frequencies in half.
986 float cnt = 0;
987 for (SwitchRange* sr = lo; sr <= hi; sr++) {
988 cnt += sr->cnt();
989 if (cnt >= total_cnt / 2) {
990 mid = sr;
991 break;
992 }
993 }
994 } else {
995 mid = lo + nr/2;
996
997 // if there is an easy choice, pivot at a singleton:
998 if (nr > 3 && !mid->is_singleton() && (mid-1)->is_singleton()) mid--;
999
1000 assert(lo < mid && mid <= hi, "good pivot choice");
1001 assert(nr != 2 || mid == hi, "should pick higher of 2");
1002 assert(nr != 3 || mid == hi-1, "should pick middle of 3");
1003 }
1004
1005
1006 Node *test_val = _gvn.intcon(mid == lo ? mid->hi() : mid->lo());
1007
1008 if (mid->is_singleton()) {
1009 IfNode *iff_ne = jump_if_fork_int(key_val, test_val, BoolTest::ne, 1-if_prob(mid->cnt(), total_cnt), if_cnt(mid->cnt()));
1010 jump_if_false_fork(iff_ne, mid->dest(), trim_ranges && mid->cnt() == 0);
1011
1012 // Special Case: If there are exactly three ranges, and the high
1013 // and low range each go to the same place, omit the "gt" test,
1014 // since it will not discriminate anything.
1015 bool eq_test_only = (hi == lo+2 && hi->dest() == lo->dest() && mid == hi-1) || mid == lo;
1016
1017 // if there is a higher range, test for it and process it:
1018 if (mid < hi && !eq_test_only) {
1019 // two comparisons of same values--should enable 1 test for 2 branches
1020 // Use BoolTest::lt instead of BoolTest::gt
1021 float cnt = sum_of_cnts(lo, mid-1);
1022 IfNode *iff_lt = jump_if_fork_int(key_val, test_val, BoolTest::lt, if_prob(cnt, total_cnt), if_cnt(cnt));
1023 Node *iftrue = _gvn.transform( new IfTrueNode(iff_lt) );
1024 Node *iffalse = _gvn.transform( new IfFalseNode(iff_lt) );
1025 { PreserveJVMState pjvms(this);
1026 set_control(iffalse);
1027 jump_switch_ranges(key_val, mid+1, hi, switch_depth+1);
1028 }
1029 set_control(iftrue);
1030 }
1031
1032 } else {
1033 // mid is a range, not a singleton, so treat mid..hi as a unit
1034 float cnt = sum_of_cnts(mid == lo ? mid+1 : mid, hi);
1035 IfNode *iff_ge = jump_if_fork_int(key_val, test_val, mid == lo ? BoolTest::gt : BoolTest::ge, if_prob(cnt, total_cnt), if_cnt(cnt));
1036
1037 // if there is a higher range, test for it and process it:
1038 if (mid == hi) {
1039 jump_if_true_fork(iff_ge, mid->dest(), trim_ranges && cnt == 0);
1040 } else {
1041 Node *iftrue = _gvn.transform( new IfTrueNode(iff_ge) );
1042 Node *iffalse = _gvn.transform( new IfFalseNode(iff_ge) );
1043 { PreserveJVMState pjvms(this);
1044 set_control(iftrue);
1045 jump_switch_ranges(key_val, mid == lo ? mid+1 : mid, hi, switch_depth+1);
1046 }
1047 set_control(iffalse);
1048 }
1049 }
1050
1051 // in any case, process the lower range
1052 if (mid == lo) {
1053 if (mid->is_singleton()) {
1054 jump_switch_ranges(key_val, lo+1, hi, switch_depth+1);
1055 } else {
1056 jump_if_always_fork(lo->dest(), trim_ranges && lo->cnt() == 0);
1057 }
1058 } else {
1059 jump_switch_ranges(key_val, lo, mid-1, switch_depth+1);
1060 }
1061 }
1062
1063 // Decrease pred_count for each successor after all is done.
1064 if (switch_depth == 0) {
1065 int unique_successors = switch_block->num_successors();
1066 for (int i = 0; i < unique_successors; i++) {
1067 Block* target = switch_block->successor_at(i);
1068 // Throw away the pre-allocated path for each unique successor.
1069 target->next_path_num();
1070 }
1071 }
1072
1073 #ifndef PRODUCT
1074 _max_switch_depth = MAX2(switch_depth, _max_switch_depth);
1075 if (TraceOptoParse && Verbose && WizardMode && switch_depth == 0) {
1076 SwitchRange* r;
1077 int nsing = 0;
1078 for( r = lo; r <= hi; r++ ) {
1079 if( r->is_singleton() ) nsing++;
1080 }
1081 tty->print(">>> ");
1082 _method->print_short_name();
1083 tty->print_cr(" switch decision tree");
1084 tty->print_cr(" %d ranges (%d singletons), max_depth=%d, est_depth=%d",
1085 (int) (hi-lo+1), nsing, _max_switch_depth, _est_switch_depth);
1086 if (_max_switch_depth > _est_switch_depth) {
1087 tty->print_cr("******** BAD SWITCH DEPTH ********");
1088 }
1089 tty->print(" ");
1090 for( r = lo; r <= hi; r++ ) {
1091 r->print();
1092 }
1093 tty->cr();
1094 }
1095 #endif
1096 }
1097
1098 Node* Parse::floating_point_mod(Node* a, Node* b, BasicType type) {
1099 assert(type == BasicType::T_FLOAT || type == BasicType::T_DOUBLE, "only float and double are floating points");
1100 CallLeafPureNode* mod = type == BasicType::T_DOUBLE ? static_cast<CallLeafPureNode*>(new ModDNode(C, a, b)) : new ModFNode(C, a, b);
1101
1102 set_predefined_input_for_runtime_call(mod);
1103 mod = _gvn.transform(mod)->as_CallLeafPure();
1104 set_predefined_output_for_runtime_call(mod);
1105 Node* result = _gvn.transform(new ProjNode(mod, TypeFunc::Parms + 0));
1106 record_for_igvn(mod);
1107 return result;
1108 }
1109
1110 void Parse::l2f() {
1111 Node* f2 = pop();
1112 Node* f1 = pop();
1113 Node* c = make_runtime_call(RC_LEAF, OptoRuntime::l2f_Type(),
1114 CAST_FROM_FN_PTR(address, SharedRuntime::l2f),
1115 "l2f", nullptr, //no memory effects
1116 f1, f2);
1117 Node* res = _gvn.transform(new ProjNode(c, TypeFunc::Parms + 0));
1118
1119 push(res);
1120 }
1121
1122 // Handle jsr and jsr_w bytecode
1123 void Parse::do_jsr() {
1124 assert(bc() == Bytecodes::_jsr || bc() == Bytecodes::_jsr_w, "wrong bytecode");
1125
1126 // Store information about current state, tagged with new _jsr_bci
1127 int return_bci = iter().next_bci();
1128 int jsr_bci = (bc() == Bytecodes::_jsr) ? iter().get_dest() : iter().get_far_dest();
1129
1130 // The way we do things now, there is only one successor block
1131 // for the jsr, because the target code is cloned by ciTypeFlow.
1132 Block* target = successor_for_bci(jsr_bci);
1133
1134 // What got pushed?
1135 const Type* ret_addr = target->peek();
1136 assert(ret_addr->singleton(), "must be a constant (cloned jsr body)");
1137
1138 // Effect on jsr on stack
1139 push(_gvn.makecon(ret_addr));
1140
1141 // Flow to the jsr.
1142 merge(jsr_bci);
1143 }
1144
1145 // Handle ret bytecode
1146 void Parse::do_ret() {
1147 // Find to whom we return.
1148 assert(block()->num_successors() == 1, "a ret can only go one place now");
1149 Block* target = block()->successor_at(0);
1150 assert(!target->is_ready(), "our arrival must be expected");
1151 int pnum = target->next_path_num();
1152 merge_common(target, pnum);
1153 }
1154
1155 static bool has_injected_profile(BoolTest::mask btest, Node* test, int& taken, int& not_taken) {
1156 if (btest != BoolTest::eq && btest != BoolTest::ne) {
1157 // Only ::eq and ::ne are supported for profile injection.
1158 return false;
1159 }
1160 if (test->is_Cmp() &&
1161 test->in(1)->Opcode() == Op_ProfileBoolean) {
1162 ProfileBooleanNode* profile = (ProfileBooleanNode*)test->in(1);
1163 int false_cnt = profile->false_count();
1164 int true_cnt = profile->true_count();
1165
1166 // Counts matching depends on the actual test operation (::eq or ::ne).
1167 // No need to scale the counts because profile injection was designed
1168 // to feed exact counts into VM.
1169 taken = (btest == BoolTest::eq) ? false_cnt : true_cnt;
1170 not_taken = (btest == BoolTest::eq) ? true_cnt : false_cnt;
1171
1172 profile->consume();
1173 return true;
1174 }
1175 return false;
1176 }
1177
1178 // Give up if too few (or too many, in which case the sum will overflow) counts to be meaningful.
1179 // We also check that individual counters are positive first, otherwise the sum can become positive.
1180 // (check for saturation, integer overflow, and immature counts)
1181 static bool counters_are_meaningful(int counter1, int counter2, int min) {
1182 // check for saturation, including "uint" values too big to fit in "int"
1183 if (counter1 < 0 || counter2 < 0) {
1184 return false;
1185 }
1186 // check for integer overflow of the sum
1187 int64_t sum = (int64_t)counter1 + (int64_t)counter2;
1188 STATIC_ASSERT(sizeof(counter1) < sizeof(sum));
1189 if (sum > INT_MAX) {
1190 return false;
1191 }
1192 // check if mature
1193 return (counter1 + counter2) >= min;
1194 }
1195
1196 //--------------------------dynamic_branch_prediction--------------------------
1197 // Try to gather dynamic branch prediction behavior. Return a probability
1198 // of the branch being taken and set the "cnt" field. Returns a -1.0
1199 // if we need to use static prediction for some reason.
1200 float Parse::dynamic_branch_prediction(float &cnt, BoolTest::mask btest, Node* test) {
1201 ResourceMark rm;
1202
1203 cnt = COUNT_UNKNOWN;
1204
1205 int taken = 0;
1206 int not_taken = 0;
1207
1208 bool use_mdo = !has_injected_profile(btest, test, taken, not_taken);
1209
1210 if (use_mdo) {
1211 // Use MethodData information if it is available
1212 // FIXME: free the ProfileData structure
1213 ciMethodData* methodData = method()->method_data();
1214 if (!methodData->is_mature()) return PROB_UNKNOWN;
1215 ciProfileData* data = methodData->bci_to_data(bci());
1216 if (data == nullptr) {
1217 return PROB_UNKNOWN;
1218 }
1219 if (!data->is_JumpData()) return PROB_UNKNOWN;
1220
1221 // get taken and not taken values
1222 // NOTE: saturated UINT_MAX values become negative,
1223 // as do counts above INT_MAX.
1224 taken = data->as_JumpData()->taken();
1225 not_taken = 0;
1226 if (data->is_BranchData()) {
1227 not_taken = data->as_BranchData()->not_taken();
1228 }
1229
1230 // scale the counts to be commensurate with invocation counts:
1231 // NOTE: overflow for positive values is clamped at INT_MAX
1232 taken = method()->scale_count(taken);
1233 not_taken = method()->scale_count(not_taken);
1234 }
1235 // At this point, saturation or overflow is indicated by INT_MAX
1236 // or a negative value.
1237
1238 // Give up if too few (or too many, in which case the sum will overflow) counts to be meaningful.
1239 // We also check that individual counters are positive first, otherwise the sum can become positive.
1240 if (!counters_are_meaningful(taken, not_taken, 40)) {
1241 if (C->log() != nullptr) {
1242 C->log()->elem("branch target_bci='%d' taken='%d' not_taken='%d'", iter().get_dest(), taken, not_taken);
1243 }
1244 return PROB_UNKNOWN;
1245 }
1246
1247 // Compute frequency that we arrive here
1248 float sum = taken + not_taken;
1249 // Adjust, if this block is a cloned private block but the
1250 // Jump counts are shared. Taken the private counts for
1251 // just this path instead of the shared counts.
1252 if( block()->count() > 0 )
1253 sum = block()->count();
1254 cnt = sum / FreqCountInvocations;
1255
1256 // Pin probability to sane limits
1257 float prob;
1258 if( !taken )
1259 prob = (0+PROB_MIN) / 2;
1260 else if( !not_taken )
1261 prob = (1+PROB_MAX) / 2;
1262 else { // Compute probability of true path
1263 prob = (float)taken / (float)(taken + not_taken);
1264 if (prob > PROB_MAX) prob = PROB_MAX;
1265 if (prob < PROB_MIN) prob = PROB_MIN;
1266 }
1267
1268 assert((cnt > 0.0f) && (prob > 0.0f),
1269 "Bad frequency assignment in if cnt=%g prob=%g taken=%d not_taken=%d", cnt, prob, taken, not_taken);
1270
1271 if (C->log() != nullptr) {
1272 const char* prob_str = nullptr;
1273 if (prob >= PROB_MAX) prob_str = (prob == PROB_MAX) ? "max" : "always";
1274 if (prob <= PROB_MIN) prob_str = (prob == PROB_MIN) ? "min" : "never";
1275 char prob_str_buf[30];
1276 if (prob_str == nullptr) {
1277 jio_snprintf(prob_str_buf, sizeof(prob_str_buf), "%20.2f", prob);
1278 prob_str = prob_str_buf;
1279 // The %20.2f adds many spaces to the string, to avoid some
1280 // picky overflow warning as noted in 8211929. But, 20 is the
1281 // *minimum* width, not *maximum*, so it's not clear how this
1282 // helps prevent overflow. Looks like we were forced to work
1283 // around a bug in gcc. In any case, strip the blanks.
1284 while (*prob_str == ' ') ++prob_str;
1285 }
1286 C->log()->elem("branch target_bci='%d' taken='%d' not_taken='%d' cnt='%f' prob='%s'",
1287 iter().get_dest(), taken, not_taken, cnt, prob_str);
1288 }
1289 return prob;
1290 }
1291
1292 //-----------------------------branch_prediction-------------------------------
1293 float Parse::branch_prediction(float& cnt,
1294 BoolTest::mask btest,
1295 int target_bci,
1296 Node* test) {
1297 float prob = dynamic_branch_prediction(cnt, btest, test);
1298 // If prob is unknown, switch to static prediction
1299 if (prob != PROB_UNKNOWN) return prob;
1300
1301 prob = PROB_FAIR; // Set default value
1302 if (btest == BoolTest::eq) // Exactly equal test?
1303 prob = PROB_STATIC_INFREQUENT; // Assume its relatively infrequent
1304 else if (btest == BoolTest::ne)
1305 prob = PROB_STATIC_FREQUENT; // Assume its relatively frequent
1306
1307 // If this is a conditional test guarding a backwards branch,
1308 // assume its a loop-back edge. Make it a likely taken branch.
1309 if (target_bci < bci()) {
1310 if (is_osr_parse()) { // Could be a hot OSR'd loop; force deopt
1311 // Since it's an OSR, we probably have profile data, but since
1312 // branch_prediction returned PROB_UNKNOWN, the counts are too small.
1313 // Let's make a special check here for completely zero counts.
1314 ciMethodData* methodData = method()->method_data();
1315 if (!methodData->is_empty()) {
1316 ciProfileData* data = methodData->bci_to_data(bci());
1317 // Only stop for truly zero counts, which mean an unknown part
1318 // of the OSR-ed method, and we want to deopt to gather more stats.
1319 // If you have ANY counts, then this loop is simply 'cold' relative
1320 // to the OSR loop.
1321 if (data == nullptr ||
1322 (data->as_BranchData()->taken() + data->as_BranchData()->not_taken() == 0)) {
1323 // This is the only way to return PROB_UNKNOWN:
1324 return PROB_UNKNOWN;
1325 }
1326 }
1327 }
1328 prob = PROB_STATIC_FREQUENT; // Likely to take backwards branch
1329 }
1330
1331 assert(prob != PROB_UNKNOWN, "must have some guess at this point");
1332 return prob;
1333 }
1334
1335 // The magic constants are chosen so as to match the output of
1336 // branch_prediction() when the profile reports a zero taken count.
1337 // It is important to distinguish zero counts unambiguously, because
1338 // some branches (e.g., _213_javac.Assembler.eliminate) validly produce
1339 // very small but nonzero probabilities, which if confused with zero
1340 // counts would keep the program recompiling indefinitely.
1341 bool Parse::seems_never_taken(float prob) const {
1342 return prob < PROB_MIN;
1343 }
1344
1345 //-------------------------------repush_if_args--------------------------------
1346 // Push arguments of an "if" bytecode back onto the stack by adjusting _sp.
1347 inline int Parse::repush_if_args() {
1348 if (PrintOpto && WizardMode) {
1349 tty->print("defending against excessive implicit null exceptions on %s @%d in ",
1350 Bytecodes::name(iter().cur_bc()), iter().cur_bci());
1351 method()->print_name(); tty->cr();
1352 }
1353 int bc_depth = - Bytecodes::depth(iter().cur_bc());
1354 assert(bc_depth == 1 || bc_depth == 2, "only two kinds of branches");
1355 DEBUG_ONLY(sync_jvms()); // argument(n) requires a synced jvms
1356 assert(argument(0) != nullptr, "must exist");
1357 assert(bc_depth == 1 || argument(1) != nullptr, "two must exist");
1358 inc_sp(bc_depth);
1359 return bc_depth;
1360 }
1361
1362 // Used by StressUnstableIfTraps
1363 static volatile int _trap_stress_counter = 0;
1364
1365 void Parse::increment_trap_stress_counter(Node*& counter, Node*& incr_store) {
1366 Node* counter_addr = makecon(TypeRawPtr::make((address)&_trap_stress_counter));
1367 counter = make_load(control(), counter_addr, TypeInt::INT, T_INT, MemNode::unordered);
1368 counter = _gvn.transform(new AddINode(counter, intcon(1)));
1369 incr_store = store_to_memory(control(), counter_addr, counter, T_INT, MemNode::unordered);
1370 }
1371
1372 //----------------------------------do_ifnull----------------------------------
1373 void Parse::do_ifnull(BoolTest::mask btest, Node *c) {
1374 int target_bci = iter().get_dest();
1375
1376 Node* counter = nullptr;
1377 Node* incr_store = nullptr;
1378 bool do_stress_trap = StressUnstableIfTraps && ((C->random() % 2) == 0);
1379 if (do_stress_trap) {
1380 increment_trap_stress_counter(counter, incr_store);
1381 }
1382
1383 Block* branch_block = successor_for_bci(target_bci);
1384 Block* next_block = successor_for_bci(iter().next_bci());
1385
1386 float cnt;
1387 float prob = branch_prediction(cnt, btest, target_bci, c);
1388 if (prob == PROB_UNKNOWN) {
1389 // (An earlier version of do_ifnull omitted this trap for OSR methods.)
1390 if (PrintOpto && Verbose) {
1391 tty->print_cr("Never-taken edge stops compilation at bci %d", bci());
1392 }
1393 repush_if_args(); // to gather stats on loop
1394 uncommon_trap(Deoptimization::Reason_unreached,
1395 Deoptimization::Action_reinterpret,
1396 nullptr, "cold");
1397 if (C->eliminate_boxing()) {
1398 // Mark the successor blocks as parsed
1399 branch_block->next_path_num();
1400 next_block->next_path_num();
1401 }
1402 return;
1403 }
1404
1405 NOT_PRODUCT(explicit_null_checks_inserted++);
1406
1407 // Generate real control flow
1408 Node *tst = _gvn.transform( new BoolNode( c, btest ) );
1409
1410 // Sanity check the probability value
1411 assert(prob > 0.0f,"Bad probability in Parser");
1412 // Need xform to put node in hash table
1413 IfNode *iff = create_and_xform_if( control(), tst, prob, cnt );
1414 assert(iff->_prob > 0.0f,"Optimizer made bad probability in parser");
1415 // True branch
1416 { PreserveJVMState pjvms(this);
1417 Node* iftrue = _gvn.transform( new IfTrueNode (iff) );
1418 set_control(iftrue);
1419
1420 if (stopped()) { // Path is dead?
1421 NOT_PRODUCT(explicit_null_checks_elided++);
1422 if (C->eliminate_boxing()) {
1423 // Mark the successor block as parsed
1424 branch_block->next_path_num();
1425 }
1426 } else { // Path is live.
1427 adjust_map_after_if(btest, c, prob, branch_block);
1428 if (!stopped()) {
1429 merge(target_bci);
1430 }
1431 }
1432 }
1433
1434 // False branch
1435 Node* iffalse = _gvn.transform( new IfFalseNode(iff) );
1436 set_control(iffalse);
1437
1438 if (stopped()) { // Path is dead?
1439 NOT_PRODUCT(explicit_null_checks_elided++);
1440 if (C->eliminate_boxing()) {
1441 // Mark the successor block as parsed
1442 next_block->next_path_num();
1443 }
1444 } else { // Path is live.
1445 adjust_map_after_if(BoolTest(btest).negate(), c, 1.0-prob, next_block);
1446 }
1447
1448 if (do_stress_trap) {
1449 stress_trap(iff, counter, incr_store);
1450 }
1451 }
1452
1453 //------------------------------------do_if------------------------------------
1454 void Parse::do_if(BoolTest::mask btest, Node* c) {
1455 int target_bci = iter().get_dest();
1456
1457 Block* branch_block = successor_for_bci(target_bci);
1458 Block* next_block = successor_for_bci(iter().next_bci());
1459
1460 float cnt;
1461 float prob = branch_prediction(cnt, btest, target_bci, c);
1462 float untaken_prob = 1.0 - prob;
1463
1464 if (prob == PROB_UNKNOWN) {
1465 if (PrintOpto && Verbose) {
1466 tty->print_cr("Never-taken edge stops compilation at bci %d", bci());
1467 }
1468 repush_if_args(); // to gather stats on loop
1469 uncommon_trap(Deoptimization::Reason_unreached,
1470 Deoptimization::Action_reinterpret,
1471 nullptr, "cold");
1472 if (C->eliminate_boxing()) {
1473 // Mark the successor blocks as parsed
1474 branch_block->next_path_num();
1475 next_block->next_path_num();
1476 }
1477 return;
1478 }
1479
1480 Node* counter = nullptr;
1481 Node* incr_store = nullptr;
1482 bool do_stress_trap = StressUnstableIfTraps && ((C->random() % 2) == 0);
1483 if (do_stress_trap) {
1484 increment_trap_stress_counter(counter, incr_store);
1485 }
1486
1487 // Sanity check the probability value
1488 assert(0.0f < prob && prob < 1.0f,"Bad probability in Parser");
1489
1490 bool taken_if_true = true;
1491 // Convert BoolTest to canonical form:
1492 if (!BoolTest(btest).is_canonical()) {
1493 btest = BoolTest(btest).negate();
1494 taken_if_true = false;
1495 // prob is NOT updated here; it remains the probability of the taken
1496 // path (as opposed to the prob of the path guarded by an 'IfTrueNode').
1497 }
1498 assert(btest != BoolTest::eq, "!= is the only canonical exact test");
1499
1500 Node* tst0 = new BoolNode(c, btest);
1501 Node* tst = _gvn.transform(tst0);
1502 BoolTest::mask taken_btest = BoolTest::illegal;
1503 BoolTest::mask untaken_btest = BoolTest::illegal;
1504
1505 if (tst->is_Bool()) {
1506 // Refresh c from the transformed bool node, since it may be
1507 // simpler than the original c. Also re-canonicalize btest.
1508 // This wins when (Bool ne (Conv2B p) 0) => (Bool ne (CmpP p null)).
1509 // That can arise from statements like: if (x instanceof C) ...
1510 if (tst != tst0) {
1511 // Canonicalize one more time since transform can change it.
1512 btest = tst->as_Bool()->_test._test;
1513 if (!BoolTest(btest).is_canonical()) {
1514 // Reverse edges one more time...
1515 tst = _gvn.transform( tst->as_Bool()->negate(&_gvn) );
1516 btest = tst->as_Bool()->_test._test;
1517 assert(BoolTest(btest).is_canonical(), "sanity");
1518 taken_if_true = !taken_if_true;
1519 }
1520 c = tst->in(1);
1521 }
1522 BoolTest::mask neg_btest = BoolTest(btest).negate();
1523 taken_btest = taken_if_true ? btest : neg_btest;
1524 untaken_btest = taken_if_true ? neg_btest : btest;
1525 }
1526
1527 // Generate real control flow
1528 float true_prob = (taken_if_true ? prob : untaken_prob);
1529 IfNode* iff = create_and_map_if(control(), tst, true_prob, cnt);
1530 assert(iff->_prob > 0.0f,"Optimizer made bad probability in parser");
1531 Node* taken_branch = new IfTrueNode(iff);
1532 Node* untaken_branch = new IfFalseNode(iff);
1533 if (!taken_if_true) { // Finish conversion to canonical form
1534 Node* tmp = taken_branch;
1535 taken_branch = untaken_branch;
1536 untaken_branch = tmp;
1537 }
1538
1539 // Branch is taken:
1540 { PreserveJVMState pjvms(this);
1541 taken_branch = _gvn.transform(taken_branch);
1542 set_control(taken_branch);
1543
1544 if (stopped()) {
1545 if (C->eliminate_boxing()) {
1546 // Mark the successor block as parsed
1547 branch_block->next_path_num();
1548 }
1549 } else {
1550 adjust_map_after_if(taken_btest, c, prob, branch_block);
1551 if (!stopped()) {
1552 merge(target_bci);
1553 }
1554 }
1555 }
1556
1557 untaken_branch = _gvn.transform(untaken_branch);
1558 set_control(untaken_branch);
1559
1560 // Branch not taken.
1561 if (stopped()) {
1562 if (C->eliminate_boxing()) {
1563 // Mark the successor block as parsed
1564 next_block->next_path_num();
1565 }
1566 } else {
1567 adjust_map_after_if(untaken_btest, c, untaken_prob, next_block);
1568 }
1569
1570 if (do_stress_trap) {
1571 stress_trap(iff, counter, incr_store);
1572 }
1573 }
1574
1575 // Force unstable if traps to be taken randomly to trigger intermittent bugs such as incorrect debug information.
1576 // Add another if before the unstable if that checks a "random" condition at runtime (a simple shared counter) and
1577 // then either takes the trap or executes the original, unstable if.
1578 void Parse::stress_trap(IfNode* orig_iff, Node* counter, Node* incr_store) {
1579 // Search for an unstable if trap
1580 CallStaticJavaNode* trap = nullptr;
1581 assert(orig_iff->Opcode() == Op_If && orig_iff->outcnt() == 2, "malformed if");
1582 ProjNode* trap_proj = orig_iff->uncommon_trap_proj(trap, Deoptimization::Reason_unstable_if);
1583 if (trap == nullptr || !trap->jvms()->should_reexecute()) {
1584 // No suitable trap found. Remove unused counter load and increment.
1585 C->gvn_replace_by(incr_store, incr_store->in(MemNode::Memory));
1586 return;
1587 }
1588
1589 // Remove trap from optimization list since we add another path to the trap.
1590 bool success = C->remove_unstable_if_trap(trap, true);
1591 assert(success, "Trap already modified");
1592
1593 // Add a check before the original if that will trap with a certain frequency and execute the original if otherwise
1594 int freq_log = (C->random() % 31) + 1; // Random logarithmic frequency in [1, 31]
1595 Node* mask = intcon(right_n_bits(freq_log));
1596 counter = _gvn.transform(new AndINode(counter, mask));
1597 Node* cmp = _gvn.transform(new CmpINode(counter, intcon(0)));
1598 Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::mask::eq));
1599 IfNode* iff = _gvn.transform(new IfNode(orig_iff->in(0), bol, orig_iff->_prob, orig_iff->_fcnt))->as_If();
1600 Node* if_true = _gvn.transform(new IfTrueNode(iff));
1601 Node* if_false = _gvn.transform(new IfFalseNode(iff));
1602 assert(!if_true->is_top() && !if_false->is_top(), "trap always / never taken");
1603
1604 // Trap
1605 assert(trap_proj->outcnt() == 1, "some other nodes are dependent on the trap projection");
1606
1607 Node* trap_region = new RegionNode(3);
1608 trap_region->set_req(1, trap_proj);
1609 trap_region->set_req(2, if_true);
1610 trap->set_req(0, _gvn.transform(trap_region));
1611
1612 // Don't trap, execute original if
1613 orig_iff->set_req(0, if_false);
1614 }
1615
1616 bool Parse::path_is_suitable_for_uncommon_trap(float prob) const {
1617 // Randomly skip emitting an uncommon trap
1618 if (StressUnstableIfTraps && ((C->random() % 2) == 0)) {
1619 return false;
1620 }
1621 // Don't want to speculate on uncommon traps when running with -Xcomp
1622 if (!UseInterpreter) {
1623 return false;
1624 }
1625 return seems_never_taken(prob) &&
1626 !C->too_many_traps(method(), bci(), Deoptimization::Reason_unstable_if);
1627 }
1628
1629 void Parse::maybe_add_predicate_after_if(Block* path) {
1630 if (path->is_SEL_head() && path->preds_parsed() == 0) {
1631 // Add predicates at bci of if dominating the loop so traps can be
1632 // recorded on the if's profile data
1633 int bc_depth = repush_if_args();
1634 add_parse_predicates();
1635 dec_sp(bc_depth);
1636 path->set_has_predicates();
1637 }
1638 }
1639
1640
1641 //----------------------------adjust_map_after_if------------------------------
1642 // Adjust the JVM state to reflect the result of taking this path.
1643 // Basically, it means inspecting the CmpNode controlling this
1644 // branch, seeing how it constrains a tested value, and then
1645 // deciding if it's worth our while to encode this constraint
1646 // as graph nodes in the current abstract interpretation map.
1647 void Parse::adjust_map_after_if(BoolTest::mask btest, Node* c, float prob, Block* path) {
1648 if (!c->is_Cmp()) {
1649 maybe_add_predicate_after_if(path);
1650 return;
1651 }
1652
1653 if (stopped() || btest == BoolTest::illegal) {
1654 return; // nothing to do
1655 }
1656
1657 bool is_fallthrough = (path == successor_for_bci(iter().next_bci()));
1658
1659 if (path_is_suitable_for_uncommon_trap(prob)) {
1660 repush_if_args();
1661 Node* call = uncommon_trap(Deoptimization::Reason_unstable_if,
1662 Deoptimization::Action_reinterpret,
1663 nullptr,
1664 (is_fallthrough ? "taken always" : "taken never"));
1665
1666 if (call != nullptr) {
1667 C->record_unstable_if_trap(new UnstableIfTrap(call->as_CallStaticJava(), path));
1668 }
1669 return;
1670 }
1671
1672 Node* val = c->in(1);
1673 Node* con = c->in(2);
1674 const Type* tcon = _gvn.type(con);
1675 const Type* tval = _gvn.type(val);
1676 bool have_con = tcon->singleton();
1677 if (tval->singleton()) {
1678 if (!have_con) {
1679 // Swap, so constant is in con.
1680 con = val;
1681 tcon = tval;
1682 val = c->in(2);
1683 tval = _gvn.type(val);
1684 btest = BoolTest(btest).commute();
1685 have_con = true;
1686 } else {
1687 // Do we have two constants? Then leave well enough alone.
1688 have_con = false;
1689 }
1690 }
1691 if (!have_con) { // remaining adjustments need a con
1692 maybe_add_predicate_after_if(path);
1693 return;
1694 }
1695
1696 sharpen_type_after_if(btest, con, tcon, val, tval);
1697 maybe_add_predicate_after_if(path);
1698 }
1699
1700
1701 static Node* extract_obj_from_klass_load(PhaseGVN* gvn, Node* n) {
1702 Node* ldk;
1703 if (n->is_DecodeNKlass()) {
1704 if (n->in(1)->Opcode() != Op_LoadNKlass) {
1705 return nullptr;
1706 } else {
1707 ldk = n->in(1);
1708 }
1709 } else if (n->Opcode() != Op_LoadKlass) {
1710 return nullptr;
1711 } else {
1712 ldk = n;
1713 }
1714 assert(ldk != nullptr && ldk->is_Load(), "should have found a LoadKlass or LoadNKlass node");
1715
1716 Node* adr = ldk->in(MemNode::Address);
1717 intptr_t off = 0;
1718 Node* obj = AddPNode::Ideal_base_and_offset(adr, gvn, off);
1719 if (obj == nullptr || off != oopDesc::klass_offset_in_bytes()) // loading oopDesc::_klass?
1720 return nullptr;
1721 const TypePtr* tp = gvn->type(obj)->is_ptr();
1722 if (tp == nullptr || !(tp->isa_instptr() || tp->isa_aryptr())) // is obj a Java object ptr?
1723 return nullptr;
1724
1725 return obj;
1726 }
1727
1728 void Parse::sharpen_type_after_if(BoolTest::mask btest,
1729 Node* con, const Type* tcon,
1730 Node* val, const Type* tval) {
1731 // Look for opportunities to sharpen the type of a node
1732 // whose klass is compared with a constant klass.
1733 if (btest == BoolTest::eq && tcon->isa_klassptr()) {
1734 Node* obj = extract_obj_from_klass_load(&_gvn, val);
1735 const TypeOopPtr* con_type = tcon->isa_klassptr()->as_instance_type();
1736 if (obj != nullptr && (con_type->isa_instptr() || con_type->isa_aryptr())) {
1737 // Found:
1738 // Bool(CmpP(LoadKlass(obj._klass), ConP(Foo.klass)), [eq])
1739 // or the narrowOop equivalent.
1740 const Type* obj_type = _gvn.type(obj);
1741 const TypeOopPtr* tboth = obj_type->join_speculative(con_type)->isa_oopptr();
1742 if (tboth != nullptr && tboth->klass_is_exact() && tboth != obj_type &&
1743 tboth->higher_equal(obj_type)) {
1744 // obj has to be of the exact type Foo if the CmpP succeeds.
1745 int obj_in_map = map()->find_edge(obj);
1746 JVMState* jvms = this->jvms();
1747 if (obj_in_map >= 0 &&
1748 (jvms->is_loc(obj_in_map) || jvms->is_stk(obj_in_map))) {
1749 TypeNode* ccast = new CheckCastPPNode(control(), obj, tboth);
1750 const Type* tcc = ccast->as_Type()->type();
1751 assert(tcc != obj_type && tcc->higher_equal(obj_type), "must improve");
1752 // Delay transform() call to allow recovery of pre-cast value
1753 // at the control merge.
1754 _gvn.set_type_bottom(ccast);
1755 record_for_igvn(ccast);
1756 // Here's the payoff.
1757 replace_in_map(obj, ccast);
1758 }
1759 }
1760 }
1761 }
1762
1763 int val_in_map = map()->find_edge(val);
1764 if (val_in_map < 0) return; // replace_in_map would be useless
1765 {
1766 JVMState* jvms = this->jvms();
1767 if (!(jvms->is_loc(val_in_map) ||
1768 jvms->is_stk(val_in_map)))
1769 return; // again, it would be useless
1770 }
1771
1772 // Check for a comparison to a constant, and "know" that the compared
1773 // value is constrained on this path.
1774 assert(tcon->singleton(), "");
1775 ConstraintCastNode* ccast = nullptr;
1776 Node* cast = nullptr;
1777
1778 switch (btest) {
1779 case BoolTest::eq: // Constant test?
1780 {
1781 const Type* tboth = tcon->join_speculative(tval);
1782 if (tboth == tval) break; // Nothing to gain.
1783 if (tcon->isa_int()) {
1784 ccast = new CastIINode(control(), val, tboth);
1785 } else if (tcon == TypePtr::NULL_PTR) {
1786 // Cast to null, but keep the pointer identity temporarily live.
1787 ccast = new CastPPNode(control(), val, tboth);
1788 } else {
1789 const TypeF* tf = tcon->isa_float_constant();
1790 const TypeD* td = tcon->isa_double_constant();
1791 // Exclude tests vs float/double 0 as these could be
1792 // either +0 or -0. Just because you are equal to +0
1793 // doesn't mean you ARE +0!
1794 // Note, following code also replaces Long and Oop values.
1795 if ((!tf || tf->_f != 0.0) &&
1796 (!td || td->_d != 0.0))
1797 cast = con; // Replace non-constant val by con.
1798 }
1799 }
1800 break;
1801
1802 case BoolTest::ne:
1803 if (tcon == TypePtr::NULL_PTR) {
1804 cast = cast_not_null(val, false);
1805 }
1806 break;
1807
1808 default:
1809 // (At this point we could record int range types with CastII.)
1810 break;
1811 }
1812
1813 if (ccast != nullptr) {
1814 const Type* tcc = ccast->as_Type()->type();
1815 assert(tcc != tval && tcc->higher_equal(tval), "must improve");
1816 // Delay transform() call to allow recovery of pre-cast value
1817 // at the control merge.
1818 _gvn.set_type_bottom(ccast);
1819 record_for_igvn(ccast);
1820 cast = ccast;
1821 }
1822
1823 if (cast != nullptr) { // Here's the payoff.
1824 replace_in_map(val, cast);
1825 }
1826 }
1827
1828 /**
1829 * Use speculative type to optimize CmpP node: if comparison is
1830 * against the low level class, cast the object to the speculative
1831 * type if any. CmpP should then go away.
1832 *
1833 * @param c expected CmpP node
1834 * @return result of CmpP on object casted to speculative type
1835 *
1836 */
1837 Node* Parse::optimize_cmp_with_klass(Node* c) {
1838 // If this is transformed by the _gvn to a comparison with the low
1839 // level klass then we may be able to use speculation
1840 if (c->Opcode() == Op_CmpP &&
1841 (c->in(1)->Opcode() == Op_LoadKlass || c->in(1)->Opcode() == Op_DecodeNKlass) &&
1842 c->in(2)->is_Con()) {
1843 Node* load_klass = nullptr;
1844 Node* decode = nullptr;
1845 if (c->in(1)->Opcode() == Op_DecodeNKlass) {
1846 decode = c->in(1);
1847 load_klass = c->in(1)->in(1);
1848 } else {
1849 load_klass = c->in(1);
1850 }
1851 if (load_klass->in(2)->is_AddP()) {
1852 Node* addp = load_klass->in(2);
1853 Node* obj = addp->in(AddPNode::Address);
1854 const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
1855 if (obj_type->speculative_type_not_null() != nullptr) {
1856 ciKlass* k = obj_type->speculative_type();
1857 inc_sp(2);
1858 obj = maybe_cast_profiled_obj(obj, k);
1859 dec_sp(2);
1860 // Make the CmpP use the casted obj
1861 addp = basic_plus_adr(obj, addp->in(AddPNode::Offset));
1862 load_klass = load_klass->clone();
1863 load_klass->set_req(2, addp);
1864 load_klass = _gvn.transform(load_klass);
1865 if (decode != nullptr) {
1866 decode = decode->clone();
1867 decode->set_req(1, load_klass);
1868 load_klass = _gvn.transform(decode);
1869 }
1870 c = c->clone();
1871 c->set_req(1, load_klass);
1872 c = _gvn.transform(c);
1873 }
1874 }
1875 }
1876 return c;
1877 }
1878
1879 //------------------------------do_one_bytecode--------------------------------
1880 // Parse this bytecode, and alter the Parsers JVM->Node mapping
1881 void Parse::do_one_bytecode() {
1882 Node *a, *b, *c, *d; // Handy temps
1883 BoolTest::mask btest;
1884 int i;
1885
1886 assert(!has_exceptions(), "bytecode entry state must be clear of throws");
1887
1888 if (C->check_node_count(NodeLimitFudgeFactor * 5,
1889 "out of nodes parsing method")) {
1890 return;
1891 }
1892
1893 #ifdef ASSERT
1894 // for setting breakpoints
1895 if (TraceOptoParse) {
1896 tty->print(" @");
1897 dump_bci(bci());
1898 tty->print(" %s", Bytecodes::name(bc()));
1899 tty->cr();
1900 }
1901 #endif
1902
1903 switch (bc()) {
1904 case Bytecodes::_nop:
1905 // do nothing
1906 break;
1907 case Bytecodes::_lconst_0:
1908 push_pair(longcon(0));
1909 break;
1910
1911 case Bytecodes::_lconst_1:
1912 push_pair(longcon(1));
1913 break;
1914
1915 case Bytecodes::_fconst_0:
1916 push(zerocon(T_FLOAT));
1917 break;
1918
1919 case Bytecodes::_fconst_1:
1920 push(makecon(TypeF::ONE));
1921 break;
1922
1923 case Bytecodes::_fconst_2:
1924 push(makecon(TypeF::make(2.0f)));
1925 break;
1926
1927 case Bytecodes::_dconst_0:
1928 push_pair(zerocon(T_DOUBLE));
1929 break;
1930
1931 case Bytecodes::_dconst_1:
1932 push_pair(makecon(TypeD::ONE));
1933 break;
1934
1935 case Bytecodes::_iconst_m1:push(intcon(-1)); break;
1936 case Bytecodes::_iconst_0: push(intcon( 0)); break;
1937 case Bytecodes::_iconst_1: push(intcon( 1)); break;
1938 case Bytecodes::_iconst_2: push(intcon( 2)); break;
1939 case Bytecodes::_iconst_3: push(intcon( 3)); break;
1940 case Bytecodes::_iconst_4: push(intcon( 4)); break;
1941 case Bytecodes::_iconst_5: push(intcon( 5)); break;
1942 case Bytecodes::_bipush: push(intcon(iter().get_constant_u1())); break;
1943 case Bytecodes::_sipush: push(intcon(iter().get_constant_u2())); break;
1944 case Bytecodes::_aconst_null: push(null()); break;
1945
1946 case Bytecodes::_ldc:
1947 case Bytecodes::_ldc_w:
1948 case Bytecodes::_ldc2_w: {
1949 // ciTypeFlow should trap if the ldc is in error state or if the constant is not loaded
1950 assert(!iter().is_in_error(), "ldc is in error state");
1951 ciConstant constant = iter().get_constant();
1952 assert(constant.is_loaded(), "constant is not loaded");
1953 const Type* con_type = Type::make_from_constant(constant);
1954 if (con_type != nullptr) {
1955 push_node(con_type->basic_type(), makecon(con_type));
1956 }
1957 break;
1958 }
1959
1960 case Bytecodes::_aload_0:
1961 push( local(0) );
1962 break;
1963 case Bytecodes::_aload_1:
1964 push( local(1) );
1965 break;
1966 case Bytecodes::_aload_2:
1967 push( local(2) );
1968 break;
1969 case Bytecodes::_aload_3:
1970 push( local(3) );
1971 break;
1972 case Bytecodes::_aload:
1973 push( local(iter().get_index()) );
1974 break;
1975
1976 case Bytecodes::_fload_0:
1977 case Bytecodes::_iload_0:
1978 push( local(0) );
1979 break;
1980 case Bytecodes::_fload_1:
1981 case Bytecodes::_iload_1:
1982 push( local(1) );
1983 break;
1984 case Bytecodes::_fload_2:
1985 case Bytecodes::_iload_2:
1986 push( local(2) );
1987 break;
1988 case Bytecodes::_fload_3:
1989 case Bytecodes::_iload_3:
1990 push( local(3) );
1991 break;
1992 case Bytecodes::_fload:
1993 case Bytecodes::_iload:
1994 push( local(iter().get_index()) );
1995 break;
1996 case Bytecodes::_lload_0:
1997 push_pair_local( 0 );
1998 break;
1999 case Bytecodes::_lload_1:
2000 push_pair_local( 1 );
2001 break;
2002 case Bytecodes::_lload_2:
2003 push_pair_local( 2 );
2004 break;
2005 case Bytecodes::_lload_3:
2006 push_pair_local( 3 );
2007 break;
2008 case Bytecodes::_lload:
2009 push_pair_local( iter().get_index() );
2010 break;
2011
2012 case Bytecodes::_dload_0:
2013 push_pair_local(0);
2014 break;
2015 case Bytecodes::_dload_1:
2016 push_pair_local(1);
2017 break;
2018 case Bytecodes::_dload_2:
2019 push_pair_local(2);
2020 break;
2021 case Bytecodes::_dload_3:
2022 push_pair_local(3);
2023 break;
2024 case Bytecodes::_dload:
2025 push_pair_local(iter().get_index());
2026 break;
2027 case Bytecodes::_fstore_0:
2028 case Bytecodes::_istore_0:
2029 case Bytecodes::_astore_0:
2030 set_local( 0, pop() );
2031 break;
2032 case Bytecodes::_fstore_1:
2033 case Bytecodes::_istore_1:
2034 case Bytecodes::_astore_1:
2035 set_local( 1, pop() );
2036 break;
2037 case Bytecodes::_fstore_2:
2038 case Bytecodes::_istore_2:
2039 case Bytecodes::_astore_2:
2040 set_local( 2, pop() );
2041 break;
2042 case Bytecodes::_fstore_3:
2043 case Bytecodes::_istore_3:
2044 case Bytecodes::_astore_3:
2045 set_local( 3, pop() );
2046 break;
2047 case Bytecodes::_fstore:
2048 case Bytecodes::_istore:
2049 case Bytecodes::_astore:
2050 set_local( iter().get_index(), pop() );
2051 break;
2052 // long stores
2053 case Bytecodes::_lstore_0:
2054 set_pair_local( 0, pop_pair() );
2055 break;
2056 case Bytecodes::_lstore_1:
2057 set_pair_local( 1, pop_pair() );
2058 break;
2059 case Bytecodes::_lstore_2:
2060 set_pair_local( 2, pop_pair() );
2061 break;
2062 case Bytecodes::_lstore_3:
2063 set_pair_local( 3, pop_pair() );
2064 break;
2065 case Bytecodes::_lstore:
2066 set_pair_local( iter().get_index(), pop_pair() );
2067 break;
2068
2069 // double stores
2070 case Bytecodes::_dstore_0:
2071 set_pair_local( 0, pop_pair() );
2072 break;
2073 case Bytecodes::_dstore_1:
2074 set_pair_local( 1, pop_pair() );
2075 break;
2076 case Bytecodes::_dstore_2:
2077 set_pair_local( 2, pop_pair() );
2078 break;
2079 case Bytecodes::_dstore_3:
2080 set_pair_local( 3, pop_pair() );
2081 break;
2082 case Bytecodes::_dstore:
2083 set_pair_local( iter().get_index(), pop_pair() );
2084 break;
2085
2086 case Bytecodes::_pop: dec_sp(1); break;
2087 case Bytecodes::_pop2: dec_sp(2); break;
2088 case Bytecodes::_swap:
2089 a = pop();
2090 b = pop();
2091 push(a);
2092 push(b);
2093 break;
2094 case Bytecodes::_dup:
2095 a = pop();
2096 push(a);
2097 push(a);
2098 break;
2099 case Bytecodes::_dup_x1:
2100 a = pop();
2101 b = pop();
2102 push( a );
2103 push( b );
2104 push( a );
2105 break;
2106 case Bytecodes::_dup_x2:
2107 a = pop();
2108 b = pop();
2109 c = pop();
2110 push( a );
2111 push( c );
2112 push( b );
2113 push( a );
2114 break;
2115 case Bytecodes::_dup2:
2116 a = pop();
2117 b = pop();
2118 push( b );
2119 push( a );
2120 push( b );
2121 push( a );
2122 break;
2123
2124 case Bytecodes::_dup2_x1:
2125 // before: .. c, b, a
2126 // after: .. b, a, c, b, a
2127 // not tested
2128 a = pop();
2129 b = pop();
2130 c = pop();
2131 push( b );
2132 push( a );
2133 push( c );
2134 push( b );
2135 push( a );
2136 break;
2137 case Bytecodes::_dup2_x2:
2138 // before: .. d, c, b, a
2139 // after: .. b, a, d, c, b, a
2140 // not tested
2141 a = pop();
2142 b = pop();
2143 c = pop();
2144 d = pop();
2145 push( b );
2146 push( a );
2147 push( d );
2148 push( c );
2149 push( b );
2150 push( a );
2151 break;
2152
2153 case Bytecodes::_arraylength: {
2154 // Must do null-check with value on expression stack
2155 Node *ary = null_check(peek(), T_ARRAY);
2156 // Compile-time detect of null-exception?
2157 if (stopped()) return;
2158 a = pop();
2159 push(load_array_length(a));
2160 break;
2161 }
2162
2163 case Bytecodes::_baload: array_load(T_BYTE); break;
2164 case Bytecodes::_caload: array_load(T_CHAR); break;
2165 case Bytecodes::_iaload: array_load(T_INT); break;
2166 case Bytecodes::_saload: array_load(T_SHORT); break;
2167 case Bytecodes::_faload: array_load(T_FLOAT); break;
2168 case Bytecodes::_aaload: array_load(T_OBJECT); break;
2169 case Bytecodes::_laload: array_load(T_LONG); break;
2170 case Bytecodes::_daload: array_load(T_DOUBLE); break;
2171 case Bytecodes::_bastore: array_store(T_BYTE); break;
2172 case Bytecodes::_castore: array_store(T_CHAR); break;
2173 case Bytecodes::_iastore: array_store(T_INT); break;
2174 case Bytecodes::_sastore: array_store(T_SHORT); break;
2175 case Bytecodes::_fastore: array_store(T_FLOAT); break;
2176 case Bytecodes::_aastore: array_store(T_OBJECT); break;
2177 case Bytecodes::_lastore: array_store(T_LONG); break;
2178 case Bytecodes::_dastore: array_store(T_DOUBLE); break;
2179
2180 case Bytecodes::_getfield:
2181 do_getfield();
2182 break;
2183
2184 case Bytecodes::_getstatic:
2185 do_getstatic();
2186 break;
2187
2188 case Bytecodes::_putfield:
2189 do_putfield();
2190 break;
2191
2192 case Bytecodes::_putstatic:
2193 do_putstatic();
2194 break;
2195
2196 case Bytecodes::_irem:
2197 // Must keep both values on the expression-stack during null-check
2198 zero_check_int(peek());
2199 // Compile-time detect of null-exception?
2200 if (stopped()) return;
2201 b = pop();
2202 a = pop();
2203 push(_gvn.transform(new ModINode(control(), a, b)));
2204 break;
2205 case Bytecodes::_idiv:
2206 // Must keep both values on the expression-stack during null-check
2207 zero_check_int(peek());
2208 // Compile-time detect of null-exception?
2209 if (stopped()) return;
2210 b = pop();
2211 a = pop();
2212 push( _gvn.transform( new DivINode(control(),a,b) ) );
2213 break;
2214 case Bytecodes::_imul:
2215 b = pop(); a = pop();
2216 push( _gvn.transform( new MulINode(a,b) ) );
2217 break;
2218 case Bytecodes::_iadd:
2219 b = pop(); a = pop();
2220 push( _gvn.transform( new AddINode(a,b) ) );
2221 break;
2222 case Bytecodes::_ineg:
2223 a = pop();
2224 push( _gvn.transform( new SubINode(_gvn.intcon(0),a)) );
2225 break;
2226 case Bytecodes::_isub:
2227 b = pop(); a = pop();
2228 push( _gvn.transform( new SubINode(a,b) ) );
2229 break;
2230 case Bytecodes::_iand:
2231 b = pop(); a = pop();
2232 push( _gvn.transform( new AndINode(a,b) ) );
2233 break;
2234 case Bytecodes::_ior:
2235 b = pop(); a = pop();
2236 push( _gvn.transform( new OrINode(a,b) ) );
2237 break;
2238 case Bytecodes::_ixor:
2239 b = pop(); a = pop();
2240 push( _gvn.transform( new XorINode(a,b) ) );
2241 break;
2242 case Bytecodes::_ishl:
2243 b = pop(); a = pop();
2244 push( _gvn.transform( new LShiftINode(a,b) ) );
2245 break;
2246 case Bytecodes::_ishr:
2247 b = pop(); a = pop();
2248 push( _gvn.transform( new RShiftINode(a,b) ) );
2249 break;
2250 case Bytecodes::_iushr:
2251 b = pop(); a = pop();
2252 push( _gvn.transform( new URShiftINode(a,b) ) );
2253 break;
2254
2255 case Bytecodes::_fneg:
2256 a = pop();
2257 b = _gvn.transform(new NegFNode (a));
2258 push(b);
2259 break;
2260
2261 case Bytecodes::_fsub:
2262 b = pop();
2263 a = pop();
2264 c = _gvn.transform( new SubFNode(a,b) );
2265 push(c);
2266 break;
2267
2268 case Bytecodes::_fadd:
2269 b = pop();
2270 a = pop();
2271 c = _gvn.transform( new AddFNode(a,b) );
2272 push(c);
2273 break;
2274
2275 case Bytecodes::_fmul:
2276 b = pop();
2277 a = pop();
2278 c = _gvn.transform( new MulFNode(a,b) );
2279 push(c);
2280 break;
2281
2282 case Bytecodes::_fdiv:
2283 b = pop();
2284 a = pop();
2285 c = _gvn.transform( new DivFNode(nullptr,a,b) );
2286 push(c);
2287 break;
2288
2289 case Bytecodes::_frem:
2290 // Generate a ModF node.
2291 b = pop();
2292 a = pop();
2293 push(floating_point_mod(a, b, BasicType::T_FLOAT));
2294 break;
2295
2296 case Bytecodes::_fcmpl:
2297 b = pop();
2298 a = pop();
2299 c = _gvn.transform( new CmpF3Node( a, b));
2300 push(c);
2301 break;
2302 case Bytecodes::_fcmpg:
2303 b = pop();
2304 a = pop();
2305
2306 // Same as fcmpl but need to flip the unordered case. Swap the inputs,
2307 // which negates the result sign except for unordered. Flip the unordered
2308 // as well by using CmpF3 which implements unordered-lesser instead of
2309 // unordered-greater semantics. Finally, commute the result bits. Result
2310 // is same as using a CmpF3Greater except we did it with CmpF3 alone.
2311 c = _gvn.transform( new CmpF3Node( b, a));
2312 c = _gvn.transform( new SubINode(_gvn.intcon(0),c) );
2313 push(c);
2314 break;
2315
2316 case Bytecodes::_f2i:
2317 a = pop();
2318 push(_gvn.transform(new ConvF2INode(a)));
2319 break;
2320
2321 case Bytecodes::_d2i:
2322 a = pop_pair();
2323 b = _gvn.transform(new ConvD2INode(a));
2324 push( b );
2325 break;
2326
2327 case Bytecodes::_f2d:
2328 a = pop();
2329 b = _gvn.transform( new ConvF2DNode(a));
2330 push_pair( b );
2331 break;
2332
2333 case Bytecodes::_d2f:
2334 a = pop_pair();
2335 b = _gvn.transform( new ConvD2FNode(a));
2336 push( b );
2337 break;
2338
2339 case Bytecodes::_l2f:
2340 if (Matcher::convL2FSupported()) {
2341 a = pop_pair();
2342 b = _gvn.transform( new ConvL2FNode(a));
2343 push(b);
2344 } else {
2345 l2f();
2346 }
2347 break;
2348
2349 case Bytecodes::_l2d:
2350 a = pop_pair();
2351 b = _gvn.transform( new ConvL2DNode(a));
2352 push_pair(b);
2353 break;
2354
2355 case Bytecodes::_f2l:
2356 a = pop();
2357 b = _gvn.transform( new ConvF2LNode(a));
2358 push_pair(b);
2359 break;
2360
2361 case Bytecodes::_d2l:
2362 a = pop_pair();
2363 b = _gvn.transform( new ConvD2LNode(a));
2364 push_pair(b);
2365 break;
2366
2367 case Bytecodes::_dsub:
2368 b = pop_pair();
2369 a = pop_pair();
2370 c = _gvn.transform( new SubDNode(a,b) );
2371 push_pair(c);
2372 break;
2373
2374 case Bytecodes::_dadd:
2375 b = pop_pair();
2376 a = pop_pair();
2377 c = _gvn.transform( new AddDNode(a,b) );
2378 push_pair(c);
2379 break;
2380
2381 case Bytecodes::_dmul:
2382 b = pop_pair();
2383 a = pop_pair();
2384 c = _gvn.transform( new MulDNode(a,b) );
2385 push_pair(c);
2386 break;
2387
2388 case Bytecodes::_ddiv:
2389 b = pop_pair();
2390 a = pop_pair();
2391 c = _gvn.transform( new DivDNode(nullptr,a,b) );
2392 push_pair(c);
2393 break;
2394
2395 case Bytecodes::_dneg:
2396 a = pop_pair();
2397 b = _gvn.transform(new NegDNode (a));
2398 push_pair(b);
2399 break;
2400
2401 case Bytecodes::_drem:
2402 // Generate a ModD node.
2403 b = pop_pair();
2404 a = pop_pair();
2405 push_pair(floating_point_mod(a, b, BasicType::T_DOUBLE));
2406 break;
2407
2408 case Bytecodes::_dcmpl:
2409 b = pop_pair();
2410 a = pop_pair();
2411 c = _gvn.transform( new CmpD3Node( a, b));
2412 push(c);
2413 break;
2414
2415 case Bytecodes::_dcmpg:
2416 b = pop_pair();
2417 a = pop_pair();
2418 // Same as dcmpl but need to flip the unordered case.
2419 // Commute the inputs, which negates the result sign except for unordered.
2420 // Flip the unordered as well by using CmpD3 which implements
2421 // unordered-lesser instead of unordered-greater semantics.
2422 // Finally, negate the result bits. Result is same as using a
2423 // CmpD3Greater except we did it with CmpD3 alone.
2424 c = _gvn.transform( new CmpD3Node( b, a));
2425 c = _gvn.transform( new SubINode(_gvn.intcon(0),c) );
2426 push(c);
2427 break;
2428
2429
2430 // Note for longs -> lo word is on TOS, hi word is on TOS - 1
2431 case Bytecodes::_land:
2432 b = pop_pair();
2433 a = pop_pair();
2434 c = _gvn.transform( new AndLNode(a,b) );
2435 push_pair(c);
2436 break;
2437 case Bytecodes::_lor:
2438 b = pop_pair();
2439 a = pop_pair();
2440 c = _gvn.transform( new OrLNode(a,b) );
2441 push_pair(c);
2442 break;
2443 case Bytecodes::_lxor:
2444 b = pop_pair();
2445 a = pop_pair();
2446 c = _gvn.transform( new XorLNode(a,b) );
2447 push_pair(c);
2448 break;
2449
2450 case Bytecodes::_lshl:
2451 b = pop(); // the shift count
2452 a = pop_pair(); // value to be shifted
2453 c = _gvn.transform( new LShiftLNode(a,b) );
2454 push_pair(c);
2455 break;
2456 case Bytecodes::_lshr:
2457 b = pop(); // the shift count
2458 a = pop_pair(); // value to be shifted
2459 c = _gvn.transform( new RShiftLNode(a,b) );
2460 push_pair(c);
2461 break;
2462 case Bytecodes::_lushr:
2463 b = pop(); // the shift count
2464 a = pop_pair(); // value to be shifted
2465 c = _gvn.transform( new URShiftLNode(a,b) );
2466 push_pair(c);
2467 break;
2468 case Bytecodes::_lmul:
2469 b = pop_pair();
2470 a = pop_pair();
2471 c = _gvn.transform( new MulLNode(a,b) );
2472 push_pair(c);
2473 break;
2474
2475 case Bytecodes::_lrem:
2476 // Must keep both values on the expression-stack during null-check
2477 assert(peek(0) == top(), "long word order");
2478 zero_check_long(peek(1));
2479 // Compile-time detect of null-exception?
2480 if (stopped()) return;
2481 b = pop_pair();
2482 a = pop_pair();
2483 c = _gvn.transform( new ModLNode(control(),a,b) );
2484 push_pair(c);
2485 break;
2486
2487 case Bytecodes::_ldiv:
2488 // Must keep both values on the expression-stack during null-check
2489 assert(peek(0) == top(), "long word order");
2490 zero_check_long(peek(1));
2491 // Compile-time detect of null-exception?
2492 if (stopped()) return;
2493 b = pop_pair();
2494 a = pop_pair();
2495 c = _gvn.transform( new DivLNode(control(),a,b) );
2496 push_pair(c);
2497 break;
2498
2499 case Bytecodes::_ladd:
2500 b = pop_pair();
2501 a = pop_pair();
2502 c = _gvn.transform( new AddLNode(a,b) );
2503 push_pair(c);
2504 break;
2505 case Bytecodes::_lsub:
2506 b = pop_pair();
2507 a = pop_pair();
2508 c = _gvn.transform( new SubLNode(a,b) );
2509 push_pair(c);
2510 break;
2511 case Bytecodes::_lcmp:
2512 // Safepoints are now inserted _before_ branches. The long-compare
2513 // bytecode painfully produces a 3-way value (-1,0,+1) which requires a
2514 // slew of control flow. These are usually followed by a CmpI vs zero and
2515 // a branch; this pattern then optimizes to the obvious long-compare and
2516 // branch. However, if the branch is backwards there's a Safepoint
2517 // inserted. The inserted Safepoint captures the JVM state at the
2518 // pre-branch point, i.e. it captures the 3-way value. Thus if a
2519 // long-compare is used to control a loop the debug info will force
2520 // computation of the 3-way value, even though the generated code uses a
2521 // long-compare and branch. We try to rectify the situation by inserting
2522 // a SafePoint here and have it dominate and kill the safepoint added at a
2523 // following backwards branch. At this point the JVM state merely holds 2
2524 // longs but not the 3-way value.
2525 switch (iter().next_bc()) {
2526 case Bytecodes::_ifgt:
2527 case Bytecodes::_iflt:
2528 case Bytecodes::_ifge:
2529 case Bytecodes::_ifle:
2530 case Bytecodes::_ifne:
2531 case Bytecodes::_ifeq:
2532 // If this is a backwards branch in the bytecodes, add Safepoint
2533 maybe_add_safepoint(iter().next_get_dest());
2534 default:
2535 break;
2536 }
2537 b = pop_pair();
2538 a = pop_pair();
2539 c = _gvn.transform( new CmpL3Node( a, b ));
2540 push(c);
2541 break;
2542
2543 case Bytecodes::_lneg:
2544 a = pop_pair();
2545 b = _gvn.transform( new SubLNode(longcon(0),a));
2546 push_pair(b);
2547 break;
2548 case Bytecodes::_l2i:
2549 a = pop_pair();
2550 push( _gvn.transform( new ConvL2INode(a)));
2551 break;
2552 case Bytecodes::_i2l:
2553 a = pop();
2554 b = _gvn.transform( new ConvI2LNode(a));
2555 push_pair(b);
2556 break;
2557 case Bytecodes::_i2b:
2558 // Sign extend
2559 a = pop();
2560 a = Compile::narrow_value(T_BYTE, a, nullptr, &_gvn, true);
2561 push(a);
2562 break;
2563 case Bytecodes::_i2s:
2564 a = pop();
2565 a = Compile::narrow_value(T_SHORT, a, nullptr, &_gvn, true);
2566 push(a);
2567 break;
2568 case Bytecodes::_i2c:
2569 a = pop();
2570 a = Compile::narrow_value(T_CHAR, a, nullptr, &_gvn, true);
2571 push(a);
2572 break;
2573
2574 case Bytecodes::_i2f:
2575 a = pop();
2576 b = _gvn.transform( new ConvI2FNode(a) ) ;
2577 push(b);
2578 break;
2579
2580 case Bytecodes::_i2d:
2581 a = pop();
2582 b = _gvn.transform( new ConvI2DNode(a));
2583 push_pair(b);
2584 break;
2585
2586 case Bytecodes::_iinc: // Increment local
2587 i = iter().get_index(); // Get local index
2588 set_local( i, _gvn.transform( new AddINode( _gvn.intcon(iter().get_iinc_con()), local(i) ) ) );
2589 break;
2590
2591 // Exit points of synchronized methods must have an unlock node
2592 case Bytecodes::_return:
2593 return_current(nullptr);
2594 break;
2595
2596 case Bytecodes::_ireturn:
2597 case Bytecodes::_areturn:
2598 case Bytecodes::_freturn:
2599 return_current(pop());
2600 break;
2601 case Bytecodes::_lreturn:
2602 return_current(pop_pair());
2603 break;
2604 case Bytecodes::_dreturn:
2605 return_current(pop_pair());
2606 break;
2607
2608 case Bytecodes::_athrow:
2609 // null exception oop throws null pointer exception
2610 null_check(peek());
2611 if (stopped()) return;
2612 // Hook the thrown exception directly to subsequent handlers.
2613 if (BailoutToInterpreterForThrows) {
2614 // Keep method interpreted from now on.
2615 uncommon_trap(Deoptimization::Reason_unhandled,
2616 Deoptimization::Action_make_not_compilable);
2617 return;
2618 }
2619 if (env()->jvmti_can_post_on_exceptions()) {
2620 // check if we must post exception events, take uncommon trap if so (with must_throw = false)
2621 uncommon_trap_if_should_post_on_exceptions(Deoptimization::Reason_unhandled, false);
2622 }
2623 // Here if either can_post_on_exceptions or should_post_on_exceptions is false
2624 add_exception_state(make_exception_state(peek()));
2625 break;
2626
2627 case Bytecodes::_goto: // fall through
2628 case Bytecodes::_goto_w: {
2629 int target_bci = (bc() == Bytecodes::_goto) ? iter().get_dest() : iter().get_far_dest();
2630
2631 // If this is a backwards branch in the bytecodes, add Safepoint
2632 maybe_add_safepoint(target_bci);
2633
2634 // Merge the current control into the target basic block
2635 merge(target_bci);
2636
2637 // See if we can get some profile data and hand it off to the next block
2638 Block *target_block = block()->successor_for_bci(target_bci);
2639 if (target_block->pred_count() != 1) break;
2640 ciMethodData* methodData = method()->method_data();
2641 if (!methodData->is_mature()) break;
2642 ciProfileData* data = methodData->bci_to_data(bci());
2643 assert(data != nullptr && data->is_JumpData(), "need JumpData for taken branch");
2644 int taken = ((ciJumpData*)data)->taken();
2645 taken = method()->scale_count(taken);
2646 target_block->set_count(taken);
2647 break;
2648 }
2649
2650 case Bytecodes::_ifnull: btest = BoolTest::eq; goto handle_if_null;
2651 case Bytecodes::_ifnonnull: btest = BoolTest::ne; goto handle_if_null;
2652 handle_if_null:
2653 // If this is a backwards branch in the bytecodes, add Safepoint
2654 maybe_add_safepoint(iter().get_dest());
2655 a = null();
2656 b = pop();
2657 if (!_gvn.type(b)->speculative_maybe_null() &&
2658 !too_many_traps(Deoptimization::Reason_speculate_null_check)) {
2659 inc_sp(1);
2660 Node* null_ctl = top();
2661 b = null_check_oop(b, &null_ctl, true, true, true);
2662 assert(null_ctl->is_top(), "no null control here");
2663 dec_sp(1);
2664 } else if (_gvn.type(b)->speculative_always_null() &&
2665 !too_many_traps(Deoptimization::Reason_speculate_null_assert)) {
2666 inc_sp(1);
2667 b = null_assert(b);
2668 dec_sp(1);
2669 }
2670 c = _gvn.transform( new CmpPNode(b, a) );
2671 do_ifnull(btest, c);
2672 break;
2673
2674 case Bytecodes::_if_acmpeq: btest = BoolTest::eq; goto handle_if_acmp;
2675 case Bytecodes::_if_acmpne: btest = BoolTest::ne; goto handle_if_acmp;
2676 handle_if_acmp:
2677 // If this is a backwards branch in the bytecodes, add Safepoint
2678 maybe_add_safepoint(iter().get_dest());
2679 a = pop();
2680 b = pop();
2681 c = _gvn.transform( new CmpPNode(b, a) );
2682 c = optimize_cmp_with_klass(c);
2683 do_if(btest, c);
2684 break;
2685
2686 case Bytecodes::_ifeq: btest = BoolTest::eq; goto handle_ifxx;
2687 case Bytecodes::_ifne: btest = BoolTest::ne; goto handle_ifxx;
2688 case Bytecodes::_iflt: btest = BoolTest::lt; goto handle_ifxx;
2689 case Bytecodes::_ifle: btest = BoolTest::le; goto handle_ifxx;
2690 case Bytecodes::_ifgt: btest = BoolTest::gt; goto handle_ifxx;
2691 case Bytecodes::_ifge: btest = BoolTest::ge; goto handle_ifxx;
2692 handle_ifxx:
2693 // If this is a backwards branch in the bytecodes, add Safepoint
2694 maybe_add_safepoint(iter().get_dest());
2695 a = _gvn.intcon(0);
2696 b = pop();
2697 c = _gvn.transform( new CmpINode(b, a) );
2698 do_if(btest, c);
2699 break;
2700
2701 case Bytecodes::_if_icmpeq: btest = BoolTest::eq; goto handle_if_icmp;
2702 case Bytecodes::_if_icmpne: btest = BoolTest::ne; goto handle_if_icmp;
2703 case Bytecodes::_if_icmplt: btest = BoolTest::lt; goto handle_if_icmp;
2704 case Bytecodes::_if_icmple: btest = BoolTest::le; goto handle_if_icmp;
2705 case Bytecodes::_if_icmpgt: btest = BoolTest::gt; goto handle_if_icmp;
2706 case Bytecodes::_if_icmpge: btest = BoolTest::ge; goto handle_if_icmp;
2707 handle_if_icmp:
2708 // If this is a backwards branch in the bytecodes, add Safepoint
2709 maybe_add_safepoint(iter().get_dest());
2710 a = pop();
2711 b = pop();
2712 c = _gvn.transform( new CmpINode( b, a ) );
2713 do_if(btest, c);
2714 break;
2715
2716 case Bytecodes::_tableswitch:
2717 do_tableswitch();
2718 break;
2719
2720 case Bytecodes::_lookupswitch:
2721 do_lookupswitch();
2722 break;
2723
2724 case Bytecodes::_invokestatic:
2725 case Bytecodes::_invokedynamic:
2726 case Bytecodes::_invokespecial:
2727 case Bytecodes::_invokevirtual:
2728 case Bytecodes::_invokeinterface:
2729 do_call();
2730 break;
2731 case Bytecodes::_checkcast:
2732 do_checkcast();
2733 break;
2734 case Bytecodes::_instanceof:
2735 do_instanceof();
2736 break;
2737 case Bytecodes::_anewarray:
2738 do_anewarray();
2739 break;
2740 case Bytecodes::_newarray:
2741 do_newarray((BasicType)iter().get_index());
2742 break;
2743 case Bytecodes::_multianewarray:
2744 do_multianewarray();
2745 break;
2746 case Bytecodes::_new:
2747 do_new();
2748 break;
2749
2750 case Bytecodes::_jsr:
2751 case Bytecodes::_jsr_w:
2752 do_jsr();
2753 break;
2754
2755 case Bytecodes::_ret:
2756 do_ret();
2757 break;
2758
2759
2760 case Bytecodes::_monitorenter:
2761 do_monitor_enter();
2762 break;
2763
2764 case Bytecodes::_monitorexit:
2765 do_monitor_exit();
2766 break;
2767
2768 case Bytecodes::_breakpoint:
2769 // Breakpoint set concurrently to compile
2770 // %%% use an uncommon trap?
2771 C->record_failure("breakpoint in method");
2772 return;
2773
2774 default:
2775 #ifndef PRODUCT
2776 map()->dump(99);
2777 #endif
2778 tty->print("\nUnhandled bytecode %s\n", Bytecodes::name(bc()) );
2779 ShouldNotReachHere();
2780 }
2781
2782 #ifndef PRODUCT
2783 if (failing()) { return; }
2784 constexpr int perBytecode = 6;
2785 if (C->should_print_igv(perBytecode)) {
2786 IdealGraphPrinter* printer = C->igv_printer();
2787 char buffer[256];
2788 jio_snprintf(buffer, sizeof(buffer), "Bytecode %d: %s, map: %d", bci(), Bytecodes::name(bc()), map() == nullptr ? -1 : map()->_idx);
2789 bool old = printer->traverse_outs();
2790 printer->set_traverse_outs(true);
2791 printer->print_graph(buffer);
2792 printer->set_traverse_outs(old);
2793 }
2794 #endif
2795 }