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