1 /*
   2  * Copyright (c) 1999, 2025, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "asm/macroAssembler.hpp"
  26 #include "ci/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/jniHandles.inline.hpp"
  68 #include "runtime/objectMonitor.hpp"
  69 #include "runtime/sharedRuntime.hpp"
  70 #include "runtime/stubRoutines.hpp"
  71 #include "utilities/globalDefinitions.hpp"
  72 #include "utilities/macros.hpp"
  73 #include "utilities/powerOfTwo.hpp"
  74 
  75 //---------------------------make_vm_intrinsic----------------------------
  76 CallGenerator* Compile::make_vm_intrinsic(ciMethod* m, bool is_virtual) {
  77   vmIntrinsicID id = m->intrinsic_id();
  78   assert(id != vmIntrinsics::_none, "must be a VM intrinsic");
  79 
  80   if (!m->is_loaded()) {
  81     // Do not attempt to inline unloaded methods.
  82     return nullptr;
  83   }
  84 
  85   C2Compiler* compiler = (C2Compiler*)CompileBroker::compiler(CompLevel_full_optimization);
  86   bool is_available = false;
  87 
  88   {
  89     // For calling is_intrinsic_supported and is_intrinsic_disabled_by_flag
  90     // the compiler must transition to '_thread_in_vm' state because both
  91     // methods access VM-internal data.
  92     VM_ENTRY_MARK;
  93     methodHandle mh(THREAD, m->get_Method());
  94     is_available = compiler != nullptr && compiler->is_intrinsic_available(mh, C->directive());
  95     if (is_available && is_virtual) {
  96       is_available = vmIntrinsics::does_virtual_dispatch(id);
  97     }
  98   }
  99 
 100   if (is_available) {
 101     assert(id <= vmIntrinsics::LAST_COMPILER_INLINE, "caller responsibility");
 102     assert(id != vmIntrinsics::_Object_init && id != vmIntrinsics::_invoke, "enum out of order?");
 103     return new LibraryIntrinsic(m, is_virtual,
 104                                 vmIntrinsics::predicates_needed(id),
 105                                 vmIntrinsics::does_virtual_dispatch(id),
 106                                 id);
 107   } else {
 108     return nullptr;
 109   }
 110 }
 111 
 112 JVMState* LibraryIntrinsic::generate(JVMState* jvms) {
 113   LibraryCallKit kit(jvms, this);
 114   Compile* C = kit.C;
 115   int nodes = C->unique();
 116 #ifndef PRODUCT
 117   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
 118     char buf[1000];
 119     const char* str = vmIntrinsics::short_name_as_C_string(intrinsic_id(), buf, sizeof(buf));
 120     tty->print_cr("Intrinsic %s", str);
 121   }
 122 #endif
 123   ciMethod* callee = kit.callee();
 124   const int bci    = kit.bci();
 125 #ifdef ASSERT
 126   Node* ctrl = kit.control();
 127 #endif
 128   // Try to inline the intrinsic.
 129   if (callee->check_intrinsic_candidate() &&
 130       kit.try_to_inline(_last_predicate)) {
 131     const char *inline_msg = is_virtual() ? "(intrinsic, virtual)"
 132                                           : "(intrinsic)";
 133     CompileTask::print_inlining_ul(callee, jvms->depth() - 1, bci, InliningResult::SUCCESS, inline_msg);
 134     C->inline_printer()->record(callee, jvms, InliningResult::SUCCESS, inline_msg);
 135     C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_worked);
 136     if (C->log()) {
 137       C->log()->elem("intrinsic id='%s'%s nodes='%d'",
 138                      vmIntrinsics::name_at(intrinsic_id()),
 139                      (is_virtual() ? " virtual='1'" : ""),
 140                      C->unique() - nodes);
 141     }
 142     // Push the result from the inlined method onto the stack.
 143     kit.push_result();
 144     return kit.transfer_exceptions_into_jvms();
 145   }
 146 
 147   // The intrinsic bailed out
 148   assert(ctrl == kit.control(), "Control flow was added although the intrinsic bailed out");
 149   assert(jvms->map() == kit.map(), "Out of sync JVM state");
 150   if (jvms->has_method()) {
 151     // Not a root compile.
 152     const char* msg;
 153     if (callee->intrinsic_candidate()) {
 154       msg = is_virtual() ? "failed to inline (intrinsic, virtual)" : "failed to inline (intrinsic)";
 155     } else {
 156       msg = is_virtual() ? "failed to inline (intrinsic, virtual), method not annotated"
 157                          : "failed to inline (intrinsic), method not annotated";
 158     }
 159     CompileTask::print_inlining_ul(callee, jvms->depth() - 1, bci, InliningResult::FAILURE, msg);
 160     C->inline_printer()->record(callee, jvms, InliningResult::FAILURE, msg);
 161   } else {
 162     // Root compile
 163     ResourceMark rm;
 164     stringStream msg_stream;
 165     msg_stream.print("Did not generate intrinsic %s%s at bci:%d in",
 166                      vmIntrinsics::name_at(intrinsic_id()),
 167                      is_virtual() ? " (virtual)" : "", bci);
 168     const char *msg = msg_stream.freeze();
 169     log_debug(jit, inlining)("%s", msg);
 170     if (C->print_intrinsics() || C->print_inlining()) {
 171       tty->print("%s", msg);
 172     }
 173   }
 174   C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_failed);
 175 
 176   return nullptr;
 177 }
 178 
 179 Node* LibraryIntrinsic::generate_predicate(JVMState* jvms, int predicate) {
 180   LibraryCallKit kit(jvms, this);
 181   Compile* C = kit.C;
 182   int nodes = C->unique();
 183   _last_predicate = predicate;
 184 #ifndef PRODUCT
 185   assert(is_predicated() && predicate < predicates_count(), "sanity");
 186   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
 187     char buf[1000];
 188     const char* str = vmIntrinsics::short_name_as_C_string(intrinsic_id(), buf, sizeof(buf));
 189     tty->print_cr("Predicate for intrinsic %s", str);
 190   }
 191 #endif
 192   ciMethod* callee = kit.callee();
 193   const int bci    = kit.bci();
 194 
 195   Node* slow_ctl = kit.try_to_predicate(predicate);
 196   if (!kit.failing()) {
 197     const char *inline_msg = is_virtual() ? "(intrinsic, virtual, predicate)"
 198                                           : "(intrinsic, predicate)";
 199     CompileTask::print_inlining_ul(callee, jvms->depth() - 1, bci, InliningResult::SUCCESS, inline_msg);
 200     C->inline_printer()->record(callee, jvms, InliningResult::SUCCESS, inline_msg);
 201 
 202     C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_worked);
 203     if (C->log()) {
 204       C->log()->elem("predicate_intrinsic id='%s'%s nodes='%d'",
 205                      vmIntrinsics::name_at(intrinsic_id()),
 206                      (is_virtual() ? " virtual='1'" : ""),
 207                      C->unique() - nodes);
 208     }
 209     return slow_ctl; // Could be null if the check folds.
 210   }
 211 
 212   // The intrinsic bailed out
 213   if (jvms->has_method()) {
 214     // Not a root compile.
 215     const char* msg = "failed to generate predicate for intrinsic";
 216     CompileTask::print_inlining_ul(kit.callee(), jvms->depth() - 1, bci, InliningResult::FAILURE, msg);
 217     C->inline_printer()->record(kit.callee(), jvms, InliningResult::FAILURE, msg);
 218   } else {
 219     // Root compile
 220     ResourceMark rm;
 221     stringStream msg_stream;
 222     msg_stream.print("Did not generate intrinsic %s%s at bci:%d in",
 223                      vmIntrinsics::name_at(intrinsic_id()),
 224                      is_virtual() ? " (virtual)" : "", bci);
 225     const char *msg = msg_stream.freeze();
 226     log_debug(jit, inlining)("%s", msg);
 227     C->inline_printer()->record(kit.callee(), jvms, InliningResult::FAILURE, msg);
 228   }
 229   C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_failed);
 230   return nullptr;
 231 }
 232 
 233 bool LibraryCallKit::try_to_inline(int predicate) {
 234   // Handle symbolic names for otherwise undistinguished boolean switches:
 235   const bool is_store       = true;
 236   const bool is_compress    = true;
 237   const bool is_static      = true;
 238   const bool is_volatile    = true;
 239 
 240   if (!jvms()->has_method()) {
 241     // Root JVMState has a null method.
 242     assert(map()->memory()->Opcode() == Op_Parm, "");
 243     // Insert the memory aliasing node
 244     set_all_memory(reset_memory());
 245   }
 246   assert(merged_memory(), "");
 247 
 248   switch (intrinsic_id()) {
 249   case vmIntrinsics::_hashCode:                 return inline_native_hashcode(intrinsic()->is_virtual(), !is_static);
 250   case vmIntrinsics::_identityHashCode:         return inline_native_hashcode(/*!virtual*/ false,         is_static);
 251   case vmIntrinsics::_getClass:                 return inline_native_getClass();
 252 
 253   case vmIntrinsics::_ceil:
 254   case vmIntrinsics::_floor:
 255   case vmIntrinsics::_rint:
 256   case vmIntrinsics::_dsin:
 257   case vmIntrinsics::_dcos:
 258   case vmIntrinsics::_dtan:
 259   case vmIntrinsics::_dsinh:
 260   case vmIntrinsics::_dtanh:
 261   case vmIntrinsics::_dcbrt:
 262   case vmIntrinsics::_dabs:
 263   case vmIntrinsics::_fabs:
 264   case vmIntrinsics::_iabs:
 265   case vmIntrinsics::_labs:
 266   case vmIntrinsics::_datan2:
 267   case vmIntrinsics::_dsqrt:
 268   case vmIntrinsics::_dsqrt_strict:
 269   case vmIntrinsics::_dexp:
 270   case vmIntrinsics::_dlog:
 271   case vmIntrinsics::_dlog10:
 272   case vmIntrinsics::_dpow:
 273   case vmIntrinsics::_dcopySign:
 274   case vmIntrinsics::_fcopySign:
 275   case vmIntrinsics::_dsignum:
 276   case vmIntrinsics::_roundF:
 277   case vmIntrinsics::_roundD:
 278   case vmIntrinsics::_fsignum:                  return inline_math_native(intrinsic_id());
 279 
 280   case vmIntrinsics::_notify:
 281   case vmIntrinsics::_notifyAll:
 282     return inline_notify(intrinsic_id());
 283 
 284   case vmIntrinsics::_addExactI:                return inline_math_addExactI(false /* add */);
 285   case vmIntrinsics::_addExactL:                return inline_math_addExactL(false /* add */);
 286   case vmIntrinsics::_decrementExactI:          return inline_math_subtractExactI(true /* decrement */);
 287   case vmIntrinsics::_decrementExactL:          return inline_math_subtractExactL(true /* decrement */);
 288   case vmIntrinsics::_incrementExactI:          return inline_math_addExactI(true /* increment */);
 289   case vmIntrinsics::_incrementExactL:          return inline_math_addExactL(true /* increment */);
 290   case vmIntrinsics::_multiplyExactI:           return inline_math_multiplyExactI();
 291   case vmIntrinsics::_multiplyExactL:           return inline_math_multiplyExactL();
 292   case vmIntrinsics::_multiplyHigh:             return inline_math_multiplyHigh();
 293   case vmIntrinsics::_unsignedMultiplyHigh:     return inline_math_unsignedMultiplyHigh();
 294   case vmIntrinsics::_negateExactI:             return inline_math_negateExactI();
 295   case vmIntrinsics::_negateExactL:             return inline_math_negateExactL();
 296   case vmIntrinsics::_subtractExactI:           return inline_math_subtractExactI(false /* subtract */);
 297   case vmIntrinsics::_subtractExactL:           return inline_math_subtractExactL(false /* subtract */);
 298 
 299   case vmIntrinsics::_arraycopy:                return inline_arraycopy();
 300 
 301   case vmIntrinsics::_arraySort:                return inline_array_sort();
 302   case vmIntrinsics::_arrayPartition:           return inline_array_partition();
 303 
 304   case vmIntrinsics::_compareToL:               return inline_string_compareTo(StrIntrinsicNode::LL);
 305   case vmIntrinsics::_compareToU:               return inline_string_compareTo(StrIntrinsicNode::UU);
 306   case vmIntrinsics::_compareToLU:              return inline_string_compareTo(StrIntrinsicNode::LU);
 307   case vmIntrinsics::_compareToUL:              return inline_string_compareTo(StrIntrinsicNode::UL);
 308 
 309   case vmIntrinsics::_indexOfL:                 return inline_string_indexOf(StrIntrinsicNode::LL);
 310   case vmIntrinsics::_indexOfU:                 return inline_string_indexOf(StrIntrinsicNode::UU);
 311   case vmIntrinsics::_indexOfUL:                return inline_string_indexOf(StrIntrinsicNode::UL);
 312   case vmIntrinsics::_indexOfIL:                return inline_string_indexOfI(StrIntrinsicNode::LL);
 313   case vmIntrinsics::_indexOfIU:                return inline_string_indexOfI(StrIntrinsicNode::UU);
 314   case vmIntrinsics::_indexOfIUL:               return inline_string_indexOfI(StrIntrinsicNode::UL);
 315   case vmIntrinsics::_indexOfU_char:            return inline_string_indexOfChar(StrIntrinsicNode::U);
 316   case vmIntrinsics::_indexOfL_char:            return inline_string_indexOfChar(StrIntrinsicNode::L);
 317 
 318   case vmIntrinsics::_equalsL:                  return inline_string_equals(StrIntrinsicNode::LL);
 319 
 320   case vmIntrinsics::_vectorizedHashCode:       return inline_vectorizedHashCode();
 321 
 322   case vmIntrinsics::_toBytesStringU:           return inline_string_toBytesU();
 323   case vmIntrinsics::_getCharsStringU:          return inline_string_getCharsU();
 324   case vmIntrinsics::_getCharStringU:           return inline_string_char_access(!is_store);
 325   case vmIntrinsics::_putCharStringU:           return inline_string_char_access( is_store);
 326 
 327   case vmIntrinsics::_compressStringC:
 328   case vmIntrinsics::_compressStringB:          return inline_string_copy( is_compress);
 329   case vmIntrinsics::_inflateStringC:
 330   case vmIntrinsics::_inflateStringB:           return inline_string_copy(!is_compress);
 331 
 332   case vmIntrinsics::_makePrivateBuffer:        return inline_unsafe_make_private_buffer();
 333   case vmIntrinsics::_finishPrivateBuffer:      return inline_unsafe_finish_private_buffer();
 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   case vmIntrinsics::_getValue:                 return inline_unsafe_access(!is_store, T_OBJECT,   Relaxed, false, true);
 344 
 345   case vmIntrinsics::_putReference:             return inline_unsafe_access( is_store, T_OBJECT,   Relaxed, false);
 346   case vmIntrinsics::_putBoolean:               return inline_unsafe_access( is_store, T_BOOLEAN,  Relaxed, false);
 347   case vmIntrinsics::_putByte:                  return inline_unsafe_access( is_store, T_BYTE,     Relaxed, false);
 348   case vmIntrinsics::_putShort:                 return inline_unsafe_access( is_store, T_SHORT,    Relaxed, false);
 349   case vmIntrinsics::_putChar:                  return inline_unsafe_access( is_store, T_CHAR,     Relaxed, false);
 350   case vmIntrinsics::_putInt:                   return inline_unsafe_access( is_store, T_INT,      Relaxed, false);
 351   case vmIntrinsics::_putLong:                  return inline_unsafe_access( is_store, T_LONG,     Relaxed, false);
 352   case vmIntrinsics::_putFloat:                 return inline_unsafe_access( is_store, T_FLOAT,    Relaxed, false);
 353   case vmIntrinsics::_putDouble:                return inline_unsafe_access( is_store, T_DOUBLE,   Relaxed, false);
 354   case vmIntrinsics::_putValue:                 return inline_unsafe_access( is_store, T_OBJECT,   Relaxed, false, true);
 355 
 356   case vmIntrinsics::_getReferenceVolatile:     return inline_unsafe_access(!is_store, T_OBJECT,   Volatile, false);
 357   case vmIntrinsics::_getBooleanVolatile:       return inline_unsafe_access(!is_store, T_BOOLEAN,  Volatile, false);
 358   case vmIntrinsics::_getByteVolatile:          return inline_unsafe_access(!is_store, T_BYTE,     Volatile, false);
 359   case vmIntrinsics::_getShortVolatile:         return inline_unsafe_access(!is_store, T_SHORT,    Volatile, false);
 360   case vmIntrinsics::_getCharVolatile:          return inline_unsafe_access(!is_store, T_CHAR,     Volatile, false);
 361   case vmIntrinsics::_getIntVolatile:           return inline_unsafe_access(!is_store, T_INT,      Volatile, false);
 362   case vmIntrinsics::_getLongVolatile:          return inline_unsafe_access(!is_store, T_LONG,     Volatile, false);
 363   case vmIntrinsics::_getFloatVolatile:         return inline_unsafe_access(!is_store, T_FLOAT,    Volatile, false);
 364   case vmIntrinsics::_getDoubleVolatile:        return inline_unsafe_access(!is_store, T_DOUBLE,   Volatile, false);
 365 
 366   case vmIntrinsics::_putReferenceVolatile:     return inline_unsafe_access( is_store, T_OBJECT,   Volatile, false);
 367   case vmIntrinsics::_putBooleanVolatile:       return inline_unsafe_access( is_store, T_BOOLEAN,  Volatile, false);
 368   case vmIntrinsics::_putByteVolatile:          return inline_unsafe_access( is_store, T_BYTE,     Volatile, false);
 369   case vmIntrinsics::_putShortVolatile:         return inline_unsafe_access( is_store, T_SHORT,    Volatile, false);
 370   case vmIntrinsics::_putCharVolatile:          return inline_unsafe_access( is_store, T_CHAR,     Volatile, false);
 371   case vmIntrinsics::_putIntVolatile:           return inline_unsafe_access( is_store, T_INT,      Volatile, false);
 372   case vmIntrinsics::_putLongVolatile:          return inline_unsafe_access( is_store, T_LONG,     Volatile, false);
 373   case vmIntrinsics::_putFloatVolatile:         return inline_unsafe_access( is_store, T_FLOAT,    Volatile, false);
 374   case vmIntrinsics::_putDoubleVolatile:        return inline_unsafe_access( is_store, T_DOUBLE,   Volatile, false);
 375 
 376   case vmIntrinsics::_getShortUnaligned:        return inline_unsafe_access(!is_store, T_SHORT,    Relaxed, true);
 377   case vmIntrinsics::_getCharUnaligned:         return inline_unsafe_access(!is_store, T_CHAR,     Relaxed, true);
 378   case vmIntrinsics::_getIntUnaligned:          return inline_unsafe_access(!is_store, T_INT,      Relaxed, true);
 379   case vmIntrinsics::_getLongUnaligned:         return inline_unsafe_access(!is_store, T_LONG,     Relaxed, true);
 380 
 381   case vmIntrinsics::_putShortUnaligned:        return inline_unsafe_access( is_store, T_SHORT,    Relaxed, true);
 382   case vmIntrinsics::_putCharUnaligned:         return inline_unsafe_access( is_store, T_CHAR,     Relaxed, true);
 383   case vmIntrinsics::_putIntUnaligned:          return inline_unsafe_access( is_store, T_INT,      Relaxed, true);
 384   case vmIntrinsics::_putLongUnaligned:         return inline_unsafe_access( is_store, T_LONG,     Relaxed, true);
 385 
 386   case vmIntrinsics::_getReferenceAcquire:      return inline_unsafe_access(!is_store, T_OBJECT,   Acquire, false);
 387   case vmIntrinsics::_getBooleanAcquire:        return inline_unsafe_access(!is_store, T_BOOLEAN,  Acquire, false);
 388   case vmIntrinsics::_getByteAcquire:           return inline_unsafe_access(!is_store, T_BYTE,     Acquire, false);
 389   case vmIntrinsics::_getShortAcquire:          return inline_unsafe_access(!is_store, T_SHORT,    Acquire, false);
 390   case vmIntrinsics::_getCharAcquire:           return inline_unsafe_access(!is_store, T_CHAR,     Acquire, false);
 391   case vmIntrinsics::_getIntAcquire:            return inline_unsafe_access(!is_store, T_INT,      Acquire, false);
 392   case vmIntrinsics::_getLongAcquire:           return inline_unsafe_access(!is_store, T_LONG,     Acquire, false);
 393   case vmIntrinsics::_getFloatAcquire:          return inline_unsafe_access(!is_store, T_FLOAT,    Acquire, false);
 394   case vmIntrinsics::_getDoubleAcquire:         return inline_unsafe_access(!is_store, T_DOUBLE,   Acquire, false);
 395 
 396   case vmIntrinsics::_putReferenceRelease:      return inline_unsafe_access( is_store, T_OBJECT,   Release, false);
 397   case vmIntrinsics::_putBooleanRelease:        return inline_unsafe_access( is_store, T_BOOLEAN,  Release, false);
 398   case vmIntrinsics::_putByteRelease:           return inline_unsafe_access( is_store, T_BYTE,     Release, false);
 399   case vmIntrinsics::_putShortRelease:          return inline_unsafe_access( is_store, T_SHORT,    Release, false);
 400   case vmIntrinsics::_putCharRelease:           return inline_unsafe_access( is_store, T_CHAR,     Release, false);
 401   case vmIntrinsics::_putIntRelease:            return inline_unsafe_access( is_store, T_INT,      Release, false);
 402   case vmIntrinsics::_putLongRelease:           return inline_unsafe_access( is_store, T_LONG,     Release, false);
 403   case vmIntrinsics::_putFloatRelease:          return inline_unsafe_access( is_store, T_FLOAT,    Release, false);
 404   case vmIntrinsics::_putDoubleRelease:         return inline_unsafe_access( is_store, T_DOUBLE,   Release, false);
 405 
 406   case vmIntrinsics::_getReferenceOpaque:       return inline_unsafe_access(!is_store, T_OBJECT,   Opaque, false);
 407   case vmIntrinsics::_getBooleanOpaque:         return inline_unsafe_access(!is_store, T_BOOLEAN,  Opaque, false);
 408   case vmIntrinsics::_getByteOpaque:            return inline_unsafe_access(!is_store, T_BYTE,     Opaque, false);
 409   case vmIntrinsics::_getShortOpaque:           return inline_unsafe_access(!is_store, T_SHORT,    Opaque, false);
 410   case vmIntrinsics::_getCharOpaque:            return inline_unsafe_access(!is_store, T_CHAR,     Opaque, false);
 411   case vmIntrinsics::_getIntOpaque:             return inline_unsafe_access(!is_store, T_INT,      Opaque, false);
 412   case vmIntrinsics::_getLongOpaque:            return inline_unsafe_access(!is_store, T_LONG,     Opaque, false);
 413   case vmIntrinsics::_getFloatOpaque:           return inline_unsafe_access(!is_store, T_FLOAT,    Opaque, false);
 414   case vmIntrinsics::_getDoubleOpaque:          return inline_unsafe_access(!is_store, T_DOUBLE,   Opaque, false);
 415 
 416   case vmIntrinsics::_putReferenceOpaque:       return inline_unsafe_access( is_store, T_OBJECT,   Opaque, false);
 417   case vmIntrinsics::_putBooleanOpaque:         return inline_unsafe_access( is_store, T_BOOLEAN,  Opaque, false);
 418   case vmIntrinsics::_putByteOpaque:            return inline_unsafe_access( is_store, T_BYTE,     Opaque, false);
 419   case vmIntrinsics::_putShortOpaque:           return inline_unsafe_access( is_store, T_SHORT,    Opaque, false);
 420   case vmIntrinsics::_putCharOpaque:            return inline_unsafe_access( is_store, T_CHAR,     Opaque, false);
 421   case vmIntrinsics::_putIntOpaque:             return inline_unsafe_access( is_store, T_INT,      Opaque, false);
 422   case vmIntrinsics::_putLongOpaque:            return inline_unsafe_access( is_store, T_LONG,     Opaque, false);
 423   case vmIntrinsics::_putFloatOpaque:           return inline_unsafe_access( is_store, T_FLOAT,    Opaque, false);
 424   case vmIntrinsics::_putDoubleOpaque:          return inline_unsafe_access( is_store, T_DOUBLE,   Opaque, false);
 425 
 426   case vmIntrinsics::_getFlatValue:             return inline_unsafe_flat_access(!is_store, Relaxed);
 427   case vmIntrinsics::_putFlatValue:             return inline_unsafe_flat_access( is_store, Relaxed);
 428 
 429   case vmIntrinsics::_compareAndSetReference:   return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap,      Volatile);
 430   case vmIntrinsics::_compareAndSetByte:        return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap,      Volatile);
 431   case vmIntrinsics::_compareAndSetShort:       return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap,      Volatile);
 432   case vmIntrinsics::_compareAndSetInt:         return inline_unsafe_load_store(T_INT,    LS_cmp_swap,      Volatile);
 433   case vmIntrinsics::_compareAndSetLong:        return inline_unsafe_load_store(T_LONG,   LS_cmp_swap,      Volatile);
 434 
 435   case vmIntrinsics::_weakCompareAndSetReferencePlain:     return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Relaxed);
 436   case vmIntrinsics::_weakCompareAndSetReferenceAcquire:   return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Acquire);
 437   case vmIntrinsics::_weakCompareAndSetReferenceRelease:   return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Release);
 438   case vmIntrinsics::_weakCompareAndSetReference:          return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Volatile);
 439   case vmIntrinsics::_weakCompareAndSetBytePlain:          return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap_weak, Relaxed);
 440   case vmIntrinsics::_weakCompareAndSetByteAcquire:        return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap_weak, Acquire);
 441   case vmIntrinsics::_weakCompareAndSetByteRelease:        return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap_weak, Release);
 442   case vmIntrinsics::_weakCompareAndSetByte:               return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap_weak, Volatile);
 443   case vmIntrinsics::_weakCompareAndSetShortPlain:         return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap_weak, Relaxed);
 444   case vmIntrinsics::_weakCompareAndSetShortAcquire:       return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap_weak, Acquire);
 445   case vmIntrinsics::_weakCompareAndSetShortRelease:       return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap_weak, Release);
 446   case vmIntrinsics::_weakCompareAndSetShort:              return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap_weak, Volatile);
 447   case vmIntrinsics::_weakCompareAndSetIntPlain:           return inline_unsafe_load_store(T_INT,    LS_cmp_swap_weak, Relaxed);
 448   case vmIntrinsics::_weakCompareAndSetIntAcquire:         return inline_unsafe_load_store(T_INT,    LS_cmp_swap_weak, Acquire);
 449   case vmIntrinsics::_weakCompareAndSetIntRelease:         return inline_unsafe_load_store(T_INT,    LS_cmp_swap_weak, Release);
 450   case vmIntrinsics::_weakCompareAndSetInt:                return inline_unsafe_load_store(T_INT,    LS_cmp_swap_weak, Volatile);
 451   case vmIntrinsics::_weakCompareAndSetLongPlain:          return inline_unsafe_load_store(T_LONG,   LS_cmp_swap_weak, Relaxed);
 452   case vmIntrinsics::_weakCompareAndSetLongAcquire:        return inline_unsafe_load_store(T_LONG,   LS_cmp_swap_weak, Acquire);
 453   case vmIntrinsics::_weakCompareAndSetLongRelease:        return inline_unsafe_load_store(T_LONG,   LS_cmp_swap_weak, Release);
 454   case vmIntrinsics::_weakCompareAndSetLong:               return inline_unsafe_load_store(T_LONG,   LS_cmp_swap_weak, Volatile);
 455 
 456   case vmIntrinsics::_compareAndExchangeReference:         return inline_unsafe_load_store(T_OBJECT, LS_cmp_exchange,  Volatile);
 457   case vmIntrinsics::_compareAndExchangeReferenceAcquire:  return inline_unsafe_load_store(T_OBJECT, LS_cmp_exchange,  Acquire);
 458   case vmIntrinsics::_compareAndExchangeReferenceRelease:  return inline_unsafe_load_store(T_OBJECT, LS_cmp_exchange,  Release);
 459   case vmIntrinsics::_compareAndExchangeByte:              return inline_unsafe_load_store(T_BYTE,   LS_cmp_exchange,  Volatile);
 460   case vmIntrinsics::_compareAndExchangeByteAcquire:       return inline_unsafe_load_store(T_BYTE,   LS_cmp_exchange,  Acquire);
 461   case vmIntrinsics::_compareAndExchangeByteRelease:       return inline_unsafe_load_store(T_BYTE,   LS_cmp_exchange,  Release);
 462   case vmIntrinsics::_compareAndExchangeShort:             return inline_unsafe_load_store(T_SHORT,  LS_cmp_exchange,  Volatile);
 463   case vmIntrinsics::_compareAndExchangeShortAcquire:      return inline_unsafe_load_store(T_SHORT,  LS_cmp_exchange,  Acquire);
 464   case vmIntrinsics::_compareAndExchangeShortRelease:      return inline_unsafe_load_store(T_SHORT,  LS_cmp_exchange,  Release);
 465   case vmIntrinsics::_compareAndExchangeInt:               return inline_unsafe_load_store(T_INT,    LS_cmp_exchange,  Volatile);
 466   case vmIntrinsics::_compareAndExchangeIntAcquire:        return inline_unsafe_load_store(T_INT,    LS_cmp_exchange,  Acquire);
 467   case vmIntrinsics::_compareAndExchangeIntRelease:        return inline_unsafe_load_store(T_INT,    LS_cmp_exchange,  Release);
 468   case vmIntrinsics::_compareAndExchangeLong:              return inline_unsafe_load_store(T_LONG,   LS_cmp_exchange,  Volatile);
 469   case vmIntrinsics::_compareAndExchangeLongAcquire:       return inline_unsafe_load_store(T_LONG,   LS_cmp_exchange,  Acquire);
 470   case vmIntrinsics::_compareAndExchangeLongRelease:       return inline_unsafe_load_store(T_LONG,   LS_cmp_exchange,  Release);
 471 
 472   case vmIntrinsics::_getAndAddByte:                    return inline_unsafe_load_store(T_BYTE,   LS_get_add,       Volatile);
 473   case vmIntrinsics::_getAndAddShort:                   return inline_unsafe_load_store(T_SHORT,  LS_get_add,       Volatile);
 474   case vmIntrinsics::_getAndAddInt:                     return inline_unsafe_load_store(T_INT,    LS_get_add,       Volatile);
 475   case vmIntrinsics::_getAndAddLong:                    return inline_unsafe_load_store(T_LONG,   LS_get_add,       Volatile);
 476 
 477   case vmIntrinsics::_getAndSetByte:                    return inline_unsafe_load_store(T_BYTE,   LS_get_set,       Volatile);
 478   case vmIntrinsics::_getAndSetShort:                   return inline_unsafe_load_store(T_SHORT,  LS_get_set,       Volatile);
 479   case vmIntrinsics::_getAndSetInt:                     return inline_unsafe_load_store(T_INT,    LS_get_set,       Volatile);
 480   case vmIntrinsics::_getAndSetLong:                    return inline_unsafe_load_store(T_LONG,   LS_get_set,       Volatile);
 481   case vmIntrinsics::_getAndSetReference:               return inline_unsafe_load_store(T_OBJECT, LS_get_set,       Volatile);
 482 
 483   case vmIntrinsics::_loadFence:
 484   case vmIntrinsics::_storeFence:
 485   case vmIntrinsics::_storeStoreFence:
 486   case vmIntrinsics::_fullFence:                return inline_unsafe_fence(intrinsic_id());
 487 
 488   case vmIntrinsics::_arrayInstanceBaseOffset:  return inline_arrayInstanceBaseOffset();
 489   case vmIntrinsics::_arrayInstanceIndexScale:  return inline_arrayInstanceIndexScale();
 490   case vmIntrinsics::_arrayLayout:              return inline_arrayLayout();
 491 
 492   case vmIntrinsics::_onSpinWait:               return inline_onspinwait();
 493 
 494   case vmIntrinsics::_currentCarrierThread:     return inline_native_currentCarrierThread();
 495   case vmIntrinsics::_currentThread:            return inline_native_currentThread();
 496   case vmIntrinsics::_setCurrentThread:         return inline_native_setCurrentThread();
 497 
 498   case vmIntrinsics::_scopedValueCache:          return inline_native_scopedValueCache();
 499   case vmIntrinsics::_setScopedValueCache:       return inline_native_setScopedValueCache();
 500 
 501   case vmIntrinsics::_Continuation_pin:          return inline_native_Continuation_pinning(false);
 502   case vmIntrinsics::_Continuation_unpin:        return inline_native_Continuation_pinning(true);
 503 
 504 #if INCLUDE_JVMTI
 505   case vmIntrinsics::_notifyJvmtiVThreadStart:   return inline_native_notify_jvmti_funcs(CAST_FROM_FN_PTR(address, OptoRuntime::notify_jvmti_vthread_start()),
 506                                                                                          "notifyJvmtiStart", true, false);
 507   case vmIntrinsics::_notifyJvmtiVThreadEnd:     return inline_native_notify_jvmti_funcs(CAST_FROM_FN_PTR(address, OptoRuntime::notify_jvmti_vthread_end()),
 508                                                                                          "notifyJvmtiEnd", false, true);
 509   case vmIntrinsics::_notifyJvmtiVThreadMount:   return inline_native_notify_jvmti_funcs(CAST_FROM_FN_PTR(address, OptoRuntime::notify_jvmti_vthread_mount()),
 510                                                                                          "notifyJvmtiMount", false, false);
 511   case vmIntrinsics::_notifyJvmtiVThreadUnmount: return inline_native_notify_jvmti_funcs(CAST_FROM_FN_PTR(address, OptoRuntime::notify_jvmti_vthread_unmount()),
 512                                                                                          "notifyJvmtiUnmount", false, false);
 513   case vmIntrinsics::_notifyJvmtiVThreadDisableSuspend: return inline_native_notify_jvmti_sync();
 514 #endif
 515 
 516 #ifdef JFR_HAVE_INTRINSICS
 517   case vmIntrinsics::_counterTime:              return inline_native_time_funcs(CAST_FROM_FN_PTR(address, JfrTime::time_function()), "counterTime");
 518   case vmIntrinsics::_getEventWriter:           return inline_native_getEventWriter();
 519   case vmIntrinsics::_jvm_commit:               return inline_native_jvm_commit();
 520 #endif
 521   case vmIntrinsics::_currentTimeMillis:        return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeMillis), "currentTimeMillis");
 522   case vmIntrinsics::_nanoTime:                 return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeNanos), "nanoTime");
 523   case vmIntrinsics::_writeback0:               return inline_unsafe_writeback0();
 524   case vmIntrinsics::_writebackPreSync0:        return inline_unsafe_writebackSync0(true);
 525   case vmIntrinsics::_writebackPostSync0:       return inline_unsafe_writebackSync0(false);
 526   case vmIntrinsics::_allocateInstance:         return inline_unsafe_allocate();
 527   case vmIntrinsics::_copyMemory:               return inline_unsafe_copyMemory();
 528   case vmIntrinsics::_setMemory:                return inline_unsafe_setMemory();
 529   case vmIntrinsics::_getLength:                return inline_native_getLength();
 530   case vmIntrinsics::_copyOf:                   return inline_array_copyOf(false);
 531   case vmIntrinsics::_copyOfRange:              return inline_array_copyOf(true);
 532   case vmIntrinsics::_equalsB:                  return inline_array_equals(StrIntrinsicNode::LL);
 533   case vmIntrinsics::_equalsC:                  return inline_array_equals(StrIntrinsicNode::UU);
 534   case vmIntrinsics::_Preconditions_checkIndex: return inline_preconditions_checkIndex(T_INT);
 535   case vmIntrinsics::_Preconditions_checkLongIndex: return inline_preconditions_checkIndex(T_LONG);
 536   case vmIntrinsics::_clone:                    return inline_native_clone(intrinsic()->is_virtual());
 537 
 538   case vmIntrinsics::_allocateUninitializedArray: return inline_unsafe_newArray(true);
 539   case vmIntrinsics::_newArray:                   return inline_unsafe_newArray(false);
 540   case vmIntrinsics::_newNullRestrictedNonAtomicArray: return inline_newArray(/* null_free */ true, /* atomic */ false);
 541   case vmIntrinsics::_newNullRestrictedAtomicArray: return inline_newArray(/* null_free */ true, /* atomic */ true);
 542   case vmIntrinsics::_newNullableAtomicArray:     return inline_newArray(/* null_free */ false, /* atomic */ true);
 543   case vmIntrinsics::_isFlatArray:              return inline_getArrayProperties(IsFlat);
 544   case vmIntrinsics::_isNullRestrictedArray:    return inline_getArrayProperties(IsNullRestricted);
 545   case vmIntrinsics::_isAtomicArray:            return inline_getArrayProperties(IsAtomic);
 546 
 547   case vmIntrinsics::_isAssignableFrom:         return inline_native_subtype_check();
 548 
 549   case vmIntrinsics::_isInstance:
 550   case vmIntrinsics::_isHidden:
 551   case vmIntrinsics::_getSuperclass:            return inline_native_Class_query(intrinsic_id());
 552 
 553   case vmIntrinsics::_floatToRawIntBits:
 554   case vmIntrinsics::_floatToIntBits:
 555   case vmIntrinsics::_intBitsToFloat:
 556   case vmIntrinsics::_doubleToRawLongBits:
 557   case vmIntrinsics::_doubleToLongBits:
 558   case vmIntrinsics::_longBitsToDouble:
 559   case vmIntrinsics::_floatToFloat16:
 560   case vmIntrinsics::_float16ToFloat:           return inline_fp_conversions(intrinsic_id());
 561   case vmIntrinsics::_sqrt_float16:             return inline_fp16_operations(intrinsic_id(), 1);
 562   case vmIntrinsics::_fma_float16:              return inline_fp16_operations(intrinsic_id(), 3);
 563   case vmIntrinsics::_floatIsFinite:
 564   case vmIntrinsics::_floatIsInfinite:
 565   case vmIntrinsics::_doubleIsFinite:
 566   case vmIntrinsics::_doubleIsInfinite:         return inline_fp_range_check(intrinsic_id());
 567 
 568   case vmIntrinsics::_numberOfLeadingZeros_i:
 569   case vmIntrinsics::_numberOfLeadingZeros_l:
 570   case vmIntrinsics::_numberOfTrailingZeros_i:
 571   case vmIntrinsics::_numberOfTrailingZeros_l:
 572   case vmIntrinsics::_bitCount_i:
 573   case vmIntrinsics::_bitCount_l:
 574   case vmIntrinsics::_reverse_i:
 575   case vmIntrinsics::_reverse_l:
 576   case vmIntrinsics::_reverseBytes_i:
 577   case vmIntrinsics::_reverseBytes_l:
 578   case vmIntrinsics::_reverseBytes_s:
 579   case vmIntrinsics::_reverseBytes_c:           return inline_number_methods(intrinsic_id());
 580 
 581   case vmIntrinsics::_compress_i:
 582   case vmIntrinsics::_compress_l:
 583   case vmIntrinsics::_expand_i:
 584   case vmIntrinsics::_expand_l:                 return inline_bitshuffle_methods(intrinsic_id());
 585 
 586   case vmIntrinsics::_compareUnsigned_i:
 587   case vmIntrinsics::_compareUnsigned_l:        return inline_compare_unsigned(intrinsic_id());
 588 
 589   case vmIntrinsics::_divideUnsigned_i:
 590   case vmIntrinsics::_divideUnsigned_l:
 591   case vmIntrinsics::_remainderUnsigned_i:
 592   case vmIntrinsics::_remainderUnsigned_l:      return inline_divmod_methods(intrinsic_id());
 593 
 594   case vmIntrinsics::_getCallerClass:           return inline_native_Reflection_getCallerClass();
 595 
 596   case vmIntrinsics::_Reference_get0:           return inline_reference_get0();
 597   case vmIntrinsics::_Reference_refersTo0:      return inline_reference_refersTo0(false);
 598   case vmIntrinsics::_PhantomReference_refersTo0: return inline_reference_refersTo0(true);
 599   case vmIntrinsics::_Reference_clear0:         return inline_reference_clear0(false);
 600   case vmIntrinsics::_PhantomReference_clear0:  return inline_reference_clear0(true);
 601 
 602   case vmIntrinsics::_Class_cast:               return inline_Class_cast();
 603 
 604   case vmIntrinsics::_aescrypt_encryptBlock:
 605   case vmIntrinsics::_aescrypt_decryptBlock:    return inline_aescrypt_Block(intrinsic_id());
 606 
 607   case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
 608   case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
 609     return inline_cipherBlockChaining_AESCrypt(intrinsic_id());
 610 
 611   case vmIntrinsics::_electronicCodeBook_encryptAESCrypt:
 612   case vmIntrinsics::_electronicCodeBook_decryptAESCrypt:
 613     return inline_electronicCodeBook_AESCrypt(intrinsic_id());
 614 
 615   case vmIntrinsics::_counterMode_AESCrypt:
 616     return inline_counterMode_AESCrypt(intrinsic_id());
 617 
 618   case vmIntrinsics::_galoisCounterMode_AESCrypt:
 619     return inline_galoisCounterMode_AESCrypt();
 620 
 621   case vmIntrinsics::_md5_implCompress:
 622   case vmIntrinsics::_sha_implCompress:
 623   case vmIntrinsics::_sha2_implCompress:
 624   case vmIntrinsics::_sha5_implCompress:
 625   case vmIntrinsics::_sha3_implCompress:
 626     return inline_digestBase_implCompress(intrinsic_id());
 627   case vmIntrinsics::_double_keccak:
 628     return inline_double_keccak();
 629 
 630   case vmIntrinsics::_digestBase_implCompressMB:
 631     return inline_digestBase_implCompressMB(predicate);
 632 
 633   case vmIntrinsics::_multiplyToLen:
 634     return inline_multiplyToLen();
 635 
 636   case vmIntrinsics::_squareToLen:
 637     return inline_squareToLen();
 638 
 639   case vmIntrinsics::_mulAdd:
 640     return inline_mulAdd();
 641 
 642   case vmIntrinsics::_montgomeryMultiply:
 643     return inline_montgomeryMultiply();
 644   case vmIntrinsics::_montgomerySquare:
 645     return inline_montgomerySquare();
 646 
 647   case vmIntrinsics::_bigIntegerRightShiftWorker:
 648     return inline_bigIntegerShift(true);
 649   case vmIntrinsics::_bigIntegerLeftShiftWorker:
 650     return inline_bigIntegerShift(false);
 651 
 652   case vmIntrinsics::_vectorizedMismatch:
 653     return inline_vectorizedMismatch();
 654 
 655   case vmIntrinsics::_ghash_processBlocks:
 656     return inline_ghash_processBlocks();
 657   case vmIntrinsics::_chacha20Block:
 658     return inline_chacha20Block();
 659   case vmIntrinsics::_kyberNtt:
 660     return inline_kyberNtt();
 661   case vmIntrinsics::_kyberInverseNtt:
 662     return inline_kyberInverseNtt();
 663   case vmIntrinsics::_kyberNttMult:
 664     return inline_kyberNttMult();
 665   case vmIntrinsics::_kyberAddPoly_2:
 666     return inline_kyberAddPoly_2();
 667   case vmIntrinsics::_kyberAddPoly_3:
 668     return inline_kyberAddPoly_3();
 669   case vmIntrinsics::_kyber12To16:
 670     return inline_kyber12To16();
 671   case vmIntrinsics::_kyberBarrettReduce:
 672     return inline_kyberBarrettReduce();
 673   case vmIntrinsics::_dilithiumAlmostNtt:
 674     return inline_dilithiumAlmostNtt();
 675   case vmIntrinsics::_dilithiumAlmostInverseNtt:
 676     return inline_dilithiumAlmostInverseNtt();
 677   case vmIntrinsics::_dilithiumNttMult:
 678     return inline_dilithiumNttMult();
 679   case vmIntrinsics::_dilithiumMontMulByConstant:
 680     return inline_dilithiumMontMulByConstant();
 681   case vmIntrinsics::_dilithiumDecomposePoly:
 682     return inline_dilithiumDecomposePoly();
 683   case vmIntrinsics::_base64_encodeBlock:
 684     return inline_base64_encodeBlock();
 685   case vmIntrinsics::_base64_decodeBlock:
 686     return inline_base64_decodeBlock();
 687   case vmIntrinsics::_poly1305_processBlocks:
 688     return inline_poly1305_processBlocks();
 689   case vmIntrinsics::_intpoly_montgomeryMult_P256:
 690     return inline_intpoly_montgomeryMult_P256();
 691   case vmIntrinsics::_intpoly_assign:
 692     return inline_intpoly_assign();
 693   case vmIntrinsics::_encodeISOArray:
 694   case vmIntrinsics::_encodeByteISOArray:
 695     return inline_encodeISOArray(false);
 696   case vmIntrinsics::_encodeAsciiArray:
 697     return inline_encodeISOArray(true);
 698 
 699   case vmIntrinsics::_updateCRC32:
 700     return inline_updateCRC32();
 701   case vmIntrinsics::_updateBytesCRC32:
 702     return inline_updateBytesCRC32();
 703   case vmIntrinsics::_updateByteBufferCRC32:
 704     return inline_updateByteBufferCRC32();
 705 
 706   case vmIntrinsics::_updateBytesCRC32C:
 707     return inline_updateBytesCRC32C();
 708   case vmIntrinsics::_updateDirectByteBufferCRC32C:
 709     return inline_updateDirectByteBufferCRC32C();
 710 
 711   case vmIntrinsics::_updateBytesAdler32:
 712     return inline_updateBytesAdler32();
 713   case vmIntrinsics::_updateByteBufferAdler32:
 714     return inline_updateByteBufferAdler32();
 715 
 716   case vmIntrinsics::_profileBoolean:
 717     return inline_profileBoolean();
 718   case vmIntrinsics::_isCompileConstant:
 719     return inline_isCompileConstant();
 720 
 721   case vmIntrinsics::_countPositives:
 722     return inline_countPositives();
 723 
 724   case vmIntrinsics::_fmaD:
 725   case vmIntrinsics::_fmaF:
 726     return inline_fma(intrinsic_id());
 727 
 728   case vmIntrinsics::_isDigit:
 729   case vmIntrinsics::_isLowerCase:
 730   case vmIntrinsics::_isUpperCase:
 731   case vmIntrinsics::_isWhitespace:
 732     return inline_character_compare(intrinsic_id());
 733 
 734   case vmIntrinsics::_min:
 735   case vmIntrinsics::_max:
 736   case vmIntrinsics::_min_strict:
 737   case vmIntrinsics::_max_strict:
 738   case vmIntrinsics::_minL:
 739   case vmIntrinsics::_maxL:
 740   case vmIntrinsics::_minF:
 741   case vmIntrinsics::_maxF:
 742   case vmIntrinsics::_minD:
 743   case vmIntrinsics::_maxD:
 744   case vmIntrinsics::_minF_strict:
 745   case vmIntrinsics::_maxF_strict:
 746   case vmIntrinsics::_minD_strict:
 747   case vmIntrinsics::_maxD_strict:
 748     return inline_min_max(intrinsic_id());
 749 
 750   case vmIntrinsics::_VectorUnaryOp:
 751     return inline_vector_nary_operation(1);
 752   case vmIntrinsics::_VectorBinaryOp:
 753     return inline_vector_nary_operation(2);
 754   case vmIntrinsics::_VectorUnaryLibOp:
 755     return inline_vector_call(1);
 756   case vmIntrinsics::_VectorBinaryLibOp:
 757     return inline_vector_call(2);
 758   case vmIntrinsics::_VectorTernaryOp:
 759     return inline_vector_nary_operation(3);
 760   case vmIntrinsics::_VectorFromBitsCoerced:
 761     return inline_vector_frombits_coerced();
 762   case vmIntrinsics::_VectorMaskOp:
 763     return inline_vector_mask_operation();
 764   case vmIntrinsics::_VectorLoadOp:
 765     return inline_vector_mem_operation(/*is_store=*/false);
 766   case vmIntrinsics::_VectorLoadMaskedOp:
 767     return inline_vector_mem_masked_operation(/*is_store*/false);
 768   case vmIntrinsics::_VectorStoreOp:
 769     return inline_vector_mem_operation(/*is_store=*/true);
 770   case vmIntrinsics::_VectorStoreMaskedOp:
 771     return inline_vector_mem_masked_operation(/*is_store=*/true);
 772   case vmIntrinsics::_VectorGatherOp:
 773     return inline_vector_gather_scatter(/*is_scatter*/ false);
 774   case vmIntrinsics::_VectorScatterOp:
 775     return inline_vector_gather_scatter(/*is_scatter*/ true);
 776   case vmIntrinsics::_VectorReductionCoerced:
 777     return inline_vector_reduction();
 778   case vmIntrinsics::_VectorTest:
 779     return inline_vector_test();
 780   case vmIntrinsics::_VectorBlend:
 781     return inline_vector_blend();
 782   case vmIntrinsics::_VectorRearrange:
 783     return inline_vector_rearrange();
 784   case vmIntrinsics::_VectorSelectFrom:
 785     return inline_vector_select_from();
 786   case vmIntrinsics::_VectorCompare:
 787     return inline_vector_compare();
 788   case vmIntrinsics::_VectorBroadcastInt:
 789     return inline_vector_broadcast_int();
 790   case vmIntrinsics::_VectorConvert:
 791     return inline_vector_convert();
 792   case vmIntrinsics::_VectorInsert:
 793     return inline_vector_insert();
 794   case vmIntrinsics::_VectorExtract:
 795     return inline_vector_extract();
 796   case vmIntrinsics::_VectorCompressExpand:
 797     return inline_vector_compress_expand();
 798   case vmIntrinsics::_VectorSelectFromTwoVectorOp:
 799     return inline_vector_select_from_two_vectors();
 800   case vmIntrinsics::_IndexVector:
 801     return inline_index_vector();
 802   case vmIntrinsics::_IndexPartiallyInUpperRange:
 803     return inline_index_partially_in_upper_range();
 804 
 805   case vmIntrinsics::_getObjectSize:
 806     return inline_getObjectSize();
 807 
 808   case vmIntrinsics::_blackhole:
 809     return inline_blackhole();
 810 
 811   default:
 812     // If you get here, it may be that someone has added a new intrinsic
 813     // to the list in vmIntrinsics.hpp without implementing it here.
 814 #ifndef PRODUCT
 815     if ((PrintMiscellaneous && (Verbose || WizardMode)) || PrintOpto) {
 816       tty->print_cr("*** Warning: Unimplemented intrinsic %s(%d)",
 817                     vmIntrinsics::name_at(intrinsic_id()), vmIntrinsics::as_int(intrinsic_id()));
 818     }
 819 #endif
 820     return false;
 821   }
 822 }
 823 
 824 Node* LibraryCallKit::try_to_predicate(int predicate) {
 825   if (!jvms()->has_method()) {
 826     // Root JVMState has a null method.
 827     assert(map()->memory()->Opcode() == Op_Parm, "");
 828     // Insert the memory aliasing node
 829     set_all_memory(reset_memory());
 830   }
 831   assert(merged_memory(), "");
 832 
 833   switch (intrinsic_id()) {
 834   case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
 835     return inline_cipherBlockChaining_AESCrypt_predicate(false);
 836   case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
 837     return inline_cipherBlockChaining_AESCrypt_predicate(true);
 838   case vmIntrinsics::_electronicCodeBook_encryptAESCrypt:
 839     return inline_electronicCodeBook_AESCrypt_predicate(false);
 840   case vmIntrinsics::_electronicCodeBook_decryptAESCrypt:
 841     return inline_electronicCodeBook_AESCrypt_predicate(true);
 842   case vmIntrinsics::_counterMode_AESCrypt:
 843     return inline_counterMode_AESCrypt_predicate();
 844   case vmIntrinsics::_digestBase_implCompressMB:
 845     return inline_digestBase_implCompressMB_predicate(predicate);
 846   case vmIntrinsics::_galoisCounterMode_AESCrypt:
 847     return inline_galoisCounterMode_AESCrypt_predicate();
 848 
 849   default:
 850     // If you get here, it may be that someone has added a new intrinsic
 851     // to the list in vmIntrinsics.hpp without implementing it here.
 852 #ifndef PRODUCT
 853     if ((PrintMiscellaneous && (Verbose || WizardMode)) || PrintOpto) {
 854       tty->print_cr("*** Warning: Unimplemented predicate for intrinsic %s(%d)",
 855                     vmIntrinsics::name_at(intrinsic_id()), vmIntrinsics::as_int(intrinsic_id()));
 856     }
 857 #endif
 858     Node* slow_ctl = control();
 859     set_control(top()); // No fast path intrinsic
 860     return slow_ctl;
 861   }
 862 }
 863 
 864 //------------------------------set_result-------------------------------
 865 // Helper function for finishing intrinsics.
 866 void LibraryCallKit::set_result(RegionNode* region, PhiNode* value) {
 867   record_for_igvn(region);
 868   set_control(_gvn.transform(region));
 869   set_result( _gvn.transform(value));
 870   assert(value->type()->basic_type() == result()->bottom_type()->basic_type(), "sanity");
 871 }
 872 
 873 //------------------------------generate_guard---------------------------
 874 // Helper function for generating guarded fast-slow graph structures.
 875 // The given 'test', if true, guards a slow path.  If the test fails
 876 // then a fast path can be taken.  (We generally hope it fails.)
 877 // In all cases, GraphKit::control() is updated to the fast path.
 878 // The returned value represents the control for the slow path.
 879 // The return value is never 'top'; it is either a valid control
 880 // or null if it is obvious that the slow path can never be taken.
 881 // Also, if region and the slow control are not null, the slow edge
 882 // is appended to the region.
 883 Node* LibraryCallKit::generate_guard(Node* test, RegionNode* region, float true_prob) {
 884   if (stopped()) {
 885     // Already short circuited.
 886     return nullptr;
 887   }
 888 
 889   // Build an if node and its projections.
 890   // If test is true we take the slow path, which we assume is uncommon.
 891   if (_gvn.type(test) == TypeInt::ZERO) {
 892     // The slow branch is never taken.  No need to build this guard.
 893     return nullptr;
 894   }
 895 
 896   IfNode* iff = create_and_map_if(control(), test, true_prob, COUNT_UNKNOWN);
 897 
 898   Node* if_slow = _gvn.transform(new IfTrueNode(iff));
 899   if (if_slow == top()) {
 900     // The slow branch is never taken.  No need to build this guard.
 901     return nullptr;
 902   }
 903 
 904   if (region != nullptr)
 905     region->add_req(if_slow);
 906 
 907   Node* if_fast = _gvn.transform(new IfFalseNode(iff));
 908   set_control(if_fast);
 909 
 910   return if_slow;
 911 }
 912 
 913 inline Node* LibraryCallKit::generate_slow_guard(Node* test, RegionNode* region) {
 914   return generate_guard(test, region, PROB_UNLIKELY_MAG(3));
 915 }
 916 inline Node* LibraryCallKit::generate_fair_guard(Node* test, RegionNode* region) {
 917   return generate_guard(test, region, PROB_FAIR);
 918 }
 919 
 920 inline Node* LibraryCallKit::generate_negative_guard(Node* index, RegionNode* region,
 921                                                      Node* *pos_index) {
 922   if (stopped())
 923     return nullptr;                // already stopped
 924   if (_gvn.type(index)->higher_equal(TypeInt::POS)) // [0,maxint]
 925     return nullptr;                // index is already adequately typed
 926   Node* cmp_lt = _gvn.transform(new CmpINode(index, intcon(0)));
 927   Node* bol_lt = _gvn.transform(new BoolNode(cmp_lt, BoolTest::lt));
 928   Node* is_neg = generate_guard(bol_lt, region, PROB_MIN);
 929   if (is_neg != nullptr && pos_index != nullptr) {
 930     // Emulate effect of Parse::adjust_map_after_if.
 931     Node* ccast = new CastIINode(control(), index, TypeInt::POS);
 932     (*pos_index) = _gvn.transform(ccast);
 933   }
 934   return is_neg;
 935 }
 936 
 937 // Make sure that 'position' is a valid limit index, in [0..length].
 938 // There are two equivalent plans for checking this:
 939 //   A. (offset + copyLength)  unsigned<=  arrayLength
 940 //   B. offset  <=  (arrayLength - copyLength)
 941 // We require that all of the values above, except for the sum and
 942 // difference, are already known to be non-negative.
 943 // Plan A is robust in the face of overflow, if offset and copyLength
 944 // are both hugely positive.
 945 //
 946 // Plan B is less direct and intuitive, but it does not overflow at
 947 // all, since the difference of two non-negatives is always
 948 // representable.  Whenever Java methods must perform the equivalent
 949 // check they generally use Plan B instead of Plan A.
 950 // For the moment we use Plan A.
 951 inline Node* LibraryCallKit::generate_limit_guard(Node* offset,
 952                                                   Node* subseq_length,
 953                                                   Node* array_length,
 954                                                   RegionNode* region) {
 955   if (stopped())
 956     return nullptr;                // already stopped
 957   bool zero_offset = _gvn.type(offset) == TypeInt::ZERO;
 958   if (zero_offset && subseq_length->eqv_uncast(array_length))
 959     return nullptr;                // common case of whole-array copy
 960   Node* last = subseq_length;
 961   if (!zero_offset)             // last += offset
 962     last = _gvn.transform(new AddINode(last, offset));
 963   Node* cmp_lt = _gvn.transform(new CmpUNode(array_length, last));
 964   Node* bol_lt = _gvn.transform(new BoolNode(cmp_lt, BoolTest::lt));
 965   Node* is_over = generate_guard(bol_lt, region, PROB_MIN);
 966   return is_over;
 967 }
 968 
 969 // Emit range checks for the given String.value byte array
 970 void LibraryCallKit::generate_string_range_check(Node* array,
 971                                                  Node* offset,
 972                                                  Node* count,
 973                                                  bool char_count,
 974                                                  bool halt_on_oob) {
 975   if (stopped()) {
 976     return; // already stopped
 977   }
 978   RegionNode* bailout = new RegionNode(1);
 979   record_for_igvn(bailout);
 980   if (char_count) {
 981     // Convert char count to byte count
 982     count = _gvn.transform(new LShiftINode(count, intcon(1)));
 983   }
 984 
 985   // Offset and count must not be negative
 986   generate_negative_guard(offset, bailout);
 987   generate_negative_guard(count, bailout);
 988   // Offset + count must not exceed length of array
 989   generate_limit_guard(offset, count, load_array_length(array), bailout);
 990 
 991   if (bailout->req() > 1) {
 992     if (halt_on_oob) {
 993       bailout = _gvn.transform(bailout)->as_Region();
 994       Node* frame = _gvn.transform(new ParmNode(C->start(), TypeFunc::FramePtr));
 995       Node* halt = _gvn.transform(new HaltNode(bailout, frame, "unexpected guard failure in intrinsic"));
 996       C->root()->add_req(halt);
 997     } else {
 998       PreserveJVMState pjvms(this);
 999       set_control(_gvn.transform(bailout));
1000       uncommon_trap(Deoptimization::Reason_intrinsic,
1001                     Deoptimization::Action_maybe_recompile);
1002     }
1003   }
1004 }
1005 
1006 Node* LibraryCallKit::current_thread_helper(Node*& tls_output, ByteSize handle_offset,
1007                                             bool is_immutable) {
1008   ciKlass* thread_klass = env()->Thread_klass();
1009   const Type* thread_type
1010     = TypeOopPtr::make_from_klass(thread_klass)->cast_to_ptr_type(TypePtr::NotNull);
1011 
1012   Node* thread = _gvn.transform(new ThreadLocalNode());
1013   Node* p = basic_plus_adr(top()/*!oop*/, thread, in_bytes(handle_offset));
1014   tls_output = thread;
1015 
1016   Node* thread_obj_handle
1017     = (is_immutable
1018       ? LoadNode::make(_gvn, nullptr, immutable_memory(), p, p->bottom_type()->is_ptr(),
1019         TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered)
1020       : make_load(nullptr, p, p->bottom_type()->is_ptr(), T_ADDRESS, MemNode::unordered));
1021   thread_obj_handle = _gvn.transform(thread_obj_handle);
1022 
1023   DecoratorSet decorators = IN_NATIVE;
1024   if (is_immutable) {
1025     decorators |= C2_IMMUTABLE_MEMORY;
1026   }
1027   return access_load(thread_obj_handle, thread_type, T_OBJECT, decorators);
1028 }
1029 
1030 //--------------------------generate_current_thread--------------------
1031 Node* LibraryCallKit::generate_current_thread(Node* &tls_output) {
1032   return current_thread_helper(tls_output, JavaThread::threadObj_offset(),
1033                                /*is_immutable*/false);
1034 }
1035 
1036 //--------------------------generate_virtual_thread--------------------
1037 Node* LibraryCallKit::generate_virtual_thread(Node* tls_output) {
1038   return current_thread_helper(tls_output, JavaThread::vthread_offset(),
1039                                !C->method()->changes_current_thread());
1040 }
1041 
1042 //------------------------------make_string_method_node------------------------
1043 // Helper method for String intrinsic functions. This version is called with
1044 // str1 and str2 pointing to byte[] nodes containing Latin1 or UTF16 encoded
1045 // characters (depending on 'is_byte'). cnt1 and cnt2 are pointing to Int nodes
1046 // containing the lengths of str1 and str2.
1047 Node* LibraryCallKit::make_string_method_node(int opcode, Node* str1_start, Node* cnt1, Node* str2_start, Node* cnt2, StrIntrinsicNode::ArgEnc ae) {
1048   Node* result = nullptr;
1049   switch (opcode) {
1050   case Op_StrIndexOf:
1051     result = new StrIndexOfNode(control(), memory(TypeAryPtr::BYTES),
1052                                 str1_start, cnt1, str2_start, cnt2, ae);
1053     break;
1054   case Op_StrComp:
1055     result = new StrCompNode(control(), memory(TypeAryPtr::BYTES),
1056                              str1_start, cnt1, str2_start, cnt2, ae);
1057     break;
1058   case Op_StrEquals:
1059     // We already know that cnt1 == cnt2 here (checked in 'inline_string_equals').
1060     // Use the constant length if there is one because optimized match rule may exist.
1061     result = new StrEqualsNode(control(), memory(TypeAryPtr::BYTES),
1062                                str1_start, str2_start, cnt2->is_Con() ? cnt2 : cnt1, ae);
1063     break;
1064   default:
1065     ShouldNotReachHere();
1066     return nullptr;
1067   }
1068 
1069   // All these intrinsics have checks.
1070   C->set_has_split_ifs(true); // Has chance for split-if optimization
1071   clear_upper_avx();
1072 
1073   return _gvn.transform(result);
1074 }
1075 
1076 //------------------------------inline_string_compareTo------------------------
1077 bool LibraryCallKit::inline_string_compareTo(StrIntrinsicNode::ArgEnc ae) {
1078   Node* arg1 = argument(0);
1079   Node* arg2 = argument(1);
1080 
1081   arg1 = must_be_not_null(arg1, true);
1082   arg2 = must_be_not_null(arg2, true);
1083 
1084   // Get start addr and length of first argument
1085   Node* arg1_start  = array_element_address(arg1, intcon(0), T_BYTE);
1086   Node* arg1_cnt    = load_array_length(arg1);
1087 
1088   // Get start addr and length of second argument
1089   Node* arg2_start  = array_element_address(arg2, intcon(0), T_BYTE);
1090   Node* arg2_cnt    = load_array_length(arg2);
1091 
1092   Node* result = make_string_method_node(Op_StrComp, arg1_start, arg1_cnt, arg2_start, arg2_cnt, ae);
1093   set_result(result);
1094   return true;
1095 }
1096 
1097 //------------------------------inline_string_equals------------------------
1098 bool LibraryCallKit::inline_string_equals(StrIntrinsicNode::ArgEnc ae) {
1099   Node* arg1 = argument(0);
1100   Node* arg2 = argument(1);
1101 
1102   // paths (plus control) merge
1103   RegionNode* region = new RegionNode(3);
1104   Node* phi = new PhiNode(region, TypeInt::BOOL);
1105 
1106   if (!stopped()) {
1107 
1108     arg1 = must_be_not_null(arg1, true);
1109     arg2 = must_be_not_null(arg2, true);
1110 
1111     // Get start addr and length of first argument
1112     Node* arg1_start  = array_element_address(arg1, intcon(0), T_BYTE);
1113     Node* arg1_cnt    = load_array_length(arg1);
1114 
1115     // Get start addr and length of second argument
1116     Node* arg2_start  = array_element_address(arg2, intcon(0), T_BYTE);
1117     Node* arg2_cnt    = load_array_length(arg2);
1118 
1119     // Check for arg1_cnt != arg2_cnt
1120     Node* cmp = _gvn.transform(new CmpINode(arg1_cnt, arg2_cnt));
1121     Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::ne));
1122     Node* if_ne = generate_slow_guard(bol, nullptr);
1123     if (if_ne != nullptr) {
1124       phi->init_req(2, intcon(0));
1125       region->init_req(2, if_ne);
1126     }
1127 
1128     // Check for count == 0 is done by assembler code for StrEquals.
1129 
1130     if (!stopped()) {
1131       Node* equals = make_string_method_node(Op_StrEquals, arg1_start, arg1_cnt, arg2_start, arg2_cnt, ae);
1132       phi->init_req(1, equals);
1133       region->init_req(1, control());
1134     }
1135   }
1136 
1137   // post merge
1138   set_control(_gvn.transform(region));
1139   record_for_igvn(region);
1140 
1141   set_result(_gvn.transform(phi));
1142   return true;
1143 }
1144 
1145 //------------------------------inline_array_equals----------------------------
1146 bool LibraryCallKit::inline_array_equals(StrIntrinsicNode::ArgEnc ae) {
1147   assert(ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::LL, "unsupported array types");
1148   Node* arg1 = argument(0);
1149   Node* arg2 = argument(1);
1150 
1151   const TypeAryPtr* mtype = (ae == StrIntrinsicNode::UU) ? TypeAryPtr::CHARS : TypeAryPtr::BYTES;
1152   set_result(_gvn.transform(new AryEqNode(control(), memory(mtype), arg1, arg2, ae)));
1153   clear_upper_avx();
1154 
1155   return true;
1156 }
1157 
1158 
1159 //------------------------------inline_countPositives------------------------------
1160 // int java.lang.StringCoding#countPositives0(byte[] ba, int off, int len)
1161 bool LibraryCallKit::inline_countPositives() {
1162   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1163     return false;
1164   }
1165 
1166   assert(callee()->signature()->size() == 3, "countPositives has 3 parameters");
1167   // no receiver since it is static method
1168   Node* ba         = argument(0);
1169   Node* offset     = argument(1);
1170   Node* len        = argument(2);
1171 
1172   if (VerifyIntrinsicChecks) {
1173     ba = must_be_not_null(ba, true);
1174     generate_string_range_check(ba, offset, len, false, true);
1175     if (stopped()) {
1176       return true;
1177     }
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::RegularDependency, 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::RegularDependency, 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 (too_many_traps(Deoptimization::Reason_intrinsic)) {
1309     return false;
1310   }
1311   if (!Matcher::match_rule_supported(Op_StrIndexOf)) {
1312     return false;
1313   }
1314 
1315   assert(callee()->signature()->size() == 5, "String.indexOf() has 5 arguments");
1316   Node* src         = argument(0); // byte[]
1317   Node* src_count   = argument(1); // char count
1318   Node* tgt         = argument(2); // byte[]
1319   Node* tgt_count   = argument(3); // char count
1320   Node* from_index  = argument(4); // char index
1321 
1322   src = must_be_not_null(src, true);
1323   tgt = must_be_not_null(tgt, true);
1324 
1325   // Multiply byte array index by 2 if String is UTF16 encoded
1326   Node* src_offset = (ae == StrIntrinsicNode::LL) ? from_index : _gvn.transform(new LShiftINode(from_index, intcon(1)));
1327   src_count = _gvn.transform(new SubINode(src_count, from_index));
1328   Node* src_start = array_element_address(src, src_offset, T_BYTE);
1329   Node* tgt_start = array_element_address(tgt, intcon(0), T_BYTE);
1330 
1331   // Range checks
1332   generate_string_range_check(src, src_offset, src_count, ae != StrIntrinsicNode::LL);
1333   generate_string_range_check(tgt, intcon(0), tgt_count, ae == StrIntrinsicNode::UU);
1334   if (stopped()) {
1335     return true;
1336   }
1337 
1338   RegionNode* region = new RegionNode(5);
1339   Node* phi = new PhiNode(region, TypeInt::INT);
1340   Node* result = nullptr;
1341 
1342   bool call_opt_stub = (StubRoutines::_string_indexof_array[ae] != nullptr);
1343 
1344   if (call_opt_stub) {
1345     Node* call = make_runtime_call(RC_LEAF, OptoRuntime::string_IndexOf_Type(),
1346                                    StubRoutines::_string_indexof_array[ae],
1347                                    "stringIndexOf", TypePtr::BOTTOM, src_start,
1348                                    src_count, tgt_start, tgt_count);
1349     result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
1350   } else {
1351     result = make_indexOf_node(src_start, src_count, tgt_start, tgt_count,
1352                                region, phi, ae);
1353   }
1354   if (result != nullptr) {
1355     // The result is index relative to from_index if substring was found, -1 otherwise.
1356     // Generate code which will fold into cmove.
1357     Node* cmp = _gvn.transform(new CmpINode(result, intcon(0)));
1358     Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::lt));
1359 
1360     Node* if_lt = generate_slow_guard(bol, nullptr);
1361     if (if_lt != nullptr) {
1362       // result == -1
1363       phi->init_req(3, result);
1364       region->init_req(3, if_lt);
1365     }
1366     if (!stopped()) {
1367       result = _gvn.transform(new AddINode(result, from_index));
1368       phi->init_req(4, result);
1369       region->init_req(4, control());
1370     }
1371   }
1372 
1373   set_control(_gvn.transform(region));
1374   record_for_igvn(region);
1375   set_result(_gvn.transform(phi));
1376   clear_upper_avx();
1377 
1378   return true;
1379 }
1380 
1381 // Create StrIndexOfNode with fast path checks
1382 Node* LibraryCallKit::make_indexOf_node(Node* src_start, Node* src_count, Node* tgt_start, Node* tgt_count,
1383                                         RegionNode* region, Node* phi, StrIntrinsicNode::ArgEnc ae) {
1384   // Check for substr count > string count
1385   Node* cmp = _gvn.transform(new CmpINode(tgt_count, src_count));
1386   Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::gt));
1387   Node* if_gt = generate_slow_guard(bol, nullptr);
1388   if (if_gt != nullptr) {
1389     phi->init_req(1, intcon(-1));
1390     region->init_req(1, if_gt);
1391   }
1392   if (!stopped()) {
1393     // Check for substr count == 0
1394     cmp = _gvn.transform(new CmpINode(tgt_count, intcon(0)));
1395     bol = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
1396     Node* if_zero = generate_slow_guard(bol, nullptr);
1397     if (if_zero != nullptr) {
1398       phi->init_req(2, intcon(0));
1399       region->init_req(2, if_zero);
1400     }
1401   }
1402   if (!stopped()) {
1403     return make_string_method_node(Op_StrIndexOf, src_start, src_count, tgt_start, tgt_count, ae);
1404   }
1405   return nullptr;
1406 }
1407 
1408 //-----------------------------inline_string_indexOfChar-----------------------
1409 bool LibraryCallKit::inline_string_indexOfChar(StrIntrinsicNode::ArgEnc ae) {
1410   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1411     return false;
1412   }
1413   if (!Matcher::match_rule_supported(Op_StrIndexOfChar)) {
1414     return false;
1415   }
1416   assert(callee()->signature()->size() == 4, "String.indexOfChar() has 4 arguments");
1417   Node* src         = argument(0); // byte[]
1418   Node* int_ch      = argument(1);
1419   Node* from_index  = argument(2);
1420   Node* max         = argument(3);
1421 
1422   src = must_be_not_null(src, true);
1423 
1424   Node* src_offset = ae == StrIntrinsicNode::L ? from_index : _gvn.transform(new LShiftINode(from_index, intcon(1)));
1425   Node* src_start = array_element_address(src, src_offset, T_BYTE);
1426   Node* src_count = _gvn.transform(new SubINode(max, from_index));
1427 
1428   // Range checks
1429   generate_string_range_check(src, src_offset, src_count, ae == StrIntrinsicNode::U);
1430 
1431   // Check for int_ch >= 0
1432   Node* int_ch_cmp = _gvn.transform(new CmpINode(int_ch, intcon(0)));
1433   Node* int_ch_bol = _gvn.transform(new BoolNode(int_ch_cmp, BoolTest::ge));
1434   {
1435     BuildCutout unless(this, int_ch_bol, PROB_MAX);
1436     uncommon_trap(Deoptimization::Reason_intrinsic,
1437                   Deoptimization::Action_maybe_recompile);
1438   }
1439   if (stopped()) {
1440     return true;
1441   }
1442 
1443   RegionNode* region = new RegionNode(3);
1444   Node* phi = new PhiNode(region, TypeInt::INT);
1445 
1446   Node* result = new StrIndexOfCharNode(control(), memory(TypeAryPtr::BYTES), src_start, src_count, int_ch, ae);
1447   C->set_has_split_ifs(true); // Has chance for split-if optimization
1448   _gvn.transform(result);
1449 
1450   Node* cmp = _gvn.transform(new CmpINode(result, intcon(0)));
1451   Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::lt));
1452 
1453   Node* if_lt = generate_slow_guard(bol, nullptr);
1454   if (if_lt != nullptr) {
1455     // result == -1
1456     phi->init_req(2, result);
1457     region->init_req(2, if_lt);
1458   }
1459   if (!stopped()) {
1460     result = _gvn.transform(new AddINode(result, from_index));
1461     phi->init_req(1, result);
1462     region->init_req(1, control());
1463   }
1464   set_control(_gvn.transform(region));
1465   record_for_igvn(region);
1466   set_result(_gvn.transform(phi));
1467   clear_upper_avx();
1468 
1469   return true;
1470 }
1471 //---------------------------inline_string_copy---------------------
1472 // compressIt == true --> generate a compressed copy operation (compress char[]/byte[] to byte[])
1473 //   int StringUTF16.compress(char[] src, int srcOff, byte[] dst, int dstOff, int len)
1474 //   int StringUTF16.compress(byte[] src, int srcOff, byte[] dst, int dstOff, int len)
1475 // compressIt == false --> generate an inflated copy operation (inflate byte[] to char[]/byte[])
1476 //   void StringLatin1.inflate(byte[] src, int srcOff, char[] dst, int dstOff, int len)
1477 //   void StringLatin1.inflate(byte[] src, int srcOff, byte[] dst, int dstOff, int len)
1478 bool LibraryCallKit::inline_string_copy(bool compress) {
1479   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1480     return false;
1481   }
1482   int nargs = 5;  // 2 oops, 3 ints
1483   assert(callee()->signature()->size() == nargs, "string copy has 5 arguments");
1484 
1485   Node* src         = argument(0);
1486   Node* src_offset  = argument(1);
1487   Node* dst         = argument(2);
1488   Node* dst_offset  = argument(3);
1489   Node* length      = argument(4);
1490 
1491   // Check for allocation before we add nodes that would confuse
1492   // tightly_coupled_allocation()
1493   AllocateArrayNode* alloc = tightly_coupled_allocation(dst);
1494 
1495   // Figure out the size and type of the elements we will be copying.
1496   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
1497   const TypeAryPtr* dst_type = dst->Value(&_gvn)->isa_aryptr();
1498   if (src_type == nullptr || dst_type == nullptr) {
1499     return false;
1500   }
1501   BasicType src_elem = src_type->elem()->array_element_basic_type();
1502   BasicType dst_elem = dst_type->elem()->array_element_basic_type();
1503   assert((compress && dst_elem == T_BYTE && (src_elem == T_BYTE || src_elem == T_CHAR)) ||
1504          (!compress && src_elem == T_BYTE && (dst_elem == T_BYTE || dst_elem == T_CHAR)),
1505          "Unsupported array types for inline_string_copy");
1506 
1507   src = must_be_not_null(src, true);
1508   dst = must_be_not_null(dst, true);
1509 
1510   // Convert char[] offsets to byte[] offsets
1511   bool convert_src = (compress && src_elem == T_BYTE);
1512   bool convert_dst = (!compress && dst_elem == T_BYTE);
1513   if (convert_src) {
1514     src_offset = _gvn.transform(new LShiftINode(src_offset, intcon(1)));
1515   } else if (convert_dst) {
1516     dst_offset = _gvn.transform(new LShiftINode(dst_offset, intcon(1)));
1517   }
1518 
1519   // Range checks
1520   generate_string_range_check(src, src_offset, length, convert_src);
1521   generate_string_range_check(dst, dst_offset, length, convert_dst);
1522   if (stopped()) {
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.toBytes(char[] value, int off, int len)
1571 bool LibraryCallKit::inline_string_toBytesU() {
1572   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1573     return false;
1574   }
1575   // Get the arguments.
1576   Node* value     = argument(0);
1577   Node* offset    = argument(1);
1578   Node* length    = argument(2);
1579 
1580   Node* newcopy = nullptr;
1581 
1582   // Set the original stack and the reexecute bit for the interpreter to reexecute
1583   // the bytecode that invokes StringUTF16.toBytes() if deoptimization happens.
1584   { PreserveReexecuteState preexecs(this);
1585     jvms()->set_should_reexecute(true);
1586 
1587     // Check if a null path was taken unconditionally.
1588     value = null_check(value);
1589 
1590     RegionNode* bailout = new RegionNode(1);
1591     record_for_igvn(bailout);
1592 
1593     // Range checks
1594     generate_negative_guard(offset, bailout);
1595     generate_negative_guard(length, bailout);
1596     generate_limit_guard(offset, length, load_array_length(value), bailout);
1597     // Make sure that resulting byte[] length does not overflow Integer.MAX_VALUE
1598     generate_limit_guard(length, intcon(0), intcon(max_jint/2), bailout);
1599 
1600     if (bailout->req() > 1) {
1601       PreserveJVMState pjvms(this);
1602       set_control(_gvn.transform(bailout));
1603       uncommon_trap(Deoptimization::Reason_intrinsic,
1604                     Deoptimization::Action_maybe_recompile);
1605     }
1606     if (stopped()) {
1607       return true;
1608     }
1609 
1610     Node* size = _gvn.transform(new LShiftINode(length, intcon(1)));
1611     Node* klass_node = makecon(TypeKlassPtr::make(ciTypeArrayKlass::make(T_BYTE)));
1612     newcopy = new_array(klass_node, size, 0);  // no arguments to push
1613     AllocateArrayNode* alloc = tightly_coupled_allocation(newcopy);
1614     guarantee(alloc != nullptr, "created above");
1615 
1616     // Calculate starting addresses.
1617     Node* src_start = array_element_address(value, offset, T_CHAR);
1618     Node* dst_start = basic_plus_adr(newcopy, arrayOopDesc::base_offset_in_bytes(T_BYTE));
1619 
1620     // Check if dst array address is aligned to HeapWordSize
1621     bool aligned = (arrayOopDesc::base_offset_in_bytes(T_BYTE) % HeapWordSize == 0);
1622     // If true, then check if src array address is aligned to HeapWordSize
1623     if (aligned) {
1624       const TypeInt* toffset = gvn().type(offset)->is_int();
1625       aligned = toffset->is_con() && ((arrayOopDesc::base_offset_in_bytes(T_CHAR) +
1626                                        toffset->get_con() * type2aelembytes(T_CHAR)) % HeapWordSize == 0);
1627     }
1628 
1629     // Figure out which arraycopy runtime method to call (disjoint, uninitialized).
1630     const char* copyfunc_name = "arraycopy";
1631     address     copyfunc_addr = StubRoutines::select_arraycopy_function(T_CHAR, aligned, true, copyfunc_name, true);
1632     Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
1633                       OptoRuntime::fast_arraycopy_Type(),
1634                       copyfunc_addr, copyfunc_name, TypeRawPtr::BOTTOM,
1635                       src_start, dst_start, ConvI2X(length) XTOP);
1636     // Do not let reads from the cloned object float above the arraycopy.
1637     if (alloc->maybe_set_complete(&_gvn)) {
1638       // "You break it, you buy it."
1639       InitializeNode* init = alloc->initialization();
1640       assert(init->is_complete(), "we just did this");
1641       init->set_complete_with_arraycopy();
1642       assert(newcopy->is_CheckCastPP(), "sanity");
1643       assert(newcopy->in(0)->in(0) == init, "dest pinned");
1644     }
1645     // Do not let stores that initialize this object be reordered with
1646     // a subsequent store that would make this object accessible by
1647     // other threads.
1648     // Record what AllocateNode this StoreStore protects so that
1649     // escape analysis can go from the MemBarStoreStoreNode to the
1650     // AllocateNode and eliminate the MemBarStoreStoreNode if possible
1651     // based on the escape status of the AllocateNode.
1652     insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
1653   } // original reexecute is set back here
1654 
1655   C->set_has_split_ifs(true); // Has chance for split-if optimization
1656   if (!stopped()) {
1657     set_result(newcopy);
1658   }
1659   clear_upper_avx();
1660 
1661   return true;
1662 }
1663 
1664 //------------------------inline_string_getCharsU--------------------------
1665 // public void StringUTF16.getChars(byte[] src, int srcBegin, int srcEnd, char dst[], int dstBegin)
1666 bool LibraryCallKit::inline_string_getCharsU() {
1667   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1668     return false;
1669   }
1670 
1671   // Get the arguments.
1672   Node* src       = argument(0);
1673   Node* src_begin = argument(1);
1674   Node* src_end   = argument(2); // exclusive offset (i < src_end)
1675   Node* dst       = argument(3);
1676   Node* dst_begin = argument(4);
1677 
1678   // Check for allocation before we add nodes that would confuse
1679   // tightly_coupled_allocation()
1680   AllocateArrayNode* alloc = tightly_coupled_allocation(dst);
1681 
1682   // Check if a null path was taken unconditionally.
1683   src = null_check(src);
1684   dst = null_check(dst);
1685   if (stopped()) {
1686     return true;
1687   }
1688 
1689   // Get length and convert char[] offset to byte[] offset
1690   Node* length = _gvn.transform(new SubINode(src_end, src_begin));
1691   src_begin = _gvn.transform(new LShiftINode(src_begin, intcon(1)));
1692 
1693   // Range checks
1694   generate_string_range_check(src, src_begin, length, true);
1695   generate_string_range_check(dst, dst_begin, length, false);
1696   if (stopped()) {
1697     return true;
1698   }
1699 
1700   if (!stopped()) {
1701     // Calculate starting addresses.
1702     Node* src_start = array_element_address(src, src_begin, T_BYTE);
1703     Node* dst_start = array_element_address(dst, dst_begin, T_CHAR);
1704 
1705     // Check if array addresses are aligned to HeapWordSize
1706     const TypeInt* tsrc = gvn().type(src_begin)->is_int();
1707     const TypeInt* tdst = gvn().type(dst_begin)->is_int();
1708     bool aligned = tsrc->is_con() && ((arrayOopDesc::base_offset_in_bytes(T_BYTE) + tsrc->get_con() * type2aelembytes(T_BYTE)) % HeapWordSize == 0) &&
1709                    tdst->is_con() && ((arrayOopDesc::base_offset_in_bytes(T_CHAR) + tdst->get_con() * type2aelembytes(T_CHAR)) % HeapWordSize == 0);
1710 
1711     // Figure out which arraycopy runtime method to call (disjoint, uninitialized).
1712     const char* copyfunc_name = "arraycopy";
1713     address     copyfunc_addr = StubRoutines::select_arraycopy_function(T_CHAR, aligned, true, copyfunc_name, true);
1714     Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
1715                       OptoRuntime::fast_arraycopy_Type(),
1716                       copyfunc_addr, copyfunc_name, TypeRawPtr::BOTTOM,
1717                       src_start, dst_start, ConvI2X(length) XTOP);
1718     // Do not let reads from the cloned object float above the arraycopy.
1719     if (alloc != nullptr) {
1720       if (alloc->maybe_set_complete(&_gvn)) {
1721         // "You break it, you buy it."
1722         InitializeNode* init = alloc->initialization();
1723         assert(init->is_complete(), "we just did this");
1724         init->set_complete_with_arraycopy();
1725         assert(dst->is_CheckCastPP(), "sanity");
1726         assert(dst->in(0)->in(0) == init, "dest pinned");
1727       }
1728       // Do not let stores that initialize this object be reordered with
1729       // a subsequent store that would make this object accessible by
1730       // other threads.
1731       // Record what AllocateNode this StoreStore protects so that
1732       // escape analysis can go from the MemBarStoreStoreNode to the
1733       // AllocateNode and eliminate the MemBarStoreStoreNode if possible
1734       // based on the escape status of the AllocateNode.
1735       insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
1736     } else {
1737       insert_mem_bar(Op_MemBarCPUOrder);
1738     }
1739   }
1740 
1741   C->set_has_split_ifs(true); // Has chance for split-if optimization
1742   return true;
1743 }
1744 
1745 //----------------------inline_string_char_access----------------------------
1746 // Store/Load char to/from byte[] array.
1747 // static void StringUTF16.putChar(byte[] val, int index, int c)
1748 // static char StringUTF16.getChar(byte[] val, int index)
1749 bool LibraryCallKit::inline_string_char_access(bool is_store) {
1750   Node* value  = argument(0);
1751   Node* index  = argument(1);
1752   Node* ch = is_store ? argument(2) : nullptr;
1753 
1754   // This intrinsic accesses byte[] array as char[] array. Computing the offsets
1755   // correctly requires matched array shapes.
1756   assert (arrayOopDesc::base_offset_in_bytes(T_CHAR) == arrayOopDesc::base_offset_in_bytes(T_BYTE),
1757           "sanity: byte[] and char[] bases agree");
1758   assert (type2aelembytes(T_CHAR) == type2aelembytes(T_BYTE)*2,
1759           "sanity: byte[] and char[] scales agree");
1760 
1761   // Bail when getChar over constants is requested: constant folding would
1762   // reject folding mismatched char access over byte[]. A normal inlining for getChar
1763   // Java method would constant fold nicely instead.
1764   if (!is_store && value->is_Con() && index->is_Con()) {
1765     return false;
1766   }
1767 
1768   // Save state and restore on bailout
1769   SavedState old_state(this);
1770 
1771   value = must_be_not_null(value, true);
1772 
1773   Node* adr = array_element_address(value, index, T_CHAR);
1774   if (adr->is_top()) {
1775     return false;
1776   }
1777   old_state.discard();
1778   if (is_store) {
1779     access_store_at(value, adr, TypeAryPtr::BYTES, ch, TypeInt::CHAR, T_CHAR, IN_HEAP | MO_UNORDERED | C2_MISMATCHED);
1780   } else {
1781     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);
1782     set_result(ch);
1783   }
1784   return true;
1785 }
1786 
1787 
1788 //------------------------------inline_math-----------------------------------
1789 // public static double Math.abs(double)
1790 // public static double Math.sqrt(double)
1791 // public static double Math.log(double)
1792 // public static double Math.log10(double)
1793 // public static double Math.round(double)
1794 bool LibraryCallKit::inline_double_math(vmIntrinsics::ID id) {
1795   Node* arg = argument(0);
1796   Node* n = nullptr;
1797   switch (id) {
1798   case vmIntrinsics::_dabs:   n = new AbsDNode(                arg);  break;
1799   case vmIntrinsics::_dsqrt:
1800   case vmIntrinsics::_dsqrt_strict:
1801                               n = new SqrtDNode(C, control(),  arg);  break;
1802   case vmIntrinsics::_ceil:   n = RoundDoubleModeNode::make(_gvn, arg, RoundDoubleModeNode::rmode_ceil); break;
1803   case vmIntrinsics::_floor:  n = RoundDoubleModeNode::make(_gvn, arg, RoundDoubleModeNode::rmode_floor); break;
1804   case vmIntrinsics::_rint:   n = RoundDoubleModeNode::make(_gvn, arg, RoundDoubleModeNode::rmode_rint); break;
1805   case vmIntrinsics::_roundD: n = new RoundDNode(arg); break;
1806   case vmIntrinsics::_dcopySign: n = CopySignDNode::make(_gvn, arg, argument(2)); break;
1807   case vmIntrinsics::_dsignum: n = SignumDNode::make(_gvn, arg); break;
1808   default:  fatal_unexpected_iid(id);  break;
1809   }
1810   set_result(_gvn.transform(n));
1811   return true;
1812 }
1813 
1814 //------------------------------inline_math-----------------------------------
1815 // public static float Math.abs(float)
1816 // public static int Math.abs(int)
1817 // public static long Math.abs(long)
1818 bool LibraryCallKit::inline_math(vmIntrinsics::ID id) {
1819   Node* arg = argument(0);
1820   Node* n = nullptr;
1821   switch (id) {
1822   case vmIntrinsics::_fabs:   n = new AbsFNode(                arg);  break;
1823   case vmIntrinsics::_iabs:   n = new AbsINode(                arg);  break;
1824   case vmIntrinsics::_labs:   n = new AbsLNode(                arg);  break;
1825   case vmIntrinsics::_fcopySign: n = new CopySignFNode(arg, argument(1)); break;
1826   case vmIntrinsics::_fsignum: n = SignumFNode::make(_gvn, arg); break;
1827   case vmIntrinsics::_roundF: n = new RoundFNode(arg); break;
1828   default:  fatal_unexpected_iid(id);  break;
1829   }
1830   set_result(_gvn.transform(n));
1831   return true;
1832 }
1833 
1834 //------------------------------runtime_math-----------------------------
1835 bool LibraryCallKit::runtime_math(const TypeFunc* call_type, address funcAddr, const char* funcName) {
1836   assert(call_type == OptoRuntime::Math_DD_D_Type() || call_type == OptoRuntime::Math_D_D_Type(),
1837          "must be (DD)D or (D)D type");
1838 
1839   // Inputs
1840   Node* a = argument(0);
1841   Node* b = (call_type == OptoRuntime::Math_DD_D_Type()) ? argument(2) : nullptr;
1842 
1843   const TypePtr* no_memory_effects = nullptr;
1844   Node* trig = make_runtime_call(RC_LEAF | RC_PURE, call_type, funcAddr, funcName,
1845                                  no_memory_effects,
1846                                  a, top(), b, b ? top() : nullptr);
1847   Node* value = _gvn.transform(new ProjNode(trig, TypeFunc::Parms+0));
1848 #ifdef ASSERT
1849   Node* value_top = _gvn.transform(new ProjNode(trig, TypeFunc::Parms+1));
1850   assert(value_top == top(), "second value must be top");
1851 #endif
1852 
1853   set_result(value);
1854   return true;
1855 }
1856 
1857 //------------------------------inline_math_pow-----------------------------
1858 bool LibraryCallKit::inline_math_pow() {
1859   Node* exp = argument(2);
1860   const TypeD* d = _gvn.type(exp)->isa_double_constant();
1861   if (d != nullptr) {
1862     if (d->getd() == 2.0) {
1863       // Special case: pow(x, 2.0) => x * x
1864       Node* base = argument(0);
1865       set_result(_gvn.transform(new MulDNode(base, base)));
1866       return true;
1867     } else if (d->getd() == 0.5 && Matcher::match_rule_supported(Op_SqrtD)) {
1868       // Special case: pow(x, 0.5) => sqrt(x)
1869       Node* base = argument(0);
1870       Node* zero = _gvn.zerocon(T_DOUBLE);
1871 
1872       RegionNode* region = new RegionNode(3);
1873       Node* phi = new PhiNode(region, Type::DOUBLE);
1874 
1875       Node* cmp  = _gvn.transform(new CmpDNode(base, zero));
1876       // According to the API specs, pow(-0.0, 0.5) = 0.0 and sqrt(-0.0) = -0.0.
1877       // So pow(-0.0, 0.5) shouldn't be replaced with sqrt(-0.0).
1878       // -0.0/+0.0 are both excluded since floating-point comparison doesn't distinguish -0.0 from +0.0.
1879       Node* test = _gvn.transform(new BoolNode(cmp, BoolTest::le));
1880 
1881       Node* if_pow = generate_slow_guard(test, nullptr);
1882       Node* value_sqrt = _gvn.transform(new SqrtDNode(C, control(), base));
1883       phi->init_req(1, value_sqrt);
1884       region->init_req(1, control());
1885 
1886       if (if_pow != nullptr) {
1887         set_control(if_pow);
1888         address target = StubRoutines::dpow() != nullptr ? StubRoutines::dpow() :
1889                                                         CAST_FROM_FN_PTR(address, SharedRuntime::dpow);
1890         const TypePtr* no_memory_effects = nullptr;
1891         Node* trig = make_runtime_call(RC_LEAF, OptoRuntime::Math_DD_D_Type(), target, "POW",
1892                                        no_memory_effects, base, top(), exp, top());
1893         Node* value_pow = _gvn.transform(new ProjNode(trig, TypeFunc::Parms+0));
1894 #ifdef ASSERT
1895         Node* value_top = _gvn.transform(new ProjNode(trig, TypeFunc::Parms+1));
1896         assert(value_top == top(), "second value must be top");
1897 #endif
1898         phi->init_req(2, value_pow);
1899         region->init_req(2, _gvn.transform(new ProjNode(trig, TypeFunc::Control)));
1900       }
1901 
1902       C->set_has_split_ifs(true); // Has chance for split-if optimization
1903       set_control(_gvn.transform(region));
1904       record_for_igvn(region);
1905       set_result(_gvn.transform(phi));
1906 
1907       return true;
1908     }
1909   }
1910 
1911   return StubRoutines::dpow() != nullptr ?
1912     runtime_math(OptoRuntime::Math_DD_D_Type(), StubRoutines::dpow(),  "dpow") :
1913     runtime_math(OptoRuntime::Math_DD_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dpow),  "POW");
1914 }
1915 
1916 //------------------------------inline_math_native-----------------------------
1917 bool LibraryCallKit::inline_math_native(vmIntrinsics::ID id) {
1918   switch (id) {
1919   case vmIntrinsics::_dsin:
1920     return StubRoutines::dsin() != nullptr ?
1921       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dsin(), "dsin") :
1922       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dsin),   "SIN");
1923   case vmIntrinsics::_dcos:
1924     return StubRoutines::dcos() != nullptr ?
1925       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dcos(), "dcos") :
1926       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dcos),   "COS");
1927   case vmIntrinsics::_dtan:
1928     return StubRoutines::dtan() != nullptr ?
1929       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dtan(), "dtan") :
1930       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dtan), "TAN");
1931   case vmIntrinsics::_dsinh:
1932     return StubRoutines::dsinh() != nullptr ?
1933       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dsinh(), "dsinh") : false;
1934   case vmIntrinsics::_dtanh:
1935     return StubRoutines::dtanh() != nullptr ?
1936       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dtanh(), "dtanh") : false;
1937   case vmIntrinsics::_dcbrt:
1938     return StubRoutines::dcbrt() != nullptr ?
1939       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dcbrt(), "dcbrt") : false;
1940   case vmIntrinsics::_dexp:
1941     return StubRoutines::dexp() != nullptr ?
1942       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dexp(),  "dexp") :
1943       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dexp),  "EXP");
1944   case vmIntrinsics::_dlog:
1945     return StubRoutines::dlog() != nullptr ?
1946       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dlog(), "dlog") :
1947       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dlog),   "LOG");
1948   case vmIntrinsics::_dlog10:
1949     return StubRoutines::dlog10() != nullptr ?
1950       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dlog10(), "dlog10") :
1951       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dlog10), "LOG10");
1952 
1953   case vmIntrinsics::_roundD: return Matcher::match_rule_supported(Op_RoundD) ? inline_double_math(id) : false;
1954   case vmIntrinsics::_ceil:
1955   case vmIntrinsics::_floor:
1956   case vmIntrinsics::_rint:   return Matcher::match_rule_supported(Op_RoundDoubleMode) ? inline_double_math(id) : false;
1957 
1958   case vmIntrinsics::_dsqrt:
1959   case vmIntrinsics::_dsqrt_strict:
1960                               return Matcher::match_rule_supported(Op_SqrtD) ? inline_double_math(id) : false;
1961   case vmIntrinsics::_dabs:   return Matcher::has_match_rule(Op_AbsD)   ? inline_double_math(id) : false;
1962   case vmIntrinsics::_fabs:   return Matcher::match_rule_supported(Op_AbsF)   ? inline_math(id) : false;
1963   case vmIntrinsics::_iabs:   return Matcher::match_rule_supported(Op_AbsI)   ? inline_math(id) : false;
1964   case vmIntrinsics::_labs:   return Matcher::match_rule_supported(Op_AbsL)   ? inline_math(id) : false;
1965 
1966   case vmIntrinsics::_dpow:      return inline_math_pow();
1967   case vmIntrinsics::_dcopySign: return inline_double_math(id);
1968   case vmIntrinsics::_fcopySign: return inline_math(id);
1969   case vmIntrinsics::_dsignum: return Matcher::match_rule_supported(Op_SignumD) ? inline_double_math(id) : false;
1970   case vmIntrinsics::_fsignum: return Matcher::match_rule_supported(Op_SignumF) ? inline_math(id) : false;
1971   case vmIntrinsics::_roundF: return Matcher::match_rule_supported(Op_RoundF) ? inline_math(id) : false;
1972 
1973    // These intrinsics are not yet correctly implemented
1974   case vmIntrinsics::_datan2:
1975     return false;
1976 
1977   default:
1978     fatal_unexpected_iid(id);
1979     return false;
1980   }
1981 }
1982 
1983 //----------------------------inline_notify-----------------------------------*
1984 bool LibraryCallKit::inline_notify(vmIntrinsics::ID id) {
1985   const TypeFunc* ftype = OptoRuntime::monitor_notify_Type();
1986   address func;
1987   if (id == vmIntrinsics::_notify) {
1988     func = OptoRuntime::monitor_notify_Java();
1989   } else {
1990     func = OptoRuntime::monitor_notifyAll_Java();
1991   }
1992   Node* call = make_runtime_call(RC_NO_LEAF, ftype, func, nullptr, TypeRawPtr::BOTTOM, argument(0));
1993   make_slow_call_ex(call, env()->Throwable_klass(), false);
1994   return true;
1995 }
1996 
1997 
1998 //----------------------------inline_min_max-----------------------------------
1999 bool LibraryCallKit::inline_min_max(vmIntrinsics::ID id) {
2000   Node* a = nullptr;
2001   Node* b = nullptr;
2002   Node* n = nullptr;
2003   switch (id) {
2004     case vmIntrinsics::_min:
2005     case vmIntrinsics::_max:
2006     case vmIntrinsics::_minF:
2007     case vmIntrinsics::_maxF:
2008     case vmIntrinsics::_minF_strict:
2009     case vmIntrinsics::_maxF_strict:
2010     case vmIntrinsics::_min_strict:
2011     case vmIntrinsics::_max_strict:
2012       assert(callee()->signature()->size() == 2, "minF/maxF has 2 parameters of size 1 each.");
2013       a = argument(0);
2014       b = argument(1);
2015       break;
2016     case vmIntrinsics::_minD:
2017     case vmIntrinsics::_maxD:
2018     case vmIntrinsics::_minD_strict:
2019     case vmIntrinsics::_maxD_strict:
2020       assert(callee()->signature()->size() == 4, "minD/maxD has 2 parameters of size 2 each.");
2021       a = argument(0);
2022       b = argument(2);
2023       break;
2024     case vmIntrinsics::_minL:
2025     case vmIntrinsics::_maxL:
2026       assert(callee()->signature()->size() == 4, "minL/maxL has 2 parameters of size 2 each.");
2027       a = argument(0);
2028       b = argument(2);
2029       break;
2030     default:
2031       fatal_unexpected_iid(id);
2032       break;
2033   }
2034 
2035   switch (id) {
2036     case vmIntrinsics::_min:
2037     case vmIntrinsics::_min_strict:
2038       n = new MinINode(a, b);
2039       break;
2040     case vmIntrinsics::_max:
2041     case vmIntrinsics::_max_strict:
2042       n = new MaxINode(a, b);
2043       break;
2044     case vmIntrinsics::_minF:
2045     case vmIntrinsics::_minF_strict:
2046       n = new MinFNode(a, b);
2047       break;
2048     case vmIntrinsics::_maxF:
2049     case vmIntrinsics::_maxF_strict:
2050       n = new MaxFNode(a, b);
2051       break;
2052     case vmIntrinsics::_minD:
2053     case vmIntrinsics::_minD_strict:
2054       n = new MinDNode(a, b);
2055       break;
2056     case vmIntrinsics::_maxD:
2057     case vmIntrinsics::_maxD_strict:
2058       n = new MaxDNode(a, b);
2059       break;
2060     case vmIntrinsics::_minL:
2061       n = new MinLNode(_gvn.C, a, b);
2062       break;
2063     case vmIntrinsics::_maxL:
2064       n = new MaxLNode(_gvn.C, a, b);
2065       break;
2066     default:
2067       fatal_unexpected_iid(id);
2068       break;
2069   }
2070 
2071   set_result(_gvn.transform(n));
2072   return true;
2073 }
2074 
2075 bool LibraryCallKit::inline_math_mathExact(Node* math, Node* test) {
2076   if (builtin_throw_too_many_traps(Deoptimization::Reason_intrinsic,
2077                                    env()->ArithmeticException_instance())) {
2078     // It has been already too many times, but we cannot use builtin_throw (e.g. we care about backtraces),
2079     // so let's bail out intrinsic rather than risking deopting again.
2080     return false;
2081   }
2082 
2083   Node* bol = _gvn.transform( new BoolNode(test, BoolTest::overflow) );
2084   IfNode* check = create_and_map_if(control(), bol, PROB_UNLIKELY_MAG(3), COUNT_UNKNOWN);
2085   Node* fast_path = _gvn.transform( new IfFalseNode(check));
2086   Node* slow_path = _gvn.transform( new IfTrueNode(check) );
2087 
2088   {
2089     PreserveJVMState pjvms(this);
2090     PreserveReexecuteState preexecs(this);
2091     jvms()->set_should_reexecute(true);
2092 
2093     set_control(slow_path);
2094     set_i_o(i_o());
2095 
2096     builtin_throw(Deoptimization::Reason_intrinsic,
2097                   env()->ArithmeticException_instance(),
2098                   /*allow_too_many_traps*/ false);
2099   }
2100 
2101   set_control(fast_path);
2102   set_result(math);
2103   return true;
2104 }
2105 
2106 template <typename OverflowOp>
2107 bool LibraryCallKit::inline_math_overflow(Node* arg1, Node* arg2) {
2108   typedef typename OverflowOp::MathOp MathOp;
2109 
2110   MathOp* mathOp = new MathOp(arg1, arg2);
2111   Node* operation = _gvn.transform( mathOp );
2112   Node* ofcheck = _gvn.transform( new OverflowOp(arg1, arg2) );
2113   return inline_math_mathExact(operation, ofcheck);
2114 }
2115 
2116 bool LibraryCallKit::inline_math_addExactI(bool is_increment) {
2117   return inline_math_overflow<OverflowAddINode>(argument(0), is_increment ? intcon(1) : argument(1));
2118 }
2119 
2120 bool LibraryCallKit::inline_math_addExactL(bool is_increment) {
2121   return inline_math_overflow<OverflowAddLNode>(argument(0), is_increment ? longcon(1) : argument(2));
2122 }
2123 
2124 bool LibraryCallKit::inline_math_subtractExactI(bool is_decrement) {
2125   return inline_math_overflow<OverflowSubINode>(argument(0), is_decrement ? intcon(1) : argument(1));
2126 }
2127 
2128 bool LibraryCallKit::inline_math_subtractExactL(bool is_decrement) {
2129   return inline_math_overflow<OverflowSubLNode>(argument(0), is_decrement ? longcon(1) : argument(2));
2130 }
2131 
2132 bool LibraryCallKit::inline_math_negateExactI() {
2133   return inline_math_overflow<OverflowSubINode>(intcon(0), argument(0));
2134 }
2135 
2136 bool LibraryCallKit::inline_math_negateExactL() {
2137   return inline_math_overflow<OverflowSubLNode>(longcon(0), argument(0));
2138 }
2139 
2140 bool LibraryCallKit::inline_math_multiplyExactI() {
2141   return inline_math_overflow<OverflowMulINode>(argument(0), argument(1));
2142 }
2143 
2144 bool LibraryCallKit::inline_math_multiplyExactL() {
2145   return inline_math_overflow<OverflowMulLNode>(argument(0), argument(2));
2146 }
2147 
2148 bool LibraryCallKit::inline_math_multiplyHigh() {
2149   set_result(_gvn.transform(new MulHiLNode(argument(0), argument(2))));
2150   return true;
2151 }
2152 
2153 bool LibraryCallKit::inline_math_unsignedMultiplyHigh() {
2154   set_result(_gvn.transform(new UMulHiLNode(argument(0), argument(2))));
2155   return true;
2156 }
2157 
2158 inline int
2159 LibraryCallKit::classify_unsafe_addr(Node* &base, Node* &offset, BasicType type) {
2160   const TypePtr* base_type = TypePtr::NULL_PTR;
2161   if (base != nullptr)  base_type = _gvn.type(base)->isa_ptr();
2162   if (base_type == nullptr) {
2163     // Unknown type.
2164     return Type::AnyPtr;
2165   } else if (_gvn.type(base->uncast()) == TypePtr::NULL_PTR) {
2166     // Since this is a null+long form, we have to switch to a rawptr.
2167     base   = _gvn.transform(new CastX2PNode(offset));
2168     offset = MakeConX(0);
2169     return Type::RawPtr;
2170   } else if (base_type->base() == Type::RawPtr) {
2171     return Type::RawPtr;
2172   } else if (base_type->isa_oopptr()) {
2173     // Base is never null => always a heap address.
2174     if (!TypePtr::NULL_PTR->higher_equal(base_type)) {
2175       return Type::OopPtr;
2176     }
2177     // Offset is small => always a heap address.
2178     const TypeX* offset_type = _gvn.type(offset)->isa_intptr_t();
2179     if (offset_type != nullptr &&
2180         base_type->offset() == 0 &&     // (should always be?)
2181         offset_type->_lo >= 0 &&
2182         !MacroAssembler::needs_explicit_null_check(offset_type->_hi)) {
2183       return Type::OopPtr;
2184     } else if (type == T_OBJECT) {
2185       // off heap access to an oop doesn't make any sense. Has to be on
2186       // heap.
2187       return Type::OopPtr;
2188     }
2189     // Otherwise, it might either be oop+off or null+addr.
2190     return Type::AnyPtr;
2191   } else {
2192     // No information:
2193     return Type::AnyPtr;
2194   }
2195 }
2196 
2197 Node* LibraryCallKit::make_unsafe_address(Node*& base, Node* offset, BasicType type, bool can_cast) {
2198   Node* uncasted_base = base;
2199   int kind = classify_unsafe_addr(uncasted_base, offset, type);
2200   if (kind == Type::RawPtr) {
2201     return basic_plus_adr(top(), uncasted_base, offset);
2202   } else if (kind == Type::AnyPtr) {
2203     assert(base == uncasted_base, "unexpected base change");
2204     if (can_cast) {
2205       if (!_gvn.type(base)->speculative_maybe_null() &&
2206           !too_many_traps(Deoptimization::Reason_speculate_null_check)) {
2207         // According to profiling, this access is always on
2208         // heap. Casting the base to not null and thus avoiding membars
2209         // around the access should allow better optimizations
2210         Node* null_ctl = top();
2211         base = null_check_oop(base, &null_ctl, true, true, true);
2212         assert(null_ctl->is_top(), "no null control here");
2213         return basic_plus_adr(base, offset);
2214       } else if (_gvn.type(base)->speculative_always_null() &&
2215                  !too_many_traps(Deoptimization::Reason_speculate_null_assert)) {
2216         // According to profiling, this access is always off
2217         // heap.
2218         base = null_assert(base);
2219         Node* raw_base = _gvn.transform(new CastX2PNode(offset));
2220         offset = MakeConX(0);
2221         return basic_plus_adr(top(), raw_base, offset);
2222       }
2223     }
2224     // We don't know if it's an on heap or off heap access. Fall back
2225     // to raw memory access.
2226     Node* raw = _gvn.transform(new CheckCastPPNode(control(), base, TypeRawPtr::BOTTOM));
2227     return basic_plus_adr(top(), raw, offset);
2228   } else {
2229     assert(base == uncasted_base, "unexpected base change");
2230     // We know it's an on heap access so base can't be null
2231     if (TypePtr::NULL_PTR->higher_equal(_gvn.type(base))) {
2232       base = must_be_not_null(base, true);
2233     }
2234     return basic_plus_adr(base, offset);
2235   }
2236 }
2237 
2238 //--------------------------inline_number_methods-----------------------------
2239 // inline int     Integer.numberOfLeadingZeros(int)
2240 // inline int        Long.numberOfLeadingZeros(long)
2241 //
2242 // inline int     Integer.numberOfTrailingZeros(int)
2243 // inline int        Long.numberOfTrailingZeros(long)
2244 //
2245 // inline int     Integer.bitCount(int)
2246 // inline int        Long.bitCount(long)
2247 //
2248 // inline char  Character.reverseBytes(char)
2249 // inline short     Short.reverseBytes(short)
2250 // inline int     Integer.reverseBytes(int)
2251 // inline long       Long.reverseBytes(long)
2252 bool LibraryCallKit::inline_number_methods(vmIntrinsics::ID id) {
2253   Node* arg = argument(0);
2254   Node* n = nullptr;
2255   switch (id) {
2256   case vmIntrinsics::_numberOfLeadingZeros_i:   n = new CountLeadingZerosINode( arg); break;
2257   case vmIntrinsics::_numberOfLeadingZeros_l:   n = new CountLeadingZerosLNode( arg); break;
2258   case vmIntrinsics::_numberOfTrailingZeros_i:  n = new CountTrailingZerosINode(arg); break;
2259   case vmIntrinsics::_numberOfTrailingZeros_l:  n = new CountTrailingZerosLNode(arg); break;
2260   case vmIntrinsics::_bitCount_i:               n = new PopCountINode(          arg); break;
2261   case vmIntrinsics::_bitCount_l:               n = new PopCountLNode(          arg); break;
2262   case vmIntrinsics::_reverseBytes_c:           n = new ReverseBytesUSNode(     arg); break;
2263   case vmIntrinsics::_reverseBytes_s:           n = new ReverseBytesSNode(      arg); break;
2264   case vmIntrinsics::_reverseBytes_i:           n = new ReverseBytesINode(      arg); break;
2265   case vmIntrinsics::_reverseBytes_l:           n = new ReverseBytesLNode(      arg); break;
2266   case vmIntrinsics::_reverse_i:                n = new ReverseINode(           arg); break;
2267   case vmIntrinsics::_reverse_l:                n = new ReverseLNode(           arg); break;
2268   default:  fatal_unexpected_iid(id);  break;
2269   }
2270   set_result(_gvn.transform(n));
2271   return true;
2272 }
2273 
2274 //--------------------------inline_bitshuffle_methods-----------------------------
2275 // inline int Integer.compress(int, int)
2276 // inline int Integer.expand(int, int)
2277 // inline long Long.compress(long, long)
2278 // inline long Long.expand(long, long)
2279 bool LibraryCallKit::inline_bitshuffle_methods(vmIntrinsics::ID id) {
2280   Node* n = nullptr;
2281   switch (id) {
2282     case vmIntrinsics::_compress_i:  n = new CompressBitsNode(argument(0), argument(1), TypeInt::INT); break;
2283     case vmIntrinsics::_expand_i:    n = new ExpandBitsNode(argument(0),  argument(1), TypeInt::INT); break;
2284     case vmIntrinsics::_compress_l:  n = new CompressBitsNode(argument(0), argument(2), TypeLong::LONG); break;
2285     case vmIntrinsics::_expand_l:    n = new ExpandBitsNode(argument(0), argument(2), TypeLong::LONG); break;
2286     default:  fatal_unexpected_iid(id);  break;
2287   }
2288   set_result(_gvn.transform(n));
2289   return true;
2290 }
2291 
2292 //--------------------------inline_number_methods-----------------------------
2293 // inline int Integer.compareUnsigned(int, int)
2294 // inline int    Long.compareUnsigned(long, long)
2295 bool LibraryCallKit::inline_compare_unsigned(vmIntrinsics::ID id) {
2296   Node* arg1 = argument(0);
2297   Node* arg2 = (id == vmIntrinsics::_compareUnsigned_l) ? argument(2) : argument(1);
2298   Node* n = nullptr;
2299   switch (id) {
2300     case vmIntrinsics::_compareUnsigned_i:   n = new CmpU3Node(arg1, arg2);  break;
2301     case vmIntrinsics::_compareUnsigned_l:   n = new CmpUL3Node(arg1, arg2); break;
2302     default:  fatal_unexpected_iid(id);  break;
2303   }
2304   set_result(_gvn.transform(n));
2305   return true;
2306 }
2307 
2308 //--------------------------inline_unsigned_divmod_methods-----------------------------
2309 // inline int Integer.divideUnsigned(int, int)
2310 // inline int Integer.remainderUnsigned(int, int)
2311 // inline long Long.divideUnsigned(long, long)
2312 // inline long Long.remainderUnsigned(long, long)
2313 bool LibraryCallKit::inline_divmod_methods(vmIntrinsics::ID id) {
2314   Node* n = nullptr;
2315   switch (id) {
2316     case vmIntrinsics::_divideUnsigned_i: {
2317       zero_check_int(argument(1));
2318       // Compile-time detect of null-exception
2319       if (stopped()) {
2320         return true; // keep the graph constructed so far
2321       }
2322       n = new UDivINode(control(), argument(0), argument(1));
2323       break;
2324     }
2325     case vmIntrinsics::_divideUnsigned_l: {
2326       zero_check_long(argument(2));
2327       // Compile-time detect of null-exception
2328       if (stopped()) {
2329         return true; // keep the graph constructed so far
2330       }
2331       n = new UDivLNode(control(), argument(0), argument(2));
2332       break;
2333     }
2334     case vmIntrinsics::_remainderUnsigned_i: {
2335       zero_check_int(argument(1));
2336       // Compile-time detect of null-exception
2337       if (stopped()) {
2338         return true; // keep the graph constructed so far
2339       }
2340       n = new UModINode(control(), argument(0), argument(1));
2341       break;
2342     }
2343     case vmIntrinsics::_remainderUnsigned_l: {
2344       zero_check_long(argument(2));
2345       // Compile-time detect of null-exception
2346       if (stopped()) {
2347         return true; // keep the graph constructed so far
2348       }
2349       n = new UModLNode(control(), argument(0), argument(2));
2350       break;
2351     }
2352     default:  fatal_unexpected_iid(id);  break;
2353   }
2354   set_result(_gvn.transform(n));
2355   return true;
2356 }
2357 
2358 //----------------------------inline_unsafe_access----------------------------
2359 
2360 const TypeOopPtr* LibraryCallKit::sharpen_unsafe_type(Compile::AliasType* alias_type, const TypePtr *adr_type) {
2361   // Attempt to infer a sharper value type from the offset and base type.
2362   ciKlass* sharpened_klass = nullptr;
2363   bool null_free = false;
2364 
2365   // See if it is an instance field, with an object type.
2366   if (alias_type->field() != nullptr) {
2367     if (alias_type->field()->type()->is_klass()) {
2368       sharpened_klass = alias_type->field()->type()->as_klass();
2369       null_free = alias_type->field()->is_null_free();
2370     }
2371   }
2372 
2373   const TypeOopPtr* result = nullptr;
2374   // See if it is a narrow oop array.
2375   if (adr_type->isa_aryptr()) {
2376     if (adr_type->offset() >= refArrayOopDesc::base_offset_in_bytes()) {
2377       const TypeOopPtr* elem_type = adr_type->is_aryptr()->elem()->make_oopptr();
2378       null_free = adr_type->is_aryptr()->is_null_free();
2379       if (elem_type != nullptr && elem_type->is_loaded()) {
2380         // Sharpen the value type.
2381         result = elem_type;
2382       }
2383     }
2384   }
2385 
2386   // The sharpened class might be unloaded if there is no class loader
2387   // contraint in place.
2388   if (result == nullptr && sharpened_klass != nullptr && sharpened_klass->is_loaded()) {
2389     // Sharpen the value type.
2390     result = TypeOopPtr::make_from_klass(sharpened_klass);
2391     if (null_free) {
2392       result = result->join_speculative(TypePtr::NOTNULL)->is_oopptr();
2393     }
2394   }
2395   if (result != nullptr) {
2396 #ifndef PRODUCT
2397     if (C->print_intrinsics() || C->print_inlining()) {
2398       tty->print("  from base type:  ");  adr_type->dump(); tty->cr();
2399       tty->print("  sharpened value: ");  result->dump();    tty->cr();
2400     }
2401 #endif
2402   }
2403   return result;
2404 }
2405 
2406 DecoratorSet LibraryCallKit::mo_decorator_for_access_kind(AccessKind kind) {
2407   switch (kind) {
2408       case Relaxed:
2409         return MO_UNORDERED;
2410       case Opaque:
2411         return MO_RELAXED;
2412       case Acquire:
2413         return MO_ACQUIRE;
2414       case Release:
2415         return MO_RELEASE;
2416       case Volatile:
2417         return MO_SEQ_CST;
2418       default:
2419         ShouldNotReachHere();
2420         return 0;
2421   }
2422 }
2423 
2424 LibraryCallKit::SavedState::SavedState(LibraryCallKit* kit) :
2425   _kit(kit),
2426   _sp(kit->sp()),
2427   _jvms(kit->jvms()),
2428   _map(kit->clone_map()),
2429   _discarded(false)
2430 {
2431   for (DUIterator_Fast imax, i = kit->control()->fast_outs(imax); i < imax; i++) {
2432     Node* out = kit->control()->fast_out(i);
2433     if (out->is_CFG()) {
2434       _ctrl_succ.push(out);
2435     }
2436   }
2437 }
2438 
2439 LibraryCallKit::SavedState::~SavedState() {
2440   if (_discarded) {
2441     _kit->destruct_map_clone(_map);
2442     return;
2443   }
2444   _kit->jvms()->set_map(_map);
2445   _kit->jvms()->set_sp(_sp);
2446   _map->set_jvms(_kit->jvms());
2447   _kit->set_map(_map);
2448   _kit->set_sp(_sp);
2449   for (DUIterator_Fast imax, i = _kit->control()->fast_outs(imax); i < imax; i++) {
2450     Node* out = _kit->control()->fast_out(i);
2451     if (out->is_CFG() && out->in(0) == _kit->control() && out != _kit->map() && !_ctrl_succ.member(out)) {
2452       _kit->_gvn.hash_delete(out);
2453       out->set_req(0, _kit->C->top());
2454       _kit->C->record_for_igvn(out);
2455       --i; --imax;
2456       _kit->_gvn.hash_find_insert(out);
2457     }
2458   }
2459 }
2460 
2461 void LibraryCallKit::SavedState::discard() {
2462   _discarded = true;
2463 }
2464 
2465 bool LibraryCallKit::inline_unsafe_access(bool is_store, const BasicType type, const AccessKind kind, const bool unaligned, const bool is_flat) {
2466   if (callee()->is_static())  return false;  // caller must have the capability!
2467   DecoratorSet decorators = C2_UNSAFE_ACCESS;
2468   guarantee(!is_store || kind != Acquire, "Acquire accesses can be produced only for loads");
2469   guarantee( is_store || kind != Release, "Release accesses can be produced only for stores");
2470   assert(type != T_OBJECT || !unaligned, "unaligned access not supported with object type");
2471 
2472   if (is_reference_type(type)) {
2473     decorators |= ON_UNKNOWN_OOP_REF;
2474   }
2475 
2476   if (unaligned) {
2477     decorators |= C2_UNALIGNED;
2478   }
2479 
2480 #ifndef PRODUCT
2481   {
2482     ResourceMark rm;
2483     // Check the signatures.
2484     ciSignature* sig = callee()->signature();
2485 #ifdef ASSERT
2486     if (!is_store) {
2487       // Object getReference(Object base, int/long offset), etc.
2488       BasicType rtype = sig->return_type()->basic_type();
2489       assert(rtype == type, "getter must return the expected value");
2490       assert(sig->count() == 2 || (is_flat && sig->count() == 3), "oop getter has 2 or 3 arguments");
2491       assert(sig->type_at(0)->basic_type() == T_OBJECT, "getter base is object");
2492       assert(sig->type_at(1)->basic_type() == T_LONG, "getter offset is correct");
2493     } else {
2494       // void putReference(Object base, int/long offset, Object x), etc.
2495       assert(sig->return_type()->basic_type() == T_VOID, "putter must not return a value");
2496       assert(sig->count() == 3 || (is_flat && sig->count() == 4), "oop putter has 3 arguments");
2497       assert(sig->type_at(0)->basic_type() == T_OBJECT, "putter base is object");
2498       assert(sig->type_at(1)->basic_type() == T_LONG, "putter offset is correct");
2499       BasicType vtype = sig->type_at(sig->count()-1)->basic_type();
2500       assert(vtype == type, "putter must accept the expected value");
2501     }
2502 #endif // ASSERT
2503  }
2504 #endif //PRODUCT
2505 
2506   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
2507 
2508   Node* receiver = argument(0);  // type: oop
2509 
2510   // Build address expression.
2511   Node* heap_base_oop = top();
2512 
2513   // The base is either a Java object or a value produced by Unsafe.staticFieldBase
2514   Node* base = argument(1);  // type: oop
2515   // The offset is a value produced by Unsafe.staticFieldOffset or Unsafe.objectFieldOffset
2516   Node* offset = argument(2);  // type: long
2517   // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
2518   // to be plain byte offsets, which are also the same as those accepted
2519   // by oopDesc::field_addr.
2520   assert(Unsafe_field_offset_to_byte_offset(11) == 11,
2521          "fieldOffset must be byte-scaled");
2522 
2523   ciInlineKlass* inline_klass = nullptr;
2524   if (is_flat) {
2525     const TypeInstPtr* cls = _gvn.type(argument(4))->isa_instptr();
2526     if (cls == nullptr || cls->const_oop() == nullptr) {
2527       return false;
2528     }
2529     ciType* mirror_type = cls->const_oop()->as_instance()->java_mirror_type();
2530     if (!mirror_type->is_inlinetype()) {
2531       return false;
2532     }
2533     inline_klass = mirror_type->as_inline_klass();
2534   }
2535 
2536   if (base->is_InlineType()) {
2537     assert(!is_store, "InlineTypeNodes are non-larval value objects");
2538     InlineTypeNode* vt = base->as_InlineType();
2539     if (offset->is_Con()) {
2540       long off = find_long_con(offset, 0);
2541       ciInlineKlass* vk = vt->type()->inline_klass();
2542       if ((long)(int)off != off || !vk->contains_field_offset(off)) {
2543         return false;
2544       }
2545 
2546       ciField* field = vk->get_non_flat_field_by_offset(off);
2547       if (field != nullptr) {
2548         BasicType bt = type2field[field->type()->basic_type()];
2549         if (bt == T_ARRAY || bt == T_NARROWOOP) {
2550           bt = T_OBJECT;
2551         }
2552         if (bt == type && (!field->is_flat() || field->type() == inline_klass)) {
2553           Node* value = vt->field_value_by_offset(off, false);
2554           if (value->is_InlineType()) {
2555             value = value->as_InlineType()->adjust_scalarization_depth(this);
2556           }
2557           set_result(value);
2558           return true;
2559         }
2560       }
2561     }
2562     {
2563       // Re-execute the unsafe access if allocation triggers deoptimization.
2564       PreserveReexecuteState preexecs(this);
2565       jvms()->set_should_reexecute(true);
2566       vt = vt->buffer(this);
2567     }
2568     base = vt->get_oop();
2569   }
2570 
2571   // 32-bit machines ignore the high half!
2572   offset = ConvL2X(offset);
2573 
2574   // Save state and restore on bailout
2575   SavedState old_state(this);
2576 
2577   Node* adr = make_unsafe_address(base, offset, type, kind == Relaxed);
2578   assert(!stopped(), "Inlining of unsafe access failed: address construction stopped unexpectedly");
2579 
2580   if (_gvn.type(base->uncast())->isa_ptr() == TypePtr::NULL_PTR) {
2581     if (type != T_OBJECT && (inline_klass == nullptr || !inline_klass->has_object_fields())) {
2582       decorators |= IN_NATIVE; // off-heap primitive access
2583     } else {
2584       return false; // off-heap oop accesses are not supported
2585     }
2586   } else {
2587     heap_base_oop = base; // on-heap or mixed access
2588   }
2589 
2590   // Can base be null? Otherwise, always on-heap access.
2591   bool can_access_non_heap = TypePtr::NULL_PTR->higher_equal(_gvn.type(base));
2592 
2593   if (!can_access_non_heap) {
2594     decorators |= IN_HEAP;
2595   }
2596 
2597   Node* val = is_store ? argument(4 + (is_flat ? 1 : 0)) : nullptr;
2598 
2599   const TypePtr* adr_type = _gvn.type(adr)->isa_ptr();
2600   if (adr_type == TypePtr::NULL_PTR) {
2601     return false; // off-heap access with zero address
2602   }
2603 
2604   // Try to categorize the address.
2605   Compile::AliasType* alias_type = C->alias_type(adr_type);
2606   assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
2607 
2608   if (alias_type->adr_type() == TypeInstPtr::KLASS ||
2609       alias_type->adr_type() == TypeAryPtr::RANGE) {
2610     return false; // not supported
2611   }
2612 
2613   bool mismatched = false;
2614   BasicType bt = T_ILLEGAL;
2615   ciField* field = nullptr;
2616   if (adr_type->isa_instptr()) {
2617     const TypeInstPtr* instptr = adr_type->is_instptr();
2618     ciInstanceKlass* k = instptr->instance_klass();
2619     int off = instptr->offset();
2620     if (instptr->const_oop() != nullptr &&
2621         k == ciEnv::current()->Class_klass() &&
2622         instptr->offset() >= (k->size_helper() * wordSize)) {
2623       k = instptr->const_oop()->as_instance()->java_lang_Class_klass()->as_instance_klass();
2624       field = k->get_field_by_offset(off, true);
2625     } else {
2626       field = k->get_non_flat_field_by_offset(off);
2627     }
2628     if (field != nullptr) {
2629       bt = type2field[field->type()->basic_type()];
2630     }
2631     if (bt != alias_type->basic_type()) {
2632       // Type mismatch. Is it an access to a nested flat field?
2633       field = k->get_field_by_offset(off, false);
2634       if (field != nullptr) {
2635         bt = type2field[field->type()->basic_type()];
2636       }
2637     }
2638     assert(bt == alias_type->basic_type() || is_flat, "should match");
2639   } else {
2640     bt = alias_type->basic_type();
2641   }
2642 
2643   if (bt != T_ILLEGAL) {
2644     assert(alias_type->adr_type()->is_oopptr(), "should be on-heap access");
2645     if (bt == T_BYTE && adr_type->isa_aryptr()) {
2646       // Alias type doesn't differentiate between byte[] and boolean[]).
2647       // Use address type to get the element type.
2648       bt = adr_type->is_aryptr()->elem()->array_element_basic_type();
2649     }
2650     if (is_reference_type(bt, true)) {
2651       // accessing an array field with getReference is not a mismatch
2652       bt = T_OBJECT;
2653     }
2654     if ((bt == T_OBJECT) != (type == T_OBJECT)) {
2655       // Don't intrinsify mismatched object accesses
2656       return false;
2657     }
2658     mismatched = (bt != type);
2659   } else if (alias_type->adr_type()->isa_oopptr()) {
2660     mismatched = true; // conservatively mark all "wide" on-heap accesses as mismatched
2661   }
2662 
2663   if (is_flat) {
2664     if (adr_type->isa_instptr()) {
2665       if (field == nullptr || field->type() != inline_klass) {
2666         mismatched = true;
2667       }
2668     } else if (adr_type->isa_aryptr()) {
2669       const Type* elem = adr_type->is_aryptr()->elem();
2670       if (!adr_type->is_flat() || elem->inline_klass() != inline_klass) {
2671         mismatched = true;
2672       }
2673     } else {
2674       mismatched = true;
2675     }
2676     if (is_store) {
2677       const Type* val_t = _gvn.type(val);
2678       if (!val_t->is_inlinetypeptr() || val_t->inline_klass() != inline_klass) {
2679         return false;
2680       }
2681     }
2682   }
2683 
2684   old_state.discard();
2685   assert(!mismatched || alias_type->adr_type()->is_oopptr(), "off-heap access can't be mismatched");
2686 
2687   if (mismatched) {
2688     decorators |= C2_MISMATCHED;
2689   }
2690 
2691   // First guess at the value type.
2692   const Type *value_type = Type::get_const_basic_type(type);
2693 
2694   // Figure out the memory ordering.
2695   decorators |= mo_decorator_for_access_kind(kind);
2696 
2697   if (!is_store) {
2698     if (type == T_OBJECT && !is_flat) {
2699       const TypeOopPtr* tjp = sharpen_unsafe_type(alias_type, adr_type);
2700       if (tjp != nullptr) {
2701         value_type = tjp;
2702       }
2703     }
2704   }
2705 
2706   receiver = null_check(receiver);
2707   if (stopped()) {
2708     return true;
2709   }
2710   // Heap pointers get a null-check from the interpreter,
2711   // as a courtesy.  However, this is not guaranteed by Unsafe,
2712   // and it is not possible to fully distinguish unintended nulls
2713   // from intended ones in this API.
2714 
2715   if (!is_store) {
2716     Node* p = nullptr;
2717     // Try to constant fold a load from a constant field
2718 
2719     if (heap_base_oop != top() && field != nullptr && field->is_constant() && !field->is_flat() && !mismatched) {
2720       // final or stable field
2721       p = make_constant_from_field(field, heap_base_oop);
2722     }
2723 
2724     if (p == nullptr) { // Could not constant fold the load
2725       if (is_flat) {
2726         p = InlineTypeNode::make_from_flat(this, inline_klass, base, adr, adr_type, false, false, true);
2727       } else {
2728         p = access_load_at(heap_base_oop, adr, adr_type, value_type, type, decorators);
2729         const TypeOopPtr* ptr = value_type->make_oopptr();
2730         if (ptr != nullptr && ptr->is_inlinetypeptr()) {
2731           // Load a non-flattened inline type from memory
2732           p = InlineTypeNode::make_from_oop(this, p, ptr->inline_klass());
2733         }
2734       }
2735       // Normalize the value returned by getBoolean in the following cases
2736       if (type == T_BOOLEAN &&
2737           (mismatched ||
2738            heap_base_oop == top() ||                  // - heap_base_oop is null or
2739            (can_access_non_heap && field == nullptr)) // - heap_base_oop is potentially null
2740                                                       //   and the unsafe access is made to large offset
2741                                                       //   (i.e., larger than the maximum offset necessary for any
2742                                                       //   field access)
2743             ) {
2744           IdealKit ideal = IdealKit(this);
2745 #define __ ideal.
2746           IdealVariable normalized_result(ideal);
2747           __ declarations_done();
2748           __ set(normalized_result, p);
2749           __ if_then(p, BoolTest::ne, ideal.ConI(0));
2750           __ set(normalized_result, ideal.ConI(1));
2751           ideal.end_if();
2752           final_sync(ideal);
2753           p = __ value(normalized_result);
2754 #undef __
2755       }
2756     }
2757     if (type == T_ADDRESS) {
2758       p = gvn().transform(new CastP2XNode(nullptr, p));
2759       p = ConvX2UL(p);
2760     }
2761     // The load node has the control of the preceding MemBarCPUOrder.  All
2762     // following nodes will have the control of the MemBarCPUOrder inserted at
2763     // the end of this method.  So, pushing the load onto the stack at a later
2764     // point is fine.
2765     set_result(p);
2766   } else {
2767     if (bt == T_ADDRESS) {
2768       // Repackage the long as a pointer.
2769       val = ConvL2X(val);
2770       val = gvn().transform(new CastX2PNode(val));
2771     }
2772     if (is_flat) {
2773       val->as_InlineType()->store_flat(this, base, adr, false, false, true, decorators);
2774     } else {
2775       access_store_at(heap_base_oop, adr, adr_type, val, value_type, type, decorators);
2776     }
2777   }
2778 
2779   return true;
2780 }
2781 
2782 bool LibraryCallKit::inline_unsafe_flat_access(bool is_store, AccessKind kind) {
2783 #ifdef ASSERT
2784   {
2785     ResourceMark rm;
2786     // Check the signatures.
2787     ciSignature* sig = callee()->signature();
2788     assert(sig->type_at(0)->basic_type() == T_OBJECT, "base should be object, but is %s", type2name(sig->type_at(0)->basic_type()));
2789     assert(sig->type_at(1)->basic_type() == T_LONG, "offset should be long, but is %s", type2name(sig->type_at(1)->basic_type()));
2790     assert(sig->type_at(2)->basic_type() == T_INT, "layout kind should be int, but is %s", type2name(sig->type_at(3)->basic_type()));
2791     assert(sig->type_at(3)->basic_type() == T_OBJECT, "value klass should be object, but is %s", type2name(sig->type_at(4)->basic_type()));
2792     if (is_store) {
2793       assert(sig->return_type()->basic_type() == T_VOID, "putter must not return a value, but returns %s", type2name(sig->return_type()->basic_type()));
2794       assert(sig->count() == 5, "flat putter should have 5 arguments, but has %d", sig->count());
2795       assert(sig->type_at(4)->basic_type() == T_OBJECT, "put value should be object, but is %s", type2name(sig->type_at(5)->basic_type()));
2796     } else {
2797       assert(sig->return_type()->basic_type() == T_OBJECT, "getter must return an object, but returns %s", type2name(sig->return_type()->basic_type()));
2798       assert(sig->count() == 4, "flat getter should have 4 arguments, but has %d", sig->count());
2799     }
2800  }
2801 #endif // ASSERT
2802 
2803   assert(kind == Relaxed, "Only plain accesses for now");
2804   if (callee()->is_static()) {
2805     // caller must have the capability!
2806     return false;
2807   }
2808   C->set_has_unsafe_access(true);
2809 
2810   const TypeInstPtr* value_klass_node = _gvn.type(argument(5))->isa_instptr();
2811   if (value_klass_node == nullptr || value_klass_node->const_oop() == nullptr) {
2812     // parameter valueType is not a constant
2813     return false;
2814   }
2815   ciType* mirror_type = value_klass_node->const_oop()->as_instance()->java_mirror_type();
2816   if (!mirror_type->is_inlinetype()) {
2817     // Dead code
2818     return false;
2819   }
2820   ciInlineKlass* value_klass = mirror_type->as_inline_klass();
2821 
2822   const TypeInt* layout_type = _gvn.type(argument(4))->isa_int();
2823   if (layout_type == nullptr || !layout_type->is_con()) {
2824     // parameter layoutKind is not a constant
2825     return false;
2826   }
2827   assert(layout_type->get_con() >= static_cast<int>(LayoutKind::REFERENCE) &&
2828          layout_type->get_con() <= static_cast<int>(LayoutKind::UNKNOWN),
2829          "invalid layoutKind %d", layout_type->get_con());
2830   LayoutKind layout = static_cast<LayoutKind>(layout_type->get_con());
2831   assert(layout == LayoutKind::REFERENCE || layout == LayoutKind::NON_ATOMIC_FLAT ||
2832          layout == LayoutKind::ATOMIC_FLAT || layout == LayoutKind::NULLABLE_ATOMIC_FLAT,
2833          "unexpected layoutKind %d", layout_type->get_con());
2834 
2835   null_check(argument(0));
2836   if (stopped()) {
2837     return true;
2838   }
2839 
2840   Node* base = must_be_not_null(argument(1), true);
2841   Node* offset = argument(2);
2842   const Type* base_type = _gvn.type(base);
2843 
2844   Node* ptr;
2845   bool immutable_memory = false;
2846   DecoratorSet decorators = C2_UNSAFE_ACCESS | IN_HEAP | MO_UNORDERED;
2847   if (base_type->isa_instptr()) {
2848     const TypeLong* offset_type = _gvn.type(offset)->isa_long();
2849     if (offset_type == nullptr || !offset_type->is_con()) {
2850       // Offset into a non-array should be a constant
2851       decorators |= C2_MISMATCHED;
2852     } else {
2853       int offset_con = checked_cast<int>(offset_type->get_con());
2854       ciInstanceKlass* base_klass = base_type->is_instptr()->instance_klass();
2855       ciField* field = base_klass->get_non_flat_field_by_offset(offset_con);
2856       if (field == nullptr) {
2857         assert(!base_klass->is_final(), "non-existence field at offset %d of class %s", offset_con, base_klass->name()->as_utf8());
2858         decorators |= C2_MISMATCHED;
2859       } else {
2860         assert(field->type() == value_klass, "field at offset %d of %s is of type %s, but valueType is %s",
2861                offset_con, base_klass->name()->as_utf8(), field->type()->name(), value_klass->name()->as_utf8());
2862         immutable_memory = field->is_strict() && field->is_final();
2863 
2864         if (base->is_InlineType()) {
2865           assert(!is_store, "Cannot store into a non-larval value object");
2866           set_result(base->as_InlineType()->field_value_by_offset(offset_con, false));
2867           return true;
2868         }
2869       }
2870     }
2871 
2872     if (base->is_InlineType()) {
2873       assert(!is_store, "Cannot store into a non-larval value object");
2874       base = base->as_InlineType()->buffer(this, true);
2875     }
2876     ptr = basic_plus_adr(base, ConvL2X(offset));
2877   } else if (base_type->isa_aryptr()) {
2878     decorators |= IS_ARRAY;
2879     if (layout == LayoutKind::REFERENCE) {
2880       if (!base_type->is_aryptr()->is_not_flat()) {
2881         const TypeAryPtr* array_type = base_type->is_aryptr()->cast_to_not_flat();
2882         Node* new_base = _gvn.transform(new CastPPNode(control(), base, array_type, ConstraintCastNode::StrongDependency));
2883         replace_in_map(base, new_base);
2884         base = new_base;
2885       }
2886       ptr = basic_plus_adr(base, ConvL2X(offset));
2887     } else {
2888       if (UseArrayFlattening) {
2889         // Flat array must have an exact type
2890         bool is_null_free = !LayoutKindHelper::is_nullable_flat(layout);
2891         bool is_atomic = LayoutKindHelper::is_atomic_flat(layout);
2892         Node* new_base = cast_to_flat_array(base, value_klass, is_null_free, !is_null_free, is_atomic);
2893         replace_in_map(base, new_base);
2894         base = new_base;
2895         ptr = basic_plus_adr(base, ConvL2X(offset));
2896         const TypeAryPtr* ptr_type = _gvn.type(ptr)->is_aryptr();
2897         if (ptr_type->field_offset().get() != 0) {
2898           ptr = _gvn.transform(new CastPPNode(control(), ptr, ptr_type->with_field_offset(0), ConstraintCastNode::StrongDependency));
2899         }
2900       } else {
2901         uncommon_trap(Deoptimization::Reason_intrinsic,
2902                       Deoptimization::Action_none);
2903         return true;
2904       }
2905     }
2906   } else {
2907     decorators |= C2_MISMATCHED;
2908     ptr = basic_plus_adr(base, ConvL2X(offset));
2909   }
2910 
2911   if (is_store) {
2912     Node* value = argument(6);
2913     const Type* value_type = _gvn.type(value);
2914     if (!value_type->is_inlinetypeptr()) {
2915       value_type = Type::get_const_type(value_klass)->filter_speculative(value_type);
2916       Node* new_value = _gvn.transform(new CastPPNode(control(), value, value_type, ConstraintCastNode::StrongDependency));
2917       new_value = InlineTypeNode::make_from_oop(this, new_value, value_klass);
2918       replace_in_map(value, new_value);
2919       value = new_value;
2920     }
2921 
2922     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());
2923     if (layout == LayoutKind::REFERENCE) {
2924       const TypePtr* ptr_type = (decorators & C2_MISMATCHED) != 0 ? TypeRawPtr::BOTTOM : _gvn.type(ptr)->is_ptr();
2925       access_store_at(base, ptr, ptr_type, value, value_type, T_OBJECT, decorators);
2926     } else {
2927       bool atomic = LayoutKindHelper::is_atomic_flat(layout);
2928       bool null_free = !LayoutKindHelper::is_nullable_flat(layout);
2929       value->as_InlineType()->store_flat(this, base, ptr, atomic, immutable_memory, null_free, decorators);
2930     }
2931 
2932     return true;
2933   } else {
2934     decorators |= (C2_CONTROL_DEPENDENT_LOAD | C2_UNKNOWN_CONTROL_LOAD);
2935     InlineTypeNode* result;
2936     if (layout == LayoutKind::REFERENCE) {
2937       const TypePtr* ptr_type = (decorators & C2_MISMATCHED) != 0 ? TypeRawPtr::BOTTOM : _gvn.type(ptr)->is_ptr();
2938       Node* oop = access_load_at(base, ptr, ptr_type, Type::get_const_type(value_klass), T_OBJECT, decorators);
2939       result = InlineTypeNode::make_from_oop(this, oop, value_klass);
2940     } else {
2941       bool atomic = LayoutKindHelper::is_atomic_flat(layout);
2942       bool null_free = !LayoutKindHelper::is_nullable_flat(layout);
2943       result = InlineTypeNode::make_from_flat(this, value_klass, base, ptr, atomic, immutable_memory, null_free, decorators);
2944     }
2945 
2946     set_result(result);
2947     return true;
2948   }
2949 }
2950 
2951 bool LibraryCallKit::inline_unsafe_make_private_buffer() {
2952   Node* receiver = argument(0);
2953   Node* value = argument(1);
2954 
2955   const Type* type = gvn().type(value);
2956   if (!type->is_inlinetypeptr()) {
2957     C->record_method_not_compilable("value passed to Unsafe::makePrivateBuffer is not of a constant value type");
2958     return false;
2959   }
2960 
2961   null_check(receiver);
2962   if (stopped()) {
2963     return true;
2964   }
2965 
2966   value = null_check(value);
2967   if (stopped()) {
2968     return true;
2969   }
2970 
2971   ciInlineKlass* vk = type->inline_klass();
2972   Node* klass = makecon(TypeKlassPtr::make(vk));
2973   Node* obj = new_instance(klass);
2974   AllocateNode::Ideal_allocation(obj)->_larval = true;
2975 
2976   assert(value->is_InlineType(), "must be an InlineTypeNode");
2977   Node* payload_ptr = basic_plus_adr(obj, vk->payload_offset());
2978   value->as_InlineType()->store_flat(this, obj, payload_ptr, false, true, true, IN_HEAP | MO_UNORDERED);
2979 
2980   set_result(obj);
2981   return true;
2982 }
2983 
2984 bool LibraryCallKit::inline_unsafe_finish_private_buffer() {
2985   Node* receiver = argument(0);
2986   Node* buffer = argument(1);
2987 
2988   const Type* type = gvn().type(buffer);
2989   if (!type->is_inlinetypeptr()) {
2990     C->record_method_not_compilable("value passed to Unsafe::finishPrivateBuffer is not of a constant value type");
2991     return false;
2992   }
2993 
2994   AllocateNode* alloc = AllocateNode::Ideal_allocation(buffer);
2995   if (alloc == nullptr) {
2996     C->record_method_not_compilable("value passed to Unsafe::finishPrivateBuffer must be allocated by Unsafe::makePrivateBuffer");
2997     return false;
2998   }
2999 
3000   null_check(receiver);
3001   if (stopped()) {
3002     return true;
3003   }
3004 
3005   // Unset the larval bit in the object header
3006   Node* old_header = make_load(control(), buffer, TypeX_X, TypeX_X->basic_type(), MemNode::unordered, LoadNode::Pinned);
3007   Node* new_header = gvn().transform(new AndXNode(old_header, MakeConX(~markWord::larval_bit_in_place)));
3008   access_store_at(buffer, buffer, type->is_ptr(), new_header, TypeX_X, TypeX_X->basic_type(), MO_UNORDERED | IN_HEAP);
3009 
3010   // We must ensure that the buffer is properly published
3011   insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out(AllocateNode::RawAddress));
3012   assert(!type->maybe_null(), "result of an allocation should not be null");
3013   set_result(InlineTypeNode::make_from_oop(this, buffer, type->inline_klass()));
3014   return true;
3015 }
3016 
3017 //----------------------------inline_unsafe_load_store----------------------------
3018 // This method serves a couple of different customers (depending on LoadStoreKind):
3019 //
3020 // LS_cmp_swap:
3021 //
3022 //   boolean compareAndSetReference(Object o, long offset, Object expected, Object x);
3023 //   boolean compareAndSetInt(   Object o, long offset, int    expected, int    x);
3024 //   boolean compareAndSetLong(  Object o, long offset, long   expected, long   x);
3025 //
3026 // LS_cmp_swap_weak:
3027 //
3028 //   boolean weakCompareAndSetReference(       Object o, long offset, Object expected, Object x);
3029 //   boolean weakCompareAndSetReferencePlain(  Object o, long offset, Object expected, Object x);
3030 //   boolean weakCompareAndSetReferenceAcquire(Object o, long offset, Object expected, Object x);
3031 //   boolean weakCompareAndSetReferenceRelease(Object o, long offset, Object expected, Object x);
3032 //
3033 //   boolean weakCompareAndSetInt(          Object o, long offset, int    expected, int    x);
3034 //   boolean weakCompareAndSetIntPlain(     Object o, long offset, int    expected, int    x);
3035 //   boolean weakCompareAndSetIntAcquire(   Object o, long offset, int    expected, int    x);
3036 //   boolean weakCompareAndSetIntRelease(   Object o, long offset, int    expected, int    x);
3037 //
3038 //   boolean weakCompareAndSetLong(         Object o, long offset, long   expected, long   x);
3039 //   boolean weakCompareAndSetLongPlain(    Object o, long offset, long   expected, long   x);
3040 //   boolean weakCompareAndSetLongAcquire(  Object o, long offset, long   expected, long   x);
3041 //   boolean weakCompareAndSetLongRelease(  Object o, long offset, long   expected, long   x);
3042 //
3043 // LS_cmp_exchange:
3044 //
3045 //   Object compareAndExchangeReferenceVolatile(Object o, long offset, Object expected, Object x);
3046 //   Object compareAndExchangeReferenceAcquire( Object o, long offset, Object expected, Object x);
3047 //   Object compareAndExchangeReferenceRelease( Object o, long offset, Object expected, Object x);
3048 //
3049 //   Object compareAndExchangeIntVolatile(   Object o, long offset, Object expected, Object x);
3050 //   Object compareAndExchangeIntAcquire(    Object o, long offset, Object expected, Object x);
3051 //   Object compareAndExchangeIntRelease(    Object o, long offset, Object expected, Object x);
3052 //
3053 //   Object compareAndExchangeLongVolatile(  Object o, long offset, Object expected, Object x);
3054 //   Object compareAndExchangeLongAcquire(   Object o, long offset, Object expected, Object x);
3055 //   Object compareAndExchangeLongRelease(   Object o, long offset, Object expected, Object x);
3056 //
3057 // LS_get_add:
3058 //
3059 //   int  getAndAddInt( Object o, long offset, int  delta)
3060 //   long getAndAddLong(Object o, long offset, long delta)
3061 //
3062 // LS_get_set:
3063 //
3064 //   int    getAndSet(Object o, long offset, int    newValue)
3065 //   long   getAndSet(Object o, long offset, long   newValue)
3066 //   Object getAndSet(Object o, long offset, Object newValue)
3067 //
3068 bool LibraryCallKit::inline_unsafe_load_store(const BasicType type, const LoadStoreKind kind, const AccessKind access_kind) {
3069   // This basic scheme here is the same as inline_unsafe_access, but
3070   // differs in enough details that combining them would make the code
3071   // overly confusing.  (This is a true fact! I originally combined
3072   // them, but even I was confused by it!) As much code/comments as
3073   // possible are retained from inline_unsafe_access though to make
3074   // the correspondences clearer. - dl
3075 
3076   if (callee()->is_static())  return false;  // caller must have the capability!
3077 
3078   DecoratorSet decorators = C2_UNSAFE_ACCESS;
3079   decorators |= mo_decorator_for_access_kind(access_kind);
3080 
3081 #ifndef PRODUCT
3082   BasicType rtype;
3083   {
3084     ResourceMark rm;
3085     // Check the signatures.
3086     ciSignature* sig = callee()->signature();
3087     rtype = sig->return_type()->basic_type();
3088     switch(kind) {
3089       case LS_get_add:
3090       case LS_get_set: {
3091       // Check the signatures.
3092 #ifdef ASSERT
3093       assert(rtype == type, "get and set must return the expected type");
3094       assert(sig->count() == 3, "get and set has 3 arguments");
3095       assert(sig->type_at(0)->basic_type() == T_OBJECT, "get and set base is object");
3096       assert(sig->type_at(1)->basic_type() == T_LONG, "get and set offset is long");
3097       assert(sig->type_at(2)->basic_type() == type, "get and set must take expected type as new value/delta");
3098       assert(access_kind == Volatile, "mo is not passed to intrinsic nodes in current implementation");
3099 #endif // ASSERT
3100         break;
3101       }
3102       case LS_cmp_swap:
3103       case LS_cmp_swap_weak: {
3104       // Check the signatures.
3105 #ifdef ASSERT
3106       assert(rtype == T_BOOLEAN, "CAS must return boolean");
3107       assert(sig->count() == 4, "CAS has 4 arguments");
3108       assert(sig->type_at(0)->basic_type() == T_OBJECT, "CAS base is object");
3109       assert(sig->type_at(1)->basic_type() == T_LONG, "CAS offset is long");
3110 #endif // ASSERT
3111         break;
3112       }
3113       case LS_cmp_exchange: {
3114       // Check the signatures.
3115 #ifdef ASSERT
3116       assert(rtype == type, "CAS must return the expected type");
3117       assert(sig->count() == 4, "CAS has 4 arguments");
3118       assert(sig->type_at(0)->basic_type() == T_OBJECT, "CAS base is object");
3119       assert(sig->type_at(1)->basic_type() == T_LONG, "CAS offset is long");
3120 #endif // ASSERT
3121         break;
3122       }
3123       default:
3124         ShouldNotReachHere();
3125     }
3126   }
3127 #endif //PRODUCT
3128 
3129   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
3130 
3131   // Get arguments:
3132   Node* receiver = nullptr;
3133   Node* base     = nullptr;
3134   Node* offset   = nullptr;
3135   Node* oldval   = nullptr;
3136   Node* newval   = nullptr;
3137   switch(kind) {
3138     case LS_cmp_swap:
3139     case LS_cmp_swap_weak:
3140     case LS_cmp_exchange: {
3141       const bool two_slot_type = type2size[type] == 2;
3142       receiver = argument(0);  // type: oop
3143       base     = argument(1);  // type: oop
3144       offset   = argument(2);  // type: long
3145       oldval   = argument(4);  // type: oop, int, or long
3146       newval   = argument(two_slot_type ? 6 : 5);  // type: oop, int, or long
3147       break;
3148     }
3149     case LS_get_add:
3150     case LS_get_set: {
3151       receiver = argument(0);  // type: oop
3152       base     = argument(1);  // type: oop
3153       offset   = argument(2);  // type: long
3154       oldval   = nullptr;
3155       newval   = argument(4);  // type: oop, int, or long
3156       break;
3157     }
3158     default:
3159       ShouldNotReachHere();
3160   }
3161 
3162   // Build field offset expression.
3163   // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
3164   // to be plain byte offsets, which are also the same as those accepted
3165   // by oopDesc::field_addr.
3166   assert(Unsafe_field_offset_to_byte_offset(11) == 11, "fieldOffset must be byte-scaled");
3167   // 32-bit machines ignore the high half of long offsets
3168   offset = ConvL2X(offset);
3169   // Save state and restore on bailout
3170   SavedState old_state(this);
3171   Node* adr = make_unsafe_address(base, offset,type, false);
3172   const TypePtr *adr_type = _gvn.type(adr)->isa_ptr();
3173 
3174   Compile::AliasType* alias_type = C->alias_type(adr_type);
3175   BasicType bt = alias_type->basic_type();
3176   if (bt != T_ILLEGAL &&
3177       (is_reference_type(bt) != (type == T_OBJECT))) {
3178     // Don't intrinsify mismatched object accesses.
3179     return false;
3180   }
3181 
3182   old_state.discard();
3183 
3184   // For CAS, unlike inline_unsafe_access, there seems no point in
3185   // trying to refine types. Just use the coarse types here.
3186   assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
3187   const Type *value_type = Type::get_const_basic_type(type);
3188 
3189   switch (kind) {
3190     case LS_get_set:
3191     case LS_cmp_exchange: {
3192       if (type == T_OBJECT) {
3193         const TypeOopPtr* tjp = sharpen_unsafe_type(alias_type, adr_type);
3194         if (tjp != nullptr) {
3195           value_type = tjp;
3196         }
3197       }
3198       break;
3199     }
3200     case LS_cmp_swap:
3201     case LS_cmp_swap_weak:
3202     case LS_get_add:
3203       break;
3204     default:
3205       ShouldNotReachHere();
3206   }
3207 
3208   // Null check receiver.
3209   receiver = null_check(receiver);
3210   if (stopped()) {
3211     return true;
3212   }
3213 
3214   int alias_idx = C->get_alias_index(adr_type);
3215 
3216   if (is_reference_type(type)) {
3217     decorators |= IN_HEAP | ON_UNKNOWN_OOP_REF;
3218 
3219     if (oldval != nullptr && oldval->is_InlineType()) {
3220       // Re-execute the unsafe access if allocation triggers deoptimization.
3221       PreserveReexecuteState preexecs(this);
3222       jvms()->set_should_reexecute(true);
3223       oldval = oldval->as_InlineType()->buffer(this)->get_oop();
3224     }
3225     if (newval != nullptr && newval->is_InlineType()) {
3226       // Re-execute the unsafe access if allocation triggers deoptimization.
3227       PreserveReexecuteState preexecs(this);
3228       jvms()->set_should_reexecute(true);
3229       newval = newval->as_InlineType()->buffer(this)->get_oop();
3230     }
3231 
3232     // Transformation of a value which could be null pointer (CastPP #null)
3233     // could be delayed during Parse (for example, in adjust_map_after_if()).
3234     // Execute transformation here to avoid barrier generation in such case.
3235     if (_gvn.type(newval) == TypePtr::NULL_PTR)
3236       newval = _gvn.makecon(TypePtr::NULL_PTR);
3237 
3238     if (oldval != nullptr && _gvn.type(oldval) == TypePtr::NULL_PTR) {
3239       // Refine the value to a null constant, when it is known to be null
3240       oldval = _gvn.makecon(TypePtr::NULL_PTR);
3241     }
3242   }
3243 
3244   Node* result = nullptr;
3245   switch (kind) {
3246     case LS_cmp_exchange: {
3247       result = access_atomic_cmpxchg_val_at(base, adr, adr_type, alias_idx,
3248                                             oldval, newval, value_type, type, decorators);
3249       break;
3250     }
3251     case LS_cmp_swap_weak:
3252       decorators |= C2_WEAK_CMPXCHG;
3253     case LS_cmp_swap: {
3254       result = access_atomic_cmpxchg_bool_at(base, adr, adr_type, alias_idx,
3255                                              oldval, newval, value_type, type, decorators);
3256       break;
3257     }
3258     case LS_get_set: {
3259       result = access_atomic_xchg_at(base, adr, adr_type, alias_idx,
3260                                      newval, value_type, type, decorators);
3261       break;
3262     }
3263     case LS_get_add: {
3264       result = access_atomic_add_at(base, adr, adr_type, alias_idx,
3265                                     newval, value_type, type, decorators);
3266       break;
3267     }
3268     default:
3269       ShouldNotReachHere();
3270   }
3271 
3272   assert(type2size[result->bottom_type()->basic_type()] == type2size[rtype], "result type should match");
3273   set_result(result);
3274   return true;
3275 }
3276 
3277 bool LibraryCallKit::inline_unsafe_fence(vmIntrinsics::ID id) {
3278   // Regardless of form, don't allow previous ld/st to move down,
3279   // then issue acquire, release, or volatile mem_bar.
3280   insert_mem_bar(Op_MemBarCPUOrder);
3281   switch(id) {
3282     case vmIntrinsics::_loadFence:
3283       insert_mem_bar(Op_LoadFence);
3284       return true;
3285     case vmIntrinsics::_storeFence:
3286       insert_mem_bar(Op_StoreFence);
3287       return true;
3288     case vmIntrinsics::_storeStoreFence:
3289       insert_mem_bar(Op_StoreStoreFence);
3290       return true;
3291     case vmIntrinsics::_fullFence:
3292       insert_mem_bar(Op_MemBarVolatile);
3293       return true;
3294     default:
3295       fatal_unexpected_iid(id);
3296       return false;
3297   }
3298 }
3299 
3300 // private native int arrayInstanceBaseOffset0(Object[] array);
3301 bool LibraryCallKit::inline_arrayInstanceBaseOffset() {
3302   Node* array = argument(1);
3303   Node* klass_node = load_object_klass(array);
3304 
3305   jint  layout_con = Klass::_lh_neutral_value;
3306   Node* layout_val = get_layout_helper(klass_node, layout_con);
3307   int   layout_is_con = (layout_val == nullptr);
3308 
3309   Node* header_size = nullptr;
3310   if (layout_is_con) {
3311     int hsize = Klass::layout_helper_header_size(layout_con);
3312     header_size = intcon(hsize);
3313   } else {
3314     Node* hss = intcon(Klass::_lh_header_size_shift);
3315     Node* hsm = intcon(Klass::_lh_header_size_mask);
3316     header_size = _gvn.transform(new URShiftINode(layout_val, hss));
3317     header_size = _gvn.transform(new AndINode(header_size, hsm));
3318   }
3319   set_result(header_size);
3320   return true;
3321 }
3322 
3323 // private native int arrayInstanceIndexScale0(Object[] array);
3324 bool LibraryCallKit::inline_arrayInstanceIndexScale() {
3325   Node* array = argument(1);
3326   Node* klass_node = load_object_klass(array);
3327 
3328   jint  layout_con = Klass::_lh_neutral_value;
3329   Node* layout_val = get_layout_helper(klass_node, layout_con);
3330   int   layout_is_con = (layout_val == nullptr);
3331 
3332   Node* element_size = nullptr;
3333   if (layout_is_con) {
3334     int log_element_size  = Klass::layout_helper_log2_element_size(layout_con);
3335     int elem_size = 1 << log_element_size;
3336     element_size = intcon(elem_size);
3337   } else {
3338     Node* ess = intcon(Klass::_lh_log2_element_size_shift);
3339     Node* esm = intcon(Klass::_lh_log2_element_size_mask);
3340     Node* log_element_size = _gvn.transform(new URShiftINode(layout_val, ess));
3341     log_element_size = _gvn.transform(new AndINode(log_element_size, esm));
3342     element_size = _gvn.transform(new LShiftINode(intcon(1), log_element_size));
3343   }
3344   set_result(element_size);
3345   return true;
3346 }
3347 
3348 // private native int arrayLayout0(Object[] array);
3349 bool LibraryCallKit::inline_arrayLayout() {
3350   RegionNode* region = new RegionNode(2);
3351   Node* phi = new PhiNode(region, TypeInt::POS);
3352 
3353   Node* array = argument(1);
3354   Node* klass_node = load_object_klass(array);
3355   generate_refArray_guard(klass_node, region);
3356   if (region->req() == 3) {
3357     phi->add_req(intcon((jint)LayoutKind::REFERENCE));
3358   }
3359 
3360   int layout_kind_offset = in_bytes(FlatArrayKlass::layout_kind_offset());
3361   Node* layout_kind_addr = basic_plus_adr(klass_node, klass_node, layout_kind_offset);
3362   Node* layout_kind = make_load(nullptr, layout_kind_addr, TypeInt::POS, T_INT, MemNode::unordered);
3363 
3364   region->init_req(1, control());
3365   phi->init_req(1, layout_kind);
3366 
3367   set_control(_gvn.transform(region));
3368   set_result(_gvn.transform(phi));
3369   return true;
3370 }
3371 
3372 bool LibraryCallKit::inline_onspinwait() {
3373   insert_mem_bar(Op_OnSpinWait);
3374   return true;
3375 }
3376 
3377 bool LibraryCallKit::klass_needs_init_guard(Node* kls) {
3378   if (!kls->is_Con()) {
3379     return true;
3380   }
3381   const TypeInstKlassPtr* klsptr = kls->bottom_type()->isa_instklassptr();
3382   if (klsptr == nullptr) {
3383     return true;
3384   }
3385   ciInstanceKlass* ik = klsptr->instance_klass();
3386   // don't need a guard for a klass that is already initialized
3387   return !ik->is_initialized();
3388 }
3389 
3390 //----------------------------inline_unsafe_writeback0-------------------------
3391 // public native void Unsafe.writeback0(long address)
3392 bool LibraryCallKit::inline_unsafe_writeback0() {
3393   if (!Matcher::has_match_rule(Op_CacheWB)) {
3394     return false;
3395   }
3396 #ifndef PRODUCT
3397   assert(Matcher::has_match_rule(Op_CacheWBPreSync), "found match rule for CacheWB but not CacheWBPreSync");
3398   assert(Matcher::has_match_rule(Op_CacheWBPostSync), "found match rule for CacheWB but not CacheWBPostSync");
3399   ciSignature* sig = callee()->signature();
3400   assert(sig->type_at(0)->basic_type() == T_LONG, "Unsafe_writeback0 address is long!");
3401 #endif
3402   null_check_receiver();  // null-check, then ignore
3403   Node *addr = argument(1);
3404   addr = new CastX2PNode(addr);
3405   addr = _gvn.transform(addr);
3406   Node *flush = new CacheWBNode(control(), memory(TypeRawPtr::BOTTOM), addr);
3407   flush = _gvn.transform(flush);
3408   set_memory(flush, TypeRawPtr::BOTTOM);
3409   return true;
3410 }
3411 
3412 //----------------------------inline_unsafe_writeback0-------------------------
3413 // public native void Unsafe.writeback0(long address)
3414 bool LibraryCallKit::inline_unsafe_writebackSync0(bool is_pre) {
3415   if (is_pre && !Matcher::has_match_rule(Op_CacheWBPreSync)) {
3416     return false;
3417   }
3418   if (!is_pre && !Matcher::has_match_rule(Op_CacheWBPostSync)) {
3419     return false;
3420   }
3421 #ifndef PRODUCT
3422   assert(Matcher::has_match_rule(Op_CacheWB),
3423          (is_pre ? "found match rule for CacheWBPreSync but not CacheWB"
3424                 : "found match rule for CacheWBPostSync but not CacheWB"));
3425 
3426 #endif
3427   null_check_receiver();  // null-check, then ignore
3428   Node *sync;
3429   if (is_pre) {
3430     sync = new CacheWBPreSyncNode(control(), memory(TypeRawPtr::BOTTOM));
3431   } else {
3432     sync = new CacheWBPostSyncNode(control(), memory(TypeRawPtr::BOTTOM));
3433   }
3434   sync = _gvn.transform(sync);
3435   set_memory(sync, TypeRawPtr::BOTTOM);
3436   return true;
3437 }
3438 
3439 //----------------------------inline_unsafe_allocate---------------------------
3440 // public native Object Unsafe.allocateInstance(Class<?> cls);
3441 bool LibraryCallKit::inline_unsafe_allocate() {
3442 
3443 #if INCLUDE_JVMTI
3444   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
3445     return false;
3446   }
3447 #endif //INCLUDE_JVMTI
3448 
3449   if (callee()->is_static())  return false;  // caller must have the capability!
3450 
3451   null_check_receiver();  // null-check, then ignore
3452   Node* cls = null_check(argument(1));
3453   if (stopped())  return true;
3454 
3455   Node* kls = load_klass_from_mirror(cls, false, nullptr, 0);
3456   kls = null_check(kls);
3457   if (stopped())  return true;  // argument was like int.class
3458 
3459 #if INCLUDE_JVMTI
3460     // Don't try to access new allocated obj in the intrinsic.
3461     // It causes perfomance issues even when jvmti event VmObjectAlloc is disabled.
3462     // Deoptimize and allocate in interpreter instead.
3463     Node* addr = makecon(TypeRawPtr::make((address) &JvmtiExport::_should_notify_object_alloc));
3464     Node* should_post_vm_object_alloc = make_load(this->control(), addr, TypeInt::INT, T_INT, MemNode::unordered);
3465     Node* chk = _gvn.transform(new CmpINode(should_post_vm_object_alloc, intcon(0)));
3466     Node* tst = _gvn.transform(new BoolNode(chk, BoolTest::eq));
3467     {
3468       BuildCutout unless(this, tst, PROB_MAX);
3469       uncommon_trap(Deoptimization::Reason_intrinsic,
3470                     Deoptimization::Action_make_not_entrant);
3471     }
3472     if (stopped()) {
3473       return true;
3474     }
3475 #endif //INCLUDE_JVMTI
3476 
3477   Node* test = nullptr;
3478   if (LibraryCallKit::klass_needs_init_guard(kls)) {
3479     // Note:  The argument might still be an illegal value like
3480     // Serializable.class or Object[].class.   The runtime will handle it.
3481     // But we must make an explicit check for initialization.
3482     Node* insp = basic_plus_adr(kls, in_bytes(InstanceKlass::init_state_offset()));
3483     // Use T_BOOLEAN for InstanceKlass::_init_state so the compiler
3484     // can generate code to load it as unsigned byte.
3485     Node* inst = make_load(nullptr, insp, TypeInt::UBYTE, T_BOOLEAN, MemNode::acquire);
3486     Node* bits = intcon(InstanceKlass::fully_initialized);
3487     test = _gvn.transform(new SubINode(inst, bits));
3488     // The 'test' is non-zero if we need to take a slow path.
3489   }
3490   Node* obj = nullptr;
3491   const TypeInstKlassPtr* tkls = _gvn.type(kls)->isa_instklassptr();
3492   if (tkls != nullptr && tkls->instance_klass()->is_inlinetype()) {
3493     obj = InlineTypeNode::make_all_zero(_gvn, tkls->instance_klass()->as_inline_klass())->buffer(this);
3494   } else {
3495     obj = new_instance(kls, test);
3496   }
3497   set_result(obj);
3498   return true;
3499 }
3500 
3501 //------------------------inline_native_time_funcs--------------
3502 // inline code for System.currentTimeMillis() and System.nanoTime()
3503 // these have the same type and signature
3504 bool LibraryCallKit::inline_native_time_funcs(address funcAddr, const char* funcName) {
3505   const TypeFunc* tf = OptoRuntime::void_long_Type();
3506   const TypePtr* no_memory_effects = nullptr;
3507   Node* time = make_runtime_call(RC_LEAF, tf, funcAddr, funcName, no_memory_effects);
3508   Node* value = _gvn.transform(new ProjNode(time, TypeFunc::Parms+0));
3509 #ifdef ASSERT
3510   Node* value_top = _gvn.transform(new ProjNode(time, TypeFunc::Parms+1));
3511   assert(value_top == top(), "second value must be top");
3512 #endif
3513   set_result(value);
3514   return true;
3515 }
3516 
3517 
3518 #if INCLUDE_JVMTI
3519 
3520 // When notifications are disabled then just update the VTMS transition bit and return.
3521 // Otherwise, the bit is updated in the given function call implementing JVMTI notification protocol.
3522 bool LibraryCallKit::inline_native_notify_jvmti_funcs(address funcAddr, const char* funcName, bool is_start, bool is_end) {
3523   if (!DoJVMTIVirtualThreadTransitions) {
3524     return true;
3525   }
3526   Node* vt_oop = _gvn.transform(must_be_not_null(argument(0), true)); // VirtualThread this argument
3527   IdealKit ideal(this);
3528 
3529   Node* ONE = ideal.ConI(1);
3530   Node* hide = is_start ? ideal.ConI(0) : (is_end ? ideal.ConI(1) : _gvn.transform(argument(1)));
3531   Node* addr = makecon(TypeRawPtr::make((address)&JvmtiVTMSTransitionDisabler::_VTMS_notify_jvmti_events));
3532   Node* notify_jvmti_enabled = ideal.load(ideal.ctrl(), addr, TypeInt::BOOL, T_BOOLEAN, Compile::AliasIdxRaw);
3533 
3534   ideal.if_then(notify_jvmti_enabled, BoolTest::eq, ONE); {
3535     sync_kit(ideal);
3536     // if notifyJvmti enabled then make a call to the given SharedRuntime function
3537     const TypeFunc* tf = OptoRuntime::notify_jvmti_vthread_Type();
3538     make_runtime_call(RC_NO_LEAF, tf, funcAddr, funcName, TypePtr::BOTTOM, vt_oop, hide);
3539     ideal.sync_kit(this);
3540   } ideal.else_(); {
3541     // set hide value to the VTMS transition bit in current JavaThread and VirtualThread object
3542     Node* thread = ideal.thread();
3543     Node* jt_addr = basic_plus_adr(thread, in_bytes(JavaThread::is_in_VTMS_transition_offset()));
3544     Node* vt_addr = basic_plus_adr(vt_oop, java_lang_Thread::is_in_VTMS_transition_offset());
3545 
3546     sync_kit(ideal);
3547     access_store_at(nullptr, jt_addr, _gvn.type(jt_addr)->is_ptr(), hide, _gvn.type(hide), T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
3548     access_store_at(nullptr, vt_addr, _gvn.type(vt_addr)->is_ptr(), hide, _gvn.type(hide), T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
3549 
3550     ideal.sync_kit(this);
3551   } ideal.end_if();
3552   final_sync(ideal);
3553 
3554   return true;
3555 }
3556 
3557 // Always update the is_disable_suspend bit.
3558 bool LibraryCallKit::inline_native_notify_jvmti_sync() {
3559   if (!DoJVMTIVirtualThreadTransitions) {
3560     return true;
3561   }
3562   IdealKit ideal(this);
3563 
3564   {
3565     // unconditionally update the is_disable_suspend bit in current JavaThread
3566     Node* thread = ideal.thread();
3567     Node* arg = _gvn.transform(argument(0)); // argument for notification
3568     Node* addr = basic_plus_adr(thread, in_bytes(JavaThread::is_disable_suspend_offset()));
3569     const TypePtr *addr_type = _gvn.type(addr)->isa_ptr();
3570 
3571     sync_kit(ideal);
3572     access_store_at(nullptr, addr, addr_type, arg, _gvn.type(arg), T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
3573     ideal.sync_kit(this);
3574   }
3575   final_sync(ideal);
3576 
3577   return true;
3578 }
3579 
3580 #endif // INCLUDE_JVMTI
3581 
3582 #ifdef JFR_HAVE_INTRINSICS
3583 
3584 /**
3585  * if oop->klass != null
3586  *   // normal class
3587  *   epoch = _epoch_state ? 2 : 1
3588  *   if oop->klass->trace_id & ((epoch << META_SHIFT) | epoch)) != epoch {
3589  *     ... // enter slow path when the klass is first recorded or the epoch of JFR shifts
3590  *   }
3591  *   id = oop->klass->trace_id >> TRACE_ID_SHIFT // normal class path
3592  * else
3593  *   // primitive class
3594  *   if oop->array_klass != null
3595  *     id = (oop->array_klass->trace_id >> TRACE_ID_SHIFT) + 1 // primitive class path
3596  *   else
3597  *     id = LAST_TYPE_ID + 1 // void class path
3598  *   if (!signaled)
3599  *     signaled = true
3600  */
3601 bool LibraryCallKit::inline_native_classID() {
3602   Node* cls = argument(0);
3603 
3604   IdealKit ideal(this);
3605 #define __ ideal.
3606   IdealVariable result(ideal); __ declarations_done();
3607   Node* kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(),
3608                                                  basic_plus_adr(cls, java_lang_Class::klass_offset()),
3609                                                  TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
3610 
3611 
3612   __ if_then(kls, BoolTest::ne, null()); {
3613     Node* kls_trace_id_addr = basic_plus_adr(kls, in_bytes(KLASS_TRACE_ID_OFFSET));
3614     Node* kls_trace_id_raw = ideal.load(ideal.ctrl(), kls_trace_id_addr,TypeLong::LONG, T_LONG, Compile::AliasIdxRaw);
3615 
3616     Node* epoch_address = makecon(TypeRawPtr::make(JfrIntrinsicSupport::epoch_address()));
3617     Node* epoch = ideal.load(ideal.ctrl(), epoch_address, TypeInt::BOOL, T_BOOLEAN, Compile::AliasIdxRaw);
3618     epoch = _gvn.transform(new LShiftLNode(longcon(1), epoch));
3619     Node* mask = _gvn.transform(new LShiftLNode(epoch, intcon(META_SHIFT)));
3620     mask = _gvn.transform(new OrLNode(mask, epoch));
3621     Node* kls_trace_id_raw_and_mask = _gvn.transform(new AndLNode(kls_trace_id_raw, mask));
3622 
3623     float unlikely  = PROB_UNLIKELY(0.999);
3624     __ if_then(kls_trace_id_raw_and_mask, BoolTest::ne, epoch, unlikely); {
3625       sync_kit(ideal);
3626       make_runtime_call(RC_LEAF,
3627                         OptoRuntime::class_id_load_barrier_Type(),
3628                         CAST_FROM_FN_PTR(address, JfrIntrinsicSupport::load_barrier),
3629                         "class id load barrier",
3630                         TypePtr::BOTTOM,
3631                         kls);
3632       ideal.sync_kit(this);
3633     } __ end_if();
3634 
3635     ideal.set(result,  _gvn.transform(new URShiftLNode(kls_trace_id_raw, ideal.ConI(TRACE_ID_SHIFT))));
3636   } __ else_(); {
3637     Node* array_kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(),
3638                                                    basic_plus_adr(cls, java_lang_Class::array_klass_offset()),
3639                                                    TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
3640     __ if_then(array_kls, BoolTest::ne, null()); {
3641       Node* array_kls_trace_id_addr = basic_plus_adr(array_kls, in_bytes(KLASS_TRACE_ID_OFFSET));
3642       Node* array_kls_trace_id_raw = ideal.load(ideal.ctrl(), array_kls_trace_id_addr, TypeLong::LONG, T_LONG, Compile::AliasIdxRaw);
3643       Node* array_kls_trace_id = _gvn.transform(new URShiftLNode(array_kls_trace_id_raw, ideal.ConI(TRACE_ID_SHIFT)));
3644       ideal.set(result, _gvn.transform(new AddLNode(array_kls_trace_id, longcon(1))));
3645     } __ else_(); {
3646       // void class case
3647       ideal.set(result, _gvn.transform(longcon(LAST_TYPE_ID + 1)));
3648     } __ end_if();
3649 
3650     Node* signaled_flag_address = makecon(TypeRawPtr::make(JfrIntrinsicSupport::signal_address()));
3651     Node* signaled = ideal.load(ideal.ctrl(), signaled_flag_address, TypeInt::BOOL, T_BOOLEAN, Compile::AliasIdxRaw, true, MemNode::acquire);
3652     __ if_then(signaled, BoolTest::ne, ideal.ConI(1)); {
3653       ideal.store(ideal.ctrl(), signaled_flag_address, ideal.ConI(1), T_BOOLEAN, Compile::AliasIdxRaw, MemNode::release, true);
3654     } __ end_if();
3655   } __ end_if();
3656 
3657   final_sync(ideal);
3658   set_result(ideal.value(result));
3659 #undef __
3660   return true;
3661 }
3662 
3663 //------------------------inline_native_jvm_commit------------------
3664 bool LibraryCallKit::inline_native_jvm_commit() {
3665   enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
3666 
3667   // Save input memory and i_o state.
3668   Node* input_memory_state = reset_memory();
3669   set_all_memory(input_memory_state);
3670   Node* input_io_state = i_o();
3671 
3672   // TLS.
3673   Node* tls_ptr = _gvn.transform(new ThreadLocalNode());
3674   // Jfr java buffer.
3675   Node* java_buffer_offset = _gvn.transform(new AddPNode(top(), tls_ptr, _gvn.transform(MakeConX(in_bytes(JAVA_BUFFER_OFFSET_JFR)))));
3676   Node* java_buffer = _gvn.transform(new LoadPNode(control(), input_memory_state, java_buffer_offset, TypePtr::BOTTOM, TypeRawPtr::NOTNULL, MemNode::unordered));
3677   Node* java_buffer_pos_offset = _gvn.transform(new AddPNode(top(), java_buffer, _gvn.transform(MakeConX(in_bytes(JFR_BUFFER_POS_OFFSET)))));
3678 
3679   // Load the current value of the notified field in the JfrThreadLocal.
3680   Node* notified_offset = basic_plus_adr(top(), tls_ptr, in_bytes(NOTIFY_OFFSET_JFR));
3681   Node* notified = make_load(control(), notified_offset, TypeInt::BOOL, T_BOOLEAN, MemNode::unordered);
3682 
3683   // Test for notification.
3684   Node* notified_cmp = _gvn.transform(new CmpINode(notified, _gvn.intcon(1)));
3685   Node* test_notified = _gvn.transform(new BoolNode(notified_cmp, BoolTest::eq));
3686   IfNode* iff_notified = create_and_map_if(control(), test_notified, PROB_MIN, COUNT_UNKNOWN);
3687 
3688   // True branch, is notified.
3689   Node* is_notified = _gvn.transform(new IfTrueNode(iff_notified));
3690   set_control(is_notified);
3691 
3692   // Reset notified state.
3693   store_to_memory(control(), notified_offset, _gvn.intcon(0), T_BOOLEAN, MemNode::unordered);
3694   Node* notified_reset_memory = reset_memory();
3695 
3696   // 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.
3697   Node* current_pos_X = _gvn.transform(new LoadXNode(control(), input_memory_state, java_buffer_pos_offset, TypeRawPtr::NOTNULL, TypeX_X, MemNode::unordered));
3698   // Convert the machine-word to a long.
3699   Node* current_pos = _gvn.transform(ConvX2L(current_pos_X));
3700 
3701   // False branch, not notified.
3702   Node* not_notified = _gvn.transform(new IfFalseNode(iff_notified));
3703   set_control(not_notified);
3704   set_all_memory(input_memory_state);
3705 
3706   // Arg is the next position as a long.
3707   Node* arg = argument(0);
3708   // Convert long to machine-word.
3709   Node* next_pos_X = _gvn.transform(ConvL2X(arg));
3710 
3711   // Store the next_position to the underlying jfr java buffer.
3712   store_to_memory(control(), java_buffer_pos_offset, next_pos_X, LP64_ONLY(T_LONG) NOT_LP64(T_INT), MemNode::release);
3713 
3714   Node* commit_memory = reset_memory();
3715   set_all_memory(commit_memory);
3716 
3717   // 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.
3718   Node* java_buffer_flags_offset = _gvn.transform(new AddPNode(top(), java_buffer, _gvn.transform(MakeConX(in_bytes(JFR_BUFFER_FLAGS_OFFSET)))));
3719   Node* flags = make_load(control(), java_buffer_flags_offset, TypeInt::UBYTE, T_BYTE, MemNode::unordered);
3720   Node* lease_constant = _gvn.transform(_gvn.intcon(4));
3721 
3722   // And flags with lease constant.
3723   Node* lease = _gvn.transform(new AndINode(flags, lease_constant));
3724 
3725   // Branch on lease to conditionalize returning the leased java buffer.
3726   Node* lease_cmp = _gvn.transform(new CmpINode(lease, lease_constant));
3727   Node* test_lease = _gvn.transform(new BoolNode(lease_cmp, BoolTest::eq));
3728   IfNode* iff_lease = create_and_map_if(control(), test_lease, PROB_MIN, COUNT_UNKNOWN);
3729 
3730   // False branch, not a lease.
3731   Node* not_lease = _gvn.transform(new IfFalseNode(iff_lease));
3732 
3733   // True branch, is lease.
3734   Node* is_lease = _gvn.transform(new IfTrueNode(iff_lease));
3735   set_control(is_lease);
3736 
3737   // Make a runtime call, which can safepoint, to return the leased buffer. This updates both the JfrThreadLocal and the Java event writer oop.
3738   Node* call_return_lease = make_runtime_call(RC_NO_LEAF,
3739                                               OptoRuntime::void_void_Type(),
3740                                               SharedRuntime::jfr_return_lease(),
3741                                               "return_lease", TypePtr::BOTTOM);
3742   Node* call_return_lease_control = _gvn.transform(new ProjNode(call_return_lease, TypeFunc::Control));
3743 
3744   RegionNode* lease_compare_rgn = new RegionNode(PATH_LIMIT);
3745   record_for_igvn(lease_compare_rgn);
3746   PhiNode* lease_compare_mem = new PhiNode(lease_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3747   record_for_igvn(lease_compare_mem);
3748   PhiNode* lease_compare_io = new PhiNode(lease_compare_rgn, Type::ABIO);
3749   record_for_igvn(lease_compare_io);
3750   PhiNode* lease_result_value = new PhiNode(lease_compare_rgn, TypeLong::LONG);
3751   record_for_igvn(lease_result_value);
3752 
3753   // Update control and phi nodes.
3754   lease_compare_rgn->init_req(_true_path, call_return_lease_control);
3755   lease_compare_rgn->init_req(_false_path, not_lease);
3756 
3757   lease_compare_mem->init_req(_true_path, _gvn.transform(reset_memory()));
3758   lease_compare_mem->init_req(_false_path, commit_memory);
3759 
3760   lease_compare_io->init_req(_true_path, i_o());
3761   lease_compare_io->init_req(_false_path, input_io_state);
3762 
3763   lease_result_value->init_req(_true_path, _gvn.longcon(0)); // if the lease was returned, return 0L.
3764   lease_result_value->init_req(_false_path, arg); // if not lease, return new updated position.
3765 
3766   RegionNode* result_rgn = new RegionNode(PATH_LIMIT);
3767   PhiNode* result_mem = new PhiNode(result_rgn, Type::MEMORY, TypePtr::BOTTOM);
3768   PhiNode* result_io = new PhiNode(result_rgn, Type::ABIO);
3769   PhiNode* result_value = new PhiNode(result_rgn, TypeLong::LONG);
3770 
3771   // Update control and phi nodes.
3772   result_rgn->init_req(_true_path, is_notified);
3773   result_rgn->init_req(_false_path, _gvn.transform(lease_compare_rgn));
3774 
3775   result_mem->init_req(_true_path, notified_reset_memory);
3776   result_mem->init_req(_false_path, _gvn.transform(lease_compare_mem));
3777 
3778   result_io->init_req(_true_path, input_io_state);
3779   result_io->init_req(_false_path, _gvn.transform(lease_compare_io));
3780 
3781   result_value->init_req(_true_path, current_pos);
3782   result_value->init_req(_false_path, _gvn.transform(lease_result_value));
3783 
3784   // Set output state.
3785   set_control(_gvn.transform(result_rgn));
3786   set_all_memory(_gvn.transform(result_mem));
3787   set_i_o(_gvn.transform(result_io));
3788   set_result(result_rgn, result_value);
3789   return true;
3790 }
3791 
3792 /*
3793  * The intrinsic is a model of this pseudo-code:
3794  *
3795  * JfrThreadLocal* const tl = Thread::jfr_thread_local()
3796  * jobject h_event_writer = tl->java_event_writer();
3797  * if (h_event_writer == nullptr) {
3798  *   return nullptr;
3799  * }
3800  * oop threadObj = Thread::threadObj();
3801  * oop vthread = java_lang_Thread::vthread(threadObj);
3802  * traceid tid;
3803  * bool pinVirtualThread;
3804  * bool excluded;
3805  * if (vthread != threadObj) {  // i.e. current thread is virtual
3806  *   tid = java_lang_Thread::tid(vthread);
3807  *   u2 vthread_epoch_raw = java_lang_Thread::jfr_epoch(vthread);
3808  *   pinVirtualThread = VMContinuations;
3809  *   excluded = vthread_epoch_raw & excluded_mask;
3810  *   if (!excluded) {
3811  *     traceid current_epoch = JfrTraceIdEpoch::current_generation();
3812  *     u2 vthread_epoch = vthread_epoch_raw & epoch_mask;
3813  *     if (vthread_epoch != current_epoch) {
3814  *       write_checkpoint();
3815  *     }
3816  *   }
3817  * } else {
3818  *   tid = java_lang_Thread::tid(threadObj);
3819  *   u2 thread_epoch_raw = java_lang_Thread::jfr_epoch(threadObj);
3820  *   pinVirtualThread = false;
3821  *   excluded = thread_epoch_raw & excluded_mask;
3822  * }
3823  * oop event_writer = JNIHandles::resolve_non_null(h_event_writer);
3824  * traceid tid_in_event_writer = getField(event_writer, "threadID");
3825  * if (tid_in_event_writer != tid) {
3826  *   setField(event_writer, "pinVirtualThread", pinVirtualThread);
3827  *   setField(event_writer, "excluded", excluded);
3828  *   setField(event_writer, "threadID", tid);
3829  * }
3830  * return event_writer
3831  */
3832 bool LibraryCallKit::inline_native_getEventWriter() {
3833   enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
3834 
3835   // Save input memory and i_o state.
3836   Node* input_memory_state = reset_memory();
3837   set_all_memory(input_memory_state);
3838   Node* input_io_state = i_o();
3839 
3840   // The most significant bit of the u2 is used to denote thread exclusion
3841   Node* excluded_shift = _gvn.intcon(15);
3842   Node* excluded_mask = _gvn.intcon(1 << 15);
3843   // The epoch generation is the range [1-32767]
3844   Node* epoch_mask = _gvn.intcon(32767);
3845 
3846   // TLS
3847   Node* tls_ptr = _gvn.transform(new ThreadLocalNode());
3848 
3849   // Load the address of java event writer jobject handle from the jfr_thread_local structure.
3850   Node* jobj_ptr = basic_plus_adr(top(), tls_ptr, in_bytes(THREAD_LOCAL_WRITER_OFFSET_JFR));
3851 
3852   // Load the eventwriter jobject handle.
3853   Node* jobj = make_load(control(), jobj_ptr, TypeRawPtr::BOTTOM, T_ADDRESS, MemNode::unordered);
3854 
3855   // Null check the jobject handle.
3856   Node* jobj_cmp_null = _gvn.transform(new CmpPNode(jobj, null()));
3857   Node* test_jobj_not_equal_null = _gvn.transform(new BoolNode(jobj_cmp_null, BoolTest::ne));
3858   IfNode* iff_jobj_not_equal_null = create_and_map_if(control(), test_jobj_not_equal_null, PROB_MAX, COUNT_UNKNOWN);
3859 
3860   // False path, jobj is null.
3861   Node* jobj_is_null = _gvn.transform(new IfFalseNode(iff_jobj_not_equal_null));
3862 
3863   // True path, jobj is not null.
3864   Node* jobj_is_not_null = _gvn.transform(new IfTrueNode(iff_jobj_not_equal_null));
3865 
3866   set_control(jobj_is_not_null);
3867 
3868   // Load the threadObj for the CarrierThread.
3869   Node* threadObj = generate_current_thread(tls_ptr);
3870 
3871   // Load the vthread.
3872   Node* vthread = generate_virtual_thread(tls_ptr);
3873 
3874   // If vthread != threadObj, this is a virtual thread.
3875   Node* vthread_cmp_threadObj = _gvn.transform(new CmpPNode(vthread, threadObj));
3876   Node* test_vthread_not_equal_threadObj = _gvn.transform(new BoolNode(vthread_cmp_threadObj, BoolTest::ne));
3877   IfNode* iff_vthread_not_equal_threadObj =
3878     create_and_map_if(jobj_is_not_null, test_vthread_not_equal_threadObj, PROB_FAIR, COUNT_UNKNOWN);
3879 
3880   // False branch, fallback to threadObj.
3881   Node* vthread_equal_threadObj = _gvn.transform(new IfFalseNode(iff_vthread_not_equal_threadObj));
3882   set_control(vthread_equal_threadObj);
3883 
3884   // Load the tid field from the vthread object.
3885   Node* thread_obj_tid = load_field_from_object(threadObj, "tid", "J");
3886 
3887   // Load the raw epoch value from the threadObj.
3888   Node* threadObj_epoch_offset = basic_plus_adr(threadObj, java_lang_Thread::jfr_epoch_offset());
3889   Node* threadObj_epoch_raw = access_load_at(threadObj, threadObj_epoch_offset,
3890                                              _gvn.type(threadObj_epoch_offset)->isa_ptr(),
3891                                              TypeInt::CHAR, T_CHAR,
3892                                              IN_HEAP | MO_UNORDERED | C2_MISMATCHED | C2_CONTROL_DEPENDENT_LOAD);
3893 
3894   // Mask off the excluded information from the epoch.
3895   Node * threadObj_is_excluded = _gvn.transform(new AndINode(threadObj_epoch_raw, excluded_mask));
3896 
3897   // True branch, this is a virtual thread.
3898   Node* vthread_not_equal_threadObj = _gvn.transform(new IfTrueNode(iff_vthread_not_equal_threadObj));
3899   set_control(vthread_not_equal_threadObj);
3900 
3901   // Load the tid field from the vthread object.
3902   Node* vthread_tid = load_field_from_object(vthread, "tid", "J");
3903 
3904   // Continuation support determines if a virtual thread should be pinned.
3905   Node* global_addr = makecon(TypeRawPtr::make((address)&VMContinuations));
3906   Node* continuation_support = make_load(control(), global_addr, TypeInt::BOOL, T_BOOLEAN, MemNode::unordered);
3907 
3908   // Load the raw epoch value from the vthread.
3909   Node* vthread_epoch_offset = basic_plus_adr(vthread, java_lang_Thread::jfr_epoch_offset());
3910   Node* vthread_epoch_raw = access_load_at(vthread, vthread_epoch_offset, _gvn.type(vthread_epoch_offset)->is_ptr(),
3911                                            TypeInt::CHAR, T_CHAR,
3912                                            IN_HEAP | MO_UNORDERED | C2_MISMATCHED | C2_CONTROL_DEPENDENT_LOAD);
3913 
3914   // Mask off the excluded information from the epoch.
3915   Node * vthread_is_excluded = _gvn.transform(new AndINode(vthread_epoch_raw, _gvn.transform(excluded_mask)));
3916 
3917   // Branch on excluded to conditionalize updating the epoch for the virtual thread.
3918   Node* is_excluded_cmp = _gvn.transform(new CmpINode(vthread_is_excluded, _gvn.transform(excluded_mask)));
3919   Node* test_not_excluded = _gvn.transform(new BoolNode(is_excluded_cmp, BoolTest::ne));
3920   IfNode* iff_not_excluded = create_and_map_if(control(), test_not_excluded, PROB_MAX, COUNT_UNKNOWN);
3921 
3922   // False branch, vthread is excluded, no need to write epoch info.
3923   Node* excluded = _gvn.transform(new IfFalseNode(iff_not_excluded));
3924 
3925   // True branch, vthread is included, update epoch info.
3926   Node* included = _gvn.transform(new IfTrueNode(iff_not_excluded));
3927   set_control(included);
3928 
3929   // Get epoch value.
3930   Node* epoch = _gvn.transform(new AndINode(vthread_epoch_raw, _gvn.transform(epoch_mask)));
3931 
3932   // Load the current epoch generation. The value is unsigned 16-bit, so we type it as T_CHAR.
3933   Node* epoch_generation_address = makecon(TypeRawPtr::make(JfrIntrinsicSupport::epoch_generation_address()));
3934   Node* current_epoch_generation = make_load(control(), epoch_generation_address, TypeInt::CHAR, T_CHAR, MemNode::unordered);
3935 
3936   // Compare the epoch in the vthread to the current epoch generation.
3937   Node* const epoch_cmp = _gvn.transform(new CmpUNode(current_epoch_generation, epoch));
3938   Node* test_epoch_not_equal = _gvn.transform(new BoolNode(epoch_cmp, BoolTest::ne));
3939   IfNode* iff_epoch_not_equal = create_and_map_if(control(), test_epoch_not_equal, PROB_FAIR, COUNT_UNKNOWN);
3940 
3941   // False path, epoch is equal, checkpoint information is valid.
3942   Node* epoch_is_equal = _gvn.transform(new IfFalseNode(iff_epoch_not_equal));
3943 
3944   // True path, epoch is not equal, write a checkpoint for the vthread.
3945   Node* epoch_is_not_equal = _gvn.transform(new IfTrueNode(iff_epoch_not_equal));
3946 
3947   set_control(epoch_is_not_equal);
3948 
3949   // Make a runtime call, which can safepoint, to write a checkpoint for the vthread for this epoch.
3950   // The call also updates the native thread local thread id and the vthread with the current epoch.
3951   Node* call_write_checkpoint = make_runtime_call(RC_NO_LEAF,
3952                                                   OptoRuntime::jfr_write_checkpoint_Type(),
3953                                                   SharedRuntime::jfr_write_checkpoint(),
3954                                                   "write_checkpoint", TypePtr::BOTTOM);
3955   Node* call_write_checkpoint_control = _gvn.transform(new ProjNode(call_write_checkpoint, TypeFunc::Control));
3956 
3957   // vthread epoch != current epoch
3958   RegionNode* epoch_compare_rgn = new RegionNode(PATH_LIMIT);
3959   record_for_igvn(epoch_compare_rgn);
3960   PhiNode* epoch_compare_mem = new PhiNode(epoch_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3961   record_for_igvn(epoch_compare_mem);
3962   PhiNode* epoch_compare_io = new PhiNode(epoch_compare_rgn, Type::ABIO);
3963   record_for_igvn(epoch_compare_io);
3964 
3965   // Update control and phi nodes.
3966   epoch_compare_rgn->init_req(_true_path, call_write_checkpoint_control);
3967   epoch_compare_rgn->init_req(_false_path, epoch_is_equal);
3968   epoch_compare_mem->init_req(_true_path, _gvn.transform(reset_memory()));
3969   epoch_compare_mem->init_req(_false_path, input_memory_state);
3970   epoch_compare_io->init_req(_true_path, i_o());
3971   epoch_compare_io->init_req(_false_path, input_io_state);
3972 
3973   // excluded != true
3974   RegionNode* exclude_compare_rgn = new RegionNode(PATH_LIMIT);
3975   record_for_igvn(exclude_compare_rgn);
3976   PhiNode* exclude_compare_mem = new PhiNode(exclude_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3977   record_for_igvn(exclude_compare_mem);
3978   PhiNode* exclude_compare_io = new PhiNode(exclude_compare_rgn, Type::ABIO);
3979   record_for_igvn(exclude_compare_io);
3980 
3981   // Update control and phi nodes.
3982   exclude_compare_rgn->init_req(_true_path, _gvn.transform(epoch_compare_rgn));
3983   exclude_compare_rgn->init_req(_false_path, excluded);
3984   exclude_compare_mem->init_req(_true_path, _gvn.transform(epoch_compare_mem));
3985   exclude_compare_mem->init_req(_false_path, input_memory_state);
3986   exclude_compare_io->init_req(_true_path, _gvn.transform(epoch_compare_io));
3987   exclude_compare_io->init_req(_false_path, input_io_state);
3988 
3989   // vthread != threadObj
3990   RegionNode* vthread_compare_rgn = new RegionNode(PATH_LIMIT);
3991   record_for_igvn(vthread_compare_rgn);
3992   PhiNode* vthread_compare_mem = new PhiNode(vthread_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3993   PhiNode* vthread_compare_io = new PhiNode(vthread_compare_rgn, Type::ABIO);
3994   record_for_igvn(vthread_compare_io);
3995   PhiNode* tid = new PhiNode(vthread_compare_rgn, TypeLong::LONG);
3996   record_for_igvn(tid);
3997   PhiNode* exclusion = new PhiNode(vthread_compare_rgn, TypeInt::CHAR);
3998   record_for_igvn(exclusion);
3999   PhiNode* pinVirtualThread = new PhiNode(vthread_compare_rgn, TypeInt::BOOL);
4000   record_for_igvn(pinVirtualThread);
4001 
4002   // Update control and phi nodes.
4003   vthread_compare_rgn->init_req(_true_path, _gvn.transform(exclude_compare_rgn));
4004   vthread_compare_rgn->init_req(_false_path, vthread_equal_threadObj);
4005   vthread_compare_mem->init_req(_true_path, _gvn.transform(exclude_compare_mem));
4006   vthread_compare_mem->init_req(_false_path, input_memory_state);
4007   vthread_compare_io->init_req(_true_path, _gvn.transform(exclude_compare_io));
4008   vthread_compare_io->init_req(_false_path, input_io_state);
4009   tid->init_req(_true_path, _gvn.transform(vthread_tid));
4010   tid->init_req(_false_path, _gvn.transform(thread_obj_tid));
4011   exclusion->init_req(_true_path, _gvn.transform(vthread_is_excluded));
4012   exclusion->init_req(_false_path, _gvn.transform(threadObj_is_excluded));
4013   pinVirtualThread->init_req(_true_path, _gvn.transform(continuation_support));
4014   pinVirtualThread->init_req(_false_path, _gvn.intcon(0));
4015 
4016   // Update branch state.
4017   set_control(_gvn.transform(vthread_compare_rgn));
4018   set_all_memory(_gvn.transform(vthread_compare_mem));
4019   set_i_o(_gvn.transform(vthread_compare_io));
4020 
4021   // Load the event writer oop by dereferencing the jobject handle.
4022   ciKlass* klass_EventWriter = env()->find_system_klass(ciSymbol::make("jdk/jfr/internal/event/EventWriter"));
4023   assert(klass_EventWriter->is_loaded(), "invariant");
4024   ciInstanceKlass* const instklass_EventWriter = klass_EventWriter->as_instance_klass();
4025   const TypeKlassPtr* const aklass = TypeKlassPtr::make(instklass_EventWriter);
4026   const TypeOopPtr* const xtype = aklass->as_instance_type();
4027   Node* jobj_untagged = _gvn.transform(new AddPNode(top(), jobj, _gvn.MakeConX(-JNIHandles::TypeTag::global)));
4028   Node* event_writer = access_load(jobj_untagged, xtype, T_OBJECT, IN_NATIVE | C2_CONTROL_DEPENDENT_LOAD);
4029 
4030   // Load the current thread id from the event writer object.
4031   Node* const event_writer_tid = load_field_from_object(event_writer, "threadID", "J");
4032   // Get the field offset to, conditionally, store an updated tid value later.
4033   Node* const event_writer_tid_field = field_address_from_object(event_writer, "threadID", "J", false);
4034   // Get the field offset to, conditionally, store an updated exclusion value later.
4035   Node* const event_writer_excluded_field = field_address_from_object(event_writer, "excluded", "Z", false);
4036   // Get the field offset to, conditionally, store an updated pinVirtualThread value later.
4037   Node* const event_writer_pin_field = field_address_from_object(event_writer, "pinVirtualThread", "Z", false);
4038 
4039   RegionNode* event_writer_tid_compare_rgn = new RegionNode(PATH_LIMIT);
4040   record_for_igvn(event_writer_tid_compare_rgn);
4041   PhiNode* event_writer_tid_compare_mem = new PhiNode(event_writer_tid_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
4042   record_for_igvn(event_writer_tid_compare_mem);
4043   PhiNode* event_writer_tid_compare_io = new PhiNode(event_writer_tid_compare_rgn, Type::ABIO);
4044   record_for_igvn(event_writer_tid_compare_io);
4045 
4046   // Compare the current tid from the thread object to what is currently stored in the event writer object.
4047   Node* const tid_cmp = _gvn.transform(new CmpLNode(event_writer_tid, _gvn.transform(tid)));
4048   Node* test_tid_not_equal = _gvn.transform(new BoolNode(tid_cmp, BoolTest::ne));
4049   IfNode* iff_tid_not_equal = create_and_map_if(_gvn.transform(vthread_compare_rgn), test_tid_not_equal, PROB_FAIR, COUNT_UNKNOWN);
4050 
4051   // False path, tids are the same.
4052   Node* tid_is_equal = _gvn.transform(new IfFalseNode(iff_tid_not_equal));
4053 
4054   // True path, tid is not equal, need to update the tid in the event writer.
4055   Node* tid_is_not_equal = _gvn.transform(new IfTrueNode(iff_tid_not_equal));
4056   record_for_igvn(tid_is_not_equal);
4057 
4058   // Store the pin state to the event writer.
4059   store_to_memory(tid_is_not_equal, event_writer_pin_field, _gvn.transform(pinVirtualThread), T_BOOLEAN, MemNode::unordered);
4060 
4061   // Store the exclusion state to the event writer.
4062   Node* excluded_bool = _gvn.transform(new URShiftINode(_gvn.transform(exclusion), excluded_shift));
4063   store_to_memory(tid_is_not_equal, event_writer_excluded_field, excluded_bool, T_BOOLEAN, MemNode::unordered);
4064 
4065   // Store the tid to the event writer.
4066   store_to_memory(tid_is_not_equal, event_writer_tid_field, tid, T_LONG, MemNode::unordered);
4067 
4068   // Update control and phi nodes.
4069   event_writer_tid_compare_rgn->init_req(_true_path, tid_is_not_equal);
4070   event_writer_tid_compare_rgn->init_req(_false_path, tid_is_equal);
4071   event_writer_tid_compare_mem->init_req(_true_path, _gvn.transform(reset_memory()));
4072   event_writer_tid_compare_mem->init_req(_false_path, _gvn.transform(vthread_compare_mem));
4073   event_writer_tid_compare_io->init_req(_true_path, _gvn.transform(i_o()));
4074   event_writer_tid_compare_io->init_req(_false_path, _gvn.transform(vthread_compare_io));
4075 
4076   // Result of top level CFG, Memory, IO and Value.
4077   RegionNode* result_rgn = new RegionNode(PATH_LIMIT);
4078   PhiNode* result_mem = new PhiNode(result_rgn, Type::MEMORY, TypePtr::BOTTOM);
4079   PhiNode* result_io = new PhiNode(result_rgn, Type::ABIO);
4080   PhiNode* result_value = new PhiNode(result_rgn, TypeInstPtr::BOTTOM);
4081 
4082   // Result control.
4083   result_rgn->init_req(_true_path, _gvn.transform(event_writer_tid_compare_rgn));
4084   result_rgn->init_req(_false_path, jobj_is_null);
4085 
4086   // Result memory.
4087   result_mem->init_req(_true_path, _gvn.transform(event_writer_tid_compare_mem));
4088   result_mem->init_req(_false_path, _gvn.transform(input_memory_state));
4089 
4090   // Result IO.
4091   result_io->init_req(_true_path, _gvn.transform(event_writer_tid_compare_io));
4092   result_io->init_req(_false_path, _gvn.transform(input_io_state));
4093 
4094   // Result value.
4095   result_value->init_req(_true_path, _gvn.transform(event_writer)); // return event writer oop
4096   result_value->init_req(_false_path, null()); // return null
4097 
4098   // Set output state.
4099   set_control(_gvn.transform(result_rgn));
4100   set_all_memory(_gvn.transform(result_mem));
4101   set_i_o(_gvn.transform(result_io));
4102   set_result(result_rgn, result_value);
4103   return true;
4104 }
4105 
4106 /*
4107  * The intrinsic is a model of this pseudo-code:
4108  *
4109  * JfrThreadLocal* const tl = thread->jfr_thread_local();
4110  * if (carrierThread != thread) { // is virtual thread
4111  *   const u2 vthread_epoch_raw = java_lang_Thread::jfr_epoch(thread);
4112  *   bool excluded = vthread_epoch_raw & excluded_mask;
4113  *   AtomicAccess::store(&tl->_contextual_tid, java_lang_Thread::tid(thread));
4114  *   AtomicAccess::store(&tl->_contextual_thread_excluded, is_excluded);
4115  *   if (!excluded) {
4116  *     const u2 vthread_epoch = vthread_epoch_raw & epoch_mask;
4117  *     AtomicAccess::store(&tl->_vthread_epoch, vthread_epoch);
4118  *   }
4119  *   AtomicAccess::release_store(&tl->_vthread, true);
4120  *   return;
4121  * }
4122  * AtomicAccess::release_store(&tl->_vthread, false);
4123  */
4124 void LibraryCallKit::extend_setCurrentThread(Node* jt, Node* thread) {
4125   enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
4126 
4127   Node* input_memory_state = reset_memory();
4128   set_all_memory(input_memory_state);
4129 
4130   // The most significant bit of the u2 is used to denote thread exclusion
4131   Node* excluded_mask = _gvn.intcon(1 << 15);
4132   // The epoch generation is the range [1-32767]
4133   Node* epoch_mask = _gvn.intcon(32767);
4134 
4135   Node* const carrierThread = generate_current_thread(jt);
4136   // If thread != carrierThread, this is a virtual thread.
4137   Node* thread_cmp_carrierThread = _gvn.transform(new CmpPNode(thread, carrierThread));
4138   Node* test_thread_not_equal_carrierThread = _gvn.transform(new BoolNode(thread_cmp_carrierThread, BoolTest::ne));
4139   IfNode* iff_thread_not_equal_carrierThread =
4140     create_and_map_if(control(), test_thread_not_equal_carrierThread, PROB_FAIR, COUNT_UNKNOWN);
4141 
4142   Node* vthread_offset = basic_plus_adr(jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_OFFSET_JFR));
4143 
4144   // False branch, is carrierThread.
4145   Node* thread_equal_carrierThread = _gvn.transform(new IfFalseNode(iff_thread_not_equal_carrierThread));
4146   // Store release
4147   Node* vthread_false_memory = store_to_memory(thread_equal_carrierThread, vthread_offset, _gvn.intcon(0), T_BOOLEAN, MemNode::release, true);
4148 
4149   set_all_memory(input_memory_state);
4150 
4151   // True branch, is virtual thread.
4152   Node* thread_not_equal_carrierThread = _gvn.transform(new IfTrueNode(iff_thread_not_equal_carrierThread));
4153   set_control(thread_not_equal_carrierThread);
4154 
4155   // Load the raw epoch value from the vthread.
4156   Node* epoch_offset = basic_plus_adr(thread, java_lang_Thread::jfr_epoch_offset());
4157   Node* epoch_raw = access_load_at(thread, epoch_offset, _gvn.type(epoch_offset)->is_ptr(), TypeInt::CHAR, T_CHAR,
4158                                    IN_HEAP | MO_UNORDERED | C2_MISMATCHED | C2_CONTROL_DEPENDENT_LOAD);
4159 
4160   // Mask off the excluded information from the epoch.
4161   Node * const is_excluded = _gvn.transform(new AndINode(epoch_raw, _gvn.transform(excluded_mask)));
4162 
4163   // Load the tid field from the thread.
4164   Node* tid = load_field_from_object(thread, "tid", "J");
4165 
4166   // Store the vthread tid to the jfr thread local.
4167   Node* thread_id_offset = basic_plus_adr(jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_ID_OFFSET_JFR));
4168   Node* tid_memory = store_to_memory(control(), thread_id_offset, tid, T_LONG, MemNode::unordered, true);
4169 
4170   // Branch is_excluded to conditionalize updating the epoch .
4171   Node* excluded_cmp = _gvn.transform(new CmpINode(is_excluded, _gvn.transform(excluded_mask)));
4172   Node* test_excluded = _gvn.transform(new BoolNode(excluded_cmp, BoolTest::eq));
4173   IfNode* iff_excluded = create_and_map_if(control(), test_excluded, PROB_MIN, COUNT_UNKNOWN);
4174 
4175   // True branch, vthread is excluded, no need to write epoch info.
4176   Node* excluded = _gvn.transform(new IfTrueNode(iff_excluded));
4177   set_control(excluded);
4178   Node* vthread_is_excluded = _gvn.intcon(1);
4179 
4180   // False branch, vthread is included, update epoch info.
4181   Node* included = _gvn.transform(new IfFalseNode(iff_excluded));
4182   set_control(included);
4183   Node* vthread_is_included = _gvn.intcon(0);
4184 
4185   // Get epoch value.
4186   Node* epoch = _gvn.transform(new AndINode(epoch_raw, _gvn.transform(epoch_mask)));
4187 
4188   // Store the vthread epoch to the jfr thread local.
4189   Node* vthread_epoch_offset = basic_plus_adr(jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_EPOCH_OFFSET_JFR));
4190   Node* included_memory = store_to_memory(control(), vthread_epoch_offset, epoch, T_CHAR, MemNode::unordered, true);
4191 
4192   RegionNode* excluded_rgn = new RegionNode(PATH_LIMIT);
4193   record_for_igvn(excluded_rgn);
4194   PhiNode* excluded_mem = new PhiNode(excluded_rgn, Type::MEMORY, TypePtr::BOTTOM);
4195   record_for_igvn(excluded_mem);
4196   PhiNode* exclusion = new PhiNode(excluded_rgn, TypeInt::BOOL);
4197   record_for_igvn(exclusion);
4198 
4199   // Merge the excluded control and memory.
4200   excluded_rgn->init_req(_true_path, excluded);
4201   excluded_rgn->init_req(_false_path, included);
4202   excluded_mem->init_req(_true_path, tid_memory);
4203   excluded_mem->init_req(_false_path, included_memory);
4204   exclusion->init_req(_true_path, _gvn.transform(vthread_is_excluded));
4205   exclusion->init_req(_false_path, _gvn.transform(vthread_is_included));
4206 
4207   // Set intermediate state.
4208   set_control(_gvn.transform(excluded_rgn));
4209   set_all_memory(excluded_mem);
4210 
4211   // Store the vthread exclusion state to the jfr thread local.
4212   Node* thread_local_excluded_offset = basic_plus_adr(jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_EXCLUDED_OFFSET_JFR));
4213   store_to_memory(control(), thread_local_excluded_offset, _gvn.transform(exclusion), T_BOOLEAN, MemNode::unordered, true);
4214 
4215   // Store release
4216   Node * vthread_true_memory = store_to_memory(control(), vthread_offset, _gvn.intcon(1), T_BOOLEAN, MemNode::release, true);
4217 
4218   RegionNode* thread_compare_rgn = new RegionNode(PATH_LIMIT);
4219   record_for_igvn(thread_compare_rgn);
4220   PhiNode* thread_compare_mem = new PhiNode(thread_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
4221   record_for_igvn(thread_compare_mem);
4222   PhiNode* vthread = new PhiNode(thread_compare_rgn, TypeInt::BOOL);
4223   record_for_igvn(vthread);
4224 
4225   // Merge the thread_compare control and memory.
4226   thread_compare_rgn->init_req(_true_path, control());
4227   thread_compare_rgn->init_req(_false_path, thread_equal_carrierThread);
4228   thread_compare_mem->init_req(_true_path, vthread_true_memory);
4229   thread_compare_mem->init_req(_false_path, vthread_false_memory);
4230 
4231   // Set output state.
4232   set_control(_gvn.transform(thread_compare_rgn));
4233   set_all_memory(_gvn.transform(thread_compare_mem));
4234 }
4235 
4236 #endif // JFR_HAVE_INTRINSICS
4237 
4238 //------------------------inline_native_currentCarrierThread------------------
4239 bool LibraryCallKit::inline_native_currentCarrierThread() {
4240   Node* junk = nullptr;
4241   set_result(generate_current_thread(junk));
4242   return true;
4243 }
4244 
4245 //------------------------inline_native_currentThread------------------
4246 bool LibraryCallKit::inline_native_currentThread() {
4247   Node* junk = nullptr;
4248   set_result(generate_virtual_thread(junk));
4249   return true;
4250 }
4251 
4252 //------------------------inline_native_setVthread------------------
4253 bool LibraryCallKit::inline_native_setCurrentThread() {
4254   assert(C->method()->changes_current_thread(),
4255          "method changes current Thread but is not annotated ChangesCurrentThread");
4256   Node* arr = argument(1);
4257   Node* thread = _gvn.transform(new ThreadLocalNode());
4258   Node* p = basic_plus_adr(top()/*!oop*/, thread, in_bytes(JavaThread::vthread_offset()));
4259   Node* thread_obj_handle
4260     = make_load(nullptr, p, p->bottom_type()->is_ptr(), T_OBJECT, MemNode::unordered);
4261   thread_obj_handle = _gvn.transform(thread_obj_handle);
4262   const TypePtr *adr_type = _gvn.type(thread_obj_handle)->isa_ptr();
4263   access_store_at(nullptr, thread_obj_handle, adr_type, arr, _gvn.type(arr), T_OBJECT, IN_NATIVE | MO_UNORDERED);
4264 
4265   // Change the _monitor_owner_id of the JavaThread
4266   Node* tid = load_field_from_object(arr, "tid", "J");
4267   Node* monitor_owner_id_offset = basic_plus_adr(thread, in_bytes(JavaThread::monitor_owner_id_offset()));
4268   store_to_memory(control(), monitor_owner_id_offset, tid, T_LONG, MemNode::unordered, true);
4269 
4270   JFR_ONLY(extend_setCurrentThread(thread, arr);)
4271   return true;
4272 }
4273 
4274 const Type* LibraryCallKit::scopedValueCache_type() {
4275   ciKlass* objects_klass = ciObjArrayKlass::make(env()->Object_klass());
4276   const TypeOopPtr* etype = TypeOopPtr::make_from_klass(env()->Object_klass());
4277   const TypeAry* arr0 = TypeAry::make(etype, TypeInt::POS, /* stable= */ false, /* flat= */ false, /* not_flat= */ true, /* not_null_free= */ true);
4278 
4279   // Because we create the scopedValue cache lazily we have to make the
4280   // type of the result BotPTR.
4281   bool xk = etype->klass_is_exact();
4282   const Type* objects_type = TypeAryPtr::make(TypePtr::BotPTR, arr0, objects_klass, xk, TypeAryPtr::Offset(0));
4283   return objects_type;
4284 }
4285 
4286 Node* LibraryCallKit::scopedValueCache_helper() {
4287   Node* thread = _gvn.transform(new ThreadLocalNode());
4288   Node* p = basic_plus_adr(top()/*!oop*/, thread, in_bytes(JavaThread::scopedValueCache_offset()));
4289   // We cannot use immutable_memory() because we might flip onto a
4290   // different carrier thread, at which point we'll need to use that
4291   // carrier thread's cache.
4292   // return _gvn.transform(LoadNode::make(_gvn, nullptr, immutable_memory(), p, p->bottom_type()->is_ptr(),
4293   //       TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered));
4294   return make_load(nullptr, p, p->bottom_type()->is_ptr(), T_ADDRESS, MemNode::unordered);
4295 }
4296 
4297 //------------------------inline_native_scopedValueCache------------------
4298 bool LibraryCallKit::inline_native_scopedValueCache() {
4299   Node* cache_obj_handle = scopedValueCache_helper();
4300   const Type* objects_type = scopedValueCache_type();
4301   set_result(access_load(cache_obj_handle, objects_type, T_OBJECT, IN_NATIVE));
4302 
4303   return true;
4304 }
4305 
4306 //------------------------inline_native_setScopedValueCache------------------
4307 bool LibraryCallKit::inline_native_setScopedValueCache() {
4308   Node* arr = argument(0);
4309   Node* cache_obj_handle = scopedValueCache_helper();
4310   const Type* objects_type = scopedValueCache_type();
4311 
4312   const TypePtr *adr_type = _gvn.type(cache_obj_handle)->isa_ptr();
4313   access_store_at(nullptr, cache_obj_handle, adr_type, arr, objects_type, T_OBJECT, IN_NATIVE | MO_UNORDERED);
4314 
4315   return true;
4316 }
4317 
4318 //------------------------inline_native_Continuation_pin and unpin-----------
4319 
4320 // Shared implementation routine for both pin and unpin.
4321 bool LibraryCallKit::inline_native_Continuation_pinning(bool unpin) {
4322   enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
4323 
4324   // Save input memory.
4325   Node* input_memory_state = reset_memory();
4326   set_all_memory(input_memory_state);
4327 
4328   // TLS
4329   Node* tls_ptr = _gvn.transform(new ThreadLocalNode());
4330   Node* last_continuation_offset = basic_plus_adr(top(), tls_ptr, in_bytes(JavaThread::cont_entry_offset()));
4331   Node* last_continuation = make_load(control(), last_continuation_offset, last_continuation_offset->get_ptr_type(), T_ADDRESS, MemNode::unordered);
4332 
4333   // Null check the last continuation object.
4334   Node* continuation_cmp_null = _gvn.transform(new CmpPNode(last_continuation, null()));
4335   Node* test_continuation_not_equal_null = _gvn.transform(new BoolNode(continuation_cmp_null, BoolTest::ne));
4336   IfNode* iff_continuation_not_equal_null = create_and_map_if(control(), test_continuation_not_equal_null, PROB_MAX, COUNT_UNKNOWN);
4337 
4338   // False path, last continuation is null.
4339   Node* continuation_is_null = _gvn.transform(new IfFalseNode(iff_continuation_not_equal_null));
4340 
4341   // True path, last continuation is not null.
4342   Node* continuation_is_not_null = _gvn.transform(new IfTrueNode(iff_continuation_not_equal_null));
4343 
4344   set_control(continuation_is_not_null);
4345 
4346   // Load the pin count from the last continuation.
4347   Node* pin_count_offset = basic_plus_adr(top(), last_continuation, in_bytes(ContinuationEntry::pin_count_offset()));
4348   Node* pin_count = make_load(control(), pin_count_offset, TypeInt::INT, T_INT, MemNode::unordered);
4349 
4350   // The loaded pin count is compared against a context specific rhs for over/underflow detection.
4351   Node* pin_count_rhs;
4352   if (unpin) {
4353     pin_count_rhs = _gvn.intcon(0);
4354   } else {
4355     pin_count_rhs = _gvn.intcon(UINT32_MAX);
4356   }
4357   Node* pin_count_cmp = _gvn.transform(new CmpUNode(_gvn.transform(pin_count), pin_count_rhs));
4358   Node* test_pin_count_over_underflow = _gvn.transform(new BoolNode(pin_count_cmp, BoolTest::eq));
4359   IfNode* iff_pin_count_over_underflow = create_and_map_if(control(), test_pin_count_over_underflow, PROB_MIN, COUNT_UNKNOWN);
4360 
4361   // True branch, pin count over/underflow.
4362   Node* pin_count_over_underflow = _gvn.transform(new IfTrueNode(iff_pin_count_over_underflow));
4363   {
4364     // Trap (but not deoptimize (Action_none)) and continue in the interpreter
4365     // which will throw IllegalStateException for pin count over/underflow.
4366     // No memory changed so far - we can use memory create by reset_memory()
4367     // at the beginning of this intrinsic. No need to call reset_memory() again.
4368     PreserveJVMState pjvms(this);
4369     set_control(pin_count_over_underflow);
4370     uncommon_trap(Deoptimization::Reason_intrinsic,
4371                   Deoptimization::Action_none);
4372     assert(stopped(), "invariant");
4373   }
4374 
4375   // False branch, no pin count over/underflow. Increment or decrement pin count and store back.
4376   Node* valid_pin_count = _gvn.transform(new IfFalseNode(iff_pin_count_over_underflow));
4377   set_control(valid_pin_count);
4378 
4379   Node* next_pin_count;
4380   if (unpin) {
4381     next_pin_count = _gvn.transform(new SubINode(pin_count, _gvn.intcon(1)));
4382   } else {
4383     next_pin_count = _gvn.transform(new AddINode(pin_count, _gvn.intcon(1)));
4384   }
4385 
4386   store_to_memory(control(), pin_count_offset, next_pin_count, T_INT, MemNode::unordered);
4387 
4388   // Result of top level CFG and Memory.
4389   RegionNode* result_rgn = new RegionNode(PATH_LIMIT);
4390   record_for_igvn(result_rgn);
4391   PhiNode* result_mem = new PhiNode(result_rgn, Type::MEMORY, TypePtr::BOTTOM);
4392   record_for_igvn(result_mem);
4393 
4394   result_rgn->init_req(_true_path, _gvn.transform(valid_pin_count));
4395   result_rgn->init_req(_false_path, _gvn.transform(continuation_is_null));
4396   result_mem->init_req(_true_path, _gvn.transform(reset_memory()));
4397   result_mem->init_req(_false_path, _gvn.transform(input_memory_state));
4398 
4399   // Set output state.
4400   set_control(_gvn.transform(result_rgn));
4401   set_all_memory(_gvn.transform(result_mem));
4402 
4403   return true;
4404 }
4405 
4406 //-----------------------load_klass_from_mirror_common-------------------------
4407 // Given a java mirror (a java.lang.Class oop), load its corresponding klass oop.
4408 // Test the klass oop for null (signifying a primitive Class like Integer.TYPE),
4409 // and branch to the given path on the region.
4410 // If never_see_null, take an uncommon trap on null, so we can optimistically
4411 // compile for the non-null case.
4412 // If the region is null, force never_see_null = true.
4413 Node* LibraryCallKit::load_klass_from_mirror_common(Node* mirror,
4414                                                     bool never_see_null,
4415                                                     RegionNode* region,
4416                                                     int null_path,
4417                                                     int offset) {
4418   if (region == nullptr)  never_see_null = true;
4419   Node* p = basic_plus_adr(mirror, offset);
4420   const TypeKlassPtr*  kls_type = TypeInstKlassPtr::OBJECT_OR_NULL;
4421   Node* kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), p, TypeRawPtr::BOTTOM, kls_type));
4422   Node* null_ctl = top();
4423   kls = null_check_oop(kls, &null_ctl, never_see_null);
4424   if (region != nullptr) {
4425     // Set region->in(null_path) if the mirror is a primitive (e.g, int.class).
4426     region->init_req(null_path, null_ctl);
4427   } else {
4428     assert(null_ctl == top(), "no loose ends");
4429   }
4430   return kls;
4431 }
4432 
4433 //--------------------(inline_native_Class_query helpers)---------------------
4434 // Use this for JVM_ACC_INTERFACE.
4435 // Fall through if (mods & mask) == bits, take the guard otherwise.
4436 Node* LibraryCallKit::generate_klass_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region,
4437                                                  ByteSize offset, const Type* type, BasicType bt) {
4438   // Branch around if the given klass has the given modifier bit set.
4439   // Like generate_guard, adds a new path onto the region.
4440   Node* modp = basic_plus_adr(kls, in_bytes(offset));
4441   Node* mods = make_load(nullptr, modp, type, bt, MemNode::unordered);
4442   Node* mask = intcon(modifier_mask);
4443   Node* bits = intcon(modifier_bits);
4444   Node* mbit = _gvn.transform(new AndINode(mods, mask));
4445   Node* cmp  = _gvn.transform(new CmpINode(mbit, bits));
4446   Node* bol  = _gvn.transform(new BoolNode(cmp, BoolTest::ne));
4447   return generate_fair_guard(bol, region);
4448 }
4449 
4450 Node* LibraryCallKit::generate_interface_guard(Node* kls, RegionNode* region) {
4451   return generate_klass_flags_guard(kls, JVM_ACC_INTERFACE, 0, region,
4452                                     Klass::access_flags_offset(), TypeInt::CHAR, T_CHAR);
4453 }
4454 
4455 // Use this for testing if Klass is_hidden, has_finalizer, and is_cloneable_fast.
4456 Node* LibraryCallKit::generate_misc_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region) {
4457   return generate_klass_flags_guard(kls, modifier_mask, modifier_bits, region,
4458                                     Klass::misc_flags_offset(), TypeInt::UBYTE, T_BOOLEAN);
4459 }
4460 
4461 Node* LibraryCallKit::generate_hidden_class_guard(Node* kls, RegionNode* region) {
4462   return generate_misc_flags_guard(kls, KlassFlags::_misc_is_hidden_class, 0, region);
4463 }
4464 
4465 //-------------------------inline_native_Class_query-------------------
4466 bool LibraryCallKit::inline_native_Class_query(vmIntrinsics::ID id) {
4467   const Type* return_type = TypeInt::BOOL;
4468   Node* prim_return_value = top();  // what happens if it's a primitive class?
4469   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
4470   bool expect_prim = false;     // most of these guys expect to work on refs
4471 
4472   enum { _normal_path = 1, _prim_path = 2, PATH_LIMIT };
4473 
4474   Node* mirror = argument(0);
4475   Node* obj    = top();
4476 
4477   switch (id) {
4478   case vmIntrinsics::_isInstance:
4479     // nothing is an instance of a primitive type
4480     prim_return_value = intcon(0);
4481     obj = argument(1);
4482     break;
4483   case vmIntrinsics::_isHidden:
4484     prim_return_value = intcon(0);
4485     break;
4486   case vmIntrinsics::_getSuperclass:
4487     prim_return_value = null();
4488     return_type = TypeInstPtr::MIRROR->cast_to_ptr_type(TypePtr::BotPTR);
4489     break;
4490   default:
4491     fatal_unexpected_iid(id);
4492     break;
4493   }
4494 
4495   const TypeInstPtr* mirror_con = _gvn.type(mirror)->isa_instptr();
4496   if (mirror_con == nullptr)  return false;  // cannot happen?
4497 
4498 #ifndef PRODUCT
4499   if (C->print_intrinsics() || C->print_inlining()) {
4500     ciType* k = mirror_con->java_mirror_type();
4501     if (k) {
4502       tty->print("Inlining %s on constant Class ", vmIntrinsics::name_at(intrinsic_id()));
4503       k->print_name();
4504       tty->cr();
4505     }
4506   }
4507 #endif
4508 
4509   // Null-check the mirror, and the mirror's klass ptr (in case it is a primitive).
4510   RegionNode* region = new RegionNode(PATH_LIMIT);
4511   record_for_igvn(region);
4512   PhiNode* phi = new PhiNode(region, return_type);
4513 
4514   // The mirror will never be null of Reflection.getClassAccessFlags, however
4515   // it may be null for Class.isInstance or Class.getModifiers. Throw a NPE
4516   // if it is. See bug 4774291.
4517 
4518   // For Reflection.getClassAccessFlags(), the null check occurs in
4519   // the wrong place; see inline_unsafe_access(), above, for a similar
4520   // situation.
4521   mirror = null_check(mirror);
4522   // If mirror or obj is dead, only null-path is taken.
4523   if (stopped())  return true;
4524 
4525   if (expect_prim)  never_see_null = false;  // expect nulls (meaning prims)
4526 
4527   // Now load the mirror's klass metaobject, and null-check it.
4528   // Side-effects region with the control path if the klass is null.
4529   Node* kls = load_klass_from_mirror(mirror, never_see_null, region, _prim_path);
4530   // If kls is null, we have a primitive mirror.
4531   phi->init_req(_prim_path, prim_return_value);
4532   if (stopped()) { set_result(region, phi); return true; }
4533   bool safe_for_replace = (region->in(_prim_path) == top());
4534 
4535   Node* p;  // handy temp
4536   Node* null_ctl;
4537 
4538   // Now that we have the non-null klass, we can perform the real query.
4539   // For constant classes, the query will constant-fold in LoadNode::Value.
4540   Node* query_value = top();
4541   switch (id) {
4542   case vmIntrinsics::_isInstance:
4543     // nothing is an instance of a primitive type
4544     query_value = gen_instanceof(obj, kls, safe_for_replace);
4545     break;
4546 
4547   case vmIntrinsics::_isHidden:
4548     // (To verify this code sequence, check the asserts in JVM_IsHiddenClass.)
4549     if (generate_hidden_class_guard(kls, region) != nullptr)
4550       // A guard was added.  If the guard is taken, it was an hidden class.
4551       phi->add_req(intcon(1));
4552     // If we fall through, it's a plain class.
4553     query_value = intcon(0);
4554     break;
4555 
4556 
4557   case vmIntrinsics::_getSuperclass:
4558     // The rules here are somewhat unfortunate, but we can still do better
4559     // with random logic than with a JNI call.
4560     // Interfaces store null or Object as _super, but must report null.
4561     // Arrays store an intermediate super as _super, but must report Object.
4562     // Other types can report the actual _super.
4563     // (To verify this code sequence, check the asserts in JVM_IsInterface.)
4564     if (generate_interface_guard(kls, region) != nullptr)
4565       // A guard was added.  If the guard is taken, it was an interface.
4566       phi->add_req(null());
4567     if (generate_array_guard(kls, region) != nullptr)
4568       // A guard was added.  If the guard is taken, it was an array.
4569       phi->add_req(makecon(TypeInstPtr::make(env()->Object_klass()->java_mirror())));
4570     // If we fall through, it's a plain class.  Get its _super.
4571     if (!stopped()) {
4572       p = basic_plus_adr(kls, in_bytes(Klass::super_offset()));
4573       kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), p, TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
4574       null_ctl = top();
4575       kls = null_check_oop(kls, &null_ctl);
4576       if (null_ctl != top()) {
4577         // If the guard is taken, Object.superClass is null (both klass and mirror).
4578         region->add_req(null_ctl);
4579         phi   ->add_req(null());
4580       }
4581       if (!stopped()) {
4582         query_value = load_mirror_from_klass(kls);
4583       }
4584     }
4585     break;
4586 
4587   default:
4588     fatal_unexpected_iid(id);
4589     break;
4590   }
4591 
4592   // Fall-through is the normal case of a query to a real class.
4593   phi->init_req(1, query_value);
4594   region->init_req(1, control());
4595 
4596   C->set_has_split_ifs(true); // Has chance for split-if optimization
4597   set_result(region, phi);
4598   return true;
4599 }
4600 
4601 
4602 //-------------------------inline_Class_cast-------------------
4603 bool LibraryCallKit::inline_Class_cast() {
4604   Node* mirror = argument(0); // Class
4605   Node* obj    = argument(1);
4606   const TypeInstPtr* mirror_con = _gvn.type(mirror)->isa_instptr();
4607   if (mirror_con == nullptr) {
4608     return false;  // dead path (mirror->is_top()).
4609   }
4610   if (obj == nullptr || obj->is_top()) {
4611     return false;  // dead path
4612   }
4613   const TypeOopPtr* tp = _gvn.type(obj)->isa_oopptr();
4614 
4615   // First, see if Class.cast() can be folded statically.
4616   // java_mirror_type() returns non-null for compile-time Class constants.
4617   ciType* tm = mirror_con->java_mirror_type();
4618   if (tm != nullptr && tm->is_klass() &&
4619       tp != nullptr) {
4620     if (!tp->is_loaded()) {
4621       // Don't use intrinsic when class is not loaded.
4622       return false;
4623     } else {
4624       const TypeKlassPtr* tklass = TypeKlassPtr::make(tm->as_klass(), Type::trust_interfaces);
4625       int static_res = C->static_subtype_check(tklass, tp->as_klass_type());
4626       if (static_res == Compile::SSC_always_true) {
4627         // isInstance() is true - fold the code.
4628         set_result(obj);
4629         return true;
4630       } else if (static_res == Compile::SSC_always_false) {
4631         // Don't use intrinsic, have to throw ClassCastException.
4632         // If the reference is null, the non-intrinsic bytecode will
4633         // be optimized appropriately.
4634         return false;
4635       }
4636     }
4637   }
4638 
4639   // Bailout intrinsic and do normal inlining if exception path is frequent.
4640   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
4641     return false;
4642   }
4643 
4644   // Generate dynamic checks.
4645   // Class.cast() is java implementation of _checkcast bytecode.
4646   // Do checkcast (Parse::do_checkcast()) optimizations here.
4647 
4648   mirror = null_check(mirror);
4649   // If mirror is dead, only null-path is taken.
4650   if (stopped()) {
4651     return true;
4652   }
4653 
4654   // Not-subtype or the mirror's klass ptr is nullptr (in case it is a primitive).
4655   enum { _bad_type_path = 1, _prim_path = 2, _npe_path = 3, PATH_LIMIT };
4656   RegionNode* region = new RegionNode(PATH_LIMIT);
4657   record_for_igvn(region);
4658 
4659   // Now load the mirror's klass metaobject, and null-check it.
4660   // If kls is null, we have a primitive mirror and
4661   // nothing is an instance of a primitive type.
4662   Node* kls = load_klass_from_mirror(mirror, false, region, _prim_path);
4663 
4664   Node* res = top();
4665   Node* io = i_o();
4666   Node* mem = merged_memory();
4667   if (!stopped()) {
4668 
4669     Node* bad_type_ctrl = top();
4670     // Do checkcast optimizations.
4671     res = gen_checkcast(obj, kls, &bad_type_ctrl);
4672     region->init_req(_bad_type_path, bad_type_ctrl);
4673   }
4674   if (region->in(_prim_path) != top() ||
4675       region->in(_bad_type_path) != top() ||
4676       region->in(_npe_path) != top()) {
4677     // Let Interpreter throw ClassCastException.
4678     PreserveJVMState pjvms(this);
4679     set_control(_gvn.transform(region));
4680     // Set IO and memory because gen_checkcast may override them when buffering inline types
4681     set_i_o(io);
4682     set_all_memory(mem);
4683     uncommon_trap(Deoptimization::Reason_intrinsic,
4684                   Deoptimization::Action_maybe_recompile);
4685   }
4686   if (!stopped()) {
4687     set_result(res);
4688   }
4689   return true;
4690 }
4691 
4692 
4693 //--------------------------inline_native_subtype_check------------------------
4694 // This intrinsic takes the JNI calls out of the heart of
4695 // UnsafeFieldAccessorImpl.set, which improves Field.set, readObject, etc.
4696 bool LibraryCallKit::inline_native_subtype_check() {
4697   // Pull both arguments off the stack.
4698   Node* args[2];                // two java.lang.Class mirrors: superc, subc
4699   args[0] = argument(0);
4700   args[1] = argument(1);
4701   Node* klasses[2];             // corresponding Klasses: superk, subk
4702   klasses[0] = klasses[1] = top();
4703 
4704   enum {
4705     // A full decision tree on {superc is prim, subc is prim}:
4706     _prim_0_path = 1,           // {P,N} => false
4707                                 // {P,P} & superc!=subc => false
4708     _prim_same_path,            // {P,P} & superc==subc => true
4709     _prim_1_path,               // {N,P} => false
4710     _ref_subtype_path,          // {N,N} & subtype check wins => true
4711     _both_ref_path,             // {N,N} & subtype check loses => false
4712     PATH_LIMIT
4713   };
4714 
4715   RegionNode* region = new RegionNode(PATH_LIMIT);
4716   RegionNode* prim_region = new RegionNode(2);
4717   Node*       phi    = new PhiNode(region, TypeInt::BOOL);
4718   record_for_igvn(region);
4719   record_for_igvn(prim_region);
4720 
4721   const TypePtr* adr_type = TypeRawPtr::BOTTOM;   // memory type of loads
4722   const TypeKlassPtr* kls_type = TypeInstKlassPtr::OBJECT_OR_NULL;
4723   int class_klass_offset = java_lang_Class::klass_offset();
4724 
4725   // First null-check both mirrors and load each mirror's klass metaobject.
4726   int which_arg;
4727   for (which_arg = 0; which_arg <= 1; which_arg++) {
4728     Node* arg = args[which_arg];
4729     arg = null_check(arg);
4730     if (stopped())  break;
4731     args[which_arg] = arg;
4732 
4733     Node* p = basic_plus_adr(arg, class_klass_offset);
4734     Node* kls = LoadKlassNode::make(_gvn, immutable_memory(), p, adr_type, kls_type);
4735     klasses[which_arg] = _gvn.transform(kls);
4736   }
4737 
4738   // Having loaded both klasses, test each for null.
4739   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
4740   for (which_arg = 0; which_arg <= 1; which_arg++) {
4741     Node* kls = klasses[which_arg];
4742     Node* null_ctl = top();
4743     kls = null_check_oop(kls, &null_ctl, never_see_null);
4744     if (which_arg == 0) {
4745       prim_region->init_req(1, null_ctl);
4746     } else {
4747       region->init_req(_prim_1_path, null_ctl);
4748     }
4749     if (stopped())  break;
4750     klasses[which_arg] = kls;
4751   }
4752 
4753   if (!stopped()) {
4754     // now we have two reference types, in klasses[0..1]
4755     Node* subk   = klasses[1];  // the argument to isAssignableFrom
4756     Node* superk = klasses[0];  // the receiver
4757     region->set_req(_both_ref_path, gen_subtype_check(subk, superk));
4758     region->set_req(_ref_subtype_path, control());
4759   }
4760 
4761   // If both operands are primitive (both klasses null), then
4762   // we must return true when they are identical primitives.
4763   // It is convenient to test this after the first null klass check.
4764   // This path is also used if superc is a value mirror.
4765   set_control(_gvn.transform(prim_region));
4766   if (!stopped()) {
4767     // Since superc is primitive, make a guard for the superc==subc case.
4768     Node* cmp_eq = _gvn.transform(new CmpPNode(args[0], args[1]));
4769     Node* bol_eq = _gvn.transform(new BoolNode(cmp_eq, BoolTest::eq));
4770     generate_fair_guard(bol_eq, region);
4771     if (region->req() == PATH_LIMIT+1) {
4772       // A guard was added.  If the added guard is taken, superc==subc.
4773       region->swap_edges(PATH_LIMIT, _prim_same_path);
4774       region->del_req(PATH_LIMIT);
4775     }
4776     region->set_req(_prim_0_path, control()); // Not equal after all.
4777   }
4778 
4779   // these are the only paths that produce 'true':
4780   phi->set_req(_prim_same_path,   intcon(1));
4781   phi->set_req(_ref_subtype_path, intcon(1));
4782 
4783   // pull together the cases:
4784   assert(region->req() == PATH_LIMIT, "sane region");
4785   for (uint i = 1; i < region->req(); i++) {
4786     Node* ctl = region->in(i);
4787     if (ctl == nullptr || ctl == top()) {
4788       region->set_req(i, top());
4789       phi   ->set_req(i, top());
4790     } else if (phi->in(i) == nullptr) {
4791       phi->set_req(i, intcon(0)); // all other paths produce 'false'
4792     }
4793   }
4794 
4795   set_control(_gvn.transform(region));
4796   set_result(_gvn.transform(phi));
4797   return true;
4798 }
4799 
4800 //---------------------generate_array_guard_common------------------------
4801 Node* LibraryCallKit::generate_array_guard_common(Node* kls, RegionNode* region, ArrayKind kind, Node** obj) {
4802 
4803   if (stopped()) {
4804     return nullptr;
4805   }
4806 
4807   // Like generate_guard, adds a new path onto the region.
4808   jint  layout_con = 0;
4809   Node* layout_val = get_layout_helper(kls, layout_con);
4810   if (layout_val == nullptr) {
4811     bool query = 0;
4812     switch(kind) {
4813       case RefArray:       query = Klass::layout_helper_is_refArray(layout_con); break;
4814       case NonRefArray:    query = !Klass::layout_helper_is_refArray(layout_con); break;
4815       case TypeArray:      query = Klass::layout_helper_is_typeArray(layout_con); break;
4816       case AnyArray:       query = Klass::layout_helper_is_array(layout_con); break;
4817       case NonArray:       query = !Klass::layout_helper_is_array(layout_con); break;
4818       default:
4819         ShouldNotReachHere();
4820     }
4821     if (!query) {
4822       return nullptr;                       // never a branch
4823     } else {                             // always a branch
4824       Node* always_branch = control();
4825       if (region != nullptr)
4826         region->add_req(always_branch);
4827       set_control(top());
4828       return always_branch;
4829     }
4830   }
4831   unsigned int value = 0;
4832   BoolTest::mask btest = BoolTest::illegal;
4833   switch(kind) {
4834     case RefArray:
4835     case NonRefArray: {
4836       value = Klass::_lh_array_tag_ref_value;
4837       layout_val = _gvn.transform(new RShiftINode(layout_val, intcon(Klass::_lh_array_tag_shift)));
4838       btest = (kind == RefArray) ? BoolTest::eq : BoolTest::ne;
4839       break;
4840     }
4841     case TypeArray: {
4842       value = Klass::_lh_array_tag_type_value;
4843       layout_val = _gvn.transform(new RShiftINode(layout_val, intcon(Klass::_lh_array_tag_shift)));
4844       btest = BoolTest::eq;
4845       break;
4846     }
4847     case AnyArray:    value = Klass::_lh_neutral_value; btest = BoolTest::lt; break;
4848     case NonArray:    value = Klass::_lh_neutral_value; btest = BoolTest::gt; break;
4849     default:
4850       ShouldNotReachHere();
4851   }
4852   // Now test the correct condition.
4853   jint nval = (jint)value;
4854   Node* cmp = _gvn.transform(new CmpINode(layout_val, intcon(nval)));
4855   Node* bol = _gvn.transform(new BoolNode(cmp, btest));
4856   Node* ctrl = generate_fair_guard(bol, region);
4857   Node* is_array_ctrl = kind == NonArray ? control() : ctrl;
4858   if (obj != nullptr && is_array_ctrl != nullptr && is_array_ctrl != top()) {
4859     // Keep track of the fact that 'obj' is an array to prevent
4860     // array specific accesses from floating above the guard.
4861     *obj = _gvn.transform(new CastPPNode(is_array_ctrl, *obj, TypeAryPtr::BOTTOM));
4862   }
4863   return ctrl;
4864 }
4865 
4866 // public static native Object[] ValueClass::newNullRestrictedAtomicArray(Class<?> componentType, int length, Object initVal);
4867 // public static native Object[] ValueClass::newNullRestrictedNonAtomicArray(Class<?> componentType, int length, Object initVal);
4868 // public static native Object[] ValueClass::newNullableAtomicArray(Class<?> componentType, int length);
4869 bool LibraryCallKit::inline_newArray(bool null_free, bool atomic) {
4870   assert(null_free || atomic, "nullable implies atomic");
4871   Node* componentType = argument(0);
4872   Node* length = argument(1);
4873   Node* init_val = null_free ? argument(2) : nullptr;
4874 
4875   const TypeInstPtr* tp = _gvn.type(componentType)->isa_instptr();
4876   if (tp != nullptr) {
4877     ciInstanceKlass* ik = tp->instance_klass();
4878     if (ik == C->env()->Class_klass()) {
4879       ciType* t = tp->java_mirror_type();
4880       if (t != nullptr && t->is_inlinetype()) {
4881 
4882         ciArrayKlass* array_klass = ciArrayKlass::make(t, null_free, atomic, true);
4883         assert(array_klass->is_elem_null_free() == null_free, "inconsistency");
4884         assert(array_klass->is_elem_atomic() == atomic, "inconsistency");
4885 
4886         // TOOD 8350865 ZGC needs card marks on initializing oop stores
4887         if (UseZGC && null_free && !array_klass->is_flat_array_klass()) {
4888           return false;
4889         }
4890 
4891         if (array_klass->is_loaded() && array_klass->element_klass()->as_inline_klass()->is_initialized()) {
4892           const TypeAryKlassPtr* array_klass_type = TypeAryKlassPtr::make(array_klass, Type::trust_interfaces, true);
4893           if (null_free) {
4894             if (init_val->is_InlineType()) {
4895               if (array_klass_type->is_flat() && init_val->as_InlineType()->is_all_zero(&gvn(), /* flat */ true)) {
4896                 // Zeroing is enough because the init value is the all-zero value
4897                 init_val = nullptr;
4898               } else {
4899                 init_val = init_val->as_InlineType()->buffer(this);
4900               }
4901             }
4902             // TODO 8350865 Should we add a check of the init_val type (maybe in debug only + halt)?
4903           }
4904           Node* obj = new_array(makecon(array_klass_type), length, 0, nullptr, false, init_val);
4905           const TypeAryPtr* arytype = gvn().type(obj)->is_aryptr();
4906           assert(arytype->is_null_free() == null_free, "inconsistency");
4907           assert(arytype->is_not_null_free() == !null_free, "inconsistency");
4908           assert(arytype->is_atomic() == atomic, "inconsistency");
4909           set_result(obj);
4910           return true;
4911         }
4912       }
4913     }
4914   }
4915   return false;
4916 }
4917 
4918 // public static native boolean ValueClass::isFlatArray(Object array);
4919 // public static native boolean ValueClass::isNullRestrictedArray(Object array);
4920 // public static native boolean ValueClass::isAtomicArray(Object array);
4921 bool LibraryCallKit::inline_getArrayProperties(ArrayPropertiesCheck check) {
4922   Node* array = argument(0);
4923 
4924   Node* bol;
4925   switch(check) {
4926     case IsFlat:
4927       // TODO 8350865 Use the object version here instead of loading the klass
4928       // 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
4929       bol = flat_array_test(load_object_klass(array));
4930       break;
4931     case IsNullRestricted:
4932       bol = null_free_array_test(array);
4933       break;
4934     case IsAtomic:
4935       // TODO 8350865 Implement this. It's a bit more complicated, see conditions in JVM_IsAtomicArray
4936       // Enable TestIntrinsics::test87/88 once this is implemented
4937       // bol = null_free_atomic_array_test
4938       return false;
4939     default:
4940       ShouldNotReachHere();
4941   }
4942 
4943   Node* res = gvn().transform(new CMoveINode(bol, intcon(0), intcon(1), TypeInt::BOOL));
4944   set_result(res);
4945   return true;
4946 }
4947 
4948 // Load the default refined array klass from an ObjArrayKlass. This relies on the first entry in the
4949 // '_next_refined_array_klass' linked list being the default (see ObjArrayKlass::klass_with_properties).
4950 Node* LibraryCallKit::load_default_refined_array_klass(Node* klass_node, bool type_array_guard) {
4951   RegionNode* region = new RegionNode(2);
4952   Node* phi = new PhiNode(region, TypeInstKlassPtr::OBJECT_OR_NULL);
4953 
4954   if (type_array_guard) {
4955     generate_typeArray_guard(klass_node, region);
4956     if (region->req() == 3) {
4957       phi->add_req(klass_node);
4958     }
4959   }
4960   Node* adr_refined_klass = basic_plus_adr(klass_node, in_bytes(ObjArrayKlass::next_refined_array_klass_offset()));
4961   Node* refined_klass = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), adr_refined_klass, TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
4962 
4963   // Can be null if not initialized yet, just deopt
4964   Node* null_ctl = top();
4965   refined_klass = null_check_oop(refined_klass, &null_ctl, /* never_see_null= */ true);
4966 
4967   region->init_req(1, control());
4968   phi->init_req(1, refined_klass);
4969 
4970   set_control(_gvn.transform(region));
4971   return _gvn.transform(phi);
4972 }
4973 
4974 // Load the non-refined array klass from an ObjArrayKlass.
4975 Node* LibraryCallKit::load_non_refined_array_klass(Node* klass_node) {
4976   const TypeAryKlassPtr* ary_klass_ptr = _gvn.type(klass_node)->isa_aryklassptr();
4977   if (ary_klass_ptr != nullptr && ary_klass_ptr->klass_is_exact()) {
4978     return _gvn.makecon(ary_klass_ptr->cast_to_refined_array_klass_ptr(false));
4979   }
4980 
4981   RegionNode* region = new RegionNode(2);
4982   Node* phi = new PhiNode(region, TypeInstKlassPtr::OBJECT);
4983 
4984   generate_typeArray_guard(klass_node, region);
4985   if (region->req() == 3) {
4986     phi->add_req(klass_node);
4987   }
4988   Node* super_adr = basic_plus_adr(klass_node, in_bytes(Klass::super_offset()));
4989   Node* super_klass = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), super_adr, TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT));
4990 
4991   region->init_req(1, control());
4992   phi->init_req(1, super_klass);
4993 
4994   set_control(_gvn.transform(region));
4995   return _gvn.transform(phi);
4996 }
4997 
4998 //-----------------------inline_native_newArray--------------------------
4999 // private static native Object java.lang.reflect.Array.newArray(Class<?> componentType, int length);
5000 // private        native Object Unsafe.allocateUninitializedArray0(Class<?> cls, int size);
5001 bool LibraryCallKit::inline_unsafe_newArray(bool uninitialized) {
5002   Node* mirror;
5003   Node* count_val;
5004   if (uninitialized) {
5005     null_check_receiver();
5006     mirror    = argument(1);
5007     count_val = argument(2);
5008   } else {
5009     mirror    = argument(0);
5010     count_val = argument(1);
5011   }
5012 
5013   mirror = null_check(mirror);
5014   // If mirror or obj is dead, only null-path is taken.
5015   if (stopped())  return true;
5016 
5017   enum { _normal_path = 1, _slow_path = 2, PATH_LIMIT };
5018   RegionNode* result_reg = new RegionNode(PATH_LIMIT);
5019   PhiNode*    result_val = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
5020   PhiNode*    result_io  = new PhiNode(result_reg, Type::ABIO);
5021   PhiNode*    result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
5022 
5023   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
5024   Node* klass_node = load_array_klass_from_mirror(mirror, never_see_null,
5025                                                   result_reg, _slow_path);
5026   Node* normal_ctl   = control();
5027   Node* no_array_ctl = result_reg->in(_slow_path);
5028 
5029   // Generate code for the slow case.  We make a call to newArray().
5030   set_control(no_array_ctl);
5031   if (!stopped()) {
5032     // Either the input type is void.class, or else the
5033     // array klass has not yet been cached.  Either the
5034     // ensuing call will throw an exception, or else it
5035     // will cache the array klass for next time.
5036     PreserveJVMState pjvms(this);
5037     CallJavaNode* slow_call = nullptr;
5038     if (uninitialized) {
5039       // Generate optimized virtual call (holder class 'Unsafe' is final)
5040       slow_call = generate_method_call(vmIntrinsics::_allocateUninitializedArray, false, false, true);
5041     } else {
5042       slow_call = generate_method_call_static(vmIntrinsics::_newArray, true);
5043     }
5044     Node* slow_result = set_results_for_java_call(slow_call);
5045     // this->control() comes from set_results_for_java_call
5046     result_reg->set_req(_slow_path, control());
5047     result_val->set_req(_slow_path, slow_result);
5048     result_io ->set_req(_slow_path, i_o());
5049     result_mem->set_req(_slow_path, reset_memory());
5050   }
5051 
5052   set_control(normal_ctl);
5053   if (!stopped()) {
5054     // Normal case:  The array type has been cached in the java.lang.Class.
5055     // The following call works fine even if the array type is polymorphic.
5056     // It could be a dynamic mix of int[], boolean[], Object[], etc.
5057 
5058     klass_node = load_default_refined_array_klass(klass_node);
5059 
5060     Node* obj = new_array(klass_node, count_val, 0);  // no arguments to push
5061     result_reg->init_req(_normal_path, control());
5062     result_val->init_req(_normal_path, obj);
5063     result_io ->init_req(_normal_path, i_o());
5064     result_mem->init_req(_normal_path, reset_memory());
5065 
5066     if (uninitialized) {
5067       // Mark the allocation so that zeroing is skipped
5068       AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(obj);
5069       alloc->maybe_set_complete(&_gvn);
5070     }
5071   }
5072 
5073   // Return the combined state.
5074   set_i_o(        _gvn.transform(result_io)  );
5075   set_all_memory( _gvn.transform(result_mem));
5076 
5077   C->set_has_split_ifs(true); // Has chance for split-if optimization
5078   set_result(result_reg, result_val);
5079   return true;
5080 }
5081 
5082 //----------------------inline_native_getLength--------------------------
5083 // public static native int java.lang.reflect.Array.getLength(Object array);
5084 bool LibraryCallKit::inline_native_getLength() {
5085   if (too_many_traps(Deoptimization::Reason_intrinsic))  return false;
5086 
5087   Node* array = null_check(argument(0));
5088   // If array is dead, only null-path is taken.
5089   if (stopped())  return true;
5090 
5091   // Deoptimize if it is a non-array.
5092   Node* non_array = generate_non_array_guard(load_object_klass(array), nullptr, &array);
5093 
5094   if (non_array != nullptr) {
5095     PreserveJVMState pjvms(this);
5096     set_control(non_array);
5097     uncommon_trap(Deoptimization::Reason_intrinsic,
5098                   Deoptimization::Action_maybe_recompile);
5099   }
5100 
5101   // If control is dead, only non-array-path is taken.
5102   if (stopped())  return true;
5103 
5104   // The works fine even if the array type is polymorphic.
5105   // It could be a dynamic mix of int[], boolean[], Object[], etc.
5106   Node* result = load_array_length(array);
5107 
5108   C->set_has_split_ifs(true);  // Has chance for split-if optimization
5109   set_result(result);
5110   return true;
5111 }
5112 
5113 //------------------------inline_array_copyOf----------------------------
5114 // public static <T,U> T[] java.util.Arrays.copyOf(     U[] original, int newLength,         Class<? extends T[]> newType);
5115 // public static <T,U> T[] java.util.Arrays.copyOfRange(U[] original, int from,      int to, Class<? extends T[]> newType);
5116 bool LibraryCallKit::inline_array_copyOf(bool is_copyOfRange) {
5117   if (too_many_traps(Deoptimization::Reason_intrinsic))  return false;
5118 
5119   // Get the arguments.
5120   Node* original          = argument(0);
5121   Node* start             = is_copyOfRange? argument(1): intcon(0);
5122   Node* end               = is_copyOfRange? argument(2): argument(1);
5123   Node* array_type_mirror = is_copyOfRange? argument(3): argument(2);
5124 
5125   Node* newcopy = nullptr;
5126 
5127   // Set the original stack and the reexecute bit for the interpreter to reexecute
5128   // the bytecode that invokes Arrays.copyOf if deoptimization happens.
5129   { PreserveReexecuteState preexecs(this);
5130     jvms()->set_should_reexecute(true);
5131 
5132     array_type_mirror = null_check(array_type_mirror);
5133     original          = null_check(original);
5134 
5135     // Check if a null path was taken unconditionally.
5136     if (stopped())  return true;
5137 
5138     Node* orig_length = load_array_length(original);
5139 
5140     Node* klass_node = load_klass_from_mirror(array_type_mirror, false, nullptr, 0);
5141     klass_node = null_check(klass_node);
5142 
5143     RegionNode* bailout = new RegionNode(1);
5144     record_for_igvn(bailout);
5145 
5146     // Despite the generic type of Arrays.copyOf, the mirror might be int, int[], etc.
5147     // Bail out if that is so.
5148     // Inline type array may have object field that would require a
5149     // write barrier. Conservatively, go to slow path.
5150     // TODO 8251971: Optimize for the case when flat src/dst are later found
5151     // to not contain oops (i.e., move this check to the macro expansion phase).
5152     BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
5153     const TypeAryPtr* orig_t = _gvn.type(original)->isa_aryptr();
5154     const TypeKlassPtr* tklass = _gvn.type(klass_node)->is_klassptr();
5155     bool exclude_flat = UseArrayFlattening && bs->array_copy_requires_gc_barriers(true, T_OBJECT, false, false, BarrierSetC2::Parsing) &&
5156                         // Can src array be flat and contain oops?
5157                         (orig_t == nullptr || (!orig_t->is_not_flat() && (!orig_t->is_flat() || orig_t->elem()->inline_klass()->contains_oops()))) &&
5158                         // Can dest array be flat and contain oops?
5159                         tklass->can_be_inline_array() && (!tklass->is_flat() || tklass->is_aryklassptr()->elem()->is_instklassptr()->instance_klass()->as_inline_klass()->contains_oops());
5160     Node* not_objArray = exclude_flat ? generate_non_refArray_guard(klass_node, bailout) : generate_typeArray_guard(klass_node, bailout);
5161 
5162     Node* refined_klass_node = load_default_refined_array_klass(klass_node, /* type_array_guard= */ false);
5163 
5164     if (not_objArray != nullptr) {
5165       // Improve the klass node's type from the new optimistic assumption:
5166       ciKlass* ak = ciArrayKlass::make(env()->Object_klass());
5167       const Type* akls = TypeKlassPtr::make(TypePtr::NotNull, ak, Type::Offset(0));
5168       Node* cast = new CastPPNode(control(), refined_klass_node, akls);
5169       refined_klass_node = _gvn.transform(cast);
5170     }
5171 
5172     // Bail out if either start or end is negative.
5173     generate_negative_guard(start, bailout, &start);
5174     generate_negative_guard(end,   bailout, &end);
5175 
5176     Node* length = end;
5177     if (_gvn.type(start) != TypeInt::ZERO) {
5178       length = _gvn.transform(new SubINode(end, start));
5179     }
5180 
5181     // Bail out if length is negative (i.e., if start > end).
5182     // Without this the new_array would throw
5183     // NegativeArraySizeException but IllegalArgumentException is what
5184     // should be thrown
5185     generate_negative_guard(length, bailout, &length);
5186 
5187     // Handle inline type arrays
5188     bool can_validate = !too_many_traps(Deoptimization::Reason_class_check);
5189     if (!stopped()) {
5190       // TODO 8251971
5191       if (!orig_t->is_null_free()) {
5192         // Not statically known to be null free, add a check
5193         generate_fair_guard(null_free_array_test(original), bailout);
5194       }
5195       orig_t = _gvn.type(original)->isa_aryptr();
5196       if (orig_t != nullptr && orig_t->is_flat()) {
5197         // Src is flat, check that dest is flat as well
5198         if (exclude_flat) {
5199           // Dest can't be flat, bail out
5200           bailout->add_req(control());
5201           set_control(top());
5202         } else {
5203           generate_fair_guard(flat_array_test(refined_klass_node, /* flat = */ false), bailout);
5204         }
5205         // TODO 8350865 This is not correct anymore. Write tests and fix logic similar to arraycopy.
5206       } else if (UseArrayFlattening && (orig_t == nullptr || !orig_t->is_not_flat()) &&
5207                  // If dest is flat, src must be flat as well (guaranteed by src <: dest check if validated).
5208                  ((!tklass->is_flat() && tklass->can_be_inline_array()) || !can_validate)) {
5209         // Src might be flat and dest might not be flat. Go to the slow path if src is flat.
5210         // TODO 8251971: Optimize for the case when src/dest are later found to be both flat.
5211         generate_fair_guard(flat_array_test(load_object_klass(original)), bailout);
5212         if (orig_t != nullptr) {
5213           orig_t = orig_t->cast_to_not_flat();
5214           original = _gvn.transform(new CheckCastPPNode(control(), original, orig_t));
5215         }
5216       }
5217       if (!can_validate) {
5218         // No validation. The subtype check emitted at macro expansion time will not go to the slow
5219         // path but call checkcast_arraycopy which can not handle flat/null-free inline type arrays.
5220         // TODO 8251971: Optimize for the case when src/dest are later found to be both flat/null-free.
5221         generate_fair_guard(flat_array_test(refined_klass_node), bailout);
5222         generate_fair_guard(null_free_array_test(original), bailout);
5223       }
5224     }
5225 
5226     // Bail out if start is larger than the original length
5227     Node* orig_tail = _gvn.transform(new SubINode(orig_length, start));
5228     generate_negative_guard(orig_tail, bailout, &orig_tail);
5229 
5230     if (bailout->req() > 1) {
5231       PreserveJVMState pjvms(this);
5232       set_control(_gvn.transform(bailout));
5233       uncommon_trap(Deoptimization::Reason_intrinsic,
5234                     Deoptimization::Action_maybe_recompile);
5235     }
5236 
5237     if (!stopped()) {
5238       // How many elements will we copy from the original?
5239       // The answer is MinI(orig_tail, length).
5240       Node* moved = _gvn.transform(new MinINode(orig_tail, length));
5241 
5242       // Generate a direct call to the right arraycopy function(s).
5243       // We know the copy is disjoint but we might not know if the
5244       // oop stores need checking.
5245       // Extreme case:  Arrays.copyOf((Integer[])x, 10, String[].class).
5246       // This will fail a store-check if x contains any non-nulls.
5247 
5248       // ArrayCopyNode:Ideal may transform the ArrayCopyNode to
5249       // loads/stores but it is legal only if we're sure the
5250       // Arrays.copyOf would succeed. So we need all input arguments
5251       // to the copyOf to be validated, including that the copy to the
5252       // new array won't trigger an ArrayStoreException. That subtype
5253       // check can be optimized if we know something on the type of
5254       // the input array from type speculation.
5255       if (_gvn.type(klass_node)->singleton()) {
5256         const TypeKlassPtr* subk = _gvn.type(load_object_klass(original))->is_klassptr();
5257         const TypeKlassPtr* superk = _gvn.type(klass_node)->is_klassptr();
5258 
5259         int test = C->static_subtype_check(superk, subk);
5260         if (test != Compile::SSC_always_true && test != Compile::SSC_always_false) {
5261           const TypeOopPtr* t_original = _gvn.type(original)->is_oopptr();
5262           if (t_original->speculative_type() != nullptr) {
5263             original = maybe_cast_profiled_obj(original, t_original->speculative_type(), true);
5264           }
5265         }
5266       }
5267 
5268       bool validated = false;
5269       // Reason_class_check rather than Reason_intrinsic because we
5270       // want to intrinsify even if this traps.
5271       if (can_validate) {
5272         Node* not_subtype_ctrl = gen_subtype_check(original, klass_node);
5273 
5274         if (not_subtype_ctrl != top()) {
5275           PreserveJVMState pjvms(this);
5276           set_control(not_subtype_ctrl);
5277           uncommon_trap(Deoptimization::Reason_class_check,
5278                         Deoptimization::Action_make_not_entrant);
5279           assert(stopped(), "Should be stopped");
5280         }
5281         validated = true;
5282       }
5283 
5284       if (!stopped()) {
5285         newcopy = new_array(refined_klass_node, length, 0);  // no arguments to push
5286 
5287         ArrayCopyNode* ac = ArrayCopyNode::make(this, true, original, start, newcopy, intcon(0), moved, true, true,
5288                                                 load_object_klass(original), klass_node);
5289         if (!is_copyOfRange) {
5290           ac->set_copyof(validated);
5291         } else {
5292           ac->set_copyofrange(validated);
5293         }
5294         Node* n = _gvn.transform(ac);
5295         if (n == ac) {
5296           ac->connect_outputs(this);
5297         } else {
5298           assert(validated, "shouldn't transform if all arguments not validated");
5299           set_all_memory(n);
5300         }
5301       }
5302     }
5303   } // original reexecute is set back here
5304 
5305   C->set_has_split_ifs(true); // Has chance for split-if optimization
5306   if (!stopped()) {
5307     set_result(newcopy);
5308   }
5309   return true;
5310 }
5311 
5312 
5313 //----------------------generate_virtual_guard---------------------------
5314 // Helper for hashCode and clone.  Peeks inside the vtable to avoid a call.
5315 Node* LibraryCallKit::generate_virtual_guard(Node* obj_klass,
5316                                              RegionNode* slow_region) {
5317   ciMethod* method = callee();
5318   int vtable_index = method->vtable_index();
5319   assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index,
5320          "bad index %d", vtable_index);
5321   // Get the Method* out of the appropriate vtable entry.
5322   int entry_offset  = in_bytes(Klass::vtable_start_offset()) +
5323                      vtable_index*vtableEntry::size_in_bytes() +
5324                      in_bytes(vtableEntry::method_offset());
5325   Node* entry_addr  = basic_plus_adr(obj_klass, entry_offset);
5326   Node* target_call = make_load(nullptr, entry_addr, TypePtr::NOTNULL, T_ADDRESS, MemNode::unordered);
5327 
5328   // Compare the target method with the expected method (e.g., Object.hashCode).
5329   const TypePtr* native_call_addr = TypeMetadataPtr::make(method);
5330 
5331   Node* native_call = makecon(native_call_addr);
5332   Node* chk_native  = _gvn.transform(new CmpPNode(target_call, native_call));
5333   Node* test_native = _gvn.transform(new BoolNode(chk_native, BoolTest::ne));
5334 
5335   return generate_slow_guard(test_native, slow_region);
5336 }
5337 
5338 //-----------------------generate_method_call----------------------------
5339 // Use generate_method_call to make a slow-call to the real
5340 // method if the fast path fails.  An alternative would be to
5341 // use a stub like OptoRuntime::slow_arraycopy_Java.
5342 // This only works for expanding the current library call,
5343 // not another intrinsic.  (E.g., don't use this for making an
5344 // arraycopy call inside of the copyOf intrinsic.)
5345 CallJavaNode*
5346 LibraryCallKit::generate_method_call(vmIntrinsicID method_id, bool is_virtual, bool is_static, bool res_not_null) {
5347   // When compiling the intrinsic method itself, do not use this technique.
5348   guarantee(callee() != C->method(), "cannot make slow-call to self");
5349 
5350   ciMethod* method = callee();
5351   // ensure the JVMS we have will be correct for this call
5352   guarantee(method_id == method->intrinsic_id(), "must match");
5353 
5354   const TypeFunc* tf = TypeFunc::make(method);
5355   if (res_not_null) {
5356     assert(tf->return_type() == T_OBJECT, "");
5357     const TypeTuple* range = tf->range_cc();
5358     const Type** fields = TypeTuple::fields(range->cnt());
5359     fields[TypeFunc::Parms] = range->field_at(TypeFunc::Parms)->filter_speculative(TypePtr::NOTNULL);
5360     const TypeTuple* new_range = TypeTuple::make(range->cnt(), fields);
5361     tf = TypeFunc::make(tf->domain_cc(), new_range);
5362   }
5363   CallJavaNode* slow_call;
5364   if (is_static) {
5365     assert(!is_virtual, "");
5366     slow_call = new CallStaticJavaNode(C, tf,
5367                            SharedRuntime::get_resolve_static_call_stub(), method);
5368   } else if (is_virtual) {
5369     assert(!gvn().type(argument(0))->maybe_null(), "should not be null");
5370     int vtable_index = Method::invalid_vtable_index;
5371     if (UseInlineCaches) {
5372       // Suppress the vtable call
5373     } else {
5374       // hashCode and clone are not a miranda methods,
5375       // so the vtable index is fixed.
5376       // No need to use the linkResolver to get it.
5377        vtable_index = method->vtable_index();
5378        assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index,
5379               "bad index %d", vtable_index);
5380     }
5381     slow_call = new CallDynamicJavaNode(tf,
5382                           SharedRuntime::get_resolve_virtual_call_stub(),
5383                           method, vtable_index);
5384   } else {  // neither virtual nor static:  opt_virtual
5385     assert(!gvn().type(argument(0))->maybe_null(), "should not be null");
5386     slow_call = new CallStaticJavaNode(C, tf,
5387                                 SharedRuntime::get_resolve_opt_virtual_call_stub(), method);
5388     slow_call->set_optimized_virtual(true);
5389   }
5390   if (CallGenerator::is_inlined_method_handle_intrinsic(this->method(), bci(), callee())) {
5391     // To be able to issue a direct call (optimized virtual or virtual)
5392     // and skip a call to MH.linkTo*/invokeBasic adapter, additional information
5393     // about the method being invoked should be attached to the call site to
5394     // make resolution logic work (see SharedRuntime::resolve_{virtual,opt_virtual}_call_C).
5395     slow_call->set_override_symbolic_info(true);
5396   }
5397   set_arguments_for_java_call(slow_call);
5398   set_edges_for_java_call(slow_call);
5399   return slow_call;
5400 }
5401 
5402 
5403 /**
5404  * Build special case code for calls to hashCode on an object. This call may
5405  * be virtual (invokevirtual) or bound (invokespecial). For each case we generate
5406  * slightly different code.
5407  */
5408 bool LibraryCallKit::inline_native_hashcode(bool is_virtual, bool is_static) {
5409   assert(is_static == callee()->is_static(), "correct intrinsic selection");
5410   assert(!(is_virtual && is_static), "either virtual, special, or static");
5411 
5412   enum { _slow_path = 1, _fast_path, _null_path, PATH_LIMIT };
5413 
5414   RegionNode* result_reg = new RegionNode(PATH_LIMIT);
5415   PhiNode*    result_val = new PhiNode(result_reg, TypeInt::INT);
5416   PhiNode*    result_io  = new PhiNode(result_reg, Type::ABIO);
5417   PhiNode*    result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
5418   Node* obj = argument(0);
5419 
5420   // Don't intrinsify hashcode on inline types for now.
5421   // The "is locked" runtime check also subsumes the inline type check (as inline types cannot be locked) and goes to the slow path.
5422   if (gvn().type(obj)->is_inlinetypeptr()) {
5423     return false;
5424   }
5425 
5426   if (!is_static) {
5427     // Check for hashing null object
5428     obj = null_check_receiver();
5429     if (stopped())  return true;        // unconditionally null
5430     result_reg->init_req(_null_path, top());
5431     result_val->init_req(_null_path, top());
5432   } else {
5433     // Do a null check, and return zero if null.
5434     // System.identityHashCode(null) == 0
5435     Node* null_ctl = top();
5436     obj = null_check_oop(obj, &null_ctl);
5437     result_reg->init_req(_null_path, null_ctl);
5438     result_val->init_req(_null_path, _gvn.intcon(0));
5439   }
5440 
5441   // Unconditionally null?  Then return right away.
5442   if (stopped()) {
5443     set_control( result_reg->in(_null_path));
5444     if (!stopped())
5445       set_result(result_val->in(_null_path));
5446     return true;
5447   }
5448 
5449   // We only go to the fast case code if we pass a number of guards.  The
5450   // paths which do not pass are accumulated in the slow_region.
5451   RegionNode* slow_region = new RegionNode(1);
5452   record_for_igvn(slow_region);
5453 
5454   // If this is a virtual call, we generate a funny guard.  We pull out
5455   // the vtable entry corresponding to hashCode() from the target object.
5456   // If the target method which we are calling happens to be the native
5457   // Object hashCode() method, we pass the guard.  We do not need this
5458   // guard for non-virtual calls -- the caller is known to be the native
5459   // Object hashCode().
5460   if (is_virtual) {
5461     // After null check, get the object's klass.
5462     Node* obj_klass = load_object_klass(obj);
5463     generate_virtual_guard(obj_klass, slow_region);
5464   }
5465 
5466   // Get the header out of the object, use LoadMarkNode when available
5467   Node* header_addr = basic_plus_adr(obj, oopDesc::mark_offset_in_bytes());
5468   // The control of the load must be null. Otherwise, the load can move before
5469   // the null check after castPP removal.
5470   Node* no_ctrl = nullptr;
5471   Node* header = make_load(no_ctrl, header_addr, TypeX_X, TypeX_X->basic_type(), MemNode::unordered);
5472 
5473   if (!UseObjectMonitorTable) {
5474     // Test the header to see if it is safe to read w.r.t. locking.
5475     // We cannot use the inline type mask as this may check bits that are overriden
5476     // by an object monitor's pointer when inflating locking.
5477     Node *lock_mask      = _gvn.MakeConX(markWord::lock_mask_in_place);
5478     Node *lmasked_header = _gvn.transform(new AndXNode(header, lock_mask));
5479     Node *monitor_val   = _gvn.MakeConX(markWord::monitor_value);
5480     Node *chk_monitor   = _gvn.transform(new CmpXNode(lmasked_header, monitor_val));
5481     Node *test_monitor  = _gvn.transform(new BoolNode(chk_monitor, BoolTest::eq));
5482 
5483     generate_slow_guard(test_monitor, slow_region);
5484   }
5485 
5486   // Get the hash value and check to see that it has been properly assigned.
5487   // We depend on hash_mask being at most 32 bits and avoid the use of
5488   // hash_mask_in_place because it could be larger than 32 bits in a 64-bit
5489   // vm: see markWord.hpp.
5490   Node *hash_mask      = _gvn.intcon(markWord::hash_mask);
5491   Node *hash_shift     = _gvn.intcon(markWord::hash_shift);
5492   Node *hshifted_header= _gvn.transform(new URShiftXNode(header, hash_shift));
5493   // This hack lets the hash bits live anywhere in the mark object now, as long
5494   // as the shift drops the relevant bits into the low 32 bits.  Note that
5495   // Java spec says that HashCode is an int so there's no point in capturing
5496   // an 'X'-sized hashcode (32 in 32-bit build or 64 in 64-bit build).
5497   hshifted_header      = ConvX2I(hshifted_header);
5498   Node *hash_val       = _gvn.transform(new AndINode(hshifted_header, hash_mask));
5499 
5500   Node *no_hash_val    = _gvn.intcon(markWord::no_hash);
5501   Node *chk_assigned   = _gvn.transform(new CmpINode( hash_val, no_hash_val));
5502   Node *test_assigned  = _gvn.transform(new BoolNode( chk_assigned, BoolTest::eq));
5503 
5504   generate_slow_guard(test_assigned, slow_region);
5505 
5506   Node* init_mem = reset_memory();
5507   // fill in the rest of the null path:
5508   result_io ->init_req(_null_path, i_o());
5509   result_mem->init_req(_null_path, init_mem);
5510 
5511   result_val->init_req(_fast_path, hash_val);
5512   result_reg->init_req(_fast_path, control());
5513   result_io ->init_req(_fast_path, i_o());
5514   result_mem->init_req(_fast_path, init_mem);
5515 
5516   // Generate code for the slow case.  We make a call to hashCode().
5517   set_control(_gvn.transform(slow_region));
5518   if (!stopped()) {
5519     // No need for PreserveJVMState, because we're using up the present state.
5520     set_all_memory(init_mem);
5521     vmIntrinsics::ID hashCode_id = is_static ? vmIntrinsics::_identityHashCode : vmIntrinsics::_hashCode;
5522     CallJavaNode* slow_call = generate_method_call(hashCode_id, is_virtual, is_static, false);
5523     Node* slow_result = set_results_for_java_call(slow_call);
5524     // this->control() comes from set_results_for_java_call
5525     result_reg->init_req(_slow_path, control());
5526     result_val->init_req(_slow_path, slow_result);
5527     result_io  ->set_req(_slow_path, i_o());
5528     result_mem ->set_req(_slow_path, reset_memory());
5529   }
5530 
5531   // Return the combined state.
5532   set_i_o(        _gvn.transform(result_io)  );
5533   set_all_memory( _gvn.transform(result_mem));
5534 
5535   set_result(result_reg, result_val);
5536   return true;
5537 }
5538 
5539 //---------------------------inline_native_getClass----------------------------
5540 // public final native Class<?> java.lang.Object.getClass();
5541 //
5542 // Build special case code for calls to getClass on an object.
5543 bool LibraryCallKit::inline_native_getClass() {
5544   Node* obj = argument(0);
5545   if (obj->is_InlineType()) {
5546     const Type* t = _gvn.type(obj);
5547     if (t->maybe_null()) {
5548       null_check(obj);
5549     }
5550     set_result(makecon(TypeInstPtr::make(t->inline_klass()->java_mirror())));
5551     return true;
5552   }
5553   obj = null_check_receiver();
5554   if (stopped())  return true;
5555   set_result(load_mirror_from_klass(load_object_klass(obj)));
5556   return true;
5557 }
5558 
5559 //-----------------inline_native_Reflection_getCallerClass---------------------
5560 // public static native Class<?> sun.reflect.Reflection.getCallerClass();
5561 //
5562 // In the presence of deep enough inlining, getCallerClass() becomes a no-op.
5563 //
5564 // NOTE: This code must perform the same logic as JVM_GetCallerClass
5565 // in that it must skip particular security frames and checks for
5566 // caller sensitive methods.
5567 bool LibraryCallKit::inline_native_Reflection_getCallerClass() {
5568 #ifndef PRODUCT
5569   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5570     tty->print_cr("Attempting to inline sun.reflect.Reflection.getCallerClass");
5571   }
5572 #endif
5573 
5574   if (!jvms()->has_method()) {
5575 #ifndef PRODUCT
5576     if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5577       tty->print_cr("  Bailing out because intrinsic was inlined at top level");
5578     }
5579 #endif
5580     return false;
5581   }
5582 
5583   // Walk back up the JVM state to find the caller at the required
5584   // depth.
5585   JVMState* caller_jvms = jvms();
5586 
5587   // Cf. JVM_GetCallerClass
5588   // NOTE: Start the loop at depth 1 because the current JVM state does
5589   // not include the Reflection.getCallerClass() frame.
5590   for (int n = 1; caller_jvms != nullptr; caller_jvms = caller_jvms->caller(), n++) {
5591     ciMethod* m = caller_jvms->method();
5592     switch (n) {
5593     case 0:
5594       fatal("current JVM state does not include the Reflection.getCallerClass frame");
5595       break;
5596     case 1:
5597       // Frame 0 and 1 must be caller sensitive (see JVM_GetCallerClass).
5598       if (!m->caller_sensitive()) {
5599 #ifndef PRODUCT
5600         if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5601           tty->print_cr("  Bailing out: CallerSensitive annotation expected at frame %d", n);
5602         }
5603 #endif
5604         return false;  // bail-out; let JVM_GetCallerClass do the work
5605       }
5606       break;
5607     default:
5608       if (!m->is_ignored_by_security_stack_walk()) {
5609         // We have reached the desired frame; return the holder class.
5610         // Acquire method holder as java.lang.Class and push as constant.
5611         ciInstanceKlass* caller_klass = caller_jvms->method()->holder();
5612         ciInstance* caller_mirror = caller_klass->java_mirror();
5613         set_result(makecon(TypeInstPtr::make(caller_mirror)));
5614 
5615 #ifndef PRODUCT
5616         if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5617           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());
5618           tty->print_cr("  JVM state at this point:");
5619           for (int i = jvms()->depth(), n = 1; i >= 1; i--, n++) {
5620             ciMethod* m = jvms()->of_depth(i)->method();
5621             tty->print_cr("   %d) %s.%s", n, m->holder()->name()->as_utf8(), m->name()->as_utf8());
5622           }
5623         }
5624 #endif
5625         return true;
5626       }
5627       break;
5628     }
5629   }
5630 
5631 #ifndef PRODUCT
5632   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5633     tty->print_cr("  Bailing out because caller depth exceeded inlining depth = %d", jvms()->depth());
5634     tty->print_cr("  JVM state at this point:");
5635     for (int i = jvms()->depth(), n = 1; i >= 1; i--, n++) {
5636       ciMethod* m = jvms()->of_depth(i)->method();
5637       tty->print_cr("   %d) %s.%s", n, m->holder()->name()->as_utf8(), m->name()->as_utf8());
5638     }
5639   }
5640 #endif
5641 
5642   return false;  // bail-out; let JVM_GetCallerClass do the work
5643 }
5644 
5645 bool LibraryCallKit::inline_fp_conversions(vmIntrinsics::ID id) {
5646   Node* arg = argument(0);
5647   Node* result = nullptr;
5648 
5649   switch (id) {
5650   case vmIntrinsics::_floatToRawIntBits:    result = new MoveF2INode(arg);  break;
5651   case vmIntrinsics::_intBitsToFloat:       result = new MoveI2FNode(arg);  break;
5652   case vmIntrinsics::_doubleToRawLongBits:  result = new MoveD2LNode(arg);  break;
5653   case vmIntrinsics::_longBitsToDouble:     result = new MoveL2DNode(arg);  break;
5654   case vmIntrinsics::_floatToFloat16:       result = new ConvF2HFNode(arg); break;
5655   case vmIntrinsics::_float16ToFloat:       result = new ConvHF2FNode(arg); break;
5656 
5657   case vmIntrinsics::_doubleToLongBits: {
5658     // two paths (plus control) merge in a wood
5659     RegionNode *r = new RegionNode(3);
5660     Node *phi = new PhiNode(r, TypeLong::LONG);
5661 
5662     Node *cmpisnan = _gvn.transform(new CmpDNode(arg, arg));
5663     // Build the boolean node
5664     Node *bolisnan = _gvn.transform(new BoolNode(cmpisnan, BoolTest::ne));
5665 
5666     // Branch either way.
5667     // NaN case is less traveled, which makes all the difference.
5668     IfNode *ifisnan = create_and_xform_if(control(), bolisnan, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
5669     Node *opt_isnan = _gvn.transform(ifisnan);
5670     assert( opt_isnan->is_If(), "Expect an IfNode");
5671     IfNode *opt_ifisnan = (IfNode*)opt_isnan;
5672     Node *iftrue = _gvn.transform(new IfTrueNode(opt_ifisnan));
5673 
5674     set_control(iftrue);
5675 
5676     static const jlong nan_bits = CONST64(0x7ff8000000000000);
5677     Node *slow_result = longcon(nan_bits); // return NaN
5678     phi->init_req(1, _gvn.transform( slow_result ));
5679     r->init_req(1, iftrue);
5680 
5681     // Else fall through
5682     Node *iffalse = _gvn.transform(new IfFalseNode(opt_ifisnan));
5683     set_control(iffalse);
5684 
5685     phi->init_req(2, _gvn.transform(new MoveD2LNode(arg)));
5686     r->init_req(2, iffalse);
5687 
5688     // Post merge
5689     set_control(_gvn.transform(r));
5690     record_for_igvn(r);
5691 
5692     C->set_has_split_ifs(true); // Has chance for split-if optimization
5693     result = phi;
5694     assert(result->bottom_type()->isa_long(), "must be");
5695     break;
5696   }
5697 
5698   case vmIntrinsics::_floatToIntBits: {
5699     // two paths (plus control) merge in a wood
5700     RegionNode *r = new RegionNode(3);
5701     Node *phi = new PhiNode(r, TypeInt::INT);
5702 
5703     Node *cmpisnan = _gvn.transform(new CmpFNode(arg, arg));
5704     // Build the boolean node
5705     Node *bolisnan = _gvn.transform(new BoolNode(cmpisnan, BoolTest::ne));
5706 
5707     // Branch either way.
5708     // NaN case is less traveled, which makes all the difference.
5709     IfNode *ifisnan = create_and_xform_if(control(), bolisnan, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
5710     Node *opt_isnan = _gvn.transform(ifisnan);
5711     assert( opt_isnan->is_If(), "Expect an IfNode");
5712     IfNode *opt_ifisnan = (IfNode*)opt_isnan;
5713     Node *iftrue = _gvn.transform(new IfTrueNode(opt_ifisnan));
5714 
5715     set_control(iftrue);
5716 
5717     static const jint nan_bits = 0x7fc00000;
5718     Node *slow_result = makecon(TypeInt::make(nan_bits)); // return NaN
5719     phi->init_req(1, _gvn.transform( slow_result ));
5720     r->init_req(1, iftrue);
5721 
5722     // Else fall through
5723     Node *iffalse = _gvn.transform(new IfFalseNode(opt_ifisnan));
5724     set_control(iffalse);
5725 
5726     phi->init_req(2, _gvn.transform(new MoveF2INode(arg)));
5727     r->init_req(2, iffalse);
5728 
5729     // Post merge
5730     set_control(_gvn.transform(r));
5731     record_for_igvn(r);
5732 
5733     C->set_has_split_ifs(true); // Has chance for split-if optimization
5734     result = phi;
5735     assert(result->bottom_type()->isa_int(), "must be");
5736     break;
5737   }
5738 
5739   default:
5740     fatal_unexpected_iid(id);
5741     break;
5742   }
5743   set_result(_gvn.transform(result));
5744   return true;
5745 }
5746 
5747 bool LibraryCallKit::inline_fp_range_check(vmIntrinsics::ID id) {
5748   Node* arg = argument(0);
5749   Node* result = nullptr;
5750 
5751   switch (id) {
5752   case vmIntrinsics::_floatIsInfinite:
5753     result = new IsInfiniteFNode(arg);
5754     break;
5755   case vmIntrinsics::_floatIsFinite:
5756     result = new IsFiniteFNode(arg);
5757     break;
5758   case vmIntrinsics::_doubleIsInfinite:
5759     result = new IsInfiniteDNode(arg);
5760     break;
5761   case vmIntrinsics::_doubleIsFinite:
5762     result = new IsFiniteDNode(arg);
5763     break;
5764   default:
5765     fatal_unexpected_iid(id);
5766     break;
5767   }
5768   set_result(_gvn.transform(result));
5769   return true;
5770 }
5771 
5772 //----------------------inline_unsafe_copyMemory-------------------------
5773 // public native void Unsafe.copyMemory0(Object srcBase, long srcOffset, Object destBase, long destOffset, long bytes);
5774 
5775 static bool has_wide_mem(PhaseGVN& gvn, Node* addr, Node* base) {
5776   const TypeAryPtr* addr_t = gvn.type(addr)->isa_aryptr();
5777   const Type*       base_t = gvn.type(base);
5778 
5779   bool in_native = (base_t == TypePtr::NULL_PTR);
5780   bool in_heap   = !TypePtr::NULL_PTR->higher_equal(base_t);
5781   bool is_mixed  = !in_heap && !in_native;
5782 
5783   if (is_mixed) {
5784     return true; // mixed accesses can touch both on-heap and off-heap memory
5785   }
5786   if (in_heap) {
5787     bool is_prim_array = (addr_t != nullptr) && (addr_t->elem() != Type::BOTTOM);
5788     if (!is_prim_array) {
5789       // Though Unsafe.copyMemory() ensures at runtime for on-heap accesses that base is a primitive array,
5790       // there's not enough type information available to determine proper memory slice for it.
5791       return true;
5792     }
5793   }
5794   return false;
5795 }
5796 
5797 bool LibraryCallKit::inline_unsafe_copyMemory() {
5798   if (callee()->is_static())  return false;  // caller must have the capability!
5799   null_check_receiver();  // null-check receiver
5800   if (stopped())  return true;
5801 
5802   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
5803 
5804   Node* src_base =         argument(1);  // type: oop
5805   Node* src_off  = ConvL2X(argument(2)); // type: long
5806   Node* dst_base =         argument(4);  // type: oop
5807   Node* dst_off  = ConvL2X(argument(5)); // type: long
5808   Node* size     = ConvL2X(argument(7)); // type: long
5809 
5810   assert(Unsafe_field_offset_to_byte_offset(11) == 11,
5811          "fieldOffset must be byte-scaled");
5812 
5813   Node* src_addr = make_unsafe_address(src_base, src_off);
5814   Node* dst_addr = make_unsafe_address(dst_base, dst_off);
5815 
5816   Node* thread = _gvn.transform(new ThreadLocalNode());
5817   Node* doing_unsafe_access_addr = basic_plus_adr(top(), thread, in_bytes(JavaThread::doing_unsafe_access_offset()));
5818   BasicType doing_unsafe_access_bt = T_BYTE;
5819   assert((sizeof(bool) * CHAR_BIT) == 8, "not implemented");
5820 
5821   // update volatile field
5822   store_to_memory(control(), doing_unsafe_access_addr, intcon(1), doing_unsafe_access_bt, MemNode::unordered);
5823 
5824   int flags = RC_LEAF | RC_NO_FP;
5825 
5826   const TypePtr* dst_type = TypePtr::BOTTOM;
5827 
5828   // Adjust memory effects of the runtime call based on input values.
5829   if (!has_wide_mem(_gvn, src_addr, src_base) &&
5830       !has_wide_mem(_gvn, dst_addr, dst_base)) {
5831     dst_type = _gvn.type(dst_addr)->is_ptr(); // narrow out memory
5832 
5833     const TypePtr* src_type = _gvn.type(src_addr)->is_ptr();
5834     if (C->get_alias_index(src_type) == C->get_alias_index(dst_type)) {
5835       flags |= RC_NARROW_MEM; // narrow in memory
5836     }
5837   }
5838 
5839   // Call it.  Note that the length argument is not scaled.
5840   make_runtime_call(flags,
5841                     OptoRuntime::fast_arraycopy_Type(),
5842                     StubRoutines::unsafe_arraycopy(),
5843                     "unsafe_arraycopy",
5844                     dst_type,
5845                     src_addr, dst_addr, size XTOP);
5846 
5847   store_to_memory(control(), doing_unsafe_access_addr, intcon(0), doing_unsafe_access_bt, MemNode::unordered);
5848 
5849   return true;
5850 }
5851 
5852 // unsafe_setmemory(void *base, ulong offset, size_t length, char fill_value);
5853 // Fill 'length' bytes starting from 'base[offset]' with 'fill_value'
5854 bool LibraryCallKit::inline_unsafe_setMemory() {
5855   if (callee()->is_static())  return false;  // caller must have the capability!
5856   null_check_receiver();  // null-check receiver
5857   if (stopped())  return true;
5858 
5859   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
5860 
5861   Node* dst_base =         argument(1);  // type: oop
5862   Node* dst_off  = ConvL2X(argument(2)); // type: long
5863   Node* size     = ConvL2X(argument(4)); // type: long
5864   Node* byte     =         argument(6);  // type: byte
5865 
5866   assert(Unsafe_field_offset_to_byte_offset(11) == 11,
5867          "fieldOffset must be byte-scaled");
5868 
5869   Node* dst_addr = make_unsafe_address(dst_base, dst_off);
5870 
5871   Node* thread = _gvn.transform(new ThreadLocalNode());
5872   Node* doing_unsafe_access_addr = basic_plus_adr(top(), thread, in_bytes(JavaThread::doing_unsafe_access_offset()));
5873   BasicType doing_unsafe_access_bt = T_BYTE;
5874   assert((sizeof(bool) * CHAR_BIT) == 8, "not implemented");
5875 
5876   // update volatile field
5877   store_to_memory(control(), doing_unsafe_access_addr, intcon(1), doing_unsafe_access_bt, MemNode::unordered);
5878 
5879   int flags = RC_LEAF | RC_NO_FP;
5880 
5881   const TypePtr* dst_type = TypePtr::BOTTOM;
5882 
5883   // Adjust memory effects of the runtime call based on input values.
5884   if (!has_wide_mem(_gvn, dst_addr, dst_base)) {
5885     dst_type = _gvn.type(dst_addr)->is_ptr(); // narrow out memory
5886 
5887     flags |= RC_NARROW_MEM; // narrow in memory
5888   }
5889 
5890   // Call it.  Note that the length argument is not scaled.
5891   make_runtime_call(flags,
5892                     OptoRuntime::unsafe_setmemory_Type(),
5893                     StubRoutines::unsafe_setmemory(),
5894                     "unsafe_setmemory",
5895                     dst_type,
5896                     dst_addr, size XTOP, byte);
5897 
5898   store_to_memory(control(), doing_unsafe_access_addr, intcon(0), doing_unsafe_access_bt, MemNode::unordered);
5899 
5900   return true;
5901 }
5902 
5903 #undef XTOP
5904 
5905 //------------------------clone_coping-----------------------------------
5906 // Helper function for inline_native_clone.
5907 void LibraryCallKit::copy_to_clone(Node* obj, Node* alloc_obj, Node* obj_size, bool is_array) {
5908   assert(obj_size != nullptr, "");
5909   Node* raw_obj = alloc_obj->in(1);
5910   assert(alloc_obj->is_CheckCastPP() && raw_obj->is_Proj() && raw_obj->in(0)->is_Allocate(), "");
5911 
5912   AllocateNode* alloc = nullptr;
5913   if (ReduceBulkZeroing &&
5914       // If we are implementing an array clone without knowing its source type
5915       // (can happen when compiling the array-guarded branch of a reflective
5916       // Object.clone() invocation), initialize the array within the allocation.
5917       // This is needed because some GCs (e.g. ZGC) might fall back in this case
5918       // to a runtime clone call that assumes fully initialized source arrays.
5919       (!is_array || obj->get_ptr_type()->isa_aryptr() != nullptr)) {
5920     // We will be completely responsible for initializing this object -
5921     // mark Initialize node as complete.
5922     alloc = AllocateNode::Ideal_allocation(alloc_obj);
5923     // The object was just allocated - there should be no any stores!
5924     guarantee(alloc != nullptr && alloc->maybe_set_complete(&_gvn), "");
5925     // Mark as complete_with_arraycopy so that on AllocateNode
5926     // expansion, we know this AllocateNode is initialized by an array
5927     // copy and a StoreStore barrier exists after the array copy.
5928     alloc->initialization()->set_complete_with_arraycopy();
5929   }
5930 
5931   Node* size = _gvn.transform(obj_size);
5932   access_clone(obj, alloc_obj, size, is_array);
5933 
5934   // Do not let reads from the cloned object float above the arraycopy.
5935   if (alloc != nullptr) {
5936     // Do not let stores that initialize this object be reordered with
5937     // a subsequent store that would make this object accessible by
5938     // other threads.
5939     // Record what AllocateNode this StoreStore protects so that
5940     // escape analysis can go from the MemBarStoreStoreNode to the
5941     // AllocateNode and eliminate the MemBarStoreStoreNode if possible
5942     // based on the escape status of the AllocateNode.
5943     insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
5944   } else {
5945     insert_mem_bar(Op_MemBarCPUOrder);
5946   }
5947 }
5948 
5949 //------------------------inline_native_clone----------------------------
5950 // protected native Object java.lang.Object.clone();
5951 //
5952 // Here are the simple edge cases:
5953 //  null receiver => normal trap
5954 //  virtual and clone was overridden => slow path to out-of-line clone
5955 //  not cloneable or finalizer => slow path to out-of-line Object.clone
5956 //
5957 // The general case has two steps, allocation and copying.
5958 // Allocation has two cases, and uses GraphKit::new_instance or new_array.
5959 //
5960 // Copying also has two cases, oop arrays and everything else.
5961 // Oop arrays use arrayof_oop_arraycopy (same as System.arraycopy).
5962 // Everything else uses the tight inline loop supplied by CopyArrayNode.
5963 //
5964 // These steps fold up nicely if and when the cloned object's klass
5965 // can be sharply typed as an object array, a type array, or an instance.
5966 //
5967 bool LibraryCallKit::inline_native_clone(bool is_virtual) {
5968   PhiNode* result_val;
5969 
5970   // Set the reexecute bit for the interpreter to reexecute
5971   // the bytecode that invokes Object.clone if deoptimization happens.
5972   { PreserveReexecuteState preexecs(this);
5973     jvms()->set_should_reexecute(true);
5974 
5975     Node* obj = argument(0);
5976     obj = null_check_receiver();
5977     if (stopped())  return true;
5978 
5979     const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
5980     if (obj_type->is_inlinetypeptr()) {
5981       // If the object to clone is an inline type, we can simply return it (i.e. a nop) since inline types have
5982       // no identity.
5983       set_result(obj);
5984       return true;
5985     }
5986 
5987     // If we are going to clone an instance, we need its exact type to
5988     // know the number and types of fields to convert the clone to
5989     // loads/stores. Maybe a speculative type can help us.
5990     if (!obj_type->klass_is_exact() &&
5991         obj_type->speculative_type() != nullptr &&
5992         obj_type->speculative_type()->is_instance_klass() &&
5993         !obj_type->speculative_type()->is_inlinetype()) {
5994       ciInstanceKlass* spec_ik = obj_type->speculative_type()->as_instance_klass();
5995       if (spec_ik->nof_nonstatic_fields() <= ArrayCopyLoadStoreMaxElem &&
5996           !spec_ik->has_injected_fields()) {
5997         if (!obj_type->isa_instptr() ||
5998             obj_type->is_instptr()->instance_klass()->has_subklass()) {
5999           obj = maybe_cast_profiled_obj(obj, obj_type->speculative_type(), false);
6000         }
6001       }
6002     }
6003 
6004     // Conservatively insert a memory barrier on all memory slices.
6005     // Do not let writes into the original float below the clone.
6006     insert_mem_bar(Op_MemBarCPUOrder);
6007 
6008     // paths into result_reg:
6009     enum {
6010       _slow_path = 1,     // out-of-line call to clone method (virtual or not)
6011       _objArray_path,     // plain array allocation, plus arrayof_oop_arraycopy
6012       _array_path,        // plain array allocation, plus arrayof_long_arraycopy
6013       _instance_path,     // plain instance allocation, plus arrayof_long_arraycopy
6014       PATH_LIMIT
6015     };
6016     RegionNode* result_reg = new RegionNode(PATH_LIMIT);
6017     result_val             = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
6018     PhiNode*    result_i_o = new PhiNode(result_reg, Type::ABIO);
6019     PhiNode*    result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
6020     record_for_igvn(result_reg);
6021 
6022     Node* obj_klass = load_object_klass(obj);
6023     // We only go to the fast case code if we pass a number of guards.
6024     // The paths which do not pass are accumulated in the slow_region.
6025     RegionNode* slow_region = new RegionNode(1);
6026     record_for_igvn(slow_region);
6027 
6028     Node* array_obj = obj;
6029     Node* array_ctl = generate_array_guard(obj_klass, (RegionNode*)nullptr, &array_obj);
6030     if (array_ctl != nullptr) {
6031       // It's an array.
6032       PreserveJVMState pjvms(this);
6033       set_control(array_ctl);
6034 
6035       BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
6036       const TypeAryPtr* ary_ptr = obj_type->isa_aryptr();
6037       if (UseArrayFlattening && bs->array_copy_requires_gc_barriers(true, T_OBJECT, true, false, BarrierSetC2::Expansion) &&
6038           obj_type->can_be_inline_array() &&
6039           (ary_ptr == nullptr || (!ary_ptr->is_not_flat() && (!ary_ptr->is_flat() || ary_ptr->elem()->inline_klass()->contains_oops())))) {
6040         // Flat inline type array may have object field that would require a
6041         // write barrier. Conservatively, go to slow path.
6042         generate_fair_guard(flat_array_test(obj_klass), slow_region);
6043       }
6044 
6045       if (!stopped()) {
6046         Node* obj_length = load_array_length(array_obj);
6047         Node* array_size = nullptr; // Size of the array without object alignment padding.
6048         Node* alloc_obj = new_array(obj_klass, obj_length, 0, &array_size, /*deoptimize_on_exception=*/true);
6049 
6050         BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
6051         if (bs->array_copy_requires_gc_barriers(true, T_OBJECT, true, false, BarrierSetC2::Parsing)) {
6052           // If it is an oop array, it requires very special treatment,
6053           // because gc barriers are required when accessing the array.
6054           Node* is_obja = generate_refArray_guard(obj_klass, (RegionNode*)nullptr);
6055           if (is_obja != nullptr) {
6056             PreserveJVMState pjvms2(this);
6057             set_control(is_obja);
6058             // Generate a direct call to the right arraycopy function(s).
6059             // Clones are always tightly coupled.
6060             ArrayCopyNode* ac = ArrayCopyNode::make(this, true, array_obj, intcon(0), alloc_obj, intcon(0), obj_length, true, false);
6061             ac->set_clone_oop_array();
6062             Node* n = _gvn.transform(ac);
6063             assert(n == ac, "cannot disappear");
6064             ac->connect_outputs(this, /*deoptimize_on_exception=*/true);
6065 
6066             result_reg->init_req(_objArray_path, control());
6067             result_val->init_req(_objArray_path, alloc_obj);
6068             result_i_o ->set_req(_objArray_path, i_o());
6069             result_mem ->set_req(_objArray_path, reset_memory());
6070           }
6071         }
6072         // Otherwise, there are no barriers to worry about.
6073         // (We can dispense with card marks if we know the allocation
6074         //  comes out of eden (TLAB)...  In fact, ReduceInitialCardMarks
6075         //  causes the non-eden paths to take compensating steps to
6076         //  simulate a fresh allocation, so that no further
6077         //  card marks are required in compiled code to initialize
6078         //  the object.)
6079 
6080         if (!stopped()) {
6081           copy_to_clone(obj, alloc_obj, array_size, true);
6082 
6083           // Present the results of the copy.
6084           result_reg->init_req(_array_path, control());
6085           result_val->init_req(_array_path, alloc_obj);
6086           result_i_o ->set_req(_array_path, i_o());
6087           result_mem ->set_req(_array_path, reset_memory());
6088         }
6089       }
6090     }
6091 
6092     if (!stopped()) {
6093       // It's an instance (we did array above).  Make the slow-path tests.
6094       // If this is a virtual call, we generate a funny guard.  We grab
6095       // the vtable entry corresponding to clone() from the target object.
6096       // If the target method which we are calling happens to be the
6097       // Object clone() method, we pass the guard.  We do not need this
6098       // guard for non-virtual calls; the caller is known to be the native
6099       // Object clone().
6100       if (is_virtual) {
6101         generate_virtual_guard(obj_klass, slow_region);
6102       }
6103 
6104       // The object must be easily cloneable and must not have a finalizer.
6105       // Both of these conditions may be checked in a single test.
6106       // We could optimize the test further, but we don't care.
6107       generate_misc_flags_guard(obj_klass,
6108                                 // Test both conditions:
6109                                 KlassFlags::_misc_is_cloneable_fast | KlassFlags::_misc_has_finalizer,
6110                                 // Must be cloneable but not finalizer:
6111                                 KlassFlags::_misc_is_cloneable_fast,
6112                                 slow_region);
6113     }
6114 
6115     if (!stopped()) {
6116       // It's an instance, and it passed the slow-path tests.
6117       PreserveJVMState pjvms(this);
6118       Node* obj_size = nullptr; // Total object size, including object alignment padding.
6119       // Need to deoptimize on exception from allocation since Object.clone intrinsic
6120       // is reexecuted if deoptimization occurs and there could be problems when merging
6121       // exception state between multiple Object.clone versions (reexecute=true vs reexecute=false).
6122       Node* alloc_obj = new_instance(obj_klass, nullptr, &obj_size, /*deoptimize_on_exception=*/true);
6123 
6124       copy_to_clone(obj, alloc_obj, obj_size, false);
6125 
6126       // Present the results of the slow call.
6127       result_reg->init_req(_instance_path, control());
6128       result_val->init_req(_instance_path, alloc_obj);
6129       result_i_o ->set_req(_instance_path, i_o());
6130       result_mem ->set_req(_instance_path, reset_memory());
6131     }
6132 
6133     // Generate code for the slow case.  We make a call to clone().
6134     set_control(_gvn.transform(slow_region));
6135     if (!stopped()) {
6136       PreserveJVMState pjvms(this);
6137       CallJavaNode* slow_call = generate_method_call(vmIntrinsics::_clone, is_virtual, false, true);
6138       // We need to deoptimize on exception (see comment above)
6139       Node* slow_result = set_results_for_java_call(slow_call, false, /* deoptimize */ true);
6140       // this->control() comes from set_results_for_java_call
6141       result_reg->init_req(_slow_path, control());
6142       result_val->init_req(_slow_path, slow_result);
6143       result_i_o ->set_req(_slow_path, i_o());
6144       result_mem ->set_req(_slow_path, reset_memory());
6145     }
6146 
6147     // Return the combined state.
6148     set_control(    _gvn.transform(result_reg));
6149     set_i_o(        _gvn.transform(result_i_o));
6150     set_all_memory( _gvn.transform(result_mem));
6151   } // original reexecute is set back here
6152 
6153   set_result(_gvn.transform(result_val));
6154   return true;
6155 }
6156 
6157 // If we have a tightly coupled allocation, the arraycopy may take care
6158 // of the array initialization. If one of the guards we insert between
6159 // the allocation and the arraycopy causes a deoptimization, an
6160 // uninitialized array will escape the compiled method. To prevent that
6161 // we set the JVM state for uncommon traps between the allocation and
6162 // the arraycopy to the state before the allocation so, in case of
6163 // deoptimization, we'll reexecute the allocation and the
6164 // initialization.
6165 JVMState* LibraryCallKit::arraycopy_restore_alloc_state(AllocateArrayNode* alloc, int& saved_reexecute_sp) {
6166   if (alloc != nullptr) {
6167     ciMethod* trap_method = alloc->jvms()->method();
6168     int trap_bci = alloc->jvms()->bci();
6169 
6170     if (!C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_intrinsic) &&
6171         !C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_null_check)) {
6172       // Make sure there's no store between the allocation and the
6173       // arraycopy otherwise visible side effects could be rexecuted
6174       // in case of deoptimization and cause incorrect execution.
6175       bool no_interfering_store = true;
6176       Node* mem = alloc->in(TypeFunc::Memory);
6177       if (mem->is_MergeMem()) {
6178         for (MergeMemStream mms(merged_memory(), mem->as_MergeMem()); mms.next_non_empty2(); ) {
6179           Node* n = mms.memory();
6180           if (n != mms.memory2() && !(n->is_Proj() && n->in(0) == alloc->initialization())) {
6181             assert(n->is_Store(), "what else?");
6182             no_interfering_store = false;
6183             break;
6184           }
6185         }
6186       } else {
6187         for (MergeMemStream mms(merged_memory()); mms.next_non_empty(); ) {
6188           Node* n = mms.memory();
6189           if (n != mem && !(n->is_Proj() && n->in(0) == alloc->initialization())) {
6190             assert(n->is_Store(), "what else?");
6191             no_interfering_store = false;
6192             break;
6193           }
6194         }
6195       }
6196 
6197       if (no_interfering_store) {
6198         SafePointNode* sfpt = create_safepoint_with_state_before_array_allocation(alloc);
6199 
6200         JVMState* saved_jvms = jvms();
6201         saved_reexecute_sp = _reexecute_sp;
6202 
6203         set_jvms(sfpt->jvms());
6204         _reexecute_sp = jvms()->sp();
6205 
6206         return saved_jvms;
6207       }
6208     }
6209   }
6210   return nullptr;
6211 }
6212 
6213 // Clone the JVMState of the array allocation and create a new safepoint with it. Re-push the array length to the stack
6214 // such that uncommon traps can be emitted to re-execute the array allocation in the interpreter.
6215 SafePointNode* LibraryCallKit::create_safepoint_with_state_before_array_allocation(const AllocateArrayNode* alloc) const {
6216   JVMState* old_jvms = alloc->jvms()->clone_shallow(C);
6217   uint size = alloc->req();
6218   SafePointNode* sfpt = new SafePointNode(size, old_jvms);
6219   old_jvms->set_map(sfpt);
6220   for (uint i = 0; i < size; i++) {
6221     sfpt->init_req(i, alloc->in(i));
6222   }
6223   int adjustment = 1;
6224   const TypeAryKlassPtr* ary_klass_ptr = alloc->in(AllocateNode::KlassNode)->bottom_type()->is_aryklassptr();
6225   if (ary_klass_ptr->is_null_free()) {
6226     // A null-free, tightly coupled array allocation can only come from LibraryCallKit::inline_newArray which
6227     // also requires the componentType and initVal on stack for re-execution.
6228     // Re-create and push the componentType.
6229     ciArrayKlass* klass = ary_klass_ptr->exact_klass()->as_array_klass();
6230     ciInstance* instance = klass->component_mirror_instance();
6231     const TypeInstPtr* t_instance = TypeInstPtr::make(instance);
6232     sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp(), makecon(t_instance));
6233     adjustment++;
6234   }
6235   // re-push array length for deoptimization
6236   sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp() + adjustment - 1, alloc->in(AllocateNode::ALength));
6237   if (ary_klass_ptr->is_null_free()) {
6238     // Re-create and push the initVal.
6239     Node* init_val = alloc->in(AllocateNode::InitValue);
6240     if (init_val == nullptr) {
6241       init_val = InlineTypeNode::make_all_zero(_gvn, ary_klass_ptr->elem()->is_instklassptr()->instance_klass()->as_inline_klass());
6242     } else if (UseCompressedOops) {
6243       init_val = _gvn.transform(new DecodeNNode(init_val, init_val->bottom_type()->make_ptr()));
6244     }
6245     sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp() + adjustment, init_val);
6246     adjustment++;
6247   }
6248   old_jvms->set_sp(old_jvms->sp() + adjustment);
6249   old_jvms->set_monoff(old_jvms->monoff() + adjustment);
6250   old_jvms->set_scloff(old_jvms->scloff() + adjustment);
6251   old_jvms->set_endoff(old_jvms->endoff() + adjustment);
6252   old_jvms->set_should_reexecute(true);
6253 
6254   sfpt->set_i_o(map()->i_o());
6255   sfpt->set_memory(map()->memory());
6256   sfpt->set_control(map()->control());
6257   return sfpt;
6258 }
6259 
6260 // In case of a deoptimization, we restart execution at the
6261 // allocation, allocating a new array. We would leave an uninitialized
6262 // array in the heap that GCs wouldn't expect. Move the allocation
6263 // after the traps so we don't allocate the array if we
6264 // deoptimize. This is possible because tightly_coupled_allocation()
6265 // guarantees there's no observer of the allocated array at this point
6266 // and the control flow is simple enough.
6267 void LibraryCallKit::arraycopy_move_allocation_here(AllocateArrayNode* alloc, Node* dest, JVMState* saved_jvms_before_guards,
6268                                                     int saved_reexecute_sp, uint new_idx) {
6269   if (saved_jvms_before_guards != nullptr && !stopped()) {
6270     replace_unrelated_uncommon_traps_with_alloc_state(alloc, saved_jvms_before_guards);
6271 
6272     assert(alloc != nullptr, "only with a tightly coupled allocation");
6273     // restore JVM state to the state at the arraycopy
6274     saved_jvms_before_guards->map()->set_control(map()->control());
6275     assert(saved_jvms_before_guards->map()->memory() == map()->memory(), "memory state changed?");
6276     assert(saved_jvms_before_guards->map()->i_o() == map()->i_o(), "IO state changed?");
6277     // If we've improved the types of some nodes (null check) while
6278     // emitting the guards, propagate them to the current state
6279     map()->replaced_nodes().apply(saved_jvms_before_guards->map(), new_idx);
6280     set_jvms(saved_jvms_before_guards);
6281     _reexecute_sp = saved_reexecute_sp;
6282 
6283     // Remove the allocation from above the guards
6284     CallProjections* callprojs = alloc->extract_projections(true);
6285     InitializeNode* init = alloc->initialization();
6286     Node* alloc_mem = alloc->in(TypeFunc::Memory);
6287     C->gvn_replace_by(callprojs->fallthrough_ioproj, alloc->in(TypeFunc::I_O));
6288     init->replace_mem_projs_by(alloc_mem, C);
6289 
6290     // The CastIINode created in GraphKit::new_array (in AllocateArrayNode::make_ideal_length) must stay below
6291     // the allocation (i.e. is only valid if the allocation succeeds):
6292     // 1) replace CastIINode with AllocateArrayNode's length here
6293     // 2) Create CastIINode again once allocation has moved (see below) at the end of this method
6294     //
6295     // Multiple identical CastIINodes might exist here. Each GraphKit::load_array_length() call will generate
6296     // new separate CastIINode (arraycopy guard checks or any array length use between array allocation and ararycopy)
6297     Node* init_control = init->proj_out(TypeFunc::Control);
6298     Node* alloc_length = alloc->Ideal_length();
6299 #ifdef ASSERT
6300     Node* prev_cast = nullptr;
6301 #endif
6302     for (uint i = 0; i < init_control->outcnt(); i++) {
6303       Node* init_out = init_control->raw_out(i);
6304       if (init_out->is_CastII() && init_out->in(TypeFunc::Control) == init_control && init_out->in(1) == alloc_length) {
6305 #ifdef ASSERT
6306         if (prev_cast == nullptr) {
6307           prev_cast = init_out;
6308         } else {
6309           if (prev_cast->cmp(*init_out) == false) {
6310             prev_cast->dump();
6311             init_out->dump();
6312             assert(false, "not equal CastIINode");
6313           }
6314         }
6315 #endif
6316         C->gvn_replace_by(init_out, alloc_length);
6317       }
6318     }
6319     C->gvn_replace_by(init->proj_out(TypeFunc::Control), alloc->in(0));
6320 
6321     // move the allocation here (after the guards)
6322     _gvn.hash_delete(alloc);
6323     alloc->set_req(TypeFunc::Control, control());
6324     alloc->set_req(TypeFunc::I_O, i_o());
6325     Node *mem = reset_memory();
6326     set_all_memory(mem);
6327     alloc->set_req(TypeFunc::Memory, mem);
6328     set_control(init->proj_out_or_null(TypeFunc::Control));
6329     set_i_o(callprojs->fallthrough_ioproj);
6330 
6331     // Update memory as done in GraphKit::set_output_for_allocation()
6332     const TypeInt* length_type = _gvn.find_int_type(alloc->in(AllocateNode::ALength));
6333     const TypeOopPtr* ary_type = _gvn.type(alloc->in(AllocateNode::KlassNode))->is_klassptr()->as_instance_type();
6334     if (ary_type->isa_aryptr() && length_type != nullptr) {
6335       ary_type = ary_type->is_aryptr()->cast_to_size(length_type);
6336     }
6337     const TypePtr* telemref = ary_type->add_offset(Type::OffsetBot);
6338     int            elemidx  = C->get_alias_index(telemref);
6339     // Need to properly move every memory projection for the Initialize
6340 #ifdef ASSERT
6341     int mark_idx = C->get_alias_index(ary_type->add_offset(oopDesc::mark_offset_in_bytes()));
6342     int klass_idx = C->get_alias_index(ary_type->add_offset(oopDesc::klass_offset_in_bytes()));
6343 #endif
6344     auto move_proj = [&](ProjNode* proj) {
6345       int alias_idx = C->get_alias_index(proj->adr_type());
6346       assert(alias_idx == Compile::AliasIdxRaw ||
6347              alias_idx == elemidx ||
6348              alias_idx == mark_idx ||
6349              alias_idx == klass_idx, "should be raw memory or array element type");
6350       set_memory(proj, alias_idx);
6351     };
6352     init->for_each_proj(move_proj, TypeFunc::Memory);
6353 
6354     Node* allocx = _gvn.transform(alloc);
6355     assert(allocx == alloc, "where has the allocation gone?");
6356     assert(dest->is_CheckCastPP(), "not an allocation result?");
6357 
6358     _gvn.hash_delete(dest);
6359     dest->set_req(0, control());
6360     Node* destx = _gvn.transform(dest);
6361     assert(destx == dest, "where has the allocation result gone?");
6362 
6363     array_ideal_length(alloc, ary_type, true);
6364   }
6365 }
6366 
6367 // Unrelated UCTs between the array allocation and the array copy, which are considered safe by tightly_coupled_allocation(),
6368 // need to be replaced by an UCT with a state before the array allocation (including the array length). This is necessary
6369 // because we could hit one of these UCTs (which are executed before the emitted array copy guards and the actual array
6370 // allocation which is moved down in arraycopy_move_allocation_here()). When later resuming execution in the interpreter,
6371 // we would have wrongly skipped the array allocation. To prevent this, we resume execution at the array allocation in
6372 // the interpreter similar to what we are doing for the newly emitted guards for the array copy.
6373 void LibraryCallKit::replace_unrelated_uncommon_traps_with_alloc_state(AllocateArrayNode* alloc,
6374                                                                        JVMState* saved_jvms_before_guards) {
6375   if (saved_jvms_before_guards->map()->control()->is_IfProj()) {
6376     // There is at least one unrelated uncommon trap which needs to be replaced.
6377     SafePointNode* sfpt = create_safepoint_with_state_before_array_allocation(alloc);
6378 
6379     JVMState* saved_jvms = jvms();
6380     const int saved_reexecute_sp = _reexecute_sp;
6381     set_jvms(sfpt->jvms());
6382     _reexecute_sp = jvms()->sp();
6383 
6384     replace_unrelated_uncommon_traps_with_alloc_state(saved_jvms_before_guards);
6385 
6386     // Restore state
6387     set_jvms(saved_jvms);
6388     _reexecute_sp = saved_reexecute_sp;
6389   }
6390 }
6391 
6392 // Replace the unrelated uncommon traps with new uncommon trap nodes by reusing the action and reason. The new uncommon
6393 // traps will have the state of the array allocation. Let the old uncommon trap nodes die.
6394 void LibraryCallKit::replace_unrelated_uncommon_traps_with_alloc_state(JVMState* saved_jvms_before_guards) {
6395   Node* if_proj = saved_jvms_before_guards->map()->control(); // Start the search right before the newly emitted guards
6396   while (if_proj->is_IfProj()) {
6397     CallStaticJavaNode* uncommon_trap = get_uncommon_trap_from_success_proj(if_proj);
6398     if (uncommon_trap != nullptr) {
6399       create_new_uncommon_trap(uncommon_trap);
6400     }
6401     assert(if_proj->in(0)->is_If(), "must be If");
6402     if_proj = if_proj->in(0)->in(0);
6403   }
6404   assert(if_proj->is_Proj() && if_proj->in(0)->is_Initialize(),
6405          "must have reached control projection of init node");
6406 }
6407 
6408 void LibraryCallKit::create_new_uncommon_trap(CallStaticJavaNode* uncommon_trap_call) {
6409   const int trap_request = uncommon_trap_call->uncommon_trap_request();
6410   assert(trap_request != 0, "no valid UCT trap request");
6411   PreserveJVMState pjvms(this);
6412   set_control(uncommon_trap_call->in(0));
6413   uncommon_trap(Deoptimization::trap_request_reason(trap_request),
6414                 Deoptimization::trap_request_action(trap_request));
6415   assert(stopped(), "Should be stopped");
6416   _gvn.hash_delete(uncommon_trap_call);
6417   uncommon_trap_call->set_req(0, top()); // not used anymore, kill it
6418 }
6419 
6420 // Common checks for array sorting intrinsics arguments.
6421 // Returns `true` if checks passed.
6422 bool LibraryCallKit::check_array_sort_arguments(Node* elementType, Node* obj, BasicType& bt) {
6423   // check address of the class
6424   if (elementType == nullptr || elementType->is_top()) {
6425     return false;  // dead path
6426   }
6427   const TypeInstPtr* elem_klass = gvn().type(elementType)->isa_instptr();
6428   if (elem_klass == nullptr) {
6429     return false;  // dead path
6430   }
6431   // java_mirror_type() returns non-null for compile-time Class constants only
6432   ciType* elem_type = elem_klass->java_mirror_type();
6433   if (elem_type == nullptr) {
6434     return false;
6435   }
6436   bt = elem_type->basic_type();
6437   // Disable the intrinsic if the CPU does not support SIMD sort
6438   if (!Matcher::supports_simd_sort(bt)) {
6439     return false;
6440   }
6441   // check address of the array
6442   if (obj == nullptr || obj->is_top()) {
6443     return false;  // dead path
6444   }
6445   const TypeAryPtr* obj_t = _gvn.type(obj)->isa_aryptr();
6446   if (obj_t == nullptr || obj_t->elem() == Type::BOTTOM) {
6447     return false; // failed input validation
6448   }
6449   return true;
6450 }
6451 
6452 //------------------------------inline_array_partition-----------------------
6453 bool LibraryCallKit::inline_array_partition() {
6454   address stubAddr = StubRoutines::select_array_partition_function();
6455   if (stubAddr == nullptr) {
6456     return false; // Intrinsic's stub is not implemented on this platform
6457   }
6458   assert(callee()->signature()->size() == 9, "arrayPartition has 8 parameters (one long)");
6459 
6460   // no receiver because it is a static method
6461   Node* elementType     = argument(0);
6462   Node* obj             = argument(1);
6463   Node* offset          = argument(2); // long
6464   Node* fromIndex       = argument(4);
6465   Node* toIndex         = argument(5);
6466   Node* indexPivot1     = argument(6);
6467   Node* indexPivot2     = argument(7);
6468   // PartitionOperation:  argument(8) is ignored
6469 
6470   Node* pivotIndices = nullptr;
6471   BasicType bt = T_ILLEGAL;
6472 
6473   if (!check_array_sort_arguments(elementType, obj, bt)) {
6474     return false;
6475   }
6476   null_check(obj);
6477   // If obj is dead, only null-path is taken.
6478   if (stopped()) {
6479     return true;
6480   }
6481   // Set the original stack and the reexecute bit for the interpreter to reexecute
6482   // the bytecode that invokes DualPivotQuicksort.partition() if deoptimization happens.
6483   { PreserveReexecuteState preexecs(this);
6484     jvms()->set_should_reexecute(true);
6485 
6486     Node* obj_adr = make_unsafe_address(obj, offset);
6487 
6488     // create the pivotIndices array of type int and size = 2
6489     Node* size = intcon(2);
6490     Node* klass_node = makecon(TypeKlassPtr::make(ciTypeArrayKlass::make(T_INT)));
6491     pivotIndices = new_array(klass_node, size, 0);  // no arguments to push
6492     AllocateArrayNode* alloc = tightly_coupled_allocation(pivotIndices);
6493     guarantee(alloc != nullptr, "created above");
6494     Node* pivotIndices_adr = basic_plus_adr(pivotIndices, arrayOopDesc::base_offset_in_bytes(T_INT));
6495 
6496     // pass the basic type enum to the stub
6497     Node* elemType = intcon(bt);
6498 
6499     // Call the stub
6500     const char *stubName = "array_partition_stub";
6501     make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::array_partition_Type(),
6502                       stubAddr, stubName, TypePtr::BOTTOM,
6503                       obj_adr, elemType, fromIndex, toIndex, pivotIndices_adr,
6504                       indexPivot1, indexPivot2);
6505 
6506   } // original reexecute is set back here
6507 
6508   if (!stopped()) {
6509     set_result(pivotIndices);
6510   }
6511 
6512   return true;
6513 }
6514 
6515 
6516 //------------------------------inline_array_sort-----------------------
6517 bool LibraryCallKit::inline_array_sort() {
6518   address stubAddr = StubRoutines::select_arraysort_function();
6519   if (stubAddr == nullptr) {
6520     return false; // Intrinsic's stub is not implemented on this platform
6521   }
6522   assert(callee()->signature()->size() == 7, "arraySort has 6 parameters (one long)");
6523 
6524   // no receiver because it is a static method
6525   Node* elementType     = argument(0);
6526   Node* obj             = argument(1);
6527   Node* offset          = argument(2); // long
6528   Node* fromIndex       = argument(4);
6529   Node* toIndex         = argument(5);
6530   // SortOperation:       argument(6) is ignored
6531 
6532   BasicType bt = T_ILLEGAL;
6533 
6534   if (!check_array_sort_arguments(elementType, obj, bt)) {
6535     return false;
6536   }
6537   null_check(obj);
6538   // If obj is dead, only null-path is taken.
6539   if (stopped()) {
6540     return true;
6541   }
6542   Node* obj_adr = make_unsafe_address(obj, offset);
6543 
6544   // pass the basic type enum to the stub
6545   Node* elemType = intcon(bt);
6546 
6547   // Call the stub.
6548   const char *stubName = "arraysort_stub";
6549   make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::array_sort_Type(),
6550                     stubAddr, stubName, TypePtr::BOTTOM,
6551                     obj_adr, elemType, fromIndex, toIndex);
6552 
6553   return true;
6554 }
6555 
6556 
6557 //------------------------------inline_arraycopy-----------------------
6558 // public static native void java.lang.System.arraycopy(Object src,  int  srcPos,
6559 //                                                      Object dest, int destPos,
6560 //                                                      int length);
6561 bool LibraryCallKit::inline_arraycopy() {
6562   // Get the arguments.
6563   Node* src         = argument(0);  // type: oop
6564   Node* src_offset  = argument(1);  // type: int
6565   Node* dest        = argument(2);  // type: oop
6566   Node* dest_offset = argument(3);  // type: int
6567   Node* length      = argument(4);  // type: int
6568 
6569   uint new_idx = C->unique();
6570 
6571   // Check for allocation before we add nodes that would confuse
6572   // tightly_coupled_allocation()
6573   AllocateArrayNode* alloc = tightly_coupled_allocation(dest);
6574 
6575   int saved_reexecute_sp = -1;
6576   JVMState* saved_jvms_before_guards = arraycopy_restore_alloc_state(alloc, saved_reexecute_sp);
6577   // See arraycopy_restore_alloc_state() comment
6578   // if alloc == null we don't have to worry about a tightly coupled allocation so we can emit all needed guards
6579   // if saved_jvms_before_guards is not null (then alloc is not null) then we can handle guards and a tightly coupled allocation
6580   // if saved_jvms_before_guards is null and alloc is not null, we can't emit any guards
6581   bool can_emit_guards = (alloc == nullptr || saved_jvms_before_guards != nullptr);
6582 
6583   // The following tests must be performed
6584   // (1) src and dest are arrays.
6585   // (2) src and dest arrays must have elements of the same BasicType
6586   // (3) src and dest must not be null.
6587   // (4) src_offset must not be negative.
6588   // (5) dest_offset must not be negative.
6589   // (6) length must not be negative.
6590   // (7) src_offset + length must not exceed length of src.
6591   // (8) dest_offset + length must not exceed length of dest.
6592   // (9) each element of an oop array must be assignable
6593 
6594   // (3) src and dest must not be null.
6595   // always do this here because we need the JVM state for uncommon traps
6596   Node* null_ctl = top();
6597   src  = saved_jvms_before_guards != nullptr ? null_check_oop(src, &null_ctl, true, true) : null_check(src, T_ARRAY);
6598   assert(null_ctl->is_top(), "no null control here");
6599   dest = null_check(dest, T_ARRAY);
6600 
6601   if (!can_emit_guards) {
6602     // if saved_jvms_before_guards is null and alloc is not null, we don't emit any
6603     // guards but the arraycopy node could still take advantage of a
6604     // tightly allocated allocation. tightly_coupled_allocation() is
6605     // called again to make sure it takes the null check above into
6606     // account: the null check is mandatory and if it caused an
6607     // uncommon trap to be emitted then the allocation can't be
6608     // considered tightly coupled in this context.
6609     alloc = tightly_coupled_allocation(dest);
6610   }
6611 
6612   bool validated = false;
6613 
6614   const Type* src_type  = _gvn.type(src);
6615   const Type* dest_type = _gvn.type(dest);
6616   const TypeAryPtr* top_src  = src_type->isa_aryptr();
6617   const TypeAryPtr* top_dest = dest_type->isa_aryptr();
6618 
6619   // Do we have the type of src?
6620   bool has_src = (top_src != nullptr && top_src->elem() != Type::BOTTOM);
6621   // Do we have the type of dest?
6622   bool has_dest = (top_dest != nullptr && top_dest->elem() != Type::BOTTOM);
6623   // Is the type for src from speculation?
6624   bool src_spec = false;
6625   // Is the type for dest from speculation?
6626   bool dest_spec = false;
6627 
6628   if ((!has_src || !has_dest) && can_emit_guards) {
6629     // We don't have sufficient type information, let's see if
6630     // speculative types can help. We need to have types for both src
6631     // and dest so that it pays off.
6632 
6633     // Do we already have or could we have type information for src
6634     bool could_have_src = has_src;
6635     // Do we already have or could we have type information for dest
6636     bool could_have_dest = has_dest;
6637 
6638     ciKlass* src_k = nullptr;
6639     if (!has_src) {
6640       src_k = src_type->speculative_type_not_null();
6641       if (src_k != nullptr && src_k->is_array_klass()) {
6642         could_have_src = true;
6643       }
6644     }
6645 
6646     ciKlass* dest_k = nullptr;
6647     if (!has_dest) {
6648       dest_k = dest_type->speculative_type_not_null();
6649       if (dest_k != nullptr && dest_k->is_array_klass()) {
6650         could_have_dest = true;
6651       }
6652     }
6653 
6654     if (could_have_src && could_have_dest) {
6655       // This is going to pay off so emit the required guards
6656       if (!has_src) {
6657         src = maybe_cast_profiled_obj(src, src_k, true);
6658         src_type  = _gvn.type(src);
6659         top_src  = src_type->isa_aryptr();
6660         has_src = (top_src != nullptr && top_src->elem() != Type::BOTTOM);
6661         src_spec = true;
6662       }
6663       if (!has_dest) {
6664         dest = maybe_cast_profiled_obj(dest, dest_k, true);
6665         dest_type  = _gvn.type(dest);
6666         top_dest  = dest_type->isa_aryptr();
6667         has_dest = (top_dest != nullptr && top_dest->elem() != Type::BOTTOM);
6668         dest_spec = true;
6669       }
6670     }
6671   }
6672 
6673   if (has_src && has_dest && can_emit_guards) {
6674     BasicType src_elem = top_src->isa_aryptr()->elem()->array_element_basic_type();
6675     BasicType dest_elem = top_dest->isa_aryptr()->elem()->array_element_basic_type();
6676     if (is_reference_type(src_elem, true)) src_elem = T_OBJECT;
6677     if (is_reference_type(dest_elem, true)) dest_elem = T_OBJECT;
6678 
6679     if (src_elem == dest_elem && top_src->is_flat() == top_dest->is_flat() && src_elem == T_OBJECT) {
6680       // If both arrays are object arrays then having the exact types
6681       // for both will remove the need for a subtype check at runtime
6682       // before the call and may make it possible to pick a faster copy
6683       // routine (without a subtype check on every element)
6684       // Do we have the exact type of src?
6685       bool could_have_src = src_spec;
6686       // Do we have the exact type of dest?
6687       bool could_have_dest = dest_spec;
6688       ciKlass* src_k = nullptr;
6689       ciKlass* dest_k = nullptr;
6690       if (!src_spec) {
6691         src_k = src_type->speculative_type_not_null();
6692         if (src_k != nullptr && src_k->is_array_klass()) {
6693           could_have_src = true;
6694         }
6695       }
6696       if (!dest_spec) {
6697         dest_k = dest_type->speculative_type_not_null();
6698         if (dest_k != nullptr && dest_k->is_array_klass()) {
6699           could_have_dest = true;
6700         }
6701       }
6702       if (could_have_src && could_have_dest) {
6703         // If we can have both exact types, emit the missing guards
6704         if (could_have_src && !src_spec) {
6705           src = maybe_cast_profiled_obj(src, src_k, true);
6706           src_type = _gvn.type(src);
6707           top_src = src_type->isa_aryptr();
6708         }
6709         if (could_have_dest && !dest_spec) {
6710           dest = maybe_cast_profiled_obj(dest, dest_k, true);
6711           dest_type = _gvn.type(dest);
6712           top_dest = dest_type->isa_aryptr();
6713         }
6714       }
6715     }
6716   }
6717 
6718   ciMethod* trap_method = method();
6719   int trap_bci = bci();
6720   if (saved_jvms_before_guards != nullptr) {
6721     trap_method = alloc->jvms()->method();
6722     trap_bci = alloc->jvms()->bci();
6723   }
6724 
6725   bool negative_length_guard_generated = false;
6726 
6727   if (!C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_intrinsic) &&
6728       can_emit_guards && !src->is_top() && !dest->is_top()) {
6729     // validate arguments: enables transformation the ArrayCopyNode
6730     validated = true;
6731 
6732     RegionNode* slow_region = new RegionNode(1);
6733     record_for_igvn(slow_region);
6734 
6735     // (1) src and dest are arrays.
6736     generate_non_array_guard(load_object_klass(src), slow_region, &src);
6737     generate_non_array_guard(load_object_klass(dest), slow_region, &dest);
6738 
6739     // (2) src and dest arrays must have elements of the same BasicType
6740     // done at macro expansion or at Ideal transformation time
6741 
6742     // (4) src_offset must not be negative.
6743     generate_negative_guard(src_offset, slow_region);
6744 
6745     // (5) dest_offset must not be negative.
6746     generate_negative_guard(dest_offset, slow_region);
6747 
6748     // (7) src_offset + length must not exceed length of src.
6749     generate_limit_guard(src_offset, length,
6750                          load_array_length(src),
6751                          slow_region);
6752 
6753     // (8) dest_offset + length must not exceed length of dest.
6754     generate_limit_guard(dest_offset, length,
6755                          load_array_length(dest),
6756                          slow_region);
6757 
6758     // (6) length must not be negative.
6759     // This is also checked in generate_arraycopy() during macro expansion, but
6760     // we also have to check it here for the case where the ArrayCopyNode will
6761     // be eliminated by Escape Analysis.
6762     if (EliminateAllocations) {
6763       generate_negative_guard(length, slow_region);
6764       negative_length_guard_generated = true;
6765     }
6766 
6767     // (9) each element of an oop array must be assignable
6768     Node* dest_klass = load_object_klass(dest);
6769     Node* refined_dest_klass = dest_klass;
6770     if (src != dest) {
6771       dest_klass = load_non_refined_array_klass(refined_dest_klass);
6772       Node* not_subtype_ctrl = gen_subtype_check(src, dest_klass);
6773       slow_region->add_req(not_subtype_ctrl);
6774     }
6775 
6776     // TODO 8350865 Improve this. What about atomicity? Make sure this is always folded for type arrays.
6777     // If destination is null-restricted, source must be null-restricted as well: src_null_restricted || !dst_null_restricted
6778     Node* src_klass = load_object_klass(src);
6779     Node* adr_prop_src = basic_plus_adr(src_klass, in_bytes(ArrayKlass::properties_offset()));
6780     Node* prop_src = _gvn.transform(LoadNode::make(_gvn, control(), immutable_memory(), adr_prop_src, TypeRawPtr::BOTTOM, TypeInt::INT, T_INT, MemNode::unordered));
6781     Node* adr_prop_dest = basic_plus_adr(refined_dest_klass, in_bytes(ArrayKlass::properties_offset()));
6782     Node* prop_dest = _gvn.transform(LoadNode::make(_gvn, control(), immutable_memory(), adr_prop_dest, TypeRawPtr::BOTTOM, TypeInt::INT, T_INT, MemNode::unordered));
6783 
6784     prop_dest = _gvn.transform(new XorINode(prop_dest, intcon(ArrayKlass::ArrayProperties::NULL_RESTRICTED)));
6785     prop_src = _gvn.transform(new OrINode(prop_dest, prop_src));
6786     prop_src = _gvn.transform(new AndINode(prop_src, intcon(ArrayKlass::ArrayProperties::NULL_RESTRICTED)));
6787 
6788     Node* chk = _gvn.transform(new CmpINode(prop_src, intcon(ArrayKlass::ArrayProperties::NULL_RESTRICTED)));
6789     Node* tst = _gvn.transform(new BoolNode(chk, BoolTest::ne));
6790     generate_fair_guard(tst, slow_region);
6791 
6792     // TODO 8350865 This is too strong
6793     generate_fair_guard(flat_array_test(src), slow_region);
6794     generate_fair_guard(flat_array_test(dest), slow_region);
6795 
6796     {
6797       PreserveJVMState pjvms(this);
6798       set_control(_gvn.transform(slow_region));
6799       uncommon_trap(Deoptimization::Reason_intrinsic,
6800                     Deoptimization::Action_make_not_entrant);
6801       assert(stopped(), "Should be stopped");
6802     }
6803 
6804     const TypeKlassPtr* dest_klass_t = _gvn.type(refined_dest_klass)->is_klassptr();
6805     const Type* toop = dest_klass_t->cast_to_exactness(false)->as_instance_type();
6806     src = _gvn.transform(new CheckCastPPNode(control(), src, toop));
6807     arraycopy_move_allocation_here(alloc, dest, saved_jvms_before_guards, saved_reexecute_sp, new_idx);
6808   }
6809 
6810   if (stopped()) {
6811     return true;
6812   }
6813 
6814   Node* dest_klass = load_object_klass(dest);
6815   dest_klass = load_non_refined_array_klass(dest_klass);
6816 
6817   ArrayCopyNode* ac = ArrayCopyNode::make(this, true, src, src_offset, dest, dest_offset, length, alloc != nullptr, negative_length_guard_generated,
6818                                           // Create LoadRange and LoadKlass nodes for use during macro expansion here
6819                                           // so the compiler has a chance to eliminate them: during macro expansion,
6820                                           // we have to set their control (CastPP nodes are eliminated).
6821                                           load_object_klass(src), dest_klass,
6822                                           load_array_length(src), load_array_length(dest));
6823 
6824   ac->set_arraycopy(validated);
6825 
6826   Node* n = _gvn.transform(ac);
6827   if (n == ac) {
6828     ac->connect_outputs(this);
6829   } else {
6830     assert(validated, "shouldn't transform if all arguments not validated");
6831     set_all_memory(n);
6832   }
6833   clear_upper_avx();
6834 
6835 
6836   return true;
6837 }
6838 
6839 
6840 // Helper function which determines if an arraycopy immediately follows
6841 // an allocation, with no intervening tests or other escapes for the object.
6842 AllocateArrayNode*
6843 LibraryCallKit::tightly_coupled_allocation(Node* ptr) {
6844   if (stopped())             return nullptr;  // no fast path
6845   if (!C->do_aliasing())     return nullptr;  // no MergeMems around
6846 
6847   AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(ptr);
6848   if (alloc == nullptr)  return nullptr;
6849 
6850   Node* rawmem = memory(Compile::AliasIdxRaw);
6851   // Is the allocation's memory state untouched?
6852   if (!(rawmem->is_Proj() && rawmem->in(0)->is_Initialize())) {
6853     // Bail out if there have been raw-memory effects since the allocation.
6854     // (Example:  There might have been a call or safepoint.)
6855     return nullptr;
6856   }
6857   rawmem = rawmem->in(0)->as_Initialize()->memory(Compile::AliasIdxRaw);
6858   if (!(rawmem->is_Proj() && rawmem->in(0) == alloc)) {
6859     return nullptr;
6860   }
6861 
6862   // There must be no unexpected observers of this allocation.
6863   for (DUIterator_Fast imax, i = ptr->fast_outs(imax); i < imax; i++) {
6864     Node* obs = ptr->fast_out(i);
6865     if (obs != this->map()) {
6866       return nullptr;
6867     }
6868   }
6869 
6870   // This arraycopy must unconditionally follow the allocation of the ptr.
6871   Node* alloc_ctl = ptr->in(0);
6872   Node* ctl = control();
6873   while (ctl != alloc_ctl) {
6874     // There may be guards which feed into the slow_region.
6875     // Any other control flow means that we might not get a chance
6876     // to finish initializing the allocated object.
6877     // Various low-level checks bottom out in uncommon traps. These
6878     // are considered safe since we've already checked above that
6879     // there is no unexpected observer of this allocation.
6880     if (get_uncommon_trap_from_success_proj(ctl) != nullptr) {
6881       assert(ctl->in(0)->is_If(), "must be If");
6882       ctl = ctl->in(0)->in(0);
6883     } else {
6884       return nullptr;
6885     }
6886   }
6887 
6888   // If we get this far, we have an allocation which immediately
6889   // precedes the arraycopy, and we can take over zeroing the new object.
6890   // The arraycopy will finish the initialization, and provide
6891   // a new control state to which we will anchor the destination pointer.
6892 
6893   return alloc;
6894 }
6895 
6896 CallStaticJavaNode* LibraryCallKit::get_uncommon_trap_from_success_proj(Node* node) {
6897   if (node->is_IfProj()) {
6898     Node* other_proj = node->as_IfProj()->other_if_proj();
6899     for (DUIterator_Fast jmax, j = other_proj->fast_outs(jmax); j < jmax; j++) {
6900       Node* obs = other_proj->fast_out(j);
6901       if (obs->in(0) == other_proj && obs->is_CallStaticJava() &&
6902           (obs->as_CallStaticJava()->entry_point() == OptoRuntime::uncommon_trap_blob()->entry_point())) {
6903         return obs->as_CallStaticJava();
6904       }
6905     }
6906   }
6907   return nullptr;
6908 }
6909 
6910 //-------------inline_encodeISOArray-----------------------------------
6911 // int sun.nio.cs.ISO_8859_1.Encoder#encodeISOArray0(byte[] sa, int sp, byte[] da, int dp, int len)
6912 // int java.lang.StringCoding#encodeISOArray0(byte[] sa, int sp, byte[] da, int dp, int len)
6913 // int java.lang.StringCoding#encodeAsciiArray0(char[] sa, int sp, byte[] da, int dp, int len)
6914 // encode char[] to byte[] in ISO_8859_1 or ASCII
6915 bool LibraryCallKit::inline_encodeISOArray(bool ascii) {
6916   assert(callee()->signature()->size() == 5, "encodeISOArray has 5 parameters");
6917   // no receiver since it is static method
6918   Node *src         = argument(0);
6919   Node *src_offset  = argument(1);
6920   Node *dst         = argument(2);
6921   Node *dst_offset  = argument(3);
6922   Node *length      = argument(4);
6923 
6924   // Cast source & target arrays to not-null
6925   if (VerifyIntrinsicChecks) {
6926     src = must_be_not_null(src, true);
6927     dst = must_be_not_null(dst, true);
6928     if (stopped()) {
6929       return true;
6930     }
6931   }
6932 
6933   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
6934   const TypeAryPtr* dst_type = dst->Value(&_gvn)->isa_aryptr();
6935   if (src_type == nullptr || src_type->elem() == Type::BOTTOM ||
6936       dst_type == nullptr || dst_type->elem() == Type::BOTTOM) {
6937     // failed array check
6938     return false;
6939   }
6940 
6941   // Figure out the size and type of the elements we will be copying.
6942   BasicType src_elem = src_type->elem()->array_element_basic_type();
6943   BasicType dst_elem = dst_type->elem()->array_element_basic_type();
6944   if (!((src_elem == T_CHAR) || (src_elem== T_BYTE)) || dst_elem != T_BYTE) {
6945     return false;
6946   }
6947 
6948   // Check source & target bounds
6949   if (VerifyIntrinsicChecks) {
6950     generate_string_range_check(src, src_offset, length, src_elem == T_BYTE, true);
6951     generate_string_range_check(dst, dst_offset, length, false, true);
6952     if (stopped()) {
6953       return true;
6954     }
6955   }
6956 
6957   Node* src_start = array_element_address(src, src_offset, T_CHAR);
6958   Node* dst_start = array_element_address(dst, dst_offset, dst_elem);
6959   // 'src_start' points to src array + scaled offset
6960   // 'dst_start' points to dst array + scaled offset
6961 
6962   const TypeAryPtr* mtype = TypeAryPtr::BYTES;
6963   Node* enc = new EncodeISOArrayNode(control(), memory(mtype), src_start, dst_start, length, ascii);
6964   enc = _gvn.transform(enc);
6965   Node* res_mem = _gvn.transform(new SCMemProjNode(enc));
6966   set_memory(res_mem, mtype);
6967   set_result(enc);
6968   clear_upper_avx();
6969 
6970   return true;
6971 }
6972 
6973 //-------------inline_multiplyToLen-----------------------------------
6974 bool LibraryCallKit::inline_multiplyToLen() {
6975   assert(UseMultiplyToLenIntrinsic, "not implemented on this platform");
6976 
6977   address stubAddr = StubRoutines::multiplyToLen();
6978   if (stubAddr == nullptr) {
6979     return false; // Intrinsic's stub is not implemented on this platform
6980   }
6981   const char* stubName = "multiplyToLen";
6982 
6983   assert(callee()->signature()->size() == 5, "multiplyToLen has 5 parameters");
6984 
6985   // no receiver because it is a static method
6986   Node* x    = argument(0);
6987   Node* xlen = argument(1);
6988   Node* y    = argument(2);
6989   Node* ylen = argument(3);
6990   Node* z    = argument(4);
6991 
6992   x = must_be_not_null(x, true);
6993   y = must_be_not_null(y, true);
6994 
6995   const TypeAryPtr* x_type = x->Value(&_gvn)->isa_aryptr();
6996   const TypeAryPtr* y_type = y->Value(&_gvn)->isa_aryptr();
6997   if (x_type == nullptr || x_type->elem() == Type::BOTTOM ||
6998       y_type == nullptr || y_type->elem() == Type::BOTTOM) {
6999     // failed array check
7000     return false;
7001   }
7002 
7003   BasicType x_elem = x_type->elem()->array_element_basic_type();
7004   BasicType y_elem = y_type->elem()->array_element_basic_type();
7005   if (x_elem != T_INT || y_elem != T_INT) {
7006     return false;
7007   }
7008 
7009   Node* x_start = array_element_address(x, intcon(0), x_elem);
7010   Node* y_start = array_element_address(y, intcon(0), y_elem);
7011   // 'x_start' points to x array + scaled xlen
7012   // 'y_start' points to y array + scaled ylen
7013 
7014   Node* z_start = array_element_address(z, intcon(0), T_INT);
7015 
7016   Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
7017                                  OptoRuntime::multiplyToLen_Type(),
7018                                  stubAddr, stubName, TypePtr::BOTTOM,
7019                                  x_start, xlen, y_start, ylen, z_start);
7020 
7021   C->set_has_split_ifs(true); // Has chance for split-if optimization
7022   set_result(z);
7023   return true;
7024 }
7025 
7026 //-------------inline_squareToLen------------------------------------
7027 bool LibraryCallKit::inline_squareToLen() {
7028   assert(UseSquareToLenIntrinsic, "not implemented on this platform");
7029 
7030   address stubAddr = StubRoutines::squareToLen();
7031   if (stubAddr == nullptr) {
7032     return false; // Intrinsic's stub is not implemented on this platform
7033   }
7034   const char* stubName = "squareToLen";
7035 
7036   assert(callee()->signature()->size() == 4, "implSquareToLen has 4 parameters");
7037 
7038   Node* x    = argument(0);
7039   Node* len  = argument(1);
7040   Node* z    = argument(2);
7041   Node* zlen = argument(3);
7042 
7043   x = must_be_not_null(x, true);
7044   z = must_be_not_null(z, true);
7045 
7046   const TypeAryPtr* x_type = x->Value(&_gvn)->isa_aryptr();
7047   const TypeAryPtr* z_type = z->Value(&_gvn)->isa_aryptr();
7048   if (x_type == nullptr || x_type->elem() == Type::BOTTOM ||
7049       z_type == nullptr || z_type->elem() == Type::BOTTOM) {
7050     // failed array check
7051     return false;
7052   }
7053 
7054   BasicType x_elem = x_type->elem()->array_element_basic_type();
7055   BasicType z_elem = z_type->elem()->array_element_basic_type();
7056   if (x_elem != T_INT || z_elem != T_INT) {
7057     return false;
7058   }
7059 
7060 
7061   Node* x_start = array_element_address(x, intcon(0), x_elem);
7062   Node* z_start = array_element_address(z, intcon(0), z_elem);
7063 
7064   Node*  call = make_runtime_call(RC_LEAF|RC_NO_FP,
7065                                   OptoRuntime::squareToLen_Type(),
7066                                   stubAddr, stubName, TypePtr::BOTTOM,
7067                                   x_start, len, z_start, zlen);
7068 
7069   set_result(z);
7070   return true;
7071 }
7072 
7073 //-------------inline_mulAdd------------------------------------------
7074 bool LibraryCallKit::inline_mulAdd() {
7075   assert(UseMulAddIntrinsic, "not implemented on this platform");
7076 
7077   address stubAddr = StubRoutines::mulAdd();
7078   if (stubAddr == nullptr) {
7079     return false; // Intrinsic's stub is not implemented on this platform
7080   }
7081   const char* stubName = "mulAdd";
7082 
7083   assert(callee()->signature()->size() == 5, "mulAdd has 5 parameters");
7084 
7085   Node* out      = argument(0);
7086   Node* in       = argument(1);
7087   Node* offset   = argument(2);
7088   Node* len      = argument(3);
7089   Node* k        = argument(4);
7090 
7091   in = must_be_not_null(in, true);
7092   out = must_be_not_null(out, true);
7093 
7094   const TypeAryPtr* out_type = out->Value(&_gvn)->isa_aryptr();
7095   const TypeAryPtr* in_type = in->Value(&_gvn)->isa_aryptr();
7096   if (out_type == nullptr || out_type->elem() == Type::BOTTOM ||
7097        in_type == nullptr ||  in_type->elem() == Type::BOTTOM) {
7098     // failed array check
7099     return false;
7100   }
7101 
7102   BasicType out_elem = out_type->elem()->array_element_basic_type();
7103   BasicType in_elem = in_type->elem()->array_element_basic_type();
7104   if (out_elem != T_INT || in_elem != T_INT) {
7105     return false;
7106   }
7107 
7108   Node* outlen = load_array_length(out);
7109   Node* new_offset = _gvn.transform(new SubINode(outlen, offset));
7110   Node* out_start = array_element_address(out, intcon(0), out_elem);
7111   Node* in_start = array_element_address(in, intcon(0), in_elem);
7112 
7113   Node*  call = make_runtime_call(RC_LEAF|RC_NO_FP,
7114                                   OptoRuntime::mulAdd_Type(),
7115                                   stubAddr, stubName, TypePtr::BOTTOM,
7116                                   out_start,in_start, new_offset, len, k);
7117   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7118   set_result(result);
7119   return true;
7120 }
7121 
7122 //-------------inline_montgomeryMultiply-----------------------------------
7123 bool LibraryCallKit::inline_montgomeryMultiply() {
7124   address stubAddr = StubRoutines::montgomeryMultiply();
7125   if (stubAddr == nullptr) {
7126     return false; // Intrinsic's stub is not implemented on this platform
7127   }
7128 
7129   assert(UseMontgomeryMultiplyIntrinsic, "not implemented on this platform");
7130   const char* stubName = "montgomery_multiply";
7131 
7132   assert(callee()->signature()->size() == 7, "montgomeryMultiply has 7 parameters");
7133 
7134   Node* a    = argument(0);
7135   Node* b    = argument(1);
7136   Node* n    = argument(2);
7137   Node* len  = argument(3);
7138   Node* inv  = argument(4);
7139   Node* m    = argument(6);
7140 
7141   const TypeAryPtr* a_type = a->Value(&_gvn)->isa_aryptr();
7142   const TypeAryPtr* b_type = b->Value(&_gvn)->isa_aryptr();
7143   const TypeAryPtr* n_type = n->Value(&_gvn)->isa_aryptr();
7144   const TypeAryPtr* m_type = m->Value(&_gvn)->isa_aryptr();
7145   if (a_type == nullptr || a_type->elem() == Type::BOTTOM ||
7146       b_type == nullptr || b_type->elem() == Type::BOTTOM ||
7147       n_type == nullptr || n_type->elem() == Type::BOTTOM ||
7148       m_type == nullptr || m_type->elem() == Type::BOTTOM) {
7149     // failed array check
7150     return false;
7151   }
7152 
7153   BasicType a_elem = a_type->elem()->array_element_basic_type();
7154   BasicType b_elem = b_type->elem()->array_element_basic_type();
7155   BasicType n_elem = n_type->elem()->array_element_basic_type();
7156   BasicType m_elem = m_type->elem()->array_element_basic_type();
7157   if (a_elem != T_INT || b_elem != T_INT || n_elem != T_INT || m_elem != T_INT) {
7158     return false;
7159   }
7160 
7161   // Make the call
7162   {
7163     Node* a_start = array_element_address(a, intcon(0), a_elem);
7164     Node* b_start = array_element_address(b, intcon(0), b_elem);
7165     Node* n_start = array_element_address(n, intcon(0), n_elem);
7166     Node* m_start = array_element_address(m, intcon(0), m_elem);
7167 
7168     Node* call = make_runtime_call(RC_LEAF,
7169                                    OptoRuntime::montgomeryMultiply_Type(),
7170                                    stubAddr, stubName, TypePtr::BOTTOM,
7171                                    a_start, b_start, n_start, len, inv, top(),
7172                                    m_start);
7173     set_result(m);
7174   }
7175 
7176   return true;
7177 }
7178 
7179 bool LibraryCallKit::inline_montgomerySquare() {
7180   address stubAddr = StubRoutines::montgomerySquare();
7181   if (stubAddr == nullptr) {
7182     return false; // Intrinsic's stub is not implemented on this platform
7183   }
7184 
7185   assert(UseMontgomerySquareIntrinsic, "not implemented on this platform");
7186   const char* stubName = "montgomery_square";
7187 
7188   assert(callee()->signature()->size() == 6, "montgomerySquare has 6 parameters");
7189 
7190   Node* a    = argument(0);
7191   Node* n    = argument(1);
7192   Node* len  = argument(2);
7193   Node* inv  = argument(3);
7194   Node* m    = argument(5);
7195 
7196   const TypeAryPtr* a_type = a->Value(&_gvn)->isa_aryptr();
7197   const TypeAryPtr* n_type = n->Value(&_gvn)->isa_aryptr();
7198   const TypeAryPtr* m_type = m->Value(&_gvn)->isa_aryptr();
7199   if (a_type == nullptr || a_type->elem() == Type::BOTTOM ||
7200       n_type == nullptr || n_type->elem() == Type::BOTTOM ||
7201       m_type == nullptr || m_type->elem() == Type::BOTTOM) {
7202     // failed array check
7203     return false;
7204   }
7205 
7206   BasicType a_elem = a_type->elem()->array_element_basic_type();
7207   BasicType n_elem = n_type->elem()->array_element_basic_type();
7208   BasicType m_elem = m_type->elem()->array_element_basic_type();
7209   if (a_elem != T_INT || n_elem != T_INT || m_elem != T_INT) {
7210     return false;
7211   }
7212 
7213   // Make the call
7214   {
7215     Node* a_start = array_element_address(a, intcon(0), a_elem);
7216     Node* n_start = array_element_address(n, intcon(0), n_elem);
7217     Node* m_start = array_element_address(m, intcon(0), m_elem);
7218 
7219     Node* call = make_runtime_call(RC_LEAF,
7220                                    OptoRuntime::montgomerySquare_Type(),
7221                                    stubAddr, stubName, TypePtr::BOTTOM,
7222                                    a_start, n_start, len, inv, top(),
7223                                    m_start);
7224     set_result(m);
7225   }
7226 
7227   return true;
7228 }
7229 
7230 bool LibraryCallKit::inline_bigIntegerShift(bool isRightShift) {
7231   address stubAddr = nullptr;
7232   const char* stubName = nullptr;
7233 
7234   stubAddr = isRightShift? StubRoutines::bigIntegerRightShift(): StubRoutines::bigIntegerLeftShift();
7235   if (stubAddr == nullptr) {
7236     return false; // Intrinsic's stub is not implemented on this platform
7237   }
7238 
7239   stubName = isRightShift? "bigIntegerRightShiftWorker" : "bigIntegerLeftShiftWorker";
7240 
7241   assert(callee()->signature()->size() == 5, "expected 5 arguments");
7242 
7243   Node* newArr = argument(0);
7244   Node* oldArr = argument(1);
7245   Node* newIdx = argument(2);
7246   Node* shiftCount = argument(3);
7247   Node* numIter = argument(4);
7248 
7249   const TypeAryPtr* newArr_type = newArr->Value(&_gvn)->isa_aryptr();
7250   const TypeAryPtr* oldArr_type = oldArr->Value(&_gvn)->isa_aryptr();
7251   if (newArr_type == nullptr || newArr_type->elem() == Type::BOTTOM ||
7252       oldArr_type == nullptr || oldArr_type->elem() == Type::BOTTOM) {
7253     return false;
7254   }
7255 
7256   BasicType newArr_elem = newArr_type->elem()->array_element_basic_type();
7257   BasicType oldArr_elem = oldArr_type->elem()->array_element_basic_type();
7258   if (newArr_elem != T_INT || oldArr_elem != T_INT) {
7259     return false;
7260   }
7261 
7262   // Make the call
7263   {
7264     Node* newArr_start = array_element_address(newArr, intcon(0), newArr_elem);
7265     Node* oldArr_start = array_element_address(oldArr, intcon(0), oldArr_elem);
7266 
7267     Node* call = make_runtime_call(RC_LEAF,
7268                                    OptoRuntime::bigIntegerShift_Type(),
7269                                    stubAddr,
7270                                    stubName,
7271                                    TypePtr::BOTTOM,
7272                                    newArr_start,
7273                                    oldArr_start,
7274                                    newIdx,
7275                                    shiftCount,
7276                                    numIter);
7277   }
7278 
7279   return true;
7280 }
7281 
7282 //-------------inline_vectorizedMismatch------------------------------
7283 bool LibraryCallKit::inline_vectorizedMismatch() {
7284   assert(UseVectorizedMismatchIntrinsic, "not implemented on this platform");
7285 
7286   assert(callee()->signature()->size() == 8, "vectorizedMismatch has 6 parameters");
7287   Node* obja    = argument(0); // Object
7288   Node* aoffset = argument(1); // long
7289   Node* objb    = argument(3); // Object
7290   Node* boffset = argument(4); // long
7291   Node* length  = argument(6); // int
7292   Node* scale   = argument(7); // int
7293 
7294   const TypeAryPtr* obja_t = _gvn.type(obja)->isa_aryptr();
7295   const TypeAryPtr* objb_t = _gvn.type(objb)->isa_aryptr();
7296   if (obja_t == nullptr || obja_t->elem() == Type::BOTTOM ||
7297       objb_t == nullptr || objb_t->elem() == Type::BOTTOM ||
7298       scale == top()) {
7299     return false; // failed input validation
7300   }
7301 
7302   Node* obja_adr = make_unsafe_address(obja, aoffset);
7303   Node* objb_adr = make_unsafe_address(objb, boffset);
7304 
7305   // Partial inlining handling for inputs smaller than ArrayOperationPartialInlineSize bytes in size.
7306   //
7307   //    inline_limit = ArrayOperationPartialInlineSize / element_size;
7308   //    if (length <= inline_limit) {
7309   //      inline_path:
7310   //        vmask   = VectorMaskGen length
7311   //        vload1  = LoadVectorMasked obja, vmask
7312   //        vload2  = LoadVectorMasked objb, vmask
7313   //        result1 = VectorCmpMasked vload1, vload2, vmask
7314   //    } else {
7315   //      call_stub_path:
7316   //        result2 = call vectorizedMismatch_stub(obja, objb, length, scale)
7317   //    }
7318   //    exit_block:
7319   //      return Phi(result1, result2);
7320   //
7321   enum { inline_path = 1,  // input is small enough to process it all at once
7322          stub_path   = 2,  // input is too large; call into the VM
7323          PATH_LIMIT  = 3
7324   };
7325 
7326   Node* exit_block = new RegionNode(PATH_LIMIT);
7327   Node* result_phi = new PhiNode(exit_block, TypeInt::INT);
7328   Node* memory_phi = new PhiNode(exit_block, Type::MEMORY, TypePtr::BOTTOM);
7329 
7330   Node* call_stub_path = control();
7331 
7332   BasicType elem_bt = T_ILLEGAL;
7333 
7334   const TypeInt* scale_t = _gvn.type(scale)->is_int();
7335   if (scale_t->is_con()) {
7336     switch (scale_t->get_con()) {
7337       case 0: elem_bt = T_BYTE;  break;
7338       case 1: elem_bt = T_SHORT; break;
7339       case 2: elem_bt = T_INT;   break;
7340       case 3: elem_bt = T_LONG;  break;
7341 
7342       default: elem_bt = T_ILLEGAL; break; // not supported
7343     }
7344   }
7345 
7346   int inline_limit = 0;
7347   bool do_partial_inline = false;
7348 
7349   if (elem_bt != T_ILLEGAL && ArrayOperationPartialInlineSize > 0) {
7350     inline_limit = ArrayOperationPartialInlineSize / type2aelembytes(elem_bt);
7351     do_partial_inline = inline_limit >= 16;
7352   }
7353 
7354   if (do_partial_inline) {
7355     assert(elem_bt != T_ILLEGAL, "sanity");
7356 
7357     if (Matcher::match_rule_supported_vector(Op_VectorMaskGen,    inline_limit, elem_bt) &&
7358         Matcher::match_rule_supported_vector(Op_LoadVectorMasked, inline_limit, elem_bt) &&
7359         Matcher::match_rule_supported_vector(Op_VectorCmpMasked,  inline_limit, elem_bt)) {
7360 
7361       const TypeVect* vt = TypeVect::make(elem_bt, inline_limit);
7362       Node* cmp_length = _gvn.transform(new CmpINode(length, intcon(inline_limit)));
7363       Node* bol_gt     = _gvn.transform(new BoolNode(cmp_length, BoolTest::gt));
7364 
7365       call_stub_path = generate_guard(bol_gt, nullptr, PROB_MIN);
7366 
7367       if (!stopped()) {
7368         Node* casted_length = _gvn.transform(new CastIINode(control(), length, TypeInt::make(0, inline_limit, Type::WidenMin)));
7369 
7370         const TypePtr* obja_adr_t = _gvn.type(obja_adr)->isa_ptr();
7371         const TypePtr* objb_adr_t = _gvn.type(objb_adr)->isa_ptr();
7372         Node* obja_adr_mem = memory(C->get_alias_index(obja_adr_t));
7373         Node* objb_adr_mem = memory(C->get_alias_index(objb_adr_t));
7374 
7375         Node* vmask      = _gvn.transform(VectorMaskGenNode::make(ConvI2X(casted_length), elem_bt));
7376         Node* vload_obja = _gvn.transform(new LoadVectorMaskedNode(control(), obja_adr_mem, obja_adr, obja_adr_t, vt, vmask));
7377         Node* vload_objb = _gvn.transform(new LoadVectorMaskedNode(control(), objb_adr_mem, objb_adr, objb_adr_t, vt, vmask));
7378         Node* result     = _gvn.transform(new VectorCmpMaskedNode(vload_obja, vload_objb, vmask, TypeInt::INT));
7379 
7380         exit_block->init_req(inline_path, control());
7381         memory_phi->init_req(inline_path, map()->memory());
7382         result_phi->init_req(inline_path, result);
7383 
7384         C->set_max_vector_size(MAX2((uint)ArrayOperationPartialInlineSize, C->max_vector_size()));
7385         clear_upper_avx();
7386       }
7387     }
7388   }
7389 
7390   if (call_stub_path != nullptr) {
7391     set_control(call_stub_path);
7392 
7393     Node* call = make_runtime_call(RC_LEAF,
7394                                    OptoRuntime::vectorizedMismatch_Type(),
7395                                    StubRoutines::vectorizedMismatch(), "vectorizedMismatch", TypePtr::BOTTOM,
7396                                    obja_adr, objb_adr, length, scale);
7397 
7398     exit_block->init_req(stub_path, control());
7399     memory_phi->init_req(stub_path, map()->memory());
7400     result_phi->init_req(stub_path, _gvn.transform(new ProjNode(call, TypeFunc::Parms)));
7401   }
7402 
7403   exit_block = _gvn.transform(exit_block);
7404   memory_phi = _gvn.transform(memory_phi);
7405   result_phi = _gvn.transform(result_phi);
7406 
7407   record_for_igvn(exit_block);
7408   record_for_igvn(memory_phi);
7409   record_for_igvn(result_phi);
7410 
7411   set_control(exit_block);
7412   set_all_memory(memory_phi);
7413   set_result(result_phi);
7414 
7415   return true;
7416 }
7417 
7418 //------------------------------inline_vectorizedHashcode----------------------------
7419 bool LibraryCallKit::inline_vectorizedHashCode() {
7420   assert(UseVectorizedHashCodeIntrinsic, "not implemented on this platform");
7421 
7422   assert(callee()->signature()->size() == 5, "vectorizedHashCode has 5 parameters");
7423   Node* array          = argument(0);
7424   Node* offset         = argument(1);
7425   Node* length         = argument(2);
7426   Node* initialValue   = argument(3);
7427   Node* basic_type     = argument(4);
7428 
7429   if (basic_type == top()) {
7430     return false; // failed input validation
7431   }
7432 
7433   const TypeInt* basic_type_t = _gvn.type(basic_type)->is_int();
7434   if (!basic_type_t->is_con()) {
7435     return false; // Only intrinsify if mode argument is constant
7436   }
7437 
7438   array = must_be_not_null(array, true);
7439 
7440   BasicType bt = (BasicType)basic_type_t->get_con();
7441 
7442   // Resolve address of first element
7443   Node* array_start = array_element_address(array, offset, bt);
7444 
7445   set_result(_gvn.transform(new VectorizedHashCodeNode(control(), memory(TypeAryPtr::get_array_body_type(bt)),
7446     array_start, length, initialValue, basic_type)));
7447   clear_upper_avx();
7448 
7449   return true;
7450 }
7451 
7452 /**
7453  * Calculate CRC32 for byte.
7454  * int java.util.zip.CRC32.update(int crc, int b)
7455  */
7456 bool LibraryCallKit::inline_updateCRC32() {
7457   assert(UseCRC32Intrinsics, "need AVX and CLMUL instructions support");
7458   assert(callee()->signature()->size() == 2, "update has 2 parameters");
7459   // no receiver since it is static method
7460   Node* crc  = argument(0); // type: int
7461   Node* b    = argument(1); // type: int
7462 
7463   /*
7464    *    int c = ~ crc;
7465    *    b = timesXtoThe32[(b ^ c) & 0xFF];
7466    *    b = b ^ (c >>> 8);
7467    *    crc = ~b;
7468    */
7469 
7470   Node* M1 = intcon(-1);
7471   crc = _gvn.transform(new XorINode(crc, M1));
7472   Node* result = _gvn.transform(new XorINode(crc, b));
7473   result = _gvn.transform(new AndINode(result, intcon(0xFF)));
7474 
7475   Node* base = makecon(TypeRawPtr::make(StubRoutines::crc_table_addr()));
7476   Node* offset = _gvn.transform(new LShiftINode(result, intcon(0x2)));
7477   Node* adr = basic_plus_adr(top(), base, ConvI2X(offset));
7478   result = make_load(control(), adr, TypeInt::INT, T_INT, MemNode::unordered);
7479 
7480   crc = _gvn.transform(new URShiftINode(crc, intcon(8)));
7481   result = _gvn.transform(new XorINode(crc, result));
7482   result = _gvn.transform(new XorINode(result, M1));
7483   set_result(result);
7484   return true;
7485 }
7486 
7487 /**
7488  * Calculate CRC32 for byte[] array.
7489  * int java.util.zip.CRC32.updateBytes(int crc, byte[] buf, int off, int len)
7490  */
7491 bool LibraryCallKit::inline_updateBytesCRC32() {
7492   assert(UseCRC32Intrinsics, "need AVX and CLMUL instructions support");
7493   assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
7494   // no receiver since it is static method
7495   Node* crc     = argument(0); // type: int
7496   Node* src     = argument(1); // type: oop
7497   Node* offset  = argument(2); // type: int
7498   Node* length  = argument(3); // type: int
7499 
7500   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7501   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
7502     // failed array check
7503     return false;
7504   }
7505 
7506   // Figure out the size and type of the elements we will be copying.
7507   BasicType src_elem = src_type->elem()->array_element_basic_type();
7508   if (src_elem != T_BYTE) {
7509     return false;
7510   }
7511 
7512   // 'src_start' points to src array + scaled offset
7513   src = must_be_not_null(src, true);
7514   Node* src_start = array_element_address(src, offset, src_elem);
7515 
7516   // We assume that range check is done by caller.
7517   // TODO: generate range check (offset+length < src.length) in debug VM.
7518 
7519   // Call the stub.
7520   address stubAddr = StubRoutines::updateBytesCRC32();
7521   const char *stubName = "updateBytesCRC32";
7522 
7523   Node* call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::updateBytesCRC32_Type(),
7524                                  stubAddr, stubName, TypePtr::BOTTOM,
7525                                  crc, src_start, length);
7526   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7527   set_result(result);
7528   return true;
7529 }
7530 
7531 /**
7532  * Calculate CRC32 for ByteBuffer.
7533  * int java.util.zip.CRC32.updateByteBuffer(int crc, long buf, int off, int len)
7534  */
7535 bool LibraryCallKit::inline_updateByteBufferCRC32() {
7536   assert(UseCRC32Intrinsics, "need AVX and CLMUL instructions support");
7537   assert(callee()->signature()->size() == 5, "updateByteBuffer has 4 parameters and one is long");
7538   // no receiver since it is static method
7539   Node* crc     = argument(0); // type: int
7540   Node* src     = argument(1); // type: long
7541   Node* offset  = argument(3); // type: int
7542   Node* length  = argument(4); // type: int
7543 
7544   src = ConvL2X(src);  // adjust Java long to machine word
7545   Node* base = _gvn.transform(new CastX2PNode(src));
7546   offset = ConvI2X(offset);
7547 
7548   // 'src_start' points to src array + scaled offset
7549   Node* src_start = basic_plus_adr(top(), base, offset);
7550 
7551   // Call the stub.
7552   address stubAddr = StubRoutines::updateBytesCRC32();
7553   const char *stubName = "updateBytesCRC32";
7554 
7555   Node* call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::updateBytesCRC32_Type(),
7556                                  stubAddr, stubName, TypePtr::BOTTOM,
7557                                  crc, src_start, length);
7558   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7559   set_result(result);
7560   return true;
7561 }
7562 
7563 //------------------------------get_table_from_crc32c_class-----------------------
7564 Node * LibraryCallKit::get_table_from_crc32c_class(ciInstanceKlass *crc32c_class) {
7565   Node* table = load_field_from_object(nullptr, "byteTable", "[I", /*decorators*/ IN_HEAP, /*is_static*/ true, crc32c_class);
7566   assert (table != nullptr, "wrong version of java.util.zip.CRC32C");
7567 
7568   return table;
7569 }
7570 
7571 //------------------------------inline_updateBytesCRC32C-----------------------
7572 //
7573 // Calculate CRC32C for byte[] array.
7574 // int java.util.zip.CRC32C.updateBytes(int crc, byte[] buf, int off, int end)
7575 //
7576 bool LibraryCallKit::inline_updateBytesCRC32C() {
7577   assert(UseCRC32CIntrinsics, "need CRC32C instruction support");
7578   assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
7579   assert(callee()->holder()->is_loaded(), "CRC32C class must be loaded");
7580   // no receiver since it is a static method
7581   Node* crc     = argument(0); // type: int
7582   Node* src     = argument(1); // type: oop
7583   Node* offset  = argument(2); // type: int
7584   Node* end     = argument(3); // type: int
7585 
7586   Node* length = _gvn.transform(new SubINode(end, offset));
7587 
7588   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7589   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
7590     // failed array check
7591     return false;
7592   }
7593 
7594   // Figure out the size and type of the elements we will be copying.
7595   BasicType src_elem = src_type->elem()->array_element_basic_type();
7596   if (src_elem != T_BYTE) {
7597     return false;
7598   }
7599 
7600   // 'src_start' points to src array + scaled offset
7601   src = must_be_not_null(src, true);
7602   Node* src_start = array_element_address(src, offset, src_elem);
7603 
7604   // static final int[] byteTable in class CRC32C
7605   Node* table = get_table_from_crc32c_class(callee()->holder());
7606   table = must_be_not_null(table, true);
7607   Node* table_start = array_element_address(table, intcon(0), T_INT);
7608 
7609   // We assume that range check is done by caller.
7610   // TODO: generate range check (offset+length < src.length) in debug VM.
7611 
7612   // Call the stub.
7613   address stubAddr = StubRoutines::updateBytesCRC32C();
7614   const char *stubName = "updateBytesCRC32C";
7615 
7616   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesCRC32C_Type(),
7617                                  stubAddr, stubName, TypePtr::BOTTOM,
7618                                  crc, src_start, length, table_start);
7619   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7620   set_result(result);
7621   return true;
7622 }
7623 
7624 //------------------------------inline_updateDirectByteBufferCRC32C-----------------------
7625 //
7626 // Calculate CRC32C for DirectByteBuffer.
7627 // int java.util.zip.CRC32C.updateDirectByteBuffer(int crc, long buf, int off, int end)
7628 //
7629 bool LibraryCallKit::inline_updateDirectByteBufferCRC32C() {
7630   assert(UseCRC32CIntrinsics, "need CRC32C instruction support");
7631   assert(callee()->signature()->size() == 5, "updateDirectByteBuffer has 4 parameters and one is long");
7632   assert(callee()->holder()->is_loaded(), "CRC32C class must be loaded");
7633   // no receiver since it is a static method
7634   Node* crc     = argument(0); // type: int
7635   Node* src     = argument(1); // type: long
7636   Node* offset  = argument(3); // type: int
7637   Node* end     = argument(4); // type: int
7638 
7639   Node* length = _gvn.transform(new SubINode(end, offset));
7640 
7641   src = ConvL2X(src);  // adjust Java long to machine word
7642   Node* base = _gvn.transform(new CastX2PNode(src));
7643   offset = ConvI2X(offset);
7644 
7645   // 'src_start' points to src array + scaled offset
7646   Node* src_start = basic_plus_adr(top(), base, offset);
7647 
7648   // static final int[] byteTable in class CRC32C
7649   Node* table = get_table_from_crc32c_class(callee()->holder());
7650   table = must_be_not_null(table, true);
7651   Node* table_start = array_element_address(table, intcon(0), T_INT);
7652 
7653   // Call the stub.
7654   address stubAddr = StubRoutines::updateBytesCRC32C();
7655   const char *stubName = "updateBytesCRC32C";
7656 
7657   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesCRC32C_Type(),
7658                                  stubAddr, stubName, TypePtr::BOTTOM,
7659                                  crc, src_start, length, table_start);
7660   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7661   set_result(result);
7662   return true;
7663 }
7664 
7665 //------------------------------inline_updateBytesAdler32----------------------
7666 //
7667 // Calculate Adler32 checksum for byte[] array.
7668 // int java.util.zip.Adler32.updateBytes(int crc, byte[] buf, int off, int len)
7669 //
7670 bool LibraryCallKit::inline_updateBytesAdler32() {
7671   assert(UseAdler32Intrinsics, "Adler32 Intrinsic support need"); // check if we actually need to check this flag or check a different one
7672   assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
7673   assert(callee()->holder()->is_loaded(), "Adler32 class must be loaded");
7674   // no receiver since it is static method
7675   Node* crc     = argument(0); // type: int
7676   Node* src     = argument(1); // type: oop
7677   Node* offset  = argument(2); // type: int
7678   Node* length  = argument(3); // type: int
7679 
7680   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7681   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
7682     // failed array check
7683     return false;
7684   }
7685 
7686   // Figure out the size and type of the elements we will be copying.
7687   BasicType src_elem = src_type->elem()->array_element_basic_type();
7688   if (src_elem != T_BYTE) {
7689     return false;
7690   }
7691 
7692   // 'src_start' points to src array + scaled offset
7693   Node* src_start = array_element_address(src, offset, src_elem);
7694 
7695   // We assume that range check is done by caller.
7696   // TODO: generate range check (offset+length < src.length) in debug VM.
7697 
7698   // Call the stub.
7699   address stubAddr = StubRoutines::updateBytesAdler32();
7700   const char *stubName = "updateBytesAdler32";
7701 
7702   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesAdler32_Type(),
7703                                  stubAddr, stubName, TypePtr::BOTTOM,
7704                                  crc, src_start, length);
7705   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7706   set_result(result);
7707   return true;
7708 }
7709 
7710 //------------------------------inline_updateByteBufferAdler32---------------
7711 //
7712 // Calculate Adler32 checksum for DirectByteBuffer.
7713 // int java.util.zip.Adler32.updateByteBuffer(int crc, long buf, int off, int len)
7714 //
7715 bool LibraryCallKit::inline_updateByteBufferAdler32() {
7716   assert(UseAdler32Intrinsics, "Adler32 Intrinsic support need"); // check if we actually need to check this flag or check a different one
7717   assert(callee()->signature()->size() == 5, "updateByteBuffer has 4 parameters and one is long");
7718   assert(callee()->holder()->is_loaded(), "Adler32 class must be loaded");
7719   // no receiver since it is static method
7720   Node* crc     = argument(0); // type: int
7721   Node* src     = argument(1); // type: long
7722   Node* offset  = argument(3); // type: int
7723   Node* length  = argument(4); // type: int
7724 
7725   src = ConvL2X(src);  // adjust Java long to machine word
7726   Node* base = _gvn.transform(new CastX2PNode(src));
7727   offset = ConvI2X(offset);
7728 
7729   // 'src_start' points to src array + scaled offset
7730   Node* src_start = basic_plus_adr(top(), base, offset);
7731 
7732   // Call the stub.
7733   address stubAddr = StubRoutines::updateBytesAdler32();
7734   const char *stubName = "updateBytesAdler32";
7735 
7736   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesAdler32_Type(),
7737                                  stubAddr, stubName, TypePtr::BOTTOM,
7738                                  crc, src_start, length);
7739 
7740   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7741   set_result(result);
7742   return true;
7743 }
7744 
7745 //----------------------------inline_reference_get0----------------------------
7746 // public T java.lang.ref.Reference.get();
7747 bool LibraryCallKit::inline_reference_get0() {
7748   const int referent_offset = java_lang_ref_Reference::referent_offset();
7749 
7750   // Get the argument:
7751   Node* reference_obj = null_check_receiver();
7752   if (stopped()) return true;
7753 
7754   DecoratorSet decorators = IN_HEAP | ON_WEAK_OOP_REF;
7755   Node* result = load_field_from_object(reference_obj, "referent", "Ljava/lang/Object;",
7756                                         decorators, /*is_static*/ false, nullptr);
7757   if (result == nullptr) return false;
7758 
7759   // Add memory barrier to prevent commoning reads from this field
7760   // across safepoint since GC can change its value.
7761   insert_mem_bar(Op_MemBarCPUOrder);
7762 
7763   set_result(result);
7764   return true;
7765 }
7766 
7767 //----------------------------inline_reference_refersTo0----------------------------
7768 // bool java.lang.ref.Reference.refersTo0();
7769 // bool java.lang.ref.PhantomReference.refersTo0();
7770 bool LibraryCallKit::inline_reference_refersTo0(bool is_phantom) {
7771   // Get arguments:
7772   Node* reference_obj = null_check_receiver();
7773   Node* other_obj = argument(1);
7774   if (stopped()) return true;
7775 
7776   DecoratorSet decorators = IN_HEAP | AS_NO_KEEPALIVE;
7777   decorators |= (is_phantom ? ON_PHANTOM_OOP_REF : ON_WEAK_OOP_REF);
7778   Node* referent = load_field_from_object(reference_obj, "referent", "Ljava/lang/Object;",
7779                                           decorators, /*is_static*/ false, nullptr);
7780   if (referent == nullptr) return false;
7781 
7782   // Add memory barrier to prevent commoning reads from this field
7783   // across safepoint since GC can change its value.
7784   insert_mem_bar(Op_MemBarCPUOrder);
7785 
7786   Node* cmp = _gvn.transform(new CmpPNode(referent, other_obj));
7787   Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
7788   IfNode* if_node = create_and_map_if(control(), bol, PROB_FAIR, COUNT_UNKNOWN);
7789 
7790   RegionNode* region = new RegionNode(3);
7791   PhiNode* phi = new PhiNode(region, TypeInt::BOOL);
7792 
7793   Node* if_true = _gvn.transform(new IfTrueNode(if_node));
7794   region->init_req(1, if_true);
7795   phi->init_req(1, intcon(1));
7796 
7797   Node* if_false = _gvn.transform(new IfFalseNode(if_node));
7798   region->init_req(2, if_false);
7799   phi->init_req(2, intcon(0));
7800 
7801   set_control(_gvn.transform(region));
7802   record_for_igvn(region);
7803   set_result(_gvn.transform(phi));
7804   return true;
7805 }
7806 
7807 //----------------------------inline_reference_clear0----------------------------
7808 // void java.lang.ref.Reference.clear0();
7809 // void java.lang.ref.PhantomReference.clear0();
7810 bool LibraryCallKit::inline_reference_clear0(bool is_phantom) {
7811   // This matches the implementation in JVM_ReferenceClear, see the comments there.
7812 
7813   // Get arguments
7814   Node* reference_obj = null_check_receiver();
7815   if (stopped()) return true;
7816 
7817   // Common access parameters
7818   DecoratorSet decorators = IN_HEAP | AS_NO_KEEPALIVE;
7819   decorators |= (is_phantom ? ON_PHANTOM_OOP_REF : ON_WEAK_OOP_REF);
7820   Node* referent_field_addr = basic_plus_adr(reference_obj, java_lang_ref_Reference::referent_offset());
7821   const TypePtr* referent_field_addr_type = _gvn.type(referent_field_addr)->isa_ptr();
7822   const Type* val_type = TypeOopPtr::make_from_klass(env()->Object_klass());
7823 
7824   Node* referent = access_load_at(reference_obj,
7825                                   referent_field_addr,
7826                                   referent_field_addr_type,
7827                                   val_type,
7828                                   T_OBJECT,
7829                                   decorators);
7830 
7831   IdealKit ideal(this);
7832 #define __ ideal.
7833   __ if_then(referent, BoolTest::ne, null());
7834     sync_kit(ideal);
7835     access_store_at(reference_obj,
7836                     referent_field_addr,
7837                     referent_field_addr_type,
7838                     null(),
7839                     val_type,
7840                     T_OBJECT,
7841                     decorators);
7842     __ sync_kit(this);
7843   __ end_if();
7844   final_sync(ideal);
7845 #undef __
7846 
7847   return true;
7848 }
7849 
7850 Node* LibraryCallKit::load_field_from_object(Node* fromObj, const char* fieldName, const char* fieldTypeString,
7851                                              DecoratorSet decorators, bool is_static,
7852                                              ciInstanceKlass* fromKls) {
7853   if (fromKls == nullptr) {
7854     const TypeInstPtr* tinst = _gvn.type(fromObj)->isa_instptr();
7855     assert(tinst != nullptr, "obj is null");
7856     assert(tinst->is_loaded(), "obj is not loaded");
7857     fromKls = tinst->instance_klass();
7858   } else {
7859     assert(is_static, "only for static field access");
7860   }
7861   ciField* field = fromKls->get_field_by_name(ciSymbol::make(fieldName),
7862                                               ciSymbol::make(fieldTypeString),
7863                                               is_static);
7864 
7865   assert(field != nullptr, "undefined field %s %s %s", fieldTypeString, fromKls->name()->as_utf8(), fieldName);
7866   if (field == nullptr) return (Node *) nullptr;
7867 
7868   if (is_static) {
7869     const TypeInstPtr* tip = TypeInstPtr::make(fromKls->java_mirror());
7870     fromObj = makecon(tip);
7871   }
7872 
7873   // Next code  copied from Parse::do_get_xxx():
7874 
7875   // Compute address and memory type.
7876   int offset  = field->offset_in_bytes();
7877   bool is_vol = field->is_volatile();
7878   ciType* field_klass = field->type();
7879   assert(field_klass->is_loaded(), "should be loaded");
7880   const TypePtr* adr_type = C->alias_type(field)->adr_type();
7881   Node *adr = basic_plus_adr(fromObj, fromObj, offset);
7882   assert(C->get_alias_index(adr_type) == C->get_alias_index(_gvn.type(adr)->isa_ptr()),
7883     "slice of address and input slice don't match");
7884   BasicType bt = field->layout_type();
7885 
7886   // Build the resultant type of the load
7887   const Type *type;
7888   if (bt == T_OBJECT) {
7889     type = TypeOopPtr::make_from_klass(field_klass->as_klass());
7890   } else {
7891     type = Type::get_const_basic_type(bt);
7892   }
7893 
7894   if (is_vol) {
7895     decorators |= MO_SEQ_CST;
7896   }
7897 
7898   return access_load_at(fromObj, adr, adr_type, type, bt, decorators);
7899 }
7900 
7901 Node * LibraryCallKit::field_address_from_object(Node * fromObj, const char * fieldName, const char * fieldTypeString,
7902                                                  bool is_exact /* true */, bool is_static /* false */,
7903                                                  ciInstanceKlass * fromKls /* nullptr */) {
7904   if (fromKls == nullptr) {
7905     const TypeInstPtr* tinst = _gvn.type(fromObj)->isa_instptr();
7906     assert(tinst != nullptr, "obj is null");
7907     assert(tinst->is_loaded(), "obj is not loaded");
7908     assert(!is_exact || tinst->klass_is_exact(), "klass not exact");
7909     fromKls = tinst->instance_klass();
7910   }
7911   else {
7912     assert(is_static, "only for static field access");
7913   }
7914   ciField* field = fromKls->get_field_by_name(ciSymbol::make(fieldName),
7915     ciSymbol::make(fieldTypeString),
7916     is_static);
7917 
7918   assert(field != nullptr, "undefined field");
7919   assert(!field->is_volatile(), "not defined for volatile fields");
7920 
7921   if (is_static) {
7922     const TypeInstPtr* tip = TypeInstPtr::make(fromKls->java_mirror());
7923     fromObj = makecon(tip);
7924   }
7925 
7926   // Next code  copied from Parse::do_get_xxx():
7927 
7928   // Compute address and memory type.
7929   int offset = field->offset_in_bytes();
7930   Node *adr = basic_plus_adr(fromObj, fromObj, offset);
7931 
7932   return adr;
7933 }
7934 
7935 //------------------------------inline_aescrypt_Block-----------------------
7936 bool LibraryCallKit::inline_aescrypt_Block(vmIntrinsics::ID id) {
7937   address stubAddr = nullptr;
7938   const char *stubName;
7939   assert(UseAES, "need AES instruction support");
7940 
7941   switch(id) {
7942   case vmIntrinsics::_aescrypt_encryptBlock:
7943     stubAddr = StubRoutines::aescrypt_encryptBlock();
7944     stubName = "aescrypt_encryptBlock";
7945     break;
7946   case vmIntrinsics::_aescrypt_decryptBlock:
7947     stubAddr = StubRoutines::aescrypt_decryptBlock();
7948     stubName = "aescrypt_decryptBlock";
7949     break;
7950   default:
7951     break;
7952   }
7953   if (stubAddr == nullptr) return false;
7954 
7955   Node* aescrypt_object = argument(0);
7956   Node* src             = argument(1);
7957   Node* src_offset      = argument(2);
7958   Node* dest            = argument(3);
7959   Node* dest_offset     = argument(4);
7960 
7961   src = must_be_not_null(src, true);
7962   dest = must_be_not_null(dest, true);
7963 
7964   // (1) src and dest are arrays.
7965   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7966   const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
7967   assert( src_type != nullptr &&  src_type->elem() != Type::BOTTOM &&
7968          dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
7969 
7970   // for the quick and dirty code we will skip all the checks.
7971   // we are just trying to get the call to be generated.
7972   Node* src_start  = src;
7973   Node* dest_start = dest;
7974   if (src_offset != nullptr || dest_offset != nullptr) {
7975     assert(src_offset != nullptr && dest_offset != nullptr, "");
7976     src_start  = array_element_address(src,  src_offset,  T_BYTE);
7977     dest_start = array_element_address(dest, dest_offset, T_BYTE);
7978   }
7979 
7980   // now need to get the start of its expanded key array
7981   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
7982   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object);
7983   if (k_start == nullptr) return false;
7984 
7985   // Call the stub.
7986   make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::aescrypt_block_Type(),
7987                     stubAddr, stubName, TypePtr::BOTTOM,
7988                     src_start, dest_start, k_start);
7989 
7990   return true;
7991 }
7992 
7993 //------------------------------inline_cipherBlockChaining_AESCrypt-----------------------
7994 bool LibraryCallKit::inline_cipherBlockChaining_AESCrypt(vmIntrinsics::ID id) {
7995   address stubAddr = nullptr;
7996   const char *stubName = nullptr;
7997 
7998   assert(UseAES, "need AES instruction support");
7999 
8000   switch(id) {
8001   case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
8002     stubAddr = StubRoutines::cipherBlockChaining_encryptAESCrypt();
8003     stubName = "cipherBlockChaining_encryptAESCrypt";
8004     break;
8005   case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
8006     stubAddr = StubRoutines::cipherBlockChaining_decryptAESCrypt();
8007     stubName = "cipherBlockChaining_decryptAESCrypt";
8008     break;
8009   default:
8010     break;
8011   }
8012   if (stubAddr == nullptr) return false;
8013 
8014   Node* cipherBlockChaining_object = argument(0);
8015   Node* src                        = argument(1);
8016   Node* src_offset                 = argument(2);
8017   Node* len                        = argument(3);
8018   Node* dest                       = argument(4);
8019   Node* dest_offset                = argument(5);
8020 
8021   src = must_be_not_null(src, false);
8022   dest = must_be_not_null(dest, false);
8023 
8024   // (1) src and dest are arrays.
8025   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
8026   const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
8027   assert( src_type != nullptr &&  src_type->elem() != Type::BOTTOM &&
8028          dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
8029 
8030   // checks are the responsibility of the caller
8031   Node* src_start  = src;
8032   Node* dest_start = dest;
8033   if (src_offset != nullptr || dest_offset != nullptr) {
8034     assert(src_offset != nullptr && dest_offset != nullptr, "");
8035     src_start  = array_element_address(src,  src_offset,  T_BYTE);
8036     dest_start = array_element_address(dest, dest_offset, T_BYTE);
8037   }
8038 
8039   // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
8040   // (because of the predicated logic executed earlier).
8041   // so we cast it here safely.
8042   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
8043 
8044   Node* embeddedCipherObj = load_field_from_object(cipherBlockChaining_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8045   if (embeddedCipherObj == nullptr) return false;
8046 
8047   // cast it to what we know it will be at runtime
8048   const TypeInstPtr* tinst = _gvn.type(cipherBlockChaining_object)->isa_instptr();
8049   assert(tinst != nullptr, "CBC obj is null");
8050   assert(tinst->is_loaded(), "CBC obj is not loaded");
8051   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8052   assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
8053 
8054   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8055   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
8056   const TypeOopPtr* xtype = aklass->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
8057   Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
8058   aescrypt_object = _gvn.transform(aescrypt_object);
8059 
8060   // we need to get the start of the aescrypt_object's expanded key array
8061   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object);
8062   if (k_start == nullptr) return false;
8063 
8064   // similarly, get the start address of the r vector
8065   Node* objRvec = load_field_from_object(cipherBlockChaining_object, "r", "[B");
8066   if (objRvec == nullptr) return false;
8067   Node* r_start = array_element_address(objRvec, intcon(0), T_BYTE);
8068 
8069   // Call the stub, passing src_start, dest_start, k_start, r_start and src_len
8070   Node* cbcCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
8071                                      OptoRuntime::cipherBlockChaining_aescrypt_Type(),
8072                                      stubAddr, stubName, TypePtr::BOTTOM,
8073                                      src_start, dest_start, k_start, r_start, len);
8074 
8075   // return cipher length (int)
8076   Node* retvalue = _gvn.transform(new ProjNode(cbcCrypt, TypeFunc::Parms));
8077   set_result(retvalue);
8078   return true;
8079 }
8080 
8081 //------------------------------inline_electronicCodeBook_AESCrypt-----------------------
8082 bool LibraryCallKit::inline_electronicCodeBook_AESCrypt(vmIntrinsics::ID id) {
8083   address stubAddr = nullptr;
8084   const char *stubName = nullptr;
8085 
8086   assert(UseAES, "need AES instruction support");
8087 
8088   switch (id) {
8089   case vmIntrinsics::_electronicCodeBook_encryptAESCrypt:
8090     stubAddr = StubRoutines::electronicCodeBook_encryptAESCrypt();
8091     stubName = "electronicCodeBook_encryptAESCrypt";
8092     break;
8093   case vmIntrinsics::_electronicCodeBook_decryptAESCrypt:
8094     stubAddr = StubRoutines::electronicCodeBook_decryptAESCrypt();
8095     stubName = "electronicCodeBook_decryptAESCrypt";
8096     break;
8097   default:
8098     break;
8099   }
8100 
8101   if (stubAddr == nullptr) return false;
8102 
8103   Node* electronicCodeBook_object = argument(0);
8104   Node* src                       = argument(1);
8105   Node* src_offset                = argument(2);
8106   Node* len                       = argument(3);
8107   Node* dest                      = argument(4);
8108   Node* dest_offset               = argument(5);
8109 
8110   // (1) src and dest are arrays.
8111   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
8112   const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
8113   assert( src_type != nullptr &&  src_type->elem() != Type::BOTTOM &&
8114          dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
8115 
8116   // checks are the responsibility of the caller
8117   Node* src_start = src;
8118   Node* dest_start = dest;
8119   if (src_offset != nullptr || dest_offset != nullptr) {
8120     assert(src_offset != nullptr && dest_offset != nullptr, "");
8121     src_start = array_element_address(src, src_offset, T_BYTE);
8122     dest_start = array_element_address(dest, dest_offset, T_BYTE);
8123   }
8124 
8125   // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
8126   // (because of the predicated logic executed earlier).
8127   // so we cast it here safely.
8128   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
8129 
8130   Node* embeddedCipherObj = load_field_from_object(electronicCodeBook_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8131   if (embeddedCipherObj == nullptr) return false;
8132 
8133   // cast it to what we know it will be at runtime
8134   const TypeInstPtr* tinst = _gvn.type(electronicCodeBook_object)->isa_instptr();
8135   assert(tinst != nullptr, "ECB obj is null");
8136   assert(tinst->is_loaded(), "ECB obj is not loaded");
8137   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8138   assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
8139 
8140   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8141   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
8142   const TypeOopPtr* xtype = aklass->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
8143   Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
8144   aescrypt_object = _gvn.transform(aescrypt_object);
8145 
8146   // we need to get the start of the aescrypt_object's expanded key array
8147   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object);
8148   if (k_start == nullptr) return false;
8149 
8150   // Call the stub, passing src_start, dest_start, k_start, r_start and src_len
8151   Node* ecbCrypt = make_runtime_call(RC_LEAF | RC_NO_FP,
8152                                      OptoRuntime::electronicCodeBook_aescrypt_Type(),
8153                                      stubAddr, stubName, TypePtr::BOTTOM,
8154                                      src_start, dest_start, k_start, len);
8155 
8156   // return cipher length (int)
8157   Node* retvalue = _gvn.transform(new ProjNode(ecbCrypt, TypeFunc::Parms));
8158   set_result(retvalue);
8159   return true;
8160 }
8161 
8162 //------------------------------inline_counterMode_AESCrypt-----------------------
8163 bool LibraryCallKit::inline_counterMode_AESCrypt(vmIntrinsics::ID id) {
8164   assert(UseAES, "need AES instruction support");
8165   if (!UseAESCTRIntrinsics) return false;
8166 
8167   address stubAddr = nullptr;
8168   const char *stubName = nullptr;
8169   if (id == vmIntrinsics::_counterMode_AESCrypt) {
8170     stubAddr = StubRoutines::counterMode_AESCrypt();
8171     stubName = "counterMode_AESCrypt";
8172   }
8173   if (stubAddr == nullptr) return false;
8174 
8175   Node* counterMode_object = argument(0);
8176   Node* src = argument(1);
8177   Node* src_offset = argument(2);
8178   Node* len = argument(3);
8179   Node* dest = argument(4);
8180   Node* dest_offset = argument(5);
8181 
8182   // (1) src and dest are arrays.
8183   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
8184   const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
8185   assert( src_type != nullptr &&  src_type->elem() != Type::BOTTOM &&
8186          dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
8187 
8188   // checks are the responsibility of the caller
8189   Node* src_start = src;
8190   Node* dest_start = dest;
8191   if (src_offset != nullptr || dest_offset != nullptr) {
8192     assert(src_offset != nullptr && dest_offset != nullptr, "");
8193     src_start = array_element_address(src, src_offset, T_BYTE);
8194     dest_start = array_element_address(dest, dest_offset, T_BYTE);
8195   }
8196 
8197   // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
8198   // (because of the predicated logic executed earlier).
8199   // so we cast it here safely.
8200   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
8201   Node* embeddedCipherObj = load_field_from_object(counterMode_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8202   if (embeddedCipherObj == nullptr) return false;
8203   // cast it to what we know it will be at runtime
8204   const TypeInstPtr* tinst = _gvn.type(counterMode_object)->isa_instptr();
8205   assert(tinst != nullptr, "CTR obj is null");
8206   assert(tinst->is_loaded(), "CTR obj is not loaded");
8207   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8208   assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
8209   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8210   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
8211   const TypeOopPtr* xtype = aklass->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
8212   Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
8213   aescrypt_object = _gvn.transform(aescrypt_object);
8214   // we need to get the start of the aescrypt_object's expanded key array
8215   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object);
8216   if (k_start == nullptr) return false;
8217   // similarly, get the start address of the r vector
8218   Node* obj_counter = load_field_from_object(counterMode_object, "counter", "[B");
8219   if (obj_counter == nullptr) return false;
8220   Node* cnt_start = array_element_address(obj_counter, intcon(0), T_BYTE);
8221 
8222   Node* saved_encCounter = load_field_from_object(counterMode_object, "encryptedCounter", "[B");
8223   if (saved_encCounter == nullptr) return false;
8224   Node* saved_encCounter_start = array_element_address(saved_encCounter, intcon(0), T_BYTE);
8225   Node* used = field_address_from_object(counterMode_object, "used", "I", /*is_exact*/ false);
8226 
8227   // Call the stub, passing src_start, dest_start, k_start, r_start and src_len
8228   Node* ctrCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
8229                                      OptoRuntime::counterMode_aescrypt_Type(),
8230                                      stubAddr, stubName, TypePtr::BOTTOM,
8231                                      src_start, dest_start, k_start, cnt_start, len, saved_encCounter_start, used);
8232 
8233   // return cipher length (int)
8234   Node* retvalue = _gvn.transform(new ProjNode(ctrCrypt, TypeFunc::Parms));
8235   set_result(retvalue);
8236   return true;
8237 }
8238 
8239 //------------------------------get_key_start_from_aescrypt_object-----------------------
8240 Node * LibraryCallKit::get_key_start_from_aescrypt_object(Node *aescrypt_object) {
8241 #if defined(PPC64) || defined(S390) || defined(RISCV64)
8242   // MixColumns for decryption can be reduced by preprocessing MixColumns with round keys.
8243   // Intel's extension is based on this optimization and AESCrypt generates round keys by preprocessing MixColumns.
8244   // However, ppc64 vncipher processes MixColumns and requires the same round keys with encryption.
8245   // The ppc64 and riscv64 stubs of encryption and decryption use the same round keys (sessionK[0]).
8246   Node* objSessionK = load_field_from_object(aescrypt_object, "sessionK", "[[I");
8247   assert (objSessionK != nullptr, "wrong version of com.sun.crypto.provider.AES_Crypt");
8248   if (objSessionK == nullptr) {
8249     return (Node *) nullptr;
8250   }
8251   Node* objAESCryptKey = load_array_element(objSessionK, intcon(0), TypeAryPtr::OOPS, /* set_ctrl */ true);
8252 #else
8253   Node* objAESCryptKey = load_field_from_object(aescrypt_object, "K", "[I");
8254 #endif // PPC64
8255   assert (objAESCryptKey != nullptr, "wrong version of com.sun.crypto.provider.AES_Crypt");
8256   if (objAESCryptKey == nullptr) return (Node *) nullptr;
8257 
8258   // now have the array, need to get the start address of the K array
8259   Node* k_start = array_element_address(objAESCryptKey, intcon(0), T_INT);
8260   return k_start;
8261 }
8262 
8263 //----------------------------inline_cipherBlockChaining_AESCrypt_predicate----------------------------
8264 // Return node representing slow path of predicate check.
8265 // the pseudo code we want to emulate with this predicate is:
8266 // for encryption:
8267 //    if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
8268 // for decryption:
8269 //    if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
8270 //    note cipher==plain is more conservative than the original java code but that's OK
8271 //
8272 Node* LibraryCallKit::inline_cipherBlockChaining_AESCrypt_predicate(bool decrypting) {
8273   // The receiver was checked for null already.
8274   Node* objCBC = argument(0);
8275 
8276   Node* src = argument(1);
8277   Node* dest = argument(4);
8278 
8279   // Load embeddedCipher field of CipherBlockChaining object.
8280   Node* embeddedCipherObj = load_field_from_object(objCBC, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8281 
8282   // get AESCrypt klass for instanceOf check
8283   // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
8284   // will have same classloader as CipherBlockChaining object
8285   const TypeInstPtr* tinst = _gvn.type(objCBC)->isa_instptr();
8286   assert(tinst != nullptr, "CBCobj is null");
8287   assert(tinst->is_loaded(), "CBCobj is not loaded");
8288 
8289   // we want to do an instanceof comparison against the AESCrypt class
8290   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8291   if (!klass_AESCrypt->is_loaded()) {
8292     // if AESCrypt is not even loaded, we never take the intrinsic fast path
8293     Node* ctrl = control();
8294     set_control(top()); // no regular fast path
8295     return ctrl;
8296   }
8297 
8298   src = must_be_not_null(src, true);
8299   dest = must_be_not_null(dest, true);
8300 
8301   // Resolve oops to stable for CmpP below.
8302   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8303 
8304   Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
8305   Node* cmp_instof  = _gvn.transform(new CmpINode(instof, intcon(1)));
8306   Node* bool_instof  = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
8307 
8308   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
8309 
8310   // for encryption, we are done
8311   if (!decrypting)
8312     return instof_false;  // even if it is null
8313 
8314   // for decryption, we need to add a further check to avoid
8315   // taking the intrinsic path when cipher and plain are the same
8316   // see the original java code for why.
8317   RegionNode* region = new RegionNode(3);
8318   region->init_req(1, instof_false);
8319 
8320   Node* cmp_src_dest = _gvn.transform(new CmpPNode(src, dest));
8321   Node* bool_src_dest = _gvn.transform(new BoolNode(cmp_src_dest, BoolTest::eq));
8322   Node* src_dest_conjoint = generate_guard(bool_src_dest, nullptr, PROB_MIN);
8323   region->init_req(2, src_dest_conjoint);
8324 
8325   record_for_igvn(region);
8326   return _gvn.transform(region);
8327 }
8328 
8329 //----------------------------inline_electronicCodeBook_AESCrypt_predicate----------------------------
8330 // Return node representing slow path of predicate check.
8331 // the pseudo code we want to emulate with this predicate is:
8332 // for encryption:
8333 //    if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
8334 // for decryption:
8335 //    if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
8336 //    note cipher==plain is more conservative than the original java code but that's OK
8337 //
8338 Node* LibraryCallKit::inline_electronicCodeBook_AESCrypt_predicate(bool decrypting) {
8339   // The receiver was checked for null already.
8340   Node* objECB = argument(0);
8341 
8342   // Load embeddedCipher field of ElectronicCodeBook object.
8343   Node* embeddedCipherObj = load_field_from_object(objECB, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8344 
8345   // get AESCrypt klass for instanceOf check
8346   // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
8347   // will have same classloader as ElectronicCodeBook object
8348   const TypeInstPtr* tinst = _gvn.type(objECB)->isa_instptr();
8349   assert(tinst != nullptr, "ECBobj is null");
8350   assert(tinst->is_loaded(), "ECBobj is not loaded");
8351 
8352   // we want to do an instanceof comparison against the AESCrypt class
8353   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8354   if (!klass_AESCrypt->is_loaded()) {
8355     // if AESCrypt is not even loaded, we never take the intrinsic fast path
8356     Node* ctrl = control();
8357     set_control(top()); // no regular fast path
8358     return ctrl;
8359   }
8360   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8361 
8362   Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
8363   Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
8364   Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
8365 
8366   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
8367 
8368   // for encryption, we are done
8369   if (!decrypting)
8370     return instof_false;  // even if it is null
8371 
8372   // for decryption, we need to add a further check to avoid
8373   // taking the intrinsic path when cipher and plain are the same
8374   // see the original java code for why.
8375   RegionNode* region = new RegionNode(3);
8376   region->init_req(1, instof_false);
8377   Node* src = argument(1);
8378   Node* dest = argument(4);
8379   Node* cmp_src_dest = _gvn.transform(new CmpPNode(src, dest));
8380   Node* bool_src_dest = _gvn.transform(new BoolNode(cmp_src_dest, BoolTest::eq));
8381   Node* src_dest_conjoint = generate_guard(bool_src_dest, nullptr, PROB_MIN);
8382   region->init_req(2, src_dest_conjoint);
8383 
8384   record_for_igvn(region);
8385   return _gvn.transform(region);
8386 }
8387 
8388 //----------------------------inline_counterMode_AESCrypt_predicate----------------------------
8389 // Return node representing slow path of predicate check.
8390 // the pseudo code we want to emulate with this predicate is:
8391 // for encryption:
8392 //    if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
8393 // for decryption:
8394 //    if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
8395 //    note cipher==plain is more conservative than the original java code but that's OK
8396 //
8397 
8398 Node* LibraryCallKit::inline_counterMode_AESCrypt_predicate() {
8399   // The receiver was checked for null already.
8400   Node* objCTR = argument(0);
8401 
8402   // Load embeddedCipher field of CipherBlockChaining object.
8403   Node* embeddedCipherObj = load_field_from_object(objCTR, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8404 
8405   // get AESCrypt klass for instanceOf check
8406   // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
8407   // will have same classloader as CipherBlockChaining object
8408   const TypeInstPtr* tinst = _gvn.type(objCTR)->isa_instptr();
8409   assert(tinst != nullptr, "CTRobj is null");
8410   assert(tinst->is_loaded(), "CTRobj is not loaded");
8411 
8412   // we want to do an instanceof comparison against the AESCrypt class
8413   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8414   if (!klass_AESCrypt->is_loaded()) {
8415     // if AESCrypt is not even loaded, we never take the intrinsic fast path
8416     Node* ctrl = control();
8417     set_control(top()); // no regular fast path
8418     return ctrl;
8419   }
8420 
8421   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8422   Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
8423   Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
8424   Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
8425   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
8426 
8427   return instof_false; // even if it is null
8428 }
8429 
8430 //------------------------------inline_ghash_processBlocks
8431 bool LibraryCallKit::inline_ghash_processBlocks() {
8432   address stubAddr;
8433   const char *stubName;
8434   assert(UseGHASHIntrinsics, "need GHASH intrinsics support");
8435 
8436   stubAddr = StubRoutines::ghash_processBlocks();
8437   stubName = "ghash_processBlocks";
8438 
8439   Node* data           = argument(0);
8440   Node* offset         = argument(1);
8441   Node* len            = argument(2);
8442   Node* state          = argument(3);
8443   Node* subkeyH        = argument(4);
8444 
8445   state = must_be_not_null(state, true);
8446   subkeyH = must_be_not_null(subkeyH, true);
8447   data = must_be_not_null(data, true);
8448 
8449   Node* state_start  = array_element_address(state, intcon(0), T_LONG);
8450   assert(state_start, "state is null");
8451   Node* subkeyH_start  = array_element_address(subkeyH, intcon(0), T_LONG);
8452   assert(subkeyH_start, "subkeyH is null");
8453   Node* data_start  = array_element_address(data, offset, T_BYTE);
8454   assert(data_start, "data is null");
8455 
8456   Node* ghash = make_runtime_call(RC_LEAF|RC_NO_FP,
8457                                   OptoRuntime::ghash_processBlocks_Type(),
8458                                   stubAddr, stubName, TypePtr::BOTTOM,
8459                                   state_start, subkeyH_start, data_start, len);
8460   return true;
8461 }
8462 
8463 //------------------------------inline_chacha20Block
8464 bool LibraryCallKit::inline_chacha20Block() {
8465   address stubAddr;
8466   const char *stubName;
8467   assert(UseChaCha20Intrinsics, "need ChaCha20 intrinsics support");
8468 
8469   stubAddr = StubRoutines::chacha20Block();
8470   stubName = "chacha20Block";
8471 
8472   Node* state          = argument(0);
8473   Node* result         = argument(1);
8474 
8475   state = must_be_not_null(state, true);
8476   result = must_be_not_null(result, true);
8477 
8478   Node* state_start  = array_element_address(state, intcon(0), T_INT);
8479   assert(state_start, "state is null");
8480   Node* result_start  = array_element_address(result, intcon(0), T_BYTE);
8481   assert(result_start, "result is null");
8482 
8483   Node* cc20Blk = make_runtime_call(RC_LEAF|RC_NO_FP,
8484                                   OptoRuntime::chacha20Block_Type(),
8485                                   stubAddr, stubName, TypePtr::BOTTOM,
8486                                   state_start, result_start);
8487   // return key stream length (int)
8488   Node* retvalue = _gvn.transform(new ProjNode(cc20Blk, TypeFunc::Parms));
8489   set_result(retvalue);
8490   return true;
8491 }
8492 
8493 //------------------------------inline_kyberNtt
8494 bool LibraryCallKit::inline_kyberNtt() {
8495   address stubAddr;
8496   const char *stubName;
8497   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8498   assert(callee()->signature()->size() == 2, "kyberNtt has 2 parameters");
8499 
8500   stubAddr = StubRoutines::kyberNtt();
8501   stubName = "kyberNtt";
8502   if (!stubAddr) return false;
8503 
8504   Node* coeffs          = argument(0);
8505   Node* ntt_zetas        = argument(1);
8506 
8507   coeffs = must_be_not_null(coeffs, true);
8508   ntt_zetas = must_be_not_null(ntt_zetas, true);
8509 
8510   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_SHORT);
8511   assert(coeffs_start, "coeffs is null");
8512   Node* ntt_zetas_start  = array_element_address(ntt_zetas, intcon(0), T_SHORT);
8513   assert(ntt_zetas_start, "ntt_zetas is null");
8514   Node* kyberNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
8515                                   OptoRuntime::kyberNtt_Type(),
8516                                   stubAddr, stubName, TypePtr::BOTTOM,
8517                                   coeffs_start, ntt_zetas_start);
8518   // return an int
8519   Node* retvalue = _gvn.transform(new ProjNode(kyberNtt, TypeFunc::Parms));
8520   set_result(retvalue);
8521   return true;
8522 }
8523 
8524 //------------------------------inline_kyberInverseNtt
8525 bool LibraryCallKit::inline_kyberInverseNtt() {
8526   address stubAddr;
8527   const char *stubName;
8528   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8529   assert(callee()->signature()->size() == 2, "kyberInverseNtt has 2 parameters");
8530 
8531   stubAddr = StubRoutines::kyberInverseNtt();
8532   stubName = "kyberInverseNtt";
8533   if (!stubAddr) return false;
8534 
8535   Node* coeffs          = argument(0);
8536   Node* zetas           = argument(1);
8537 
8538   coeffs = must_be_not_null(coeffs, true);
8539   zetas = must_be_not_null(zetas, true);
8540 
8541   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_SHORT);
8542   assert(coeffs_start, "coeffs is null");
8543   Node* zetas_start  = array_element_address(zetas, intcon(0), T_SHORT);
8544   assert(zetas_start, "inverseNtt_zetas is null");
8545   Node* kyberInverseNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
8546                                   OptoRuntime::kyberInverseNtt_Type(),
8547                                   stubAddr, stubName, TypePtr::BOTTOM,
8548                                   coeffs_start, zetas_start);
8549 
8550   // return an int
8551   Node* retvalue = _gvn.transform(new ProjNode(kyberInverseNtt, TypeFunc::Parms));
8552   set_result(retvalue);
8553   return true;
8554 }
8555 
8556 //------------------------------inline_kyberNttMult
8557 bool LibraryCallKit::inline_kyberNttMult() {
8558   address stubAddr;
8559   const char *stubName;
8560   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8561   assert(callee()->signature()->size() == 4, "kyberNttMult has 4 parameters");
8562 
8563   stubAddr = StubRoutines::kyberNttMult();
8564   stubName = "kyberNttMult";
8565   if (!stubAddr) return false;
8566 
8567   Node* result          = argument(0);
8568   Node* ntta            = argument(1);
8569   Node* nttb            = argument(2);
8570   Node* zetas           = argument(3);
8571 
8572   result = must_be_not_null(result, true);
8573   ntta = must_be_not_null(ntta, true);
8574   nttb = must_be_not_null(nttb, true);
8575   zetas = must_be_not_null(zetas, true);
8576 
8577   Node* result_start  = array_element_address(result, intcon(0), T_SHORT);
8578   assert(result_start, "result is null");
8579   Node* ntta_start  = array_element_address(ntta, intcon(0), T_SHORT);
8580   assert(ntta_start, "ntta is null");
8581   Node* nttb_start  = array_element_address(nttb, intcon(0), T_SHORT);
8582   assert(nttb_start, "nttb is null");
8583   Node* zetas_start  = array_element_address(zetas, intcon(0), T_SHORT);
8584   assert(zetas_start, "nttMult_zetas is null");
8585   Node* kyberNttMult = make_runtime_call(RC_LEAF|RC_NO_FP,
8586                                   OptoRuntime::kyberNttMult_Type(),
8587                                   stubAddr, stubName, TypePtr::BOTTOM,
8588                                   result_start, ntta_start, nttb_start,
8589                                   zetas_start);
8590 
8591   // return an int
8592   Node* retvalue = _gvn.transform(new ProjNode(kyberNttMult, TypeFunc::Parms));
8593   set_result(retvalue);
8594 
8595   return true;
8596 }
8597 
8598 //------------------------------inline_kyberAddPoly_2
8599 bool LibraryCallKit::inline_kyberAddPoly_2() {
8600   address stubAddr;
8601   const char *stubName;
8602   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8603   assert(callee()->signature()->size() == 3, "kyberAddPoly_2 has 3 parameters");
8604 
8605   stubAddr = StubRoutines::kyberAddPoly_2();
8606   stubName = "kyberAddPoly_2";
8607   if (!stubAddr) return false;
8608 
8609   Node* result          = argument(0);
8610   Node* a               = argument(1);
8611   Node* b               = argument(2);
8612 
8613   result = must_be_not_null(result, true);
8614   a = must_be_not_null(a, true);
8615   b = must_be_not_null(b, true);
8616 
8617   Node* result_start  = array_element_address(result, intcon(0), T_SHORT);
8618   assert(result_start, "result is null");
8619   Node* a_start  = array_element_address(a, intcon(0), T_SHORT);
8620   assert(a_start, "a is null");
8621   Node* b_start  = array_element_address(b, intcon(0), T_SHORT);
8622   assert(b_start, "b is null");
8623   Node* kyberAddPoly_2 = make_runtime_call(RC_LEAF|RC_NO_FP,
8624                                   OptoRuntime::kyberAddPoly_2_Type(),
8625                                   stubAddr, stubName, TypePtr::BOTTOM,
8626                                   result_start, a_start, b_start);
8627   // return an int
8628   Node* retvalue = _gvn.transform(new ProjNode(kyberAddPoly_2, TypeFunc::Parms));
8629   set_result(retvalue);
8630   return true;
8631 }
8632 
8633 //------------------------------inline_kyberAddPoly_3
8634 bool LibraryCallKit::inline_kyberAddPoly_3() {
8635   address stubAddr;
8636   const char *stubName;
8637   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8638   assert(callee()->signature()->size() == 4, "kyberAddPoly_3 has 4 parameters");
8639 
8640   stubAddr = StubRoutines::kyberAddPoly_3();
8641   stubName = "kyberAddPoly_3";
8642   if (!stubAddr) return false;
8643 
8644   Node* result          = argument(0);
8645   Node* a               = argument(1);
8646   Node* b               = argument(2);
8647   Node* c               = argument(3);
8648 
8649   result = must_be_not_null(result, true);
8650   a = must_be_not_null(a, true);
8651   b = must_be_not_null(b, true);
8652   c = must_be_not_null(c, true);
8653 
8654   Node* result_start  = array_element_address(result, intcon(0), T_SHORT);
8655   assert(result_start, "result is null");
8656   Node* a_start  = array_element_address(a, intcon(0), T_SHORT);
8657   assert(a_start, "a is null");
8658   Node* b_start  = array_element_address(b, intcon(0), T_SHORT);
8659   assert(b_start, "b is null");
8660   Node* c_start  = array_element_address(c, intcon(0), T_SHORT);
8661   assert(c_start, "c is null");
8662   Node* kyberAddPoly_3 = make_runtime_call(RC_LEAF|RC_NO_FP,
8663                                   OptoRuntime::kyberAddPoly_3_Type(),
8664                                   stubAddr, stubName, TypePtr::BOTTOM,
8665                                   result_start, a_start, b_start, c_start);
8666   // return an int
8667   Node* retvalue = _gvn.transform(new ProjNode(kyberAddPoly_3, TypeFunc::Parms));
8668   set_result(retvalue);
8669   return true;
8670 }
8671 
8672 //------------------------------inline_kyber12To16
8673 bool LibraryCallKit::inline_kyber12To16() {
8674   address stubAddr;
8675   const char *stubName;
8676   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8677   assert(callee()->signature()->size() == 4, "kyber12To16 has 4 parameters");
8678 
8679   stubAddr = StubRoutines::kyber12To16();
8680   stubName = "kyber12To16";
8681   if (!stubAddr) return false;
8682 
8683   Node* condensed       = argument(0);
8684   Node* condensedOffs   = argument(1);
8685   Node* parsed          = argument(2);
8686   Node* parsedLength    = argument(3);
8687 
8688   condensed = must_be_not_null(condensed, true);
8689   parsed = must_be_not_null(parsed, true);
8690 
8691   Node* condensed_start  = array_element_address(condensed, intcon(0), T_BYTE);
8692   assert(condensed_start, "condensed is null");
8693   Node* parsed_start  = array_element_address(parsed, intcon(0), T_SHORT);
8694   assert(parsed_start, "parsed is null");
8695   Node* kyber12To16 = make_runtime_call(RC_LEAF|RC_NO_FP,
8696                                   OptoRuntime::kyber12To16_Type(),
8697                                   stubAddr, stubName, TypePtr::BOTTOM,
8698                                   condensed_start, condensedOffs, parsed_start, parsedLength);
8699   // return an int
8700   Node* retvalue = _gvn.transform(new ProjNode(kyber12To16, TypeFunc::Parms));
8701   set_result(retvalue);
8702   return true;
8703 
8704 }
8705 
8706 //------------------------------inline_kyberBarrettReduce
8707 bool LibraryCallKit::inline_kyberBarrettReduce() {
8708   address stubAddr;
8709   const char *stubName;
8710   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8711   assert(callee()->signature()->size() == 1, "kyberBarrettReduce has 1 parameters");
8712 
8713   stubAddr = StubRoutines::kyberBarrettReduce();
8714   stubName = "kyberBarrettReduce";
8715   if (!stubAddr) return false;
8716 
8717   Node* coeffs          = argument(0);
8718 
8719   coeffs = must_be_not_null(coeffs, true);
8720 
8721   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_SHORT);
8722   assert(coeffs_start, "coeffs is null");
8723   Node* kyberBarrettReduce = make_runtime_call(RC_LEAF|RC_NO_FP,
8724                                   OptoRuntime::kyberBarrettReduce_Type(),
8725                                   stubAddr, stubName, TypePtr::BOTTOM,
8726                                   coeffs_start);
8727   // return an int
8728   Node* retvalue = _gvn.transform(new ProjNode(kyberBarrettReduce, TypeFunc::Parms));
8729   set_result(retvalue);
8730   return true;
8731 }
8732 
8733 //------------------------------inline_dilithiumAlmostNtt
8734 bool LibraryCallKit::inline_dilithiumAlmostNtt() {
8735   address stubAddr;
8736   const char *stubName;
8737   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8738   assert(callee()->signature()->size() == 2, "dilithiumAlmostNtt has 2 parameters");
8739 
8740   stubAddr = StubRoutines::dilithiumAlmostNtt();
8741   stubName = "dilithiumAlmostNtt";
8742   if (!stubAddr) return false;
8743 
8744   Node* coeffs          = argument(0);
8745   Node* ntt_zetas        = argument(1);
8746 
8747   coeffs = must_be_not_null(coeffs, true);
8748   ntt_zetas = must_be_not_null(ntt_zetas, true);
8749 
8750   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_INT);
8751   assert(coeffs_start, "coeffs is null");
8752   Node* ntt_zetas_start  = array_element_address(ntt_zetas, intcon(0), T_INT);
8753   assert(ntt_zetas_start, "ntt_zetas is null");
8754   Node* dilithiumAlmostNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
8755                                   OptoRuntime::dilithiumAlmostNtt_Type(),
8756                                   stubAddr, stubName, TypePtr::BOTTOM,
8757                                   coeffs_start, ntt_zetas_start);
8758   // return an int
8759   Node* retvalue = _gvn.transform(new ProjNode(dilithiumAlmostNtt, TypeFunc::Parms));
8760   set_result(retvalue);
8761   return true;
8762 }
8763 
8764 //------------------------------inline_dilithiumAlmostInverseNtt
8765 bool LibraryCallKit::inline_dilithiumAlmostInverseNtt() {
8766   address stubAddr;
8767   const char *stubName;
8768   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8769   assert(callee()->signature()->size() == 2, "dilithiumAlmostInverseNtt has 2 parameters");
8770 
8771   stubAddr = StubRoutines::dilithiumAlmostInverseNtt();
8772   stubName = "dilithiumAlmostInverseNtt";
8773   if (!stubAddr) return false;
8774 
8775   Node* coeffs          = argument(0);
8776   Node* zetas           = argument(1);
8777 
8778   coeffs = must_be_not_null(coeffs, true);
8779   zetas = must_be_not_null(zetas, true);
8780 
8781   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_INT);
8782   assert(coeffs_start, "coeffs is null");
8783   Node* zetas_start  = array_element_address(zetas, intcon(0), T_INT);
8784   assert(zetas_start, "inverseNtt_zetas is null");
8785   Node* dilithiumAlmostInverseNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
8786                                   OptoRuntime::dilithiumAlmostInverseNtt_Type(),
8787                                   stubAddr, stubName, TypePtr::BOTTOM,
8788                                   coeffs_start, zetas_start);
8789   // return an int
8790   Node* retvalue = _gvn.transform(new ProjNode(dilithiumAlmostInverseNtt, TypeFunc::Parms));
8791   set_result(retvalue);
8792   return true;
8793 }
8794 
8795 //------------------------------inline_dilithiumNttMult
8796 bool LibraryCallKit::inline_dilithiumNttMult() {
8797   address stubAddr;
8798   const char *stubName;
8799   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8800   assert(callee()->signature()->size() == 3, "dilithiumNttMult has 3 parameters");
8801 
8802   stubAddr = StubRoutines::dilithiumNttMult();
8803   stubName = "dilithiumNttMult";
8804   if (!stubAddr) return false;
8805 
8806   Node* result          = argument(0);
8807   Node* ntta            = argument(1);
8808   Node* nttb            = argument(2);
8809   Node* zetas           = argument(3);
8810 
8811   result = must_be_not_null(result, true);
8812   ntta = must_be_not_null(ntta, true);
8813   nttb = must_be_not_null(nttb, true);
8814   zetas = must_be_not_null(zetas, true);
8815 
8816   Node* result_start  = array_element_address(result, intcon(0), T_INT);
8817   assert(result_start, "result is null");
8818   Node* ntta_start  = array_element_address(ntta, intcon(0), T_INT);
8819   assert(ntta_start, "ntta is null");
8820   Node* nttb_start  = array_element_address(nttb, intcon(0), T_INT);
8821   assert(nttb_start, "nttb is null");
8822   Node* dilithiumNttMult = make_runtime_call(RC_LEAF|RC_NO_FP,
8823                                   OptoRuntime::dilithiumNttMult_Type(),
8824                                   stubAddr, stubName, TypePtr::BOTTOM,
8825                                   result_start, ntta_start, nttb_start);
8826 
8827   // return an int
8828   Node* retvalue = _gvn.transform(new ProjNode(dilithiumNttMult, TypeFunc::Parms));
8829   set_result(retvalue);
8830 
8831   return true;
8832 }
8833 
8834 //------------------------------inline_dilithiumMontMulByConstant
8835 bool LibraryCallKit::inline_dilithiumMontMulByConstant() {
8836   address stubAddr;
8837   const char *stubName;
8838   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8839   assert(callee()->signature()->size() == 2, "dilithiumMontMulByConstant has 2 parameters");
8840 
8841   stubAddr = StubRoutines::dilithiumMontMulByConstant();
8842   stubName = "dilithiumMontMulByConstant";
8843   if (!stubAddr) return false;
8844 
8845   Node* coeffs          = argument(0);
8846   Node* constant        = argument(1);
8847 
8848   coeffs = must_be_not_null(coeffs, true);
8849 
8850   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_INT);
8851   assert(coeffs_start, "coeffs is null");
8852   Node* dilithiumMontMulByConstant = make_runtime_call(RC_LEAF|RC_NO_FP,
8853                                   OptoRuntime::dilithiumMontMulByConstant_Type(),
8854                                   stubAddr, stubName, TypePtr::BOTTOM,
8855                                   coeffs_start, constant);
8856 
8857   // return an int
8858   Node* retvalue = _gvn.transform(new ProjNode(dilithiumMontMulByConstant, TypeFunc::Parms));
8859   set_result(retvalue);
8860   return true;
8861 }
8862 
8863 
8864 //------------------------------inline_dilithiumDecomposePoly
8865 bool LibraryCallKit::inline_dilithiumDecomposePoly() {
8866   address stubAddr;
8867   const char *stubName;
8868   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8869   assert(callee()->signature()->size() == 5, "dilithiumDecomposePoly has 5 parameters");
8870 
8871   stubAddr = StubRoutines::dilithiumDecomposePoly();
8872   stubName = "dilithiumDecomposePoly";
8873   if (!stubAddr) return false;
8874 
8875   Node* input          = argument(0);
8876   Node* lowPart        = argument(1);
8877   Node* highPart       = argument(2);
8878   Node* twoGamma2      = argument(3);
8879   Node* multiplier     = argument(4);
8880 
8881   input = must_be_not_null(input, true);
8882   lowPart = must_be_not_null(lowPart, true);
8883   highPart = must_be_not_null(highPart, true);
8884 
8885   Node* input_start  = array_element_address(input, intcon(0), T_INT);
8886   assert(input_start, "input is null");
8887   Node* lowPart_start  = array_element_address(lowPart, intcon(0), T_INT);
8888   assert(lowPart_start, "lowPart is null");
8889   Node* highPart_start  = array_element_address(highPart, intcon(0), T_INT);
8890   assert(highPart_start, "highPart is null");
8891 
8892   Node* dilithiumDecomposePoly = make_runtime_call(RC_LEAF|RC_NO_FP,
8893                                   OptoRuntime::dilithiumDecomposePoly_Type(),
8894                                   stubAddr, stubName, TypePtr::BOTTOM,
8895                                   input_start, lowPart_start, highPart_start,
8896                                   twoGamma2, multiplier);
8897 
8898   // return an int
8899   Node* retvalue = _gvn.transform(new ProjNode(dilithiumDecomposePoly, TypeFunc::Parms));
8900   set_result(retvalue);
8901   return true;
8902 }
8903 
8904 bool LibraryCallKit::inline_base64_encodeBlock() {
8905   address stubAddr;
8906   const char *stubName;
8907   assert(UseBASE64Intrinsics, "need Base64 intrinsics support");
8908   assert(callee()->signature()->size() == 6, "base64_encodeBlock has 6 parameters");
8909   stubAddr = StubRoutines::base64_encodeBlock();
8910   stubName = "encodeBlock";
8911 
8912   if (!stubAddr) return false;
8913   Node* base64obj = argument(0);
8914   Node* src = argument(1);
8915   Node* offset = argument(2);
8916   Node* len = argument(3);
8917   Node* dest = argument(4);
8918   Node* dp = argument(5);
8919   Node* isURL = argument(6);
8920 
8921   src = must_be_not_null(src, true);
8922   dest = must_be_not_null(dest, true);
8923 
8924   Node* src_start = array_element_address(src, intcon(0), T_BYTE);
8925   assert(src_start, "source array is null");
8926   Node* dest_start = array_element_address(dest, intcon(0), T_BYTE);
8927   assert(dest_start, "destination array is null");
8928 
8929   Node* base64 = make_runtime_call(RC_LEAF,
8930                                    OptoRuntime::base64_encodeBlock_Type(),
8931                                    stubAddr, stubName, TypePtr::BOTTOM,
8932                                    src_start, offset, len, dest_start, dp, isURL);
8933   return true;
8934 }
8935 
8936 bool LibraryCallKit::inline_base64_decodeBlock() {
8937   address stubAddr;
8938   const char *stubName;
8939   assert(UseBASE64Intrinsics, "need Base64 intrinsics support");
8940   assert(callee()->signature()->size() == 7, "base64_decodeBlock has 7 parameters");
8941   stubAddr = StubRoutines::base64_decodeBlock();
8942   stubName = "decodeBlock";
8943 
8944   if (!stubAddr) return false;
8945   Node* base64obj = argument(0);
8946   Node* src = argument(1);
8947   Node* src_offset = argument(2);
8948   Node* len = argument(3);
8949   Node* dest = argument(4);
8950   Node* dest_offset = argument(5);
8951   Node* isURL = argument(6);
8952   Node* isMIME = argument(7);
8953 
8954   src = must_be_not_null(src, true);
8955   dest = must_be_not_null(dest, true);
8956 
8957   Node* src_start = array_element_address(src, intcon(0), T_BYTE);
8958   assert(src_start, "source array is null");
8959   Node* dest_start = array_element_address(dest, intcon(0), T_BYTE);
8960   assert(dest_start, "destination array is null");
8961 
8962   Node* call = make_runtime_call(RC_LEAF,
8963                                  OptoRuntime::base64_decodeBlock_Type(),
8964                                  stubAddr, stubName, TypePtr::BOTTOM,
8965                                  src_start, src_offset, len, dest_start, dest_offset, isURL, isMIME);
8966   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
8967   set_result(result);
8968   return true;
8969 }
8970 
8971 bool LibraryCallKit::inline_poly1305_processBlocks() {
8972   address stubAddr;
8973   const char *stubName;
8974   assert(UsePoly1305Intrinsics, "need Poly intrinsics support");
8975   assert(callee()->signature()->size() == 5, "poly1305_processBlocks has %d parameters", callee()->signature()->size());
8976   stubAddr = StubRoutines::poly1305_processBlocks();
8977   stubName = "poly1305_processBlocks";
8978 
8979   if (!stubAddr) return false;
8980   null_check_receiver();  // null-check receiver
8981   if (stopped())  return true;
8982 
8983   Node* input = argument(1);
8984   Node* input_offset = argument(2);
8985   Node* len = argument(3);
8986   Node* alimbs = argument(4);
8987   Node* rlimbs = argument(5);
8988 
8989   input = must_be_not_null(input, true);
8990   alimbs = must_be_not_null(alimbs, true);
8991   rlimbs = must_be_not_null(rlimbs, true);
8992 
8993   Node* input_start = array_element_address(input, input_offset, T_BYTE);
8994   assert(input_start, "input array is null");
8995   Node* acc_start = array_element_address(alimbs, intcon(0), T_LONG);
8996   assert(acc_start, "acc array is null");
8997   Node* r_start = array_element_address(rlimbs, intcon(0), T_LONG);
8998   assert(r_start, "r array is null");
8999 
9000   Node* call = make_runtime_call(RC_LEAF | RC_NO_FP,
9001                                  OptoRuntime::poly1305_processBlocks_Type(),
9002                                  stubAddr, stubName, TypePtr::BOTTOM,
9003                                  input_start, len, acc_start, r_start);
9004   return true;
9005 }
9006 
9007 bool LibraryCallKit::inline_intpoly_montgomeryMult_P256() {
9008   address stubAddr;
9009   const char *stubName;
9010   assert(UseIntPolyIntrinsics, "need intpoly intrinsics support");
9011   assert(callee()->signature()->size() == 3, "intpoly_montgomeryMult_P256 has %d parameters", callee()->signature()->size());
9012   stubAddr = StubRoutines::intpoly_montgomeryMult_P256();
9013   stubName = "intpoly_montgomeryMult_P256";
9014 
9015   if (!stubAddr) return false;
9016   null_check_receiver();  // null-check receiver
9017   if (stopped())  return true;
9018 
9019   Node* a = argument(1);
9020   Node* b = argument(2);
9021   Node* r = argument(3);
9022 
9023   a = must_be_not_null(a, true);
9024   b = must_be_not_null(b, true);
9025   r = must_be_not_null(r, true);
9026 
9027   Node* a_start = array_element_address(a, intcon(0), T_LONG);
9028   assert(a_start, "a array is null");
9029   Node* b_start = array_element_address(b, intcon(0), T_LONG);
9030   assert(b_start, "b array is null");
9031   Node* r_start = array_element_address(r, intcon(0), T_LONG);
9032   assert(r_start, "r array is null");
9033 
9034   Node* call = make_runtime_call(RC_LEAF | RC_NO_FP,
9035                                  OptoRuntime::intpoly_montgomeryMult_P256_Type(),
9036                                  stubAddr, stubName, TypePtr::BOTTOM,
9037                                  a_start, b_start, r_start);
9038   return true;
9039 }
9040 
9041 bool LibraryCallKit::inline_intpoly_assign() {
9042   assert(UseIntPolyIntrinsics, "need intpoly intrinsics support");
9043   assert(callee()->signature()->size() == 3, "intpoly_assign has %d parameters", callee()->signature()->size());
9044   const char *stubName = "intpoly_assign";
9045   address stubAddr = StubRoutines::intpoly_assign();
9046   if (!stubAddr) return false;
9047 
9048   Node* set = argument(0);
9049   Node* a = argument(1);
9050   Node* b = argument(2);
9051   Node* arr_length = load_array_length(a);
9052 
9053   a = must_be_not_null(a, true);
9054   b = must_be_not_null(b, true);
9055 
9056   Node* a_start = array_element_address(a, intcon(0), T_LONG);
9057   assert(a_start, "a array is null");
9058   Node* b_start = array_element_address(b, intcon(0), T_LONG);
9059   assert(b_start, "b array is null");
9060 
9061   Node* call = make_runtime_call(RC_LEAF | RC_NO_FP,
9062                                  OptoRuntime::intpoly_assign_Type(),
9063                                  stubAddr, stubName, TypePtr::BOTTOM,
9064                                  set, a_start, b_start, arr_length);
9065   return true;
9066 }
9067 
9068 //------------------------------inline_digestBase_implCompress-----------------------
9069 //
9070 // Calculate MD5 for single-block byte[] array.
9071 // void com.sun.security.provider.MD5.implCompress(byte[] buf, int ofs)
9072 //
9073 // Calculate SHA (i.e., SHA-1) for single-block byte[] array.
9074 // void com.sun.security.provider.SHA.implCompress(byte[] buf, int ofs)
9075 //
9076 // Calculate SHA2 (i.e., SHA-244 or SHA-256) for single-block byte[] array.
9077 // void com.sun.security.provider.SHA2.implCompress(byte[] buf, int ofs)
9078 //
9079 // Calculate SHA5 (i.e., SHA-384 or SHA-512) for single-block byte[] array.
9080 // void com.sun.security.provider.SHA5.implCompress(byte[] buf, int ofs)
9081 //
9082 // Calculate SHA3 (i.e., SHA3-224 or SHA3-256 or SHA3-384 or SHA3-512) for single-block byte[] array.
9083 // void com.sun.security.provider.SHA3.implCompress(byte[] buf, int ofs)
9084 //
9085 bool LibraryCallKit::inline_digestBase_implCompress(vmIntrinsics::ID id) {
9086   assert(callee()->signature()->size() == 2, "sha_implCompress has 2 parameters");
9087 
9088   Node* digestBase_obj = argument(0);
9089   Node* src            = argument(1); // type oop
9090   Node* ofs            = argument(2); // type int
9091 
9092   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
9093   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
9094     // failed array check
9095     return false;
9096   }
9097   // Figure out the size and type of the elements we will be copying.
9098   BasicType src_elem = src_type->elem()->array_element_basic_type();
9099   if (src_elem != T_BYTE) {
9100     return false;
9101   }
9102   // 'src_start' points to src array + offset
9103   src = must_be_not_null(src, true);
9104   Node* src_start = array_element_address(src, ofs, src_elem);
9105   Node* state = nullptr;
9106   Node* block_size = nullptr;
9107   address stubAddr;
9108   const char *stubName;
9109 
9110   switch(id) {
9111   case vmIntrinsics::_md5_implCompress:
9112     assert(UseMD5Intrinsics, "need MD5 instruction support");
9113     state = get_state_from_digest_object(digestBase_obj, T_INT);
9114     stubAddr = StubRoutines::md5_implCompress();
9115     stubName = "md5_implCompress";
9116     break;
9117   case vmIntrinsics::_sha_implCompress:
9118     assert(UseSHA1Intrinsics, "need SHA1 instruction support");
9119     state = get_state_from_digest_object(digestBase_obj, T_INT);
9120     stubAddr = StubRoutines::sha1_implCompress();
9121     stubName = "sha1_implCompress";
9122     break;
9123   case vmIntrinsics::_sha2_implCompress:
9124     assert(UseSHA256Intrinsics, "need SHA256 instruction support");
9125     state = get_state_from_digest_object(digestBase_obj, T_INT);
9126     stubAddr = StubRoutines::sha256_implCompress();
9127     stubName = "sha256_implCompress";
9128     break;
9129   case vmIntrinsics::_sha5_implCompress:
9130     assert(UseSHA512Intrinsics, "need SHA512 instruction support");
9131     state = get_state_from_digest_object(digestBase_obj, T_LONG);
9132     stubAddr = StubRoutines::sha512_implCompress();
9133     stubName = "sha512_implCompress";
9134     break;
9135   case vmIntrinsics::_sha3_implCompress:
9136     assert(UseSHA3Intrinsics, "need SHA3 instruction support");
9137     state = get_state_from_digest_object(digestBase_obj, T_LONG);
9138     stubAddr = StubRoutines::sha3_implCompress();
9139     stubName = "sha3_implCompress";
9140     block_size = get_block_size_from_digest_object(digestBase_obj);
9141     if (block_size == nullptr) return false;
9142     break;
9143   default:
9144     fatal_unexpected_iid(id);
9145     return false;
9146   }
9147   if (state == nullptr) return false;
9148 
9149   assert(stubAddr != nullptr, "Stub %s is not generated", stubName);
9150   if (stubAddr == nullptr) return false;
9151 
9152   // Call the stub.
9153   Node* call;
9154   if (block_size == nullptr) {
9155     call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::digestBase_implCompress_Type(false),
9156                              stubAddr, stubName, TypePtr::BOTTOM,
9157                              src_start, state);
9158   } else {
9159     call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::digestBase_implCompress_Type(true),
9160                              stubAddr, stubName, TypePtr::BOTTOM,
9161                              src_start, state, block_size);
9162   }
9163 
9164   return true;
9165 }
9166 
9167 //------------------------------inline_double_keccak
9168 bool LibraryCallKit::inline_double_keccak() {
9169   address stubAddr;
9170   const char *stubName;
9171   assert(UseSHA3Intrinsics, "need SHA3 intrinsics support");
9172   assert(callee()->signature()->size() == 2, "double_keccak has 2 parameters");
9173 
9174   stubAddr = StubRoutines::double_keccak();
9175   stubName = "double_keccak";
9176   if (!stubAddr) return false;
9177 
9178   Node* status0        = argument(0);
9179   Node* status1        = argument(1);
9180 
9181   status0 = must_be_not_null(status0, true);
9182   status1 = must_be_not_null(status1, true);
9183 
9184   Node* status0_start  = array_element_address(status0, intcon(0), T_LONG);
9185   assert(status0_start, "status0 is null");
9186   Node* status1_start  = array_element_address(status1, intcon(0), T_LONG);
9187   assert(status1_start, "status1 is null");
9188   Node* double_keccak = make_runtime_call(RC_LEAF|RC_NO_FP,
9189                                   OptoRuntime::double_keccak_Type(),
9190                                   stubAddr, stubName, TypePtr::BOTTOM,
9191                                   status0_start, status1_start);
9192   // return an int
9193   Node* retvalue = _gvn.transform(new ProjNode(double_keccak, TypeFunc::Parms));
9194   set_result(retvalue);
9195   return true;
9196 }
9197 
9198 
9199 //------------------------------inline_digestBase_implCompressMB-----------------------
9200 //
9201 // Calculate MD5/SHA/SHA2/SHA5/SHA3 for multi-block byte[] array.
9202 // int com.sun.security.provider.DigestBase.implCompressMultiBlock(byte[] b, int ofs, int limit)
9203 //
9204 bool LibraryCallKit::inline_digestBase_implCompressMB(int predicate) {
9205   assert(UseMD5Intrinsics || UseSHA1Intrinsics || UseSHA256Intrinsics || UseSHA512Intrinsics || UseSHA3Intrinsics,
9206          "need MD5/SHA1/SHA256/SHA512/SHA3 instruction support");
9207   assert((uint)predicate < 5, "sanity");
9208   assert(callee()->signature()->size() == 3, "digestBase_implCompressMB has 3 parameters");
9209 
9210   Node* digestBase_obj = argument(0); // The receiver was checked for null already.
9211   Node* src            = argument(1); // byte[] array
9212   Node* ofs            = argument(2); // type int
9213   Node* limit          = argument(3); // type int
9214 
9215   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
9216   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
9217     // failed array check
9218     return false;
9219   }
9220   // Figure out the size and type of the elements we will be copying.
9221   BasicType src_elem = src_type->elem()->array_element_basic_type();
9222   if (src_elem != T_BYTE) {
9223     return false;
9224   }
9225   // 'src_start' points to src array + offset
9226   src = must_be_not_null(src, false);
9227   Node* src_start = array_element_address(src, ofs, src_elem);
9228 
9229   const char* klass_digestBase_name = nullptr;
9230   const char* stub_name = nullptr;
9231   address     stub_addr = nullptr;
9232   BasicType elem_type = T_INT;
9233 
9234   switch (predicate) {
9235   case 0:
9236     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_md5_implCompress)) {
9237       klass_digestBase_name = "sun/security/provider/MD5";
9238       stub_name = "md5_implCompressMB";
9239       stub_addr = StubRoutines::md5_implCompressMB();
9240     }
9241     break;
9242   case 1:
9243     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha_implCompress)) {
9244       klass_digestBase_name = "sun/security/provider/SHA";
9245       stub_name = "sha1_implCompressMB";
9246       stub_addr = StubRoutines::sha1_implCompressMB();
9247     }
9248     break;
9249   case 2:
9250     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha2_implCompress)) {
9251       klass_digestBase_name = "sun/security/provider/SHA2";
9252       stub_name = "sha256_implCompressMB";
9253       stub_addr = StubRoutines::sha256_implCompressMB();
9254     }
9255     break;
9256   case 3:
9257     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha5_implCompress)) {
9258       klass_digestBase_name = "sun/security/provider/SHA5";
9259       stub_name = "sha512_implCompressMB";
9260       stub_addr = StubRoutines::sha512_implCompressMB();
9261       elem_type = T_LONG;
9262     }
9263     break;
9264   case 4:
9265     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha3_implCompress)) {
9266       klass_digestBase_name = "sun/security/provider/SHA3";
9267       stub_name = "sha3_implCompressMB";
9268       stub_addr = StubRoutines::sha3_implCompressMB();
9269       elem_type = T_LONG;
9270     }
9271     break;
9272   default:
9273     fatal("unknown DigestBase intrinsic predicate: %d", predicate);
9274   }
9275   if (klass_digestBase_name != nullptr) {
9276     assert(stub_addr != nullptr, "Stub is generated");
9277     if (stub_addr == nullptr) return false;
9278 
9279     // get DigestBase klass to lookup for SHA klass
9280     const TypeInstPtr* tinst = _gvn.type(digestBase_obj)->isa_instptr();
9281     assert(tinst != nullptr, "digestBase_obj is not instance???");
9282     assert(tinst->is_loaded(), "DigestBase is not loaded");
9283 
9284     ciKlass* klass_digestBase = tinst->instance_klass()->find_klass(ciSymbol::make(klass_digestBase_name));
9285     assert(klass_digestBase->is_loaded(), "predicate checks that this class is loaded");
9286     ciInstanceKlass* instklass_digestBase = klass_digestBase->as_instance_klass();
9287     return inline_digestBase_implCompressMB(digestBase_obj, instklass_digestBase, elem_type, stub_addr, stub_name, src_start, ofs, limit);
9288   }
9289   return false;
9290 }
9291 
9292 //------------------------------inline_digestBase_implCompressMB-----------------------
9293 bool LibraryCallKit::inline_digestBase_implCompressMB(Node* digestBase_obj, ciInstanceKlass* instklass_digestBase,
9294                                                       BasicType elem_type, address stubAddr, const char *stubName,
9295                                                       Node* src_start, Node* ofs, Node* limit) {
9296   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_digestBase);
9297   const TypeOopPtr* xtype = aklass->cast_to_exactness(false)->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
9298   Node* digest_obj = new CheckCastPPNode(control(), digestBase_obj, xtype);
9299   digest_obj = _gvn.transform(digest_obj);
9300 
9301   Node* state = get_state_from_digest_object(digest_obj, elem_type);
9302   if (state == nullptr) return false;
9303 
9304   Node* block_size = nullptr;
9305   if (strcmp("sha3_implCompressMB", stubName) == 0) {
9306     block_size = get_block_size_from_digest_object(digest_obj);
9307     if (block_size == nullptr) return false;
9308   }
9309 
9310   // Call the stub.
9311   Node* call;
9312   if (block_size == nullptr) {
9313     call = make_runtime_call(RC_LEAF|RC_NO_FP,
9314                              OptoRuntime::digestBase_implCompressMB_Type(false),
9315                              stubAddr, stubName, TypePtr::BOTTOM,
9316                              src_start, state, ofs, limit);
9317   } else {
9318      call = make_runtime_call(RC_LEAF|RC_NO_FP,
9319                              OptoRuntime::digestBase_implCompressMB_Type(true),
9320                              stubAddr, stubName, TypePtr::BOTTOM,
9321                              src_start, state, block_size, ofs, limit);
9322   }
9323 
9324   // return ofs (int)
9325   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
9326   set_result(result);
9327 
9328   return true;
9329 }
9330 
9331 //------------------------------inline_galoisCounterMode_AESCrypt-----------------------
9332 bool LibraryCallKit::inline_galoisCounterMode_AESCrypt() {
9333   assert(UseAES, "need AES instruction support");
9334   address stubAddr = nullptr;
9335   const char *stubName = nullptr;
9336   stubAddr = StubRoutines::galoisCounterMode_AESCrypt();
9337   stubName = "galoisCounterMode_AESCrypt";
9338 
9339   if (stubAddr == nullptr) return false;
9340 
9341   Node* in      = argument(0);
9342   Node* inOfs   = argument(1);
9343   Node* len     = argument(2);
9344   Node* ct      = argument(3);
9345   Node* ctOfs   = argument(4);
9346   Node* out     = argument(5);
9347   Node* outOfs  = argument(6);
9348   Node* gctr_object = argument(7);
9349   Node* ghash_object = argument(8);
9350 
9351   // (1) in, ct and out are arrays.
9352   const TypeAryPtr* in_type = in->Value(&_gvn)->isa_aryptr();
9353   const TypeAryPtr* ct_type = ct->Value(&_gvn)->isa_aryptr();
9354   const TypeAryPtr* out_type = out->Value(&_gvn)->isa_aryptr();
9355   assert( in_type != nullptr &&  in_type->elem() != Type::BOTTOM &&
9356           ct_type != nullptr &&  ct_type->elem() != Type::BOTTOM &&
9357          out_type != nullptr && out_type->elem() != Type::BOTTOM, "args are strange");
9358 
9359   // checks are the responsibility of the caller
9360   Node* in_start = in;
9361   Node* ct_start = ct;
9362   Node* out_start = out;
9363   if (inOfs != nullptr || ctOfs != nullptr || outOfs != nullptr) {
9364     assert(inOfs != nullptr && ctOfs != nullptr && outOfs != nullptr, "");
9365     in_start = array_element_address(in, inOfs, T_BYTE);
9366     ct_start = array_element_address(ct, ctOfs, T_BYTE);
9367     out_start = array_element_address(out, outOfs, T_BYTE);
9368   }
9369 
9370   // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
9371   // (because of the predicated logic executed earlier).
9372   // so we cast it here safely.
9373   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
9374   Node* embeddedCipherObj = load_field_from_object(gctr_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
9375   Node* counter = load_field_from_object(gctr_object, "counter", "[B");
9376   Node* subkeyHtbl = load_field_from_object(ghash_object, "subkeyHtbl", "[J");
9377   Node* state = load_field_from_object(ghash_object, "state", "[J");
9378 
9379   if (embeddedCipherObj == nullptr || counter == nullptr || subkeyHtbl == nullptr || state == nullptr) {
9380     return false;
9381   }
9382   // cast it to what we know it will be at runtime
9383   const TypeInstPtr* tinst = _gvn.type(gctr_object)->isa_instptr();
9384   assert(tinst != nullptr, "GCTR obj is null");
9385   assert(tinst->is_loaded(), "GCTR obj is not loaded");
9386   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
9387   assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
9388   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
9389   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
9390   const TypeOopPtr* xtype = aklass->as_instance_type();
9391   Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
9392   aescrypt_object = _gvn.transform(aescrypt_object);
9393   // we need to get the start of the aescrypt_object's expanded key array
9394   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object);
9395   if (k_start == nullptr) return false;
9396   // similarly, get the start address of the r vector
9397   Node* cnt_start = array_element_address(counter, intcon(0), T_BYTE);
9398   Node* state_start = array_element_address(state, intcon(0), T_LONG);
9399   Node* subkeyHtbl_start = array_element_address(subkeyHtbl, intcon(0), T_LONG);
9400 
9401 
9402   // Call the stub, passing params
9403   Node* gcmCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
9404                                OptoRuntime::galoisCounterMode_aescrypt_Type(),
9405                                stubAddr, stubName, TypePtr::BOTTOM,
9406                                in_start, len, ct_start, out_start, k_start, state_start, subkeyHtbl_start, cnt_start);
9407 
9408   // return cipher length (int)
9409   Node* retvalue = _gvn.transform(new ProjNode(gcmCrypt, TypeFunc::Parms));
9410   set_result(retvalue);
9411 
9412   return true;
9413 }
9414 
9415 //----------------------------inline_galoisCounterMode_AESCrypt_predicate----------------------------
9416 // Return node representing slow path of predicate check.
9417 // the pseudo code we want to emulate with this predicate is:
9418 // for encryption:
9419 //    if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
9420 // for decryption:
9421 //    if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
9422 //    note cipher==plain is more conservative than the original java code but that's OK
9423 //
9424 
9425 Node* LibraryCallKit::inline_galoisCounterMode_AESCrypt_predicate() {
9426   // The receiver was checked for null already.
9427   Node* objGCTR = argument(7);
9428   // Load embeddedCipher field of GCTR object.
9429   Node* embeddedCipherObj = load_field_from_object(objGCTR, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
9430   assert(embeddedCipherObj != nullptr, "embeddedCipherObj is null");
9431 
9432   // get AESCrypt klass for instanceOf check
9433   // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
9434   // will have same classloader as CipherBlockChaining object
9435   const TypeInstPtr* tinst = _gvn.type(objGCTR)->isa_instptr();
9436   assert(tinst != nullptr, "GCTR obj is null");
9437   assert(tinst->is_loaded(), "GCTR obj is not loaded");
9438 
9439   // we want to do an instanceof comparison against the AESCrypt class
9440   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
9441   if (!klass_AESCrypt->is_loaded()) {
9442     // if AESCrypt is not even loaded, we never take the intrinsic fast path
9443     Node* ctrl = control();
9444     set_control(top()); // no regular fast path
9445     return ctrl;
9446   }
9447 
9448   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
9449   Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
9450   Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
9451   Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
9452   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
9453 
9454   return instof_false; // even if it is null
9455 }
9456 
9457 //------------------------------get_state_from_digest_object-----------------------
9458 Node * LibraryCallKit::get_state_from_digest_object(Node *digest_object, BasicType elem_type) {
9459   const char* state_type;
9460   switch (elem_type) {
9461     case T_BYTE: state_type = "[B"; break;
9462     case T_INT:  state_type = "[I"; break;
9463     case T_LONG: state_type = "[J"; break;
9464     default: ShouldNotReachHere();
9465   }
9466   Node* digest_state = load_field_from_object(digest_object, "state", state_type);
9467   assert (digest_state != nullptr, "wrong version of sun.security.provider.MD5/SHA/SHA2/SHA5/SHA3");
9468   if (digest_state == nullptr) return (Node *) nullptr;
9469 
9470   // now have the array, need to get the start address of the state array
9471   Node* state = array_element_address(digest_state, intcon(0), elem_type);
9472   return state;
9473 }
9474 
9475 //------------------------------get_block_size_from_sha3_object----------------------------------
9476 Node * LibraryCallKit::get_block_size_from_digest_object(Node *digest_object) {
9477   Node* block_size = load_field_from_object(digest_object, "blockSize", "I");
9478   assert (block_size != nullptr, "sanity");
9479   return block_size;
9480 }
9481 
9482 //----------------------------inline_digestBase_implCompressMB_predicate----------------------------
9483 // Return node representing slow path of predicate check.
9484 // the pseudo code we want to emulate with this predicate is:
9485 //    if (digestBaseObj instanceof MD5/SHA/SHA2/SHA5/SHA3) do_intrinsic, else do_javapath
9486 //
9487 Node* LibraryCallKit::inline_digestBase_implCompressMB_predicate(int predicate) {
9488   assert(UseMD5Intrinsics || UseSHA1Intrinsics || UseSHA256Intrinsics || UseSHA512Intrinsics || UseSHA3Intrinsics,
9489          "need MD5/SHA1/SHA256/SHA512/SHA3 instruction support");
9490   assert((uint)predicate < 5, "sanity");
9491 
9492   // The receiver was checked for null already.
9493   Node* digestBaseObj = argument(0);
9494 
9495   // get DigestBase klass for instanceOf check
9496   const TypeInstPtr* tinst = _gvn.type(digestBaseObj)->isa_instptr();
9497   assert(tinst != nullptr, "digestBaseObj is null");
9498   assert(tinst->is_loaded(), "DigestBase is not loaded");
9499 
9500   const char* klass_name = nullptr;
9501   switch (predicate) {
9502   case 0:
9503     if (UseMD5Intrinsics) {
9504       // we want to do an instanceof comparison against the MD5 class
9505       klass_name = "sun/security/provider/MD5";
9506     }
9507     break;
9508   case 1:
9509     if (UseSHA1Intrinsics) {
9510       // we want to do an instanceof comparison against the SHA class
9511       klass_name = "sun/security/provider/SHA";
9512     }
9513     break;
9514   case 2:
9515     if (UseSHA256Intrinsics) {
9516       // we want to do an instanceof comparison against the SHA2 class
9517       klass_name = "sun/security/provider/SHA2";
9518     }
9519     break;
9520   case 3:
9521     if (UseSHA512Intrinsics) {
9522       // we want to do an instanceof comparison against the SHA5 class
9523       klass_name = "sun/security/provider/SHA5";
9524     }
9525     break;
9526   case 4:
9527     if (UseSHA3Intrinsics) {
9528       // we want to do an instanceof comparison against the SHA3 class
9529       klass_name = "sun/security/provider/SHA3";
9530     }
9531     break;
9532   default:
9533     fatal("unknown SHA intrinsic predicate: %d", predicate);
9534   }
9535 
9536   ciKlass* klass = nullptr;
9537   if (klass_name != nullptr) {
9538     klass = tinst->instance_klass()->find_klass(ciSymbol::make(klass_name));
9539   }
9540   if ((klass == nullptr) || !klass->is_loaded()) {
9541     // if none of MD5/SHA/SHA2/SHA5 is loaded, we never take the intrinsic fast path
9542     Node* ctrl = control();
9543     set_control(top()); // no intrinsic path
9544     return ctrl;
9545   }
9546   ciInstanceKlass* instklass = klass->as_instance_klass();
9547 
9548   Node* instof = gen_instanceof(digestBaseObj, makecon(TypeKlassPtr::make(instklass)));
9549   Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
9550   Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
9551   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
9552 
9553   return instof_false;  // even if it is null
9554 }
9555 
9556 //-------------inline_fma-----------------------------------
9557 bool LibraryCallKit::inline_fma(vmIntrinsics::ID id) {
9558   Node *a = nullptr;
9559   Node *b = nullptr;
9560   Node *c = nullptr;
9561   Node* result = nullptr;
9562   switch (id) {
9563   case vmIntrinsics::_fmaD:
9564     assert(callee()->signature()->size() == 6, "fma has 3 parameters of size 2 each.");
9565     // no receiver since it is static method
9566     a = argument(0);
9567     b = argument(2);
9568     c = argument(4);
9569     result = _gvn.transform(new FmaDNode(a, b, c));
9570     break;
9571   case vmIntrinsics::_fmaF:
9572     assert(callee()->signature()->size() == 3, "fma has 3 parameters of size 1 each.");
9573     a = argument(0);
9574     b = argument(1);
9575     c = argument(2);
9576     result = _gvn.transform(new FmaFNode(a, b, c));
9577     break;
9578   default:
9579     fatal_unexpected_iid(id);  break;
9580   }
9581   set_result(result);
9582   return true;
9583 }
9584 
9585 bool LibraryCallKit::inline_character_compare(vmIntrinsics::ID id) {
9586   // argument(0) is receiver
9587   Node* codePoint = argument(1);
9588   Node* n = nullptr;
9589 
9590   switch (id) {
9591     case vmIntrinsics::_isDigit :
9592       n = new DigitNode(control(), codePoint);
9593       break;
9594     case vmIntrinsics::_isLowerCase :
9595       n = new LowerCaseNode(control(), codePoint);
9596       break;
9597     case vmIntrinsics::_isUpperCase :
9598       n = new UpperCaseNode(control(), codePoint);
9599       break;
9600     case vmIntrinsics::_isWhitespace :
9601       n = new WhitespaceNode(control(), codePoint);
9602       break;
9603     default:
9604       fatal_unexpected_iid(id);
9605   }
9606 
9607   set_result(_gvn.transform(n));
9608   return true;
9609 }
9610 
9611 bool LibraryCallKit::inline_profileBoolean() {
9612   Node* counts = argument(1);
9613   const TypeAryPtr* ary = nullptr;
9614   ciArray* aobj = nullptr;
9615   if (counts->is_Con()
9616       && (ary = counts->bottom_type()->isa_aryptr()) != nullptr
9617       && (aobj = ary->const_oop()->as_array()) != nullptr
9618       && (aobj->length() == 2)) {
9619     // Profile is int[2] where [0] and [1] correspond to false and true value occurrences respectively.
9620     jint false_cnt = aobj->element_value(0).as_int();
9621     jint  true_cnt = aobj->element_value(1).as_int();
9622 
9623     if (C->log() != nullptr) {
9624       C->log()->elem("observe source='profileBoolean' false='%d' true='%d'",
9625                      false_cnt, true_cnt);
9626     }
9627 
9628     if (false_cnt + true_cnt == 0) {
9629       // According to profile, never executed.
9630       uncommon_trap_exact(Deoptimization::Reason_intrinsic,
9631                           Deoptimization::Action_reinterpret);
9632       return true;
9633     }
9634 
9635     // result is a boolean (0 or 1) and its profile (false_cnt & true_cnt)
9636     // is a number of each value occurrences.
9637     Node* result = argument(0);
9638     if (false_cnt == 0 || true_cnt == 0) {
9639       // According to profile, one value has been never seen.
9640       int expected_val = (false_cnt == 0) ? 1 : 0;
9641 
9642       Node* cmp  = _gvn.transform(new CmpINode(result, intcon(expected_val)));
9643       Node* test = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
9644 
9645       IfNode* check = create_and_map_if(control(), test, PROB_ALWAYS, COUNT_UNKNOWN);
9646       Node* fast_path = _gvn.transform(new IfTrueNode(check));
9647       Node* slow_path = _gvn.transform(new IfFalseNode(check));
9648 
9649       { // Slow path: uncommon trap for never seen value and then reexecute
9650         // MethodHandleImpl::profileBoolean() to bump the count, so JIT knows
9651         // the value has been seen at least once.
9652         PreserveJVMState pjvms(this);
9653         PreserveReexecuteState preexecs(this);
9654         jvms()->set_should_reexecute(true);
9655 
9656         set_control(slow_path);
9657         set_i_o(i_o());
9658 
9659         uncommon_trap_exact(Deoptimization::Reason_intrinsic,
9660                             Deoptimization::Action_reinterpret);
9661       }
9662       // The guard for never seen value enables sharpening of the result and
9663       // returning a constant. It allows to eliminate branches on the same value
9664       // later on.
9665       set_control(fast_path);
9666       result = intcon(expected_val);
9667     }
9668     // Stop profiling.
9669     // MethodHandleImpl::profileBoolean() has profiling logic in its bytecode.
9670     // By replacing method body with profile data (represented as ProfileBooleanNode
9671     // on IR level) we effectively disable profiling.
9672     // It enables full speed execution once optimized code is generated.
9673     Node* profile = _gvn.transform(new ProfileBooleanNode(result, false_cnt, true_cnt));
9674     C->record_for_igvn(profile);
9675     set_result(profile);
9676     return true;
9677   } else {
9678     // Continue profiling.
9679     // Profile data isn't available at the moment. So, execute method's bytecode version.
9680     // Usually, when GWT LambdaForms are profiled it means that a stand-alone nmethod
9681     // is compiled and counters aren't available since corresponding MethodHandle
9682     // isn't a compile-time constant.
9683     return false;
9684   }
9685 }
9686 
9687 bool LibraryCallKit::inline_isCompileConstant() {
9688   Node* n = argument(0);
9689   set_result(n->is_Con() ? intcon(1) : intcon(0));
9690   return true;
9691 }
9692 
9693 //------------------------------- inline_getObjectSize --------------------------------------
9694 //
9695 // Calculate the runtime size of the object/array.
9696 //   native long sun.instrument.InstrumentationImpl.getObjectSize0(long nativeAgent, Object objectToSize);
9697 //
9698 bool LibraryCallKit::inline_getObjectSize() {
9699   Node* obj = argument(3);
9700   Node* klass_node = load_object_klass(obj);
9701 
9702   jint  layout_con = Klass::_lh_neutral_value;
9703   Node* layout_val = get_layout_helper(klass_node, layout_con);
9704   int   layout_is_con = (layout_val == nullptr);
9705 
9706   if (layout_is_con) {
9707     // Layout helper is constant, can figure out things at compile time.
9708 
9709     if (Klass::layout_helper_is_instance(layout_con)) {
9710       // Instance case:  layout_con contains the size itself.
9711       Node *size = longcon(Klass::layout_helper_size_in_bytes(layout_con));
9712       set_result(size);
9713     } else {
9714       // Array case: size is round(header + element_size*arraylength).
9715       // Since arraylength is different for every array instance, we have to
9716       // compute the whole thing at runtime.
9717 
9718       Node* arr_length = load_array_length(obj);
9719 
9720       int round_mask = MinObjAlignmentInBytes - 1;
9721       int hsize  = Klass::layout_helper_header_size(layout_con);
9722       int eshift = Klass::layout_helper_log2_element_size(layout_con);
9723 
9724       if ((round_mask & ~right_n_bits(eshift)) == 0) {
9725         round_mask = 0;  // strength-reduce it if it goes away completely
9726       }
9727       assert((hsize & right_n_bits(eshift)) == 0, "hsize is pre-rounded");
9728       Node* header_size = intcon(hsize + round_mask);
9729 
9730       Node* lengthx = ConvI2X(arr_length);
9731       Node* headerx = ConvI2X(header_size);
9732 
9733       Node* abody = lengthx;
9734       if (eshift != 0) {
9735         abody = _gvn.transform(new LShiftXNode(lengthx, intcon(eshift)));
9736       }
9737       Node* size = _gvn.transform( new AddXNode(headerx, abody) );
9738       if (round_mask != 0) {
9739         size = _gvn.transform( new AndXNode(size, MakeConX(~round_mask)) );
9740       }
9741       size = ConvX2L(size);
9742       set_result(size);
9743     }
9744   } else {
9745     // Layout helper is not constant, need to test for array-ness at runtime.
9746 
9747     enum { _instance_path = 1, _array_path, PATH_LIMIT };
9748     RegionNode* result_reg = new RegionNode(PATH_LIMIT);
9749     PhiNode* result_val = new PhiNode(result_reg, TypeLong::LONG);
9750     record_for_igvn(result_reg);
9751 
9752     Node* array_ctl = generate_array_guard(klass_node, nullptr, &obj);
9753     if (array_ctl != nullptr) {
9754       // Array case: size is round(header + element_size*arraylength).
9755       // Since arraylength is different for every array instance, we have to
9756       // compute the whole thing at runtime.
9757 
9758       PreserveJVMState pjvms(this);
9759       set_control(array_ctl);
9760       Node* arr_length = load_array_length(obj);
9761 
9762       int round_mask = MinObjAlignmentInBytes - 1;
9763       Node* mask = intcon(round_mask);
9764 
9765       Node* hss = intcon(Klass::_lh_header_size_shift);
9766       Node* hsm = intcon(Klass::_lh_header_size_mask);
9767       Node* header_size = _gvn.transform(new URShiftINode(layout_val, hss));
9768       header_size = _gvn.transform(new AndINode(header_size, hsm));
9769       header_size = _gvn.transform(new AddINode(header_size, mask));
9770 
9771       // There is no need to mask or shift this value.
9772       // The semantics of LShiftINode include an implicit mask to 0x1F.
9773       assert(Klass::_lh_log2_element_size_shift == 0, "use shift in place");
9774       Node* elem_shift = layout_val;
9775 
9776       Node* lengthx = ConvI2X(arr_length);
9777       Node* headerx = ConvI2X(header_size);
9778 
9779       Node* abody = _gvn.transform(new LShiftXNode(lengthx, elem_shift));
9780       Node* size = _gvn.transform(new AddXNode(headerx, abody));
9781       if (round_mask != 0) {
9782         size = _gvn.transform(new AndXNode(size, MakeConX(~round_mask)));
9783       }
9784       size = ConvX2L(size);
9785 
9786       result_reg->init_req(_array_path, control());
9787       result_val->init_req(_array_path, size);
9788     }
9789 
9790     if (!stopped()) {
9791       // Instance case: the layout helper gives us instance size almost directly,
9792       // but we need to mask out the _lh_instance_slow_path_bit.
9793       Node* size = ConvI2X(layout_val);
9794       assert((int) Klass::_lh_instance_slow_path_bit < BytesPerLong, "clear bit");
9795       Node* mask = MakeConX(~(intptr_t) right_n_bits(LogBytesPerLong));
9796       size = _gvn.transform(new AndXNode(size, mask));
9797       size = ConvX2L(size);
9798 
9799       result_reg->init_req(_instance_path, control());
9800       result_val->init_req(_instance_path, size);
9801     }
9802 
9803     set_result(result_reg, result_val);
9804   }
9805 
9806   return true;
9807 }
9808 
9809 //------------------------------- inline_blackhole --------------------------------------
9810 //
9811 // Make sure all arguments to this node are alive.
9812 // This matches methods that were requested to be blackholed through compile commands.
9813 //
9814 bool LibraryCallKit::inline_blackhole() {
9815   assert(callee()->is_static(), "Should have been checked before: only static methods here");
9816   assert(callee()->is_empty(), "Should have been checked before: only empty methods here");
9817   assert(callee()->holder()->is_loaded(), "Should have been checked before: only methods for loaded classes here");
9818 
9819   // Blackhole node pinches only the control, not memory. This allows
9820   // the blackhole to be pinned in the loop that computes blackholed
9821   // values, but have no other side effects, like breaking the optimizations
9822   // across the blackhole.
9823 
9824   Node* bh = _gvn.transform(new BlackholeNode(control()));
9825   set_control(_gvn.transform(new ProjNode(bh, TypeFunc::Control)));
9826 
9827   // Bind call arguments as blackhole arguments to keep them alive
9828   uint nargs = callee()->arg_size();
9829   for (uint i = 0; i < nargs; i++) {
9830     bh->add_req(argument(i));
9831   }
9832 
9833   return true;
9834 }
9835 
9836 Node* LibraryCallKit::unbox_fp16_value(const TypeInstPtr* float16_box_type, ciField* field, Node* box) {
9837   const TypeInstPtr* box_type = _gvn.type(box)->isa_instptr();
9838   if (box_type == nullptr || box_type->instance_klass() != float16_box_type->instance_klass()) {
9839     return nullptr; // box klass is not Float16
9840   }
9841 
9842   // Null check; get notnull casted pointer
9843   Node* null_ctl = top();
9844   Node* not_null_box = null_check_oop(box, &null_ctl, true);
9845   // If not_null_box is dead, only null-path is taken
9846   if (stopped()) {
9847     set_control(null_ctl);
9848     return nullptr;
9849   }
9850   assert(not_null_box->bottom_type()->is_instptr()->maybe_null() == false, "");
9851   const TypePtr* adr_type = C->alias_type(field)->adr_type();
9852   Node* adr = basic_plus_adr(not_null_box, field->offset_in_bytes());
9853   return access_load_at(not_null_box, adr, adr_type, TypeInt::SHORT, T_SHORT, IN_HEAP);
9854 }
9855 
9856 Node* LibraryCallKit::box_fp16_value(const TypeInstPtr* float16_box_type, ciField* field, Node* value) {
9857   PreserveReexecuteState preexecs(this);
9858   jvms()->set_should_reexecute(true);
9859 
9860   const TypeKlassPtr* klass_type = float16_box_type->as_klass_type();
9861   Node* klass_node = makecon(klass_type);
9862   Node* box = new_instance(klass_node);
9863 
9864   Node* value_field = basic_plus_adr(box, field->offset_in_bytes());
9865   const TypePtr* value_adr_type = value_field->bottom_type()->is_ptr();
9866 
9867   Node* field_store = _gvn.transform(access_store_at(box,
9868                                                      value_field,
9869                                                      value_adr_type,
9870                                                      value,
9871                                                      TypeInt::SHORT,
9872                                                      T_SHORT,
9873                                                      IN_HEAP));
9874   set_memory(field_store, value_adr_type);
9875   return box;
9876 }
9877 
9878 bool LibraryCallKit::inline_fp16_operations(vmIntrinsics::ID id, int num_args) {
9879   if (!Matcher::match_rule_supported(Op_ReinterpretS2HF) ||
9880       !Matcher::match_rule_supported(Op_ReinterpretHF2S)) {
9881     return false;
9882   }
9883 
9884   const TypeInstPtr* box_type = _gvn.type(argument(0))->isa_instptr();
9885   if (box_type == nullptr || box_type->const_oop() == nullptr) {
9886     return false;
9887   }
9888 
9889   ciInstanceKlass* float16_klass = box_type->const_oop()->as_instance()->java_lang_Class_klass()->as_instance_klass();
9890   const TypeInstPtr* float16_box_type = TypeInstPtr::make_exact(TypePtr::NotNull, float16_klass);
9891   ciField* field = float16_klass->get_field_by_name(ciSymbols::value_name(),
9892                                                     ciSymbols::short_signature(),
9893                                                     false);
9894   assert(field != nullptr, "");
9895 
9896   // Transformed nodes
9897   Node* fld1 = nullptr;
9898   Node* fld2 = nullptr;
9899   Node* fld3 = nullptr;
9900   switch(num_args) {
9901     case 3:
9902       fld3 = unbox_fp16_value(float16_box_type, field, argument(3));
9903       if (fld3 == nullptr) {
9904         return false;
9905       }
9906       fld3 = _gvn.transform(new ReinterpretS2HFNode(fld3));
9907     // fall-through
9908     case 2:
9909       fld2 = unbox_fp16_value(float16_box_type, field, argument(2));
9910       if (fld2 == nullptr) {
9911         return false;
9912       }
9913       fld2 = _gvn.transform(new ReinterpretS2HFNode(fld2));
9914     // fall-through
9915     case 1:
9916       fld1 = unbox_fp16_value(float16_box_type, field, argument(1));
9917       if (fld1 == nullptr) {
9918         return false;
9919       }
9920       fld1 = _gvn.transform(new ReinterpretS2HFNode(fld1));
9921       break;
9922     default: fatal("Unsupported number of arguments %d", num_args);
9923   }
9924 
9925   Node* result = nullptr;
9926   switch (id) {
9927     // Unary operations
9928     case vmIntrinsics::_sqrt_float16:
9929       result = _gvn.transform(new SqrtHFNode(C, control(), fld1));
9930       break;
9931     // Ternary operations
9932     case vmIntrinsics::_fma_float16:
9933       result = _gvn.transform(new FmaHFNode(fld1, fld2, fld3));
9934       break;
9935     default:
9936       fatal_unexpected_iid(id);
9937       break;
9938   }
9939   result = _gvn.transform(new ReinterpretHF2SNode(result));
9940   set_result(box_fp16_value(float16_box_type, field, result));
9941   return true;
9942 }
9943