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