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