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