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