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