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