1 /*
   2  * Copyright (c) 1999, 2025, 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 "asm/macroAssembler.hpp"
  26 #include "ci/ciSymbols.hpp"
  27 #include "ci/ciUtilities.inline.hpp"
  28 #include "classfile/vmIntrinsics.hpp"
  29 #include "compiler/compileBroker.hpp"
  30 #include "compiler/compileLog.hpp"
  31 #include "gc/shared/barrierSet.hpp"
  32 #include "jfr/support/jfrIntrinsics.hpp"
  33 #include "memory/resourceArea.hpp"
  34 #include "oops/klass.inline.hpp"
  35 #include "oops/objArrayKlass.hpp"
  36 #include "opto/addnode.hpp"
  37 #include "opto/arraycopynode.hpp"
  38 #include "opto/c2compiler.hpp"
  39 #include "opto/castnode.hpp"
  40 #include "opto/cfgnode.hpp"
  41 #include "opto/convertnode.hpp"
  42 #include "opto/countbitsnode.hpp"
  43 #include "opto/idealKit.hpp"
  44 #include "opto/library_call.hpp"
  45 #include "opto/mathexactnode.hpp"
  46 #include "opto/mulnode.hpp"
  47 #include "opto/narrowptrnode.hpp"
  48 #include "opto/opaquenode.hpp"
  49 #include "opto/parse.hpp"
  50 #include "opto/rootnode.hpp"
  51 #include "opto/runtime.hpp"
  52 #include "opto/subnode.hpp"
  53 #include "opto/vectornode.hpp"
  54 #include "prims/jvmtiExport.hpp"
  55 #include "prims/jvmtiThreadState.hpp"
  56 #include "prims/unsafe.hpp"
  57 #include "runtime/jniHandles.inline.hpp"
  58 #include "runtime/mountUnmountDisabler.hpp"
  59 #include "runtime/objectMonitor.hpp"
  60 #include "runtime/sharedRuntime.hpp"
  61 #include "runtime/stubRoutines.hpp"
  62 #include "utilities/macros.hpp"
  63 #include "utilities/powerOfTwo.hpp"
  64 
  65 //---------------------------make_vm_intrinsic----------------------------
  66 CallGenerator* Compile::make_vm_intrinsic(ciMethod* m, bool is_virtual) {
  67   vmIntrinsicID id = m->intrinsic_id();
  68   assert(id != vmIntrinsics::_none, "must be a VM intrinsic");
  69 
  70   if (!m->is_loaded()) {
  71     // Do not attempt to inline unloaded methods.
  72     return nullptr;
  73   }
  74 
  75   C2Compiler* compiler = (C2Compiler*)CompileBroker::compiler(CompLevel_full_optimization);
  76   bool is_available = false;
  77 
  78   {
  79     // For calling is_intrinsic_supported and is_intrinsic_disabled_by_flag
  80     // the compiler must transition to '_thread_in_vm' state because both
  81     // methods access VM-internal data.
  82     VM_ENTRY_MARK;
  83     methodHandle mh(THREAD, m->get_Method());
  84     is_available = compiler != nullptr && compiler->is_intrinsic_available(mh, C->directive());
  85     if (is_available && is_virtual) {
  86       is_available = vmIntrinsics::does_virtual_dispatch(id);
  87     }
  88   }
  89 
  90   if (is_available) {
  91     assert(id <= vmIntrinsics::LAST_COMPILER_INLINE, "caller responsibility");
  92     assert(id != vmIntrinsics::_Object_init && id != vmIntrinsics::_invoke, "enum out of order?");
  93     return new LibraryIntrinsic(m, is_virtual,
  94                                 vmIntrinsics::predicates_needed(id),
  95                                 vmIntrinsics::does_virtual_dispatch(id),
  96                                 id);
  97   } else {
  98     return nullptr;
  99   }
 100 }
 101 
 102 JVMState* LibraryIntrinsic::generate(JVMState* jvms) {
 103   LibraryCallKit kit(jvms, this);
 104   Compile* C = kit.C;
 105   int nodes = C->unique();
 106 #ifndef PRODUCT
 107   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
 108     char buf[1000];
 109     const char* str = vmIntrinsics::short_name_as_C_string(intrinsic_id(), buf, sizeof(buf));
 110     tty->print_cr("Intrinsic %s", str);
 111   }
 112 #endif
 113   ciMethod* callee = kit.callee();
 114   const int bci    = kit.bci();
 115 #ifdef ASSERT
 116   Node* ctrl = kit.control();
 117 #endif
 118   // Try to inline the intrinsic.
 119   if (callee->check_intrinsic_candidate() &&
 120       kit.try_to_inline(_last_predicate)) {
 121     const char *inline_msg = is_virtual() ? "(intrinsic, virtual)"
 122                                           : "(intrinsic)";
 123     CompileTask::print_inlining_ul(callee, jvms->depth() - 1, bci, InliningResult::SUCCESS, inline_msg);
 124     C->inline_printer()->record(callee, jvms, InliningResult::SUCCESS, inline_msg);
 125     C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_worked);
 126     if (C->log()) {
 127       C->log()->elem("intrinsic id='%s'%s nodes='%d'",
 128                      vmIntrinsics::name_at(intrinsic_id()),
 129                      (is_virtual() ? " virtual='1'" : ""),
 130                      C->unique() - nodes);
 131     }
 132     // Push the result from the inlined method onto the stack.
 133     kit.push_result();
 134     return kit.transfer_exceptions_into_jvms();
 135   }
 136 
 137   // The intrinsic bailed out
 138   assert(ctrl == kit.control(), "Control flow was added although the intrinsic bailed out");
 139   assert(jvms->map() == kit.map(), "Out of sync JVM state");
 140   if (jvms->has_method()) {
 141     // Not a root compile.
 142     const char* msg;
 143     if (callee->intrinsic_candidate()) {
 144       msg = is_virtual() ? "failed to inline (intrinsic, virtual)" : "failed to inline (intrinsic)";
 145     } else {
 146       msg = is_virtual() ? "failed to inline (intrinsic, virtual), method not annotated"
 147                          : "failed to inline (intrinsic), method not annotated";
 148     }
 149     CompileTask::print_inlining_ul(callee, jvms->depth() - 1, bci, InliningResult::FAILURE, msg);
 150     C->inline_printer()->record(callee, jvms, InliningResult::FAILURE, msg);
 151   } else {
 152     // Root compile
 153     ResourceMark rm;
 154     stringStream msg_stream;
 155     msg_stream.print("Did not generate intrinsic %s%s at bci:%d in",
 156                      vmIntrinsics::name_at(intrinsic_id()),
 157                      is_virtual() ? " (virtual)" : "", bci);
 158     const char *msg = msg_stream.freeze();
 159     log_debug(jit, inlining)("%s", msg);
 160     if (C->print_intrinsics() || C->print_inlining()) {
 161       tty->print("%s", msg);
 162     }
 163   }
 164   C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_failed);
 165 
 166   return nullptr;
 167 }
 168 
 169 Node* LibraryIntrinsic::generate_predicate(JVMState* jvms, int predicate) {
 170   LibraryCallKit kit(jvms, this);
 171   Compile* C = kit.C;
 172   int nodes = C->unique();
 173   _last_predicate = predicate;
 174 #ifndef PRODUCT
 175   assert(is_predicated() && predicate < predicates_count(), "sanity");
 176   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
 177     char buf[1000];
 178     const char* str = vmIntrinsics::short_name_as_C_string(intrinsic_id(), buf, sizeof(buf));
 179     tty->print_cr("Predicate for intrinsic %s", str);
 180   }
 181 #endif
 182   ciMethod* callee = kit.callee();
 183   const int bci    = kit.bci();
 184 
 185   Node* slow_ctl = kit.try_to_predicate(predicate);
 186   if (!kit.failing()) {
 187     const char *inline_msg = is_virtual() ? "(intrinsic, virtual, predicate)"
 188                                           : "(intrinsic, predicate)";
 189     CompileTask::print_inlining_ul(callee, jvms->depth() - 1, bci, InliningResult::SUCCESS, inline_msg);
 190     C->inline_printer()->record(callee, jvms, InliningResult::SUCCESS, inline_msg);
 191 
 192     C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_worked);
 193     if (C->log()) {
 194       C->log()->elem("predicate_intrinsic id='%s'%s nodes='%d'",
 195                      vmIntrinsics::name_at(intrinsic_id()),
 196                      (is_virtual() ? " virtual='1'" : ""),
 197                      C->unique() - nodes);
 198     }
 199     return slow_ctl; // Could be null if the check folds.
 200   }
 201 
 202   // The intrinsic bailed out
 203   if (jvms->has_method()) {
 204     // Not a root compile.
 205     const char* msg = "failed to generate predicate for intrinsic";
 206     CompileTask::print_inlining_ul(kit.callee(), jvms->depth() - 1, bci, InliningResult::FAILURE, msg);
 207     C->inline_printer()->record(kit.callee(), jvms, InliningResult::FAILURE, msg);
 208   } else {
 209     // Root compile
 210     ResourceMark rm;
 211     stringStream msg_stream;
 212     msg_stream.print("Did not generate intrinsic %s%s at bci:%d in",
 213                      vmIntrinsics::name_at(intrinsic_id()),
 214                      is_virtual() ? " (virtual)" : "", bci);
 215     const char *msg = msg_stream.freeze();
 216     log_debug(jit, inlining)("%s", msg);
 217     C->inline_printer()->record(kit.callee(), jvms, InliningResult::FAILURE, msg);
 218   }
 219   C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_failed);
 220   return nullptr;
 221 }
 222 
 223 bool LibraryCallKit::try_to_inline(int predicate) {
 224   // Handle symbolic names for otherwise undistinguished boolean switches:
 225   const bool is_store       = true;
 226   const bool is_compress    = true;
 227   const bool is_static      = true;
 228   const bool is_volatile    = true;
 229 
 230   if (!jvms()->has_method()) {
 231     // Root JVMState has a null method.
 232     assert(map()->memory()->Opcode() == Op_Parm, "");
 233     // Insert the memory aliasing node
 234     set_all_memory(reset_memory());
 235   }
 236   assert(merged_memory(), "");
 237 
 238   switch (intrinsic_id()) {
 239   case vmIntrinsics::_hashCode:                 return inline_native_hashcode(intrinsic()->is_virtual(), !is_static);
 240   case vmIntrinsics::_identityHashCode:         return inline_native_hashcode(/*!virtual*/ false,         is_static);
 241   case vmIntrinsics::_getClass:                 return inline_native_getClass();
 242 
 243   case vmIntrinsics::_ceil:
 244   case vmIntrinsics::_floor:
 245   case vmIntrinsics::_rint:
 246   case vmIntrinsics::_dsin:
 247   case vmIntrinsics::_dcos:
 248   case vmIntrinsics::_dtan:
 249   case vmIntrinsics::_dsinh:
 250   case vmIntrinsics::_dtanh:
 251   case vmIntrinsics::_dcbrt:
 252   case vmIntrinsics::_dabs:
 253   case vmIntrinsics::_fabs:
 254   case vmIntrinsics::_iabs:
 255   case vmIntrinsics::_labs:
 256   case vmIntrinsics::_datan2:
 257   case vmIntrinsics::_dsqrt:
 258   case vmIntrinsics::_dsqrt_strict:
 259   case vmIntrinsics::_dexp:
 260   case vmIntrinsics::_dlog:
 261   case vmIntrinsics::_dlog10:
 262   case vmIntrinsics::_dpow:
 263   case vmIntrinsics::_dcopySign:
 264   case vmIntrinsics::_fcopySign:
 265   case vmIntrinsics::_dsignum:
 266   case vmIntrinsics::_roundF:
 267   case vmIntrinsics::_roundD:
 268   case vmIntrinsics::_fsignum:                  return inline_math_native(intrinsic_id());
 269 
 270   case vmIntrinsics::_notify:
 271   case vmIntrinsics::_notifyAll:
 272     return inline_notify(intrinsic_id());
 273 
 274   case vmIntrinsics::_addExactI:                return inline_math_addExactI(false /* add */);
 275   case vmIntrinsics::_addExactL:                return inline_math_addExactL(false /* add */);
 276   case vmIntrinsics::_decrementExactI:          return inline_math_subtractExactI(true /* decrement */);
 277   case vmIntrinsics::_decrementExactL:          return inline_math_subtractExactL(true /* decrement */);
 278   case vmIntrinsics::_incrementExactI:          return inline_math_addExactI(true /* increment */);
 279   case vmIntrinsics::_incrementExactL:          return inline_math_addExactL(true /* increment */);
 280   case vmIntrinsics::_multiplyExactI:           return inline_math_multiplyExactI();
 281   case vmIntrinsics::_multiplyExactL:           return inline_math_multiplyExactL();
 282   case vmIntrinsics::_multiplyHigh:             return inline_math_multiplyHigh();
 283   case vmIntrinsics::_unsignedMultiplyHigh:     return inline_math_unsignedMultiplyHigh();
 284   case vmIntrinsics::_negateExactI:             return inline_math_negateExactI();
 285   case vmIntrinsics::_negateExactL:             return inline_math_negateExactL();
 286   case vmIntrinsics::_subtractExactI:           return inline_math_subtractExactI(false /* subtract */);
 287   case vmIntrinsics::_subtractExactL:           return inline_math_subtractExactL(false /* subtract */);
 288 
 289   case vmIntrinsics::_arraycopy:                return inline_arraycopy();
 290 
 291   case vmIntrinsics::_arraySort:                return inline_array_sort();
 292   case vmIntrinsics::_arrayPartition:           return inline_array_partition();
 293 
 294   case vmIntrinsics::_compareToL:               return inline_string_compareTo(StrIntrinsicNode::LL);
 295   case vmIntrinsics::_compareToU:               return inline_string_compareTo(StrIntrinsicNode::UU);
 296   case vmIntrinsics::_compareToLU:              return inline_string_compareTo(StrIntrinsicNode::LU);
 297   case vmIntrinsics::_compareToUL:              return inline_string_compareTo(StrIntrinsicNode::UL);
 298 
 299   case vmIntrinsics::_indexOfL:                 return inline_string_indexOf(StrIntrinsicNode::LL);
 300   case vmIntrinsics::_indexOfU:                 return inline_string_indexOf(StrIntrinsicNode::UU);
 301   case vmIntrinsics::_indexOfUL:                return inline_string_indexOf(StrIntrinsicNode::UL);
 302   case vmIntrinsics::_indexOfIL:                return inline_string_indexOfI(StrIntrinsicNode::LL);
 303   case vmIntrinsics::_indexOfIU:                return inline_string_indexOfI(StrIntrinsicNode::UU);
 304   case vmIntrinsics::_indexOfIUL:               return inline_string_indexOfI(StrIntrinsicNode::UL);
 305   case vmIntrinsics::_indexOfU_char:            return inline_string_indexOfChar(StrIntrinsicNode::U);
 306   case vmIntrinsics::_indexOfL_char:            return inline_string_indexOfChar(StrIntrinsicNode::L);
 307 
 308   case vmIntrinsics::_equalsL:                  return inline_string_equals(StrIntrinsicNode::LL);
 309 
 310   case vmIntrinsics::_vectorizedHashCode:       return inline_vectorizedHashCode();
 311 
 312   case vmIntrinsics::_toBytesStringU:           return inline_string_toBytesU();
 313   case vmIntrinsics::_getCharsStringU:          return inline_string_getCharsU();
 314   case vmIntrinsics::_getCharStringU:           return inline_string_char_access(!is_store);
 315   case vmIntrinsics::_putCharStringU:           return inline_string_char_access( is_store);
 316 
 317   case vmIntrinsics::_compressStringC:
 318   case vmIntrinsics::_compressStringB:          return inline_string_copy( is_compress);
 319   case vmIntrinsics::_inflateStringC:
 320   case vmIntrinsics::_inflateStringB:           return inline_string_copy(!is_compress);
 321 
 322   case vmIntrinsics::_getReference:             return inline_unsafe_access(!is_store, T_OBJECT,   Relaxed, false);
 323   case vmIntrinsics::_getBoolean:               return inline_unsafe_access(!is_store, T_BOOLEAN,  Relaxed, false);
 324   case vmIntrinsics::_getByte:                  return inline_unsafe_access(!is_store, T_BYTE,     Relaxed, false);
 325   case vmIntrinsics::_getShort:                 return inline_unsafe_access(!is_store, T_SHORT,    Relaxed, false);
 326   case vmIntrinsics::_getChar:                  return inline_unsafe_access(!is_store, T_CHAR,     Relaxed, false);
 327   case vmIntrinsics::_getInt:                   return inline_unsafe_access(!is_store, T_INT,      Relaxed, false);
 328   case vmIntrinsics::_getLong:                  return inline_unsafe_access(!is_store, T_LONG,     Relaxed, false);
 329   case vmIntrinsics::_getFloat:                 return inline_unsafe_access(!is_store, T_FLOAT,    Relaxed, false);
 330   case vmIntrinsics::_getDouble:                return inline_unsafe_access(!is_store, T_DOUBLE,   Relaxed, false);
 331 
 332   case vmIntrinsics::_putReference:             return inline_unsafe_access( is_store, T_OBJECT,   Relaxed, false);
 333   case vmIntrinsics::_putBoolean:               return inline_unsafe_access( is_store, T_BOOLEAN,  Relaxed, false);
 334   case vmIntrinsics::_putByte:                  return inline_unsafe_access( is_store, T_BYTE,     Relaxed, false);
 335   case vmIntrinsics::_putShort:                 return inline_unsafe_access( is_store, T_SHORT,    Relaxed, false);
 336   case vmIntrinsics::_putChar:                  return inline_unsafe_access( is_store, T_CHAR,     Relaxed, false);
 337   case vmIntrinsics::_putInt:                   return inline_unsafe_access( is_store, T_INT,      Relaxed, false);
 338   case vmIntrinsics::_putLong:                  return inline_unsafe_access( is_store, T_LONG,     Relaxed, false);
 339   case vmIntrinsics::_putFloat:                 return inline_unsafe_access( is_store, T_FLOAT,    Relaxed, false);
 340   case vmIntrinsics::_putDouble:                return inline_unsafe_access( is_store, T_DOUBLE,   Relaxed, false);
 341 
 342   case vmIntrinsics::_getReferenceVolatile:     return inline_unsafe_access(!is_store, T_OBJECT,   Volatile, false);
 343   case vmIntrinsics::_getBooleanVolatile:       return inline_unsafe_access(!is_store, T_BOOLEAN,  Volatile, false);
 344   case vmIntrinsics::_getByteVolatile:          return inline_unsafe_access(!is_store, T_BYTE,     Volatile, false);
 345   case vmIntrinsics::_getShortVolatile:         return inline_unsafe_access(!is_store, T_SHORT,    Volatile, false);
 346   case vmIntrinsics::_getCharVolatile:          return inline_unsafe_access(!is_store, T_CHAR,     Volatile, false);
 347   case vmIntrinsics::_getIntVolatile:           return inline_unsafe_access(!is_store, T_INT,      Volatile, false);
 348   case vmIntrinsics::_getLongVolatile:          return inline_unsafe_access(!is_store, T_LONG,     Volatile, false);
 349   case vmIntrinsics::_getFloatVolatile:         return inline_unsafe_access(!is_store, T_FLOAT,    Volatile, false);
 350   case vmIntrinsics::_getDoubleVolatile:        return inline_unsafe_access(!is_store, T_DOUBLE,   Volatile, false);
 351 
 352   case vmIntrinsics::_putReferenceVolatile:     return inline_unsafe_access( is_store, T_OBJECT,   Volatile, false);
 353   case vmIntrinsics::_putBooleanVolatile:       return inline_unsafe_access( is_store, T_BOOLEAN,  Volatile, false);
 354   case vmIntrinsics::_putByteVolatile:          return inline_unsafe_access( is_store, T_BYTE,     Volatile, false);
 355   case vmIntrinsics::_putShortVolatile:         return inline_unsafe_access( is_store, T_SHORT,    Volatile, false);
 356   case vmIntrinsics::_putCharVolatile:          return inline_unsafe_access( is_store, T_CHAR,     Volatile, false);
 357   case vmIntrinsics::_putIntVolatile:           return inline_unsafe_access( is_store, T_INT,      Volatile, false);
 358   case vmIntrinsics::_putLongVolatile:          return inline_unsafe_access( is_store, T_LONG,     Volatile, false);
 359   case vmIntrinsics::_putFloatVolatile:         return inline_unsafe_access( is_store, T_FLOAT,    Volatile, false);
 360   case vmIntrinsics::_putDoubleVolatile:        return inline_unsafe_access( is_store, T_DOUBLE,   Volatile, false);
 361 
 362   case vmIntrinsics::_getShortUnaligned:        return inline_unsafe_access(!is_store, T_SHORT,    Relaxed, true);
 363   case vmIntrinsics::_getCharUnaligned:         return inline_unsafe_access(!is_store, T_CHAR,     Relaxed, true);
 364   case vmIntrinsics::_getIntUnaligned:          return inline_unsafe_access(!is_store, T_INT,      Relaxed, true);
 365   case vmIntrinsics::_getLongUnaligned:         return inline_unsafe_access(!is_store, T_LONG,     Relaxed, true);
 366 
 367   case vmIntrinsics::_putShortUnaligned:        return inline_unsafe_access( is_store, T_SHORT,    Relaxed, true);
 368   case vmIntrinsics::_putCharUnaligned:         return inline_unsafe_access( is_store, T_CHAR,     Relaxed, true);
 369   case vmIntrinsics::_putIntUnaligned:          return inline_unsafe_access( is_store, T_INT,      Relaxed, true);
 370   case vmIntrinsics::_putLongUnaligned:         return inline_unsafe_access( is_store, T_LONG,     Relaxed, true);
 371 
 372   case vmIntrinsics::_getReferenceAcquire:      return inline_unsafe_access(!is_store, T_OBJECT,   Acquire, false);
 373   case vmIntrinsics::_getBooleanAcquire:        return inline_unsafe_access(!is_store, T_BOOLEAN,  Acquire, false);
 374   case vmIntrinsics::_getByteAcquire:           return inline_unsafe_access(!is_store, T_BYTE,     Acquire, false);
 375   case vmIntrinsics::_getShortAcquire:          return inline_unsafe_access(!is_store, T_SHORT,    Acquire, false);
 376   case vmIntrinsics::_getCharAcquire:           return inline_unsafe_access(!is_store, T_CHAR,     Acquire, false);
 377   case vmIntrinsics::_getIntAcquire:            return inline_unsafe_access(!is_store, T_INT,      Acquire, false);
 378   case vmIntrinsics::_getLongAcquire:           return inline_unsafe_access(!is_store, T_LONG,     Acquire, false);
 379   case vmIntrinsics::_getFloatAcquire:          return inline_unsafe_access(!is_store, T_FLOAT,    Acquire, false);
 380   case vmIntrinsics::_getDoubleAcquire:         return inline_unsafe_access(!is_store, T_DOUBLE,   Acquire, false);
 381 
 382   case vmIntrinsics::_putReferenceRelease:      return inline_unsafe_access( is_store, T_OBJECT,   Release, false);
 383   case vmIntrinsics::_putBooleanRelease:        return inline_unsafe_access( is_store, T_BOOLEAN,  Release, false);
 384   case vmIntrinsics::_putByteRelease:           return inline_unsafe_access( is_store, T_BYTE,     Release, false);
 385   case vmIntrinsics::_putShortRelease:          return inline_unsafe_access( is_store, T_SHORT,    Release, false);
 386   case vmIntrinsics::_putCharRelease:           return inline_unsafe_access( is_store, T_CHAR,     Release, false);
 387   case vmIntrinsics::_putIntRelease:            return inline_unsafe_access( is_store, T_INT,      Release, false);
 388   case vmIntrinsics::_putLongRelease:           return inline_unsafe_access( is_store, T_LONG,     Release, false);
 389   case vmIntrinsics::_putFloatRelease:          return inline_unsafe_access( is_store, T_FLOAT,    Release, false);
 390   case vmIntrinsics::_putDoubleRelease:         return inline_unsafe_access( is_store, T_DOUBLE,   Release, false);
 391 
 392   case vmIntrinsics::_getReferenceOpaque:       return inline_unsafe_access(!is_store, T_OBJECT,   Opaque, false);
 393   case vmIntrinsics::_getBooleanOpaque:         return inline_unsafe_access(!is_store, T_BOOLEAN,  Opaque, false);
 394   case vmIntrinsics::_getByteOpaque:            return inline_unsafe_access(!is_store, T_BYTE,     Opaque, false);
 395   case vmIntrinsics::_getShortOpaque:           return inline_unsafe_access(!is_store, T_SHORT,    Opaque, false);
 396   case vmIntrinsics::_getCharOpaque:            return inline_unsafe_access(!is_store, T_CHAR,     Opaque, false);
 397   case vmIntrinsics::_getIntOpaque:             return inline_unsafe_access(!is_store, T_INT,      Opaque, false);
 398   case vmIntrinsics::_getLongOpaque:            return inline_unsafe_access(!is_store, T_LONG,     Opaque, false);
 399   case vmIntrinsics::_getFloatOpaque:           return inline_unsafe_access(!is_store, T_FLOAT,    Opaque, false);
 400   case vmIntrinsics::_getDoubleOpaque:          return inline_unsafe_access(!is_store, T_DOUBLE,   Opaque, false);
 401 
 402   case vmIntrinsics::_putReferenceOpaque:       return inline_unsafe_access( is_store, T_OBJECT,   Opaque, false);
 403   case vmIntrinsics::_putBooleanOpaque:         return inline_unsafe_access( is_store, T_BOOLEAN,  Opaque, false);
 404   case vmIntrinsics::_putByteOpaque:            return inline_unsafe_access( is_store, T_BYTE,     Opaque, false);
 405   case vmIntrinsics::_putShortOpaque:           return inline_unsafe_access( is_store, T_SHORT,    Opaque, false);
 406   case vmIntrinsics::_putCharOpaque:            return inline_unsafe_access( is_store, T_CHAR,     Opaque, false);
 407   case vmIntrinsics::_putIntOpaque:             return inline_unsafe_access( is_store, T_INT,      Opaque, false);
 408   case vmIntrinsics::_putLongOpaque:            return inline_unsafe_access( is_store, T_LONG,     Opaque, false);
 409   case vmIntrinsics::_putFloatOpaque:           return inline_unsafe_access( is_store, T_FLOAT,    Opaque, false);
 410   case vmIntrinsics::_putDoubleOpaque:          return inline_unsafe_access( is_store, T_DOUBLE,   Opaque, false);
 411 
 412   case vmIntrinsics::_compareAndSetReference:   return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap,      Volatile);
 413   case vmIntrinsics::_compareAndSetByte:        return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap,      Volatile);
 414   case vmIntrinsics::_compareAndSetShort:       return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap,      Volatile);
 415   case vmIntrinsics::_compareAndSetInt:         return inline_unsafe_load_store(T_INT,    LS_cmp_swap,      Volatile);
 416   case vmIntrinsics::_compareAndSetLong:        return inline_unsafe_load_store(T_LONG,   LS_cmp_swap,      Volatile);
 417 
 418   case vmIntrinsics::_weakCompareAndSetReferencePlain:     return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Relaxed);
 419   case vmIntrinsics::_weakCompareAndSetReferenceAcquire:   return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Acquire);
 420   case vmIntrinsics::_weakCompareAndSetReferenceRelease:   return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Release);
 421   case vmIntrinsics::_weakCompareAndSetReference:          return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Volatile);
 422   case vmIntrinsics::_weakCompareAndSetBytePlain:          return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap_weak, Relaxed);
 423   case vmIntrinsics::_weakCompareAndSetByteAcquire:        return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap_weak, Acquire);
 424   case vmIntrinsics::_weakCompareAndSetByteRelease:        return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap_weak, Release);
 425   case vmIntrinsics::_weakCompareAndSetByte:               return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap_weak, Volatile);
 426   case vmIntrinsics::_weakCompareAndSetShortPlain:         return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap_weak, Relaxed);
 427   case vmIntrinsics::_weakCompareAndSetShortAcquire:       return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap_weak, Acquire);
 428   case vmIntrinsics::_weakCompareAndSetShortRelease:       return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap_weak, Release);
 429   case vmIntrinsics::_weakCompareAndSetShort:              return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap_weak, Volatile);
 430   case vmIntrinsics::_weakCompareAndSetIntPlain:           return inline_unsafe_load_store(T_INT,    LS_cmp_swap_weak, Relaxed);
 431   case vmIntrinsics::_weakCompareAndSetIntAcquire:         return inline_unsafe_load_store(T_INT,    LS_cmp_swap_weak, Acquire);
 432   case vmIntrinsics::_weakCompareAndSetIntRelease:         return inline_unsafe_load_store(T_INT,    LS_cmp_swap_weak, Release);
 433   case vmIntrinsics::_weakCompareAndSetInt:                return inline_unsafe_load_store(T_INT,    LS_cmp_swap_weak, Volatile);
 434   case vmIntrinsics::_weakCompareAndSetLongPlain:          return inline_unsafe_load_store(T_LONG,   LS_cmp_swap_weak, Relaxed);
 435   case vmIntrinsics::_weakCompareAndSetLongAcquire:        return inline_unsafe_load_store(T_LONG,   LS_cmp_swap_weak, Acquire);
 436   case vmIntrinsics::_weakCompareAndSetLongRelease:        return inline_unsafe_load_store(T_LONG,   LS_cmp_swap_weak, Release);
 437   case vmIntrinsics::_weakCompareAndSetLong:               return inline_unsafe_load_store(T_LONG,   LS_cmp_swap_weak, Volatile);
 438 
 439   case vmIntrinsics::_compareAndExchangeReference:         return inline_unsafe_load_store(T_OBJECT, LS_cmp_exchange,  Volatile);
 440   case vmIntrinsics::_compareAndExchangeReferenceAcquire:  return inline_unsafe_load_store(T_OBJECT, LS_cmp_exchange,  Acquire);
 441   case vmIntrinsics::_compareAndExchangeReferenceRelease:  return inline_unsafe_load_store(T_OBJECT, LS_cmp_exchange,  Release);
 442   case vmIntrinsics::_compareAndExchangeByte:              return inline_unsafe_load_store(T_BYTE,   LS_cmp_exchange,  Volatile);
 443   case vmIntrinsics::_compareAndExchangeByteAcquire:       return inline_unsafe_load_store(T_BYTE,   LS_cmp_exchange,  Acquire);
 444   case vmIntrinsics::_compareAndExchangeByteRelease:       return inline_unsafe_load_store(T_BYTE,   LS_cmp_exchange,  Release);
 445   case vmIntrinsics::_compareAndExchangeShort:             return inline_unsafe_load_store(T_SHORT,  LS_cmp_exchange,  Volatile);
 446   case vmIntrinsics::_compareAndExchangeShortAcquire:      return inline_unsafe_load_store(T_SHORT,  LS_cmp_exchange,  Acquire);
 447   case vmIntrinsics::_compareAndExchangeShortRelease:      return inline_unsafe_load_store(T_SHORT,  LS_cmp_exchange,  Release);
 448   case vmIntrinsics::_compareAndExchangeInt:               return inline_unsafe_load_store(T_INT,    LS_cmp_exchange,  Volatile);
 449   case vmIntrinsics::_compareAndExchangeIntAcquire:        return inline_unsafe_load_store(T_INT,    LS_cmp_exchange,  Acquire);
 450   case vmIntrinsics::_compareAndExchangeIntRelease:        return inline_unsafe_load_store(T_INT,    LS_cmp_exchange,  Release);
 451   case vmIntrinsics::_compareAndExchangeLong:              return inline_unsafe_load_store(T_LONG,   LS_cmp_exchange,  Volatile);
 452   case vmIntrinsics::_compareAndExchangeLongAcquire:       return inline_unsafe_load_store(T_LONG,   LS_cmp_exchange,  Acquire);
 453   case vmIntrinsics::_compareAndExchangeLongRelease:       return inline_unsafe_load_store(T_LONG,   LS_cmp_exchange,  Release);
 454 
 455   case vmIntrinsics::_getAndAddByte:                    return inline_unsafe_load_store(T_BYTE,   LS_get_add,       Volatile);
 456   case vmIntrinsics::_getAndAddShort:                   return inline_unsafe_load_store(T_SHORT,  LS_get_add,       Volatile);
 457   case vmIntrinsics::_getAndAddInt:                     return inline_unsafe_load_store(T_INT,    LS_get_add,       Volatile);
 458   case vmIntrinsics::_getAndAddLong:                    return inline_unsafe_load_store(T_LONG,   LS_get_add,       Volatile);
 459 
 460   case vmIntrinsics::_getAndSetByte:                    return inline_unsafe_load_store(T_BYTE,   LS_get_set,       Volatile);
 461   case vmIntrinsics::_getAndSetShort:                   return inline_unsafe_load_store(T_SHORT,  LS_get_set,       Volatile);
 462   case vmIntrinsics::_getAndSetInt:                     return inline_unsafe_load_store(T_INT,    LS_get_set,       Volatile);
 463   case vmIntrinsics::_getAndSetLong:                    return inline_unsafe_load_store(T_LONG,   LS_get_set,       Volatile);
 464   case vmIntrinsics::_getAndSetReference:               return inline_unsafe_load_store(T_OBJECT, LS_get_set,       Volatile);
 465 
 466   case vmIntrinsics::_loadFence:
 467   case vmIntrinsics::_storeFence:
 468   case vmIntrinsics::_storeStoreFence:
 469   case vmIntrinsics::_fullFence:                return inline_unsafe_fence(intrinsic_id());
 470 
 471   case vmIntrinsics::_onSpinWait:               return inline_onspinwait();
 472 
 473   case vmIntrinsics::_currentCarrierThread:     return inline_native_currentCarrierThread();
 474   case vmIntrinsics::_currentThread:            return inline_native_currentThread();
 475   case vmIntrinsics::_setCurrentThread:         return inline_native_setCurrentThread();
 476 
 477   case vmIntrinsics::_scopedValueCache:          return inline_native_scopedValueCache();
 478   case vmIntrinsics::_setScopedValueCache:       return inline_native_setScopedValueCache();
 479 
 480   case vmIntrinsics::_Continuation_pin:          return inline_native_Continuation_pinning(false);
 481   case vmIntrinsics::_Continuation_unpin:        return inline_native_Continuation_pinning(true);
 482 
 483   case vmIntrinsics::_vthreadEndFirstTransition:    return inline_native_vthread_end_transition(CAST_FROM_FN_PTR(address, OptoRuntime::vthread_end_first_transition_Java()),
 484                                                                                                 "endFirstTransition", true);
 485   case vmIntrinsics::_vthreadStartFinalTransition:  return inline_native_vthread_start_transition(CAST_FROM_FN_PTR(address, OptoRuntime::vthread_start_final_transition_Java()),
 486                                                                                                   "startFinalTransition", true);
 487   case vmIntrinsics::_vthreadStartTransition:       return inline_native_vthread_start_transition(CAST_FROM_FN_PTR(address, OptoRuntime::vthread_start_transition_Java()),
 488                                                                                                   "startTransition", false);
 489   case vmIntrinsics::_vthreadEndTransition:         return inline_native_vthread_end_transition(CAST_FROM_FN_PTR(address, OptoRuntime::vthread_end_transition_Java()),
 490                                                                                                 "endTransition", false);
 491 #if INCLUDE_JVMTI
 492   case vmIntrinsics::_notifyJvmtiVThreadDisableSuspend: return inline_native_notify_jvmti_sync();
 493 #endif
 494 
 495 #ifdef JFR_HAVE_INTRINSICS
 496   case vmIntrinsics::_counterTime:              return inline_native_time_funcs(CAST_FROM_FN_PTR(address, JfrTime::time_function()), "counterTime");
 497   case vmIntrinsics::_getEventWriter:           return inline_native_getEventWriter();
 498   case vmIntrinsics::_jvm_commit:               return inline_native_jvm_commit();
 499 #endif
 500   case vmIntrinsics::_currentTimeMillis:        return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeMillis), "currentTimeMillis");
 501   case vmIntrinsics::_nanoTime:                 return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeNanos), "nanoTime");
 502   case vmIntrinsics::_writeback0:               return inline_unsafe_writeback0();
 503   case vmIntrinsics::_writebackPreSync0:        return inline_unsafe_writebackSync0(true);
 504   case vmIntrinsics::_writebackPostSync0:       return inline_unsafe_writebackSync0(false);
 505   case vmIntrinsics::_allocateInstance:         return inline_unsafe_allocate();
 506   case vmIntrinsics::_copyMemory:               return inline_unsafe_copyMemory();
 507   case vmIntrinsics::_setMemory:                return inline_unsafe_setMemory();
 508   case vmIntrinsics::_getLength:                return inline_native_getLength();
 509   case vmIntrinsics::_copyOf:                   return inline_array_copyOf(false);
 510   case vmIntrinsics::_copyOfRange:              return inline_array_copyOf(true);
 511   case vmIntrinsics::_equalsB:                  return inline_array_equals(StrIntrinsicNode::LL);
 512   case vmIntrinsics::_equalsC:                  return inline_array_equals(StrIntrinsicNode::UU);
 513   case vmIntrinsics::_Preconditions_checkIndex: return inline_preconditions_checkIndex(T_INT);
 514   case vmIntrinsics::_Preconditions_checkLongIndex: return inline_preconditions_checkIndex(T_LONG);
 515   case vmIntrinsics::_clone:                    return inline_native_clone(intrinsic()->is_virtual());
 516 
 517   case vmIntrinsics::_allocateUninitializedArray: return inline_unsafe_newArray(true);
 518   case vmIntrinsics::_newArray:                   return inline_unsafe_newArray(false);
 519 
 520   case vmIntrinsics::_isAssignableFrom:         return inline_native_subtype_check();
 521 
 522   case vmIntrinsics::_isInstance:
 523   case vmIntrinsics::_isHidden:
 524   case vmIntrinsics::_getSuperclass:            return inline_native_Class_query(intrinsic_id());
 525 
 526   case vmIntrinsics::_floatToRawIntBits:
 527   case vmIntrinsics::_floatToIntBits:
 528   case vmIntrinsics::_intBitsToFloat:
 529   case vmIntrinsics::_doubleToRawLongBits:
 530   case vmIntrinsics::_doubleToLongBits:
 531   case vmIntrinsics::_longBitsToDouble:
 532   case vmIntrinsics::_floatToFloat16:
 533   case vmIntrinsics::_float16ToFloat:           return inline_fp_conversions(intrinsic_id());
 534   case vmIntrinsics::_sqrt_float16:             return inline_fp16_operations(intrinsic_id(), 1);
 535   case vmIntrinsics::_fma_float16:              return inline_fp16_operations(intrinsic_id(), 3);
 536   case vmIntrinsics::_floatIsFinite:
 537   case vmIntrinsics::_floatIsInfinite:
 538   case vmIntrinsics::_doubleIsFinite:
 539   case vmIntrinsics::_doubleIsInfinite:         return inline_fp_range_check(intrinsic_id());
 540 
 541   case vmIntrinsics::_numberOfLeadingZeros_i:
 542   case vmIntrinsics::_numberOfLeadingZeros_l:
 543   case vmIntrinsics::_numberOfTrailingZeros_i:
 544   case vmIntrinsics::_numberOfTrailingZeros_l:
 545   case vmIntrinsics::_bitCount_i:
 546   case vmIntrinsics::_bitCount_l:
 547   case vmIntrinsics::_reverse_i:
 548   case vmIntrinsics::_reverse_l:
 549   case vmIntrinsics::_reverseBytes_i:
 550   case vmIntrinsics::_reverseBytes_l:
 551   case vmIntrinsics::_reverseBytes_s:
 552   case vmIntrinsics::_reverseBytes_c:           return inline_number_methods(intrinsic_id());
 553 
 554   case vmIntrinsics::_compress_i:
 555   case vmIntrinsics::_compress_l:
 556   case vmIntrinsics::_expand_i:
 557   case vmIntrinsics::_expand_l:                 return inline_bitshuffle_methods(intrinsic_id());
 558 
 559   case vmIntrinsics::_compareUnsigned_i:
 560   case vmIntrinsics::_compareUnsigned_l:        return inline_compare_unsigned(intrinsic_id());
 561 
 562   case vmIntrinsics::_divideUnsigned_i:
 563   case vmIntrinsics::_divideUnsigned_l:
 564   case vmIntrinsics::_remainderUnsigned_i:
 565   case vmIntrinsics::_remainderUnsigned_l:      return inline_divmod_methods(intrinsic_id());
 566 
 567   case vmIntrinsics::_getCallerClass:           return inline_native_Reflection_getCallerClass();
 568 
 569   case vmIntrinsics::_Reference_get0:           return inline_reference_get0();
 570   case vmIntrinsics::_Reference_refersTo0:      return inline_reference_refersTo0(false);
 571   case vmIntrinsics::_PhantomReference_refersTo0: return inline_reference_refersTo0(true);
 572   case vmIntrinsics::_Reference_clear0:         return inline_reference_clear0(false);
 573   case vmIntrinsics::_PhantomReference_clear0:  return inline_reference_clear0(true);
 574 
 575   case vmIntrinsics::_Class_cast:               return inline_Class_cast();
 576 
 577   case vmIntrinsics::_aescrypt_encryptBlock:
 578   case vmIntrinsics::_aescrypt_decryptBlock:    return inline_aescrypt_Block(intrinsic_id());
 579 
 580   case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
 581   case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
 582     return inline_cipherBlockChaining_AESCrypt(intrinsic_id());
 583 
 584   case vmIntrinsics::_electronicCodeBook_encryptAESCrypt:
 585   case vmIntrinsics::_electronicCodeBook_decryptAESCrypt:
 586     return inline_electronicCodeBook_AESCrypt(intrinsic_id());
 587 
 588   case vmIntrinsics::_counterMode_AESCrypt:
 589     return inline_counterMode_AESCrypt(intrinsic_id());
 590 
 591   case vmIntrinsics::_galoisCounterMode_AESCrypt:
 592     return inline_galoisCounterMode_AESCrypt();
 593 
 594   case vmIntrinsics::_md5_implCompress:
 595   case vmIntrinsics::_sha_implCompress:
 596   case vmIntrinsics::_sha2_implCompress:
 597   case vmIntrinsics::_sha5_implCompress:
 598   case vmIntrinsics::_sha3_implCompress:
 599     return inline_digestBase_implCompress(intrinsic_id());
 600   case vmIntrinsics::_double_keccak:
 601     return inline_double_keccak();
 602 
 603   case vmIntrinsics::_digestBase_implCompressMB:
 604     return inline_digestBase_implCompressMB(predicate);
 605 
 606   case vmIntrinsics::_multiplyToLen:
 607     return inline_multiplyToLen();
 608 
 609   case vmIntrinsics::_squareToLen:
 610     return inline_squareToLen();
 611 
 612   case vmIntrinsics::_mulAdd:
 613     return inline_mulAdd();
 614 
 615   case vmIntrinsics::_montgomeryMultiply:
 616     return inline_montgomeryMultiply();
 617   case vmIntrinsics::_montgomerySquare:
 618     return inline_montgomerySquare();
 619 
 620   case vmIntrinsics::_bigIntegerRightShiftWorker:
 621     return inline_bigIntegerShift(true);
 622   case vmIntrinsics::_bigIntegerLeftShiftWorker:
 623     return inline_bigIntegerShift(false);
 624 
 625   case vmIntrinsics::_vectorizedMismatch:
 626     return inline_vectorizedMismatch();
 627 
 628   case vmIntrinsics::_ghash_processBlocks:
 629     return inline_ghash_processBlocks();
 630   case vmIntrinsics::_chacha20Block:
 631     return inline_chacha20Block();
 632   case vmIntrinsics::_kyberNtt:
 633     return inline_kyberNtt();
 634   case vmIntrinsics::_kyberInverseNtt:
 635     return inline_kyberInverseNtt();
 636   case vmIntrinsics::_kyberNttMult:
 637     return inline_kyberNttMult();
 638   case vmIntrinsics::_kyberAddPoly_2:
 639     return inline_kyberAddPoly_2();
 640   case vmIntrinsics::_kyberAddPoly_3:
 641     return inline_kyberAddPoly_3();
 642   case vmIntrinsics::_kyber12To16:
 643     return inline_kyber12To16();
 644   case vmIntrinsics::_kyberBarrettReduce:
 645     return inline_kyberBarrettReduce();
 646   case vmIntrinsics::_dilithiumAlmostNtt:
 647     return inline_dilithiumAlmostNtt();
 648   case vmIntrinsics::_dilithiumAlmostInverseNtt:
 649     return inline_dilithiumAlmostInverseNtt();
 650   case vmIntrinsics::_dilithiumNttMult:
 651     return inline_dilithiumNttMult();
 652   case vmIntrinsics::_dilithiumMontMulByConstant:
 653     return inline_dilithiumMontMulByConstant();
 654   case vmIntrinsics::_dilithiumDecomposePoly:
 655     return inline_dilithiumDecomposePoly();
 656   case vmIntrinsics::_base64_encodeBlock:
 657     return inline_base64_encodeBlock();
 658   case vmIntrinsics::_base64_decodeBlock:
 659     return inline_base64_decodeBlock();
 660   case vmIntrinsics::_poly1305_processBlocks:
 661     return inline_poly1305_processBlocks();
 662   case vmIntrinsics::_intpoly_montgomeryMult_P256:
 663     return inline_intpoly_montgomeryMult_P256();
 664   case vmIntrinsics::_intpoly_assign:
 665     return inline_intpoly_assign();
 666   case vmIntrinsics::_encodeISOArray:
 667   case vmIntrinsics::_encodeByteISOArray:
 668     return inline_encodeISOArray(false);
 669   case vmIntrinsics::_encodeAsciiArray:
 670     return inline_encodeISOArray(true);
 671 
 672   case vmIntrinsics::_updateCRC32:
 673     return inline_updateCRC32();
 674   case vmIntrinsics::_updateBytesCRC32:
 675     return inline_updateBytesCRC32();
 676   case vmIntrinsics::_updateByteBufferCRC32:
 677     return inline_updateByteBufferCRC32();
 678 
 679   case vmIntrinsics::_updateBytesCRC32C:
 680     return inline_updateBytesCRC32C();
 681   case vmIntrinsics::_updateDirectByteBufferCRC32C:
 682     return inline_updateDirectByteBufferCRC32C();
 683 
 684   case vmIntrinsics::_updateBytesAdler32:
 685     return inline_updateBytesAdler32();
 686   case vmIntrinsics::_updateByteBufferAdler32:
 687     return inline_updateByteBufferAdler32();
 688 
 689   case vmIntrinsics::_profileBoolean:
 690     return inline_profileBoolean();
 691   case vmIntrinsics::_isCompileConstant:
 692     return inline_isCompileConstant();
 693 
 694   case vmIntrinsics::_countPositives:
 695     return inline_countPositives();
 696 
 697   case vmIntrinsics::_fmaD:
 698   case vmIntrinsics::_fmaF:
 699     return inline_fma(intrinsic_id());
 700 
 701   case vmIntrinsics::_isDigit:
 702   case vmIntrinsics::_isLowerCase:
 703   case vmIntrinsics::_isUpperCase:
 704   case vmIntrinsics::_isWhitespace:
 705     return inline_character_compare(intrinsic_id());
 706 
 707   case vmIntrinsics::_min:
 708   case vmIntrinsics::_max:
 709   case vmIntrinsics::_min_strict:
 710   case vmIntrinsics::_max_strict:
 711   case vmIntrinsics::_minL:
 712   case vmIntrinsics::_maxL:
 713   case vmIntrinsics::_minF:
 714   case vmIntrinsics::_maxF:
 715   case vmIntrinsics::_minD:
 716   case vmIntrinsics::_maxD:
 717   case vmIntrinsics::_minF_strict:
 718   case vmIntrinsics::_maxF_strict:
 719   case vmIntrinsics::_minD_strict:
 720   case vmIntrinsics::_maxD_strict:
 721     return inline_min_max(intrinsic_id());
 722 
 723   case vmIntrinsics::_VectorUnaryOp:
 724     return inline_vector_nary_operation(1);
 725   case vmIntrinsics::_VectorBinaryOp:
 726     return inline_vector_nary_operation(2);
 727   case vmIntrinsics::_VectorUnaryLibOp:
 728     return inline_vector_call(1);
 729   case vmIntrinsics::_VectorBinaryLibOp:
 730     return inline_vector_call(2);
 731   case vmIntrinsics::_VectorTernaryOp:
 732     return inline_vector_nary_operation(3);
 733   case vmIntrinsics::_VectorFromBitsCoerced:
 734     return inline_vector_frombits_coerced();
 735   case vmIntrinsics::_VectorMaskOp:
 736     return inline_vector_mask_operation();
 737   case vmIntrinsics::_VectorLoadOp:
 738     return inline_vector_mem_operation(/*is_store=*/false);
 739   case vmIntrinsics::_VectorLoadMaskedOp:
 740     return inline_vector_mem_masked_operation(/*is_store*/false);
 741   case vmIntrinsics::_VectorStoreOp:
 742     return inline_vector_mem_operation(/*is_store=*/true);
 743   case vmIntrinsics::_VectorStoreMaskedOp:
 744     return inline_vector_mem_masked_operation(/*is_store=*/true);
 745   case vmIntrinsics::_VectorGatherOp:
 746     return inline_vector_gather_scatter(/*is_scatter*/ false);
 747   case vmIntrinsics::_VectorScatterOp:
 748     return inline_vector_gather_scatter(/*is_scatter*/ true);
 749   case vmIntrinsics::_VectorReductionCoerced:
 750     return inline_vector_reduction();
 751   case vmIntrinsics::_VectorTest:
 752     return inline_vector_test();
 753   case vmIntrinsics::_VectorBlend:
 754     return inline_vector_blend();
 755   case vmIntrinsics::_VectorRearrange:
 756     return inline_vector_rearrange();
 757   case vmIntrinsics::_VectorSelectFrom:
 758     return inline_vector_select_from();
 759   case vmIntrinsics::_VectorCompare:
 760     return inline_vector_compare();
 761   case vmIntrinsics::_VectorBroadcastInt:
 762     return inline_vector_broadcast_int();
 763   case vmIntrinsics::_VectorConvert:
 764     return inline_vector_convert();
 765   case vmIntrinsics::_VectorInsert:
 766     return inline_vector_insert();
 767   case vmIntrinsics::_VectorExtract:
 768     return inline_vector_extract();
 769   case vmIntrinsics::_VectorCompressExpand:
 770     return inline_vector_compress_expand();
 771   case vmIntrinsics::_VectorSelectFromTwoVectorOp:
 772     return inline_vector_select_from_two_vectors();
 773   case vmIntrinsics::_IndexVector:
 774     return inline_index_vector();
 775   case vmIntrinsics::_IndexPartiallyInUpperRange:
 776     return inline_index_partially_in_upper_range();
 777 
 778   case vmIntrinsics::_getObjectSize:
 779     return inline_getObjectSize();
 780 
 781   case vmIntrinsics::_blackhole:
 782     return inline_blackhole();
 783 
 784   default:
 785     // If you get here, it may be that someone has added a new intrinsic
 786     // to the list in vmIntrinsics.hpp without implementing it here.
 787 #ifndef PRODUCT
 788     if ((PrintMiscellaneous && (Verbose || WizardMode)) || PrintOpto) {
 789       tty->print_cr("*** Warning: Unimplemented intrinsic %s(%d)",
 790                     vmIntrinsics::name_at(intrinsic_id()), vmIntrinsics::as_int(intrinsic_id()));
 791     }
 792 #endif
 793     return false;
 794   }
 795 }
 796 
 797 Node* LibraryCallKit::try_to_predicate(int predicate) {
 798   if (!jvms()->has_method()) {
 799     // Root JVMState has a null method.
 800     assert(map()->memory()->Opcode() == Op_Parm, "");
 801     // Insert the memory aliasing node
 802     set_all_memory(reset_memory());
 803   }
 804   assert(merged_memory(), "");
 805 
 806   switch (intrinsic_id()) {
 807   case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
 808     return inline_cipherBlockChaining_AESCrypt_predicate(false);
 809   case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
 810     return inline_cipherBlockChaining_AESCrypt_predicate(true);
 811   case vmIntrinsics::_electronicCodeBook_encryptAESCrypt:
 812     return inline_electronicCodeBook_AESCrypt_predicate(false);
 813   case vmIntrinsics::_electronicCodeBook_decryptAESCrypt:
 814     return inline_electronicCodeBook_AESCrypt_predicate(true);
 815   case vmIntrinsics::_counterMode_AESCrypt:
 816     return inline_counterMode_AESCrypt_predicate();
 817   case vmIntrinsics::_digestBase_implCompressMB:
 818     return inline_digestBase_implCompressMB_predicate(predicate);
 819   case vmIntrinsics::_galoisCounterMode_AESCrypt:
 820     return inline_galoisCounterMode_AESCrypt_predicate();
 821 
 822   default:
 823     // If you get here, it may be that someone has added a new intrinsic
 824     // to the list in vmIntrinsics.hpp without implementing it here.
 825 #ifndef PRODUCT
 826     if ((PrintMiscellaneous && (Verbose || WizardMode)) || PrintOpto) {
 827       tty->print_cr("*** Warning: Unimplemented predicate for intrinsic %s(%d)",
 828                     vmIntrinsics::name_at(intrinsic_id()), vmIntrinsics::as_int(intrinsic_id()));
 829     }
 830 #endif
 831     Node* slow_ctl = control();
 832     set_control(top()); // No fast path intrinsic
 833     return slow_ctl;
 834   }
 835 }
 836 
 837 //------------------------------set_result-------------------------------
 838 // Helper function for finishing intrinsics.
 839 void LibraryCallKit::set_result(RegionNode* region, PhiNode* value) {
 840   record_for_igvn(region);
 841   set_control(_gvn.transform(region));
 842   set_result( _gvn.transform(value));
 843   assert(value->type()->basic_type() == result()->bottom_type()->basic_type(), "sanity");
 844 }
 845 
 846 //------------------------------generate_guard---------------------------
 847 // Helper function for generating guarded fast-slow graph structures.
 848 // The given 'test', if true, guards a slow path.  If the test fails
 849 // then a fast path can be taken.  (We generally hope it fails.)
 850 // In all cases, GraphKit::control() is updated to the fast path.
 851 // The returned value represents the control for the slow path.
 852 // The return value is never 'top'; it is either a valid control
 853 // or null if it is obvious that the slow path can never be taken.
 854 // Also, if region and the slow control are not null, the slow edge
 855 // is appended to the region.
 856 Node* LibraryCallKit::generate_guard(Node* test, RegionNode* region, float true_prob) {
 857   if (stopped()) {
 858     // Already short circuited.
 859     return nullptr;
 860   }
 861 
 862   // Build an if node and its projections.
 863   // If test is true we take the slow path, which we assume is uncommon.
 864   if (_gvn.type(test) == TypeInt::ZERO) {
 865     // The slow branch is never taken.  No need to build this guard.
 866     return nullptr;
 867   }
 868 
 869   IfNode* iff = create_and_map_if(control(), test, true_prob, COUNT_UNKNOWN);
 870 
 871   Node* if_slow = _gvn.transform(new IfTrueNode(iff));
 872   if (if_slow == top()) {
 873     // The slow branch is never taken.  No need to build this guard.
 874     return nullptr;
 875   }
 876 
 877   if (region != nullptr)
 878     region->add_req(if_slow);
 879 
 880   Node* if_fast = _gvn.transform(new IfFalseNode(iff));
 881   set_control(if_fast);
 882 
 883   return if_slow;
 884 }
 885 
 886 inline Node* LibraryCallKit::generate_slow_guard(Node* test, RegionNode* region) {
 887   return generate_guard(test, region, PROB_UNLIKELY_MAG(3));
 888 }
 889 inline Node* LibraryCallKit::generate_fair_guard(Node* test, RegionNode* region) {
 890   return generate_guard(test, region, PROB_FAIR);
 891 }
 892 
 893 inline Node* LibraryCallKit::generate_negative_guard(Node* index, RegionNode* region,
 894                                                      Node* *pos_index) {
 895   if (stopped())
 896     return nullptr;                // already stopped
 897   if (_gvn.type(index)->higher_equal(TypeInt::POS)) // [0,maxint]
 898     return nullptr;                // index is already adequately typed
 899   Node* cmp_lt = _gvn.transform(new CmpINode(index, intcon(0)));
 900   Node* bol_lt = _gvn.transform(new BoolNode(cmp_lt, BoolTest::lt));
 901   Node* is_neg = generate_guard(bol_lt, region, PROB_MIN);
 902   if (is_neg != nullptr && pos_index != nullptr) {
 903     // Emulate effect of Parse::adjust_map_after_if.
 904     Node* ccast = new CastIINode(control(), index, TypeInt::POS);
 905     (*pos_index) = _gvn.transform(ccast);
 906   }
 907   return is_neg;
 908 }
 909 
 910 // Make sure that 'position' is a valid limit index, in [0..length].
 911 // There are two equivalent plans for checking this:
 912 //   A. (offset + copyLength)  unsigned<=  arrayLength
 913 //   B. offset  <=  (arrayLength - copyLength)
 914 // We require that all of the values above, except for the sum and
 915 // difference, are already known to be non-negative.
 916 // Plan A is robust in the face of overflow, if offset and copyLength
 917 // are both hugely positive.
 918 //
 919 // Plan B is less direct and intuitive, but it does not overflow at
 920 // all, since the difference of two non-negatives is always
 921 // representable.  Whenever Java methods must perform the equivalent
 922 // check they generally use Plan B instead of Plan A.
 923 // For the moment we use Plan A.
 924 inline Node* LibraryCallKit::generate_limit_guard(Node* offset,
 925                                                   Node* subseq_length,
 926                                                   Node* array_length,
 927                                                   RegionNode* region) {
 928   if (stopped())
 929     return nullptr;                // already stopped
 930   bool zero_offset = _gvn.type(offset) == TypeInt::ZERO;
 931   if (zero_offset && subseq_length->eqv_uncast(array_length))
 932     return nullptr;                // common case of whole-array copy
 933   Node* last = subseq_length;
 934   if (!zero_offset)             // last += offset
 935     last = _gvn.transform(new AddINode(last, offset));
 936   Node* cmp_lt = _gvn.transform(new CmpUNode(array_length, last));
 937   Node* bol_lt = _gvn.transform(new BoolNode(cmp_lt, BoolTest::lt));
 938   Node* is_over = generate_guard(bol_lt, region, PROB_MIN);
 939   return is_over;
 940 }
 941 
 942 // Emit range checks for the given String.value byte array
 943 void LibraryCallKit::generate_string_range_check(Node* array,
 944                                                  Node* offset,
 945                                                  Node* count,
 946                                                  bool char_count,
 947                                                  bool halt_on_oob) {
 948   if (stopped()) {
 949     return; // already stopped
 950   }
 951   RegionNode* bailout = new RegionNode(1);
 952   record_for_igvn(bailout);
 953   if (char_count) {
 954     // Convert char count to byte count
 955     count = _gvn.transform(new LShiftINode(count, intcon(1)));
 956   }
 957 
 958   // Offset and count must not be negative
 959   generate_negative_guard(offset, bailout);
 960   generate_negative_guard(count, bailout);
 961   // Offset + count must not exceed length of array
 962   generate_limit_guard(offset, count, load_array_length(array), bailout);
 963 
 964   if (bailout->req() > 1) {
 965     if (halt_on_oob) {
 966       bailout = _gvn.transform(bailout)->as_Region();
 967       Node* frame = _gvn.transform(new ParmNode(C->start(), TypeFunc::FramePtr));
 968       Node* halt = _gvn.transform(new HaltNode(bailout, frame, "unexpected guard failure in intrinsic"));
 969       C->root()->add_req(halt);
 970     } else {
 971       PreserveJVMState pjvms(this);
 972       set_control(_gvn.transform(bailout));
 973       uncommon_trap(Deoptimization::Reason_intrinsic,
 974                     Deoptimization::Action_maybe_recompile);
 975     }
 976   }
 977 }
 978 
 979 Node* LibraryCallKit::current_thread_helper(Node*& tls_output, ByteSize handle_offset,
 980                                             bool is_immutable) {
 981   ciKlass* thread_klass = env()->Thread_klass();
 982   const Type* thread_type
 983     = TypeOopPtr::make_from_klass(thread_klass)->cast_to_ptr_type(TypePtr::NotNull);
 984 
 985   Node* thread = _gvn.transform(new ThreadLocalNode());
 986   Node* p = basic_plus_adr(top()/*!oop*/, thread, in_bytes(handle_offset));
 987   tls_output = thread;
 988 
 989   Node* thread_obj_handle
 990     = (is_immutable
 991       ? LoadNode::make(_gvn, nullptr, immutable_memory(), p, p->bottom_type()->is_ptr(),
 992         TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered)
 993       : make_load(nullptr, p, p->bottom_type()->is_ptr(), T_ADDRESS, MemNode::unordered));
 994   thread_obj_handle = _gvn.transform(thread_obj_handle);
 995 
 996   DecoratorSet decorators = IN_NATIVE;
 997   if (is_immutable) {
 998     decorators |= C2_IMMUTABLE_MEMORY;
 999   }
1000   return access_load(thread_obj_handle, thread_type, T_OBJECT, decorators);
1001 }
1002 
1003 //--------------------------generate_current_thread--------------------
1004 Node* LibraryCallKit::generate_current_thread(Node* &tls_output) {
1005   return current_thread_helper(tls_output, JavaThread::threadObj_offset(),
1006                                /*is_immutable*/false);
1007 }
1008 
1009 //--------------------------generate_virtual_thread--------------------
1010 Node* LibraryCallKit::generate_virtual_thread(Node* tls_output) {
1011   return current_thread_helper(tls_output, JavaThread::vthread_offset(),
1012                                !C->method()->changes_current_thread());
1013 }
1014 
1015 //------------------------------make_string_method_node------------------------
1016 // Helper method for String intrinsic functions. This version is called with
1017 // str1 and str2 pointing to byte[] nodes containing Latin1 or UTF16 encoded
1018 // characters (depending on 'is_byte'). cnt1 and cnt2 are pointing to Int nodes
1019 // containing the lengths of str1 and str2.
1020 Node* LibraryCallKit::make_string_method_node(int opcode, Node* str1_start, Node* cnt1, Node* str2_start, Node* cnt2, StrIntrinsicNode::ArgEnc ae) {
1021   Node* result = nullptr;
1022   switch (opcode) {
1023   case Op_StrIndexOf:
1024     result = new StrIndexOfNode(control(), memory(TypeAryPtr::BYTES),
1025                                 str1_start, cnt1, str2_start, cnt2, ae);
1026     break;
1027   case Op_StrComp:
1028     result = new StrCompNode(control(), memory(TypeAryPtr::BYTES),
1029                              str1_start, cnt1, str2_start, cnt2, ae);
1030     break;
1031   case Op_StrEquals:
1032     // We already know that cnt1 == cnt2 here (checked in 'inline_string_equals').
1033     // Use the constant length if there is one because optimized match rule may exist.
1034     result = new StrEqualsNode(control(), memory(TypeAryPtr::BYTES),
1035                                str1_start, str2_start, cnt2->is_Con() ? cnt2 : cnt1, ae);
1036     break;
1037   default:
1038     ShouldNotReachHere();
1039     return nullptr;
1040   }
1041 
1042   // All these intrinsics have checks.
1043   C->set_has_split_ifs(true); // Has chance for split-if optimization
1044   clear_upper_avx();
1045 
1046   return _gvn.transform(result);
1047 }
1048 
1049 //------------------------------inline_string_compareTo------------------------
1050 bool LibraryCallKit::inline_string_compareTo(StrIntrinsicNode::ArgEnc ae) {
1051   Node* arg1 = argument(0);
1052   Node* arg2 = argument(1);
1053 
1054   arg1 = must_be_not_null(arg1, true);
1055   arg2 = must_be_not_null(arg2, true);
1056 
1057   // Get start addr and length of first argument
1058   Node* arg1_start  = array_element_address(arg1, intcon(0), T_BYTE);
1059   Node* arg1_cnt    = load_array_length(arg1);
1060 
1061   // Get start addr and length of second argument
1062   Node* arg2_start  = array_element_address(arg2, intcon(0), T_BYTE);
1063   Node* arg2_cnt    = load_array_length(arg2);
1064 
1065   Node* result = make_string_method_node(Op_StrComp, arg1_start, arg1_cnt, arg2_start, arg2_cnt, ae);
1066   set_result(result);
1067   return true;
1068 }
1069 
1070 //------------------------------inline_string_equals------------------------
1071 bool LibraryCallKit::inline_string_equals(StrIntrinsicNode::ArgEnc ae) {
1072   Node* arg1 = argument(0);
1073   Node* arg2 = argument(1);
1074 
1075   // paths (plus control) merge
1076   RegionNode* region = new RegionNode(3);
1077   Node* phi = new PhiNode(region, TypeInt::BOOL);
1078 
1079   if (!stopped()) {
1080 
1081     arg1 = must_be_not_null(arg1, true);
1082     arg2 = must_be_not_null(arg2, true);
1083 
1084     // Get start addr and length of first argument
1085     Node* arg1_start  = array_element_address(arg1, intcon(0), T_BYTE);
1086     Node* arg1_cnt    = load_array_length(arg1);
1087 
1088     // Get start addr and length of second argument
1089     Node* arg2_start  = array_element_address(arg2, intcon(0), T_BYTE);
1090     Node* arg2_cnt    = load_array_length(arg2);
1091 
1092     // Check for arg1_cnt != arg2_cnt
1093     Node* cmp = _gvn.transform(new CmpINode(arg1_cnt, arg2_cnt));
1094     Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::ne));
1095     Node* if_ne = generate_slow_guard(bol, nullptr);
1096     if (if_ne != nullptr) {
1097       phi->init_req(2, intcon(0));
1098       region->init_req(2, if_ne);
1099     }
1100 
1101     // Check for count == 0 is done by assembler code for StrEquals.
1102 
1103     if (!stopped()) {
1104       Node* equals = make_string_method_node(Op_StrEquals, arg1_start, arg1_cnt, arg2_start, arg2_cnt, ae);
1105       phi->init_req(1, equals);
1106       region->init_req(1, control());
1107     }
1108   }
1109 
1110   // post merge
1111   set_control(_gvn.transform(region));
1112   record_for_igvn(region);
1113 
1114   set_result(_gvn.transform(phi));
1115   return true;
1116 }
1117 
1118 //------------------------------inline_array_equals----------------------------
1119 bool LibraryCallKit::inline_array_equals(StrIntrinsicNode::ArgEnc ae) {
1120   assert(ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::LL, "unsupported array types");
1121   Node* arg1 = argument(0);
1122   Node* arg2 = argument(1);
1123 
1124   const TypeAryPtr* mtype = (ae == StrIntrinsicNode::UU) ? TypeAryPtr::CHARS : TypeAryPtr::BYTES;
1125   set_result(_gvn.transform(new AryEqNode(control(), memory(mtype), arg1, arg2, ae)));
1126   clear_upper_avx();
1127 
1128   return true;
1129 }
1130 
1131 
1132 //------------------------------inline_countPositives------------------------------
1133 // int java.lang.StringCoding#countPositives0(byte[] ba, int off, int len)
1134 bool LibraryCallKit::inline_countPositives() {
1135   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1136     return false;
1137   }
1138 
1139   assert(callee()->signature()->size() == 3, "countPositives has 3 parameters");
1140   // no receiver since it is static method
1141   Node* ba         = argument(0);
1142   Node* offset     = argument(1);
1143   Node* len        = argument(2);
1144 
1145   if (VerifyIntrinsicChecks) {
1146     ba = must_be_not_null(ba, true);
1147     generate_string_range_check(ba, offset, len, false, true);
1148     if (stopped()) {
1149       return true;
1150     }
1151   }
1152 
1153   Node* ba_start = array_element_address(ba, offset, T_BYTE);
1154   Node* result = new CountPositivesNode(control(), memory(TypeAryPtr::BYTES), ba_start, len);
1155   set_result(_gvn.transform(result));
1156   clear_upper_avx();
1157   return true;
1158 }
1159 
1160 bool LibraryCallKit::inline_preconditions_checkIndex(BasicType bt) {
1161   Node* index = argument(0);
1162   Node* length = bt == T_INT ? argument(1) : argument(2);
1163   if (too_many_traps(Deoptimization::Reason_intrinsic) || too_many_traps(Deoptimization::Reason_range_check)) {
1164     return false;
1165   }
1166 
1167   // check that length is positive
1168   Node* len_pos_cmp = _gvn.transform(CmpNode::make(length, integercon(0, bt), bt));
1169   Node* len_pos_bol = _gvn.transform(new BoolNode(len_pos_cmp, BoolTest::ge));
1170 
1171   {
1172     BuildCutout unless(this, len_pos_bol, PROB_MAX);
1173     uncommon_trap(Deoptimization::Reason_intrinsic,
1174                   Deoptimization::Action_make_not_entrant);
1175   }
1176 
1177   if (stopped()) {
1178     // Length is known to be always negative during compilation and the IR graph so far constructed is good so return success
1179     return true;
1180   }
1181 
1182   // length is now known positive, add a cast node to make this explicit
1183   jlong upper_bound = _gvn.type(length)->is_integer(bt)->hi_as_long();
1184   Node* casted_length = ConstraintCastNode::make_cast_for_basic_type(
1185       control(), length, TypeInteger::make(0, upper_bound, Type::WidenMax, bt),
1186       ConstraintCastNode::DependencyType::FloatingNarrowing, bt);
1187   casted_length = _gvn.transform(casted_length);
1188   replace_in_map(length, casted_length);
1189   length = casted_length;
1190 
1191   // Use an unsigned comparison for the range check itself
1192   Node* rc_cmp = _gvn.transform(CmpNode::make(index, length, bt, true));
1193   BoolTest::mask btest = BoolTest::lt;
1194   Node* rc_bool = _gvn.transform(new BoolNode(rc_cmp, btest));
1195   RangeCheckNode* rc = new RangeCheckNode(control(), rc_bool, PROB_MAX, COUNT_UNKNOWN);
1196   _gvn.set_type(rc, rc->Value(&_gvn));
1197   if (!rc_bool->is_Con()) {
1198     record_for_igvn(rc);
1199   }
1200   set_control(_gvn.transform(new IfTrueNode(rc)));
1201   {
1202     PreserveJVMState pjvms(this);
1203     set_control(_gvn.transform(new IfFalseNode(rc)));
1204     uncommon_trap(Deoptimization::Reason_range_check,
1205                   Deoptimization::Action_make_not_entrant);
1206   }
1207 
1208   if (stopped()) {
1209     // Range check is known to always fail during compilation and the IR graph so far constructed is good so return success
1210     return true;
1211   }
1212 
1213   // index is now known to be >= 0 and < length, cast it
1214   Node* result = ConstraintCastNode::make_cast_for_basic_type(
1215       control(), index, TypeInteger::make(0, upper_bound, Type::WidenMax, bt),
1216       ConstraintCastNode::DependencyType::FloatingNarrowing, bt);
1217   result = _gvn.transform(result);
1218   set_result(result);
1219   replace_in_map(index, result);
1220   return true;
1221 }
1222 
1223 //------------------------------inline_string_indexOf------------------------
1224 bool LibraryCallKit::inline_string_indexOf(StrIntrinsicNode::ArgEnc ae) {
1225   if (!Matcher::match_rule_supported(Op_StrIndexOf)) {
1226     return false;
1227   }
1228   Node* src = argument(0);
1229   Node* tgt = argument(1);
1230 
1231   // Make the merge point
1232   RegionNode* result_rgn = new RegionNode(4);
1233   Node*       result_phi = new PhiNode(result_rgn, TypeInt::INT);
1234 
1235   src = must_be_not_null(src, true);
1236   tgt = must_be_not_null(tgt, true);
1237 
1238   // Get start addr and length of source string
1239   Node* src_start = array_element_address(src, intcon(0), T_BYTE);
1240   Node* src_count = load_array_length(src);
1241 
1242   // Get start addr and length of substring
1243   Node* tgt_start = array_element_address(tgt, intcon(0), T_BYTE);
1244   Node* tgt_count = load_array_length(tgt);
1245 
1246   Node* result = nullptr;
1247   bool call_opt_stub = (StubRoutines::_string_indexof_array[ae] != nullptr);
1248 
1249   if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
1250     // Divide src size by 2 if String is UTF16 encoded
1251     src_count = _gvn.transform(new RShiftINode(src_count, intcon(1)));
1252   }
1253   if (ae == StrIntrinsicNode::UU) {
1254     // Divide substring size by 2 if String is UTF16 encoded
1255     tgt_count = _gvn.transform(new RShiftINode(tgt_count, intcon(1)));
1256   }
1257 
1258   if (call_opt_stub) {
1259     Node* call = make_runtime_call(RC_LEAF, OptoRuntime::string_IndexOf_Type(),
1260                                    StubRoutines::_string_indexof_array[ae],
1261                                    "stringIndexOf", TypePtr::BOTTOM, src_start,
1262                                    src_count, tgt_start, tgt_count);
1263     result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
1264   } else {
1265     result = make_indexOf_node(src_start, src_count, tgt_start, tgt_count,
1266                                result_rgn, result_phi, ae);
1267   }
1268   if (result != nullptr) {
1269     result_phi->init_req(3, result);
1270     result_rgn->init_req(3, control());
1271   }
1272   set_control(_gvn.transform(result_rgn));
1273   record_for_igvn(result_rgn);
1274   set_result(_gvn.transform(result_phi));
1275 
1276   return true;
1277 }
1278 
1279 //-----------------------------inline_string_indexOfI-----------------------
1280 bool LibraryCallKit::inline_string_indexOfI(StrIntrinsicNode::ArgEnc ae) {
1281   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1282     return false;
1283   }
1284   if (!Matcher::match_rule_supported(Op_StrIndexOf)) {
1285     return false;
1286   }
1287 
1288   assert(callee()->signature()->size() == 5, "String.indexOf() has 5 arguments");
1289   Node* src         = argument(0); // byte[]
1290   Node* src_count   = argument(1); // char count
1291   Node* tgt         = argument(2); // byte[]
1292   Node* tgt_count   = argument(3); // char count
1293   Node* from_index  = argument(4); // char index
1294 
1295   src = must_be_not_null(src, true);
1296   tgt = must_be_not_null(tgt, true);
1297 
1298   // Multiply byte array index by 2 if String is UTF16 encoded
1299   Node* src_offset = (ae == StrIntrinsicNode::LL) ? from_index : _gvn.transform(new LShiftINode(from_index, intcon(1)));
1300   src_count = _gvn.transform(new SubINode(src_count, from_index));
1301   Node* src_start = array_element_address(src, src_offset, T_BYTE);
1302   Node* tgt_start = array_element_address(tgt, intcon(0), T_BYTE);
1303 
1304   // Range checks
1305   generate_string_range_check(src, src_offset, src_count, ae != StrIntrinsicNode::LL);
1306   generate_string_range_check(tgt, intcon(0), tgt_count, ae == StrIntrinsicNode::UU);
1307   if (stopped()) {
1308     return true;
1309   }
1310 
1311   RegionNode* region = new RegionNode(5);
1312   Node* phi = new PhiNode(region, TypeInt::INT);
1313   Node* result = nullptr;
1314 
1315   bool call_opt_stub = (StubRoutines::_string_indexof_array[ae] != nullptr);
1316 
1317   if (call_opt_stub) {
1318     Node* call = make_runtime_call(RC_LEAF, OptoRuntime::string_IndexOf_Type(),
1319                                    StubRoutines::_string_indexof_array[ae],
1320                                    "stringIndexOf", TypePtr::BOTTOM, src_start,
1321                                    src_count, tgt_start, tgt_count);
1322     result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
1323   } else {
1324     result = make_indexOf_node(src_start, src_count, tgt_start, tgt_count,
1325                                region, phi, ae);
1326   }
1327   if (result != nullptr) {
1328     // The result is index relative to from_index if substring was found, -1 otherwise.
1329     // Generate code which will fold into cmove.
1330     Node* cmp = _gvn.transform(new CmpINode(result, intcon(0)));
1331     Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::lt));
1332 
1333     Node* if_lt = generate_slow_guard(bol, nullptr);
1334     if (if_lt != nullptr) {
1335       // result == -1
1336       phi->init_req(3, result);
1337       region->init_req(3, if_lt);
1338     }
1339     if (!stopped()) {
1340       result = _gvn.transform(new AddINode(result, from_index));
1341       phi->init_req(4, result);
1342       region->init_req(4, control());
1343     }
1344   }
1345 
1346   set_control(_gvn.transform(region));
1347   record_for_igvn(region);
1348   set_result(_gvn.transform(phi));
1349   clear_upper_avx();
1350 
1351   return true;
1352 }
1353 
1354 // Create StrIndexOfNode with fast path checks
1355 Node* LibraryCallKit::make_indexOf_node(Node* src_start, Node* src_count, Node* tgt_start, Node* tgt_count,
1356                                         RegionNode* region, Node* phi, StrIntrinsicNode::ArgEnc ae) {
1357   // Check for substr count > string count
1358   Node* cmp = _gvn.transform(new CmpINode(tgt_count, src_count));
1359   Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::gt));
1360   Node* if_gt = generate_slow_guard(bol, nullptr);
1361   if (if_gt != nullptr) {
1362     phi->init_req(1, intcon(-1));
1363     region->init_req(1, if_gt);
1364   }
1365   if (!stopped()) {
1366     // Check for substr count == 0
1367     cmp = _gvn.transform(new CmpINode(tgt_count, intcon(0)));
1368     bol = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
1369     Node* if_zero = generate_slow_guard(bol, nullptr);
1370     if (if_zero != nullptr) {
1371       phi->init_req(2, intcon(0));
1372       region->init_req(2, if_zero);
1373     }
1374   }
1375   if (!stopped()) {
1376     return make_string_method_node(Op_StrIndexOf, src_start, src_count, tgt_start, tgt_count, ae);
1377   }
1378   return nullptr;
1379 }
1380 
1381 //-----------------------------inline_string_indexOfChar-----------------------
1382 bool LibraryCallKit::inline_string_indexOfChar(StrIntrinsicNode::ArgEnc ae) {
1383   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1384     return false;
1385   }
1386   if (!Matcher::match_rule_supported(Op_StrIndexOfChar)) {
1387     return false;
1388   }
1389   assert(callee()->signature()->size() == 4, "String.indexOfChar() has 4 arguments");
1390   Node* src         = argument(0); // byte[]
1391   Node* int_ch      = argument(1);
1392   Node* from_index  = argument(2);
1393   Node* max         = argument(3);
1394 
1395   src = must_be_not_null(src, true);
1396 
1397   Node* src_offset = ae == StrIntrinsicNode::L ? from_index : _gvn.transform(new LShiftINode(from_index, intcon(1)));
1398   Node* src_start = array_element_address(src, src_offset, T_BYTE);
1399   Node* src_count = _gvn.transform(new SubINode(max, from_index));
1400 
1401   // Range checks
1402   generate_string_range_check(src, src_offset, src_count, ae == StrIntrinsicNode::U);
1403 
1404   // Check for int_ch >= 0
1405   Node* int_ch_cmp = _gvn.transform(new CmpINode(int_ch, intcon(0)));
1406   Node* int_ch_bol = _gvn.transform(new BoolNode(int_ch_cmp, BoolTest::ge));
1407   {
1408     BuildCutout unless(this, int_ch_bol, PROB_MAX);
1409     uncommon_trap(Deoptimization::Reason_intrinsic,
1410                   Deoptimization::Action_maybe_recompile);
1411   }
1412   if (stopped()) {
1413     return true;
1414   }
1415 
1416   RegionNode* region = new RegionNode(3);
1417   Node* phi = new PhiNode(region, TypeInt::INT);
1418 
1419   Node* result = new StrIndexOfCharNode(control(), memory(TypeAryPtr::BYTES), src_start, src_count, int_ch, ae);
1420   C->set_has_split_ifs(true); // Has chance for split-if optimization
1421   _gvn.transform(result);
1422 
1423   Node* cmp = _gvn.transform(new CmpINode(result, intcon(0)));
1424   Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::lt));
1425 
1426   Node* if_lt = generate_slow_guard(bol, nullptr);
1427   if (if_lt != nullptr) {
1428     // result == -1
1429     phi->init_req(2, result);
1430     region->init_req(2, if_lt);
1431   }
1432   if (!stopped()) {
1433     result = _gvn.transform(new AddINode(result, from_index));
1434     phi->init_req(1, result);
1435     region->init_req(1, control());
1436   }
1437   set_control(_gvn.transform(region));
1438   record_for_igvn(region);
1439   set_result(_gvn.transform(phi));
1440   clear_upper_avx();
1441 
1442   return true;
1443 }
1444 //---------------------------inline_string_copy---------------------
1445 // compressIt == true --> generate a compressed copy operation (compress char[]/byte[] to byte[])
1446 //   int StringUTF16.compress(char[] src, int srcOff, byte[] dst, int dstOff, int len)
1447 //   int StringUTF16.compress(byte[] src, int srcOff, byte[] dst, int dstOff, int len)
1448 // compressIt == false --> generate an inflated copy operation (inflate byte[] to char[]/byte[])
1449 //   void StringLatin1.inflate(byte[] src, int srcOff, char[] dst, int dstOff, int len)
1450 //   void StringLatin1.inflate(byte[] src, int srcOff, byte[] dst, int dstOff, int len)
1451 bool LibraryCallKit::inline_string_copy(bool compress) {
1452   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1453     return false;
1454   }
1455   int nargs = 5;  // 2 oops, 3 ints
1456   assert(callee()->signature()->size() == nargs, "string copy has 5 arguments");
1457 
1458   Node* src         = argument(0);
1459   Node* src_offset  = argument(1);
1460   Node* dst         = argument(2);
1461   Node* dst_offset  = argument(3);
1462   Node* length      = argument(4);
1463 
1464   // Check for allocation before we add nodes that would confuse
1465   // tightly_coupled_allocation()
1466   AllocateArrayNode* alloc = tightly_coupled_allocation(dst);
1467 
1468   // Figure out the size and type of the elements we will be copying.
1469   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
1470   const TypeAryPtr* dst_type = dst->Value(&_gvn)->isa_aryptr();
1471   if (src_type == nullptr || dst_type == nullptr) {
1472     return false;
1473   }
1474   BasicType src_elem = src_type->elem()->array_element_basic_type();
1475   BasicType dst_elem = dst_type->elem()->array_element_basic_type();
1476   assert((compress && dst_elem == T_BYTE && (src_elem == T_BYTE || src_elem == T_CHAR)) ||
1477          (!compress && src_elem == T_BYTE && (dst_elem == T_BYTE || dst_elem == T_CHAR)),
1478          "Unsupported array types for inline_string_copy");
1479 
1480   src = must_be_not_null(src, true);
1481   dst = must_be_not_null(dst, true);
1482 
1483   // Convert char[] offsets to byte[] offsets
1484   bool convert_src = (compress && src_elem == T_BYTE);
1485   bool convert_dst = (!compress && dst_elem == T_BYTE);
1486   if (convert_src) {
1487     src_offset = _gvn.transform(new LShiftINode(src_offset, intcon(1)));
1488   } else if (convert_dst) {
1489     dst_offset = _gvn.transform(new LShiftINode(dst_offset, intcon(1)));
1490   }
1491 
1492   // Range checks
1493   generate_string_range_check(src, src_offset, length, convert_src);
1494   generate_string_range_check(dst, dst_offset, length, convert_dst);
1495   if (stopped()) {
1496     return true;
1497   }
1498 
1499   Node* src_start = array_element_address(src, src_offset, src_elem);
1500   Node* dst_start = array_element_address(dst, dst_offset, dst_elem);
1501   // 'src_start' points to src array + scaled offset
1502   // 'dst_start' points to dst array + scaled offset
1503   Node* count = nullptr;
1504   if (compress) {
1505     count = compress_string(src_start, TypeAryPtr::get_array_body_type(src_elem), dst_start, length);
1506   } else {
1507     inflate_string(src_start, dst_start, TypeAryPtr::get_array_body_type(dst_elem), length);
1508   }
1509 
1510   if (alloc != nullptr) {
1511     if (alloc->maybe_set_complete(&_gvn)) {
1512       // "You break it, you buy it."
1513       InitializeNode* init = alloc->initialization();
1514       assert(init->is_complete(), "we just did this");
1515       init->set_complete_with_arraycopy();
1516       assert(dst->is_CheckCastPP(), "sanity");
1517       assert(dst->in(0)->in(0) == init, "dest pinned");
1518     }
1519     // Do not let stores that initialize this object be reordered with
1520     // a subsequent store that would make this object accessible by
1521     // other threads.
1522     // Record what AllocateNode this StoreStore protects so that
1523     // escape analysis can go from the MemBarStoreStoreNode to the
1524     // AllocateNode and eliminate the MemBarStoreStoreNode if possible
1525     // based on the escape status of the AllocateNode.
1526     insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
1527   }
1528   if (compress) {
1529     set_result(_gvn.transform(count));
1530   }
1531   clear_upper_avx();
1532 
1533   return true;
1534 }
1535 
1536 #ifdef _LP64
1537 #define XTOP ,top() /*additional argument*/
1538 #else  //_LP64
1539 #define XTOP        /*no additional argument*/
1540 #endif //_LP64
1541 
1542 //------------------------inline_string_toBytesU--------------------------
1543 // public static byte[] StringUTF16.toBytes(char[] value, int off, int len)
1544 bool LibraryCallKit::inline_string_toBytesU() {
1545   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1546     return false;
1547   }
1548   // Get the arguments.
1549   Node* value     = argument(0);
1550   Node* offset    = argument(1);
1551   Node* length    = argument(2);
1552 
1553   Node* newcopy = nullptr;
1554 
1555   // Set the original stack and the reexecute bit for the interpreter to reexecute
1556   // the bytecode that invokes StringUTF16.toBytes() if deoptimization happens.
1557   { PreserveReexecuteState preexecs(this);
1558     jvms()->set_should_reexecute(true);
1559 
1560     // Check if a null path was taken unconditionally.
1561     value = null_check(value);
1562 
1563     RegionNode* bailout = new RegionNode(1);
1564     record_for_igvn(bailout);
1565 
1566     // Range checks
1567     generate_negative_guard(offset, bailout);
1568     generate_negative_guard(length, bailout);
1569     generate_limit_guard(offset, length, load_array_length(value), bailout);
1570     // Make sure that resulting byte[] length does not overflow Integer.MAX_VALUE
1571     generate_limit_guard(length, intcon(0), intcon(max_jint/2), bailout);
1572 
1573     if (bailout->req() > 1) {
1574       PreserveJVMState pjvms(this);
1575       set_control(_gvn.transform(bailout));
1576       uncommon_trap(Deoptimization::Reason_intrinsic,
1577                     Deoptimization::Action_maybe_recompile);
1578     }
1579     if (stopped()) {
1580       return true;
1581     }
1582 
1583     Node* size = _gvn.transform(new LShiftINode(length, intcon(1)));
1584     Node* klass_node = makecon(TypeKlassPtr::make(ciTypeArrayKlass::make(T_BYTE)));
1585     newcopy = new_array(klass_node, size, 0);  // no arguments to push
1586     AllocateArrayNode* alloc = tightly_coupled_allocation(newcopy);
1587     guarantee(alloc != nullptr, "created above");
1588 
1589     // Calculate starting addresses.
1590     Node* src_start = array_element_address(value, offset, T_CHAR);
1591     Node* dst_start = basic_plus_adr(newcopy, arrayOopDesc::base_offset_in_bytes(T_BYTE));
1592 
1593     // Check if dst array address is aligned to HeapWordSize
1594     bool aligned = (arrayOopDesc::base_offset_in_bytes(T_BYTE) % HeapWordSize == 0);
1595     // If true, then check if src array address is aligned to HeapWordSize
1596     if (aligned) {
1597       const TypeInt* toffset = gvn().type(offset)->is_int();
1598       aligned = toffset->is_con() && ((arrayOopDesc::base_offset_in_bytes(T_CHAR) +
1599                                        toffset->get_con() * type2aelembytes(T_CHAR)) % HeapWordSize == 0);
1600     }
1601 
1602     // Figure out which arraycopy runtime method to call (disjoint, uninitialized).
1603     const char* copyfunc_name = "arraycopy";
1604     address     copyfunc_addr = StubRoutines::select_arraycopy_function(T_CHAR, aligned, true, copyfunc_name, true);
1605     Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
1606                       OptoRuntime::fast_arraycopy_Type(),
1607                       copyfunc_addr, copyfunc_name, TypeRawPtr::BOTTOM,
1608                       src_start, dst_start, ConvI2X(length) XTOP);
1609     // Do not let reads from the cloned object float above the arraycopy.
1610     if (alloc->maybe_set_complete(&_gvn)) {
1611       // "You break it, you buy it."
1612       InitializeNode* init = alloc->initialization();
1613       assert(init->is_complete(), "we just did this");
1614       init->set_complete_with_arraycopy();
1615       assert(newcopy->is_CheckCastPP(), "sanity");
1616       assert(newcopy->in(0)->in(0) == init, "dest pinned");
1617     }
1618     // Do not let stores that initialize this object be reordered with
1619     // a subsequent store that would make this object accessible by
1620     // other threads.
1621     // Record what AllocateNode this StoreStore protects so that
1622     // escape analysis can go from the MemBarStoreStoreNode to the
1623     // AllocateNode and eliminate the MemBarStoreStoreNode if possible
1624     // based on the escape status of the AllocateNode.
1625     insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
1626   } // original reexecute is set back here
1627 
1628   C->set_has_split_ifs(true); // Has chance for split-if optimization
1629   if (!stopped()) {
1630     set_result(newcopy);
1631   }
1632   clear_upper_avx();
1633 
1634   return true;
1635 }
1636 
1637 //------------------------inline_string_getCharsU--------------------------
1638 // public void StringUTF16.getChars(byte[] src, int srcBegin, int srcEnd, char dst[], int dstBegin)
1639 bool LibraryCallKit::inline_string_getCharsU() {
1640   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1641     return false;
1642   }
1643 
1644   // Get the arguments.
1645   Node* src       = argument(0);
1646   Node* src_begin = argument(1);
1647   Node* src_end   = argument(2); // exclusive offset (i < src_end)
1648   Node* dst       = argument(3);
1649   Node* dst_begin = argument(4);
1650 
1651   // Check for allocation before we add nodes that would confuse
1652   // tightly_coupled_allocation()
1653   AllocateArrayNode* alloc = tightly_coupled_allocation(dst);
1654 
1655   // Check if a null path was taken unconditionally.
1656   src = null_check(src);
1657   dst = null_check(dst);
1658   if (stopped()) {
1659     return true;
1660   }
1661 
1662   // Get length and convert char[] offset to byte[] offset
1663   Node* length = _gvn.transform(new SubINode(src_end, src_begin));
1664   src_begin = _gvn.transform(new LShiftINode(src_begin, intcon(1)));
1665 
1666   // Range checks
1667   generate_string_range_check(src, src_begin, length, true);
1668   generate_string_range_check(dst, dst_begin, length, false);
1669   if (stopped()) {
1670     return true;
1671   }
1672 
1673   if (!stopped()) {
1674     // Calculate starting addresses.
1675     Node* src_start = array_element_address(src, src_begin, T_BYTE);
1676     Node* dst_start = array_element_address(dst, dst_begin, T_CHAR);
1677 
1678     // Check if array addresses are aligned to HeapWordSize
1679     const TypeInt* tsrc = gvn().type(src_begin)->is_int();
1680     const TypeInt* tdst = gvn().type(dst_begin)->is_int();
1681     bool aligned = tsrc->is_con() && ((arrayOopDesc::base_offset_in_bytes(T_BYTE) + tsrc->get_con() * type2aelembytes(T_BYTE)) % HeapWordSize == 0) &&
1682                    tdst->is_con() && ((arrayOopDesc::base_offset_in_bytes(T_CHAR) + tdst->get_con() * type2aelembytes(T_CHAR)) % HeapWordSize == 0);
1683 
1684     // Figure out which arraycopy runtime method to call (disjoint, uninitialized).
1685     const char* copyfunc_name = "arraycopy";
1686     address     copyfunc_addr = StubRoutines::select_arraycopy_function(T_CHAR, aligned, true, copyfunc_name, true);
1687     Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
1688                       OptoRuntime::fast_arraycopy_Type(),
1689                       copyfunc_addr, copyfunc_name, TypeRawPtr::BOTTOM,
1690                       src_start, dst_start, ConvI2X(length) XTOP);
1691     // Do not let reads from the cloned object float above the arraycopy.
1692     if (alloc != nullptr) {
1693       if (alloc->maybe_set_complete(&_gvn)) {
1694         // "You break it, you buy it."
1695         InitializeNode* init = alloc->initialization();
1696         assert(init->is_complete(), "we just did this");
1697         init->set_complete_with_arraycopy();
1698         assert(dst->is_CheckCastPP(), "sanity");
1699         assert(dst->in(0)->in(0) == init, "dest pinned");
1700       }
1701       // Do not let stores that initialize this object be reordered with
1702       // a subsequent store that would make this object accessible by
1703       // other threads.
1704       // Record what AllocateNode this StoreStore protects so that
1705       // escape analysis can go from the MemBarStoreStoreNode to the
1706       // AllocateNode and eliminate the MemBarStoreStoreNode if possible
1707       // based on the escape status of the AllocateNode.
1708       insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
1709     } else {
1710       insert_mem_bar(Op_MemBarCPUOrder);
1711     }
1712   }
1713 
1714   C->set_has_split_ifs(true); // Has chance for split-if optimization
1715   return true;
1716 }
1717 
1718 //----------------------inline_string_char_access----------------------------
1719 // Store/Load char to/from byte[] array.
1720 // static void StringUTF16.putChar(byte[] val, int index, int c)
1721 // static char StringUTF16.getChar(byte[] val, int index)
1722 bool LibraryCallKit::inline_string_char_access(bool is_store) {
1723   Node* value  = argument(0);
1724   Node* index  = argument(1);
1725   Node* ch = is_store ? argument(2) : nullptr;
1726 
1727   // This intrinsic accesses byte[] array as char[] array. Computing the offsets
1728   // correctly requires matched array shapes.
1729   assert (arrayOopDesc::base_offset_in_bytes(T_CHAR) == arrayOopDesc::base_offset_in_bytes(T_BYTE),
1730           "sanity: byte[] and char[] bases agree");
1731   assert (type2aelembytes(T_CHAR) == type2aelembytes(T_BYTE)*2,
1732           "sanity: byte[] and char[] scales agree");
1733 
1734   // Bail when getChar over constants is requested: constant folding would
1735   // reject folding mismatched char access over byte[]. A normal inlining for getChar
1736   // Java method would constant fold nicely instead.
1737   if (!is_store && value->is_Con() && index->is_Con()) {
1738     return false;
1739   }
1740 
1741   // Save state and restore on bailout
1742   SavedState old_state(this);
1743 
1744   value = must_be_not_null(value, true);
1745 
1746   Node* adr = array_element_address(value, index, T_CHAR);
1747   if (adr->is_top()) {
1748     return false;
1749   }
1750   old_state.discard();
1751   if (is_store) {
1752     access_store_at(value, adr, TypeAryPtr::BYTES, ch, TypeInt::CHAR, T_CHAR, IN_HEAP | MO_UNORDERED | C2_MISMATCHED);
1753   } else {
1754     ch = access_load_at(value, adr, TypeAryPtr::BYTES, TypeInt::CHAR, T_CHAR, IN_HEAP | MO_UNORDERED | C2_MISMATCHED | C2_CONTROL_DEPENDENT_LOAD | C2_UNKNOWN_CONTROL_LOAD);
1755     set_result(ch);
1756   }
1757   return true;
1758 }
1759 
1760 
1761 //------------------------------inline_math-----------------------------------
1762 // public static double Math.abs(double)
1763 // public static double Math.sqrt(double)
1764 // public static double Math.log(double)
1765 // public static double Math.log10(double)
1766 // public static double Math.round(double)
1767 bool LibraryCallKit::inline_double_math(vmIntrinsics::ID id) {
1768   Node* arg = argument(0);
1769   Node* n = nullptr;
1770   switch (id) {
1771   case vmIntrinsics::_dabs:   n = new AbsDNode(                arg);  break;
1772   case vmIntrinsics::_dsqrt:
1773   case vmIntrinsics::_dsqrt_strict:
1774                               n = new SqrtDNode(C, control(),  arg);  break;
1775   case vmIntrinsics::_ceil:   n = RoundDoubleModeNode::make(_gvn, arg, RoundDoubleModeNode::rmode_ceil); break;
1776   case vmIntrinsics::_floor:  n = RoundDoubleModeNode::make(_gvn, arg, RoundDoubleModeNode::rmode_floor); break;
1777   case vmIntrinsics::_rint:   n = RoundDoubleModeNode::make(_gvn, arg, RoundDoubleModeNode::rmode_rint); break;
1778   case vmIntrinsics::_roundD: n = new RoundDNode(arg); break;
1779   case vmIntrinsics::_dcopySign: n = CopySignDNode::make(_gvn, arg, argument(2)); break;
1780   case vmIntrinsics::_dsignum: n = SignumDNode::make(_gvn, arg); break;
1781   default:  fatal_unexpected_iid(id);  break;
1782   }
1783   set_result(_gvn.transform(n));
1784   return true;
1785 }
1786 
1787 //------------------------------inline_math-----------------------------------
1788 // public static float Math.abs(float)
1789 // public static int Math.abs(int)
1790 // public static long Math.abs(long)
1791 bool LibraryCallKit::inline_math(vmIntrinsics::ID id) {
1792   Node* arg = argument(0);
1793   Node* n = nullptr;
1794   switch (id) {
1795   case vmIntrinsics::_fabs:   n = new AbsFNode(                arg);  break;
1796   case vmIntrinsics::_iabs:   n = new AbsINode(                arg);  break;
1797   case vmIntrinsics::_labs:   n = new AbsLNode(                arg);  break;
1798   case vmIntrinsics::_fcopySign: n = new CopySignFNode(arg, argument(1)); break;
1799   case vmIntrinsics::_fsignum: n = SignumFNode::make(_gvn, arg); break;
1800   case vmIntrinsics::_roundF: n = new RoundFNode(arg); break;
1801   default:  fatal_unexpected_iid(id);  break;
1802   }
1803   set_result(_gvn.transform(n));
1804   return true;
1805 }
1806 
1807 //------------------------------runtime_math-----------------------------
1808 bool LibraryCallKit::runtime_math(const TypeFunc* call_type, address funcAddr, const char* funcName) {
1809   assert(call_type == OptoRuntime::Math_DD_D_Type() || call_type == OptoRuntime::Math_D_D_Type(),
1810          "must be (DD)D or (D)D type");
1811 
1812   // Inputs
1813   Node* a = argument(0);
1814   Node* b = (call_type == OptoRuntime::Math_DD_D_Type()) ? argument(2) : nullptr;
1815 
1816   const TypePtr* no_memory_effects = nullptr;
1817   Node* trig = make_runtime_call(RC_LEAF | RC_PURE, call_type, funcAddr, funcName,
1818                                  no_memory_effects,
1819                                  a, top(), b, b ? top() : nullptr);
1820   Node* value = _gvn.transform(new ProjNode(trig, TypeFunc::Parms+0));
1821 #ifdef ASSERT
1822   Node* value_top = _gvn.transform(new ProjNode(trig, TypeFunc::Parms+1));
1823   assert(value_top == top(), "second value must be top");
1824 #endif
1825 
1826   set_result(value);
1827   return true;
1828 }
1829 
1830 //------------------------------inline_math_pow-----------------------------
1831 bool LibraryCallKit::inline_math_pow() {
1832   Node* exp = argument(2);
1833   const TypeD* d = _gvn.type(exp)->isa_double_constant();
1834   if (d != nullptr) {
1835     if (d->getd() == 2.0) {
1836       // Special case: pow(x, 2.0) => x * x
1837       Node* base = argument(0);
1838       set_result(_gvn.transform(new MulDNode(base, base)));
1839       return true;
1840     } else if (d->getd() == 0.5 && Matcher::match_rule_supported(Op_SqrtD)) {
1841       // Special case: pow(x, 0.5) => sqrt(x)
1842       Node* base = argument(0);
1843       Node* zero = _gvn.zerocon(T_DOUBLE);
1844 
1845       RegionNode* region = new RegionNode(3);
1846       Node* phi = new PhiNode(region, Type::DOUBLE);
1847 
1848       Node* cmp  = _gvn.transform(new CmpDNode(base, zero));
1849       // According to the API specs, pow(-0.0, 0.5) = 0.0 and sqrt(-0.0) = -0.0.
1850       // So pow(-0.0, 0.5) shouldn't be replaced with sqrt(-0.0).
1851       // -0.0/+0.0 are both excluded since floating-point comparison doesn't distinguish -0.0 from +0.0.
1852       Node* test = _gvn.transform(new BoolNode(cmp, BoolTest::le));
1853 
1854       Node* if_pow = generate_slow_guard(test, nullptr);
1855       Node* value_sqrt = _gvn.transform(new SqrtDNode(C, control(), base));
1856       phi->init_req(1, value_sqrt);
1857       region->init_req(1, control());
1858 
1859       if (if_pow != nullptr) {
1860         set_control(if_pow);
1861         address target = StubRoutines::dpow() != nullptr ? StubRoutines::dpow() :
1862                                                         CAST_FROM_FN_PTR(address, SharedRuntime::dpow);
1863         const TypePtr* no_memory_effects = nullptr;
1864         Node* trig = make_runtime_call(RC_LEAF, OptoRuntime::Math_DD_D_Type(), target, "POW",
1865                                        no_memory_effects, base, top(), exp, top());
1866         Node* value_pow = _gvn.transform(new ProjNode(trig, TypeFunc::Parms+0));
1867 #ifdef ASSERT
1868         Node* value_top = _gvn.transform(new ProjNode(trig, TypeFunc::Parms+1));
1869         assert(value_top == top(), "second value must be top");
1870 #endif
1871         phi->init_req(2, value_pow);
1872         region->init_req(2, _gvn.transform(new ProjNode(trig, TypeFunc::Control)));
1873       }
1874 
1875       C->set_has_split_ifs(true); // Has chance for split-if optimization
1876       set_control(_gvn.transform(region));
1877       record_for_igvn(region);
1878       set_result(_gvn.transform(phi));
1879 
1880       return true;
1881     }
1882   }
1883 
1884   return StubRoutines::dpow() != nullptr ?
1885     runtime_math(OptoRuntime::Math_DD_D_Type(), StubRoutines::dpow(),  "dpow") :
1886     runtime_math(OptoRuntime::Math_DD_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dpow),  "POW");
1887 }
1888 
1889 //------------------------------inline_math_native-----------------------------
1890 bool LibraryCallKit::inline_math_native(vmIntrinsics::ID id) {
1891   switch (id) {
1892   case vmIntrinsics::_dsin:
1893     return StubRoutines::dsin() != nullptr ?
1894       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dsin(), "dsin") :
1895       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dsin),   "SIN");
1896   case vmIntrinsics::_dcos:
1897     return StubRoutines::dcos() != nullptr ?
1898       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dcos(), "dcos") :
1899       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dcos),   "COS");
1900   case vmIntrinsics::_dtan:
1901     return StubRoutines::dtan() != nullptr ?
1902       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dtan(), "dtan") :
1903       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dtan), "TAN");
1904   case vmIntrinsics::_dsinh:
1905     return StubRoutines::dsinh() != nullptr ?
1906       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dsinh(), "dsinh") : false;
1907   case vmIntrinsics::_dtanh:
1908     return StubRoutines::dtanh() != nullptr ?
1909       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dtanh(), "dtanh") : false;
1910   case vmIntrinsics::_dcbrt:
1911     return StubRoutines::dcbrt() != nullptr ?
1912       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dcbrt(), "dcbrt") : false;
1913   case vmIntrinsics::_dexp:
1914     return StubRoutines::dexp() != nullptr ?
1915       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dexp(),  "dexp") :
1916       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dexp),  "EXP");
1917   case vmIntrinsics::_dlog:
1918     return StubRoutines::dlog() != nullptr ?
1919       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dlog(), "dlog") :
1920       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dlog),   "LOG");
1921   case vmIntrinsics::_dlog10:
1922     return StubRoutines::dlog10() != nullptr ?
1923       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dlog10(), "dlog10") :
1924       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dlog10), "LOG10");
1925 
1926   case vmIntrinsics::_roundD: return Matcher::match_rule_supported(Op_RoundD) ? inline_double_math(id) : false;
1927   case vmIntrinsics::_ceil:
1928   case vmIntrinsics::_floor:
1929   case vmIntrinsics::_rint:   return Matcher::match_rule_supported(Op_RoundDoubleMode) ? inline_double_math(id) : false;
1930 
1931   case vmIntrinsics::_dsqrt:
1932   case vmIntrinsics::_dsqrt_strict:
1933                               return Matcher::match_rule_supported(Op_SqrtD) ? inline_double_math(id) : false;
1934   case vmIntrinsics::_dabs:   return Matcher::has_match_rule(Op_AbsD)   ? inline_double_math(id) : false;
1935   case vmIntrinsics::_fabs:   return Matcher::match_rule_supported(Op_AbsF)   ? inline_math(id) : false;
1936   case vmIntrinsics::_iabs:   return Matcher::match_rule_supported(Op_AbsI)   ? inline_math(id) : false;
1937   case vmIntrinsics::_labs:   return Matcher::match_rule_supported(Op_AbsL)   ? inline_math(id) : false;
1938 
1939   case vmIntrinsics::_dpow:      return inline_math_pow();
1940   case vmIntrinsics::_dcopySign: return inline_double_math(id);
1941   case vmIntrinsics::_fcopySign: return inline_math(id);
1942   case vmIntrinsics::_dsignum: return Matcher::match_rule_supported(Op_SignumD) ? inline_double_math(id) : false;
1943   case vmIntrinsics::_fsignum: return Matcher::match_rule_supported(Op_SignumF) ? inline_math(id) : false;
1944   case vmIntrinsics::_roundF: return Matcher::match_rule_supported(Op_RoundF) ? inline_math(id) : false;
1945 
1946    // These intrinsics are not yet correctly implemented
1947   case vmIntrinsics::_datan2:
1948     return false;
1949 
1950   default:
1951     fatal_unexpected_iid(id);
1952     return false;
1953   }
1954 }
1955 
1956 //----------------------------inline_notify-----------------------------------*
1957 bool LibraryCallKit::inline_notify(vmIntrinsics::ID id) {
1958   const TypeFunc* ftype = OptoRuntime::monitor_notify_Type();
1959   address func;
1960   if (id == vmIntrinsics::_notify) {
1961     func = OptoRuntime::monitor_notify_Java();
1962   } else {
1963     func = OptoRuntime::monitor_notifyAll_Java();
1964   }
1965   Node* call = make_runtime_call(RC_NO_LEAF, ftype, func, nullptr, TypeRawPtr::BOTTOM, argument(0));
1966   make_slow_call_ex(call, env()->Throwable_klass(), false);
1967   return true;
1968 }
1969 
1970 
1971 //----------------------------inline_min_max-----------------------------------
1972 bool LibraryCallKit::inline_min_max(vmIntrinsics::ID id) {
1973   Node* a = nullptr;
1974   Node* b = nullptr;
1975   Node* n = nullptr;
1976   switch (id) {
1977     case vmIntrinsics::_min:
1978     case vmIntrinsics::_max:
1979     case vmIntrinsics::_minF:
1980     case vmIntrinsics::_maxF:
1981     case vmIntrinsics::_minF_strict:
1982     case vmIntrinsics::_maxF_strict:
1983     case vmIntrinsics::_min_strict:
1984     case vmIntrinsics::_max_strict:
1985       assert(callee()->signature()->size() == 2, "minF/maxF has 2 parameters of size 1 each.");
1986       a = argument(0);
1987       b = argument(1);
1988       break;
1989     case vmIntrinsics::_minD:
1990     case vmIntrinsics::_maxD:
1991     case vmIntrinsics::_minD_strict:
1992     case vmIntrinsics::_maxD_strict:
1993       assert(callee()->signature()->size() == 4, "minD/maxD has 2 parameters of size 2 each.");
1994       a = argument(0);
1995       b = argument(2);
1996       break;
1997     case vmIntrinsics::_minL:
1998     case vmIntrinsics::_maxL:
1999       assert(callee()->signature()->size() == 4, "minL/maxL has 2 parameters of size 2 each.");
2000       a = argument(0);
2001       b = argument(2);
2002       break;
2003     default:
2004       fatal_unexpected_iid(id);
2005       break;
2006   }
2007 
2008   switch (id) {
2009     case vmIntrinsics::_min:
2010     case vmIntrinsics::_min_strict:
2011       n = new MinINode(a, b);
2012       break;
2013     case vmIntrinsics::_max:
2014     case vmIntrinsics::_max_strict:
2015       n = new MaxINode(a, b);
2016       break;
2017     case vmIntrinsics::_minF:
2018     case vmIntrinsics::_minF_strict:
2019       n = new MinFNode(a, b);
2020       break;
2021     case vmIntrinsics::_maxF:
2022     case vmIntrinsics::_maxF_strict:
2023       n = new MaxFNode(a, b);
2024       break;
2025     case vmIntrinsics::_minD:
2026     case vmIntrinsics::_minD_strict:
2027       n = new MinDNode(a, b);
2028       break;
2029     case vmIntrinsics::_maxD:
2030     case vmIntrinsics::_maxD_strict:
2031       n = new MaxDNode(a, b);
2032       break;
2033     case vmIntrinsics::_minL:
2034       n = new MinLNode(_gvn.C, a, b);
2035       break;
2036     case vmIntrinsics::_maxL:
2037       n = new MaxLNode(_gvn.C, a, b);
2038       break;
2039     default:
2040       fatal_unexpected_iid(id);
2041       break;
2042   }
2043 
2044   set_result(_gvn.transform(n));
2045   return true;
2046 }
2047 
2048 bool LibraryCallKit::inline_math_mathExact(Node* math, Node* test) {
2049   if (builtin_throw_too_many_traps(Deoptimization::Reason_intrinsic,
2050                                    env()->ArithmeticException_instance())) {
2051     // It has been already too many times, but we cannot use builtin_throw (e.g. we care about backtraces),
2052     // so let's bail out intrinsic rather than risking deopting again.
2053     return false;
2054   }
2055 
2056   Node* bol = _gvn.transform( new BoolNode(test, BoolTest::overflow) );
2057   IfNode* check = create_and_map_if(control(), bol, PROB_UNLIKELY_MAG(3), COUNT_UNKNOWN);
2058   Node* fast_path = _gvn.transform( new IfFalseNode(check));
2059   Node* slow_path = _gvn.transform( new IfTrueNode(check) );
2060 
2061   {
2062     PreserveJVMState pjvms(this);
2063     PreserveReexecuteState preexecs(this);
2064     jvms()->set_should_reexecute(true);
2065 
2066     set_control(slow_path);
2067     set_i_o(i_o());
2068 
2069     builtin_throw(Deoptimization::Reason_intrinsic,
2070                   env()->ArithmeticException_instance(),
2071                   /*allow_too_many_traps*/ false);
2072   }
2073 
2074   set_control(fast_path);
2075   set_result(math);
2076   return true;
2077 }
2078 
2079 template <typename OverflowOp>
2080 bool LibraryCallKit::inline_math_overflow(Node* arg1, Node* arg2) {
2081   typedef typename OverflowOp::MathOp MathOp;
2082 
2083   MathOp* mathOp = new MathOp(arg1, arg2);
2084   Node* operation = _gvn.transform( mathOp );
2085   Node* ofcheck = _gvn.transform( new OverflowOp(arg1, arg2) );
2086   return inline_math_mathExact(operation, ofcheck);
2087 }
2088 
2089 bool LibraryCallKit::inline_math_addExactI(bool is_increment) {
2090   return inline_math_overflow<OverflowAddINode>(argument(0), is_increment ? intcon(1) : argument(1));
2091 }
2092 
2093 bool LibraryCallKit::inline_math_addExactL(bool is_increment) {
2094   return inline_math_overflow<OverflowAddLNode>(argument(0), is_increment ? longcon(1) : argument(2));
2095 }
2096 
2097 bool LibraryCallKit::inline_math_subtractExactI(bool is_decrement) {
2098   return inline_math_overflow<OverflowSubINode>(argument(0), is_decrement ? intcon(1) : argument(1));
2099 }
2100 
2101 bool LibraryCallKit::inline_math_subtractExactL(bool is_decrement) {
2102   return inline_math_overflow<OverflowSubLNode>(argument(0), is_decrement ? longcon(1) : argument(2));
2103 }
2104 
2105 bool LibraryCallKit::inline_math_negateExactI() {
2106   return inline_math_overflow<OverflowSubINode>(intcon(0), argument(0));
2107 }
2108 
2109 bool LibraryCallKit::inline_math_negateExactL() {
2110   return inline_math_overflow<OverflowSubLNode>(longcon(0), argument(0));
2111 }
2112 
2113 bool LibraryCallKit::inline_math_multiplyExactI() {
2114   return inline_math_overflow<OverflowMulINode>(argument(0), argument(1));
2115 }
2116 
2117 bool LibraryCallKit::inline_math_multiplyExactL() {
2118   return inline_math_overflow<OverflowMulLNode>(argument(0), argument(2));
2119 }
2120 
2121 bool LibraryCallKit::inline_math_multiplyHigh() {
2122   set_result(_gvn.transform(new MulHiLNode(argument(0), argument(2))));
2123   return true;
2124 }
2125 
2126 bool LibraryCallKit::inline_math_unsignedMultiplyHigh() {
2127   set_result(_gvn.transform(new UMulHiLNode(argument(0), argument(2))));
2128   return true;
2129 }
2130 
2131 inline int
2132 LibraryCallKit::classify_unsafe_addr(Node* &base, Node* &offset, BasicType type) {
2133   const TypePtr* base_type = TypePtr::NULL_PTR;
2134   if (base != nullptr)  base_type = _gvn.type(base)->isa_ptr();
2135   if (base_type == nullptr) {
2136     // Unknown type.
2137     return Type::AnyPtr;
2138   } else if (_gvn.type(base->uncast()) == TypePtr::NULL_PTR) {
2139     // Since this is a null+long form, we have to switch to a rawptr.
2140     base   = _gvn.transform(new CastX2PNode(offset));
2141     offset = MakeConX(0);
2142     return Type::RawPtr;
2143   } else if (base_type->base() == Type::RawPtr) {
2144     return Type::RawPtr;
2145   } else if (base_type->isa_oopptr()) {
2146     // Base is never null => always a heap address.
2147     if (!TypePtr::NULL_PTR->higher_equal(base_type)) {
2148       return Type::OopPtr;
2149     }
2150     // Offset is small => always a heap address.
2151     const TypeX* offset_type = _gvn.type(offset)->isa_intptr_t();
2152     if (offset_type != nullptr &&
2153         base_type->offset() == 0 &&     // (should always be?)
2154         offset_type->_lo >= 0 &&
2155         !MacroAssembler::needs_explicit_null_check(offset_type->_hi)) {
2156       return Type::OopPtr;
2157     } else if (type == T_OBJECT) {
2158       // off heap access to an oop doesn't make any sense. Has to be on
2159       // heap.
2160       return Type::OopPtr;
2161     }
2162     // Otherwise, it might either be oop+off or null+addr.
2163     return Type::AnyPtr;
2164   } else {
2165     // No information:
2166     return Type::AnyPtr;
2167   }
2168 }
2169 
2170 Node* LibraryCallKit::make_unsafe_address(Node*& base, Node* offset, BasicType type, bool can_cast) {
2171   Node* uncasted_base = base;
2172   int kind = classify_unsafe_addr(uncasted_base, offset, type);
2173   if (kind == Type::RawPtr) {
2174     return basic_plus_adr(top(), uncasted_base, offset);
2175   } else if (kind == Type::AnyPtr) {
2176     assert(base == uncasted_base, "unexpected base change");
2177     if (can_cast) {
2178       if (!_gvn.type(base)->speculative_maybe_null() &&
2179           !too_many_traps(Deoptimization::Reason_speculate_null_check)) {
2180         // According to profiling, this access is always on
2181         // heap. Casting the base to not null and thus avoiding membars
2182         // around the access should allow better optimizations
2183         Node* null_ctl = top();
2184         base = null_check_oop(base, &null_ctl, true, true, true);
2185         assert(null_ctl->is_top(), "no null control here");
2186         return basic_plus_adr(base, offset);
2187       } else if (_gvn.type(base)->speculative_always_null() &&
2188                  !too_many_traps(Deoptimization::Reason_speculate_null_assert)) {
2189         // According to profiling, this access is always off
2190         // heap.
2191         base = null_assert(base);
2192         Node* raw_base = _gvn.transform(new CastX2PNode(offset));
2193         offset = MakeConX(0);
2194         return basic_plus_adr(top(), raw_base, offset);
2195       }
2196     }
2197     // We don't know if it's an on heap or off heap access. Fall back
2198     // to raw memory access.
2199     Node* raw = _gvn.transform(new CheckCastPPNode(control(), base, TypeRawPtr::BOTTOM));
2200     return basic_plus_adr(top(), raw, offset);
2201   } else {
2202     assert(base == uncasted_base, "unexpected base change");
2203     // We know it's an on heap access so base can't be null
2204     if (TypePtr::NULL_PTR->higher_equal(_gvn.type(base))) {
2205       base = must_be_not_null(base, true);
2206     }
2207     return basic_plus_adr(base, offset);
2208   }
2209 }
2210 
2211 //--------------------------inline_number_methods-----------------------------
2212 // inline int     Integer.numberOfLeadingZeros(int)
2213 // inline int        Long.numberOfLeadingZeros(long)
2214 //
2215 // inline int     Integer.numberOfTrailingZeros(int)
2216 // inline int        Long.numberOfTrailingZeros(long)
2217 //
2218 // inline int     Integer.bitCount(int)
2219 // inline int        Long.bitCount(long)
2220 //
2221 // inline char  Character.reverseBytes(char)
2222 // inline short     Short.reverseBytes(short)
2223 // inline int     Integer.reverseBytes(int)
2224 // inline long       Long.reverseBytes(long)
2225 bool LibraryCallKit::inline_number_methods(vmIntrinsics::ID id) {
2226   Node* arg = argument(0);
2227   Node* n = nullptr;
2228   switch (id) {
2229   case vmIntrinsics::_numberOfLeadingZeros_i:   n = new CountLeadingZerosINode( arg); break;
2230   case vmIntrinsics::_numberOfLeadingZeros_l:   n = new CountLeadingZerosLNode( arg); break;
2231   case vmIntrinsics::_numberOfTrailingZeros_i:  n = new CountTrailingZerosINode(arg); break;
2232   case vmIntrinsics::_numberOfTrailingZeros_l:  n = new CountTrailingZerosLNode(arg); break;
2233   case vmIntrinsics::_bitCount_i:               n = new PopCountINode(          arg); break;
2234   case vmIntrinsics::_bitCount_l:               n = new PopCountLNode(          arg); break;
2235   case vmIntrinsics::_reverseBytes_c:           n = new ReverseBytesUSNode(     arg); break;
2236   case vmIntrinsics::_reverseBytes_s:           n = new ReverseBytesSNode(      arg); break;
2237   case vmIntrinsics::_reverseBytes_i:           n = new ReverseBytesINode(      arg); break;
2238   case vmIntrinsics::_reverseBytes_l:           n = new ReverseBytesLNode(      arg); break;
2239   case vmIntrinsics::_reverse_i:                n = new ReverseINode(           arg); break;
2240   case vmIntrinsics::_reverse_l:                n = new ReverseLNode(           arg); break;
2241   default:  fatal_unexpected_iid(id);  break;
2242   }
2243   set_result(_gvn.transform(n));
2244   return true;
2245 }
2246 
2247 //--------------------------inline_bitshuffle_methods-----------------------------
2248 // inline int Integer.compress(int, int)
2249 // inline int Integer.expand(int, int)
2250 // inline long Long.compress(long, long)
2251 // inline long Long.expand(long, long)
2252 bool LibraryCallKit::inline_bitshuffle_methods(vmIntrinsics::ID id) {
2253   Node* n = nullptr;
2254   switch (id) {
2255     case vmIntrinsics::_compress_i:  n = new CompressBitsNode(argument(0), argument(1), TypeInt::INT); break;
2256     case vmIntrinsics::_expand_i:    n = new ExpandBitsNode(argument(0),  argument(1), TypeInt::INT); break;
2257     case vmIntrinsics::_compress_l:  n = new CompressBitsNode(argument(0), argument(2), TypeLong::LONG); break;
2258     case vmIntrinsics::_expand_l:    n = new ExpandBitsNode(argument(0), argument(2), TypeLong::LONG); break;
2259     default:  fatal_unexpected_iid(id);  break;
2260   }
2261   set_result(_gvn.transform(n));
2262   return true;
2263 }
2264 
2265 //--------------------------inline_number_methods-----------------------------
2266 // inline int Integer.compareUnsigned(int, int)
2267 // inline int    Long.compareUnsigned(long, long)
2268 bool LibraryCallKit::inline_compare_unsigned(vmIntrinsics::ID id) {
2269   Node* arg1 = argument(0);
2270   Node* arg2 = (id == vmIntrinsics::_compareUnsigned_l) ? argument(2) : argument(1);
2271   Node* n = nullptr;
2272   switch (id) {
2273     case vmIntrinsics::_compareUnsigned_i:   n = new CmpU3Node(arg1, arg2);  break;
2274     case vmIntrinsics::_compareUnsigned_l:   n = new CmpUL3Node(arg1, arg2); break;
2275     default:  fatal_unexpected_iid(id);  break;
2276   }
2277   set_result(_gvn.transform(n));
2278   return true;
2279 }
2280 
2281 //--------------------------inline_unsigned_divmod_methods-----------------------------
2282 // inline int Integer.divideUnsigned(int, int)
2283 // inline int Integer.remainderUnsigned(int, int)
2284 // inline long Long.divideUnsigned(long, long)
2285 // inline long Long.remainderUnsigned(long, long)
2286 bool LibraryCallKit::inline_divmod_methods(vmIntrinsics::ID id) {
2287   Node* n = nullptr;
2288   switch (id) {
2289     case vmIntrinsics::_divideUnsigned_i: {
2290       zero_check_int(argument(1));
2291       // Compile-time detect of null-exception
2292       if (stopped()) {
2293         return true; // keep the graph constructed so far
2294       }
2295       n = new UDivINode(control(), argument(0), argument(1));
2296       break;
2297     }
2298     case vmIntrinsics::_divideUnsigned_l: {
2299       zero_check_long(argument(2));
2300       // Compile-time detect of null-exception
2301       if (stopped()) {
2302         return true; // keep the graph constructed so far
2303       }
2304       n = new UDivLNode(control(), argument(0), argument(2));
2305       break;
2306     }
2307     case vmIntrinsics::_remainderUnsigned_i: {
2308       zero_check_int(argument(1));
2309       // Compile-time detect of null-exception
2310       if (stopped()) {
2311         return true; // keep the graph constructed so far
2312       }
2313       n = new UModINode(control(), argument(0), argument(1));
2314       break;
2315     }
2316     case vmIntrinsics::_remainderUnsigned_l: {
2317       zero_check_long(argument(2));
2318       // Compile-time detect of null-exception
2319       if (stopped()) {
2320         return true; // keep the graph constructed so far
2321       }
2322       n = new UModLNode(control(), argument(0), argument(2));
2323       break;
2324     }
2325     default:  fatal_unexpected_iid(id);  break;
2326   }
2327   set_result(_gvn.transform(n));
2328   return true;
2329 }
2330 
2331 //----------------------------inline_unsafe_access----------------------------
2332 
2333 const TypeOopPtr* LibraryCallKit::sharpen_unsafe_type(Compile::AliasType* alias_type, const TypePtr *adr_type) {
2334   // Attempt to infer a sharper value type from the offset and base type.
2335   ciKlass* sharpened_klass = nullptr;
2336 
2337   // See if it is an instance field, with an object type.
2338   if (alias_type->field() != nullptr) {
2339     if (alias_type->field()->type()->is_klass()) {
2340       sharpened_klass = alias_type->field()->type()->as_klass();
2341     }
2342   }
2343 
2344   const TypeOopPtr* result = nullptr;
2345   // See if it is a narrow oop array.
2346   if (adr_type->isa_aryptr()) {
2347     if (adr_type->offset() >= objArrayOopDesc::base_offset_in_bytes()) {
2348       const TypeOopPtr* elem_type = adr_type->is_aryptr()->elem()->make_oopptr();
2349       if (elem_type != nullptr && elem_type->is_loaded()) {
2350         // Sharpen the value type.
2351         result = elem_type;
2352       }
2353     }
2354   }
2355 
2356   // The sharpened class might be unloaded if there is no class loader
2357   // contraint in place.
2358   if (result == nullptr && sharpened_klass != nullptr && sharpened_klass->is_loaded()) {
2359     // Sharpen the value type.
2360     result = TypeOopPtr::make_from_klass(sharpened_klass);
2361   }
2362   if (result != nullptr) {
2363 #ifndef PRODUCT
2364     if (C->print_intrinsics() || C->print_inlining()) {
2365       tty->print("  from base type:  ");  adr_type->dump(); tty->cr();
2366       tty->print("  sharpened value: ");  result->dump();    tty->cr();
2367     }
2368 #endif
2369   }
2370   return result;
2371 }
2372 
2373 DecoratorSet LibraryCallKit::mo_decorator_for_access_kind(AccessKind kind) {
2374   switch (kind) {
2375       case Relaxed:
2376         return MO_UNORDERED;
2377       case Opaque:
2378         return MO_RELAXED;
2379       case Acquire:
2380         return MO_ACQUIRE;
2381       case Release:
2382         return MO_RELEASE;
2383       case Volatile:
2384         return MO_SEQ_CST;
2385       default:
2386         ShouldNotReachHere();
2387         return 0;
2388   }
2389 }
2390 
2391 LibraryCallKit::SavedState::SavedState(LibraryCallKit* kit) :
2392   _kit(kit),
2393   _sp(kit->sp()),
2394   _jvms(kit->jvms()),
2395   _map(kit->clone_map()),
2396   _discarded(false)
2397 {
2398   for (DUIterator_Fast imax, i = kit->control()->fast_outs(imax); i < imax; i++) {
2399     Node* out = kit->control()->fast_out(i);
2400     if (out->is_CFG()) {
2401       _ctrl_succ.push(out);
2402     }
2403   }
2404 }
2405 
2406 LibraryCallKit::SavedState::~SavedState() {
2407   if (_discarded) {
2408     _kit->destruct_map_clone(_map);
2409     return;
2410   }
2411   _kit->jvms()->set_map(_map);
2412   _kit->jvms()->set_sp(_sp);
2413   _map->set_jvms(_kit->jvms());
2414   _kit->set_map(_map);
2415   _kit->set_sp(_sp);
2416   for (DUIterator_Fast imax, i = _kit->control()->fast_outs(imax); i < imax; i++) {
2417     Node* out = _kit->control()->fast_out(i);
2418     if (out->is_CFG() && out->in(0) == _kit->control() && out != _kit->map() && !_ctrl_succ.member(out)) {
2419       _kit->_gvn.hash_delete(out);
2420       out->set_req(0, _kit->C->top());
2421       _kit->C->record_for_igvn(out);
2422       --i; --imax;
2423       _kit->_gvn.hash_find_insert(out);
2424     }
2425   }
2426 }
2427 
2428 void LibraryCallKit::SavedState::discard() {
2429   _discarded = true;
2430 }
2431 
2432 bool LibraryCallKit::inline_unsafe_access(bool is_store, const BasicType type, const AccessKind kind, const bool unaligned) {
2433   if (callee()->is_static())  return false;  // caller must have the capability!
2434   DecoratorSet decorators = C2_UNSAFE_ACCESS;
2435   guarantee(!is_store || kind != Acquire, "Acquire accesses can be produced only for loads");
2436   guarantee( is_store || kind != Release, "Release accesses can be produced only for stores");
2437   assert(type != T_OBJECT || !unaligned, "unaligned access not supported with object type");
2438 
2439   if (is_reference_type(type)) {
2440     decorators |= ON_UNKNOWN_OOP_REF;
2441   }
2442 
2443   if (unaligned) {
2444     decorators |= C2_UNALIGNED;
2445   }
2446 
2447 #ifndef PRODUCT
2448   {
2449     ResourceMark rm;
2450     // Check the signatures.
2451     ciSignature* sig = callee()->signature();
2452 #ifdef ASSERT
2453     if (!is_store) {
2454       // Object getReference(Object base, int/long offset), etc.
2455       BasicType rtype = sig->return_type()->basic_type();
2456       assert(rtype == type, "getter must return the expected value");
2457       assert(sig->count() == 2, "oop getter has 2 arguments");
2458       assert(sig->type_at(0)->basic_type() == T_OBJECT, "getter base is object");
2459       assert(sig->type_at(1)->basic_type() == T_LONG, "getter offset is correct");
2460     } else {
2461       // void putReference(Object base, int/long offset, Object x), etc.
2462       assert(sig->return_type()->basic_type() == T_VOID, "putter must not return a value");
2463       assert(sig->count() == 3, "oop putter has 3 arguments");
2464       assert(sig->type_at(0)->basic_type() == T_OBJECT, "putter base is object");
2465       assert(sig->type_at(1)->basic_type() == T_LONG, "putter offset is correct");
2466       BasicType vtype = sig->type_at(sig->count()-1)->basic_type();
2467       assert(vtype == type, "putter must accept the expected value");
2468     }
2469 #endif // ASSERT
2470  }
2471 #endif //PRODUCT
2472 
2473   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
2474 
2475   Node* receiver = argument(0);  // type: oop
2476 
2477   // Build address expression.
2478   Node* heap_base_oop = top();
2479 
2480   // The base is either a Java object or a value produced by Unsafe.staticFieldBase
2481   Node* base = argument(1);  // type: oop
2482   // The offset is a value produced by Unsafe.staticFieldOffset or Unsafe.objectFieldOffset
2483   Node* offset = argument(2);  // type: long
2484   // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
2485   // to be plain byte offsets, which are also the same as those accepted
2486   // by oopDesc::field_addr.
2487   assert(Unsafe_field_offset_to_byte_offset(11) == 11,
2488          "fieldOffset must be byte-scaled");
2489   // 32-bit machines ignore the high half!
2490   offset = ConvL2X(offset);
2491 
2492   // Save state and restore on bailout
2493   SavedState old_state(this);
2494 
2495   Node* adr = make_unsafe_address(base, offset, type, kind == Relaxed);
2496   assert(!stopped(), "Inlining of unsafe access failed: address construction stopped unexpectedly");
2497 
2498   if (_gvn.type(base->uncast())->isa_ptr() == TypePtr::NULL_PTR) {
2499     if (type != T_OBJECT) {
2500       decorators |= IN_NATIVE; // off-heap primitive access
2501     } else {
2502       return false; // off-heap oop accesses are not supported
2503     }
2504   } else {
2505     heap_base_oop = base; // on-heap or mixed access
2506   }
2507 
2508   // Can base be null? Otherwise, always on-heap access.
2509   bool can_access_non_heap = TypePtr::NULL_PTR->higher_equal(_gvn.type(base));
2510 
2511   if (!can_access_non_heap) {
2512     decorators |= IN_HEAP;
2513   }
2514 
2515   Node* val = is_store ? argument(4) : nullptr;
2516 
2517   const TypePtr* adr_type = _gvn.type(adr)->isa_ptr();
2518   if (adr_type == TypePtr::NULL_PTR) {
2519     return false; // off-heap access with zero address
2520   }
2521 
2522   // Try to categorize the address.
2523   Compile::AliasType* alias_type = C->alias_type(adr_type);
2524   assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
2525 
2526   if (alias_type->adr_type() == TypeInstPtr::KLASS ||
2527       alias_type->adr_type() == TypeAryPtr::RANGE) {
2528     return false; // not supported
2529   }
2530 
2531   bool mismatched = false;
2532   BasicType bt = alias_type->basic_type();
2533   if (bt != T_ILLEGAL) {
2534     assert(alias_type->adr_type()->is_oopptr(), "should be on-heap access");
2535     if (bt == T_BYTE && adr_type->isa_aryptr()) {
2536       // Alias type doesn't differentiate between byte[] and boolean[]).
2537       // Use address type to get the element type.
2538       bt = adr_type->is_aryptr()->elem()->array_element_basic_type();
2539     }
2540     if (is_reference_type(bt, true)) {
2541       // accessing an array field with getReference is not a mismatch
2542       bt = T_OBJECT;
2543     }
2544     if ((bt == T_OBJECT) != (type == T_OBJECT)) {
2545       // Don't intrinsify mismatched object accesses
2546       return false;
2547     }
2548     mismatched = (bt != type);
2549   } else if (alias_type->adr_type()->isa_oopptr()) {
2550     mismatched = true; // conservatively mark all "wide" on-heap accesses as mismatched
2551   }
2552 
2553   old_state.discard();
2554   assert(!mismatched || alias_type->adr_type()->is_oopptr(), "off-heap access can't be mismatched");
2555 
2556   if (mismatched) {
2557     decorators |= C2_MISMATCHED;
2558   }
2559 
2560   // First guess at the value type.
2561   const Type *value_type = Type::get_const_basic_type(type);
2562 
2563   // Figure out the memory ordering.
2564   decorators |= mo_decorator_for_access_kind(kind);
2565 
2566   if (!is_store && type == T_OBJECT) {
2567     const TypeOopPtr* tjp = sharpen_unsafe_type(alias_type, adr_type);
2568     if (tjp != nullptr) {
2569       value_type = tjp;
2570     }
2571   }
2572 
2573   receiver = null_check(receiver);
2574   if (stopped()) {
2575     return true;
2576   }
2577   // Heap pointers get a null-check from the interpreter,
2578   // as a courtesy.  However, this is not guaranteed by Unsafe,
2579   // and it is not possible to fully distinguish unintended nulls
2580   // from intended ones in this API.
2581 
2582   if (!is_store) {
2583     Node* p = nullptr;
2584     // Try to constant fold a load from a constant field
2585     ciField* field = alias_type->field();
2586     if (heap_base_oop != top() && field != nullptr && field->is_constant() && !mismatched) {
2587       // final or stable field
2588       p = make_constant_from_field(field, heap_base_oop);
2589     }
2590 
2591     if (p == nullptr) { // Could not constant fold the load
2592       p = access_load_at(heap_base_oop, adr, adr_type, value_type, type, decorators);
2593       // Normalize the value returned by getBoolean in the following cases
2594       if (type == T_BOOLEAN &&
2595           (mismatched ||
2596            heap_base_oop == top() ||                  // - heap_base_oop is null or
2597            (can_access_non_heap && field == nullptr)) // - heap_base_oop is potentially null
2598                                                       //   and the unsafe access is made to large offset
2599                                                       //   (i.e., larger than the maximum offset necessary for any
2600                                                       //   field access)
2601             ) {
2602           IdealKit ideal = IdealKit(this);
2603 #define __ ideal.
2604           IdealVariable normalized_result(ideal);
2605           __ declarations_done();
2606           __ set(normalized_result, p);
2607           __ if_then(p, BoolTest::ne, ideal.ConI(0));
2608           __ set(normalized_result, ideal.ConI(1));
2609           ideal.end_if();
2610           final_sync(ideal);
2611           p = __ value(normalized_result);
2612 #undef __
2613       }
2614     }
2615     if (type == T_ADDRESS) {
2616       p = gvn().transform(new CastP2XNode(nullptr, p));
2617       p = ConvX2UL(p);
2618     }
2619     // The load node has the control of the preceding MemBarCPUOrder.  All
2620     // following nodes will have the control of the MemBarCPUOrder inserted at
2621     // the end of this method.  So, pushing the load onto the stack at a later
2622     // point is fine.
2623     set_result(p);
2624   } else {
2625     if (bt == T_ADDRESS) {
2626       // Repackage the long as a pointer.
2627       val = ConvL2X(val);
2628       val = gvn().transform(new CastX2PNode(val));
2629     }
2630     access_store_at(heap_base_oop, adr, adr_type, val, value_type, type, decorators);
2631   }
2632 
2633   return true;
2634 }
2635 
2636 //----------------------------inline_unsafe_load_store----------------------------
2637 // This method serves a couple of different customers (depending on LoadStoreKind):
2638 //
2639 // LS_cmp_swap:
2640 //
2641 //   boolean compareAndSetReference(Object o, long offset, Object expected, Object x);
2642 //   boolean compareAndSetInt(   Object o, long offset, int    expected, int    x);
2643 //   boolean compareAndSetLong(  Object o, long offset, long   expected, long   x);
2644 //
2645 // LS_cmp_swap_weak:
2646 //
2647 //   boolean weakCompareAndSetReference(       Object o, long offset, Object expected, Object x);
2648 //   boolean weakCompareAndSetReferencePlain(  Object o, long offset, Object expected, Object x);
2649 //   boolean weakCompareAndSetReferenceAcquire(Object o, long offset, Object expected, Object x);
2650 //   boolean weakCompareAndSetReferenceRelease(Object o, long offset, Object expected, Object x);
2651 //
2652 //   boolean weakCompareAndSetInt(          Object o, long offset, int    expected, int    x);
2653 //   boolean weakCompareAndSetIntPlain(     Object o, long offset, int    expected, int    x);
2654 //   boolean weakCompareAndSetIntAcquire(   Object o, long offset, int    expected, int    x);
2655 //   boolean weakCompareAndSetIntRelease(   Object o, long offset, int    expected, int    x);
2656 //
2657 //   boolean weakCompareAndSetLong(         Object o, long offset, long   expected, long   x);
2658 //   boolean weakCompareAndSetLongPlain(    Object o, long offset, long   expected, long   x);
2659 //   boolean weakCompareAndSetLongAcquire(  Object o, long offset, long   expected, long   x);
2660 //   boolean weakCompareAndSetLongRelease(  Object o, long offset, long   expected, long   x);
2661 //
2662 // LS_cmp_exchange:
2663 //
2664 //   Object compareAndExchangeReferenceVolatile(Object o, long offset, Object expected, Object x);
2665 //   Object compareAndExchangeReferenceAcquire( Object o, long offset, Object expected, Object x);
2666 //   Object compareAndExchangeReferenceRelease( Object o, long offset, Object expected, Object x);
2667 //
2668 //   Object compareAndExchangeIntVolatile(   Object o, long offset, Object expected, Object x);
2669 //   Object compareAndExchangeIntAcquire(    Object o, long offset, Object expected, Object x);
2670 //   Object compareAndExchangeIntRelease(    Object o, long offset, Object expected, Object x);
2671 //
2672 //   Object compareAndExchangeLongVolatile(  Object o, long offset, Object expected, Object x);
2673 //   Object compareAndExchangeLongAcquire(   Object o, long offset, Object expected, Object x);
2674 //   Object compareAndExchangeLongRelease(   Object o, long offset, Object expected, Object x);
2675 //
2676 // LS_get_add:
2677 //
2678 //   int  getAndAddInt( Object o, long offset, int  delta)
2679 //   long getAndAddLong(Object o, long offset, long delta)
2680 //
2681 // LS_get_set:
2682 //
2683 //   int    getAndSet(Object o, long offset, int    newValue)
2684 //   long   getAndSet(Object o, long offset, long   newValue)
2685 //   Object getAndSet(Object o, long offset, Object newValue)
2686 //
2687 bool LibraryCallKit::inline_unsafe_load_store(const BasicType type, const LoadStoreKind kind, const AccessKind access_kind) {
2688   // This basic scheme here is the same as inline_unsafe_access, but
2689   // differs in enough details that combining them would make the code
2690   // overly confusing.  (This is a true fact! I originally combined
2691   // them, but even I was confused by it!) As much code/comments as
2692   // possible are retained from inline_unsafe_access though to make
2693   // the correspondences clearer. - dl
2694 
2695   if (callee()->is_static())  return false;  // caller must have the capability!
2696 
2697   DecoratorSet decorators = C2_UNSAFE_ACCESS;
2698   decorators |= mo_decorator_for_access_kind(access_kind);
2699 
2700 #ifndef PRODUCT
2701   BasicType rtype;
2702   {
2703     ResourceMark rm;
2704     // Check the signatures.
2705     ciSignature* sig = callee()->signature();
2706     rtype = sig->return_type()->basic_type();
2707     switch(kind) {
2708       case LS_get_add:
2709       case LS_get_set: {
2710       // Check the signatures.
2711 #ifdef ASSERT
2712       assert(rtype == type, "get and set must return the expected type");
2713       assert(sig->count() == 3, "get and set has 3 arguments");
2714       assert(sig->type_at(0)->basic_type() == T_OBJECT, "get and set base is object");
2715       assert(sig->type_at(1)->basic_type() == T_LONG, "get and set offset is long");
2716       assert(sig->type_at(2)->basic_type() == type, "get and set must take expected type as new value/delta");
2717       assert(access_kind == Volatile, "mo is not passed to intrinsic nodes in current implementation");
2718 #endif // ASSERT
2719         break;
2720       }
2721       case LS_cmp_swap:
2722       case LS_cmp_swap_weak: {
2723       // Check the signatures.
2724 #ifdef ASSERT
2725       assert(rtype == T_BOOLEAN, "CAS must return boolean");
2726       assert(sig->count() == 4, "CAS has 4 arguments");
2727       assert(sig->type_at(0)->basic_type() == T_OBJECT, "CAS base is object");
2728       assert(sig->type_at(1)->basic_type() == T_LONG, "CAS offset is long");
2729 #endif // ASSERT
2730         break;
2731       }
2732       case LS_cmp_exchange: {
2733       // Check the signatures.
2734 #ifdef ASSERT
2735       assert(rtype == type, "CAS must return the expected type");
2736       assert(sig->count() == 4, "CAS has 4 arguments");
2737       assert(sig->type_at(0)->basic_type() == T_OBJECT, "CAS base is object");
2738       assert(sig->type_at(1)->basic_type() == T_LONG, "CAS offset is long");
2739 #endif // ASSERT
2740         break;
2741       }
2742       default:
2743         ShouldNotReachHere();
2744     }
2745   }
2746 #endif //PRODUCT
2747 
2748   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
2749 
2750   // Get arguments:
2751   Node* receiver = nullptr;
2752   Node* base     = nullptr;
2753   Node* offset   = nullptr;
2754   Node* oldval   = nullptr;
2755   Node* newval   = nullptr;
2756   switch(kind) {
2757     case LS_cmp_swap:
2758     case LS_cmp_swap_weak:
2759     case LS_cmp_exchange: {
2760       const bool two_slot_type = type2size[type] == 2;
2761       receiver = argument(0);  // type: oop
2762       base     = argument(1);  // type: oop
2763       offset   = argument(2);  // type: long
2764       oldval   = argument(4);  // type: oop, int, or long
2765       newval   = argument(two_slot_type ? 6 : 5);  // type: oop, int, or long
2766       break;
2767     }
2768     case LS_get_add:
2769     case LS_get_set: {
2770       receiver = argument(0);  // type: oop
2771       base     = argument(1);  // type: oop
2772       offset   = argument(2);  // type: long
2773       oldval   = nullptr;
2774       newval   = argument(4);  // type: oop, int, or long
2775       break;
2776     }
2777     default:
2778       ShouldNotReachHere();
2779   }
2780 
2781   // Build field offset expression.
2782   // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
2783   // to be plain byte offsets, which are also the same as those accepted
2784   // by oopDesc::field_addr.
2785   assert(Unsafe_field_offset_to_byte_offset(11) == 11, "fieldOffset must be byte-scaled");
2786   // 32-bit machines ignore the high half of long offsets
2787   offset = ConvL2X(offset);
2788   // Save state and restore on bailout
2789   SavedState old_state(this);
2790   Node* adr = make_unsafe_address(base, offset,type, false);
2791   const TypePtr *adr_type = _gvn.type(adr)->isa_ptr();
2792 
2793   Compile::AliasType* alias_type = C->alias_type(adr_type);
2794   BasicType bt = alias_type->basic_type();
2795   if (bt != T_ILLEGAL &&
2796       (is_reference_type(bt) != (type == T_OBJECT))) {
2797     // Don't intrinsify mismatched object accesses.
2798     return false;
2799   }
2800 
2801   old_state.discard();
2802 
2803   // For CAS, unlike inline_unsafe_access, there seems no point in
2804   // trying to refine types. Just use the coarse types here.
2805   assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
2806   const Type *value_type = Type::get_const_basic_type(type);
2807 
2808   switch (kind) {
2809     case LS_get_set:
2810     case LS_cmp_exchange: {
2811       if (type == T_OBJECT) {
2812         const TypeOopPtr* tjp = sharpen_unsafe_type(alias_type, adr_type);
2813         if (tjp != nullptr) {
2814           value_type = tjp;
2815         }
2816       }
2817       break;
2818     }
2819     case LS_cmp_swap:
2820     case LS_cmp_swap_weak:
2821     case LS_get_add:
2822       break;
2823     default:
2824       ShouldNotReachHere();
2825   }
2826 
2827   // Null check receiver.
2828   receiver = null_check(receiver);
2829   if (stopped()) {
2830     return true;
2831   }
2832 
2833   int alias_idx = C->get_alias_index(adr_type);
2834 
2835   if (is_reference_type(type)) {
2836     decorators |= IN_HEAP | ON_UNKNOWN_OOP_REF;
2837 
2838     // Transformation of a value which could be null pointer (CastPP #null)
2839     // could be delayed during Parse (for example, in adjust_map_after_if()).
2840     // Execute transformation here to avoid barrier generation in such case.
2841     if (_gvn.type(newval) == TypePtr::NULL_PTR)
2842       newval = _gvn.makecon(TypePtr::NULL_PTR);
2843 
2844     if (oldval != nullptr && _gvn.type(oldval) == TypePtr::NULL_PTR) {
2845       // Refine the value to a null constant, when it is known to be null
2846       oldval = _gvn.makecon(TypePtr::NULL_PTR);
2847     }
2848   }
2849 
2850   Node* result = nullptr;
2851   switch (kind) {
2852     case LS_cmp_exchange: {
2853       result = access_atomic_cmpxchg_val_at(base, adr, adr_type, alias_idx,
2854                                             oldval, newval, value_type, type, decorators);
2855       break;
2856     }
2857     case LS_cmp_swap_weak:
2858       decorators |= C2_WEAK_CMPXCHG;
2859     case LS_cmp_swap: {
2860       result = access_atomic_cmpxchg_bool_at(base, adr, adr_type, alias_idx,
2861                                              oldval, newval, value_type, type, decorators);
2862       break;
2863     }
2864     case LS_get_set: {
2865       result = access_atomic_xchg_at(base, adr, adr_type, alias_idx,
2866                                      newval, value_type, type, decorators);
2867       break;
2868     }
2869     case LS_get_add: {
2870       result = access_atomic_add_at(base, adr, adr_type, alias_idx,
2871                                     newval, value_type, type, decorators);
2872       break;
2873     }
2874     default:
2875       ShouldNotReachHere();
2876   }
2877 
2878   assert(type2size[result->bottom_type()->basic_type()] == type2size[rtype], "result type should match");
2879   set_result(result);
2880   return true;
2881 }
2882 
2883 bool LibraryCallKit::inline_unsafe_fence(vmIntrinsics::ID id) {
2884   // Regardless of form, don't allow previous ld/st to move down,
2885   // then issue acquire, release, or volatile mem_bar.
2886   insert_mem_bar(Op_MemBarCPUOrder);
2887   switch(id) {
2888     case vmIntrinsics::_loadFence:
2889       insert_mem_bar(Op_LoadFence);
2890       return true;
2891     case vmIntrinsics::_storeFence:
2892       insert_mem_bar(Op_StoreFence);
2893       return true;
2894     case vmIntrinsics::_storeStoreFence:
2895       insert_mem_bar(Op_StoreStoreFence);
2896       return true;
2897     case vmIntrinsics::_fullFence:
2898       insert_mem_bar(Op_MemBarVolatile);
2899       return true;
2900     default:
2901       fatal_unexpected_iid(id);
2902       return false;
2903   }
2904 }
2905 
2906 bool LibraryCallKit::inline_onspinwait() {
2907   insert_mem_bar(Op_OnSpinWait);
2908   return true;
2909 }
2910 
2911 bool LibraryCallKit::klass_needs_init_guard(Node* kls) {
2912   if (!kls->is_Con()) {
2913     return true;
2914   }
2915   const TypeInstKlassPtr* klsptr = kls->bottom_type()->isa_instklassptr();
2916   if (klsptr == nullptr) {
2917     return true;
2918   }
2919   ciInstanceKlass* ik = klsptr->instance_klass();
2920   // don't need a guard for a klass that is already initialized
2921   return !ik->is_initialized();
2922 }
2923 
2924 //----------------------------inline_unsafe_writeback0-------------------------
2925 // public native void Unsafe.writeback0(long address)
2926 bool LibraryCallKit::inline_unsafe_writeback0() {
2927   if (!Matcher::has_match_rule(Op_CacheWB)) {
2928     return false;
2929   }
2930 #ifndef PRODUCT
2931   assert(Matcher::has_match_rule(Op_CacheWBPreSync), "found match rule for CacheWB but not CacheWBPreSync");
2932   assert(Matcher::has_match_rule(Op_CacheWBPostSync), "found match rule for CacheWB but not CacheWBPostSync");
2933   ciSignature* sig = callee()->signature();
2934   assert(sig->type_at(0)->basic_type() == T_LONG, "Unsafe_writeback0 address is long!");
2935 #endif
2936   null_check_receiver();  // null-check, then ignore
2937   Node *addr = argument(1);
2938   addr = new CastX2PNode(addr);
2939   addr = _gvn.transform(addr);
2940   Node *flush = new CacheWBNode(control(), memory(TypeRawPtr::BOTTOM), addr);
2941   flush = _gvn.transform(flush);
2942   set_memory(flush, TypeRawPtr::BOTTOM);
2943   return true;
2944 }
2945 
2946 //----------------------------inline_unsafe_writeback0-------------------------
2947 // public native void Unsafe.writeback0(long address)
2948 bool LibraryCallKit::inline_unsafe_writebackSync0(bool is_pre) {
2949   if (is_pre && !Matcher::has_match_rule(Op_CacheWBPreSync)) {
2950     return false;
2951   }
2952   if (!is_pre && !Matcher::has_match_rule(Op_CacheWBPostSync)) {
2953     return false;
2954   }
2955 #ifndef PRODUCT
2956   assert(Matcher::has_match_rule(Op_CacheWB),
2957          (is_pre ? "found match rule for CacheWBPreSync but not CacheWB"
2958                 : "found match rule for CacheWBPostSync but not CacheWB"));
2959 
2960 #endif
2961   null_check_receiver();  // null-check, then ignore
2962   Node *sync;
2963   if (is_pre) {
2964     sync = new CacheWBPreSyncNode(control(), memory(TypeRawPtr::BOTTOM));
2965   } else {
2966     sync = new CacheWBPostSyncNode(control(), memory(TypeRawPtr::BOTTOM));
2967   }
2968   sync = _gvn.transform(sync);
2969   set_memory(sync, TypeRawPtr::BOTTOM);
2970   return true;
2971 }
2972 
2973 //----------------------------inline_unsafe_allocate---------------------------
2974 // public native Object Unsafe.allocateInstance(Class<?> cls);
2975 bool LibraryCallKit::inline_unsafe_allocate() {
2976 
2977 #if INCLUDE_JVMTI
2978   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
2979     return false;
2980   }
2981 #endif //INCLUDE_JVMTI
2982 
2983   if (callee()->is_static())  return false;  // caller must have the capability!
2984 
2985   null_check_receiver();  // null-check, then ignore
2986   Node* cls = null_check(argument(1));
2987   if (stopped())  return true;
2988 
2989   Node* kls = load_klass_from_mirror(cls, false, nullptr, 0);
2990   kls = null_check(kls);
2991   if (stopped())  return true;  // argument was like int.class
2992 
2993 #if INCLUDE_JVMTI
2994     // Don't try to access new allocated obj in the intrinsic.
2995     // It causes perfomance issues even when jvmti event VmObjectAlloc is disabled.
2996     // Deoptimize and allocate in interpreter instead.
2997     Node* addr = makecon(TypeRawPtr::make((address) &JvmtiExport::_should_notify_object_alloc));
2998     Node* should_post_vm_object_alloc = make_load(this->control(), addr, TypeInt::INT, T_INT, MemNode::unordered);
2999     Node* chk = _gvn.transform(new CmpINode(should_post_vm_object_alloc, intcon(0)));
3000     Node* tst = _gvn.transform(new BoolNode(chk, BoolTest::eq));
3001     {
3002       BuildCutout unless(this, tst, PROB_MAX);
3003       uncommon_trap(Deoptimization::Reason_intrinsic,
3004                     Deoptimization::Action_make_not_entrant);
3005     }
3006     if (stopped()) {
3007       return true;
3008     }
3009 #endif //INCLUDE_JVMTI
3010 
3011   Node* test = nullptr;
3012   if (LibraryCallKit::klass_needs_init_guard(kls)) {
3013     // Note:  The argument might still be an illegal value like
3014     // Serializable.class or Object[].class.   The runtime will handle it.
3015     // But we must make an explicit check for initialization.
3016     Node* insp = basic_plus_adr(kls, in_bytes(InstanceKlass::init_state_offset()));
3017     // Use T_BOOLEAN for InstanceKlass::_init_state so the compiler
3018     // can generate code to load it as unsigned byte.
3019     Node* inst = make_load(nullptr, insp, TypeInt::UBYTE, T_BOOLEAN, MemNode::acquire);
3020     Node* bits = intcon(InstanceKlass::fully_initialized);
3021     test = _gvn.transform(new SubINode(inst, bits));
3022     // The 'test' is non-zero if we need to take a slow path.
3023   }
3024 
3025   Node* obj = new_instance(kls, test);
3026   set_result(obj);
3027   return true;
3028 }
3029 
3030 //------------------------inline_native_time_funcs--------------
3031 // inline code for System.currentTimeMillis() and System.nanoTime()
3032 // these have the same type and signature
3033 bool LibraryCallKit::inline_native_time_funcs(address funcAddr, const char* funcName) {
3034   const TypeFunc* tf = OptoRuntime::void_long_Type();
3035   const TypePtr* no_memory_effects = nullptr;
3036   Node* time = make_runtime_call(RC_LEAF, tf, funcAddr, funcName, no_memory_effects);
3037   Node* value = _gvn.transform(new ProjNode(time, TypeFunc::Parms+0));
3038 #ifdef ASSERT
3039   Node* value_top = _gvn.transform(new ProjNode(time, TypeFunc::Parms+1));
3040   assert(value_top == top(), "second value must be top");
3041 #endif
3042   set_result(value);
3043   return true;
3044 }
3045 
3046 //--------------------inline_native_vthread_start_transition--------------------
3047 // inline void startTransition(boolean is_mount);
3048 // inline void startFinalTransition();
3049 // Pseudocode of implementation:
3050 //
3051 // java_lang_Thread::set_is_in_vthread_transition(vthread, true);
3052 // carrier->set_is_in_vthread_transition(true);
3053 // OrderAccess::storeload();
3054 // int disable_requests = java_lang_Thread::vthread_transition_disable_count(vthread)
3055 //                        + global_vthread_transition_disable_count();
3056 // if (disable_requests > 0) {
3057 //   slow path: runtime call
3058 // }
3059 bool LibraryCallKit::inline_native_vthread_start_transition(address funcAddr, const char* funcName, bool is_final_transition) {
3060   Node* vt_oop = _gvn.transform(must_be_not_null(argument(0), true)); // VirtualThread this argument
3061   IdealKit ideal(this);
3062 
3063   Node* thread = ideal.thread();
3064   Node* jt_addr = basic_plus_adr(thread, in_bytes(JavaThread::is_in_vthread_transition_offset()));
3065   Node* vt_addr = basic_plus_adr(vt_oop, java_lang_Thread::is_in_vthread_transition_offset());
3066   access_store_at(nullptr, jt_addr, _gvn.type(jt_addr)->is_ptr(), ideal.ConI(1), TypeInt::BOOL, T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
3067   access_store_at(nullptr, vt_addr, _gvn.type(vt_addr)->is_ptr(), ideal.ConI(1), TypeInt::BOOL, T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
3068   insert_mem_bar(Op_MemBarVolatile);
3069   ideal.sync_kit(this);
3070 
3071   Node* global_disable_addr = makecon(TypeRawPtr::make((address)MountUnmountDisabler::global_vthread_transition_disable_count_address()));
3072   Node* global_disable = ideal.load(ideal.ctrl(), global_disable_addr, TypeInt::INT, T_INT, Compile::AliasIdxRaw, true /*require_atomic_access*/);
3073   Node* vt_disable_addr = basic_plus_adr(vt_oop, java_lang_Thread::vthread_transition_disable_count_offset());
3074   Node* vt_disable = ideal.load(ideal.ctrl(), vt_disable_addr, TypeInt::INT, T_INT, Compile::AliasIdxRaw, true /*require_atomic_access*/);
3075   Node* disabled = _gvn.transform(new AddINode(global_disable, vt_disable));
3076 
3077   ideal.if_then(disabled, BoolTest::ne, ideal.ConI(0)); {
3078     sync_kit(ideal);
3079     Node* is_mount = is_final_transition ? ideal.ConI(0) : _gvn.transform(argument(1));
3080     const TypeFunc* tf = OptoRuntime::vthread_transition_Type();
3081     make_runtime_call(RC_NO_LEAF, tf, funcAddr, funcName, TypePtr::BOTTOM, vt_oop, is_mount);
3082     ideal.sync_kit(this);
3083   }
3084   ideal.end_if();
3085 
3086   final_sync(ideal);
3087   return true;
3088 }
3089 
3090 bool LibraryCallKit::inline_native_vthread_end_transition(address funcAddr, const char* funcName, bool is_first_transition) {
3091   Node* vt_oop = _gvn.transform(must_be_not_null(argument(0), true)); // VirtualThread this argument
3092   IdealKit ideal(this);
3093 
3094   Node* _notify_jvmti_addr = makecon(TypeRawPtr::make((address)MountUnmountDisabler::notify_jvmti_events_address()));
3095   Node* _notify_jvmti = ideal.load(ideal.ctrl(), _notify_jvmti_addr, TypeInt::BOOL, T_BOOLEAN, Compile::AliasIdxRaw);
3096 
3097   ideal.if_then(_notify_jvmti, BoolTest::eq, ideal.ConI(1)); {
3098     sync_kit(ideal);
3099     Node* is_mount = is_first_transition ? ideal.ConI(1) : _gvn.transform(argument(1));
3100     const TypeFunc* tf = OptoRuntime::vthread_transition_Type();
3101     make_runtime_call(RC_NO_LEAF, tf, funcAddr, funcName, TypePtr::BOTTOM, vt_oop, is_mount);
3102     ideal.sync_kit(this);
3103   } ideal.else_(); {
3104     Node* thread = ideal.thread();
3105     Node* jt_addr = basic_plus_adr(thread, in_bytes(JavaThread::is_in_vthread_transition_offset()));
3106     Node* vt_addr = basic_plus_adr(vt_oop, java_lang_Thread::is_in_vthread_transition_offset());
3107 
3108     sync_kit(ideal);
3109     access_store_at(nullptr, jt_addr, _gvn.type(jt_addr)->is_ptr(), ideal.ConI(0), TypeInt::BOOL, T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
3110     access_store_at(nullptr, vt_addr, _gvn.type(vt_addr)->is_ptr(), ideal.ConI(0), TypeInt::BOOL, T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
3111     ideal.sync_kit(this);
3112   } ideal.end_if();
3113 
3114   final_sync(ideal);
3115   return true;
3116 }
3117 
3118 #if INCLUDE_JVMTI
3119 
3120 // Always update the is_disable_suspend bit.
3121 bool LibraryCallKit::inline_native_notify_jvmti_sync() {
3122   if (!DoJVMTIVirtualThreadTransitions) {
3123     return true;
3124   }
3125   IdealKit ideal(this);
3126 
3127   {
3128     // unconditionally update the is_disable_suspend bit in current JavaThread
3129     Node* thread = ideal.thread();
3130     Node* arg = _gvn.transform(argument(0)); // argument for notification
3131     Node* addr = basic_plus_adr(thread, in_bytes(JavaThread::is_disable_suspend_offset()));
3132     const TypePtr *addr_type = _gvn.type(addr)->isa_ptr();
3133 
3134     sync_kit(ideal);
3135     access_store_at(nullptr, addr, addr_type, arg, _gvn.type(arg), T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
3136     ideal.sync_kit(this);
3137   }
3138   final_sync(ideal);
3139 
3140   return true;
3141 }
3142 
3143 #endif // INCLUDE_JVMTI
3144 
3145 #ifdef JFR_HAVE_INTRINSICS
3146 
3147 /**
3148  * if oop->klass != null
3149  *   // normal class
3150  *   epoch = _epoch_state ? 2 : 1
3151  *   if oop->klass->trace_id & ((epoch << META_SHIFT) | epoch)) != epoch {
3152  *     ... // enter slow path when the klass is first recorded or the epoch of JFR shifts
3153  *   }
3154  *   id = oop->klass->trace_id >> TRACE_ID_SHIFT // normal class path
3155  * else
3156  *   // primitive class
3157  *   if oop->array_klass != null
3158  *     id = (oop->array_klass->trace_id >> TRACE_ID_SHIFT) + 1 // primitive class path
3159  *   else
3160  *     id = LAST_TYPE_ID + 1 // void class path
3161  *   if (!signaled)
3162  *     signaled = true
3163  */
3164 bool LibraryCallKit::inline_native_classID() {
3165   Node* cls = argument(0);
3166 
3167   IdealKit ideal(this);
3168 #define __ ideal.
3169   IdealVariable result(ideal); __ declarations_done();
3170   Node* kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(),
3171                                                  basic_plus_adr(cls, java_lang_Class::klass_offset()),
3172                                                  TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
3173 
3174 
3175   __ if_then(kls, BoolTest::ne, null()); {
3176     Node* kls_trace_id_addr = basic_plus_adr(kls, in_bytes(KLASS_TRACE_ID_OFFSET));
3177     Node* kls_trace_id_raw = ideal.load(ideal.ctrl(), kls_trace_id_addr,TypeLong::LONG, T_LONG, Compile::AliasIdxRaw);
3178 
3179     Node* epoch_address = makecon(TypeRawPtr::make(JfrIntrinsicSupport::epoch_address()));
3180     Node* epoch = ideal.load(ideal.ctrl(), epoch_address, TypeInt::BOOL, T_BOOLEAN, Compile::AliasIdxRaw);
3181     epoch = _gvn.transform(new LShiftLNode(longcon(1), epoch));
3182     Node* mask = _gvn.transform(new LShiftLNode(epoch, intcon(META_SHIFT)));
3183     mask = _gvn.transform(new OrLNode(mask, epoch));
3184     Node* kls_trace_id_raw_and_mask = _gvn.transform(new AndLNode(kls_trace_id_raw, mask));
3185 
3186     float unlikely  = PROB_UNLIKELY(0.999);
3187     __ if_then(kls_trace_id_raw_and_mask, BoolTest::ne, epoch, unlikely); {
3188       sync_kit(ideal);
3189       make_runtime_call(RC_LEAF,
3190                         OptoRuntime::class_id_load_barrier_Type(),
3191                         CAST_FROM_FN_PTR(address, JfrIntrinsicSupport::load_barrier),
3192                         "class id load barrier",
3193                         TypePtr::BOTTOM,
3194                         kls);
3195       ideal.sync_kit(this);
3196     } __ end_if();
3197 
3198     ideal.set(result,  _gvn.transform(new URShiftLNode(kls_trace_id_raw, ideal.ConI(TRACE_ID_SHIFT))));
3199   } __ else_(); {
3200     Node* array_kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(),
3201                                                    basic_plus_adr(cls, java_lang_Class::array_klass_offset()),
3202                                                    TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
3203     __ if_then(array_kls, BoolTest::ne, null()); {
3204       Node* array_kls_trace_id_addr = basic_plus_adr(array_kls, in_bytes(KLASS_TRACE_ID_OFFSET));
3205       Node* array_kls_trace_id_raw = ideal.load(ideal.ctrl(), array_kls_trace_id_addr, TypeLong::LONG, T_LONG, Compile::AliasIdxRaw);
3206       Node* array_kls_trace_id = _gvn.transform(new URShiftLNode(array_kls_trace_id_raw, ideal.ConI(TRACE_ID_SHIFT)));
3207       ideal.set(result, _gvn.transform(new AddLNode(array_kls_trace_id, longcon(1))));
3208     } __ else_(); {
3209       // void class case
3210       ideal.set(result, _gvn.transform(longcon(LAST_TYPE_ID + 1)));
3211     } __ end_if();
3212 
3213     Node* signaled_flag_address = makecon(TypeRawPtr::make(JfrIntrinsicSupport::signal_address()));
3214     Node* signaled = ideal.load(ideal.ctrl(), signaled_flag_address, TypeInt::BOOL, T_BOOLEAN, Compile::AliasIdxRaw, true, MemNode::acquire);
3215     __ if_then(signaled, BoolTest::ne, ideal.ConI(1)); {
3216       ideal.store(ideal.ctrl(), signaled_flag_address, ideal.ConI(1), T_BOOLEAN, Compile::AliasIdxRaw, MemNode::release, true);
3217     } __ end_if();
3218   } __ end_if();
3219 
3220   final_sync(ideal);
3221   set_result(ideal.value(result));
3222 #undef __
3223   return true;
3224 }
3225 
3226 //------------------------inline_native_jvm_commit------------------
3227 bool LibraryCallKit::inline_native_jvm_commit() {
3228   enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
3229 
3230   // Save input memory and i_o state.
3231   Node* input_memory_state = reset_memory();
3232   set_all_memory(input_memory_state);
3233   Node* input_io_state = i_o();
3234 
3235   // TLS.
3236   Node* tls_ptr = _gvn.transform(new ThreadLocalNode());
3237   // Jfr java buffer.
3238   Node* java_buffer_offset = _gvn.transform(new AddPNode(top(), tls_ptr, _gvn.transform(MakeConX(in_bytes(JAVA_BUFFER_OFFSET_JFR)))));
3239   Node* java_buffer = _gvn.transform(new LoadPNode(control(), input_memory_state, java_buffer_offset, TypePtr::BOTTOM, TypeRawPtr::NOTNULL, MemNode::unordered));
3240   Node* java_buffer_pos_offset = _gvn.transform(new AddPNode(top(), java_buffer, _gvn.transform(MakeConX(in_bytes(JFR_BUFFER_POS_OFFSET)))));
3241 
3242   // Load the current value of the notified field in the JfrThreadLocal.
3243   Node* notified_offset = basic_plus_adr(top(), tls_ptr, in_bytes(NOTIFY_OFFSET_JFR));
3244   Node* notified = make_load(control(), notified_offset, TypeInt::BOOL, T_BOOLEAN, MemNode::unordered);
3245 
3246   // Test for notification.
3247   Node* notified_cmp = _gvn.transform(new CmpINode(notified, _gvn.intcon(1)));
3248   Node* test_notified = _gvn.transform(new BoolNode(notified_cmp, BoolTest::eq));
3249   IfNode* iff_notified = create_and_map_if(control(), test_notified, PROB_MIN, COUNT_UNKNOWN);
3250 
3251   // True branch, is notified.
3252   Node* is_notified = _gvn.transform(new IfTrueNode(iff_notified));
3253   set_control(is_notified);
3254 
3255   // Reset notified state.
3256   store_to_memory(control(), notified_offset, _gvn.intcon(0), T_BOOLEAN, MemNode::unordered);
3257   Node* notified_reset_memory = reset_memory();
3258 
3259   // Iff notified, the return address of the commit method is the current position of the backing java buffer. This is used to reset the event writer.
3260   Node* current_pos_X = _gvn.transform(new LoadXNode(control(), input_memory_state, java_buffer_pos_offset, TypeRawPtr::NOTNULL, TypeX_X, MemNode::unordered));
3261   // Convert the machine-word to a long.
3262   Node* current_pos = _gvn.transform(ConvX2L(current_pos_X));
3263 
3264   // False branch, not notified.
3265   Node* not_notified = _gvn.transform(new IfFalseNode(iff_notified));
3266   set_control(not_notified);
3267   set_all_memory(input_memory_state);
3268 
3269   // Arg is the next position as a long.
3270   Node* arg = argument(0);
3271   // Convert long to machine-word.
3272   Node* next_pos_X = _gvn.transform(ConvL2X(arg));
3273 
3274   // Store the next_position to the underlying jfr java buffer.
3275   store_to_memory(control(), java_buffer_pos_offset, next_pos_X, LP64_ONLY(T_LONG) NOT_LP64(T_INT), MemNode::release);
3276 
3277   Node* commit_memory = reset_memory();
3278   set_all_memory(commit_memory);
3279 
3280   // Now load the flags from off the java buffer and decide if the buffer is a lease. If so, it needs to be returned post-commit.
3281   Node* java_buffer_flags_offset = _gvn.transform(new AddPNode(top(), java_buffer, _gvn.transform(MakeConX(in_bytes(JFR_BUFFER_FLAGS_OFFSET)))));
3282   Node* flags = make_load(control(), java_buffer_flags_offset, TypeInt::UBYTE, T_BYTE, MemNode::unordered);
3283   Node* lease_constant = _gvn.transform(_gvn.intcon(4));
3284 
3285   // And flags with lease constant.
3286   Node* lease = _gvn.transform(new AndINode(flags, lease_constant));
3287 
3288   // Branch on lease to conditionalize returning the leased java buffer.
3289   Node* lease_cmp = _gvn.transform(new CmpINode(lease, lease_constant));
3290   Node* test_lease = _gvn.transform(new BoolNode(lease_cmp, BoolTest::eq));
3291   IfNode* iff_lease = create_and_map_if(control(), test_lease, PROB_MIN, COUNT_UNKNOWN);
3292 
3293   // False branch, not a lease.
3294   Node* not_lease = _gvn.transform(new IfFalseNode(iff_lease));
3295 
3296   // True branch, is lease.
3297   Node* is_lease = _gvn.transform(new IfTrueNode(iff_lease));
3298   set_control(is_lease);
3299 
3300   // Make a runtime call, which can safepoint, to return the leased buffer. This updates both the JfrThreadLocal and the Java event writer oop.
3301   Node* call_return_lease = make_runtime_call(RC_NO_LEAF,
3302                                               OptoRuntime::void_void_Type(),
3303                                               SharedRuntime::jfr_return_lease(),
3304                                               "return_lease", TypePtr::BOTTOM);
3305   Node* call_return_lease_control = _gvn.transform(new ProjNode(call_return_lease, TypeFunc::Control));
3306 
3307   RegionNode* lease_compare_rgn = new RegionNode(PATH_LIMIT);
3308   record_for_igvn(lease_compare_rgn);
3309   PhiNode* lease_compare_mem = new PhiNode(lease_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3310   record_for_igvn(lease_compare_mem);
3311   PhiNode* lease_compare_io = new PhiNode(lease_compare_rgn, Type::ABIO);
3312   record_for_igvn(lease_compare_io);
3313   PhiNode* lease_result_value = new PhiNode(lease_compare_rgn, TypeLong::LONG);
3314   record_for_igvn(lease_result_value);
3315 
3316   // Update control and phi nodes.
3317   lease_compare_rgn->init_req(_true_path, call_return_lease_control);
3318   lease_compare_rgn->init_req(_false_path, not_lease);
3319 
3320   lease_compare_mem->init_req(_true_path, _gvn.transform(reset_memory()));
3321   lease_compare_mem->init_req(_false_path, commit_memory);
3322 
3323   lease_compare_io->init_req(_true_path, i_o());
3324   lease_compare_io->init_req(_false_path, input_io_state);
3325 
3326   lease_result_value->init_req(_true_path, _gvn.longcon(0)); // if the lease was returned, return 0L.
3327   lease_result_value->init_req(_false_path, arg); // if not lease, return new updated position.
3328 
3329   RegionNode* result_rgn = new RegionNode(PATH_LIMIT);
3330   PhiNode* result_mem = new PhiNode(result_rgn, Type::MEMORY, TypePtr::BOTTOM);
3331   PhiNode* result_io = new PhiNode(result_rgn, Type::ABIO);
3332   PhiNode* result_value = new PhiNode(result_rgn, TypeLong::LONG);
3333 
3334   // Update control and phi nodes.
3335   result_rgn->init_req(_true_path, is_notified);
3336   result_rgn->init_req(_false_path, _gvn.transform(lease_compare_rgn));
3337 
3338   result_mem->init_req(_true_path, notified_reset_memory);
3339   result_mem->init_req(_false_path, _gvn.transform(lease_compare_mem));
3340 
3341   result_io->init_req(_true_path, input_io_state);
3342   result_io->init_req(_false_path, _gvn.transform(lease_compare_io));
3343 
3344   result_value->init_req(_true_path, current_pos);
3345   result_value->init_req(_false_path, _gvn.transform(lease_result_value));
3346 
3347   // Set output state.
3348   set_control(_gvn.transform(result_rgn));
3349   set_all_memory(_gvn.transform(result_mem));
3350   set_i_o(_gvn.transform(result_io));
3351   set_result(result_rgn, result_value);
3352   return true;
3353 }
3354 
3355 /*
3356  * The intrinsic is a model of this pseudo-code:
3357  *
3358  * JfrThreadLocal* const tl = Thread::jfr_thread_local()
3359  * jobject h_event_writer = tl->java_event_writer();
3360  * if (h_event_writer == nullptr) {
3361  *   return nullptr;
3362  * }
3363  * oop threadObj = Thread::threadObj();
3364  * oop vthread = java_lang_Thread::vthread(threadObj);
3365  * traceid tid;
3366  * bool pinVirtualThread;
3367  * bool excluded;
3368  * if (vthread != threadObj) {  // i.e. current thread is virtual
3369  *   tid = java_lang_Thread::tid(vthread);
3370  *   u2 vthread_epoch_raw = java_lang_Thread::jfr_epoch(vthread);
3371  *   pinVirtualThread = VMContinuations;
3372  *   excluded = vthread_epoch_raw & excluded_mask;
3373  *   if (!excluded) {
3374  *     traceid current_epoch = JfrTraceIdEpoch::current_generation();
3375  *     u2 vthread_epoch = vthread_epoch_raw & epoch_mask;
3376  *     if (vthread_epoch != current_epoch) {
3377  *       write_checkpoint();
3378  *     }
3379  *   }
3380  * } else {
3381  *   tid = java_lang_Thread::tid(threadObj);
3382  *   u2 thread_epoch_raw = java_lang_Thread::jfr_epoch(threadObj);
3383  *   pinVirtualThread = false;
3384  *   excluded = thread_epoch_raw & excluded_mask;
3385  * }
3386  * oop event_writer = JNIHandles::resolve_non_null(h_event_writer);
3387  * traceid tid_in_event_writer = getField(event_writer, "threadID");
3388  * if (tid_in_event_writer != tid) {
3389  *   setField(event_writer, "pinVirtualThread", pinVirtualThread);
3390  *   setField(event_writer, "excluded", excluded);
3391  *   setField(event_writer, "threadID", tid);
3392  * }
3393  * return event_writer
3394  */
3395 bool LibraryCallKit::inline_native_getEventWriter() {
3396   enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
3397 
3398   // Save input memory and i_o state.
3399   Node* input_memory_state = reset_memory();
3400   set_all_memory(input_memory_state);
3401   Node* input_io_state = i_o();
3402 
3403   // The most significant bit of the u2 is used to denote thread exclusion
3404   Node* excluded_shift = _gvn.intcon(15);
3405   Node* excluded_mask = _gvn.intcon(1 << 15);
3406   // The epoch generation is the range [1-32767]
3407   Node* epoch_mask = _gvn.intcon(32767);
3408 
3409   // TLS
3410   Node* tls_ptr = _gvn.transform(new ThreadLocalNode());
3411 
3412   // Load the address of java event writer jobject handle from the jfr_thread_local structure.
3413   Node* jobj_ptr = basic_plus_adr(top(), tls_ptr, in_bytes(THREAD_LOCAL_WRITER_OFFSET_JFR));
3414 
3415   // Load the eventwriter jobject handle.
3416   Node* jobj = make_load(control(), jobj_ptr, TypeRawPtr::BOTTOM, T_ADDRESS, MemNode::unordered);
3417 
3418   // Null check the jobject handle.
3419   Node* jobj_cmp_null = _gvn.transform(new CmpPNode(jobj, null()));
3420   Node* test_jobj_not_equal_null = _gvn.transform(new BoolNode(jobj_cmp_null, BoolTest::ne));
3421   IfNode* iff_jobj_not_equal_null = create_and_map_if(control(), test_jobj_not_equal_null, PROB_MAX, COUNT_UNKNOWN);
3422 
3423   // False path, jobj is null.
3424   Node* jobj_is_null = _gvn.transform(new IfFalseNode(iff_jobj_not_equal_null));
3425 
3426   // True path, jobj is not null.
3427   Node* jobj_is_not_null = _gvn.transform(new IfTrueNode(iff_jobj_not_equal_null));
3428 
3429   set_control(jobj_is_not_null);
3430 
3431   // Load the threadObj for the CarrierThread.
3432   Node* threadObj = generate_current_thread(tls_ptr);
3433 
3434   // Load the vthread.
3435   Node* vthread = generate_virtual_thread(tls_ptr);
3436 
3437   // If vthread != threadObj, this is a virtual thread.
3438   Node* vthread_cmp_threadObj = _gvn.transform(new CmpPNode(vthread, threadObj));
3439   Node* test_vthread_not_equal_threadObj = _gvn.transform(new BoolNode(vthread_cmp_threadObj, BoolTest::ne));
3440   IfNode* iff_vthread_not_equal_threadObj =
3441     create_and_map_if(jobj_is_not_null, test_vthread_not_equal_threadObj, PROB_FAIR, COUNT_UNKNOWN);
3442 
3443   // False branch, fallback to threadObj.
3444   Node* vthread_equal_threadObj = _gvn.transform(new IfFalseNode(iff_vthread_not_equal_threadObj));
3445   set_control(vthread_equal_threadObj);
3446 
3447   // Load the tid field from the vthread object.
3448   Node* thread_obj_tid = load_field_from_object(threadObj, "tid", "J");
3449 
3450   // Load the raw epoch value from the threadObj.
3451   Node* threadObj_epoch_offset = basic_plus_adr(threadObj, java_lang_Thread::jfr_epoch_offset());
3452   Node* threadObj_epoch_raw = access_load_at(threadObj, threadObj_epoch_offset,
3453                                              _gvn.type(threadObj_epoch_offset)->isa_ptr(),
3454                                              TypeInt::CHAR, T_CHAR,
3455                                              IN_HEAP | MO_UNORDERED | C2_MISMATCHED | C2_CONTROL_DEPENDENT_LOAD);
3456 
3457   // Mask off the excluded information from the epoch.
3458   Node * threadObj_is_excluded = _gvn.transform(new AndINode(threadObj_epoch_raw, excluded_mask));
3459 
3460   // True branch, this is a virtual thread.
3461   Node* vthread_not_equal_threadObj = _gvn.transform(new IfTrueNode(iff_vthread_not_equal_threadObj));
3462   set_control(vthread_not_equal_threadObj);
3463 
3464   // Load the tid field from the vthread object.
3465   Node* vthread_tid = load_field_from_object(vthread, "tid", "J");
3466 
3467   // Continuation support determines if a virtual thread should be pinned.
3468   Node* global_addr = makecon(TypeRawPtr::make((address)&VMContinuations));
3469   Node* continuation_support = make_load(control(), global_addr, TypeInt::BOOL, T_BOOLEAN, MemNode::unordered);
3470 
3471   // Load the raw epoch value from the vthread.
3472   Node* vthread_epoch_offset = basic_plus_adr(vthread, java_lang_Thread::jfr_epoch_offset());
3473   Node* vthread_epoch_raw = access_load_at(vthread, vthread_epoch_offset, _gvn.type(vthread_epoch_offset)->is_ptr(),
3474                                            TypeInt::CHAR, T_CHAR,
3475                                            IN_HEAP | MO_UNORDERED | C2_MISMATCHED | C2_CONTROL_DEPENDENT_LOAD);
3476 
3477   // Mask off the excluded information from the epoch.
3478   Node * vthread_is_excluded = _gvn.transform(new AndINode(vthread_epoch_raw, _gvn.transform(excluded_mask)));
3479 
3480   // Branch on excluded to conditionalize updating the epoch for the virtual thread.
3481   Node* is_excluded_cmp = _gvn.transform(new CmpINode(vthread_is_excluded, _gvn.transform(excluded_mask)));
3482   Node* test_not_excluded = _gvn.transform(new BoolNode(is_excluded_cmp, BoolTest::ne));
3483   IfNode* iff_not_excluded = create_and_map_if(control(), test_not_excluded, PROB_MAX, COUNT_UNKNOWN);
3484 
3485   // False branch, vthread is excluded, no need to write epoch info.
3486   Node* excluded = _gvn.transform(new IfFalseNode(iff_not_excluded));
3487 
3488   // True branch, vthread is included, update epoch info.
3489   Node* included = _gvn.transform(new IfTrueNode(iff_not_excluded));
3490   set_control(included);
3491 
3492   // Get epoch value.
3493   Node* epoch = _gvn.transform(new AndINode(vthread_epoch_raw, _gvn.transform(epoch_mask)));
3494 
3495   // Load the current epoch generation. The value is unsigned 16-bit, so we type it as T_CHAR.
3496   Node* epoch_generation_address = makecon(TypeRawPtr::make(JfrIntrinsicSupport::epoch_generation_address()));
3497   Node* current_epoch_generation = make_load(control(), epoch_generation_address, TypeInt::CHAR, T_CHAR, MemNode::unordered);
3498 
3499   // Compare the epoch in the vthread to the current epoch generation.
3500   Node* const epoch_cmp = _gvn.transform(new CmpUNode(current_epoch_generation, epoch));
3501   Node* test_epoch_not_equal = _gvn.transform(new BoolNode(epoch_cmp, BoolTest::ne));
3502   IfNode* iff_epoch_not_equal = create_and_map_if(control(), test_epoch_not_equal, PROB_FAIR, COUNT_UNKNOWN);
3503 
3504   // False path, epoch is equal, checkpoint information is valid.
3505   Node* epoch_is_equal = _gvn.transform(new IfFalseNode(iff_epoch_not_equal));
3506 
3507   // True path, epoch is not equal, write a checkpoint for the vthread.
3508   Node* epoch_is_not_equal = _gvn.transform(new IfTrueNode(iff_epoch_not_equal));
3509 
3510   set_control(epoch_is_not_equal);
3511 
3512   // Make a runtime call, which can safepoint, to write a checkpoint for the vthread for this epoch.
3513   // The call also updates the native thread local thread id and the vthread with the current epoch.
3514   Node* call_write_checkpoint = make_runtime_call(RC_NO_LEAF,
3515                                                   OptoRuntime::jfr_write_checkpoint_Type(),
3516                                                   SharedRuntime::jfr_write_checkpoint(),
3517                                                   "write_checkpoint", TypePtr::BOTTOM);
3518   Node* call_write_checkpoint_control = _gvn.transform(new ProjNode(call_write_checkpoint, TypeFunc::Control));
3519 
3520   // vthread epoch != current epoch
3521   RegionNode* epoch_compare_rgn = new RegionNode(PATH_LIMIT);
3522   record_for_igvn(epoch_compare_rgn);
3523   PhiNode* epoch_compare_mem = new PhiNode(epoch_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3524   record_for_igvn(epoch_compare_mem);
3525   PhiNode* epoch_compare_io = new PhiNode(epoch_compare_rgn, Type::ABIO);
3526   record_for_igvn(epoch_compare_io);
3527 
3528   // Update control and phi nodes.
3529   epoch_compare_rgn->init_req(_true_path, call_write_checkpoint_control);
3530   epoch_compare_rgn->init_req(_false_path, epoch_is_equal);
3531   epoch_compare_mem->init_req(_true_path, _gvn.transform(reset_memory()));
3532   epoch_compare_mem->init_req(_false_path, input_memory_state);
3533   epoch_compare_io->init_req(_true_path, i_o());
3534   epoch_compare_io->init_req(_false_path, input_io_state);
3535 
3536   // excluded != true
3537   RegionNode* exclude_compare_rgn = new RegionNode(PATH_LIMIT);
3538   record_for_igvn(exclude_compare_rgn);
3539   PhiNode* exclude_compare_mem = new PhiNode(exclude_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3540   record_for_igvn(exclude_compare_mem);
3541   PhiNode* exclude_compare_io = new PhiNode(exclude_compare_rgn, Type::ABIO);
3542   record_for_igvn(exclude_compare_io);
3543 
3544   // Update control and phi nodes.
3545   exclude_compare_rgn->init_req(_true_path, _gvn.transform(epoch_compare_rgn));
3546   exclude_compare_rgn->init_req(_false_path, excluded);
3547   exclude_compare_mem->init_req(_true_path, _gvn.transform(epoch_compare_mem));
3548   exclude_compare_mem->init_req(_false_path, input_memory_state);
3549   exclude_compare_io->init_req(_true_path, _gvn.transform(epoch_compare_io));
3550   exclude_compare_io->init_req(_false_path, input_io_state);
3551 
3552   // vthread != threadObj
3553   RegionNode* vthread_compare_rgn = new RegionNode(PATH_LIMIT);
3554   record_for_igvn(vthread_compare_rgn);
3555   PhiNode* vthread_compare_mem = new PhiNode(vthread_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3556   PhiNode* vthread_compare_io = new PhiNode(vthread_compare_rgn, Type::ABIO);
3557   record_for_igvn(vthread_compare_io);
3558   PhiNode* tid = new PhiNode(vthread_compare_rgn, TypeLong::LONG);
3559   record_for_igvn(tid);
3560   PhiNode* exclusion = new PhiNode(vthread_compare_rgn, TypeInt::CHAR);
3561   record_for_igvn(exclusion);
3562   PhiNode* pinVirtualThread = new PhiNode(vthread_compare_rgn, TypeInt::BOOL);
3563   record_for_igvn(pinVirtualThread);
3564 
3565   // Update control and phi nodes.
3566   vthread_compare_rgn->init_req(_true_path, _gvn.transform(exclude_compare_rgn));
3567   vthread_compare_rgn->init_req(_false_path, vthread_equal_threadObj);
3568   vthread_compare_mem->init_req(_true_path, _gvn.transform(exclude_compare_mem));
3569   vthread_compare_mem->init_req(_false_path, input_memory_state);
3570   vthread_compare_io->init_req(_true_path, _gvn.transform(exclude_compare_io));
3571   vthread_compare_io->init_req(_false_path, input_io_state);
3572   tid->init_req(_true_path, _gvn.transform(vthread_tid));
3573   tid->init_req(_false_path, _gvn.transform(thread_obj_tid));
3574   exclusion->init_req(_true_path, _gvn.transform(vthread_is_excluded));
3575   exclusion->init_req(_false_path, _gvn.transform(threadObj_is_excluded));
3576   pinVirtualThread->init_req(_true_path, _gvn.transform(continuation_support));
3577   pinVirtualThread->init_req(_false_path, _gvn.intcon(0));
3578 
3579   // Update branch state.
3580   set_control(_gvn.transform(vthread_compare_rgn));
3581   set_all_memory(_gvn.transform(vthread_compare_mem));
3582   set_i_o(_gvn.transform(vthread_compare_io));
3583 
3584   // Load the event writer oop by dereferencing the jobject handle.
3585   ciKlass* klass_EventWriter = env()->find_system_klass(ciSymbol::make("jdk/jfr/internal/event/EventWriter"));
3586   assert(klass_EventWriter->is_loaded(), "invariant");
3587   ciInstanceKlass* const instklass_EventWriter = klass_EventWriter->as_instance_klass();
3588   const TypeKlassPtr* const aklass = TypeKlassPtr::make(instklass_EventWriter);
3589   const TypeOopPtr* const xtype = aklass->as_instance_type();
3590   Node* jobj_untagged = _gvn.transform(new AddPNode(top(), jobj, _gvn.MakeConX(-JNIHandles::TypeTag::global)));
3591   Node* event_writer = access_load(jobj_untagged, xtype, T_OBJECT, IN_NATIVE | C2_CONTROL_DEPENDENT_LOAD);
3592 
3593   // Load the current thread id from the event writer object.
3594   Node* const event_writer_tid = load_field_from_object(event_writer, "threadID", "J");
3595   // Get the field offset to, conditionally, store an updated tid value later.
3596   Node* const event_writer_tid_field = field_address_from_object(event_writer, "threadID", "J", false);
3597   // Get the field offset to, conditionally, store an updated exclusion value later.
3598   Node* const event_writer_excluded_field = field_address_from_object(event_writer, "excluded", "Z", false);
3599   // Get the field offset to, conditionally, store an updated pinVirtualThread value later.
3600   Node* const event_writer_pin_field = field_address_from_object(event_writer, "pinVirtualThread", "Z", false);
3601 
3602   RegionNode* event_writer_tid_compare_rgn = new RegionNode(PATH_LIMIT);
3603   record_for_igvn(event_writer_tid_compare_rgn);
3604   PhiNode* event_writer_tid_compare_mem = new PhiNode(event_writer_tid_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3605   record_for_igvn(event_writer_tid_compare_mem);
3606   PhiNode* event_writer_tid_compare_io = new PhiNode(event_writer_tid_compare_rgn, Type::ABIO);
3607   record_for_igvn(event_writer_tid_compare_io);
3608 
3609   // Compare the current tid from the thread object to what is currently stored in the event writer object.
3610   Node* const tid_cmp = _gvn.transform(new CmpLNode(event_writer_tid, _gvn.transform(tid)));
3611   Node* test_tid_not_equal = _gvn.transform(new BoolNode(tid_cmp, BoolTest::ne));
3612   IfNode* iff_tid_not_equal = create_and_map_if(_gvn.transform(vthread_compare_rgn), test_tid_not_equal, PROB_FAIR, COUNT_UNKNOWN);
3613 
3614   // False path, tids are the same.
3615   Node* tid_is_equal = _gvn.transform(new IfFalseNode(iff_tid_not_equal));
3616 
3617   // True path, tid is not equal, need to update the tid in the event writer.
3618   Node* tid_is_not_equal = _gvn.transform(new IfTrueNode(iff_tid_not_equal));
3619   record_for_igvn(tid_is_not_equal);
3620 
3621   // Store the pin state to the event writer.
3622   store_to_memory(tid_is_not_equal, event_writer_pin_field, _gvn.transform(pinVirtualThread), T_BOOLEAN, MemNode::unordered);
3623 
3624   // Store the exclusion state to the event writer.
3625   Node* excluded_bool = _gvn.transform(new URShiftINode(_gvn.transform(exclusion), excluded_shift));
3626   store_to_memory(tid_is_not_equal, event_writer_excluded_field, excluded_bool, T_BOOLEAN, MemNode::unordered);
3627 
3628   // Store the tid to the event writer.
3629   store_to_memory(tid_is_not_equal, event_writer_tid_field, tid, T_LONG, MemNode::unordered);
3630 
3631   // Update control and phi nodes.
3632   event_writer_tid_compare_rgn->init_req(_true_path, tid_is_not_equal);
3633   event_writer_tid_compare_rgn->init_req(_false_path, tid_is_equal);
3634   event_writer_tid_compare_mem->init_req(_true_path, _gvn.transform(reset_memory()));
3635   event_writer_tid_compare_mem->init_req(_false_path, _gvn.transform(vthread_compare_mem));
3636   event_writer_tid_compare_io->init_req(_true_path, _gvn.transform(i_o()));
3637   event_writer_tid_compare_io->init_req(_false_path, _gvn.transform(vthread_compare_io));
3638 
3639   // Result of top level CFG, Memory, IO and Value.
3640   RegionNode* result_rgn = new RegionNode(PATH_LIMIT);
3641   PhiNode* result_mem = new PhiNode(result_rgn, Type::MEMORY, TypePtr::BOTTOM);
3642   PhiNode* result_io = new PhiNode(result_rgn, Type::ABIO);
3643   PhiNode* result_value = new PhiNode(result_rgn, TypeInstPtr::BOTTOM);
3644 
3645   // Result control.
3646   result_rgn->init_req(_true_path, _gvn.transform(event_writer_tid_compare_rgn));
3647   result_rgn->init_req(_false_path, jobj_is_null);
3648 
3649   // Result memory.
3650   result_mem->init_req(_true_path, _gvn.transform(event_writer_tid_compare_mem));
3651   result_mem->init_req(_false_path, _gvn.transform(input_memory_state));
3652 
3653   // Result IO.
3654   result_io->init_req(_true_path, _gvn.transform(event_writer_tid_compare_io));
3655   result_io->init_req(_false_path, _gvn.transform(input_io_state));
3656 
3657   // Result value.
3658   result_value->init_req(_true_path, _gvn.transform(event_writer)); // return event writer oop
3659   result_value->init_req(_false_path, null()); // return null
3660 
3661   // Set output state.
3662   set_control(_gvn.transform(result_rgn));
3663   set_all_memory(_gvn.transform(result_mem));
3664   set_i_o(_gvn.transform(result_io));
3665   set_result(result_rgn, result_value);
3666   return true;
3667 }
3668 
3669 /*
3670  * The intrinsic is a model of this pseudo-code:
3671  *
3672  * JfrThreadLocal* const tl = thread->jfr_thread_local();
3673  * if (carrierThread != thread) { // is virtual thread
3674  *   const u2 vthread_epoch_raw = java_lang_Thread::jfr_epoch(thread);
3675  *   bool excluded = vthread_epoch_raw & excluded_mask;
3676  *   AtomicAccess::store(&tl->_contextual_tid, java_lang_Thread::tid(thread));
3677  *   AtomicAccess::store(&tl->_contextual_thread_excluded, is_excluded);
3678  *   if (!excluded) {
3679  *     const u2 vthread_epoch = vthread_epoch_raw & epoch_mask;
3680  *     AtomicAccess::store(&tl->_vthread_epoch, vthread_epoch);
3681  *   }
3682  *   AtomicAccess::release_store(&tl->_vthread, true);
3683  *   return;
3684  * }
3685  * AtomicAccess::release_store(&tl->_vthread, false);
3686  */
3687 void LibraryCallKit::extend_setCurrentThread(Node* jt, Node* thread) {
3688   enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
3689 
3690   Node* input_memory_state = reset_memory();
3691   set_all_memory(input_memory_state);
3692 
3693   // The most significant bit of the u2 is used to denote thread exclusion
3694   Node* excluded_mask = _gvn.intcon(1 << 15);
3695   // The epoch generation is the range [1-32767]
3696   Node* epoch_mask = _gvn.intcon(32767);
3697 
3698   Node* const carrierThread = generate_current_thread(jt);
3699   // If thread != carrierThread, this is a virtual thread.
3700   Node* thread_cmp_carrierThread = _gvn.transform(new CmpPNode(thread, carrierThread));
3701   Node* test_thread_not_equal_carrierThread = _gvn.transform(new BoolNode(thread_cmp_carrierThread, BoolTest::ne));
3702   IfNode* iff_thread_not_equal_carrierThread =
3703     create_and_map_if(control(), test_thread_not_equal_carrierThread, PROB_FAIR, COUNT_UNKNOWN);
3704 
3705   Node* vthread_offset = basic_plus_adr(jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_OFFSET_JFR));
3706 
3707   // False branch, is carrierThread.
3708   Node* thread_equal_carrierThread = _gvn.transform(new IfFalseNode(iff_thread_not_equal_carrierThread));
3709   // Store release
3710   Node* vthread_false_memory = store_to_memory(thread_equal_carrierThread, vthread_offset, _gvn.intcon(0), T_BOOLEAN, MemNode::release, true);
3711 
3712   set_all_memory(input_memory_state);
3713 
3714   // True branch, is virtual thread.
3715   Node* thread_not_equal_carrierThread = _gvn.transform(new IfTrueNode(iff_thread_not_equal_carrierThread));
3716   set_control(thread_not_equal_carrierThread);
3717 
3718   // Load the raw epoch value from the vthread.
3719   Node* epoch_offset = basic_plus_adr(thread, java_lang_Thread::jfr_epoch_offset());
3720   Node* epoch_raw = access_load_at(thread, epoch_offset, _gvn.type(epoch_offset)->is_ptr(), TypeInt::CHAR, T_CHAR,
3721                                    IN_HEAP | MO_UNORDERED | C2_MISMATCHED | C2_CONTROL_DEPENDENT_LOAD);
3722 
3723   // Mask off the excluded information from the epoch.
3724   Node * const is_excluded = _gvn.transform(new AndINode(epoch_raw, _gvn.transform(excluded_mask)));
3725 
3726   // Load the tid field from the thread.
3727   Node* tid = load_field_from_object(thread, "tid", "J");
3728 
3729   // Store the vthread tid to the jfr thread local.
3730   Node* thread_id_offset = basic_plus_adr(jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_ID_OFFSET_JFR));
3731   Node* tid_memory = store_to_memory(control(), thread_id_offset, tid, T_LONG, MemNode::unordered, true);
3732 
3733   // Branch is_excluded to conditionalize updating the epoch .
3734   Node* excluded_cmp = _gvn.transform(new CmpINode(is_excluded, _gvn.transform(excluded_mask)));
3735   Node* test_excluded = _gvn.transform(new BoolNode(excluded_cmp, BoolTest::eq));
3736   IfNode* iff_excluded = create_and_map_if(control(), test_excluded, PROB_MIN, COUNT_UNKNOWN);
3737 
3738   // True branch, vthread is excluded, no need to write epoch info.
3739   Node* excluded = _gvn.transform(new IfTrueNode(iff_excluded));
3740   set_control(excluded);
3741   Node* vthread_is_excluded = _gvn.intcon(1);
3742 
3743   // False branch, vthread is included, update epoch info.
3744   Node* included = _gvn.transform(new IfFalseNode(iff_excluded));
3745   set_control(included);
3746   Node* vthread_is_included = _gvn.intcon(0);
3747 
3748   // Get epoch value.
3749   Node* epoch = _gvn.transform(new AndINode(epoch_raw, _gvn.transform(epoch_mask)));
3750 
3751   // Store the vthread epoch to the jfr thread local.
3752   Node* vthread_epoch_offset = basic_plus_adr(jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_EPOCH_OFFSET_JFR));
3753   Node* included_memory = store_to_memory(control(), vthread_epoch_offset, epoch, T_CHAR, MemNode::unordered, true);
3754 
3755   RegionNode* excluded_rgn = new RegionNode(PATH_LIMIT);
3756   record_for_igvn(excluded_rgn);
3757   PhiNode* excluded_mem = new PhiNode(excluded_rgn, Type::MEMORY, TypePtr::BOTTOM);
3758   record_for_igvn(excluded_mem);
3759   PhiNode* exclusion = new PhiNode(excluded_rgn, TypeInt::BOOL);
3760   record_for_igvn(exclusion);
3761 
3762   // Merge the excluded control and memory.
3763   excluded_rgn->init_req(_true_path, excluded);
3764   excluded_rgn->init_req(_false_path, included);
3765   excluded_mem->init_req(_true_path, tid_memory);
3766   excluded_mem->init_req(_false_path, included_memory);
3767   exclusion->init_req(_true_path, _gvn.transform(vthread_is_excluded));
3768   exclusion->init_req(_false_path, _gvn.transform(vthread_is_included));
3769 
3770   // Set intermediate state.
3771   set_control(_gvn.transform(excluded_rgn));
3772   set_all_memory(excluded_mem);
3773 
3774   // Store the vthread exclusion state to the jfr thread local.
3775   Node* thread_local_excluded_offset = basic_plus_adr(jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_EXCLUDED_OFFSET_JFR));
3776   store_to_memory(control(), thread_local_excluded_offset, _gvn.transform(exclusion), T_BOOLEAN, MemNode::unordered, true);
3777 
3778   // Store release
3779   Node * vthread_true_memory = store_to_memory(control(), vthread_offset, _gvn.intcon(1), T_BOOLEAN, MemNode::release, true);
3780 
3781   RegionNode* thread_compare_rgn = new RegionNode(PATH_LIMIT);
3782   record_for_igvn(thread_compare_rgn);
3783   PhiNode* thread_compare_mem = new PhiNode(thread_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3784   record_for_igvn(thread_compare_mem);
3785   PhiNode* vthread = new PhiNode(thread_compare_rgn, TypeInt::BOOL);
3786   record_for_igvn(vthread);
3787 
3788   // Merge the thread_compare control and memory.
3789   thread_compare_rgn->init_req(_true_path, control());
3790   thread_compare_rgn->init_req(_false_path, thread_equal_carrierThread);
3791   thread_compare_mem->init_req(_true_path, vthread_true_memory);
3792   thread_compare_mem->init_req(_false_path, vthread_false_memory);
3793 
3794   // Set output state.
3795   set_control(_gvn.transform(thread_compare_rgn));
3796   set_all_memory(_gvn.transform(thread_compare_mem));
3797 }
3798 
3799 #endif // JFR_HAVE_INTRINSICS
3800 
3801 //------------------------inline_native_currentCarrierThread------------------
3802 bool LibraryCallKit::inline_native_currentCarrierThread() {
3803   Node* junk = nullptr;
3804   set_result(generate_current_thread(junk));
3805   return true;
3806 }
3807 
3808 //------------------------inline_native_currentThread------------------
3809 bool LibraryCallKit::inline_native_currentThread() {
3810   Node* junk = nullptr;
3811   set_result(generate_virtual_thread(junk));
3812   return true;
3813 }
3814 
3815 //------------------------inline_native_setVthread------------------
3816 bool LibraryCallKit::inline_native_setCurrentThread() {
3817   assert(C->method()->changes_current_thread(),
3818          "method changes current Thread but is not annotated ChangesCurrentThread");
3819   Node* arr = argument(1);
3820   Node* thread = _gvn.transform(new ThreadLocalNode());
3821   Node* p = basic_plus_adr(top()/*!oop*/, thread, in_bytes(JavaThread::vthread_offset()));
3822   Node* thread_obj_handle
3823     = make_load(nullptr, p, p->bottom_type()->is_ptr(), T_OBJECT, MemNode::unordered);
3824   thread_obj_handle = _gvn.transform(thread_obj_handle);
3825   const TypePtr *adr_type = _gvn.type(thread_obj_handle)->isa_ptr();
3826   access_store_at(nullptr, thread_obj_handle, adr_type, arr, _gvn.type(arr), T_OBJECT, IN_NATIVE | MO_UNORDERED);
3827 
3828   // Change the _monitor_owner_id of the JavaThread
3829   Node* tid = load_field_from_object(arr, "tid", "J");
3830   Node* monitor_owner_id_offset = basic_plus_adr(thread, in_bytes(JavaThread::monitor_owner_id_offset()));
3831   store_to_memory(control(), monitor_owner_id_offset, tid, T_LONG, MemNode::unordered, true);
3832 
3833   JFR_ONLY(extend_setCurrentThread(thread, arr);)
3834   return true;
3835 }
3836 
3837 const Type* LibraryCallKit::scopedValueCache_type() {
3838   ciKlass* objects_klass = ciObjArrayKlass::make(env()->Object_klass());
3839   const TypeOopPtr* etype = TypeOopPtr::make_from_klass(env()->Object_klass());
3840   const TypeAry* arr0 = TypeAry::make(etype, TypeInt::POS);
3841 
3842   // Because we create the scopedValue cache lazily we have to make the
3843   // type of the result BotPTR.
3844   bool xk = etype->klass_is_exact();
3845   const Type* objects_type = TypeAryPtr::make(TypePtr::BotPTR, arr0, objects_klass, xk, 0);
3846   return objects_type;
3847 }
3848 
3849 Node* LibraryCallKit::scopedValueCache_helper() {
3850   Node* thread = _gvn.transform(new ThreadLocalNode());
3851   Node* p = basic_plus_adr(top()/*!oop*/, thread, in_bytes(JavaThread::scopedValueCache_offset()));
3852   // We cannot use immutable_memory() because we might flip onto a
3853   // different carrier thread, at which point we'll need to use that
3854   // carrier thread's cache.
3855   // return _gvn.transform(LoadNode::make(_gvn, nullptr, immutable_memory(), p, p->bottom_type()->is_ptr(),
3856   //       TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered));
3857   return make_load(nullptr, p, p->bottom_type()->is_ptr(), T_ADDRESS, MemNode::unordered);
3858 }
3859 
3860 //------------------------inline_native_scopedValueCache------------------
3861 bool LibraryCallKit::inline_native_scopedValueCache() {
3862   Node* cache_obj_handle = scopedValueCache_helper();
3863   const Type* objects_type = scopedValueCache_type();
3864   set_result(access_load(cache_obj_handle, objects_type, T_OBJECT, IN_NATIVE));
3865 
3866   return true;
3867 }
3868 
3869 //------------------------inline_native_setScopedValueCache------------------
3870 bool LibraryCallKit::inline_native_setScopedValueCache() {
3871   Node* arr = argument(0);
3872   Node* cache_obj_handle = scopedValueCache_helper();
3873   const Type* objects_type = scopedValueCache_type();
3874 
3875   const TypePtr *adr_type = _gvn.type(cache_obj_handle)->isa_ptr();
3876   access_store_at(nullptr, cache_obj_handle, adr_type, arr, objects_type, T_OBJECT, IN_NATIVE | MO_UNORDERED);
3877 
3878   return true;
3879 }
3880 
3881 //------------------------inline_native_Continuation_pin and unpin-----------
3882 
3883 // Shared implementation routine for both pin and unpin.
3884 bool LibraryCallKit::inline_native_Continuation_pinning(bool unpin) {
3885   enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
3886 
3887   // Save input memory.
3888   Node* input_memory_state = reset_memory();
3889   set_all_memory(input_memory_state);
3890 
3891   // TLS
3892   Node* tls_ptr = _gvn.transform(new ThreadLocalNode());
3893   Node* last_continuation_offset = basic_plus_adr(top(), tls_ptr, in_bytes(JavaThread::cont_entry_offset()));
3894   Node* last_continuation = make_load(control(), last_continuation_offset, last_continuation_offset->get_ptr_type(), T_ADDRESS, MemNode::unordered);
3895 
3896   // Null check the last continuation object.
3897   Node* continuation_cmp_null = _gvn.transform(new CmpPNode(last_continuation, null()));
3898   Node* test_continuation_not_equal_null = _gvn.transform(new BoolNode(continuation_cmp_null, BoolTest::ne));
3899   IfNode* iff_continuation_not_equal_null = create_and_map_if(control(), test_continuation_not_equal_null, PROB_MAX, COUNT_UNKNOWN);
3900 
3901   // False path, last continuation is null.
3902   Node* continuation_is_null = _gvn.transform(new IfFalseNode(iff_continuation_not_equal_null));
3903 
3904   // True path, last continuation is not null.
3905   Node* continuation_is_not_null = _gvn.transform(new IfTrueNode(iff_continuation_not_equal_null));
3906 
3907   set_control(continuation_is_not_null);
3908 
3909   // Load the pin count from the last continuation.
3910   Node* pin_count_offset = basic_plus_adr(top(), last_continuation, in_bytes(ContinuationEntry::pin_count_offset()));
3911   Node* pin_count = make_load(control(), pin_count_offset, TypeInt::INT, T_INT, MemNode::unordered);
3912 
3913   // The loaded pin count is compared against a context specific rhs for over/underflow detection.
3914   Node* pin_count_rhs;
3915   if (unpin) {
3916     pin_count_rhs = _gvn.intcon(0);
3917   } else {
3918     pin_count_rhs = _gvn.intcon(UINT32_MAX);
3919   }
3920   Node* pin_count_cmp = _gvn.transform(new CmpUNode(_gvn.transform(pin_count), pin_count_rhs));
3921   Node* test_pin_count_over_underflow = _gvn.transform(new BoolNode(pin_count_cmp, BoolTest::eq));
3922   IfNode* iff_pin_count_over_underflow = create_and_map_if(control(), test_pin_count_over_underflow, PROB_MIN, COUNT_UNKNOWN);
3923 
3924   // True branch, pin count over/underflow.
3925   Node* pin_count_over_underflow = _gvn.transform(new IfTrueNode(iff_pin_count_over_underflow));
3926   {
3927     // Trap (but not deoptimize (Action_none)) and continue in the interpreter
3928     // which will throw IllegalStateException for pin count over/underflow.
3929     // No memory changed so far - we can use memory create by reset_memory()
3930     // at the beginning of this intrinsic. No need to call reset_memory() again.
3931     PreserveJVMState pjvms(this);
3932     set_control(pin_count_over_underflow);
3933     uncommon_trap(Deoptimization::Reason_intrinsic,
3934                   Deoptimization::Action_none);
3935     assert(stopped(), "invariant");
3936   }
3937 
3938   // False branch, no pin count over/underflow. Increment or decrement pin count and store back.
3939   Node* valid_pin_count = _gvn.transform(new IfFalseNode(iff_pin_count_over_underflow));
3940   set_control(valid_pin_count);
3941 
3942   Node* next_pin_count;
3943   if (unpin) {
3944     next_pin_count = _gvn.transform(new SubINode(pin_count, _gvn.intcon(1)));
3945   } else {
3946     next_pin_count = _gvn.transform(new AddINode(pin_count, _gvn.intcon(1)));
3947   }
3948 
3949   store_to_memory(control(), pin_count_offset, next_pin_count, T_INT, MemNode::unordered);
3950 
3951   // Result of top level CFG and Memory.
3952   RegionNode* result_rgn = new RegionNode(PATH_LIMIT);
3953   record_for_igvn(result_rgn);
3954   PhiNode* result_mem = new PhiNode(result_rgn, Type::MEMORY, TypePtr::BOTTOM);
3955   record_for_igvn(result_mem);
3956 
3957   result_rgn->init_req(_true_path, _gvn.transform(valid_pin_count));
3958   result_rgn->init_req(_false_path, _gvn.transform(continuation_is_null));
3959   result_mem->init_req(_true_path, _gvn.transform(reset_memory()));
3960   result_mem->init_req(_false_path, _gvn.transform(input_memory_state));
3961 
3962   // Set output state.
3963   set_control(_gvn.transform(result_rgn));
3964   set_all_memory(_gvn.transform(result_mem));
3965 
3966   return true;
3967 }
3968 
3969 //---------------------------load_mirror_from_klass----------------------------
3970 // Given a klass oop, load its java mirror (a java.lang.Class oop).
3971 Node* LibraryCallKit::load_mirror_from_klass(Node* klass) {
3972   Node* p = basic_plus_adr(klass, in_bytes(Klass::java_mirror_offset()));
3973   Node* load = make_load(nullptr, p, TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered);
3974   // mirror = ((OopHandle)mirror)->resolve();
3975   return access_load(load, TypeInstPtr::MIRROR, T_OBJECT, IN_NATIVE);
3976 }
3977 
3978 //-----------------------load_klass_from_mirror_common-------------------------
3979 // Given a java mirror (a java.lang.Class oop), load its corresponding klass oop.
3980 // Test the klass oop for null (signifying a primitive Class like Integer.TYPE),
3981 // and branch to the given path on the region.
3982 // If never_see_null, take an uncommon trap on null, so we can optimistically
3983 // compile for the non-null case.
3984 // If the region is null, force never_see_null = true.
3985 Node* LibraryCallKit::load_klass_from_mirror_common(Node* mirror,
3986                                                     bool never_see_null,
3987                                                     RegionNode* region,
3988                                                     int null_path,
3989                                                     int offset) {
3990   if (region == nullptr)  never_see_null = true;
3991   Node* p = basic_plus_adr(mirror, offset);
3992   const TypeKlassPtr*  kls_type = TypeInstKlassPtr::OBJECT_OR_NULL;
3993   Node* kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), p, TypeRawPtr::BOTTOM, kls_type));
3994   Node* null_ctl = top();
3995   kls = null_check_oop(kls, &null_ctl, never_see_null);
3996   if (region != nullptr) {
3997     // Set region->in(null_path) if the mirror is a primitive (e.g, int.class).
3998     region->init_req(null_path, null_ctl);
3999   } else {
4000     assert(null_ctl == top(), "no loose ends");
4001   }
4002   return kls;
4003 }
4004 
4005 //--------------------(inline_native_Class_query helpers)---------------------
4006 // Use this for JVM_ACC_INTERFACE.
4007 // Fall through if (mods & mask) == bits, take the guard otherwise.
4008 Node* LibraryCallKit::generate_klass_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region,
4009                                                  ByteSize offset, const Type* type, BasicType bt) {
4010   // Branch around if the given klass has the given modifier bit set.
4011   // Like generate_guard, adds a new path onto the region.
4012   Node* modp = basic_plus_adr(kls, in_bytes(offset));
4013   Node* mods = make_load(nullptr, modp, type, bt, MemNode::unordered);
4014   Node* mask = intcon(modifier_mask);
4015   Node* bits = intcon(modifier_bits);
4016   Node* mbit = _gvn.transform(new AndINode(mods, mask));
4017   Node* cmp  = _gvn.transform(new CmpINode(mbit, bits));
4018   Node* bol  = _gvn.transform(new BoolNode(cmp, BoolTest::ne));
4019   return generate_fair_guard(bol, region);
4020 }
4021 Node* LibraryCallKit::generate_interface_guard(Node* kls, RegionNode* region) {
4022   return generate_klass_flags_guard(kls, JVM_ACC_INTERFACE, 0, region,
4023                                     InstanceKlass::access_flags_offset(), TypeInt::CHAR, T_CHAR);
4024 }
4025 
4026 // Use this for testing if Klass is_hidden, has_finalizer, and is_cloneable_fast.
4027 Node* LibraryCallKit::generate_misc_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region) {
4028   return generate_klass_flags_guard(kls, modifier_mask, modifier_bits, region,
4029                                     Klass::misc_flags_offset(), TypeInt::UBYTE, T_BOOLEAN);
4030 }
4031 
4032 Node* LibraryCallKit::generate_hidden_class_guard(Node* kls, RegionNode* region) {
4033   return generate_misc_flags_guard(kls, KlassFlags::_misc_is_hidden_class, 0, region);
4034 }
4035 
4036 //-------------------------inline_native_Class_query-------------------
4037 bool LibraryCallKit::inline_native_Class_query(vmIntrinsics::ID id) {
4038   const Type* return_type = TypeInt::BOOL;
4039   Node* prim_return_value = top();  // what happens if it's a primitive class?
4040   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
4041   bool expect_prim = false;     // most of these guys expect to work on refs
4042 
4043   enum { _normal_path = 1, _prim_path = 2, PATH_LIMIT };
4044 
4045   Node* mirror = argument(0);
4046   Node* obj    = top();
4047 
4048   switch (id) {
4049   case vmIntrinsics::_isInstance:
4050     // nothing is an instance of a primitive type
4051     prim_return_value = intcon(0);
4052     obj = argument(1);
4053     break;
4054   case vmIntrinsics::_isHidden:
4055     prim_return_value = intcon(0);
4056     break;
4057   case vmIntrinsics::_getSuperclass:
4058     prim_return_value = null();
4059     return_type = TypeInstPtr::MIRROR->cast_to_ptr_type(TypePtr::BotPTR);
4060     break;
4061   default:
4062     fatal_unexpected_iid(id);
4063     break;
4064   }
4065 
4066   const TypeInstPtr* mirror_con = _gvn.type(mirror)->isa_instptr();
4067   if (mirror_con == nullptr)  return false;  // cannot happen?
4068 
4069 #ifndef PRODUCT
4070   if (C->print_intrinsics() || C->print_inlining()) {
4071     ciType* k = mirror_con->java_mirror_type();
4072     if (k) {
4073       tty->print("Inlining %s on constant Class ", vmIntrinsics::name_at(intrinsic_id()));
4074       k->print_name();
4075       tty->cr();
4076     }
4077   }
4078 #endif
4079 
4080   // Null-check the mirror, and the mirror's klass ptr (in case it is a primitive).
4081   RegionNode* region = new RegionNode(PATH_LIMIT);
4082   record_for_igvn(region);
4083   PhiNode* phi = new PhiNode(region, return_type);
4084 
4085   // The mirror will never be null of Reflection.getClassAccessFlags, however
4086   // it may be null for Class.isInstance or Class.getModifiers. Throw a NPE
4087   // if it is. See bug 4774291.
4088 
4089   // For Reflection.getClassAccessFlags(), the null check occurs in
4090   // the wrong place; see inline_unsafe_access(), above, for a similar
4091   // situation.
4092   mirror = null_check(mirror);
4093   // If mirror or obj is dead, only null-path is taken.
4094   if (stopped())  return true;
4095 
4096   if (expect_prim)  never_see_null = false;  // expect nulls (meaning prims)
4097 
4098   // Now load the mirror's klass metaobject, and null-check it.
4099   // Side-effects region with the control path if the klass is null.
4100   Node* kls = load_klass_from_mirror(mirror, never_see_null, region, _prim_path);
4101   // If kls is null, we have a primitive mirror.
4102   phi->init_req(_prim_path, prim_return_value);
4103   if (stopped()) { set_result(region, phi); return true; }
4104   bool safe_for_replace = (region->in(_prim_path) == top());
4105 
4106   Node* p;  // handy temp
4107   Node* null_ctl;
4108 
4109   // Now that we have the non-null klass, we can perform the real query.
4110   // For constant classes, the query will constant-fold in LoadNode::Value.
4111   Node* query_value = top();
4112   switch (id) {
4113   case vmIntrinsics::_isInstance:
4114     // nothing is an instance of a primitive type
4115     query_value = gen_instanceof(obj, kls, safe_for_replace);
4116     break;
4117 
4118   case vmIntrinsics::_isHidden:
4119     // (To verify this code sequence, check the asserts in JVM_IsHiddenClass.)
4120     if (generate_hidden_class_guard(kls, region) != nullptr)
4121       // A guard was added.  If the guard is taken, it was an hidden class.
4122       phi->add_req(intcon(1));
4123     // If we fall through, it's a plain class.
4124     query_value = intcon(0);
4125     break;
4126 
4127 
4128   case vmIntrinsics::_getSuperclass:
4129     // The rules here are somewhat unfortunate, but we can still do better
4130     // with random logic than with a JNI call.
4131     // Interfaces store null or Object as _super, but must report null.
4132     // Arrays store an intermediate super as _super, but must report Object.
4133     // Other types can report the actual _super.
4134     // (To verify this code sequence, check the asserts in JVM_IsInterface.)
4135     if (generate_array_guard(kls, region) != nullptr) {
4136       // A guard was added.  If the guard is taken, it was an array.
4137       phi->add_req(makecon(TypeInstPtr::make(env()->Object_klass()->java_mirror())));
4138     }
4139     // Check for interface after array since this checks AccessFlags offset into InstanceKlass.
4140     // In other words, we are accessing subtype-specific information, so we need to determine the subtype first.
4141     if (generate_interface_guard(kls, region) != nullptr) {
4142       // A guard was added.  If the guard is taken, it was an interface.
4143       phi->add_req(null());
4144     }
4145     // If we fall through, it's a plain class.  Get its _super.
4146     p = basic_plus_adr(kls, in_bytes(Klass::super_offset()));
4147     kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), p, TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
4148     null_ctl = top();
4149     kls = null_check_oop(kls, &null_ctl);
4150     if (null_ctl != top()) {
4151       // If the guard is taken, Object.superClass is null (both klass and mirror).
4152       region->add_req(null_ctl);
4153       phi   ->add_req(null());
4154     }
4155     if (!stopped()) {
4156       query_value = load_mirror_from_klass(kls);
4157     }
4158     break;
4159 
4160   default:
4161     fatal_unexpected_iid(id);
4162     break;
4163   }
4164 
4165   // Fall-through is the normal case of a query to a real class.
4166   phi->init_req(1, query_value);
4167   region->init_req(1, control());
4168 
4169   C->set_has_split_ifs(true); // Has chance for split-if optimization
4170   set_result(region, phi);
4171   return true;
4172 }
4173 
4174 //-------------------------inline_Class_cast-------------------
4175 bool LibraryCallKit::inline_Class_cast() {
4176   Node* mirror = argument(0); // Class
4177   Node* obj    = argument(1);
4178   const TypeInstPtr* mirror_con = _gvn.type(mirror)->isa_instptr();
4179   if (mirror_con == nullptr) {
4180     return false;  // dead path (mirror->is_top()).
4181   }
4182   if (obj == nullptr || obj->is_top()) {
4183     return false;  // dead path
4184   }
4185   const TypeOopPtr* tp = _gvn.type(obj)->isa_oopptr();
4186 
4187   // First, see if Class.cast() can be folded statically.
4188   // java_mirror_type() returns non-null for compile-time Class constants.
4189   ciType* tm = mirror_con->java_mirror_type();
4190   if (tm != nullptr && tm->is_klass() &&
4191       tp != nullptr) {
4192     if (!tp->is_loaded()) {
4193       // Don't use intrinsic when class is not loaded.
4194       return false;
4195     } else {
4196       int static_res = C->static_subtype_check(TypeKlassPtr::make(tm->as_klass(), Type::trust_interfaces), tp->as_klass_type());
4197       if (static_res == Compile::SSC_always_true) {
4198         // isInstance() is true - fold the code.
4199         set_result(obj);
4200         return true;
4201       } else if (static_res == Compile::SSC_always_false) {
4202         // Don't use intrinsic, have to throw ClassCastException.
4203         // If the reference is null, the non-intrinsic bytecode will
4204         // be optimized appropriately.
4205         return false;
4206       }
4207     }
4208   }
4209 
4210   // Bailout intrinsic and do normal inlining if exception path is frequent.
4211   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
4212     return false;
4213   }
4214 
4215   // Generate dynamic checks.
4216   // Class.cast() is java implementation of _checkcast bytecode.
4217   // Do checkcast (Parse::do_checkcast()) optimizations here.
4218 
4219   mirror = null_check(mirror);
4220   // If mirror is dead, only null-path is taken.
4221   if (stopped()) {
4222     return true;
4223   }
4224 
4225   // Not-subtype or the mirror's klass ptr is null (in case it is a primitive).
4226   enum { _bad_type_path = 1, _prim_path = 2, PATH_LIMIT };
4227   RegionNode* region = new RegionNode(PATH_LIMIT);
4228   record_for_igvn(region);
4229 
4230   // Now load the mirror's klass metaobject, and null-check it.
4231   // If kls is null, we have a primitive mirror and
4232   // nothing is an instance of a primitive type.
4233   Node* kls = load_klass_from_mirror(mirror, false, region, _prim_path);
4234 
4235   Node* res = top();
4236   if (!stopped()) {
4237     Node* bad_type_ctrl = top();
4238     // Do checkcast optimizations.
4239     res = gen_checkcast(obj, kls, &bad_type_ctrl);
4240     region->init_req(_bad_type_path, bad_type_ctrl);
4241   }
4242   if (region->in(_prim_path) != top() ||
4243       region->in(_bad_type_path) != top()) {
4244     // Let Interpreter throw ClassCastException.
4245     PreserveJVMState pjvms(this);
4246     set_control(_gvn.transform(region));
4247     uncommon_trap(Deoptimization::Reason_intrinsic,
4248                   Deoptimization::Action_maybe_recompile);
4249   }
4250   if (!stopped()) {
4251     set_result(res);
4252   }
4253   return true;
4254 }
4255 
4256 
4257 //--------------------------inline_native_subtype_check------------------------
4258 // This intrinsic takes the JNI calls out of the heart of
4259 // UnsafeFieldAccessorImpl.set, which improves Field.set, readObject, etc.
4260 bool LibraryCallKit::inline_native_subtype_check() {
4261   // Pull both arguments off the stack.
4262   Node* args[2];                // two java.lang.Class mirrors: superc, subc
4263   args[0] = argument(0);
4264   args[1] = argument(1);
4265   Node* klasses[2];             // corresponding Klasses: superk, subk
4266   klasses[0] = klasses[1] = top();
4267 
4268   enum {
4269     // A full decision tree on {superc is prim, subc is prim}:
4270     _prim_0_path = 1,           // {P,N} => false
4271                                 // {P,P} & superc!=subc => false
4272     _prim_same_path,            // {P,P} & superc==subc => true
4273     _prim_1_path,               // {N,P} => false
4274     _ref_subtype_path,          // {N,N} & subtype check wins => true
4275     _both_ref_path,             // {N,N} & subtype check loses => false
4276     PATH_LIMIT
4277   };
4278 
4279   RegionNode* region = new RegionNode(PATH_LIMIT);
4280   Node*       phi    = new PhiNode(region, TypeInt::BOOL);
4281   record_for_igvn(region);
4282 
4283   const TypePtr* adr_type = TypeRawPtr::BOTTOM;   // memory type of loads
4284   const TypeKlassPtr* kls_type = TypeInstKlassPtr::OBJECT_OR_NULL;
4285   int class_klass_offset = java_lang_Class::klass_offset();
4286 
4287   // First null-check both mirrors and load each mirror's klass metaobject.
4288   int which_arg;
4289   for (which_arg = 0; which_arg <= 1; which_arg++) {
4290     Node* arg = args[which_arg];
4291     arg = null_check(arg);
4292     if (stopped())  break;
4293     args[which_arg] = arg;
4294 
4295     Node* p = basic_plus_adr(arg, class_klass_offset);
4296     Node* kls = LoadKlassNode::make(_gvn, immutable_memory(), p, adr_type, kls_type);
4297     klasses[which_arg] = _gvn.transform(kls);
4298   }
4299 
4300   // Having loaded both klasses, test each for null.
4301   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
4302   for (which_arg = 0; which_arg <= 1; which_arg++) {
4303     Node* kls = klasses[which_arg];
4304     Node* null_ctl = top();
4305     kls = null_check_oop(kls, &null_ctl, never_see_null);
4306     int prim_path = (which_arg == 0 ? _prim_0_path : _prim_1_path);
4307     region->init_req(prim_path, null_ctl);
4308     if (stopped())  break;
4309     klasses[which_arg] = kls;
4310   }
4311 
4312   if (!stopped()) {
4313     // now we have two reference types, in klasses[0..1]
4314     Node* subk   = klasses[1];  // the argument to isAssignableFrom
4315     Node* superk = klasses[0];  // the receiver
4316     region->set_req(_both_ref_path, gen_subtype_check(subk, superk));
4317     // now we have a successful reference subtype check
4318     region->set_req(_ref_subtype_path, control());
4319   }
4320 
4321   // If both operands are primitive (both klasses null), then
4322   // we must return true when they are identical primitives.
4323   // It is convenient to test this after the first null klass check.
4324   set_control(region->in(_prim_0_path)); // go back to first null check
4325   if (!stopped()) {
4326     // Since superc is primitive, make a guard for the superc==subc case.
4327     Node* cmp_eq = _gvn.transform(new CmpPNode(args[0], args[1]));
4328     Node* bol_eq = _gvn.transform(new BoolNode(cmp_eq, BoolTest::eq));
4329     generate_guard(bol_eq, region, PROB_FAIR);
4330     if (region->req() == PATH_LIMIT+1) {
4331       // A guard was added.  If the added guard is taken, superc==subc.
4332       region->swap_edges(PATH_LIMIT, _prim_same_path);
4333       region->del_req(PATH_LIMIT);
4334     }
4335     region->set_req(_prim_0_path, control()); // Not equal after all.
4336   }
4337 
4338   // these are the only paths that produce 'true':
4339   phi->set_req(_prim_same_path,   intcon(1));
4340   phi->set_req(_ref_subtype_path, intcon(1));
4341 
4342   // pull together the cases:
4343   assert(region->req() == PATH_LIMIT, "sane region");
4344   for (uint i = 1; i < region->req(); i++) {
4345     Node* ctl = region->in(i);
4346     if (ctl == nullptr || ctl == top()) {
4347       region->set_req(i, top());
4348       phi   ->set_req(i, top());
4349     } else if (phi->in(i) == nullptr) {
4350       phi->set_req(i, intcon(0)); // all other paths produce 'false'
4351     }
4352   }
4353 
4354   set_control(_gvn.transform(region));
4355   set_result(_gvn.transform(phi));
4356   return true;
4357 }
4358 
4359 //---------------------generate_array_guard_common------------------------
4360 Node* LibraryCallKit::generate_array_guard_common(Node* kls, RegionNode* region,
4361                                                   bool obj_array, bool not_array, Node** obj) {
4362 
4363   if (stopped()) {
4364     return nullptr;
4365   }
4366 
4367   // If obj_array/non_array==false/false:
4368   // Branch around if the given klass is in fact an array (either obj or prim).
4369   // If obj_array/non_array==false/true:
4370   // Branch around if the given klass is not an array klass of any kind.
4371   // If obj_array/non_array==true/true:
4372   // Branch around if the kls is not an oop array (kls is int[], String, etc.)
4373   // If obj_array/non_array==true/false:
4374   // Branch around if the kls is an oop array (Object[] or subtype)
4375   //
4376   // Like generate_guard, adds a new path onto the region.
4377   jint  layout_con = 0;
4378   Node* layout_val = get_layout_helper(kls, layout_con);
4379   if (layout_val == nullptr) {
4380     bool query = (obj_array
4381                   ? Klass::layout_helper_is_objArray(layout_con)
4382                   : Klass::layout_helper_is_array(layout_con));
4383     if (query == not_array) {
4384       return nullptr;                       // never a branch
4385     } else {                             // always a branch
4386       Node* always_branch = control();
4387       if (region != nullptr)
4388         region->add_req(always_branch);
4389       set_control(top());
4390       return always_branch;
4391     }
4392   }
4393   // Now test the correct condition.
4394   jint  nval = (obj_array
4395                 ? (jint)(Klass::_lh_array_tag_type_value
4396                    <<    Klass::_lh_array_tag_shift)
4397                 : Klass::_lh_neutral_value);
4398   Node* cmp = _gvn.transform(new CmpINode(layout_val, intcon(nval)));
4399   BoolTest::mask btest = BoolTest::lt;  // correct for testing is_[obj]array
4400   // invert the test if we are looking for a non-array
4401   if (not_array)  btest = BoolTest(btest).negate();
4402   Node* bol = _gvn.transform(new BoolNode(cmp, btest));
4403   Node* ctrl = generate_fair_guard(bol, region);
4404   Node* is_array_ctrl = not_array ? control() : ctrl;
4405   if (obj != nullptr && is_array_ctrl != nullptr && is_array_ctrl != top()) {
4406     // Keep track of the fact that 'obj' is an array to prevent
4407     // array specific accesses from floating above the guard.
4408     *obj = _gvn.transform(new CastPPNode(is_array_ctrl, *obj, TypeAryPtr::BOTTOM));
4409   }
4410   return ctrl;
4411 }
4412 
4413 
4414 //-----------------------inline_native_newArray--------------------------
4415 // private static native Object java.lang.reflect.newArray(Class<?> componentType, int length);
4416 // private        native Object Unsafe.allocateUninitializedArray0(Class<?> cls, int size);
4417 bool LibraryCallKit::inline_unsafe_newArray(bool uninitialized) {
4418   Node* mirror;
4419   Node* count_val;
4420   if (uninitialized) {
4421     null_check_receiver();
4422     mirror    = argument(1);
4423     count_val = argument(2);
4424   } else {
4425     mirror    = argument(0);
4426     count_val = argument(1);
4427   }
4428 
4429   mirror = null_check(mirror);
4430   // If mirror or obj is dead, only null-path is taken.
4431   if (stopped())  return true;
4432 
4433   enum { _normal_path = 1, _slow_path = 2, PATH_LIMIT };
4434   RegionNode* result_reg = new RegionNode(PATH_LIMIT);
4435   PhiNode*    result_val = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
4436   PhiNode*    result_io  = new PhiNode(result_reg, Type::ABIO);
4437   PhiNode*    result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
4438 
4439   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
4440   Node* klass_node = load_array_klass_from_mirror(mirror, never_see_null,
4441                                                   result_reg, _slow_path);
4442   Node* normal_ctl   = control();
4443   Node* no_array_ctl = result_reg->in(_slow_path);
4444 
4445   // Generate code for the slow case.  We make a call to newArray().
4446   set_control(no_array_ctl);
4447   if (!stopped()) {
4448     // Either the input type is void.class, or else the
4449     // array klass has not yet been cached.  Either the
4450     // ensuing call will throw an exception, or else it
4451     // will cache the array klass for next time.
4452     PreserveJVMState pjvms(this);
4453     CallJavaNode* slow_call = nullptr;
4454     if (uninitialized) {
4455       // Generate optimized virtual call (holder class 'Unsafe' is final)
4456       slow_call = generate_method_call(vmIntrinsics::_allocateUninitializedArray, false, false, true);
4457     } else {
4458       slow_call = generate_method_call_static(vmIntrinsics::_newArray, true);
4459     }
4460     Node* slow_result = set_results_for_java_call(slow_call);
4461     // this->control() comes from set_results_for_java_call
4462     result_reg->set_req(_slow_path, control());
4463     result_val->set_req(_slow_path, slow_result);
4464     result_io ->set_req(_slow_path, i_o());
4465     result_mem->set_req(_slow_path, reset_memory());
4466   }
4467 
4468   set_control(normal_ctl);
4469   if (!stopped()) {
4470     // Normal case:  The array type has been cached in the java.lang.Class.
4471     // The following call works fine even if the array type is polymorphic.
4472     // It could be a dynamic mix of int[], boolean[], Object[], etc.
4473     Node* obj = new_array(klass_node, count_val, 0);  // no arguments to push
4474     result_reg->init_req(_normal_path, control());
4475     result_val->init_req(_normal_path, obj);
4476     result_io ->init_req(_normal_path, i_o());
4477     result_mem->init_req(_normal_path, reset_memory());
4478 
4479     if (uninitialized) {
4480       // Mark the allocation so that zeroing is skipped
4481       AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(obj);
4482       alloc->maybe_set_complete(&_gvn);
4483     }
4484   }
4485 
4486   // Return the combined state.
4487   set_i_o(        _gvn.transform(result_io)  );
4488   set_all_memory( _gvn.transform(result_mem));
4489 
4490   C->set_has_split_ifs(true); // Has chance for split-if optimization
4491   set_result(result_reg, result_val);
4492   return true;
4493 }
4494 
4495 //----------------------inline_native_getLength--------------------------
4496 // public static native int java.lang.reflect.Array.getLength(Object array);
4497 bool LibraryCallKit::inline_native_getLength() {
4498   if (too_many_traps(Deoptimization::Reason_intrinsic))  return false;
4499 
4500   Node* array = null_check(argument(0));
4501   // If array is dead, only null-path is taken.
4502   if (stopped())  return true;
4503 
4504   // Deoptimize if it is a non-array.
4505   Node* non_array = generate_non_array_guard(load_object_klass(array), nullptr, &array);
4506 
4507   if (non_array != nullptr) {
4508     PreserveJVMState pjvms(this);
4509     set_control(non_array);
4510     uncommon_trap(Deoptimization::Reason_intrinsic,
4511                   Deoptimization::Action_maybe_recompile);
4512   }
4513 
4514   // If control is dead, only non-array-path is taken.
4515   if (stopped())  return true;
4516 
4517   // The works fine even if the array type is polymorphic.
4518   // It could be a dynamic mix of int[], boolean[], Object[], etc.
4519   Node* result = load_array_length(array);
4520 
4521   C->set_has_split_ifs(true);  // Has chance for split-if optimization
4522   set_result(result);
4523   return true;
4524 }
4525 
4526 //------------------------inline_array_copyOf----------------------------
4527 // public static <T,U> T[] java.util.Arrays.copyOf(     U[] original, int newLength,         Class<? extends T[]> newType);
4528 // public static <T,U> T[] java.util.Arrays.copyOfRange(U[] original, int from,      int to, Class<? extends T[]> newType);
4529 bool LibraryCallKit::inline_array_copyOf(bool is_copyOfRange) {
4530   if (too_many_traps(Deoptimization::Reason_intrinsic))  return false;
4531 
4532   // Get the arguments.
4533   Node* original          = argument(0);
4534   Node* start             = is_copyOfRange? argument(1): intcon(0);
4535   Node* end               = is_copyOfRange? argument(2): argument(1);
4536   Node* array_type_mirror = is_copyOfRange? argument(3): argument(2);
4537 
4538   Node* newcopy = nullptr;
4539 
4540   // Set the original stack and the reexecute bit for the interpreter to reexecute
4541   // the bytecode that invokes Arrays.copyOf if deoptimization happens.
4542   { PreserveReexecuteState preexecs(this);
4543     jvms()->set_should_reexecute(true);
4544 
4545     array_type_mirror = null_check(array_type_mirror);
4546     original          = null_check(original);
4547 
4548     // Check if a null path was taken unconditionally.
4549     if (stopped())  return true;
4550 
4551     Node* orig_length = load_array_length(original);
4552 
4553     Node* klass_node = load_klass_from_mirror(array_type_mirror, false, nullptr, 0);
4554     klass_node = null_check(klass_node);
4555 
4556     RegionNode* bailout = new RegionNode(1);
4557     record_for_igvn(bailout);
4558 
4559     // Despite the generic type of Arrays.copyOf, the mirror might be int, int[], etc.
4560     // Bail out if that is so.
4561     Node* not_objArray = generate_non_objArray_guard(klass_node, bailout);
4562     if (not_objArray != nullptr) {
4563       // Improve the klass node's type from the new optimistic assumption:
4564       ciKlass* ak = ciArrayKlass::make(env()->Object_klass());
4565       const Type* akls = TypeKlassPtr::make(TypePtr::NotNull, ak, 0/*offset*/);
4566       Node* cast = new CastPPNode(control(), klass_node, akls);
4567       klass_node = _gvn.transform(cast);
4568     }
4569 
4570     // Bail out if either start or end is negative.
4571     generate_negative_guard(start, bailout, &start);
4572     generate_negative_guard(end,   bailout, &end);
4573 
4574     Node* length = end;
4575     if (_gvn.type(start) != TypeInt::ZERO) {
4576       length = _gvn.transform(new SubINode(end, start));
4577     }
4578 
4579     // Bail out if length is negative (i.e., if start > end).
4580     // Without this the new_array would throw
4581     // NegativeArraySizeException but IllegalArgumentException is what
4582     // should be thrown
4583     generate_negative_guard(length, bailout, &length);
4584 
4585     // Bail out if start is larger than the original length
4586     Node* orig_tail = _gvn.transform(new SubINode(orig_length, start));
4587     generate_negative_guard(orig_tail, bailout, &orig_tail);
4588 
4589     if (bailout->req() > 1) {
4590       PreserveJVMState pjvms(this);
4591       set_control(_gvn.transform(bailout));
4592       uncommon_trap(Deoptimization::Reason_intrinsic,
4593                     Deoptimization::Action_maybe_recompile);
4594     }
4595 
4596     if (!stopped()) {
4597       // How many elements will we copy from the original?
4598       // The answer is MinI(orig_tail, length).
4599       Node* moved = _gvn.transform(new MinINode(orig_tail, length));
4600 
4601       // Generate a direct call to the right arraycopy function(s).
4602       // We know the copy is disjoint but we might not know if the
4603       // oop stores need checking.
4604       // Extreme case:  Arrays.copyOf((Integer[])x, 10, String[].class).
4605       // This will fail a store-check if x contains any non-nulls.
4606 
4607       // ArrayCopyNode:Ideal may transform the ArrayCopyNode to
4608       // loads/stores but it is legal only if we're sure the
4609       // Arrays.copyOf would succeed. So we need all input arguments
4610       // to the copyOf to be validated, including that the copy to the
4611       // new array won't trigger an ArrayStoreException. That subtype
4612       // check can be optimized if we know something on the type of
4613       // the input array from type speculation.
4614       if (_gvn.type(klass_node)->singleton()) {
4615         const TypeKlassPtr* subk = _gvn.type(load_object_klass(original))->is_klassptr();
4616         const TypeKlassPtr* superk = _gvn.type(klass_node)->is_klassptr();
4617 
4618         int test = C->static_subtype_check(superk, subk);
4619         if (test != Compile::SSC_always_true && test != Compile::SSC_always_false) {
4620           const TypeOopPtr* t_original = _gvn.type(original)->is_oopptr();
4621           if (t_original->speculative_type() != nullptr) {
4622             original = maybe_cast_profiled_obj(original, t_original->speculative_type(), true);
4623           }
4624         }
4625       }
4626 
4627       bool validated = false;
4628       // Reason_class_check rather than Reason_intrinsic because we
4629       // want to intrinsify even if this traps.
4630       if (!too_many_traps(Deoptimization::Reason_class_check)) {
4631         Node* not_subtype_ctrl = gen_subtype_check(original, klass_node);
4632 
4633         if (not_subtype_ctrl != top()) {
4634           PreserveJVMState pjvms(this);
4635           set_control(not_subtype_ctrl);
4636           uncommon_trap(Deoptimization::Reason_class_check,
4637                         Deoptimization::Action_make_not_entrant);
4638           assert(stopped(), "Should be stopped");
4639         }
4640         validated = true;
4641       }
4642 
4643       if (!stopped()) {
4644         newcopy = new_array(klass_node, length, 0);  // no arguments to push
4645 
4646         ArrayCopyNode* ac = ArrayCopyNode::make(this, true, original, start, newcopy, intcon(0), moved, true, true,
4647                                                 load_object_klass(original), klass_node);
4648         if (!is_copyOfRange) {
4649           ac->set_copyof(validated);
4650         } else {
4651           ac->set_copyofrange(validated);
4652         }
4653         Node* n = _gvn.transform(ac);
4654         if (n == ac) {
4655           ac->connect_outputs(this);
4656         } else {
4657           assert(validated, "shouldn't transform if all arguments not validated");
4658           set_all_memory(n);
4659         }
4660       }
4661     }
4662   } // original reexecute is set back here
4663 
4664   C->set_has_split_ifs(true); // Has chance for split-if optimization
4665   if (!stopped()) {
4666     set_result(newcopy);
4667   }
4668   return true;
4669 }
4670 
4671 
4672 //----------------------generate_virtual_guard---------------------------
4673 // Helper for hashCode and clone.  Peeks inside the vtable to avoid a call.
4674 Node* LibraryCallKit::generate_virtual_guard(Node* obj_klass,
4675                                              RegionNode* slow_region) {
4676   ciMethod* method = callee();
4677   int vtable_index = method->vtable_index();
4678   assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index,
4679          "bad index %d", vtable_index);
4680   // Get the Method* out of the appropriate vtable entry.
4681   int entry_offset  = in_bytes(Klass::vtable_start_offset()) +
4682                      vtable_index*vtableEntry::size_in_bytes() +
4683                      in_bytes(vtableEntry::method_offset());
4684   Node* entry_addr  = basic_plus_adr(obj_klass, entry_offset);
4685   Node* target_call = make_load(nullptr, entry_addr, TypePtr::NOTNULL, T_ADDRESS, MemNode::unordered);
4686 
4687   // Compare the target method with the expected method (e.g., Object.hashCode).
4688   const TypePtr* native_call_addr = TypeMetadataPtr::make(method);
4689 
4690   Node* native_call = makecon(native_call_addr);
4691   Node* chk_native  = _gvn.transform(new CmpPNode(target_call, native_call));
4692   Node* test_native = _gvn.transform(new BoolNode(chk_native, BoolTest::ne));
4693 
4694   return generate_slow_guard(test_native, slow_region);
4695 }
4696 
4697 //-----------------------generate_method_call----------------------------
4698 // Use generate_method_call to make a slow-call to the real
4699 // method if the fast path fails.  An alternative would be to
4700 // use a stub like OptoRuntime::slow_arraycopy_Java.
4701 // This only works for expanding the current library call,
4702 // not another intrinsic.  (E.g., don't use this for making an
4703 // arraycopy call inside of the copyOf intrinsic.)
4704 CallJavaNode*
4705 LibraryCallKit::generate_method_call(vmIntrinsicID method_id, bool is_virtual, bool is_static, bool res_not_null) {
4706   // When compiling the intrinsic method itself, do not use this technique.
4707   guarantee(callee() != C->method(), "cannot make slow-call to self");
4708 
4709   ciMethod* method = callee();
4710   // ensure the JVMS we have will be correct for this call
4711   guarantee(method_id == method->intrinsic_id(), "must match");
4712 
4713   const TypeFunc* tf = TypeFunc::make(method);
4714   if (res_not_null) {
4715     assert(tf->return_type() == T_OBJECT, "");
4716     const TypeTuple* range = tf->range();
4717     const Type** fields = TypeTuple::fields(range->cnt());
4718     fields[TypeFunc::Parms] = range->field_at(TypeFunc::Parms)->filter_speculative(TypePtr::NOTNULL);
4719     const TypeTuple* new_range = TypeTuple::make(range->cnt(), fields);
4720     tf = TypeFunc::make(tf->domain(), new_range);
4721   }
4722   CallJavaNode* slow_call;
4723   if (is_static) {
4724     assert(!is_virtual, "");
4725     slow_call = new CallStaticJavaNode(C, tf,
4726                            SharedRuntime::get_resolve_static_call_stub(), method);
4727   } else if (is_virtual) {
4728     assert(!gvn().type(argument(0))->maybe_null(), "should not be null");
4729     int vtable_index = Method::invalid_vtable_index;
4730     if (UseInlineCaches) {
4731       // Suppress the vtable call
4732     } else {
4733       // hashCode and clone are not a miranda methods,
4734       // so the vtable index is fixed.
4735       // No need to use the linkResolver to get it.
4736        vtable_index = method->vtable_index();
4737        assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index,
4738               "bad index %d", vtable_index);
4739     }
4740     slow_call = new CallDynamicJavaNode(tf,
4741                           SharedRuntime::get_resolve_virtual_call_stub(),
4742                           method, vtable_index);
4743   } else {  // neither virtual nor static:  opt_virtual
4744     assert(!gvn().type(argument(0))->maybe_null(), "should not be null");
4745     slow_call = new CallStaticJavaNode(C, tf,
4746                                 SharedRuntime::get_resolve_opt_virtual_call_stub(), method);
4747     slow_call->set_optimized_virtual(true);
4748   }
4749   if (CallGenerator::is_inlined_method_handle_intrinsic(this->method(), bci(), callee())) {
4750     // To be able to issue a direct call (optimized virtual or virtual)
4751     // and skip a call to MH.linkTo*/invokeBasic adapter, additional information
4752     // about the method being invoked should be attached to the call site to
4753     // make resolution logic work (see SharedRuntime::resolve_{virtual,opt_virtual}_call_C).
4754     slow_call->set_override_symbolic_info(true);
4755   }
4756   set_arguments_for_java_call(slow_call);
4757   set_edges_for_java_call(slow_call);
4758   return slow_call;
4759 }
4760 
4761 
4762 /**
4763  * Build special case code for calls to hashCode on an object. This call may
4764  * be virtual (invokevirtual) or bound (invokespecial). For each case we generate
4765  * slightly different code.
4766  */
4767 bool LibraryCallKit::inline_native_hashcode(bool is_virtual, bool is_static) {
4768   assert(is_static == callee()->is_static(), "correct intrinsic selection");
4769   assert(!(is_virtual && is_static), "either virtual, special, or static");
4770 
4771   enum { _slow_path = 1, _fast_path, _null_path, PATH_LIMIT };
4772 
4773   RegionNode* result_reg = new RegionNode(PATH_LIMIT);
4774   PhiNode*    result_val = new PhiNode(result_reg, TypeInt::INT);
4775   PhiNode*    result_io  = new PhiNode(result_reg, Type::ABIO);
4776   PhiNode*    result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
4777   Node* obj = nullptr;
4778   if (!is_static) {
4779     // Check for hashing null object
4780     obj = null_check_receiver();
4781     if (stopped())  return true;        // unconditionally null
4782     result_reg->init_req(_null_path, top());
4783     result_val->init_req(_null_path, top());
4784   } else {
4785     // Do a null check, and return zero if null.
4786     // System.identityHashCode(null) == 0
4787     obj = argument(0);
4788     Node* null_ctl = top();
4789     obj = null_check_oop(obj, &null_ctl);
4790     result_reg->init_req(_null_path, null_ctl);
4791     result_val->init_req(_null_path, _gvn.intcon(0));
4792   }
4793 
4794   // Unconditionally null?  Then return right away.
4795   if (stopped()) {
4796     set_control( result_reg->in(_null_path));
4797     if (!stopped())
4798       set_result(result_val->in(_null_path));
4799     return true;
4800   }
4801 
4802   // We only go to the fast case code if we pass a number of guards.  The
4803   // paths which do not pass are accumulated in the slow_region.
4804   RegionNode* slow_region = new RegionNode(1);
4805   record_for_igvn(slow_region);
4806 
4807   // If this is a virtual call, we generate a funny guard.  We pull out
4808   // the vtable entry corresponding to hashCode() from the target object.
4809   // If the target method which we are calling happens to be the native
4810   // Object hashCode() method, we pass the guard.  We do not need this
4811   // guard for non-virtual calls -- the caller is known to be the native
4812   // Object hashCode().
4813   if (is_virtual) {
4814     // After null check, get the object's klass.
4815     Node* obj_klass = load_object_klass(obj);
4816     generate_virtual_guard(obj_klass, slow_region);
4817   }
4818 
4819   // Get the header out of the object, use LoadMarkNode when available
4820   Node* header_addr = basic_plus_adr(obj, oopDesc::mark_offset_in_bytes());
4821   // The control of the load must be null. Otherwise, the load can move before
4822   // the null check after castPP removal.
4823   Node* no_ctrl = nullptr;
4824   Node* header = make_load(no_ctrl, header_addr, TypeX_X, TypeX_X->basic_type(), MemNode::unordered);
4825 
4826   if (!UseObjectMonitorTable) {
4827     // Test the header to see if it is safe to read w.r.t. locking.
4828     Node *lock_mask      = _gvn.MakeConX(markWord::lock_mask_in_place);
4829     Node *lmasked_header = _gvn.transform(new AndXNode(header, lock_mask));
4830     Node *monitor_val   = _gvn.MakeConX(markWord::monitor_value);
4831     Node *chk_monitor   = _gvn.transform(new CmpXNode(lmasked_header, monitor_val));
4832     Node *test_monitor  = _gvn.transform(new BoolNode(chk_monitor, BoolTest::eq));
4833 
4834     generate_slow_guard(test_monitor, slow_region);
4835   }
4836 
4837   // Get the hash value and check to see that it has been properly assigned.
4838   // We depend on hash_mask being at most 32 bits and avoid the use of
4839   // hash_mask_in_place because it could be larger than 32 bits in a 64-bit
4840   // vm: see markWord.hpp.
4841   Node *hash_mask      = _gvn.intcon(markWord::hash_mask);
4842   Node *hash_shift     = _gvn.intcon(markWord::hash_shift);
4843   Node *hshifted_header= _gvn.transform(new URShiftXNode(header, hash_shift));
4844   // This hack lets the hash bits live anywhere in the mark object now, as long
4845   // as the shift drops the relevant bits into the low 32 bits.  Note that
4846   // Java spec says that HashCode is an int so there's no point in capturing
4847   // an 'X'-sized hashcode (32 in 32-bit build or 64 in 64-bit build).
4848   hshifted_header      = ConvX2I(hshifted_header);
4849   Node *hash_val       = _gvn.transform(new AndINode(hshifted_header, hash_mask));
4850 
4851   Node *no_hash_val    = _gvn.intcon(markWord::no_hash);
4852   Node *chk_assigned   = _gvn.transform(new CmpINode( hash_val, no_hash_val));
4853   Node *test_assigned  = _gvn.transform(new BoolNode( chk_assigned, BoolTest::eq));
4854 
4855   generate_slow_guard(test_assigned, slow_region);
4856 
4857   Node* init_mem = reset_memory();
4858   // fill in the rest of the null path:
4859   result_io ->init_req(_null_path, i_o());
4860   result_mem->init_req(_null_path, init_mem);
4861 
4862   result_val->init_req(_fast_path, hash_val);
4863   result_reg->init_req(_fast_path, control());
4864   result_io ->init_req(_fast_path, i_o());
4865   result_mem->init_req(_fast_path, init_mem);
4866 
4867   // Generate code for the slow case.  We make a call to hashCode().
4868   set_control(_gvn.transform(slow_region));
4869   if (!stopped()) {
4870     // No need for PreserveJVMState, because we're using up the present state.
4871     set_all_memory(init_mem);
4872     vmIntrinsics::ID hashCode_id = is_static ? vmIntrinsics::_identityHashCode : vmIntrinsics::_hashCode;
4873     CallJavaNode* slow_call = generate_method_call(hashCode_id, is_virtual, is_static, false);
4874     Node* slow_result = set_results_for_java_call(slow_call);
4875     // this->control() comes from set_results_for_java_call
4876     result_reg->init_req(_slow_path, control());
4877     result_val->init_req(_slow_path, slow_result);
4878     result_io  ->set_req(_slow_path, i_o());
4879     result_mem ->set_req(_slow_path, reset_memory());
4880   }
4881 
4882   // Return the combined state.
4883   set_i_o(        _gvn.transform(result_io)  );
4884   set_all_memory( _gvn.transform(result_mem));
4885 
4886   set_result(result_reg, result_val);
4887   return true;
4888 }
4889 
4890 //---------------------------inline_native_getClass----------------------------
4891 // public final native Class<?> java.lang.Object.getClass();
4892 //
4893 // Build special case code for calls to getClass on an object.
4894 bool LibraryCallKit::inline_native_getClass() {
4895   Node* obj = null_check_receiver();
4896   if (stopped())  return true;
4897   set_result(load_mirror_from_klass(load_object_klass(obj)));
4898   return true;
4899 }
4900 
4901 //-----------------inline_native_Reflection_getCallerClass---------------------
4902 // public static native Class<?> sun.reflect.Reflection.getCallerClass();
4903 //
4904 // In the presence of deep enough inlining, getCallerClass() becomes a no-op.
4905 //
4906 // NOTE: This code must perform the same logic as JVM_GetCallerClass
4907 // in that it must skip particular security frames and checks for
4908 // caller sensitive methods.
4909 bool LibraryCallKit::inline_native_Reflection_getCallerClass() {
4910 #ifndef PRODUCT
4911   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
4912     tty->print_cr("Attempting to inline sun.reflect.Reflection.getCallerClass");
4913   }
4914 #endif
4915 
4916   if (!jvms()->has_method()) {
4917 #ifndef PRODUCT
4918     if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
4919       tty->print_cr("  Bailing out because intrinsic was inlined at top level");
4920     }
4921 #endif
4922     return false;
4923   }
4924 
4925   // Walk back up the JVM state to find the caller at the required
4926   // depth.
4927   JVMState* caller_jvms = jvms();
4928 
4929   // Cf. JVM_GetCallerClass
4930   // NOTE: Start the loop at depth 1 because the current JVM state does
4931   // not include the Reflection.getCallerClass() frame.
4932   for (int n = 1; caller_jvms != nullptr; caller_jvms = caller_jvms->caller(), n++) {
4933     ciMethod* m = caller_jvms->method();
4934     switch (n) {
4935     case 0:
4936       fatal("current JVM state does not include the Reflection.getCallerClass frame");
4937       break;
4938     case 1:
4939       // Frame 0 and 1 must be caller sensitive (see JVM_GetCallerClass).
4940       if (!m->caller_sensitive()) {
4941 #ifndef PRODUCT
4942         if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
4943           tty->print_cr("  Bailing out: CallerSensitive annotation expected at frame %d", n);
4944         }
4945 #endif
4946         return false;  // bail-out; let JVM_GetCallerClass do the work
4947       }
4948       break;
4949     default:
4950       if (!m->is_ignored_by_security_stack_walk()) {
4951         // We have reached the desired frame; return the holder class.
4952         // Acquire method holder as java.lang.Class and push as constant.
4953         ciInstanceKlass* caller_klass = caller_jvms->method()->holder();
4954         ciInstance* caller_mirror = caller_klass->java_mirror();
4955         set_result(makecon(TypeInstPtr::make(caller_mirror)));
4956 
4957 #ifndef PRODUCT
4958         if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
4959           tty->print_cr("  Succeeded: caller = %d) %s.%s, JVMS depth = %d", n, caller_klass->name()->as_utf8(), caller_jvms->method()->name()->as_utf8(), jvms()->depth());
4960           tty->print_cr("  JVM state at this point:");
4961           for (int i = jvms()->depth(), n = 1; i >= 1; i--, n++) {
4962             ciMethod* m = jvms()->of_depth(i)->method();
4963             tty->print_cr("   %d) %s.%s", n, m->holder()->name()->as_utf8(), m->name()->as_utf8());
4964           }
4965         }
4966 #endif
4967         return true;
4968       }
4969       break;
4970     }
4971   }
4972 
4973 #ifndef PRODUCT
4974   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
4975     tty->print_cr("  Bailing out because caller depth exceeded inlining depth = %d", jvms()->depth());
4976     tty->print_cr("  JVM state at this point:");
4977     for (int i = jvms()->depth(), n = 1; i >= 1; i--, n++) {
4978       ciMethod* m = jvms()->of_depth(i)->method();
4979       tty->print_cr("   %d) %s.%s", n, m->holder()->name()->as_utf8(), m->name()->as_utf8());
4980     }
4981   }
4982 #endif
4983 
4984   return false;  // bail-out; let JVM_GetCallerClass do the work
4985 }
4986 
4987 bool LibraryCallKit::inline_fp_conversions(vmIntrinsics::ID id) {
4988   Node* arg = argument(0);
4989   Node* result = nullptr;
4990 
4991   switch (id) {
4992   case vmIntrinsics::_floatToRawIntBits:    result = new MoveF2INode(arg);  break;
4993   case vmIntrinsics::_intBitsToFloat:       result = new MoveI2FNode(arg);  break;
4994   case vmIntrinsics::_doubleToRawLongBits:  result = new MoveD2LNode(arg);  break;
4995   case vmIntrinsics::_longBitsToDouble:     result = new MoveL2DNode(arg);  break;
4996   case vmIntrinsics::_floatToFloat16:       result = new ConvF2HFNode(arg); break;
4997   case vmIntrinsics::_float16ToFloat:       result = new ConvHF2FNode(arg); break;
4998 
4999   case vmIntrinsics::_doubleToLongBits: {
5000     // two paths (plus control) merge in a wood
5001     RegionNode *r = new RegionNode(3);
5002     Node *phi = new PhiNode(r, TypeLong::LONG);
5003 
5004     Node *cmpisnan = _gvn.transform(new CmpDNode(arg, arg));
5005     // Build the boolean node
5006     Node *bolisnan = _gvn.transform(new BoolNode(cmpisnan, BoolTest::ne));
5007 
5008     // Branch either way.
5009     // NaN case is less traveled, which makes all the difference.
5010     IfNode *ifisnan = create_and_xform_if(control(), bolisnan, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
5011     Node *opt_isnan = _gvn.transform(ifisnan);
5012     assert( opt_isnan->is_If(), "Expect an IfNode");
5013     IfNode *opt_ifisnan = (IfNode*)opt_isnan;
5014     Node *iftrue = _gvn.transform(new IfTrueNode(opt_ifisnan));
5015 
5016     set_control(iftrue);
5017 
5018     static const jlong nan_bits = CONST64(0x7ff8000000000000);
5019     Node *slow_result = longcon(nan_bits); // return NaN
5020     phi->init_req(1, _gvn.transform( slow_result ));
5021     r->init_req(1, iftrue);
5022 
5023     // Else fall through
5024     Node *iffalse = _gvn.transform(new IfFalseNode(opt_ifisnan));
5025     set_control(iffalse);
5026 
5027     phi->init_req(2, _gvn.transform(new MoveD2LNode(arg)));
5028     r->init_req(2, iffalse);
5029 
5030     // Post merge
5031     set_control(_gvn.transform(r));
5032     record_for_igvn(r);
5033 
5034     C->set_has_split_ifs(true); // Has chance for split-if optimization
5035     result = phi;
5036     assert(result->bottom_type()->isa_long(), "must be");
5037     break;
5038   }
5039 
5040   case vmIntrinsics::_floatToIntBits: {
5041     // two paths (plus control) merge in a wood
5042     RegionNode *r = new RegionNode(3);
5043     Node *phi = new PhiNode(r, TypeInt::INT);
5044 
5045     Node *cmpisnan = _gvn.transform(new CmpFNode(arg, arg));
5046     // Build the boolean node
5047     Node *bolisnan = _gvn.transform(new BoolNode(cmpisnan, BoolTest::ne));
5048 
5049     // Branch either way.
5050     // NaN case is less traveled, which makes all the difference.
5051     IfNode *ifisnan = create_and_xform_if(control(), bolisnan, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
5052     Node *opt_isnan = _gvn.transform(ifisnan);
5053     assert( opt_isnan->is_If(), "Expect an IfNode");
5054     IfNode *opt_ifisnan = (IfNode*)opt_isnan;
5055     Node *iftrue = _gvn.transform(new IfTrueNode(opt_ifisnan));
5056 
5057     set_control(iftrue);
5058 
5059     static const jint nan_bits = 0x7fc00000;
5060     Node *slow_result = makecon(TypeInt::make(nan_bits)); // return NaN
5061     phi->init_req(1, _gvn.transform( slow_result ));
5062     r->init_req(1, iftrue);
5063 
5064     // Else fall through
5065     Node *iffalse = _gvn.transform(new IfFalseNode(opt_ifisnan));
5066     set_control(iffalse);
5067 
5068     phi->init_req(2, _gvn.transform(new MoveF2INode(arg)));
5069     r->init_req(2, iffalse);
5070 
5071     // Post merge
5072     set_control(_gvn.transform(r));
5073     record_for_igvn(r);
5074 
5075     C->set_has_split_ifs(true); // Has chance for split-if optimization
5076     result = phi;
5077     assert(result->bottom_type()->isa_int(), "must be");
5078     break;
5079   }
5080 
5081   default:
5082     fatal_unexpected_iid(id);
5083     break;
5084   }
5085   set_result(_gvn.transform(result));
5086   return true;
5087 }
5088 
5089 bool LibraryCallKit::inline_fp_range_check(vmIntrinsics::ID id) {
5090   Node* arg = argument(0);
5091   Node* result = nullptr;
5092 
5093   switch (id) {
5094   case vmIntrinsics::_floatIsInfinite:
5095     result = new IsInfiniteFNode(arg);
5096     break;
5097   case vmIntrinsics::_floatIsFinite:
5098     result = new IsFiniteFNode(arg);
5099     break;
5100   case vmIntrinsics::_doubleIsInfinite:
5101     result = new IsInfiniteDNode(arg);
5102     break;
5103   case vmIntrinsics::_doubleIsFinite:
5104     result = new IsFiniteDNode(arg);
5105     break;
5106   default:
5107     fatal_unexpected_iid(id);
5108     break;
5109   }
5110   set_result(_gvn.transform(result));
5111   return true;
5112 }
5113 
5114 //----------------------inline_unsafe_copyMemory-------------------------
5115 // public native void Unsafe.copyMemory0(Object srcBase, long srcOffset, Object destBase, long destOffset, long bytes);
5116 
5117 static bool has_wide_mem(PhaseGVN& gvn, Node* addr, Node* base) {
5118   const TypeAryPtr* addr_t = gvn.type(addr)->isa_aryptr();
5119   const Type*       base_t = gvn.type(base);
5120 
5121   bool in_native = (base_t == TypePtr::NULL_PTR);
5122   bool in_heap   = !TypePtr::NULL_PTR->higher_equal(base_t);
5123   bool is_mixed  = !in_heap && !in_native;
5124 
5125   if (is_mixed) {
5126     return true; // mixed accesses can touch both on-heap and off-heap memory
5127   }
5128   if (in_heap) {
5129     bool is_prim_array = (addr_t != nullptr) && (addr_t->elem() != Type::BOTTOM);
5130     if (!is_prim_array) {
5131       // Though Unsafe.copyMemory() ensures at runtime for on-heap accesses that base is a primitive array,
5132       // there's not enough type information available to determine proper memory slice for it.
5133       return true;
5134     }
5135   }
5136   return false;
5137 }
5138 
5139 bool LibraryCallKit::inline_unsafe_copyMemory() {
5140   if (callee()->is_static())  return false;  // caller must have the capability!
5141   null_check_receiver();  // null-check receiver
5142   if (stopped())  return true;
5143 
5144   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
5145 
5146   Node* src_base =         argument(1);  // type: oop
5147   Node* src_off  = ConvL2X(argument(2)); // type: long
5148   Node* dst_base =         argument(4);  // type: oop
5149   Node* dst_off  = ConvL2X(argument(5)); // type: long
5150   Node* size     = ConvL2X(argument(7)); // type: long
5151 
5152   assert(Unsafe_field_offset_to_byte_offset(11) == 11,
5153          "fieldOffset must be byte-scaled");
5154 
5155   Node* src_addr = make_unsafe_address(src_base, src_off);
5156   Node* dst_addr = make_unsafe_address(dst_base, dst_off);
5157 
5158   Node* thread = _gvn.transform(new ThreadLocalNode());
5159   Node* doing_unsafe_access_addr = basic_plus_adr(top(), thread, in_bytes(JavaThread::doing_unsafe_access_offset()));
5160   BasicType doing_unsafe_access_bt = T_BYTE;
5161   assert((sizeof(bool) * CHAR_BIT) == 8, "not implemented");
5162 
5163   // update volatile field
5164   store_to_memory(control(), doing_unsafe_access_addr, intcon(1), doing_unsafe_access_bt, MemNode::unordered);
5165 
5166   int flags = RC_LEAF | RC_NO_FP;
5167 
5168   const TypePtr* dst_type = TypePtr::BOTTOM;
5169 
5170   // Adjust memory effects of the runtime call based on input values.
5171   if (!has_wide_mem(_gvn, src_addr, src_base) &&
5172       !has_wide_mem(_gvn, dst_addr, dst_base)) {
5173     dst_type = _gvn.type(dst_addr)->is_ptr(); // narrow out memory
5174 
5175     const TypePtr* src_type = _gvn.type(src_addr)->is_ptr();
5176     if (C->get_alias_index(src_type) == C->get_alias_index(dst_type)) {
5177       flags |= RC_NARROW_MEM; // narrow in memory
5178     }
5179   }
5180 
5181   // Call it.  Note that the length argument is not scaled.
5182   make_runtime_call(flags,
5183                     OptoRuntime::fast_arraycopy_Type(),
5184                     StubRoutines::unsafe_arraycopy(),
5185                     "unsafe_arraycopy",
5186                     dst_type,
5187                     src_addr, dst_addr, size XTOP);
5188 
5189   store_to_memory(control(), doing_unsafe_access_addr, intcon(0), doing_unsafe_access_bt, MemNode::unordered);
5190 
5191   return true;
5192 }
5193 
5194 // unsafe_setmemory(void *base, ulong offset, size_t length, char fill_value);
5195 // Fill 'length' bytes starting from 'base[offset]' with 'fill_value'
5196 bool LibraryCallKit::inline_unsafe_setMemory() {
5197   if (callee()->is_static())  return false;  // caller must have the capability!
5198   null_check_receiver();  // null-check receiver
5199   if (stopped())  return true;
5200 
5201   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
5202 
5203   Node* dst_base =         argument(1);  // type: oop
5204   Node* dst_off  = ConvL2X(argument(2)); // type: long
5205   Node* size     = ConvL2X(argument(4)); // type: long
5206   Node* byte     =         argument(6);  // type: byte
5207 
5208   assert(Unsafe_field_offset_to_byte_offset(11) == 11,
5209          "fieldOffset must be byte-scaled");
5210 
5211   Node* dst_addr = make_unsafe_address(dst_base, dst_off);
5212 
5213   Node* thread = _gvn.transform(new ThreadLocalNode());
5214   Node* doing_unsafe_access_addr = basic_plus_adr(top(), thread, in_bytes(JavaThread::doing_unsafe_access_offset()));
5215   BasicType doing_unsafe_access_bt = T_BYTE;
5216   assert((sizeof(bool) * CHAR_BIT) == 8, "not implemented");
5217 
5218   // update volatile field
5219   store_to_memory(control(), doing_unsafe_access_addr, intcon(1), doing_unsafe_access_bt, MemNode::unordered);
5220 
5221   int flags = RC_LEAF | RC_NO_FP;
5222 
5223   const TypePtr* dst_type = TypePtr::BOTTOM;
5224 
5225   // Adjust memory effects of the runtime call based on input values.
5226   if (!has_wide_mem(_gvn, dst_addr, dst_base)) {
5227     dst_type = _gvn.type(dst_addr)->is_ptr(); // narrow out memory
5228 
5229     flags |= RC_NARROW_MEM; // narrow in memory
5230   }
5231 
5232   // Call it.  Note that the length argument is not scaled.
5233   make_runtime_call(flags,
5234                     OptoRuntime::unsafe_setmemory_Type(),
5235                     StubRoutines::unsafe_setmemory(),
5236                     "unsafe_setmemory",
5237                     dst_type,
5238                     dst_addr, size XTOP, byte);
5239 
5240   store_to_memory(control(), doing_unsafe_access_addr, intcon(0), doing_unsafe_access_bt, MemNode::unordered);
5241 
5242   return true;
5243 }
5244 
5245 #undef XTOP
5246 
5247 //------------------------clone_coping-----------------------------------
5248 // Helper function for inline_native_clone.
5249 void LibraryCallKit::copy_to_clone(Node* obj, Node* alloc_obj, Node* obj_size, bool is_array) {
5250   assert(obj_size != nullptr, "");
5251   Node* raw_obj = alloc_obj->in(1);
5252   assert(alloc_obj->is_CheckCastPP() && raw_obj->is_Proj() && raw_obj->in(0)->is_Allocate(), "");
5253 
5254   AllocateNode* alloc = nullptr;
5255   if (ReduceBulkZeroing &&
5256       // If we are implementing an array clone without knowing its source type
5257       // (can happen when compiling the array-guarded branch of a reflective
5258       // Object.clone() invocation), initialize the array within the allocation.
5259       // This is needed because some GCs (e.g. ZGC) might fall back in this case
5260       // to a runtime clone call that assumes fully initialized source arrays.
5261       (!is_array || obj->get_ptr_type()->isa_aryptr() != nullptr)) {
5262     // We will be completely responsible for initializing this object -
5263     // mark Initialize node as complete.
5264     alloc = AllocateNode::Ideal_allocation(alloc_obj);
5265     // The object was just allocated - there should be no any stores!
5266     guarantee(alloc != nullptr && alloc->maybe_set_complete(&_gvn), "");
5267     // Mark as complete_with_arraycopy so that on AllocateNode
5268     // expansion, we know this AllocateNode is initialized by an array
5269     // copy and a StoreStore barrier exists after the array copy.
5270     alloc->initialization()->set_complete_with_arraycopy();
5271   }
5272 
5273   Node* size = _gvn.transform(obj_size);
5274   access_clone(obj, alloc_obj, size, is_array);
5275 
5276   // Do not let reads from the cloned object float above the arraycopy.
5277   if (alloc != nullptr) {
5278     // Do not let stores that initialize this object be reordered with
5279     // a subsequent store that would make this object accessible by
5280     // other threads.
5281     // Record what AllocateNode this StoreStore protects so that
5282     // escape analysis can go from the MemBarStoreStoreNode to the
5283     // AllocateNode and eliminate the MemBarStoreStoreNode if possible
5284     // based on the escape status of the AllocateNode.
5285     insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
5286   } else {
5287     insert_mem_bar(Op_MemBarCPUOrder);
5288   }
5289 }
5290 
5291 //------------------------inline_native_clone----------------------------
5292 // protected native Object java.lang.Object.clone();
5293 //
5294 // Here are the simple edge cases:
5295 //  null receiver => normal trap
5296 //  virtual and clone was overridden => slow path to out-of-line clone
5297 //  not cloneable or finalizer => slow path to out-of-line Object.clone
5298 //
5299 // The general case has two steps, allocation and copying.
5300 // Allocation has two cases, and uses GraphKit::new_instance or new_array.
5301 //
5302 // Copying also has two cases, oop arrays and everything else.
5303 // Oop arrays use arrayof_oop_arraycopy (same as System.arraycopy).
5304 // Everything else uses the tight inline loop supplied by CopyArrayNode.
5305 //
5306 // These steps fold up nicely if and when the cloned object's klass
5307 // can be sharply typed as an object array, a type array, or an instance.
5308 //
5309 bool LibraryCallKit::inline_native_clone(bool is_virtual) {
5310   PhiNode* result_val;
5311 
5312   // Set the reexecute bit for the interpreter to reexecute
5313   // the bytecode that invokes Object.clone if deoptimization happens.
5314   { PreserveReexecuteState preexecs(this);
5315     jvms()->set_should_reexecute(true);
5316 
5317     Node* obj = null_check_receiver();
5318     if (stopped())  return true;
5319 
5320     const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
5321 
5322     // If we are going to clone an instance, we need its exact type to
5323     // know the number and types of fields to convert the clone to
5324     // loads/stores. Maybe a speculative type can help us.
5325     if (!obj_type->klass_is_exact() &&
5326         obj_type->speculative_type() != nullptr &&
5327         obj_type->speculative_type()->is_instance_klass()) {
5328       ciInstanceKlass* spec_ik = obj_type->speculative_type()->as_instance_klass();
5329       if (spec_ik->nof_nonstatic_fields() <= ArrayCopyLoadStoreMaxElem &&
5330           !spec_ik->has_injected_fields()) {
5331         if (!obj_type->isa_instptr() ||
5332             obj_type->is_instptr()->instance_klass()->has_subklass()) {
5333           obj = maybe_cast_profiled_obj(obj, obj_type->speculative_type(), false);
5334         }
5335       }
5336     }
5337 
5338     // Conservatively insert a memory barrier on all memory slices.
5339     // Do not let writes into the original float below the clone.
5340     insert_mem_bar(Op_MemBarCPUOrder);
5341 
5342     // paths into result_reg:
5343     enum {
5344       _slow_path = 1,     // out-of-line call to clone method (virtual or not)
5345       _objArray_path,     // plain array allocation, plus arrayof_oop_arraycopy
5346       _array_path,        // plain array allocation, plus arrayof_long_arraycopy
5347       _instance_path,     // plain instance allocation, plus arrayof_long_arraycopy
5348       PATH_LIMIT
5349     };
5350     RegionNode* result_reg = new RegionNode(PATH_LIMIT);
5351     result_val             = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
5352     PhiNode*    result_i_o = new PhiNode(result_reg, Type::ABIO);
5353     PhiNode*    result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
5354     record_for_igvn(result_reg);
5355 
5356     Node* obj_klass = load_object_klass(obj);
5357     Node* array_obj = obj;
5358     Node* array_ctl = generate_array_guard(obj_klass, (RegionNode*)nullptr, &array_obj);
5359     if (array_ctl != nullptr) {
5360       // It's an array.
5361       PreserveJVMState pjvms(this);
5362       set_control(array_ctl);
5363       Node* obj_length = load_array_length(array_obj);
5364       Node* array_size = nullptr; // Size of the array without object alignment padding.
5365       Node* alloc_obj = new_array(obj_klass, obj_length, 0, &array_size, /*deoptimize_on_exception=*/true);
5366 
5367       BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
5368       if (bs->array_copy_requires_gc_barriers(true, T_OBJECT, true, false, BarrierSetC2::Parsing)) {
5369         // If it is an oop array, it requires very special treatment,
5370         // because gc barriers are required when accessing the array.
5371         Node* is_obja = generate_objArray_guard(obj_klass, (RegionNode*)nullptr);
5372         if (is_obja != nullptr) {
5373           PreserveJVMState pjvms2(this);
5374           set_control(is_obja);
5375           // Generate a direct call to the right arraycopy function(s).
5376           // Clones are always tightly coupled.
5377           ArrayCopyNode* ac = ArrayCopyNode::make(this, true, array_obj, intcon(0), alloc_obj, intcon(0), obj_length, true, false);
5378           ac->set_clone_oop_array();
5379           Node* n = _gvn.transform(ac);
5380           assert(n == ac, "cannot disappear");
5381           ac->connect_outputs(this, /*deoptimize_on_exception=*/true);
5382 
5383           result_reg->init_req(_objArray_path, control());
5384           result_val->init_req(_objArray_path, alloc_obj);
5385           result_i_o ->set_req(_objArray_path, i_o());
5386           result_mem ->set_req(_objArray_path, reset_memory());
5387         }
5388       }
5389       // Otherwise, there are no barriers to worry about.
5390       // (We can dispense with card marks if we know the allocation
5391       //  comes out of eden (TLAB)...  In fact, ReduceInitialCardMarks
5392       //  causes the non-eden paths to take compensating steps to
5393       //  simulate a fresh allocation, so that no further
5394       //  card marks are required in compiled code to initialize
5395       //  the object.)
5396 
5397       if (!stopped()) {
5398         copy_to_clone(array_obj, alloc_obj, array_size, true);
5399 
5400         // Present the results of the copy.
5401         result_reg->init_req(_array_path, control());
5402         result_val->init_req(_array_path, alloc_obj);
5403         result_i_o ->set_req(_array_path, i_o());
5404         result_mem ->set_req(_array_path, reset_memory());
5405       }
5406     }
5407 
5408     // We only go to the instance fast case code if we pass a number of guards.
5409     // The paths which do not pass are accumulated in the slow_region.
5410     RegionNode* slow_region = new RegionNode(1);
5411     record_for_igvn(slow_region);
5412     if (!stopped()) {
5413       // It's an instance (we did array above).  Make the slow-path tests.
5414       // If this is a virtual call, we generate a funny guard.  We grab
5415       // the vtable entry corresponding to clone() from the target object.
5416       // If the target method which we are calling happens to be the
5417       // Object clone() method, we pass the guard.  We do not need this
5418       // guard for non-virtual calls; the caller is known to be the native
5419       // Object clone().
5420       if (is_virtual) {
5421         generate_virtual_guard(obj_klass, slow_region);
5422       }
5423 
5424       // The object must be easily cloneable and must not have a finalizer.
5425       // Both of these conditions may be checked in a single test.
5426       // We could optimize the test further, but we don't care.
5427       generate_misc_flags_guard(obj_klass,
5428                                 // Test both conditions:
5429                                 KlassFlags::_misc_is_cloneable_fast | KlassFlags::_misc_has_finalizer,
5430                                 // Must be cloneable but not finalizer:
5431                                 KlassFlags::_misc_is_cloneable_fast,
5432                                 slow_region);
5433     }
5434 
5435     if (!stopped()) {
5436       // It's an instance, and it passed the slow-path tests.
5437       PreserveJVMState pjvms(this);
5438       Node* obj_size = nullptr; // Total object size, including object alignment padding.
5439       // Need to deoptimize on exception from allocation since Object.clone intrinsic
5440       // is reexecuted if deoptimization occurs and there could be problems when merging
5441       // exception state between multiple Object.clone versions (reexecute=true vs reexecute=false).
5442       Node* alloc_obj = new_instance(obj_klass, nullptr, &obj_size, /*deoptimize_on_exception=*/true);
5443 
5444       copy_to_clone(obj, alloc_obj, obj_size, false);
5445 
5446       // Present the results of the slow call.
5447       result_reg->init_req(_instance_path, control());
5448       result_val->init_req(_instance_path, alloc_obj);
5449       result_i_o ->set_req(_instance_path, i_o());
5450       result_mem ->set_req(_instance_path, reset_memory());
5451     }
5452 
5453     // Generate code for the slow case.  We make a call to clone().
5454     set_control(_gvn.transform(slow_region));
5455     if (!stopped()) {
5456       PreserveJVMState pjvms(this);
5457       CallJavaNode* slow_call = generate_method_call(vmIntrinsics::_clone, is_virtual, false, true);
5458       // We need to deoptimize on exception (see comment above)
5459       Node* slow_result = set_results_for_java_call(slow_call, false, /* deoptimize */ true);
5460       // this->control() comes from set_results_for_java_call
5461       result_reg->init_req(_slow_path, control());
5462       result_val->init_req(_slow_path, slow_result);
5463       result_i_o ->set_req(_slow_path, i_o());
5464       result_mem ->set_req(_slow_path, reset_memory());
5465     }
5466 
5467     // Return the combined state.
5468     set_control(    _gvn.transform(result_reg));
5469     set_i_o(        _gvn.transform(result_i_o));
5470     set_all_memory( _gvn.transform(result_mem));
5471   } // original reexecute is set back here
5472 
5473   set_result(_gvn.transform(result_val));
5474   return true;
5475 }
5476 
5477 // If we have a tightly coupled allocation, the arraycopy may take care
5478 // of the array initialization. If one of the guards we insert between
5479 // the allocation and the arraycopy causes a deoptimization, an
5480 // uninitialized array will escape the compiled method. To prevent that
5481 // we set the JVM state for uncommon traps between the allocation and
5482 // the arraycopy to the state before the allocation so, in case of
5483 // deoptimization, we'll reexecute the allocation and the
5484 // initialization.
5485 JVMState* LibraryCallKit::arraycopy_restore_alloc_state(AllocateArrayNode* alloc, int& saved_reexecute_sp) {
5486   if (alloc != nullptr) {
5487     ciMethod* trap_method = alloc->jvms()->method();
5488     int trap_bci = alloc->jvms()->bci();
5489 
5490     if (!C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_intrinsic) &&
5491         !C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_null_check)) {
5492       // Make sure there's no store between the allocation and the
5493       // arraycopy otherwise visible side effects could be rexecuted
5494       // in case of deoptimization and cause incorrect execution.
5495       bool no_interfering_store = true;
5496       Node* mem = alloc->in(TypeFunc::Memory);
5497       if (mem->is_MergeMem()) {
5498         for (MergeMemStream mms(merged_memory(), mem->as_MergeMem()); mms.next_non_empty2(); ) {
5499           Node* n = mms.memory();
5500           if (n != mms.memory2() && !(n->is_Proj() && n->in(0) == alloc->initialization())) {
5501             assert(n->is_Store(), "what else?");
5502             no_interfering_store = false;
5503             break;
5504           }
5505         }
5506       } else {
5507         for (MergeMemStream mms(merged_memory()); mms.next_non_empty(); ) {
5508           Node* n = mms.memory();
5509           if (n != mem && !(n->is_Proj() && n->in(0) == alloc->initialization())) {
5510             assert(n->is_Store(), "what else?");
5511             no_interfering_store = false;
5512             break;
5513           }
5514         }
5515       }
5516 
5517       if (no_interfering_store) {
5518         SafePointNode* sfpt = create_safepoint_with_state_before_array_allocation(alloc);
5519 
5520         JVMState* saved_jvms = jvms();
5521         saved_reexecute_sp = _reexecute_sp;
5522 
5523         set_jvms(sfpt->jvms());
5524         _reexecute_sp = jvms()->sp();
5525 
5526         return saved_jvms;
5527       }
5528     }
5529   }
5530   return nullptr;
5531 }
5532 
5533 // Clone the JVMState of the array allocation and create a new safepoint with it. Re-push the array length to the stack
5534 // such that uncommon traps can be emitted to re-execute the array allocation in the interpreter.
5535 SafePointNode* LibraryCallKit::create_safepoint_with_state_before_array_allocation(const AllocateArrayNode* alloc) const {
5536   JVMState* old_jvms = alloc->jvms()->clone_shallow(C);
5537   uint size = alloc->req();
5538   SafePointNode* sfpt = new SafePointNode(size, old_jvms);
5539   old_jvms->set_map(sfpt);
5540   for (uint i = 0; i < size; i++) {
5541     sfpt->init_req(i, alloc->in(i));
5542   }
5543   // re-push array length for deoptimization
5544   sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp(), alloc->in(AllocateNode::ALength));
5545   old_jvms->set_sp(old_jvms->sp()+1);
5546   old_jvms->set_monoff(old_jvms->monoff()+1);
5547   old_jvms->set_scloff(old_jvms->scloff()+1);
5548   old_jvms->set_endoff(old_jvms->endoff()+1);
5549   old_jvms->set_should_reexecute(true);
5550 
5551   sfpt->set_i_o(map()->i_o());
5552   sfpt->set_memory(map()->memory());
5553   sfpt->set_control(map()->control());
5554   return sfpt;
5555 }
5556 
5557 // In case of a deoptimization, we restart execution at the
5558 // allocation, allocating a new array. We would leave an uninitialized
5559 // array in the heap that GCs wouldn't expect. Move the allocation
5560 // after the traps so we don't allocate the array if we
5561 // deoptimize. This is possible because tightly_coupled_allocation()
5562 // guarantees there's no observer of the allocated array at this point
5563 // and the control flow is simple enough.
5564 void LibraryCallKit::arraycopy_move_allocation_here(AllocateArrayNode* alloc, Node* dest, JVMState* saved_jvms_before_guards,
5565                                                     int saved_reexecute_sp, uint new_idx) {
5566   if (saved_jvms_before_guards != nullptr && !stopped()) {
5567     replace_unrelated_uncommon_traps_with_alloc_state(alloc, saved_jvms_before_guards);
5568 
5569     assert(alloc != nullptr, "only with a tightly coupled allocation");
5570     // restore JVM state to the state at the arraycopy
5571     saved_jvms_before_guards->map()->set_control(map()->control());
5572     assert(saved_jvms_before_guards->map()->memory() == map()->memory(), "memory state changed?");
5573     assert(saved_jvms_before_guards->map()->i_o() == map()->i_o(), "IO state changed?");
5574     // If we've improved the types of some nodes (null check) while
5575     // emitting the guards, propagate them to the current state
5576     map()->replaced_nodes().apply(saved_jvms_before_guards->map(), new_idx);
5577     set_jvms(saved_jvms_before_guards);
5578     _reexecute_sp = saved_reexecute_sp;
5579 
5580     // Remove the allocation from above the guards
5581     CallProjections callprojs;
5582     alloc->extract_projections(&callprojs, true);
5583     InitializeNode* init = alloc->initialization();
5584     Node* alloc_mem = alloc->in(TypeFunc::Memory);
5585     C->gvn_replace_by(callprojs.fallthrough_ioproj, alloc->in(TypeFunc::I_O));
5586     init->replace_mem_projs_by(alloc_mem, C);
5587 
5588     // The CastIINode created in GraphKit::new_array (in AllocateArrayNode::make_ideal_length) must stay below
5589     // the allocation (i.e. is only valid if the allocation succeeds):
5590     // 1) replace CastIINode with AllocateArrayNode's length here
5591     // 2) Create CastIINode again once allocation has moved (see below) at the end of this method
5592     //
5593     // Multiple identical CastIINodes might exist here. Each GraphKit::load_array_length() call will generate
5594     // new separate CastIINode (arraycopy guard checks or any array length use between array allocation and ararycopy)
5595     Node* init_control = init->proj_out(TypeFunc::Control);
5596     Node* alloc_length = alloc->Ideal_length();
5597 #ifdef ASSERT
5598     Node* prev_cast = nullptr;
5599 #endif
5600     for (uint i = 0; i < init_control->outcnt(); i++) {
5601       Node* init_out = init_control->raw_out(i);
5602       if (init_out->is_CastII() && init_out->in(TypeFunc::Control) == init_control && init_out->in(1) == alloc_length) {
5603 #ifdef ASSERT
5604         if (prev_cast == nullptr) {
5605           prev_cast = init_out;
5606         } else {
5607           if (prev_cast->cmp(*init_out) == false) {
5608             prev_cast->dump();
5609             init_out->dump();
5610             assert(false, "not equal CastIINode");
5611           }
5612         }
5613 #endif
5614         C->gvn_replace_by(init_out, alloc_length);
5615       }
5616     }
5617     C->gvn_replace_by(init->proj_out(TypeFunc::Control), alloc->in(0));
5618 
5619     // move the allocation here (after the guards)
5620     _gvn.hash_delete(alloc);
5621     alloc->set_req(TypeFunc::Control, control());
5622     alloc->set_req(TypeFunc::I_O, i_o());
5623     Node *mem = reset_memory();
5624     set_all_memory(mem);
5625     alloc->set_req(TypeFunc::Memory, mem);
5626     set_control(init->proj_out_or_null(TypeFunc::Control));
5627     set_i_o(callprojs.fallthrough_ioproj);
5628 
5629     // Update memory as done in GraphKit::set_output_for_allocation()
5630     const TypeInt* length_type = _gvn.find_int_type(alloc->in(AllocateNode::ALength));
5631     const TypeOopPtr* ary_type = _gvn.type(alloc->in(AllocateNode::KlassNode))->is_klassptr()->as_instance_type();
5632     if (ary_type->isa_aryptr() && length_type != nullptr) {
5633       ary_type = ary_type->is_aryptr()->cast_to_size(length_type);
5634     }
5635     const TypePtr* telemref = ary_type->add_offset(Type::OffsetBot);
5636     int            elemidx  = C->get_alias_index(telemref);
5637     // Need to properly move every memory projection for the Initialize
5638 #ifdef ASSERT
5639     int mark_idx = C->get_alias_index(ary_type->add_offset(oopDesc::mark_offset_in_bytes()));
5640     int klass_idx = C->get_alias_index(ary_type->add_offset(oopDesc::klass_offset_in_bytes()));
5641 #endif
5642     auto move_proj = [&](ProjNode* proj) {
5643       int alias_idx = C->get_alias_index(proj->adr_type());
5644       assert(alias_idx == Compile::AliasIdxRaw ||
5645              alias_idx == elemidx ||
5646              alias_idx == mark_idx ||
5647              alias_idx == klass_idx, "should be raw memory or array element type");
5648       set_memory(proj, alias_idx);
5649     };
5650     init->for_each_proj(move_proj, TypeFunc::Memory);
5651 
5652     Node* allocx = _gvn.transform(alloc);
5653     assert(allocx == alloc, "where has the allocation gone?");
5654     assert(dest->is_CheckCastPP(), "not an allocation result?");
5655 
5656     _gvn.hash_delete(dest);
5657     dest->set_req(0, control());
5658     Node* destx = _gvn.transform(dest);
5659     assert(destx == dest, "where has the allocation result gone?");
5660 
5661     array_ideal_length(alloc, ary_type, true);
5662   }
5663 }
5664 
5665 // Unrelated UCTs between the array allocation and the array copy, which are considered safe by tightly_coupled_allocation(),
5666 // need to be replaced by an UCT with a state before the array allocation (including the array length). This is necessary
5667 // because we could hit one of these UCTs (which are executed before the emitted array copy guards and the actual array
5668 // allocation which is moved down in arraycopy_move_allocation_here()). When later resuming execution in the interpreter,
5669 // we would have wrongly skipped the array allocation. To prevent this, we resume execution at the array allocation in
5670 // the interpreter similar to what we are doing for the newly emitted guards for the array copy.
5671 void LibraryCallKit::replace_unrelated_uncommon_traps_with_alloc_state(AllocateArrayNode* alloc,
5672                                                                        JVMState* saved_jvms_before_guards) {
5673   if (saved_jvms_before_guards->map()->control()->is_IfProj()) {
5674     // There is at least one unrelated uncommon trap which needs to be replaced.
5675     SafePointNode* sfpt = create_safepoint_with_state_before_array_allocation(alloc);
5676 
5677     JVMState* saved_jvms = jvms();
5678     const int saved_reexecute_sp = _reexecute_sp;
5679     set_jvms(sfpt->jvms());
5680     _reexecute_sp = jvms()->sp();
5681 
5682     replace_unrelated_uncommon_traps_with_alloc_state(saved_jvms_before_guards);
5683 
5684     // Restore state
5685     set_jvms(saved_jvms);
5686     _reexecute_sp = saved_reexecute_sp;
5687   }
5688 }
5689 
5690 // Replace the unrelated uncommon traps with new uncommon trap nodes by reusing the action and reason. The new uncommon
5691 // traps will have the state of the array allocation. Let the old uncommon trap nodes die.
5692 void LibraryCallKit::replace_unrelated_uncommon_traps_with_alloc_state(JVMState* saved_jvms_before_guards) {
5693   Node* if_proj = saved_jvms_before_guards->map()->control(); // Start the search right before the newly emitted guards
5694   while (if_proj->is_IfProj()) {
5695     CallStaticJavaNode* uncommon_trap = get_uncommon_trap_from_success_proj(if_proj);
5696     if (uncommon_trap != nullptr) {
5697       create_new_uncommon_trap(uncommon_trap);
5698     }
5699     assert(if_proj->in(0)->is_If(), "must be If");
5700     if_proj = if_proj->in(0)->in(0);
5701   }
5702   assert(if_proj->is_Proj() && if_proj->in(0)->is_Initialize(),
5703          "must have reached control projection of init node");
5704 }
5705 
5706 void LibraryCallKit::create_new_uncommon_trap(CallStaticJavaNode* uncommon_trap_call) {
5707   const int trap_request = uncommon_trap_call->uncommon_trap_request();
5708   assert(trap_request != 0, "no valid UCT trap request");
5709   PreserveJVMState pjvms(this);
5710   set_control(uncommon_trap_call->in(0));
5711   uncommon_trap(Deoptimization::trap_request_reason(trap_request),
5712                 Deoptimization::trap_request_action(trap_request));
5713   assert(stopped(), "Should be stopped");
5714   _gvn.hash_delete(uncommon_trap_call);
5715   uncommon_trap_call->set_req(0, top()); // not used anymore, kill it
5716 }
5717 
5718 // Common checks for array sorting intrinsics arguments.
5719 // Returns `true` if checks passed.
5720 bool LibraryCallKit::check_array_sort_arguments(Node* elementType, Node* obj, BasicType& bt) {
5721   // check address of the class
5722   if (elementType == nullptr || elementType->is_top()) {
5723     return false;  // dead path
5724   }
5725   const TypeInstPtr* elem_klass = gvn().type(elementType)->isa_instptr();
5726   if (elem_klass == nullptr) {
5727     return false;  // dead path
5728   }
5729   // java_mirror_type() returns non-null for compile-time Class constants only
5730   ciType* elem_type = elem_klass->java_mirror_type();
5731   if (elem_type == nullptr) {
5732     return false;
5733   }
5734   bt = elem_type->basic_type();
5735   // Disable the intrinsic if the CPU does not support SIMD sort
5736   if (!Matcher::supports_simd_sort(bt)) {
5737     return false;
5738   }
5739   // check address of the array
5740   if (obj == nullptr || obj->is_top()) {
5741     return false;  // dead path
5742   }
5743   const TypeAryPtr* obj_t = _gvn.type(obj)->isa_aryptr();
5744   if (obj_t == nullptr || obj_t->elem() == Type::BOTTOM) {
5745     return false; // failed input validation
5746   }
5747   return true;
5748 }
5749 
5750 //------------------------------inline_array_partition-----------------------
5751 bool LibraryCallKit::inline_array_partition() {
5752   address stubAddr = StubRoutines::select_array_partition_function();
5753   if (stubAddr == nullptr) {
5754     return false; // Intrinsic's stub is not implemented on this platform
5755   }
5756   assert(callee()->signature()->size() == 9, "arrayPartition has 8 parameters (one long)");
5757 
5758   // no receiver because it is a static method
5759   Node* elementType     = argument(0);
5760   Node* obj             = argument(1);
5761   Node* offset          = argument(2); // long
5762   Node* fromIndex       = argument(4);
5763   Node* toIndex         = argument(5);
5764   Node* indexPivot1     = argument(6);
5765   Node* indexPivot2     = argument(7);
5766   // PartitionOperation:  argument(8) is ignored
5767 
5768   Node* pivotIndices = nullptr;
5769   BasicType bt = T_ILLEGAL;
5770 
5771   if (!check_array_sort_arguments(elementType, obj, bt)) {
5772     return false;
5773   }
5774   null_check(obj);
5775   // If obj is dead, only null-path is taken.
5776   if (stopped()) {
5777     return true;
5778   }
5779   // Set the original stack and the reexecute bit for the interpreter to reexecute
5780   // the bytecode that invokes DualPivotQuicksort.partition() if deoptimization happens.
5781   { PreserveReexecuteState preexecs(this);
5782     jvms()->set_should_reexecute(true);
5783 
5784     Node* obj_adr = make_unsafe_address(obj, offset);
5785 
5786     // create the pivotIndices array of type int and size = 2
5787     Node* size = intcon(2);
5788     Node* klass_node = makecon(TypeKlassPtr::make(ciTypeArrayKlass::make(T_INT)));
5789     pivotIndices = new_array(klass_node, size, 0);  // no arguments to push
5790     AllocateArrayNode* alloc = tightly_coupled_allocation(pivotIndices);
5791     guarantee(alloc != nullptr, "created above");
5792     Node* pivotIndices_adr = basic_plus_adr(pivotIndices, arrayOopDesc::base_offset_in_bytes(T_INT));
5793 
5794     // pass the basic type enum to the stub
5795     Node* elemType = intcon(bt);
5796 
5797     // Call the stub
5798     const char *stubName = "array_partition_stub";
5799     make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::array_partition_Type(),
5800                       stubAddr, stubName, TypePtr::BOTTOM,
5801                       obj_adr, elemType, fromIndex, toIndex, pivotIndices_adr,
5802                       indexPivot1, indexPivot2);
5803 
5804   } // original reexecute is set back here
5805 
5806   if (!stopped()) {
5807     set_result(pivotIndices);
5808   }
5809 
5810   return true;
5811 }
5812 
5813 
5814 //------------------------------inline_array_sort-----------------------
5815 bool LibraryCallKit::inline_array_sort() {
5816   address stubAddr = StubRoutines::select_arraysort_function();
5817   if (stubAddr == nullptr) {
5818     return false; // Intrinsic's stub is not implemented on this platform
5819   }
5820   assert(callee()->signature()->size() == 7, "arraySort has 6 parameters (one long)");
5821 
5822   // no receiver because it is a static method
5823   Node* elementType     = argument(0);
5824   Node* obj             = argument(1);
5825   Node* offset          = argument(2); // long
5826   Node* fromIndex       = argument(4);
5827   Node* toIndex         = argument(5);
5828   // SortOperation:       argument(6) is ignored
5829 
5830   BasicType bt = T_ILLEGAL;
5831 
5832   if (!check_array_sort_arguments(elementType, obj, bt)) {
5833     return false;
5834   }
5835   null_check(obj);
5836   // If obj is dead, only null-path is taken.
5837   if (stopped()) {
5838     return true;
5839   }
5840   Node* obj_adr = make_unsafe_address(obj, offset);
5841 
5842   // pass the basic type enum to the stub
5843   Node* elemType = intcon(bt);
5844 
5845   // Call the stub.
5846   const char *stubName = "arraysort_stub";
5847   make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::array_sort_Type(),
5848                     stubAddr, stubName, TypePtr::BOTTOM,
5849                     obj_adr, elemType, fromIndex, toIndex);
5850 
5851   return true;
5852 }
5853 
5854 
5855 //------------------------------inline_arraycopy-----------------------
5856 // public static native void java.lang.System.arraycopy(Object src,  int  srcPos,
5857 //                                                      Object dest, int destPos,
5858 //                                                      int length);
5859 bool LibraryCallKit::inline_arraycopy() {
5860   // Get the arguments.
5861   Node* src         = argument(0);  // type: oop
5862   Node* src_offset  = argument(1);  // type: int
5863   Node* dest        = argument(2);  // type: oop
5864   Node* dest_offset = argument(3);  // type: int
5865   Node* length      = argument(4);  // type: int
5866 
5867   uint new_idx = C->unique();
5868 
5869   // Check for allocation before we add nodes that would confuse
5870   // tightly_coupled_allocation()
5871   AllocateArrayNode* alloc = tightly_coupled_allocation(dest);
5872 
5873   int saved_reexecute_sp = -1;
5874   JVMState* saved_jvms_before_guards = arraycopy_restore_alloc_state(alloc, saved_reexecute_sp);
5875   // See arraycopy_restore_alloc_state() comment
5876   // if alloc == null we don't have to worry about a tightly coupled allocation so we can emit all needed guards
5877   // if saved_jvms_before_guards is not null (then alloc is not null) then we can handle guards and a tightly coupled allocation
5878   // if saved_jvms_before_guards is null and alloc is not null, we can't emit any guards
5879   bool can_emit_guards = (alloc == nullptr || saved_jvms_before_guards != nullptr);
5880 
5881   // The following tests must be performed
5882   // (1) src and dest are arrays.
5883   // (2) src and dest arrays must have elements of the same BasicType
5884   // (3) src and dest must not be null.
5885   // (4) src_offset must not be negative.
5886   // (5) dest_offset must not be negative.
5887   // (6) length must not be negative.
5888   // (7) src_offset + length must not exceed length of src.
5889   // (8) dest_offset + length must not exceed length of dest.
5890   // (9) each element of an oop array must be assignable
5891 
5892   // (3) src and dest must not be null.
5893   // always do this here because we need the JVM state for uncommon traps
5894   Node* null_ctl = top();
5895   src  = saved_jvms_before_guards != nullptr ? null_check_oop(src, &null_ctl, true, true) : null_check(src, T_ARRAY);
5896   assert(null_ctl->is_top(), "no null control here");
5897   dest = null_check(dest, T_ARRAY);
5898 
5899   if (!can_emit_guards) {
5900     // if saved_jvms_before_guards is null and alloc is not null, we don't emit any
5901     // guards but the arraycopy node could still take advantage of a
5902     // tightly allocated allocation. tightly_coupled_allocation() is
5903     // called again to make sure it takes the null check above into
5904     // account: the null check is mandatory and if it caused an
5905     // uncommon trap to be emitted then the allocation can't be
5906     // considered tightly coupled in this context.
5907     alloc = tightly_coupled_allocation(dest);
5908   }
5909 
5910   bool validated = false;
5911 
5912   const Type* src_type  = _gvn.type(src);
5913   const Type* dest_type = _gvn.type(dest);
5914   const TypeAryPtr* top_src  = src_type->isa_aryptr();
5915   const TypeAryPtr* top_dest = dest_type->isa_aryptr();
5916 
5917   // Do we have the type of src?
5918   bool has_src = (top_src != nullptr && top_src->elem() != Type::BOTTOM);
5919   // Do we have the type of dest?
5920   bool has_dest = (top_dest != nullptr && top_dest->elem() != Type::BOTTOM);
5921   // Is the type for src from speculation?
5922   bool src_spec = false;
5923   // Is the type for dest from speculation?
5924   bool dest_spec = false;
5925 
5926   if ((!has_src || !has_dest) && can_emit_guards) {
5927     // We don't have sufficient type information, let's see if
5928     // speculative types can help. We need to have types for both src
5929     // and dest so that it pays off.
5930 
5931     // Do we already have or could we have type information for src
5932     bool could_have_src = has_src;
5933     // Do we already have or could we have type information for dest
5934     bool could_have_dest = has_dest;
5935 
5936     ciKlass* src_k = nullptr;
5937     if (!has_src) {
5938       src_k = src_type->speculative_type_not_null();
5939       if (src_k != nullptr && src_k->is_array_klass()) {
5940         could_have_src = true;
5941       }
5942     }
5943 
5944     ciKlass* dest_k = nullptr;
5945     if (!has_dest) {
5946       dest_k = dest_type->speculative_type_not_null();
5947       if (dest_k != nullptr && dest_k->is_array_klass()) {
5948         could_have_dest = true;
5949       }
5950     }
5951 
5952     if (could_have_src && could_have_dest) {
5953       // This is going to pay off so emit the required guards
5954       if (!has_src) {
5955         src = maybe_cast_profiled_obj(src, src_k, true);
5956         src_type  = _gvn.type(src);
5957         top_src  = src_type->isa_aryptr();
5958         has_src = (top_src != nullptr && top_src->elem() != Type::BOTTOM);
5959         src_spec = true;
5960       }
5961       if (!has_dest) {
5962         dest = maybe_cast_profiled_obj(dest, dest_k, true);
5963         dest_type  = _gvn.type(dest);
5964         top_dest  = dest_type->isa_aryptr();
5965         has_dest = (top_dest != nullptr && top_dest->elem() != Type::BOTTOM);
5966         dest_spec = true;
5967       }
5968     }
5969   }
5970 
5971   if (has_src && has_dest && can_emit_guards) {
5972     BasicType src_elem = top_src->isa_aryptr()->elem()->array_element_basic_type();
5973     BasicType dest_elem = top_dest->isa_aryptr()->elem()->array_element_basic_type();
5974     if (is_reference_type(src_elem, true)) src_elem = T_OBJECT;
5975     if (is_reference_type(dest_elem, true)) dest_elem = T_OBJECT;
5976 
5977     if (src_elem == dest_elem && src_elem == T_OBJECT) {
5978       // If both arrays are object arrays then having the exact types
5979       // for both will remove the need for a subtype check at runtime
5980       // before the call and may make it possible to pick a faster copy
5981       // routine (without a subtype check on every element)
5982       // Do we have the exact type of src?
5983       bool could_have_src = src_spec;
5984       // Do we have the exact type of dest?
5985       bool could_have_dest = dest_spec;
5986       ciKlass* src_k = nullptr;
5987       ciKlass* dest_k = nullptr;
5988       if (!src_spec) {
5989         src_k = src_type->speculative_type_not_null();
5990         if (src_k != nullptr && src_k->is_array_klass()) {
5991           could_have_src = true;
5992         }
5993       }
5994       if (!dest_spec) {
5995         dest_k = dest_type->speculative_type_not_null();
5996         if (dest_k != nullptr && dest_k->is_array_klass()) {
5997           could_have_dest = true;
5998         }
5999       }
6000       if (could_have_src && could_have_dest) {
6001         // If we can have both exact types, emit the missing guards
6002         if (could_have_src && !src_spec) {
6003           src = maybe_cast_profiled_obj(src, src_k, true);
6004         }
6005         if (could_have_dest && !dest_spec) {
6006           dest = maybe_cast_profiled_obj(dest, dest_k, true);
6007         }
6008       }
6009     }
6010   }
6011 
6012   ciMethod* trap_method = method();
6013   int trap_bci = bci();
6014   if (saved_jvms_before_guards != nullptr) {
6015     trap_method = alloc->jvms()->method();
6016     trap_bci = alloc->jvms()->bci();
6017   }
6018 
6019   bool negative_length_guard_generated = false;
6020 
6021   if (!C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_intrinsic) &&
6022       can_emit_guards &&
6023       !src->is_top() && !dest->is_top()) {
6024     // validate arguments: enables transformation the ArrayCopyNode
6025     validated = true;
6026 
6027     RegionNode* slow_region = new RegionNode(1);
6028     record_for_igvn(slow_region);
6029 
6030     // (1) src and dest are arrays.
6031     generate_non_array_guard(load_object_klass(src), slow_region, &src);
6032     generate_non_array_guard(load_object_klass(dest), slow_region, &dest);
6033 
6034     // (2) src and dest arrays must have elements of the same BasicType
6035     // done at macro expansion or at Ideal transformation time
6036 
6037     // (4) src_offset must not be negative.
6038     generate_negative_guard(src_offset, slow_region);
6039 
6040     // (5) dest_offset must not be negative.
6041     generate_negative_guard(dest_offset, slow_region);
6042 
6043     // (7) src_offset + length must not exceed length of src.
6044     generate_limit_guard(src_offset, length,
6045                          load_array_length(src),
6046                          slow_region);
6047 
6048     // (8) dest_offset + length must not exceed length of dest.
6049     generate_limit_guard(dest_offset, length,
6050                          load_array_length(dest),
6051                          slow_region);
6052 
6053     // (6) length must not be negative.
6054     // This is also checked in generate_arraycopy() during macro expansion, but
6055     // we also have to check it here for the case where the ArrayCopyNode will
6056     // be eliminated by Escape Analysis.
6057     if (EliminateAllocations) {
6058       generate_negative_guard(length, slow_region);
6059       negative_length_guard_generated = true;
6060     }
6061 
6062     // (9) each element of an oop array must be assignable
6063     Node* dest_klass = load_object_klass(dest);
6064     if (src != dest) {
6065       Node* not_subtype_ctrl = gen_subtype_check(src, dest_klass);
6066 
6067       if (not_subtype_ctrl != top()) {
6068         PreserveJVMState pjvms(this);
6069         set_control(not_subtype_ctrl);
6070         uncommon_trap(Deoptimization::Reason_intrinsic,
6071                       Deoptimization::Action_make_not_entrant);
6072         assert(stopped(), "Should be stopped");
6073       }
6074     }
6075     {
6076       PreserveJVMState pjvms(this);
6077       set_control(_gvn.transform(slow_region));
6078       uncommon_trap(Deoptimization::Reason_intrinsic,
6079                     Deoptimization::Action_make_not_entrant);
6080       assert(stopped(), "Should be stopped");
6081     }
6082 
6083     const TypeKlassPtr* dest_klass_t = _gvn.type(dest_klass)->is_klassptr();
6084     const Type *toop = dest_klass_t->cast_to_exactness(false)->as_instance_type();
6085     src = _gvn.transform(new CheckCastPPNode(control(), src, toop));
6086     arraycopy_move_allocation_here(alloc, dest, saved_jvms_before_guards, saved_reexecute_sp, new_idx);
6087   }
6088 
6089   if (stopped()) {
6090     return true;
6091   }
6092 
6093   ArrayCopyNode* ac = ArrayCopyNode::make(this, true, src, src_offset, dest, dest_offset, length, alloc != nullptr, negative_length_guard_generated,
6094                                           // Create LoadRange and LoadKlass nodes for use during macro expansion here
6095                                           // so the compiler has a chance to eliminate them: during macro expansion,
6096                                           // we have to set their control (CastPP nodes are eliminated).
6097                                           load_object_klass(src), load_object_klass(dest),
6098                                           load_array_length(src), load_array_length(dest));
6099 
6100   ac->set_arraycopy(validated);
6101 
6102   Node* n = _gvn.transform(ac);
6103   if (n == ac) {
6104     ac->connect_outputs(this);
6105   } else {
6106     assert(validated, "shouldn't transform if all arguments not validated");
6107     set_all_memory(n);
6108   }
6109   clear_upper_avx();
6110 
6111 
6112   return true;
6113 }
6114 
6115 
6116 // Helper function which determines if an arraycopy immediately follows
6117 // an allocation, with no intervening tests or other escapes for the object.
6118 AllocateArrayNode*
6119 LibraryCallKit::tightly_coupled_allocation(Node* ptr) {
6120   if (stopped())             return nullptr;  // no fast path
6121   if (!C->do_aliasing())     return nullptr;  // no MergeMems around
6122 
6123   AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(ptr);
6124   if (alloc == nullptr)  return nullptr;
6125 
6126   Node* rawmem = memory(Compile::AliasIdxRaw);
6127   // Is the allocation's memory state untouched?
6128   if (!(rawmem->is_Proj() && rawmem->in(0)->is_Initialize())) {
6129     // Bail out if there have been raw-memory effects since the allocation.
6130     // (Example:  There might have been a call or safepoint.)
6131     return nullptr;
6132   }
6133   rawmem = rawmem->in(0)->as_Initialize()->memory(Compile::AliasIdxRaw);
6134   if (!(rawmem->is_Proj() && rawmem->in(0) == alloc)) {
6135     return nullptr;
6136   }
6137 
6138   // There must be no unexpected observers of this allocation.
6139   for (DUIterator_Fast imax, i = ptr->fast_outs(imax); i < imax; i++) {
6140     Node* obs = ptr->fast_out(i);
6141     if (obs != this->map()) {
6142       return nullptr;
6143     }
6144   }
6145 
6146   // This arraycopy must unconditionally follow the allocation of the ptr.
6147   Node* alloc_ctl = ptr->in(0);
6148   Node* ctl = control();
6149   while (ctl != alloc_ctl) {
6150     // There may be guards which feed into the slow_region.
6151     // Any other control flow means that we might not get a chance
6152     // to finish initializing the allocated object.
6153     // Various low-level checks bottom out in uncommon traps. These
6154     // are considered safe since we've already checked above that
6155     // there is no unexpected observer of this allocation.
6156     if (get_uncommon_trap_from_success_proj(ctl) != nullptr) {
6157       assert(ctl->in(0)->is_If(), "must be If");
6158       ctl = ctl->in(0)->in(0);
6159     } else {
6160       return nullptr;
6161     }
6162   }
6163 
6164   // If we get this far, we have an allocation which immediately
6165   // precedes the arraycopy, and we can take over zeroing the new object.
6166   // The arraycopy will finish the initialization, and provide
6167   // a new control state to which we will anchor the destination pointer.
6168 
6169   return alloc;
6170 }
6171 
6172 CallStaticJavaNode* LibraryCallKit::get_uncommon_trap_from_success_proj(Node* node) {
6173   if (node->is_IfProj()) {
6174     IfProjNode* other_proj = node->as_IfProj()->other_if_proj();
6175     for (DUIterator_Fast jmax, j = other_proj->fast_outs(jmax); j < jmax; j++) {
6176       Node* obs = other_proj->fast_out(j);
6177       if (obs->in(0) == other_proj && obs->is_CallStaticJava() &&
6178           (obs->as_CallStaticJava()->entry_point() == OptoRuntime::uncommon_trap_blob()->entry_point())) {
6179         return obs->as_CallStaticJava();
6180       }
6181     }
6182   }
6183   return nullptr;
6184 }
6185 
6186 //-------------inline_encodeISOArray-----------------------------------
6187 // int sun.nio.cs.ISO_8859_1.Encoder#encodeISOArray0(byte[] sa, int sp, byte[] da, int dp, int len)
6188 // int java.lang.StringCoding#encodeISOArray0(byte[] sa, int sp, byte[] da, int dp, int len)
6189 // int java.lang.StringCoding#encodeAsciiArray0(char[] sa, int sp, byte[] da, int dp, int len)
6190 // encode char[] to byte[] in ISO_8859_1 or ASCII
6191 bool LibraryCallKit::inline_encodeISOArray(bool ascii) {
6192   assert(callee()->signature()->size() == 5, "encodeISOArray has 5 parameters");
6193   // no receiver since it is static method
6194   Node *src         = argument(0);
6195   Node *src_offset  = argument(1);
6196   Node *dst         = argument(2);
6197   Node *dst_offset  = argument(3);
6198   Node *length      = argument(4);
6199 
6200   // Cast source & target arrays to not-null
6201   if (VerifyIntrinsicChecks) {
6202     src = must_be_not_null(src, true);
6203     dst = must_be_not_null(dst, true);
6204     if (stopped()) {
6205       return true;
6206     }
6207   }
6208 
6209   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
6210   const TypeAryPtr* dst_type = dst->Value(&_gvn)->isa_aryptr();
6211   if (src_type == nullptr || src_type->elem() == Type::BOTTOM ||
6212       dst_type == nullptr || dst_type->elem() == Type::BOTTOM) {
6213     // failed array check
6214     return false;
6215   }
6216 
6217   // Figure out the size and type of the elements we will be copying.
6218   BasicType src_elem = src_type->elem()->array_element_basic_type();
6219   BasicType dst_elem = dst_type->elem()->array_element_basic_type();
6220   if (!((src_elem == T_CHAR) || (src_elem== T_BYTE)) || dst_elem != T_BYTE) {
6221     return false;
6222   }
6223 
6224   // Check source & target bounds
6225   if (VerifyIntrinsicChecks) {
6226     generate_string_range_check(src, src_offset, length, src_elem == T_BYTE, true);
6227     generate_string_range_check(dst, dst_offset, length, false, true);
6228     if (stopped()) {
6229       return true;
6230     }
6231   }
6232 
6233   Node* src_start = array_element_address(src, src_offset, T_CHAR);
6234   Node* dst_start = array_element_address(dst, dst_offset, dst_elem);
6235   // 'src_start' points to src array + scaled offset
6236   // 'dst_start' points to dst array + scaled offset
6237 
6238   const TypeAryPtr* mtype = TypeAryPtr::BYTES;
6239   Node* enc = new EncodeISOArrayNode(control(), memory(mtype), src_start, dst_start, length, ascii);
6240   enc = _gvn.transform(enc);
6241   Node* res_mem = _gvn.transform(new SCMemProjNode(enc));
6242   set_memory(res_mem, mtype);
6243   set_result(enc);
6244   clear_upper_avx();
6245 
6246   return true;
6247 }
6248 
6249 //-------------inline_multiplyToLen-----------------------------------
6250 bool LibraryCallKit::inline_multiplyToLen() {
6251   assert(UseMultiplyToLenIntrinsic, "not implemented on this platform");
6252 
6253   address stubAddr = StubRoutines::multiplyToLen();
6254   if (stubAddr == nullptr) {
6255     return false; // Intrinsic's stub is not implemented on this platform
6256   }
6257   const char* stubName = "multiplyToLen";
6258 
6259   assert(callee()->signature()->size() == 5, "multiplyToLen has 5 parameters");
6260 
6261   // no receiver because it is a static method
6262   Node* x    = argument(0);
6263   Node* xlen = argument(1);
6264   Node* y    = argument(2);
6265   Node* ylen = argument(3);
6266   Node* z    = argument(4);
6267 
6268   x = must_be_not_null(x, true);
6269   y = must_be_not_null(y, true);
6270 
6271   const TypeAryPtr* x_type = x->Value(&_gvn)->isa_aryptr();
6272   const TypeAryPtr* y_type = y->Value(&_gvn)->isa_aryptr();
6273   if (x_type == nullptr || x_type->elem() == Type::BOTTOM ||
6274       y_type == nullptr || y_type->elem() == Type::BOTTOM) {
6275     // failed array check
6276     return false;
6277   }
6278 
6279   BasicType x_elem = x_type->elem()->array_element_basic_type();
6280   BasicType y_elem = y_type->elem()->array_element_basic_type();
6281   if (x_elem != T_INT || y_elem != T_INT) {
6282     return false;
6283   }
6284 
6285   Node* x_start = array_element_address(x, intcon(0), x_elem);
6286   Node* y_start = array_element_address(y, intcon(0), y_elem);
6287   // 'x_start' points to x array + scaled xlen
6288   // 'y_start' points to y array + scaled ylen
6289 
6290   Node* z_start = array_element_address(z, intcon(0), T_INT);
6291 
6292   Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
6293                                  OptoRuntime::multiplyToLen_Type(),
6294                                  stubAddr, stubName, TypePtr::BOTTOM,
6295                                  x_start, xlen, y_start, ylen, z_start);
6296 
6297   C->set_has_split_ifs(true); // Has chance for split-if optimization
6298   set_result(z);
6299   return true;
6300 }
6301 
6302 //-------------inline_squareToLen------------------------------------
6303 bool LibraryCallKit::inline_squareToLen() {
6304   assert(UseSquareToLenIntrinsic, "not implemented on this platform");
6305 
6306   address stubAddr = StubRoutines::squareToLen();
6307   if (stubAddr == nullptr) {
6308     return false; // Intrinsic's stub is not implemented on this platform
6309   }
6310   const char* stubName = "squareToLen";
6311 
6312   assert(callee()->signature()->size() == 4, "implSquareToLen has 4 parameters");
6313 
6314   Node* x    = argument(0);
6315   Node* len  = argument(1);
6316   Node* z    = argument(2);
6317   Node* zlen = argument(3);
6318 
6319   x = must_be_not_null(x, true);
6320   z = must_be_not_null(z, true);
6321 
6322   const TypeAryPtr* x_type = x->Value(&_gvn)->isa_aryptr();
6323   const TypeAryPtr* z_type = z->Value(&_gvn)->isa_aryptr();
6324   if (x_type == nullptr || x_type->elem() == Type::BOTTOM ||
6325       z_type == nullptr || z_type->elem() == Type::BOTTOM) {
6326     // failed array check
6327     return false;
6328   }
6329 
6330   BasicType x_elem = x_type->elem()->array_element_basic_type();
6331   BasicType z_elem = z_type->elem()->array_element_basic_type();
6332   if (x_elem != T_INT || z_elem != T_INT) {
6333     return false;
6334   }
6335 
6336 
6337   Node* x_start = array_element_address(x, intcon(0), x_elem);
6338   Node* z_start = array_element_address(z, intcon(0), z_elem);
6339 
6340   Node*  call = make_runtime_call(RC_LEAF|RC_NO_FP,
6341                                   OptoRuntime::squareToLen_Type(),
6342                                   stubAddr, stubName, TypePtr::BOTTOM,
6343                                   x_start, len, z_start, zlen);
6344 
6345   set_result(z);
6346   return true;
6347 }
6348 
6349 //-------------inline_mulAdd------------------------------------------
6350 bool LibraryCallKit::inline_mulAdd() {
6351   assert(UseMulAddIntrinsic, "not implemented on this platform");
6352 
6353   address stubAddr = StubRoutines::mulAdd();
6354   if (stubAddr == nullptr) {
6355     return false; // Intrinsic's stub is not implemented on this platform
6356   }
6357   const char* stubName = "mulAdd";
6358 
6359   assert(callee()->signature()->size() == 5, "mulAdd has 5 parameters");
6360 
6361   Node* out      = argument(0);
6362   Node* in       = argument(1);
6363   Node* offset   = argument(2);
6364   Node* len      = argument(3);
6365   Node* k        = argument(4);
6366 
6367   in = must_be_not_null(in, true);
6368   out = must_be_not_null(out, true);
6369 
6370   const TypeAryPtr* out_type = out->Value(&_gvn)->isa_aryptr();
6371   const TypeAryPtr* in_type = in->Value(&_gvn)->isa_aryptr();
6372   if (out_type == nullptr || out_type->elem() == Type::BOTTOM ||
6373        in_type == nullptr ||  in_type->elem() == Type::BOTTOM) {
6374     // failed array check
6375     return false;
6376   }
6377 
6378   BasicType out_elem = out_type->elem()->array_element_basic_type();
6379   BasicType in_elem = in_type->elem()->array_element_basic_type();
6380   if (out_elem != T_INT || in_elem != T_INT) {
6381     return false;
6382   }
6383 
6384   Node* outlen = load_array_length(out);
6385   Node* new_offset = _gvn.transform(new SubINode(outlen, offset));
6386   Node* out_start = array_element_address(out, intcon(0), out_elem);
6387   Node* in_start = array_element_address(in, intcon(0), in_elem);
6388 
6389   Node*  call = make_runtime_call(RC_LEAF|RC_NO_FP,
6390                                   OptoRuntime::mulAdd_Type(),
6391                                   stubAddr, stubName, TypePtr::BOTTOM,
6392                                   out_start,in_start, new_offset, len, k);
6393   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
6394   set_result(result);
6395   return true;
6396 }
6397 
6398 //-------------inline_montgomeryMultiply-----------------------------------
6399 bool LibraryCallKit::inline_montgomeryMultiply() {
6400   address stubAddr = StubRoutines::montgomeryMultiply();
6401   if (stubAddr == nullptr) {
6402     return false; // Intrinsic's stub is not implemented on this platform
6403   }
6404 
6405   assert(UseMontgomeryMultiplyIntrinsic, "not implemented on this platform");
6406   const char* stubName = "montgomery_multiply";
6407 
6408   assert(callee()->signature()->size() == 7, "montgomeryMultiply has 7 parameters");
6409 
6410   Node* a    = argument(0);
6411   Node* b    = argument(1);
6412   Node* n    = argument(2);
6413   Node* len  = argument(3);
6414   Node* inv  = argument(4);
6415   Node* m    = argument(6);
6416 
6417   const TypeAryPtr* a_type = a->Value(&_gvn)->isa_aryptr();
6418   const TypeAryPtr* b_type = b->Value(&_gvn)->isa_aryptr();
6419   const TypeAryPtr* n_type = n->Value(&_gvn)->isa_aryptr();
6420   const TypeAryPtr* m_type = m->Value(&_gvn)->isa_aryptr();
6421   if (a_type == nullptr || a_type->elem() == Type::BOTTOM ||
6422       b_type == nullptr || b_type->elem() == Type::BOTTOM ||
6423       n_type == nullptr || n_type->elem() == Type::BOTTOM ||
6424       m_type == nullptr || m_type->elem() == Type::BOTTOM) {
6425     // failed array check
6426     return false;
6427   }
6428 
6429   BasicType a_elem = a_type->elem()->array_element_basic_type();
6430   BasicType b_elem = b_type->elem()->array_element_basic_type();
6431   BasicType n_elem = n_type->elem()->array_element_basic_type();
6432   BasicType m_elem = m_type->elem()->array_element_basic_type();
6433   if (a_elem != T_INT || b_elem != T_INT || n_elem != T_INT || m_elem != T_INT) {
6434     return false;
6435   }
6436 
6437   // Make the call
6438   {
6439     Node* a_start = array_element_address(a, intcon(0), a_elem);
6440     Node* b_start = array_element_address(b, intcon(0), b_elem);
6441     Node* n_start = array_element_address(n, intcon(0), n_elem);
6442     Node* m_start = array_element_address(m, intcon(0), m_elem);
6443 
6444     Node* call = make_runtime_call(RC_LEAF,
6445                                    OptoRuntime::montgomeryMultiply_Type(),
6446                                    stubAddr, stubName, TypePtr::BOTTOM,
6447                                    a_start, b_start, n_start, len, inv, top(),
6448                                    m_start);
6449     set_result(m);
6450   }
6451 
6452   return true;
6453 }
6454 
6455 bool LibraryCallKit::inline_montgomerySquare() {
6456   address stubAddr = StubRoutines::montgomerySquare();
6457   if (stubAddr == nullptr) {
6458     return false; // Intrinsic's stub is not implemented on this platform
6459   }
6460 
6461   assert(UseMontgomerySquareIntrinsic, "not implemented on this platform");
6462   const char* stubName = "montgomery_square";
6463 
6464   assert(callee()->signature()->size() == 6, "montgomerySquare has 6 parameters");
6465 
6466   Node* a    = argument(0);
6467   Node* n    = argument(1);
6468   Node* len  = argument(2);
6469   Node* inv  = argument(3);
6470   Node* m    = argument(5);
6471 
6472   const TypeAryPtr* a_type = a->Value(&_gvn)->isa_aryptr();
6473   const TypeAryPtr* n_type = n->Value(&_gvn)->isa_aryptr();
6474   const TypeAryPtr* m_type = m->Value(&_gvn)->isa_aryptr();
6475   if (a_type == nullptr || a_type->elem() == Type::BOTTOM ||
6476       n_type == nullptr || n_type->elem() == Type::BOTTOM ||
6477       m_type == nullptr || m_type->elem() == Type::BOTTOM) {
6478     // failed array check
6479     return false;
6480   }
6481 
6482   BasicType a_elem = a_type->elem()->array_element_basic_type();
6483   BasicType n_elem = n_type->elem()->array_element_basic_type();
6484   BasicType m_elem = m_type->elem()->array_element_basic_type();
6485   if (a_elem != T_INT || n_elem != T_INT || m_elem != T_INT) {
6486     return false;
6487   }
6488 
6489   // Make the call
6490   {
6491     Node* a_start = array_element_address(a, intcon(0), a_elem);
6492     Node* n_start = array_element_address(n, intcon(0), n_elem);
6493     Node* m_start = array_element_address(m, intcon(0), m_elem);
6494 
6495     Node* call = make_runtime_call(RC_LEAF,
6496                                    OptoRuntime::montgomerySquare_Type(),
6497                                    stubAddr, stubName, TypePtr::BOTTOM,
6498                                    a_start, n_start, len, inv, top(),
6499                                    m_start);
6500     set_result(m);
6501   }
6502 
6503   return true;
6504 }
6505 
6506 bool LibraryCallKit::inline_bigIntegerShift(bool isRightShift) {
6507   address stubAddr = nullptr;
6508   const char* stubName = nullptr;
6509 
6510   stubAddr = isRightShift? StubRoutines::bigIntegerRightShift(): StubRoutines::bigIntegerLeftShift();
6511   if (stubAddr == nullptr) {
6512     return false; // Intrinsic's stub is not implemented on this platform
6513   }
6514 
6515   stubName = isRightShift? "bigIntegerRightShiftWorker" : "bigIntegerLeftShiftWorker";
6516 
6517   assert(callee()->signature()->size() == 5, "expected 5 arguments");
6518 
6519   Node* newArr = argument(0);
6520   Node* oldArr = argument(1);
6521   Node* newIdx = argument(2);
6522   Node* shiftCount = argument(3);
6523   Node* numIter = argument(4);
6524 
6525   const TypeAryPtr* newArr_type = newArr->Value(&_gvn)->isa_aryptr();
6526   const TypeAryPtr* oldArr_type = oldArr->Value(&_gvn)->isa_aryptr();
6527   if (newArr_type == nullptr || newArr_type->elem() == Type::BOTTOM ||
6528       oldArr_type == nullptr || oldArr_type->elem() == Type::BOTTOM) {
6529     return false;
6530   }
6531 
6532   BasicType newArr_elem = newArr_type->elem()->array_element_basic_type();
6533   BasicType oldArr_elem = oldArr_type->elem()->array_element_basic_type();
6534   if (newArr_elem != T_INT || oldArr_elem != T_INT) {
6535     return false;
6536   }
6537 
6538   // Make the call
6539   {
6540     Node* newArr_start = array_element_address(newArr, intcon(0), newArr_elem);
6541     Node* oldArr_start = array_element_address(oldArr, intcon(0), oldArr_elem);
6542 
6543     Node* call = make_runtime_call(RC_LEAF,
6544                                    OptoRuntime::bigIntegerShift_Type(),
6545                                    stubAddr,
6546                                    stubName,
6547                                    TypePtr::BOTTOM,
6548                                    newArr_start,
6549                                    oldArr_start,
6550                                    newIdx,
6551                                    shiftCount,
6552                                    numIter);
6553   }
6554 
6555   return true;
6556 }
6557 
6558 //-------------inline_vectorizedMismatch------------------------------
6559 bool LibraryCallKit::inline_vectorizedMismatch() {
6560   assert(UseVectorizedMismatchIntrinsic, "not implemented on this platform");
6561 
6562   assert(callee()->signature()->size() == 8, "vectorizedMismatch has 6 parameters");
6563   Node* obja    = argument(0); // Object
6564   Node* aoffset = argument(1); // long
6565   Node* objb    = argument(3); // Object
6566   Node* boffset = argument(4); // long
6567   Node* length  = argument(6); // int
6568   Node* scale   = argument(7); // int
6569 
6570   const TypeAryPtr* obja_t = _gvn.type(obja)->isa_aryptr();
6571   const TypeAryPtr* objb_t = _gvn.type(objb)->isa_aryptr();
6572   if (obja_t == nullptr || obja_t->elem() == Type::BOTTOM ||
6573       objb_t == nullptr || objb_t->elem() == Type::BOTTOM ||
6574       scale == top()) {
6575     return false; // failed input validation
6576   }
6577 
6578   Node* obja_adr = make_unsafe_address(obja, aoffset);
6579   Node* objb_adr = make_unsafe_address(objb, boffset);
6580 
6581   // Partial inlining handling for inputs smaller than ArrayOperationPartialInlineSize bytes in size.
6582   //
6583   //    inline_limit = ArrayOperationPartialInlineSize / element_size;
6584   //    if (length <= inline_limit) {
6585   //      inline_path:
6586   //        vmask   = VectorMaskGen length
6587   //        vload1  = LoadVectorMasked obja, vmask
6588   //        vload2  = LoadVectorMasked objb, vmask
6589   //        result1 = VectorCmpMasked vload1, vload2, vmask
6590   //    } else {
6591   //      call_stub_path:
6592   //        result2 = call vectorizedMismatch_stub(obja, objb, length, scale)
6593   //    }
6594   //    exit_block:
6595   //      return Phi(result1, result2);
6596   //
6597   enum { inline_path = 1,  // input is small enough to process it all at once
6598          stub_path   = 2,  // input is too large; call into the VM
6599          PATH_LIMIT  = 3
6600   };
6601 
6602   Node* exit_block = new RegionNode(PATH_LIMIT);
6603   Node* result_phi = new PhiNode(exit_block, TypeInt::INT);
6604   Node* memory_phi = new PhiNode(exit_block, Type::MEMORY, TypePtr::BOTTOM);
6605 
6606   Node* call_stub_path = control();
6607 
6608   BasicType elem_bt = T_ILLEGAL;
6609 
6610   const TypeInt* scale_t = _gvn.type(scale)->is_int();
6611   if (scale_t->is_con()) {
6612     switch (scale_t->get_con()) {
6613       case 0: elem_bt = T_BYTE;  break;
6614       case 1: elem_bt = T_SHORT; break;
6615       case 2: elem_bt = T_INT;   break;
6616       case 3: elem_bt = T_LONG;  break;
6617 
6618       default: elem_bt = T_ILLEGAL; break; // not supported
6619     }
6620   }
6621 
6622   int inline_limit = 0;
6623   bool do_partial_inline = false;
6624 
6625   if (elem_bt != T_ILLEGAL && ArrayOperationPartialInlineSize > 0) {
6626     inline_limit = ArrayOperationPartialInlineSize / type2aelembytes(elem_bt);
6627     do_partial_inline = inline_limit >= 16;
6628   }
6629 
6630   if (do_partial_inline) {
6631     assert(elem_bt != T_ILLEGAL, "sanity");
6632 
6633     if (Matcher::match_rule_supported_vector(Op_VectorMaskGen,    inline_limit, elem_bt) &&
6634         Matcher::match_rule_supported_vector(Op_LoadVectorMasked, inline_limit, elem_bt) &&
6635         Matcher::match_rule_supported_vector(Op_VectorCmpMasked,  inline_limit, elem_bt)) {
6636 
6637       const TypeVect* vt = TypeVect::make(elem_bt, inline_limit);
6638       Node* cmp_length = _gvn.transform(new CmpINode(length, intcon(inline_limit)));
6639       Node* bol_gt     = _gvn.transform(new BoolNode(cmp_length, BoolTest::gt));
6640 
6641       call_stub_path = generate_guard(bol_gt, nullptr, PROB_MIN);
6642 
6643       if (!stopped()) {
6644         Node* casted_length = _gvn.transform(new CastIINode(control(), length, TypeInt::make(0, inline_limit, Type::WidenMin)));
6645 
6646         const TypePtr* obja_adr_t = _gvn.type(obja_adr)->isa_ptr();
6647         const TypePtr* objb_adr_t = _gvn.type(objb_adr)->isa_ptr();
6648         Node* obja_adr_mem = memory(C->get_alias_index(obja_adr_t));
6649         Node* objb_adr_mem = memory(C->get_alias_index(objb_adr_t));
6650 
6651         Node* vmask      = _gvn.transform(VectorMaskGenNode::make(ConvI2X(casted_length), elem_bt));
6652         Node* vload_obja = _gvn.transform(new LoadVectorMaskedNode(control(), obja_adr_mem, obja_adr, obja_adr_t, vt, vmask));
6653         Node* vload_objb = _gvn.transform(new LoadVectorMaskedNode(control(), objb_adr_mem, objb_adr, objb_adr_t, vt, vmask));
6654         Node* result     = _gvn.transform(new VectorCmpMaskedNode(vload_obja, vload_objb, vmask, TypeInt::INT));
6655 
6656         exit_block->init_req(inline_path, control());
6657         memory_phi->init_req(inline_path, map()->memory());
6658         result_phi->init_req(inline_path, result);
6659 
6660         C->set_max_vector_size(MAX2((uint)ArrayOperationPartialInlineSize, C->max_vector_size()));
6661         clear_upper_avx();
6662       }
6663     }
6664   }
6665 
6666   if (call_stub_path != nullptr) {
6667     set_control(call_stub_path);
6668 
6669     Node* call = make_runtime_call(RC_LEAF,
6670                                    OptoRuntime::vectorizedMismatch_Type(),
6671                                    StubRoutines::vectorizedMismatch(), "vectorizedMismatch", TypePtr::BOTTOM,
6672                                    obja_adr, objb_adr, length, scale);
6673 
6674     exit_block->init_req(stub_path, control());
6675     memory_phi->init_req(stub_path, map()->memory());
6676     result_phi->init_req(stub_path, _gvn.transform(new ProjNode(call, TypeFunc::Parms)));
6677   }
6678 
6679   exit_block = _gvn.transform(exit_block);
6680   memory_phi = _gvn.transform(memory_phi);
6681   result_phi = _gvn.transform(result_phi);
6682 
6683   record_for_igvn(exit_block);
6684   record_for_igvn(memory_phi);
6685   record_for_igvn(result_phi);
6686 
6687   set_control(exit_block);
6688   set_all_memory(memory_phi);
6689   set_result(result_phi);
6690 
6691   return true;
6692 }
6693 
6694 //------------------------------inline_vectorizedHashcode----------------------------
6695 bool LibraryCallKit::inline_vectorizedHashCode() {
6696   assert(UseVectorizedHashCodeIntrinsic, "not implemented on this platform");
6697 
6698   assert(callee()->signature()->size() == 5, "vectorizedHashCode has 5 parameters");
6699   Node* array          = argument(0);
6700   Node* offset         = argument(1);
6701   Node* length         = argument(2);
6702   Node* initialValue   = argument(3);
6703   Node* basic_type     = argument(4);
6704 
6705   if (basic_type == top()) {
6706     return false; // failed input validation
6707   }
6708 
6709   const TypeInt* basic_type_t = _gvn.type(basic_type)->is_int();
6710   if (!basic_type_t->is_con()) {
6711     return false; // Only intrinsify if mode argument is constant
6712   }
6713 
6714   array = must_be_not_null(array, true);
6715 
6716   BasicType bt = (BasicType)basic_type_t->get_con();
6717 
6718   // Resolve address of first element
6719   Node* array_start = array_element_address(array, offset, bt);
6720 
6721   set_result(_gvn.transform(new VectorizedHashCodeNode(control(), memory(TypeAryPtr::get_array_body_type(bt)),
6722     array_start, length, initialValue, basic_type)));
6723   clear_upper_avx();
6724 
6725   return true;
6726 }
6727 
6728 /**
6729  * Calculate CRC32 for byte.
6730  * int java.util.zip.CRC32.update(int crc, int b)
6731  */
6732 bool LibraryCallKit::inline_updateCRC32() {
6733   assert(UseCRC32Intrinsics, "need AVX and CLMUL instructions support");
6734   assert(callee()->signature()->size() == 2, "update has 2 parameters");
6735   // no receiver since it is static method
6736   Node* crc  = argument(0); // type: int
6737   Node* b    = argument(1); // type: int
6738 
6739   /*
6740    *    int c = ~ crc;
6741    *    b = timesXtoThe32[(b ^ c) & 0xFF];
6742    *    b = b ^ (c >>> 8);
6743    *    crc = ~b;
6744    */
6745 
6746   Node* M1 = intcon(-1);
6747   crc = _gvn.transform(new XorINode(crc, M1));
6748   Node* result = _gvn.transform(new XorINode(crc, b));
6749   result = _gvn.transform(new AndINode(result, intcon(0xFF)));
6750 
6751   Node* base = makecon(TypeRawPtr::make(StubRoutines::crc_table_addr()));
6752   Node* offset = _gvn.transform(new LShiftINode(result, intcon(0x2)));
6753   Node* adr = basic_plus_adr(top(), base, ConvI2X(offset));
6754   result = make_load(control(), adr, TypeInt::INT, T_INT, MemNode::unordered);
6755 
6756   crc = _gvn.transform(new URShiftINode(crc, intcon(8)));
6757   result = _gvn.transform(new XorINode(crc, result));
6758   result = _gvn.transform(new XorINode(result, M1));
6759   set_result(result);
6760   return true;
6761 }
6762 
6763 /**
6764  * Calculate CRC32 for byte[] array.
6765  * int java.util.zip.CRC32.updateBytes(int crc, byte[] buf, int off, int len)
6766  */
6767 bool LibraryCallKit::inline_updateBytesCRC32() {
6768   assert(UseCRC32Intrinsics, "need AVX and CLMUL instructions support");
6769   assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
6770   // no receiver since it is static method
6771   Node* crc     = argument(0); // type: int
6772   Node* src     = argument(1); // type: oop
6773   Node* offset  = argument(2); // type: int
6774   Node* length  = argument(3); // type: int
6775 
6776   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
6777   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
6778     // failed array check
6779     return false;
6780   }
6781 
6782   // Figure out the size and type of the elements we will be copying.
6783   BasicType src_elem = src_type->elem()->array_element_basic_type();
6784   if (src_elem != T_BYTE) {
6785     return false;
6786   }
6787 
6788   // 'src_start' points to src array + scaled offset
6789   src = must_be_not_null(src, true);
6790   Node* src_start = array_element_address(src, offset, src_elem);
6791 
6792   // We assume that range check is done by caller.
6793   // TODO: generate range check (offset+length < src.length) in debug VM.
6794 
6795   // Call the stub.
6796   address stubAddr = StubRoutines::updateBytesCRC32();
6797   const char *stubName = "updateBytesCRC32";
6798 
6799   Node* call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::updateBytesCRC32_Type(),
6800                                  stubAddr, stubName, TypePtr::BOTTOM,
6801                                  crc, src_start, length);
6802   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
6803   set_result(result);
6804   return true;
6805 }
6806 
6807 /**
6808  * Calculate CRC32 for ByteBuffer.
6809  * int java.util.zip.CRC32.updateByteBuffer(int crc, long buf, int off, int len)
6810  */
6811 bool LibraryCallKit::inline_updateByteBufferCRC32() {
6812   assert(UseCRC32Intrinsics, "need AVX and CLMUL instructions support");
6813   assert(callee()->signature()->size() == 5, "updateByteBuffer has 4 parameters and one is long");
6814   // no receiver since it is static method
6815   Node* crc     = argument(0); // type: int
6816   Node* src     = argument(1); // type: long
6817   Node* offset  = argument(3); // type: int
6818   Node* length  = argument(4); // type: int
6819 
6820   src = ConvL2X(src);  // adjust Java long to machine word
6821   Node* base = _gvn.transform(new CastX2PNode(src));
6822   offset = ConvI2X(offset);
6823 
6824   // 'src_start' points to src array + scaled offset
6825   Node* src_start = basic_plus_adr(top(), base, offset);
6826 
6827   // Call the stub.
6828   address stubAddr = StubRoutines::updateBytesCRC32();
6829   const char *stubName = "updateBytesCRC32";
6830 
6831   Node* call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::updateBytesCRC32_Type(),
6832                                  stubAddr, stubName, TypePtr::BOTTOM,
6833                                  crc, src_start, length);
6834   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
6835   set_result(result);
6836   return true;
6837 }
6838 
6839 //------------------------------get_table_from_crc32c_class-----------------------
6840 Node * LibraryCallKit::get_table_from_crc32c_class(ciInstanceKlass *crc32c_class) {
6841   Node* table = load_field_from_object(nullptr, "byteTable", "[I", /*decorators*/ IN_HEAP, /*is_static*/ true, crc32c_class);
6842   assert (table != nullptr, "wrong version of java.util.zip.CRC32C");
6843 
6844   return table;
6845 }
6846 
6847 //------------------------------inline_updateBytesCRC32C-----------------------
6848 //
6849 // Calculate CRC32C for byte[] array.
6850 // int java.util.zip.CRC32C.updateBytes(int crc, byte[] buf, int off, int end)
6851 //
6852 bool LibraryCallKit::inline_updateBytesCRC32C() {
6853   assert(UseCRC32CIntrinsics, "need CRC32C instruction support");
6854   assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
6855   assert(callee()->holder()->is_loaded(), "CRC32C class must be loaded");
6856   // no receiver since it is a static method
6857   Node* crc     = argument(0); // type: int
6858   Node* src     = argument(1); // type: oop
6859   Node* offset  = argument(2); // type: int
6860   Node* end     = argument(3); // type: int
6861 
6862   Node* length = _gvn.transform(new SubINode(end, offset));
6863 
6864   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
6865   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
6866     // failed array check
6867     return false;
6868   }
6869 
6870   // Figure out the size and type of the elements we will be copying.
6871   BasicType src_elem = src_type->elem()->array_element_basic_type();
6872   if (src_elem != T_BYTE) {
6873     return false;
6874   }
6875 
6876   // 'src_start' points to src array + scaled offset
6877   src = must_be_not_null(src, true);
6878   Node* src_start = array_element_address(src, offset, src_elem);
6879 
6880   // static final int[] byteTable in class CRC32C
6881   Node* table = get_table_from_crc32c_class(callee()->holder());
6882   table = must_be_not_null(table, true);
6883   Node* table_start = array_element_address(table, intcon(0), T_INT);
6884 
6885   // We assume that range check is done by caller.
6886   // TODO: generate range check (offset+length < src.length) in debug VM.
6887 
6888   // Call the stub.
6889   address stubAddr = StubRoutines::updateBytesCRC32C();
6890   const char *stubName = "updateBytesCRC32C";
6891 
6892   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesCRC32C_Type(),
6893                                  stubAddr, stubName, TypePtr::BOTTOM,
6894                                  crc, src_start, length, table_start);
6895   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
6896   set_result(result);
6897   return true;
6898 }
6899 
6900 //------------------------------inline_updateDirectByteBufferCRC32C-----------------------
6901 //
6902 // Calculate CRC32C for DirectByteBuffer.
6903 // int java.util.zip.CRC32C.updateDirectByteBuffer(int crc, long buf, int off, int end)
6904 //
6905 bool LibraryCallKit::inline_updateDirectByteBufferCRC32C() {
6906   assert(UseCRC32CIntrinsics, "need CRC32C instruction support");
6907   assert(callee()->signature()->size() == 5, "updateDirectByteBuffer has 4 parameters and one is long");
6908   assert(callee()->holder()->is_loaded(), "CRC32C class must be loaded");
6909   // no receiver since it is a static method
6910   Node* crc     = argument(0); // type: int
6911   Node* src     = argument(1); // type: long
6912   Node* offset  = argument(3); // type: int
6913   Node* end     = argument(4); // type: int
6914 
6915   Node* length = _gvn.transform(new SubINode(end, offset));
6916 
6917   src = ConvL2X(src);  // adjust Java long to machine word
6918   Node* base = _gvn.transform(new CastX2PNode(src));
6919   offset = ConvI2X(offset);
6920 
6921   // 'src_start' points to src array + scaled offset
6922   Node* src_start = basic_plus_adr(top(), base, offset);
6923 
6924   // static final int[] byteTable in class CRC32C
6925   Node* table = get_table_from_crc32c_class(callee()->holder());
6926   table = must_be_not_null(table, true);
6927   Node* table_start = array_element_address(table, intcon(0), T_INT);
6928 
6929   // Call the stub.
6930   address stubAddr = StubRoutines::updateBytesCRC32C();
6931   const char *stubName = "updateBytesCRC32C";
6932 
6933   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesCRC32C_Type(),
6934                                  stubAddr, stubName, TypePtr::BOTTOM,
6935                                  crc, src_start, length, table_start);
6936   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
6937   set_result(result);
6938   return true;
6939 }
6940 
6941 //------------------------------inline_updateBytesAdler32----------------------
6942 //
6943 // Calculate Adler32 checksum for byte[] array.
6944 // int java.util.zip.Adler32.updateBytes(int crc, byte[] buf, int off, int len)
6945 //
6946 bool LibraryCallKit::inline_updateBytesAdler32() {
6947   assert(UseAdler32Intrinsics, "Adler32 Intrinsic support need"); // check if we actually need to check this flag or check a different one
6948   assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
6949   assert(callee()->holder()->is_loaded(), "Adler32 class must be loaded");
6950   // no receiver since it is static method
6951   Node* crc     = argument(0); // type: int
6952   Node* src     = argument(1); // type: oop
6953   Node* offset  = argument(2); // type: int
6954   Node* length  = argument(3); // type: int
6955 
6956   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
6957   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
6958     // failed array check
6959     return false;
6960   }
6961 
6962   // Figure out the size and type of the elements we will be copying.
6963   BasicType src_elem = src_type->elem()->array_element_basic_type();
6964   if (src_elem != T_BYTE) {
6965     return false;
6966   }
6967 
6968   // 'src_start' points to src array + scaled offset
6969   Node* src_start = array_element_address(src, offset, src_elem);
6970 
6971   // We assume that range check is done by caller.
6972   // TODO: generate range check (offset+length < src.length) in debug VM.
6973 
6974   // Call the stub.
6975   address stubAddr = StubRoutines::updateBytesAdler32();
6976   const char *stubName = "updateBytesAdler32";
6977 
6978   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesAdler32_Type(),
6979                                  stubAddr, stubName, TypePtr::BOTTOM,
6980                                  crc, src_start, length);
6981   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
6982   set_result(result);
6983   return true;
6984 }
6985 
6986 //------------------------------inline_updateByteBufferAdler32---------------
6987 //
6988 // Calculate Adler32 checksum for DirectByteBuffer.
6989 // int java.util.zip.Adler32.updateByteBuffer(int crc, long buf, int off, int len)
6990 //
6991 bool LibraryCallKit::inline_updateByteBufferAdler32() {
6992   assert(UseAdler32Intrinsics, "Adler32 Intrinsic support need"); // check if we actually need to check this flag or check a different one
6993   assert(callee()->signature()->size() == 5, "updateByteBuffer has 4 parameters and one is long");
6994   assert(callee()->holder()->is_loaded(), "Adler32 class must be loaded");
6995   // no receiver since it is static method
6996   Node* crc     = argument(0); // type: int
6997   Node* src     = argument(1); // type: long
6998   Node* offset  = argument(3); // type: int
6999   Node* length  = argument(4); // type: int
7000 
7001   src = ConvL2X(src);  // adjust Java long to machine word
7002   Node* base = _gvn.transform(new CastX2PNode(src));
7003   offset = ConvI2X(offset);
7004 
7005   // 'src_start' points to src array + scaled offset
7006   Node* src_start = basic_plus_adr(top(), base, offset);
7007 
7008   // Call the stub.
7009   address stubAddr = StubRoutines::updateBytesAdler32();
7010   const char *stubName = "updateBytesAdler32";
7011 
7012   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesAdler32_Type(),
7013                                  stubAddr, stubName, TypePtr::BOTTOM,
7014                                  crc, src_start, length);
7015 
7016   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7017   set_result(result);
7018   return true;
7019 }
7020 
7021 //----------------------------inline_reference_get0----------------------------
7022 // public T java.lang.ref.Reference.get();
7023 bool LibraryCallKit::inline_reference_get0() {
7024   const int referent_offset = java_lang_ref_Reference::referent_offset();
7025 
7026   // Get the argument:
7027   Node* reference_obj = null_check_receiver();
7028   if (stopped()) return true;
7029 
7030   DecoratorSet decorators = IN_HEAP | ON_WEAK_OOP_REF;
7031   Node* result = load_field_from_object(reference_obj, "referent", "Ljava/lang/Object;",
7032                                         decorators, /*is_static*/ false, nullptr);
7033   if (result == nullptr) return false;
7034 
7035   // Add memory barrier to prevent commoning reads from this field
7036   // across safepoint since GC can change its value.
7037   insert_mem_bar(Op_MemBarCPUOrder);
7038 
7039   set_result(result);
7040   return true;
7041 }
7042 
7043 //----------------------------inline_reference_refersTo0----------------------------
7044 // bool java.lang.ref.Reference.refersTo0();
7045 // bool java.lang.ref.PhantomReference.refersTo0();
7046 bool LibraryCallKit::inline_reference_refersTo0(bool is_phantom) {
7047   // Get arguments:
7048   Node* reference_obj = null_check_receiver();
7049   Node* other_obj = argument(1);
7050   if (stopped()) return true;
7051 
7052   DecoratorSet decorators = IN_HEAP | AS_NO_KEEPALIVE;
7053   decorators |= (is_phantom ? ON_PHANTOM_OOP_REF : ON_WEAK_OOP_REF);
7054   Node* referent = load_field_from_object(reference_obj, "referent", "Ljava/lang/Object;",
7055                                           decorators, /*is_static*/ false, nullptr);
7056   if (referent == nullptr) return false;
7057 
7058   // Add memory barrier to prevent commoning reads from this field
7059   // across safepoint since GC can change its value.
7060   insert_mem_bar(Op_MemBarCPUOrder);
7061 
7062   Node* cmp = _gvn.transform(new CmpPNode(referent, other_obj));
7063   Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
7064   IfNode* if_node = create_and_map_if(control(), bol, PROB_FAIR, COUNT_UNKNOWN);
7065 
7066   RegionNode* region = new RegionNode(3);
7067   PhiNode* phi = new PhiNode(region, TypeInt::BOOL);
7068 
7069   Node* if_true = _gvn.transform(new IfTrueNode(if_node));
7070   region->init_req(1, if_true);
7071   phi->init_req(1, intcon(1));
7072 
7073   Node* if_false = _gvn.transform(new IfFalseNode(if_node));
7074   region->init_req(2, if_false);
7075   phi->init_req(2, intcon(0));
7076 
7077   set_control(_gvn.transform(region));
7078   record_for_igvn(region);
7079   set_result(_gvn.transform(phi));
7080   return true;
7081 }
7082 
7083 //----------------------------inline_reference_clear0----------------------------
7084 // void java.lang.ref.Reference.clear0();
7085 // void java.lang.ref.PhantomReference.clear0();
7086 bool LibraryCallKit::inline_reference_clear0(bool is_phantom) {
7087   // This matches the implementation in JVM_ReferenceClear, see the comments there.
7088 
7089   // Get arguments
7090   Node* reference_obj = null_check_receiver();
7091   if (stopped()) return true;
7092 
7093   // Common access parameters
7094   DecoratorSet decorators = IN_HEAP | AS_NO_KEEPALIVE;
7095   decorators |= (is_phantom ? ON_PHANTOM_OOP_REF : ON_WEAK_OOP_REF);
7096   Node* referent_field_addr = basic_plus_adr(reference_obj, java_lang_ref_Reference::referent_offset());
7097   const TypePtr* referent_field_addr_type = _gvn.type(referent_field_addr)->isa_ptr();
7098   const Type* val_type = TypeOopPtr::make_from_klass(env()->Object_klass());
7099 
7100   Node* referent = access_load_at(reference_obj,
7101                                   referent_field_addr,
7102                                   referent_field_addr_type,
7103                                   val_type,
7104                                   T_OBJECT,
7105                                   decorators);
7106 
7107   IdealKit ideal(this);
7108 #define __ ideal.
7109   __ if_then(referent, BoolTest::ne, null());
7110     sync_kit(ideal);
7111     access_store_at(reference_obj,
7112                     referent_field_addr,
7113                     referent_field_addr_type,
7114                     null(),
7115                     val_type,
7116                     T_OBJECT,
7117                     decorators);
7118     __ sync_kit(this);
7119   __ end_if();
7120   final_sync(ideal);
7121 #undef __
7122 
7123   return true;
7124 }
7125 
7126 Node* LibraryCallKit::load_field_from_object(Node* fromObj, const char* fieldName, const char* fieldTypeString,
7127                                              DecoratorSet decorators, bool is_static,
7128                                              ciInstanceKlass* fromKls) {
7129   if (fromKls == nullptr) {
7130     const TypeInstPtr* tinst = _gvn.type(fromObj)->isa_instptr();
7131     assert(tinst != nullptr, "obj is null");
7132     assert(tinst->is_loaded(), "obj is not loaded");
7133     fromKls = tinst->instance_klass();
7134   } else {
7135     assert(is_static, "only for static field access");
7136   }
7137   ciField* field = fromKls->get_field_by_name(ciSymbol::make(fieldName),
7138                                               ciSymbol::make(fieldTypeString),
7139                                               is_static);
7140 
7141   assert(field != nullptr, "undefined field %s %s %s", fieldTypeString, fromKls->name()->as_utf8(), fieldName);
7142   if (field == nullptr) return (Node *) nullptr;
7143 
7144   if (is_static) {
7145     const TypeInstPtr* tip = TypeInstPtr::make(fromKls->java_mirror());
7146     fromObj = makecon(tip);
7147   }
7148 
7149   // Next code  copied from Parse::do_get_xxx():
7150 
7151   // Compute address and memory type.
7152   int offset  = field->offset_in_bytes();
7153   bool is_vol = field->is_volatile();
7154   ciType* field_klass = field->type();
7155   assert(field_klass->is_loaded(), "should be loaded");
7156   const TypePtr* adr_type = C->alias_type(field)->adr_type();
7157   Node *adr = basic_plus_adr(fromObj, fromObj, offset);
7158   assert(C->get_alias_index(adr_type) == C->get_alias_index(_gvn.type(adr)->isa_ptr()),
7159     "slice of address and input slice don't match");
7160   BasicType bt = field->layout_type();
7161 
7162   // Build the resultant type of the load
7163   const Type *type;
7164   if (bt == T_OBJECT) {
7165     type = TypeOopPtr::make_from_klass(field_klass->as_klass());
7166   } else {
7167     type = Type::get_const_basic_type(bt);
7168   }
7169 
7170   if (is_vol) {
7171     decorators |= MO_SEQ_CST;
7172   }
7173 
7174   return access_load_at(fromObj, adr, adr_type, type, bt, decorators);
7175 }
7176 
7177 Node * LibraryCallKit::field_address_from_object(Node * fromObj, const char * fieldName, const char * fieldTypeString,
7178                                                  bool is_exact /* true */, bool is_static /* false */,
7179                                                  ciInstanceKlass * fromKls /* nullptr */) {
7180   if (fromKls == nullptr) {
7181     const TypeInstPtr* tinst = _gvn.type(fromObj)->isa_instptr();
7182     assert(tinst != nullptr, "obj is null");
7183     assert(tinst->is_loaded(), "obj is not loaded");
7184     assert(!is_exact || tinst->klass_is_exact(), "klass not exact");
7185     fromKls = tinst->instance_klass();
7186   }
7187   else {
7188     assert(is_static, "only for static field access");
7189   }
7190   ciField* field = fromKls->get_field_by_name(ciSymbol::make(fieldName),
7191     ciSymbol::make(fieldTypeString),
7192     is_static);
7193 
7194   assert(field != nullptr, "undefined field");
7195   assert(!field->is_volatile(), "not defined for volatile fields");
7196 
7197   if (is_static) {
7198     const TypeInstPtr* tip = TypeInstPtr::make(fromKls->java_mirror());
7199     fromObj = makecon(tip);
7200   }
7201 
7202   // Next code  copied from Parse::do_get_xxx():
7203 
7204   // Compute address and memory type.
7205   int offset = field->offset_in_bytes();
7206   Node *adr = basic_plus_adr(fromObj, fromObj, offset);
7207 
7208   return adr;
7209 }
7210 
7211 //------------------------------inline_aescrypt_Block-----------------------
7212 bool LibraryCallKit::inline_aescrypt_Block(vmIntrinsics::ID id) {
7213   address stubAddr = nullptr;
7214   const char *stubName;
7215   bool is_decrypt = false;
7216   assert(UseAES, "need AES instruction support");
7217 
7218   switch(id) {
7219   case vmIntrinsics::_aescrypt_encryptBlock:
7220     stubAddr = StubRoutines::aescrypt_encryptBlock();
7221     stubName = "aescrypt_encryptBlock";
7222     break;
7223   case vmIntrinsics::_aescrypt_decryptBlock:
7224     stubAddr = StubRoutines::aescrypt_decryptBlock();
7225     stubName = "aescrypt_decryptBlock";
7226     is_decrypt = true;
7227     break;
7228   default:
7229     break;
7230   }
7231   if (stubAddr == nullptr) return false;
7232 
7233   Node* aescrypt_object = argument(0);
7234   Node* src             = argument(1);
7235   Node* src_offset      = argument(2);
7236   Node* dest            = argument(3);
7237   Node* dest_offset     = argument(4);
7238 
7239   src = must_be_not_null(src, true);
7240   dest = must_be_not_null(dest, true);
7241 
7242   // (1) src and dest are arrays.
7243   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7244   const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
7245   assert( src_type != nullptr &&  src_type->elem() != Type::BOTTOM &&
7246          dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
7247 
7248   // for the quick and dirty code we will skip all the checks.
7249   // we are just trying to get the call to be generated.
7250   Node* src_start  = src;
7251   Node* dest_start = dest;
7252   if (src_offset != nullptr || dest_offset != nullptr) {
7253     assert(src_offset != nullptr && dest_offset != nullptr, "");
7254     src_start  = array_element_address(src,  src_offset,  T_BYTE);
7255     dest_start = array_element_address(dest, dest_offset, T_BYTE);
7256   }
7257 
7258   // now need to get the start of its expanded key array
7259   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
7260   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object, is_decrypt);
7261   if (k_start == nullptr) return false;
7262 
7263   // Call the stub.
7264   make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::aescrypt_block_Type(),
7265                     stubAddr, stubName, TypePtr::BOTTOM,
7266                     src_start, dest_start, k_start);
7267 
7268   return true;
7269 }
7270 
7271 //------------------------------inline_cipherBlockChaining_AESCrypt-----------------------
7272 bool LibraryCallKit::inline_cipherBlockChaining_AESCrypt(vmIntrinsics::ID id) {
7273   address stubAddr = nullptr;
7274   const char *stubName = nullptr;
7275   bool is_decrypt = false;
7276   assert(UseAES, "need AES instruction support");
7277 
7278   switch(id) {
7279   case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
7280     stubAddr = StubRoutines::cipherBlockChaining_encryptAESCrypt();
7281     stubName = "cipherBlockChaining_encryptAESCrypt";
7282     break;
7283   case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
7284     stubAddr = StubRoutines::cipherBlockChaining_decryptAESCrypt();
7285     stubName = "cipherBlockChaining_decryptAESCrypt";
7286     is_decrypt = true;
7287     break;
7288   default:
7289     break;
7290   }
7291   if (stubAddr == nullptr) return false;
7292 
7293   Node* cipherBlockChaining_object = argument(0);
7294   Node* src                        = argument(1);
7295   Node* src_offset                 = argument(2);
7296   Node* len                        = argument(3);
7297   Node* dest                       = argument(4);
7298   Node* dest_offset                = argument(5);
7299 
7300   src = must_be_not_null(src, false);
7301   dest = must_be_not_null(dest, false);
7302 
7303   // (1) src and dest are arrays.
7304   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7305   const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
7306   assert( src_type != nullptr &&  src_type->elem() != Type::BOTTOM &&
7307          dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
7308 
7309   // checks are the responsibility of the caller
7310   Node* src_start  = src;
7311   Node* dest_start = dest;
7312   if (src_offset != nullptr || dest_offset != nullptr) {
7313     assert(src_offset != nullptr && dest_offset != nullptr, "");
7314     src_start  = array_element_address(src,  src_offset,  T_BYTE);
7315     dest_start = array_element_address(dest, dest_offset, T_BYTE);
7316   }
7317 
7318   // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
7319   // (because of the predicated logic executed earlier).
7320   // so we cast it here safely.
7321   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
7322 
7323   Node* embeddedCipherObj = load_field_from_object(cipherBlockChaining_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
7324   if (embeddedCipherObj == nullptr) return false;
7325 
7326   // cast it to what we know it will be at runtime
7327   const TypeInstPtr* tinst = _gvn.type(cipherBlockChaining_object)->isa_instptr();
7328   assert(tinst != nullptr, "CBC obj is null");
7329   assert(tinst->is_loaded(), "CBC obj is not loaded");
7330   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
7331   assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
7332 
7333   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
7334   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
7335   const TypeOopPtr* xtype = aklass->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
7336   Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
7337   aescrypt_object = _gvn.transform(aescrypt_object);
7338 
7339   // we need to get the start of the aescrypt_object's expanded key array
7340   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object, is_decrypt);
7341   if (k_start == nullptr) return false;
7342 
7343   // similarly, get the start address of the r vector
7344   Node* objRvec = load_field_from_object(cipherBlockChaining_object, "r", "[B");
7345   if (objRvec == nullptr) return false;
7346   Node* r_start = array_element_address(objRvec, intcon(0), T_BYTE);
7347 
7348   // Call the stub, passing src_start, dest_start, k_start, r_start and src_len
7349   Node* cbcCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
7350                                      OptoRuntime::cipherBlockChaining_aescrypt_Type(),
7351                                      stubAddr, stubName, TypePtr::BOTTOM,
7352                                      src_start, dest_start, k_start, r_start, len);
7353 
7354   // return cipher length (int)
7355   Node* retvalue = _gvn.transform(new ProjNode(cbcCrypt, TypeFunc::Parms));
7356   set_result(retvalue);
7357   return true;
7358 }
7359 
7360 //------------------------------inline_electronicCodeBook_AESCrypt-----------------------
7361 bool LibraryCallKit::inline_electronicCodeBook_AESCrypt(vmIntrinsics::ID id) {
7362   address stubAddr = nullptr;
7363   const char *stubName = nullptr;
7364   bool is_decrypt = false;
7365   assert(UseAES, "need AES instruction support");
7366 
7367   switch (id) {
7368   case vmIntrinsics::_electronicCodeBook_encryptAESCrypt:
7369     stubAddr = StubRoutines::electronicCodeBook_encryptAESCrypt();
7370     stubName = "electronicCodeBook_encryptAESCrypt";
7371     break;
7372   case vmIntrinsics::_electronicCodeBook_decryptAESCrypt:
7373     stubAddr = StubRoutines::electronicCodeBook_decryptAESCrypt();
7374     stubName = "electronicCodeBook_decryptAESCrypt";
7375     is_decrypt = true;
7376     break;
7377   default:
7378     break;
7379   }
7380 
7381   if (stubAddr == nullptr) return false;
7382 
7383   Node* electronicCodeBook_object = argument(0);
7384   Node* src                       = argument(1);
7385   Node* src_offset                = argument(2);
7386   Node* len                       = argument(3);
7387   Node* dest                      = argument(4);
7388   Node* dest_offset               = argument(5);
7389 
7390   // (1) src and dest are arrays.
7391   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7392   const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
7393   assert( src_type != nullptr &&  src_type->elem() != Type::BOTTOM &&
7394          dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
7395 
7396   // checks are the responsibility of the caller
7397   Node* src_start = src;
7398   Node* dest_start = dest;
7399   if (src_offset != nullptr || dest_offset != nullptr) {
7400     assert(src_offset != nullptr && dest_offset != nullptr, "");
7401     src_start = array_element_address(src, src_offset, T_BYTE);
7402     dest_start = array_element_address(dest, dest_offset, T_BYTE);
7403   }
7404 
7405   // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
7406   // (because of the predicated logic executed earlier).
7407   // so we cast it here safely.
7408   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
7409 
7410   Node* embeddedCipherObj = load_field_from_object(electronicCodeBook_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
7411   if (embeddedCipherObj == nullptr) return false;
7412 
7413   // cast it to what we know it will be at runtime
7414   const TypeInstPtr* tinst = _gvn.type(electronicCodeBook_object)->isa_instptr();
7415   assert(tinst != nullptr, "ECB obj is null");
7416   assert(tinst->is_loaded(), "ECB obj is not loaded");
7417   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
7418   assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
7419 
7420   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
7421   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
7422   const TypeOopPtr* xtype = aklass->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
7423   Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
7424   aescrypt_object = _gvn.transform(aescrypt_object);
7425 
7426   // we need to get the start of the aescrypt_object's expanded key array
7427   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object, is_decrypt);
7428   if (k_start == nullptr) return false;
7429 
7430   // Call the stub, passing src_start, dest_start, k_start, r_start and src_len
7431   Node* ecbCrypt = make_runtime_call(RC_LEAF | RC_NO_FP,
7432                                      OptoRuntime::electronicCodeBook_aescrypt_Type(),
7433                                      stubAddr, stubName, TypePtr::BOTTOM,
7434                                      src_start, dest_start, k_start, len);
7435 
7436   // return cipher length (int)
7437   Node* retvalue = _gvn.transform(new ProjNode(ecbCrypt, TypeFunc::Parms));
7438   set_result(retvalue);
7439   return true;
7440 }
7441 
7442 //------------------------------inline_counterMode_AESCrypt-----------------------
7443 bool LibraryCallKit::inline_counterMode_AESCrypt(vmIntrinsics::ID id) {
7444   assert(UseAES, "need AES instruction support");
7445   if (!UseAESCTRIntrinsics) return false;
7446 
7447   address stubAddr = nullptr;
7448   const char *stubName = nullptr;
7449   if (id == vmIntrinsics::_counterMode_AESCrypt) {
7450     stubAddr = StubRoutines::counterMode_AESCrypt();
7451     stubName = "counterMode_AESCrypt";
7452   }
7453   if (stubAddr == nullptr) return false;
7454 
7455   Node* counterMode_object = argument(0);
7456   Node* src = argument(1);
7457   Node* src_offset = argument(2);
7458   Node* len = argument(3);
7459   Node* dest = argument(4);
7460   Node* dest_offset = argument(5);
7461 
7462   // (1) src and dest are arrays.
7463   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7464   const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
7465   assert( src_type != nullptr &&  src_type->elem() != Type::BOTTOM &&
7466          dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
7467 
7468   // checks are the responsibility of the caller
7469   Node* src_start = src;
7470   Node* dest_start = dest;
7471   if (src_offset != nullptr || dest_offset != nullptr) {
7472     assert(src_offset != nullptr && dest_offset != nullptr, "");
7473     src_start = array_element_address(src, src_offset, T_BYTE);
7474     dest_start = array_element_address(dest, dest_offset, T_BYTE);
7475   }
7476 
7477   // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
7478   // (because of the predicated logic executed earlier).
7479   // so we cast it here safely.
7480   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
7481   Node* embeddedCipherObj = load_field_from_object(counterMode_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
7482   if (embeddedCipherObj == nullptr) return false;
7483   // cast it to what we know it will be at runtime
7484   const TypeInstPtr* tinst = _gvn.type(counterMode_object)->isa_instptr();
7485   assert(tinst != nullptr, "CTR obj is null");
7486   assert(tinst->is_loaded(), "CTR obj is not loaded");
7487   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
7488   assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
7489   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
7490   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
7491   const TypeOopPtr* xtype = aklass->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
7492   Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
7493   aescrypt_object = _gvn.transform(aescrypt_object);
7494   // we need to get the start of the aescrypt_object's expanded key array
7495   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object, /* is_decrypt */ false);
7496   if (k_start == nullptr) return false;
7497   // similarly, get the start address of the r vector
7498   Node* obj_counter = load_field_from_object(counterMode_object, "counter", "[B");
7499   if (obj_counter == nullptr) return false;
7500   Node* cnt_start = array_element_address(obj_counter, intcon(0), T_BYTE);
7501 
7502   Node* saved_encCounter = load_field_from_object(counterMode_object, "encryptedCounter", "[B");
7503   if (saved_encCounter == nullptr) return false;
7504   Node* saved_encCounter_start = array_element_address(saved_encCounter, intcon(0), T_BYTE);
7505   Node* used = field_address_from_object(counterMode_object, "used", "I", /*is_exact*/ false);
7506 
7507   // Call the stub, passing src_start, dest_start, k_start, r_start and src_len
7508   Node* ctrCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
7509                                      OptoRuntime::counterMode_aescrypt_Type(),
7510                                      stubAddr, stubName, TypePtr::BOTTOM,
7511                                      src_start, dest_start, k_start, cnt_start, len, saved_encCounter_start, used);
7512 
7513   // return cipher length (int)
7514   Node* retvalue = _gvn.transform(new ProjNode(ctrCrypt, TypeFunc::Parms));
7515   set_result(retvalue);
7516   return true;
7517 }
7518 
7519 //------------------------------get_key_start_from_aescrypt_object-----------------------
7520 Node* LibraryCallKit::get_key_start_from_aescrypt_object(Node* aescrypt_object, bool is_decrypt) {
7521   // MixColumns for decryption can be reduced by preprocessing MixColumns with round keys.
7522   // Intel's extension is based on this optimization and AESCrypt generates round keys by preprocessing MixColumns.
7523   // However, ppc64 vncipher processes MixColumns and requires the same round keys with encryption.
7524   // The following platform specific stubs of encryption and decryption use the same round keys.
7525 #if defined(PPC64) || defined(S390) || defined(RISCV64)
7526   bool use_decryption_key = false;
7527 #else
7528   bool use_decryption_key = is_decrypt;
7529 #endif
7530   Node* objAESCryptKey = load_field_from_object(aescrypt_object, use_decryption_key ? "sessionKd" : "sessionKe", "[I");
7531   assert(objAESCryptKey != nullptr, "wrong version of com.sun.crypto.provider.AES_Crypt");
7532   if (objAESCryptKey == nullptr) return (Node *) nullptr;
7533 
7534   // now have the array, need to get the start address of the selected key array
7535   Node* k_start = array_element_address(objAESCryptKey, intcon(0), T_INT);
7536   return k_start;
7537 }
7538 
7539 //----------------------------inline_cipherBlockChaining_AESCrypt_predicate----------------------------
7540 // Return node representing slow path of predicate check.
7541 // the pseudo code we want to emulate with this predicate is:
7542 // for encryption:
7543 //    if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
7544 // for decryption:
7545 //    if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
7546 //    note cipher==plain is more conservative than the original java code but that's OK
7547 //
7548 Node* LibraryCallKit::inline_cipherBlockChaining_AESCrypt_predicate(bool decrypting) {
7549   // The receiver was checked for null already.
7550   Node* objCBC = argument(0);
7551 
7552   Node* src = argument(1);
7553   Node* dest = argument(4);
7554 
7555   // Load embeddedCipher field of CipherBlockChaining object.
7556   Node* embeddedCipherObj = load_field_from_object(objCBC, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
7557 
7558   // get AESCrypt klass for instanceOf check
7559   // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
7560   // will have same classloader as CipherBlockChaining object
7561   const TypeInstPtr* tinst = _gvn.type(objCBC)->isa_instptr();
7562   assert(tinst != nullptr, "CBCobj is null");
7563   assert(tinst->is_loaded(), "CBCobj is not loaded");
7564 
7565   // we want to do an instanceof comparison against the AESCrypt class
7566   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
7567   if (!klass_AESCrypt->is_loaded()) {
7568     // if AESCrypt is not even loaded, we never take the intrinsic fast path
7569     Node* ctrl = control();
7570     set_control(top()); // no regular fast path
7571     return ctrl;
7572   }
7573 
7574   src = must_be_not_null(src, true);
7575   dest = must_be_not_null(dest, true);
7576 
7577   // Resolve oops to stable for CmpP below.
7578   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
7579 
7580   Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
7581   Node* cmp_instof  = _gvn.transform(new CmpINode(instof, intcon(1)));
7582   Node* bool_instof  = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
7583 
7584   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
7585 
7586   // for encryption, we are done
7587   if (!decrypting)
7588     return instof_false;  // even if it is null
7589 
7590   // for decryption, we need to add a further check to avoid
7591   // taking the intrinsic path when cipher and plain are the same
7592   // see the original java code for why.
7593   RegionNode* region = new RegionNode(3);
7594   region->init_req(1, instof_false);
7595 
7596   Node* cmp_src_dest = _gvn.transform(new CmpPNode(src, dest));
7597   Node* bool_src_dest = _gvn.transform(new BoolNode(cmp_src_dest, BoolTest::eq));
7598   Node* src_dest_conjoint = generate_guard(bool_src_dest, nullptr, PROB_MIN);
7599   region->init_req(2, src_dest_conjoint);
7600 
7601   record_for_igvn(region);
7602   return _gvn.transform(region);
7603 }
7604 
7605 //----------------------------inline_electronicCodeBook_AESCrypt_predicate----------------------------
7606 // Return node representing slow path of predicate check.
7607 // the pseudo code we want to emulate with this predicate is:
7608 // for encryption:
7609 //    if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
7610 // for decryption:
7611 //    if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
7612 //    note cipher==plain is more conservative than the original java code but that's OK
7613 //
7614 Node* LibraryCallKit::inline_electronicCodeBook_AESCrypt_predicate(bool decrypting) {
7615   // The receiver was checked for null already.
7616   Node* objECB = argument(0);
7617 
7618   // Load embeddedCipher field of ElectronicCodeBook object.
7619   Node* embeddedCipherObj = load_field_from_object(objECB, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
7620 
7621   // get AESCrypt klass for instanceOf check
7622   // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
7623   // will have same classloader as ElectronicCodeBook object
7624   const TypeInstPtr* tinst = _gvn.type(objECB)->isa_instptr();
7625   assert(tinst != nullptr, "ECBobj is null");
7626   assert(tinst->is_loaded(), "ECBobj is not loaded");
7627 
7628   // we want to do an instanceof comparison against the AESCrypt class
7629   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
7630   if (!klass_AESCrypt->is_loaded()) {
7631     // if AESCrypt is not even loaded, we never take the intrinsic fast path
7632     Node* ctrl = control();
7633     set_control(top()); // no regular fast path
7634     return ctrl;
7635   }
7636   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
7637 
7638   Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
7639   Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
7640   Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
7641 
7642   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
7643 
7644   // for encryption, we are done
7645   if (!decrypting)
7646     return instof_false;  // even if it is null
7647 
7648   // for decryption, we need to add a further check to avoid
7649   // taking the intrinsic path when cipher and plain are the same
7650   // see the original java code for why.
7651   RegionNode* region = new RegionNode(3);
7652   region->init_req(1, instof_false);
7653   Node* src = argument(1);
7654   Node* dest = argument(4);
7655   Node* cmp_src_dest = _gvn.transform(new CmpPNode(src, dest));
7656   Node* bool_src_dest = _gvn.transform(new BoolNode(cmp_src_dest, BoolTest::eq));
7657   Node* src_dest_conjoint = generate_guard(bool_src_dest, nullptr, PROB_MIN);
7658   region->init_req(2, src_dest_conjoint);
7659 
7660   record_for_igvn(region);
7661   return _gvn.transform(region);
7662 }
7663 
7664 //----------------------------inline_counterMode_AESCrypt_predicate----------------------------
7665 // Return node representing slow path of predicate check.
7666 // the pseudo code we want to emulate with this predicate is:
7667 // for encryption:
7668 //    if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
7669 // for decryption:
7670 //    if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
7671 //    note cipher==plain is more conservative than the original java code but that's OK
7672 //
7673 
7674 Node* LibraryCallKit::inline_counterMode_AESCrypt_predicate() {
7675   // The receiver was checked for null already.
7676   Node* objCTR = argument(0);
7677 
7678   // Load embeddedCipher field of CipherBlockChaining object.
7679   Node* embeddedCipherObj = load_field_from_object(objCTR, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
7680 
7681   // get AESCrypt klass for instanceOf check
7682   // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
7683   // will have same classloader as CipherBlockChaining object
7684   const TypeInstPtr* tinst = _gvn.type(objCTR)->isa_instptr();
7685   assert(tinst != nullptr, "CTRobj is null");
7686   assert(tinst->is_loaded(), "CTRobj is not loaded");
7687 
7688   // we want to do an instanceof comparison against the AESCrypt class
7689   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
7690   if (!klass_AESCrypt->is_loaded()) {
7691     // if AESCrypt is not even loaded, we never take the intrinsic fast path
7692     Node* ctrl = control();
7693     set_control(top()); // no regular fast path
7694     return ctrl;
7695   }
7696 
7697   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
7698   Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
7699   Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
7700   Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
7701   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
7702 
7703   return instof_false; // even if it is null
7704 }
7705 
7706 //------------------------------inline_ghash_processBlocks
7707 bool LibraryCallKit::inline_ghash_processBlocks() {
7708   address stubAddr;
7709   const char *stubName;
7710   assert(UseGHASHIntrinsics, "need GHASH intrinsics support");
7711 
7712   stubAddr = StubRoutines::ghash_processBlocks();
7713   stubName = "ghash_processBlocks";
7714 
7715   Node* data           = argument(0);
7716   Node* offset         = argument(1);
7717   Node* len            = argument(2);
7718   Node* state          = argument(3);
7719   Node* subkeyH        = argument(4);
7720 
7721   state = must_be_not_null(state, true);
7722   subkeyH = must_be_not_null(subkeyH, true);
7723   data = must_be_not_null(data, true);
7724 
7725   Node* state_start  = array_element_address(state, intcon(0), T_LONG);
7726   assert(state_start, "state is null");
7727   Node* subkeyH_start  = array_element_address(subkeyH, intcon(0), T_LONG);
7728   assert(subkeyH_start, "subkeyH is null");
7729   Node* data_start  = array_element_address(data, offset, T_BYTE);
7730   assert(data_start, "data is null");
7731 
7732   Node* ghash = make_runtime_call(RC_LEAF|RC_NO_FP,
7733                                   OptoRuntime::ghash_processBlocks_Type(),
7734                                   stubAddr, stubName, TypePtr::BOTTOM,
7735                                   state_start, subkeyH_start, data_start, len);
7736   return true;
7737 }
7738 
7739 //------------------------------inline_chacha20Block
7740 bool LibraryCallKit::inline_chacha20Block() {
7741   address stubAddr;
7742   const char *stubName;
7743   assert(UseChaCha20Intrinsics, "need ChaCha20 intrinsics support");
7744 
7745   stubAddr = StubRoutines::chacha20Block();
7746   stubName = "chacha20Block";
7747 
7748   Node* state          = argument(0);
7749   Node* result         = argument(1);
7750 
7751   state = must_be_not_null(state, true);
7752   result = must_be_not_null(result, true);
7753 
7754   Node* state_start  = array_element_address(state, intcon(0), T_INT);
7755   assert(state_start, "state is null");
7756   Node* result_start  = array_element_address(result, intcon(0), T_BYTE);
7757   assert(result_start, "result is null");
7758 
7759   Node* cc20Blk = make_runtime_call(RC_LEAF|RC_NO_FP,
7760                                   OptoRuntime::chacha20Block_Type(),
7761                                   stubAddr, stubName, TypePtr::BOTTOM,
7762                                   state_start, result_start);
7763   // return key stream length (int)
7764   Node* retvalue = _gvn.transform(new ProjNode(cc20Blk, TypeFunc::Parms));
7765   set_result(retvalue);
7766   return true;
7767 }
7768 
7769 //------------------------------inline_kyberNtt
7770 bool LibraryCallKit::inline_kyberNtt() {
7771   address stubAddr;
7772   const char *stubName;
7773   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
7774   assert(callee()->signature()->size() == 2, "kyberNtt has 2 parameters");
7775 
7776   stubAddr = StubRoutines::kyberNtt();
7777   stubName = "kyberNtt";
7778   if (!stubAddr) return false;
7779 
7780   Node* coeffs          = argument(0);
7781   Node* ntt_zetas        = argument(1);
7782 
7783   coeffs = must_be_not_null(coeffs, true);
7784   ntt_zetas = must_be_not_null(ntt_zetas, true);
7785 
7786   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_SHORT);
7787   assert(coeffs_start, "coeffs is null");
7788   Node* ntt_zetas_start  = array_element_address(ntt_zetas, intcon(0), T_SHORT);
7789   assert(ntt_zetas_start, "ntt_zetas is null");
7790   Node* kyberNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
7791                                   OptoRuntime::kyberNtt_Type(),
7792                                   stubAddr, stubName, TypePtr::BOTTOM,
7793                                   coeffs_start, ntt_zetas_start);
7794   // return an int
7795   Node* retvalue = _gvn.transform(new ProjNode(kyberNtt, TypeFunc::Parms));
7796   set_result(retvalue);
7797   return true;
7798 }
7799 
7800 //------------------------------inline_kyberInverseNtt
7801 bool LibraryCallKit::inline_kyberInverseNtt() {
7802   address stubAddr;
7803   const char *stubName;
7804   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
7805   assert(callee()->signature()->size() == 2, "kyberInverseNtt has 2 parameters");
7806 
7807   stubAddr = StubRoutines::kyberInverseNtt();
7808   stubName = "kyberInverseNtt";
7809   if (!stubAddr) return false;
7810 
7811   Node* coeffs          = argument(0);
7812   Node* zetas           = argument(1);
7813 
7814   coeffs = must_be_not_null(coeffs, true);
7815   zetas = must_be_not_null(zetas, true);
7816 
7817   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_SHORT);
7818   assert(coeffs_start, "coeffs is null");
7819   Node* zetas_start  = array_element_address(zetas, intcon(0), T_SHORT);
7820   assert(zetas_start, "inverseNtt_zetas is null");
7821   Node* kyberInverseNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
7822                                   OptoRuntime::kyberInverseNtt_Type(),
7823                                   stubAddr, stubName, TypePtr::BOTTOM,
7824                                   coeffs_start, zetas_start);
7825 
7826   // return an int
7827   Node* retvalue = _gvn.transform(new ProjNode(kyberInverseNtt, TypeFunc::Parms));
7828   set_result(retvalue);
7829   return true;
7830 }
7831 
7832 //------------------------------inline_kyberNttMult
7833 bool LibraryCallKit::inline_kyberNttMult() {
7834   address stubAddr;
7835   const char *stubName;
7836   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
7837   assert(callee()->signature()->size() == 4, "kyberNttMult has 4 parameters");
7838 
7839   stubAddr = StubRoutines::kyberNttMult();
7840   stubName = "kyberNttMult";
7841   if (!stubAddr) return false;
7842 
7843   Node* result          = argument(0);
7844   Node* ntta            = argument(1);
7845   Node* nttb            = argument(2);
7846   Node* zetas           = argument(3);
7847 
7848   result = must_be_not_null(result, true);
7849   ntta = must_be_not_null(ntta, true);
7850   nttb = must_be_not_null(nttb, true);
7851   zetas = must_be_not_null(zetas, true);
7852 
7853   Node* result_start  = array_element_address(result, intcon(0), T_SHORT);
7854   assert(result_start, "result is null");
7855   Node* ntta_start  = array_element_address(ntta, intcon(0), T_SHORT);
7856   assert(ntta_start, "ntta is null");
7857   Node* nttb_start  = array_element_address(nttb, intcon(0), T_SHORT);
7858   assert(nttb_start, "nttb is null");
7859   Node* zetas_start  = array_element_address(zetas, intcon(0), T_SHORT);
7860   assert(zetas_start, "nttMult_zetas is null");
7861   Node* kyberNttMult = make_runtime_call(RC_LEAF|RC_NO_FP,
7862                                   OptoRuntime::kyberNttMult_Type(),
7863                                   stubAddr, stubName, TypePtr::BOTTOM,
7864                                   result_start, ntta_start, nttb_start,
7865                                   zetas_start);
7866 
7867   // return an int
7868   Node* retvalue = _gvn.transform(new ProjNode(kyberNttMult, TypeFunc::Parms));
7869   set_result(retvalue);
7870 
7871   return true;
7872 }
7873 
7874 //------------------------------inline_kyberAddPoly_2
7875 bool LibraryCallKit::inline_kyberAddPoly_2() {
7876   address stubAddr;
7877   const char *stubName;
7878   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
7879   assert(callee()->signature()->size() == 3, "kyberAddPoly_2 has 3 parameters");
7880 
7881   stubAddr = StubRoutines::kyberAddPoly_2();
7882   stubName = "kyberAddPoly_2";
7883   if (!stubAddr) return false;
7884 
7885   Node* result          = argument(0);
7886   Node* a               = argument(1);
7887   Node* b               = argument(2);
7888 
7889   result = must_be_not_null(result, true);
7890   a = must_be_not_null(a, true);
7891   b = must_be_not_null(b, true);
7892 
7893   Node* result_start  = array_element_address(result, intcon(0), T_SHORT);
7894   assert(result_start, "result is null");
7895   Node* a_start  = array_element_address(a, intcon(0), T_SHORT);
7896   assert(a_start, "a is null");
7897   Node* b_start  = array_element_address(b, intcon(0), T_SHORT);
7898   assert(b_start, "b is null");
7899   Node* kyberAddPoly_2 = make_runtime_call(RC_LEAF|RC_NO_FP,
7900                                   OptoRuntime::kyberAddPoly_2_Type(),
7901                                   stubAddr, stubName, TypePtr::BOTTOM,
7902                                   result_start, a_start, b_start);
7903   // return an int
7904   Node* retvalue = _gvn.transform(new ProjNode(kyberAddPoly_2, TypeFunc::Parms));
7905   set_result(retvalue);
7906   return true;
7907 }
7908 
7909 //------------------------------inline_kyberAddPoly_3
7910 bool LibraryCallKit::inline_kyberAddPoly_3() {
7911   address stubAddr;
7912   const char *stubName;
7913   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
7914   assert(callee()->signature()->size() == 4, "kyberAddPoly_3 has 4 parameters");
7915 
7916   stubAddr = StubRoutines::kyberAddPoly_3();
7917   stubName = "kyberAddPoly_3";
7918   if (!stubAddr) return false;
7919 
7920   Node* result          = argument(0);
7921   Node* a               = argument(1);
7922   Node* b               = argument(2);
7923   Node* c               = argument(3);
7924 
7925   result = must_be_not_null(result, true);
7926   a = must_be_not_null(a, true);
7927   b = must_be_not_null(b, true);
7928   c = must_be_not_null(c, true);
7929 
7930   Node* result_start  = array_element_address(result, intcon(0), T_SHORT);
7931   assert(result_start, "result is null");
7932   Node* a_start  = array_element_address(a, intcon(0), T_SHORT);
7933   assert(a_start, "a is null");
7934   Node* b_start  = array_element_address(b, intcon(0), T_SHORT);
7935   assert(b_start, "b is null");
7936   Node* c_start  = array_element_address(c, intcon(0), T_SHORT);
7937   assert(c_start, "c is null");
7938   Node* kyberAddPoly_3 = make_runtime_call(RC_LEAF|RC_NO_FP,
7939                                   OptoRuntime::kyberAddPoly_3_Type(),
7940                                   stubAddr, stubName, TypePtr::BOTTOM,
7941                                   result_start, a_start, b_start, c_start);
7942   // return an int
7943   Node* retvalue = _gvn.transform(new ProjNode(kyberAddPoly_3, TypeFunc::Parms));
7944   set_result(retvalue);
7945   return true;
7946 }
7947 
7948 //------------------------------inline_kyber12To16
7949 bool LibraryCallKit::inline_kyber12To16() {
7950   address stubAddr;
7951   const char *stubName;
7952   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
7953   assert(callee()->signature()->size() == 4, "kyber12To16 has 4 parameters");
7954 
7955   stubAddr = StubRoutines::kyber12To16();
7956   stubName = "kyber12To16";
7957   if (!stubAddr) return false;
7958 
7959   Node* condensed       = argument(0);
7960   Node* condensedOffs   = argument(1);
7961   Node* parsed          = argument(2);
7962   Node* parsedLength    = argument(3);
7963 
7964   condensed = must_be_not_null(condensed, true);
7965   parsed = must_be_not_null(parsed, true);
7966 
7967   Node* condensed_start  = array_element_address(condensed, intcon(0), T_BYTE);
7968   assert(condensed_start, "condensed is null");
7969   Node* parsed_start  = array_element_address(parsed, intcon(0), T_SHORT);
7970   assert(parsed_start, "parsed is null");
7971   Node* kyber12To16 = make_runtime_call(RC_LEAF|RC_NO_FP,
7972                                   OptoRuntime::kyber12To16_Type(),
7973                                   stubAddr, stubName, TypePtr::BOTTOM,
7974                                   condensed_start, condensedOffs, parsed_start, parsedLength);
7975   // return an int
7976   Node* retvalue = _gvn.transform(new ProjNode(kyber12To16, TypeFunc::Parms));
7977   set_result(retvalue);
7978   return true;
7979 
7980 }
7981 
7982 //------------------------------inline_kyberBarrettReduce
7983 bool LibraryCallKit::inline_kyberBarrettReduce() {
7984   address stubAddr;
7985   const char *stubName;
7986   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
7987   assert(callee()->signature()->size() == 1, "kyberBarrettReduce has 1 parameters");
7988 
7989   stubAddr = StubRoutines::kyberBarrettReduce();
7990   stubName = "kyberBarrettReduce";
7991   if (!stubAddr) return false;
7992 
7993   Node* coeffs          = argument(0);
7994 
7995   coeffs = must_be_not_null(coeffs, true);
7996 
7997   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_SHORT);
7998   assert(coeffs_start, "coeffs is null");
7999   Node* kyberBarrettReduce = make_runtime_call(RC_LEAF|RC_NO_FP,
8000                                   OptoRuntime::kyberBarrettReduce_Type(),
8001                                   stubAddr, stubName, TypePtr::BOTTOM,
8002                                   coeffs_start);
8003   // return an int
8004   Node* retvalue = _gvn.transform(new ProjNode(kyberBarrettReduce, TypeFunc::Parms));
8005   set_result(retvalue);
8006   return true;
8007 }
8008 
8009 //------------------------------inline_dilithiumAlmostNtt
8010 bool LibraryCallKit::inline_dilithiumAlmostNtt() {
8011   address stubAddr;
8012   const char *stubName;
8013   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8014   assert(callee()->signature()->size() == 2, "dilithiumAlmostNtt has 2 parameters");
8015 
8016   stubAddr = StubRoutines::dilithiumAlmostNtt();
8017   stubName = "dilithiumAlmostNtt";
8018   if (!stubAddr) return false;
8019 
8020   Node* coeffs          = argument(0);
8021   Node* ntt_zetas        = argument(1);
8022 
8023   coeffs = must_be_not_null(coeffs, true);
8024   ntt_zetas = must_be_not_null(ntt_zetas, true);
8025 
8026   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_INT);
8027   assert(coeffs_start, "coeffs is null");
8028   Node* ntt_zetas_start  = array_element_address(ntt_zetas, intcon(0), T_INT);
8029   assert(ntt_zetas_start, "ntt_zetas is null");
8030   Node* dilithiumAlmostNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
8031                                   OptoRuntime::dilithiumAlmostNtt_Type(),
8032                                   stubAddr, stubName, TypePtr::BOTTOM,
8033                                   coeffs_start, ntt_zetas_start);
8034   // return an int
8035   Node* retvalue = _gvn.transform(new ProjNode(dilithiumAlmostNtt, TypeFunc::Parms));
8036   set_result(retvalue);
8037   return true;
8038 }
8039 
8040 //------------------------------inline_dilithiumAlmostInverseNtt
8041 bool LibraryCallKit::inline_dilithiumAlmostInverseNtt() {
8042   address stubAddr;
8043   const char *stubName;
8044   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8045   assert(callee()->signature()->size() == 2, "dilithiumAlmostInverseNtt has 2 parameters");
8046 
8047   stubAddr = StubRoutines::dilithiumAlmostInverseNtt();
8048   stubName = "dilithiumAlmostInverseNtt";
8049   if (!stubAddr) return false;
8050 
8051   Node* coeffs          = argument(0);
8052   Node* zetas           = argument(1);
8053 
8054   coeffs = must_be_not_null(coeffs, true);
8055   zetas = must_be_not_null(zetas, true);
8056 
8057   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_INT);
8058   assert(coeffs_start, "coeffs is null");
8059   Node* zetas_start  = array_element_address(zetas, intcon(0), T_INT);
8060   assert(zetas_start, "inverseNtt_zetas is null");
8061   Node* dilithiumAlmostInverseNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
8062                                   OptoRuntime::dilithiumAlmostInverseNtt_Type(),
8063                                   stubAddr, stubName, TypePtr::BOTTOM,
8064                                   coeffs_start, zetas_start);
8065   // return an int
8066   Node* retvalue = _gvn.transform(new ProjNode(dilithiumAlmostInverseNtt, TypeFunc::Parms));
8067   set_result(retvalue);
8068   return true;
8069 }
8070 
8071 //------------------------------inline_dilithiumNttMult
8072 bool LibraryCallKit::inline_dilithiumNttMult() {
8073   address stubAddr;
8074   const char *stubName;
8075   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8076   assert(callee()->signature()->size() == 3, "dilithiumNttMult has 3 parameters");
8077 
8078   stubAddr = StubRoutines::dilithiumNttMult();
8079   stubName = "dilithiumNttMult";
8080   if (!stubAddr) return false;
8081 
8082   Node* result          = argument(0);
8083   Node* ntta            = argument(1);
8084   Node* nttb            = argument(2);
8085   Node* zetas           = argument(3);
8086 
8087   result = must_be_not_null(result, true);
8088   ntta = must_be_not_null(ntta, true);
8089   nttb = must_be_not_null(nttb, true);
8090   zetas = must_be_not_null(zetas, true);
8091 
8092   Node* result_start  = array_element_address(result, intcon(0), T_INT);
8093   assert(result_start, "result is null");
8094   Node* ntta_start  = array_element_address(ntta, intcon(0), T_INT);
8095   assert(ntta_start, "ntta is null");
8096   Node* nttb_start  = array_element_address(nttb, intcon(0), T_INT);
8097   assert(nttb_start, "nttb is null");
8098   Node* dilithiumNttMult = make_runtime_call(RC_LEAF|RC_NO_FP,
8099                                   OptoRuntime::dilithiumNttMult_Type(),
8100                                   stubAddr, stubName, TypePtr::BOTTOM,
8101                                   result_start, ntta_start, nttb_start);
8102 
8103   // return an int
8104   Node* retvalue = _gvn.transform(new ProjNode(dilithiumNttMult, TypeFunc::Parms));
8105   set_result(retvalue);
8106 
8107   return true;
8108 }
8109 
8110 //------------------------------inline_dilithiumMontMulByConstant
8111 bool LibraryCallKit::inline_dilithiumMontMulByConstant() {
8112   address stubAddr;
8113   const char *stubName;
8114   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8115   assert(callee()->signature()->size() == 2, "dilithiumMontMulByConstant has 2 parameters");
8116 
8117   stubAddr = StubRoutines::dilithiumMontMulByConstant();
8118   stubName = "dilithiumMontMulByConstant";
8119   if (!stubAddr) return false;
8120 
8121   Node* coeffs          = argument(0);
8122   Node* constant        = argument(1);
8123 
8124   coeffs = must_be_not_null(coeffs, true);
8125 
8126   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_INT);
8127   assert(coeffs_start, "coeffs is null");
8128   Node* dilithiumMontMulByConstant = make_runtime_call(RC_LEAF|RC_NO_FP,
8129                                   OptoRuntime::dilithiumMontMulByConstant_Type(),
8130                                   stubAddr, stubName, TypePtr::BOTTOM,
8131                                   coeffs_start, constant);
8132 
8133   // return an int
8134   Node* retvalue = _gvn.transform(new ProjNode(dilithiumMontMulByConstant, TypeFunc::Parms));
8135   set_result(retvalue);
8136   return true;
8137 }
8138 
8139 
8140 //------------------------------inline_dilithiumDecomposePoly
8141 bool LibraryCallKit::inline_dilithiumDecomposePoly() {
8142   address stubAddr;
8143   const char *stubName;
8144   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8145   assert(callee()->signature()->size() == 5, "dilithiumDecomposePoly has 5 parameters");
8146 
8147   stubAddr = StubRoutines::dilithiumDecomposePoly();
8148   stubName = "dilithiumDecomposePoly";
8149   if (!stubAddr) return false;
8150 
8151   Node* input          = argument(0);
8152   Node* lowPart        = argument(1);
8153   Node* highPart       = argument(2);
8154   Node* twoGamma2      = argument(3);
8155   Node* multiplier     = argument(4);
8156 
8157   input = must_be_not_null(input, true);
8158   lowPart = must_be_not_null(lowPart, true);
8159   highPart = must_be_not_null(highPart, true);
8160 
8161   Node* input_start  = array_element_address(input, intcon(0), T_INT);
8162   assert(input_start, "input is null");
8163   Node* lowPart_start  = array_element_address(lowPart, intcon(0), T_INT);
8164   assert(lowPart_start, "lowPart is null");
8165   Node* highPart_start  = array_element_address(highPart, intcon(0), T_INT);
8166   assert(highPart_start, "highPart is null");
8167 
8168   Node* dilithiumDecomposePoly = make_runtime_call(RC_LEAF|RC_NO_FP,
8169                                   OptoRuntime::dilithiumDecomposePoly_Type(),
8170                                   stubAddr, stubName, TypePtr::BOTTOM,
8171                                   input_start, lowPart_start, highPart_start,
8172                                   twoGamma2, multiplier);
8173 
8174   // return an int
8175   Node* retvalue = _gvn.transform(new ProjNode(dilithiumDecomposePoly, TypeFunc::Parms));
8176   set_result(retvalue);
8177   return true;
8178 }
8179 
8180 bool LibraryCallKit::inline_base64_encodeBlock() {
8181   address stubAddr;
8182   const char *stubName;
8183   assert(UseBASE64Intrinsics, "need Base64 intrinsics support");
8184   assert(callee()->signature()->size() == 6, "base64_encodeBlock has 6 parameters");
8185   stubAddr = StubRoutines::base64_encodeBlock();
8186   stubName = "encodeBlock";
8187 
8188   if (!stubAddr) return false;
8189   Node* base64obj = argument(0);
8190   Node* src = argument(1);
8191   Node* offset = argument(2);
8192   Node* len = argument(3);
8193   Node* dest = argument(4);
8194   Node* dp = argument(5);
8195   Node* isURL = argument(6);
8196 
8197   src = must_be_not_null(src, true);
8198   dest = must_be_not_null(dest, true);
8199 
8200   Node* src_start = array_element_address(src, intcon(0), T_BYTE);
8201   assert(src_start, "source array is null");
8202   Node* dest_start = array_element_address(dest, intcon(0), T_BYTE);
8203   assert(dest_start, "destination array is null");
8204 
8205   Node* base64 = make_runtime_call(RC_LEAF,
8206                                    OptoRuntime::base64_encodeBlock_Type(),
8207                                    stubAddr, stubName, TypePtr::BOTTOM,
8208                                    src_start, offset, len, dest_start, dp, isURL);
8209   return true;
8210 }
8211 
8212 bool LibraryCallKit::inline_base64_decodeBlock() {
8213   address stubAddr;
8214   const char *stubName;
8215   assert(UseBASE64Intrinsics, "need Base64 intrinsics support");
8216   assert(callee()->signature()->size() == 7, "base64_decodeBlock has 7 parameters");
8217   stubAddr = StubRoutines::base64_decodeBlock();
8218   stubName = "decodeBlock";
8219 
8220   if (!stubAddr) return false;
8221   Node* base64obj = argument(0);
8222   Node* src = argument(1);
8223   Node* src_offset = argument(2);
8224   Node* len = argument(3);
8225   Node* dest = argument(4);
8226   Node* dest_offset = argument(5);
8227   Node* isURL = argument(6);
8228   Node* isMIME = argument(7);
8229 
8230   src = must_be_not_null(src, true);
8231   dest = must_be_not_null(dest, true);
8232 
8233   Node* src_start = array_element_address(src, intcon(0), T_BYTE);
8234   assert(src_start, "source array is null");
8235   Node* dest_start = array_element_address(dest, intcon(0), T_BYTE);
8236   assert(dest_start, "destination array is null");
8237 
8238   Node* call = make_runtime_call(RC_LEAF,
8239                                  OptoRuntime::base64_decodeBlock_Type(),
8240                                  stubAddr, stubName, TypePtr::BOTTOM,
8241                                  src_start, src_offset, len, dest_start, dest_offset, isURL, isMIME);
8242   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
8243   set_result(result);
8244   return true;
8245 }
8246 
8247 bool LibraryCallKit::inline_poly1305_processBlocks() {
8248   address stubAddr;
8249   const char *stubName;
8250   assert(UsePoly1305Intrinsics, "need Poly intrinsics support");
8251   assert(callee()->signature()->size() == 5, "poly1305_processBlocks has %d parameters", callee()->signature()->size());
8252   stubAddr = StubRoutines::poly1305_processBlocks();
8253   stubName = "poly1305_processBlocks";
8254 
8255   if (!stubAddr) return false;
8256   null_check_receiver();  // null-check receiver
8257   if (stopped())  return true;
8258 
8259   Node* input = argument(1);
8260   Node* input_offset = argument(2);
8261   Node* len = argument(3);
8262   Node* alimbs = argument(4);
8263   Node* rlimbs = argument(5);
8264 
8265   input = must_be_not_null(input, true);
8266   alimbs = must_be_not_null(alimbs, true);
8267   rlimbs = must_be_not_null(rlimbs, true);
8268 
8269   Node* input_start = array_element_address(input, input_offset, T_BYTE);
8270   assert(input_start, "input array is null");
8271   Node* acc_start = array_element_address(alimbs, intcon(0), T_LONG);
8272   assert(acc_start, "acc array is null");
8273   Node* r_start = array_element_address(rlimbs, intcon(0), T_LONG);
8274   assert(r_start, "r array is null");
8275 
8276   Node* call = make_runtime_call(RC_LEAF | RC_NO_FP,
8277                                  OptoRuntime::poly1305_processBlocks_Type(),
8278                                  stubAddr, stubName, TypePtr::BOTTOM,
8279                                  input_start, len, acc_start, r_start);
8280   return true;
8281 }
8282 
8283 bool LibraryCallKit::inline_intpoly_montgomeryMult_P256() {
8284   address stubAddr;
8285   const char *stubName;
8286   assert(UseIntPolyIntrinsics, "need intpoly intrinsics support");
8287   assert(callee()->signature()->size() == 3, "intpoly_montgomeryMult_P256 has %d parameters", callee()->signature()->size());
8288   stubAddr = StubRoutines::intpoly_montgomeryMult_P256();
8289   stubName = "intpoly_montgomeryMult_P256";
8290 
8291   if (!stubAddr) return false;
8292   null_check_receiver();  // null-check receiver
8293   if (stopped())  return true;
8294 
8295   Node* a = argument(1);
8296   Node* b = argument(2);
8297   Node* r = argument(3);
8298 
8299   a = must_be_not_null(a, true);
8300   b = must_be_not_null(b, true);
8301   r = must_be_not_null(r, true);
8302 
8303   Node* a_start = array_element_address(a, intcon(0), T_LONG);
8304   assert(a_start, "a array is null");
8305   Node* b_start = array_element_address(b, intcon(0), T_LONG);
8306   assert(b_start, "b array is null");
8307   Node* r_start = array_element_address(r, intcon(0), T_LONG);
8308   assert(r_start, "r array is null");
8309 
8310   Node* call = make_runtime_call(RC_LEAF | RC_NO_FP,
8311                                  OptoRuntime::intpoly_montgomeryMult_P256_Type(),
8312                                  stubAddr, stubName, TypePtr::BOTTOM,
8313                                  a_start, b_start, r_start);
8314   return true;
8315 }
8316 
8317 bool LibraryCallKit::inline_intpoly_assign() {
8318   assert(UseIntPolyIntrinsics, "need intpoly intrinsics support");
8319   assert(callee()->signature()->size() == 3, "intpoly_assign has %d parameters", callee()->signature()->size());
8320   const char *stubName = "intpoly_assign";
8321   address stubAddr = StubRoutines::intpoly_assign();
8322   if (!stubAddr) return false;
8323 
8324   Node* set = argument(0);
8325   Node* a = argument(1);
8326   Node* b = argument(2);
8327   Node* arr_length = load_array_length(a);
8328 
8329   a = must_be_not_null(a, true);
8330   b = must_be_not_null(b, true);
8331 
8332   Node* a_start = array_element_address(a, intcon(0), T_LONG);
8333   assert(a_start, "a array is null");
8334   Node* b_start = array_element_address(b, intcon(0), T_LONG);
8335   assert(b_start, "b array is null");
8336 
8337   Node* call = make_runtime_call(RC_LEAF | RC_NO_FP,
8338                                  OptoRuntime::intpoly_assign_Type(),
8339                                  stubAddr, stubName, TypePtr::BOTTOM,
8340                                  set, a_start, b_start, arr_length);
8341   return true;
8342 }
8343 
8344 //------------------------------inline_digestBase_implCompress-----------------------
8345 //
8346 // Calculate MD5 for single-block byte[] array.
8347 // void com.sun.security.provider.MD5.implCompress(byte[] buf, int ofs)
8348 //
8349 // Calculate SHA (i.e., SHA-1) for single-block byte[] array.
8350 // void com.sun.security.provider.SHA.implCompress(byte[] buf, int ofs)
8351 //
8352 // Calculate SHA2 (i.e., SHA-244 or SHA-256) for single-block byte[] array.
8353 // void com.sun.security.provider.SHA2.implCompress(byte[] buf, int ofs)
8354 //
8355 // Calculate SHA5 (i.e., SHA-384 or SHA-512) for single-block byte[] array.
8356 // void com.sun.security.provider.SHA5.implCompress(byte[] buf, int ofs)
8357 //
8358 // Calculate SHA3 (i.e., SHA3-224 or SHA3-256 or SHA3-384 or SHA3-512) for single-block byte[] array.
8359 // void com.sun.security.provider.SHA3.implCompress(byte[] buf, int ofs)
8360 //
8361 bool LibraryCallKit::inline_digestBase_implCompress(vmIntrinsics::ID id) {
8362   assert(callee()->signature()->size() == 2, "sha_implCompress has 2 parameters");
8363 
8364   Node* digestBase_obj = argument(0);
8365   Node* src            = argument(1); // type oop
8366   Node* ofs            = argument(2); // type int
8367 
8368   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
8369   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
8370     // failed array check
8371     return false;
8372   }
8373   // Figure out the size and type of the elements we will be copying.
8374   BasicType src_elem = src_type->elem()->array_element_basic_type();
8375   if (src_elem != T_BYTE) {
8376     return false;
8377   }
8378   // 'src_start' points to src array + offset
8379   src = must_be_not_null(src, true);
8380   Node* src_start = array_element_address(src, ofs, src_elem);
8381   Node* state = nullptr;
8382   Node* block_size = nullptr;
8383   address stubAddr;
8384   const char *stubName;
8385 
8386   switch(id) {
8387   case vmIntrinsics::_md5_implCompress:
8388     assert(UseMD5Intrinsics, "need MD5 instruction support");
8389     state = get_state_from_digest_object(digestBase_obj, T_INT);
8390     stubAddr = StubRoutines::md5_implCompress();
8391     stubName = "md5_implCompress";
8392     break;
8393   case vmIntrinsics::_sha_implCompress:
8394     assert(UseSHA1Intrinsics, "need SHA1 instruction support");
8395     state = get_state_from_digest_object(digestBase_obj, T_INT);
8396     stubAddr = StubRoutines::sha1_implCompress();
8397     stubName = "sha1_implCompress";
8398     break;
8399   case vmIntrinsics::_sha2_implCompress:
8400     assert(UseSHA256Intrinsics, "need SHA256 instruction support");
8401     state = get_state_from_digest_object(digestBase_obj, T_INT);
8402     stubAddr = StubRoutines::sha256_implCompress();
8403     stubName = "sha256_implCompress";
8404     break;
8405   case vmIntrinsics::_sha5_implCompress:
8406     assert(UseSHA512Intrinsics, "need SHA512 instruction support");
8407     state = get_state_from_digest_object(digestBase_obj, T_LONG);
8408     stubAddr = StubRoutines::sha512_implCompress();
8409     stubName = "sha512_implCompress";
8410     break;
8411   case vmIntrinsics::_sha3_implCompress:
8412     assert(UseSHA3Intrinsics, "need SHA3 instruction support");
8413     state = get_state_from_digest_object(digestBase_obj, T_LONG);
8414     stubAddr = StubRoutines::sha3_implCompress();
8415     stubName = "sha3_implCompress";
8416     block_size = get_block_size_from_digest_object(digestBase_obj);
8417     if (block_size == nullptr) return false;
8418     break;
8419   default:
8420     fatal_unexpected_iid(id);
8421     return false;
8422   }
8423   if (state == nullptr) return false;
8424 
8425   assert(stubAddr != nullptr, "Stub %s is not generated", stubName);
8426   if (stubAddr == nullptr) return false;
8427 
8428   // Call the stub.
8429   Node* call;
8430   if (block_size == nullptr) {
8431     call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::digestBase_implCompress_Type(false),
8432                              stubAddr, stubName, TypePtr::BOTTOM,
8433                              src_start, state);
8434   } else {
8435     call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::digestBase_implCompress_Type(true),
8436                              stubAddr, stubName, TypePtr::BOTTOM,
8437                              src_start, state, block_size);
8438   }
8439 
8440   return true;
8441 }
8442 
8443 //------------------------------inline_double_keccak
8444 bool LibraryCallKit::inline_double_keccak() {
8445   address stubAddr;
8446   const char *stubName;
8447   assert(UseSHA3Intrinsics, "need SHA3 intrinsics support");
8448   assert(callee()->signature()->size() == 2, "double_keccak has 2 parameters");
8449 
8450   stubAddr = StubRoutines::double_keccak();
8451   stubName = "double_keccak";
8452   if (!stubAddr) return false;
8453 
8454   Node* status0        = argument(0);
8455   Node* status1        = argument(1);
8456 
8457   status0 = must_be_not_null(status0, true);
8458   status1 = must_be_not_null(status1, true);
8459 
8460   Node* status0_start  = array_element_address(status0, intcon(0), T_LONG);
8461   assert(status0_start, "status0 is null");
8462   Node* status1_start  = array_element_address(status1, intcon(0), T_LONG);
8463   assert(status1_start, "status1 is null");
8464   Node* double_keccak = make_runtime_call(RC_LEAF|RC_NO_FP,
8465                                   OptoRuntime::double_keccak_Type(),
8466                                   stubAddr, stubName, TypePtr::BOTTOM,
8467                                   status0_start, status1_start);
8468   // return an int
8469   Node* retvalue = _gvn.transform(new ProjNode(double_keccak, TypeFunc::Parms));
8470   set_result(retvalue);
8471   return true;
8472 }
8473 
8474 
8475 //------------------------------inline_digestBase_implCompressMB-----------------------
8476 //
8477 // Calculate MD5/SHA/SHA2/SHA5/SHA3 for multi-block byte[] array.
8478 // int com.sun.security.provider.DigestBase.implCompressMultiBlock(byte[] b, int ofs, int limit)
8479 //
8480 bool LibraryCallKit::inline_digestBase_implCompressMB(int predicate) {
8481   assert(UseMD5Intrinsics || UseSHA1Intrinsics || UseSHA256Intrinsics || UseSHA512Intrinsics || UseSHA3Intrinsics,
8482          "need MD5/SHA1/SHA256/SHA512/SHA3 instruction support");
8483   assert((uint)predicate < 5, "sanity");
8484   assert(callee()->signature()->size() == 3, "digestBase_implCompressMB has 3 parameters");
8485 
8486   Node* digestBase_obj = argument(0); // The receiver was checked for null already.
8487   Node* src            = argument(1); // byte[] array
8488   Node* ofs            = argument(2); // type int
8489   Node* limit          = argument(3); // type int
8490 
8491   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
8492   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
8493     // failed array check
8494     return false;
8495   }
8496   // Figure out the size and type of the elements we will be copying.
8497   BasicType src_elem = src_type->elem()->array_element_basic_type();
8498   if (src_elem != T_BYTE) {
8499     return false;
8500   }
8501   // 'src_start' points to src array + offset
8502   src = must_be_not_null(src, false);
8503   Node* src_start = array_element_address(src, ofs, src_elem);
8504 
8505   const char* klass_digestBase_name = nullptr;
8506   const char* stub_name = nullptr;
8507   address     stub_addr = nullptr;
8508   BasicType elem_type = T_INT;
8509 
8510   switch (predicate) {
8511   case 0:
8512     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_md5_implCompress)) {
8513       klass_digestBase_name = "sun/security/provider/MD5";
8514       stub_name = "md5_implCompressMB";
8515       stub_addr = StubRoutines::md5_implCompressMB();
8516     }
8517     break;
8518   case 1:
8519     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha_implCompress)) {
8520       klass_digestBase_name = "sun/security/provider/SHA";
8521       stub_name = "sha1_implCompressMB";
8522       stub_addr = StubRoutines::sha1_implCompressMB();
8523     }
8524     break;
8525   case 2:
8526     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha2_implCompress)) {
8527       klass_digestBase_name = "sun/security/provider/SHA2";
8528       stub_name = "sha256_implCompressMB";
8529       stub_addr = StubRoutines::sha256_implCompressMB();
8530     }
8531     break;
8532   case 3:
8533     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha5_implCompress)) {
8534       klass_digestBase_name = "sun/security/provider/SHA5";
8535       stub_name = "sha512_implCompressMB";
8536       stub_addr = StubRoutines::sha512_implCompressMB();
8537       elem_type = T_LONG;
8538     }
8539     break;
8540   case 4:
8541     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha3_implCompress)) {
8542       klass_digestBase_name = "sun/security/provider/SHA3";
8543       stub_name = "sha3_implCompressMB";
8544       stub_addr = StubRoutines::sha3_implCompressMB();
8545       elem_type = T_LONG;
8546     }
8547     break;
8548   default:
8549     fatal("unknown DigestBase intrinsic predicate: %d", predicate);
8550   }
8551   if (klass_digestBase_name != nullptr) {
8552     assert(stub_addr != nullptr, "Stub is generated");
8553     if (stub_addr == nullptr) return false;
8554 
8555     // get DigestBase klass to lookup for SHA klass
8556     const TypeInstPtr* tinst = _gvn.type(digestBase_obj)->isa_instptr();
8557     assert(tinst != nullptr, "digestBase_obj is not instance???");
8558     assert(tinst->is_loaded(), "DigestBase is not loaded");
8559 
8560     ciKlass* klass_digestBase = tinst->instance_klass()->find_klass(ciSymbol::make(klass_digestBase_name));
8561     assert(klass_digestBase->is_loaded(), "predicate checks that this class is loaded");
8562     ciInstanceKlass* instklass_digestBase = klass_digestBase->as_instance_klass();
8563     return inline_digestBase_implCompressMB(digestBase_obj, instklass_digestBase, elem_type, stub_addr, stub_name, src_start, ofs, limit);
8564   }
8565   return false;
8566 }
8567 
8568 //------------------------------inline_digestBase_implCompressMB-----------------------
8569 bool LibraryCallKit::inline_digestBase_implCompressMB(Node* digestBase_obj, ciInstanceKlass* instklass_digestBase,
8570                                                       BasicType elem_type, address stubAddr, const char *stubName,
8571                                                       Node* src_start, Node* ofs, Node* limit) {
8572   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_digestBase);
8573   const TypeOopPtr* xtype = aklass->cast_to_exactness(false)->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
8574   Node* digest_obj = new CheckCastPPNode(control(), digestBase_obj, xtype);
8575   digest_obj = _gvn.transform(digest_obj);
8576 
8577   Node* state = get_state_from_digest_object(digest_obj, elem_type);
8578   if (state == nullptr) return false;
8579 
8580   Node* block_size = nullptr;
8581   if (strcmp("sha3_implCompressMB", stubName) == 0) {
8582     block_size = get_block_size_from_digest_object(digest_obj);
8583     if (block_size == nullptr) return false;
8584   }
8585 
8586   // Call the stub.
8587   Node* call;
8588   if (block_size == nullptr) {
8589     call = make_runtime_call(RC_LEAF|RC_NO_FP,
8590                              OptoRuntime::digestBase_implCompressMB_Type(false),
8591                              stubAddr, stubName, TypePtr::BOTTOM,
8592                              src_start, state, ofs, limit);
8593   } else {
8594      call = make_runtime_call(RC_LEAF|RC_NO_FP,
8595                              OptoRuntime::digestBase_implCompressMB_Type(true),
8596                              stubAddr, stubName, TypePtr::BOTTOM,
8597                              src_start, state, block_size, ofs, limit);
8598   }
8599 
8600   // return ofs (int)
8601   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
8602   set_result(result);
8603 
8604   return true;
8605 }
8606 
8607 //------------------------------inline_galoisCounterMode_AESCrypt-----------------------
8608 bool LibraryCallKit::inline_galoisCounterMode_AESCrypt() {
8609   assert(UseAES, "need AES instruction support");
8610   address stubAddr = nullptr;
8611   const char *stubName = nullptr;
8612   stubAddr = StubRoutines::galoisCounterMode_AESCrypt();
8613   stubName = "galoisCounterMode_AESCrypt";
8614 
8615   if (stubAddr == nullptr) return false;
8616 
8617   Node* in      = argument(0);
8618   Node* inOfs   = argument(1);
8619   Node* len     = argument(2);
8620   Node* ct      = argument(3);
8621   Node* ctOfs   = argument(4);
8622   Node* out     = argument(5);
8623   Node* outOfs  = argument(6);
8624   Node* gctr_object = argument(7);
8625   Node* ghash_object = argument(8);
8626 
8627   // (1) in, ct and out are arrays.
8628   const TypeAryPtr* in_type = in->Value(&_gvn)->isa_aryptr();
8629   const TypeAryPtr* ct_type = ct->Value(&_gvn)->isa_aryptr();
8630   const TypeAryPtr* out_type = out->Value(&_gvn)->isa_aryptr();
8631   assert( in_type != nullptr &&  in_type->elem() != Type::BOTTOM &&
8632           ct_type != nullptr &&  ct_type->elem() != Type::BOTTOM &&
8633          out_type != nullptr && out_type->elem() != Type::BOTTOM, "args are strange");
8634 
8635   // checks are the responsibility of the caller
8636   Node* in_start = in;
8637   Node* ct_start = ct;
8638   Node* out_start = out;
8639   if (inOfs != nullptr || ctOfs != nullptr || outOfs != nullptr) {
8640     assert(inOfs != nullptr && ctOfs != nullptr && outOfs != nullptr, "");
8641     in_start = array_element_address(in, inOfs, T_BYTE);
8642     ct_start = array_element_address(ct, ctOfs, T_BYTE);
8643     out_start = array_element_address(out, outOfs, T_BYTE);
8644   }
8645 
8646   // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
8647   // (because of the predicated logic executed earlier).
8648   // so we cast it here safely.
8649   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
8650   Node* embeddedCipherObj = load_field_from_object(gctr_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8651   Node* counter = load_field_from_object(gctr_object, "counter", "[B");
8652   Node* subkeyHtbl = load_field_from_object(ghash_object, "subkeyHtbl", "[J");
8653   Node* state = load_field_from_object(ghash_object, "state", "[J");
8654 
8655   if (embeddedCipherObj == nullptr || counter == nullptr || subkeyHtbl == nullptr || state == nullptr) {
8656     return false;
8657   }
8658   // cast it to what we know it will be at runtime
8659   const TypeInstPtr* tinst = _gvn.type(gctr_object)->isa_instptr();
8660   assert(tinst != nullptr, "GCTR obj is null");
8661   assert(tinst->is_loaded(), "GCTR obj is not loaded");
8662   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8663   assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
8664   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8665   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
8666   const TypeOopPtr* xtype = aklass->as_instance_type();
8667   Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
8668   aescrypt_object = _gvn.transform(aescrypt_object);
8669   // we need to get the start of the aescrypt_object's expanded key array
8670   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object, /* is_decrypt */ false);
8671   if (k_start == nullptr) return false;
8672   // similarly, get the start address of the r vector
8673   Node* cnt_start = array_element_address(counter, intcon(0), T_BYTE);
8674   Node* state_start = array_element_address(state, intcon(0), T_LONG);
8675   Node* subkeyHtbl_start = array_element_address(subkeyHtbl, intcon(0), T_LONG);
8676 
8677 
8678   // Call the stub, passing params
8679   Node* gcmCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
8680                                OptoRuntime::galoisCounterMode_aescrypt_Type(),
8681                                stubAddr, stubName, TypePtr::BOTTOM,
8682                                in_start, len, ct_start, out_start, k_start, state_start, subkeyHtbl_start, cnt_start);
8683 
8684   // return cipher length (int)
8685   Node* retvalue = _gvn.transform(new ProjNode(gcmCrypt, TypeFunc::Parms));
8686   set_result(retvalue);
8687 
8688   return true;
8689 }
8690 
8691 //----------------------------inline_galoisCounterMode_AESCrypt_predicate----------------------------
8692 // Return node representing slow path of predicate check.
8693 // the pseudo code we want to emulate with this predicate is:
8694 // for encryption:
8695 //    if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
8696 // for decryption:
8697 //    if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
8698 //    note cipher==plain is more conservative than the original java code but that's OK
8699 //
8700 
8701 Node* LibraryCallKit::inline_galoisCounterMode_AESCrypt_predicate() {
8702   // The receiver was checked for null already.
8703   Node* objGCTR = argument(7);
8704   // Load embeddedCipher field of GCTR object.
8705   Node* embeddedCipherObj = load_field_from_object(objGCTR, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8706   assert(embeddedCipherObj != nullptr, "embeddedCipherObj is null");
8707 
8708   // get AESCrypt klass for instanceOf check
8709   // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
8710   // will have same classloader as CipherBlockChaining object
8711   const TypeInstPtr* tinst = _gvn.type(objGCTR)->isa_instptr();
8712   assert(tinst != nullptr, "GCTR obj is null");
8713   assert(tinst->is_loaded(), "GCTR obj is not loaded");
8714 
8715   // we want to do an instanceof comparison against the AESCrypt class
8716   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8717   if (!klass_AESCrypt->is_loaded()) {
8718     // if AESCrypt is not even loaded, we never take the intrinsic fast path
8719     Node* ctrl = control();
8720     set_control(top()); // no regular fast path
8721     return ctrl;
8722   }
8723 
8724   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8725   Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
8726   Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
8727   Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
8728   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
8729 
8730   return instof_false; // even if it is null
8731 }
8732 
8733 //------------------------------get_state_from_digest_object-----------------------
8734 Node * LibraryCallKit::get_state_from_digest_object(Node *digest_object, BasicType elem_type) {
8735   const char* state_type;
8736   switch (elem_type) {
8737     case T_BYTE: state_type = "[B"; break;
8738     case T_INT:  state_type = "[I"; break;
8739     case T_LONG: state_type = "[J"; break;
8740     default: ShouldNotReachHere();
8741   }
8742   Node* digest_state = load_field_from_object(digest_object, "state", state_type);
8743   assert (digest_state != nullptr, "wrong version of sun.security.provider.MD5/SHA/SHA2/SHA5/SHA3");
8744   if (digest_state == nullptr) return (Node *) nullptr;
8745 
8746   // now have the array, need to get the start address of the state array
8747   Node* state = array_element_address(digest_state, intcon(0), elem_type);
8748   return state;
8749 }
8750 
8751 //------------------------------get_block_size_from_sha3_object----------------------------------
8752 Node * LibraryCallKit::get_block_size_from_digest_object(Node *digest_object) {
8753   Node* block_size = load_field_from_object(digest_object, "blockSize", "I");
8754   assert (block_size != nullptr, "sanity");
8755   return block_size;
8756 }
8757 
8758 //----------------------------inline_digestBase_implCompressMB_predicate----------------------------
8759 // Return node representing slow path of predicate check.
8760 // the pseudo code we want to emulate with this predicate is:
8761 //    if (digestBaseObj instanceof MD5/SHA/SHA2/SHA5/SHA3) do_intrinsic, else do_javapath
8762 //
8763 Node* LibraryCallKit::inline_digestBase_implCompressMB_predicate(int predicate) {
8764   assert(UseMD5Intrinsics || UseSHA1Intrinsics || UseSHA256Intrinsics || UseSHA512Intrinsics || UseSHA3Intrinsics,
8765          "need MD5/SHA1/SHA256/SHA512/SHA3 instruction support");
8766   assert((uint)predicate < 5, "sanity");
8767 
8768   // The receiver was checked for null already.
8769   Node* digestBaseObj = argument(0);
8770 
8771   // get DigestBase klass for instanceOf check
8772   const TypeInstPtr* tinst = _gvn.type(digestBaseObj)->isa_instptr();
8773   assert(tinst != nullptr, "digestBaseObj is null");
8774   assert(tinst->is_loaded(), "DigestBase is not loaded");
8775 
8776   const char* klass_name = nullptr;
8777   switch (predicate) {
8778   case 0:
8779     if (UseMD5Intrinsics) {
8780       // we want to do an instanceof comparison against the MD5 class
8781       klass_name = "sun/security/provider/MD5";
8782     }
8783     break;
8784   case 1:
8785     if (UseSHA1Intrinsics) {
8786       // we want to do an instanceof comparison against the SHA class
8787       klass_name = "sun/security/provider/SHA";
8788     }
8789     break;
8790   case 2:
8791     if (UseSHA256Intrinsics) {
8792       // we want to do an instanceof comparison against the SHA2 class
8793       klass_name = "sun/security/provider/SHA2";
8794     }
8795     break;
8796   case 3:
8797     if (UseSHA512Intrinsics) {
8798       // we want to do an instanceof comparison against the SHA5 class
8799       klass_name = "sun/security/provider/SHA5";
8800     }
8801     break;
8802   case 4:
8803     if (UseSHA3Intrinsics) {
8804       // we want to do an instanceof comparison against the SHA3 class
8805       klass_name = "sun/security/provider/SHA3";
8806     }
8807     break;
8808   default:
8809     fatal("unknown SHA intrinsic predicate: %d", predicate);
8810   }
8811 
8812   ciKlass* klass = nullptr;
8813   if (klass_name != nullptr) {
8814     klass = tinst->instance_klass()->find_klass(ciSymbol::make(klass_name));
8815   }
8816   if ((klass == nullptr) || !klass->is_loaded()) {
8817     // if none of MD5/SHA/SHA2/SHA5 is loaded, we never take the intrinsic fast path
8818     Node* ctrl = control();
8819     set_control(top()); // no intrinsic path
8820     return ctrl;
8821   }
8822   ciInstanceKlass* instklass = klass->as_instance_klass();
8823 
8824   Node* instof = gen_instanceof(digestBaseObj, makecon(TypeKlassPtr::make(instklass)));
8825   Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
8826   Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
8827   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
8828 
8829   return instof_false;  // even if it is null
8830 }
8831 
8832 //-------------inline_fma-----------------------------------
8833 bool LibraryCallKit::inline_fma(vmIntrinsics::ID id) {
8834   Node *a = nullptr;
8835   Node *b = nullptr;
8836   Node *c = nullptr;
8837   Node* result = nullptr;
8838   switch (id) {
8839   case vmIntrinsics::_fmaD:
8840     assert(callee()->signature()->size() == 6, "fma has 3 parameters of size 2 each.");
8841     // no receiver since it is static method
8842     a = argument(0);
8843     b = argument(2);
8844     c = argument(4);
8845     result = _gvn.transform(new FmaDNode(a, b, c));
8846     break;
8847   case vmIntrinsics::_fmaF:
8848     assert(callee()->signature()->size() == 3, "fma has 3 parameters of size 1 each.");
8849     a = argument(0);
8850     b = argument(1);
8851     c = argument(2);
8852     result = _gvn.transform(new FmaFNode(a, b, c));
8853     break;
8854   default:
8855     fatal_unexpected_iid(id);  break;
8856   }
8857   set_result(result);
8858   return true;
8859 }
8860 
8861 bool LibraryCallKit::inline_character_compare(vmIntrinsics::ID id) {
8862   // argument(0) is receiver
8863   Node* codePoint = argument(1);
8864   Node* n = nullptr;
8865 
8866   switch (id) {
8867     case vmIntrinsics::_isDigit :
8868       n = new DigitNode(control(), codePoint);
8869       break;
8870     case vmIntrinsics::_isLowerCase :
8871       n = new LowerCaseNode(control(), codePoint);
8872       break;
8873     case vmIntrinsics::_isUpperCase :
8874       n = new UpperCaseNode(control(), codePoint);
8875       break;
8876     case vmIntrinsics::_isWhitespace :
8877       n = new WhitespaceNode(control(), codePoint);
8878       break;
8879     default:
8880       fatal_unexpected_iid(id);
8881   }
8882 
8883   set_result(_gvn.transform(n));
8884   return true;
8885 }
8886 
8887 bool LibraryCallKit::inline_profileBoolean() {
8888   Node* counts = argument(1);
8889   const TypeAryPtr* ary = nullptr;
8890   ciArray* aobj = nullptr;
8891   if (counts->is_Con()
8892       && (ary = counts->bottom_type()->isa_aryptr()) != nullptr
8893       && (aobj = ary->const_oop()->as_array()) != nullptr
8894       && (aobj->length() == 2)) {
8895     // Profile is int[2] where [0] and [1] correspond to false and true value occurrences respectively.
8896     jint false_cnt = aobj->element_value(0).as_int();
8897     jint  true_cnt = aobj->element_value(1).as_int();
8898 
8899     if (C->log() != nullptr) {
8900       C->log()->elem("observe source='profileBoolean' false='%d' true='%d'",
8901                      false_cnt, true_cnt);
8902     }
8903 
8904     if (false_cnt + true_cnt == 0) {
8905       // According to profile, never executed.
8906       uncommon_trap_exact(Deoptimization::Reason_intrinsic,
8907                           Deoptimization::Action_reinterpret);
8908       return true;
8909     }
8910 
8911     // result is a boolean (0 or 1) and its profile (false_cnt & true_cnt)
8912     // is a number of each value occurrences.
8913     Node* result = argument(0);
8914     if (false_cnt == 0 || true_cnt == 0) {
8915       // According to profile, one value has been never seen.
8916       int expected_val = (false_cnt == 0) ? 1 : 0;
8917 
8918       Node* cmp  = _gvn.transform(new CmpINode(result, intcon(expected_val)));
8919       Node* test = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
8920 
8921       IfNode* check = create_and_map_if(control(), test, PROB_ALWAYS, COUNT_UNKNOWN);
8922       Node* fast_path = _gvn.transform(new IfTrueNode(check));
8923       Node* slow_path = _gvn.transform(new IfFalseNode(check));
8924 
8925       { // Slow path: uncommon trap for never seen value and then reexecute
8926         // MethodHandleImpl::profileBoolean() to bump the count, so JIT knows
8927         // the value has been seen at least once.
8928         PreserveJVMState pjvms(this);
8929         PreserveReexecuteState preexecs(this);
8930         jvms()->set_should_reexecute(true);
8931 
8932         set_control(slow_path);
8933         set_i_o(i_o());
8934 
8935         uncommon_trap_exact(Deoptimization::Reason_intrinsic,
8936                             Deoptimization::Action_reinterpret);
8937       }
8938       // The guard for never seen value enables sharpening of the result and
8939       // returning a constant. It allows to eliminate branches on the same value
8940       // later on.
8941       set_control(fast_path);
8942       result = intcon(expected_val);
8943     }
8944     // Stop profiling.
8945     // MethodHandleImpl::profileBoolean() has profiling logic in its bytecode.
8946     // By replacing method body with profile data (represented as ProfileBooleanNode
8947     // on IR level) we effectively disable profiling.
8948     // It enables full speed execution once optimized code is generated.
8949     Node* profile = _gvn.transform(new ProfileBooleanNode(result, false_cnt, true_cnt));
8950     C->record_for_igvn(profile);
8951     set_result(profile);
8952     return true;
8953   } else {
8954     // Continue profiling.
8955     // Profile data isn't available at the moment. So, execute method's bytecode version.
8956     // Usually, when GWT LambdaForms are profiled it means that a stand-alone nmethod
8957     // is compiled and counters aren't available since corresponding MethodHandle
8958     // isn't a compile-time constant.
8959     return false;
8960   }
8961 }
8962 
8963 bool LibraryCallKit::inline_isCompileConstant() {
8964   Node* n = argument(0);
8965   set_result(n->is_Con() ? intcon(1) : intcon(0));
8966   return true;
8967 }
8968 
8969 //------------------------------- inline_getObjectSize --------------------------------------
8970 //
8971 // Calculate the runtime size of the object/array.
8972 //   native long sun.instrument.InstrumentationImpl.getObjectSize0(long nativeAgent, Object objectToSize);
8973 //
8974 bool LibraryCallKit::inline_getObjectSize() {
8975   Node* obj = argument(3);
8976   Node* klass_node = load_object_klass(obj);
8977 
8978   jint  layout_con = Klass::_lh_neutral_value;
8979   Node* layout_val = get_layout_helper(klass_node, layout_con);
8980   int   layout_is_con = (layout_val == nullptr);
8981 
8982   if (layout_is_con) {
8983     // Layout helper is constant, can figure out things at compile time.
8984 
8985     if (Klass::layout_helper_is_instance(layout_con)) {
8986       // Instance case:  layout_con contains the size itself.
8987       Node *size = longcon(Klass::layout_helper_size_in_bytes(layout_con));
8988       set_result(size);
8989     } else {
8990       // Array case: size is round(header + element_size*arraylength).
8991       // Since arraylength is different for every array instance, we have to
8992       // compute the whole thing at runtime.
8993 
8994       Node* arr_length = load_array_length(obj);
8995 
8996       int round_mask = MinObjAlignmentInBytes - 1;
8997       int hsize  = Klass::layout_helper_header_size(layout_con);
8998       int eshift = Klass::layout_helper_log2_element_size(layout_con);
8999 
9000       if ((round_mask & ~right_n_bits(eshift)) == 0) {
9001         round_mask = 0;  // strength-reduce it if it goes away completely
9002       }
9003       assert((hsize & right_n_bits(eshift)) == 0, "hsize is pre-rounded");
9004       Node* header_size = intcon(hsize + round_mask);
9005 
9006       Node* lengthx = ConvI2X(arr_length);
9007       Node* headerx = ConvI2X(header_size);
9008 
9009       Node* abody = lengthx;
9010       if (eshift != 0) {
9011         abody = _gvn.transform(new LShiftXNode(lengthx, intcon(eshift)));
9012       }
9013       Node* size = _gvn.transform( new AddXNode(headerx, abody) );
9014       if (round_mask != 0) {
9015         size = _gvn.transform( new AndXNode(size, MakeConX(~round_mask)) );
9016       }
9017       size = ConvX2L(size);
9018       set_result(size);
9019     }
9020   } else {
9021     // Layout helper is not constant, need to test for array-ness at runtime.
9022 
9023     enum { _instance_path = 1, _array_path, PATH_LIMIT };
9024     RegionNode* result_reg = new RegionNode(PATH_LIMIT);
9025     PhiNode* result_val = new PhiNode(result_reg, TypeLong::LONG);
9026     record_for_igvn(result_reg);
9027 
9028     Node* array_ctl = generate_array_guard(klass_node, nullptr, &obj);
9029     if (array_ctl != nullptr) {
9030       // Array case: size is round(header + element_size*arraylength).
9031       // Since arraylength is different for every array instance, we have to
9032       // compute the whole thing at runtime.
9033 
9034       PreserveJVMState pjvms(this);
9035       set_control(array_ctl);
9036       Node* arr_length = load_array_length(obj);
9037 
9038       int round_mask = MinObjAlignmentInBytes - 1;
9039       Node* mask = intcon(round_mask);
9040 
9041       Node* hss = intcon(Klass::_lh_header_size_shift);
9042       Node* hsm = intcon(Klass::_lh_header_size_mask);
9043       Node* header_size = _gvn.transform(new URShiftINode(layout_val, hss));
9044       header_size = _gvn.transform(new AndINode(header_size, hsm));
9045       header_size = _gvn.transform(new AddINode(header_size, mask));
9046 
9047       // There is no need to mask or shift this value.
9048       // The semantics of LShiftINode include an implicit mask to 0x1F.
9049       assert(Klass::_lh_log2_element_size_shift == 0, "use shift in place");
9050       Node* elem_shift = layout_val;
9051 
9052       Node* lengthx = ConvI2X(arr_length);
9053       Node* headerx = ConvI2X(header_size);
9054 
9055       Node* abody = _gvn.transform(new LShiftXNode(lengthx, elem_shift));
9056       Node* size = _gvn.transform(new AddXNode(headerx, abody));
9057       if (round_mask != 0) {
9058         size = _gvn.transform(new AndXNode(size, MakeConX(~round_mask)));
9059       }
9060       size = ConvX2L(size);
9061 
9062       result_reg->init_req(_array_path, control());
9063       result_val->init_req(_array_path, size);
9064     }
9065 
9066     if (!stopped()) {
9067       // Instance case: the layout helper gives us instance size almost directly,
9068       // but we need to mask out the _lh_instance_slow_path_bit.
9069       Node* size = ConvI2X(layout_val);
9070       assert((int) Klass::_lh_instance_slow_path_bit < BytesPerLong, "clear bit");
9071       Node* mask = MakeConX(~(intptr_t) right_n_bits(LogBytesPerLong));
9072       size = _gvn.transform(new AndXNode(size, mask));
9073       size = ConvX2L(size);
9074 
9075       result_reg->init_req(_instance_path, control());
9076       result_val->init_req(_instance_path, size);
9077     }
9078 
9079     set_result(result_reg, result_val);
9080   }
9081 
9082   return true;
9083 }
9084 
9085 //------------------------------- inline_blackhole --------------------------------------
9086 //
9087 // Make sure all arguments to this node are alive.
9088 // This matches methods that were requested to be blackholed through compile commands.
9089 //
9090 bool LibraryCallKit::inline_blackhole() {
9091   assert(callee()->is_static(), "Should have been checked before: only static methods here");
9092   assert(callee()->is_empty(), "Should have been checked before: only empty methods here");
9093   assert(callee()->holder()->is_loaded(), "Should have been checked before: only methods for loaded classes here");
9094 
9095   // Blackhole node pinches only the control, not memory. This allows
9096   // the blackhole to be pinned in the loop that computes blackholed
9097   // values, but have no other side effects, like breaking the optimizations
9098   // across the blackhole.
9099 
9100   Node* bh = _gvn.transform(new BlackholeNode(control()));
9101   set_control(_gvn.transform(new ProjNode(bh, TypeFunc::Control)));
9102 
9103   // Bind call arguments as blackhole arguments to keep them alive
9104   uint nargs = callee()->arg_size();
9105   for (uint i = 0; i < nargs; i++) {
9106     bh->add_req(argument(i));
9107   }
9108 
9109   return true;
9110 }
9111 
9112 Node* LibraryCallKit::unbox_fp16_value(const TypeInstPtr* float16_box_type, ciField* field, Node* box) {
9113   const TypeInstPtr* box_type = _gvn.type(box)->isa_instptr();
9114   if (box_type == nullptr || box_type->instance_klass() != float16_box_type->instance_klass()) {
9115     return nullptr; // box klass is not Float16
9116   }
9117 
9118   // Null check; get notnull casted pointer
9119   Node* null_ctl = top();
9120   Node* not_null_box = null_check_oop(box, &null_ctl, true);
9121   // If not_null_box is dead, only null-path is taken
9122   if (stopped()) {
9123     set_control(null_ctl);
9124     return nullptr;
9125   }
9126   assert(not_null_box->bottom_type()->is_instptr()->maybe_null() == false, "");
9127   const TypePtr* adr_type = C->alias_type(field)->adr_type();
9128   Node* adr = basic_plus_adr(not_null_box, field->offset_in_bytes());
9129   return access_load_at(not_null_box, adr, adr_type, TypeInt::SHORT, T_SHORT, IN_HEAP);
9130 }
9131 
9132 Node* LibraryCallKit::box_fp16_value(const TypeInstPtr* float16_box_type, ciField* field, Node* value) {
9133   PreserveReexecuteState preexecs(this);
9134   jvms()->set_should_reexecute(true);
9135 
9136   const TypeKlassPtr* klass_type = float16_box_type->as_klass_type();
9137   Node* klass_node = makecon(klass_type);
9138   Node* box = new_instance(klass_node);
9139 
9140   Node* value_field = basic_plus_adr(box, field->offset_in_bytes());
9141   const TypePtr* value_adr_type = value_field->bottom_type()->is_ptr();
9142 
9143   Node* field_store = _gvn.transform(access_store_at(box,
9144                                                      value_field,
9145                                                      value_adr_type,
9146                                                      value,
9147                                                      TypeInt::SHORT,
9148                                                      T_SHORT,
9149                                                      IN_HEAP));
9150   set_memory(field_store, value_adr_type);
9151   return box;
9152 }
9153 
9154 bool LibraryCallKit::inline_fp16_operations(vmIntrinsics::ID id, int num_args) {
9155   if (!Matcher::match_rule_supported(Op_ReinterpretS2HF) ||
9156       !Matcher::match_rule_supported(Op_ReinterpretHF2S)) {
9157     return false;
9158   }
9159 
9160   const TypeInstPtr* box_type = _gvn.type(argument(0))->isa_instptr();
9161   if (box_type == nullptr || box_type->const_oop() == nullptr) {
9162     return false;
9163   }
9164 
9165   ciInstanceKlass* float16_klass = box_type->const_oop()->as_instance()->java_lang_Class_klass()->as_instance_klass();
9166   const TypeInstPtr* float16_box_type = TypeInstPtr::make_exact(TypePtr::NotNull, float16_klass);
9167   ciField* field = float16_klass->get_field_by_name(ciSymbols::value_name(),
9168                                                     ciSymbols::short_signature(),
9169                                                     false);
9170   assert(field != nullptr, "");
9171 
9172   // Transformed nodes
9173   Node* fld1 = nullptr;
9174   Node* fld2 = nullptr;
9175   Node* fld3 = nullptr;
9176   switch(num_args) {
9177     case 3:
9178       fld3 = unbox_fp16_value(float16_box_type, field, argument(3));
9179       if (fld3 == nullptr) {
9180         return false;
9181       }
9182       fld3 = _gvn.transform(new ReinterpretS2HFNode(fld3));
9183     // fall-through
9184     case 2:
9185       fld2 = unbox_fp16_value(float16_box_type, field, argument(2));
9186       if (fld2 == nullptr) {
9187         return false;
9188       }
9189       fld2 = _gvn.transform(new ReinterpretS2HFNode(fld2));
9190     // fall-through
9191     case 1:
9192       fld1 = unbox_fp16_value(float16_box_type, field, argument(1));
9193       if (fld1 == nullptr) {
9194         return false;
9195       }
9196       fld1 = _gvn.transform(new ReinterpretS2HFNode(fld1));
9197       break;
9198     default: fatal("Unsupported number of arguments %d", num_args);
9199   }
9200 
9201   Node* result = nullptr;
9202   switch (id) {
9203     // Unary operations
9204     case vmIntrinsics::_sqrt_float16:
9205       result = _gvn.transform(new SqrtHFNode(C, control(), fld1));
9206       break;
9207     // Ternary operations
9208     case vmIntrinsics::_fma_float16:
9209       result = _gvn.transform(new FmaHFNode(fld1, fld2, fld3));
9210       break;
9211     default:
9212       fatal_unexpected_iid(id);
9213       break;
9214   }
9215   result = _gvn.transform(new ReinterpretHF2SNode(result));
9216   set_result(box_fp16_value(float16_box_type, field, result));
9217   return true;
9218 }
9219