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