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