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