1 /*
   2  * Copyright (c) 1999, 2026, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "asm/macroAssembler.hpp"
  26 #include "ci/ciArrayKlass.hpp"
  27 #include "ci/ciFlatArrayKlass.hpp"
  28 #include "ci/ciInstanceKlass.hpp"
  29 #include "ci/ciSymbols.hpp"
  30 #include "ci/ciUtilities.inline.hpp"
  31 #include "classfile/vmIntrinsics.hpp"
  32 #include "compiler/compileBroker.hpp"
  33 #include "compiler/compileLog.hpp"
  34 #include "gc/shared/barrierSet.hpp"
  35 #include "gc/shared/c2/barrierSetC2.hpp"
  36 #include "jfr/support/jfrIntrinsics.hpp"
  37 #include "memory/resourceArea.hpp"
  38 #include "oops/accessDecorators.hpp"
  39 #include "oops/klass.inline.hpp"
  40 #include "oops/layoutKind.hpp"
  41 #include "oops/objArrayKlass.hpp"
  42 #include "opto/addnode.hpp"
  43 #include "opto/arraycopynode.hpp"
  44 #include "opto/c2compiler.hpp"
  45 #include "opto/castnode.hpp"
  46 #include "opto/cfgnode.hpp"
  47 #include "opto/convertnode.hpp"
  48 #include "opto/countbitsnode.hpp"
  49 #include "opto/graphKit.hpp"
  50 #include "opto/idealKit.hpp"
  51 #include "opto/inlinetypenode.hpp"
  52 #include "opto/library_call.hpp"
  53 #include "opto/mathexactnode.hpp"
  54 #include "opto/mulnode.hpp"
  55 #include "opto/narrowptrnode.hpp"
  56 #include "opto/opaquenode.hpp"
  57 #include "opto/opcodes.hpp"
  58 #include "opto/parse.hpp"
  59 #include "opto/rootnode.hpp"
  60 #include "opto/runtime.hpp"
  61 #include "opto/subnode.hpp"
  62 #include "opto/type.hpp"
  63 #include "opto/vectornode.hpp"
  64 #include "prims/jvmtiExport.hpp"
  65 #include "prims/jvmtiThreadState.hpp"
  66 #include "prims/unsafe.hpp"
  67 #include "runtime/globals.hpp"
  68 #include "runtime/jniHandles.inline.hpp"
  69 #include "runtime/mountUnmountDisabler.hpp"
  70 #include "runtime/objectMonitor.hpp"
  71 #include "runtime/sharedRuntime.hpp"
  72 #include "runtime/stubRoutines.hpp"
  73 #include "utilities/globalDefinitions.hpp"
  74 #include "utilities/macros.hpp"
  75 #include "utilities/powerOfTwo.hpp"
  76 
  77 //---------------------------make_vm_intrinsic----------------------------
  78 CallGenerator* Compile::make_vm_intrinsic(ciMethod* m, bool is_virtual) {
  79   vmIntrinsicID id = m->intrinsic_id();
  80   assert(id != vmIntrinsics::_none, "must be a VM intrinsic");
  81 
  82   if (!m->is_loaded()) {
  83     // Do not attempt to inline unloaded methods.
  84     return nullptr;
  85   }
  86 
  87   C2Compiler* compiler = (C2Compiler*)CompileBroker::compiler(CompLevel_full_optimization);
  88   bool is_available = false;
  89 
  90   {
  91     // For calling is_intrinsic_supported and is_intrinsic_disabled_by_flag
  92     // the compiler must transition to '_thread_in_vm' state because both
  93     // methods access VM-internal data.
  94     VM_ENTRY_MARK;
  95     methodHandle mh(THREAD, m->get_Method());
  96     is_available = compiler != nullptr && compiler->is_intrinsic_available(mh, C->directive());
  97     if (is_available && is_virtual) {
  98       is_available = vmIntrinsics::does_virtual_dispatch(id);
  99     }
 100   }
 101 
 102   if (is_available) {
 103     assert(id <= vmIntrinsics::LAST_COMPILER_INLINE, "caller responsibility");
 104     assert(id != vmIntrinsics::_Object_init && id != vmIntrinsics::_invoke, "enum out of order?");
 105     return new LibraryIntrinsic(m, is_virtual,
 106                                 vmIntrinsics::predicates_needed(id),
 107                                 vmIntrinsics::does_virtual_dispatch(id),
 108                                 id);
 109   } else {
 110     return nullptr;
 111   }
 112 }
 113 
 114 JVMState* LibraryIntrinsic::generate(JVMState* jvms) {
 115   LibraryCallKit kit(jvms, this);
 116   Compile* C = kit.C;
 117   int nodes = C->unique();
 118 #ifndef PRODUCT
 119   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
 120     char buf[1000];
 121     const char* str = vmIntrinsics::short_name_as_C_string(intrinsic_id(), buf, sizeof(buf));
 122     tty->print_cr("Intrinsic %s", str);
 123   }
 124 #endif
 125   ciMethod* callee = kit.callee();
 126   const int bci    = kit.bci();
 127 #ifdef ASSERT
 128   Node* ctrl = kit.control();
 129 #endif
 130   // Try to inline the intrinsic.
 131   if (callee->check_intrinsic_candidate() &&
 132       kit.try_to_inline(_last_predicate)) {
 133     const char *inline_msg = is_virtual() ? "(intrinsic, virtual)"
 134                                           : "(intrinsic)";
 135     CompileTask::print_inlining_ul(callee, jvms->depth() - 1, bci, InliningResult::SUCCESS, inline_msg);
 136     C->inline_printer()->record(callee, jvms, InliningResult::SUCCESS, inline_msg);
 137     C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_worked);
 138     if (C->log()) {
 139       C->log()->elem("intrinsic id='%s'%s nodes='%d'",
 140                      vmIntrinsics::name_at(intrinsic_id()),
 141                      (is_virtual() ? " virtual='1'" : ""),
 142                      C->unique() - nodes);
 143     }
 144     // Push the result from the inlined method onto the stack.
 145     kit.push_result();
 146     return kit.transfer_exceptions_into_jvms();
 147   }
 148 
 149   // The intrinsic bailed out
 150   assert(ctrl == kit.control(), "Control flow was added although the intrinsic bailed out");
 151   assert(jvms->map() == kit.map(), "Out of sync JVM state");
 152   if (jvms->has_method()) {
 153     // Not a root compile.
 154     const char* msg;
 155     if (callee->intrinsic_candidate()) {
 156       msg = is_virtual() ? "failed to inline (intrinsic, virtual)" : "failed to inline (intrinsic)";
 157     } else {
 158       msg = is_virtual() ? "failed to inline (intrinsic, virtual), method not annotated"
 159                          : "failed to inline (intrinsic), method not annotated";
 160     }
 161     CompileTask::print_inlining_ul(callee, jvms->depth() - 1, bci, InliningResult::FAILURE, msg);
 162     C->inline_printer()->record(callee, jvms, InliningResult::FAILURE, msg);
 163   } else {
 164     // Root compile
 165     ResourceMark rm;
 166     stringStream msg_stream;
 167     msg_stream.print("Did not generate intrinsic %s%s at bci:%d in",
 168                      vmIntrinsics::name_at(intrinsic_id()),
 169                      is_virtual() ? " (virtual)" : "", bci);
 170     const char *msg = msg_stream.freeze();
 171     log_debug(jit, inlining)("%s", msg);
 172     if (C->print_intrinsics() || C->print_inlining()) {
 173       tty->print("%s", msg);
 174     }
 175   }
 176   C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_failed);
 177 
 178   return nullptr;
 179 }
 180 
 181 Node* LibraryIntrinsic::generate_predicate(JVMState* jvms, int predicate) {
 182   LibraryCallKit kit(jvms, this);
 183   Compile* C = kit.C;
 184   int nodes = C->unique();
 185   _last_predicate = predicate;
 186 #ifndef PRODUCT
 187   assert(is_predicated() && predicate < predicates_count(), "sanity");
 188   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
 189     char buf[1000];
 190     const char* str = vmIntrinsics::short_name_as_C_string(intrinsic_id(), buf, sizeof(buf));
 191     tty->print_cr("Predicate for intrinsic %s", str);
 192   }
 193 #endif
 194   ciMethod* callee = kit.callee();
 195   const int bci    = kit.bci();
 196 
 197   Node* slow_ctl = kit.try_to_predicate(predicate);
 198   if (!kit.failing()) {
 199     const char *inline_msg = is_virtual() ? "(intrinsic, virtual, predicate)"
 200                                           : "(intrinsic, predicate)";
 201     CompileTask::print_inlining_ul(callee, jvms->depth() - 1, bci, InliningResult::SUCCESS, inline_msg);
 202     C->inline_printer()->record(callee, jvms, InliningResult::SUCCESS, inline_msg);
 203 
 204     C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_worked);
 205     if (C->log()) {
 206       C->log()->elem("predicate_intrinsic id='%s'%s nodes='%d'",
 207                      vmIntrinsics::name_at(intrinsic_id()),
 208                      (is_virtual() ? " virtual='1'" : ""),
 209                      C->unique() - nodes);
 210     }
 211     return slow_ctl; // Could be null if the check folds.
 212   }
 213 
 214   // The intrinsic bailed out
 215   if (jvms->has_method()) {
 216     // Not a root compile.
 217     const char* msg = "failed to generate predicate for intrinsic";
 218     CompileTask::print_inlining_ul(kit.callee(), jvms->depth() - 1, bci, InliningResult::FAILURE, msg);
 219     C->inline_printer()->record(kit.callee(), jvms, InliningResult::FAILURE, msg);
 220   } else {
 221     // Root compile
 222     ResourceMark rm;
 223     stringStream msg_stream;
 224     msg_stream.print("Did not generate intrinsic %s%s at bci:%d in",
 225                      vmIntrinsics::name_at(intrinsic_id()),
 226                      is_virtual() ? " (virtual)" : "", bci);
 227     const char *msg = msg_stream.freeze();
 228     log_debug(jit, inlining)("%s", msg);
 229     C->inline_printer()->record(kit.callee(), jvms, InliningResult::FAILURE, msg);
 230   }
 231   C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_failed);
 232   return nullptr;
 233 }
 234 
 235 bool LibraryCallKit::try_to_inline(int predicate) {
 236   // Handle symbolic names for otherwise undistinguished boolean switches:
 237   const bool is_store       = true;
 238   const bool is_compress    = true;
 239   const bool is_static      = true;
 240   const bool is_volatile    = true;
 241 
 242   if (!jvms()->has_method()) {
 243     // Root JVMState has a null method.
 244     assert(map()->memory()->Opcode() == Op_Parm, "");
 245     // Insert the memory aliasing node
 246     set_all_memory(reset_memory());
 247   }
 248   assert(merged_memory(), "");
 249 
 250   switch (intrinsic_id()) {
 251   case vmIntrinsics::_hashCode:                 return inline_native_hashcode(intrinsic()->is_virtual(), !is_static);
 252   case vmIntrinsics::_identityHashCode:         return inline_native_hashcode(/*!virtual*/ false,         is_static);
 253   case vmIntrinsics::_getClass:                 return inline_native_getClass();
 254 
 255   case vmIntrinsics::_ceil:
 256   case vmIntrinsics::_floor:
 257   case vmIntrinsics::_rint:
 258   case vmIntrinsics::_dsin:
 259   case vmIntrinsics::_dcos:
 260   case vmIntrinsics::_dtan:
 261   case vmIntrinsics::_dsinh:
 262   case vmIntrinsics::_dtanh:
 263   case vmIntrinsics::_dcbrt:
 264   case vmIntrinsics::_dabs:
 265   case vmIntrinsics::_fabs:
 266   case vmIntrinsics::_iabs:
 267   case vmIntrinsics::_labs:
 268   case vmIntrinsics::_datan2:
 269   case vmIntrinsics::_dsqrt:
 270   case vmIntrinsics::_dsqrt_strict:
 271   case vmIntrinsics::_dexp:
 272   case vmIntrinsics::_dlog:
 273   case vmIntrinsics::_dlog10:
 274   case vmIntrinsics::_dpow:
 275   case vmIntrinsics::_dcopySign:
 276   case vmIntrinsics::_fcopySign:
 277   case vmIntrinsics::_dsignum:
 278   case vmIntrinsics::_roundF:
 279   case vmIntrinsics::_roundD:
 280   case vmIntrinsics::_fsignum:                  return inline_math_native(intrinsic_id());
 281 
 282   case vmIntrinsics::_notify:
 283   case vmIntrinsics::_notifyAll:
 284     return inline_notify(intrinsic_id());
 285 
 286   case vmIntrinsics::_addExactI:                return inline_math_addExactI(false /* add */);
 287   case vmIntrinsics::_addExactL:                return inline_math_addExactL(false /* add */);
 288   case vmIntrinsics::_decrementExactI:          return inline_math_subtractExactI(true /* decrement */);
 289   case vmIntrinsics::_decrementExactL:          return inline_math_subtractExactL(true /* decrement */);
 290   case vmIntrinsics::_incrementExactI:          return inline_math_addExactI(true /* increment */);
 291   case vmIntrinsics::_incrementExactL:          return inline_math_addExactL(true /* increment */);
 292   case vmIntrinsics::_multiplyExactI:           return inline_math_multiplyExactI();
 293   case vmIntrinsics::_multiplyExactL:           return inline_math_multiplyExactL();
 294   case vmIntrinsics::_multiplyHigh:             return inline_math_multiplyHigh();
 295   case vmIntrinsics::_unsignedMultiplyHigh:     return inline_math_unsignedMultiplyHigh();
 296   case vmIntrinsics::_negateExactI:             return inline_math_negateExactI();
 297   case vmIntrinsics::_negateExactL:             return inline_math_negateExactL();
 298   case vmIntrinsics::_subtractExactI:           return inline_math_subtractExactI(false /* subtract */);
 299   case vmIntrinsics::_subtractExactL:           return inline_math_subtractExactL(false /* subtract */);
 300 
 301   case vmIntrinsics::_arraycopy:                return inline_arraycopy();
 302 
 303   case vmIntrinsics::_arraySort:                return inline_array_sort();
 304   case vmIntrinsics::_arrayPartition:           return inline_array_partition();
 305 
 306   case vmIntrinsics::_compareToL:               return inline_string_compareTo(StrIntrinsicNode::LL);
 307   case vmIntrinsics::_compareToU:               return inline_string_compareTo(StrIntrinsicNode::UU);
 308   case vmIntrinsics::_compareToLU:              return inline_string_compareTo(StrIntrinsicNode::LU);
 309   case vmIntrinsics::_compareToUL:              return inline_string_compareTo(StrIntrinsicNode::UL);
 310 
 311   case vmIntrinsics::_indexOfL:                 return inline_string_indexOf(StrIntrinsicNode::LL);
 312   case vmIntrinsics::_indexOfU:                 return inline_string_indexOf(StrIntrinsicNode::UU);
 313   case vmIntrinsics::_indexOfUL:                return inline_string_indexOf(StrIntrinsicNode::UL);
 314   case vmIntrinsics::_indexOfIL:                return inline_string_indexOfI(StrIntrinsicNode::LL);
 315   case vmIntrinsics::_indexOfIU:                return inline_string_indexOfI(StrIntrinsicNode::UU);
 316   case vmIntrinsics::_indexOfIUL:               return inline_string_indexOfI(StrIntrinsicNode::UL);
 317   case vmIntrinsics::_indexOfU_char:            return inline_string_indexOfChar(StrIntrinsicNode::U);
 318   case vmIntrinsics::_indexOfL_char:            return inline_string_indexOfChar(StrIntrinsicNode::L);
 319 
 320   case vmIntrinsics::_equalsL:                  return inline_string_equals(StrIntrinsicNode::LL);
 321 
 322   case vmIntrinsics::_vectorizedHashCode:       return inline_vectorizedHashCode();
 323 
 324   case vmIntrinsics::_toBytesStringU:           return inline_string_toBytesU();
 325   case vmIntrinsics::_getCharsStringU:          return inline_string_getCharsU();
 326   case vmIntrinsics::_getCharStringU:           return inline_string_char_access(!is_store);
 327   case vmIntrinsics::_putCharStringU:           return inline_string_char_access( is_store);
 328 
 329   case vmIntrinsics::_compressStringC:
 330   case vmIntrinsics::_compressStringB:          return inline_string_copy( is_compress);
 331   case vmIntrinsics::_inflateStringC:
 332   case vmIntrinsics::_inflateStringB:           return inline_string_copy(!is_compress);
 333 
 334   case vmIntrinsics::_getReference:             return inline_unsafe_access(!is_store, T_OBJECT,   Relaxed, false);
 335   case vmIntrinsics::_getBoolean:               return inline_unsafe_access(!is_store, T_BOOLEAN,  Relaxed, false);
 336   case vmIntrinsics::_getByte:                  return inline_unsafe_access(!is_store, T_BYTE,     Relaxed, false);
 337   case vmIntrinsics::_getShort:                 return inline_unsafe_access(!is_store, T_SHORT,    Relaxed, false);
 338   case vmIntrinsics::_getChar:                  return inline_unsafe_access(!is_store, T_CHAR,     Relaxed, false);
 339   case vmIntrinsics::_getInt:                   return inline_unsafe_access(!is_store, T_INT,      Relaxed, false);
 340   case vmIntrinsics::_getLong:                  return inline_unsafe_access(!is_store, T_LONG,     Relaxed, false);
 341   case vmIntrinsics::_getFloat:                 return inline_unsafe_access(!is_store, T_FLOAT,    Relaxed, false);
 342   case vmIntrinsics::_getDouble:                return inline_unsafe_access(!is_store, T_DOUBLE,   Relaxed, false);
 343 
 344   case vmIntrinsics::_putReference:             return inline_unsafe_access( is_store, T_OBJECT,   Relaxed, false);
 345   case vmIntrinsics::_putBoolean:               return inline_unsafe_access( is_store, T_BOOLEAN,  Relaxed, false);
 346   case vmIntrinsics::_putByte:                  return inline_unsafe_access( is_store, T_BYTE,     Relaxed, false);
 347   case vmIntrinsics::_putShort:                 return inline_unsafe_access( is_store, T_SHORT,    Relaxed, false);
 348   case vmIntrinsics::_putChar:                  return inline_unsafe_access( is_store, T_CHAR,     Relaxed, false);
 349   case vmIntrinsics::_putInt:                   return inline_unsafe_access( is_store, T_INT,      Relaxed, false);
 350   case vmIntrinsics::_putLong:                  return inline_unsafe_access( is_store, T_LONG,     Relaxed, false);
 351   case vmIntrinsics::_putFloat:                 return inline_unsafe_access( is_store, T_FLOAT,    Relaxed, false);
 352   case vmIntrinsics::_putDouble:                return inline_unsafe_access( is_store, T_DOUBLE,   Relaxed, false);
 353 
 354   case vmIntrinsics::_getReferenceVolatile:     return inline_unsafe_access(!is_store, T_OBJECT,   Volatile, false);
 355   case vmIntrinsics::_getBooleanVolatile:       return inline_unsafe_access(!is_store, T_BOOLEAN,  Volatile, false);
 356   case vmIntrinsics::_getByteVolatile:          return inline_unsafe_access(!is_store, T_BYTE,     Volatile, false);
 357   case vmIntrinsics::_getShortVolatile:         return inline_unsafe_access(!is_store, T_SHORT,    Volatile, false);
 358   case vmIntrinsics::_getCharVolatile:          return inline_unsafe_access(!is_store, T_CHAR,     Volatile, false);
 359   case vmIntrinsics::_getIntVolatile:           return inline_unsafe_access(!is_store, T_INT,      Volatile, false);
 360   case vmIntrinsics::_getLongVolatile:          return inline_unsafe_access(!is_store, T_LONG,     Volatile, false);
 361   case vmIntrinsics::_getFloatVolatile:         return inline_unsafe_access(!is_store, T_FLOAT,    Volatile, false);
 362   case vmIntrinsics::_getDoubleVolatile:        return inline_unsafe_access(!is_store, T_DOUBLE,   Volatile, false);
 363 
 364   case vmIntrinsics::_putReferenceVolatile:     return inline_unsafe_access( is_store, T_OBJECT,   Volatile, false);
 365   case vmIntrinsics::_putBooleanVolatile:       return inline_unsafe_access( is_store, T_BOOLEAN,  Volatile, false);
 366   case vmIntrinsics::_putByteVolatile:          return inline_unsafe_access( is_store, T_BYTE,     Volatile, false);
 367   case vmIntrinsics::_putShortVolatile:         return inline_unsafe_access( is_store, T_SHORT,    Volatile, false);
 368   case vmIntrinsics::_putCharVolatile:          return inline_unsafe_access( is_store, T_CHAR,     Volatile, false);
 369   case vmIntrinsics::_putIntVolatile:           return inline_unsafe_access( is_store, T_INT,      Volatile, false);
 370   case vmIntrinsics::_putLongVolatile:          return inline_unsafe_access( is_store, T_LONG,     Volatile, false);
 371   case vmIntrinsics::_putFloatVolatile:         return inline_unsafe_access( is_store, T_FLOAT,    Volatile, false);
 372   case vmIntrinsics::_putDoubleVolatile:        return inline_unsafe_access( is_store, T_DOUBLE,   Volatile, false);
 373 
 374   case vmIntrinsics::_getShortUnaligned:        return inline_unsafe_access(!is_store, T_SHORT,    Relaxed, true);
 375   case vmIntrinsics::_getCharUnaligned:         return inline_unsafe_access(!is_store, T_CHAR,     Relaxed, true);
 376   case vmIntrinsics::_getIntUnaligned:          return inline_unsafe_access(!is_store, T_INT,      Relaxed, true);
 377   case vmIntrinsics::_getLongUnaligned:         return inline_unsafe_access(!is_store, T_LONG,     Relaxed, true);
 378 
 379   case vmIntrinsics::_putShortUnaligned:        return inline_unsafe_access( is_store, T_SHORT,    Relaxed, true);
 380   case vmIntrinsics::_putCharUnaligned:         return inline_unsafe_access( is_store, T_CHAR,     Relaxed, true);
 381   case vmIntrinsics::_putIntUnaligned:          return inline_unsafe_access( is_store, T_INT,      Relaxed, true);
 382   case vmIntrinsics::_putLongUnaligned:         return inline_unsafe_access( is_store, T_LONG,     Relaxed, true);
 383 
 384   case vmIntrinsics::_getReferenceAcquire:      return inline_unsafe_access(!is_store, T_OBJECT,   Acquire, false);
 385   case vmIntrinsics::_getBooleanAcquire:        return inline_unsafe_access(!is_store, T_BOOLEAN,  Acquire, false);
 386   case vmIntrinsics::_getByteAcquire:           return inline_unsafe_access(!is_store, T_BYTE,     Acquire, false);
 387   case vmIntrinsics::_getShortAcquire:          return inline_unsafe_access(!is_store, T_SHORT,    Acquire, false);
 388   case vmIntrinsics::_getCharAcquire:           return inline_unsafe_access(!is_store, T_CHAR,     Acquire, false);
 389   case vmIntrinsics::_getIntAcquire:            return inline_unsafe_access(!is_store, T_INT,      Acquire, false);
 390   case vmIntrinsics::_getLongAcquire:           return inline_unsafe_access(!is_store, T_LONG,     Acquire, false);
 391   case vmIntrinsics::_getFloatAcquire:          return inline_unsafe_access(!is_store, T_FLOAT,    Acquire, false);
 392   case vmIntrinsics::_getDoubleAcquire:         return inline_unsafe_access(!is_store, T_DOUBLE,   Acquire, false);
 393 
 394   case vmIntrinsics::_putReferenceRelease:      return inline_unsafe_access( is_store, T_OBJECT,   Release, false);
 395   case vmIntrinsics::_putBooleanRelease:        return inline_unsafe_access( is_store, T_BOOLEAN,  Release, false);
 396   case vmIntrinsics::_putByteRelease:           return inline_unsafe_access( is_store, T_BYTE,     Release, false);
 397   case vmIntrinsics::_putShortRelease:          return inline_unsafe_access( is_store, T_SHORT,    Release, false);
 398   case vmIntrinsics::_putCharRelease:           return inline_unsafe_access( is_store, T_CHAR,     Release, false);
 399   case vmIntrinsics::_putIntRelease:            return inline_unsafe_access( is_store, T_INT,      Release, false);
 400   case vmIntrinsics::_putLongRelease:           return inline_unsafe_access( is_store, T_LONG,     Release, false);
 401   case vmIntrinsics::_putFloatRelease:          return inline_unsafe_access( is_store, T_FLOAT,    Release, false);
 402   case vmIntrinsics::_putDoubleRelease:         return inline_unsafe_access( is_store, T_DOUBLE,   Release, false);
 403 
 404   case vmIntrinsics::_getReferenceOpaque:       return inline_unsafe_access(!is_store, T_OBJECT,   Opaque, false);
 405   case vmIntrinsics::_getBooleanOpaque:         return inline_unsafe_access(!is_store, T_BOOLEAN,  Opaque, false);
 406   case vmIntrinsics::_getByteOpaque:            return inline_unsafe_access(!is_store, T_BYTE,     Opaque, false);
 407   case vmIntrinsics::_getShortOpaque:           return inline_unsafe_access(!is_store, T_SHORT,    Opaque, false);
 408   case vmIntrinsics::_getCharOpaque:            return inline_unsafe_access(!is_store, T_CHAR,     Opaque, false);
 409   case vmIntrinsics::_getIntOpaque:             return inline_unsafe_access(!is_store, T_INT,      Opaque, false);
 410   case vmIntrinsics::_getLongOpaque:            return inline_unsafe_access(!is_store, T_LONG,     Opaque, false);
 411   case vmIntrinsics::_getFloatOpaque:           return inline_unsafe_access(!is_store, T_FLOAT,    Opaque, false);
 412   case vmIntrinsics::_getDoubleOpaque:          return inline_unsafe_access(!is_store, T_DOUBLE,   Opaque, false);
 413 
 414   case vmIntrinsics::_putReferenceOpaque:       return inline_unsafe_access( is_store, T_OBJECT,   Opaque, false);
 415   case vmIntrinsics::_putBooleanOpaque:         return inline_unsafe_access( is_store, T_BOOLEAN,  Opaque, false);
 416   case vmIntrinsics::_putByteOpaque:            return inline_unsafe_access( is_store, T_BYTE,     Opaque, false);
 417   case vmIntrinsics::_putShortOpaque:           return inline_unsafe_access( is_store, T_SHORT,    Opaque, false);
 418   case vmIntrinsics::_putCharOpaque:            return inline_unsafe_access( is_store, T_CHAR,     Opaque, false);
 419   case vmIntrinsics::_putIntOpaque:             return inline_unsafe_access( is_store, T_INT,      Opaque, false);
 420   case vmIntrinsics::_putLongOpaque:            return inline_unsafe_access( is_store, T_LONG,     Opaque, false);
 421   case vmIntrinsics::_putFloatOpaque:           return inline_unsafe_access( is_store, T_FLOAT,    Opaque, false);
 422   case vmIntrinsics::_putDoubleOpaque:          return inline_unsafe_access( is_store, T_DOUBLE,   Opaque, false);
 423 
 424   case vmIntrinsics::_getFlatValue:             return inline_unsafe_flat_access(!is_store, Relaxed);
 425   case vmIntrinsics::_putFlatValue:             return inline_unsafe_flat_access( is_store, Relaxed);
 426 
 427   case vmIntrinsics::_compareAndSetReference:   return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap,      Volatile);
 428   case vmIntrinsics::_compareAndSetByte:        return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap,      Volatile);
 429   case vmIntrinsics::_compareAndSetShort:       return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap,      Volatile);
 430   case vmIntrinsics::_compareAndSetInt:         return inline_unsafe_load_store(T_INT,    LS_cmp_swap,      Volatile);
 431   case vmIntrinsics::_compareAndSetLong:        return inline_unsafe_load_store(T_LONG,   LS_cmp_swap,      Volatile);
 432 
 433   case vmIntrinsics::_weakCompareAndSetReferencePlain:     return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Relaxed);
 434   case vmIntrinsics::_weakCompareAndSetReferenceAcquire:   return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Acquire);
 435   case vmIntrinsics::_weakCompareAndSetReferenceRelease:   return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Release);
 436   case vmIntrinsics::_weakCompareAndSetReference:          return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Volatile);
 437   case vmIntrinsics::_weakCompareAndSetBytePlain:          return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap_weak, Relaxed);
 438   case vmIntrinsics::_weakCompareAndSetByteAcquire:        return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap_weak, Acquire);
 439   case vmIntrinsics::_weakCompareAndSetByteRelease:        return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap_weak, Release);
 440   case vmIntrinsics::_weakCompareAndSetByte:               return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap_weak, Volatile);
 441   case vmIntrinsics::_weakCompareAndSetShortPlain:         return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap_weak, Relaxed);
 442   case vmIntrinsics::_weakCompareAndSetShortAcquire:       return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap_weak, Acquire);
 443   case vmIntrinsics::_weakCompareAndSetShortRelease:       return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap_weak, Release);
 444   case vmIntrinsics::_weakCompareAndSetShort:              return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap_weak, Volatile);
 445   case vmIntrinsics::_weakCompareAndSetIntPlain:           return inline_unsafe_load_store(T_INT,    LS_cmp_swap_weak, Relaxed);
 446   case vmIntrinsics::_weakCompareAndSetIntAcquire:         return inline_unsafe_load_store(T_INT,    LS_cmp_swap_weak, Acquire);
 447   case vmIntrinsics::_weakCompareAndSetIntRelease:         return inline_unsafe_load_store(T_INT,    LS_cmp_swap_weak, Release);
 448   case vmIntrinsics::_weakCompareAndSetInt:                return inline_unsafe_load_store(T_INT,    LS_cmp_swap_weak, Volatile);
 449   case vmIntrinsics::_weakCompareAndSetLongPlain:          return inline_unsafe_load_store(T_LONG,   LS_cmp_swap_weak, Relaxed);
 450   case vmIntrinsics::_weakCompareAndSetLongAcquire:        return inline_unsafe_load_store(T_LONG,   LS_cmp_swap_weak, Acquire);
 451   case vmIntrinsics::_weakCompareAndSetLongRelease:        return inline_unsafe_load_store(T_LONG,   LS_cmp_swap_weak, Release);
 452   case vmIntrinsics::_weakCompareAndSetLong:               return inline_unsafe_load_store(T_LONG,   LS_cmp_swap_weak, Volatile);
 453 
 454   case vmIntrinsics::_compareAndExchangeReference:         return inline_unsafe_load_store(T_OBJECT, LS_cmp_exchange,  Volatile);
 455   case vmIntrinsics::_compareAndExchangeReferenceAcquire:  return inline_unsafe_load_store(T_OBJECT, LS_cmp_exchange,  Acquire);
 456   case vmIntrinsics::_compareAndExchangeReferenceRelease:  return inline_unsafe_load_store(T_OBJECT, LS_cmp_exchange,  Release);
 457   case vmIntrinsics::_compareAndExchangeByte:              return inline_unsafe_load_store(T_BYTE,   LS_cmp_exchange,  Volatile);
 458   case vmIntrinsics::_compareAndExchangeByteAcquire:       return inline_unsafe_load_store(T_BYTE,   LS_cmp_exchange,  Acquire);
 459   case vmIntrinsics::_compareAndExchangeByteRelease:       return inline_unsafe_load_store(T_BYTE,   LS_cmp_exchange,  Release);
 460   case vmIntrinsics::_compareAndExchangeShort:             return inline_unsafe_load_store(T_SHORT,  LS_cmp_exchange,  Volatile);
 461   case vmIntrinsics::_compareAndExchangeShortAcquire:      return inline_unsafe_load_store(T_SHORT,  LS_cmp_exchange,  Acquire);
 462   case vmIntrinsics::_compareAndExchangeShortRelease:      return inline_unsafe_load_store(T_SHORT,  LS_cmp_exchange,  Release);
 463   case vmIntrinsics::_compareAndExchangeInt:               return inline_unsafe_load_store(T_INT,    LS_cmp_exchange,  Volatile);
 464   case vmIntrinsics::_compareAndExchangeIntAcquire:        return inline_unsafe_load_store(T_INT,    LS_cmp_exchange,  Acquire);
 465   case vmIntrinsics::_compareAndExchangeIntRelease:        return inline_unsafe_load_store(T_INT,    LS_cmp_exchange,  Release);
 466   case vmIntrinsics::_compareAndExchangeLong:              return inline_unsafe_load_store(T_LONG,   LS_cmp_exchange,  Volatile);
 467   case vmIntrinsics::_compareAndExchangeLongAcquire:       return inline_unsafe_load_store(T_LONG,   LS_cmp_exchange,  Acquire);
 468   case vmIntrinsics::_compareAndExchangeLongRelease:       return inline_unsafe_load_store(T_LONG,   LS_cmp_exchange,  Release);
 469 
 470   case vmIntrinsics::_getAndAddByte:                    return inline_unsafe_load_store(T_BYTE,   LS_get_add,       Volatile);
 471   case vmIntrinsics::_getAndAddShort:                   return inline_unsafe_load_store(T_SHORT,  LS_get_add,       Volatile);
 472   case vmIntrinsics::_getAndAddInt:                     return inline_unsafe_load_store(T_INT,    LS_get_add,       Volatile);
 473   case vmIntrinsics::_getAndAddLong:                    return inline_unsafe_load_store(T_LONG,   LS_get_add,       Volatile);
 474 
 475   case vmIntrinsics::_getAndSetByte:                    return inline_unsafe_load_store(T_BYTE,   LS_get_set,       Volatile);
 476   case vmIntrinsics::_getAndSetShort:                   return inline_unsafe_load_store(T_SHORT,  LS_get_set,       Volatile);
 477   case vmIntrinsics::_getAndSetInt:                     return inline_unsafe_load_store(T_INT,    LS_get_set,       Volatile);
 478   case vmIntrinsics::_getAndSetLong:                    return inline_unsafe_load_store(T_LONG,   LS_get_set,       Volatile);
 479   case vmIntrinsics::_getAndSetReference:               return inline_unsafe_load_store(T_OBJECT, LS_get_set,       Volatile);
 480 
 481   case vmIntrinsics::_loadFence:
 482   case vmIntrinsics::_storeFence:
 483   case vmIntrinsics::_storeStoreFence:
 484   case vmIntrinsics::_fullFence:                return inline_unsafe_fence(intrinsic_id());
 485 
 486   case vmIntrinsics::_arrayInstanceBaseOffset:  return inline_arrayInstanceBaseOffset();
 487   case vmIntrinsics::_arrayInstanceIndexScale:  return inline_arrayInstanceIndexScale();
 488   case vmIntrinsics::_arrayLayout:              return inline_arrayLayout();
 489   case vmIntrinsics::_getFieldMap:              return inline_getFieldMap();
 490 
 491   case vmIntrinsics::_onSpinWait:               return inline_onspinwait();
 492 
 493   case vmIntrinsics::_currentCarrierThread:     return inline_native_currentCarrierThread();
 494   case vmIntrinsics::_currentThread:            return inline_native_currentThread();
 495   case vmIntrinsics::_setCurrentThread:         return inline_native_setCurrentThread();
 496 
 497   case vmIntrinsics::_scopedValueCache:          return inline_native_scopedValueCache();
 498   case vmIntrinsics::_setScopedValueCache:       return inline_native_setScopedValueCache();
 499 
 500   case vmIntrinsics::_Continuation_pin:          return inline_native_Continuation_pinning(false);
 501   case vmIntrinsics::_Continuation_unpin:        return inline_native_Continuation_pinning(true);
 502 
 503   case vmIntrinsics::_vthreadEndFirstTransition:    return inline_native_vthread_end_transition(CAST_FROM_FN_PTR(address, OptoRuntime::vthread_end_first_transition_Java()),
 504                                                                                                 "endFirstTransition", true);
 505   case vmIntrinsics::_vthreadStartFinalTransition:  return inline_native_vthread_start_transition(CAST_FROM_FN_PTR(address, OptoRuntime::vthread_start_final_transition_Java()),
 506                                                                                                   "startFinalTransition", true);
 507   case vmIntrinsics::_vthreadStartTransition:       return inline_native_vthread_start_transition(CAST_FROM_FN_PTR(address, OptoRuntime::vthread_start_transition_Java()),
 508                                                                                                   "startTransition", false);
 509   case vmIntrinsics::_vthreadEndTransition:         return inline_native_vthread_end_transition(CAST_FROM_FN_PTR(address, OptoRuntime::vthread_end_transition_Java()),
 510                                                                                                 "endTransition", false);
 511 #if INCLUDE_JVMTI
 512   case vmIntrinsics::_notifyJvmtiVThreadDisableSuspend: return inline_native_notify_jvmti_sync();
 513 #endif
 514 
 515 #ifdef JFR_HAVE_INTRINSICS
 516   case vmIntrinsics::_counterTime:              return inline_native_time_funcs(CAST_FROM_FN_PTR(address, JfrTime::time_function()), "counterTime");
 517   case vmIntrinsics::_getEventWriter:           return inline_native_getEventWriter();
 518   case vmIntrinsics::_jvm_commit:               return inline_native_jvm_commit();
 519 #endif
 520   case vmIntrinsics::_currentTimeMillis:        return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeMillis), "currentTimeMillis");
 521   case vmIntrinsics::_nanoTime:                 return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeNanos), "nanoTime");
 522   case vmIntrinsics::_writeback0:               return inline_unsafe_writeback0();
 523   case vmIntrinsics::_writebackPreSync0:        return inline_unsafe_writebackSync0(true);
 524   case vmIntrinsics::_writebackPostSync0:       return inline_unsafe_writebackSync0(false);
 525   case vmIntrinsics::_allocateInstance:         return inline_unsafe_allocate();
 526   case vmIntrinsics::_copyMemory:               return inline_unsafe_copyMemory();
 527   case vmIntrinsics::_setMemory:                return inline_unsafe_setMemory();
 528   case vmIntrinsics::_getLength:                return inline_native_getLength();
 529   case vmIntrinsics::_copyOf:                   return inline_array_copyOf(false);
 530   case vmIntrinsics::_copyOfRange:              return inline_array_copyOf(true);
 531   case vmIntrinsics::_equalsB:                  return inline_array_equals(StrIntrinsicNode::LL);
 532   case vmIntrinsics::_equalsC:                  return inline_array_equals(StrIntrinsicNode::UU);
 533   case vmIntrinsics::_Preconditions_checkIndex: return inline_preconditions_checkIndex(T_INT);
 534   case vmIntrinsics::_Preconditions_checkLongIndex: return inline_preconditions_checkIndex(T_LONG);
 535   case vmIntrinsics::_clone:                    return inline_native_clone(intrinsic()->is_virtual());
 536 
 537   case vmIntrinsics::_allocateUninitializedArray: return inline_unsafe_newArray(true);
 538   case vmIntrinsics::_newArray:                   return inline_unsafe_newArray(false);
 539   case vmIntrinsics::_newNullRestrictedNonAtomicArray: return inline_newArray(/* null_free */ true, /* atomic */ false);
 540   case vmIntrinsics::_newNullRestrictedAtomicArray: return inline_newArray(/* null_free */ true, /* atomic */ true);
 541   case vmIntrinsics::_newNullableAtomicArray:     return inline_newArray(/* null_free */ false, /* atomic */ true);
 542   case vmIntrinsics::_isFlatArray:              return inline_getArrayProperties(IsFlat);
 543   case vmIntrinsics::_isNullRestrictedArray:    return inline_getArrayProperties(IsNullRestricted);
 544   case vmIntrinsics::_isAtomicArray:            return inline_getArrayProperties(IsAtomic);
 545 
 546   case vmIntrinsics::_isAssignableFrom:         return inline_native_subtype_check();
 547 
 548   case vmIntrinsics::_isInstance:
 549   case vmIntrinsics::_isHidden:
 550   case vmIntrinsics::_getSuperclass:            return inline_native_Class_query(intrinsic_id());
 551 
 552   case vmIntrinsics::_floatToRawIntBits:
 553   case vmIntrinsics::_floatToIntBits:
 554   case vmIntrinsics::_intBitsToFloat:
 555   case vmIntrinsics::_doubleToRawLongBits:
 556   case vmIntrinsics::_doubleToLongBits:
 557   case vmIntrinsics::_longBitsToDouble:
 558   case vmIntrinsics::_floatToFloat16:
 559   case vmIntrinsics::_float16ToFloat:           return inline_fp_conversions(intrinsic_id());
 560   case vmIntrinsics::_sqrt_float16:             return inline_fp16_operations(intrinsic_id(), 1);
 561   case vmIntrinsics::_fma_float16:              return inline_fp16_operations(intrinsic_id(), 3);
 562   case vmIntrinsics::_floatIsFinite:
 563   case vmIntrinsics::_floatIsInfinite:
 564   case vmIntrinsics::_doubleIsFinite:
 565   case vmIntrinsics::_doubleIsInfinite:         return inline_fp_range_check(intrinsic_id());
 566 
 567   case vmIntrinsics::_numberOfLeadingZeros_i:
 568   case vmIntrinsics::_numberOfLeadingZeros_l:
 569   case vmIntrinsics::_numberOfTrailingZeros_i:
 570   case vmIntrinsics::_numberOfTrailingZeros_l:
 571   case vmIntrinsics::_bitCount_i:
 572   case vmIntrinsics::_bitCount_l:
 573   case vmIntrinsics::_reverse_i:
 574   case vmIntrinsics::_reverse_l:
 575   case vmIntrinsics::_reverseBytes_i:
 576   case vmIntrinsics::_reverseBytes_l:
 577   case vmIntrinsics::_reverseBytes_s:
 578   case vmIntrinsics::_reverseBytes_c:           return inline_number_methods(intrinsic_id());
 579 
 580   case vmIntrinsics::_compress_i:
 581   case vmIntrinsics::_compress_l:
 582   case vmIntrinsics::_expand_i:
 583   case vmIntrinsics::_expand_l:                 return inline_bitshuffle_methods(intrinsic_id());
 584 
 585   case vmIntrinsics::_compareUnsigned_i:
 586   case vmIntrinsics::_compareUnsigned_l:        return inline_compare_unsigned(intrinsic_id());
 587 
 588   case vmIntrinsics::_divideUnsigned_i:
 589   case vmIntrinsics::_divideUnsigned_l:
 590   case vmIntrinsics::_remainderUnsigned_i:
 591   case vmIntrinsics::_remainderUnsigned_l:      return inline_divmod_methods(intrinsic_id());
 592 
 593   case vmIntrinsics::_getCallerClass:           return inline_native_Reflection_getCallerClass();
 594 
 595   case vmIntrinsics::_Reference_get0:           return inline_reference_get0();
 596   case vmIntrinsics::_Reference_refersTo0:      return inline_reference_refersTo0(false);
 597   case vmIntrinsics::_PhantomReference_refersTo0: return inline_reference_refersTo0(true);
 598   case vmIntrinsics::_Reference_clear0:         return inline_reference_clear0(false);
 599   case vmIntrinsics::_PhantomReference_clear0:  return inline_reference_clear0(true);
 600 
 601   case vmIntrinsics::_Class_cast:               return inline_Class_cast();
 602 
 603   case vmIntrinsics::_aescrypt_encryptBlock:
 604   case vmIntrinsics::_aescrypt_decryptBlock:    return inline_aescrypt_Block(intrinsic_id());
 605 
 606   case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
 607   case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
 608     return inline_cipherBlockChaining_AESCrypt(intrinsic_id());
 609 
 610   case vmIntrinsics::_electronicCodeBook_encryptAESCrypt:
 611   case vmIntrinsics::_electronicCodeBook_decryptAESCrypt:
 612     return inline_electronicCodeBook_AESCrypt(intrinsic_id());
 613 
 614   case vmIntrinsics::_counterMode_AESCrypt:
 615     return inline_counterMode_AESCrypt(intrinsic_id());
 616 
 617   case vmIntrinsics::_galoisCounterMode_AESCrypt:
 618     return inline_galoisCounterMode_AESCrypt();
 619 
 620   case vmIntrinsics::_md5_implCompress:
 621   case vmIntrinsics::_sha_implCompress:
 622   case vmIntrinsics::_sha2_implCompress:
 623   case vmIntrinsics::_sha5_implCompress:
 624   case vmIntrinsics::_sha3_implCompress:
 625     return inline_digestBase_implCompress(intrinsic_id());
 626   case vmIntrinsics::_double_keccak:
 627     return inline_double_keccak();
 628 
 629   case vmIntrinsics::_digestBase_implCompressMB:
 630     return inline_digestBase_implCompressMB(predicate);
 631 
 632   case vmIntrinsics::_multiplyToLen:
 633     return inline_multiplyToLen();
 634 
 635   case vmIntrinsics::_squareToLen:
 636     return inline_squareToLen();
 637 
 638   case vmIntrinsics::_mulAdd:
 639     return inline_mulAdd();
 640 
 641   case vmIntrinsics::_montgomeryMultiply:
 642     return inline_montgomeryMultiply();
 643   case vmIntrinsics::_montgomerySquare:
 644     return inline_montgomerySquare();
 645 
 646   case vmIntrinsics::_bigIntegerRightShiftWorker:
 647     return inline_bigIntegerShift(true);
 648   case vmIntrinsics::_bigIntegerLeftShiftWorker:
 649     return inline_bigIntegerShift(false);
 650 
 651   case vmIntrinsics::_vectorizedMismatch:
 652     return inline_vectorizedMismatch();
 653 
 654   case vmIntrinsics::_ghash_processBlocks:
 655     return inline_ghash_processBlocks();
 656   case vmIntrinsics::_chacha20Block:
 657     return inline_chacha20Block();
 658   case vmIntrinsics::_kyberNtt:
 659     return inline_kyberNtt();
 660   case vmIntrinsics::_kyberInverseNtt:
 661     return inline_kyberInverseNtt();
 662   case vmIntrinsics::_kyberNttMult:
 663     return inline_kyberNttMult();
 664   case vmIntrinsics::_kyberAddPoly_2:
 665     return inline_kyberAddPoly_2();
 666   case vmIntrinsics::_kyberAddPoly_3:
 667     return inline_kyberAddPoly_3();
 668   case vmIntrinsics::_kyber12To16:
 669     return inline_kyber12To16();
 670   case vmIntrinsics::_kyberBarrettReduce:
 671     return inline_kyberBarrettReduce();
 672   case vmIntrinsics::_dilithiumAlmostNtt:
 673     return inline_dilithiumAlmostNtt();
 674   case vmIntrinsics::_dilithiumAlmostInverseNtt:
 675     return inline_dilithiumAlmostInverseNtt();
 676   case vmIntrinsics::_dilithiumNttMult:
 677     return inline_dilithiumNttMult();
 678   case vmIntrinsics::_dilithiumMontMulByConstant:
 679     return inline_dilithiumMontMulByConstant();
 680   case vmIntrinsics::_dilithiumDecomposePoly:
 681     return inline_dilithiumDecomposePoly();
 682   case vmIntrinsics::_base64_encodeBlock:
 683     return inline_base64_encodeBlock();
 684   case vmIntrinsics::_base64_decodeBlock:
 685     return inline_base64_decodeBlock();
 686   case vmIntrinsics::_poly1305_processBlocks:
 687     return inline_poly1305_processBlocks();
 688   case vmIntrinsics::_intpoly_montgomeryMult_P256:
 689     return inline_intpoly_montgomeryMult_P256();
 690   case vmIntrinsics::_intpoly_assign:
 691     return inline_intpoly_assign();
 692   case vmIntrinsics::_encodeISOArray:
 693   case vmIntrinsics::_encodeByteISOArray:
 694     return inline_encodeISOArray(false);
 695   case vmIntrinsics::_encodeAsciiArray:
 696     return inline_encodeISOArray(true);
 697 
 698   case vmIntrinsics::_updateCRC32:
 699     return inline_updateCRC32();
 700   case vmIntrinsics::_updateBytesCRC32:
 701     return inline_updateBytesCRC32();
 702   case vmIntrinsics::_updateByteBufferCRC32:
 703     return inline_updateByteBufferCRC32();
 704 
 705   case vmIntrinsics::_updateBytesCRC32C:
 706     return inline_updateBytesCRC32C();
 707   case vmIntrinsics::_updateDirectByteBufferCRC32C:
 708     return inline_updateDirectByteBufferCRC32C();
 709 
 710   case vmIntrinsics::_updateBytesAdler32:
 711     return inline_updateBytesAdler32();
 712   case vmIntrinsics::_updateByteBufferAdler32:
 713     return inline_updateByteBufferAdler32();
 714 
 715   case vmIntrinsics::_profileBoolean:
 716     return inline_profileBoolean();
 717   case vmIntrinsics::_isCompileConstant:
 718     return inline_isCompileConstant();
 719 
 720   case vmIntrinsics::_countPositives:
 721     return inline_countPositives();
 722 
 723   case vmIntrinsics::_fmaD:
 724   case vmIntrinsics::_fmaF:
 725     return inline_fma(intrinsic_id());
 726 
 727   case vmIntrinsics::_isDigit:
 728   case vmIntrinsics::_isLowerCase:
 729   case vmIntrinsics::_isUpperCase:
 730   case vmIntrinsics::_isWhitespace:
 731     return inline_character_compare(intrinsic_id());
 732 
 733   case vmIntrinsics::_min:
 734   case vmIntrinsics::_max:
 735   case vmIntrinsics::_min_strict:
 736   case vmIntrinsics::_max_strict:
 737   case vmIntrinsics::_minL:
 738   case vmIntrinsics::_maxL:
 739   case vmIntrinsics::_minF:
 740   case vmIntrinsics::_maxF:
 741   case vmIntrinsics::_minD:
 742   case vmIntrinsics::_maxD:
 743   case vmIntrinsics::_minF_strict:
 744   case vmIntrinsics::_maxF_strict:
 745   case vmIntrinsics::_minD_strict:
 746   case vmIntrinsics::_maxD_strict:
 747     return inline_min_max(intrinsic_id());
 748 
 749   case vmIntrinsics::_VectorUnaryOp:
 750     return inline_vector_nary_operation(1);
 751   case vmIntrinsics::_VectorBinaryOp:
 752     return inline_vector_nary_operation(2);
 753   case vmIntrinsics::_VectorUnaryLibOp:
 754     return inline_vector_call(1);
 755   case vmIntrinsics::_VectorBinaryLibOp:
 756     return inline_vector_call(2);
 757   case vmIntrinsics::_VectorTernaryOp:
 758     return inline_vector_nary_operation(3);
 759   case vmIntrinsics::_VectorFromBitsCoerced:
 760     return inline_vector_frombits_coerced();
 761   case vmIntrinsics::_VectorMaskOp:
 762     return inline_vector_mask_operation();
 763   case vmIntrinsics::_VectorLoadOp:
 764     return inline_vector_mem_operation(/*is_store=*/false);
 765   case vmIntrinsics::_VectorLoadMaskedOp:
 766     return inline_vector_mem_masked_operation(/*is_store*/false);
 767   case vmIntrinsics::_VectorStoreOp:
 768     return inline_vector_mem_operation(/*is_store=*/true);
 769   case vmIntrinsics::_VectorStoreMaskedOp:
 770     return inline_vector_mem_masked_operation(/*is_store=*/true);
 771   case vmIntrinsics::_VectorGatherOp:
 772     return inline_vector_gather_scatter(/*is_scatter*/ false);
 773   case vmIntrinsics::_VectorScatterOp:
 774     return inline_vector_gather_scatter(/*is_scatter*/ true);
 775   case vmIntrinsics::_VectorReductionCoerced:
 776     return inline_vector_reduction();
 777   case vmIntrinsics::_VectorTest:
 778     return inline_vector_test();
 779   case vmIntrinsics::_VectorBlend:
 780     return inline_vector_blend();
 781   case vmIntrinsics::_VectorRearrange:
 782     return inline_vector_rearrange();
 783   case vmIntrinsics::_VectorSelectFrom:
 784     return inline_vector_select_from();
 785   case vmIntrinsics::_VectorCompare:
 786     return inline_vector_compare();
 787   case vmIntrinsics::_VectorBroadcastInt:
 788     return inline_vector_broadcast_int();
 789   case vmIntrinsics::_VectorConvert:
 790     return inline_vector_convert();
 791   case vmIntrinsics::_VectorInsert:
 792     return inline_vector_insert();
 793   case vmIntrinsics::_VectorExtract:
 794     return inline_vector_extract();
 795   case vmIntrinsics::_VectorCompressExpand:
 796     return inline_vector_compress_expand();
 797   case vmIntrinsics::_VectorSelectFromTwoVectorOp:
 798     return inline_vector_select_from_two_vectors();
 799   case vmIntrinsics::_IndexVector:
 800     return inline_index_vector();
 801   case vmIntrinsics::_IndexPartiallyInUpperRange:
 802     return inline_index_partially_in_upper_range();
 803 
 804   case vmIntrinsics::_getObjectSize:
 805     return inline_getObjectSize();
 806 
 807   case vmIntrinsics::_blackhole:
 808     return inline_blackhole();
 809 
 810   default:
 811     // If you get here, it may be that someone has added a new intrinsic
 812     // to the list in vmIntrinsics.hpp without implementing it here.
 813 #ifndef PRODUCT
 814     if ((PrintMiscellaneous && (Verbose || WizardMode)) || PrintOpto) {
 815       tty->print_cr("*** Warning: Unimplemented intrinsic %s(%d)",
 816                     vmIntrinsics::name_at(intrinsic_id()), vmIntrinsics::as_int(intrinsic_id()));
 817     }
 818 #endif
 819     return false;
 820   }
 821 }
 822 
 823 Node* LibraryCallKit::try_to_predicate(int predicate) {
 824   if (!jvms()->has_method()) {
 825     // Root JVMState has a null method.
 826     assert(map()->memory()->Opcode() == Op_Parm, "");
 827     // Insert the memory aliasing node
 828     set_all_memory(reset_memory());
 829   }
 830   assert(merged_memory(), "");
 831 
 832   switch (intrinsic_id()) {
 833   case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
 834     return inline_cipherBlockChaining_AESCrypt_predicate(false);
 835   case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
 836     return inline_cipherBlockChaining_AESCrypt_predicate(true);
 837   case vmIntrinsics::_electronicCodeBook_encryptAESCrypt:
 838     return inline_electronicCodeBook_AESCrypt_predicate(false);
 839   case vmIntrinsics::_electronicCodeBook_decryptAESCrypt:
 840     return inline_electronicCodeBook_AESCrypt_predicate(true);
 841   case vmIntrinsics::_counterMode_AESCrypt:
 842     return inline_counterMode_AESCrypt_predicate();
 843   case vmIntrinsics::_digestBase_implCompressMB:
 844     return inline_digestBase_implCompressMB_predicate(predicate);
 845   case vmIntrinsics::_galoisCounterMode_AESCrypt:
 846     return inline_galoisCounterMode_AESCrypt_predicate();
 847 
 848   default:
 849     // If you get here, it may be that someone has added a new intrinsic
 850     // to the list in vmIntrinsics.hpp without implementing it here.
 851 #ifndef PRODUCT
 852     if ((PrintMiscellaneous && (Verbose || WizardMode)) || PrintOpto) {
 853       tty->print_cr("*** Warning: Unimplemented predicate for intrinsic %s(%d)",
 854                     vmIntrinsics::name_at(intrinsic_id()), vmIntrinsics::as_int(intrinsic_id()));
 855     }
 856 #endif
 857     Node* slow_ctl = control();
 858     set_control(top()); // No fast path intrinsic
 859     return slow_ctl;
 860   }
 861 }
 862 
 863 //------------------------------set_result-------------------------------
 864 // Helper function for finishing intrinsics.
 865 void LibraryCallKit::set_result(RegionNode* region, PhiNode* value) {
 866   record_for_igvn(region);
 867   set_control(_gvn.transform(region));
 868   set_result( _gvn.transform(value));
 869   assert(value->type()->basic_type() == result()->bottom_type()->basic_type(), "sanity");
 870 }
 871 
 872 RegionNode* LibraryCallKit::create_bailout() {
 873   RegionNode* bailout = new RegionNode(1);
 874   record_for_igvn(bailout);
 875   return bailout;
 876 }
 877 
 878 bool LibraryCallKit::check_bailout(RegionNode* bailout) {
 879   if (bailout->req() > 1) {
 880     bailout = _gvn.transform(bailout)->as_Region();
 881     Node* frame = _gvn.transform(new ParmNode(C->start(), TypeFunc::FramePtr));
 882     Node* halt = _gvn.transform(new HaltNode(bailout, frame, "unexpected guard failure in intrinsic"));
 883     C->root()->add_req(halt);
 884   }
 885   return stopped();
 886 }
 887 
 888 //------------------------------generate_guard---------------------------
 889 // Helper function for generating guarded fast-slow graph structures.
 890 // The given 'test', if true, guards a slow path.  If the test fails
 891 // then a fast path can be taken.  (We generally hope it fails.)
 892 // In all cases, GraphKit::control() is updated to the fast path.
 893 // The returned value represents the control for the slow path.
 894 // The return value is never 'top'; it is either a valid control
 895 // or null if it is obvious that the slow path can never be taken.
 896 // Also, if region and the slow control are not null, the slow edge
 897 // is appended to the region.
 898 Node* LibraryCallKit::generate_guard(Node* test, RegionNode* region, float true_prob) {
 899   if (stopped()) {
 900     // Already short circuited.
 901     return nullptr;
 902   }
 903 
 904   // Build an if node and its projections.
 905   // If test is true we take the slow path, which we assume is uncommon.
 906   if (_gvn.type(test) == TypeInt::ZERO) {
 907     // The slow branch is never taken.  No need to build this guard.
 908     return nullptr;
 909   }
 910 
 911   IfNode* iff = create_and_map_if(control(), test, true_prob, COUNT_UNKNOWN);
 912 
 913   Node* if_slow = _gvn.transform(new IfTrueNode(iff));
 914   if (if_slow == top()) {
 915     // The slow branch is never taken.  No need to build this guard.
 916     return nullptr;
 917   }
 918 
 919   if (region != nullptr)
 920     region->add_req(if_slow);
 921 
 922   Node* if_fast = _gvn.transform(new IfFalseNode(iff));
 923   set_control(if_fast);
 924 
 925   return if_slow;
 926 }
 927 
 928 inline Node* LibraryCallKit::generate_slow_guard(Node* test, RegionNode* region) {
 929   return generate_guard(test, region, PROB_UNLIKELY_MAG(3));
 930 }
 931 inline Node* LibraryCallKit::generate_fair_guard(Node* test, RegionNode* region) {
 932   return generate_guard(test, region, PROB_FAIR);
 933 }
 934 
 935 inline Node* LibraryCallKit::generate_negative_guard(Node* index, RegionNode* region,
 936                                                      Node** pos_index, bool with_opaque) {
 937   if (stopped())
 938     return nullptr;                // already stopped
 939   if (_gvn.type(index)->higher_equal(TypeInt::POS)) // [0,maxint]
 940     return nullptr;                // index is already adequately typed
 941   Node* cmp_lt = _gvn.transform(new CmpINode(index, intcon(0)));
 942   Node* bol_lt = _gvn.transform(new BoolNode(cmp_lt, BoolTest::lt));
 943   if (with_opaque) {
 944     bol_lt = _gvn.transform(new OpaqueConstantBoolNode(C, bol_lt, false));
 945   }
 946   Node* is_neg = generate_guard(bol_lt, region, PROB_MIN);
 947   if (is_neg != nullptr && pos_index != nullptr) {
 948     // Emulate effect of Parse::adjust_map_after_if.
 949     Node* ccast = new CastIINode(control(), index, TypeInt::POS);
 950     (*pos_index) = _gvn.transform(ccast);
 951   }
 952   return is_neg;
 953 }
 954 
 955 // Make sure that 'position' is a valid limit index, in [0..length].
 956 // There are two equivalent plans for checking this:
 957 //   A. (offset + copyLength)  unsigned<=  arrayLength
 958 //   B. offset  <=  (arrayLength - copyLength)
 959 // We require that all of the values above, except for the sum and
 960 // difference, are already known to be non-negative.
 961 // Plan A is robust in the face of overflow, if offset and copyLength
 962 // are both hugely positive.
 963 //
 964 // Plan B is less direct and intuitive, but it does not overflow at
 965 // all, since the difference of two non-negatives is always
 966 // representable.  Whenever Java methods must perform the equivalent
 967 // check they generally use Plan B instead of Plan A.
 968 // For the moment we use Plan A.
 969 inline Node* LibraryCallKit::generate_limit_guard(Node* offset,
 970                                                   Node* subseq_length,
 971                                                   Node* array_length,
 972                                                   RegionNode* region,
 973                                                   bool with_opaque) {
 974   if (stopped())
 975     return nullptr;                // already stopped
 976   bool zero_offset = _gvn.type(offset) == TypeInt::ZERO;
 977   if (zero_offset && subseq_length->eqv_uncast(array_length))
 978     return nullptr;                // common case of whole-array copy
 979   Node* last = subseq_length;
 980   if (!zero_offset)             // last += offset
 981     last = _gvn.transform(new AddINode(last, offset));
 982   Node* cmp_lt = _gvn.transform(new CmpUNode(array_length, last));
 983   Node* bol_lt = _gvn.transform(new BoolNode(cmp_lt, BoolTest::lt));
 984   if (with_opaque) {
 985     bol_lt = _gvn.transform(new OpaqueConstantBoolNode(C, bol_lt, false));
 986   }
 987   Node* is_over = generate_guard(bol_lt, region, PROB_MIN);
 988   return is_over;
 989 }
 990 
 991 // Emit range checks for the given String.value byte array
 992 void LibraryCallKit::generate_string_range_check(Node* array,
 993                                                  Node* offset,
 994                                                  Node* count,
 995                                                  bool char_count,
 996                                                  RegionNode* region) {
 997   if (stopped()) {
 998     return; // already stopped
 999   }
1000   if (char_count) {
1001     // Convert char count to byte count
1002     count = _gvn.transform(new LShiftINode(count, intcon(1)));
1003   }
1004   // Offset and count must not be negative
1005   generate_negative_guard(offset, region, nullptr, true);
1006   generate_negative_guard(count, region, nullptr, true);
1007   // Offset + count must not exceed length of array
1008   generate_limit_guard(offset, count, load_array_length(array), region, true);
1009 }
1010 
1011 Node* LibraryCallKit::current_thread_helper(Node*& tls_output, ByteSize handle_offset,
1012                                             bool is_immutable) {
1013   ciKlass* thread_klass = env()->Thread_klass();
1014   const Type* thread_type
1015     = TypeOopPtr::make_from_klass(thread_klass)->cast_to_ptr_type(TypePtr::NotNull);
1016 
1017   Node* thread = _gvn.transform(new ThreadLocalNode());
1018   Node* p = off_heap_plus_addr(thread, in_bytes(handle_offset));
1019   tls_output = thread;
1020 
1021   Node* thread_obj_handle
1022     = (is_immutable
1023       ? LoadNode::make(_gvn, nullptr, immutable_memory(), p, p->bottom_type()->is_ptr(),
1024         TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered)
1025       : make_load(nullptr, p, p->bottom_type()->is_ptr(), T_ADDRESS, MemNode::unordered));
1026   thread_obj_handle = _gvn.transform(thread_obj_handle);
1027 
1028   DecoratorSet decorators = IN_NATIVE;
1029   if (is_immutable) {
1030     decorators |= C2_IMMUTABLE_MEMORY;
1031   }
1032   return access_load(thread_obj_handle, thread_type, T_OBJECT, decorators);
1033 }
1034 
1035 //--------------------------generate_current_thread--------------------
1036 Node* LibraryCallKit::generate_current_thread(Node* &tls_output) {
1037   return current_thread_helper(tls_output, JavaThread::threadObj_offset(),
1038                                /*is_immutable*/false);
1039 }
1040 
1041 //--------------------------generate_virtual_thread--------------------
1042 Node* LibraryCallKit::generate_virtual_thread(Node* tls_output) {
1043   return current_thread_helper(tls_output, JavaThread::vthread_offset(),
1044                                !C->method()->changes_current_thread());
1045 }
1046 
1047 //------------------------------make_string_method_node------------------------
1048 // Helper method for String intrinsic functions. This version is called with
1049 // str1 and str2 pointing to byte[] nodes containing Latin1 or UTF16 encoded
1050 // characters (depending on 'is_byte'). cnt1 and cnt2 are pointing to Int nodes
1051 // containing the lengths of str1 and str2.
1052 Node* LibraryCallKit::make_string_method_node(int opcode, Node* str1_start, Node* cnt1, Node* str2_start, Node* cnt2, StrIntrinsicNode::ArgEnc ae) {
1053   Node* result = nullptr;
1054   switch (opcode) {
1055   case Op_StrIndexOf:
1056     result = new StrIndexOfNode(control(), memory(TypeAryPtr::BYTES),
1057                                 str1_start, cnt1, str2_start, cnt2, ae);
1058     break;
1059   case Op_StrComp:
1060     result = new StrCompNode(control(), memory(TypeAryPtr::BYTES),
1061                              str1_start, cnt1, str2_start, cnt2, ae);
1062     break;
1063   case Op_StrEquals:
1064     // We already know that cnt1 == cnt2 here (checked in 'inline_string_equals').
1065     // Use the constant length if there is one because optimized match rule may exist.
1066     result = new StrEqualsNode(control(), memory(TypeAryPtr::BYTES),
1067                                str1_start, str2_start, cnt2->is_Con() ? cnt2 : cnt1, ae);
1068     break;
1069   default:
1070     ShouldNotReachHere();
1071     return nullptr;
1072   }
1073 
1074   // All these intrinsics have checks.
1075   C->set_has_split_ifs(true); // Has chance for split-if optimization
1076   clear_upper_avx();
1077 
1078   return _gvn.transform(result);
1079 }
1080 
1081 //------------------------------inline_string_compareTo------------------------
1082 bool LibraryCallKit::inline_string_compareTo(StrIntrinsicNode::ArgEnc ae) {
1083   Node* arg1 = argument(0);
1084   Node* arg2 = argument(1);
1085 
1086   arg1 = must_be_not_null(arg1, true);
1087   arg2 = must_be_not_null(arg2, true);
1088 
1089   // Get start addr and length of first argument
1090   Node* arg1_start  = array_element_address(arg1, intcon(0), T_BYTE);
1091   Node* arg1_cnt    = load_array_length(arg1);
1092 
1093   // Get start addr and length of second argument
1094   Node* arg2_start  = array_element_address(arg2, intcon(0), T_BYTE);
1095   Node* arg2_cnt    = load_array_length(arg2);
1096 
1097   Node* result = make_string_method_node(Op_StrComp, arg1_start, arg1_cnt, arg2_start, arg2_cnt, ae);
1098   set_result(result);
1099   return true;
1100 }
1101 
1102 //------------------------------inline_string_equals------------------------
1103 bool LibraryCallKit::inline_string_equals(StrIntrinsicNode::ArgEnc ae) {
1104   Node* arg1 = argument(0);
1105   Node* arg2 = argument(1);
1106 
1107   // paths (plus control) merge
1108   RegionNode* region = new RegionNode(3);
1109   Node* phi = new PhiNode(region, TypeInt::BOOL);
1110 
1111   if (!stopped()) {
1112 
1113     arg1 = must_be_not_null(arg1, true);
1114     arg2 = must_be_not_null(arg2, true);
1115 
1116     // Get start addr and length of first argument
1117     Node* arg1_start  = array_element_address(arg1, intcon(0), T_BYTE);
1118     Node* arg1_cnt    = load_array_length(arg1);
1119 
1120     // Get start addr and length of second argument
1121     Node* arg2_start  = array_element_address(arg2, intcon(0), T_BYTE);
1122     Node* arg2_cnt    = load_array_length(arg2);
1123 
1124     // Check for arg1_cnt != arg2_cnt
1125     Node* cmp = _gvn.transform(new CmpINode(arg1_cnt, arg2_cnt));
1126     Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::ne));
1127     Node* if_ne = generate_slow_guard(bol, nullptr);
1128     if (if_ne != nullptr) {
1129       phi->init_req(2, intcon(0));
1130       region->init_req(2, if_ne);
1131     }
1132 
1133     // Check for count == 0 is done by assembler code for StrEquals.
1134 
1135     if (!stopped()) {
1136       Node* equals = make_string_method_node(Op_StrEquals, arg1_start, arg1_cnt, arg2_start, arg2_cnt, ae);
1137       phi->init_req(1, equals);
1138       region->init_req(1, control());
1139     }
1140   }
1141 
1142   // post merge
1143   set_control(_gvn.transform(region));
1144   record_for_igvn(region);
1145 
1146   set_result(_gvn.transform(phi));
1147   return true;
1148 }
1149 
1150 //------------------------------inline_array_equals----------------------------
1151 bool LibraryCallKit::inline_array_equals(StrIntrinsicNode::ArgEnc ae) {
1152   assert(ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::LL, "unsupported array types");
1153   Node* arg1 = argument(0);
1154   Node* arg2 = argument(1);
1155 
1156   const TypeAryPtr* mtype = (ae == StrIntrinsicNode::UU) ? TypeAryPtr::CHARS : TypeAryPtr::BYTES;
1157   set_result(_gvn.transform(new AryEqNode(control(), memory(mtype), arg1, arg2, ae)));
1158   clear_upper_avx();
1159 
1160   return true;
1161 }
1162 
1163 
1164 //------------------------------inline_countPositives------------------------------
1165 // int java.lang.StringCoding#countPositives0(byte[] ba, int off, int len)
1166 bool LibraryCallKit::inline_countPositives() {
1167   assert(callee()->signature()->size() == 3, "countPositives has 3 parameters");
1168   // no receiver since it is static method
1169   Node* ba         = argument(0);
1170   Node* offset     = argument(1);
1171   Node* len        = argument(2);
1172 
1173   ba = must_be_not_null(ba, true);
1174   RegionNode* bailout = create_bailout();
1175   generate_string_range_check(ba, offset, len, false, bailout);
1176   if (check_bailout(bailout)) {
1177     return true;
1178   }
1179 
1180   Node* ba_start = array_element_address(ba, offset, T_BYTE);
1181   Node* result = new CountPositivesNode(control(), memory(TypeAryPtr::BYTES), ba_start, len);
1182   set_result(_gvn.transform(result));
1183   clear_upper_avx();
1184   return true;
1185 }
1186 
1187 bool LibraryCallKit::inline_preconditions_checkIndex(BasicType bt) {
1188   Node* index = argument(0);
1189   Node* length = bt == T_INT ? argument(1) : argument(2);
1190   if (too_many_traps(Deoptimization::Reason_intrinsic) || too_many_traps(Deoptimization::Reason_range_check)) {
1191     return false;
1192   }
1193 
1194   // check that length is positive
1195   Node* len_pos_cmp = _gvn.transform(CmpNode::make(length, integercon(0, bt), bt));
1196   Node* len_pos_bol = _gvn.transform(new BoolNode(len_pos_cmp, BoolTest::ge));
1197 
1198   {
1199     BuildCutout unless(this, len_pos_bol, PROB_MAX);
1200     uncommon_trap(Deoptimization::Reason_intrinsic,
1201                   Deoptimization::Action_make_not_entrant);
1202   }
1203 
1204   if (stopped()) {
1205     // Length is known to be always negative during compilation and the IR graph so far constructed is good so return success
1206     return true;
1207   }
1208 
1209   // length is now known positive, add a cast node to make this explicit
1210   jlong upper_bound = _gvn.type(length)->is_integer(bt)->hi_as_long();
1211   Node* casted_length = ConstraintCastNode::make_cast_for_basic_type(
1212       control(), length, TypeInteger::make(0, upper_bound, Type::WidenMax, bt),
1213       ConstraintCastNode::DependencyType::FloatingNarrowing, bt);
1214   casted_length = _gvn.transform(casted_length);
1215   replace_in_map(length, casted_length);
1216   length = casted_length;
1217 
1218   // Use an unsigned comparison for the range check itself
1219   Node* rc_cmp = _gvn.transform(CmpNode::make(index, length, bt, true));
1220   BoolTest::mask btest = BoolTest::lt;
1221   Node* rc_bool = _gvn.transform(new BoolNode(rc_cmp, btest));
1222   RangeCheckNode* rc = new RangeCheckNode(control(), rc_bool, PROB_MAX, COUNT_UNKNOWN);
1223   _gvn.set_type(rc, rc->Value(&_gvn));
1224   if (!rc_bool->is_Con()) {
1225     record_for_igvn(rc);
1226   }
1227   set_control(_gvn.transform(new IfTrueNode(rc)));
1228   {
1229     PreserveJVMState pjvms(this);
1230     set_control(_gvn.transform(new IfFalseNode(rc)));
1231     uncommon_trap(Deoptimization::Reason_range_check,
1232                   Deoptimization::Action_make_not_entrant);
1233   }
1234 
1235   if (stopped()) {
1236     // Range check is known to always fail during compilation and the IR graph so far constructed is good so return success
1237     return true;
1238   }
1239 
1240   // index is now known to be >= 0 and < length, cast it
1241   Node* result = ConstraintCastNode::make_cast_for_basic_type(
1242       control(), index, TypeInteger::make(0, upper_bound, Type::WidenMax, bt),
1243       ConstraintCastNode::DependencyType::FloatingNarrowing, bt);
1244   result = _gvn.transform(result);
1245   set_result(result);
1246   replace_in_map(index, result);
1247   return true;
1248 }
1249 
1250 //------------------------------inline_string_indexOf------------------------
1251 bool LibraryCallKit::inline_string_indexOf(StrIntrinsicNode::ArgEnc ae) {
1252   if (!Matcher::match_rule_supported(Op_StrIndexOf)) {
1253     return false;
1254   }
1255   Node* src = argument(0);
1256   Node* tgt = argument(1);
1257 
1258   // Make the merge point
1259   RegionNode* result_rgn = new RegionNode(4);
1260   Node*       result_phi = new PhiNode(result_rgn, TypeInt::INT);
1261 
1262   src = must_be_not_null(src, true);
1263   tgt = must_be_not_null(tgt, true);
1264 
1265   // Get start addr and length of source string
1266   Node* src_start = array_element_address(src, intcon(0), T_BYTE);
1267   Node* src_count = load_array_length(src);
1268 
1269   // Get start addr and length of substring
1270   Node* tgt_start = array_element_address(tgt, intcon(0), T_BYTE);
1271   Node* tgt_count = load_array_length(tgt);
1272 
1273   Node* result = nullptr;
1274   bool call_opt_stub = (StubRoutines::_string_indexof_array[ae] != nullptr);
1275 
1276   if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
1277     // Divide src size by 2 if String is UTF16 encoded
1278     src_count = _gvn.transform(new RShiftINode(src_count, intcon(1)));
1279   }
1280   if (ae == StrIntrinsicNode::UU) {
1281     // Divide substring size by 2 if String is UTF16 encoded
1282     tgt_count = _gvn.transform(new RShiftINode(tgt_count, intcon(1)));
1283   }
1284 
1285   if (call_opt_stub) {
1286     Node* call = make_runtime_call(RC_LEAF, OptoRuntime::string_IndexOf_Type(),
1287                                    StubRoutines::_string_indexof_array[ae],
1288                                    "stringIndexOf", TypePtr::BOTTOM, src_start,
1289                                    src_count, tgt_start, tgt_count);
1290     result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
1291   } else {
1292     result = make_indexOf_node(src_start, src_count, tgt_start, tgt_count,
1293                                result_rgn, result_phi, ae);
1294   }
1295   if (result != nullptr) {
1296     result_phi->init_req(3, result);
1297     result_rgn->init_req(3, control());
1298   }
1299   set_control(_gvn.transform(result_rgn));
1300   record_for_igvn(result_rgn);
1301   set_result(_gvn.transform(result_phi));
1302 
1303   return true;
1304 }
1305 
1306 //-----------------------------inline_string_indexOfI-----------------------
1307 bool LibraryCallKit::inline_string_indexOfI(StrIntrinsicNode::ArgEnc ae) {
1308   if (!Matcher::match_rule_supported(Op_StrIndexOf)) {
1309     return false;
1310   }
1311 
1312   assert(callee()->signature()->size() == 5, "String.indexOf() has 5 arguments");
1313   Node* src         = argument(0); // byte[]
1314   Node* src_count   = argument(1); // char count
1315   Node* tgt         = argument(2); // byte[]
1316   Node* tgt_count   = argument(3); // char count
1317   Node* from_index  = argument(4); // char index
1318 
1319   src = must_be_not_null(src, true);
1320   tgt = must_be_not_null(tgt, true);
1321 
1322   // Multiply byte array index by 2 if String is UTF16 encoded
1323   Node* src_offset = (ae == StrIntrinsicNode::LL) ? from_index : _gvn.transform(new LShiftINode(from_index, intcon(1)));
1324   src_count = _gvn.transform(new SubINode(src_count, from_index));
1325   Node* src_start = array_element_address(src, src_offset, T_BYTE);
1326   Node* tgt_start = array_element_address(tgt, intcon(0), T_BYTE);
1327 
1328   // Range checks
1329   RegionNode* bailout = create_bailout();
1330   generate_string_range_check(src, src_offset, src_count, ae != StrIntrinsicNode::LL, bailout);
1331   generate_string_range_check(tgt, intcon(0), tgt_count, ae == StrIntrinsicNode::UU, bailout);
1332   if (check_bailout(bailout)) {
1333     return true;
1334   }
1335 
1336   RegionNode* region = new RegionNode(5);
1337   Node* phi = new PhiNode(region, TypeInt::INT);
1338   Node* result = nullptr;
1339 
1340   bool call_opt_stub = (StubRoutines::_string_indexof_array[ae] != nullptr);
1341 
1342   if (call_opt_stub) {
1343     Node* call = make_runtime_call(RC_LEAF, OptoRuntime::string_IndexOf_Type(),
1344                                    StubRoutines::_string_indexof_array[ae],
1345                                    "stringIndexOf", TypePtr::BOTTOM, src_start,
1346                                    src_count, tgt_start, tgt_count);
1347     result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
1348   } else {
1349     result = make_indexOf_node(src_start, src_count, tgt_start, tgt_count,
1350                                region, phi, ae);
1351   }
1352   if (result != nullptr) {
1353     // The result is index relative to from_index if substring was found, -1 otherwise.
1354     // Generate code which will fold into cmove.
1355     Node* cmp = _gvn.transform(new CmpINode(result, intcon(0)));
1356     Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::lt));
1357 
1358     Node* if_lt = generate_slow_guard(bol, nullptr);
1359     if (if_lt != nullptr) {
1360       // result == -1
1361       phi->init_req(3, result);
1362       region->init_req(3, if_lt);
1363     }
1364     if (!stopped()) {
1365       result = _gvn.transform(new AddINode(result, from_index));
1366       phi->init_req(4, result);
1367       region->init_req(4, control());
1368     }
1369   }
1370 
1371   set_control(_gvn.transform(region));
1372   record_for_igvn(region);
1373   set_result(_gvn.transform(phi));
1374   clear_upper_avx();
1375 
1376   return true;
1377 }
1378 
1379 // Create StrIndexOfNode with fast path checks
1380 Node* LibraryCallKit::make_indexOf_node(Node* src_start, Node* src_count, Node* tgt_start, Node* tgt_count,
1381                                         RegionNode* region, Node* phi, StrIntrinsicNode::ArgEnc ae) {
1382   // Check for substr count > string count
1383   Node* cmp = _gvn.transform(new CmpINode(tgt_count, src_count));
1384   Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::gt));
1385   Node* if_gt = generate_slow_guard(bol, nullptr);
1386   if (if_gt != nullptr) {
1387     phi->init_req(1, intcon(-1));
1388     region->init_req(1, if_gt);
1389   }
1390   if (!stopped()) {
1391     // Check for substr count == 0
1392     cmp = _gvn.transform(new CmpINode(tgt_count, intcon(0)));
1393     bol = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
1394     Node* if_zero = generate_slow_guard(bol, nullptr);
1395     if (if_zero != nullptr) {
1396       phi->init_req(2, intcon(0));
1397       region->init_req(2, if_zero);
1398     }
1399   }
1400   if (!stopped()) {
1401     return make_string_method_node(Op_StrIndexOf, src_start, src_count, tgt_start, tgt_count, ae);
1402   }
1403   return nullptr;
1404 }
1405 
1406 //-----------------------------inline_string_indexOfChar-----------------------
1407 bool LibraryCallKit::inline_string_indexOfChar(StrIntrinsicNode::ArgEnc ae) {
1408   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1409     return false;
1410   }
1411   if (!Matcher::match_rule_supported(Op_StrIndexOfChar)) {
1412     return false;
1413   }
1414   assert(callee()->signature()->size() == 4, "String.indexOfChar() has 4 arguments");
1415   Node* src         = argument(0); // byte[]
1416   Node* int_ch      = argument(1);
1417   Node* from_index  = argument(2);
1418   Node* max         = argument(3);
1419 
1420   src = must_be_not_null(src, true);
1421 
1422   Node* src_offset = ae == StrIntrinsicNode::L ? from_index : _gvn.transform(new LShiftINode(from_index, intcon(1)));
1423   Node* src_start = array_element_address(src, src_offset, T_BYTE);
1424   Node* src_count = _gvn.transform(new SubINode(max, from_index));
1425 
1426   // Range checks
1427   RegionNode* bailout = create_bailout();
1428   generate_string_range_check(src, src_offset, src_count, ae == StrIntrinsicNode::U, bailout);
1429   if (check_bailout(bailout)) {
1430     return true;
1431   }
1432 
1433   // Check for int_ch >= 0
1434   Node* int_ch_cmp = _gvn.transform(new CmpINode(int_ch, intcon(0)));
1435   Node* int_ch_bol = _gvn.transform(new BoolNode(int_ch_cmp, BoolTest::ge));
1436   {
1437     BuildCutout unless(this, int_ch_bol, PROB_MAX);
1438     uncommon_trap(Deoptimization::Reason_intrinsic,
1439                   Deoptimization::Action_maybe_recompile);
1440   }
1441   if (stopped()) {
1442     return true;
1443   }
1444 
1445   RegionNode* region = new RegionNode(3);
1446   Node* phi = new PhiNode(region, TypeInt::INT);
1447 
1448   Node* result = new StrIndexOfCharNode(control(), memory(TypeAryPtr::BYTES), src_start, src_count, int_ch, ae);
1449   C->set_has_split_ifs(true); // Has chance for split-if optimization
1450   _gvn.transform(result);
1451 
1452   Node* cmp = _gvn.transform(new CmpINode(result, intcon(0)));
1453   Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::lt));
1454 
1455   Node* if_lt = generate_slow_guard(bol, nullptr);
1456   if (if_lt != nullptr) {
1457     // result == -1
1458     phi->init_req(2, result);
1459     region->init_req(2, if_lt);
1460   }
1461   if (!stopped()) {
1462     result = _gvn.transform(new AddINode(result, from_index));
1463     phi->init_req(1, result);
1464     region->init_req(1, control());
1465   }
1466   set_control(_gvn.transform(region));
1467   record_for_igvn(region);
1468   set_result(_gvn.transform(phi));
1469   clear_upper_avx();
1470 
1471   return true;
1472 }
1473 //---------------------------inline_string_copy---------------------
1474 // compressIt == true --> generate a compressed copy operation (compress char[]/byte[] to byte[])
1475 //   int StringUTF16.compress0(char[] src, int srcOff, byte[] dst, int dstOff, int len)
1476 //   int StringUTF16.compress0(byte[] src, int srcOff, byte[] dst, int dstOff, int len)
1477 // compressIt == false --> generate an inflated copy operation (inflate byte[] to char[]/byte[])
1478 //   void StringLatin1.inflate0(byte[] src, int srcOff, char[] dst, int dstOff, int len)
1479 //   void StringLatin1.inflate0(byte[] src, int srcOff, byte[] dst, int dstOff, int len)
1480 bool LibraryCallKit::inline_string_copy(bool compress) {
1481   int nargs = 5;  // 2 oops, 3 ints
1482   assert(callee()->signature()->size() == nargs, "string copy has 5 arguments");
1483 
1484   Node* src         = argument(0);
1485   Node* src_offset  = argument(1);
1486   Node* dst         = argument(2);
1487   Node* dst_offset  = argument(3);
1488   Node* length      = argument(4);
1489 
1490   // Check for allocation before we add nodes that would confuse
1491   // tightly_coupled_allocation()
1492   AllocateArrayNode* alloc = tightly_coupled_allocation(dst);
1493 
1494   // Figure out the size and type of the elements we will be copying.
1495   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
1496   const TypeAryPtr* dst_type = dst->Value(&_gvn)->isa_aryptr();
1497   if (src_type == nullptr || dst_type == nullptr) {
1498     return false;
1499   }
1500   BasicType src_elem = src_type->elem()->array_element_basic_type();
1501   BasicType dst_elem = dst_type->elem()->array_element_basic_type();
1502   assert((compress && dst_elem == T_BYTE && (src_elem == T_BYTE || src_elem == T_CHAR)) ||
1503          (!compress && src_elem == T_BYTE && (dst_elem == T_BYTE || dst_elem == T_CHAR)),
1504          "Unsupported array types for inline_string_copy");
1505 
1506   src = must_be_not_null(src, true);
1507   dst = must_be_not_null(dst, true);
1508 
1509   // Convert char[] offsets to byte[] offsets
1510   bool convert_src = (compress && src_elem == T_BYTE);
1511   bool convert_dst = (!compress && dst_elem == T_BYTE);
1512   if (convert_src) {
1513     src_offset = _gvn.transform(new LShiftINode(src_offset, intcon(1)));
1514   } else if (convert_dst) {
1515     dst_offset = _gvn.transform(new LShiftINode(dst_offset, intcon(1)));
1516   }
1517 
1518   // Range checks
1519   RegionNode* bailout = create_bailout();
1520   generate_string_range_check(src, src_offset, length, convert_src, bailout);
1521   generate_string_range_check(dst, dst_offset, length, convert_dst, bailout);
1522   if (check_bailout(bailout)) {
1523     return true;
1524   }
1525 
1526   Node* src_start = array_element_address(src, src_offset, src_elem);
1527   Node* dst_start = array_element_address(dst, dst_offset, dst_elem);
1528   // 'src_start' points to src array + scaled offset
1529   // 'dst_start' points to dst array + scaled offset
1530   Node* count = nullptr;
1531   if (compress) {
1532     count = compress_string(src_start, TypeAryPtr::get_array_body_type(src_elem), dst_start, length);
1533   } else {
1534     inflate_string(src_start, dst_start, TypeAryPtr::get_array_body_type(dst_elem), length);
1535   }
1536 
1537   if (alloc != nullptr) {
1538     if (alloc->maybe_set_complete(&_gvn)) {
1539       // "You break it, you buy it."
1540       InitializeNode* init = alloc->initialization();
1541       assert(init->is_complete(), "we just did this");
1542       init->set_complete_with_arraycopy();
1543       assert(dst->is_CheckCastPP(), "sanity");
1544       assert(dst->in(0)->in(0) == init, "dest pinned");
1545     }
1546     // Do not let stores that initialize this object be reordered with
1547     // a subsequent store that would make this object accessible by
1548     // other threads.
1549     // Record what AllocateNode this StoreStore protects so that
1550     // escape analysis can go from the MemBarStoreStoreNode to the
1551     // AllocateNode and eliminate the MemBarStoreStoreNode if possible
1552     // based on the escape status of the AllocateNode.
1553     insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
1554   }
1555   if (compress) {
1556     set_result(_gvn.transform(count));
1557   }
1558   clear_upper_avx();
1559 
1560   return true;
1561 }
1562 
1563 #ifdef _LP64
1564 #define XTOP ,top() /*additional argument*/
1565 #else  //_LP64
1566 #define XTOP        /*no additional argument*/
1567 #endif //_LP64
1568 
1569 //------------------------inline_string_toBytesU--------------------------
1570 // public static byte[] StringUTF16.toBytes0(char[] value, int off, int len)
1571 bool LibraryCallKit::inline_string_toBytesU() {
1572   // Get the arguments.
1573   assert(callee()->signature()->size() == 3, "character array encoder requires 3 arguments");
1574   Node* value     = argument(0);
1575   Node* offset    = argument(1);
1576   Node* length    = argument(2);
1577 
1578   Node* newcopy = nullptr;
1579 
1580   // Set the original stack and the reexecute bit for the interpreter to reexecute
1581   // the bytecode that invokes StringUTF16.toBytes0() if deoptimization happens.
1582   { PreserveReexecuteState preexecs(this);
1583     jvms()->set_should_reexecute(true);
1584 
1585     value = must_be_not_null(value, true);
1586     RegionNode* bailout = create_bailout();
1587     generate_negative_guard(offset, bailout, nullptr, true);
1588     generate_negative_guard(length, bailout, nullptr, true);
1589     generate_limit_guard(offset, length, load_array_length(value), bailout, true);
1590     // Make sure that resulting byte[] length does not overflow Integer.MAX_VALUE
1591     generate_limit_guard(length, intcon(0), intcon(max_jint/2), bailout, true);
1592     if (check_bailout(bailout)) {
1593       return true;
1594     }
1595 
1596     Node* size = _gvn.transform(new LShiftINode(length, intcon(1)));
1597     Node* klass_node = makecon(TypeKlassPtr::make(ciTypeArrayKlass::make(T_BYTE)));
1598     newcopy = new_array(klass_node, size, 0);  // no arguments to push
1599     AllocateArrayNode* alloc = tightly_coupled_allocation(newcopy);
1600     guarantee(alloc != nullptr, "created above");
1601 
1602     // Calculate starting addresses.
1603     Node* src_start = array_element_address(value, offset, T_CHAR);
1604     Node* dst_start = basic_plus_adr(newcopy, arrayOopDesc::base_offset_in_bytes(T_BYTE));
1605 
1606     // Check if dst array address is aligned to HeapWordSize
1607     bool aligned = (arrayOopDesc::base_offset_in_bytes(T_BYTE) % HeapWordSize == 0);
1608     // If true, then check if src array address is aligned to HeapWordSize
1609     if (aligned) {
1610       const TypeInt* toffset = gvn().type(offset)->is_int();
1611       aligned = toffset->is_con() && ((arrayOopDesc::base_offset_in_bytes(T_CHAR) +
1612                                        toffset->get_con() * type2aelembytes(T_CHAR)) % HeapWordSize == 0);
1613     }
1614 
1615     // Figure out which arraycopy runtime method to call (disjoint, uninitialized).
1616     const char* copyfunc_name = "arraycopy";
1617     address     copyfunc_addr = StubRoutines::select_arraycopy_function(T_CHAR, aligned, true, copyfunc_name, true);
1618     Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
1619                       OptoRuntime::fast_arraycopy_Type(),
1620                       copyfunc_addr, copyfunc_name, TypeRawPtr::BOTTOM,
1621                       src_start, dst_start, ConvI2X(length) XTOP);
1622     // Do not let reads from the cloned object float above the arraycopy.
1623     if (alloc->maybe_set_complete(&_gvn)) {
1624       // "You break it, you buy it."
1625       InitializeNode* init = alloc->initialization();
1626       assert(init->is_complete(), "we just did this");
1627       init->set_complete_with_arraycopy();
1628       assert(newcopy->is_CheckCastPP(), "sanity");
1629       assert(newcopy->in(0)->in(0) == init, "dest pinned");
1630     }
1631     // Do not let stores that initialize this object be reordered with
1632     // a subsequent store that would make this object accessible by
1633     // other threads.
1634     // Record what AllocateNode this StoreStore protects so that
1635     // escape analysis can go from the MemBarStoreStoreNode to the
1636     // AllocateNode and eliminate the MemBarStoreStoreNode if possible
1637     // based on the escape status of the AllocateNode.
1638     insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
1639   } // original reexecute is set back here
1640 
1641   C->set_has_split_ifs(true); // Has chance for split-if optimization
1642   if (!stopped()) {
1643     set_result(newcopy);
1644   }
1645   clear_upper_avx();
1646 
1647   return true;
1648 }
1649 
1650 //------------------------inline_string_getCharsU--------------------------
1651 // public void StringUTF16.getChars0(byte[] src, int srcBegin, int srcEnd, char dst[], int dstBegin)
1652 bool LibraryCallKit::inline_string_getCharsU() {
1653   assert(callee()->signature()->size() == 5, "StringUTF16.getChars0() has 5 arguments");
1654   // Get the arguments.
1655   Node* src       = argument(0);
1656   Node* src_begin = argument(1);
1657   Node* src_end   = argument(2); // exclusive offset (i < src_end)
1658   Node* dst       = argument(3);
1659   Node* dst_begin = argument(4);
1660 
1661   // Check for allocation before we add nodes that would confuse
1662   // tightly_coupled_allocation()
1663   AllocateArrayNode* alloc = tightly_coupled_allocation(dst);
1664 
1665   // Check if a null path was taken unconditionally.
1666   src = must_be_not_null(src, true);
1667   dst = must_be_not_null(dst, true);
1668   if (stopped()) {
1669     return true;
1670   }
1671 
1672   // Get length and convert char[] offset to byte[] offset
1673   Node* length = _gvn.transform(new SubINode(src_end, src_begin));
1674   src_begin = _gvn.transform(new LShiftINode(src_begin, intcon(1)));
1675 
1676   // Range checks
1677   RegionNode* bailout = create_bailout();
1678   generate_string_range_check(src, src_begin, length, true, bailout);
1679   generate_string_range_check(dst, dst_begin, length, false, bailout);
1680   if (check_bailout(bailout)) {
1681     return true;
1682   }
1683 
1684   // Calculate starting addresses.
1685   Node* src_start = array_element_address(src, src_begin, T_BYTE);
1686   Node* dst_start = array_element_address(dst, dst_begin, T_CHAR);
1687 
1688   // Check if array addresses are aligned to HeapWordSize
1689   const TypeInt* tsrc = gvn().type(src_begin)->is_int();
1690   const TypeInt* tdst = gvn().type(dst_begin)->is_int();
1691   bool aligned = tsrc->is_con() && ((arrayOopDesc::base_offset_in_bytes(T_BYTE) + tsrc->get_con() * type2aelembytes(T_BYTE)) % HeapWordSize == 0) &&
1692                  tdst->is_con() && ((arrayOopDesc::base_offset_in_bytes(T_CHAR) + tdst->get_con() * type2aelembytes(T_CHAR)) % HeapWordSize == 0);
1693 
1694   // Figure out which arraycopy runtime method to call (disjoint, uninitialized).
1695   const char* copyfunc_name = "arraycopy";
1696   address     copyfunc_addr = StubRoutines::select_arraycopy_function(T_CHAR, aligned, true, copyfunc_name, true);
1697   Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
1698                     OptoRuntime::fast_arraycopy_Type(),
1699                     copyfunc_addr, copyfunc_name, TypeRawPtr::BOTTOM,
1700                     src_start, dst_start, ConvI2X(length) XTOP);
1701   // Do not let reads from the cloned object float above the arraycopy.
1702   if (alloc != nullptr) {
1703     if (alloc->maybe_set_complete(&_gvn)) {
1704       // "You break it, you buy it."
1705       InitializeNode* init = alloc->initialization();
1706       assert(init->is_complete(), "we just did this");
1707       init->set_complete_with_arraycopy();
1708       assert(dst->is_CheckCastPP(), "sanity");
1709       assert(dst->in(0)->in(0) == init, "dest pinned");
1710     }
1711     // Do not let stores that initialize this object be reordered with
1712     // a subsequent store that would make this object accessible by
1713     // other threads.
1714     // Record what AllocateNode this StoreStore protects so that
1715     // escape analysis can go from the MemBarStoreStoreNode to the
1716     // AllocateNode and eliminate the MemBarStoreStoreNode if possible
1717     // based on the escape status of the AllocateNode.
1718     insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
1719   } else {
1720     insert_mem_bar(Op_MemBarCPUOrder);
1721   }
1722 
1723   C->set_has_split_ifs(true); // Has chance for split-if optimization
1724   return true;
1725 }
1726 
1727 //----------------------inline_string_char_access----------------------------
1728 // Store/Load char to/from byte[] array.
1729 // static void StringUTF16.putChar(byte[] val, int index, int c)
1730 // static char StringUTF16.getChar(byte[] val, int index)
1731 bool LibraryCallKit::inline_string_char_access(bool is_store) {
1732   Node* ch;
1733   if (is_store) {
1734     assert(callee()->signature()->size() == 3, "StringUTF16.putChar() has 3 arguments");
1735     ch = argument(2);
1736   } else {
1737     assert(callee()->signature()->size() == 2, "StringUTF16.getChar() has 2 arguments");
1738     ch = nullptr;
1739   }
1740   Node* value  = argument(0);
1741   Node* index  = argument(1);
1742 
1743   // This intrinsic accesses byte[] array as char[] array. Computing the offsets
1744   // correctly requires matched array shapes.
1745   assert (arrayOopDesc::base_offset_in_bytes(T_CHAR) == arrayOopDesc::base_offset_in_bytes(T_BYTE),
1746           "sanity: byte[] and char[] bases agree");
1747   assert (type2aelembytes(T_CHAR) == type2aelembytes(T_BYTE)*2,
1748           "sanity: byte[] and char[] scales agree");
1749 
1750   // Bail when getChar over constants is requested: constant folding would
1751   // reject folding mismatched char access over byte[]. A normal inlining for getChar
1752   // Java method would constant fold nicely instead.
1753   if (!is_store && value->is_Con() && index->is_Con()) {
1754     return false;
1755   }
1756 
1757   // Save state and restore on bailout
1758   SavedState old_state(this);
1759 
1760   value = must_be_not_null(value, true);
1761 
1762   Node* adr = array_element_address(value, index, T_CHAR);
1763   if (adr->is_top()) {
1764     return false;
1765   }
1766   old_state.discard();
1767   if (is_store) {
1768     access_store_at(value, adr, TypeAryPtr::BYTES, ch, TypeInt::CHAR, T_CHAR, IN_HEAP | MO_UNORDERED | C2_MISMATCHED);
1769   } else {
1770     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);
1771     set_result(ch);
1772   }
1773   return true;
1774 }
1775 
1776 
1777 //------------------------------inline_math-----------------------------------
1778 // public static double Math.abs(double)
1779 // public static double Math.sqrt(double)
1780 // public static double Math.log(double)
1781 // public static double Math.log10(double)
1782 // public static double Math.round(double)
1783 bool LibraryCallKit::inline_double_math(vmIntrinsics::ID id) {
1784   Node* arg = argument(0);
1785   Node* n = nullptr;
1786   switch (id) {
1787   case vmIntrinsics::_dabs:   n = new AbsDNode(                arg);  break;
1788   case vmIntrinsics::_dsqrt:
1789   case vmIntrinsics::_dsqrt_strict:
1790                               n = new SqrtDNode(C, control(),  arg);  break;
1791   case vmIntrinsics::_ceil:   n = RoundDoubleModeNode::make(_gvn, arg, RoundDoubleModeNode::rmode_ceil); break;
1792   case vmIntrinsics::_floor:  n = RoundDoubleModeNode::make(_gvn, arg, RoundDoubleModeNode::rmode_floor); break;
1793   case vmIntrinsics::_rint:   n = RoundDoubleModeNode::make(_gvn, arg, RoundDoubleModeNode::rmode_rint); break;
1794   case vmIntrinsics::_roundD: n = new RoundDNode(arg); break;
1795   case vmIntrinsics::_dcopySign: n = CopySignDNode::make(_gvn, arg, argument(2)); break;
1796   case vmIntrinsics::_dsignum: n = SignumDNode::make(_gvn, arg); break;
1797   default:  fatal_unexpected_iid(id);  break;
1798   }
1799   set_result(_gvn.transform(n));
1800   return true;
1801 }
1802 
1803 //------------------------------inline_math-----------------------------------
1804 // public static float Math.abs(float)
1805 // public static int Math.abs(int)
1806 // public static long Math.abs(long)
1807 bool LibraryCallKit::inline_math(vmIntrinsics::ID id) {
1808   Node* arg = argument(0);
1809   Node* n = nullptr;
1810   switch (id) {
1811   case vmIntrinsics::_fabs:   n = new AbsFNode(                arg);  break;
1812   case vmIntrinsics::_iabs:   n = new AbsINode(                arg);  break;
1813   case vmIntrinsics::_labs:   n = new AbsLNode(                arg);  break;
1814   case vmIntrinsics::_fcopySign: n = new CopySignFNode(arg, argument(1)); break;
1815   case vmIntrinsics::_fsignum: n = SignumFNode::make(_gvn, arg); break;
1816   case vmIntrinsics::_roundF: n = new RoundFNode(arg); break;
1817   default:  fatal_unexpected_iid(id);  break;
1818   }
1819   set_result(_gvn.transform(n));
1820   return true;
1821 }
1822 
1823 //------------------------------runtime_math-----------------------------
1824 bool LibraryCallKit::runtime_math(const TypeFunc* call_type, address funcAddr, const char* funcName) {
1825   assert(call_type == OptoRuntime::Math_DD_D_Type() || call_type == OptoRuntime::Math_D_D_Type(),
1826          "must be (DD)D or (D)D type");
1827 
1828   // Inputs
1829   Node* a = argument(0);
1830   Node* b = (call_type == OptoRuntime::Math_DD_D_Type()) ? argument(2) : nullptr;
1831 
1832   const TypePtr* no_memory_effects = nullptr;
1833   Node* trig = make_runtime_call(RC_LEAF | RC_PURE, call_type, funcAddr, funcName,
1834                                  no_memory_effects,
1835                                  a, top(), b, b ? top() : nullptr);
1836   Node* value = _gvn.transform(new ProjNode(trig, TypeFunc::Parms+0));
1837 #ifdef ASSERT
1838   Node* value_top = _gvn.transform(new ProjNode(trig, TypeFunc::Parms+1));
1839   assert(value_top == top(), "second value must be top");
1840 #endif
1841 
1842   set_result(value);
1843   return true;
1844 }
1845 
1846 //------------------------------inline_math_pow-----------------------------
1847 bool LibraryCallKit::inline_math_pow() {
1848   Node* base = argument(0);
1849   Node* exp = argument(2);
1850 
1851   CallNode* pow = new PowDNode(C, base, exp);
1852   set_predefined_input_for_runtime_call(pow);
1853   pow = _gvn.transform(pow)->as_CallLeafPure();
1854   set_predefined_output_for_runtime_call(pow);
1855   Node* result = _gvn.transform(new ProjNode(pow, TypeFunc::Parms + 0));
1856   record_for_igvn(pow);
1857   set_result(result);
1858   return true;
1859 }
1860 
1861 //------------------------------inline_math_native-----------------------------
1862 bool LibraryCallKit::inline_math_native(vmIntrinsics::ID id) {
1863   switch (id) {
1864   case vmIntrinsics::_dsin:
1865     return StubRoutines::dsin() != nullptr ?
1866       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dsin(), "dsin") :
1867       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dsin),   "SIN");
1868   case vmIntrinsics::_dcos:
1869     return StubRoutines::dcos() != nullptr ?
1870       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dcos(), "dcos") :
1871       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dcos),   "COS");
1872   case vmIntrinsics::_dtan:
1873     return StubRoutines::dtan() != nullptr ?
1874       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dtan(), "dtan") :
1875       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dtan), "TAN");
1876   case vmIntrinsics::_dsinh:
1877     return StubRoutines::dsinh() != nullptr ?
1878       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dsinh(), "dsinh") : false;
1879   case vmIntrinsics::_dtanh:
1880     return StubRoutines::dtanh() != nullptr ?
1881       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dtanh(), "dtanh") : false;
1882   case vmIntrinsics::_dcbrt:
1883     return StubRoutines::dcbrt() != nullptr ?
1884       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dcbrt(), "dcbrt") : false;
1885   case vmIntrinsics::_dexp:
1886     return StubRoutines::dexp() != nullptr ?
1887       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dexp(),  "dexp") :
1888       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dexp),  "EXP");
1889   case vmIntrinsics::_dlog:
1890     return StubRoutines::dlog() != nullptr ?
1891       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dlog(), "dlog") :
1892       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dlog),   "LOG");
1893   case vmIntrinsics::_dlog10:
1894     return StubRoutines::dlog10() != nullptr ?
1895       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dlog10(), "dlog10") :
1896       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dlog10), "LOG10");
1897 
1898   case vmIntrinsics::_roundD: return Matcher::match_rule_supported(Op_RoundD) ? inline_double_math(id) : false;
1899   case vmIntrinsics::_ceil:
1900   case vmIntrinsics::_floor:
1901   case vmIntrinsics::_rint:   return Matcher::match_rule_supported(Op_RoundDoubleMode) ? inline_double_math(id) : false;
1902 
1903   case vmIntrinsics::_dsqrt:
1904   case vmIntrinsics::_dsqrt_strict:
1905                               return Matcher::match_rule_supported(Op_SqrtD) ? inline_double_math(id) : false;
1906   case vmIntrinsics::_dabs:   return Matcher::has_match_rule(Op_AbsD)   ? inline_double_math(id) : false;
1907   case vmIntrinsics::_fabs:   return Matcher::match_rule_supported(Op_AbsF)   ? inline_math(id) : false;
1908   case vmIntrinsics::_iabs:   return Matcher::match_rule_supported(Op_AbsI)   ? inline_math(id) : false;
1909   case vmIntrinsics::_labs:   return Matcher::match_rule_supported(Op_AbsL)   ? inline_math(id) : false;
1910 
1911   case vmIntrinsics::_dpow:      return inline_math_pow();
1912   case vmIntrinsics::_dcopySign: return inline_double_math(id);
1913   case vmIntrinsics::_fcopySign: return inline_math(id);
1914   case vmIntrinsics::_dsignum: return Matcher::match_rule_supported(Op_SignumD) ? inline_double_math(id) : false;
1915   case vmIntrinsics::_fsignum: return Matcher::match_rule_supported(Op_SignumF) ? inline_math(id) : false;
1916   case vmIntrinsics::_roundF: return Matcher::match_rule_supported(Op_RoundF) ? inline_math(id) : false;
1917 
1918    // These intrinsics are not yet correctly implemented
1919   case vmIntrinsics::_datan2:
1920     return false;
1921 
1922   default:
1923     fatal_unexpected_iid(id);
1924     return false;
1925   }
1926 }
1927 
1928 //----------------------------inline_notify-----------------------------------*
1929 bool LibraryCallKit::inline_notify(vmIntrinsics::ID id) {
1930   const TypeFunc* ftype = OptoRuntime::monitor_notify_Type();
1931   address func;
1932   if (id == vmIntrinsics::_notify) {
1933     func = OptoRuntime::monitor_notify_Java();
1934   } else {
1935     func = OptoRuntime::monitor_notifyAll_Java();
1936   }
1937   Node* call = make_runtime_call(RC_NO_LEAF, ftype, func, nullptr, TypeRawPtr::BOTTOM, argument(0));
1938   make_slow_call_ex(call, env()->Throwable_klass(), false);
1939   return true;
1940 }
1941 
1942 
1943 //----------------------------inline_min_max-----------------------------------
1944 bool LibraryCallKit::inline_min_max(vmIntrinsics::ID id) {
1945   Node* a = nullptr;
1946   Node* b = nullptr;
1947   Node* n = nullptr;
1948   switch (id) {
1949     case vmIntrinsics::_min:
1950     case vmIntrinsics::_max:
1951     case vmIntrinsics::_minF:
1952     case vmIntrinsics::_maxF:
1953     case vmIntrinsics::_minF_strict:
1954     case vmIntrinsics::_maxF_strict:
1955     case vmIntrinsics::_min_strict:
1956     case vmIntrinsics::_max_strict:
1957       assert(callee()->signature()->size() == 2, "minF/maxF has 2 parameters of size 1 each.");
1958       a = argument(0);
1959       b = argument(1);
1960       break;
1961     case vmIntrinsics::_minD:
1962     case vmIntrinsics::_maxD:
1963     case vmIntrinsics::_minD_strict:
1964     case vmIntrinsics::_maxD_strict:
1965       assert(callee()->signature()->size() == 4, "minD/maxD has 2 parameters of size 2 each.");
1966       a = argument(0);
1967       b = argument(2);
1968       break;
1969     case vmIntrinsics::_minL:
1970     case vmIntrinsics::_maxL:
1971       assert(callee()->signature()->size() == 4, "minL/maxL has 2 parameters of size 2 each.");
1972       a = argument(0);
1973       b = argument(2);
1974       break;
1975     default:
1976       fatal_unexpected_iid(id);
1977       break;
1978   }
1979 
1980   switch (id) {
1981     case vmIntrinsics::_min:
1982     case vmIntrinsics::_min_strict:
1983       n = new MinINode(a, b);
1984       break;
1985     case vmIntrinsics::_max:
1986     case vmIntrinsics::_max_strict:
1987       n = new MaxINode(a, b);
1988       break;
1989     case vmIntrinsics::_minF:
1990     case vmIntrinsics::_minF_strict:
1991       n = new MinFNode(a, b);
1992       break;
1993     case vmIntrinsics::_maxF:
1994     case vmIntrinsics::_maxF_strict:
1995       n = new MaxFNode(a, b);
1996       break;
1997     case vmIntrinsics::_minD:
1998     case vmIntrinsics::_minD_strict:
1999       n = new MinDNode(a, b);
2000       break;
2001     case vmIntrinsics::_maxD:
2002     case vmIntrinsics::_maxD_strict:
2003       n = new MaxDNode(a, b);
2004       break;
2005     case vmIntrinsics::_minL:
2006       n = new MinLNode(_gvn.C, a, b);
2007       break;
2008     case vmIntrinsics::_maxL:
2009       n = new MaxLNode(_gvn.C, a, b);
2010       break;
2011     default:
2012       fatal_unexpected_iid(id);
2013       break;
2014   }
2015 
2016   set_result(_gvn.transform(n));
2017   return true;
2018 }
2019 
2020 bool LibraryCallKit::inline_math_mathExact(Node* math, Node* test) {
2021   if (builtin_throw_too_many_traps(Deoptimization::Reason_intrinsic,
2022                                    env()->ArithmeticException_instance())) {
2023     // It has been already too many times, but we cannot use builtin_throw (e.g. we care about backtraces),
2024     // so let's bail out intrinsic rather than risking deopting again.
2025     return false;
2026   }
2027 
2028   Node* bol = _gvn.transform( new BoolNode(test, BoolTest::overflow) );
2029   IfNode* check = create_and_map_if(control(), bol, PROB_UNLIKELY_MAG(3), COUNT_UNKNOWN);
2030   Node* fast_path = _gvn.transform( new IfFalseNode(check));
2031   Node* slow_path = _gvn.transform( new IfTrueNode(check) );
2032 
2033   {
2034     PreserveJVMState pjvms(this);
2035     PreserveReexecuteState preexecs(this);
2036     jvms()->set_should_reexecute(true);
2037 
2038     set_control(slow_path);
2039     set_i_o(i_o());
2040 
2041     builtin_throw(Deoptimization::Reason_intrinsic,
2042                   env()->ArithmeticException_instance(),
2043                   /*allow_too_many_traps*/ false);
2044   }
2045 
2046   set_control(fast_path);
2047   set_result(math);
2048   return true;
2049 }
2050 
2051 template <typename OverflowOp>
2052 bool LibraryCallKit::inline_math_overflow(Node* arg1, Node* arg2) {
2053   typedef typename OverflowOp::MathOp MathOp;
2054 
2055   MathOp* mathOp = new MathOp(arg1, arg2);
2056   Node* operation = _gvn.transform( mathOp );
2057   Node* ofcheck = _gvn.transform( new OverflowOp(arg1, arg2) );
2058   return inline_math_mathExact(operation, ofcheck);
2059 }
2060 
2061 bool LibraryCallKit::inline_math_addExactI(bool is_increment) {
2062   return inline_math_overflow<OverflowAddINode>(argument(0), is_increment ? intcon(1) : argument(1));
2063 }
2064 
2065 bool LibraryCallKit::inline_math_addExactL(bool is_increment) {
2066   return inline_math_overflow<OverflowAddLNode>(argument(0), is_increment ? longcon(1) : argument(2));
2067 }
2068 
2069 bool LibraryCallKit::inline_math_subtractExactI(bool is_decrement) {
2070   return inline_math_overflow<OverflowSubINode>(argument(0), is_decrement ? intcon(1) : argument(1));
2071 }
2072 
2073 bool LibraryCallKit::inline_math_subtractExactL(bool is_decrement) {
2074   return inline_math_overflow<OverflowSubLNode>(argument(0), is_decrement ? longcon(1) : argument(2));
2075 }
2076 
2077 bool LibraryCallKit::inline_math_negateExactI() {
2078   return inline_math_overflow<OverflowSubINode>(intcon(0), argument(0));
2079 }
2080 
2081 bool LibraryCallKit::inline_math_negateExactL() {
2082   return inline_math_overflow<OverflowSubLNode>(longcon(0), argument(0));
2083 }
2084 
2085 bool LibraryCallKit::inline_math_multiplyExactI() {
2086   return inline_math_overflow<OverflowMulINode>(argument(0), argument(1));
2087 }
2088 
2089 bool LibraryCallKit::inline_math_multiplyExactL() {
2090   return inline_math_overflow<OverflowMulLNode>(argument(0), argument(2));
2091 }
2092 
2093 bool LibraryCallKit::inline_math_multiplyHigh() {
2094   set_result(_gvn.transform(new MulHiLNode(argument(0), argument(2))));
2095   return true;
2096 }
2097 
2098 bool LibraryCallKit::inline_math_unsignedMultiplyHigh() {
2099   set_result(_gvn.transform(new UMulHiLNode(argument(0), argument(2))));
2100   return true;
2101 }
2102 
2103 inline int
2104 LibraryCallKit::classify_unsafe_addr(Node* &base, Node* &offset, BasicType type) {
2105   const TypePtr* base_type = TypePtr::NULL_PTR;
2106   if (base != nullptr)  base_type = _gvn.type(base)->isa_ptr();
2107   if (base_type == nullptr) {
2108     // Unknown type.
2109     return Type::AnyPtr;
2110   } else if (_gvn.type(base->uncast()) == TypePtr::NULL_PTR) {
2111     // Since this is a null+long form, we have to switch to a rawptr.
2112     base   = _gvn.transform(new CastX2PNode(offset));
2113     offset = MakeConX(0);
2114     return Type::RawPtr;
2115   } else if (base_type->base() == Type::RawPtr) {
2116     return Type::RawPtr;
2117   } else if (base_type->isa_oopptr()) {
2118     // Base is never null => always a heap address.
2119     if (!TypePtr::NULL_PTR->higher_equal(base_type)) {
2120       return Type::OopPtr;
2121     }
2122     // Offset is small => always a heap address.
2123     const TypeX* offset_type = _gvn.type(offset)->isa_intptr_t();
2124     if (offset_type != nullptr &&
2125         base_type->offset() == 0 &&     // (should always be?)
2126         offset_type->_lo >= 0 &&
2127         !MacroAssembler::needs_explicit_null_check(offset_type->_hi)) {
2128       return Type::OopPtr;
2129     } else if (type == T_OBJECT) {
2130       // off heap access to an oop doesn't make any sense. Has to be on
2131       // heap.
2132       return Type::OopPtr;
2133     }
2134     // Otherwise, it might either be oop+off or null+addr.
2135     return Type::AnyPtr;
2136   } else {
2137     // No information:
2138     return Type::AnyPtr;
2139   }
2140 }
2141 
2142 Node* LibraryCallKit::make_unsafe_address(Node*& base, Node* offset, BasicType type, bool can_cast) {
2143   Node* uncasted_base = base;
2144   int kind = classify_unsafe_addr(uncasted_base, offset, type);
2145   if (kind == Type::RawPtr) {
2146     return off_heap_plus_addr(uncasted_base, offset);
2147   } else if (kind == Type::AnyPtr) {
2148     assert(base == uncasted_base, "unexpected base change");
2149     if (can_cast) {
2150       if (!_gvn.type(base)->speculative_maybe_null() &&
2151           !too_many_traps(Deoptimization::Reason_speculate_null_check)) {
2152         // According to profiling, this access is always on
2153         // heap. Casting the base to not null and thus avoiding membars
2154         // around the access should allow better optimizations
2155         Node* null_ctl = top();
2156         base = null_check_oop(base, &null_ctl, true, true, true);
2157         assert(null_ctl->is_top(), "no null control here");
2158         return basic_plus_adr(base, offset);
2159       } else if (_gvn.type(base)->speculative_always_null() &&
2160                  !too_many_traps(Deoptimization::Reason_speculate_null_assert)) {
2161         // According to profiling, this access is always off
2162         // heap.
2163         base = null_assert(base);
2164         Node* raw_base = _gvn.transform(new CastX2PNode(offset));
2165         offset = MakeConX(0);
2166         return off_heap_plus_addr(raw_base, offset);
2167       }
2168     }
2169     // We don't know if it's an on heap or off heap access. Fall back
2170     // to raw memory access.
2171     Node* raw = _gvn.transform(new CheckCastPPNode(control(), base, TypeRawPtr::BOTTOM));
2172     return off_heap_plus_addr(raw, offset);
2173   } else {
2174     assert(base == uncasted_base, "unexpected base change");
2175     // We know it's an on heap access so base can't be null
2176     if (TypePtr::NULL_PTR->higher_equal(_gvn.type(base))) {
2177       base = must_be_not_null(base, true);
2178     }
2179     return basic_plus_adr(base, offset);
2180   }
2181 }
2182 
2183 //--------------------------inline_number_methods-----------------------------
2184 // inline int     Integer.numberOfLeadingZeros(int)
2185 // inline int        Long.numberOfLeadingZeros(long)
2186 //
2187 // inline int     Integer.numberOfTrailingZeros(int)
2188 // inline int        Long.numberOfTrailingZeros(long)
2189 //
2190 // inline int     Integer.bitCount(int)
2191 // inline int        Long.bitCount(long)
2192 //
2193 // inline char  Character.reverseBytes(char)
2194 // inline short     Short.reverseBytes(short)
2195 // inline int     Integer.reverseBytes(int)
2196 // inline long       Long.reverseBytes(long)
2197 bool LibraryCallKit::inline_number_methods(vmIntrinsics::ID id) {
2198   Node* arg = argument(0);
2199   Node* n = nullptr;
2200   switch (id) {
2201   case vmIntrinsics::_numberOfLeadingZeros_i:   n = new CountLeadingZerosINode( arg); break;
2202   case vmIntrinsics::_numberOfLeadingZeros_l:   n = new CountLeadingZerosLNode( arg); break;
2203   case vmIntrinsics::_numberOfTrailingZeros_i:  n = new CountTrailingZerosINode(arg); break;
2204   case vmIntrinsics::_numberOfTrailingZeros_l:  n = new CountTrailingZerosLNode(arg); break;
2205   case vmIntrinsics::_bitCount_i:               n = new PopCountINode(          arg); break;
2206   case vmIntrinsics::_bitCount_l:               n = new PopCountLNode(          arg); break;
2207   case vmIntrinsics::_reverseBytes_c:           n = new ReverseBytesUSNode(     arg); break;
2208   case vmIntrinsics::_reverseBytes_s:           n = new ReverseBytesSNode(      arg); break;
2209   case vmIntrinsics::_reverseBytes_i:           n = new ReverseBytesINode(      arg); break;
2210   case vmIntrinsics::_reverseBytes_l:           n = new ReverseBytesLNode(      arg); break;
2211   case vmIntrinsics::_reverse_i:                n = new ReverseINode(           arg); break;
2212   case vmIntrinsics::_reverse_l:                n = new ReverseLNode(           arg); break;
2213   default:  fatal_unexpected_iid(id);  break;
2214   }
2215   set_result(_gvn.transform(n));
2216   return true;
2217 }
2218 
2219 //--------------------------inline_bitshuffle_methods-----------------------------
2220 // inline int Integer.compress(int, int)
2221 // inline int Integer.expand(int, int)
2222 // inline long Long.compress(long, long)
2223 // inline long Long.expand(long, long)
2224 bool LibraryCallKit::inline_bitshuffle_methods(vmIntrinsics::ID id) {
2225   Node* n = nullptr;
2226   switch (id) {
2227     case vmIntrinsics::_compress_i:  n = new CompressBitsNode(argument(0), argument(1), TypeInt::INT); break;
2228     case vmIntrinsics::_expand_i:    n = new ExpandBitsNode(argument(0),  argument(1), TypeInt::INT); break;
2229     case vmIntrinsics::_compress_l:  n = new CompressBitsNode(argument(0), argument(2), TypeLong::LONG); break;
2230     case vmIntrinsics::_expand_l:    n = new ExpandBitsNode(argument(0), argument(2), TypeLong::LONG); break;
2231     default:  fatal_unexpected_iid(id);  break;
2232   }
2233   set_result(_gvn.transform(n));
2234   return true;
2235 }
2236 
2237 //--------------------------inline_number_methods-----------------------------
2238 // inline int Integer.compareUnsigned(int, int)
2239 // inline int    Long.compareUnsigned(long, long)
2240 bool LibraryCallKit::inline_compare_unsigned(vmIntrinsics::ID id) {
2241   Node* arg1 = argument(0);
2242   Node* arg2 = (id == vmIntrinsics::_compareUnsigned_l) ? argument(2) : argument(1);
2243   Node* n = nullptr;
2244   switch (id) {
2245     case vmIntrinsics::_compareUnsigned_i:   n = new CmpU3Node(arg1, arg2);  break;
2246     case vmIntrinsics::_compareUnsigned_l:   n = new CmpUL3Node(arg1, arg2); break;
2247     default:  fatal_unexpected_iid(id);  break;
2248   }
2249   set_result(_gvn.transform(n));
2250   return true;
2251 }
2252 
2253 //--------------------------inline_unsigned_divmod_methods-----------------------------
2254 // inline int Integer.divideUnsigned(int, int)
2255 // inline int Integer.remainderUnsigned(int, int)
2256 // inline long Long.divideUnsigned(long, long)
2257 // inline long Long.remainderUnsigned(long, long)
2258 bool LibraryCallKit::inline_divmod_methods(vmIntrinsics::ID id) {
2259   Node* n = nullptr;
2260   switch (id) {
2261     case vmIntrinsics::_divideUnsigned_i: {
2262       zero_check_int(argument(1));
2263       // Compile-time detect of null-exception
2264       if (stopped()) {
2265         return true; // keep the graph constructed so far
2266       }
2267       n = new UDivINode(control(), argument(0), argument(1));
2268       break;
2269     }
2270     case vmIntrinsics::_divideUnsigned_l: {
2271       zero_check_long(argument(2));
2272       // Compile-time detect of null-exception
2273       if (stopped()) {
2274         return true; // keep the graph constructed so far
2275       }
2276       n = new UDivLNode(control(), argument(0), argument(2));
2277       break;
2278     }
2279     case vmIntrinsics::_remainderUnsigned_i: {
2280       zero_check_int(argument(1));
2281       // Compile-time detect of null-exception
2282       if (stopped()) {
2283         return true; // keep the graph constructed so far
2284       }
2285       n = new UModINode(control(), argument(0), argument(1));
2286       break;
2287     }
2288     case vmIntrinsics::_remainderUnsigned_l: {
2289       zero_check_long(argument(2));
2290       // Compile-time detect of null-exception
2291       if (stopped()) {
2292         return true; // keep the graph constructed so far
2293       }
2294       n = new UModLNode(control(), argument(0), argument(2));
2295       break;
2296     }
2297     default:  fatal_unexpected_iid(id);  break;
2298   }
2299   set_result(_gvn.transform(n));
2300   return true;
2301 }
2302 
2303 //----------------------------inline_unsafe_access----------------------------
2304 
2305 const TypeOopPtr* LibraryCallKit::sharpen_unsafe_type(Compile::AliasType* alias_type, const TypePtr *adr_type) {
2306   // Attempt to infer a sharper value type from the offset and base type.
2307   ciKlass* sharpened_klass = nullptr;
2308   bool null_free = false;
2309 
2310   // See if it is an instance field, with an object type.
2311   if (alias_type->field() != nullptr) {
2312     if (alias_type->field()->type()->is_klass()) {
2313       sharpened_klass = alias_type->field()->type()->as_klass();
2314       null_free = alias_type->field()->is_null_free();
2315     }
2316   }
2317 
2318   const TypeOopPtr* result = nullptr;
2319   // See if it is a narrow oop array.
2320   if (adr_type->isa_aryptr()) {
2321     if (adr_type->offset() >= refArrayOopDesc::base_offset_in_bytes()) {
2322       const TypeOopPtr* elem_type = adr_type->is_aryptr()->elem()->make_oopptr();
2323       null_free = adr_type->is_aryptr()->is_null_free();
2324       if (elem_type != nullptr && elem_type->is_loaded()) {
2325         // Sharpen the value type.
2326         result = elem_type;
2327       }
2328     }
2329   }
2330 
2331   // The sharpened class might be unloaded if there is no class loader
2332   // contraint in place.
2333   if (result == nullptr && sharpened_klass != nullptr && sharpened_klass->is_loaded()) {
2334     // Sharpen the value type.
2335     result = TypeOopPtr::make_from_klass(sharpened_klass);
2336     if (null_free) {
2337       result = result->join_speculative(TypePtr::NOTNULL)->is_oopptr();
2338     }
2339   }
2340   if (result != nullptr) {
2341 #ifndef PRODUCT
2342     if (C->print_intrinsics() || C->print_inlining()) {
2343       tty->print("  from base type:  ");  adr_type->dump(); tty->cr();
2344       tty->print("  sharpened value: ");  result->dump();    tty->cr();
2345     }
2346 #endif
2347   }
2348   return result;
2349 }
2350 
2351 DecoratorSet LibraryCallKit::mo_decorator_for_access_kind(AccessKind kind) {
2352   switch (kind) {
2353       case Relaxed:
2354         return MO_UNORDERED;
2355       case Opaque:
2356         return MO_RELAXED;
2357       case Acquire:
2358         return MO_ACQUIRE;
2359       case Release:
2360         return MO_RELEASE;
2361       case Volatile:
2362         return MO_SEQ_CST;
2363       default:
2364         ShouldNotReachHere();
2365         return 0;
2366   }
2367 }
2368 
2369 bool LibraryCallKit::inline_unsafe_access(bool is_store, const BasicType type, const AccessKind kind, const bool unaligned) {
2370   if (callee()->is_static())  return false;  // caller must have the capability!
2371   DecoratorSet decorators = C2_UNSAFE_ACCESS;
2372   guarantee(!is_store || kind != Acquire, "Acquire accesses can be produced only for loads");
2373   guarantee( is_store || kind != Release, "Release accesses can be produced only for stores");
2374   assert(type != T_OBJECT || !unaligned, "unaligned access not supported with object type");
2375 
2376   if (is_reference_type(type)) {
2377     decorators |= ON_UNKNOWN_OOP_REF;
2378   }
2379 
2380   if (unaligned) {
2381     decorators |= C2_UNALIGNED;
2382   }
2383 
2384 #ifndef PRODUCT
2385   {
2386     ResourceMark rm;
2387     // Check the signatures.
2388     ciSignature* sig = callee()->signature();
2389 #ifdef ASSERT
2390     if (!is_store) {
2391       // Object getReference(Object base, int/long offset), etc.
2392       BasicType rtype = sig->return_type()->basic_type();
2393       assert(rtype == type, "getter must return the expected value");
2394       assert(sig->count() == 2, "oop getter has 2 arguments");
2395       assert(sig->type_at(0)->basic_type() == T_OBJECT, "getter base is object");
2396       assert(sig->type_at(1)->basic_type() == T_LONG, "getter offset is correct");
2397     } else {
2398       // void putReference(Object base, int/long offset, Object x), etc.
2399       assert(sig->return_type()->basic_type() == T_VOID, "putter must not return a value");
2400       assert(sig->count() == 3, "oop putter has 3 arguments");
2401       assert(sig->type_at(0)->basic_type() == T_OBJECT, "putter base is object");
2402       assert(sig->type_at(1)->basic_type() == T_LONG, "putter offset is correct");
2403       BasicType vtype = sig->type_at(sig->count()-1)->basic_type();
2404       assert(vtype == type, "putter must accept the expected value");
2405     }
2406 #endif // ASSERT
2407  }
2408 #endif //PRODUCT
2409 
2410   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
2411 
2412   Node* receiver = argument(0);  // type: oop
2413 
2414   // Build address expression.
2415   Node* heap_base_oop = top();
2416 
2417   // The base is either a Java object or a value produced by Unsafe.staticFieldBase
2418   Node* base = argument(1);  // type: oop
2419   // The offset is a value produced by Unsafe.staticFieldOffset or Unsafe.objectFieldOffset
2420   Node* offset = argument(2);  // type: long
2421   // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
2422   // to be plain byte offsets, which are also the same as those accepted
2423   // by oopDesc::field_addr.
2424   assert(Unsafe_field_offset_to_byte_offset(11) == 11,
2425          "fieldOffset must be byte-scaled");
2426 
2427   if (base->is_InlineType()) {
2428     assert(!is_store, "InlineTypeNodes are non-larval value objects");
2429     InlineTypeNode* vt = base->as_InlineType();
2430     if (offset->is_Con()) {
2431       long off = find_long_con(offset, 0);
2432       ciInlineKlass* vk = vt->type()->inline_klass();
2433       if ((long)(int)off != off || !vk->contains_field_offset(off)) {
2434         return false;
2435       }
2436 
2437       ciField* field = vk->get_non_flat_field_by_offset(off);
2438       if (field != nullptr) {
2439         BasicType bt = type2field[field->type()->basic_type()];
2440         if (bt == T_ARRAY || bt == T_NARROWOOP) {
2441           bt = T_OBJECT;
2442         }
2443         if (bt == type && !field->is_flat()) {
2444           Node* value = vt->field_value_by_offset(off, false);
2445           const Type* value_type = _gvn.type(value);
2446           if (value->is_InlineType()) {
2447             value = value->as_InlineType()->adjust_scalarization_depth(this);
2448           } else if (value_type->is_inlinetypeptr()) {
2449             value = InlineTypeNode::make_from_oop(this, value, value_type->inline_klass());
2450           }
2451           set_result(value);
2452           return true;
2453         }
2454       }
2455     }
2456     {
2457       // Re-execute the unsafe access if allocation triggers deoptimization.
2458       PreserveReexecuteState preexecs(this);
2459       jvms()->set_should_reexecute(true);
2460       vt = vt->buffer(this);
2461     }
2462     base = vt->get_oop();
2463   }
2464 
2465   // 32-bit machines ignore the high half!
2466   offset = ConvL2X(offset);
2467 
2468   // Save state and restore on bailout
2469   SavedState old_state(this);
2470 
2471   Node* adr = make_unsafe_address(base, offset, type, kind == Relaxed);
2472   assert(!stopped(), "Inlining of unsafe access failed: address construction stopped unexpectedly");
2473 
2474   if (_gvn.type(base->uncast())->isa_ptr() == TypePtr::NULL_PTR) {
2475     if (type != T_OBJECT) {
2476       decorators |= IN_NATIVE; // off-heap primitive access
2477     } else {
2478       return false; // off-heap oop accesses are not supported
2479     }
2480   } else {
2481     heap_base_oop = base; // on-heap or mixed access
2482   }
2483 
2484   // Can base be null? Otherwise, always on-heap access.
2485   bool can_access_non_heap = TypePtr::NULL_PTR->higher_equal(_gvn.type(base));
2486 
2487   if (!can_access_non_heap) {
2488     decorators |= IN_HEAP;
2489   }
2490 
2491   Node* val = is_store ? argument(4) : nullptr;
2492 
2493   const TypePtr* adr_type = _gvn.type(adr)->isa_ptr();
2494   if (adr_type == TypePtr::NULL_PTR) {
2495     return false; // off-heap access with zero address
2496   }
2497 
2498   // Try to categorize the address.
2499   Compile::AliasType* alias_type = C->alias_type(adr_type);
2500   assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
2501 
2502   if (alias_type->adr_type() == TypeInstPtr::KLASS ||
2503       alias_type->adr_type() == TypeAryPtr::RANGE) {
2504     return false; // not supported
2505   }
2506 
2507   bool mismatched = false;
2508   BasicType bt = T_ILLEGAL;
2509   ciField* field = nullptr;
2510   if (adr_type->isa_instptr()) {
2511     const TypeInstPtr* instptr = adr_type->is_instptr();
2512     ciInstanceKlass* k = instptr->instance_klass();
2513     int off = instptr->offset();
2514     if (instptr->const_oop() != nullptr &&
2515         k == ciEnv::current()->Class_klass() &&
2516         instptr->offset() >= (k->size_helper() * wordSize)) {
2517       k = instptr->const_oop()->as_instance()->java_lang_Class_klass()->as_instance_klass();
2518       field = k->get_field_by_offset(off, true);
2519     } else {
2520       field = k->get_non_flat_field_by_offset(off);
2521     }
2522     if (field != nullptr) {
2523       bt = type2field[field->type()->basic_type()];
2524     }
2525     if (bt != alias_type->basic_type()) {
2526       // Type mismatch. Is it an access to a nested flat field?
2527       field = k->get_field_by_offset(off, false);
2528       if (field != nullptr) {
2529         bt = type2field[field->type()->basic_type()];
2530       }
2531     }
2532     assert(bt == alias_type->basic_type(), "should match");
2533   } else {
2534     bt = alias_type->basic_type();
2535   }
2536 
2537   if (bt != T_ILLEGAL) {
2538     assert(alias_type->adr_type()->is_oopptr(), "should be on-heap access");
2539     if (bt == T_BYTE && adr_type->isa_aryptr()) {
2540       // Alias type doesn't differentiate between byte[] and boolean[]).
2541       // Use address type to get the element type.
2542       bt = adr_type->is_aryptr()->elem()->array_element_basic_type();
2543     }
2544     if (is_reference_type(bt, true)) {
2545       // accessing an array field with getReference is not a mismatch
2546       bt = T_OBJECT;
2547     }
2548     if ((bt == T_OBJECT) != (type == T_OBJECT)) {
2549       // Don't intrinsify mismatched object accesses
2550       return false;
2551     }
2552     mismatched = (bt != type);
2553   } else if (alias_type->adr_type()->isa_oopptr()) {
2554     mismatched = true; // conservatively mark all "wide" on-heap accesses as mismatched
2555   }
2556 
2557   old_state.discard();
2558   assert(!mismatched || alias_type->adr_type()->is_oopptr(), "off-heap access can't be mismatched");
2559 
2560   if (mismatched) {
2561     decorators |= C2_MISMATCHED;
2562   }
2563 
2564   // First guess at the value type.
2565   const Type *value_type = Type::get_const_basic_type(type);
2566 
2567   // Figure out the memory ordering.
2568   decorators |= mo_decorator_for_access_kind(kind);
2569 
2570   if (!is_store) {
2571     if (type == T_OBJECT) {
2572       const TypeOopPtr* tjp = sharpen_unsafe_type(alias_type, adr_type);
2573       if (tjp != nullptr) {
2574         value_type = tjp;
2575       }
2576     }
2577   }
2578 
2579   receiver = null_check(receiver);
2580   if (stopped()) {
2581     return true;
2582   }
2583   // Heap pointers get a null-check from the interpreter,
2584   // as a courtesy.  However, this is not guaranteed by Unsafe,
2585   // and it is not possible to fully distinguish unintended nulls
2586   // from intended ones in this API.
2587 
2588   if (!is_store) {
2589     Node* p = nullptr;
2590     // Try to constant fold a load from a constant field
2591 
2592     if (heap_base_oop != top() && field != nullptr && field->is_constant() && !field->is_flat() && !mismatched) {
2593       // final or stable field
2594       p = make_constant_from_field(field, heap_base_oop);
2595     }
2596 
2597     if (p == nullptr) { // Could not constant fold the load
2598       p = access_load_at(heap_base_oop, adr, adr_type, value_type, type, decorators);
2599       const TypeOopPtr* ptr = value_type->make_oopptr();
2600       if (ptr != nullptr && ptr->is_inlinetypeptr()) {
2601         // Load a non-flattened inline type from memory
2602         p = InlineTypeNode::make_from_oop(this, p, ptr->inline_klass());
2603       }
2604       // Normalize the value returned by getBoolean in the following cases
2605       if (type == T_BOOLEAN &&
2606           (mismatched ||
2607            heap_base_oop == top() ||                  // - heap_base_oop is null or
2608            (can_access_non_heap && field == nullptr)) // - heap_base_oop is potentially null
2609                                                       //   and the unsafe access is made to large offset
2610                                                       //   (i.e., larger than the maximum offset necessary for any
2611                                                       //   field access)
2612             ) {
2613           IdealKit ideal = IdealKit(this);
2614 #define __ ideal.
2615           IdealVariable normalized_result(ideal);
2616           __ declarations_done();
2617           __ set(normalized_result, p);
2618           __ if_then(p, BoolTest::ne, ideal.ConI(0));
2619           __ set(normalized_result, ideal.ConI(1));
2620           ideal.end_if();
2621           final_sync(ideal);
2622           p = __ value(normalized_result);
2623 #undef __
2624       }
2625     }
2626     if (type == T_ADDRESS) {
2627       p = gvn().transform(new CastP2XNode(nullptr, p));
2628       p = ConvX2UL(p);
2629     }
2630     // The load node has the control of the preceding MemBarCPUOrder.  All
2631     // following nodes will have the control of the MemBarCPUOrder inserted at
2632     // the end of this method.  So, pushing the load onto the stack at a later
2633     // point is fine.
2634     set_result(p);
2635   } else {
2636     if (bt == T_ADDRESS) {
2637       // Repackage the long as a pointer.
2638       val = ConvL2X(val);
2639       val = gvn().transform(new CastX2PNode(val));
2640     }
2641     access_store_at(heap_base_oop, adr, adr_type, val, value_type, type, decorators);
2642   }
2643 
2644   return true;
2645 }
2646 
2647 bool LibraryCallKit::inline_unsafe_flat_access(bool is_store, AccessKind kind) {
2648 #ifdef ASSERT
2649   {
2650     ResourceMark rm;
2651     // Check the signatures.
2652     ciSignature* sig = callee()->signature();
2653     assert(sig->type_at(0)->basic_type() == T_OBJECT, "base should be object, but is %s", type2name(sig->type_at(0)->basic_type()));
2654     assert(sig->type_at(1)->basic_type() == T_LONG, "offset should be long, but is %s", type2name(sig->type_at(1)->basic_type()));
2655     assert(sig->type_at(2)->basic_type() == T_INT, "layout kind should be int, but is %s", type2name(sig->type_at(3)->basic_type()));
2656     assert(sig->type_at(3)->basic_type() == T_OBJECT, "value klass should be object, but is %s", type2name(sig->type_at(4)->basic_type()));
2657     if (is_store) {
2658       assert(sig->return_type()->basic_type() == T_VOID, "putter must not return a value, but returns %s", type2name(sig->return_type()->basic_type()));
2659       assert(sig->count() == 5, "flat putter should have 5 arguments, but has %d", sig->count());
2660       assert(sig->type_at(4)->basic_type() == T_OBJECT, "put value should be object, but is %s", type2name(sig->type_at(5)->basic_type()));
2661     } else {
2662       assert(sig->return_type()->basic_type() == T_OBJECT, "getter must return an object, but returns %s", type2name(sig->return_type()->basic_type()));
2663       assert(sig->count() == 4, "flat getter should have 4 arguments, but has %d", sig->count());
2664     }
2665  }
2666 #endif // ASSERT
2667 
2668   assert(kind == Relaxed, "Only plain accesses for now");
2669   if (callee()->is_static()) {
2670     // caller must have the capability!
2671     return false;
2672   }
2673   C->set_has_unsafe_access(true);
2674 
2675   const TypeInstPtr* value_klass_node = _gvn.type(argument(5))->isa_instptr();
2676   if (value_klass_node == nullptr || value_klass_node->const_oop() == nullptr) {
2677     // parameter valueType is not a constant
2678     return false;
2679   }
2680   ciType* mirror_type = value_klass_node->const_oop()->as_instance()->java_mirror_type();
2681   if (!mirror_type->is_inlinetype()) {
2682     // Dead code
2683     return false;
2684   }
2685   ciInlineKlass* value_klass = mirror_type->as_inline_klass();
2686 
2687   const TypeInt* layout_type = _gvn.type(argument(4))->isa_int();
2688   if (layout_type == nullptr || !layout_type->is_con()) {
2689     // parameter layoutKind is not a constant
2690     return false;
2691   }
2692   assert(layout_type->get_con() >= static_cast<int>(LayoutKind::REFERENCE) &&
2693          layout_type->get_con() < static_cast<int>(LayoutKind::UNKNOWN),
2694          "invalid layoutKind %d", layout_type->get_con());
2695   LayoutKind layout = static_cast<LayoutKind>(layout_type->get_con());
2696   assert(layout == LayoutKind::REFERENCE || layout == LayoutKind::NULL_FREE_NON_ATOMIC_FLAT ||
2697          layout == LayoutKind::NULL_FREE_ATOMIC_FLAT || layout == LayoutKind::NULLABLE_ATOMIC_FLAT,
2698          "unexpected layoutKind %d", layout_type->get_con());
2699 
2700   null_check(argument(0));
2701   if (stopped()) {
2702     return true;
2703   }
2704 
2705   Node* base = must_be_not_null(argument(1), true);
2706   Node* offset = argument(2);
2707   const Type* base_type = _gvn.type(base);
2708 
2709   Node* ptr;
2710   bool immutable_memory = false;
2711   DecoratorSet decorators = C2_UNSAFE_ACCESS | IN_HEAP | MO_UNORDERED;
2712   if (base_type->isa_instptr()) {
2713     const TypeLong* offset_type = _gvn.type(offset)->isa_long();
2714     if (offset_type == nullptr || !offset_type->is_con()) {
2715       // Offset into a non-array should be a constant
2716       decorators |= C2_MISMATCHED;
2717     } else {
2718       int offset_con = checked_cast<int>(offset_type->get_con());
2719       ciInstanceKlass* base_klass = base_type->is_instptr()->instance_klass();
2720       ciField* field = base_klass->get_non_flat_field_by_offset(offset_con);
2721       if (field == nullptr) {
2722         assert(!base_klass->is_final(), "non-existence field at offset %d of class %s", offset_con, base_klass->name()->as_utf8());
2723         decorators |= C2_MISMATCHED;
2724       } else {
2725         assert(field->type() == value_klass, "field at offset %d of %s is of type %s, but valueType is %s",
2726                offset_con, base_klass->name()->as_utf8(), field->type()->name(), value_klass->name()->as_utf8());
2727         immutable_memory = field->is_strict() && field->is_final();
2728 
2729         if (base->is_InlineType()) {
2730           assert(!is_store, "Cannot store into a non-larval value object");
2731           set_result(base->as_InlineType()->field_value_by_offset(offset_con, false));
2732           return true;
2733         }
2734       }
2735     }
2736 
2737     if (base->is_InlineType()) {
2738       assert(!is_store, "Cannot store into a non-larval value object");
2739       base = base->as_InlineType()->buffer(this, true);
2740     }
2741     ptr = basic_plus_adr(base, ConvL2X(offset));
2742   } else if (base_type->isa_aryptr()) {
2743     decorators |= IS_ARRAY;
2744     if (layout == LayoutKind::REFERENCE) {
2745       if (!base_type->is_aryptr()->is_not_flat()) {
2746         const TypeAryPtr* array_type = base_type->is_aryptr()->cast_to_not_flat();
2747         Node* new_base = _gvn.transform(new CastPPNode(control(), base, array_type, ConstraintCastNode::DependencyType::NonFloatingNarrowing));
2748         replace_in_map(base, new_base);
2749         base = new_base;
2750       }
2751       ptr = basic_plus_adr(base, ConvL2X(offset));
2752     } else {
2753       if (UseArrayFlattening) {
2754         // Flat array must have an exact type
2755         bool is_null_free = !LayoutKindHelper::is_nullable_flat(layout);
2756         bool is_atomic = LayoutKindHelper::is_atomic_flat(layout);
2757         Node* new_base = cast_to_flat_array_exact(base, value_klass, is_null_free, is_atomic);
2758         replace_in_map(base, new_base);
2759         base = new_base;
2760         ptr = basic_plus_adr(base, ConvL2X(offset));
2761         const TypeAryPtr* ptr_type = _gvn.type(ptr)->is_aryptr();
2762         if (ptr_type->field_offset().get() != 0) {
2763           ptr = _gvn.transform(new CastPPNode(control(), ptr, ptr_type->with_field_offset(0), ConstraintCastNode::DependencyType::NonFloatingNarrowing));
2764         }
2765       } else {
2766         uncommon_trap(Deoptimization::Reason_intrinsic,
2767                       Deoptimization::Action_none);
2768         return true;
2769       }
2770     }
2771   } else {
2772     decorators |= C2_MISMATCHED;
2773     ptr = basic_plus_adr(base, ConvL2X(offset));
2774   }
2775 
2776   if (is_store) {
2777     Node* value = argument(6);
2778     const Type* value_type = _gvn.type(value);
2779     if (!value_type->is_inlinetypeptr()) {
2780       value_type = Type::get_const_type(value_klass)->filter_speculative(value_type);
2781       Node* new_value = _gvn.transform(new CastPPNode(control(), value, value_type, ConstraintCastNode::DependencyType::NonFloatingNarrowing));
2782       new_value = InlineTypeNode::make_from_oop(this, new_value, value_klass);
2783       replace_in_map(value, new_value);
2784       value = new_value;
2785     }
2786 
2787     assert(value_type->inline_klass() == value_klass, "value is of type %s while valueType is %s", value_type->inline_klass()->name()->as_utf8(), value_klass->name()->as_utf8());
2788     if (layout == LayoutKind::REFERENCE) {
2789       const TypePtr* ptr_type = (decorators & C2_MISMATCHED) != 0 ? TypeRawPtr::BOTTOM : _gvn.type(ptr)->is_ptr();
2790       access_store_at(base, ptr, ptr_type, value, value_type, T_OBJECT, decorators);
2791     } else {
2792       bool atomic = LayoutKindHelper::is_atomic_flat(layout);
2793       bool null_free = !LayoutKindHelper::is_nullable_flat(layout);
2794       value->as_InlineType()->store_flat(this, base, ptr, atomic, immutable_memory, null_free, decorators);
2795     }
2796 
2797     return true;
2798   } else {
2799     decorators |= (C2_CONTROL_DEPENDENT_LOAD | C2_UNKNOWN_CONTROL_LOAD);
2800     InlineTypeNode* result;
2801     if (layout == LayoutKind::REFERENCE) {
2802       const TypePtr* ptr_type = (decorators & C2_MISMATCHED) != 0 ? TypeRawPtr::BOTTOM : _gvn.type(ptr)->is_ptr();
2803       Node* oop = access_load_at(base, ptr, ptr_type, Type::get_const_type(value_klass), T_OBJECT, decorators);
2804       result = InlineTypeNode::make_from_oop(this, oop, value_klass);
2805     } else {
2806       bool atomic = LayoutKindHelper::is_atomic_flat(layout);
2807       bool null_free = !LayoutKindHelper::is_nullable_flat(layout);
2808       result = InlineTypeNode::make_from_flat(this, value_klass, base, ptr, atomic, immutable_memory, null_free, decorators);
2809     }
2810 
2811     set_result(result);
2812     return true;
2813   }
2814 }
2815 
2816 //----------------------------inline_unsafe_load_store----------------------------
2817 // This method serves a couple of different customers (depending on LoadStoreKind):
2818 //
2819 // LS_cmp_swap:
2820 //
2821 //   boolean compareAndSetReference(Object o, long offset, Object expected, Object x);
2822 //   boolean compareAndSetInt(   Object o, long offset, int    expected, int    x);
2823 //   boolean compareAndSetLong(  Object o, long offset, long   expected, long   x);
2824 //
2825 // LS_cmp_swap_weak:
2826 //
2827 //   boolean weakCompareAndSetReference(       Object o, long offset, Object expected, Object x);
2828 //   boolean weakCompareAndSetReferencePlain(  Object o, long offset, Object expected, Object x);
2829 //   boolean weakCompareAndSetReferenceAcquire(Object o, long offset, Object expected, Object x);
2830 //   boolean weakCompareAndSetReferenceRelease(Object o, long offset, Object expected, Object x);
2831 //
2832 //   boolean weakCompareAndSetInt(          Object o, long offset, int    expected, int    x);
2833 //   boolean weakCompareAndSetIntPlain(     Object o, long offset, int    expected, int    x);
2834 //   boolean weakCompareAndSetIntAcquire(   Object o, long offset, int    expected, int    x);
2835 //   boolean weakCompareAndSetIntRelease(   Object o, long offset, int    expected, int    x);
2836 //
2837 //   boolean weakCompareAndSetLong(         Object o, long offset, long   expected, long   x);
2838 //   boolean weakCompareAndSetLongPlain(    Object o, long offset, long   expected, long   x);
2839 //   boolean weakCompareAndSetLongAcquire(  Object o, long offset, long   expected, long   x);
2840 //   boolean weakCompareAndSetLongRelease(  Object o, long offset, long   expected, long   x);
2841 //
2842 // LS_cmp_exchange:
2843 //
2844 //   Object compareAndExchangeReferenceVolatile(Object o, long offset, Object expected, Object x);
2845 //   Object compareAndExchangeReferenceAcquire( Object o, long offset, Object expected, Object x);
2846 //   Object compareAndExchangeReferenceRelease( Object o, long offset, Object expected, Object x);
2847 //
2848 //   Object compareAndExchangeIntVolatile(   Object o, long offset, Object expected, Object x);
2849 //   Object compareAndExchangeIntAcquire(    Object o, long offset, Object expected, Object x);
2850 //   Object compareAndExchangeIntRelease(    Object o, long offset, Object expected, Object x);
2851 //
2852 //   Object compareAndExchangeLongVolatile(  Object o, long offset, Object expected, Object x);
2853 //   Object compareAndExchangeLongAcquire(   Object o, long offset, Object expected, Object x);
2854 //   Object compareAndExchangeLongRelease(   Object o, long offset, Object expected, Object x);
2855 //
2856 // LS_get_add:
2857 //
2858 //   int  getAndAddInt( Object o, long offset, int  delta)
2859 //   long getAndAddLong(Object o, long offset, long delta)
2860 //
2861 // LS_get_set:
2862 //
2863 //   int    getAndSet(Object o, long offset, int    newValue)
2864 //   long   getAndSet(Object o, long offset, long   newValue)
2865 //   Object getAndSet(Object o, long offset, Object newValue)
2866 //
2867 bool LibraryCallKit::inline_unsafe_load_store(const BasicType type, const LoadStoreKind kind, const AccessKind access_kind) {
2868   // This basic scheme here is the same as inline_unsafe_access, but
2869   // differs in enough details that combining them would make the code
2870   // overly confusing.  (This is a true fact! I originally combined
2871   // them, but even I was confused by it!) As much code/comments as
2872   // possible are retained from inline_unsafe_access though to make
2873   // the correspondences clearer. - dl
2874 
2875   if (callee()->is_static())  return false;  // caller must have the capability!
2876 
2877   DecoratorSet decorators = C2_UNSAFE_ACCESS;
2878   decorators |= mo_decorator_for_access_kind(access_kind);
2879 
2880 #ifndef PRODUCT
2881   BasicType rtype;
2882   {
2883     ResourceMark rm;
2884     // Check the signatures.
2885     ciSignature* sig = callee()->signature();
2886     rtype = sig->return_type()->basic_type();
2887     switch(kind) {
2888       case LS_get_add:
2889       case LS_get_set: {
2890       // Check the signatures.
2891 #ifdef ASSERT
2892       assert(rtype == type, "get and set must return the expected type");
2893       assert(sig->count() == 3, "get and set has 3 arguments");
2894       assert(sig->type_at(0)->basic_type() == T_OBJECT, "get and set base is object");
2895       assert(sig->type_at(1)->basic_type() == T_LONG, "get and set offset is long");
2896       assert(sig->type_at(2)->basic_type() == type, "get and set must take expected type as new value/delta");
2897       assert(access_kind == Volatile, "mo is not passed to intrinsic nodes in current implementation");
2898 #endif // ASSERT
2899         break;
2900       }
2901       case LS_cmp_swap:
2902       case LS_cmp_swap_weak: {
2903       // Check the signatures.
2904 #ifdef ASSERT
2905       assert(rtype == T_BOOLEAN, "CAS must return boolean");
2906       assert(sig->count() == 4, "CAS has 4 arguments");
2907       assert(sig->type_at(0)->basic_type() == T_OBJECT, "CAS base is object");
2908       assert(sig->type_at(1)->basic_type() == T_LONG, "CAS offset is long");
2909 #endif // ASSERT
2910         break;
2911       }
2912       case LS_cmp_exchange: {
2913       // Check the signatures.
2914 #ifdef ASSERT
2915       assert(rtype == type, "CAS must return the expected type");
2916       assert(sig->count() == 4, "CAS has 4 arguments");
2917       assert(sig->type_at(0)->basic_type() == T_OBJECT, "CAS base is object");
2918       assert(sig->type_at(1)->basic_type() == T_LONG, "CAS offset is long");
2919 #endif // ASSERT
2920         break;
2921       }
2922       default:
2923         ShouldNotReachHere();
2924     }
2925   }
2926 #endif //PRODUCT
2927 
2928   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
2929 
2930   // Get arguments:
2931   Node* receiver = nullptr;
2932   Node* base     = nullptr;
2933   Node* offset   = nullptr;
2934   Node* oldval   = nullptr;
2935   Node* newval   = nullptr;
2936   switch(kind) {
2937     case LS_cmp_swap:
2938     case LS_cmp_swap_weak:
2939     case LS_cmp_exchange: {
2940       const bool two_slot_type = type2size[type] == 2;
2941       receiver = argument(0);  // type: oop
2942       base     = argument(1);  // type: oop
2943       offset   = argument(2);  // type: long
2944       oldval   = argument(4);  // type: oop, int, or long
2945       newval   = argument(two_slot_type ? 6 : 5);  // type: oop, int, or long
2946       break;
2947     }
2948     case LS_get_add:
2949     case LS_get_set: {
2950       receiver = argument(0);  // type: oop
2951       base     = argument(1);  // type: oop
2952       offset   = argument(2);  // type: long
2953       oldval   = nullptr;
2954       newval   = argument(4);  // type: oop, int, or long
2955       break;
2956     }
2957     default:
2958       ShouldNotReachHere();
2959   }
2960 
2961   // Build field offset expression.
2962   // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
2963   // to be plain byte offsets, which are also the same as those accepted
2964   // by oopDesc::field_addr.
2965   assert(Unsafe_field_offset_to_byte_offset(11) == 11, "fieldOffset must be byte-scaled");
2966   // 32-bit machines ignore the high half of long offsets
2967   offset = ConvL2X(offset);
2968   // Save state and restore on bailout
2969   SavedState old_state(this);
2970   Node* adr = make_unsafe_address(base, offset,type, false);
2971   const TypePtr *adr_type = _gvn.type(adr)->isa_ptr();
2972 
2973   Compile::AliasType* alias_type = C->alias_type(adr_type);
2974   BasicType bt = alias_type->basic_type();
2975   if (bt != T_ILLEGAL &&
2976       (is_reference_type(bt) != (type == T_OBJECT))) {
2977     // Don't intrinsify mismatched object accesses.
2978     return false;
2979   }
2980 
2981   old_state.discard();
2982 
2983   // For CAS, unlike inline_unsafe_access, there seems no point in
2984   // trying to refine types. Just use the coarse types here.
2985   assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
2986   const Type *value_type = Type::get_const_basic_type(type);
2987 
2988   switch (kind) {
2989     case LS_get_set:
2990     case LS_cmp_exchange: {
2991       if (type == T_OBJECT) {
2992         const TypeOopPtr* tjp = sharpen_unsafe_type(alias_type, adr_type);
2993         if (tjp != nullptr) {
2994           value_type = tjp;
2995         }
2996       }
2997       break;
2998     }
2999     case LS_cmp_swap:
3000     case LS_cmp_swap_weak:
3001     case LS_get_add:
3002       break;
3003     default:
3004       ShouldNotReachHere();
3005   }
3006 
3007   // Null check receiver.
3008   receiver = null_check(receiver);
3009   if (stopped()) {
3010     return true;
3011   }
3012 
3013   int alias_idx = C->get_alias_index(adr_type);
3014 
3015   if (is_reference_type(type)) {
3016     decorators |= IN_HEAP | ON_UNKNOWN_OOP_REF;
3017 
3018     if (oldval != nullptr && oldval->is_InlineType()) {
3019       // Re-execute the unsafe access if allocation triggers deoptimization.
3020       PreserveReexecuteState preexecs(this);
3021       jvms()->set_should_reexecute(true);
3022       oldval = oldval->as_InlineType()->buffer(this)->get_oop();
3023     }
3024     if (newval != nullptr && newval->is_InlineType()) {
3025       // Re-execute the unsafe access if allocation triggers deoptimization.
3026       PreserveReexecuteState preexecs(this);
3027       jvms()->set_should_reexecute(true);
3028       newval = newval->as_InlineType()->buffer(this)->get_oop();
3029     }
3030 
3031     // Transformation of a value which could be null pointer (CastPP #null)
3032     // could be delayed during Parse (for example, in adjust_map_after_if()).
3033     // Execute transformation here to avoid barrier generation in such case.
3034     if (_gvn.type(newval) == TypePtr::NULL_PTR)
3035       newval = _gvn.makecon(TypePtr::NULL_PTR);
3036 
3037     if (oldval != nullptr && _gvn.type(oldval) == TypePtr::NULL_PTR) {
3038       // Refine the value to a null constant, when it is known to be null
3039       oldval = _gvn.makecon(TypePtr::NULL_PTR);
3040     }
3041   }
3042 
3043   Node* result = nullptr;
3044   switch (kind) {
3045     case LS_cmp_exchange: {
3046       result = access_atomic_cmpxchg_val_at(base, adr, adr_type, alias_idx,
3047                                             oldval, newval, value_type, type, decorators);
3048       break;
3049     }
3050     case LS_cmp_swap_weak:
3051       decorators |= C2_WEAK_CMPXCHG;
3052     case LS_cmp_swap: {
3053       result = access_atomic_cmpxchg_bool_at(base, adr, adr_type, alias_idx,
3054                                              oldval, newval, value_type, type, decorators);
3055       break;
3056     }
3057     case LS_get_set: {
3058       result = access_atomic_xchg_at(base, adr, adr_type, alias_idx,
3059                                      newval, value_type, type, decorators);
3060       break;
3061     }
3062     case LS_get_add: {
3063       result = access_atomic_add_at(base, adr, adr_type, alias_idx,
3064                                     newval, value_type, type, decorators);
3065       break;
3066     }
3067     default:
3068       ShouldNotReachHere();
3069   }
3070 
3071   assert(type2size[result->bottom_type()->basic_type()] == type2size[rtype], "result type should match");
3072   set_result(result);
3073   return true;
3074 }
3075 
3076 bool LibraryCallKit::inline_unsafe_fence(vmIntrinsics::ID id) {
3077   // Regardless of form, don't allow previous ld/st to move down,
3078   // then issue acquire, release, or volatile mem_bar.
3079   insert_mem_bar(Op_MemBarCPUOrder);
3080   switch(id) {
3081     case vmIntrinsics::_loadFence:
3082       insert_mem_bar(Op_LoadFence);
3083       return true;
3084     case vmIntrinsics::_storeFence:
3085       insert_mem_bar(Op_StoreFence);
3086       return true;
3087     case vmIntrinsics::_storeStoreFence:
3088       insert_mem_bar(Op_StoreStoreFence);
3089       return true;
3090     case vmIntrinsics::_fullFence:
3091       insert_mem_bar(Op_MemBarFull);
3092       return true;
3093     default:
3094       fatal_unexpected_iid(id);
3095       return false;
3096   }
3097 }
3098 
3099 // private native int arrayInstanceBaseOffset0(Object[] array);
3100 bool LibraryCallKit::inline_arrayInstanceBaseOffset() {
3101   Node* array = argument(1);
3102   Node* klass_node = load_object_klass(array);
3103 
3104   jint  layout_con = Klass::_lh_neutral_value;
3105   Node* layout_val = get_layout_helper(klass_node, layout_con);
3106   int   layout_is_con = (layout_val == nullptr);
3107 
3108   Node* header_size = nullptr;
3109   if (layout_is_con) {
3110     int hsize = Klass::layout_helper_header_size(layout_con);
3111     header_size = intcon(hsize);
3112   } else {
3113     Node* hss = intcon(Klass::_lh_header_size_shift);
3114     Node* hsm = intcon(Klass::_lh_header_size_mask);
3115     header_size = _gvn.transform(new URShiftINode(layout_val, hss));
3116     header_size = _gvn.transform(new AndINode(header_size, hsm));
3117   }
3118   set_result(header_size);
3119   return true;
3120 }
3121 
3122 // private native int arrayInstanceIndexScale0(Object[] array);
3123 bool LibraryCallKit::inline_arrayInstanceIndexScale() {
3124   Node* array = argument(1);
3125   Node* klass_node = load_object_klass(array);
3126 
3127   jint  layout_con = Klass::_lh_neutral_value;
3128   Node* layout_val = get_layout_helper(klass_node, layout_con);
3129   int   layout_is_con = (layout_val == nullptr);
3130 
3131   Node* element_size = nullptr;
3132   if (layout_is_con) {
3133     int log_element_size  = Klass::layout_helper_log2_element_size(layout_con);
3134     int elem_size = 1 << log_element_size;
3135     element_size = intcon(elem_size);
3136   } else {
3137     Node* ess = intcon(Klass::_lh_log2_element_size_shift);
3138     Node* esm = intcon(Klass::_lh_log2_element_size_mask);
3139     Node* log_element_size = _gvn.transform(new URShiftINode(layout_val, ess));
3140     log_element_size = _gvn.transform(new AndINode(log_element_size, esm));
3141     element_size = _gvn.transform(new LShiftINode(intcon(1), log_element_size));
3142   }
3143   set_result(element_size);
3144   return true;
3145 }
3146 
3147 // private native int arrayLayout0(Object[] array);
3148 bool LibraryCallKit::inline_arrayLayout() {
3149   RegionNode* region = new RegionNode(2);
3150   Node* phi = new PhiNode(region, TypeInt::POS);
3151 
3152   Node* array = argument(1);
3153   Node* klass_node = load_object_klass(array);
3154   generate_refArray_guard(klass_node, region);
3155   if (region->req() == 3) {
3156     phi->add_req(intcon((jint)LayoutKind::REFERENCE));
3157   }
3158 
3159   int layout_kind_offset = in_bytes(FlatArrayKlass::layout_kind_offset());
3160   Node* layout_kind_addr = basic_plus_adr(top(), klass_node, layout_kind_offset);
3161   Node* layout_kind = make_load(nullptr, layout_kind_addr, TypeInt::POS, T_INT, MemNode::unordered);
3162 
3163   region->init_req(1, control());
3164   phi->init_req(1, layout_kind);
3165 
3166   set_control(_gvn.transform(region));
3167   set_result(_gvn.transform(phi));
3168   return true;
3169 }
3170 
3171 // private native int[] getFieldMap0(Class <?> c);
3172 //   int offset = c._klass._acmp_maps_offset;
3173 //   return (int[])c.obj_field(offset);
3174 bool LibraryCallKit::inline_getFieldMap() {
3175   Node* mirror = argument(1);
3176   Node* klass = load_klass_from_mirror(mirror, false, nullptr, 0);
3177 
3178   int field_map_offset_offset = in_bytes(InstanceKlass::acmp_maps_offset_offset());
3179   Node* field_map_offset_addr = basic_plus_adr(top(), klass, field_map_offset_offset);
3180   Node* field_map_offset = make_load(nullptr, field_map_offset_addr, TypeInt::INT, T_INT, MemNode::unordered);
3181   field_map_offset = _gvn.transform(ConvI2L(field_map_offset));
3182 
3183   Node* map_addr = basic_plus_adr(mirror, field_map_offset);
3184   const TypeAryPtr* val_type = TypeAryPtr::INTS->cast_to_ptr_type(TypePtr::NotNull)->with_offset(0);
3185   // TODO 8350865 Remove this
3186   val_type = val_type->cast_to_not_flat(true)->cast_to_not_null_free(true);
3187   Node* map = access_load_at(mirror, map_addr, TypeAryPtr::INTS, val_type, T_ARRAY, IN_HEAP | MO_UNORDERED);
3188 
3189   set_result(map);
3190   return true;
3191 }
3192 
3193 bool LibraryCallKit::inline_onspinwait() {
3194   insert_mem_bar(Op_OnSpinWait);
3195   return true;
3196 }
3197 
3198 bool LibraryCallKit::klass_needs_init_guard(Node* kls) {
3199   if (!kls->is_Con()) {
3200     return true;
3201   }
3202   const TypeInstKlassPtr* klsptr = kls->bottom_type()->isa_instklassptr();
3203   if (klsptr == nullptr) {
3204     return true;
3205   }
3206   ciInstanceKlass* ik = klsptr->instance_klass();
3207   // don't need a guard for a klass that is already initialized
3208   return !ik->is_initialized();
3209 }
3210 
3211 //----------------------------inline_unsafe_writeback0-------------------------
3212 // public native void Unsafe.writeback0(long address)
3213 bool LibraryCallKit::inline_unsafe_writeback0() {
3214   if (!Matcher::has_match_rule(Op_CacheWB)) {
3215     return false;
3216   }
3217 #ifndef PRODUCT
3218   assert(Matcher::has_match_rule(Op_CacheWBPreSync), "found match rule for CacheWB but not CacheWBPreSync");
3219   assert(Matcher::has_match_rule(Op_CacheWBPostSync), "found match rule for CacheWB but not CacheWBPostSync");
3220   ciSignature* sig = callee()->signature();
3221   assert(sig->type_at(0)->basic_type() == T_LONG, "Unsafe_writeback0 address is long!");
3222 #endif
3223   null_check_receiver();  // null-check, then ignore
3224   Node *addr = argument(1);
3225   addr = new CastX2PNode(addr);
3226   addr = _gvn.transform(addr);
3227   Node *flush = new CacheWBNode(control(), memory(TypeRawPtr::BOTTOM), addr);
3228   flush = _gvn.transform(flush);
3229   set_memory(flush, TypeRawPtr::BOTTOM);
3230   return true;
3231 }
3232 
3233 //----------------------------inline_unsafe_writeback0-------------------------
3234 // public native void Unsafe.writeback0(long address)
3235 bool LibraryCallKit::inline_unsafe_writebackSync0(bool is_pre) {
3236   if (is_pre && !Matcher::has_match_rule(Op_CacheWBPreSync)) {
3237     return false;
3238   }
3239   if (!is_pre && !Matcher::has_match_rule(Op_CacheWBPostSync)) {
3240     return false;
3241   }
3242 #ifndef PRODUCT
3243   assert(Matcher::has_match_rule(Op_CacheWB),
3244          (is_pre ? "found match rule for CacheWBPreSync but not CacheWB"
3245                 : "found match rule for CacheWBPostSync but not CacheWB"));
3246 
3247 #endif
3248   null_check_receiver();  // null-check, then ignore
3249   Node *sync;
3250   if (is_pre) {
3251     sync = new CacheWBPreSyncNode(control(), memory(TypeRawPtr::BOTTOM));
3252   } else {
3253     sync = new CacheWBPostSyncNode(control(), memory(TypeRawPtr::BOTTOM));
3254   }
3255   sync = _gvn.transform(sync);
3256   set_memory(sync, TypeRawPtr::BOTTOM);
3257   return true;
3258 }
3259 
3260 //----------------------------inline_unsafe_allocate---------------------------
3261 // public native Object Unsafe.allocateInstance(Class<?> cls);
3262 bool LibraryCallKit::inline_unsafe_allocate() {
3263 
3264 #if INCLUDE_JVMTI
3265   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
3266     return false;
3267   }
3268 #endif //INCLUDE_JVMTI
3269 
3270   if (callee()->is_static())  return false;  // caller must have the capability!
3271 
3272   null_check_receiver();  // null-check, then ignore
3273   Node* cls = null_check(argument(1));
3274   if (stopped())  return true;
3275 
3276   Node* kls = load_klass_from_mirror(cls, false, nullptr, 0);
3277   kls = null_check(kls);
3278   if (stopped())  return true;  // argument was like int.class
3279 
3280 #if INCLUDE_JVMTI
3281     // Don't try to access new allocated obj in the intrinsic.
3282     // It causes perfomance issues even when jvmti event VmObjectAlloc is disabled.
3283     // Deoptimize and allocate in interpreter instead.
3284     Node* addr = makecon(TypeRawPtr::make((address) &JvmtiExport::_should_notify_object_alloc));
3285     Node* should_post_vm_object_alloc = make_load(this->control(), addr, TypeInt::INT, T_INT, MemNode::unordered);
3286     Node* chk = _gvn.transform(new CmpINode(should_post_vm_object_alloc, intcon(0)));
3287     Node* tst = _gvn.transform(new BoolNode(chk, BoolTest::eq));
3288     {
3289       BuildCutout unless(this, tst, PROB_MAX);
3290       uncommon_trap(Deoptimization::Reason_intrinsic,
3291                     Deoptimization::Action_make_not_entrant);
3292     }
3293     if (stopped()) {
3294       return true;
3295     }
3296 #endif //INCLUDE_JVMTI
3297 
3298   Node* test = nullptr;
3299   if (LibraryCallKit::klass_needs_init_guard(kls)) {
3300     // Note:  The argument might still be an illegal value like
3301     // Serializable.class or Object[].class.   The runtime will handle it.
3302     // But we must make an explicit check for initialization.
3303     Node* insp = off_heap_plus_addr(kls, in_bytes(InstanceKlass::init_state_offset()));
3304     // Use T_BOOLEAN for InstanceKlass::_init_state so the compiler
3305     // can generate code to load it as unsigned byte.
3306     Node* inst = make_load(nullptr, insp, TypeInt::UBYTE, T_BOOLEAN, MemNode::acquire);
3307     Node* bits = intcon(InstanceKlass::fully_initialized);
3308     test = _gvn.transform(new SubINode(inst, bits));
3309     // The 'test' is non-zero if we need to take a slow path.
3310   }
3311   Node* obj = new_instance(kls, test);
3312   set_result(obj);
3313   return true;
3314 }
3315 
3316 //------------------------inline_native_time_funcs--------------
3317 // inline code for System.currentTimeMillis() and System.nanoTime()
3318 // these have the same type and signature
3319 bool LibraryCallKit::inline_native_time_funcs(address funcAddr, const char* funcName) {
3320   const TypeFunc* tf = OptoRuntime::void_long_Type();
3321   const TypePtr* no_memory_effects = nullptr;
3322   Node* time = make_runtime_call(RC_LEAF, tf, funcAddr, funcName, no_memory_effects);
3323   Node* value = _gvn.transform(new ProjNode(time, TypeFunc::Parms+0));
3324 #ifdef ASSERT
3325   Node* value_top = _gvn.transform(new ProjNode(time, TypeFunc::Parms+1));
3326   assert(value_top == top(), "second value must be top");
3327 #endif
3328   set_result(value);
3329   return true;
3330 }
3331 
3332 //--------------------inline_native_vthread_start_transition--------------------
3333 // inline void startTransition(boolean is_mount);
3334 // inline void startFinalTransition();
3335 // Pseudocode of implementation:
3336 //
3337 // java_lang_Thread::set_is_in_vthread_transition(vthread, true);
3338 // carrier->set_is_in_vthread_transition(true);
3339 // OrderAccess::storeload();
3340 // int disable_requests = java_lang_Thread::vthread_transition_disable_count(vthread)
3341 //                        + global_vthread_transition_disable_count();
3342 // if (disable_requests > 0) {
3343 //   slow path: runtime call
3344 // }
3345 bool LibraryCallKit::inline_native_vthread_start_transition(address funcAddr, const char* funcName, bool is_final_transition) {
3346   Node* vt_oop = must_be_not_null(argument(0), true); // VirtualThread this argument
3347   IdealKit ideal(this);
3348 
3349   Node* thread = ideal.thread();
3350   Node* jt_addr = off_heap_plus_addr(thread, in_bytes(JavaThread::is_in_vthread_transition_offset()));
3351   Node* vt_addr = basic_plus_adr(vt_oop, java_lang_Thread::is_in_vthread_transition_offset());
3352   access_store_at(nullptr, jt_addr, _gvn.type(jt_addr)->is_ptr(), ideal.ConI(1), TypeInt::BOOL, T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
3353   access_store_at(nullptr, vt_addr, _gvn.type(vt_addr)->is_ptr(), ideal.ConI(1), TypeInt::BOOL, T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
3354   insert_mem_bar(Op_MemBarStoreLoad);
3355   ideal.sync_kit(this);
3356 
3357   Node* global_disable_addr = makecon(TypeRawPtr::make((address)MountUnmountDisabler::global_vthread_transition_disable_count_address()));
3358   Node* global_disable = ideal.load(ideal.ctrl(), global_disable_addr, TypeInt::INT, T_INT, Compile::AliasIdxRaw, true /*require_atomic_access*/);
3359   Node* vt_disable_addr = basic_plus_adr(vt_oop, java_lang_Thread::vthread_transition_disable_count_offset());
3360   const TypePtr* vt_disable_addr_t = _gvn.type(vt_disable_addr)->is_ptr();
3361   Node* vt_disable = ideal.load(ideal.ctrl(), vt_disable_addr, TypeInt::INT, T_INT, C->get_alias_index(vt_disable_addr_t), true /*require_atomic_access*/);
3362   Node* disabled = _gvn.transform(new AddINode(global_disable, vt_disable));
3363 
3364   ideal.if_then(disabled, BoolTest::ne, ideal.ConI(0)); {
3365     sync_kit(ideal);
3366     Node* is_mount = is_final_transition ? ideal.ConI(0) : argument(1);
3367     const TypeFunc* tf = OptoRuntime::vthread_transition_Type();
3368     make_runtime_call(RC_NO_LEAF, tf, funcAddr, funcName, TypePtr::BOTTOM, vt_oop, is_mount);
3369     ideal.sync_kit(this);
3370   }
3371   ideal.end_if();
3372 
3373   final_sync(ideal);
3374   return true;
3375 }
3376 
3377 bool LibraryCallKit::inline_native_vthread_end_transition(address funcAddr, const char* funcName, bool is_first_transition) {
3378   Node* vt_oop = must_be_not_null(argument(0), true); // VirtualThread this argument
3379   IdealKit ideal(this);
3380 
3381   Node* _notify_jvmti_addr = makecon(TypeRawPtr::make((address)MountUnmountDisabler::notify_jvmti_events_address()));
3382   Node* _notify_jvmti = ideal.load(ideal.ctrl(), _notify_jvmti_addr, TypeInt::BOOL, T_BOOLEAN, Compile::AliasIdxRaw);
3383 
3384   ideal.if_then(_notify_jvmti, BoolTest::eq, ideal.ConI(1)); {
3385     sync_kit(ideal);
3386     Node* is_mount = is_first_transition ? ideal.ConI(1) : argument(1);
3387     const TypeFunc* tf = OptoRuntime::vthread_transition_Type();
3388     make_runtime_call(RC_NO_LEAF, tf, funcAddr, funcName, TypePtr::BOTTOM, vt_oop, is_mount);
3389     ideal.sync_kit(this);
3390   } ideal.else_(); {
3391     Node* thread = ideal.thread();
3392     Node* jt_addr = off_heap_plus_addr(thread, in_bytes(JavaThread::is_in_vthread_transition_offset()));
3393     Node* vt_addr = basic_plus_adr(vt_oop, java_lang_Thread::is_in_vthread_transition_offset());
3394 
3395     sync_kit(ideal);
3396     access_store_at(nullptr, jt_addr, _gvn.type(jt_addr)->is_ptr(), ideal.ConI(0), TypeInt::BOOL, T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
3397     access_store_at(nullptr, vt_addr, _gvn.type(vt_addr)->is_ptr(), ideal.ConI(0), TypeInt::BOOL, T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
3398     ideal.sync_kit(this);
3399   } ideal.end_if();
3400 
3401   final_sync(ideal);
3402   return true;
3403 }
3404 
3405 #if INCLUDE_JVMTI
3406 
3407 // Always update the is_disable_suspend bit.
3408 bool LibraryCallKit::inline_native_notify_jvmti_sync() {
3409   if (!DoJVMTIVirtualThreadTransitions) {
3410     return true;
3411   }
3412   IdealKit ideal(this);
3413 
3414   {
3415     // unconditionally update the is_disable_suspend bit in current JavaThread
3416     Node* thread = ideal.thread();
3417     Node* arg = argument(0); // argument for notification
3418     Node* addr = off_heap_plus_addr(thread, in_bytes(JavaThread::is_disable_suspend_offset()));
3419     const TypePtr *addr_type = _gvn.type(addr)->isa_ptr();
3420 
3421     sync_kit(ideal);
3422     access_store_at(nullptr, addr, addr_type, arg, _gvn.type(arg), T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
3423     ideal.sync_kit(this);
3424   }
3425   final_sync(ideal);
3426 
3427   return true;
3428 }
3429 
3430 #endif // INCLUDE_JVMTI
3431 
3432 #ifdef JFR_HAVE_INTRINSICS
3433 
3434 /**
3435  * if oop->klass != null
3436  *   // normal class
3437  *   epoch = _epoch_state ? 2 : 1
3438  *   if oop->klass->trace_id & ((epoch << META_SHIFT) | epoch)) != epoch {
3439  *     ... // enter slow path when the klass is first recorded or the epoch of JFR shifts
3440  *   }
3441  *   id = oop->klass->trace_id >> TRACE_ID_SHIFT // normal class path
3442  * else
3443  *   // primitive class
3444  *   if oop->array_klass != null
3445  *     id = (oop->array_klass->trace_id >> TRACE_ID_SHIFT) + 1 // primitive class path
3446  *   else
3447  *     id = LAST_TYPE_ID + 1 // void class path
3448  *   if (!signaled)
3449  *     signaled = true
3450  */
3451 bool LibraryCallKit::inline_native_classID() {
3452   Node* cls = argument(0);
3453 
3454   IdealKit ideal(this);
3455 #define __ ideal.
3456   IdealVariable result(ideal); __ declarations_done();
3457   Node* kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(),
3458                                                  basic_plus_adr(cls, java_lang_Class::klass_offset()),
3459                                                  TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
3460 
3461 
3462   __ if_then(kls, BoolTest::ne, null()); {
3463     Node* kls_trace_id_addr = basic_plus_adr(kls, in_bytes(KLASS_TRACE_ID_OFFSET));
3464     Node* kls_trace_id_raw = ideal.load(ideal.ctrl(), kls_trace_id_addr,TypeLong::LONG, T_LONG, Compile::AliasIdxRaw);
3465 
3466     Node* epoch_address = makecon(TypeRawPtr::make(JfrIntrinsicSupport::epoch_address()));
3467     Node* epoch = ideal.load(ideal.ctrl(), epoch_address, TypeInt::BOOL, T_BOOLEAN, Compile::AliasIdxRaw);
3468     epoch = _gvn.transform(new LShiftLNode(longcon(1), epoch));
3469     Node* mask = _gvn.transform(new LShiftLNode(epoch, intcon(META_SHIFT)));
3470     mask = _gvn.transform(new OrLNode(mask, epoch));
3471     Node* kls_trace_id_raw_and_mask = _gvn.transform(new AndLNode(kls_trace_id_raw, mask));
3472 
3473     float unlikely  = PROB_UNLIKELY(0.999);
3474     __ if_then(kls_trace_id_raw_and_mask, BoolTest::ne, epoch, unlikely); {
3475       sync_kit(ideal);
3476       make_runtime_call(RC_LEAF,
3477                         OptoRuntime::class_id_load_barrier_Type(),
3478                         CAST_FROM_FN_PTR(address, JfrIntrinsicSupport::load_barrier),
3479                         "class id load barrier",
3480                         TypePtr::BOTTOM,
3481                         kls);
3482       ideal.sync_kit(this);
3483     } __ end_if();
3484 
3485     ideal.set(result,  _gvn.transform(new URShiftLNode(kls_trace_id_raw, ideal.ConI(TRACE_ID_SHIFT))));
3486   } __ else_(); {
3487     Node* array_kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(),
3488                                                    basic_plus_adr(cls, java_lang_Class::array_klass_offset()),
3489                                                    TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
3490     __ if_then(array_kls, BoolTest::ne, null()); {
3491       Node* array_kls_trace_id_addr = basic_plus_adr(array_kls, in_bytes(KLASS_TRACE_ID_OFFSET));
3492       Node* array_kls_trace_id_raw = ideal.load(ideal.ctrl(), array_kls_trace_id_addr, TypeLong::LONG, T_LONG, Compile::AliasIdxRaw);
3493       Node* array_kls_trace_id = _gvn.transform(new URShiftLNode(array_kls_trace_id_raw, ideal.ConI(TRACE_ID_SHIFT)));
3494       ideal.set(result, _gvn.transform(new AddLNode(array_kls_trace_id, longcon(1))));
3495     } __ else_(); {
3496       // void class case
3497       ideal.set(result, longcon(LAST_TYPE_ID + 1));
3498     } __ end_if();
3499 
3500     Node* signaled_flag_address = makecon(TypeRawPtr::make(JfrIntrinsicSupport::signal_address()));
3501     Node* signaled = ideal.load(ideal.ctrl(), signaled_flag_address, TypeInt::BOOL, T_BOOLEAN, Compile::AliasIdxRaw, true, MemNode::acquire);
3502     __ if_then(signaled, BoolTest::ne, ideal.ConI(1)); {
3503       ideal.store(ideal.ctrl(), signaled_flag_address, ideal.ConI(1), T_BOOLEAN, Compile::AliasIdxRaw, MemNode::release, true);
3504     } __ end_if();
3505   } __ end_if();
3506 
3507   final_sync(ideal);
3508   set_result(ideal.value(result));
3509 #undef __
3510   return true;
3511 }
3512 
3513 //------------------------inline_native_jvm_commit------------------
3514 bool LibraryCallKit::inline_native_jvm_commit() {
3515   enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
3516 
3517   // Save input memory and i_o state.
3518   Node* input_memory_state = reset_memory();
3519   set_all_memory(input_memory_state);
3520   Node* input_io_state = i_o();
3521 
3522   // TLS.
3523   Node* tls_ptr = _gvn.transform(new ThreadLocalNode());
3524   // Jfr java buffer.
3525   Node* java_buffer_offset = _gvn.transform(AddPNode::make_off_heap(tls_ptr, MakeConX(in_bytes(JAVA_BUFFER_OFFSET_JFR))));
3526   Node* java_buffer = _gvn.transform(new LoadPNode(control(), input_memory_state, java_buffer_offset, TypePtr::BOTTOM, TypeRawPtr::NOTNULL, MemNode::unordered));
3527   Node* java_buffer_pos_offset = _gvn.transform(AddPNode::make_off_heap(java_buffer, MakeConX(in_bytes(JFR_BUFFER_POS_OFFSET))));
3528 
3529   // Load the current value of the notified field in the JfrThreadLocal.
3530   Node* notified_offset = off_heap_plus_addr(tls_ptr, in_bytes(NOTIFY_OFFSET_JFR));
3531   Node* notified = make_load(control(), notified_offset, TypeInt::BOOL, T_BOOLEAN, MemNode::unordered);
3532 
3533   // Test for notification.
3534   Node* notified_cmp = _gvn.transform(new CmpINode(notified, _gvn.intcon(1)));
3535   Node* test_notified = _gvn.transform(new BoolNode(notified_cmp, BoolTest::eq));
3536   IfNode* iff_notified = create_and_map_if(control(), test_notified, PROB_MIN, COUNT_UNKNOWN);
3537 
3538   // True branch, is notified.
3539   Node* is_notified = _gvn.transform(new IfTrueNode(iff_notified));
3540   set_control(is_notified);
3541 
3542   // Reset notified state.
3543   store_to_memory(control(), notified_offset, _gvn.intcon(0), T_BOOLEAN, MemNode::unordered);
3544   Node* notified_reset_memory = reset_memory();
3545 
3546   // 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.
3547   Node* current_pos_X = _gvn.transform(new LoadXNode(control(), input_memory_state, java_buffer_pos_offset, TypeRawPtr::NOTNULL, TypeX_X, MemNode::unordered));
3548   // Convert the machine-word to a long.
3549   Node* current_pos = ConvX2L(current_pos_X);
3550 
3551   // False branch, not notified.
3552   Node* not_notified = _gvn.transform(new IfFalseNode(iff_notified));
3553   set_control(not_notified);
3554   set_all_memory(input_memory_state);
3555 
3556   // Arg is the next position as a long.
3557   Node* arg = argument(0);
3558   // Convert long to machine-word.
3559   Node* next_pos_X = ConvL2X(arg);
3560 
3561   // Store the next_position to the underlying jfr java buffer.
3562   store_to_memory(control(), java_buffer_pos_offset, next_pos_X, LP64_ONLY(T_LONG) NOT_LP64(T_INT), MemNode::release);
3563 
3564   Node* commit_memory = reset_memory();
3565   set_all_memory(commit_memory);
3566 
3567   // 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.
3568   Node* java_buffer_flags_offset = _gvn.transform(AddPNode::make_off_heap(java_buffer, MakeConX(in_bytes(JFR_BUFFER_FLAGS_OFFSET))));
3569   Node* flags = make_load(control(), java_buffer_flags_offset, TypeInt::UBYTE, T_BYTE, MemNode::unordered);
3570   Node* lease_constant = _gvn.intcon(4);
3571 
3572   // And flags with lease constant.
3573   Node* lease = _gvn.transform(new AndINode(flags, lease_constant));
3574 
3575   // Branch on lease to conditionalize returning the leased java buffer.
3576   Node* lease_cmp = _gvn.transform(new CmpINode(lease, lease_constant));
3577   Node* test_lease = _gvn.transform(new BoolNode(lease_cmp, BoolTest::eq));
3578   IfNode* iff_lease = create_and_map_if(control(), test_lease, PROB_MIN, COUNT_UNKNOWN);
3579 
3580   // False branch, not a lease.
3581   Node* not_lease = _gvn.transform(new IfFalseNode(iff_lease));
3582 
3583   // True branch, is lease.
3584   Node* is_lease = _gvn.transform(new IfTrueNode(iff_lease));
3585   set_control(is_lease);
3586 
3587   // Make a runtime call, which can safepoint, to return the leased buffer. This updates both the JfrThreadLocal and the Java event writer oop.
3588   Node* call_return_lease = make_runtime_call(RC_NO_LEAF,
3589                                               OptoRuntime::void_void_Type(),
3590                                               SharedRuntime::jfr_return_lease(),
3591                                               "return_lease", TypePtr::BOTTOM);
3592   Node* call_return_lease_control = _gvn.transform(new ProjNode(call_return_lease, TypeFunc::Control));
3593 
3594   RegionNode* lease_compare_rgn = new RegionNode(PATH_LIMIT);
3595   record_for_igvn(lease_compare_rgn);
3596   PhiNode* lease_compare_mem = new PhiNode(lease_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3597   record_for_igvn(lease_compare_mem);
3598   PhiNode* lease_compare_io = new PhiNode(lease_compare_rgn, Type::ABIO);
3599   record_for_igvn(lease_compare_io);
3600   PhiNode* lease_result_value = new PhiNode(lease_compare_rgn, TypeLong::LONG);
3601   record_for_igvn(lease_result_value);
3602 
3603   // Update control and phi nodes.
3604   lease_compare_rgn->init_req(_true_path, call_return_lease_control);
3605   lease_compare_rgn->init_req(_false_path, not_lease);
3606 
3607   lease_compare_mem->init_req(_true_path, reset_memory());
3608   lease_compare_mem->init_req(_false_path, commit_memory);
3609 
3610   lease_compare_io->init_req(_true_path, i_o());
3611   lease_compare_io->init_req(_false_path, input_io_state);
3612 
3613   lease_result_value->init_req(_true_path, _gvn.longcon(0)); // if the lease was returned, return 0L.
3614   lease_result_value->init_req(_false_path, arg); // if not lease, return new updated position.
3615 
3616   RegionNode* result_rgn = new RegionNode(PATH_LIMIT);
3617   PhiNode* result_mem = new PhiNode(result_rgn, Type::MEMORY, TypePtr::BOTTOM);
3618   PhiNode* result_io = new PhiNode(result_rgn, Type::ABIO);
3619   PhiNode* result_value = new PhiNode(result_rgn, TypeLong::LONG);
3620 
3621   // Update control and phi nodes.
3622   result_rgn->init_req(_true_path, is_notified);
3623   result_rgn->init_req(_false_path, _gvn.transform(lease_compare_rgn));
3624 
3625   result_mem->init_req(_true_path, notified_reset_memory);
3626   result_mem->init_req(_false_path, _gvn.transform(lease_compare_mem));
3627 
3628   result_io->init_req(_true_path, input_io_state);
3629   result_io->init_req(_false_path, _gvn.transform(lease_compare_io));
3630 
3631   result_value->init_req(_true_path, current_pos);
3632   result_value->init_req(_false_path, _gvn.transform(lease_result_value));
3633 
3634   // Set output state.
3635   set_control(_gvn.transform(result_rgn));
3636   set_all_memory(_gvn.transform(result_mem));
3637   set_i_o(_gvn.transform(result_io));
3638   set_result(result_rgn, result_value);
3639   return true;
3640 }
3641 
3642 /*
3643  * The intrinsic is a model of this pseudo-code:
3644  *
3645  * JfrThreadLocal* const tl = Thread::jfr_thread_local()
3646  * jobject h_event_writer = tl->java_event_writer();
3647  * if (h_event_writer == nullptr) {
3648  *   return nullptr;
3649  * }
3650  * oop threadObj = Thread::threadObj();
3651  * oop vthread = java_lang_Thread::vthread(threadObj);
3652  * traceid tid;
3653  * bool pinVirtualThread;
3654  * bool excluded;
3655  * if (vthread != threadObj) {  // i.e. current thread is virtual
3656  *   tid = java_lang_Thread::tid(vthread);
3657  *   u2 vthread_epoch_raw = java_lang_Thread::jfr_epoch(vthread);
3658  *   pinVirtualThread = VMContinuations;
3659  *   excluded = vthread_epoch_raw & excluded_mask;
3660  *   if (!excluded) {
3661  *     traceid current_epoch = JfrTraceIdEpoch::current_generation();
3662  *     u2 vthread_epoch = vthread_epoch_raw & epoch_mask;
3663  *     if (vthread_epoch != current_epoch) {
3664  *       write_checkpoint();
3665  *     }
3666  *   }
3667  * } else {
3668  *   tid = java_lang_Thread::tid(threadObj);
3669  *   u2 thread_epoch_raw = java_lang_Thread::jfr_epoch(threadObj);
3670  *   pinVirtualThread = false;
3671  *   excluded = thread_epoch_raw & excluded_mask;
3672  * }
3673  * oop event_writer = JNIHandles::resolve_non_null(h_event_writer);
3674  * traceid tid_in_event_writer = getField(event_writer, "threadID");
3675  * if (tid_in_event_writer != tid) {
3676  *   setField(event_writer, "pinVirtualThread", pinVirtualThread);
3677  *   setField(event_writer, "excluded", excluded);
3678  *   setField(event_writer, "threadID", tid);
3679  * }
3680  * return event_writer
3681  */
3682 bool LibraryCallKit::inline_native_getEventWriter() {
3683   enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
3684 
3685   // Save input memory and i_o state.
3686   Node* input_memory_state = reset_memory();
3687   set_all_memory(input_memory_state);
3688   Node* input_io_state = i_o();
3689 
3690   // The most significant bit of the u2 is used to denote thread exclusion
3691   Node* excluded_shift = _gvn.intcon(15);
3692   Node* excluded_mask = _gvn.intcon(1 << 15);
3693   // The epoch generation is the range [1-32767]
3694   Node* epoch_mask = _gvn.intcon(32767);
3695 
3696   // TLS
3697   Node* tls_ptr = _gvn.transform(new ThreadLocalNode());
3698 
3699   // Load the address of java event writer jobject handle from the jfr_thread_local structure.
3700   Node* jobj_ptr = off_heap_plus_addr(tls_ptr, in_bytes(THREAD_LOCAL_WRITER_OFFSET_JFR));
3701 
3702   // Load the eventwriter jobject handle.
3703   Node* jobj = make_load(control(), jobj_ptr, TypeRawPtr::BOTTOM, T_ADDRESS, MemNode::unordered);
3704 
3705   // Null check the jobject handle.
3706   Node* jobj_cmp_null = _gvn.transform(new CmpPNode(jobj, null()));
3707   Node* test_jobj_not_equal_null = _gvn.transform(new BoolNode(jobj_cmp_null, BoolTest::ne));
3708   IfNode* iff_jobj_not_equal_null = create_and_map_if(control(), test_jobj_not_equal_null, PROB_MAX, COUNT_UNKNOWN);
3709 
3710   // False path, jobj is null.
3711   Node* jobj_is_null = _gvn.transform(new IfFalseNode(iff_jobj_not_equal_null));
3712 
3713   // True path, jobj is not null.
3714   Node* jobj_is_not_null = _gvn.transform(new IfTrueNode(iff_jobj_not_equal_null));
3715 
3716   set_control(jobj_is_not_null);
3717 
3718   // Load the threadObj for the CarrierThread.
3719   Node* threadObj = generate_current_thread(tls_ptr);
3720 
3721   // Load the vthread.
3722   Node* vthread = generate_virtual_thread(tls_ptr);
3723 
3724   // If vthread != threadObj, this is a virtual thread.
3725   Node* vthread_cmp_threadObj = _gvn.transform(new CmpPNode(vthread, threadObj));
3726   Node* test_vthread_not_equal_threadObj = _gvn.transform(new BoolNode(vthread_cmp_threadObj, BoolTest::ne));
3727   IfNode* iff_vthread_not_equal_threadObj =
3728     create_and_map_if(jobj_is_not_null, test_vthread_not_equal_threadObj, PROB_FAIR, COUNT_UNKNOWN);
3729 
3730   // False branch, fallback to threadObj.
3731   Node* vthread_equal_threadObj = _gvn.transform(new IfFalseNode(iff_vthread_not_equal_threadObj));
3732   set_control(vthread_equal_threadObj);
3733 
3734   // Load the tid field from the vthread object.
3735   Node* thread_obj_tid = load_field_from_object(threadObj, "tid", "J");
3736 
3737   // Load the raw epoch value from the threadObj.
3738   Node* threadObj_epoch_offset = basic_plus_adr(threadObj, java_lang_Thread::jfr_epoch_offset());
3739   Node* threadObj_epoch_raw = access_load_at(threadObj, threadObj_epoch_offset,
3740                                              _gvn.type(threadObj_epoch_offset)->isa_ptr(),
3741                                              TypeInt::CHAR, T_CHAR,
3742                                              IN_HEAP | MO_UNORDERED | C2_MISMATCHED | C2_CONTROL_DEPENDENT_LOAD);
3743 
3744   // Mask off the excluded information from the epoch.
3745   Node * threadObj_is_excluded = _gvn.transform(new AndINode(threadObj_epoch_raw, excluded_mask));
3746 
3747   // True branch, this is a virtual thread.
3748   Node* vthread_not_equal_threadObj = _gvn.transform(new IfTrueNode(iff_vthread_not_equal_threadObj));
3749   set_control(vthread_not_equal_threadObj);
3750 
3751   // Load the tid field from the vthread object.
3752   Node* vthread_tid = load_field_from_object(vthread, "tid", "J");
3753 
3754   // Continuation support determines if a virtual thread should be pinned.
3755   Node* global_addr = makecon(TypeRawPtr::make((address)&VMContinuations));
3756   Node* continuation_support = make_load(control(), global_addr, TypeInt::BOOL, T_BOOLEAN, MemNode::unordered);
3757 
3758   // Load the raw epoch value from the vthread.
3759   Node* vthread_epoch_offset = basic_plus_adr(vthread, java_lang_Thread::jfr_epoch_offset());
3760   Node* vthread_epoch_raw = access_load_at(vthread, vthread_epoch_offset, _gvn.type(vthread_epoch_offset)->is_ptr(),
3761                                            TypeInt::CHAR, T_CHAR,
3762                                            IN_HEAP | MO_UNORDERED | C2_MISMATCHED | C2_CONTROL_DEPENDENT_LOAD);
3763 
3764   // Mask off the excluded information from the epoch.
3765   Node * vthread_is_excluded = _gvn.transform(new AndINode(vthread_epoch_raw, excluded_mask));
3766 
3767   // Branch on excluded to conditionalize updating the epoch for the virtual thread.
3768   Node* is_excluded_cmp = _gvn.transform(new CmpINode(vthread_is_excluded, excluded_mask));
3769   Node* test_not_excluded = _gvn.transform(new BoolNode(is_excluded_cmp, BoolTest::ne));
3770   IfNode* iff_not_excluded = create_and_map_if(control(), test_not_excluded, PROB_MAX, COUNT_UNKNOWN);
3771 
3772   // False branch, vthread is excluded, no need to write epoch info.
3773   Node* excluded = _gvn.transform(new IfFalseNode(iff_not_excluded));
3774 
3775   // True branch, vthread is included, update epoch info.
3776   Node* included = _gvn.transform(new IfTrueNode(iff_not_excluded));
3777   set_control(included);
3778 
3779   // Get epoch value.
3780   Node* epoch = _gvn.transform(new AndINode(vthread_epoch_raw, epoch_mask));
3781 
3782   // Load the current epoch generation. The value is unsigned 16-bit, so we type it as T_CHAR.
3783   Node* epoch_generation_address = makecon(TypeRawPtr::make(JfrIntrinsicSupport::epoch_generation_address()));
3784   Node* current_epoch_generation = make_load(control(), epoch_generation_address, TypeInt::CHAR, T_CHAR, MemNode::unordered);
3785 
3786   // Compare the epoch in the vthread to the current epoch generation.
3787   Node* const epoch_cmp = _gvn.transform(new CmpUNode(current_epoch_generation, epoch));
3788   Node* test_epoch_not_equal = _gvn.transform(new BoolNode(epoch_cmp, BoolTest::ne));
3789   IfNode* iff_epoch_not_equal = create_and_map_if(control(), test_epoch_not_equal, PROB_FAIR, COUNT_UNKNOWN);
3790 
3791   // False path, epoch is equal, checkpoint information is valid.
3792   Node* epoch_is_equal = _gvn.transform(new IfFalseNode(iff_epoch_not_equal));
3793 
3794   // True path, epoch is not equal, write a checkpoint for the vthread.
3795   Node* epoch_is_not_equal = _gvn.transform(new IfTrueNode(iff_epoch_not_equal));
3796 
3797   set_control(epoch_is_not_equal);
3798 
3799   // Make a runtime call, which can safepoint, to write a checkpoint for the vthread for this epoch.
3800   // The call also updates the native thread local thread id and the vthread with the current epoch.
3801   Node* call_write_checkpoint = make_runtime_call(RC_NO_LEAF,
3802                                                   OptoRuntime::jfr_write_checkpoint_Type(),
3803                                                   SharedRuntime::jfr_write_checkpoint(),
3804                                                   "write_checkpoint", TypePtr::BOTTOM);
3805   Node* call_write_checkpoint_control = _gvn.transform(new ProjNode(call_write_checkpoint, TypeFunc::Control));
3806 
3807   // vthread epoch != current epoch
3808   RegionNode* epoch_compare_rgn = new RegionNode(PATH_LIMIT);
3809   record_for_igvn(epoch_compare_rgn);
3810   PhiNode* epoch_compare_mem = new PhiNode(epoch_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3811   record_for_igvn(epoch_compare_mem);
3812   PhiNode* epoch_compare_io = new PhiNode(epoch_compare_rgn, Type::ABIO);
3813   record_for_igvn(epoch_compare_io);
3814 
3815   // Update control and phi nodes.
3816   epoch_compare_rgn->init_req(_true_path, call_write_checkpoint_control);
3817   epoch_compare_rgn->init_req(_false_path, epoch_is_equal);
3818   epoch_compare_mem->init_req(_true_path, reset_memory());
3819   epoch_compare_mem->init_req(_false_path, input_memory_state);
3820   epoch_compare_io->init_req(_true_path, i_o());
3821   epoch_compare_io->init_req(_false_path, input_io_state);
3822 
3823   // excluded != true
3824   RegionNode* exclude_compare_rgn = new RegionNode(PATH_LIMIT);
3825   record_for_igvn(exclude_compare_rgn);
3826   PhiNode* exclude_compare_mem = new PhiNode(exclude_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3827   record_for_igvn(exclude_compare_mem);
3828   PhiNode* exclude_compare_io = new PhiNode(exclude_compare_rgn, Type::ABIO);
3829   record_for_igvn(exclude_compare_io);
3830 
3831   // Update control and phi nodes.
3832   exclude_compare_rgn->init_req(_true_path, _gvn.transform(epoch_compare_rgn));
3833   exclude_compare_rgn->init_req(_false_path, excluded);
3834   exclude_compare_mem->init_req(_true_path, _gvn.transform(epoch_compare_mem));
3835   exclude_compare_mem->init_req(_false_path, input_memory_state);
3836   exclude_compare_io->init_req(_true_path, _gvn.transform(epoch_compare_io));
3837   exclude_compare_io->init_req(_false_path, input_io_state);
3838 
3839   // vthread != threadObj
3840   RegionNode* vthread_compare_rgn = new RegionNode(PATH_LIMIT);
3841   record_for_igvn(vthread_compare_rgn);
3842   PhiNode* vthread_compare_mem = new PhiNode(vthread_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3843   PhiNode* vthread_compare_io = new PhiNode(vthread_compare_rgn, Type::ABIO);
3844   record_for_igvn(vthread_compare_io);
3845   PhiNode* tid = new PhiNode(vthread_compare_rgn, TypeLong::LONG);
3846   record_for_igvn(tid);
3847   PhiNode* exclusion = new PhiNode(vthread_compare_rgn, TypeInt::CHAR);
3848   record_for_igvn(exclusion);
3849   PhiNode* pinVirtualThread = new PhiNode(vthread_compare_rgn, TypeInt::BOOL);
3850   record_for_igvn(pinVirtualThread);
3851 
3852   // Update control and phi nodes.
3853   vthread_compare_rgn->init_req(_true_path, _gvn.transform(exclude_compare_rgn));
3854   vthread_compare_rgn->init_req(_false_path, vthread_equal_threadObj);
3855   vthread_compare_mem->init_req(_true_path, _gvn.transform(exclude_compare_mem));
3856   vthread_compare_mem->init_req(_false_path, input_memory_state);
3857   vthread_compare_io->init_req(_true_path, _gvn.transform(exclude_compare_io));
3858   vthread_compare_io->init_req(_false_path, input_io_state);
3859   tid->init_req(_true_path, vthread_tid);
3860   tid->init_req(_false_path, thread_obj_tid);
3861   exclusion->init_req(_true_path, vthread_is_excluded);
3862   exclusion->init_req(_false_path, threadObj_is_excluded);
3863   pinVirtualThread->init_req(_true_path, continuation_support);
3864   pinVirtualThread->init_req(_false_path, _gvn.intcon(0));
3865 
3866   // Update branch state.
3867   set_control(_gvn.transform(vthread_compare_rgn));
3868   set_all_memory(_gvn.transform(vthread_compare_mem));
3869   set_i_o(_gvn.transform(vthread_compare_io));
3870 
3871   // Load the event writer oop by dereferencing the jobject handle.
3872   ciKlass* klass_EventWriter = env()->find_system_klass(ciSymbol::make("jdk/jfr/internal/event/EventWriter"));
3873   assert(klass_EventWriter->is_loaded(), "invariant");
3874   ciInstanceKlass* const instklass_EventWriter = klass_EventWriter->as_instance_klass();
3875   const TypeKlassPtr* const aklass = TypeKlassPtr::make(instklass_EventWriter);
3876   const TypeOopPtr* const xtype = aklass->as_instance_type();
3877   Node* jobj_untagged = _gvn.transform(AddPNode::make_off_heap(jobj, _gvn.MakeConX(-JNIHandles::TypeTag::global)));
3878   Node* event_writer = access_load(jobj_untagged, xtype, T_OBJECT, IN_NATIVE | C2_CONTROL_DEPENDENT_LOAD);
3879 
3880   // Load the current thread id from the event writer object.
3881   Node* const event_writer_tid = load_field_from_object(event_writer, "threadID", "J");
3882   // Get the field offset to, conditionally, store an updated tid value later.
3883   Node* const event_writer_tid_field = field_address_from_object(event_writer, "threadID", "J", false);
3884   // Get the field offset to, conditionally, store an updated exclusion value later.
3885   Node* const event_writer_excluded_field = field_address_from_object(event_writer, "excluded", "Z", false);
3886   // Get the field offset to, conditionally, store an updated pinVirtualThread value later.
3887   Node* const event_writer_pin_field = field_address_from_object(event_writer, "pinVirtualThread", "Z", false);
3888 
3889   RegionNode* event_writer_tid_compare_rgn = new RegionNode(PATH_LIMIT);
3890   record_for_igvn(event_writer_tid_compare_rgn);
3891   PhiNode* event_writer_tid_compare_mem = new PhiNode(event_writer_tid_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3892   record_for_igvn(event_writer_tid_compare_mem);
3893   PhiNode* event_writer_tid_compare_io = new PhiNode(event_writer_tid_compare_rgn, Type::ABIO);
3894   record_for_igvn(event_writer_tid_compare_io);
3895 
3896   // Compare the current tid from the thread object to what is currently stored in the event writer object.
3897   Node* const tid_cmp = _gvn.transform(new CmpLNode(event_writer_tid, _gvn.transform(tid)));
3898   Node* test_tid_not_equal = _gvn.transform(new BoolNode(tid_cmp, BoolTest::ne));
3899   IfNode* iff_tid_not_equal = create_and_map_if(_gvn.transform(vthread_compare_rgn), test_tid_not_equal, PROB_FAIR, COUNT_UNKNOWN);
3900 
3901   // False path, tids are the same.
3902   Node* tid_is_equal = _gvn.transform(new IfFalseNode(iff_tid_not_equal));
3903 
3904   // True path, tid is not equal, need to update the tid in the event writer.
3905   Node* tid_is_not_equal = _gvn.transform(new IfTrueNode(iff_tid_not_equal));
3906   record_for_igvn(tid_is_not_equal);
3907 
3908   // Store the pin state to the event writer.
3909   store_to_memory(tid_is_not_equal, event_writer_pin_field, _gvn.transform(pinVirtualThread), T_BOOLEAN, MemNode::unordered);
3910 
3911   // Store the exclusion state to the event writer.
3912   Node* excluded_bool = _gvn.transform(new URShiftINode(_gvn.transform(exclusion), excluded_shift));
3913   store_to_memory(tid_is_not_equal, event_writer_excluded_field, excluded_bool, T_BOOLEAN, MemNode::unordered);
3914 
3915   // Store the tid to the event writer.
3916   store_to_memory(tid_is_not_equal, event_writer_tid_field, tid, T_LONG, MemNode::unordered);
3917 
3918   // Update control and phi nodes.
3919   event_writer_tid_compare_rgn->init_req(_true_path, tid_is_not_equal);
3920   event_writer_tid_compare_rgn->init_req(_false_path, tid_is_equal);
3921   event_writer_tid_compare_mem->init_req(_true_path, reset_memory());
3922   event_writer_tid_compare_mem->init_req(_false_path, _gvn.transform(vthread_compare_mem));
3923   event_writer_tid_compare_io->init_req(_true_path, i_o());
3924   event_writer_tid_compare_io->init_req(_false_path, _gvn.transform(vthread_compare_io));
3925 
3926   // Result of top level CFG, Memory, IO and Value.
3927   RegionNode* result_rgn = new RegionNode(PATH_LIMIT);
3928   PhiNode* result_mem = new PhiNode(result_rgn, Type::MEMORY, TypePtr::BOTTOM);
3929   PhiNode* result_io = new PhiNode(result_rgn, Type::ABIO);
3930   PhiNode* result_value = new PhiNode(result_rgn, TypeInstPtr::BOTTOM);
3931 
3932   // Result control.
3933   result_rgn->init_req(_true_path, _gvn.transform(event_writer_tid_compare_rgn));
3934   result_rgn->init_req(_false_path, jobj_is_null);
3935 
3936   // Result memory.
3937   result_mem->init_req(_true_path, _gvn.transform(event_writer_tid_compare_mem));
3938   result_mem->init_req(_false_path, input_memory_state);
3939 
3940   // Result IO.
3941   result_io->init_req(_true_path, _gvn.transform(event_writer_tid_compare_io));
3942   result_io->init_req(_false_path, input_io_state);
3943 
3944   // Result value.
3945   result_value->init_req(_true_path, event_writer); // return event writer oop
3946   result_value->init_req(_false_path, null()); // return null
3947 
3948   // Set output state.
3949   set_control(_gvn.transform(result_rgn));
3950   set_all_memory(_gvn.transform(result_mem));
3951   set_i_o(_gvn.transform(result_io));
3952   set_result(result_rgn, result_value);
3953   return true;
3954 }
3955 
3956 /*
3957  * The intrinsic is a model of this pseudo-code:
3958  *
3959  * JfrThreadLocal* const tl = thread->jfr_thread_local();
3960  * if (carrierThread != thread) { // is virtual thread
3961  *   const u2 vthread_epoch_raw = java_lang_Thread::jfr_epoch(thread);
3962  *   bool excluded = vthread_epoch_raw & excluded_mask;
3963  *   AtomicAccess::store(&tl->_contextual_tid, java_lang_Thread::tid(thread));
3964  *   AtomicAccess::store(&tl->_contextual_thread_excluded, is_excluded);
3965  *   if (!excluded) {
3966  *     const u2 vthread_epoch = vthread_epoch_raw & epoch_mask;
3967  *     AtomicAccess::store(&tl->_vthread_epoch, vthread_epoch);
3968  *   }
3969  *   AtomicAccess::release_store(&tl->_vthread, true);
3970  *   return;
3971  * }
3972  * AtomicAccess::release_store(&tl->_vthread, false);
3973  */
3974 void LibraryCallKit::extend_setCurrentThread(Node* jt, Node* thread) {
3975   enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
3976 
3977   Node* input_memory_state = reset_memory();
3978   set_all_memory(input_memory_state);
3979 
3980   // The most significant bit of the u2 is used to denote thread exclusion
3981   Node* excluded_mask = _gvn.intcon(1 << 15);
3982   // The epoch generation is the range [1-32767]
3983   Node* epoch_mask = _gvn.intcon(32767);
3984 
3985   Node* const carrierThread = generate_current_thread(jt);
3986   // If thread != carrierThread, this is a virtual thread.
3987   Node* thread_cmp_carrierThread = _gvn.transform(new CmpPNode(thread, carrierThread));
3988   Node* test_thread_not_equal_carrierThread = _gvn.transform(new BoolNode(thread_cmp_carrierThread, BoolTest::ne));
3989   IfNode* iff_thread_not_equal_carrierThread =
3990     create_and_map_if(control(), test_thread_not_equal_carrierThread, PROB_FAIR, COUNT_UNKNOWN);
3991 
3992   Node* vthread_offset = off_heap_plus_addr(jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_OFFSET_JFR));
3993 
3994   // False branch, is carrierThread.
3995   Node* thread_equal_carrierThread = _gvn.transform(new IfFalseNode(iff_thread_not_equal_carrierThread));
3996   // Store release
3997   Node* vthread_false_memory = store_to_memory(thread_equal_carrierThread, vthread_offset, _gvn.intcon(0), T_BOOLEAN, MemNode::release, true);
3998 
3999   set_all_memory(input_memory_state);
4000 
4001   // True branch, is virtual thread.
4002   Node* thread_not_equal_carrierThread = _gvn.transform(new IfTrueNode(iff_thread_not_equal_carrierThread));
4003   set_control(thread_not_equal_carrierThread);
4004 
4005   // Load the raw epoch value from the vthread.
4006   Node* epoch_offset = basic_plus_adr(thread, java_lang_Thread::jfr_epoch_offset());
4007   Node* epoch_raw = access_load_at(thread, epoch_offset, _gvn.type(epoch_offset)->is_ptr(), TypeInt::CHAR, T_CHAR,
4008                                    IN_HEAP | MO_UNORDERED | C2_MISMATCHED | C2_CONTROL_DEPENDENT_LOAD);
4009 
4010   // Mask off the excluded information from the epoch.
4011   Node * const is_excluded = _gvn.transform(new AndINode(epoch_raw, excluded_mask));
4012 
4013   // Load the tid field from the thread.
4014   Node* tid = load_field_from_object(thread, "tid", "J");
4015 
4016   // Store the vthread tid to the jfr thread local.
4017   Node* thread_id_offset = off_heap_plus_addr(jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_ID_OFFSET_JFR));
4018   Node* tid_memory = store_to_memory(control(), thread_id_offset, tid, T_LONG, MemNode::unordered, true);
4019 
4020   // Branch is_excluded to conditionalize updating the epoch .
4021   Node* excluded_cmp = _gvn.transform(new CmpINode(is_excluded, excluded_mask));
4022   Node* test_excluded = _gvn.transform(new BoolNode(excluded_cmp, BoolTest::eq));
4023   IfNode* iff_excluded = create_and_map_if(control(), test_excluded, PROB_MIN, COUNT_UNKNOWN);
4024 
4025   // True branch, vthread is excluded, no need to write epoch info.
4026   Node* excluded = _gvn.transform(new IfTrueNode(iff_excluded));
4027   set_control(excluded);
4028   Node* vthread_is_excluded = _gvn.intcon(1);
4029 
4030   // False branch, vthread is included, update epoch info.
4031   Node* included = _gvn.transform(new IfFalseNode(iff_excluded));
4032   set_control(included);
4033   Node* vthread_is_included = _gvn.intcon(0);
4034 
4035   // Get epoch value.
4036   Node* epoch = _gvn.transform(new AndINode(epoch_raw, epoch_mask));
4037 
4038   // Store the vthread epoch to the jfr thread local.
4039   Node* vthread_epoch_offset = off_heap_plus_addr(jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_EPOCH_OFFSET_JFR));
4040   Node* included_memory = store_to_memory(control(), vthread_epoch_offset, epoch, T_CHAR, MemNode::unordered, true);
4041 
4042   RegionNode* excluded_rgn = new RegionNode(PATH_LIMIT);
4043   record_for_igvn(excluded_rgn);
4044   PhiNode* excluded_mem = new PhiNode(excluded_rgn, Type::MEMORY, TypePtr::BOTTOM);
4045   record_for_igvn(excluded_mem);
4046   PhiNode* exclusion = new PhiNode(excluded_rgn, TypeInt::BOOL);
4047   record_for_igvn(exclusion);
4048 
4049   // Merge the excluded control and memory.
4050   excluded_rgn->init_req(_true_path, excluded);
4051   excluded_rgn->init_req(_false_path, included);
4052   excluded_mem->init_req(_true_path, tid_memory);
4053   excluded_mem->init_req(_false_path, included_memory);
4054   exclusion->init_req(_true_path, vthread_is_excluded);
4055   exclusion->init_req(_false_path, vthread_is_included);
4056 
4057   // Set intermediate state.
4058   set_control(_gvn.transform(excluded_rgn));
4059   set_all_memory(excluded_mem);
4060 
4061   // Store the vthread exclusion state to the jfr thread local.
4062   Node* thread_local_excluded_offset = off_heap_plus_addr(jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_EXCLUDED_OFFSET_JFR));
4063   store_to_memory(control(), thread_local_excluded_offset, _gvn.transform(exclusion), T_BOOLEAN, MemNode::unordered, true);
4064 
4065   // Store release
4066   Node * vthread_true_memory = store_to_memory(control(), vthread_offset, _gvn.intcon(1), T_BOOLEAN, MemNode::release, true);
4067 
4068   RegionNode* thread_compare_rgn = new RegionNode(PATH_LIMIT);
4069   record_for_igvn(thread_compare_rgn);
4070   PhiNode* thread_compare_mem = new PhiNode(thread_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
4071   record_for_igvn(thread_compare_mem);
4072   PhiNode* vthread = new PhiNode(thread_compare_rgn, TypeInt::BOOL);
4073   record_for_igvn(vthread);
4074 
4075   // Merge the thread_compare control and memory.
4076   thread_compare_rgn->init_req(_true_path, control());
4077   thread_compare_rgn->init_req(_false_path, thread_equal_carrierThread);
4078   thread_compare_mem->init_req(_true_path, vthread_true_memory);
4079   thread_compare_mem->init_req(_false_path, vthread_false_memory);
4080 
4081   // Set output state.
4082   set_control(_gvn.transform(thread_compare_rgn));
4083   set_all_memory(_gvn.transform(thread_compare_mem));
4084 }
4085 
4086 #endif // JFR_HAVE_INTRINSICS
4087 
4088 //------------------------inline_native_currentCarrierThread------------------
4089 bool LibraryCallKit::inline_native_currentCarrierThread() {
4090   Node* junk = nullptr;
4091   set_result(generate_current_thread(junk));
4092   return true;
4093 }
4094 
4095 //------------------------inline_native_currentThread------------------
4096 bool LibraryCallKit::inline_native_currentThread() {
4097   Node* junk = nullptr;
4098   set_result(generate_virtual_thread(junk));
4099   return true;
4100 }
4101 
4102 //------------------------inline_native_setVthread------------------
4103 bool LibraryCallKit::inline_native_setCurrentThread() {
4104   assert(C->method()->changes_current_thread(),
4105          "method changes current Thread but is not annotated ChangesCurrentThread");
4106   Node* arr = argument(1);
4107   Node* thread = _gvn.transform(new ThreadLocalNode());
4108   Node* p = off_heap_plus_addr(thread, in_bytes(JavaThread::vthread_offset()));
4109   Node* thread_obj_handle
4110     = make_load(nullptr, p, p->bottom_type()->is_ptr(), T_OBJECT, MemNode::unordered);
4111   const TypePtr *adr_type = _gvn.type(thread_obj_handle)->isa_ptr();
4112   access_store_at(nullptr, thread_obj_handle, adr_type, arr, _gvn.type(arr), T_OBJECT, IN_NATIVE | MO_UNORDERED);
4113 
4114   // Change the _monitor_owner_id of the JavaThread
4115   Node* tid = load_field_from_object(arr, "tid", "J");
4116   Node* monitor_owner_id_offset = off_heap_plus_addr(thread, in_bytes(JavaThread::monitor_owner_id_offset()));
4117   store_to_memory(control(), monitor_owner_id_offset, tid, T_LONG, MemNode::unordered, true);
4118 
4119   JFR_ONLY(extend_setCurrentThread(thread, arr);)
4120   return true;
4121 }
4122 
4123 const Type* LibraryCallKit::scopedValueCache_type() {
4124   ciKlass* objects_klass = ciObjArrayKlass::make(env()->Object_klass());
4125   const TypeOopPtr* etype = TypeOopPtr::make_from_klass(env()->Object_klass());
4126   const TypeAry* arr0 = TypeAry::make(etype, TypeInt::POS, /* stable= */ false, /* flat= */ false, /* not_flat= */ true, /* not_null_free= */ true, true);
4127 
4128   // Because we create the scopedValue cache lazily we have to make the
4129   // type of the result BotPTR.
4130   bool xk = etype->klass_is_exact();
4131   const Type* objects_type = TypeAryPtr::make(TypePtr::BotPTR, arr0, objects_klass, xk, TypeAryPtr::Offset(0));
4132   return objects_type;
4133 }
4134 
4135 Node* LibraryCallKit::scopedValueCache_helper() {
4136   Node* thread = _gvn.transform(new ThreadLocalNode());
4137   Node* p = off_heap_plus_addr(thread, in_bytes(JavaThread::scopedValueCache_offset()));
4138   // We cannot use immutable_memory() because we might flip onto a
4139   // different carrier thread, at which point we'll need to use that
4140   // carrier thread's cache.
4141   // return _gvn.transform(LoadNode::make(_gvn, nullptr, immutable_memory(), p, p->bottom_type()->is_ptr(),
4142   //       TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered));
4143   return make_load(nullptr, p, p->bottom_type()->is_ptr(), T_ADDRESS, MemNode::unordered);
4144 }
4145 
4146 //------------------------inline_native_scopedValueCache------------------
4147 bool LibraryCallKit::inline_native_scopedValueCache() {
4148   Node* cache_obj_handle = scopedValueCache_helper();
4149   const Type* objects_type = scopedValueCache_type();
4150   set_result(access_load(cache_obj_handle, objects_type, T_OBJECT, IN_NATIVE));
4151 
4152   return true;
4153 }
4154 
4155 //------------------------inline_native_setScopedValueCache------------------
4156 bool LibraryCallKit::inline_native_setScopedValueCache() {
4157   Node* arr = argument(0);
4158   Node* cache_obj_handle = scopedValueCache_helper();
4159   const Type* objects_type = scopedValueCache_type();
4160 
4161   const TypePtr *adr_type = _gvn.type(cache_obj_handle)->isa_ptr();
4162   access_store_at(nullptr, cache_obj_handle, adr_type, arr, objects_type, T_OBJECT, IN_NATIVE | MO_UNORDERED);
4163 
4164   return true;
4165 }
4166 
4167 //------------------------inline_native_Continuation_pin and unpin-----------
4168 
4169 // Shared implementation routine for both pin and unpin.
4170 bool LibraryCallKit::inline_native_Continuation_pinning(bool unpin) {
4171   enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
4172 
4173   // Save input memory.
4174   Node* input_memory_state = reset_memory();
4175   set_all_memory(input_memory_state);
4176 
4177   // TLS
4178   Node* tls_ptr = _gvn.transform(new ThreadLocalNode());
4179   Node* last_continuation_offset = off_heap_plus_addr(tls_ptr, in_bytes(JavaThread::cont_entry_offset()));
4180   Node* last_continuation = make_load(control(), last_continuation_offset, last_continuation_offset->get_ptr_type(), T_ADDRESS, MemNode::unordered);
4181 
4182   // Null check the last continuation object.
4183   Node* continuation_cmp_null = _gvn.transform(new CmpPNode(last_continuation, null()));
4184   Node* test_continuation_not_equal_null = _gvn.transform(new BoolNode(continuation_cmp_null, BoolTest::ne));
4185   IfNode* iff_continuation_not_equal_null = create_and_map_if(control(), test_continuation_not_equal_null, PROB_MAX, COUNT_UNKNOWN);
4186 
4187   // False path, last continuation is null.
4188   Node* continuation_is_null = _gvn.transform(new IfFalseNode(iff_continuation_not_equal_null));
4189 
4190   // True path, last continuation is not null.
4191   Node* continuation_is_not_null = _gvn.transform(new IfTrueNode(iff_continuation_not_equal_null));
4192 
4193   set_control(continuation_is_not_null);
4194 
4195   // Load the pin count from the last continuation.
4196   Node* pin_count_offset = off_heap_plus_addr(last_continuation, in_bytes(ContinuationEntry::pin_count_offset()));
4197   Node* pin_count = make_load(control(), pin_count_offset, TypeInt::INT, T_INT, MemNode::unordered);
4198 
4199   // The loaded pin count is compared against a context specific rhs for over/underflow detection.
4200   Node* pin_count_rhs;
4201   if (unpin) {
4202     pin_count_rhs = _gvn.intcon(0);
4203   } else {
4204     pin_count_rhs = _gvn.intcon(UINT32_MAX);
4205   }
4206   Node* pin_count_cmp = _gvn.transform(new CmpUNode(pin_count, pin_count_rhs));
4207   Node* test_pin_count_over_underflow = _gvn.transform(new BoolNode(pin_count_cmp, BoolTest::eq));
4208   IfNode* iff_pin_count_over_underflow = create_and_map_if(control(), test_pin_count_over_underflow, PROB_MIN, COUNT_UNKNOWN);
4209 
4210   // True branch, pin count over/underflow.
4211   Node* pin_count_over_underflow = _gvn.transform(new IfTrueNode(iff_pin_count_over_underflow));
4212   {
4213     // Trap (but not deoptimize (Action_none)) and continue in the interpreter
4214     // which will throw IllegalStateException for pin count over/underflow.
4215     // No memory changed so far - we can use memory create by reset_memory()
4216     // at the beginning of this intrinsic. No need to call reset_memory() again.
4217     PreserveJVMState pjvms(this);
4218     set_control(pin_count_over_underflow);
4219     uncommon_trap(Deoptimization::Reason_intrinsic,
4220                   Deoptimization::Action_none);
4221     assert(stopped(), "invariant");
4222   }
4223 
4224   // False branch, no pin count over/underflow. Increment or decrement pin count and store back.
4225   Node* valid_pin_count = _gvn.transform(new IfFalseNode(iff_pin_count_over_underflow));
4226   set_control(valid_pin_count);
4227 
4228   Node* next_pin_count;
4229   if (unpin) {
4230     next_pin_count = _gvn.transform(new SubINode(pin_count, _gvn.intcon(1)));
4231   } else {
4232     next_pin_count = _gvn.transform(new AddINode(pin_count, _gvn.intcon(1)));
4233   }
4234 
4235   store_to_memory(control(), pin_count_offset, next_pin_count, T_INT, MemNode::unordered);
4236 
4237   // Result of top level CFG and Memory.
4238   RegionNode* result_rgn = new RegionNode(PATH_LIMIT);
4239   record_for_igvn(result_rgn);
4240   PhiNode* result_mem = new PhiNode(result_rgn, Type::MEMORY, TypePtr::BOTTOM);
4241   record_for_igvn(result_mem);
4242 
4243   result_rgn->init_req(_true_path, valid_pin_count);
4244   result_rgn->init_req(_false_path, continuation_is_null);
4245   result_mem->init_req(_true_path, reset_memory());
4246   result_mem->init_req(_false_path, input_memory_state);
4247 
4248   // Set output state.
4249   set_control(_gvn.transform(result_rgn));
4250   set_all_memory(_gvn.transform(result_mem));
4251 
4252   return true;
4253 }
4254 
4255 //---------------------------load_mirror_from_klass----------------------------
4256 // Given a klass oop, load its java mirror (a java.lang.Class oop).
4257 Node* LibraryCallKit::load_mirror_from_klass(Node* klass) {
4258   Node* p = off_heap_plus_addr(klass, in_bytes(Klass::java_mirror_offset()));
4259   Node* load = make_load(nullptr, p, TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered);
4260   // mirror = ((OopHandle)mirror)->resolve();
4261   return access_load(load, TypeInstPtr::MIRROR, T_OBJECT, IN_NATIVE);
4262 }
4263 
4264 //-----------------------load_klass_from_mirror_common-------------------------
4265 // Given a java mirror (a java.lang.Class oop), load its corresponding klass oop.
4266 // Test the klass oop for null (signifying a primitive Class like Integer.TYPE),
4267 // and branch to the given path on the region.
4268 // If never_see_null, take an uncommon trap on null, so we can optimistically
4269 // compile for the non-null case.
4270 // If the region is null, force never_see_null = true.
4271 Node* LibraryCallKit::load_klass_from_mirror_common(Node* mirror,
4272                                                     bool never_see_null,
4273                                                     RegionNode* region,
4274                                                     int null_path,
4275                                                     int offset) {
4276   if (region == nullptr)  never_see_null = true;
4277   Node* p = basic_plus_adr(mirror, offset);
4278   const TypeKlassPtr*  kls_type = TypeInstKlassPtr::OBJECT_OR_NULL;
4279   Node* kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), p, TypeRawPtr::BOTTOM, kls_type));
4280   Node* null_ctl = top();
4281   kls = null_check_oop(kls, &null_ctl, never_see_null);
4282   if (region != nullptr) {
4283     // Set region->in(null_path) if the mirror is a primitive (e.g, int.class).
4284     region->init_req(null_path, null_ctl);
4285   } else {
4286     assert(null_ctl == top(), "no loose ends");
4287   }
4288   return kls;
4289 }
4290 
4291 //--------------------(inline_native_Class_query helpers)---------------------
4292 // Use this for JVM_ACC_INTERFACE.
4293 // Fall through if (mods & mask) == bits, take the guard otherwise.
4294 Node* LibraryCallKit::generate_klass_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region,
4295                                                  ByteSize offset, const Type* type, BasicType bt) {
4296   // Branch around if the given klass has the given modifier bit set.
4297   // Like generate_guard, adds a new path onto the region.
4298   Node* modp = off_heap_plus_addr(kls, in_bytes(offset));
4299   Node* mods = make_load(nullptr, modp, type, bt, MemNode::unordered);
4300   Node* mask = intcon(modifier_mask);
4301   Node* bits = intcon(modifier_bits);
4302   Node* mbit = _gvn.transform(new AndINode(mods, mask));
4303   Node* cmp  = _gvn.transform(new CmpINode(mbit, bits));
4304   Node* bol  = _gvn.transform(new BoolNode(cmp, BoolTest::ne));
4305   return generate_fair_guard(bol, region);
4306 }
4307 
4308 Node* LibraryCallKit::generate_interface_guard(Node* kls, RegionNode* region) {
4309   return generate_klass_flags_guard(kls, JVM_ACC_INTERFACE, 0, region,
4310                                     InstanceKlass::access_flags_offset(), TypeInt::CHAR, T_CHAR);
4311 }
4312 
4313 // Use this for testing if Klass is_hidden, has_finalizer, and is_cloneable_fast.
4314 Node* LibraryCallKit::generate_misc_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region) {
4315   return generate_klass_flags_guard(kls, modifier_mask, modifier_bits, region,
4316                                     Klass::misc_flags_offset(), TypeInt::UBYTE, T_BOOLEAN);
4317 }
4318 
4319 Node* LibraryCallKit::generate_hidden_class_guard(Node* kls, RegionNode* region) {
4320   return generate_misc_flags_guard(kls, KlassFlags::_misc_is_hidden_class, 0, region);
4321 }
4322 
4323 //-------------------------inline_native_Class_query-------------------
4324 bool LibraryCallKit::inline_native_Class_query(vmIntrinsics::ID id) {
4325   const Type* return_type = TypeInt::BOOL;
4326   Node* prim_return_value = top();  // what happens if it's a primitive class?
4327   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
4328   bool expect_prim = false;     // most of these guys expect to work on refs
4329 
4330   enum { _normal_path = 1, _prim_path = 2, PATH_LIMIT };
4331 
4332   Node* mirror = argument(0);
4333   Node* obj    = top();
4334 
4335   switch (id) {
4336   case vmIntrinsics::_isInstance:
4337     // nothing is an instance of a primitive type
4338     prim_return_value = intcon(0);
4339     obj = argument(1);
4340     break;
4341   case vmIntrinsics::_isHidden:
4342     prim_return_value = intcon(0);
4343     break;
4344   case vmIntrinsics::_getSuperclass:
4345     prim_return_value = null();
4346     return_type = TypeInstPtr::MIRROR->cast_to_ptr_type(TypePtr::BotPTR);
4347     break;
4348   default:
4349     fatal_unexpected_iid(id);
4350     break;
4351   }
4352 
4353   const TypeInstPtr* mirror_con = _gvn.type(mirror)->isa_instptr();
4354   if (mirror_con == nullptr)  return false;  // cannot happen?
4355 
4356 #ifndef PRODUCT
4357   if (C->print_intrinsics() || C->print_inlining()) {
4358     ciType* k = mirror_con->java_mirror_type();
4359     if (k) {
4360       tty->print("Inlining %s on constant Class ", vmIntrinsics::name_at(intrinsic_id()));
4361       k->print_name();
4362       tty->cr();
4363     }
4364   }
4365 #endif
4366 
4367   // Null-check the mirror, and the mirror's klass ptr (in case it is a primitive).
4368   RegionNode* region = new RegionNode(PATH_LIMIT);
4369   record_for_igvn(region);
4370   PhiNode* phi = new PhiNode(region, return_type);
4371 
4372   // The mirror will never be null of Reflection.getClassAccessFlags, however
4373   // it may be null for Class.isInstance or Class.getModifiers. Throw a NPE
4374   // if it is. See bug 4774291.
4375 
4376   // For Reflection.getClassAccessFlags(), the null check occurs in
4377   // the wrong place; see inline_unsafe_access(), above, for a similar
4378   // situation.
4379   mirror = null_check(mirror);
4380   // If mirror or obj is dead, only null-path is taken.
4381   if (stopped())  return true;
4382 
4383   if (expect_prim)  never_see_null = false;  // expect nulls (meaning prims)
4384 
4385   // Now load the mirror's klass metaobject, and null-check it.
4386   // Side-effects region with the control path if the klass is null.
4387   Node* kls = load_klass_from_mirror(mirror, never_see_null, region, _prim_path);
4388   // If kls is null, we have a primitive mirror.
4389   phi->init_req(_prim_path, prim_return_value);
4390   if (stopped()) { set_result(region, phi); return true; }
4391   bool safe_for_replace = (region->in(_prim_path) == top());
4392 
4393   Node* p;  // handy temp
4394   Node* null_ctl;
4395 
4396   // Now that we have the non-null klass, we can perform the real query.
4397   // For constant classes, the query will constant-fold in LoadNode::Value.
4398   Node* query_value = top();
4399   switch (id) {
4400   case vmIntrinsics::_isInstance:
4401     // nothing is an instance of a primitive type
4402     query_value = gen_instanceof(obj, kls, safe_for_replace);
4403     break;
4404 
4405   case vmIntrinsics::_isHidden:
4406     // (To verify this code sequence, check the asserts in JVM_IsHiddenClass.)
4407     if (generate_hidden_class_guard(kls, region) != nullptr)
4408       // A guard was added.  If the guard is taken, it was an hidden class.
4409       phi->add_req(intcon(1));
4410     // If we fall through, it's a plain class.
4411     query_value = intcon(0);
4412     break;
4413 
4414 
4415   case vmIntrinsics::_getSuperclass:
4416     // The rules here are somewhat unfortunate, but we can still do better
4417     // with random logic than with a JNI call.
4418     // Interfaces store null or Object as _super, but must report null.
4419     // Arrays store an intermediate super as _super, but must report Object.
4420     // Other types can report the actual _super.
4421     // (To verify this code sequence, check the asserts in JVM_IsInterface.)
4422     if (generate_array_guard(kls, region) != nullptr) {
4423       // A guard was added.  If the guard is taken, it was an array.
4424       phi->add_req(makecon(TypeInstPtr::make(env()->Object_klass()->java_mirror())));
4425     }
4426     // Check for interface after array since this checks AccessFlags offset into InstanceKlass.
4427     // In other words, we are accessing subtype-specific information, so we need to determine the subtype first.
4428     if (generate_interface_guard(kls, region) != nullptr) {
4429       // A guard was added.  If the guard is taken, it was an interface.
4430       phi->add_req(null());
4431     }
4432     // If we fall through, it's a plain class.  Get its _super.
4433     if (!stopped()) {
4434       p = basic_plus_adr(top(), kls, in_bytes(Klass::super_offset()));
4435       kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), p, TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
4436       null_ctl = top();
4437       kls = null_check_oop(kls, &null_ctl);
4438       if (null_ctl != top()) {
4439         // If the guard is taken, Object.superClass is null (both klass and mirror).
4440         region->add_req(null_ctl);
4441         phi   ->add_req(null());
4442       }
4443       if (!stopped()) {
4444         query_value = load_mirror_from_klass(kls);
4445       }
4446     }
4447     break;
4448 
4449   default:
4450     fatal_unexpected_iid(id);
4451     break;
4452   }
4453 
4454   // Fall-through is the normal case of a query to a real class.
4455   phi->init_req(1, query_value);
4456   region->init_req(1, control());
4457 
4458   C->set_has_split_ifs(true); // Has chance for split-if optimization
4459   set_result(region, phi);
4460   return true;
4461 }
4462 
4463 
4464 //-------------------------inline_Class_cast-------------------
4465 bool LibraryCallKit::inline_Class_cast() {
4466   Node* mirror = argument(0); // Class
4467   Node* obj    = argument(1);
4468   const TypeInstPtr* mirror_con = _gvn.type(mirror)->isa_instptr();
4469   if (mirror_con == nullptr) {
4470     return false;  // dead path (mirror->is_top()).
4471   }
4472   if (obj == nullptr || obj->is_top()) {
4473     return false;  // dead path
4474   }
4475   const TypeOopPtr* tp = _gvn.type(obj)->isa_oopptr();
4476 
4477   // First, see if Class.cast() can be folded statically.
4478   // java_mirror_type() returns non-null for compile-time Class constants.
4479   ciType* tm = mirror_con->java_mirror_type();
4480   if (tm != nullptr && tm->is_klass() &&
4481       tp != nullptr) {
4482     if (!tp->is_loaded()) {
4483       // Don't use intrinsic when class is not loaded.
4484       return false;
4485     } else {
4486       const TypeKlassPtr* tklass = TypeKlassPtr::make(tm->as_klass(), Type::trust_interfaces);
4487       int static_res = C->static_subtype_check(tklass, tp->as_klass_type());
4488       if (static_res == Compile::SSC_always_true) {
4489         // isInstance() is true - fold the code.
4490         set_result(obj);
4491         return true;
4492       } else if (static_res == Compile::SSC_always_false) {
4493         // Don't use intrinsic, have to throw ClassCastException.
4494         // If the reference is null, the non-intrinsic bytecode will
4495         // be optimized appropriately.
4496         return false;
4497       }
4498     }
4499   }
4500 
4501   // Bailout intrinsic and do normal inlining if exception path is frequent.
4502   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
4503     return false;
4504   }
4505 
4506   // Generate dynamic checks.
4507   // Class.cast() is java implementation of _checkcast bytecode.
4508   // Do checkcast (Parse::do_checkcast()) optimizations here.
4509 
4510   mirror = null_check(mirror);
4511   // If mirror is dead, only null-path is taken.
4512   if (stopped()) {
4513     return true;
4514   }
4515 
4516   // Not-subtype or the mirror's klass ptr is nullptr (in case it is a primitive).
4517   enum { _bad_type_path = 1, _prim_path = 2, _npe_path = 3, PATH_LIMIT };
4518   RegionNode* region = new RegionNode(PATH_LIMIT);
4519   record_for_igvn(region);
4520 
4521   // Now load the mirror's klass metaobject, and null-check it.
4522   // If kls is null, we have a primitive mirror and
4523   // nothing is an instance of a primitive type.
4524   Node* kls = load_klass_from_mirror(mirror, false, region, _prim_path);
4525 
4526   Node* res = top();
4527   Node* io = i_o();
4528   Node* mem = merged_memory();
4529   SafePointNode* new_cast_failure_map = nullptr;
4530 
4531   if (!stopped()) {
4532 
4533     Node* bad_type_ctrl = top();
4534     // Do checkcast optimizations.
4535     res = gen_checkcast(obj, kls, &bad_type_ctrl, &new_cast_failure_map);
4536     region->init_req(_bad_type_path, bad_type_ctrl);
4537   }
4538   if (region->in(_prim_path) != top() ||
4539       region->in(_bad_type_path) != top() ||
4540       region->in(_npe_path) != top()) {
4541     // Let Interpreter throw ClassCastException.
4542     PreserveJVMState pjvms(this);
4543     if (new_cast_failure_map != nullptr) {
4544       // The current map on the success path could have been modified. Use the dedicated failure path map.
4545       set_map(new_cast_failure_map);
4546     }
4547     set_control(_gvn.transform(region));
4548     // Set IO and memory because gen_checkcast may override them when buffering inline types
4549     set_i_o(io);
4550     set_all_memory(mem);
4551     uncommon_trap(Deoptimization::Reason_intrinsic,
4552                   Deoptimization::Action_maybe_recompile);
4553   }
4554   if (!stopped()) {
4555     set_result(res);
4556   }
4557   return true;
4558 }
4559 
4560 
4561 //--------------------------inline_native_subtype_check------------------------
4562 // This intrinsic takes the JNI calls out of the heart of
4563 // UnsafeFieldAccessorImpl.set, which improves Field.set, readObject, etc.
4564 bool LibraryCallKit::inline_native_subtype_check() {
4565   // Pull both arguments off the stack.
4566   Node* args[2];                // two java.lang.Class mirrors: superc, subc
4567   args[0] = argument(0);
4568   args[1] = argument(1);
4569   Node* klasses[2];             // corresponding Klasses: superk, subk
4570   klasses[0] = klasses[1] = top();
4571 
4572   enum {
4573     // A full decision tree on {superc is prim, subc is prim}:
4574     _prim_0_path = 1,           // {P,N} => false
4575                                 // {P,P} & superc!=subc => false
4576     _prim_same_path,            // {P,P} & superc==subc => true
4577     _prim_1_path,               // {N,P} => false
4578     _ref_subtype_path,          // {N,N} & subtype check wins => true
4579     _both_ref_path,             // {N,N} & subtype check loses => false
4580     PATH_LIMIT
4581   };
4582 
4583   RegionNode* region = new RegionNode(PATH_LIMIT);
4584   RegionNode* prim_region = new RegionNode(2);
4585   Node*       phi    = new PhiNode(region, TypeInt::BOOL);
4586   record_for_igvn(region);
4587   record_for_igvn(prim_region);
4588 
4589   const TypePtr* adr_type = TypeRawPtr::BOTTOM;   // memory type of loads
4590   const TypeKlassPtr* kls_type = TypeInstKlassPtr::OBJECT_OR_NULL;
4591   int class_klass_offset = java_lang_Class::klass_offset();
4592 
4593   // First null-check both mirrors and load each mirror's klass metaobject.
4594   int which_arg;
4595   for (which_arg = 0; which_arg <= 1; which_arg++) {
4596     Node* arg = args[which_arg];
4597     arg = null_check(arg);
4598     if (stopped())  break;
4599     args[which_arg] = arg;
4600 
4601     Node* p = basic_plus_adr(arg, class_klass_offset);
4602     Node* kls = LoadKlassNode::make(_gvn, immutable_memory(), p, adr_type, kls_type);
4603     klasses[which_arg] = _gvn.transform(kls);
4604   }
4605 
4606   // Having loaded both klasses, test each for null.
4607   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
4608   for (which_arg = 0; which_arg <= 1; which_arg++) {
4609     Node* kls = klasses[which_arg];
4610     Node* null_ctl = top();
4611     kls = null_check_oop(kls, &null_ctl, never_see_null);
4612     if (which_arg == 0) {
4613       prim_region->init_req(1, null_ctl);
4614     } else {
4615       region->init_req(_prim_1_path, null_ctl);
4616     }
4617     if (stopped())  break;
4618     klasses[which_arg] = kls;
4619   }
4620 
4621   if (!stopped()) {
4622     // now we have two reference types, in klasses[0..1]
4623     Node* subk   = klasses[1];  // the argument to isAssignableFrom
4624     Node* superk = klasses[0];  // the receiver
4625     region->set_req(_both_ref_path, gen_subtype_check(subk, superk));
4626     region->set_req(_ref_subtype_path, control());
4627   }
4628 
4629   // If both operands are primitive (both klasses null), then
4630   // we must return true when they are identical primitives.
4631   // It is convenient to test this after the first null klass check.
4632   // This path is also used if superc is a value mirror.
4633   set_control(_gvn.transform(prim_region));
4634   if (!stopped()) {
4635     // Since superc is primitive, make a guard for the superc==subc case.
4636     Node* cmp_eq = _gvn.transform(new CmpPNode(args[0], args[1]));
4637     Node* bol_eq = _gvn.transform(new BoolNode(cmp_eq, BoolTest::eq));
4638     generate_fair_guard(bol_eq, region);
4639     if (region->req() == PATH_LIMIT+1) {
4640       // A guard was added.  If the added guard is taken, superc==subc.
4641       region->swap_edges(PATH_LIMIT, _prim_same_path);
4642       region->del_req(PATH_LIMIT);
4643     }
4644     region->set_req(_prim_0_path, control()); // Not equal after all.
4645   }
4646 
4647   // these are the only paths that produce 'true':
4648   phi->set_req(_prim_same_path,   intcon(1));
4649   phi->set_req(_ref_subtype_path, intcon(1));
4650 
4651   // pull together the cases:
4652   assert(region->req() == PATH_LIMIT, "sane region");
4653   for (uint i = 1; i < region->req(); i++) {
4654     Node* ctl = region->in(i);
4655     if (ctl == nullptr || ctl == top()) {
4656       region->set_req(i, top());
4657       phi   ->set_req(i, top());
4658     } else if (phi->in(i) == nullptr) {
4659       phi->set_req(i, intcon(0)); // all other paths produce 'false'
4660     }
4661   }
4662 
4663   set_control(_gvn.transform(region));
4664   set_result(_gvn.transform(phi));
4665   return true;
4666 }
4667 
4668 //---------------------generate_array_guard_common------------------------
4669 Node* LibraryCallKit::generate_array_guard_common(Node* kls, RegionNode* region, ArrayKind kind, Node** obj) {
4670 
4671   if (stopped()) {
4672     return nullptr;
4673   }
4674 
4675   // Like generate_guard, adds a new path onto the region.
4676   jint  layout_con = 0;
4677   Node* layout_val = get_layout_helper(kls, layout_con);
4678   if (layout_val == nullptr) {
4679     bool query = 0;
4680     switch(kind) {
4681       case RefArray:       query = Klass::layout_helper_is_refArray(layout_con); break;
4682       case NonRefArray:    query = !Klass::layout_helper_is_refArray(layout_con); break;
4683       case TypeArray:      query = Klass::layout_helper_is_typeArray(layout_con); break;
4684       case AnyArray:       query = Klass::layout_helper_is_array(layout_con); break;
4685       case NonArray:       query = !Klass::layout_helper_is_array(layout_con); break;
4686       default:
4687         ShouldNotReachHere();
4688     }
4689     if (!query) {
4690       return nullptr;                       // never a branch
4691     } else {                             // always a branch
4692       Node* always_branch = control();
4693       if (region != nullptr)
4694         region->add_req(always_branch);
4695       set_control(top());
4696       return always_branch;
4697     }
4698   }
4699   unsigned int value = 0;
4700   BoolTest::mask btest = BoolTest::illegal;
4701   switch(kind) {
4702     case RefArray:
4703     case NonRefArray: {
4704       value = Klass::_lh_array_tag_ref_value;
4705       layout_val = _gvn.transform(new RShiftINode(layout_val, intcon(Klass::_lh_array_tag_shift)));
4706       btest = (kind == RefArray) ? BoolTest::eq : BoolTest::ne;
4707       break;
4708     }
4709     case TypeArray: {
4710       value = Klass::_lh_array_tag_type_value;
4711       layout_val = _gvn.transform(new RShiftINode(layout_val, intcon(Klass::_lh_array_tag_shift)));
4712       btest = BoolTest::eq;
4713       break;
4714     }
4715     case AnyArray:    value = Klass::_lh_neutral_value; btest = BoolTest::lt; break;
4716     case NonArray:    value = Klass::_lh_neutral_value; btest = BoolTest::gt; break;
4717     default:
4718       ShouldNotReachHere();
4719   }
4720   // Now test the correct condition.
4721   jint nval = (jint)value;
4722   Node* cmp = _gvn.transform(new CmpINode(layout_val, intcon(nval)));
4723   Node* bol = _gvn.transform(new BoolNode(cmp, btest));
4724   Node* ctrl = generate_fair_guard(bol, region);
4725   Node* is_array_ctrl = kind == NonArray ? control() : ctrl;
4726   if (obj != nullptr && is_array_ctrl != nullptr && is_array_ctrl != top()) {
4727     // Keep track of the fact that 'obj' is an array to prevent
4728     // array specific accesses from floating above the guard.
4729     *obj = _gvn.transform(new CastPPNode(is_array_ctrl, *obj, TypeAryPtr::BOTTOM));
4730   }
4731   return ctrl;
4732 }
4733 
4734 // public static native Object[] ValueClass::newNullRestrictedAtomicArray(Class<?> componentType, int length, Object initVal);
4735 // public static native Object[] ValueClass::newNullRestrictedNonAtomicArray(Class<?> componentType, int length, Object initVal);
4736 // public static native Object[] ValueClass::newNullableAtomicArray(Class<?> componentType, int length);
4737 bool LibraryCallKit::inline_newArray(bool null_free, bool atomic) {
4738   assert(null_free || atomic, "nullable implies atomic");
4739   Node* componentType = argument(0);
4740   Node* length = argument(1);
4741   Node* init_val = null_free ? argument(2) : nullptr;
4742 
4743   const TypeInstPtr* tp = _gvn.type(componentType)->isa_instptr();
4744   if (tp != nullptr) {
4745     ciInstanceKlass* ik = tp->instance_klass();
4746     if (ik == C->env()->Class_klass()) {
4747       ciType* t = tp->java_mirror_type();
4748       if (t != nullptr && t->is_inlinetype()) {
4749 
4750         ciArrayKlass* array_klass = ciArrayKlass::make(t, null_free, atomic, true);
4751         assert(array_klass->is_elem_null_free() == null_free, "inconsistency");
4752 
4753         // TOOD 8350865 ZGC needs card marks on initializing oop stores
4754         if (UseZGC && null_free && !array_klass->is_flat_array_klass()) {
4755           return false;
4756         }
4757 
4758         if (array_klass->is_loaded() && array_klass->element_klass()->as_inline_klass()->is_initialized()) {
4759           const TypeAryKlassPtr* array_klass_type = TypeAryKlassPtr::make(array_klass, Type::trust_interfaces);
4760           if (null_free) {
4761             if (init_val->is_InlineType()) {
4762               if (array_klass_type->is_flat() && init_val->as_InlineType()->is_all_zero(&gvn(), /* flat */ true)) {
4763                 // Zeroing is enough because the init value is the all-zero value
4764                 init_val = nullptr;
4765               } else {
4766                 init_val = init_val->as_InlineType()->buffer(this);
4767               }
4768             }
4769             // TODO 8350865 Should we add a check of the init_val type (maybe in debug only + halt)?
4770             // If we insert a checkcast here, we can be sure that init_val is an InlineTypeNode, so
4771             // when we folded a field load from an allocation (e.g. during escape analysis), we can
4772             // remove the check init_val->is_InlineType().
4773           }
4774           Node* obj = new_array(makecon(array_klass_type), length, 0, nullptr, false, init_val);
4775           const TypeAryPtr* arytype = gvn().type(obj)->is_aryptr();
4776           assert(arytype->is_null_free() == null_free, "inconsistency");
4777           assert(arytype->is_not_null_free() == !null_free, "inconsistency");
4778           set_result(obj);
4779           return true;
4780         }
4781       }
4782     }
4783   }
4784   return false;
4785 }
4786 
4787 // public static native boolean ValueClass::isFlatArray(Object array);
4788 // public static native boolean ValueClass::isNullRestrictedArray(Object array);
4789 // public static native boolean ValueClass::isAtomicArray(Object array);
4790 bool LibraryCallKit::inline_getArrayProperties(ArrayPropertiesCheck check) {
4791   Node* array = argument(0);
4792 
4793   Node* bol;
4794   switch(check) {
4795     case IsFlat:
4796       // TODO 8350865 Use the object version here instead of loading the klass
4797       // The problem is that PhaseMacroExpand::expand_flatarraycheck_node can only handle some IR shapes and will fail, for example, if the bol is directly wired to a ReturnNode
4798       bol = flat_array_test(load_object_klass(array));
4799       break;
4800     case IsNullRestricted:
4801       bol = null_free_array_test(array);
4802       break;
4803     case IsAtomic:
4804       // TODO 8350865 Implement this. It's a bit more complicated, see conditions in JVM_IsAtomicArray
4805       // Enable TestIntrinsics::test87/88 once this is implemented
4806       // bol = null_free_atomic_array_test
4807       return false;
4808     default:
4809       ShouldNotReachHere();
4810   }
4811 
4812   Node* res = gvn().transform(new CMoveINode(bol, intcon(0), intcon(1), TypeInt::BOOL));
4813   set_result(res);
4814   return true;
4815 }
4816 
4817 // Load the default refined array klass from an ObjArrayKlass. This relies on the first entry in the
4818 // '_next_refined_array_klass' linked list being the default (see ObjArrayKlass::klass_with_properties).
4819 Node* LibraryCallKit::load_default_refined_array_klass(Node* klass_node, bool type_array_guard) {
4820   RegionNode* region = new RegionNode(2);
4821   Node* phi = new PhiNode(region, TypeInstKlassPtr::OBJECT_OR_NULL);
4822 
4823   if (type_array_guard) {
4824     generate_typeArray_guard(klass_node, region);
4825     if (region->req() == 3) {
4826       phi->add_req(klass_node);
4827     }
4828   }
4829   Node* adr_refined_klass = basic_plus_adr(top(), klass_node, in_bytes(ObjArrayKlass::next_refined_array_klass_offset()));
4830   Node* refined_klass = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), adr_refined_klass, TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
4831 
4832   // Can be null if not initialized yet, just deopt
4833   Node* null_ctl = top();
4834   refined_klass = null_check_oop(refined_klass, &null_ctl, /* never_see_null= */ true);
4835 
4836   region->init_req(1, control());
4837   phi->init_req(1, refined_klass);
4838 
4839   set_control(_gvn.transform(region));
4840   return _gvn.transform(phi);
4841 }
4842 
4843 // Load the non-refined array klass from an ObjArrayKlass.
4844 Node* LibraryCallKit::load_non_refined_array_klass(Node* klass_node) {
4845   const TypeAryKlassPtr* ary_klass_ptr = _gvn.type(klass_node)->isa_aryklassptr();
4846   if (ary_klass_ptr != nullptr && ary_klass_ptr->klass_is_exact()) {
4847     return _gvn.makecon(ary_klass_ptr->cast_to_refined_array_klass_ptr(false));
4848   }
4849 
4850   RegionNode* region = new RegionNode(2);
4851   Node* phi = new PhiNode(region, TypeInstKlassPtr::OBJECT);
4852 
4853   generate_typeArray_guard(klass_node, region);
4854   if (region->req() == 3) {
4855     phi->add_req(klass_node);
4856   }
4857   Node* super_adr = basic_plus_adr(top(), klass_node, in_bytes(Klass::super_offset()));
4858   Node* super_klass = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), super_adr, TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT));
4859 
4860   region->init_req(1, control());
4861   phi->init_req(1, super_klass);
4862 
4863   set_control(_gvn.transform(region));
4864   return _gvn.transform(phi);
4865 }
4866 
4867 //-----------------------inline_native_newArray--------------------------
4868 // private static native Object java.lang.reflect.Array.newArray(Class<?> componentType, int length);
4869 // private        native Object Unsafe.allocateUninitializedArray0(Class<?> cls, int size);
4870 bool LibraryCallKit::inline_unsafe_newArray(bool uninitialized) {
4871   Node* mirror;
4872   Node* count_val;
4873   if (uninitialized) {
4874     null_check_receiver();
4875     mirror    = argument(1);
4876     count_val = argument(2);
4877   } else {
4878     mirror    = argument(0);
4879     count_val = argument(1);
4880   }
4881 
4882   mirror = null_check(mirror);
4883   // If mirror or obj is dead, only null-path is taken.
4884   if (stopped())  return true;
4885 
4886   enum { _normal_path = 1, _slow_path = 2, PATH_LIMIT };
4887   RegionNode* result_reg = new RegionNode(PATH_LIMIT);
4888   PhiNode*    result_val = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
4889   PhiNode*    result_io  = new PhiNode(result_reg, Type::ABIO);
4890   PhiNode*    result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
4891 
4892   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
4893   Node* klass_node = load_array_klass_from_mirror(mirror, never_see_null,
4894                                                   result_reg, _slow_path);
4895   Node* normal_ctl   = control();
4896   Node* no_array_ctl = result_reg->in(_slow_path);
4897 
4898   // Generate code for the slow case.  We make a call to newArray().
4899   set_control(no_array_ctl);
4900   if (!stopped()) {
4901     // Either the input type is void.class, or else the
4902     // array klass has not yet been cached.  Either the
4903     // ensuing call will throw an exception, or else it
4904     // will cache the array klass for next time.
4905     PreserveJVMState pjvms(this);
4906     CallJavaNode* slow_call = nullptr;
4907     if (uninitialized) {
4908       // Generate optimized virtual call (holder class 'Unsafe' is final)
4909       slow_call = generate_method_call(vmIntrinsics::_allocateUninitializedArray, false, false, true);
4910     } else {
4911       slow_call = generate_method_call_static(vmIntrinsics::_newArray, true);
4912     }
4913     Node* slow_result = set_results_for_java_call(slow_call);
4914     // this->control() comes from set_results_for_java_call
4915     result_reg->set_req(_slow_path, control());
4916     result_val->set_req(_slow_path, slow_result);
4917     result_io ->set_req(_slow_path, i_o());
4918     result_mem->set_req(_slow_path, reset_memory());
4919   }
4920 
4921   set_control(normal_ctl);
4922   if (!stopped()) {
4923     // Normal case:  The array type has been cached in the java.lang.Class.
4924     // The following call works fine even if the array type is polymorphic.
4925     // It could be a dynamic mix of int[], boolean[], Object[], etc.
4926 
4927     klass_node = load_default_refined_array_klass(klass_node);
4928 
4929     Node* obj = new_array(klass_node, count_val, 0);  // no arguments to push
4930     result_reg->init_req(_normal_path, control());
4931     result_val->init_req(_normal_path, obj);
4932     result_io ->init_req(_normal_path, i_o());
4933     result_mem->init_req(_normal_path, reset_memory());
4934 
4935     if (uninitialized) {
4936       // Mark the allocation so that zeroing is skipped
4937       AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(obj);
4938       alloc->maybe_set_complete(&_gvn);
4939     }
4940   }
4941 
4942   // Return the combined state.
4943   set_i_o(        _gvn.transform(result_io)  );
4944   set_all_memory( _gvn.transform(result_mem));
4945 
4946   C->set_has_split_ifs(true); // Has chance for split-if optimization
4947   set_result(result_reg, result_val);
4948   return true;
4949 }
4950 
4951 //----------------------inline_native_getLength--------------------------
4952 // public static native int java.lang.reflect.Array.getLength(Object array);
4953 bool LibraryCallKit::inline_native_getLength() {
4954   if (too_many_traps(Deoptimization::Reason_intrinsic))  return false;
4955 
4956   Node* array = null_check(argument(0));
4957   // If array is dead, only null-path is taken.
4958   if (stopped())  return true;
4959 
4960   // Deoptimize if it is a non-array.
4961   Node* non_array = generate_non_array_guard(load_object_klass(array), nullptr, &array);
4962 
4963   if (non_array != nullptr) {
4964     PreserveJVMState pjvms(this);
4965     set_control(non_array);
4966     uncommon_trap(Deoptimization::Reason_intrinsic,
4967                   Deoptimization::Action_maybe_recompile);
4968   }
4969 
4970   // If control is dead, only non-array-path is taken.
4971   if (stopped())  return true;
4972 
4973   // The works fine even if the array type is polymorphic.
4974   // It could be a dynamic mix of int[], boolean[], Object[], etc.
4975   Node* result = load_array_length(array);
4976 
4977   C->set_has_split_ifs(true);  // Has chance for split-if optimization
4978   set_result(result);
4979   return true;
4980 }
4981 
4982 //------------------------inline_array_copyOf----------------------------
4983 // public static <T,U> T[] java.util.Arrays.copyOf(     U[] original, int newLength,         Class<? extends T[]> newType);
4984 // public static <T,U> T[] java.util.Arrays.copyOfRange(U[] original, int from,      int to, Class<? extends T[]> newType);
4985 bool LibraryCallKit::inline_array_copyOf(bool is_copyOfRange) {
4986   if (too_many_traps(Deoptimization::Reason_intrinsic))  return false;
4987 
4988   // Get the arguments.
4989   Node* original          = argument(0);
4990   Node* start             = is_copyOfRange? argument(1): intcon(0);
4991   Node* end               = is_copyOfRange? argument(2): argument(1);
4992   Node* array_type_mirror = is_copyOfRange? argument(3): argument(2);
4993 
4994   Node* newcopy = nullptr;
4995 
4996   // Set the original stack and the reexecute bit for the interpreter to reexecute
4997   // the bytecode that invokes Arrays.copyOf if deoptimization happens.
4998   { PreserveReexecuteState preexecs(this);
4999     jvms()->set_should_reexecute(true);
5000 
5001     array_type_mirror = null_check(array_type_mirror);
5002     original          = null_check(original);
5003 
5004     // Check if a null path was taken unconditionally.
5005     if (stopped())  return true;
5006 
5007     Node* orig_length = load_array_length(original);
5008 
5009     Node* klass_node = load_klass_from_mirror(array_type_mirror, false, nullptr, 0);
5010     klass_node = null_check(klass_node);
5011 
5012     RegionNode* bailout = new RegionNode(1);
5013     record_for_igvn(bailout);
5014 
5015     // Despite the generic type of Arrays.copyOf, the mirror might be int, int[], etc.
5016     // Bail out if that is so.
5017     // Inline type array may have object field that would require a
5018     // write barrier. Conservatively, go to slow path.
5019     // TODO 8251971: Optimize for the case when flat src/dst are later found
5020     // to not contain oops (i.e., move this check to the macro expansion phase).
5021     BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
5022     const TypeAryPtr* orig_t = _gvn.type(original)->isa_aryptr();
5023     const TypeKlassPtr* tklass = _gvn.type(klass_node)->is_klassptr();
5024     bool exclude_flat = UseArrayFlattening && bs->array_copy_requires_gc_barriers(true, T_OBJECT, false, false, BarrierSetC2::Parsing) &&
5025                         // Can src array be flat and contain oops?
5026                         (orig_t == nullptr || (!orig_t->is_not_flat() && (!orig_t->is_flat() || orig_t->elem()->inline_klass()->contains_oops()))) &&
5027                         // Can dest array be flat and contain oops?
5028                         tklass->can_be_inline_array() && (!tklass->is_flat() || tklass->is_aryklassptr()->elem()->is_instklassptr()->instance_klass()->as_inline_klass()->contains_oops());
5029     Node* not_objArray = exclude_flat ? generate_non_refArray_guard(klass_node, bailout) : generate_typeArray_guard(klass_node, bailout);
5030 
5031     Node* refined_klass_node = load_default_refined_array_klass(klass_node, /* type_array_guard= */ false);
5032 
5033     if (not_objArray != nullptr) {
5034       // Improve the klass node's type from the new optimistic assumption:
5035       ciKlass* ak = ciArrayKlass::make(env()->Object_klass());
5036       bool not_flat = !UseArrayFlattening;
5037       bool not_null_free = !Arguments::is_valhalla_enabled();
5038       const Type* akls = TypeAryKlassPtr::make(TypePtr::NotNull, ak, Type::Offset(0), Type::trust_interfaces, not_flat, not_null_free, false, false, not_flat, true);
5039       Node* cast = new CastPPNode(control(), refined_klass_node, akls);
5040       refined_klass_node = _gvn.transform(cast);
5041     }
5042 
5043     // Bail out if either start or end is negative.
5044     generate_negative_guard(start, bailout, &start);
5045     generate_negative_guard(end,   bailout, &end);
5046 
5047     Node* length = end;
5048     if (_gvn.type(start) != TypeInt::ZERO) {
5049       length = _gvn.transform(new SubINode(end, start));
5050     }
5051 
5052     // Bail out if length is negative (i.e., if start > end).
5053     // Without this the new_array would throw
5054     // NegativeArraySizeException but IllegalArgumentException is what
5055     // should be thrown
5056     generate_negative_guard(length, bailout, &length);
5057 
5058     // Handle inline type arrays
5059     bool can_validate = !too_many_traps(Deoptimization::Reason_class_check);
5060     if (!stopped()) {
5061       // TODO 8251971
5062       if (!orig_t->is_null_free()) {
5063         // Not statically known to be null free, add a check
5064         generate_fair_guard(null_free_array_test(original), bailout);
5065       }
5066       orig_t = _gvn.type(original)->isa_aryptr();
5067       if (orig_t != nullptr && orig_t->is_flat()) {
5068         // Src is flat, check that dest is flat as well
5069         if (exclude_flat) {
5070           // Dest can't be flat, bail out
5071           bailout->add_req(control());
5072           set_control(top());
5073         } else {
5074           generate_fair_guard(flat_array_test(refined_klass_node, /* flat = */ false), bailout);
5075         }
5076         // TODO 8350865 This is not correct anymore. Write tests and fix logic similar to arraycopy.
5077       } else if (UseArrayFlattening && (orig_t == nullptr || !orig_t->is_not_flat()) &&
5078                  // If dest is flat, src must be flat as well (guaranteed by src <: dest check if validated).
5079                  ((!tklass->is_flat() && tklass->can_be_inline_array()) || !can_validate)) {
5080         // Src might be flat and dest might not be flat. Go to the slow path if src is flat.
5081         // TODO 8251971: Optimize for the case when src/dest are later found to be both flat.
5082         generate_fair_guard(flat_array_test(load_object_klass(original)), bailout);
5083         if (orig_t != nullptr) {
5084           orig_t = orig_t->cast_to_not_flat();
5085           original = _gvn.transform(new CheckCastPPNode(control(), original, orig_t));
5086         }
5087       }
5088       if (!can_validate) {
5089         // No validation. The subtype check emitted at macro expansion time will not go to the slow
5090         // path but call checkcast_arraycopy which can not handle flat/null-free inline type arrays.
5091         // TODO 8251971: Optimize for the case when src/dest are later found to be both flat/null-free.
5092         generate_fair_guard(flat_array_test(refined_klass_node), bailout);
5093         generate_fair_guard(null_free_array_test(original), bailout);
5094       }
5095     }
5096 
5097     // Bail out if start is larger than the original length
5098     Node* orig_tail = _gvn.transform(new SubINode(orig_length, start));
5099     generate_negative_guard(orig_tail, bailout, &orig_tail);
5100 
5101     if (bailout->req() > 1) {
5102       PreserveJVMState pjvms(this);
5103       set_control(_gvn.transform(bailout));
5104       uncommon_trap(Deoptimization::Reason_intrinsic,
5105                     Deoptimization::Action_maybe_recompile);
5106     }
5107 
5108     if (!stopped()) {
5109       // How many elements will we copy from the original?
5110       // The answer is MinI(orig_tail, length).
5111       Node* moved = _gvn.transform(new MinINode(orig_tail, length));
5112 
5113       // Generate a direct call to the right arraycopy function(s).
5114       // We know the copy is disjoint but we might not know if the
5115       // oop stores need checking.
5116       // Extreme case:  Arrays.copyOf((Integer[])x, 10, String[].class).
5117       // This will fail a store-check if x contains any non-nulls.
5118 
5119       // ArrayCopyNode:Ideal may transform the ArrayCopyNode to
5120       // loads/stores but it is legal only if we're sure the
5121       // Arrays.copyOf would succeed. So we need all input arguments
5122       // to the copyOf to be validated, including that the copy to the
5123       // new array won't trigger an ArrayStoreException. That subtype
5124       // check can be optimized if we know something on the type of
5125       // the input array from type speculation.
5126       if (_gvn.type(klass_node)->singleton()) {
5127         const TypeKlassPtr* subk = _gvn.type(load_object_klass(original))->is_klassptr();
5128         const TypeKlassPtr* superk = _gvn.type(klass_node)->is_klassptr();
5129 
5130         int test = C->static_subtype_check(superk, subk);
5131         if (test != Compile::SSC_always_true && test != Compile::SSC_always_false) {
5132           const TypeOopPtr* t_original = _gvn.type(original)->is_oopptr();
5133           if (t_original->speculative_type() != nullptr) {
5134             original = maybe_cast_profiled_obj(original, t_original->speculative_type(), true);
5135           }
5136         }
5137       }
5138 
5139       bool validated = false;
5140       // Reason_class_check rather than Reason_intrinsic because we
5141       // want to intrinsify even if this traps.
5142       if (can_validate) {
5143         Node* not_subtype_ctrl = gen_subtype_check(original, klass_node);
5144 
5145         if (not_subtype_ctrl != top()) {
5146           PreserveJVMState pjvms(this);
5147           set_control(not_subtype_ctrl);
5148           uncommon_trap(Deoptimization::Reason_class_check,
5149                         Deoptimization::Action_make_not_entrant);
5150           assert(stopped(), "Should be stopped");
5151         }
5152         validated = true;
5153       }
5154 
5155       if (!stopped()) {
5156         newcopy = new_array(refined_klass_node, length, 0);  // no arguments to push
5157 
5158         ArrayCopyNode* ac = ArrayCopyNode::make(this, true, original, start, newcopy, intcon(0), moved, true, true,
5159                                                 load_object_klass(original), klass_node);
5160         if (!is_copyOfRange) {
5161           ac->set_copyof(validated);
5162         } else {
5163           ac->set_copyofrange(validated);
5164         }
5165         Node* n = _gvn.transform(ac);
5166         if (n == ac) {
5167           ac->connect_outputs(this);
5168         } else {
5169           assert(validated, "shouldn't transform if all arguments not validated");
5170           set_all_memory(n);
5171         }
5172       }
5173     }
5174   } // original reexecute is set back here
5175 
5176   C->set_has_split_ifs(true); // Has chance for split-if optimization
5177   if (!stopped()) {
5178     set_result(newcopy);
5179   }
5180   return true;
5181 }
5182 
5183 
5184 //----------------------generate_virtual_guard---------------------------
5185 // Helper for hashCode and clone.  Peeks inside the vtable to avoid a call.
5186 Node* LibraryCallKit::generate_virtual_guard(Node* obj_klass,
5187                                              RegionNode* slow_region) {
5188   ciMethod* method = callee();
5189   int vtable_index = method->vtable_index();
5190   assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index,
5191          "bad index %d", vtable_index);
5192   // Get the Method* out of the appropriate vtable entry.
5193   int entry_offset = in_bytes(Klass::vtable_start_offset()) +
5194                      vtable_index*vtableEntry::size_in_bytes() +
5195                      in_bytes(vtableEntry::method_offset());
5196   Node* entry_addr = off_heap_plus_addr(obj_klass, entry_offset);
5197   Node* target_call = make_load(nullptr, entry_addr, TypePtr::NOTNULL, T_ADDRESS, MemNode::unordered);
5198 
5199   // Compare the target method with the expected method (e.g., Object.hashCode).
5200   const TypePtr* native_call_addr = TypeMetadataPtr::make(method);
5201 
5202   Node* native_call = makecon(native_call_addr);
5203   Node* chk_native  = _gvn.transform(new CmpPNode(target_call, native_call));
5204   Node* test_native = _gvn.transform(new BoolNode(chk_native, BoolTest::ne));
5205 
5206   return generate_slow_guard(test_native, slow_region);
5207 }
5208 
5209 //-----------------------generate_method_call----------------------------
5210 // Use generate_method_call to make a slow-call to the real
5211 // method if the fast path fails.  An alternative would be to
5212 // use a stub like OptoRuntime::slow_arraycopy_Java.
5213 // This only works for expanding the current library call,
5214 // not another intrinsic.  (E.g., don't use this for making an
5215 // arraycopy call inside of the copyOf intrinsic.)
5216 CallJavaNode*
5217 LibraryCallKit::generate_method_call(vmIntrinsicID method_id, bool is_virtual, bool is_static, bool res_not_null) {
5218   // When compiling the intrinsic method itself, do not use this technique.
5219   guarantee(callee() != C->method(), "cannot make slow-call to self");
5220 
5221   ciMethod* method = callee();
5222   // ensure the JVMS we have will be correct for this call
5223   guarantee(method_id == method->intrinsic_id(), "must match");
5224 
5225   const TypeFunc* tf = TypeFunc::make(method);
5226   if (res_not_null) {
5227     assert(tf->return_type() == T_OBJECT, "");
5228     const TypeTuple* range = tf->range_cc();
5229     const Type** fields = TypeTuple::fields(range->cnt());
5230     fields[TypeFunc::Parms] = range->field_at(TypeFunc::Parms)->filter_speculative(TypePtr::NOTNULL);
5231     const TypeTuple* new_range = TypeTuple::make(range->cnt(), fields);
5232     tf = TypeFunc::make(tf->domain_cc(), new_range);
5233   }
5234   CallJavaNode* slow_call;
5235   if (is_static) {
5236     assert(!is_virtual, "");
5237     slow_call = new CallStaticJavaNode(C, tf,
5238                            SharedRuntime::get_resolve_static_call_stub(), method);
5239   } else if (is_virtual) {
5240     assert(!gvn().type(argument(0))->maybe_null(), "should not be null");
5241     int vtable_index = Method::invalid_vtable_index;
5242     if (UseInlineCaches) {
5243       // Suppress the vtable call
5244     } else {
5245       // hashCode and clone are not a miranda methods,
5246       // so the vtable index is fixed.
5247       // No need to use the linkResolver to get it.
5248        vtable_index = method->vtable_index();
5249        assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index,
5250               "bad index %d", vtable_index);
5251     }
5252     slow_call = new CallDynamicJavaNode(tf,
5253                           SharedRuntime::get_resolve_virtual_call_stub(),
5254                           method, vtable_index);
5255   } else {  // neither virtual nor static:  opt_virtual
5256     assert(!gvn().type(argument(0))->maybe_null(), "should not be null");
5257     slow_call = new CallStaticJavaNode(C, tf,
5258                                 SharedRuntime::get_resolve_opt_virtual_call_stub(), method);
5259     slow_call->set_optimized_virtual(true);
5260   }
5261   if (CallGenerator::is_inlined_method_handle_intrinsic(this->method(), bci(), callee())) {
5262     // To be able to issue a direct call (optimized virtual or virtual)
5263     // and skip a call to MH.linkTo*/invokeBasic adapter, additional information
5264     // about the method being invoked should be attached to the call site to
5265     // make resolution logic work (see SharedRuntime::resolve_{virtual,opt_virtual}_call_C).
5266     slow_call->set_override_symbolic_info(true);
5267   }
5268   set_arguments_for_java_call(slow_call);
5269   set_edges_for_java_call(slow_call);
5270   return slow_call;
5271 }
5272 
5273 
5274 /**
5275  * Build special case code for calls to hashCode on an object. This call may
5276  * be virtual (invokevirtual) or bound (invokespecial). For each case we generate
5277  * slightly different code.
5278  */
5279 bool LibraryCallKit::inline_native_hashcode(bool is_virtual, bool is_static) {
5280   assert(is_static == callee()->is_static(), "correct intrinsic selection");
5281   assert(!(is_virtual && is_static), "either virtual, special, or static");
5282 
5283   enum { _slow_path = 1, _fast_path, _null_path, PATH_LIMIT };
5284 
5285   RegionNode* result_reg = new RegionNode(PATH_LIMIT);
5286   PhiNode*    result_val = new PhiNode(result_reg, TypeInt::INT);
5287   PhiNode*    result_io  = new PhiNode(result_reg, Type::ABIO);
5288   PhiNode*    result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
5289   Node* obj = argument(0);
5290 
5291   // Don't intrinsify hashcode on inline types for now.
5292   // The "is locked" runtime check also subsumes the inline type check (as inline types cannot be locked) and goes to the slow path.
5293   if (gvn().type(obj)->is_inlinetypeptr()) {
5294     return false;
5295   }
5296 
5297   if (!is_static) {
5298     // Check for hashing null object
5299     obj = null_check_receiver();
5300     if (stopped())  return true;        // unconditionally null
5301     result_reg->init_req(_null_path, top());
5302     result_val->init_req(_null_path, top());
5303   } else {
5304     // Do a null check, and return zero if null.
5305     // System.identityHashCode(null) == 0
5306     Node* null_ctl = top();
5307     obj = null_check_oop(obj, &null_ctl);
5308     result_reg->init_req(_null_path, null_ctl);
5309     result_val->init_req(_null_path, _gvn.intcon(0));
5310   }
5311 
5312   // Unconditionally null?  Then return right away.
5313   if (stopped()) {
5314     set_control( result_reg->in(_null_path));
5315     if (!stopped())
5316       set_result(result_val->in(_null_path));
5317     return true;
5318   }
5319 
5320   // We only go to the fast case code if we pass a number of guards.  The
5321   // paths which do not pass are accumulated in the slow_region.
5322   RegionNode* slow_region = new RegionNode(1);
5323   record_for_igvn(slow_region);
5324 
5325   // If this is a virtual call, we generate a funny guard.  We pull out
5326   // the vtable entry corresponding to hashCode() from the target object.
5327   // If the target method which we are calling happens to be the native
5328   // Object hashCode() method, we pass the guard.  We do not need this
5329   // guard for non-virtual calls -- the caller is known to be the native
5330   // Object hashCode().
5331   if (is_virtual) {
5332     // After null check, get the object's klass.
5333     Node* obj_klass = load_object_klass(obj);
5334     generate_virtual_guard(obj_klass, slow_region);
5335   }
5336 
5337   // Get the header out of the object, use LoadMarkNode when available
5338   Node* header_addr = basic_plus_adr(obj, oopDesc::mark_offset_in_bytes());
5339   // The control of the load must be null. Otherwise, the load can move before
5340   // the null check after castPP removal.
5341   Node* no_ctrl = nullptr;
5342   Node* header = make_load(no_ctrl, header_addr, TypeX_X, TypeX_X->basic_type(), MemNode::unordered);
5343 
5344   if (!UseObjectMonitorTable) {
5345     // Test the header to see if it is safe to read w.r.t. locking.
5346     // We cannot use the inline type mask as this may check bits that are overriden
5347     // by an object monitor's pointer when inflating locking.
5348     Node *lock_mask      = _gvn.MakeConX(markWord::lock_mask_in_place);
5349     Node *lmasked_header = _gvn.transform(new AndXNode(header, lock_mask));
5350     Node *monitor_val   = _gvn.MakeConX(markWord::monitor_value);
5351     Node *chk_monitor   = _gvn.transform(new CmpXNode(lmasked_header, monitor_val));
5352     Node *test_monitor  = _gvn.transform(new BoolNode(chk_monitor, BoolTest::eq));
5353 
5354     generate_slow_guard(test_monitor, slow_region);
5355   }
5356 
5357   // Get the hash value and check to see that it has been properly assigned.
5358   // We depend on hash_mask being at most 32 bits and avoid the use of
5359   // hash_mask_in_place because it could be larger than 32 bits in a 64-bit
5360   // vm: see markWord.hpp.
5361   Node *hash_mask      = _gvn.intcon(markWord::hash_mask);
5362   Node *hash_shift     = _gvn.intcon(markWord::hash_shift);
5363   Node *hshifted_header= _gvn.transform(new URShiftXNode(header, hash_shift));
5364   // This hack lets the hash bits live anywhere in the mark object now, as long
5365   // as the shift drops the relevant bits into the low 32 bits.  Note that
5366   // Java spec says that HashCode is an int so there's no point in capturing
5367   // an 'X'-sized hashcode (32 in 32-bit build or 64 in 64-bit build).
5368   hshifted_header      = ConvX2I(hshifted_header);
5369   Node *hash_val       = _gvn.transform(new AndINode(hshifted_header, hash_mask));
5370 
5371   Node *no_hash_val    = _gvn.intcon(markWord::no_hash);
5372   Node *chk_assigned   = _gvn.transform(new CmpINode( hash_val, no_hash_val));
5373   Node *test_assigned  = _gvn.transform(new BoolNode( chk_assigned, BoolTest::eq));
5374 
5375   generate_slow_guard(test_assigned, slow_region);
5376 
5377   Node* init_mem = reset_memory();
5378   // fill in the rest of the null path:
5379   result_io ->init_req(_null_path, i_o());
5380   result_mem->init_req(_null_path, init_mem);
5381 
5382   result_val->init_req(_fast_path, hash_val);
5383   result_reg->init_req(_fast_path, control());
5384   result_io ->init_req(_fast_path, i_o());
5385   result_mem->init_req(_fast_path, init_mem);
5386 
5387   // Generate code for the slow case.  We make a call to hashCode().
5388   set_control(_gvn.transform(slow_region));
5389   if (!stopped()) {
5390     // No need for PreserveJVMState, because we're using up the present state.
5391     set_all_memory(init_mem);
5392     vmIntrinsics::ID hashCode_id = is_static ? vmIntrinsics::_identityHashCode : vmIntrinsics::_hashCode;
5393     CallJavaNode* slow_call = generate_method_call(hashCode_id, is_virtual, is_static, false);
5394     Node* slow_result = set_results_for_java_call(slow_call);
5395     // this->control() comes from set_results_for_java_call
5396     result_reg->init_req(_slow_path, control());
5397     result_val->init_req(_slow_path, slow_result);
5398     result_io  ->set_req(_slow_path, i_o());
5399     result_mem ->set_req(_slow_path, reset_memory());
5400   }
5401 
5402   // Return the combined state.
5403   set_i_o(        _gvn.transform(result_io)  );
5404   set_all_memory( _gvn.transform(result_mem));
5405 
5406   set_result(result_reg, result_val);
5407   return true;
5408 }
5409 
5410 //---------------------------inline_native_getClass----------------------------
5411 // public final native Class<?> java.lang.Object.getClass();
5412 //
5413 // Build special case code for calls to getClass on an object.
5414 bool LibraryCallKit::inline_native_getClass() {
5415   Node* obj = argument(0);
5416   if (obj->is_InlineType()) {
5417     const Type* t = _gvn.type(obj);
5418     if (t->maybe_null()) {
5419       null_check(obj);
5420     }
5421     set_result(makecon(TypeInstPtr::make(t->inline_klass()->java_mirror())));
5422     return true;
5423   }
5424   obj = null_check_receiver();
5425   if (stopped())  return true;
5426   set_result(load_mirror_from_klass(load_object_klass(obj)));
5427   return true;
5428 }
5429 
5430 //-----------------inline_native_Reflection_getCallerClass---------------------
5431 // public static native Class<?> sun.reflect.Reflection.getCallerClass();
5432 //
5433 // In the presence of deep enough inlining, getCallerClass() becomes a no-op.
5434 //
5435 // NOTE: This code must perform the same logic as JVM_GetCallerClass
5436 // in that it must skip particular security frames and checks for
5437 // caller sensitive methods.
5438 bool LibraryCallKit::inline_native_Reflection_getCallerClass() {
5439 #ifndef PRODUCT
5440   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5441     tty->print_cr("Attempting to inline sun.reflect.Reflection.getCallerClass");
5442   }
5443 #endif
5444 
5445   if (!jvms()->has_method()) {
5446 #ifndef PRODUCT
5447     if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5448       tty->print_cr("  Bailing out because intrinsic was inlined at top level");
5449     }
5450 #endif
5451     return false;
5452   }
5453 
5454   // Walk back up the JVM state to find the caller at the required
5455   // depth.
5456   JVMState* caller_jvms = jvms();
5457 
5458   // Cf. JVM_GetCallerClass
5459   // NOTE: Start the loop at depth 1 because the current JVM state does
5460   // not include the Reflection.getCallerClass() frame.
5461   for (int n = 1; caller_jvms != nullptr; caller_jvms = caller_jvms->caller(), n++) {
5462     ciMethod* m = caller_jvms->method();
5463     switch (n) {
5464     case 0:
5465       fatal("current JVM state does not include the Reflection.getCallerClass frame");
5466       break;
5467     case 1:
5468       // Frame 0 and 1 must be caller sensitive (see JVM_GetCallerClass).
5469       if (!m->caller_sensitive()) {
5470 #ifndef PRODUCT
5471         if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5472           tty->print_cr("  Bailing out: CallerSensitive annotation expected at frame %d", n);
5473         }
5474 #endif
5475         return false;  // bail-out; let JVM_GetCallerClass do the work
5476       }
5477       break;
5478     default:
5479       if (!m->is_ignored_by_security_stack_walk()) {
5480         // We have reached the desired frame; return the holder class.
5481         // Acquire method holder as java.lang.Class and push as constant.
5482         ciInstanceKlass* caller_klass = caller_jvms->method()->holder();
5483         ciInstance* caller_mirror = caller_klass->java_mirror();
5484         set_result(makecon(TypeInstPtr::make(caller_mirror)));
5485 
5486 #ifndef PRODUCT
5487         if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5488           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());
5489           tty->print_cr("  JVM state at this point:");
5490           for (int i = jvms()->depth(), n = 1; i >= 1; i--, n++) {
5491             ciMethod* m = jvms()->of_depth(i)->method();
5492             tty->print_cr("   %d) %s.%s", n, m->holder()->name()->as_utf8(), m->name()->as_utf8());
5493           }
5494         }
5495 #endif
5496         return true;
5497       }
5498       break;
5499     }
5500   }
5501 
5502 #ifndef PRODUCT
5503   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5504     tty->print_cr("  Bailing out because caller depth exceeded inlining depth = %d", jvms()->depth());
5505     tty->print_cr("  JVM state at this point:");
5506     for (int i = jvms()->depth(), n = 1; i >= 1; i--, n++) {
5507       ciMethod* m = jvms()->of_depth(i)->method();
5508       tty->print_cr("   %d) %s.%s", n, m->holder()->name()->as_utf8(), m->name()->as_utf8());
5509     }
5510   }
5511 #endif
5512 
5513   return false;  // bail-out; let JVM_GetCallerClass do the work
5514 }
5515 
5516 bool LibraryCallKit::inline_fp_conversions(vmIntrinsics::ID id) {
5517   Node* arg = argument(0);
5518   Node* result = nullptr;
5519 
5520   switch (id) {
5521   case vmIntrinsics::_floatToRawIntBits:    result = new MoveF2INode(arg);  break;
5522   case vmIntrinsics::_intBitsToFloat:       result = new MoveI2FNode(arg);  break;
5523   case vmIntrinsics::_doubleToRawLongBits:  result = new MoveD2LNode(arg);  break;
5524   case vmIntrinsics::_longBitsToDouble:     result = new MoveL2DNode(arg);  break;
5525   case vmIntrinsics::_floatToFloat16:       result = new ConvF2HFNode(arg); break;
5526   case vmIntrinsics::_float16ToFloat:       result = new ConvHF2FNode(arg); break;
5527 
5528   case vmIntrinsics::_doubleToLongBits: {
5529     // two paths (plus control) merge in a wood
5530     RegionNode *r = new RegionNode(3);
5531     Node *phi = new PhiNode(r, TypeLong::LONG);
5532 
5533     Node *cmpisnan = _gvn.transform(new CmpDNode(arg, arg));
5534     // Build the boolean node
5535     Node *bolisnan = _gvn.transform(new BoolNode(cmpisnan, BoolTest::ne));
5536 
5537     // Branch either way.
5538     // NaN case is less traveled, which makes all the difference.
5539     IfNode *ifisnan = create_and_xform_if(control(), bolisnan, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
5540     Node *opt_isnan = _gvn.transform(ifisnan);
5541     assert( opt_isnan->is_If(), "Expect an IfNode");
5542     IfNode *opt_ifisnan = (IfNode*)opt_isnan;
5543     Node *iftrue = _gvn.transform(new IfTrueNode(opt_ifisnan));
5544 
5545     set_control(iftrue);
5546 
5547     static const jlong nan_bits = CONST64(0x7ff8000000000000);
5548     Node *slow_result = longcon(nan_bits); // return NaN
5549     phi->init_req(1, _gvn.transform( slow_result ));
5550     r->init_req(1, iftrue);
5551 
5552     // Else fall through
5553     Node *iffalse = _gvn.transform(new IfFalseNode(opt_ifisnan));
5554     set_control(iffalse);
5555 
5556     phi->init_req(2, _gvn.transform(new MoveD2LNode(arg)));
5557     r->init_req(2, iffalse);
5558 
5559     // Post merge
5560     set_control(_gvn.transform(r));
5561     record_for_igvn(r);
5562 
5563     C->set_has_split_ifs(true); // Has chance for split-if optimization
5564     result = phi;
5565     assert(result->bottom_type()->isa_long(), "must be");
5566     break;
5567   }
5568 
5569   case vmIntrinsics::_floatToIntBits: {
5570     // two paths (plus control) merge in a wood
5571     RegionNode *r = new RegionNode(3);
5572     Node *phi = new PhiNode(r, TypeInt::INT);
5573 
5574     Node *cmpisnan = _gvn.transform(new CmpFNode(arg, arg));
5575     // Build the boolean node
5576     Node *bolisnan = _gvn.transform(new BoolNode(cmpisnan, BoolTest::ne));
5577 
5578     // Branch either way.
5579     // NaN case is less traveled, which makes all the difference.
5580     IfNode *ifisnan = create_and_xform_if(control(), bolisnan, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
5581     Node *opt_isnan = _gvn.transform(ifisnan);
5582     assert( opt_isnan->is_If(), "Expect an IfNode");
5583     IfNode *opt_ifisnan = (IfNode*)opt_isnan;
5584     Node *iftrue = _gvn.transform(new IfTrueNode(opt_ifisnan));
5585 
5586     set_control(iftrue);
5587 
5588     static const jint nan_bits = 0x7fc00000;
5589     Node *slow_result = makecon(TypeInt::make(nan_bits)); // return NaN
5590     phi->init_req(1, _gvn.transform( slow_result ));
5591     r->init_req(1, iftrue);
5592 
5593     // Else fall through
5594     Node *iffalse = _gvn.transform(new IfFalseNode(opt_ifisnan));
5595     set_control(iffalse);
5596 
5597     phi->init_req(2, _gvn.transform(new MoveF2INode(arg)));
5598     r->init_req(2, iffalse);
5599 
5600     // Post merge
5601     set_control(_gvn.transform(r));
5602     record_for_igvn(r);
5603 
5604     C->set_has_split_ifs(true); // Has chance for split-if optimization
5605     result = phi;
5606     assert(result->bottom_type()->isa_int(), "must be");
5607     break;
5608   }
5609 
5610   default:
5611     fatal_unexpected_iid(id);
5612     break;
5613   }
5614   set_result(_gvn.transform(result));
5615   return true;
5616 }
5617 
5618 bool LibraryCallKit::inline_fp_range_check(vmIntrinsics::ID id) {
5619   Node* arg = argument(0);
5620   Node* result = nullptr;
5621 
5622   switch (id) {
5623   case vmIntrinsics::_floatIsInfinite:
5624     result = new IsInfiniteFNode(arg);
5625     break;
5626   case vmIntrinsics::_floatIsFinite:
5627     result = new IsFiniteFNode(arg);
5628     break;
5629   case vmIntrinsics::_doubleIsInfinite:
5630     result = new IsInfiniteDNode(arg);
5631     break;
5632   case vmIntrinsics::_doubleIsFinite:
5633     result = new IsFiniteDNode(arg);
5634     break;
5635   default:
5636     fatal_unexpected_iid(id);
5637     break;
5638   }
5639   set_result(_gvn.transform(result));
5640   return true;
5641 }
5642 
5643 //----------------------inline_unsafe_copyMemory-------------------------
5644 // public native void Unsafe.copyMemory0(Object srcBase, long srcOffset, Object destBase, long destOffset, long bytes);
5645 
5646 static bool has_wide_mem(PhaseGVN& gvn, Node* addr, Node* base) {
5647   const TypeAryPtr* addr_t = gvn.type(addr)->isa_aryptr();
5648   const Type*       base_t = gvn.type(base);
5649 
5650   bool in_native = (base_t == TypePtr::NULL_PTR);
5651   bool in_heap   = !TypePtr::NULL_PTR->higher_equal(base_t);
5652   bool is_mixed  = !in_heap && !in_native;
5653 
5654   if (is_mixed) {
5655     return true; // mixed accesses can touch both on-heap and off-heap memory
5656   }
5657   if (in_heap) {
5658     bool is_prim_array = (addr_t != nullptr) && (addr_t->elem() != Type::BOTTOM);
5659     if (!is_prim_array) {
5660       // Though Unsafe.copyMemory() ensures at runtime for on-heap accesses that base is a primitive array,
5661       // there's not enough type information available to determine proper memory slice for it.
5662       return true;
5663     }
5664   }
5665   return false;
5666 }
5667 
5668 bool LibraryCallKit::inline_unsafe_copyMemory() {
5669   if (callee()->is_static())  return false;  // caller must have the capability!
5670   null_check_receiver();  // null-check receiver
5671   if (stopped())  return true;
5672 
5673   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
5674 
5675   Node* src_base =         argument(1);  // type: oop
5676   Node* src_off  = ConvL2X(argument(2)); // type: long
5677   Node* dst_base =         argument(4);  // type: oop
5678   Node* dst_off  = ConvL2X(argument(5)); // type: long
5679   Node* size     = ConvL2X(argument(7)); // type: long
5680 
5681   assert(Unsafe_field_offset_to_byte_offset(11) == 11,
5682          "fieldOffset must be byte-scaled");
5683 
5684   Node* src_addr = make_unsafe_address(src_base, src_off);
5685   Node* dst_addr = make_unsafe_address(dst_base, dst_off);
5686 
5687   Node* thread = _gvn.transform(new ThreadLocalNode());
5688   Node* doing_unsafe_access_addr = off_heap_plus_addr(thread, in_bytes(JavaThread::doing_unsafe_access_offset()));
5689   BasicType doing_unsafe_access_bt = T_BYTE;
5690   assert((sizeof(bool) * CHAR_BIT) == 8, "not implemented");
5691 
5692   // update volatile field
5693   store_to_memory(control(), doing_unsafe_access_addr, intcon(1), doing_unsafe_access_bt, MemNode::unordered);
5694 
5695   int flags = RC_LEAF | RC_NO_FP;
5696 
5697   const TypePtr* dst_type = TypePtr::BOTTOM;
5698 
5699   // Adjust memory effects of the runtime call based on input values.
5700   if (!has_wide_mem(_gvn, src_addr, src_base) &&
5701       !has_wide_mem(_gvn, dst_addr, dst_base)) {
5702     dst_type = _gvn.type(dst_addr)->is_ptr(); // narrow out memory
5703 
5704     const TypePtr* src_type = _gvn.type(src_addr)->is_ptr();
5705     if (C->get_alias_index(src_type) == C->get_alias_index(dst_type)) {
5706       flags |= RC_NARROW_MEM; // narrow in memory
5707     }
5708   }
5709 
5710   // Call it.  Note that the length argument is not scaled.
5711   make_runtime_call(flags,
5712                     OptoRuntime::fast_arraycopy_Type(),
5713                     StubRoutines::unsafe_arraycopy(),
5714                     "unsafe_arraycopy",
5715                     dst_type,
5716                     src_addr, dst_addr, size XTOP);
5717 
5718   store_to_memory(control(), doing_unsafe_access_addr, intcon(0), doing_unsafe_access_bt, MemNode::unordered);
5719 
5720   return true;
5721 }
5722 
5723 // unsafe_setmemory(void *base, ulong offset, size_t length, char fill_value);
5724 // Fill 'length' bytes starting from 'base[offset]' with 'fill_value'
5725 bool LibraryCallKit::inline_unsafe_setMemory() {
5726   if (callee()->is_static())  return false;  // caller must have the capability!
5727   null_check_receiver();  // null-check receiver
5728   if (stopped())  return true;
5729 
5730   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
5731 
5732   Node* dst_base =         argument(1);  // type: oop
5733   Node* dst_off  = ConvL2X(argument(2)); // type: long
5734   Node* size     = ConvL2X(argument(4)); // type: long
5735   Node* byte     =         argument(6);  // type: byte
5736 
5737   assert(Unsafe_field_offset_to_byte_offset(11) == 11,
5738          "fieldOffset must be byte-scaled");
5739 
5740   Node* dst_addr = make_unsafe_address(dst_base, dst_off);
5741 
5742   Node* thread = _gvn.transform(new ThreadLocalNode());
5743   Node* doing_unsafe_access_addr = off_heap_plus_addr(thread, in_bytes(JavaThread::doing_unsafe_access_offset()));
5744   BasicType doing_unsafe_access_bt = T_BYTE;
5745   assert((sizeof(bool) * CHAR_BIT) == 8, "not implemented");
5746 
5747   // update volatile field
5748   store_to_memory(control(), doing_unsafe_access_addr, intcon(1), doing_unsafe_access_bt, MemNode::unordered);
5749 
5750   int flags = RC_LEAF | RC_NO_FP;
5751 
5752   const TypePtr* dst_type = TypePtr::BOTTOM;
5753 
5754   // Adjust memory effects of the runtime call based on input values.
5755   if (!has_wide_mem(_gvn, dst_addr, dst_base)) {
5756     dst_type = _gvn.type(dst_addr)->is_ptr(); // narrow out memory
5757 
5758     flags |= RC_NARROW_MEM; // narrow in memory
5759   }
5760 
5761   // Call it.  Note that the length argument is not scaled.
5762   make_runtime_call(flags,
5763                     OptoRuntime::unsafe_setmemory_Type(),
5764                     StubRoutines::unsafe_setmemory(),
5765                     "unsafe_setmemory",
5766                     dst_type,
5767                     dst_addr, size XTOP, byte);
5768 
5769   store_to_memory(control(), doing_unsafe_access_addr, intcon(0), doing_unsafe_access_bt, MemNode::unordered);
5770 
5771   return true;
5772 }
5773 
5774 #undef XTOP
5775 
5776 //------------------------clone_coping-----------------------------------
5777 // Helper function for inline_native_clone.
5778 void LibraryCallKit::copy_to_clone(Node* obj, Node* alloc_obj, Node* obj_size, bool is_array) {
5779   assert(obj_size != nullptr, "");
5780   Node* raw_obj = alloc_obj->in(1);
5781   assert(alloc_obj->is_CheckCastPP() && raw_obj->is_Proj() && raw_obj->in(0)->is_Allocate(), "");
5782 
5783   AllocateNode* alloc = nullptr;
5784   if (ReduceBulkZeroing &&
5785       // If we are implementing an array clone without knowing its source type
5786       // (can happen when compiling the array-guarded branch of a reflective
5787       // Object.clone() invocation), initialize the array within the allocation.
5788       // This is needed because some GCs (e.g. ZGC) might fall back in this case
5789       // to a runtime clone call that assumes fully initialized source arrays.
5790       (!is_array || obj->get_ptr_type()->isa_aryptr() != nullptr)) {
5791     // We will be completely responsible for initializing this object -
5792     // mark Initialize node as complete.
5793     alloc = AllocateNode::Ideal_allocation(alloc_obj);
5794     // The object was just allocated - there should be no any stores!
5795     guarantee(alloc != nullptr && alloc->maybe_set_complete(&_gvn), "");
5796     // Mark as complete_with_arraycopy so that on AllocateNode
5797     // expansion, we know this AllocateNode is initialized by an array
5798     // copy and a StoreStore barrier exists after the array copy.
5799     alloc->initialization()->set_complete_with_arraycopy();
5800   }
5801 
5802   Node* size = _gvn.transform(obj_size);
5803   access_clone(obj, alloc_obj, size, is_array);
5804 
5805   // Do not let reads from the cloned object float above the arraycopy.
5806   if (alloc != nullptr) {
5807     // Do not let stores that initialize this object be reordered with
5808     // a subsequent store that would make this object accessible by
5809     // other threads.
5810     // Record what AllocateNode this StoreStore protects so that
5811     // escape analysis can go from the MemBarStoreStoreNode to the
5812     // AllocateNode and eliminate the MemBarStoreStoreNode if possible
5813     // based on the escape status of the AllocateNode.
5814     insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
5815   } else {
5816     insert_mem_bar(Op_MemBarCPUOrder);
5817   }
5818 }
5819 
5820 //------------------------inline_native_clone----------------------------
5821 // protected native Object java.lang.Object.clone();
5822 //
5823 // Here are the simple edge cases:
5824 //  null receiver => normal trap
5825 //  virtual and clone was overridden => slow path to out-of-line clone
5826 //  not cloneable or finalizer => slow path to out-of-line Object.clone
5827 //
5828 // The general case has two steps, allocation and copying.
5829 // Allocation has two cases, and uses GraphKit::new_instance or new_array.
5830 //
5831 // Copying also has two cases, oop arrays and everything else.
5832 // Oop arrays use arrayof_oop_arraycopy (same as System.arraycopy).
5833 // Everything else uses the tight inline loop supplied by CopyArrayNode.
5834 //
5835 // These steps fold up nicely if and when the cloned object's klass
5836 // can be sharply typed as an object array, a type array, or an instance.
5837 //
5838 bool LibraryCallKit::inline_native_clone(bool is_virtual) {
5839   PhiNode* result_val;
5840 
5841   // Set the reexecute bit for the interpreter to reexecute
5842   // the bytecode that invokes Object.clone if deoptimization happens.
5843   { PreserveReexecuteState preexecs(this);
5844     jvms()->set_should_reexecute(true);
5845 
5846     Node* obj = argument(0);
5847     obj = null_check_receiver();
5848     if (stopped())  return true;
5849 
5850     const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
5851     if (obj_type->is_inlinetypeptr()) {
5852       // If the object to clone is an inline type, we can simply return it (i.e. a nop) since inline types have
5853       // no identity.
5854       set_result(obj);
5855       return true;
5856     }
5857 
5858     // If we are going to clone an instance, we need its exact type to
5859     // know the number and types of fields to convert the clone to
5860     // loads/stores. Maybe a speculative type can help us.
5861     if (!obj_type->klass_is_exact() &&
5862         obj_type->speculative_type() != nullptr &&
5863         obj_type->speculative_type()->is_instance_klass() &&
5864         !obj_type->speculative_type()->is_inlinetype()) {
5865       ciInstanceKlass* spec_ik = obj_type->speculative_type()->as_instance_klass();
5866       if (spec_ik->nof_nonstatic_fields() <= ArrayCopyLoadStoreMaxElem &&
5867           !spec_ik->has_injected_fields()) {
5868         if (!obj_type->isa_instptr() ||
5869             obj_type->is_instptr()->instance_klass()->has_subklass()) {
5870           obj = maybe_cast_profiled_obj(obj, obj_type->speculative_type(), false);
5871         }
5872       }
5873     }
5874 
5875     // Conservatively insert a memory barrier on all memory slices.
5876     // Do not let writes into the original float below the clone.
5877     insert_mem_bar(Op_MemBarCPUOrder);
5878 
5879     // paths into result_reg:
5880     enum {
5881       _slow_path = 1,     // out-of-line call to clone method (virtual or not)
5882       _objArray_path,     // plain array allocation, plus arrayof_oop_arraycopy
5883       _array_path,        // plain array allocation, plus arrayof_long_arraycopy
5884       _instance_path,     // plain instance allocation, plus arrayof_long_arraycopy
5885       PATH_LIMIT
5886     };
5887     RegionNode* result_reg = new RegionNode(PATH_LIMIT);
5888     result_val             = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
5889     PhiNode*    result_i_o = new PhiNode(result_reg, Type::ABIO);
5890     PhiNode*    result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
5891     record_for_igvn(result_reg);
5892 
5893     Node* obj_klass = load_object_klass(obj);
5894     // We only go to the fast case code if we pass a number of guards.
5895     // The paths which do not pass are accumulated in the slow_region.
5896     RegionNode* slow_region = new RegionNode(1);
5897     record_for_igvn(slow_region);
5898 
5899     Node* array_obj = obj;
5900     Node* array_ctl = generate_array_guard(obj_klass, (RegionNode*)nullptr, &array_obj);
5901     if (array_ctl != nullptr) {
5902       // It's an array.
5903       PreserveJVMState pjvms(this);
5904       set_control(array_ctl);
5905 
5906       BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
5907       const TypeAryPtr* ary_ptr = obj_type->isa_aryptr();
5908       if (UseArrayFlattening && bs->array_copy_requires_gc_barriers(true, T_OBJECT, true, false, BarrierSetC2::Expansion) &&
5909           obj_type->can_be_inline_array() &&
5910           (ary_ptr == nullptr || (!ary_ptr->is_not_flat() && (!ary_ptr->is_flat() || ary_ptr->elem()->inline_klass()->contains_oops())))) {
5911         // Flat inline type array may have object field that would require a
5912         // write barrier. Conservatively, go to slow path.
5913         generate_fair_guard(flat_array_test(obj_klass), slow_region);
5914       }
5915 
5916       if (!stopped()) {
5917         Node* obj_length = load_array_length(array_obj);
5918         Node* array_size = nullptr; // Size of the array without object alignment padding.
5919         Node* alloc_obj = new_array(obj_klass, obj_length, 0, &array_size, /*deoptimize_on_exception=*/true);
5920 
5921         BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
5922         if (bs->array_copy_requires_gc_barriers(true, T_OBJECT, true, false, BarrierSetC2::Parsing)) {
5923           // If it is an oop array, it requires very special treatment,
5924           // because gc barriers are required when accessing the array.
5925           Node* is_obja = generate_refArray_guard(obj_klass, (RegionNode*)nullptr);
5926           if (is_obja != nullptr) {
5927             PreserveJVMState pjvms2(this);
5928             set_control(is_obja);
5929             // Generate a direct call to the right arraycopy function(s).
5930             // Clones are always tightly coupled.
5931             ArrayCopyNode* ac = ArrayCopyNode::make(this, true, array_obj, intcon(0), alloc_obj, intcon(0), obj_length, true, false);
5932             ac->set_clone_oop_array();
5933             Node* n = _gvn.transform(ac);
5934             assert(n == ac, "cannot disappear");
5935             ac->connect_outputs(this, /*deoptimize_on_exception=*/true);
5936 
5937             result_reg->init_req(_objArray_path, control());
5938             result_val->init_req(_objArray_path, alloc_obj);
5939             result_i_o ->set_req(_objArray_path, i_o());
5940             result_mem ->set_req(_objArray_path, reset_memory());
5941           }
5942         }
5943         // Otherwise, there are no barriers to worry about.
5944         // (We can dispense with card marks if we know the allocation
5945         //  comes out of eden (TLAB)...  In fact, ReduceInitialCardMarks
5946         //  causes the non-eden paths to take compensating steps to
5947         //  simulate a fresh allocation, so that no further
5948         //  card marks are required in compiled code to initialize
5949         //  the object.)
5950 
5951         if (!stopped()) {
5952           copy_to_clone(obj, alloc_obj, array_size, true);
5953 
5954           // Present the results of the copy.
5955           result_reg->init_req(_array_path, control());
5956           result_val->init_req(_array_path, alloc_obj);
5957           result_i_o ->set_req(_array_path, i_o());
5958           result_mem ->set_req(_array_path, reset_memory());
5959         }
5960       }
5961     }
5962 
5963     if (!stopped()) {
5964       // It's an instance (we did array above).  Make the slow-path tests.
5965       // If this is a virtual call, we generate a funny guard.  We grab
5966       // the vtable entry corresponding to clone() from the target object.
5967       // If the target method which we are calling happens to be the
5968       // Object clone() method, we pass the guard.  We do not need this
5969       // guard for non-virtual calls; the caller is known to be the native
5970       // Object clone().
5971       if (is_virtual) {
5972         generate_virtual_guard(obj_klass, slow_region);
5973       }
5974 
5975       // The object must be easily cloneable and must not have a finalizer.
5976       // Both of these conditions may be checked in a single test.
5977       // We could optimize the test further, but we don't care.
5978       generate_misc_flags_guard(obj_klass,
5979                                 // Test both conditions:
5980                                 KlassFlags::_misc_is_cloneable_fast | KlassFlags::_misc_has_finalizer,
5981                                 // Must be cloneable but not finalizer:
5982                                 KlassFlags::_misc_is_cloneable_fast,
5983                                 slow_region);
5984     }
5985 
5986     if (!stopped()) {
5987       // It's an instance, and it passed the slow-path tests.
5988       PreserveJVMState pjvms(this);
5989       Node* obj_size = nullptr; // Total object size, including object alignment padding.
5990       // Need to deoptimize on exception from allocation since Object.clone intrinsic
5991       // is reexecuted if deoptimization occurs and there could be problems when merging
5992       // exception state between multiple Object.clone versions (reexecute=true vs reexecute=false).
5993       Node* alloc_obj = new_instance(obj_klass, nullptr, &obj_size, /*deoptimize_on_exception=*/true);
5994 
5995       copy_to_clone(obj, alloc_obj, obj_size, false);
5996 
5997       // Present the results of the slow call.
5998       result_reg->init_req(_instance_path, control());
5999       result_val->init_req(_instance_path, alloc_obj);
6000       result_i_o ->set_req(_instance_path, i_o());
6001       result_mem ->set_req(_instance_path, reset_memory());
6002     }
6003 
6004     // Generate code for the slow case.  We make a call to clone().
6005     set_control(_gvn.transform(slow_region));
6006     if (!stopped()) {
6007       PreserveJVMState pjvms(this);
6008       CallJavaNode* slow_call = generate_method_call(vmIntrinsics::_clone, is_virtual, false, true);
6009       // We need to deoptimize on exception (see comment above)
6010       Node* slow_result = set_results_for_java_call(slow_call, false, /* deoptimize */ true);
6011       // this->control() comes from set_results_for_java_call
6012       result_reg->init_req(_slow_path, control());
6013       result_val->init_req(_slow_path, slow_result);
6014       result_i_o ->set_req(_slow_path, i_o());
6015       result_mem ->set_req(_slow_path, reset_memory());
6016     }
6017 
6018     // Return the combined state.
6019     set_control(    _gvn.transform(result_reg));
6020     set_i_o(        _gvn.transform(result_i_o));
6021     set_all_memory( _gvn.transform(result_mem));
6022   } // original reexecute is set back here
6023 
6024   set_result(_gvn.transform(result_val));
6025   return true;
6026 }
6027 
6028 // If we have a tightly coupled allocation, the arraycopy may take care
6029 // of the array initialization. If one of the guards we insert between
6030 // the allocation and the arraycopy causes a deoptimization, an
6031 // uninitialized array will escape the compiled method. To prevent that
6032 // we set the JVM state for uncommon traps between the allocation and
6033 // the arraycopy to the state before the allocation so, in case of
6034 // deoptimization, we'll reexecute the allocation and the
6035 // initialization.
6036 JVMState* LibraryCallKit::arraycopy_restore_alloc_state(AllocateArrayNode* alloc, int& saved_reexecute_sp) {
6037   if (alloc != nullptr) {
6038     ciMethod* trap_method = alloc->jvms()->method();
6039     int trap_bci = alloc->jvms()->bci();
6040 
6041     if (!C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_intrinsic) &&
6042         !C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_null_check)) {
6043       // Make sure there's no store between the allocation and the
6044       // arraycopy otherwise visible side effects could be rexecuted
6045       // in case of deoptimization and cause incorrect execution.
6046       bool no_interfering_store = true;
6047       Node* mem = alloc->in(TypeFunc::Memory);
6048       if (mem->is_MergeMem()) {
6049         for (MergeMemStream mms(merged_memory(), mem->as_MergeMem()); mms.next_non_empty2(); ) {
6050           Node* n = mms.memory();
6051           if (n != mms.memory2() && !(n->is_Proj() && n->in(0) == alloc->initialization())) {
6052             assert(n->is_Store(), "what else?");
6053             no_interfering_store = false;
6054             break;
6055           }
6056         }
6057       } else {
6058         for (MergeMemStream mms(merged_memory()); mms.next_non_empty(); ) {
6059           Node* n = mms.memory();
6060           if (n != mem && !(n->is_Proj() && n->in(0) == alloc->initialization())) {
6061             assert(n->is_Store(), "what else?");
6062             no_interfering_store = false;
6063             break;
6064           }
6065         }
6066       }
6067 
6068       if (no_interfering_store) {
6069         SafePointNode* sfpt = create_safepoint_with_state_before_array_allocation(alloc);
6070 
6071         JVMState* saved_jvms = jvms();
6072         saved_reexecute_sp = _reexecute_sp;
6073 
6074         set_jvms(sfpt->jvms());
6075         _reexecute_sp = jvms()->sp();
6076 
6077         return saved_jvms;
6078       }
6079     }
6080   }
6081   return nullptr;
6082 }
6083 
6084 // Clone the JVMState of the array allocation and create a new safepoint with it. Re-push the array length to the stack
6085 // such that uncommon traps can be emitted to re-execute the array allocation in the interpreter.
6086 SafePointNode* LibraryCallKit::create_safepoint_with_state_before_array_allocation(const AllocateArrayNode* alloc) const {
6087   JVMState* old_jvms = alloc->jvms()->clone_shallow(C);
6088   uint size = alloc->req();
6089   SafePointNode* sfpt = new SafePointNode(size, old_jvms);
6090   old_jvms->set_map(sfpt);
6091   for (uint i = 0; i < size; i++) {
6092     sfpt->init_req(i, alloc->in(i));
6093   }
6094   int adjustment = 1;
6095   const TypeAryKlassPtr* ary_klass_ptr = alloc->in(AllocateNode::KlassNode)->bottom_type()->is_aryklassptr();
6096   if (ary_klass_ptr->is_null_free()) {
6097     // A null-free, tightly coupled array allocation can only come from LibraryCallKit::inline_newArray which
6098     // also requires the componentType and initVal on stack for re-execution.
6099     // Re-create and push the componentType.
6100     ciArrayKlass* klass = ary_klass_ptr->exact_klass()->as_array_klass();
6101     ciInstance* instance = klass->component_mirror_instance();
6102     const TypeInstPtr* t_instance = TypeInstPtr::make(instance);
6103     sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp(), makecon(t_instance));
6104     adjustment++;
6105   }
6106   // re-push array length for deoptimization
6107   sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp() + adjustment - 1, alloc->in(AllocateNode::ALength));
6108   if (ary_klass_ptr->is_null_free()) {
6109     // Re-create and push the initVal.
6110     Node* init_val = alloc->in(AllocateNode::InitValue);
6111     if (init_val == nullptr) {
6112       init_val = InlineTypeNode::make_all_zero(_gvn, ary_klass_ptr->elem()->is_instklassptr()->instance_klass()->as_inline_klass());
6113     } else if (UseCompressedOops) {
6114       init_val = _gvn.transform(new DecodeNNode(init_val, init_val->bottom_type()->make_ptr()));
6115     }
6116     sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp() + adjustment, init_val);
6117     adjustment++;
6118   }
6119   old_jvms->set_sp(old_jvms->sp() + adjustment);
6120   old_jvms->set_monoff(old_jvms->monoff() + adjustment);
6121   old_jvms->set_scloff(old_jvms->scloff() + adjustment);
6122   old_jvms->set_endoff(old_jvms->endoff() + adjustment);
6123   old_jvms->set_should_reexecute(true);
6124 
6125   sfpt->set_i_o(map()->i_o());
6126   sfpt->set_memory(map()->memory());
6127   sfpt->set_control(map()->control());
6128   return sfpt;
6129 }
6130 
6131 // In case of a deoptimization, we restart execution at the
6132 // allocation, allocating a new array. We would leave an uninitialized
6133 // array in the heap that GCs wouldn't expect. Move the allocation
6134 // after the traps so we don't allocate the array if we
6135 // deoptimize. This is possible because tightly_coupled_allocation()
6136 // guarantees there's no observer of the allocated array at this point
6137 // and the control flow is simple enough.
6138 void LibraryCallKit::arraycopy_move_allocation_here(AllocateArrayNode* alloc, Node* dest, JVMState* saved_jvms_before_guards,
6139                                                     int saved_reexecute_sp, uint new_idx) {
6140   if (saved_jvms_before_guards != nullptr && !stopped()) {
6141     replace_unrelated_uncommon_traps_with_alloc_state(alloc, saved_jvms_before_guards);
6142 
6143     assert(alloc != nullptr, "only with a tightly coupled allocation");
6144     // restore JVM state to the state at the arraycopy
6145     saved_jvms_before_guards->map()->set_control(map()->control());
6146     assert(saved_jvms_before_guards->map()->memory() == map()->memory(), "memory state changed?");
6147     assert(saved_jvms_before_guards->map()->i_o() == map()->i_o(), "IO state changed?");
6148     // If we've improved the types of some nodes (null check) while
6149     // emitting the guards, propagate them to the current state
6150     map()->replaced_nodes().apply(saved_jvms_before_guards->map(), new_idx);
6151     set_jvms(saved_jvms_before_guards);
6152     _reexecute_sp = saved_reexecute_sp;
6153 
6154     // Remove the allocation from above the guards
6155     CallProjections* callprojs = alloc->extract_projections(true);
6156     InitializeNode* init = alloc->initialization();
6157     Node* alloc_mem = alloc->in(TypeFunc::Memory);
6158     C->gvn_replace_by(callprojs->fallthrough_ioproj, alloc->in(TypeFunc::I_O));
6159     init->replace_mem_projs_by(alloc_mem, C);
6160 
6161     // The CastIINode created in GraphKit::new_array (in AllocateArrayNode::make_ideal_length) must stay below
6162     // the allocation (i.e. is only valid if the allocation succeeds):
6163     // 1) replace CastIINode with AllocateArrayNode's length here
6164     // 2) Create CastIINode again once allocation has moved (see below) at the end of this method
6165     //
6166     // Multiple identical CastIINodes might exist here. Each GraphKit::load_array_length() call will generate
6167     // new separate CastIINode (arraycopy guard checks or any array length use between array allocation and ararycopy)
6168     Node* init_control = init->proj_out(TypeFunc::Control);
6169     Node* alloc_length = alloc->Ideal_length();
6170 #ifdef ASSERT
6171     Node* prev_cast = nullptr;
6172 #endif
6173     for (uint i = 0; i < init_control->outcnt(); i++) {
6174       Node* init_out = init_control->raw_out(i);
6175       if (init_out->is_CastII() && init_out->in(TypeFunc::Control) == init_control && init_out->in(1) == alloc_length) {
6176 #ifdef ASSERT
6177         if (prev_cast == nullptr) {
6178           prev_cast = init_out;
6179         } else {
6180           if (prev_cast->cmp(*init_out) == false) {
6181             prev_cast->dump();
6182             init_out->dump();
6183             assert(false, "not equal CastIINode");
6184           }
6185         }
6186 #endif
6187         C->gvn_replace_by(init_out, alloc_length);
6188       }
6189     }
6190     C->gvn_replace_by(init->proj_out(TypeFunc::Control), alloc->in(0));
6191 
6192     // move the allocation here (after the guards)
6193     _gvn.hash_delete(alloc);
6194     alloc->set_req(TypeFunc::Control, control());
6195     alloc->set_req(TypeFunc::I_O, i_o());
6196     Node *mem = reset_memory();
6197     set_all_memory(mem);
6198     alloc->set_req(TypeFunc::Memory, mem);
6199     set_control(init->proj_out_or_null(TypeFunc::Control));
6200     set_i_o(callprojs->fallthrough_ioproj);
6201 
6202     // Update memory as done in GraphKit::set_output_for_allocation()
6203     const TypeInt* length_type = _gvn.find_int_type(alloc->in(AllocateNode::ALength));
6204     const TypeOopPtr* ary_type = _gvn.type(alloc->in(AllocateNode::KlassNode))->is_klassptr()->as_instance_type();
6205     if (ary_type->isa_aryptr() && length_type != nullptr) {
6206       ary_type = ary_type->is_aryptr()->cast_to_size(length_type);
6207     }
6208     const TypePtr* telemref = ary_type->add_offset(Type::OffsetBot);
6209     int            elemidx  = C->get_alias_index(telemref);
6210     // Need to properly move every memory projection for the Initialize
6211 #ifdef ASSERT
6212     int mark_idx = C->get_alias_index(ary_type->add_offset(oopDesc::mark_offset_in_bytes()));
6213     int klass_idx = C->get_alias_index(ary_type->add_offset(oopDesc::klass_offset_in_bytes()));
6214 #endif
6215     auto move_proj = [&](ProjNode* proj) {
6216       int alias_idx = C->get_alias_index(proj->adr_type());
6217       assert(alias_idx == Compile::AliasIdxRaw ||
6218              alias_idx == elemidx ||
6219              alias_idx == mark_idx ||
6220              alias_idx == klass_idx, "should be raw memory or array element type");
6221       set_memory(proj, alias_idx);
6222     };
6223     init->for_each_proj(move_proj, TypeFunc::Memory);
6224 
6225     Node* allocx = _gvn.transform(alloc);
6226     assert(allocx == alloc, "where has the allocation gone?");
6227     assert(dest->is_CheckCastPP(), "not an allocation result?");
6228 
6229     _gvn.hash_delete(dest);
6230     dest->set_req(0, control());
6231     Node* destx = _gvn.transform(dest);
6232     assert(destx == dest, "where has the allocation result gone?");
6233 
6234     array_ideal_length(alloc, ary_type, true);
6235   }
6236 }
6237 
6238 // Unrelated UCTs between the array allocation and the array copy, which are considered safe by tightly_coupled_allocation(),
6239 // need to be replaced by an UCT with a state before the array allocation (including the array length). This is necessary
6240 // because we could hit one of these UCTs (which are executed before the emitted array copy guards and the actual array
6241 // allocation which is moved down in arraycopy_move_allocation_here()). When later resuming execution in the interpreter,
6242 // we would have wrongly skipped the array allocation. To prevent this, we resume execution at the array allocation in
6243 // the interpreter similar to what we are doing for the newly emitted guards for the array copy.
6244 void LibraryCallKit::replace_unrelated_uncommon_traps_with_alloc_state(AllocateArrayNode* alloc,
6245                                                                        JVMState* saved_jvms_before_guards) {
6246   if (saved_jvms_before_guards->map()->control()->is_IfProj()) {
6247     // There is at least one unrelated uncommon trap which needs to be replaced.
6248     SafePointNode* sfpt = create_safepoint_with_state_before_array_allocation(alloc);
6249 
6250     JVMState* saved_jvms = jvms();
6251     const int saved_reexecute_sp = _reexecute_sp;
6252     set_jvms(sfpt->jvms());
6253     _reexecute_sp = jvms()->sp();
6254 
6255     replace_unrelated_uncommon_traps_with_alloc_state(saved_jvms_before_guards);
6256 
6257     // Restore state
6258     set_jvms(saved_jvms);
6259     _reexecute_sp = saved_reexecute_sp;
6260   }
6261 }
6262 
6263 // Replace the unrelated uncommon traps with new uncommon trap nodes by reusing the action and reason. The new uncommon
6264 // traps will have the state of the array allocation. Let the old uncommon trap nodes die.
6265 void LibraryCallKit::replace_unrelated_uncommon_traps_with_alloc_state(JVMState* saved_jvms_before_guards) {
6266   Node* if_proj = saved_jvms_before_guards->map()->control(); // Start the search right before the newly emitted guards
6267   while (if_proj->is_IfProj()) {
6268     CallStaticJavaNode* uncommon_trap = get_uncommon_trap_from_success_proj(if_proj);
6269     if (uncommon_trap != nullptr) {
6270       create_new_uncommon_trap(uncommon_trap);
6271     }
6272     assert(if_proj->in(0)->is_If(), "must be If");
6273     if_proj = if_proj->in(0)->in(0);
6274   }
6275   assert(if_proj->is_Proj() && if_proj->in(0)->is_Initialize(),
6276          "must have reached control projection of init node");
6277 }
6278 
6279 void LibraryCallKit::create_new_uncommon_trap(CallStaticJavaNode* uncommon_trap_call) {
6280   const int trap_request = uncommon_trap_call->uncommon_trap_request();
6281   assert(trap_request != 0, "no valid UCT trap request");
6282   PreserveJVMState pjvms(this);
6283   set_control(uncommon_trap_call->in(0));
6284   uncommon_trap(Deoptimization::trap_request_reason(trap_request),
6285                 Deoptimization::trap_request_action(trap_request));
6286   assert(stopped(), "Should be stopped");
6287   _gvn.hash_delete(uncommon_trap_call);
6288   uncommon_trap_call->set_req(0, top()); // not used anymore, kill it
6289 }
6290 
6291 // Common checks for array sorting intrinsics arguments.
6292 // Returns `true` if checks passed.
6293 bool LibraryCallKit::check_array_sort_arguments(Node* elementType, Node* obj, BasicType& bt) {
6294   // check address of the class
6295   if (elementType == nullptr || elementType->is_top()) {
6296     return false;  // dead path
6297   }
6298   const TypeInstPtr* elem_klass = gvn().type(elementType)->isa_instptr();
6299   if (elem_klass == nullptr) {
6300     return false;  // dead path
6301   }
6302   // java_mirror_type() returns non-null for compile-time Class constants only
6303   ciType* elem_type = elem_klass->java_mirror_type();
6304   if (elem_type == nullptr) {
6305     return false;
6306   }
6307   bt = elem_type->basic_type();
6308   // Disable the intrinsic if the CPU does not support SIMD sort
6309   if (!Matcher::supports_simd_sort(bt)) {
6310     return false;
6311   }
6312   // check address of the array
6313   if (obj == nullptr || obj->is_top()) {
6314     return false;  // dead path
6315   }
6316   const TypeAryPtr* obj_t = _gvn.type(obj)->isa_aryptr();
6317   if (obj_t == nullptr || obj_t->elem() == Type::BOTTOM) {
6318     return false; // failed input validation
6319   }
6320   return true;
6321 }
6322 
6323 //------------------------------inline_array_partition-----------------------
6324 bool LibraryCallKit::inline_array_partition() {
6325   address stubAddr = StubRoutines::select_array_partition_function();
6326   if (stubAddr == nullptr) {
6327     return false; // Intrinsic's stub is not implemented on this platform
6328   }
6329   assert(callee()->signature()->size() == 9, "arrayPartition has 8 parameters (one long)");
6330 
6331   // no receiver because it is a static method
6332   Node* elementType     = argument(0);
6333   Node* obj             = argument(1);
6334   Node* offset          = argument(2); // long
6335   Node* fromIndex       = argument(4);
6336   Node* toIndex         = argument(5);
6337   Node* indexPivot1     = argument(6);
6338   Node* indexPivot2     = argument(7);
6339   // PartitionOperation:  argument(8) is ignored
6340 
6341   Node* pivotIndices = nullptr;
6342   BasicType bt = T_ILLEGAL;
6343 
6344   if (!check_array_sort_arguments(elementType, obj, bt)) {
6345     return false;
6346   }
6347   null_check(obj);
6348   // If obj is dead, only null-path is taken.
6349   if (stopped()) {
6350     return true;
6351   }
6352   // Set the original stack and the reexecute bit for the interpreter to reexecute
6353   // the bytecode that invokes DualPivotQuicksort.partition() if deoptimization happens.
6354   { PreserveReexecuteState preexecs(this);
6355     jvms()->set_should_reexecute(true);
6356 
6357     Node* obj_adr = make_unsafe_address(obj, offset);
6358 
6359     // create the pivotIndices array of type int and size = 2
6360     Node* size = intcon(2);
6361     Node* klass_node = makecon(TypeKlassPtr::make(ciTypeArrayKlass::make(T_INT)));
6362     pivotIndices = new_array(klass_node, size, 0);  // no arguments to push
6363     AllocateArrayNode* alloc = tightly_coupled_allocation(pivotIndices);
6364     guarantee(alloc != nullptr, "created above");
6365     Node* pivotIndices_adr = basic_plus_adr(pivotIndices, arrayOopDesc::base_offset_in_bytes(T_INT));
6366 
6367     // pass the basic type enum to the stub
6368     Node* elemType = intcon(bt);
6369 
6370     // Call the stub
6371     const char *stubName = "array_partition_stub";
6372     make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::array_partition_Type(),
6373                       stubAddr, stubName, TypePtr::BOTTOM,
6374                       obj_adr, elemType, fromIndex, toIndex, pivotIndices_adr,
6375                       indexPivot1, indexPivot2);
6376 
6377   } // original reexecute is set back here
6378 
6379   if (!stopped()) {
6380     set_result(pivotIndices);
6381   }
6382 
6383   return true;
6384 }
6385 
6386 
6387 //------------------------------inline_array_sort-----------------------
6388 bool LibraryCallKit::inline_array_sort() {
6389   address stubAddr = StubRoutines::select_arraysort_function();
6390   if (stubAddr == nullptr) {
6391     return false; // Intrinsic's stub is not implemented on this platform
6392   }
6393   assert(callee()->signature()->size() == 7, "arraySort has 6 parameters (one long)");
6394 
6395   // no receiver because it is a static method
6396   Node* elementType     = argument(0);
6397   Node* obj             = argument(1);
6398   Node* offset          = argument(2); // long
6399   Node* fromIndex       = argument(4);
6400   Node* toIndex         = argument(5);
6401   // SortOperation:       argument(6) is ignored
6402 
6403   BasicType bt = T_ILLEGAL;
6404 
6405   if (!check_array_sort_arguments(elementType, obj, bt)) {
6406     return false;
6407   }
6408   null_check(obj);
6409   // If obj is dead, only null-path is taken.
6410   if (stopped()) {
6411     return true;
6412   }
6413   Node* obj_adr = make_unsafe_address(obj, offset);
6414 
6415   // pass the basic type enum to the stub
6416   Node* elemType = intcon(bt);
6417 
6418   // Call the stub.
6419   const char *stubName = "arraysort_stub";
6420   make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::array_sort_Type(),
6421                     stubAddr, stubName, TypePtr::BOTTOM,
6422                     obj_adr, elemType, fromIndex, toIndex);
6423 
6424   return true;
6425 }
6426 
6427 
6428 //------------------------------inline_arraycopy-----------------------
6429 // public static native void java.lang.System.arraycopy(Object src,  int  srcPos,
6430 //                                                      Object dest, int destPos,
6431 //                                                      int length);
6432 bool LibraryCallKit::inline_arraycopy() {
6433   // Get the arguments.
6434   Node* src         = argument(0);  // type: oop
6435   Node* src_offset  = argument(1);  // type: int
6436   Node* dest        = argument(2);  // type: oop
6437   Node* dest_offset = argument(3);  // type: int
6438   Node* length      = argument(4);  // type: int
6439 
6440   uint new_idx = C->unique();
6441 
6442   // Check for allocation before we add nodes that would confuse
6443   // tightly_coupled_allocation()
6444   AllocateArrayNode* alloc = tightly_coupled_allocation(dest);
6445 
6446   int saved_reexecute_sp = -1;
6447   JVMState* saved_jvms_before_guards = arraycopy_restore_alloc_state(alloc, saved_reexecute_sp);
6448   // See arraycopy_restore_alloc_state() comment
6449   // if alloc == null we don't have to worry about a tightly coupled allocation so we can emit all needed guards
6450   // if saved_jvms_before_guards is not null (then alloc is not null) then we can handle guards and a tightly coupled allocation
6451   // if saved_jvms_before_guards is null and alloc is not null, we can't emit any guards
6452   bool can_emit_guards = (alloc == nullptr || saved_jvms_before_guards != nullptr);
6453 
6454   // The following tests must be performed
6455   // (1) src and dest are arrays.
6456   // (2) src and dest arrays must have elements of the same BasicType
6457   // (3) src and dest must not be null.
6458   // (4) src_offset must not be negative.
6459   // (5) dest_offset must not be negative.
6460   // (6) length must not be negative.
6461   // (7) src_offset + length must not exceed length of src.
6462   // (8) dest_offset + length must not exceed length of dest.
6463   // (9) each element of an oop array must be assignable
6464 
6465   // (3) src and dest must not be null.
6466   // always do this here because we need the JVM state for uncommon traps
6467   Node* null_ctl = top();
6468   src  = saved_jvms_before_guards != nullptr ? null_check_oop(src, &null_ctl, true, true) : null_check(src, T_ARRAY);
6469   assert(null_ctl->is_top(), "no null control here");
6470   dest = null_check(dest, T_ARRAY);
6471 
6472   if (!can_emit_guards) {
6473     // if saved_jvms_before_guards is null and alloc is not null, we don't emit any
6474     // guards but the arraycopy node could still take advantage of a
6475     // tightly allocated allocation. tightly_coupled_allocation() is
6476     // called again to make sure it takes the null check above into
6477     // account: the null check is mandatory and if it caused an
6478     // uncommon trap to be emitted then the allocation can't be
6479     // considered tightly coupled in this context.
6480     alloc = tightly_coupled_allocation(dest);
6481   }
6482 
6483   bool validated = false;
6484 
6485   const Type* src_type  = _gvn.type(src);
6486   const Type* dest_type = _gvn.type(dest);
6487   const TypeAryPtr* top_src  = src_type->isa_aryptr();
6488   const TypeAryPtr* top_dest = dest_type->isa_aryptr();
6489 
6490   // Do we have the type of src?
6491   bool has_src = (top_src != nullptr && top_src->elem() != Type::BOTTOM);
6492   // Do we have the type of dest?
6493   bool has_dest = (top_dest != nullptr && top_dest->elem() != Type::BOTTOM);
6494   // Is the type for src from speculation?
6495   bool src_spec = false;
6496   // Is the type for dest from speculation?
6497   bool dest_spec = false;
6498 
6499   if ((!has_src || !has_dest) && can_emit_guards) {
6500     // We don't have sufficient type information, let's see if
6501     // speculative types can help. We need to have types for both src
6502     // and dest so that it pays off.
6503 
6504     // Do we already have or could we have type information for src
6505     bool could_have_src = has_src;
6506     // Do we already have or could we have type information for dest
6507     bool could_have_dest = has_dest;
6508 
6509     ciKlass* src_k = nullptr;
6510     if (!has_src) {
6511       src_k = src_type->speculative_type_not_null();
6512       if (src_k != nullptr && src_k->is_array_klass()) {
6513         could_have_src = true;
6514       }
6515     }
6516 
6517     ciKlass* dest_k = nullptr;
6518     if (!has_dest) {
6519       dest_k = dest_type->speculative_type_not_null();
6520       if (dest_k != nullptr && dest_k->is_array_klass()) {
6521         could_have_dest = true;
6522       }
6523     }
6524 
6525     if (could_have_src && could_have_dest) {
6526       // This is going to pay off so emit the required guards
6527       if (!has_src) {
6528         src = maybe_cast_profiled_obj(src, src_k, true);
6529         src_type  = _gvn.type(src);
6530         top_src  = src_type->isa_aryptr();
6531         has_src = (top_src != nullptr && top_src->elem() != Type::BOTTOM);
6532         src_spec = true;
6533       }
6534       if (!has_dest) {
6535         dest = maybe_cast_profiled_obj(dest, dest_k, true);
6536         dest_type  = _gvn.type(dest);
6537         top_dest  = dest_type->isa_aryptr();
6538         has_dest = (top_dest != nullptr && top_dest->elem() != Type::BOTTOM);
6539         dest_spec = true;
6540       }
6541     }
6542   }
6543 
6544   if (has_src && has_dest && can_emit_guards) {
6545     BasicType src_elem = top_src->isa_aryptr()->elem()->array_element_basic_type();
6546     BasicType dest_elem = top_dest->isa_aryptr()->elem()->array_element_basic_type();
6547     if (is_reference_type(src_elem, true)) src_elem = T_OBJECT;
6548     if (is_reference_type(dest_elem, true)) dest_elem = T_OBJECT;
6549 
6550     if (src_elem == dest_elem && top_src->is_flat() == top_dest->is_flat() && src_elem == T_OBJECT) {
6551       // If both arrays are object arrays then having the exact types
6552       // for both will remove the need for a subtype check at runtime
6553       // before the call and may make it possible to pick a faster copy
6554       // routine (without a subtype check on every element)
6555       // Do we have the exact type of src?
6556       bool could_have_src = src_spec;
6557       // Do we have the exact type of dest?
6558       bool could_have_dest = dest_spec;
6559       ciKlass* src_k = nullptr;
6560       ciKlass* dest_k = nullptr;
6561       if (!src_spec) {
6562         src_k = src_type->speculative_type_not_null();
6563         if (src_k != nullptr && src_k->is_array_klass()) {
6564           could_have_src = true;
6565         }
6566       }
6567       if (!dest_spec) {
6568         dest_k = dest_type->speculative_type_not_null();
6569         if (dest_k != nullptr && dest_k->is_array_klass()) {
6570           could_have_dest = true;
6571         }
6572       }
6573       if (could_have_src && could_have_dest) {
6574         // If we can have both exact types, emit the missing guards
6575         if (could_have_src && !src_spec) {
6576           src = maybe_cast_profiled_obj(src, src_k, true);
6577           src_type = _gvn.type(src);
6578           top_src = src_type->isa_aryptr();
6579         }
6580         if (could_have_dest && !dest_spec) {
6581           dest = maybe_cast_profiled_obj(dest, dest_k, true);
6582           dest_type = _gvn.type(dest);
6583           top_dest = dest_type->isa_aryptr();
6584         }
6585       }
6586     }
6587   }
6588 
6589   ciMethod* trap_method = method();
6590   int trap_bci = bci();
6591   if (saved_jvms_before_guards != nullptr) {
6592     trap_method = alloc->jvms()->method();
6593     trap_bci = alloc->jvms()->bci();
6594   }
6595 
6596   bool negative_length_guard_generated = false;
6597 
6598   if (!C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_intrinsic) &&
6599       can_emit_guards && !src->is_top() && !dest->is_top()) {
6600     // validate arguments: enables transformation the ArrayCopyNode
6601     validated = true;
6602 
6603     RegionNode* slow_region = new RegionNode(1);
6604     record_for_igvn(slow_region);
6605 
6606     // (1) src and dest are arrays.
6607     generate_non_array_guard(load_object_klass(src), slow_region, &src);
6608     generate_non_array_guard(load_object_klass(dest), slow_region, &dest);
6609 
6610     // (2) src and dest arrays must have elements of the same BasicType
6611     // done at macro expansion or at Ideal transformation time
6612 
6613     // (4) src_offset must not be negative.
6614     generate_negative_guard(src_offset, slow_region);
6615 
6616     // (5) dest_offset must not be negative.
6617     generate_negative_guard(dest_offset, slow_region);
6618 
6619     // (7) src_offset + length must not exceed length of src.
6620     generate_limit_guard(src_offset, length,
6621                          load_array_length(src),
6622                          slow_region);
6623 
6624     // (8) dest_offset + length must not exceed length of dest.
6625     generate_limit_guard(dest_offset, length,
6626                          load_array_length(dest),
6627                          slow_region);
6628 
6629     // (6) length must not be negative.
6630     // This is also checked in generate_arraycopy() during macro expansion, but
6631     // we also have to check it here for the case where the ArrayCopyNode will
6632     // be eliminated by Escape Analysis.
6633     if (EliminateAllocations) {
6634       generate_negative_guard(length, slow_region);
6635       negative_length_guard_generated = true;
6636     }
6637 
6638     // (9) each element of an oop array must be assignable
6639     Node* dest_klass = load_object_klass(dest);
6640     Node* refined_dest_klass = dest_klass;
6641     if (src != dest) {
6642       dest_klass = load_non_refined_array_klass(refined_dest_klass);
6643       Node* not_subtype_ctrl = gen_subtype_check(src, dest_klass);
6644       slow_region->add_req(not_subtype_ctrl);
6645     }
6646 
6647     // TODO 8350865 Improve this. What about atomicity? Make sure this is always folded for type arrays.
6648     // If destination is null-restricted, source must be null-restricted as well: src_null_restricted || !dst_null_restricted
6649     Node* src_klass = load_object_klass(src);
6650     Node* adr_prop_src = basic_plus_adr(top(), src_klass, in_bytes(ArrayKlass::properties_offset()));
6651     Node* prop_src = _gvn.transform(LoadNode::make(_gvn, control(), immutable_memory(), adr_prop_src,
6652                                                    _gvn.type(adr_prop_src)->is_ptr(), TypeInt::INT, T_INT,
6653                                                    MemNode::unordered));
6654     Node* adr_prop_dest = basic_plus_adr(top(), refined_dest_klass, in_bytes(ArrayKlass::properties_offset()));
6655     Node* prop_dest = _gvn.transform(LoadNode::make(_gvn, control(), immutable_memory(), adr_prop_dest,
6656                                                     _gvn.type(adr_prop_dest)->is_ptr(), TypeInt::INT, T_INT,
6657                                                     MemNode::unordered));
6658 
6659     const ArrayProperties props_null_restricted = ArrayProperties::Default().with_null_restricted();
6660     jint props_value = (jint)props_null_restricted.value();
6661 
6662     prop_dest = _gvn.transform(new XorINode(prop_dest, intcon(props_value)));
6663     prop_src = _gvn.transform(new OrINode(prop_dest, prop_src));
6664     prop_src = _gvn.transform(new AndINode(prop_src, intcon(props_value)));
6665 
6666     Node* chk = _gvn.transform(new CmpINode(prop_src, intcon(props_value)));
6667     Node* tst = _gvn.transform(new BoolNode(chk, BoolTest::ne));
6668     generate_fair_guard(tst, slow_region);
6669 
6670     // TODO 8350865 This is too strong
6671     generate_fair_guard(flat_array_test(src), slow_region);
6672     generate_fair_guard(flat_array_test(dest), slow_region);
6673 
6674     {
6675       PreserveJVMState pjvms(this);
6676       set_control(_gvn.transform(slow_region));
6677       uncommon_trap(Deoptimization::Reason_intrinsic,
6678                     Deoptimization::Action_make_not_entrant);
6679       assert(stopped(), "Should be stopped");
6680     }
6681 
6682     const TypeKlassPtr* dest_klass_t = _gvn.type(dest_klass)->isa_klassptr();
6683     if (dest_klass_t == nullptr) {
6684       // refined_dest_klass may not be an array, which leads to dest_klass being top. This means we
6685       // are in a dead path.
6686       uncommon_trap(Deoptimization::Reason_intrinsic,
6687                     Deoptimization::Action_make_not_entrant);
6688       return true;
6689     }
6690 
6691     const Type* toop = dest_klass_t->cast_to_exactness(false)->as_instance_type();
6692     src = _gvn.transform(new CheckCastPPNode(control(), src, toop));
6693     arraycopy_move_allocation_here(alloc, dest, saved_jvms_before_guards, saved_reexecute_sp, new_idx);
6694   }
6695 
6696   if (stopped()) {
6697     return true;
6698   }
6699 
6700   Node* dest_klass = load_object_klass(dest);
6701   dest_klass = load_non_refined_array_klass(dest_klass);
6702 
6703   ArrayCopyNode* ac = ArrayCopyNode::make(this, true, src, src_offset, dest, dest_offset, length, alloc != nullptr, negative_length_guard_generated,
6704                                           // Create LoadRange and LoadKlass nodes for use during macro expansion here
6705                                           // so the compiler has a chance to eliminate them: during macro expansion,
6706                                           // we have to set their control (CastPP nodes are eliminated).
6707                                           load_object_klass(src), dest_klass,
6708                                           load_array_length(src), load_array_length(dest));
6709 
6710   ac->set_arraycopy(validated);
6711 
6712   Node* n = _gvn.transform(ac);
6713   if (n == ac) {
6714     ac->connect_outputs(this);
6715   } else {
6716     assert(validated, "shouldn't transform if all arguments not validated");
6717     set_all_memory(n);
6718   }
6719   clear_upper_avx();
6720 
6721 
6722   return true;
6723 }
6724 
6725 
6726 // Helper function which determines if an arraycopy immediately follows
6727 // an allocation, with no intervening tests or other escapes for the object.
6728 AllocateArrayNode*
6729 LibraryCallKit::tightly_coupled_allocation(Node* ptr) {
6730   if (stopped())             return nullptr;  // no fast path
6731   if (!C->do_aliasing())     return nullptr;  // no MergeMems around
6732 
6733   AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(ptr);
6734   if (alloc == nullptr)  return nullptr;
6735 
6736   Node* rawmem = memory(Compile::AliasIdxRaw);
6737   // Is the allocation's memory state untouched?
6738   if (!(rawmem->is_Proj() && rawmem->in(0)->is_Initialize())) {
6739     // Bail out if there have been raw-memory effects since the allocation.
6740     // (Example:  There might have been a call or safepoint.)
6741     return nullptr;
6742   }
6743   rawmem = rawmem->in(0)->as_Initialize()->memory(Compile::AliasIdxRaw);
6744   if (!(rawmem->is_Proj() && rawmem->in(0) == alloc)) {
6745     return nullptr;
6746   }
6747 
6748   // There must be no unexpected observers of this allocation.
6749   for (DUIterator_Fast imax, i = ptr->fast_outs(imax); i < imax; i++) {
6750     Node* obs = ptr->fast_out(i);
6751     if (obs != this->map()) {
6752       return nullptr;
6753     }
6754   }
6755 
6756   // This arraycopy must unconditionally follow the allocation of the ptr.
6757   Node* alloc_ctl = ptr->in(0);
6758   Node* ctl = control();
6759   while (ctl != alloc_ctl) {
6760     // There may be guards which feed into the slow_region.
6761     // Any other control flow means that we might not get a chance
6762     // to finish initializing the allocated object.
6763     // Various low-level checks bottom out in uncommon traps. These
6764     // are considered safe since we've already checked above that
6765     // there is no unexpected observer of this allocation.
6766     if (get_uncommon_trap_from_success_proj(ctl) != nullptr) {
6767       assert(ctl->in(0)->is_If(), "must be If");
6768       ctl = ctl->in(0)->in(0);
6769     } else {
6770       return nullptr;
6771     }
6772   }
6773 
6774   // If we get this far, we have an allocation which immediately
6775   // precedes the arraycopy, and we can take over zeroing the new object.
6776   // The arraycopy will finish the initialization, and provide
6777   // a new control state to which we will anchor the destination pointer.
6778 
6779   return alloc;
6780 }
6781 
6782 CallStaticJavaNode* LibraryCallKit::get_uncommon_trap_from_success_proj(Node* node) {
6783   if (node->is_IfProj()) {
6784     IfProjNode* other_proj = node->as_IfProj()->other_if_proj();
6785     for (DUIterator_Fast jmax, j = other_proj->fast_outs(jmax); j < jmax; j++) {
6786       Node* obs = other_proj->fast_out(j);
6787       if (obs->in(0) == other_proj && obs->is_CallStaticJava() &&
6788           (obs->as_CallStaticJava()->entry_point() == OptoRuntime::uncommon_trap_blob()->entry_point())) {
6789         return obs->as_CallStaticJava();
6790       }
6791     }
6792   }
6793   return nullptr;
6794 }
6795 
6796 //-------------inline_encodeISOArray-----------------------------------
6797 // int sun.nio.cs.ISO_8859_1.Encoder#encodeISOArray0(byte[] sa, int sp, byte[] da, int dp, int len)
6798 // int java.lang.StringCoding#encodeISOArray0(byte[] sa, int sp, byte[] da, int dp, int len)
6799 // int java.lang.StringCoding#encodeAsciiArray0(char[] sa, int sp, byte[] da, int dp, int len)
6800 // encode char[] to byte[] in ISO_8859_1 or ASCII
6801 bool LibraryCallKit::inline_encodeISOArray(bool ascii) {
6802   assert(callee()->signature()->size() == 5, "encodeISOArray has 5 parameters");
6803   // no receiver since it is static method
6804   Node *src         = argument(0);
6805   Node *src_offset  = argument(1);
6806   Node *dst         = argument(2);
6807   Node *dst_offset  = argument(3);
6808   Node *length      = argument(4);
6809 
6810   // Cast source & target arrays to not-null
6811   src = must_be_not_null(src, true);
6812   dst = must_be_not_null(dst, true);
6813   if (stopped()) {
6814     return true;
6815   }
6816 
6817   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
6818   const TypeAryPtr* dst_type = dst->Value(&_gvn)->isa_aryptr();
6819   if (src_type == nullptr || src_type->elem() == Type::BOTTOM ||
6820       dst_type == nullptr || dst_type->elem() == Type::BOTTOM) {
6821     // failed array check
6822     return false;
6823   }
6824 
6825   // Figure out the size and type of the elements we will be copying.
6826   BasicType src_elem = src_type->elem()->array_element_basic_type();
6827   BasicType dst_elem = dst_type->elem()->array_element_basic_type();
6828   if (!((src_elem == T_CHAR) || (src_elem== T_BYTE)) || dst_elem != T_BYTE) {
6829     return false;
6830   }
6831 
6832   // Check source & target bounds
6833   RegionNode* bailout = create_bailout();
6834   generate_string_range_check(src, src_offset, length, src_elem == T_BYTE, bailout);
6835   generate_string_range_check(dst, dst_offset, length, false, bailout);
6836   if (check_bailout(bailout)) {
6837     return true;
6838   }
6839 
6840   Node* src_start = array_element_address(src, src_offset, T_CHAR);
6841   Node* dst_start = array_element_address(dst, dst_offset, dst_elem);
6842   // 'src_start' points to src array + scaled offset
6843   // 'dst_start' points to dst array + scaled offset
6844 
6845   const TypeAryPtr* mtype = TypeAryPtr::BYTES;
6846   Node* enc = new EncodeISOArrayNode(control(), memory(mtype), src_start, dst_start, length, ascii);
6847   enc = _gvn.transform(enc);
6848   Node* res_mem = _gvn.transform(new SCMemProjNode(enc));
6849   set_memory(res_mem, mtype);
6850   set_result(enc);
6851   clear_upper_avx();
6852 
6853   return true;
6854 }
6855 
6856 //-------------inline_multiplyToLen-----------------------------------
6857 bool LibraryCallKit::inline_multiplyToLen() {
6858   assert(UseMultiplyToLenIntrinsic, "not implemented on this platform");
6859 
6860   address stubAddr = StubRoutines::multiplyToLen();
6861   if (stubAddr == nullptr) {
6862     return false; // Intrinsic's stub is not implemented on this platform
6863   }
6864   const char* stubName = "multiplyToLen";
6865 
6866   assert(callee()->signature()->size() == 5, "multiplyToLen has 5 parameters");
6867 
6868   // no receiver because it is a static method
6869   Node* x    = argument(0);
6870   Node* xlen = argument(1);
6871   Node* y    = argument(2);
6872   Node* ylen = argument(3);
6873   Node* z    = argument(4);
6874 
6875   x = must_be_not_null(x, true);
6876   y = must_be_not_null(y, true);
6877 
6878   const TypeAryPtr* x_type = x->Value(&_gvn)->isa_aryptr();
6879   const TypeAryPtr* y_type = y->Value(&_gvn)->isa_aryptr();
6880   if (x_type == nullptr || x_type->elem() == Type::BOTTOM ||
6881       y_type == nullptr || y_type->elem() == Type::BOTTOM) {
6882     // failed array check
6883     return false;
6884   }
6885 
6886   BasicType x_elem = x_type->elem()->array_element_basic_type();
6887   BasicType y_elem = y_type->elem()->array_element_basic_type();
6888   if (x_elem != T_INT || y_elem != T_INT) {
6889     return false;
6890   }
6891 
6892   Node* x_start = array_element_address(x, intcon(0), x_elem);
6893   Node* y_start = array_element_address(y, intcon(0), y_elem);
6894   // 'x_start' points to x array + scaled xlen
6895   // 'y_start' points to y array + scaled ylen
6896 
6897   Node* z_start = array_element_address(z, intcon(0), T_INT);
6898 
6899   Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
6900                                  OptoRuntime::multiplyToLen_Type(),
6901                                  stubAddr, stubName, TypePtr::BOTTOM,
6902                                  x_start, xlen, y_start, ylen, z_start);
6903 
6904   C->set_has_split_ifs(true); // Has chance for split-if optimization
6905   set_result(z);
6906   return true;
6907 }
6908 
6909 //-------------inline_squareToLen------------------------------------
6910 bool LibraryCallKit::inline_squareToLen() {
6911   assert(UseSquareToLenIntrinsic, "not implemented on this platform");
6912 
6913   address stubAddr = StubRoutines::squareToLen();
6914   if (stubAddr == nullptr) {
6915     return false; // Intrinsic's stub is not implemented on this platform
6916   }
6917   const char* stubName = "squareToLen";
6918 
6919   assert(callee()->signature()->size() == 4, "implSquareToLen has 4 parameters");
6920 
6921   Node* x    = argument(0);
6922   Node* len  = argument(1);
6923   Node* z    = argument(2);
6924   Node* zlen = argument(3);
6925 
6926   x = must_be_not_null(x, true);
6927   z = must_be_not_null(z, true);
6928 
6929   const TypeAryPtr* x_type = x->Value(&_gvn)->isa_aryptr();
6930   const TypeAryPtr* z_type = z->Value(&_gvn)->isa_aryptr();
6931   if (x_type == nullptr || x_type->elem() == Type::BOTTOM ||
6932       z_type == nullptr || z_type->elem() == Type::BOTTOM) {
6933     // failed array check
6934     return false;
6935   }
6936 
6937   BasicType x_elem = x_type->elem()->array_element_basic_type();
6938   BasicType z_elem = z_type->elem()->array_element_basic_type();
6939   if (x_elem != T_INT || z_elem != T_INT) {
6940     return false;
6941   }
6942 
6943 
6944   Node* x_start = array_element_address(x, intcon(0), x_elem);
6945   Node* z_start = array_element_address(z, intcon(0), z_elem);
6946 
6947   Node*  call = make_runtime_call(RC_LEAF|RC_NO_FP,
6948                                   OptoRuntime::squareToLen_Type(),
6949                                   stubAddr, stubName, TypePtr::BOTTOM,
6950                                   x_start, len, z_start, zlen);
6951 
6952   set_result(z);
6953   return true;
6954 }
6955 
6956 //-------------inline_mulAdd------------------------------------------
6957 bool LibraryCallKit::inline_mulAdd() {
6958   assert(UseMulAddIntrinsic, "not implemented on this platform");
6959 
6960   address stubAddr = StubRoutines::mulAdd();
6961   if (stubAddr == nullptr) {
6962     return false; // Intrinsic's stub is not implemented on this platform
6963   }
6964   const char* stubName = "mulAdd";
6965 
6966   assert(callee()->signature()->size() == 5, "mulAdd has 5 parameters");
6967 
6968   Node* out      = argument(0);
6969   Node* in       = argument(1);
6970   Node* offset   = argument(2);
6971   Node* len      = argument(3);
6972   Node* k        = argument(4);
6973 
6974   in = must_be_not_null(in, true);
6975   out = must_be_not_null(out, true);
6976 
6977   const TypeAryPtr* out_type = out->Value(&_gvn)->isa_aryptr();
6978   const TypeAryPtr* in_type = in->Value(&_gvn)->isa_aryptr();
6979   if (out_type == nullptr || out_type->elem() == Type::BOTTOM ||
6980        in_type == nullptr ||  in_type->elem() == Type::BOTTOM) {
6981     // failed array check
6982     return false;
6983   }
6984 
6985   BasicType out_elem = out_type->elem()->array_element_basic_type();
6986   BasicType in_elem = in_type->elem()->array_element_basic_type();
6987   if (out_elem != T_INT || in_elem != T_INT) {
6988     return false;
6989   }
6990 
6991   Node* outlen = load_array_length(out);
6992   Node* new_offset = _gvn.transform(new SubINode(outlen, offset));
6993   Node* out_start = array_element_address(out, intcon(0), out_elem);
6994   Node* in_start = array_element_address(in, intcon(0), in_elem);
6995 
6996   Node*  call = make_runtime_call(RC_LEAF|RC_NO_FP,
6997                                   OptoRuntime::mulAdd_Type(),
6998                                   stubAddr, stubName, TypePtr::BOTTOM,
6999                                   out_start,in_start, new_offset, len, k);
7000   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7001   set_result(result);
7002   return true;
7003 }
7004 
7005 //-------------inline_montgomeryMultiply-----------------------------------
7006 bool LibraryCallKit::inline_montgomeryMultiply() {
7007   address stubAddr = StubRoutines::montgomeryMultiply();
7008   if (stubAddr == nullptr) {
7009     return false; // Intrinsic's stub is not implemented on this platform
7010   }
7011 
7012   assert(UseMontgomeryMultiplyIntrinsic, "not implemented on this platform");
7013   const char* stubName = "montgomery_multiply";
7014 
7015   assert(callee()->signature()->size() == 7, "montgomeryMultiply has 7 parameters");
7016 
7017   Node* a    = argument(0);
7018   Node* b    = argument(1);
7019   Node* n    = argument(2);
7020   Node* len  = argument(3);
7021   Node* inv  = argument(4);
7022   Node* m    = argument(6);
7023 
7024   const TypeAryPtr* a_type = a->Value(&_gvn)->isa_aryptr();
7025   const TypeAryPtr* b_type = b->Value(&_gvn)->isa_aryptr();
7026   const TypeAryPtr* n_type = n->Value(&_gvn)->isa_aryptr();
7027   const TypeAryPtr* m_type = m->Value(&_gvn)->isa_aryptr();
7028   if (a_type == nullptr || a_type->elem() == Type::BOTTOM ||
7029       b_type == nullptr || b_type->elem() == Type::BOTTOM ||
7030       n_type == nullptr || n_type->elem() == Type::BOTTOM ||
7031       m_type == nullptr || m_type->elem() == Type::BOTTOM) {
7032     // failed array check
7033     return false;
7034   }
7035 
7036   BasicType a_elem = a_type->elem()->array_element_basic_type();
7037   BasicType b_elem = b_type->elem()->array_element_basic_type();
7038   BasicType n_elem = n_type->elem()->array_element_basic_type();
7039   BasicType m_elem = m_type->elem()->array_element_basic_type();
7040   if (a_elem != T_INT || b_elem != T_INT || n_elem != T_INT || m_elem != T_INT) {
7041     return false;
7042   }
7043 
7044   // Make the call
7045   {
7046     Node* a_start = array_element_address(a, intcon(0), a_elem);
7047     Node* b_start = array_element_address(b, intcon(0), b_elem);
7048     Node* n_start = array_element_address(n, intcon(0), n_elem);
7049     Node* m_start = array_element_address(m, intcon(0), m_elem);
7050 
7051     Node* call = make_runtime_call(RC_LEAF,
7052                                    OptoRuntime::montgomeryMultiply_Type(),
7053                                    stubAddr, stubName, TypePtr::BOTTOM,
7054                                    a_start, b_start, n_start, len, inv, top(),
7055                                    m_start);
7056     set_result(m);
7057   }
7058 
7059   return true;
7060 }
7061 
7062 bool LibraryCallKit::inline_montgomerySquare() {
7063   address stubAddr = StubRoutines::montgomerySquare();
7064   if (stubAddr == nullptr) {
7065     return false; // Intrinsic's stub is not implemented on this platform
7066   }
7067 
7068   assert(UseMontgomerySquareIntrinsic, "not implemented on this platform");
7069   const char* stubName = "montgomery_square";
7070 
7071   assert(callee()->signature()->size() == 6, "montgomerySquare has 6 parameters");
7072 
7073   Node* a    = argument(0);
7074   Node* n    = argument(1);
7075   Node* len  = argument(2);
7076   Node* inv  = argument(3);
7077   Node* m    = argument(5);
7078 
7079   const TypeAryPtr* a_type = a->Value(&_gvn)->isa_aryptr();
7080   const TypeAryPtr* n_type = n->Value(&_gvn)->isa_aryptr();
7081   const TypeAryPtr* m_type = m->Value(&_gvn)->isa_aryptr();
7082   if (a_type == nullptr || a_type->elem() == Type::BOTTOM ||
7083       n_type == nullptr || n_type->elem() == Type::BOTTOM ||
7084       m_type == nullptr || m_type->elem() == Type::BOTTOM) {
7085     // failed array check
7086     return false;
7087   }
7088 
7089   BasicType a_elem = a_type->elem()->array_element_basic_type();
7090   BasicType n_elem = n_type->elem()->array_element_basic_type();
7091   BasicType m_elem = m_type->elem()->array_element_basic_type();
7092   if (a_elem != T_INT || n_elem != T_INT || m_elem != T_INT) {
7093     return false;
7094   }
7095 
7096   // Make the call
7097   {
7098     Node* a_start = array_element_address(a, intcon(0), a_elem);
7099     Node* n_start = array_element_address(n, intcon(0), n_elem);
7100     Node* m_start = array_element_address(m, intcon(0), m_elem);
7101 
7102     Node* call = make_runtime_call(RC_LEAF,
7103                                    OptoRuntime::montgomerySquare_Type(),
7104                                    stubAddr, stubName, TypePtr::BOTTOM,
7105                                    a_start, n_start, len, inv, top(),
7106                                    m_start);
7107     set_result(m);
7108   }
7109 
7110   return true;
7111 }
7112 
7113 bool LibraryCallKit::inline_bigIntegerShift(bool isRightShift) {
7114   address stubAddr = nullptr;
7115   const char* stubName = nullptr;
7116 
7117   stubAddr = isRightShift? StubRoutines::bigIntegerRightShift(): StubRoutines::bigIntegerLeftShift();
7118   if (stubAddr == nullptr) {
7119     return false; // Intrinsic's stub is not implemented on this platform
7120   }
7121 
7122   stubName = isRightShift? "bigIntegerRightShiftWorker" : "bigIntegerLeftShiftWorker";
7123 
7124   assert(callee()->signature()->size() == 5, "expected 5 arguments");
7125 
7126   Node* newArr = argument(0);
7127   Node* oldArr = argument(1);
7128   Node* newIdx = argument(2);
7129   Node* shiftCount = argument(3);
7130   Node* numIter = argument(4);
7131 
7132   const TypeAryPtr* newArr_type = newArr->Value(&_gvn)->isa_aryptr();
7133   const TypeAryPtr* oldArr_type = oldArr->Value(&_gvn)->isa_aryptr();
7134   if (newArr_type == nullptr || newArr_type->elem() == Type::BOTTOM ||
7135       oldArr_type == nullptr || oldArr_type->elem() == Type::BOTTOM) {
7136     return false;
7137   }
7138 
7139   BasicType newArr_elem = newArr_type->elem()->array_element_basic_type();
7140   BasicType oldArr_elem = oldArr_type->elem()->array_element_basic_type();
7141   if (newArr_elem != T_INT || oldArr_elem != T_INT) {
7142     return false;
7143   }
7144 
7145   // Make the call
7146   {
7147     Node* newArr_start = array_element_address(newArr, intcon(0), newArr_elem);
7148     Node* oldArr_start = array_element_address(oldArr, intcon(0), oldArr_elem);
7149 
7150     Node* call = make_runtime_call(RC_LEAF,
7151                                    OptoRuntime::bigIntegerShift_Type(),
7152                                    stubAddr,
7153                                    stubName,
7154                                    TypePtr::BOTTOM,
7155                                    newArr_start,
7156                                    oldArr_start,
7157                                    newIdx,
7158                                    shiftCount,
7159                                    numIter);
7160   }
7161 
7162   return true;
7163 }
7164 
7165 //-------------inline_vectorizedMismatch------------------------------
7166 bool LibraryCallKit::inline_vectorizedMismatch() {
7167   assert(UseVectorizedMismatchIntrinsic, "not implemented on this platform");
7168 
7169   assert(callee()->signature()->size() == 8, "vectorizedMismatch has 6 parameters");
7170   Node* obja    = argument(0); // Object
7171   Node* aoffset = argument(1); // long
7172   Node* objb    = argument(3); // Object
7173   Node* boffset = argument(4); // long
7174   Node* length  = argument(6); // int
7175   Node* scale   = argument(7); // int
7176 
7177   const TypeAryPtr* obja_t = _gvn.type(obja)->isa_aryptr();
7178   const TypeAryPtr* objb_t = _gvn.type(objb)->isa_aryptr();
7179   if (obja_t == nullptr || obja_t->elem() == Type::BOTTOM ||
7180       objb_t == nullptr || objb_t->elem() == Type::BOTTOM ||
7181       scale == top()) {
7182     return false; // failed input validation
7183   }
7184 
7185   Node* obja_adr = make_unsafe_address(obja, aoffset);
7186   Node* objb_adr = make_unsafe_address(objb, boffset);
7187 
7188   // Partial inlining handling for inputs smaller than ArrayOperationPartialInlineSize bytes in size.
7189   //
7190   //    inline_limit = ArrayOperationPartialInlineSize / element_size;
7191   //    if (length <= inline_limit) {
7192   //      inline_path:
7193   //        vmask   = VectorMaskGen length
7194   //        vload1  = LoadVectorMasked obja, vmask
7195   //        vload2  = LoadVectorMasked objb, vmask
7196   //        result1 = VectorCmpMasked vload1, vload2, vmask
7197   //    } else {
7198   //      call_stub_path:
7199   //        result2 = call vectorizedMismatch_stub(obja, objb, length, scale)
7200   //    }
7201   //    exit_block:
7202   //      return Phi(result1, result2);
7203   //
7204   enum { inline_path = 1,  // input is small enough to process it all at once
7205          stub_path   = 2,  // input is too large; call into the VM
7206          PATH_LIMIT  = 3
7207   };
7208 
7209   Node* exit_block = new RegionNode(PATH_LIMIT);
7210   Node* result_phi = new PhiNode(exit_block, TypeInt::INT);
7211   Node* memory_phi = new PhiNode(exit_block, Type::MEMORY, TypePtr::BOTTOM);
7212 
7213   Node* call_stub_path = control();
7214 
7215   BasicType elem_bt = T_ILLEGAL;
7216 
7217   const TypeInt* scale_t = _gvn.type(scale)->is_int();
7218   if (scale_t->is_con()) {
7219     switch (scale_t->get_con()) {
7220       case 0: elem_bt = T_BYTE;  break;
7221       case 1: elem_bt = T_SHORT; break;
7222       case 2: elem_bt = T_INT;   break;
7223       case 3: elem_bt = T_LONG;  break;
7224 
7225       default: elem_bt = T_ILLEGAL; break; // not supported
7226     }
7227   }
7228 
7229   int inline_limit = 0;
7230   bool do_partial_inline = false;
7231 
7232   if (elem_bt != T_ILLEGAL && ArrayOperationPartialInlineSize > 0) {
7233     inline_limit = ArrayOperationPartialInlineSize / type2aelembytes(elem_bt);
7234     do_partial_inline = inline_limit >= 16;
7235   }
7236 
7237   if (do_partial_inline) {
7238     assert(elem_bt != T_ILLEGAL, "sanity");
7239 
7240     if (Matcher::match_rule_supported_vector(Op_VectorMaskGen,    inline_limit, elem_bt) &&
7241         Matcher::match_rule_supported_vector(Op_LoadVectorMasked, inline_limit, elem_bt) &&
7242         Matcher::match_rule_supported_vector(Op_VectorCmpMasked,  inline_limit, elem_bt)) {
7243 
7244       const TypeVect* vt = TypeVect::make(elem_bt, inline_limit);
7245       Node* cmp_length = _gvn.transform(new CmpINode(length, intcon(inline_limit)));
7246       Node* bol_gt     = _gvn.transform(new BoolNode(cmp_length, BoolTest::gt));
7247 
7248       call_stub_path = generate_guard(bol_gt, nullptr, PROB_MIN);
7249 
7250       if (!stopped()) {
7251         Node* casted_length = _gvn.transform(new CastIINode(control(), length, TypeInt::make(0, inline_limit, Type::WidenMin)));
7252 
7253         const TypePtr* obja_adr_t = _gvn.type(obja_adr)->isa_ptr();
7254         const TypePtr* objb_adr_t = _gvn.type(objb_adr)->isa_ptr();
7255         Node* obja_adr_mem = memory(C->get_alias_index(obja_adr_t));
7256         Node* objb_adr_mem = memory(C->get_alias_index(objb_adr_t));
7257 
7258         Node* vmask      = _gvn.transform(VectorMaskGenNode::make(ConvI2X(casted_length), elem_bt));
7259         Node* vload_obja = _gvn.transform(new LoadVectorMaskedNode(control(), obja_adr_mem, obja_adr, obja_adr_t, vt, vmask));
7260         Node* vload_objb = _gvn.transform(new LoadVectorMaskedNode(control(), objb_adr_mem, objb_adr, objb_adr_t, vt, vmask));
7261         Node* result     = _gvn.transform(new VectorCmpMaskedNode(vload_obja, vload_objb, vmask, TypeInt::INT));
7262 
7263         exit_block->init_req(inline_path, control());
7264         memory_phi->init_req(inline_path, map()->memory());
7265         result_phi->init_req(inline_path, result);
7266 
7267         C->set_max_vector_size(MAX2((uint)ArrayOperationPartialInlineSize, C->max_vector_size()));
7268         clear_upper_avx();
7269       }
7270     }
7271   }
7272 
7273   if (call_stub_path != nullptr) {
7274     set_control(call_stub_path);
7275 
7276     Node* call = make_runtime_call(RC_LEAF,
7277                                    OptoRuntime::vectorizedMismatch_Type(),
7278                                    StubRoutines::vectorizedMismatch(), "vectorizedMismatch", TypePtr::BOTTOM,
7279                                    obja_adr, objb_adr, length, scale);
7280 
7281     exit_block->init_req(stub_path, control());
7282     memory_phi->init_req(stub_path, map()->memory());
7283     result_phi->init_req(stub_path, _gvn.transform(new ProjNode(call, TypeFunc::Parms)));
7284   }
7285 
7286   exit_block = _gvn.transform(exit_block);
7287   memory_phi = _gvn.transform(memory_phi);
7288   result_phi = _gvn.transform(result_phi);
7289 
7290   record_for_igvn(exit_block);
7291   record_for_igvn(memory_phi);
7292   record_for_igvn(result_phi);
7293 
7294   set_control(exit_block);
7295   set_all_memory(memory_phi);
7296   set_result(result_phi);
7297 
7298   return true;
7299 }
7300 
7301 //------------------------------inline_vectorizedHashcode----------------------------
7302 bool LibraryCallKit::inline_vectorizedHashCode() {
7303   assert(UseVectorizedHashCodeIntrinsic, "not implemented on this platform");
7304 
7305   assert(callee()->signature()->size() == 5, "vectorizedHashCode has 5 parameters");
7306   Node* array          = argument(0);
7307   Node* offset         = argument(1);
7308   Node* length         = argument(2);
7309   Node* initialValue   = argument(3);
7310   Node* basic_type     = argument(4);
7311 
7312   if (basic_type == top()) {
7313     return false; // failed input validation
7314   }
7315 
7316   const TypeInt* basic_type_t = _gvn.type(basic_type)->is_int();
7317   if (!basic_type_t->is_con()) {
7318     return false; // Only intrinsify if mode argument is constant
7319   }
7320 
7321   array = must_be_not_null(array, true);
7322 
7323   BasicType bt = (BasicType)basic_type_t->get_con();
7324 
7325   // Resolve address of first element
7326   Node* array_start = array_element_address(array, offset, bt);
7327 
7328   set_result(_gvn.transform(new VectorizedHashCodeNode(control(), memory(TypeAryPtr::get_array_body_type(bt)),
7329     array_start, length, initialValue, basic_type)));
7330   clear_upper_avx();
7331 
7332   return true;
7333 }
7334 
7335 /**
7336  * Calculate CRC32 for byte.
7337  * int java.util.zip.CRC32.update(int crc, int b)
7338  */
7339 bool LibraryCallKit::inline_updateCRC32() {
7340   assert(UseCRC32Intrinsics, "need AVX and CLMUL instructions support");
7341   assert(callee()->signature()->size() == 2, "update has 2 parameters");
7342   // no receiver since it is static method
7343   Node* crc  = argument(0); // type: int
7344   Node* b    = argument(1); // type: int
7345 
7346   /*
7347    *    int c = ~ crc;
7348    *    b = timesXtoThe32[(b ^ c) & 0xFF];
7349    *    b = b ^ (c >>> 8);
7350    *    crc = ~b;
7351    */
7352 
7353   Node* M1 = intcon(-1);
7354   crc = _gvn.transform(new XorINode(crc, M1));
7355   Node* result = _gvn.transform(new XorINode(crc, b));
7356   result = _gvn.transform(new AndINode(result, intcon(0xFF)));
7357 
7358   Node* base = makecon(TypeRawPtr::make(StubRoutines::crc_table_addr()));
7359   Node* offset = _gvn.transform(new LShiftINode(result, intcon(0x2)));
7360   Node* adr = off_heap_plus_addr(base, ConvI2X(offset));
7361   result = make_load(control(), adr, TypeInt::INT, T_INT, MemNode::unordered);
7362 
7363   crc = _gvn.transform(new URShiftINode(crc, intcon(8)));
7364   result = _gvn.transform(new XorINode(crc, result));
7365   result = _gvn.transform(new XorINode(result, M1));
7366   set_result(result);
7367   return true;
7368 }
7369 
7370 /**
7371  * Calculate CRC32 for byte[] array.
7372  * int java.util.zip.CRC32.updateBytes(int crc, byte[] buf, int off, int len)
7373  */
7374 bool LibraryCallKit::inline_updateBytesCRC32() {
7375   assert(UseCRC32Intrinsics, "need AVX and CLMUL instructions support");
7376   assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
7377   // no receiver since it is static method
7378   Node* crc     = argument(0); // type: int
7379   Node* src     = argument(1); // type: oop
7380   Node* offset  = argument(2); // type: int
7381   Node* length  = argument(3); // type: int
7382 
7383   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7384   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
7385     // failed array check
7386     return false;
7387   }
7388 
7389   // Figure out the size and type of the elements we will be copying.
7390   BasicType src_elem = src_type->elem()->array_element_basic_type();
7391   if (src_elem != T_BYTE) {
7392     return false;
7393   }
7394 
7395   // 'src_start' points to src array + scaled offset
7396   src = must_be_not_null(src, true);
7397   Node* src_start = array_element_address(src, offset, src_elem);
7398 
7399   // We assume that range check is done by caller.
7400   // TODO: generate range check (offset+length < src.length) in debug VM.
7401 
7402   // Call the stub.
7403   address stubAddr = StubRoutines::updateBytesCRC32();
7404   const char *stubName = "updateBytesCRC32";
7405 
7406   Node* call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::updateBytesCRC32_Type(),
7407                                  stubAddr, stubName, TypePtr::BOTTOM,
7408                                  crc, src_start, length);
7409   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7410   set_result(result);
7411   return true;
7412 }
7413 
7414 /**
7415  * Calculate CRC32 for ByteBuffer.
7416  * int java.util.zip.CRC32.updateByteBuffer(int crc, long buf, int off, int len)
7417  */
7418 bool LibraryCallKit::inline_updateByteBufferCRC32() {
7419   assert(UseCRC32Intrinsics, "need AVX and CLMUL instructions support");
7420   assert(callee()->signature()->size() == 5, "updateByteBuffer has 4 parameters and one is long");
7421   // no receiver since it is static method
7422   Node* crc     = argument(0); // type: int
7423   Node* src     = argument(1); // type: long
7424   Node* offset  = argument(3); // type: int
7425   Node* length  = argument(4); // type: int
7426 
7427   src = ConvL2X(src);  // adjust Java long to machine word
7428   Node* base = _gvn.transform(new CastX2PNode(src));
7429   offset = ConvI2X(offset);
7430 
7431   // 'src_start' points to src array + scaled offset
7432   Node* src_start = off_heap_plus_addr(base, offset);
7433 
7434   // Call the stub.
7435   address stubAddr = StubRoutines::updateBytesCRC32();
7436   const char *stubName = "updateBytesCRC32";
7437 
7438   Node* call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::updateBytesCRC32_Type(),
7439                                  stubAddr, stubName, TypePtr::BOTTOM,
7440                                  crc, src_start, length);
7441   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7442   set_result(result);
7443   return true;
7444 }
7445 
7446 //------------------------------get_table_from_crc32c_class-----------------------
7447 Node * LibraryCallKit::get_table_from_crc32c_class(ciInstanceKlass *crc32c_class) {
7448   Node* table = load_field_from_object(nullptr, "byteTable", "[I", /*decorators*/ IN_HEAP, /*is_static*/ true, crc32c_class);
7449   assert (table != nullptr, "wrong version of java.util.zip.CRC32C");
7450 
7451   return table;
7452 }
7453 
7454 //------------------------------inline_updateBytesCRC32C-----------------------
7455 //
7456 // Calculate CRC32C for byte[] array.
7457 // int java.util.zip.CRC32C.updateBytes(int crc, byte[] buf, int off, int end)
7458 //
7459 bool LibraryCallKit::inline_updateBytesCRC32C() {
7460   assert(UseCRC32CIntrinsics, "need CRC32C instruction support");
7461   assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
7462   assert(callee()->holder()->is_loaded(), "CRC32C class must be loaded");
7463   // no receiver since it is a static method
7464   Node* crc     = argument(0); // type: int
7465   Node* src     = argument(1); // type: oop
7466   Node* offset  = argument(2); // type: int
7467   Node* end     = argument(3); // type: int
7468 
7469   Node* length = _gvn.transform(new SubINode(end, offset));
7470 
7471   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7472   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
7473     // failed array check
7474     return false;
7475   }
7476 
7477   // Figure out the size and type of the elements we will be copying.
7478   BasicType src_elem = src_type->elem()->array_element_basic_type();
7479   if (src_elem != T_BYTE) {
7480     return false;
7481   }
7482 
7483   // 'src_start' points to src array + scaled offset
7484   src = must_be_not_null(src, true);
7485   Node* src_start = array_element_address(src, offset, src_elem);
7486 
7487   // static final int[] byteTable in class CRC32C
7488   Node* table = get_table_from_crc32c_class(callee()->holder());
7489   table = must_be_not_null(table, true);
7490   Node* table_start = array_element_address(table, intcon(0), T_INT);
7491 
7492   // We assume that range check is done by caller.
7493   // TODO: generate range check (offset+length < src.length) in debug VM.
7494 
7495   // Call the stub.
7496   address stubAddr = StubRoutines::updateBytesCRC32C();
7497   const char *stubName = "updateBytesCRC32C";
7498 
7499   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesCRC32C_Type(),
7500                                  stubAddr, stubName, TypePtr::BOTTOM,
7501                                  crc, src_start, length, table_start);
7502   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7503   set_result(result);
7504   return true;
7505 }
7506 
7507 //------------------------------inline_updateDirectByteBufferCRC32C-----------------------
7508 //
7509 // Calculate CRC32C for DirectByteBuffer.
7510 // int java.util.zip.CRC32C.updateDirectByteBuffer(int crc, long buf, int off, int end)
7511 //
7512 bool LibraryCallKit::inline_updateDirectByteBufferCRC32C() {
7513   assert(UseCRC32CIntrinsics, "need CRC32C instruction support");
7514   assert(callee()->signature()->size() == 5, "updateDirectByteBuffer has 4 parameters and one is long");
7515   assert(callee()->holder()->is_loaded(), "CRC32C class must be loaded");
7516   // no receiver since it is a static method
7517   Node* crc     = argument(0); // type: int
7518   Node* src     = argument(1); // type: long
7519   Node* offset  = argument(3); // type: int
7520   Node* end     = argument(4); // type: int
7521 
7522   Node* length = _gvn.transform(new SubINode(end, offset));
7523 
7524   src = ConvL2X(src);  // adjust Java long to machine word
7525   Node* base = _gvn.transform(new CastX2PNode(src));
7526   offset = ConvI2X(offset);
7527 
7528   // 'src_start' points to src array + scaled offset
7529   Node* src_start = off_heap_plus_addr(base, offset);
7530 
7531   // static final int[] byteTable in class CRC32C
7532   Node* table = get_table_from_crc32c_class(callee()->holder());
7533   table = must_be_not_null(table, true);
7534   Node* table_start = array_element_address(table, intcon(0), T_INT);
7535 
7536   // Call the stub.
7537   address stubAddr = StubRoutines::updateBytesCRC32C();
7538   const char *stubName = "updateBytesCRC32C";
7539 
7540   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesCRC32C_Type(),
7541                                  stubAddr, stubName, TypePtr::BOTTOM,
7542                                  crc, src_start, length, table_start);
7543   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7544   set_result(result);
7545   return true;
7546 }
7547 
7548 //------------------------------inline_updateBytesAdler32----------------------
7549 //
7550 // Calculate Adler32 checksum for byte[] array.
7551 // int java.util.zip.Adler32.updateBytes(int crc, byte[] buf, int off, int len)
7552 //
7553 bool LibraryCallKit::inline_updateBytesAdler32() {
7554   assert(UseAdler32Intrinsics, "Adler32 Intrinsic support need"); // check if we actually need to check this flag or check a different one
7555   assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
7556   assert(callee()->holder()->is_loaded(), "Adler32 class must be loaded");
7557   // no receiver since it is static method
7558   Node* crc     = argument(0); // type: int
7559   Node* src     = argument(1); // type: oop
7560   Node* offset  = argument(2); // type: int
7561   Node* length  = argument(3); // type: int
7562 
7563   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7564   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
7565     // failed array check
7566     return false;
7567   }
7568 
7569   // Figure out the size and type of the elements we will be copying.
7570   BasicType src_elem = src_type->elem()->array_element_basic_type();
7571   if (src_elem != T_BYTE) {
7572     return false;
7573   }
7574 
7575   // 'src_start' points to src array + scaled offset
7576   Node* src_start = array_element_address(src, offset, src_elem);
7577 
7578   // We assume that range check is done by caller.
7579   // TODO: generate range check (offset+length < src.length) in debug VM.
7580 
7581   // Call the stub.
7582   address stubAddr = StubRoutines::updateBytesAdler32();
7583   const char *stubName = "updateBytesAdler32";
7584 
7585   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesAdler32_Type(),
7586                                  stubAddr, stubName, TypePtr::BOTTOM,
7587                                  crc, src_start, length);
7588   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7589   set_result(result);
7590   return true;
7591 }
7592 
7593 //------------------------------inline_updateByteBufferAdler32---------------
7594 //
7595 // Calculate Adler32 checksum for DirectByteBuffer.
7596 // int java.util.zip.Adler32.updateByteBuffer(int crc, long buf, int off, int len)
7597 //
7598 bool LibraryCallKit::inline_updateByteBufferAdler32() {
7599   assert(UseAdler32Intrinsics, "Adler32 Intrinsic support need"); // check if we actually need to check this flag or check a different one
7600   assert(callee()->signature()->size() == 5, "updateByteBuffer has 4 parameters and one is long");
7601   assert(callee()->holder()->is_loaded(), "Adler32 class must be loaded");
7602   // no receiver since it is static method
7603   Node* crc     = argument(0); // type: int
7604   Node* src     = argument(1); // type: long
7605   Node* offset  = argument(3); // type: int
7606   Node* length  = argument(4); // type: int
7607 
7608   src = ConvL2X(src);  // adjust Java long to machine word
7609   Node* base = _gvn.transform(new CastX2PNode(src));
7610   offset = ConvI2X(offset);
7611 
7612   // 'src_start' points to src array + scaled offset
7613   Node* src_start = off_heap_plus_addr(base, offset);
7614 
7615   // Call the stub.
7616   address stubAddr = StubRoutines::updateBytesAdler32();
7617   const char *stubName = "updateBytesAdler32";
7618 
7619   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesAdler32_Type(),
7620                                  stubAddr, stubName, TypePtr::BOTTOM,
7621                                  crc, src_start, length);
7622 
7623   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7624   set_result(result);
7625   return true;
7626 }
7627 
7628 //----------------------------inline_reference_get0----------------------------
7629 // public T java.lang.ref.Reference.get();
7630 bool LibraryCallKit::inline_reference_get0() {
7631   const int referent_offset = java_lang_ref_Reference::referent_offset();
7632 
7633   // Get the argument:
7634   Node* reference_obj = null_check_receiver();
7635   if (stopped()) return true;
7636 
7637   DecoratorSet decorators = IN_HEAP | ON_WEAK_OOP_REF;
7638   Node* result = load_field_from_object(reference_obj, "referent", "Ljava/lang/Object;",
7639                                         decorators, /*is_static*/ false, nullptr);
7640   if (result == nullptr) return false;
7641 
7642   // Add memory barrier to prevent commoning reads from this field
7643   // across safepoint since GC can change its value.
7644   insert_mem_bar(Op_MemBarCPUOrder);
7645 
7646   set_result(result);
7647   return true;
7648 }
7649 
7650 //----------------------------inline_reference_refersTo0----------------------------
7651 // bool java.lang.ref.Reference.refersTo0();
7652 // bool java.lang.ref.PhantomReference.refersTo0();
7653 bool LibraryCallKit::inline_reference_refersTo0(bool is_phantom) {
7654   // Get arguments:
7655   Node* reference_obj = null_check_receiver();
7656   Node* other_obj = argument(1);
7657   if (stopped()) return true;
7658 
7659   DecoratorSet decorators = IN_HEAP | AS_NO_KEEPALIVE;
7660   decorators |= (is_phantom ? ON_PHANTOM_OOP_REF : ON_WEAK_OOP_REF);
7661   Node* referent = load_field_from_object(reference_obj, "referent", "Ljava/lang/Object;",
7662                                           decorators, /*is_static*/ false, nullptr);
7663   if (referent == nullptr) return false;
7664 
7665   // Add memory barrier to prevent commoning reads from this field
7666   // across safepoint since GC can change its value.
7667   insert_mem_bar(Op_MemBarCPUOrder);
7668 
7669   Node* cmp = _gvn.transform(new CmpPNode(referent, other_obj));
7670   Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
7671   IfNode* if_node = create_and_map_if(control(), bol, PROB_FAIR, COUNT_UNKNOWN);
7672 
7673   RegionNode* region = new RegionNode(3);
7674   PhiNode* phi = new PhiNode(region, TypeInt::BOOL);
7675 
7676   Node* if_true = _gvn.transform(new IfTrueNode(if_node));
7677   region->init_req(1, if_true);
7678   phi->init_req(1, intcon(1));
7679 
7680   Node* if_false = _gvn.transform(new IfFalseNode(if_node));
7681   region->init_req(2, if_false);
7682   phi->init_req(2, intcon(0));
7683 
7684   set_control(_gvn.transform(region));
7685   record_for_igvn(region);
7686   set_result(_gvn.transform(phi));
7687   return true;
7688 }
7689 
7690 //----------------------------inline_reference_clear0----------------------------
7691 // void java.lang.ref.Reference.clear0();
7692 // void java.lang.ref.PhantomReference.clear0();
7693 bool LibraryCallKit::inline_reference_clear0(bool is_phantom) {
7694   // This matches the implementation in JVM_ReferenceClear, see the comments there.
7695 
7696   // Get arguments
7697   Node* reference_obj = null_check_receiver();
7698   if (stopped()) return true;
7699 
7700   // Common access parameters
7701   DecoratorSet decorators = IN_HEAP | AS_NO_KEEPALIVE;
7702   decorators |= (is_phantom ? ON_PHANTOM_OOP_REF : ON_WEAK_OOP_REF);
7703   Node* referent_field_addr = basic_plus_adr(reference_obj, java_lang_ref_Reference::referent_offset());
7704   const TypePtr* referent_field_addr_type = _gvn.type(referent_field_addr)->isa_ptr();
7705   const Type* val_type = TypeOopPtr::make_from_klass(env()->Object_klass());
7706 
7707   Node* referent = access_load_at(reference_obj,
7708                                   referent_field_addr,
7709                                   referent_field_addr_type,
7710                                   val_type,
7711                                   T_OBJECT,
7712                                   decorators);
7713 
7714   IdealKit ideal(this);
7715 #define __ ideal.
7716   __ if_then(referent, BoolTest::ne, null());
7717     sync_kit(ideal);
7718     access_store_at(reference_obj,
7719                     referent_field_addr,
7720                     referent_field_addr_type,
7721                     null(),
7722                     val_type,
7723                     T_OBJECT,
7724                     decorators);
7725     __ sync_kit(this);
7726   __ end_if();
7727   final_sync(ideal);
7728 #undef __
7729 
7730   return true;
7731 }
7732 
7733 Node* LibraryCallKit::load_field_from_object(Node* fromObj, const char* fieldName, const char* fieldTypeString,
7734                                              DecoratorSet decorators, bool is_static,
7735                                              ciInstanceKlass* fromKls) {
7736   if (fromKls == nullptr) {
7737     const TypeInstPtr* tinst = _gvn.type(fromObj)->isa_instptr();
7738     assert(tinst != nullptr, "obj is null");
7739     assert(tinst->is_loaded(), "obj is not loaded");
7740     fromKls = tinst->instance_klass();
7741   } else {
7742     assert(is_static, "only for static field access");
7743   }
7744   ciField* field = fromKls->get_field_by_name(ciSymbol::make(fieldName),
7745                                               ciSymbol::make(fieldTypeString),
7746                                               is_static);
7747 
7748   assert(field != nullptr, "undefined field %s %s %s", fieldTypeString, fromKls->name()->as_utf8(), fieldName);
7749   if (field == nullptr) return (Node *) nullptr;
7750 
7751   if (is_static) {
7752     const TypeInstPtr* tip = TypeInstPtr::make(fromKls->java_mirror());
7753     fromObj = makecon(tip);
7754   }
7755 
7756   // Next code  copied from Parse::do_get_xxx():
7757 
7758   // Compute address and memory type.
7759   int offset  = field->offset_in_bytes();
7760   bool is_vol = field->is_volatile();
7761   ciType* field_klass = field->type();
7762   assert(field_klass->is_loaded(), "should be loaded");
7763   const TypePtr* adr_type = C->alias_type(field)->adr_type();
7764   Node *adr = basic_plus_adr(fromObj, fromObj, offset);
7765   assert(C->get_alias_index(adr_type) == C->get_alias_index(_gvn.type(adr)->isa_ptr()),
7766     "slice of address and input slice don't match");
7767   BasicType bt = field->layout_type();
7768 
7769   // Build the resultant type of the load
7770   const Type *type;
7771   if (bt == T_OBJECT) {
7772     type = TypeOopPtr::make_from_klass(field_klass->as_klass());
7773   } else {
7774     type = Type::get_const_basic_type(bt);
7775   }
7776 
7777   if (is_vol) {
7778     decorators |= MO_SEQ_CST;
7779   }
7780 
7781   return access_load_at(fromObj, adr, adr_type, type, bt, decorators);
7782 }
7783 
7784 Node * LibraryCallKit::field_address_from_object(Node * fromObj, const char * fieldName, const char * fieldTypeString,
7785                                                  bool is_exact /* true */, bool is_static /* false */,
7786                                                  ciInstanceKlass * fromKls /* nullptr */) {
7787   if (fromKls == nullptr) {
7788     const TypeInstPtr* tinst = _gvn.type(fromObj)->isa_instptr();
7789     assert(tinst != nullptr, "obj is null");
7790     assert(tinst->is_loaded(), "obj is not loaded");
7791     assert(!is_exact || tinst->klass_is_exact(), "klass not exact");
7792     fromKls = tinst->instance_klass();
7793   }
7794   else {
7795     assert(is_static, "only for static field access");
7796   }
7797   ciField* field = fromKls->get_field_by_name(ciSymbol::make(fieldName),
7798     ciSymbol::make(fieldTypeString),
7799     is_static);
7800 
7801   assert(field != nullptr, "undefined field");
7802   assert(!field->is_volatile(), "not defined for volatile fields");
7803 
7804   if (is_static) {
7805     const TypeInstPtr* tip = TypeInstPtr::make(fromKls->java_mirror());
7806     fromObj = makecon(tip);
7807   }
7808 
7809   // Next code  copied from Parse::do_get_xxx():
7810 
7811   // Compute address and memory type.
7812   int offset = field->offset_in_bytes();
7813   Node *adr = basic_plus_adr(fromObj, fromObj, offset);
7814 
7815   return adr;
7816 }
7817 
7818 //------------------------------inline_aescrypt_Block-----------------------
7819 bool LibraryCallKit::inline_aescrypt_Block(vmIntrinsics::ID id) {
7820   address stubAddr = nullptr;
7821   const char *stubName;
7822   bool is_decrypt = false;
7823   assert(UseAES, "need AES instruction support");
7824 
7825   switch(id) {
7826   case vmIntrinsics::_aescrypt_encryptBlock:
7827     stubAddr = StubRoutines::aescrypt_encryptBlock();
7828     stubName = "aescrypt_encryptBlock";
7829     break;
7830   case vmIntrinsics::_aescrypt_decryptBlock:
7831     stubAddr = StubRoutines::aescrypt_decryptBlock();
7832     stubName = "aescrypt_decryptBlock";
7833     is_decrypt = true;
7834     break;
7835   default:
7836     break;
7837   }
7838   if (stubAddr == nullptr) return false;
7839 
7840   Node* aescrypt_object = argument(0);
7841   Node* src             = argument(1);
7842   Node* src_offset      = argument(2);
7843   Node* dest            = argument(3);
7844   Node* dest_offset     = argument(4);
7845 
7846   src = must_be_not_null(src, true);
7847   dest = must_be_not_null(dest, true);
7848 
7849   // (1) src and dest are arrays.
7850   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7851   const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
7852   assert( src_type != nullptr &&  src_type->elem() != Type::BOTTOM &&
7853          dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
7854 
7855   // for the quick and dirty code we will skip all the checks.
7856   // we are just trying to get the call to be generated.
7857   Node* src_start  = src;
7858   Node* dest_start = dest;
7859   if (src_offset != nullptr || dest_offset != nullptr) {
7860     assert(src_offset != nullptr && dest_offset != nullptr, "");
7861     src_start  = array_element_address(src,  src_offset,  T_BYTE);
7862     dest_start = array_element_address(dest, dest_offset, T_BYTE);
7863   }
7864 
7865   // now need to get the start of its expanded key array
7866   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
7867   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object, is_decrypt);
7868   if (k_start == nullptr) return false;
7869 
7870   // Call the stub.
7871   make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::aescrypt_block_Type(),
7872                     stubAddr, stubName, TypePtr::BOTTOM,
7873                     src_start, dest_start, k_start);
7874 
7875   return true;
7876 }
7877 
7878 //------------------------------inline_cipherBlockChaining_AESCrypt-----------------------
7879 bool LibraryCallKit::inline_cipherBlockChaining_AESCrypt(vmIntrinsics::ID id) {
7880   address stubAddr = nullptr;
7881   const char *stubName = nullptr;
7882   bool is_decrypt = false;
7883   assert(UseAES, "need AES instruction support");
7884 
7885   switch(id) {
7886   case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
7887     stubAddr = StubRoutines::cipherBlockChaining_encryptAESCrypt();
7888     stubName = "cipherBlockChaining_encryptAESCrypt";
7889     break;
7890   case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
7891     stubAddr = StubRoutines::cipherBlockChaining_decryptAESCrypt();
7892     stubName = "cipherBlockChaining_decryptAESCrypt";
7893     is_decrypt = true;
7894     break;
7895   default:
7896     break;
7897   }
7898   if (stubAddr == nullptr) return false;
7899 
7900   Node* cipherBlockChaining_object = argument(0);
7901   Node* src                        = argument(1);
7902   Node* src_offset                 = argument(2);
7903   Node* len                        = argument(3);
7904   Node* dest                       = argument(4);
7905   Node* dest_offset                = argument(5);
7906 
7907   src = must_be_not_null(src, false);
7908   dest = must_be_not_null(dest, false);
7909 
7910   // (1) src and dest are arrays.
7911   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7912   const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
7913   assert( src_type != nullptr &&  src_type->elem() != Type::BOTTOM &&
7914          dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
7915 
7916   // checks are the responsibility of the caller
7917   Node* src_start  = src;
7918   Node* dest_start = dest;
7919   if (src_offset != nullptr || dest_offset != nullptr) {
7920     assert(src_offset != nullptr && dest_offset != nullptr, "");
7921     src_start  = array_element_address(src,  src_offset,  T_BYTE);
7922     dest_start = array_element_address(dest, dest_offset, T_BYTE);
7923   }
7924 
7925   // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
7926   // (because of the predicated logic executed earlier).
7927   // so we cast it here safely.
7928   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
7929 
7930   Node* embeddedCipherObj = load_field_from_object(cipherBlockChaining_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
7931   if (embeddedCipherObj == nullptr) return false;
7932 
7933   // cast it to what we know it will be at runtime
7934   const TypeInstPtr* tinst = _gvn.type(cipherBlockChaining_object)->isa_instptr();
7935   assert(tinst != nullptr, "CBC obj is null");
7936   assert(tinst->is_loaded(), "CBC obj is not loaded");
7937   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
7938   assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
7939 
7940   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
7941   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
7942   const TypeOopPtr* xtype = aklass->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
7943   Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
7944   aescrypt_object = _gvn.transform(aescrypt_object);
7945 
7946   // we need to get the start of the aescrypt_object's expanded key array
7947   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object, is_decrypt);
7948   if (k_start == nullptr) return false;
7949 
7950   // similarly, get the start address of the r vector
7951   Node* objRvec = load_field_from_object(cipherBlockChaining_object, "r", "[B");
7952   if (objRvec == nullptr) return false;
7953   Node* r_start = array_element_address(objRvec, intcon(0), T_BYTE);
7954 
7955   // Call the stub, passing src_start, dest_start, k_start, r_start and src_len
7956   Node* cbcCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
7957                                      OptoRuntime::cipherBlockChaining_aescrypt_Type(),
7958                                      stubAddr, stubName, TypePtr::BOTTOM,
7959                                      src_start, dest_start, k_start, r_start, len);
7960 
7961   // return cipher length (int)
7962   Node* retvalue = _gvn.transform(new ProjNode(cbcCrypt, TypeFunc::Parms));
7963   set_result(retvalue);
7964   return true;
7965 }
7966 
7967 //------------------------------inline_electronicCodeBook_AESCrypt-----------------------
7968 bool LibraryCallKit::inline_electronicCodeBook_AESCrypt(vmIntrinsics::ID id) {
7969   address stubAddr = nullptr;
7970   const char *stubName = nullptr;
7971   bool is_decrypt = false;
7972   assert(UseAES, "need AES instruction support");
7973 
7974   switch (id) {
7975   case vmIntrinsics::_electronicCodeBook_encryptAESCrypt:
7976     stubAddr = StubRoutines::electronicCodeBook_encryptAESCrypt();
7977     stubName = "electronicCodeBook_encryptAESCrypt";
7978     break;
7979   case vmIntrinsics::_electronicCodeBook_decryptAESCrypt:
7980     stubAddr = StubRoutines::electronicCodeBook_decryptAESCrypt();
7981     stubName = "electronicCodeBook_decryptAESCrypt";
7982     is_decrypt = true;
7983     break;
7984   default:
7985     break;
7986   }
7987 
7988   if (stubAddr == nullptr) return false;
7989 
7990   Node* electronicCodeBook_object = argument(0);
7991   Node* src                       = argument(1);
7992   Node* src_offset                = argument(2);
7993   Node* len                       = argument(3);
7994   Node* dest                      = argument(4);
7995   Node* dest_offset               = argument(5);
7996 
7997   // (1) src and dest are arrays.
7998   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7999   const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
8000   assert( src_type != nullptr &&  src_type->elem() != Type::BOTTOM &&
8001          dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
8002 
8003   // checks are the responsibility of the caller
8004   Node* src_start = src;
8005   Node* dest_start = dest;
8006   if (src_offset != nullptr || dest_offset != nullptr) {
8007     assert(src_offset != nullptr && dest_offset != nullptr, "");
8008     src_start = array_element_address(src, src_offset, T_BYTE);
8009     dest_start = array_element_address(dest, dest_offset, T_BYTE);
8010   }
8011 
8012   // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
8013   // (because of the predicated logic executed earlier).
8014   // so we cast it here safely.
8015   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
8016 
8017   Node* embeddedCipherObj = load_field_from_object(electronicCodeBook_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8018   if (embeddedCipherObj == nullptr) return false;
8019 
8020   // cast it to what we know it will be at runtime
8021   const TypeInstPtr* tinst = _gvn.type(electronicCodeBook_object)->isa_instptr();
8022   assert(tinst != nullptr, "ECB obj is null");
8023   assert(tinst->is_loaded(), "ECB obj is not loaded");
8024   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8025   assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
8026 
8027   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8028   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
8029   const TypeOopPtr* xtype = aklass->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
8030   Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
8031   aescrypt_object = _gvn.transform(aescrypt_object);
8032 
8033   // we need to get the start of the aescrypt_object's expanded key array
8034   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object, is_decrypt);
8035   if (k_start == nullptr) return false;
8036 
8037   // Call the stub, passing src_start, dest_start, k_start, r_start and src_len
8038   Node* ecbCrypt = make_runtime_call(RC_LEAF | RC_NO_FP,
8039                                      OptoRuntime::electronicCodeBook_aescrypt_Type(),
8040                                      stubAddr, stubName, TypePtr::BOTTOM,
8041                                      src_start, dest_start, k_start, len);
8042 
8043   // return cipher length (int)
8044   Node* retvalue = _gvn.transform(new ProjNode(ecbCrypt, TypeFunc::Parms));
8045   set_result(retvalue);
8046   return true;
8047 }
8048 
8049 //------------------------------inline_counterMode_AESCrypt-----------------------
8050 bool LibraryCallKit::inline_counterMode_AESCrypt(vmIntrinsics::ID id) {
8051   assert(UseAES, "need AES instruction support");
8052   if (!UseAESCTRIntrinsics) return false;
8053 
8054   address stubAddr = nullptr;
8055   const char *stubName = nullptr;
8056   if (id == vmIntrinsics::_counterMode_AESCrypt) {
8057     stubAddr = StubRoutines::counterMode_AESCrypt();
8058     stubName = "counterMode_AESCrypt";
8059   }
8060   if (stubAddr == nullptr) return false;
8061 
8062   Node* counterMode_object = argument(0);
8063   Node* src = argument(1);
8064   Node* src_offset = argument(2);
8065   Node* len = argument(3);
8066   Node* dest = argument(4);
8067   Node* dest_offset = argument(5);
8068 
8069   // (1) src and dest are arrays.
8070   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
8071   const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
8072   assert( src_type != nullptr &&  src_type->elem() != Type::BOTTOM &&
8073          dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
8074 
8075   // checks are the responsibility of the caller
8076   Node* src_start = src;
8077   Node* dest_start = dest;
8078   if (src_offset != nullptr || dest_offset != nullptr) {
8079     assert(src_offset != nullptr && dest_offset != nullptr, "");
8080     src_start = array_element_address(src, src_offset, T_BYTE);
8081     dest_start = array_element_address(dest, dest_offset, T_BYTE);
8082   }
8083 
8084   // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
8085   // (because of the predicated logic executed earlier).
8086   // so we cast it here safely.
8087   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
8088   Node* embeddedCipherObj = load_field_from_object(counterMode_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8089   if (embeddedCipherObj == nullptr) return false;
8090   // cast it to what we know it will be at runtime
8091   const TypeInstPtr* tinst = _gvn.type(counterMode_object)->isa_instptr();
8092   assert(tinst != nullptr, "CTR obj is null");
8093   assert(tinst->is_loaded(), "CTR obj is not loaded");
8094   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8095   assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
8096   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8097   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
8098   const TypeOopPtr* xtype = aklass->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
8099   Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
8100   aescrypt_object = _gvn.transform(aescrypt_object);
8101   // we need to get the start of the aescrypt_object's expanded key array
8102   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object, /* is_decrypt */ false);
8103   if (k_start == nullptr) return false;
8104   // similarly, get the start address of the r vector
8105   Node* obj_counter = load_field_from_object(counterMode_object, "counter", "[B");
8106   if (obj_counter == nullptr) return false;
8107   Node* cnt_start = array_element_address(obj_counter, intcon(0), T_BYTE);
8108 
8109   Node* saved_encCounter = load_field_from_object(counterMode_object, "encryptedCounter", "[B");
8110   if (saved_encCounter == nullptr) return false;
8111   Node* saved_encCounter_start = array_element_address(saved_encCounter, intcon(0), T_BYTE);
8112   Node* used = field_address_from_object(counterMode_object, "used", "I", /*is_exact*/ false);
8113 
8114   // Call the stub, passing src_start, dest_start, k_start, r_start and src_len
8115   Node* ctrCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
8116                                      OptoRuntime::counterMode_aescrypt_Type(),
8117                                      stubAddr, stubName, TypePtr::BOTTOM,
8118                                      src_start, dest_start, k_start, cnt_start, len, saved_encCounter_start, used);
8119 
8120   // return cipher length (int)
8121   Node* retvalue = _gvn.transform(new ProjNode(ctrCrypt, TypeFunc::Parms));
8122   set_result(retvalue);
8123   return true;
8124 }
8125 
8126 //------------------------------get_key_start_from_aescrypt_object-----------------------
8127 Node* LibraryCallKit::get_key_start_from_aescrypt_object(Node* aescrypt_object, bool is_decrypt) {
8128   // MixColumns for decryption can be reduced by preprocessing MixColumns with round keys.
8129   // Intel's extension is based on this optimization and AESCrypt generates round keys by preprocessing MixColumns.
8130   // However, ppc64 vncipher processes MixColumns and requires the same round keys with encryption.
8131   // The following platform specific stubs of encryption and decryption use the same round keys.
8132 #if defined(PPC64) || defined(S390) || defined(RISCV64)
8133   bool use_decryption_key = false;
8134 #else
8135   bool use_decryption_key = is_decrypt;
8136 #endif
8137   Node* objAESCryptKey = load_field_from_object(aescrypt_object, use_decryption_key ? "sessionKd" : "sessionKe", "[I");
8138   assert(objAESCryptKey != nullptr, "wrong version of com.sun.crypto.provider.AES_Crypt");
8139   if (objAESCryptKey == nullptr) return (Node *) nullptr;
8140 
8141   // now have the array, need to get the start address of the selected key array
8142   Node* k_start = array_element_address(objAESCryptKey, intcon(0), T_INT);
8143   return k_start;
8144 }
8145 
8146 //----------------------------inline_cipherBlockChaining_AESCrypt_predicate----------------------------
8147 // Return node representing slow path of predicate check.
8148 // the pseudo code we want to emulate with this predicate is:
8149 // for encryption:
8150 //    if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
8151 // for decryption:
8152 //    if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
8153 //    note cipher==plain is more conservative than the original java code but that's OK
8154 //
8155 Node* LibraryCallKit::inline_cipherBlockChaining_AESCrypt_predicate(bool decrypting) {
8156   // The receiver was checked for null already.
8157   Node* objCBC = argument(0);
8158 
8159   Node* src = argument(1);
8160   Node* dest = argument(4);
8161 
8162   // Load embeddedCipher field of CipherBlockChaining object.
8163   Node* embeddedCipherObj = load_field_from_object(objCBC, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8164 
8165   // get AESCrypt klass for instanceOf check
8166   // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
8167   // will have same classloader as CipherBlockChaining object
8168   const TypeInstPtr* tinst = _gvn.type(objCBC)->isa_instptr();
8169   assert(tinst != nullptr, "CBCobj is null");
8170   assert(tinst->is_loaded(), "CBCobj is not loaded");
8171 
8172   // we want to do an instanceof comparison against the AESCrypt class
8173   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8174   if (!klass_AESCrypt->is_loaded()) {
8175     // if AESCrypt is not even loaded, we never take the intrinsic fast path
8176     Node* ctrl = control();
8177     set_control(top()); // no regular fast path
8178     return ctrl;
8179   }
8180 
8181   src = must_be_not_null(src, true);
8182   dest = must_be_not_null(dest, true);
8183 
8184   // Resolve oops to stable for CmpP below.
8185   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8186 
8187   Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
8188   Node* cmp_instof  = _gvn.transform(new CmpINode(instof, intcon(1)));
8189   Node* bool_instof  = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
8190 
8191   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
8192 
8193   // for encryption, we are done
8194   if (!decrypting)
8195     return instof_false;  // even if it is null
8196 
8197   // for decryption, we need to add a further check to avoid
8198   // taking the intrinsic path when cipher and plain are the same
8199   // see the original java code for why.
8200   RegionNode* region = new RegionNode(3);
8201   region->init_req(1, instof_false);
8202 
8203   Node* cmp_src_dest = _gvn.transform(new CmpPNode(src, dest));
8204   Node* bool_src_dest = _gvn.transform(new BoolNode(cmp_src_dest, BoolTest::eq));
8205   Node* src_dest_conjoint = generate_guard(bool_src_dest, nullptr, PROB_MIN);
8206   region->init_req(2, src_dest_conjoint);
8207 
8208   record_for_igvn(region);
8209   return _gvn.transform(region);
8210 }
8211 
8212 //----------------------------inline_electronicCodeBook_AESCrypt_predicate----------------------------
8213 // Return node representing slow path of predicate check.
8214 // the pseudo code we want to emulate with this predicate is:
8215 // for encryption:
8216 //    if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
8217 // for decryption:
8218 //    if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
8219 //    note cipher==plain is more conservative than the original java code but that's OK
8220 //
8221 Node* LibraryCallKit::inline_electronicCodeBook_AESCrypt_predicate(bool decrypting) {
8222   // The receiver was checked for null already.
8223   Node* objECB = argument(0);
8224 
8225   // Load embeddedCipher field of ElectronicCodeBook object.
8226   Node* embeddedCipherObj = load_field_from_object(objECB, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8227 
8228   // get AESCrypt klass for instanceOf check
8229   // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
8230   // will have same classloader as ElectronicCodeBook object
8231   const TypeInstPtr* tinst = _gvn.type(objECB)->isa_instptr();
8232   assert(tinst != nullptr, "ECBobj is null");
8233   assert(tinst->is_loaded(), "ECBobj is not loaded");
8234 
8235   // we want to do an instanceof comparison against the AESCrypt class
8236   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8237   if (!klass_AESCrypt->is_loaded()) {
8238     // if AESCrypt is not even loaded, we never take the intrinsic fast path
8239     Node* ctrl = control();
8240     set_control(top()); // no regular fast path
8241     return ctrl;
8242   }
8243   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8244 
8245   Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
8246   Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
8247   Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
8248 
8249   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
8250 
8251   // for encryption, we are done
8252   if (!decrypting)
8253     return instof_false;  // even if it is null
8254 
8255   // for decryption, we need to add a further check to avoid
8256   // taking the intrinsic path when cipher and plain are the same
8257   // see the original java code for why.
8258   RegionNode* region = new RegionNode(3);
8259   region->init_req(1, instof_false);
8260   Node* src = argument(1);
8261   Node* dest = argument(4);
8262   Node* cmp_src_dest = _gvn.transform(new CmpPNode(src, dest));
8263   Node* bool_src_dest = _gvn.transform(new BoolNode(cmp_src_dest, BoolTest::eq));
8264   Node* src_dest_conjoint = generate_guard(bool_src_dest, nullptr, PROB_MIN);
8265   region->init_req(2, src_dest_conjoint);
8266 
8267   record_for_igvn(region);
8268   return _gvn.transform(region);
8269 }
8270 
8271 //----------------------------inline_counterMode_AESCrypt_predicate----------------------------
8272 // Return node representing slow path of predicate check.
8273 // the pseudo code we want to emulate with this predicate is:
8274 // for encryption:
8275 //    if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
8276 // for decryption:
8277 //    if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
8278 //    note cipher==plain is more conservative than the original java code but that's OK
8279 //
8280 
8281 Node* LibraryCallKit::inline_counterMode_AESCrypt_predicate() {
8282   // The receiver was checked for null already.
8283   Node* objCTR = argument(0);
8284 
8285   // Load embeddedCipher field of CipherBlockChaining object.
8286   Node* embeddedCipherObj = load_field_from_object(objCTR, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8287 
8288   // get AESCrypt klass for instanceOf check
8289   // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
8290   // will have same classloader as CipherBlockChaining object
8291   const TypeInstPtr* tinst = _gvn.type(objCTR)->isa_instptr();
8292   assert(tinst != nullptr, "CTRobj is null");
8293   assert(tinst->is_loaded(), "CTRobj is not loaded");
8294 
8295   // we want to do an instanceof comparison against the AESCrypt class
8296   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8297   if (!klass_AESCrypt->is_loaded()) {
8298     // if AESCrypt is not even loaded, we never take the intrinsic fast path
8299     Node* ctrl = control();
8300     set_control(top()); // no regular fast path
8301     return ctrl;
8302   }
8303 
8304   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8305   Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
8306   Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
8307   Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
8308   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
8309 
8310   return instof_false; // even if it is null
8311 }
8312 
8313 //------------------------------inline_ghash_processBlocks
8314 bool LibraryCallKit::inline_ghash_processBlocks() {
8315   address stubAddr;
8316   const char *stubName;
8317   assert(UseGHASHIntrinsics, "need GHASH intrinsics support");
8318 
8319   stubAddr = StubRoutines::ghash_processBlocks();
8320   stubName = "ghash_processBlocks";
8321 
8322   Node* data           = argument(0);
8323   Node* offset         = argument(1);
8324   Node* len            = argument(2);
8325   Node* state          = argument(3);
8326   Node* subkeyH        = argument(4);
8327 
8328   state = must_be_not_null(state, true);
8329   subkeyH = must_be_not_null(subkeyH, true);
8330   data = must_be_not_null(data, true);
8331 
8332   Node* state_start  = array_element_address(state, intcon(0), T_LONG);
8333   assert(state_start, "state is null");
8334   Node* subkeyH_start  = array_element_address(subkeyH, intcon(0), T_LONG);
8335   assert(subkeyH_start, "subkeyH is null");
8336   Node* data_start  = array_element_address(data, offset, T_BYTE);
8337   assert(data_start, "data is null");
8338 
8339   Node* ghash = make_runtime_call(RC_LEAF|RC_NO_FP,
8340                                   OptoRuntime::ghash_processBlocks_Type(),
8341                                   stubAddr, stubName, TypePtr::BOTTOM,
8342                                   state_start, subkeyH_start, data_start, len);
8343   return true;
8344 }
8345 
8346 //------------------------------inline_chacha20Block
8347 bool LibraryCallKit::inline_chacha20Block() {
8348   address stubAddr;
8349   const char *stubName;
8350   assert(UseChaCha20Intrinsics, "need ChaCha20 intrinsics support");
8351 
8352   stubAddr = StubRoutines::chacha20Block();
8353   stubName = "chacha20Block";
8354 
8355   Node* state          = argument(0);
8356   Node* result         = argument(1);
8357 
8358   state = must_be_not_null(state, true);
8359   result = must_be_not_null(result, true);
8360 
8361   Node* state_start  = array_element_address(state, intcon(0), T_INT);
8362   assert(state_start, "state is null");
8363   Node* result_start  = array_element_address(result, intcon(0), T_BYTE);
8364   assert(result_start, "result is null");
8365 
8366   Node* cc20Blk = make_runtime_call(RC_LEAF|RC_NO_FP,
8367                                   OptoRuntime::chacha20Block_Type(),
8368                                   stubAddr, stubName, TypePtr::BOTTOM,
8369                                   state_start, result_start);
8370   // return key stream length (int)
8371   Node* retvalue = _gvn.transform(new ProjNode(cc20Blk, TypeFunc::Parms));
8372   set_result(retvalue);
8373   return true;
8374 }
8375 
8376 //------------------------------inline_kyberNtt
8377 bool LibraryCallKit::inline_kyberNtt() {
8378   address stubAddr;
8379   const char *stubName;
8380   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8381   assert(callee()->signature()->size() == 2, "kyberNtt has 2 parameters");
8382 
8383   stubAddr = StubRoutines::kyberNtt();
8384   stubName = "kyberNtt";
8385   if (!stubAddr) return false;
8386 
8387   Node* coeffs          = argument(0);
8388   Node* ntt_zetas        = argument(1);
8389 
8390   coeffs = must_be_not_null(coeffs, true);
8391   ntt_zetas = must_be_not_null(ntt_zetas, true);
8392 
8393   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_SHORT);
8394   assert(coeffs_start, "coeffs is null");
8395   Node* ntt_zetas_start  = array_element_address(ntt_zetas, intcon(0), T_SHORT);
8396   assert(ntt_zetas_start, "ntt_zetas is null");
8397   Node* kyberNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
8398                                   OptoRuntime::kyberNtt_Type(),
8399                                   stubAddr, stubName, TypePtr::BOTTOM,
8400                                   coeffs_start, ntt_zetas_start);
8401   // return an int
8402   Node* retvalue = _gvn.transform(new ProjNode(kyberNtt, TypeFunc::Parms));
8403   set_result(retvalue);
8404   return true;
8405 }
8406 
8407 //------------------------------inline_kyberInverseNtt
8408 bool LibraryCallKit::inline_kyberInverseNtt() {
8409   address stubAddr;
8410   const char *stubName;
8411   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8412   assert(callee()->signature()->size() == 2, "kyberInverseNtt has 2 parameters");
8413 
8414   stubAddr = StubRoutines::kyberInverseNtt();
8415   stubName = "kyberInverseNtt";
8416   if (!stubAddr) return false;
8417 
8418   Node* coeffs          = argument(0);
8419   Node* zetas           = argument(1);
8420 
8421   coeffs = must_be_not_null(coeffs, true);
8422   zetas = must_be_not_null(zetas, true);
8423 
8424   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_SHORT);
8425   assert(coeffs_start, "coeffs is null");
8426   Node* zetas_start  = array_element_address(zetas, intcon(0), T_SHORT);
8427   assert(zetas_start, "inverseNtt_zetas is null");
8428   Node* kyberInverseNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
8429                                   OptoRuntime::kyberInverseNtt_Type(),
8430                                   stubAddr, stubName, TypePtr::BOTTOM,
8431                                   coeffs_start, zetas_start);
8432 
8433   // return an int
8434   Node* retvalue = _gvn.transform(new ProjNode(kyberInverseNtt, TypeFunc::Parms));
8435   set_result(retvalue);
8436   return true;
8437 }
8438 
8439 //------------------------------inline_kyberNttMult
8440 bool LibraryCallKit::inline_kyberNttMult() {
8441   address stubAddr;
8442   const char *stubName;
8443   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8444   assert(callee()->signature()->size() == 4, "kyberNttMult has 4 parameters");
8445 
8446   stubAddr = StubRoutines::kyberNttMult();
8447   stubName = "kyberNttMult";
8448   if (!stubAddr) return false;
8449 
8450   Node* result          = argument(0);
8451   Node* ntta            = argument(1);
8452   Node* nttb            = argument(2);
8453   Node* zetas           = argument(3);
8454 
8455   result = must_be_not_null(result, true);
8456   ntta = must_be_not_null(ntta, true);
8457   nttb = must_be_not_null(nttb, true);
8458   zetas = must_be_not_null(zetas, true);
8459 
8460   Node* result_start  = array_element_address(result, intcon(0), T_SHORT);
8461   assert(result_start, "result is null");
8462   Node* ntta_start  = array_element_address(ntta, intcon(0), T_SHORT);
8463   assert(ntta_start, "ntta is null");
8464   Node* nttb_start  = array_element_address(nttb, intcon(0), T_SHORT);
8465   assert(nttb_start, "nttb is null");
8466   Node* zetas_start  = array_element_address(zetas, intcon(0), T_SHORT);
8467   assert(zetas_start, "nttMult_zetas is null");
8468   Node* kyberNttMult = make_runtime_call(RC_LEAF|RC_NO_FP,
8469                                   OptoRuntime::kyberNttMult_Type(),
8470                                   stubAddr, stubName, TypePtr::BOTTOM,
8471                                   result_start, ntta_start, nttb_start,
8472                                   zetas_start);
8473 
8474   // return an int
8475   Node* retvalue = _gvn.transform(new ProjNode(kyberNttMult, TypeFunc::Parms));
8476   set_result(retvalue);
8477 
8478   return true;
8479 }
8480 
8481 //------------------------------inline_kyberAddPoly_2
8482 bool LibraryCallKit::inline_kyberAddPoly_2() {
8483   address stubAddr;
8484   const char *stubName;
8485   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8486   assert(callee()->signature()->size() == 3, "kyberAddPoly_2 has 3 parameters");
8487 
8488   stubAddr = StubRoutines::kyberAddPoly_2();
8489   stubName = "kyberAddPoly_2";
8490   if (!stubAddr) return false;
8491 
8492   Node* result          = argument(0);
8493   Node* a               = argument(1);
8494   Node* b               = argument(2);
8495 
8496   result = must_be_not_null(result, true);
8497   a = must_be_not_null(a, true);
8498   b = must_be_not_null(b, true);
8499 
8500   Node* result_start  = array_element_address(result, intcon(0), T_SHORT);
8501   assert(result_start, "result is null");
8502   Node* a_start  = array_element_address(a, intcon(0), T_SHORT);
8503   assert(a_start, "a is null");
8504   Node* b_start  = array_element_address(b, intcon(0), T_SHORT);
8505   assert(b_start, "b is null");
8506   Node* kyberAddPoly_2 = make_runtime_call(RC_LEAF|RC_NO_FP,
8507                                   OptoRuntime::kyberAddPoly_2_Type(),
8508                                   stubAddr, stubName, TypePtr::BOTTOM,
8509                                   result_start, a_start, b_start);
8510   // return an int
8511   Node* retvalue = _gvn.transform(new ProjNode(kyberAddPoly_2, TypeFunc::Parms));
8512   set_result(retvalue);
8513   return true;
8514 }
8515 
8516 //------------------------------inline_kyberAddPoly_3
8517 bool LibraryCallKit::inline_kyberAddPoly_3() {
8518   address stubAddr;
8519   const char *stubName;
8520   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8521   assert(callee()->signature()->size() == 4, "kyberAddPoly_3 has 4 parameters");
8522 
8523   stubAddr = StubRoutines::kyberAddPoly_3();
8524   stubName = "kyberAddPoly_3";
8525   if (!stubAddr) return false;
8526 
8527   Node* result          = argument(0);
8528   Node* a               = argument(1);
8529   Node* b               = argument(2);
8530   Node* c               = argument(3);
8531 
8532   result = must_be_not_null(result, true);
8533   a = must_be_not_null(a, true);
8534   b = must_be_not_null(b, true);
8535   c = must_be_not_null(c, true);
8536 
8537   Node* result_start  = array_element_address(result, intcon(0), T_SHORT);
8538   assert(result_start, "result is null");
8539   Node* a_start  = array_element_address(a, intcon(0), T_SHORT);
8540   assert(a_start, "a is null");
8541   Node* b_start  = array_element_address(b, intcon(0), T_SHORT);
8542   assert(b_start, "b is null");
8543   Node* c_start  = array_element_address(c, intcon(0), T_SHORT);
8544   assert(c_start, "c is null");
8545   Node* kyberAddPoly_3 = make_runtime_call(RC_LEAF|RC_NO_FP,
8546                                   OptoRuntime::kyberAddPoly_3_Type(),
8547                                   stubAddr, stubName, TypePtr::BOTTOM,
8548                                   result_start, a_start, b_start, c_start);
8549   // return an int
8550   Node* retvalue = _gvn.transform(new ProjNode(kyberAddPoly_3, TypeFunc::Parms));
8551   set_result(retvalue);
8552   return true;
8553 }
8554 
8555 //------------------------------inline_kyber12To16
8556 bool LibraryCallKit::inline_kyber12To16() {
8557   address stubAddr;
8558   const char *stubName;
8559   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8560   assert(callee()->signature()->size() == 4, "kyber12To16 has 4 parameters");
8561 
8562   stubAddr = StubRoutines::kyber12To16();
8563   stubName = "kyber12To16";
8564   if (!stubAddr) return false;
8565 
8566   Node* condensed       = argument(0);
8567   Node* condensedOffs   = argument(1);
8568   Node* parsed          = argument(2);
8569   Node* parsedLength    = argument(3);
8570 
8571   condensed = must_be_not_null(condensed, true);
8572   parsed = must_be_not_null(parsed, true);
8573 
8574   Node* condensed_start  = array_element_address(condensed, intcon(0), T_BYTE);
8575   assert(condensed_start, "condensed is null");
8576   Node* parsed_start  = array_element_address(parsed, intcon(0), T_SHORT);
8577   assert(parsed_start, "parsed is null");
8578   Node* kyber12To16 = make_runtime_call(RC_LEAF|RC_NO_FP,
8579                                   OptoRuntime::kyber12To16_Type(),
8580                                   stubAddr, stubName, TypePtr::BOTTOM,
8581                                   condensed_start, condensedOffs, parsed_start, parsedLength);
8582   // return an int
8583   Node* retvalue = _gvn.transform(new ProjNode(kyber12To16, TypeFunc::Parms));
8584   set_result(retvalue);
8585   return true;
8586 
8587 }
8588 
8589 //------------------------------inline_kyberBarrettReduce
8590 bool LibraryCallKit::inline_kyberBarrettReduce() {
8591   address stubAddr;
8592   const char *stubName;
8593   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8594   assert(callee()->signature()->size() == 1, "kyberBarrettReduce has 1 parameters");
8595 
8596   stubAddr = StubRoutines::kyberBarrettReduce();
8597   stubName = "kyberBarrettReduce";
8598   if (!stubAddr) return false;
8599 
8600   Node* coeffs          = argument(0);
8601 
8602   coeffs = must_be_not_null(coeffs, true);
8603 
8604   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_SHORT);
8605   assert(coeffs_start, "coeffs is null");
8606   Node* kyberBarrettReduce = make_runtime_call(RC_LEAF|RC_NO_FP,
8607                                   OptoRuntime::kyberBarrettReduce_Type(),
8608                                   stubAddr, stubName, TypePtr::BOTTOM,
8609                                   coeffs_start);
8610   // return an int
8611   Node* retvalue = _gvn.transform(new ProjNode(kyberBarrettReduce, TypeFunc::Parms));
8612   set_result(retvalue);
8613   return true;
8614 }
8615 
8616 //------------------------------inline_dilithiumAlmostNtt
8617 bool LibraryCallKit::inline_dilithiumAlmostNtt() {
8618   address stubAddr;
8619   const char *stubName;
8620   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8621   assert(callee()->signature()->size() == 2, "dilithiumAlmostNtt has 2 parameters");
8622 
8623   stubAddr = StubRoutines::dilithiumAlmostNtt();
8624   stubName = "dilithiumAlmostNtt";
8625   if (!stubAddr) return false;
8626 
8627   Node* coeffs          = argument(0);
8628   Node* ntt_zetas        = argument(1);
8629 
8630   coeffs = must_be_not_null(coeffs, true);
8631   ntt_zetas = must_be_not_null(ntt_zetas, true);
8632 
8633   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_INT);
8634   assert(coeffs_start, "coeffs is null");
8635   Node* ntt_zetas_start  = array_element_address(ntt_zetas, intcon(0), T_INT);
8636   assert(ntt_zetas_start, "ntt_zetas is null");
8637   Node* dilithiumAlmostNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
8638                                   OptoRuntime::dilithiumAlmostNtt_Type(),
8639                                   stubAddr, stubName, TypePtr::BOTTOM,
8640                                   coeffs_start, ntt_zetas_start);
8641   // return an int
8642   Node* retvalue = _gvn.transform(new ProjNode(dilithiumAlmostNtt, TypeFunc::Parms));
8643   set_result(retvalue);
8644   return true;
8645 }
8646 
8647 //------------------------------inline_dilithiumAlmostInverseNtt
8648 bool LibraryCallKit::inline_dilithiumAlmostInverseNtt() {
8649   address stubAddr;
8650   const char *stubName;
8651   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8652   assert(callee()->signature()->size() == 2, "dilithiumAlmostInverseNtt has 2 parameters");
8653 
8654   stubAddr = StubRoutines::dilithiumAlmostInverseNtt();
8655   stubName = "dilithiumAlmostInverseNtt";
8656   if (!stubAddr) return false;
8657 
8658   Node* coeffs          = argument(0);
8659   Node* zetas           = argument(1);
8660 
8661   coeffs = must_be_not_null(coeffs, true);
8662   zetas = must_be_not_null(zetas, true);
8663 
8664   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_INT);
8665   assert(coeffs_start, "coeffs is null");
8666   Node* zetas_start  = array_element_address(zetas, intcon(0), T_INT);
8667   assert(zetas_start, "inverseNtt_zetas is null");
8668   Node* dilithiumAlmostInverseNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
8669                                   OptoRuntime::dilithiumAlmostInverseNtt_Type(),
8670                                   stubAddr, stubName, TypePtr::BOTTOM,
8671                                   coeffs_start, zetas_start);
8672   // return an int
8673   Node* retvalue = _gvn.transform(new ProjNode(dilithiumAlmostInverseNtt, TypeFunc::Parms));
8674   set_result(retvalue);
8675   return true;
8676 }
8677 
8678 //------------------------------inline_dilithiumNttMult
8679 bool LibraryCallKit::inline_dilithiumNttMult() {
8680   address stubAddr;
8681   const char *stubName;
8682   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8683   assert(callee()->signature()->size() == 3, "dilithiumNttMult has 3 parameters");
8684 
8685   stubAddr = StubRoutines::dilithiumNttMult();
8686   stubName = "dilithiumNttMult";
8687   if (!stubAddr) return false;
8688 
8689   Node* result          = argument(0);
8690   Node* ntta            = argument(1);
8691   Node* nttb            = argument(2);
8692   Node* zetas           = argument(3);
8693 
8694   result = must_be_not_null(result, true);
8695   ntta = must_be_not_null(ntta, true);
8696   nttb = must_be_not_null(nttb, true);
8697   zetas = must_be_not_null(zetas, true);
8698 
8699   Node* result_start  = array_element_address(result, intcon(0), T_INT);
8700   assert(result_start, "result is null");
8701   Node* ntta_start  = array_element_address(ntta, intcon(0), T_INT);
8702   assert(ntta_start, "ntta is null");
8703   Node* nttb_start  = array_element_address(nttb, intcon(0), T_INT);
8704   assert(nttb_start, "nttb is null");
8705   Node* dilithiumNttMult = make_runtime_call(RC_LEAF|RC_NO_FP,
8706                                   OptoRuntime::dilithiumNttMult_Type(),
8707                                   stubAddr, stubName, TypePtr::BOTTOM,
8708                                   result_start, ntta_start, nttb_start);
8709 
8710   // return an int
8711   Node* retvalue = _gvn.transform(new ProjNode(dilithiumNttMult, TypeFunc::Parms));
8712   set_result(retvalue);
8713 
8714   return true;
8715 }
8716 
8717 //------------------------------inline_dilithiumMontMulByConstant
8718 bool LibraryCallKit::inline_dilithiumMontMulByConstant() {
8719   address stubAddr;
8720   const char *stubName;
8721   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8722   assert(callee()->signature()->size() == 2, "dilithiumMontMulByConstant has 2 parameters");
8723 
8724   stubAddr = StubRoutines::dilithiumMontMulByConstant();
8725   stubName = "dilithiumMontMulByConstant";
8726   if (!stubAddr) return false;
8727 
8728   Node* coeffs          = argument(0);
8729   Node* constant        = argument(1);
8730 
8731   coeffs = must_be_not_null(coeffs, true);
8732 
8733   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_INT);
8734   assert(coeffs_start, "coeffs is null");
8735   Node* dilithiumMontMulByConstant = make_runtime_call(RC_LEAF|RC_NO_FP,
8736                                   OptoRuntime::dilithiumMontMulByConstant_Type(),
8737                                   stubAddr, stubName, TypePtr::BOTTOM,
8738                                   coeffs_start, constant);
8739 
8740   // return an int
8741   Node* retvalue = _gvn.transform(new ProjNode(dilithiumMontMulByConstant, TypeFunc::Parms));
8742   set_result(retvalue);
8743   return true;
8744 }
8745 
8746 
8747 //------------------------------inline_dilithiumDecomposePoly
8748 bool LibraryCallKit::inline_dilithiumDecomposePoly() {
8749   address stubAddr;
8750   const char *stubName;
8751   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8752   assert(callee()->signature()->size() == 5, "dilithiumDecomposePoly has 5 parameters");
8753 
8754   stubAddr = StubRoutines::dilithiumDecomposePoly();
8755   stubName = "dilithiumDecomposePoly";
8756   if (!stubAddr) return false;
8757 
8758   Node* input          = argument(0);
8759   Node* lowPart        = argument(1);
8760   Node* highPart       = argument(2);
8761   Node* twoGamma2      = argument(3);
8762   Node* multiplier     = argument(4);
8763 
8764   input = must_be_not_null(input, true);
8765   lowPart = must_be_not_null(lowPart, true);
8766   highPart = must_be_not_null(highPart, true);
8767 
8768   Node* input_start  = array_element_address(input, intcon(0), T_INT);
8769   assert(input_start, "input is null");
8770   Node* lowPart_start  = array_element_address(lowPart, intcon(0), T_INT);
8771   assert(lowPart_start, "lowPart is null");
8772   Node* highPart_start  = array_element_address(highPart, intcon(0), T_INT);
8773   assert(highPart_start, "highPart is null");
8774 
8775   Node* dilithiumDecomposePoly = make_runtime_call(RC_LEAF|RC_NO_FP,
8776                                   OptoRuntime::dilithiumDecomposePoly_Type(),
8777                                   stubAddr, stubName, TypePtr::BOTTOM,
8778                                   input_start, lowPart_start, highPart_start,
8779                                   twoGamma2, multiplier);
8780 
8781   // return an int
8782   Node* retvalue = _gvn.transform(new ProjNode(dilithiumDecomposePoly, TypeFunc::Parms));
8783   set_result(retvalue);
8784   return true;
8785 }
8786 
8787 bool LibraryCallKit::inline_base64_encodeBlock() {
8788   address stubAddr;
8789   const char *stubName;
8790   assert(UseBASE64Intrinsics, "need Base64 intrinsics support");
8791   assert(callee()->signature()->size() == 6, "base64_encodeBlock has 6 parameters");
8792   stubAddr = StubRoutines::base64_encodeBlock();
8793   stubName = "encodeBlock";
8794 
8795   if (!stubAddr) return false;
8796   Node* base64obj = argument(0);
8797   Node* src = argument(1);
8798   Node* offset = argument(2);
8799   Node* len = argument(3);
8800   Node* dest = argument(4);
8801   Node* dp = argument(5);
8802   Node* isURL = argument(6);
8803 
8804   src = must_be_not_null(src, true);
8805   dest = must_be_not_null(dest, true);
8806 
8807   Node* src_start = array_element_address(src, intcon(0), T_BYTE);
8808   assert(src_start, "source array is null");
8809   Node* dest_start = array_element_address(dest, intcon(0), T_BYTE);
8810   assert(dest_start, "destination array is null");
8811 
8812   Node* base64 = make_runtime_call(RC_LEAF,
8813                                    OptoRuntime::base64_encodeBlock_Type(),
8814                                    stubAddr, stubName, TypePtr::BOTTOM,
8815                                    src_start, offset, len, dest_start, dp, isURL);
8816   return true;
8817 }
8818 
8819 bool LibraryCallKit::inline_base64_decodeBlock() {
8820   address stubAddr;
8821   const char *stubName;
8822   assert(UseBASE64Intrinsics, "need Base64 intrinsics support");
8823   assert(callee()->signature()->size() == 7, "base64_decodeBlock has 7 parameters");
8824   stubAddr = StubRoutines::base64_decodeBlock();
8825   stubName = "decodeBlock";
8826 
8827   if (!stubAddr) return false;
8828   Node* base64obj = argument(0);
8829   Node* src = argument(1);
8830   Node* src_offset = argument(2);
8831   Node* len = argument(3);
8832   Node* dest = argument(4);
8833   Node* dest_offset = argument(5);
8834   Node* isURL = argument(6);
8835   Node* isMIME = argument(7);
8836 
8837   src = must_be_not_null(src, true);
8838   dest = must_be_not_null(dest, true);
8839 
8840   Node* src_start = array_element_address(src, intcon(0), T_BYTE);
8841   assert(src_start, "source array is null");
8842   Node* dest_start = array_element_address(dest, intcon(0), T_BYTE);
8843   assert(dest_start, "destination array is null");
8844 
8845   Node* call = make_runtime_call(RC_LEAF,
8846                                  OptoRuntime::base64_decodeBlock_Type(),
8847                                  stubAddr, stubName, TypePtr::BOTTOM,
8848                                  src_start, src_offset, len, dest_start, dest_offset, isURL, isMIME);
8849   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
8850   set_result(result);
8851   return true;
8852 }
8853 
8854 bool LibraryCallKit::inline_poly1305_processBlocks() {
8855   address stubAddr;
8856   const char *stubName;
8857   assert(UsePoly1305Intrinsics, "need Poly intrinsics support");
8858   assert(callee()->signature()->size() == 5, "poly1305_processBlocks has %d parameters", callee()->signature()->size());
8859   stubAddr = StubRoutines::poly1305_processBlocks();
8860   stubName = "poly1305_processBlocks";
8861 
8862   if (!stubAddr) return false;
8863   null_check_receiver();  // null-check receiver
8864   if (stopped())  return true;
8865 
8866   Node* input = argument(1);
8867   Node* input_offset = argument(2);
8868   Node* len = argument(3);
8869   Node* alimbs = argument(4);
8870   Node* rlimbs = argument(5);
8871 
8872   input = must_be_not_null(input, true);
8873   alimbs = must_be_not_null(alimbs, true);
8874   rlimbs = must_be_not_null(rlimbs, true);
8875 
8876   Node* input_start = array_element_address(input, input_offset, T_BYTE);
8877   assert(input_start, "input array is null");
8878   Node* acc_start = array_element_address(alimbs, intcon(0), T_LONG);
8879   assert(acc_start, "acc array is null");
8880   Node* r_start = array_element_address(rlimbs, intcon(0), T_LONG);
8881   assert(r_start, "r array is null");
8882 
8883   Node* call = make_runtime_call(RC_LEAF | RC_NO_FP,
8884                                  OptoRuntime::poly1305_processBlocks_Type(),
8885                                  stubAddr, stubName, TypePtr::BOTTOM,
8886                                  input_start, len, acc_start, r_start);
8887   return true;
8888 }
8889 
8890 bool LibraryCallKit::inline_intpoly_montgomeryMult_P256() {
8891   address stubAddr;
8892   const char *stubName;
8893   assert(UseIntPolyIntrinsics, "need intpoly intrinsics support");
8894   assert(callee()->signature()->size() == 3, "intpoly_montgomeryMult_P256 has %d parameters", callee()->signature()->size());
8895   stubAddr = StubRoutines::intpoly_montgomeryMult_P256();
8896   stubName = "intpoly_montgomeryMult_P256";
8897 
8898   if (!stubAddr) return false;
8899   null_check_receiver();  // null-check receiver
8900   if (stopped())  return true;
8901 
8902   Node* a = argument(1);
8903   Node* b = argument(2);
8904   Node* r = argument(3);
8905 
8906   a = must_be_not_null(a, true);
8907   b = must_be_not_null(b, true);
8908   r = must_be_not_null(r, true);
8909 
8910   Node* a_start = array_element_address(a, intcon(0), T_LONG);
8911   assert(a_start, "a array is null");
8912   Node* b_start = array_element_address(b, intcon(0), T_LONG);
8913   assert(b_start, "b array is null");
8914   Node* r_start = array_element_address(r, intcon(0), T_LONG);
8915   assert(r_start, "r array is null");
8916 
8917   Node* call = make_runtime_call(RC_LEAF | RC_NO_FP,
8918                                  OptoRuntime::intpoly_montgomeryMult_P256_Type(),
8919                                  stubAddr, stubName, TypePtr::BOTTOM,
8920                                  a_start, b_start, r_start);
8921   return true;
8922 }
8923 
8924 bool LibraryCallKit::inline_intpoly_assign() {
8925   assert(UseIntPolyIntrinsics, "need intpoly intrinsics support");
8926   assert(callee()->signature()->size() == 3, "intpoly_assign has %d parameters", callee()->signature()->size());
8927   const char *stubName = "intpoly_assign";
8928   address stubAddr = StubRoutines::intpoly_assign();
8929   if (!stubAddr) return false;
8930 
8931   Node* set = argument(0);
8932   Node* a = argument(1);
8933   Node* b = argument(2);
8934   Node* arr_length = load_array_length(a);
8935 
8936   a = must_be_not_null(a, true);
8937   b = must_be_not_null(b, true);
8938 
8939   Node* a_start = array_element_address(a, intcon(0), T_LONG);
8940   assert(a_start, "a array is null");
8941   Node* b_start = array_element_address(b, intcon(0), T_LONG);
8942   assert(b_start, "b array is null");
8943 
8944   Node* call = make_runtime_call(RC_LEAF | RC_NO_FP,
8945                                  OptoRuntime::intpoly_assign_Type(),
8946                                  stubAddr, stubName, TypePtr::BOTTOM,
8947                                  set, a_start, b_start, arr_length);
8948   return true;
8949 }
8950 
8951 //------------------------------inline_digestBase_implCompress-----------------------
8952 //
8953 // Calculate MD5 for single-block byte[] array.
8954 // void com.sun.security.provider.MD5.implCompress(byte[] buf, int ofs)
8955 //
8956 // Calculate SHA (i.e., SHA-1) for single-block byte[] array.
8957 // void com.sun.security.provider.SHA.implCompress(byte[] buf, int ofs)
8958 //
8959 // Calculate SHA2 (i.e., SHA-244 or SHA-256) for single-block byte[] array.
8960 // void com.sun.security.provider.SHA2.implCompress(byte[] buf, int ofs)
8961 //
8962 // Calculate SHA5 (i.e., SHA-384 or SHA-512) for single-block byte[] array.
8963 // void com.sun.security.provider.SHA5.implCompress(byte[] buf, int ofs)
8964 //
8965 // Calculate SHA3 (i.e., SHA3-224 or SHA3-256 or SHA3-384 or SHA3-512) for single-block byte[] array.
8966 // void com.sun.security.provider.SHA3.implCompress(byte[] buf, int ofs)
8967 //
8968 bool LibraryCallKit::inline_digestBase_implCompress(vmIntrinsics::ID id) {
8969   assert(callee()->signature()->size() == 2, "sha_implCompress has 2 parameters");
8970 
8971   Node* digestBase_obj = argument(0);
8972   Node* src            = argument(1); // type oop
8973   Node* ofs            = argument(2); // type int
8974 
8975   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
8976   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
8977     // failed array check
8978     return false;
8979   }
8980   // Figure out the size and type of the elements we will be copying.
8981   BasicType src_elem = src_type->elem()->array_element_basic_type();
8982   if (src_elem != T_BYTE) {
8983     return false;
8984   }
8985   // 'src_start' points to src array + offset
8986   src = must_be_not_null(src, true);
8987   Node* src_start = array_element_address(src, ofs, src_elem);
8988   Node* state = nullptr;
8989   Node* block_size = nullptr;
8990   address stubAddr;
8991   const char *stubName;
8992 
8993   switch(id) {
8994   case vmIntrinsics::_md5_implCompress:
8995     assert(UseMD5Intrinsics, "need MD5 instruction support");
8996     state = get_state_from_digest_object(digestBase_obj, T_INT);
8997     stubAddr = StubRoutines::md5_implCompress();
8998     stubName = "md5_implCompress";
8999     break;
9000   case vmIntrinsics::_sha_implCompress:
9001     assert(UseSHA1Intrinsics, "need SHA1 instruction support");
9002     state = get_state_from_digest_object(digestBase_obj, T_INT);
9003     stubAddr = StubRoutines::sha1_implCompress();
9004     stubName = "sha1_implCompress";
9005     break;
9006   case vmIntrinsics::_sha2_implCompress:
9007     assert(UseSHA256Intrinsics, "need SHA256 instruction support");
9008     state = get_state_from_digest_object(digestBase_obj, T_INT);
9009     stubAddr = StubRoutines::sha256_implCompress();
9010     stubName = "sha256_implCompress";
9011     break;
9012   case vmIntrinsics::_sha5_implCompress:
9013     assert(UseSHA512Intrinsics, "need SHA512 instruction support");
9014     state = get_state_from_digest_object(digestBase_obj, T_LONG);
9015     stubAddr = StubRoutines::sha512_implCompress();
9016     stubName = "sha512_implCompress";
9017     break;
9018   case vmIntrinsics::_sha3_implCompress:
9019     assert(UseSHA3Intrinsics, "need SHA3 instruction support");
9020     state = get_state_from_digest_object(digestBase_obj, T_LONG);
9021     stubAddr = StubRoutines::sha3_implCompress();
9022     stubName = "sha3_implCompress";
9023     block_size = get_block_size_from_digest_object(digestBase_obj);
9024     if (block_size == nullptr) return false;
9025     break;
9026   default:
9027     fatal_unexpected_iid(id);
9028     return false;
9029   }
9030   if (state == nullptr) return false;
9031 
9032   assert(stubAddr != nullptr, "Stub %s is not generated", stubName);
9033   if (stubAddr == nullptr) return false;
9034 
9035   // Call the stub.
9036   Node* call;
9037   if (block_size == nullptr) {
9038     call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::digestBase_implCompress_Type(false),
9039                              stubAddr, stubName, TypePtr::BOTTOM,
9040                              src_start, state);
9041   } else {
9042     call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::digestBase_implCompress_Type(true),
9043                              stubAddr, stubName, TypePtr::BOTTOM,
9044                              src_start, state, block_size);
9045   }
9046 
9047   return true;
9048 }
9049 
9050 //------------------------------inline_double_keccak
9051 bool LibraryCallKit::inline_double_keccak() {
9052   address stubAddr;
9053   const char *stubName;
9054   assert(UseSHA3Intrinsics, "need SHA3 intrinsics support");
9055   assert(callee()->signature()->size() == 2, "double_keccak has 2 parameters");
9056 
9057   stubAddr = StubRoutines::double_keccak();
9058   stubName = "double_keccak";
9059   if (!stubAddr) return false;
9060 
9061   Node* status0        = argument(0);
9062   Node* status1        = argument(1);
9063 
9064   status0 = must_be_not_null(status0, true);
9065   status1 = must_be_not_null(status1, true);
9066 
9067   Node* status0_start  = array_element_address(status0, intcon(0), T_LONG);
9068   assert(status0_start, "status0 is null");
9069   Node* status1_start  = array_element_address(status1, intcon(0), T_LONG);
9070   assert(status1_start, "status1 is null");
9071   Node* double_keccak = make_runtime_call(RC_LEAF|RC_NO_FP,
9072                                   OptoRuntime::double_keccak_Type(),
9073                                   stubAddr, stubName, TypePtr::BOTTOM,
9074                                   status0_start, status1_start);
9075   // return an int
9076   Node* retvalue = _gvn.transform(new ProjNode(double_keccak, TypeFunc::Parms));
9077   set_result(retvalue);
9078   return true;
9079 }
9080 
9081 
9082 //------------------------------inline_digestBase_implCompressMB-----------------------
9083 //
9084 // Calculate MD5/SHA/SHA2/SHA5/SHA3 for multi-block byte[] array.
9085 // int com.sun.security.provider.DigestBase.implCompressMultiBlock(byte[] b, int ofs, int limit)
9086 //
9087 bool LibraryCallKit::inline_digestBase_implCompressMB(int predicate) {
9088   assert(UseMD5Intrinsics || UseSHA1Intrinsics || UseSHA256Intrinsics || UseSHA512Intrinsics || UseSHA3Intrinsics,
9089          "need MD5/SHA1/SHA256/SHA512/SHA3 instruction support");
9090   assert((uint)predicate < 5, "sanity");
9091   assert(callee()->signature()->size() == 3, "digestBase_implCompressMB has 3 parameters");
9092 
9093   Node* digestBase_obj = argument(0); // The receiver was checked for null already.
9094   Node* src            = argument(1); // byte[] array
9095   Node* ofs            = argument(2); // type int
9096   Node* limit          = argument(3); // type int
9097 
9098   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
9099   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
9100     // failed array check
9101     return false;
9102   }
9103   // Figure out the size and type of the elements we will be copying.
9104   BasicType src_elem = src_type->elem()->array_element_basic_type();
9105   if (src_elem != T_BYTE) {
9106     return false;
9107   }
9108   // 'src_start' points to src array + offset
9109   src = must_be_not_null(src, false);
9110   Node* src_start = array_element_address(src, ofs, src_elem);
9111 
9112   const char* klass_digestBase_name = nullptr;
9113   const char* stub_name = nullptr;
9114   address     stub_addr = nullptr;
9115   BasicType elem_type = T_INT;
9116 
9117   switch (predicate) {
9118   case 0:
9119     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_md5_implCompress)) {
9120       klass_digestBase_name = "sun/security/provider/MD5";
9121       stub_name = "md5_implCompressMB";
9122       stub_addr = StubRoutines::md5_implCompressMB();
9123     }
9124     break;
9125   case 1:
9126     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha_implCompress)) {
9127       klass_digestBase_name = "sun/security/provider/SHA";
9128       stub_name = "sha1_implCompressMB";
9129       stub_addr = StubRoutines::sha1_implCompressMB();
9130     }
9131     break;
9132   case 2:
9133     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha2_implCompress)) {
9134       klass_digestBase_name = "sun/security/provider/SHA2";
9135       stub_name = "sha256_implCompressMB";
9136       stub_addr = StubRoutines::sha256_implCompressMB();
9137     }
9138     break;
9139   case 3:
9140     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha5_implCompress)) {
9141       klass_digestBase_name = "sun/security/provider/SHA5";
9142       stub_name = "sha512_implCompressMB";
9143       stub_addr = StubRoutines::sha512_implCompressMB();
9144       elem_type = T_LONG;
9145     }
9146     break;
9147   case 4:
9148     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha3_implCompress)) {
9149       klass_digestBase_name = "sun/security/provider/SHA3";
9150       stub_name = "sha3_implCompressMB";
9151       stub_addr = StubRoutines::sha3_implCompressMB();
9152       elem_type = T_LONG;
9153     }
9154     break;
9155   default:
9156     fatal("unknown DigestBase intrinsic predicate: %d", predicate);
9157   }
9158   if (klass_digestBase_name != nullptr) {
9159     assert(stub_addr != nullptr, "Stub is generated");
9160     if (stub_addr == nullptr) return false;
9161 
9162     // get DigestBase klass to lookup for SHA klass
9163     const TypeInstPtr* tinst = _gvn.type(digestBase_obj)->isa_instptr();
9164     assert(tinst != nullptr, "digestBase_obj is not instance???");
9165     assert(tinst->is_loaded(), "DigestBase is not loaded");
9166 
9167     ciKlass* klass_digestBase = tinst->instance_klass()->find_klass(ciSymbol::make(klass_digestBase_name));
9168     assert(klass_digestBase->is_loaded(), "predicate checks that this class is loaded");
9169     ciInstanceKlass* instklass_digestBase = klass_digestBase->as_instance_klass();
9170     return inline_digestBase_implCompressMB(digestBase_obj, instklass_digestBase, elem_type, stub_addr, stub_name, src_start, ofs, limit);
9171   }
9172   return false;
9173 }
9174 
9175 //------------------------------inline_digestBase_implCompressMB-----------------------
9176 bool LibraryCallKit::inline_digestBase_implCompressMB(Node* digestBase_obj, ciInstanceKlass* instklass_digestBase,
9177                                                       BasicType elem_type, address stubAddr, const char *stubName,
9178                                                       Node* src_start, Node* ofs, Node* limit) {
9179   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_digestBase);
9180   const TypeOopPtr* xtype = aklass->cast_to_exactness(false)->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
9181   Node* digest_obj = new CheckCastPPNode(control(), digestBase_obj, xtype);
9182   digest_obj = _gvn.transform(digest_obj);
9183 
9184   Node* state = get_state_from_digest_object(digest_obj, elem_type);
9185   if (state == nullptr) return false;
9186 
9187   Node* block_size = nullptr;
9188   if (strcmp("sha3_implCompressMB", stubName) == 0) {
9189     block_size = get_block_size_from_digest_object(digest_obj);
9190     if (block_size == nullptr) return false;
9191   }
9192 
9193   // Call the stub.
9194   Node* call;
9195   if (block_size == nullptr) {
9196     call = make_runtime_call(RC_LEAF|RC_NO_FP,
9197                              OptoRuntime::digestBase_implCompressMB_Type(false),
9198                              stubAddr, stubName, TypePtr::BOTTOM,
9199                              src_start, state, ofs, limit);
9200   } else {
9201      call = make_runtime_call(RC_LEAF|RC_NO_FP,
9202                              OptoRuntime::digestBase_implCompressMB_Type(true),
9203                              stubAddr, stubName, TypePtr::BOTTOM,
9204                              src_start, state, block_size, ofs, limit);
9205   }
9206 
9207   // return ofs (int)
9208   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
9209   set_result(result);
9210 
9211   return true;
9212 }
9213 
9214 //------------------------------inline_galoisCounterMode_AESCrypt-----------------------
9215 bool LibraryCallKit::inline_galoisCounterMode_AESCrypt() {
9216   assert(UseAES, "need AES instruction support");
9217   address stubAddr = nullptr;
9218   const char *stubName = nullptr;
9219   stubAddr = StubRoutines::galoisCounterMode_AESCrypt();
9220   stubName = "galoisCounterMode_AESCrypt";
9221 
9222   if (stubAddr == nullptr) return false;
9223 
9224   Node* in      = argument(0);
9225   Node* inOfs   = argument(1);
9226   Node* len     = argument(2);
9227   Node* ct      = argument(3);
9228   Node* ctOfs   = argument(4);
9229   Node* out     = argument(5);
9230   Node* outOfs  = argument(6);
9231   Node* gctr_object = argument(7);
9232   Node* ghash_object = argument(8);
9233 
9234   // (1) in, ct and out are arrays.
9235   const TypeAryPtr* in_type = in->Value(&_gvn)->isa_aryptr();
9236   const TypeAryPtr* ct_type = ct->Value(&_gvn)->isa_aryptr();
9237   const TypeAryPtr* out_type = out->Value(&_gvn)->isa_aryptr();
9238   assert( in_type != nullptr &&  in_type->elem() != Type::BOTTOM &&
9239           ct_type != nullptr &&  ct_type->elem() != Type::BOTTOM &&
9240          out_type != nullptr && out_type->elem() != Type::BOTTOM, "args are strange");
9241 
9242   // checks are the responsibility of the caller
9243   Node* in_start = in;
9244   Node* ct_start = ct;
9245   Node* out_start = out;
9246   if (inOfs != nullptr || ctOfs != nullptr || outOfs != nullptr) {
9247     assert(inOfs != nullptr && ctOfs != nullptr && outOfs != nullptr, "");
9248     in_start = array_element_address(in, inOfs, T_BYTE);
9249     ct_start = array_element_address(ct, ctOfs, T_BYTE);
9250     out_start = array_element_address(out, outOfs, T_BYTE);
9251   }
9252 
9253   // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
9254   // (because of the predicated logic executed earlier).
9255   // so we cast it here safely.
9256   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
9257   Node* embeddedCipherObj = load_field_from_object(gctr_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
9258   Node* counter = load_field_from_object(gctr_object, "counter", "[B");
9259   Node* subkeyHtbl = load_field_from_object(ghash_object, "subkeyHtbl", "[J");
9260   Node* state = load_field_from_object(ghash_object, "state", "[J");
9261 
9262   if (embeddedCipherObj == nullptr || counter == nullptr || subkeyHtbl == nullptr || state == nullptr) {
9263     return false;
9264   }
9265   // cast it to what we know it will be at runtime
9266   const TypeInstPtr* tinst = _gvn.type(gctr_object)->isa_instptr();
9267   assert(tinst != nullptr, "GCTR obj is null");
9268   assert(tinst->is_loaded(), "GCTR obj is not loaded");
9269   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
9270   assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
9271   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
9272   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
9273   const TypeOopPtr* xtype = aklass->as_instance_type();
9274   Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
9275   aescrypt_object = _gvn.transform(aescrypt_object);
9276   // we need to get the start of the aescrypt_object's expanded key array
9277   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object, /* is_decrypt */ false);
9278   if (k_start == nullptr) return false;
9279   // similarly, get the start address of the r vector
9280   Node* cnt_start = array_element_address(counter, intcon(0), T_BYTE);
9281   Node* state_start = array_element_address(state, intcon(0), T_LONG);
9282   Node* subkeyHtbl_start = array_element_address(subkeyHtbl, intcon(0), T_LONG);
9283 
9284 
9285   // Call the stub, passing params
9286   Node* gcmCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
9287                                OptoRuntime::galoisCounterMode_aescrypt_Type(),
9288                                stubAddr, stubName, TypePtr::BOTTOM,
9289                                in_start, len, ct_start, out_start, k_start, state_start, subkeyHtbl_start, cnt_start);
9290 
9291   // return cipher length (int)
9292   Node* retvalue = _gvn.transform(new ProjNode(gcmCrypt, TypeFunc::Parms));
9293   set_result(retvalue);
9294 
9295   return true;
9296 }
9297 
9298 //----------------------------inline_galoisCounterMode_AESCrypt_predicate----------------------------
9299 // Return node representing slow path of predicate check.
9300 // the pseudo code we want to emulate with this predicate is:
9301 // for encryption:
9302 //    if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
9303 // for decryption:
9304 //    if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
9305 //    note cipher==plain is more conservative than the original java code but that's OK
9306 //
9307 
9308 Node* LibraryCallKit::inline_galoisCounterMode_AESCrypt_predicate() {
9309   // The receiver was checked for null already.
9310   Node* objGCTR = argument(7);
9311   // Load embeddedCipher field of GCTR object.
9312   Node* embeddedCipherObj = load_field_from_object(objGCTR, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
9313   assert(embeddedCipherObj != nullptr, "embeddedCipherObj is null");
9314 
9315   // get AESCrypt klass for instanceOf check
9316   // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
9317   // will have same classloader as CipherBlockChaining object
9318   const TypeInstPtr* tinst = _gvn.type(objGCTR)->isa_instptr();
9319   assert(tinst != nullptr, "GCTR obj is null");
9320   assert(tinst->is_loaded(), "GCTR obj is not loaded");
9321 
9322   // we want to do an instanceof comparison against the AESCrypt class
9323   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
9324   if (!klass_AESCrypt->is_loaded()) {
9325     // if AESCrypt is not even loaded, we never take the intrinsic fast path
9326     Node* ctrl = control();
9327     set_control(top()); // no regular fast path
9328     return ctrl;
9329   }
9330 
9331   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
9332   Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
9333   Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
9334   Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
9335   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
9336 
9337   return instof_false; // even if it is null
9338 }
9339 
9340 //------------------------------get_state_from_digest_object-----------------------
9341 Node * LibraryCallKit::get_state_from_digest_object(Node *digest_object, BasicType elem_type) {
9342   const char* state_type;
9343   switch (elem_type) {
9344     case T_BYTE: state_type = "[B"; break;
9345     case T_INT:  state_type = "[I"; break;
9346     case T_LONG: state_type = "[J"; break;
9347     default: ShouldNotReachHere();
9348   }
9349   Node* digest_state = load_field_from_object(digest_object, "state", state_type);
9350   assert (digest_state != nullptr, "wrong version of sun.security.provider.MD5/SHA/SHA2/SHA5/SHA3");
9351   if (digest_state == nullptr) return (Node *) nullptr;
9352 
9353   // now have the array, need to get the start address of the state array
9354   Node* state = array_element_address(digest_state, intcon(0), elem_type);
9355   return state;
9356 }
9357 
9358 //------------------------------get_block_size_from_sha3_object----------------------------------
9359 Node * LibraryCallKit::get_block_size_from_digest_object(Node *digest_object) {
9360   Node* block_size = load_field_from_object(digest_object, "blockSize", "I");
9361   assert (block_size != nullptr, "sanity");
9362   return block_size;
9363 }
9364 
9365 //----------------------------inline_digestBase_implCompressMB_predicate----------------------------
9366 // Return node representing slow path of predicate check.
9367 // the pseudo code we want to emulate with this predicate is:
9368 //    if (digestBaseObj instanceof MD5/SHA/SHA2/SHA5/SHA3) do_intrinsic, else do_javapath
9369 //
9370 Node* LibraryCallKit::inline_digestBase_implCompressMB_predicate(int predicate) {
9371   assert(UseMD5Intrinsics || UseSHA1Intrinsics || UseSHA256Intrinsics || UseSHA512Intrinsics || UseSHA3Intrinsics,
9372          "need MD5/SHA1/SHA256/SHA512/SHA3 instruction support");
9373   assert((uint)predicate < 5, "sanity");
9374 
9375   // The receiver was checked for null already.
9376   Node* digestBaseObj = argument(0);
9377 
9378   // get DigestBase klass for instanceOf check
9379   const TypeInstPtr* tinst = _gvn.type(digestBaseObj)->isa_instptr();
9380   assert(tinst != nullptr, "digestBaseObj is null");
9381   assert(tinst->is_loaded(), "DigestBase is not loaded");
9382 
9383   const char* klass_name = nullptr;
9384   switch (predicate) {
9385   case 0:
9386     if (UseMD5Intrinsics) {
9387       // we want to do an instanceof comparison against the MD5 class
9388       klass_name = "sun/security/provider/MD5";
9389     }
9390     break;
9391   case 1:
9392     if (UseSHA1Intrinsics) {
9393       // we want to do an instanceof comparison against the SHA class
9394       klass_name = "sun/security/provider/SHA";
9395     }
9396     break;
9397   case 2:
9398     if (UseSHA256Intrinsics) {
9399       // we want to do an instanceof comparison against the SHA2 class
9400       klass_name = "sun/security/provider/SHA2";
9401     }
9402     break;
9403   case 3:
9404     if (UseSHA512Intrinsics) {
9405       // we want to do an instanceof comparison against the SHA5 class
9406       klass_name = "sun/security/provider/SHA5";
9407     }
9408     break;
9409   case 4:
9410     if (UseSHA3Intrinsics) {
9411       // we want to do an instanceof comparison against the SHA3 class
9412       klass_name = "sun/security/provider/SHA3";
9413     }
9414     break;
9415   default:
9416     fatal("unknown SHA intrinsic predicate: %d", predicate);
9417   }
9418 
9419   ciKlass* klass = nullptr;
9420   if (klass_name != nullptr) {
9421     klass = tinst->instance_klass()->find_klass(ciSymbol::make(klass_name));
9422   }
9423   if ((klass == nullptr) || !klass->is_loaded()) {
9424     // if none of MD5/SHA/SHA2/SHA5 is loaded, we never take the intrinsic fast path
9425     Node* ctrl = control();
9426     set_control(top()); // no intrinsic path
9427     return ctrl;
9428   }
9429   ciInstanceKlass* instklass = klass->as_instance_klass();
9430 
9431   Node* instof = gen_instanceof(digestBaseObj, makecon(TypeKlassPtr::make(instklass)));
9432   Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
9433   Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
9434   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
9435 
9436   return instof_false;  // even if it is null
9437 }
9438 
9439 //-------------inline_fma-----------------------------------
9440 bool LibraryCallKit::inline_fma(vmIntrinsics::ID id) {
9441   Node *a = nullptr;
9442   Node *b = nullptr;
9443   Node *c = nullptr;
9444   Node* result = nullptr;
9445   switch (id) {
9446   case vmIntrinsics::_fmaD:
9447     assert(callee()->signature()->size() == 6, "fma has 3 parameters of size 2 each.");
9448     // no receiver since it is static method
9449     a = argument(0);
9450     b = argument(2);
9451     c = argument(4);
9452     result = _gvn.transform(new FmaDNode(a, b, c));
9453     break;
9454   case vmIntrinsics::_fmaF:
9455     assert(callee()->signature()->size() == 3, "fma has 3 parameters of size 1 each.");
9456     a = argument(0);
9457     b = argument(1);
9458     c = argument(2);
9459     result = _gvn.transform(new FmaFNode(a, b, c));
9460     break;
9461   default:
9462     fatal_unexpected_iid(id);  break;
9463   }
9464   set_result(result);
9465   return true;
9466 }
9467 
9468 bool LibraryCallKit::inline_character_compare(vmIntrinsics::ID id) {
9469   // argument(0) is receiver
9470   Node* codePoint = argument(1);
9471   Node* n = nullptr;
9472 
9473   switch (id) {
9474     case vmIntrinsics::_isDigit :
9475       n = new DigitNode(control(), codePoint);
9476       break;
9477     case vmIntrinsics::_isLowerCase :
9478       n = new LowerCaseNode(control(), codePoint);
9479       break;
9480     case vmIntrinsics::_isUpperCase :
9481       n = new UpperCaseNode(control(), codePoint);
9482       break;
9483     case vmIntrinsics::_isWhitespace :
9484       n = new WhitespaceNode(control(), codePoint);
9485       break;
9486     default:
9487       fatal_unexpected_iid(id);
9488   }
9489 
9490   set_result(_gvn.transform(n));
9491   return true;
9492 }
9493 
9494 bool LibraryCallKit::inline_profileBoolean() {
9495   Node* counts = argument(1);
9496   const TypeAryPtr* ary = nullptr;
9497   ciArray* aobj = nullptr;
9498   if (counts->is_Con()
9499       && (ary = counts->bottom_type()->isa_aryptr()) != nullptr
9500       && (aobj = ary->const_oop()->as_array()) != nullptr
9501       && (aobj->length() == 2)) {
9502     // Profile is int[2] where [0] and [1] correspond to false and true value occurrences respectively.
9503     jint false_cnt = aobj->element_value(0).as_int();
9504     jint  true_cnt = aobj->element_value(1).as_int();
9505 
9506     if (C->log() != nullptr) {
9507       C->log()->elem("observe source='profileBoolean' false='%d' true='%d'",
9508                      false_cnt, true_cnt);
9509     }
9510 
9511     if (false_cnt + true_cnt == 0) {
9512       // According to profile, never executed.
9513       uncommon_trap_exact(Deoptimization::Reason_intrinsic,
9514                           Deoptimization::Action_reinterpret);
9515       return true;
9516     }
9517 
9518     // result is a boolean (0 or 1) and its profile (false_cnt & true_cnt)
9519     // is a number of each value occurrences.
9520     Node* result = argument(0);
9521     if (false_cnt == 0 || true_cnt == 0) {
9522       // According to profile, one value has been never seen.
9523       int expected_val = (false_cnt == 0) ? 1 : 0;
9524 
9525       Node* cmp  = _gvn.transform(new CmpINode(result, intcon(expected_val)));
9526       Node* test = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
9527 
9528       IfNode* check = create_and_map_if(control(), test, PROB_ALWAYS, COUNT_UNKNOWN);
9529       Node* fast_path = _gvn.transform(new IfTrueNode(check));
9530       Node* slow_path = _gvn.transform(new IfFalseNode(check));
9531 
9532       { // Slow path: uncommon trap for never seen value and then reexecute
9533         // MethodHandleImpl::profileBoolean() to bump the count, so JIT knows
9534         // the value has been seen at least once.
9535         PreserveJVMState pjvms(this);
9536         PreserveReexecuteState preexecs(this);
9537         jvms()->set_should_reexecute(true);
9538 
9539         set_control(slow_path);
9540         set_i_o(i_o());
9541 
9542         uncommon_trap_exact(Deoptimization::Reason_intrinsic,
9543                             Deoptimization::Action_reinterpret);
9544       }
9545       // The guard for never seen value enables sharpening of the result and
9546       // returning a constant. It allows to eliminate branches on the same value
9547       // later on.
9548       set_control(fast_path);
9549       result = intcon(expected_val);
9550     }
9551     // Stop profiling.
9552     // MethodHandleImpl::profileBoolean() has profiling logic in its bytecode.
9553     // By replacing method body with profile data (represented as ProfileBooleanNode
9554     // on IR level) we effectively disable profiling.
9555     // It enables full speed execution once optimized code is generated.
9556     Node* profile = _gvn.transform(new ProfileBooleanNode(result, false_cnt, true_cnt));
9557     C->record_for_igvn(profile);
9558     set_result(profile);
9559     return true;
9560   } else {
9561     // Continue profiling.
9562     // Profile data isn't available at the moment. So, execute method's bytecode version.
9563     // Usually, when GWT LambdaForms are profiled it means that a stand-alone nmethod
9564     // is compiled and counters aren't available since corresponding MethodHandle
9565     // isn't a compile-time constant.
9566     return false;
9567   }
9568 }
9569 
9570 bool LibraryCallKit::inline_isCompileConstant() {
9571   Node* n = argument(0);
9572   set_result(n->is_Con() ? intcon(1) : intcon(0));
9573   return true;
9574 }
9575 
9576 //------------------------------- inline_getObjectSize --------------------------------------
9577 //
9578 // Calculate the runtime size of the object/array.
9579 //   native long sun.instrument.InstrumentationImpl.getObjectSize0(long nativeAgent, Object objectToSize);
9580 //
9581 bool LibraryCallKit::inline_getObjectSize() {
9582   Node* obj = argument(3);
9583   Node* klass_node = load_object_klass(obj);
9584 
9585   jint  layout_con = Klass::_lh_neutral_value;
9586   Node* layout_val = get_layout_helper(klass_node, layout_con);
9587   int   layout_is_con = (layout_val == nullptr);
9588 
9589   if (layout_is_con) {
9590     // Layout helper is constant, can figure out things at compile time.
9591 
9592     if (Klass::layout_helper_is_instance(layout_con)) {
9593       // Instance case:  layout_con contains the size itself.
9594       Node *size = longcon(Klass::layout_helper_size_in_bytes(layout_con));
9595       set_result(size);
9596     } else {
9597       // Array case: size is round(header + element_size*arraylength).
9598       // Since arraylength is different for every array instance, we have to
9599       // compute the whole thing at runtime.
9600 
9601       Node* arr_length = load_array_length(obj);
9602 
9603       int round_mask = MinObjAlignmentInBytes - 1;
9604       int hsize  = Klass::layout_helper_header_size(layout_con);
9605       int eshift = Klass::layout_helper_log2_element_size(layout_con);
9606 
9607       if ((round_mask & ~right_n_bits(eshift)) == 0) {
9608         round_mask = 0;  // strength-reduce it if it goes away completely
9609       }
9610       assert((hsize & right_n_bits(eshift)) == 0, "hsize is pre-rounded");
9611       Node* header_size = intcon(hsize + round_mask);
9612 
9613       Node* lengthx = ConvI2X(arr_length);
9614       Node* headerx = ConvI2X(header_size);
9615 
9616       Node* abody = lengthx;
9617       if (eshift != 0) {
9618         abody = _gvn.transform(new LShiftXNode(lengthx, intcon(eshift)));
9619       }
9620       Node* size = _gvn.transform( new AddXNode(headerx, abody) );
9621       if (round_mask != 0) {
9622         size = _gvn.transform( new AndXNode(size, MakeConX(~round_mask)) );
9623       }
9624       size = ConvX2L(size);
9625       set_result(size);
9626     }
9627   } else {
9628     // Layout helper is not constant, need to test for array-ness at runtime.
9629 
9630     enum { _instance_path = 1, _array_path, PATH_LIMIT };
9631     RegionNode* result_reg = new RegionNode(PATH_LIMIT);
9632     PhiNode* result_val = new PhiNode(result_reg, TypeLong::LONG);
9633     record_for_igvn(result_reg);
9634 
9635     Node* array_ctl = generate_array_guard(klass_node, nullptr, &obj);
9636     if (array_ctl != nullptr) {
9637       // Array case: size is round(header + element_size*arraylength).
9638       // Since arraylength is different for every array instance, we have to
9639       // compute the whole thing at runtime.
9640 
9641       PreserveJVMState pjvms(this);
9642       set_control(array_ctl);
9643       Node* arr_length = load_array_length(obj);
9644 
9645       int round_mask = MinObjAlignmentInBytes - 1;
9646       Node* mask = intcon(round_mask);
9647 
9648       Node* hss = intcon(Klass::_lh_header_size_shift);
9649       Node* hsm = intcon(Klass::_lh_header_size_mask);
9650       Node* header_size = _gvn.transform(new URShiftINode(layout_val, hss));
9651       header_size = _gvn.transform(new AndINode(header_size, hsm));
9652       header_size = _gvn.transform(new AddINode(header_size, mask));
9653 
9654       // There is no need to mask or shift this value.
9655       // The semantics of LShiftINode include an implicit mask to 0x1F.
9656       assert(Klass::_lh_log2_element_size_shift == 0, "use shift in place");
9657       Node* elem_shift = layout_val;
9658 
9659       Node* lengthx = ConvI2X(arr_length);
9660       Node* headerx = ConvI2X(header_size);
9661 
9662       Node* abody = _gvn.transform(new LShiftXNode(lengthx, elem_shift));
9663       Node* size = _gvn.transform(new AddXNode(headerx, abody));
9664       if (round_mask != 0) {
9665         size = _gvn.transform(new AndXNode(size, MakeConX(~round_mask)));
9666       }
9667       size = ConvX2L(size);
9668 
9669       result_reg->init_req(_array_path, control());
9670       result_val->init_req(_array_path, size);
9671     }
9672 
9673     if (!stopped()) {
9674       // Instance case: the layout helper gives us instance size almost directly,
9675       // but we need to mask out the _lh_instance_slow_path_bit.
9676       Node* size = ConvI2X(layout_val);
9677       assert((int) Klass::_lh_instance_slow_path_bit < BytesPerLong, "clear bit");
9678       Node* mask = MakeConX(~(intptr_t) right_n_bits(LogBytesPerLong));
9679       size = _gvn.transform(new AndXNode(size, mask));
9680       size = ConvX2L(size);
9681 
9682       result_reg->init_req(_instance_path, control());
9683       result_val->init_req(_instance_path, size);
9684     }
9685 
9686     set_result(result_reg, result_val);
9687   }
9688 
9689   return true;
9690 }
9691 
9692 //------------------------------- inline_blackhole --------------------------------------
9693 //
9694 // Make sure all arguments to this node are alive.
9695 // This matches methods that were requested to be blackholed through compile commands.
9696 //
9697 bool LibraryCallKit::inline_blackhole() {
9698   assert(callee()->is_static(), "Should have been checked before: only static methods here");
9699   assert(callee()->is_empty(), "Should have been checked before: only empty methods here");
9700   assert(callee()->holder()->is_loaded(), "Should have been checked before: only methods for loaded classes here");
9701 
9702   // Blackhole node pinches only the control, not memory. This allows
9703   // the blackhole to be pinned in the loop that computes blackholed
9704   // values, but have no other side effects, like breaking the optimizations
9705   // across the blackhole.
9706 
9707   Node* bh = _gvn.transform(new BlackholeNode(control()));
9708   set_control(_gvn.transform(new ProjNode(bh, TypeFunc::Control)));
9709 
9710   // Bind call arguments as blackhole arguments to keep them alive
9711   uint nargs = callee()->arg_size();
9712   for (uint i = 0; i < nargs; i++) {
9713     bh->add_req(argument(i));
9714   }
9715 
9716   return true;
9717 }
9718 
9719 Node* LibraryCallKit::unbox_fp16_value(const TypeInstPtr* float16_box_type, ciField* field, Node* box) {
9720   const TypeInstPtr* box_type = _gvn.type(box)->isa_instptr();
9721   if (box_type == nullptr || box_type->instance_klass() != float16_box_type->instance_klass()) {
9722     return nullptr; // box klass is not Float16
9723   }
9724 
9725   // Null check; get notnull casted pointer
9726   Node* null_ctl = top();
9727   Node* not_null_box = null_check_oop(box, &null_ctl, true);
9728   // If not_null_box is dead, only null-path is taken
9729   if (stopped()) {
9730     set_control(null_ctl);
9731     return nullptr;
9732   }
9733   assert(not_null_box->bottom_type()->is_instptr()->maybe_null() == false, "");
9734   const TypePtr* adr_type = C->alias_type(field)->adr_type();
9735   Node* adr = basic_plus_adr(not_null_box, field->offset_in_bytes());
9736   return access_load_at(not_null_box, adr, adr_type, TypeInt::SHORT, T_SHORT, IN_HEAP);
9737 }
9738 
9739 Node* LibraryCallKit::box_fp16_value(const TypeInstPtr* float16_box_type, ciField* field, Node* value) {
9740   PreserveReexecuteState preexecs(this);
9741   jvms()->set_should_reexecute(true);
9742 
9743   const TypeKlassPtr* klass_type = float16_box_type->as_klass_type();
9744   Node* klass_node = makecon(klass_type);
9745   Node* box = new_instance(klass_node);
9746 
9747   Node* value_field = basic_plus_adr(box, field->offset_in_bytes());
9748   const TypePtr* value_adr_type = value_field->bottom_type()->is_ptr();
9749 
9750   Node* field_store = _gvn.transform(access_store_at(box,
9751                                                      value_field,
9752                                                      value_adr_type,
9753                                                      value,
9754                                                      TypeInt::SHORT,
9755                                                      T_SHORT,
9756                                                      IN_HEAP));
9757   set_memory(field_store, value_adr_type);
9758   return box;
9759 }
9760 
9761 bool LibraryCallKit::inline_fp16_operations(vmIntrinsics::ID id, int num_args) {
9762   if (!Matcher::match_rule_supported(Op_ReinterpretS2HF) ||
9763       !Matcher::match_rule_supported(Op_ReinterpretHF2S)) {
9764     return false;
9765   }
9766 
9767   const TypeInstPtr* box_type = _gvn.type(argument(0))->isa_instptr();
9768   if (box_type == nullptr || box_type->const_oop() == nullptr) {
9769     return false;
9770   }
9771 
9772   ciInstanceKlass* float16_klass = box_type->const_oop()->as_instance()->java_lang_Class_klass()->as_instance_klass();
9773   const TypeInstPtr* float16_box_type = TypeInstPtr::make_exact(TypePtr::NotNull, float16_klass);
9774   ciField* field = float16_klass->get_field_by_name(ciSymbols::value_name(),
9775                                                     ciSymbols::short_signature(),
9776                                                     false);
9777   assert(field != nullptr, "");
9778 
9779   // Transformed nodes
9780   Node* fld1 = nullptr;
9781   Node* fld2 = nullptr;
9782   Node* fld3 = nullptr;
9783   switch(num_args) {
9784     case 3:
9785       fld3 = unbox_fp16_value(float16_box_type, field, argument(3));
9786       if (fld3 == nullptr) {
9787         return false;
9788       }
9789       fld3 = _gvn.transform(new ReinterpretS2HFNode(fld3));
9790     // fall-through
9791     case 2:
9792       fld2 = unbox_fp16_value(float16_box_type, field, argument(2));
9793       if (fld2 == nullptr) {
9794         return false;
9795       }
9796       fld2 = _gvn.transform(new ReinterpretS2HFNode(fld2));
9797     // fall-through
9798     case 1:
9799       fld1 = unbox_fp16_value(float16_box_type, field, argument(1));
9800       if (fld1 == nullptr) {
9801         return false;
9802       }
9803       fld1 = _gvn.transform(new ReinterpretS2HFNode(fld1));
9804       break;
9805     default: fatal("Unsupported number of arguments %d", num_args);
9806   }
9807 
9808   Node* result = nullptr;
9809   switch (id) {
9810     // Unary operations
9811     case vmIntrinsics::_sqrt_float16:
9812       result = _gvn.transform(new SqrtHFNode(C, control(), fld1));
9813       break;
9814     // Ternary operations
9815     case vmIntrinsics::_fma_float16:
9816       result = _gvn.transform(new FmaHFNode(fld1, fld2, fld3));
9817       break;
9818     default:
9819       fatal_unexpected_iid(id);
9820       break;
9821   }
9822   result = _gvn.transform(new ReinterpretHF2SNode(result));
9823   set_result(box_fp16_value(float16_box_type, field, result));
9824   return true;
9825 }
9826