1 /*
   2  * Copyright (c) 1999, 2026, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "asm/macroAssembler.hpp"
  26 #include "ci/ciArrayKlass.hpp"
  27 #include "ci/ciFlatArrayKlass.hpp"
  28 #include "ci/ciInstanceKlass.hpp"
  29 #include "ci/ciSymbols.hpp"
  30 #include "ci/ciUtilities.inline.hpp"
  31 #include "classfile/vmIntrinsics.hpp"
  32 #include "compiler/compileBroker.hpp"
  33 #include "compiler/compileLog.hpp"
  34 #include "gc/shared/barrierSet.hpp"
  35 #include "gc/shared/c2/barrierSetC2.hpp"
  36 #include "jfr/support/jfrIntrinsics.hpp"
  37 #include "memory/resourceArea.hpp"
  38 #include "oops/accessDecorators.hpp"
  39 #include "oops/klass.inline.hpp"
  40 #include "oops/layoutKind.hpp"
  41 #include "oops/objArrayKlass.hpp"
  42 #include "opto/addnode.hpp"
  43 #include "opto/arraycopynode.hpp"
  44 #include "opto/c2compiler.hpp"
  45 #include "opto/castnode.hpp"
  46 #include "opto/cfgnode.hpp"
  47 #include "opto/convertnode.hpp"
  48 #include "opto/countbitsnode.hpp"
  49 #include "opto/graphKit.hpp"
  50 #include "opto/idealKit.hpp"
  51 #include "opto/inlinetypenode.hpp"
  52 #include "opto/library_call.hpp"
  53 #include "opto/mathexactnode.hpp"
  54 #include "opto/mulnode.hpp"
  55 #include "opto/narrowptrnode.hpp"
  56 #include "opto/opaquenode.hpp"
  57 #include "opto/opcodes.hpp"
  58 #include "opto/parse.hpp"
  59 #include "opto/rootnode.hpp"
  60 #include "opto/runtime.hpp"
  61 #include "opto/subnode.hpp"
  62 #include "opto/type.hpp"
  63 #include "opto/vectornode.hpp"
  64 #include "prims/jvmtiExport.hpp"
  65 #include "prims/jvmtiThreadState.hpp"
  66 #include "prims/unsafe.hpp"
  67 #include "runtime/globals.hpp"
  68 #include "runtime/jniHandles.inline.hpp"
  69 #include "runtime/mountUnmountDisabler.hpp"
  70 #include "runtime/objectMonitor.hpp"
  71 #include "runtime/sharedRuntime.hpp"
  72 #include "runtime/stubRoutines.hpp"
  73 #include "utilities/globalDefinitions.hpp"
  74 #include "utilities/macros.hpp"
  75 #include "utilities/powerOfTwo.hpp"
  76 
  77 //---------------------------make_vm_intrinsic----------------------------
  78 CallGenerator* Compile::make_vm_intrinsic(ciMethod* m, bool is_virtual) {
  79   vmIntrinsicID id = m->intrinsic_id();
  80   assert(id != vmIntrinsics::_none, "must be a VM intrinsic");
  81 
  82   if (!m->is_loaded()) {
  83     // Do not attempt to inline unloaded methods.
  84     return nullptr;
  85   }
  86 
  87   C2Compiler* compiler = (C2Compiler*)CompileBroker::compiler(CompLevel_full_optimization);
  88   bool is_available = false;
  89 
  90   {
  91     // For calling is_intrinsic_supported and is_intrinsic_disabled_by_flag
  92     // the compiler must transition to '_thread_in_vm' state because both
  93     // methods access VM-internal data.
  94     VM_ENTRY_MARK;
  95     methodHandle mh(THREAD, m->get_Method());
  96     is_available = compiler != nullptr && compiler->is_intrinsic_available(mh, C->directive());
  97     if (is_available && is_virtual) {
  98       is_available = vmIntrinsics::does_virtual_dispatch(id);
  99     }
 100   }
 101 
 102   if (is_available) {
 103     assert(id <= vmIntrinsics::LAST_COMPILER_INLINE, "caller responsibility");
 104     assert(id != vmIntrinsics::_Object_init && id != vmIntrinsics::_invoke, "enum out of order?");
 105     return new LibraryIntrinsic(m, is_virtual,
 106                                 vmIntrinsics::predicates_needed(id),
 107                                 vmIntrinsics::does_virtual_dispatch(id),
 108                                 id);
 109   } else {
 110     return nullptr;
 111   }
 112 }
 113 
 114 JVMState* LibraryIntrinsic::generate(JVMState* jvms) {
 115   LibraryCallKit kit(jvms, this);
 116   Compile* C = kit.C;
 117   int nodes = C->unique();
 118 #ifndef PRODUCT
 119   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
 120     char buf[1000];
 121     const char* str = vmIntrinsics::short_name_as_C_string(intrinsic_id(), buf, sizeof(buf));
 122     tty->print_cr("Intrinsic %s", str);
 123   }
 124 #endif
 125   ciMethod* callee = kit.callee();
 126   const int bci    = kit.bci();
 127 #ifdef ASSERT
 128   Node* ctrl = kit.control();
 129 #endif
 130   // Try to inline the intrinsic.
 131   if (callee->check_intrinsic_candidate() &&
 132       kit.try_to_inline(_last_predicate)) {
 133     const char *inline_msg = is_virtual() ? "(intrinsic, virtual)"
 134                                           : "(intrinsic)";
 135     CompileTask::print_inlining_ul(callee, jvms->depth() - 1, bci, InliningResult::SUCCESS, inline_msg);
 136     C->inline_printer()->record(callee, jvms, InliningResult::SUCCESS, inline_msg);
 137     C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_worked);
 138     if (C->log()) {
 139       C->log()->elem("intrinsic id='%s'%s nodes='%d'",
 140                      vmIntrinsics::name_at(intrinsic_id()),
 141                      (is_virtual() ? " virtual='1'" : ""),
 142                      C->unique() - nodes);
 143     }
 144     // Push the result from the inlined method onto the stack.
 145     kit.push_result();
 146     return kit.transfer_exceptions_into_jvms();
 147   }
 148 
 149   // The intrinsic bailed out
 150   assert(ctrl == kit.control(), "Control flow was added although the intrinsic bailed out");
 151   assert(jvms->map() == kit.map(), "Out of sync JVM state");
 152   if (jvms->has_method()) {
 153     // Not a root compile.
 154     const char* msg;
 155     if (callee->intrinsic_candidate()) {
 156       msg = is_virtual() ? "failed to inline (intrinsic, virtual)" : "failed to inline (intrinsic)";
 157     } else {
 158       msg = is_virtual() ? "failed to inline (intrinsic, virtual), method not annotated"
 159                          : "failed to inline (intrinsic), method not annotated";
 160     }
 161     CompileTask::print_inlining_ul(callee, jvms->depth() - 1, bci, InliningResult::FAILURE, msg);
 162     C->inline_printer()->record(callee, jvms, InliningResult::FAILURE, msg);
 163   } else {
 164     // Root compile
 165     ResourceMark rm;
 166     stringStream msg_stream;
 167     msg_stream.print("Did not generate intrinsic %s%s at bci:%d in",
 168                      vmIntrinsics::name_at(intrinsic_id()),
 169                      is_virtual() ? " (virtual)" : "", bci);
 170     const char *msg = msg_stream.freeze();
 171     log_debug(jit, inlining)("%s", msg);
 172     if (C->print_intrinsics() || C->print_inlining()) {
 173       tty->print("%s", msg);
 174     }
 175   }
 176   C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_failed);
 177 
 178   return nullptr;
 179 }
 180 
 181 Node* LibraryIntrinsic::generate_predicate(JVMState* jvms, int predicate) {
 182   LibraryCallKit kit(jvms, this);
 183   Compile* C = kit.C;
 184   int nodes = C->unique();
 185   _last_predicate = predicate;
 186 #ifndef PRODUCT
 187   assert(is_predicated() && predicate < predicates_count(), "sanity");
 188   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
 189     char buf[1000];
 190     const char* str = vmIntrinsics::short_name_as_C_string(intrinsic_id(), buf, sizeof(buf));
 191     tty->print_cr("Predicate for intrinsic %s", str);
 192   }
 193 #endif
 194   ciMethod* callee = kit.callee();
 195   const int bci    = kit.bci();
 196 
 197   Node* slow_ctl = kit.try_to_predicate(predicate);
 198   if (!kit.failing()) {
 199     const char *inline_msg = is_virtual() ? "(intrinsic, virtual, predicate)"
 200                                           : "(intrinsic, predicate)";
 201     CompileTask::print_inlining_ul(callee, jvms->depth() - 1, bci, InliningResult::SUCCESS, inline_msg);
 202     C->inline_printer()->record(callee, jvms, InliningResult::SUCCESS, inline_msg);
 203 
 204     C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_worked);
 205     if (C->log()) {
 206       C->log()->elem("predicate_intrinsic id='%s'%s nodes='%d'",
 207                      vmIntrinsics::name_at(intrinsic_id()),
 208                      (is_virtual() ? " virtual='1'" : ""),
 209                      C->unique() - nodes);
 210     }
 211     return slow_ctl; // Could be null if the check folds.
 212   }
 213 
 214   // The intrinsic bailed out
 215   if (jvms->has_method()) {
 216     // Not a root compile.
 217     const char* msg = "failed to generate predicate for intrinsic";
 218     CompileTask::print_inlining_ul(kit.callee(), jvms->depth() - 1, bci, InliningResult::FAILURE, msg);
 219     C->inline_printer()->record(kit.callee(), jvms, InliningResult::FAILURE, msg);
 220   } else {
 221     // Root compile
 222     ResourceMark rm;
 223     stringStream msg_stream;
 224     msg_stream.print("Did not generate intrinsic %s%s at bci:%d in",
 225                      vmIntrinsics::name_at(intrinsic_id()),
 226                      is_virtual() ? " (virtual)" : "", bci);
 227     const char *msg = msg_stream.freeze();
 228     log_debug(jit, inlining)("%s", msg);
 229     C->inline_printer()->record(kit.callee(), jvms, InliningResult::FAILURE, msg);
 230   }
 231   C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_failed);
 232   return nullptr;
 233 }
 234 
 235 bool LibraryCallKit::try_to_inline(int predicate) {
 236   // Handle symbolic names for otherwise undistinguished boolean switches:
 237   const bool is_store       = true;
 238   const bool is_compress    = true;
 239   const bool is_static      = true;
 240   const bool is_volatile    = true;
 241 
 242   if (!jvms()->has_method()) {
 243     // Root JVMState has a null method.
 244     assert(map()->memory()->Opcode() == Op_Parm, "");
 245     // Insert the memory aliasing node
 246     set_all_memory(reset_memory());
 247   }
 248   assert(merged_memory(), "");
 249 
 250   switch (intrinsic_id()) {
 251   case vmIntrinsics::_hashCode:                 return inline_native_hashcode(intrinsic()->is_virtual(), !is_static);
 252   case vmIntrinsics::_identityHashCode:         return inline_native_hashcode(/*!virtual*/ false,         is_static);
 253   case vmIntrinsics::_getClass:                 return inline_native_getClass();
 254 
 255   case vmIntrinsics::_ceil:
 256   case vmIntrinsics::_floor:
 257   case vmIntrinsics::_rint:
 258   case vmIntrinsics::_dsin:
 259   case vmIntrinsics::_dcos:
 260   case vmIntrinsics::_dtan:
 261   case vmIntrinsics::_dsinh:
 262   case vmIntrinsics::_dtanh:
 263   case vmIntrinsics::_dcbrt:
 264   case vmIntrinsics::_dabs:
 265   case vmIntrinsics::_fabs:
 266   case vmIntrinsics::_iabs:
 267   case vmIntrinsics::_labs:
 268   case vmIntrinsics::_datan2:
 269   case vmIntrinsics::_dsqrt:
 270   case vmIntrinsics::_dsqrt_strict:
 271   case vmIntrinsics::_dexp:
 272   case vmIntrinsics::_dlog:
 273   case vmIntrinsics::_dlog10:
 274   case vmIntrinsics::_dpow:
 275   case vmIntrinsics::_dcopySign:
 276   case vmIntrinsics::_fcopySign:
 277   case vmIntrinsics::_dsignum:
 278   case vmIntrinsics::_roundF:
 279   case vmIntrinsics::_roundD:
 280   case vmIntrinsics::_fsignum:                  return inline_math_native(intrinsic_id());
 281 
 282   case vmIntrinsics::_notify:
 283   case vmIntrinsics::_notifyAll:
 284     return inline_notify(intrinsic_id());
 285 
 286   case vmIntrinsics::_addExactI:                return inline_math_addExactI(false /* add */);
 287   case vmIntrinsics::_addExactL:                return inline_math_addExactL(false /* add */);
 288   case vmIntrinsics::_decrementExactI:          return inline_math_subtractExactI(true /* decrement */);
 289   case vmIntrinsics::_decrementExactL:          return inline_math_subtractExactL(true /* decrement */);
 290   case vmIntrinsics::_incrementExactI:          return inline_math_addExactI(true /* increment */);
 291   case vmIntrinsics::_incrementExactL:          return inline_math_addExactL(true /* increment */);
 292   case vmIntrinsics::_multiplyExactI:           return inline_math_multiplyExactI();
 293   case vmIntrinsics::_multiplyExactL:           return inline_math_multiplyExactL();
 294   case vmIntrinsics::_multiplyHigh:             return inline_math_multiplyHigh();
 295   case vmIntrinsics::_unsignedMultiplyHigh:     return inline_math_unsignedMultiplyHigh();
 296   case vmIntrinsics::_negateExactI:             return inline_math_negateExactI();
 297   case vmIntrinsics::_negateExactL:             return inline_math_negateExactL();
 298   case vmIntrinsics::_subtractExactI:           return inline_math_subtractExactI(false /* subtract */);
 299   case vmIntrinsics::_subtractExactL:           return inline_math_subtractExactL(false /* subtract */);
 300 
 301   case vmIntrinsics::_arraycopy:                return inline_arraycopy();
 302 
 303   case vmIntrinsics::_arraySort:                return inline_array_sort();
 304   case vmIntrinsics::_arrayPartition:           return inline_array_partition();
 305 
 306   case vmIntrinsics::_compareToL:               return inline_string_compareTo(StrIntrinsicNode::LL);
 307   case vmIntrinsics::_compareToU:               return inline_string_compareTo(StrIntrinsicNode::UU);
 308   case vmIntrinsics::_compareToLU:              return inline_string_compareTo(StrIntrinsicNode::LU);
 309   case vmIntrinsics::_compareToUL:              return inline_string_compareTo(StrIntrinsicNode::UL);
 310 
 311   case vmIntrinsics::_indexOfL:                 return inline_string_indexOf(StrIntrinsicNode::LL);
 312   case vmIntrinsics::_indexOfU:                 return inline_string_indexOf(StrIntrinsicNode::UU);
 313   case vmIntrinsics::_indexOfUL:                return inline_string_indexOf(StrIntrinsicNode::UL);
 314   case vmIntrinsics::_indexOfIL:                return inline_string_indexOfI(StrIntrinsicNode::LL);
 315   case vmIntrinsics::_indexOfIU:                return inline_string_indexOfI(StrIntrinsicNode::UU);
 316   case vmIntrinsics::_indexOfIUL:               return inline_string_indexOfI(StrIntrinsicNode::UL);
 317   case vmIntrinsics::_indexOfU_char:            return inline_string_indexOfChar(StrIntrinsicNode::U);
 318   case vmIntrinsics::_indexOfL_char:            return inline_string_indexOfChar(StrIntrinsicNode::L);
 319 
 320   case vmIntrinsics::_equalsL:                  return inline_string_equals(StrIntrinsicNode::LL);
 321 
 322   case vmIntrinsics::_vectorizedHashCode:       return inline_vectorizedHashCode();
 323 
 324   case vmIntrinsics::_toBytesStringU:           return inline_string_toBytesU();
 325   case vmIntrinsics::_getCharsStringU:          return inline_string_getCharsU();
 326   case vmIntrinsics::_getCharStringU:           return inline_string_char_access(!is_store);
 327   case vmIntrinsics::_putCharStringU:           return inline_string_char_access( is_store);
 328 
 329   case vmIntrinsics::_compressStringC:
 330   case vmIntrinsics::_compressStringB:          return inline_string_copy( is_compress);
 331   case vmIntrinsics::_inflateStringC:
 332   case vmIntrinsics::_inflateStringB:           return inline_string_copy(!is_compress);
 333 
 334   case vmIntrinsics::_getReference:             return inline_unsafe_access(!is_store, T_OBJECT,   Relaxed, false);
 335   case vmIntrinsics::_getBoolean:               return inline_unsafe_access(!is_store, T_BOOLEAN,  Relaxed, false);
 336   case vmIntrinsics::_getByte:                  return inline_unsafe_access(!is_store, T_BYTE,     Relaxed, false);
 337   case vmIntrinsics::_getShort:                 return inline_unsafe_access(!is_store, T_SHORT,    Relaxed, false);
 338   case vmIntrinsics::_getChar:                  return inline_unsafe_access(!is_store, T_CHAR,     Relaxed, false);
 339   case vmIntrinsics::_getInt:                   return inline_unsafe_access(!is_store, T_INT,      Relaxed, false);
 340   case vmIntrinsics::_getLong:                  return inline_unsafe_access(!is_store, T_LONG,     Relaxed, false);
 341   case vmIntrinsics::_getFloat:                 return inline_unsafe_access(!is_store, T_FLOAT,    Relaxed, false);
 342   case vmIntrinsics::_getDouble:                return inline_unsafe_access(!is_store, T_DOUBLE,   Relaxed, false);
 343 
 344   case vmIntrinsics::_putReference:             return inline_unsafe_access( is_store, T_OBJECT,   Relaxed, false);
 345   case vmIntrinsics::_putBoolean:               return inline_unsafe_access( is_store, T_BOOLEAN,  Relaxed, false);
 346   case vmIntrinsics::_putByte:                  return inline_unsafe_access( is_store, T_BYTE,     Relaxed, false);
 347   case vmIntrinsics::_putShort:                 return inline_unsafe_access( is_store, T_SHORT,    Relaxed, false);
 348   case vmIntrinsics::_putChar:                  return inline_unsafe_access( is_store, T_CHAR,     Relaxed, false);
 349   case vmIntrinsics::_putInt:                   return inline_unsafe_access( is_store, T_INT,      Relaxed, false);
 350   case vmIntrinsics::_putLong:                  return inline_unsafe_access( is_store, T_LONG,     Relaxed, false);
 351   case vmIntrinsics::_putFloat:                 return inline_unsafe_access( is_store, T_FLOAT,    Relaxed, false);
 352   case vmIntrinsics::_putDouble:                return inline_unsafe_access( is_store, T_DOUBLE,   Relaxed, false);
 353 
 354   case vmIntrinsics::_getReferenceVolatile:     return inline_unsafe_access(!is_store, T_OBJECT,   Volatile, false);
 355   case vmIntrinsics::_getBooleanVolatile:       return inline_unsafe_access(!is_store, T_BOOLEAN,  Volatile, false);
 356   case vmIntrinsics::_getByteVolatile:          return inline_unsafe_access(!is_store, T_BYTE,     Volatile, false);
 357   case vmIntrinsics::_getShortVolatile:         return inline_unsafe_access(!is_store, T_SHORT,    Volatile, false);
 358   case vmIntrinsics::_getCharVolatile:          return inline_unsafe_access(!is_store, T_CHAR,     Volatile, false);
 359   case vmIntrinsics::_getIntVolatile:           return inline_unsafe_access(!is_store, T_INT,      Volatile, false);
 360   case vmIntrinsics::_getLongVolatile:          return inline_unsafe_access(!is_store, T_LONG,     Volatile, false);
 361   case vmIntrinsics::_getFloatVolatile:         return inline_unsafe_access(!is_store, T_FLOAT,    Volatile, false);
 362   case vmIntrinsics::_getDoubleVolatile:        return inline_unsafe_access(!is_store, T_DOUBLE,   Volatile, false);
 363 
 364   case vmIntrinsics::_putReferenceVolatile:     return inline_unsafe_access( is_store, T_OBJECT,   Volatile, false);
 365   case vmIntrinsics::_putBooleanVolatile:       return inline_unsafe_access( is_store, T_BOOLEAN,  Volatile, false);
 366   case vmIntrinsics::_putByteVolatile:          return inline_unsafe_access( is_store, T_BYTE,     Volatile, false);
 367   case vmIntrinsics::_putShortVolatile:         return inline_unsafe_access( is_store, T_SHORT,    Volatile, false);
 368   case vmIntrinsics::_putCharVolatile:          return inline_unsafe_access( is_store, T_CHAR,     Volatile, false);
 369   case vmIntrinsics::_putIntVolatile:           return inline_unsafe_access( is_store, T_INT,      Volatile, false);
 370   case vmIntrinsics::_putLongVolatile:          return inline_unsafe_access( is_store, T_LONG,     Volatile, false);
 371   case vmIntrinsics::_putFloatVolatile:         return inline_unsafe_access( is_store, T_FLOAT,    Volatile, false);
 372   case vmIntrinsics::_putDoubleVolatile:        return inline_unsafe_access( is_store, T_DOUBLE,   Volatile, false);
 373 
 374   case vmIntrinsics::_getShortUnaligned:        return inline_unsafe_access(!is_store, T_SHORT,    Relaxed, true);
 375   case vmIntrinsics::_getCharUnaligned:         return inline_unsafe_access(!is_store, T_CHAR,     Relaxed, true);
 376   case vmIntrinsics::_getIntUnaligned:          return inline_unsafe_access(!is_store, T_INT,      Relaxed, true);
 377   case vmIntrinsics::_getLongUnaligned:         return inline_unsafe_access(!is_store, T_LONG,     Relaxed, true);
 378 
 379   case vmIntrinsics::_putShortUnaligned:        return inline_unsafe_access( is_store, T_SHORT,    Relaxed, true);
 380   case vmIntrinsics::_putCharUnaligned:         return inline_unsafe_access( is_store, T_CHAR,     Relaxed, true);
 381   case vmIntrinsics::_putIntUnaligned:          return inline_unsafe_access( is_store, T_INT,      Relaxed, true);
 382   case vmIntrinsics::_putLongUnaligned:         return inline_unsafe_access( is_store, T_LONG,     Relaxed, true);
 383 
 384   case vmIntrinsics::_getReferenceAcquire:      return inline_unsafe_access(!is_store, T_OBJECT,   Acquire, false);
 385   case vmIntrinsics::_getBooleanAcquire:        return inline_unsafe_access(!is_store, T_BOOLEAN,  Acquire, false);
 386   case vmIntrinsics::_getByteAcquire:           return inline_unsafe_access(!is_store, T_BYTE,     Acquire, false);
 387   case vmIntrinsics::_getShortAcquire:          return inline_unsafe_access(!is_store, T_SHORT,    Acquire, false);
 388   case vmIntrinsics::_getCharAcquire:           return inline_unsafe_access(!is_store, T_CHAR,     Acquire, false);
 389   case vmIntrinsics::_getIntAcquire:            return inline_unsafe_access(!is_store, T_INT,      Acquire, false);
 390   case vmIntrinsics::_getLongAcquire:           return inline_unsafe_access(!is_store, T_LONG,     Acquire, false);
 391   case vmIntrinsics::_getFloatAcquire:          return inline_unsafe_access(!is_store, T_FLOAT,    Acquire, false);
 392   case vmIntrinsics::_getDoubleAcquire:         return inline_unsafe_access(!is_store, T_DOUBLE,   Acquire, false);
 393 
 394   case vmIntrinsics::_putReferenceRelease:      return inline_unsafe_access( is_store, T_OBJECT,   Release, false);
 395   case vmIntrinsics::_putBooleanRelease:        return inline_unsafe_access( is_store, T_BOOLEAN,  Release, false);
 396   case vmIntrinsics::_putByteRelease:           return inline_unsafe_access( is_store, T_BYTE,     Release, false);
 397   case vmIntrinsics::_putShortRelease:          return inline_unsafe_access( is_store, T_SHORT,    Release, false);
 398   case vmIntrinsics::_putCharRelease:           return inline_unsafe_access( is_store, T_CHAR,     Release, false);
 399   case vmIntrinsics::_putIntRelease:            return inline_unsafe_access( is_store, T_INT,      Release, false);
 400   case vmIntrinsics::_putLongRelease:           return inline_unsafe_access( is_store, T_LONG,     Release, false);
 401   case vmIntrinsics::_putFloatRelease:          return inline_unsafe_access( is_store, T_FLOAT,    Release, false);
 402   case vmIntrinsics::_putDoubleRelease:         return inline_unsafe_access( is_store, T_DOUBLE,   Release, false);
 403 
 404   case vmIntrinsics::_getReferenceOpaque:       return inline_unsafe_access(!is_store, T_OBJECT,   Opaque, false);
 405   case vmIntrinsics::_getBooleanOpaque:         return inline_unsafe_access(!is_store, T_BOOLEAN,  Opaque, false);
 406   case vmIntrinsics::_getByteOpaque:            return inline_unsafe_access(!is_store, T_BYTE,     Opaque, false);
 407   case vmIntrinsics::_getShortOpaque:           return inline_unsafe_access(!is_store, T_SHORT,    Opaque, false);
 408   case vmIntrinsics::_getCharOpaque:            return inline_unsafe_access(!is_store, T_CHAR,     Opaque, false);
 409   case vmIntrinsics::_getIntOpaque:             return inline_unsafe_access(!is_store, T_INT,      Opaque, false);
 410   case vmIntrinsics::_getLongOpaque:            return inline_unsafe_access(!is_store, T_LONG,     Opaque, false);
 411   case vmIntrinsics::_getFloatOpaque:           return inline_unsafe_access(!is_store, T_FLOAT,    Opaque, false);
 412   case vmIntrinsics::_getDoubleOpaque:          return inline_unsafe_access(!is_store, T_DOUBLE,   Opaque, false);
 413 
 414   case vmIntrinsics::_putReferenceOpaque:       return inline_unsafe_access( is_store, T_OBJECT,   Opaque, false);
 415   case vmIntrinsics::_putBooleanOpaque:         return inline_unsafe_access( is_store, T_BOOLEAN,  Opaque, false);
 416   case vmIntrinsics::_putByteOpaque:            return inline_unsafe_access( is_store, T_BYTE,     Opaque, false);
 417   case vmIntrinsics::_putShortOpaque:           return inline_unsafe_access( is_store, T_SHORT,    Opaque, false);
 418   case vmIntrinsics::_putCharOpaque:            return inline_unsafe_access( is_store, T_CHAR,     Opaque, false);
 419   case vmIntrinsics::_putIntOpaque:             return inline_unsafe_access( is_store, T_INT,      Opaque, false);
 420   case vmIntrinsics::_putLongOpaque:            return inline_unsafe_access( is_store, T_LONG,     Opaque, false);
 421   case vmIntrinsics::_putFloatOpaque:           return inline_unsafe_access( is_store, T_FLOAT,    Opaque, false);
 422   case vmIntrinsics::_putDoubleOpaque:          return inline_unsafe_access( is_store, T_DOUBLE,   Opaque, false);
 423 
 424   case vmIntrinsics::_getFlatValue:             return inline_unsafe_flat_access(!is_store, Relaxed);
 425   case vmIntrinsics::_putFlatValue:             return inline_unsafe_flat_access( is_store, Relaxed);
 426 
 427   case vmIntrinsics::_compareAndSetReference:   return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap,      Volatile);
 428   case vmIntrinsics::_compareAndSetByte:        return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap,      Volatile);
 429   case vmIntrinsics::_compareAndSetShort:       return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap,      Volatile);
 430   case vmIntrinsics::_compareAndSetInt:         return inline_unsafe_load_store(T_INT,    LS_cmp_swap,      Volatile);
 431   case vmIntrinsics::_compareAndSetLong:        return inline_unsafe_load_store(T_LONG,   LS_cmp_swap,      Volatile);
 432 
 433   case vmIntrinsics::_weakCompareAndSetReferencePlain:     return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Relaxed);
 434   case vmIntrinsics::_weakCompareAndSetReferenceAcquire:   return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Acquire);
 435   case vmIntrinsics::_weakCompareAndSetReferenceRelease:   return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Release);
 436   case vmIntrinsics::_weakCompareAndSetReference:          return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Volatile);
 437   case vmIntrinsics::_weakCompareAndSetBytePlain:          return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap_weak, Relaxed);
 438   case vmIntrinsics::_weakCompareAndSetByteAcquire:        return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap_weak, Acquire);
 439   case vmIntrinsics::_weakCompareAndSetByteRelease:        return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap_weak, Release);
 440   case vmIntrinsics::_weakCompareAndSetByte:               return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap_weak, Volatile);
 441   case vmIntrinsics::_weakCompareAndSetShortPlain:         return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap_weak, Relaxed);
 442   case vmIntrinsics::_weakCompareAndSetShortAcquire:       return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap_weak, Acquire);
 443   case vmIntrinsics::_weakCompareAndSetShortRelease:       return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap_weak, Release);
 444   case vmIntrinsics::_weakCompareAndSetShort:              return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap_weak, Volatile);
 445   case vmIntrinsics::_weakCompareAndSetIntPlain:           return inline_unsafe_load_store(T_INT,    LS_cmp_swap_weak, Relaxed);
 446   case vmIntrinsics::_weakCompareAndSetIntAcquire:         return inline_unsafe_load_store(T_INT,    LS_cmp_swap_weak, Acquire);
 447   case vmIntrinsics::_weakCompareAndSetIntRelease:         return inline_unsafe_load_store(T_INT,    LS_cmp_swap_weak, Release);
 448   case vmIntrinsics::_weakCompareAndSetInt:                return inline_unsafe_load_store(T_INT,    LS_cmp_swap_weak, Volatile);
 449   case vmIntrinsics::_weakCompareAndSetLongPlain:          return inline_unsafe_load_store(T_LONG,   LS_cmp_swap_weak, Relaxed);
 450   case vmIntrinsics::_weakCompareAndSetLongAcquire:        return inline_unsafe_load_store(T_LONG,   LS_cmp_swap_weak, Acquire);
 451   case vmIntrinsics::_weakCompareAndSetLongRelease:        return inline_unsafe_load_store(T_LONG,   LS_cmp_swap_weak, Release);
 452   case vmIntrinsics::_weakCompareAndSetLong:               return inline_unsafe_load_store(T_LONG,   LS_cmp_swap_weak, Volatile);
 453 
 454   case vmIntrinsics::_compareAndExchangeReference:         return inline_unsafe_load_store(T_OBJECT, LS_cmp_exchange,  Volatile);
 455   case vmIntrinsics::_compareAndExchangeReferenceAcquire:  return inline_unsafe_load_store(T_OBJECT, LS_cmp_exchange,  Acquire);
 456   case vmIntrinsics::_compareAndExchangeReferenceRelease:  return inline_unsafe_load_store(T_OBJECT, LS_cmp_exchange,  Release);
 457   case vmIntrinsics::_compareAndExchangeByte:              return inline_unsafe_load_store(T_BYTE,   LS_cmp_exchange,  Volatile);
 458   case vmIntrinsics::_compareAndExchangeByteAcquire:       return inline_unsafe_load_store(T_BYTE,   LS_cmp_exchange,  Acquire);
 459   case vmIntrinsics::_compareAndExchangeByteRelease:       return inline_unsafe_load_store(T_BYTE,   LS_cmp_exchange,  Release);
 460   case vmIntrinsics::_compareAndExchangeShort:             return inline_unsafe_load_store(T_SHORT,  LS_cmp_exchange,  Volatile);
 461   case vmIntrinsics::_compareAndExchangeShortAcquire:      return inline_unsafe_load_store(T_SHORT,  LS_cmp_exchange,  Acquire);
 462   case vmIntrinsics::_compareAndExchangeShortRelease:      return inline_unsafe_load_store(T_SHORT,  LS_cmp_exchange,  Release);
 463   case vmIntrinsics::_compareAndExchangeInt:               return inline_unsafe_load_store(T_INT,    LS_cmp_exchange,  Volatile);
 464   case vmIntrinsics::_compareAndExchangeIntAcquire:        return inline_unsafe_load_store(T_INT,    LS_cmp_exchange,  Acquire);
 465   case vmIntrinsics::_compareAndExchangeIntRelease:        return inline_unsafe_load_store(T_INT,    LS_cmp_exchange,  Release);
 466   case vmIntrinsics::_compareAndExchangeLong:              return inline_unsafe_load_store(T_LONG,   LS_cmp_exchange,  Volatile);
 467   case vmIntrinsics::_compareAndExchangeLongAcquire:       return inline_unsafe_load_store(T_LONG,   LS_cmp_exchange,  Acquire);
 468   case vmIntrinsics::_compareAndExchangeLongRelease:       return inline_unsafe_load_store(T_LONG,   LS_cmp_exchange,  Release);
 469 
 470   case vmIntrinsics::_getAndAddByte:                    return inline_unsafe_load_store(T_BYTE,   LS_get_add,       Volatile);
 471   case vmIntrinsics::_getAndAddShort:                   return inline_unsafe_load_store(T_SHORT,  LS_get_add,       Volatile);
 472   case vmIntrinsics::_getAndAddInt:                     return inline_unsafe_load_store(T_INT,    LS_get_add,       Volatile);
 473   case vmIntrinsics::_getAndAddLong:                    return inline_unsafe_load_store(T_LONG,   LS_get_add,       Volatile);
 474 
 475   case vmIntrinsics::_getAndSetByte:                    return inline_unsafe_load_store(T_BYTE,   LS_get_set,       Volatile);
 476   case vmIntrinsics::_getAndSetShort:                   return inline_unsafe_load_store(T_SHORT,  LS_get_set,       Volatile);
 477   case vmIntrinsics::_getAndSetInt:                     return inline_unsafe_load_store(T_INT,    LS_get_set,       Volatile);
 478   case vmIntrinsics::_getAndSetLong:                    return inline_unsafe_load_store(T_LONG,   LS_get_set,       Volatile);
 479   case vmIntrinsics::_getAndSetReference:               return inline_unsafe_load_store(T_OBJECT, LS_get_set,       Volatile);
 480 
 481   case vmIntrinsics::_loadFence:
 482   case vmIntrinsics::_storeFence:
 483   case vmIntrinsics::_storeStoreFence:
 484   case vmIntrinsics::_fullFence:                return inline_unsafe_fence(intrinsic_id());
 485 
 486   case vmIntrinsics::_arrayInstanceBaseOffset:  return inline_arrayInstanceBaseOffset();
 487   case vmIntrinsics::_arrayInstanceIndexScale:  return inline_arrayInstanceIndexScale();
 488   case vmIntrinsics::_arrayLayout:              return inline_arrayLayout();
 489   case vmIntrinsics::_getFieldMap:              return inline_getFieldMap();
 490 
 491   case vmIntrinsics::_onSpinWait:               return inline_onspinwait();
 492 
 493   case vmIntrinsics::_currentCarrierThread:     return inline_native_currentCarrierThread();
 494   case vmIntrinsics::_currentThread:            return inline_native_currentThread();
 495   case vmIntrinsics::_setCurrentThread:         return inline_native_setCurrentThread();
 496 
 497   case vmIntrinsics::_scopedValueCache:          return inline_native_scopedValueCache();
 498   case vmIntrinsics::_setScopedValueCache:       return inline_native_setScopedValueCache();
 499 
 500   case vmIntrinsics::_Continuation_pin:          return inline_native_Continuation_pinning(false);
 501   case vmIntrinsics::_Continuation_unpin:        return inline_native_Continuation_pinning(true);
 502 
 503   case vmIntrinsics::_vthreadEndFirstTransition:    return inline_native_vthread_end_transition(CAST_FROM_FN_PTR(address, OptoRuntime::vthread_end_first_transition_Java()),
 504                                                                                                 "endFirstTransition", true);
 505   case vmIntrinsics::_vthreadStartFinalTransition:  return inline_native_vthread_start_transition(CAST_FROM_FN_PTR(address, OptoRuntime::vthread_start_final_transition_Java()),
 506                                                                                                   "startFinalTransition", true);
 507   case vmIntrinsics::_vthreadStartTransition:       return inline_native_vthread_start_transition(CAST_FROM_FN_PTR(address, OptoRuntime::vthread_start_transition_Java()),
 508                                                                                                   "startTransition", false);
 509   case vmIntrinsics::_vthreadEndTransition:         return inline_native_vthread_end_transition(CAST_FROM_FN_PTR(address, OptoRuntime::vthread_end_transition_Java()),
 510                                                                                                 "endTransition", false);
 511 #if INCLUDE_JVMTI
 512   case vmIntrinsics::_notifyJvmtiVThreadDisableSuspend: return inline_native_notify_jvmti_sync();
 513 #endif
 514 
 515 #ifdef JFR_HAVE_INTRINSICS
 516   case vmIntrinsics::_counterTime:              return inline_native_time_funcs(CAST_FROM_FN_PTR(address, JfrTime::time_function()), "counterTime");
 517   case vmIntrinsics::_getEventWriter:           return inline_native_getEventWriter();
 518   case vmIntrinsics::_jvm_commit:               return inline_native_jvm_commit();
 519   case vmIntrinsics::_tryUpdateEpochField:      return inline_native_try_update_epoch();
 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::_Reference_reachabilityFence: return inline_reference_reachabilityFence();
 599   case vmIntrinsics::_PhantomReference_refersTo0: return inline_reference_refersTo0(true);
 600   case vmIntrinsics::_Reference_clear0:         return inline_reference_clear0(false);
 601   case vmIntrinsics::_PhantomReference_clear0:  return inline_reference_clear0(true);
 602 
 603   case vmIntrinsics::_Class_cast:               return inline_Class_cast();
 604 
 605   case vmIntrinsics::_aescrypt_encryptBlock:
 606   case vmIntrinsics::_aescrypt_decryptBlock:    return inline_aescrypt_Block(intrinsic_id());
 607 
 608   case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
 609   case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
 610     return inline_cipherBlockChaining_AESCrypt(intrinsic_id());
 611 
 612   case vmIntrinsics::_electronicCodeBook_encryptAESCrypt:
 613   case vmIntrinsics::_electronicCodeBook_decryptAESCrypt:
 614     return inline_electronicCodeBook_AESCrypt(intrinsic_id());
 615 
 616   case vmIntrinsics::_counterMode_AESCrypt:
 617     return inline_counterMode_AESCrypt(intrinsic_id());
 618 
 619   case vmIntrinsics::_galoisCounterMode_AESCrypt:
 620     return inline_galoisCounterMode_AESCrypt();
 621 
 622   case vmIntrinsics::_md5_implCompress:
 623   case vmIntrinsics::_sha_implCompress:
 624   case vmIntrinsics::_sha2_implCompress:
 625   case vmIntrinsics::_sha5_implCompress:
 626   case vmIntrinsics::_sha3_implCompress:
 627     return inline_digestBase_implCompress(intrinsic_id());
 628   case vmIntrinsics::_double_keccak:
 629     return inline_double_keccak();
 630 
 631   case vmIntrinsics::_digestBase_implCompressMB:
 632     return inline_digestBase_implCompressMB(predicate);
 633 
 634   case vmIntrinsics::_multiplyToLen:
 635     return inline_multiplyToLen();
 636 
 637   case vmIntrinsics::_squareToLen:
 638     return inline_squareToLen();
 639 
 640   case vmIntrinsics::_mulAdd:
 641     return inline_mulAdd();
 642 
 643   case vmIntrinsics::_montgomeryMultiply:
 644     return inline_montgomeryMultiply();
 645   case vmIntrinsics::_montgomerySquare:
 646     return inline_montgomerySquare();
 647 
 648   case vmIntrinsics::_bigIntegerRightShiftWorker:
 649     return inline_bigIntegerShift(true);
 650   case vmIntrinsics::_bigIntegerLeftShiftWorker:
 651     return inline_bigIntegerShift(false);
 652 
 653   case vmIntrinsics::_vectorizedMismatch:
 654     return inline_vectorizedMismatch();
 655 
 656   case vmIntrinsics::_ghash_processBlocks:
 657     return inline_ghash_processBlocks();
 658   case vmIntrinsics::_chacha20Block:
 659     return inline_chacha20Block();
 660   case vmIntrinsics::_kyberNtt:
 661     return inline_kyberNtt();
 662   case vmIntrinsics::_kyberInverseNtt:
 663     return inline_kyberInverseNtt();
 664   case vmIntrinsics::_kyberNttMult:
 665     return inline_kyberNttMult();
 666   case vmIntrinsics::_kyberAddPoly_2:
 667     return inline_kyberAddPoly_2();
 668   case vmIntrinsics::_kyberAddPoly_3:
 669     return inline_kyberAddPoly_3();
 670   case vmIntrinsics::_kyber12To16:
 671     return inline_kyber12To16();
 672   case vmIntrinsics::_kyberBarrettReduce:
 673     return inline_kyberBarrettReduce();
 674   case vmIntrinsics::_dilithiumAlmostNtt:
 675     return inline_dilithiumAlmostNtt();
 676   case vmIntrinsics::_dilithiumAlmostInverseNtt:
 677     return inline_dilithiumAlmostInverseNtt();
 678   case vmIntrinsics::_dilithiumNttMult:
 679     return inline_dilithiumNttMult();
 680   case vmIntrinsics::_dilithiumMontMulByConstant:
 681     return inline_dilithiumMontMulByConstant();
 682   case vmIntrinsics::_dilithiumDecomposePoly:
 683     return inline_dilithiumDecomposePoly();
 684   case vmIntrinsics::_base64_encodeBlock:
 685     return inline_base64_encodeBlock();
 686   case vmIntrinsics::_base64_decodeBlock:
 687     return inline_base64_decodeBlock();
 688   case vmIntrinsics::_poly1305_processBlocks:
 689     return inline_poly1305_processBlocks();
 690   case vmIntrinsics::_intpoly_montgomeryMult_P256:
 691     return inline_intpoly_montgomeryMult_P256();
 692   case vmIntrinsics::_intpoly_assign:
 693     return inline_intpoly_assign();
 694   case vmIntrinsics::_encodeISOArray:
 695   case vmIntrinsics::_encodeByteISOArray:
 696     return inline_encodeISOArray(false);
 697   case vmIntrinsics::_encodeAsciiArray:
 698     return inline_encodeISOArray(true);
 699 
 700   case vmIntrinsics::_updateCRC32:
 701     return inline_updateCRC32();
 702   case vmIntrinsics::_updateBytesCRC32:
 703     return inline_updateBytesCRC32();
 704   case vmIntrinsics::_updateByteBufferCRC32:
 705     return inline_updateByteBufferCRC32();
 706 
 707   case vmIntrinsics::_updateBytesCRC32C:
 708     return inline_updateBytesCRC32C();
 709   case vmIntrinsics::_updateDirectByteBufferCRC32C:
 710     return inline_updateDirectByteBufferCRC32C();
 711 
 712   case vmIntrinsics::_updateBytesAdler32:
 713     return inline_updateBytesAdler32();
 714   case vmIntrinsics::_updateByteBufferAdler32:
 715     return inline_updateByteBufferAdler32();
 716 
 717   case vmIntrinsics::_profileBoolean:
 718     return inline_profileBoolean();
 719   case vmIntrinsics::_isCompileConstant:
 720     return inline_isCompileConstant();
 721 
 722   case vmIntrinsics::_countPositives:
 723     return inline_countPositives();
 724 
 725   case vmIntrinsics::_fmaD:
 726   case vmIntrinsics::_fmaF:
 727     return inline_fma(intrinsic_id());
 728 
 729   case vmIntrinsics::_isDigit:
 730   case vmIntrinsics::_isLowerCase:
 731   case vmIntrinsics::_isUpperCase:
 732   case vmIntrinsics::_isWhitespace:
 733     return inline_character_compare(intrinsic_id());
 734 
 735   case vmIntrinsics::_min:
 736   case vmIntrinsics::_max:
 737   case vmIntrinsics::_min_strict:
 738   case vmIntrinsics::_max_strict:
 739   case vmIntrinsics::_minL:
 740   case vmIntrinsics::_maxL:
 741   case vmIntrinsics::_minF:
 742   case vmIntrinsics::_maxF:
 743   case vmIntrinsics::_minD:
 744   case vmIntrinsics::_maxD:
 745   case vmIntrinsics::_minF_strict:
 746   case vmIntrinsics::_maxF_strict:
 747   case vmIntrinsics::_minD_strict:
 748   case vmIntrinsics::_maxD_strict:
 749     return inline_min_max(intrinsic_id());
 750 
 751   case vmIntrinsics::_VectorUnaryOp:
 752     return inline_vector_nary_operation(1);
 753   case vmIntrinsics::_VectorBinaryOp:
 754     return inline_vector_nary_operation(2);
 755   case vmIntrinsics::_VectorUnaryLibOp:
 756     return inline_vector_call(1);
 757   case vmIntrinsics::_VectorBinaryLibOp:
 758     return inline_vector_call(2);
 759   case vmIntrinsics::_VectorTernaryOp:
 760     return inline_vector_nary_operation(3);
 761   case vmIntrinsics::_VectorFromBitsCoerced:
 762     return inline_vector_frombits_coerced();
 763   case vmIntrinsics::_VectorMaskOp:
 764     return inline_vector_mask_operation();
 765   case vmIntrinsics::_VectorLoadOp:
 766     return inline_vector_mem_operation(/*is_store=*/false);
 767   case vmIntrinsics::_VectorLoadMaskedOp:
 768     return inline_vector_mem_masked_operation(/*is_store*/false);
 769   case vmIntrinsics::_VectorStoreOp:
 770     return inline_vector_mem_operation(/*is_store=*/true);
 771   case vmIntrinsics::_VectorStoreMaskedOp:
 772     return inline_vector_mem_masked_operation(/*is_store=*/true);
 773   case vmIntrinsics::_VectorGatherOp:
 774     return inline_vector_gather_scatter(/*is_scatter*/ false);
 775   case vmIntrinsics::_VectorScatterOp:
 776     return inline_vector_gather_scatter(/*is_scatter*/ true);
 777   case vmIntrinsics::_VectorReductionCoerced:
 778     return inline_vector_reduction();
 779   case vmIntrinsics::_VectorTest:
 780     return inline_vector_test();
 781   case vmIntrinsics::_VectorBlend:
 782     return inline_vector_blend();
 783   case vmIntrinsics::_VectorRearrange:
 784     return inline_vector_rearrange();
 785   case vmIntrinsics::_VectorSelectFrom:
 786     return inline_vector_select_from();
 787   case vmIntrinsics::_VectorCompare:
 788     return inline_vector_compare();
 789   case vmIntrinsics::_VectorBroadcastInt:
 790     return inline_vector_broadcast_int();
 791   case vmIntrinsics::_VectorConvert:
 792     return inline_vector_convert();
 793   case vmIntrinsics::_VectorInsert:
 794     return inline_vector_insert();
 795   case vmIntrinsics::_VectorExtract:
 796     return inline_vector_extract();
 797   case vmIntrinsics::_VectorCompressExpand:
 798     return inline_vector_compress_expand();
 799   case vmIntrinsics::_VectorSelectFromTwoVectorOp:
 800     return inline_vector_select_from_two_vectors();
 801   case vmIntrinsics::_IndexVector:
 802     return inline_index_vector();
 803   case vmIntrinsics::_IndexPartiallyInUpperRange:
 804     return inline_index_partially_in_upper_range();
 805 
 806   case vmIntrinsics::_getObjectSize:
 807     return inline_getObjectSize();
 808 
 809   case vmIntrinsics::_blackhole:
 810     return inline_blackhole();
 811 
 812   default:
 813     // If you get here, it may be that someone has added a new intrinsic
 814     // to the list in vmIntrinsics.hpp without implementing it here.
 815 #ifndef PRODUCT
 816     if ((PrintMiscellaneous && (Verbose || WizardMode)) || PrintOpto) {
 817       tty->print_cr("*** Warning: Unimplemented intrinsic %s(%d)",
 818                     vmIntrinsics::name_at(intrinsic_id()), vmIntrinsics::as_int(intrinsic_id()));
 819     }
 820 #endif
 821     return false;
 822   }
 823 }
 824 
 825 Node* LibraryCallKit::try_to_predicate(int predicate) {
 826   if (!jvms()->has_method()) {
 827     // Root JVMState has a null method.
 828     assert(map()->memory()->Opcode() == Op_Parm, "");
 829     // Insert the memory aliasing node
 830     set_all_memory(reset_memory());
 831   }
 832   assert(merged_memory(), "");
 833 
 834   switch (intrinsic_id()) {
 835   case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
 836     return inline_cipherBlockChaining_AESCrypt_predicate(false);
 837   case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
 838     return inline_cipherBlockChaining_AESCrypt_predicate(true);
 839   case vmIntrinsics::_electronicCodeBook_encryptAESCrypt:
 840     return inline_electronicCodeBook_AESCrypt_predicate(false);
 841   case vmIntrinsics::_electronicCodeBook_decryptAESCrypt:
 842     return inline_electronicCodeBook_AESCrypt_predicate(true);
 843   case vmIntrinsics::_counterMode_AESCrypt:
 844     return inline_counterMode_AESCrypt_predicate();
 845   case vmIntrinsics::_digestBase_implCompressMB:
 846     return inline_digestBase_implCompressMB_predicate(predicate);
 847   case vmIntrinsics::_galoisCounterMode_AESCrypt:
 848     return inline_galoisCounterMode_AESCrypt_predicate();
 849 
 850   default:
 851     // If you get here, it may be that someone has added a new intrinsic
 852     // to the list in vmIntrinsics.hpp without implementing it here.
 853 #ifndef PRODUCT
 854     if ((PrintMiscellaneous && (Verbose || WizardMode)) || PrintOpto) {
 855       tty->print_cr("*** Warning: Unimplemented predicate for intrinsic %s(%d)",
 856                     vmIntrinsics::name_at(intrinsic_id()), vmIntrinsics::as_int(intrinsic_id()));
 857     }
 858 #endif
 859     Node* slow_ctl = control();
 860     set_control(top()); // No fast path intrinsic
 861     return slow_ctl;
 862   }
 863 }
 864 
 865 //------------------------------set_result-------------------------------
 866 // Helper function for finishing intrinsics.
 867 void LibraryCallKit::set_result(RegionNode* region, PhiNode* value) {
 868   record_for_igvn(region);
 869   set_control(_gvn.transform(region));
 870   set_result( _gvn.transform(value));
 871   assert(value->type()->basic_type() == result()->bottom_type()->basic_type(), "sanity");
 872 }
 873 
 874 RegionNode* LibraryCallKit::create_bailout() {
 875   RegionNode* bailout = new RegionNode(1);
 876   record_for_igvn(bailout);
 877   return bailout;
 878 }
 879 
 880 bool LibraryCallKit::check_bailout(RegionNode* bailout) {
 881   if (bailout->req() > 1) {
 882     bailout = _gvn.transform(bailout)->as_Region();
 883     Node* frame = _gvn.transform(new ParmNode(C->start(), TypeFunc::FramePtr));
 884     Node* halt = _gvn.transform(new HaltNode(bailout, frame, "unexpected guard failure in intrinsic"));
 885     C->root()->add_req(halt);
 886   }
 887   return stopped();
 888 }
 889 
 890 //------------------------------generate_guard---------------------------
 891 // Helper function for generating guarded fast-slow graph structures.
 892 // The given 'test', if true, guards a slow path.  If the test fails
 893 // then a fast path can be taken.  (We generally hope it fails.)
 894 // In all cases, GraphKit::control() is updated to the fast path.
 895 // The returned value represents the control for the slow path.
 896 // The return value is never 'top'; it is either a valid control
 897 // or null if it is obvious that the slow path can never be taken.
 898 // Also, if region and the slow control are not null, the slow edge
 899 // is appended to the region.
 900 Node* LibraryCallKit::generate_guard(Node* test, RegionNode* region, float true_prob) {
 901   if (stopped()) {
 902     // Already short circuited.
 903     return nullptr;
 904   }
 905 
 906   // Build an if node and its projections.
 907   // If test is true we take the slow path, which we assume is uncommon.
 908   if (_gvn.type(test) == TypeInt::ZERO) {
 909     // The slow branch is never taken.  No need to build this guard.
 910     return nullptr;
 911   }
 912 
 913   IfNode* iff = create_and_map_if(control(), test, true_prob, COUNT_UNKNOWN);
 914 
 915   Node* if_slow = _gvn.transform(new IfTrueNode(iff));
 916   if (if_slow == top()) {
 917     // The slow branch is never taken.  No need to build this guard.
 918     return nullptr;
 919   }
 920 
 921   if (region != nullptr)
 922     region->add_req(if_slow);
 923 
 924   Node* if_fast = _gvn.transform(new IfFalseNode(iff));
 925   set_control(if_fast);
 926 
 927   return if_slow;
 928 }
 929 
 930 inline Node* LibraryCallKit::generate_slow_guard(Node* test, RegionNode* region) {
 931   return generate_guard(test, region, PROB_UNLIKELY_MAG(3));
 932 }
 933 inline Node* LibraryCallKit::generate_fair_guard(Node* test, RegionNode* region) {
 934   return generate_guard(test, region, PROB_FAIR);
 935 }
 936 
 937 inline Node* LibraryCallKit::generate_negative_guard(Node* index, RegionNode* region,
 938                                                      Node** pos_index, bool with_opaque) {
 939   if (stopped())
 940     return nullptr;                // already stopped
 941   if (_gvn.type(index)->higher_equal(TypeInt::POS)) // [0,maxint]
 942     return nullptr;                // index is already adequately typed
 943   Node* cmp_lt = _gvn.transform(new CmpINode(index, intcon(0)));
 944   Node* bol_lt = _gvn.transform(new BoolNode(cmp_lt, BoolTest::lt));
 945   if (with_opaque) {
 946     bol_lt = _gvn.transform(new OpaqueConstantBoolNode(C, bol_lt, false));
 947   }
 948   Node* is_neg = generate_guard(bol_lt, region, PROB_MIN);
 949   if (is_neg != nullptr && pos_index != nullptr) {
 950     // Emulate effect of Parse::adjust_map_after_if.
 951     Node* ccast = new CastIINode(control(), index, TypeInt::POS);
 952     (*pos_index) = _gvn.transform(ccast);
 953   }
 954   return is_neg;
 955 }
 956 
 957 // Make sure that 'position' is a valid limit index, in [0..length].
 958 // There are two equivalent plans for checking this:
 959 //   A. (offset + copyLength)  unsigned<=  arrayLength
 960 //   B. offset  <=  (arrayLength - copyLength)
 961 // We require that all of the values above, except for the sum and
 962 // difference, are already known to be non-negative.
 963 // Plan A is robust in the face of overflow, if offset and copyLength
 964 // are both hugely positive.
 965 //
 966 // Plan B is less direct and intuitive, but it does not overflow at
 967 // all, since the difference of two non-negatives is always
 968 // representable.  Whenever Java methods must perform the equivalent
 969 // check they generally use Plan B instead of Plan A.
 970 // For the moment we use Plan A.
 971 inline Node* LibraryCallKit::generate_limit_guard(Node* offset,
 972                                                   Node* subseq_length,
 973                                                   Node* array_length,
 974                                                   RegionNode* region,
 975                                                   bool with_opaque) {
 976   if (stopped())
 977     return nullptr;                // already stopped
 978   bool zero_offset = _gvn.type(offset) == TypeInt::ZERO;
 979   if (zero_offset && subseq_length->eqv_uncast(array_length))
 980     return nullptr;                // common case of whole-array copy
 981   Node* last = subseq_length;
 982   if (!zero_offset)             // last += offset
 983     last = _gvn.transform(new AddINode(last, offset));
 984   Node* cmp_lt = _gvn.transform(new CmpUNode(array_length, last));
 985   Node* bol_lt = _gvn.transform(new BoolNode(cmp_lt, BoolTest::lt));
 986   if (with_opaque) {
 987     bol_lt = _gvn.transform(new OpaqueConstantBoolNode(C, bol_lt, false));
 988   }
 989   Node* is_over = generate_guard(bol_lt, region, PROB_MIN);
 990   return is_over;
 991 }
 992 
 993 // Emit range checks for the given String.value byte array
 994 void LibraryCallKit::generate_string_range_check(Node* array,
 995                                                  Node* offset,
 996                                                  Node* count,
 997                                                  bool char_count,
 998                                                  RegionNode* region) {
 999   if (stopped()) {
1000     return; // already stopped
1001   }
1002   if (char_count) {
1003     // Convert char count to byte count
1004     count = _gvn.transform(new LShiftINode(count, intcon(1)));
1005   }
1006   // Offset and count must not be negative
1007   generate_negative_guard(offset, region, nullptr, true);
1008   generate_negative_guard(count, region, nullptr, true);
1009   // Offset + count must not exceed length of array
1010   generate_limit_guard(offset, count, load_array_length(array), region, true);
1011 }
1012 
1013 Node* LibraryCallKit::current_thread_helper(Node*& tls_output, ByteSize handle_offset,
1014                                             bool is_immutable) {
1015   ciKlass* thread_klass = env()->Thread_klass();
1016   const Type* thread_type
1017     = TypeOopPtr::make_from_klass(thread_klass)->cast_to_ptr_type(TypePtr::NotNull);
1018 
1019   Node* thread = _gvn.transform(new ThreadLocalNode());
1020   Node* p = off_heap_plus_addr(thread, in_bytes(handle_offset));
1021   tls_output = thread;
1022 
1023   Node* thread_obj_handle
1024     = (is_immutable
1025       ? LoadNode::make(_gvn, nullptr, immutable_memory(), p, p->bottom_type()->is_ptr(),
1026         TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered)
1027       : make_load(nullptr, p, p->bottom_type()->is_ptr(), T_ADDRESS, MemNode::unordered));
1028   thread_obj_handle = _gvn.transform(thread_obj_handle);
1029 
1030   DecoratorSet decorators = IN_NATIVE;
1031   if (is_immutable) {
1032     decorators |= C2_IMMUTABLE_MEMORY;
1033   }
1034   return access_load(thread_obj_handle, thread_type, T_OBJECT, decorators);
1035 }
1036 
1037 //--------------------------generate_current_thread--------------------
1038 Node* LibraryCallKit::generate_current_thread(Node* &tls_output) {
1039   return current_thread_helper(tls_output, JavaThread::threadObj_offset(),
1040                                /*is_immutable*/false);
1041 }
1042 
1043 //--------------------------generate_virtual_thread--------------------
1044 Node* LibraryCallKit::generate_virtual_thread(Node* tls_output) {
1045   return current_thread_helper(tls_output, JavaThread::vthread_offset(),
1046                                !C->method()->changes_current_thread());
1047 }
1048 
1049 //------------------------------make_string_method_node------------------------
1050 // Helper method for String intrinsic functions. This version is called with
1051 // str1 and str2 pointing to byte[] nodes containing Latin1 or UTF16 encoded
1052 // characters (depending on 'is_byte'). cnt1 and cnt2 are pointing to Int nodes
1053 // containing the lengths of str1 and str2.
1054 Node* LibraryCallKit::make_string_method_node(int opcode, Node* str1_start, Node* cnt1, Node* str2_start, Node* cnt2, StrIntrinsicNode::ArgEnc ae) {
1055   Node* result = nullptr;
1056   switch (opcode) {
1057   case Op_StrIndexOf:
1058     result = new StrIndexOfNode(control(), memory(TypeAryPtr::BYTES),
1059                                 str1_start, cnt1, str2_start, cnt2, ae);
1060     break;
1061   case Op_StrComp:
1062     result = new StrCompNode(control(), memory(TypeAryPtr::BYTES),
1063                              str1_start, cnt1, str2_start, cnt2, ae);
1064     break;
1065   case Op_StrEquals:
1066     // We already know that cnt1 == cnt2 here (checked in 'inline_string_equals').
1067     // Use the constant length if there is one because optimized match rule may exist.
1068     result = new StrEqualsNode(control(), memory(TypeAryPtr::BYTES),
1069                                str1_start, str2_start, cnt2->is_Con() ? cnt2 : cnt1, ae);
1070     break;
1071   default:
1072     ShouldNotReachHere();
1073     return nullptr;
1074   }
1075 
1076   // All these intrinsics have checks.
1077   C->set_has_split_ifs(true); // Has chance for split-if optimization
1078   clear_upper_avx();
1079 
1080   return _gvn.transform(result);
1081 }
1082 
1083 //------------------------------inline_string_compareTo------------------------
1084 bool LibraryCallKit::inline_string_compareTo(StrIntrinsicNode::ArgEnc ae) {
1085   Node* arg1 = argument(0);
1086   Node* arg2 = argument(1);
1087 
1088   arg1 = must_be_not_null(arg1, true);
1089   arg2 = must_be_not_null(arg2, true);
1090 
1091   // Get start addr and length of first argument
1092   Node* arg1_start  = array_element_address(arg1, intcon(0), T_BYTE);
1093   Node* arg1_cnt    = load_array_length(arg1);
1094 
1095   // Get start addr and length of second argument
1096   Node* arg2_start  = array_element_address(arg2, intcon(0), T_BYTE);
1097   Node* arg2_cnt    = load_array_length(arg2);
1098 
1099   Node* result = make_string_method_node(Op_StrComp, arg1_start, arg1_cnt, arg2_start, arg2_cnt, ae);
1100   set_result(result);
1101   return true;
1102 }
1103 
1104 //------------------------------inline_string_equals------------------------
1105 bool LibraryCallKit::inline_string_equals(StrIntrinsicNode::ArgEnc ae) {
1106   Node* arg1 = argument(0);
1107   Node* arg2 = argument(1);
1108 
1109   // paths (plus control) merge
1110   RegionNode* region = new RegionNode(3);
1111   Node* phi = new PhiNode(region, TypeInt::BOOL);
1112 
1113   if (!stopped()) {
1114 
1115     arg1 = must_be_not_null(arg1, true);
1116     arg2 = must_be_not_null(arg2, true);
1117 
1118     // Get start addr and length of first argument
1119     Node* arg1_start  = array_element_address(arg1, intcon(0), T_BYTE);
1120     Node* arg1_cnt    = load_array_length(arg1);
1121 
1122     // Get start addr and length of second argument
1123     Node* arg2_start  = array_element_address(arg2, intcon(0), T_BYTE);
1124     Node* arg2_cnt    = load_array_length(arg2);
1125 
1126     // Check for arg1_cnt != arg2_cnt
1127     Node* cmp = _gvn.transform(new CmpINode(arg1_cnt, arg2_cnt));
1128     Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::ne));
1129     Node* if_ne = generate_slow_guard(bol, nullptr);
1130     if (if_ne != nullptr) {
1131       phi->init_req(2, intcon(0));
1132       region->init_req(2, if_ne);
1133     }
1134 
1135     // Check for count == 0 is done by assembler code for StrEquals.
1136 
1137     if (!stopped()) {
1138       Node* equals = make_string_method_node(Op_StrEquals, arg1_start, arg1_cnt, arg2_start, arg2_cnt, ae);
1139       phi->init_req(1, equals);
1140       region->init_req(1, control());
1141     }
1142   }
1143 
1144   // post merge
1145   set_control(_gvn.transform(region));
1146   record_for_igvn(region);
1147 
1148   set_result(_gvn.transform(phi));
1149   return true;
1150 }
1151 
1152 //------------------------------inline_array_equals----------------------------
1153 bool LibraryCallKit::inline_array_equals(StrIntrinsicNode::ArgEnc ae) {
1154   assert(ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::LL, "unsupported array types");
1155   Node* arg1 = argument(0);
1156   Node* arg2 = argument(1);
1157 
1158   const TypeAryPtr* mtype = (ae == StrIntrinsicNode::UU) ? TypeAryPtr::CHARS : TypeAryPtr::BYTES;
1159   set_result(_gvn.transform(new AryEqNode(control(), memory(mtype), mtype, arg1, arg2, ae)));
1160   clear_upper_avx();
1161 
1162   return true;
1163 }
1164 
1165 
1166 //------------------------------inline_countPositives------------------------------
1167 // int java.lang.StringCoding#countPositives0(byte[] ba, int off, int len)
1168 bool LibraryCallKit::inline_countPositives() {
1169   assert(callee()->signature()->size() == 3, "countPositives has 3 parameters");
1170   // no receiver since it is static method
1171   Node* ba         = argument(0);
1172   Node* offset     = argument(1);
1173   Node* len        = argument(2);
1174 
1175   ba = must_be_not_null(ba, true);
1176   RegionNode* bailout = create_bailout();
1177   generate_string_range_check(ba, offset, len, false, bailout);
1178   if (check_bailout(bailout)) {
1179     return true;
1180   }
1181 
1182   Node* ba_start = array_element_address(ba, offset, T_BYTE);
1183   Node* result = new CountPositivesNode(control(), memory(TypeAryPtr::BYTES), ba_start, len);
1184   set_result(_gvn.transform(result));
1185   clear_upper_avx();
1186   return true;
1187 }
1188 
1189 bool LibraryCallKit::inline_preconditions_checkIndex(BasicType bt) {
1190   Node* index = argument(0);
1191   Node* length = bt == T_INT ? argument(1) : argument(2);
1192   if (too_many_traps(Deoptimization::Reason_intrinsic) || too_many_traps(Deoptimization::Reason_range_check)) {
1193     return false;
1194   }
1195 
1196   // check that length is positive
1197   Node* len_pos_cmp = _gvn.transform(CmpNode::make(length, integercon(0, bt), bt));
1198   Node* len_pos_bol = _gvn.transform(new BoolNode(len_pos_cmp, BoolTest::ge));
1199 
1200   {
1201     BuildCutout unless(this, len_pos_bol, PROB_MAX);
1202     uncommon_trap(Deoptimization::Reason_intrinsic,
1203                   Deoptimization::Action_make_not_entrant);
1204   }
1205 
1206   if (stopped()) {
1207     // Length is known to be always negative during compilation and the IR graph so far constructed is good so return success
1208     return true;
1209   }
1210 
1211   // length is now known positive, add a cast node to make this explicit
1212   jlong upper_bound = _gvn.type(length)->is_integer(bt)->hi_as_long();
1213   Node* casted_length = ConstraintCastNode::make_cast_for_basic_type(
1214       control(), length, TypeInteger::make(0, upper_bound, Type::WidenMax, bt),
1215       ConstraintCastNode::DependencyType::FloatingNarrowing, bt);
1216   casted_length = _gvn.transform(casted_length);
1217   replace_in_map(length, casted_length);
1218   length = casted_length;
1219 
1220   // Use an unsigned comparison for the range check itself
1221   Node* rc_cmp = _gvn.transform(CmpNode::make(index, length, bt, true));
1222   BoolTest::mask btest = BoolTest::lt;
1223   Node* rc_bool = _gvn.transform(new BoolNode(rc_cmp, btest));
1224   RangeCheckNode* rc = new RangeCheckNode(control(), rc_bool, PROB_MAX, COUNT_UNKNOWN);
1225   _gvn.set_type(rc, rc->Value(&_gvn));
1226   if (!rc_bool->is_Con()) {
1227     record_for_igvn(rc);
1228   }
1229   set_control(_gvn.transform(new IfTrueNode(rc)));
1230   {
1231     PreserveJVMState pjvms(this);
1232     set_control(_gvn.transform(new IfFalseNode(rc)));
1233     uncommon_trap(Deoptimization::Reason_range_check,
1234                   Deoptimization::Action_make_not_entrant);
1235   }
1236 
1237   if (stopped()) {
1238     // Range check is known to always fail during compilation and the IR graph so far constructed is good so return success
1239     return true;
1240   }
1241 
1242   // index is now known to be >= 0 and < length, cast it
1243   Node* result = ConstraintCastNode::make_cast_for_basic_type(
1244       control(), index, TypeInteger::make(0, upper_bound, Type::WidenMax, bt),
1245       ConstraintCastNode::DependencyType::FloatingNarrowing, bt);
1246   result = _gvn.transform(result);
1247   set_result(result);
1248   replace_in_map(index, result);
1249   return true;
1250 }
1251 
1252 //------------------------------inline_string_indexOf------------------------
1253 bool LibraryCallKit::inline_string_indexOf(StrIntrinsicNode::ArgEnc ae) {
1254   if (!Matcher::match_rule_supported(Op_StrIndexOf)) {
1255     return false;
1256   }
1257   Node* src = argument(0);
1258   Node* tgt = argument(1);
1259 
1260   // Make the merge point
1261   RegionNode* result_rgn = new RegionNode(4);
1262   Node*       result_phi = new PhiNode(result_rgn, TypeInt::INT);
1263 
1264   src = must_be_not_null(src, true);
1265   tgt = must_be_not_null(tgt, true);
1266 
1267   // Get start addr and length of source string
1268   Node* src_start = array_element_address(src, intcon(0), T_BYTE);
1269   Node* src_count = load_array_length(src);
1270 
1271   // Get start addr and length of substring
1272   Node* tgt_start = array_element_address(tgt, intcon(0), T_BYTE);
1273   Node* tgt_count = load_array_length(tgt);
1274 
1275   Node* result = nullptr;
1276   bool call_opt_stub = (StubRoutines::_string_indexof_array[ae] != nullptr);
1277 
1278   if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
1279     // Divide src size by 2 if String is UTF16 encoded
1280     src_count = _gvn.transform(new RShiftINode(src_count, intcon(1)));
1281   }
1282   if (ae == StrIntrinsicNode::UU) {
1283     // Divide substring size by 2 if String is UTF16 encoded
1284     tgt_count = _gvn.transform(new RShiftINode(tgt_count, intcon(1)));
1285   }
1286 
1287   if (call_opt_stub) {
1288     Node* call = make_runtime_call(RC_LEAF, OptoRuntime::string_IndexOf_Type(),
1289                                    StubRoutines::_string_indexof_array[ae],
1290                                    "stringIndexOf", TypePtr::BOTTOM, src_start,
1291                                    src_count, tgt_start, tgt_count);
1292     result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
1293   } else {
1294     result = make_indexOf_node(src_start, src_count, tgt_start, tgt_count,
1295                                result_rgn, result_phi, ae);
1296   }
1297   if (result != nullptr) {
1298     result_phi->init_req(3, result);
1299     result_rgn->init_req(3, control());
1300   }
1301   set_control(_gvn.transform(result_rgn));
1302   record_for_igvn(result_rgn);
1303   set_result(_gvn.transform(result_phi));
1304 
1305   return true;
1306 }
1307 
1308 //-----------------------------inline_string_indexOfI-----------------------
1309 bool LibraryCallKit::inline_string_indexOfI(StrIntrinsicNode::ArgEnc ae) {
1310   if (!Matcher::match_rule_supported(Op_StrIndexOf)) {
1311     return false;
1312   }
1313 
1314   assert(callee()->signature()->size() == 5, "String.indexOf() has 5 arguments");
1315   Node* src         = argument(0); // byte[]
1316   Node* src_count   = argument(1); // char count
1317   Node* tgt         = argument(2); // byte[]
1318   Node* tgt_count   = argument(3); // char count
1319   Node* from_index  = argument(4); // char index
1320 
1321   src = must_be_not_null(src, true);
1322   tgt = must_be_not_null(tgt, true);
1323 
1324   // Multiply byte array index by 2 if String is UTF16 encoded
1325   Node* src_offset = (ae == StrIntrinsicNode::LL) ? from_index : _gvn.transform(new LShiftINode(from_index, intcon(1)));
1326   src_count = _gvn.transform(new SubINode(src_count, from_index));
1327   Node* src_start = array_element_address(src, src_offset, T_BYTE);
1328   Node* tgt_start = array_element_address(tgt, intcon(0), T_BYTE);
1329 
1330   // Range checks
1331   RegionNode* bailout = create_bailout();
1332   generate_string_range_check(src, src_offset, src_count, ae != StrIntrinsicNode::LL, bailout);
1333   generate_string_range_check(tgt, intcon(0), tgt_count, ae == StrIntrinsicNode::UU, bailout);
1334   if (check_bailout(bailout)) {
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   RegionNode* bailout = create_bailout();
1430   generate_string_range_check(src, src_offset, src_count, ae == StrIntrinsicNode::U, bailout);
1431   if (check_bailout(bailout)) {
1432     return true;
1433   }
1434 
1435   // Check for int_ch >= 0
1436   Node* int_ch_cmp = _gvn.transform(new CmpINode(int_ch, intcon(0)));
1437   Node* int_ch_bol = _gvn.transform(new BoolNode(int_ch_cmp, BoolTest::ge));
1438   {
1439     BuildCutout unless(this, int_ch_bol, PROB_MAX);
1440     uncommon_trap(Deoptimization::Reason_intrinsic,
1441                   Deoptimization::Action_maybe_recompile);
1442   }
1443   if (stopped()) {
1444     return true;
1445   }
1446 
1447   RegionNode* region = new RegionNode(3);
1448   Node* phi = new PhiNode(region, TypeInt::INT);
1449 
1450   Node* result = new StrIndexOfCharNode(control(), memory(TypeAryPtr::BYTES), src_start, src_count, int_ch, ae);
1451   C->set_has_split_ifs(true); // Has chance for split-if optimization
1452   _gvn.transform(result);
1453 
1454   Node* cmp = _gvn.transform(new CmpINode(result, intcon(0)));
1455   Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::lt));
1456 
1457   Node* if_lt = generate_slow_guard(bol, nullptr);
1458   if (if_lt != nullptr) {
1459     // result == -1
1460     phi->init_req(2, result);
1461     region->init_req(2, if_lt);
1462   }
1463   if (!stopped()) {
1464     result = _gvn.transform(new AddINode(result, from_index));
1465     phi->init_req(1, result);
1466     region->init_req(1, control());
1467   }
1468   set_control(_gvn.transform(region));
1469   record_for_igvn(region);
1470   set_result(_gvn.transform(phi));
1471   clear_upper_avx();
1472 
1473   return true;
1474 }
1475 //---------------------------inline_string_copy---------------------
1476 // compressIt == true --> generate a compressed copy operation (compress char[]/byte[] to byte[])
1477 //   int StringUTF16.compress0(char[] src, int srcOff, byte[] dst, int dstOff, int len)
1478 //   int StringUTF16.compress0(byte[] src, int srcOff, byte[] dst, int dstOff, int len)
1479 // compressIt == false --> generate an inflated copy operation (inflate byte[] to char[]/byte[])
1480 //   void StringLatin1.inflate0(byte[] src, int srcOff, char[] dst, int dstOff, int len)
1481 //   void StringLatin1.inflate0(byte[] src, int srcOff, byte[] dst, int dstOff, int len)
1482 bool LibraryCallKit::inline_string_copy(bool compress) {
1483   int nargs = 5;  // 2 oops, 3 ints
1484   assert(callee()->signature()->size() == nargs, "string copy has 5 arguments");
1485 
1486   Node* src         = argument(0);
1487   Node* src_offset  = argument(1);
1488   Node* dst         = argument(2);
1489   Node* dst_offset  = argument(3);
1490   Node* length      = argument(4);
1491 
1492   // Check for allocation before we add nodes that would confuse
1493   // tightly_coupled_allocation()
1494   AllocateArrayNode* alloc = tightly_coupled_allocation(dst);
1495 
1496   // Figure out the size and type of the elements we will be copying.
1497   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
1498   const TypeAryPtr* dst_type = dst->Value(&_gvn)->isa_aryptr();
1499   if (src_type == nullptr || dst_type == nullptr) {
1500     return false;
1501   }
1502   BasicType src_elem = src_type->elem()->array_element_basic_type();
1503   BasicType dst_elem = dst_type->elem()->array_element_basic_type();
1504   assert((compress && dst_elem == T_BYTE && (src_elem == T_BYTE || src_elem == T_CHAR)) ||
1505          (!compress && src_elem == T_BYTE && (dst_elem == T_BYTE || dst_elem == T_CHAR)),
1506          "Unsupported array types for inline_string_copy");
1507 
1508   src = must_be_not_null(src, true);
1509   dst = must_be_not_null(dst, true);
1510 
1511   // Convert char[] offsets to byte[] offsets
1512   bool convert_src = (compress && src_elem == T_BYTE);
1513   bool convert_dst = (!compress && dst_elem == T_BYTE);
1514   if (convert_src) {
1515     src_offset = _gvn.transform(new LShiftINode(src_offset, intcon(1)));
1516   } else if (convert_dst) {
1517     dst_offset = _gvn.transform(new LShiftINode(dst_offset, intcon(1)));
1518   }
1519 
1520   // Range checks
1521   RegionNode* bailout = create_bailout();
1522   generate_string_range_check(src, src_offset, length, convert_src, bailout);
1523   generate_string_range_check(dst, dst_offset, length, convert_dst, bailout);
1524   if (check_bailout(bailout)) {
1525     return true;
1526   }
1527 
1528   Node* src_start = array_element_address(src, src_offset, src_elem);
1529   Node* dst_start = array_element_address(dst, dst_offset, dst_elem);
1530   // 'src_start' points to src array + scaled offset
1531   // 'dst_start' points to dst array + scaled offset
1532   Node* count = nullptr;
1533   if (compress) {
1534     count = compress_string(src_start, TypeAryPtr::get_array_body_type(src_elem), dst_start, length);
1535   } else {
1536     inflate_string(src_start, dst_start, TypeAryPtr::get_array_body_type(dst_elem), length);
1537   }
1538 
1539   if (alloc != nullptr) {
1540     if (alloc->maybe_set_complete(&_gvn)) {
1541       // "You break it, you buy it."
1542       InitializeNode* init = alloc->initialization();
1543       assert(init->is_complete(), "we just did this");
1544       init->set_complete_with_arraycopy();
1545       assert(dst->is_CheckCastPP(), "sanity");
1546       assert(dst->in(0)->in(0) == init, "dest pinned");
1547     }
1548     // Do not let stores that initialize this object be reordered with
1549     // a subsequent store that would make this object accessible by
1550     // other threads.
1551     // Record what AllocateNode this StoreStore protects so that
1552     // escape analysis can go from the MemBarStoreStoreNode to the
1553     // AllocateNode and eliminate the MemBarStoreStoreNode if possible
1554     // based on the escape status of the AllocateNode.
1555     insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
1556   }
1557   if (compress) {
1558     set_result(_gvn.transform(count));
1559   }
1560   clear_upper_avx();
1561 
1562   return true;
1563 }
1564 
1565 #ifdef _LP64
1566 #define XTOP ,top() /*additional argument*/
1567 #else  //_LP64
1568 #define XTOP        /*no additional argument*/
1569 #endif //_LP64
1570 
1571 //------------------------inline_string_toBytesU--------------------------
1572 // public static byte[] StringUTF16.toBytes0(char[] value, int off, int len)
1573 bool LibraryCallKit::inline_string_toBytesU() {
1574   // Get the arguments.
1575   assert(callee()->signature()->size() == 3, "character array encoder requires 3 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.toBytes0() if deoptimization happens.
1584   { PreserveReexecuteState preexecs(this);
1585     jvms()->set_should_reexecute(true);
1586 
1587     value = must_be_not_null(value, true);
1588     RegionNode* bailout = create_bailout();
1589     generate_negative_guard(offset, bailout, nullptr, true);
1590     generate_negative_guard(length, bailout, nullptr, true);
1591     generate_limit_guard(offset, length, load_array_length(value), bailout, true);
1592     // Make sure that resulting byte[] length does not overflow Integer.MAX_VALUE
1593     generate_limit_guard(length, intcon(0), intcon(max_jint/2), bailout, true);
1594     if (check_bailout(bailout)) {
1595       return true;
1596     }
1597 
1598     Node* size = _gvn.transform(new LShiftINode(length, intcon(1)));
1599     Node* klass_node = makecon(TypeKlassPtr::make(ciTypeArrayKlass::make(T_BYTE)));
1600     newcopy = new_array(klass_node, size, 0);  // no arguments to push
1601     AllocateArrayNode* alloc = tightly_coupled_allocation(newcopy);
1602     guarantee(alloc != nullptr, "created above");
1603 
1604     // Calculate starting addresses.
1605     Node* src_start = array_element_address(value, offset, T_CHAR);
1606     Node* dst_start = basic_plus_adr(newcopy, arrayOopDesc::base_offset_in_bytes(T_BYTE));
1607 
1608     // Check if dst array address is aligned to HeapWordSize
1609     bool aligned = (arrayOopDesc::base_offset_in_bytes(T_BYTE) % HeapWordSize == 0);
1610     // If true, then check if src array address is aligned to HeapWordSize
1611     if (aligned) {
1612       const TypeInt* toffset = gvn().type(offset)->is_int();
1613       aligned = toffset->is_con() && ((arrayOopDesc::base_offset_in_bytes(T_CHAR) +
1614                                        toffset->get_con() * type2aelembytes(T_CHAR)) % HeapWordSize == 0);
1615     }
1616 
1617     // Figure out which arraycopy runtime method to call (disjoint, uninitialized).
1618     const char* copyfunc_name = "arraycopy";
1619     address     copyfunc_addr = StubRoutines::select_arraycopy_function(T_CHAR, aligned, true, copyfunc_name, true);
1620     Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
1621                       OptoRuntime::fast_arraycopy_Type(),
1622                       copyfunc_addr, copyfunc_name, TypeRawPtr::BOTTOM,
1623                       src_start, dst_start, ConvI2X(length) XTOP);
1624     // Do not let reads from the cloned object float above the arraycopy.
1625     if (alloc->maybe_set_complete(&_gvn)) {
1626       // "You break it, you buy it."
1627       InitializeNode* init = alloc->initialization();
1628       assert(init->is_complete(), "we just did this");
1629       init->set_complete_with_arraycopy();
1630       assert(newcopy->is_CheckCastPP(), "sanity");
1631       assert(newcopy->in(0)->in(0) == init, "dest pinned");
1632     }
1633     // Do not let stores that initialize this object be reordered with
1634     // a subsequent store that would make this object accessible by
1635     // other threads.
1636     // Record what AllocateNode this StoreStore protects so that
1637     // escape analysis can go from the MemBarStoreStoreNode to the
1638     // AllocateNode and eliminate the MemBarStoreStoreNode if possible
1639     // based on the escape status of the AllocateNode.
1640     insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
1641   } // original reexecute is set back here
1642 
1643   C->set_has_split_ifs(true); // Has chance for split-if optimization
1644   if (!stopped()) {
1645     set_result(newcopy);
1646   }
1647   clear_upper_avx();
1648 
1649   return true;
1650 }
1651 
1652 //------------------------inline_string_getCharsU--------------------------
1653 // public void StringUTF16.getChars0(byte[] src, int srcBegin, int srcEnd, char dst[], int dstBegin)
1654 bool LibraryCallKit::inline_string_getCharsU() {
1655   assert(callee()->signature()->size() == 5, "StringUTF16.getChars0() has 5 arguments");
1656   // Get the arguments.
1657   Node* src       = argument(0);
1658   Node* src_begin = argument(1);
1659   Node* src_end   = argument(2); // exclusive offset (i < src_end)
1660   Node* dst       = argument(3);
1661   Node* dst_begin = argument(4);
1662 
1663   // Check for allocation before we add nodes that would confuse
1664   // tightly_coupled_allocation()
1665   AllocateArrayNode* alloc = tightly_coupled_allocation(dst);
1666 
1667   // Check if a null path was taken unconditionally.
1668   src = must_be_not_null(src, true);
1669   dst = must_be_not_null(dst, true);
1670   if (stopped()) {
1671     return true;
1672   }
1673 
1674   // Get length and convert char[] offset to byte[] offset
1675   Node* length = _gvn.transform(new SubINode(src_end, src_begin));
1676   src_begin = _gvn.transform(new LShiftINode(src_begin, intcon(1)));
1677 
1678   // Range checks
1679   RegionNode* bailout = create_bailout();
1680   generate_string_range_check(src, src_begin, length, true, bailout);
1681   generate_string_range_check(dst, dst_begin, length, false, bailout);
1682   if (check_bailout(bailout)) {
1683     return true;
1684   }
1685 
1686   // Calculate starting addresses.
1687   Node* src_start = array_element_address(src, src_begin, T_BYTE);
1688   Node* dst_start = array_element_address(dst, dst_begin, T_CHAR);
1689 
1690   // Check if array addresses are aligned to HeapWordSize
1691   const TypeInt* tsrc = gvn().type(src_begin)->is_int();
1692   const TypeInt* tdst = gvn().type(dst_begin)->is_int();
1693   bool aligned = tsrc->is_con() && ((arrayOopDesc::base_offset_in_bytes(T_BYTE) + tsrc->get_con() * type2aelembytes(T_BYTE)) % HeapWordSize == 0) &&
1694                  tdst->is_con() && ((arrayOopDesc::base_offset_in_bytes(T_CHAR) + tdst->get_con() * type2aelembytes(T_CHAR)) % HeapWordSize == 0);
1695 
1696   // Figure out which arraycopy runtime method to call (disjoint, uninitialized).
1697   const char* copyfunc_name = "arraycopy";
1698   address     copyfunc_addr = StubRoutines::select_arraycopy_function(T_CHAR, aligned, true, copyfunc_name, true);
1699   Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
1700                     OptoRuntime::fast_arraycopy_Type(),
1701                     copyfunc_addr, copyfunc_name, TypeRawPtr::BOTTOM,
1702                     src_start, dst_start, ConvI2X(length) XTOP);
1703   // Do not let reads from the cloned object float above the arraycopy.
1704   if (alloc != nullptr) {
1705     if (alloc->maybe_set_complete(&_gvn)) {
1706       // "You break it, you buy it."
1707       InitializeNode* init = alloc->initialization();
1708       assert(init->is_complete(), "we just did this");
1709       init->set_complete_with_arraycopy();
1710       assert(dst->is_CheckCastPP(), "sanity");
1711       assert(dst->in(0)->in(0) == init, "dest pinned");
1712     }
1713     // Do not let stores that initialize this object be reordered with
1714     // a subsequent store that would make this object accessible by
1715     // other threads.
1716     // Record what AllocateNode this StoreStore protects so that
1717     // escape analysis can go from the MemBarStoreStoreNode to the
1718     // AllocateNode and eliminate the MemBarStoreStoreNode if possible
1719     // based on the escape status of the AllocateNode.
1720     insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
1721   } else {
1722     insert_mem_bar(Op_MemBarCPUOrder);
1723   }
1724 
1725   C->set_has_split_ifs(true); // Has chance for split-if optimization
1726   return true;
1727 }
1728 
1729 //----------------------inline_string_char_access----------------------------
1730 // Store/Load char to/from byte[] array.
1731 // static void StringUTF16.putChar(byte[] val, int index, int c)
1732 // static char StringUTF16.getChar(byte[] val, int index)
1733 bool LibraryCallKit::inline_string_char_access(bool is_store) {
1734   Node* ch;
1735   if (is_store) {
1736     assert(callee()->signature()->size() == 3, "StringUTF16.putChar() has 3 arguments");
1737     ch = argument(2);
1738   } else {
1739     assert(callee()->signature()->size() == 2, "StringUTF16.getChar() has 2 arguments");
1740     ch = nullptr;
1741   }
1742   Node* value  = argument(0);
1743   Node* index  = argument(1);
1744 
1745   // This intrinsic accesses byte[] array as char[] array. Computing the offsets
1746   // correctly requires matched array shapes.
1747   assert (arrayOopDesc::base_offset_in_bytes(T_CHAR) == arrayOopDesc::base_offset_in_bytes(T_BYTE),
1748           "sanity: byte[] and char[] bases agree");
1749   assert (type2aelembytes(T_CHAR) == type2aelembytes(T_BYTE)*2,
1750           "sanity: byte[] and char[] scales agree");
1751 
1752   // Bail when getChar over constants is requested: constant folding would
1753   // reject folding mismatched char access over byte[]. A normal inlining for getChar
1754   // Java method would constant fold nicely instead.
1755   if (!is_store && value->is_Con() && index->is_Con()) {
1756     return false;
1757   }
1758 
1759   // Save state and restore on bailout
1760   SavedState old_state(this);
1761 
1762   value = must_be_not_null(value, true);
1763 
1764   Node* adr = array_element_address(value, index, T_CHAR);
1765   if (adr->is_top()) {
1766     return false;
1767   }
1768   old_state.discard();
1769   if (is_store) {
1770     access_store_at(value, adr, TypeAryPtr::BYTES, ch, TypeInt::CHAR, T_CHAR, IN_HEAP | MO_UNORDERED | C2_MISMATCHED);
1771   } else {
1772     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);
1773     set_result(ch);
1774   }
1775   return true;
1776 }
1777 
1778 
1779 //------------------------------inline_math-----------------------------------
1780 // public static double Math.abs(double)
1781 // public static double Math.sqrt(double)
1782 // public static double Math.log(double)
1783 // public static double Math.log10(double)
1784 // public static double Math.round(double)
1785 bool LibraryCallKit::inline_double_math(vmIntrinsics::ID id) {
1786   Node* arg = argument(0);
1787   Node* n = nullptr;
1788   switch (id) {
1789   case vmIntrinsics::_dabs:   n = new AbsDNode(                arg);  break;
1790   case vmIntrinsics::_dsqrt:
1791   case vmIntrinsics::_dsqrt_strict:
1792                               n = new SqrtDNode(C, control(),  arg);  break;
1793   case vmIntrinsics::_ceil:   n = RoundDoubleModeNode::make(_gvn, arg, RoundDoubleModeNode::rmode_ceil); break;
1794   case vmIntrinsics::_floor:  n = RoundDoubleModeNode::make(_gvn, arg, RoundDoubleModeNode::rmode_floor); break;
1795   case vmIntrinsics::_rint:   n = RoundDoubleModeNode::make(_gvn, arg, RoundDoubleModeNode::rmode_rint); break;
1796   case vmIntrinsics::_roundD: n = new RoundDNode(arg); break;
1797   case vmIntrinsics::_dcopySign: n = CopySignDNode::make(_gvn, arg, argument(2)); break;
1798   case vmIntrinsics::_dsignum: n = SignumDNode::make(_gvn, arg); break;
1799   default:  fatal_unexpected_iid(id);  break;
1800   }
1801   set_result(_gvn.transform(n));
1802   return true;
1803 }
1804 
1805 //------------------------------inline_math-----------------------------------
1806 // public static float Math.abs(float)
1807 // public static int Math.abs(int)
1808 // public static long Math.abs(long)
1809 bool LibraryCallKit::inline_math(vmIntrinsics::ID id) {
1810   Node* arg = argument(0);
1811   Node* n = nullptr;
1812   switch (id) {
1813   case vmIntrinsics::_fabs:   n = new AbsFNode(                arg);  break;
1814   case vmIntrinsics::_iabs:   n = new AbsINode(                arg);  break;
1815   case vmIntrinsics::_labs:   n = new AbsLNode(                arg);  break;
1816   case vmIntrinsics::_fcopySign: n = new CopySignFNode(arg, argument(1)); break;
1817   case vmIntrinsics::_fsignum: n = SignumFNode::make(_gvn, arg); break;
1818   case vmIntrinsics::_roundF: n = new RoundFNode(arg); break;
1819   default:  fatal_unexpected_iid(id);  break;
1820   }
1821   set_result(_gvn.transform(n));
1822   return true;
1823 }
1824 
1825 //------------------------------runtime_math-----------------------------
1826 bool LibraryCallKit::runtime_math(const TypeFunc* call_type, address funcAddr, const char* funcName) {
1827   assert(call_type == OptoRuntime::Math_DD_D_Type() || call_type == OptoRuntime::Math_D_D_Type(),
1828          "must be (DD)D or (D)D type");
1829 
1830   // Inputs
1831   Node* a = argument(0);
1832   Node* b = (call_type == OptoRuntime::Math_DD_D_Type()) ? argument(2) : nullptr;
1833 
1834   const TypePtr* no_memory_effects = nullptr;
1835   Node* trig = make_runtime_call(RC_LEAF | RC_PURE, call_type, funcAddr, funcName,
1836                                  no_memory_effects,
1837                                  a, top(), b, b ? top() : nullptr);
1838   Node* value = _gvn.transform(new ProjNode(trig, TypeFunc::Parms+0));
1839 #ifdef ASSERT
1840   Node* value_top = _gvn.transform(new ProjNode(trig, TypeFunc::Parms+1));
1841   assert(value_top == top(), "second value must be top");
1842 #endif
1843 
1844   set_result(value);
1845   return true;
1846 }
1847 
1848 //------------------------------inline_math_pow-----------------------------
1849 bool LibraryCallKit::inline_math_pow() {
1850   Node* base = argument(0);
1851   Node* exp = argument(2);
1852 
1853   CallNode* pow = new PowDNode(C, base, exp);
1854   set_predefined_input_for_runtime_call(pow);
1855   pow = _gvn.transform(pow)->as_CallLeafPure();
1856   set_predefined_output_for_runtime_call(pow);
1857   Node* result = _gvn.transform(new ProjNode(pow, TypeFunc::Parms + 0));
1858   record_for_igvn(pow);
1859   set_result(result);
1860   return true;
1861 }
1862 
1863 //------------------------------inline_math_native-----------------------------
1864 bool LibraryCallKit::inline_math_native(vmIntrinsics::ID id) {
1865   switch (id) {
1866   case vmIntrinsics::_dsin:
1867     return StubRoutines::dsin() != nullptr ?
1868       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dsin(), "dsin") :
1869       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dsin),   "SIN");
1870   case vmIntrinsics::_dcos:
1871     return StubRoutines::dcos() != nullptr ?
1872       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dcos(), "dcos") :
1873       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dcos),   "COS");
1874   case vmIntrinsics::_dtan:
1875     return StubRoutines::dtan() != nullptr ?
1876       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dtan(), "dtan") :
1877       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dtan), "TAN");
1878   case vmIntrinsics::_dsinh:
1879     return StubRoutines::dsinh() != nullptr ?
1880       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dsinh(), "dsinh") : false;
1881   case vmIntrinsics::_dtanh:
1882     return StubRoutines::dtanh() != nullptr ?
1883       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dtanh(), "dtanh") : false;
1884   case vmIntrinsics::_dcbrt:
1885     return StubRoutines::dcbrt() != nullptr ?
1886       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dcbrt(), "dcbrt") : false;
1887   case vmIntrinsics::_dexp:
1888     return StubRoutines::dexp() != nullptr ?
1889       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dexp(),  "dexp") :
1890       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dexp),  "EXP");
1891   case vmIntrinsics::_dlog:
1892     return StubRoutines::dlog() != nullptr ?
1893       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dlog(), "dlog") :
1894       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dlog),   "LOG");
1895   case vmIntrinsics::_dlog10:
1896     return StubRoutines::dlog10() != nullptr ?
1897       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dlog10(), "dlog10") :
1898       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dlog10), "LOG10");
1899 
1900   case vmIntrinsics::_roundD: return Matcher::match_rule_supported(Op_RoundD) ? inline_double_math(id) : false;
1901   case vmIntrinsics::_ceil:
1902   case vmIntrinsics::_floor:
1903   case vmIntrinsics::_rint:   return Matcher::match_rule_supported(Op_RoundDoubleMode) ? inline_double_math(id) : false;
1904 
1905   case vmIntrinsics::_dsqrt:
1906   case vmIntrinsics::_dsqrt_strict:
1907                               return Matcher::match_rule_supported(Op_SqrtD) ? inline_double_math(id) : false;
1908   case vmIntrinsics::_dabs:   return Matcher::has_match_rule(Op_AbsD)   ? inline_double_math(id) : false;
1909   case vmIntrinsics::_fabs:   return Matcher::match_rule_supported(Op_AbsF)   ? inline_math(id) : false;
1910   case vmIntrinsics::_iabs:   return Matcher::match_rule_supported(Op_AbsI)   ? inline_math(id) : false;
1911   case vmIntrinsics::_labs:   return Matcher::match_rule_supported(Op_AbsL)   ? inline_math(id) : false;
1912 
1913   case vmIntrinsics::_dpow:      return inline_math_pow();
1914   case vmIntrinsics::_dcopySign: return inline_double_math(id);
1915   case vmIntrinsics::_fcopySign: return inline_math(id);
1916   case vmIntrinsics::_dsignum: return Matcher::match_rule_supported(Op_SignumD) ? inline_double_math(id) : false;
1917   case vmIntrinsics::_fsignum: return Matcher::match_rule_supported(Op_SignumF) ? inline_math(id) : false;
1918   case vmIntrinsics::_roundF: return Matcher::match_rule_supported(Op_RoundF) ? inline_math(id) : false;
1919 
1920    // These intrinsics are not yet correctly implemented
1921   case vmIntrinsics::_datan2:
1922     return false;
1923 
1924   default:
1925     fatal_unexpected_iid(id);
1926     return false;
1927   }
1928 }
1929 
1930 //----------------------------inline_notify-----------------------------------*
1931 bool LibraryCallKit::inline_notify(vmIntrinsics::ID id) {
1932   const TypeFunc* ftype = OptoRuntime::monitor_notify_Type();
1933   address func;
1934   if (id == vmIntrinsics::_notify) {
1935     func = OptoRuntime::monitor_notify_Java();
1936   } else {
1937     func = OptoRuntime::monitor_notifyAll_Java();
1938   }
1939   Node* call = make_runtime_call(RC_NO_LEAF, ftype, func, nullptr, TypeRawPtr::BOTTOM, argument(0));
1940   make_slow_call_ex(call, env()->Throwable_klass(), false);
1941   return true;
1942 }
1943 
1944 
1945 //----------------------------inline_min_max-----------------------------------
1946 bool LibraryCallKit::inline_min_max(vmIntrinsics::ID id) {
1947   Node* a = nullptr;
1948   Node* b = nullptr;
1949   Node* n = nullptr;
1950   switch (id) {
1951     case vmIntrinsics::_min:
1952     case vmIntrinsics::_max:
1953     case vmIntrinsics::_minF:
1954     case vmIntrinsics::_maxF:
1955     case vmIntrinsics::_minF_strict:
1956     case vmIntrinsics::_maxF_strict:
1957     case vmIntrinsics::_min_strict:
1958     case vmIntrinsics::_max_strict:
1959       assert(callee()->signature()->size() == 2, "minF/maxF has 2 parameters of size 1 each.");
1960       a = argument(0);
1961       b = argument(1);
1962       break;
1963     case vmIntrinsics::_minD:
1964     case vmIntrinsics::_maxD:
1965     case vmIntrinsics::_minD_strict:
1966     case vmIntrinsics::_maxD_strict:
1967       assert(callee()->signature()->size() == 4, "minD/maxD has 2 parameters of size 2 each.");
1968       a = argument(0);
1969       b = argument(2);
1970       break;
1971     case vmIntrinsics::_minL:
1972     case vmIntrinsics::_maxL:
1973       assert(callee()->signature()->size() == 4, "minL/maxL has 2 parameters of size 2 each.");
1974       a = argument(0);
1975       b = argument(2);
1976       break;
1977     default:
1978       fatal_unexpected_iid(id);
1979       break;
1980   }
1981 
1982   switch (id) {
1983     case vmIntrinsics::_min:
1984     case vmIntrinsics::_min_strict:
1985       n = new MinINode(a, b);
1986       break;
1987     case vmIntrinsics::_max:
1988     case vmIntrinsics::_max_strict:
1989       n = new MaxINode(a, b);
1990       break;
1991     case vmIntrinsics::_minF:
1992     case vmIntrinsics::_minF_strict:
1993       n = new MinFNode(a, b);
1994       break;
1995     case vmIntrinsics::_maxF:
1996     case vmIntrinsics::_maxF_strict:
1997       n = new MaxFNode(a, b);
1998       break;
1999     case vmIntrinsics::_minD:
2000     case vmIntrinsics::_minD_strict:
2001       n = new MinDNode(a, b);
2002       break;
2003     case vmIntrinsics::_maxD:
2004     case vmIntrinsics::_maxD_strict:
2005       n = new MaxDNode(a, b);
2006       break;
2007     case vmIntrinsics::_minL:
2008       n = new MinLNode(_gvn.C, a, b);
2009       break;
2010     case vmIntrinsics::_maxL:
2011       n = new MaxLNode(_gvn.C, a, b);
2012       break;
2013     default:
2014       fatal_unexpected_iid(id);
2015       break;
2016   }
2017 
2018   set_result(_gvn.transform(n));
2019   return true;
2020 }
2021 
2022 bool LibraryCallKit::inline_math_mathExact(Node* math, Node* test) {
2023   if (builtin_throw_too_many_traps(Deoptimization::Reason_intrinsic,
2024                                    env()->ArithmeticException_instance())) {
2025     // It has been already too many times, but we cannot use builtin_throw (e.g. we care about backtraces),
2026     // so let's bail out intrinsic rather than risking deopting again.
2027     return false;
2028   }
2029 
2030   Node* bol = _gvn.transform( new BoolNode(test, BoolTest::overflow) );
2031   IfNode* check = create_and_map_if(control(), bol, PROB_UNLIKELY_MAG(3), COUNT_UNKNOWN);
2032   Node* fast_path = _gvn.transform( new IfFalseNode(check));
2033   Node* slow_path = _gvn.transform( new IfTrueNode(check) );
2034 
2035   {
2036     PreserveJVMState pjvms(this);
2037     PreserveReexecuteState preexecs(this);
2038     jvms()->set_should_reexecute(true);
2039 
2040     set_control(slow_path);
2041     set_i_o(i_o());
2042 
2043     builtin_throw(Deoptimization::Reason_intrinsic,
2044                   env()->ArithmeticException_instance(),
2045                   /*allow_too_many_traps*/ false);
2046   }
2047 
2048   set_control(fast_path);
2049   set_result(math);
2050   return true;
2051 }
2052 
2053 template <typename OverflowOp>
2054 bool LibraryCallKit::inline_math_overflow(Node* arg1, Node* arg2) {
2055   typedef typename OverflowOp::MathOp MathOp;
2056 
2057   MathOp* mathOp = new MathOp(arg1, arg2);
2058   Node* operation = _gvn.transform( mathOp );
2059   Node* ofcheck = _gvn.transform( new OverflowOp(arg1, arg2) );
2060   return inline_math_mathExact(operation, ofcheck);
2061 }
2062 
2063 bool LibraryCallKit::inline_math_addExactI(bool is_increment) {
2064   return inline_math_overflow<OverflowAddINode>(argument(0), is_increment ? intcon(1) : argument(1));
2065 }
2066 
2067 bool LibraryCallKit::inline_math_addExactL(bool is_increment) {
2068   return inline_math_overflow<OverflowAddLNode>(argument(0), is_increment ? longcon(1) : argument(2));
2069 }
2070 
2071 bool LibraryCallKit::inline_math_subtractExactI(bool is_decrement) {
2072   return inline_math_overflow<OverflowSubINode>(argument(0), is_decrement ? intcon(1) : argument(1));
2073 }
2074 
2075 bool LibraryCallKit::inline_math_subtractExactL(bool is_decrement) {
2076   return inline_math_overflow<OverflowSubLNode>(argument(0), is_decrement ? longcon(1) : argument(2));
2077 }
2078 
2079 bool LibraryCallKit::inline_math_negateExactI() {
2080   return inline_math_overflow<OverflowSubINode>(intcon(0), argument(0));
2081 }
2082 
2083 bool LibraryCallKit::inline_math_negateExactL() {
2084   return inline_math_overflow<OverflowSubLNode>(longcon(0), argument(0));
2085 }
2086 
2087 bool LibraryCallKit::inline_math_multiplyExactI() {
2088   return inline_math_overflow<OverflowMulINode>(argument(0), argument(1));
2089 }
2090 
2091 bool LibraryCallKit::inline_math_multiplyExactL() {
2092   return inline_math_overflow<OverflowMulLNode>(argument(0), argument(2));
2093 }
2094 
2095 bool LibraryCallKit::inline_math_multiplyHigh() {
2096   set_result(_gvn.transform(new MulHiLNode(argument(0), argument(2))));
2097   return true;
2098 }
2099 
2100 bool LibraryCallKit::inline_math_unsignedMultiplyHigh() {
2101   set_result(_gvn.transform(new UMulHiLNode(argument(0), argument(2))));
2102   return true;
2103 }
2104 
2105 inline int
2106 LibraryCallKit::classify_unsafe_addr(Node* &base, Node* &offset, BasicType type) {
2107   const TypePtr* base_type = TypePtr::NULL_PTR;
2108   if (base != nullptr)  base_type = _gvn.type(base)->isa_ptr();
2109   if (base_type == nullptr) {
2110     // Unknown type.
2111     return Type::AnyPtr;
2112   } else if (_gvn.type(base->uncast()) == TypePtr::NULL_PTR) {
2113     // Since this is a null+long form, we have to switch to a rawptr.
2114     base   = _gvn.transform(new CastX2PNode(offset));
2115     offset = MakeConX(0);
2116     return Type::RawPtr;
2117   } else if (base_type->base() == Type::RawPtr) {
2118     return Type::RawPtr;
2119   } else if (base_type->isa_oopptr()) {
2120     // Base is never null => always a heap address.
2121     if (!TypePtr::NULL_PTR->higher_equal(base_type)) {
2122       return Type::OopPtr;
2123     }
2124     // Offset is small => always a heap address.
2125     const TypeX* offset_type = _gvn.type(offset)->isa_intptr_t();
2126     if (offset_type != nullptr &&
2127         base_type->offset() == 0 &&     // (should always be?)
2128         offset_type->_lo >= 0 &&
2129         !MacroAssembler::needs_explicit_null_check(offset_type->_hi)) {
2130       return Type::OopPtr;
2131     } else if (type == T_OBJECT) {
2132       // off heap access to an oop doesn't make any sense. Has to be on
2133       // heap.
2134       return Type::OopPtr;
2135     }
2136     // Otherwise, it might either be oop+off or null+addr.
2137     return Type::AnyPtr;
2138   } else {
2139     // No information:
2140     return Type::AnyPtr;
2141   }
2142 }
2143 
2144 Node* LibraryCallKit::make_unsafe_address(Node*& base, Node* offset, BasicType type, bool can_cast) {
2145   Node* uncasted_base = base;
2146   int kind = classify_unsafe_addr(uncasted_base, offset, type);
2147   if (kind == Type::RawPtr) {
2148     return off_heap_plus_addr(uncasted_base, offset);
2149   } else if (kind == Type::AnyPtr) {
2150     assert(base == uncasted_base, "unexpected base change");
2151     if (can_cast) {
2152       if (!_gvn.type(base)->speculative_maybe_null() &&
2153           !too_many_traps(Deoptimization::Reason_speculate_null_check)) {
2154         // According to profiling, this access is always on
2155         // heap. Casting the base to not null and thus avoiding membars
2156         // around the access should allow better optimizations
2157         Node* null_ctl = top();
2158         base = null_check_oop(base, &null_ctl, true, true, true);
2159         assert(null_ctl->is_top(), "no null control here");
2160         return basic_plus_adr(base, offset);
2161       } else if (_gvn.type(base)->speculative_always_null() &&
2162                  !too_many_traps(Deoptimization::Reason_speculate_null_assert)) {
2163         // According to profiling, this access is always off
2164         // heap.
2165         base = null_assert(base);
2166         Node* raw_base = _gvn.transform(new CastX2PNode(offset));
2167         offset = MakeConX(0);
2168         return off_heap_plus_addr(raw_base, offset);
2169       }
2170     }
2171     // We don't know if it's an on heap or off heap access. Fall back
2172     // to raw memory access.
2173     Node* raw = _gvn.transform(new CheckCastPPNode(control(), base, TypeRawPtr::BOTTOM));
2174     return off_heap_plus_addr(raw, offset);
2175   } else {
2176     assert(base == uncasted_base, "unexpected base change");
2177     // We know it's an on heap access so base can't be null
2178     if (TypePtr::NULL_PTR->higher_equal(_gvn.type(base))) {
2179       base = must_be_not_null(base, true);
2180     }
2181     return basic_plus_adr(base, offset);
2182   }
2183 }
2184 
2185 //--------------------------inline_number_methods-----------------------------
2186 // inline int     Integer.numberOfLeadingZeros(int)
2187 // inline int        Long.numberOfLeadingZeros(long)
2188 //
2189 // inline int     Integer.numberOfTrailingZeros(int)
2190 // inline int        Long.numberOfTrailingZeros(long)
2191 //
2192 // inline int     Integer.bitCount(int)
2193 // inline int        Long.bitCount(long)
2194 //
2195 // inline char  Character.reverseBytes(char)
2196 // inline short     Short.reverseBytes(short)
2197 // inline int     Integer.reverseBytes(int)
2198 // inline long       Long.reverseBytes(long)
2199 bool LibraryCallKit::inline_number_methods(vmIntrinsics::ID id) {
2200   Node* arg = argument(0);
2201   Node* n = nullptr;
2202   switch (id) {
2203   case vmIntrinsics::_numberOfLeadingZeros_i:   n = new CountLeadingZerosINode( arg); break;
2204   case vmIntrinsics::_numberOfLeadingZeros_l:   n = new CountLeadingZerosLNode( arg); break;
2205   case vmIntrinsics::_numberOfTrailingZeros_i:  n = new CountTrailingZerosINode(arg); break;
2206   case vmIntrinsics::_numberOfTrailingZeros_l:  n = new CountTrailingZerosLNode(arg); break;
2207   case vmIntrinsics::_bitCount_i:               n = new PopCountINode(          arg); break;
2208   case vmIntrinsics::_bitCount_l:               n = new PopCountLNode(          arg); break;
2209   case vmIntrinsics::_reverseBytes_c:           n = new ReverseBytesUSNode(     arg); break;
2210   case vmIntrinsics::_reverseBytes_s:           n = new ReverseBytesSNode(      arg); break;
2211   case vmIntrinsics::_reverseBytes_i:           n = new ReverseBytesINode(      arg); break;
2212   case vmIntrinsics::_reverseBytes_l:           n = new ReverseBytesLNode(      arg); break;
2213   case vmIntrinsics::_reverse_i:                n = new ReverseINode(           arg); break;
2214   case vmIntrinsics::_reverse_l:                n = new ReverseLNode(           arg); break;
2215   default:  fatal_unexpected_iid(id);  break;
2216   }
2217   set_result(_gvn.transform(n));
2218   return true;
2219 }
2220 
2221 //--------------------------inline_bitshuffle_methods-----------------------------
2222 // inline int Integer.compress(int, int)
2223 // inline int Integer.expand(int, int)
2224 // inline long Long.compress(long, long)
2225 // inline long Long.expand(long, long)
2226 bool LibraryCallKit::inline_bitshuffle_methods(vmIntrinsics::ID id) {
2227   Node* n = nullptr;
2228   switch (id) {
2229     case vmIntrinsics::_compress_i:  n = new CompressBitsNode(argument(0), argument(1), TypeInt::INT); break;
2230     case vmIntrinsics::_expand_i:    n = new ExpandBitsNode(argument(0),  argument(1), TypeInt::INT); break;
2231     case vmIntrinsics::_compress_l:  n = new CompressBitsNode(argument(0), argument(2), TypeLong::LONG); break;
2232     case vmIntrinsics::_expand_l:    n = new ExpandBitsNode(argument(0), argument(2), TypeLong::LONG); break;
2233     default:  fatal_unexpected_iid(id);  break;
2234   }
2235   set_result(_gvn.transform(n));
2236   return true;
2237 }
2238 
2239 //--------------------------inline_number_methods-----------------------------
2240 // inline int Integer.compareUnsigned(int, int)
2241 // inline int    Long.compareUnsigned(long, long)
2242 bool LibraryCallKit::inline_compare_unsigned(vmIntrinsics::ID id) {
2243   Node* arg1 = argument(0);
2244   Node* arg2 = (id == vmIntrinsics::_compareUnsigned_l) ? argument(2) : argument(1);
2245   Node* n = nullptr;
2246   switch (id) {
2247     case vmIntrinsics::_compareUnsigned_i:   n = new CmpU3Node(arg1, arg2);  break;
2248     case vmIntrinsics::_compareUnsigned_l:   n = new CmpUL3Node(arg1, arg2); break;
2249     default:  fatal_unexpected_iid(id);  break;
2250   }
2251   set_result(_gvn.transform(n));
2252   return true;
2253 }
2254 
2255 //--------------------------inline_unsigned_divmod_methods-----------------------------
2256 // inline int Integer.divideUnsigned(int, int)
2257 // inline int Integer.remainderUnsigned(int, int)
2258 // inline long Long.divideUnsigned(long, long)
2259 // inline long Long.remainderUnsigned(long, long)
2260 bool LibraryCallKit::inline_divmod_methods(vmIntrinsics::ID id) {
2261   Node* n = nullptr;
2262   switch (id) {
2263     case vmIntrinsics::_divideUnsigned_i: {
2264       zero_check_int(argument(1));
2265       // Compile-time detect of null-exception
2266       if (stopped()) {
2267         return true; // keep the graph constructed so far
2268       }
2269       n = new UDivINode(control(), argument(0), argument(1));
2270       break;
2271     }
2272     case vmIntrinsics::_divideUnsigned_l: {
2273       zero_check_long(argument(2));
2274       // Compile-time detect of null-exception
2275       if (stopped()) {
2276         return true; // keep the graph constructed so far
2277       }
2278       n = new UDivLNode(control(), argument(0), argument(2));
2279       break;
2280     }
2281     case vmIntrinsics::_remainderUnsigned_i: {
2282       zero_check_int(argument(1));
2283       // Compile-time detect of null-exception
2284       if (stopped()) {
2285         return true; // keep the graph constructed so far
2286       }
2287       n = new UModINode(control(), argument(0), argument(1));
2288       break;
2289     }
2290     case vmIntrinsics::_remainderUnsigned_l: {
2291       zero_check_long(argument(2));
2292       // Compile-time detect of null-exception
2293       if (stopped()) {
2294         return true; // keep the graph constructed so far
2295       }
2296       n = new UModLNode(control(), argument(0), argument(2));
2297       break;
2298     }
2299     default:  fatal_unexpected_iid(id);  break;
2300   }
2301   set_result(_gvn.transform(n));
2302   return true;
2303 }
2304 
2305 //----------------------------inline_unsafe_access----------------------------
2306 
2307 const TypeOopPtr* LibraryCallKit::sharpen_unsafe_type(Compile::AliasType* alias_type, const TypePtr *adr_type) {
2308   // Attempt to infer a sharper value type from the offset and base type.
2309   ciKlass* sharpened_klass = nullptr;
2310   bool null_free = false;
2311 
2312   // See if it is an instance field, with an object type.
2313   if (alias_type->field() != nullptr) {
2314     if (alias_type->field()->type()->is_klass()) {
2315       sharpened_klass = alias_type->field()->type()->as_klass();
2316       null_free = alias_type->field()->is_null_free();
2317     }
2318   }
2319 
2320   const TypeOopPtr* result = nullptr;
2321   // See if it is a narrow oop array.
2322   if (adr_type->isa_aryptr()) {
2323     if (adr_type->offset() >= refArrayOopDesc::base_offset_in_bytes()) {
2324       const TypeOopPtr* elem_type = adr_type->is_aryptr()->elem()->make_oopptr();
2325       null_free = adr_type->is_aryptr()->is_null_free();
2326       if (elem_type != nullptr && elem_type->is_loaded()) {
2327         // Sharpen the value type.
2328         result = elem_type;
2329       }
2330     }
2331   }
2332 
2333   // The sharpened class might be unloaded if there is no class loader
2334   // contraint in place.
2335   if (result == nullptr && sharpened_klass != nullptr && sharpened_klass->is_loaded()) {
2336     // Sharpen the value type.
2337     result = TypeOopPtr::make_from_klass(sharpened_klass);
2338     if (null_free) {
2339       result = result->join_speculative(TypePtr::NOTNULL)->is_oopptr();
2340     }
2341   }
2342   if (result != nullptr) {
2343 #ifndef PRODUCT
2344     if (C->print_intrinsics() || C->print_inlining()) {
2345       tty->print("  from base type:  ");  adr_type->dump(); tty->cr();
2346       tty->print("  sharpened value: ");  result->dump();    tty->cr();
2347     }
2348 #endif
2349   }
2350   return result;
2351 }
2352 
2353 DecoratorSet LibraryCallKit::mo_decorator_for_access_kind(AccessKind kind) {
2354   switch (kind) {
2355       case Relaxed:
2356         return MO_UNORDERED;
2357       case Opaque:
2358         return MO_RELAXED;
2359       case Acquire:
2360         return MO_ACQUIRE;
2361       case Release:
2362         return MO_RELEASE;
2363       case Volatile:
2364         return MO_SEQ_CST;
2365       default:
2366         ShouldNotReachHere();
2367         return 0;
2368   }
2369 }
2370 
2371 bool LibraryCallKit::inline_unsafe_access(bool is_store, const BasicType type, const AccessKind kind, const bool unaligned) {
2372   if (callee()->is_static())  return false;  // caller must have the capability!
2373   DecoratorSet decorators = C2_UNSAFE_ACCESS;
2374   guarantee(!is_store || kind != Acquire, "Acquire accesses can be produced only for loads");
2375   guarantee( is_store || kind != Release, "Release accesses can be produced only for stores");
2376   assert(type != T_OBJECT || !unaligned, "unaligned access not supported with object type");
2377 
2378   if (is_reference_type(type)) {
2379     decorators |= ON_UNKNOWN_OOP_REF;
2380   }
2381 
2382   if (unaligned) {
2383     decorators |= C2_UNALIGNED;
2384   }
2385 
2386 #ifndef PRODUCT
2387   {
2388     ResourceMark rm;
2389     // Check the signatures.
2390     ciSignature* sig = callee()->signature();
2391 #ifdef ASSERT
2392     if (!is_store) {
2393       // Object getReference(Object base, int/long offset), etc.
2394       BasicType rtype = sig->return_type()->basic_type();
2395       assert(rtype == type, "getter must return the expected value");
2396       assert(sig->count() == 2, "oop getter has 2 arguments");
2397       assert(sig->type_at(0)->basic_type() == T_OBJECT, "getter base is object");
2398       assert(sig->type_at(1)->basic_type() == T_LONG, "getter offset is correct");
2399     } else {
2400       // void putReference(Object base, int/long offset, Object x), etc.
2401       assert(sig->return_type()->basic_type() == T_VOID, "putter must not return a value");
2402       assert(sig->count() == 3, "oop putter has 3 arguments");
2403       assert(sig->type_at(0)->basic_type() == T_OBJECT, "putter base is object");
2404       assert(sig->type_at(1)->basic_type() == T_LONG, "putter offset is correct");
2405       BasicType vtype = sig->type_at(sig->count()-1)->basic_type();
2406       assert(vtype == type, "putter must accept the expected value");
2407     }
2408 #endif // ASSERT
2409  }
2410 #endif //PRODUCT
2411 
2412   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
2413 
2414   Node* receiver = argument(0);  // type: oop
2415 
2416   // Build address expression.
2417   Node* heap_base_oop = top();
2418 
2419   // The base is either a Java object or a value produced by Unsafe.staticFieldBase
2420   Node* base = argument(1);  // type: oop
2421   // The offset is a value produced by Unsafe.staticFieldOffset or Unsafe.objectFieldOffset
2422   Node* offset = argument(2);  // type: long
2423   // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
2424   // to be plain byte offsets, which are also the same as those accepted
2425   // by oopDesc::field_addr.
2426   assert(Unsafe_field_offset_to_byte_offset(11) == 11,
2427          "fieldOffset must be byte-scaled");
2428 
2429   if (base->is_InlineType()) {
2430     assert(!is_store, "InlineTypeNodes are non-larval value objects");
2431     InlineTypeNode* vt = base->as_InlineType();
2432     if (offset->is_Con()) {
2433       long off = find_long_con(offset, 0);
2434       ciInlineKlass* vk = vt->type()->inline_klass();
2435       if ((long)(int)off != off || !vk->contains_field_offset(off)) {
2436         return false;
2437       }
2438 
2439       ciField* field = vk->get_non_flat_field_by_offset(off);
2440       if (field != nullptr) {
2441         BasicType bt = type2field[field->type()->basic_type()];
2442         if (bt == T_ARRAY || bt == T_NARROWOOP) {
2443           bt = T_OBJECT;
2444         }
2445         if (bt == type && !field->is_flat()) {
2446           Node* value = vt->field_value_by_offset(off, false);
2447           const Type* value_type = _gvn.type(value);
2448           if (value_type->is_inlinetypeptr()) {
2449             value = InlineTypeNode::make_from_oop(this, value, value_type->inline_klass());
2450           }
2451           set_result(value);
2452           return true;
2453         }
2454       }
2455     }
2456     {
2457       // Re-execute the unsafe access if allocation triggers deoptimization.
2458       PreserveReexecuteState preexecs(this);
2459       jvms()->set_should_reexecute(true);
2460       vt = vt->buffer(this);
2461     }
2462     base = vt->get_oop();
2463   }
2464 
2465   // 32-bit machines ignore the high half!
2466   offset = ConvL2X(offset);
2467 
2468   // Save state and restore on bailout
2469   SavedState old_state(this);
2470 
2471   Node* adr = make_unsafe_address(base, offset, type, kind == Relaxed);
2472   assert(!stopped(), "Inlining of unsafe access failed: address construction stopped unexpectedly");
2473 
2474   if (_gvn.type(base->uncast())->isa_ptr() == TypePtr::NULL_PTR) {
2475     if (type != T_OBJECT) {
2476       decorators |= IN_NATIVE; // off-heap primitive access
2477     } else {
2478       return false; // off-heap oop accesses are not supported
2479     }
2480   } else {
2481     heap_base_oop = base; // on-heap or mixed access
2482   }
2483 
2484   // Can base be null? Otherwise, always on-heap access.
2485   bool can_access_non_heap = TypePtr::NULL_PTR->higher_equal(_gvn.type(base));
2486 
2487   if (!can_access_non_heap) {
2488     decorators |= IN_HEAP;
2489   }
2490 
2491   Node* val = is_store ? argument(4) : nullptr;
2492 
2493   const TypePtr* adr_type = _gvn.type(adr)->isa_ptr();
2494   if (adr_type == TypePtr::NULL_PTR) {
2495     return false; // off-heap access with zero address
2496   }
2497 
2498   // Try to categorize the address.
2499   Compile::AliasType* alias_type = C->alias_type(adr_type);
2500   assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
2501 
2502   if (alias_type->adr_type() == TypeInstPtr::KLASS ||
2503       alias_type->adr_type() == TypeAryPtr::RANGE) {
2504     return false; // not supported
2505   }
2506 
2507   bool mismatched = false;
2508   BasicType bt = T_ILLEGAL;
2509   ciField* field = nullptr;
2510   if (adr_type->isa_instptr()) {
2511     const TypeInstPtr* instptr = adr_type->is_instptr();
2512     ciInstanceKlass* k = instptr->instance_klass();
2513     int off = instptr->offset();
2514     if (instptr->const_oop() != nullptr &&
2515         k == ciEnv::current()->Class_klass() &&
2516         instptr->offset() >= (k->size_helper() * wordSize)) {
2517       k = instptr->const_oop()->as_instance()->java_lang_Class_klass()->as_instance_klass();
2518       field = k->get_field_by_offset(off, true);
2519     } else {
2520       field = k->get_non_flat_field_by_offset(off);
2521     }
2522     if (field != nullptr) {
2523       bt = type2field[field->type()->basic_type()];
2524     }
2525     if (bt != alias_type->basic_type()) {
2526       // Type mismatch. Is it an access to a nested flat field?
2527       field = k->get_field_by_offset(off, false);
2528       if (field != nullptr) {
2529         bt = type2field[field->type()->basic_type()];
2530       }
2531     }
2532     assert(bt == alias_type->basic_type(), "should match");
2533   } else {
2534     bt = alias_type->basic_type();
2535   }
2536 
2537   if (bt != T_ILLEGAL) {
2538     assert(alias_type->adr_type()->is_oopptr(), "should be on-heap access");
2539     if (bt == T_BYTE && adr_type->isa_aryptr()) {
2540       // Alias type doesn't differentiate between byte[] and boolean[]).
2541       // Use address type to get the element type.
2542       bt = adr_type->is_aryptr()->elem()->array_element_basic_type();
2543     }
2544     if (is_reference_type(bt, true)) {
2545       // accessing an array field with getReference is not a mismatch
2546       bt = T_OBJECT;
2547     }
2548     if ((bt == T_OBJECT) != (type == T_OBJECT)) {
2549       // Don't intrinsify mismatched object accesses
2550       return false;
2551     }
2552     mismatched = (bt != type);
2553   } else if (alias_type->adr_type()->isa_oopptr()) {
2554     mismatched = true; // conservatively mark all "wide" on-heap accesses as mismatched
2555   }
2556 
2557   old_state.discard();
2558   assert(!mismatched || alias_type->adr_type()->is_oopptr(), "off-heap access can't be mismatched");
2559 
2560   if (mismatched) {
2561     decorators |= C2_MISMATCHED;
2562   }
2563 
2564   // First guess at the value type.
2565   const Type *value_type = Type::get_const_basic_type(type);
2566 
2567   // Figure out the memory ordering.
2568   decorators |= mo_decorator_for_access_kind(kind);
2569 
2570   if (!is_store) {
2571     if (type == T_OBJECT) {
2572       const TypeOopPtr* tjp = sharpen_unsafe_type(alias_type, adr_type);
2573       if (tjp != nullptr) {
2574         value_type = tjp;
2575       }
2576     }
2577   }
2578 
2579   receiver = null_check(receiver);
2580   if (stopped()) {
2581     return true;
2582   }
2583   // Heap pointers get a null-check from the interpreter,
2584   // as a courtesy.  However, this is not guaranteed by Unsafe,
2585   // and it is not possible to fully distinguish unintended nulls
2586   // from intended ones in this API.
2587 
2588   if (!is_store) {
2589     Node* p = nullptr;
2590     // Try to constant fold a load from a constant field
2591 
2592     if (heap_base_oop != top() && field != nullptr && field->is_constant() && !field->is_flat() && !mismatched) {
2593       // final or stable field
2594       p = make_constant_from_field(field, heap_base_oop);
2595     }
2596 
2597     if (p == nullptr) { // Could not constant fold the load
2598       p = access_load_at(heap_base_oop, adr, adr_type, value_type, type, decorators);
2599       const TypeOopPtr* ptr = value_type->make_oopptr();
2600       if (ptr != nullptr && ptr->is_inlinetypeptr()) {
2601         // Load a non-flattened inline type from memory
2602         p = InlineTypeNode::make_from_oop(this, p, ptr->inline_klass());
2603       }
2604       // Normalize the value returned by getBoolean in the following cases
2605       if (type == T_BOOLEAN &&
2606           (mismatched ||
2607            heap_base_oop == top() ||                  // - heap_base_oop is null or
2608            (can_access_non_heap && field == nullptr)) // - heap_base_oop is potentially null
2609                                                       //   and the unsafe access is made to large offset
2610                                                       //   (i.e., larger than the maximum offset necessary for any
2611                                                       //   field access)
2612             ) {
2613           IdealKit ideal = IdealKit(this);
2614 #define __ ideal.
2615           IdealVariable normalized_result(ideal);
2616           __ declarations_done();
2617           __ set(normalized_result, p);
2618           __ if_then(p, BoolTest::ne, ideal.ConI(0));
2619           __ set(normalized_result, ideal.ConI(1));
2620           ideal.end_if();
2621           final_sync(ideal);
2622           p = __ value(normalized_result);
2623 #undef __
2624       }
2625     }
2626     if (type == T_ADDRESS) {
2627       p = gvn().transform(new CastP2XNode(nullptr, p));
2628       p = ConvX2UL(p);
2629     }
2630     // The load node has the control of the preceding MemBarCPUOrder.  All
2631     // following nodes will have the control of the MemBarCPUOrder inserted at
2632     // the end of this method.  So, pushing the load onto the stack at a later
2633     // point is fine.
2634     set_result(p);
2635   } else {
2636     if (bt == T_ADDRESS) {
2637       // Repackage the long as a pointer.
2638       val = ConvL2X(val);
2639       val = gvn().transform(new CastX2PNode(val));
2640     }
2641     access_store_at(heap_base_oop, adr, adr_type, val, value_type, type, decorators);
2642   }
2643 
2644   return true;
2645 }
2646 
2647 bool LibraryCallKit::inline_unsafe_flat_access(bool is_store, AccessKind kind) {
2648 #ifdef ASSERT
2649   {
2650     ResourceMark rm;
2651     // Check the signatures.
2652     ciSignature* sig = callee()->signature();
2653     assert(sig->type_at(0)->basic_type() == T_OBJECT, "base should be object, but is %s", type2name(sig->type_at(0)->basic_type()));
2654     assert(sig->type_at(1)->basic_type() == T_LONG, "offset should be long, but is %s", type2name(sig->type_at(1)->basic_type()));
2655     assert(sig->type_at(2)->basic_type() == T_INT, "layout kind should be int, but is %s", type2name(sig->type_at(3)->basic_type()));
2656     assert(sig->type_at(3)->basic_type() == T_OBJECT, "value klass should be object, but is %s", type2name(sig->type_at(4)->basic_type()));
2657     if (is_store) {
2658       assert(sig->return_type()->basic_type() == T_VOID, "putter must not return a value, but returns %s", type2name(sig->return_type()->basic_type()));
2659       assert(sig->count() == 5, "flat putter should have 5 arguments, but has %d", sig->count());
2660       assert(sig->type_at(4)->basic_type() == T_OBJECT, "put value should be object, but is %s", type2name(sig->type_at(5)->basic_type()));
2661     } else {
2662       assert(sig->return_type()->basic_type() == T_OBJECT, "getter must return an object, but returns %s", type2name(sig->return_type()->basic_type()));
2663       assert(sig->count() == 4, "flat getter should have 4 arguments, but has %d", sig->count());
2664     }
2665  }
2666 #endif // ASSERT
2667 
2668   assert(kind == Relaxed, "Only plain accesses for now");
2669   if (callee()->is_static()) {
2670     // caller must have the capability!
2671     return false;
2672   }
2673   C->set_has_unsafe_access(true);
2674 
2675   const TypeInstPtr* value_klass_node = _gvn.type(argument(5))->isa_instptr();
2676   if (value_klass_node == nullptr || value_klass_node->const_oop() == nullptr) {
2677     // parameter valueType is not a constant
2678     return false;
2679   }
2680   ciType* mirror_type = value_klass_node->const_oop()->as_instance()->java_mirror_type();
2681   if (!mirror_type->is_inlinetype()) {
2682     // Dead code
2683     return false;
2684   }
2685   ciInlineKlass* value_klass = mirror_type->as_inline_klass();
2686 
2687   const TypeInt* layout_type = _gvn.type(argument(4))->isa_int();
2688   if (layout_type == nullptr || !layout_type->is_con()) {
2689     // parameter layoutKind is not a constant
2690     return false;
2691   }
2692   assert(layout_type->get_con() >= static_cast<int>(LayoutKind::REFERENCE) &&
2693          layout_type->get_con() < static_cast<int>(LayoutKind::UNKNOWN),
2694          "invalid layoutKind %d", layout_type->get_con());
2695   LayoutKind layout = static_cast<LayoutKind>(layout_type->get_con());
2696   assert(layout == LayoutKind::REFERENCE || layout == LayoutKind::NULL_FREE_NON_ATOMIC_FLAT ||
2697          layout == LayoutKind::NULL_FREE_ATOMIC_FLAT || layout == LayoutKind::NULLABLE_ATOMIC_FLAT,
2698          "unexpected layoutKind %d", layout_type->get_con());
2699 
2700   null_check(argument(0));
2701   if (stopped()) {
2702     return true;
2703   }
2704 
2705   Node* base = must_be_not_null(argument(1), true);
2706   Node* offset = argument(2);
2707   const Type* base_type = _gvn.type(base);
2708 
2709   Node* ptr;
2710   bool immutable_memory = false;
2711   DecoratorSet decorators = C2_UNSAFE_ACCESS | IN_HEAP | MO_UNORDERED;
2712   if (base_type->isa_instptr()) {
2713     const TypeLong* offset_type = _gvn.type(offset)->isa_long();
2714     if (offset_type == nullptr || !offset_type->is_con()) {
2715       // Offset into a non-array should be a constant
2716       decorators |= C2_MISMATCHED;
2717     } else {
2718       int offset_con = checked_cast<int>(offset_type->get_con());
2719       ciInstanceKlass* base_klass = base_type->is_instptr()->instance_klass();
2720       ciField* field = base_klass->get_non_flat_field_by_offset(offset_con);
2721       if (field == nullptr) {
2722         assert(!base_klass->is_final(), "non-existence field at offset %d of class %s", offset_con, base_klass->name()->as_utf8());
2723         decorators |= C2_MISMATCHED;
2724       } else {
2725         assert(field->type() == value_klass, "field at offset %d of %s is of type %s, but valueType is %s",
2726                offset_con, base_klass->name()->as_utf8(), field->type()->name(), value_klass->name()->as_utf8());
2727         immutable_memory = field->is_strict() && field->is_final();
2728 
2729         if (base->is_InlineType()) {
2730           assert(!is_store, "Cannot store into a non-larval value object");
2731           set_result(base->as_InlineType()->field_value_by_offset(offset_con, false));
2732           return true;
2733         }
2734       }
2735     }
2736 
2737     if (base->is_InlineType()) {
2738       assert(!is_store, "Cannot store into a non-larval value object");
2739       base = base->as_InlineType()->buffer(this, true);
2740     }
2741     ptr = basic_plus_adr(base, ConvL2X(offset));
2742   } else if (base_type->isa_aryptr()) {
2743     decorators |= IS_ARRAY;
2744     if (layout == LayoutKind::REFERENCE) {
2745       if (!base_type->is_aryptr()->is_not_flat()) {
2746         const TypeAryPtr* array_type = base_type->is_aryptr()->cast_to_not_flat();
2747         // TODO 8350865 This should be a CheckCastPP, can we add a test?
2748         Node* new_base = _gvn.transform(new CastPPNode(control(), base, array_type, ConstraintCastNode::DependencyType::NonFloatingNarrowing));
2749         replace_in_map(base, new_base);
2750         base = new_base;
2751       }
2752       ptr = basic_plus_adr(base, ConvL2X(offset));
2753     } else {
2754       if (UseArrayFlattening) {
2755         // Flat array must have an exact type
2756         bool is_null_free = !LayoutKindHelper::is_nullable_flat(layout);
2757         bool is_atomic = LayoutKindHelper::is_atomic_flat(layout);
2758         Node* new_base = cast_to_flat_array_exact(base, value_klass, is_null_free, is_atomic);
2759         replace_in_map(base, new_base);
2760         base = new_base;
2761         ptr = basic_plus_adr(base, ConvL2X(offset));
2762         const TypeAryPtr* ptr_type = _gvn.type(ptr)->is_aryptr();
2763         if (ptr_type->field_offset().get() != 0) {
2764           // TODO 8350865 This should be a CheckCastPP, can we add a test?
2765           ptr = _gvn.transform(new CastPPNode(control(), ptr, ptr_type->with_field_offset(0), ConstraintCastNode::DependencyType::NonFloatingNarrowing));
2766         }
2767       } else {
2768         uncommon_trap(Deoptimization::Reason_intrinsic,
2769                       Deoptimization::Action_none);
2770         return true;
2771       }
2772     }
2773   } else {
2774     decorators |= C2_MISMATCHED;
2775     ptr = basic_plus_adr(base, ConvL2X(offset));
2776   }
2777 
2778   if (is_store) {
2779     Node* value = argument(6);
2780     const Type* value_type = _gvn.type(value);
2781     if (!value_type->is_inlinetypeptr()) {
2782       value_type = Type::get_const_type(value_klass)->filter_speculative(value_type);
2783       Node* new_value = _gvn.transform(new CheckCastPPNode(control(), value, value_type, ConstraintCastNode::DependencyType::NonFloatingNarrowing));
2784       new_value = InlineTypeNode::make_from_oop(this, new_value, value_klass);
2785       replace_in_map(value, new_value);
2786       value = new_value;
2787     }
2788 
2789     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());
2790     if (layout == LayoutKind::REFERENCE) {
2791       const TypePtr* ptr_type = (decorators & C2_MISMATCHED) != 0 ? TypeRawPtr::BOTTOM : _gvn.type(ptr)->is_ptr();
2792       access_store_at(base, ptr, ptr_type, value, value_type, T_OBJECT, decorators);
2793     } else {
2794       bool atomic = LayoutKindHelper::is_atomic_flat(layout);
2795       bool null_free = !LayoutKindHelper::is_nullable_flat(layout);
2796       value->as_InlineType()->store_flat(this, base, ptr, atomic, immutable_memory, null_free, decorators);
2797     }
2798 
2799     return true;
2800   } else {
2801     decorators |= (C2_CONTROL_DEPENDENT_LOAD | C2_UNKNOWN_CONTROL_LOAD);
2802     InlineTypeNode* result;
2803     if (layout == LayoutKind::REFERENCE) {
2804       const TypePtr* ptr_type = (decorators & C2_MISMATCHED) != 0 ? TypeRawPtr::BOTTOM : _gvn.type(ptr)->is_ptr();
2805       Node* oop = access_load_at(base, ptr, ptr_type, Type::get_const_type(value_klass), T_OBJECT, decorators);
2806       result = InlineTypeNode::make_from_oop(this, oop, value_klass);
2807     } else {
2808       bool atomic = LayoutKindHelper::is_atomic_flat(layout);
2809       bool null_free = !LayoutKindHelper::is_nullable_flat(layout);
2810       result = InlineTypeNode::make_from_flat(this, value_klass, base, ptr, atomic, immutable_memory, null_free, decorators);
2811     }
2812 
2813     set_result(result);
2814     return true;
2815   }
2816 }
2817 
2818 //----------------------------inline_unsafe_load_store----------------------------
2819 // This method serves a couple of different customers (depending on LoadStoreKind):
2820 //
2821 // LS_cmp_swap:
2822 //
2823 //   boolean compareAndSetReference(Object o, long offset, Object expected, Object x);
2824 //   boolean compareAndSetInt(   Object o, long offset, int    expected, int    x);
2825 //   boolean compareAndSetLong(  Object o, long offset, long   expected, long   x);
2826 //
2827 // LS_cmp_swap_weak:
2828 //
2829 //   boolean weakCompareAndSetReference(       Object o, long offset, Object expected, Object x);
2830 //   boolean weakCompareAndSetReferencePlain(  Object o, long offset, Object expected, Object x);
2831 //   boolean weakCompareAndSetReferenceAcquire(Object o, long offset, Object expected, Object x);
2832 //   boolean weakCompareAndSetReferenceRelease(Object o, long offset, Object expected, Object x);
2833 //
2834 //   boolean weakCompareAndSetInt(          Object o, long offset, int    expected, int    x);
2835 //   boolean weakCompareAndSetIntPlain(     Object o, long offset, int    expected, int    x);
2836 //   boolean weakCompareAndSetIntAcquire(   Object o, long offset, int    expected, int    x);
2837 //   boolean weakCompareAndSetIntRelease(   Object o, long offset, int    expected, int    x);
2838 //
2839 //   boolean weakCompareAndSetLong(         Object o, long offset, long   expected, long   x);
2840 //   boolean weakCompareAndSetLongPlain(    Object o, long offset, long   expected, long   x);
2841 //   boolean weakCompareAndSetLongAcquire(  Object o, long offset, long   expected, long   x);
2842 //   boolean weakCompareAndSetLongRelease(  Object o, long offset, long   expected, long   x);
2843 //
2844 // LS_cmp_exchange:
2845 //
2846 //   Object compareAndExchangeReferenceVolatile(Object o, long offset, Object expected, Object x);
2847 //   Object compareAndExchangeReferenceAcquire( Object o, long offset, Object expected, Object x);
2848 //   Object compareAndExchangeReferenceRelease( Object o, long offset, Object expected, Object x);
2849 //
2850 //   Object compareAndExchangeIntVolatile(   Object o, long offset, Object expected, Object x);
2851 //   Object compareAndExchangeIntAcquire(    Object o, long offset, Object expected, Object x);
2852 //   Object compareAndExchangeIntRelease(    Object o, long offset, Object expected, Object x);
2853 //
2854 //   Object compareAndExchangeLongVolatile(  Object o, long offset, Object expected, Object x);
2855 //   Object compareAndExchangeLongAcquire(   Object o, long offset, Object expected, Object x);
2856 //   Object compareAndExchangeLongRelease(   Object o, long offset, Object expected, Object x);
2857 //
2858 // LS_get_add:
2859 //
2860 //   int  getAndAddInt( Object o, long offset, int  delta)
2861 //   long getAndAddLong(Object o, long offset, long delta)
2862 //
2863 // LS_get_set:
2864 //
2865 //   int    getAndSet(Object o, long offset, int    newValue)
2866 //   long   getAndSet(Object o, long offset, long   newValue)
2867 //   Object getAndSet(Object o, long offset, Object newValue)
2868 //
2869 bool LibraryCallKit::inline_unsafe_load_store(const BasicType type, const LoadStoreKind kind, const AccessKind access_kind) {
2870   // This basic scheme here is the same as inline_unsafe_access, but
2871   // differs in enough details that combining them would make the code
2872   // overly confusing.  (This is a true fact! I originally combined
2873   // them, but even I was confused by it!) As much code/comments as
2874   // possible are retained from inline_unsafe_access though to make
2875   // the correspondences clearer. - dl
2876 
2877   if (callee()->is_static())  return false;  // caller must have the capability!
2878 
2879   DecoratorSet decorators = C2_UNSAFE_ACCESS;
2880   decorators |= mo_decorator_for_access_kind(access_kind);
2881 
2882 #ifndef PRODUCT
2883   BasicType rtype;
2884   {
2885     ResourceMark rm;
2886     // Check the signatures.
2887     ciSignature* sig = callee()->signature();
2888     rtype = sig->return_type()->basic_type();
2889     switch(kind) {
2890       case LS_get_add:
2891       case LS_get_set: {
2892       // Check the signatures.
2893 #ifdef ASSERT
2894       assert(rtype == type, "get and set must return the expected type");
2895       assert(sig->count() == 3, "get and set has 3 arguments");
2896       assert(sig->type_at(0)->basic_type() == T_OBJECT, "get and set base is object");
2897       assert(sig->type_at(1)->basic_type() == T_LONG, "get and set offset is long");
2898       assert(sig->type_at(2)->basic_type() == type, "get and set must take expected type as new value/delta");
2899       assert(access_kind == Volatile, "mo is not passed to intrinsic nodes in current implementation");
2900 #endif // ASSERT
2901         break;
2902       }
2903       case LS_cmp_swap:
2904       case LS_cmp_swap_weak: {
2905       // Check the signatures.
2906 #ifdef ASSERT
2907       assert(rtype == T_BOOLEAN, "CAS must return boolean");
2908       assert(sig->count() == 4, "CAS has 4 arguments");
2909       assert(sig->type_at(0)->basic_type() == T_OBJECT, "CAS base is object");
2910       assert(sig->type_at(1)->basic_type() == T_LONG, "CAS offset is long");
2911 #endif // ASSERT
2912         break;
2913       }
2914       case LS_cmp_exchange: {
2915       // Check the signatures.
2916 #ifdef ASSERT
2917       assert(rtype == type, "CAS must return the expected type");
2918       assert(sig->count() == 4, "CAS has 4 arguments");
2919       assert(sig->type_at(0)->basic_type() == T_OBJECT, "CAS base is object");
2920       assert(sig->type_at(1)->basic_type() == T_LONG, "CAS offset is long");
2921 #endif // ASSERT
2922         break;
2923       }
2924       default:
2925         ShouldNotReachHere();
2926     }
2927   }
2928 #endif //PRODUCT
2929 
2930   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
2931 
2932   // Get arguments:
2933   Node* receiver = nullptr;
2934   Node* base     = nullptr;
2935   Node* offset   = nullptr;
2936   Node* oldval   = nullptr;
2937   Node* newval   = nullptr;
2938   switch(kind) {
2939     case LS_cmp_swap:
2940     case LS_cmp_swap_weak:
2941     case LS_cmp_exchange: {
2942       const bool two_slot_type = type2size[type] == 2;
2943       receiver = argument(0);  // type: oop
2944       base     = argument(1);  // type: oop
2945       offset   = argument(2);  // type: long
2946       oldval   = argument(4);  // type: oop, int, or long
2947       newval   = argument(two_slot_type ? 6 : 5);  // type: oop, int, or long
2948       break;
2949     }
2950     case LS_get_add:
2951     case LS_get_set: {
2952       receiver = argument(0);  // type: oop
2953       base     = argument(1);  // type: oop
2954       offset   = argument(2);  // type: long
2955       oldval   = nullptr;
2956       newval   = argument(4);  // type: oop, int, or long
2957       break;
2958     }
2959     default:
2960       ShouldNotReachHere();
2961   }
2962 
2963   // Build field offset expression.
2964   // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
2965   // to be plain byte offsets, which are also the same as those accepted
2966   // by oopDesc::field_addr.
2967   assert(Unsafe_field_offset_to_byte_offset(11) == 11, "fieldOffset must be byte-scaled");
2968   // 32-bit machines ignore the high half of long offsets
2969   offset = ConvL2X(offset);
2970   // Save state and restore on bailout
2971   SavedState old_state(this);
2972   Node* adr = make_unsafe_address(base, offset,type, false);
2973   const TypePtr *adr_type = _gvn.type(adr)->isa_ptr();
2974 
2975   Compile::AliasType* alias_type = C->alias_type(adr_type);
2976   BasicType bt = alias_type->basic_type();
2977   if (bt != T_ILLEGAL &&
2978       (is_reference_type(bt) != (type == T_OBJECT))) {
2979     // Don't intrinsify mismatched object accesses.
2980     return false;
2981   }
2982 
2983   old_state.discard();
2984 
2985   // For CAS, unlike inline_unsafe_access, there seems no point in
2986   // trying to refine types. Just use the coarse types here.
2987   assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
2988   const Type *value_type = Type::get_const_basic_type(type);
2989 
2990   switch (kind) {
2991     case LS_get_set:
2992     case LS_cmp_exchange: {
2993       if (type == T_OBJECT) {
2994         const TypeOopPtr* tjp = sharpen_unsafe_type(alias_type, adr_type);
2995         if (tjp != nullptr) {
2996           value_type = tjp;
2997         }
2998       }
2999       break;
3000     }
3001     case LS_cmp_swap:
3002     case LS_cmp_swap_weak:
3003     case LS_get_add:
3004       break;
3005     default:
3006       ShouldNotReachHere();
3007   }
3008 
3009   // Null check receiver.
3010   receiver = null_check(receiver);
3011   if (stopped()) {
3012     return true;
3013   }
3014 
3015   int alias_idx = C->get_alias_index(adr_type);
3016 
3017   if (is_reference_type(type)) {
3018     decorators |= IN_HEAP | ON_UNKNOWN_OOP_REF;
3019 
3020     if (oldval != nullptr && oldval->is_InlineType()) {
3021       // Re-execute the unsafe access if allocation triggers deoptimization.
3022       PreserveReexecuteState preexecs(this);
3023       jvms()->set_should_reexecute(true);
3024       oldval = oldval->as_InlineType()->buffer(this)->get_oop();
3025     }
3026     if (newval != nullptr && newval->is_InlineType()) {
3027       // Re-execute the unsafe access if allocation triggers deoptimization.
3028       PreserveReexecuteState preexecs(this);
3029       jvms()->set_should_reexecute(true);
3030       newval = newval->as_InlineType()->buffer(this)->get_oop();
3031     }
3032 
3033     // Transformation of a value which could be null pointer (CastPP #null)
3034     // could be delayed during Parse (for example, in adjust_map_after_if()).
3035     // Execute transformation here to avoid barrier generation in such case.
3036     if (_gvn.type(newval) == TypePtr::NULL_PTR)
3037       newval = _gvn.makecon(TypePtr::NULL_PTR);
3038 
3039     if (oldval != nullptr && _gvn.type(oldval) == TypePtr::NULL_PTR) {
3040       // Refine the value to a null constant, when it is known to be null
3041       oldval = _gvn.makecon(TypePtr::NULL_PTR);
3042     }
3043   }
3044 
3045   Node* result = nullptr;
3046   switch (kind) {
3047     case LS_cmp_exchange: {
3048       result = access_atomic_cmpxchg_val_at(base, adr, adr_type, alias_idx,
3049                                             oldval, newval, value_type, type, decorators);
3050       break;
3051     }
3052     case LS_cmp_swap_weak:
3053       decorators |= C2_WEAK_CMPXCHG;
3054     case LS_cmp_swap: {
3055       result = access_atomic_cmpxchg_bool_at(base, adr, adr_type, alias_idx,
3056                                              oldval, newval, value_type, type, decorators);
3057       break;
3058     }
3059     case LS_get_set: {
3060       result = access_atomic_xchg_at(base, adr, adr_type, alias_idx,
3061                                      newval, value_type, type, decorators);
3062       break;
3063     }
3064     case LS_get_add: {
3065       result = access_atomic_add_at(base, adr, adr_type, alias_idx,
3066                                     newval, value_type, type, decorators);
3067       break;
3068     }
3069     default:
3070       ShouldNotReachHere();
3071   }
3072 
3073   assert(type2size[result->bottom_type()->basic_type()] == type2size[rtype], "result type should match");
3074   set_result(result);
3075   return true;
3076 }
3077 
3078 bool LibraryCallKit::inline_unsafe_fence(vmIntrinsics::ID id) {
3079   // Regardless of form, don't allow previous ld/st to move down,
3080   // then issue acquire, release, or volatile mem_bar.
3081   insert_mem_bar(Op_MemBarCPUOrder);
3082   switch(id) {
3083     case vmIntrinsics::_loadFence:
3084       insert_mem_bar(Op_LoadFence);
3085       return true;
3086     case vmIntrinsics::_storeFence:
3087       insert_mem_bar(Op_StoreFence);
3088       return true;
3089     case vmIntrinsics::_storeStoreFence:
3090       insert_mem_bar(Op_StoreStoreFence);
3091       return true;
3092     case vmIntrinsics::_fullFence:
3093       insert_mem_bar(Op_MemBarFull);
3094       return true;
3095     default:
3096       fatal_unexpected_iid(id);
3097       return false;
3098   }
3099 }
3100 
3101 // private native int arrayInstanceBaseOffset0(Object[] array);
3102 bool LibraryCallKit::inline_arrayInstanceBaseOffset() {
3103   Node* array = argument(1);
3104   Node* klass_node = load_object_klass(array);
3105 
3106   jint  layout_con = Klass::_lh_neutral_value;
3107   Node* layout_val = get_layout_helper(klass_node, layout_con);
3108   int   layout_is_con = (layout_val == nullptr);
3109 
3110   Node* header_size = nullptr;
3111   if (layout_is_con) {
3112     int hsize = Klass::layout_helper_header_size(layout_con);
3113     header_size = intcon(hsize);
3114   } else {
3115     Node* hss = intcon(Klass::_lh_header_size_shift);
3116     Node* hsm = intcon(Klass::_lh_header_size_mask);
3117     header_size = _gvn.transform(new URShiftINode(layout_val, hss));
3118     header_size = _gvn.transform(new AndINode(header_size, hsm));
3119   }
3120   set_result(header_size);
3121   return true;
3122 }
3123 
3124 // private native int arrayInstanceIndexScale0(Object[] array);
3125 bool LibraryCallKit::inline_arrayInstanceIndexScale() {
3126   Node* array = argument(1);
3127   Node* klass_node = load_object_klass(array);
3128 
3129   jint  layout_con = Klass::_lh_neutral_value;
3130   Node* layout_val = get_layout_helper(klass_node, layout_con);
3131   int   layout_is_con = (layout_val == nullptr);
3132 
3133   Node* element_size = nullptr;
3134   if (layout_is_con) {
3135     int log_element_size  = Klass::layout_helper_log2_element_size(layout_con);
3136     int elem_size = 1 << log_element_size;
3137     element_size = intcon(elem_size);
3138   } else {
3139     Node* ess = intcon(Klass::_lh_log2_element_size_shift);
3140     Node* esm = intcon(Klass::_lh_log2_element_size_mask);
3141     Node* log_element_size = _gvn.transform(new URShiftINode(layout_val, ess));
3142     log_element_size = _gvn.transform(new AndINode(log_element_size, esm));
3143     element_size = _gvn.transform(new LShiftINode(intcon(1), log_element_size));
3144   }
3145   set_result(element_size);
3146   return true;
3147 }
3148 
3149 // private native int arrayLayout0(Object[] array);
3150 bool LibraryCallKit::inline_arrayLayout() {
3151   RegionNode* region = new RegionNode(2);
3152   Node* phi = new PhiNode(region, TypeInt::POS);
3153 
3154   Node* array = argument(1);
3155   Node* klass_node = load_object_klass(array);
3156   generate_refArray_guard(klass_node, region);
3157   if (region->req() == 3) {
3158     phi->add_req(intcon((jint)LayoutKind::REFERENCE));
3159   }
3160 
3161   int layout_kind_offset = in_bytes(FlatArrayKlass::layout_kind_offset());
3162   Node* layout_kind_addr = basic_plus_adr(top(), klass_node, layout_kind_offset);
3163   Node* layout_kind = make_load(nullptr, layout_kind_addr, TypeInt::POS, T_INT, MemNode::unordered);
3164 
3165   region->init_req(1, control());
3166   phi->init_req(1, layout_kind);
3167 
3168   set_control(_gvn.transform(region));
3169   set_result(_gvn.transform(phi));
3170   return true;
3171 }
3172 
3173 // private native int[] getFieldMap0(Class <?> c);
3174 //   int offset = c._klass._acmp_maps_offset;
3175 //   return (int[])c.obj_field(offset);
3176 bool LibraryCallKit::inline_getFieldMap() {
3177   Node* mirror = argument(1);
3178   Node* klass = load_klass_from_mirror(mirror, false, nullptr, 0);
3179 
3180   int field_map_offset_offset = in_bytes(InstanceKlass::acmp_maps_offset_offset());
3181   Node* field_map_offset_addr = basic_plus_adr(top(), klass, field_map_offset_offset);
3182   Node* field_map_offset = make_load(nullptr, field_map_offset_addr, TypeInt::INT, T_INT, MemNode::unordered);
3183   field_map_offset = _gvn.transform(ConvI2L(field_map_offset));
3184 
3185   Node* map_addr = basic_plus_adr(mirror, field_map_offset);
3186   const TypeAryPtr* val_type = TypeAryPtr::INTS->cast_to_ptr_type(TypePtr::NotNull)->with_offset(0);
3187   Node* map = access_load_at(mirror, map_addr, TypeAryPtr::INTS, val_type, T_ARRAY, IN_HEAP | MO_UNORDERED);
3188 
3189   set_result(map);
3190   return true;
3191 }
3192 
3193 bool LibraryCallKit::inline_onspinwait() {
3194   insert_mem_bar(Op_OnSpinWait);
3195   return true;
3196 }
3197 
3198 bool LibraryCallKit::klass_needs_init_guard(Node* kls) {
3199   if (!kls->is_Con()) {
3200     return true;
3201   }
3202   const TypeInstKlassPtr* klsptr = kls->bottom_type()->isa_instklassptr();
3203   if (klsptr == nullptr) {
3204     return true;
3205   }
3206   ciInstanceKlass* ik = klsptr->instance_klass();
3207   // don't need a guard for a klass that is already initialized
3208   return !ik->is_initialized();
3209 }
3210 
3211 //----------------------------inline_unsafe_writeback0-------------------------
3212 // public native void Unsafe.writeback0(long address)
3213 bool LibraryCallKit::inline_unsafe_writeback0() {
3214   if (!Matcher::has_match_rule(Op_CacheWB)) {
3215     return false;
3216   }
3217 #ifndef PRODUCT
3218   assert(Matcher::has_match_rule(Op_CacheWBPreSync), "found match rule for CacheWB but not CacheWBPreSync");
3219   assert(Matcher::has_match_rule(Op_CacheWBPostSync), "found match rule for CacheWB but not CacheWBPostSync");
3220   ciSignature* sig = callee()->signature();
3221   assert(sig->type_at(0)->basic_type() == T_LONG, "Unsafe_writeback0 address is long!");
3222 #endif
3223   null_check_receiver();  // null-check, then ignore
3224   Node *addr = argument(1);
3225   addr = new CastX2PNode(addr);
3226   addr = _gvn.transform(addr);
3227   Node *flush = new CacheWBNode(control(), memory(TypeRawPtr::BOTTOM), addr);
3228   flush = _gvn.transform(flush);
3229   set_memory(flush, TypeRawPtr::BOTTOM);
3230   return true;
3231 }
3232 
3233 //----------------------------inline_unsafe_writeback0-------------------------
3234 // public native void Unsafe.writeback0(long address)
3235 bool LibraryCallKit::inline_unsafe_writebackSync0(bool is_pre) {
3236   if (is_pre && !Matcher::has_match_rule(Op_CacheWBPreSync)) {
3237     return false;
3238   }
3239   if (!is_pre && !Matcher::has_match_rule(Op_CacheWBPostSync)) {
3240     return false;
3241   }
3242 #ifndef PRODUCT
3243   assert(Matcher::has_match_rule(Op_CacheWB),
3244          (is_pre ? "found match rule for CacheWBPreSync but not CacheWB"
3245                 : "found match rule for CacheWBPostSync but not CacheWB"));
3246 
3247 #endif
3248   null_check_receiver();  // null-check, then ignore
3249   Node *sync;
3250   if (is_pre) {
3251     sync = new CacheWBPreSyncNode(control(), memory(TypeRawPtr::BOTTOM));
3252   } else {
3253     sync = new CacheWBPostSyncNode(control(), memory(TypeRawPtr::BOTTOM));
3254   }
3255   sync = _gvn.transform(sync);
3256   set_memory(sync, TypeRawPtr::BOTTOM);
3257   return true;
3258 }
3259 
3260 //----------------------------inline_unsafe_allocate---------------------------
3261 // public native Object Unsafe.allocateInstance(Class<?> cls);
3262 bool LibraryCallKit::inline_unsafe_allocate() {
3263 
3264 #if INCLUDE_JVMTI
3265   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
3266     return false;
3267   }
3268 #endif //INCLUDE_JVMTI
3269 
3270   if (callee()->is_static())  return false;  // caller must have the capability!
3271 
3272   null_check_receiver();  // null-check, then ignore
3273   Node* cls = null_check(argument(1));
3274   if (stopped())  return true;
3275 
3276   Node* kls = load_klass_from_mirror(cls, false, nullptr, 0);
3277   kls = null_check(kls);
3278   if (stopped())  return true;  // argument was like int.class
3279 
3280 #if INCLUDE_JVMTI
3281     // Don't try to access new allocated obj in the intrinsic.
3282     // It causes perfomance issues even when jvmti event VmObjectAlloc is disabled.
3283     // Deoptimize and allocate in interpreter instead.
3284     Node* addr = makecon(TypeRawPtr::make((address) &JvmtiExport::_should_notify_object_alloc));
3285     Node* should_post_vm_object_alloc = make_load(this->control(), addr, TypeInt::INT, T_INT, MemNode::unordered);
3286     Node* chk = _gvn.transform(new CmpINode(should_post_vm_object_alloc, intcon(0)));
3287     Node* tst = _gvn.transform(new BoolNode(chk, BoolTest::eq));
3288     {
3289       BuildCutout unless(this, tst, PROB_MAX);
3290       uncommon_trap(Deoptimization::Reason_intrinsic,
3291                     Deoptimization::Action_make_not_entrant);
3292     }
3293     if (stopped()) {
3294       return true;
3295     }
3296 #endif //INCLUDE_JVMTI
3297 
3298   Node* test = nullptr;
3299   if (LibraryCallKit::klass_needs_init_guard(kls)) {
3300     // Note:  The argument might still be an illegal value like
3301     // Serializable.class or Object[].class.   The runtime will handle it.
3302     // But we must make an explicit check for initialization.
3303     Node* insp = off_heap_plus_addr(kls, in_bytes(InstanceKlass::init_state_offset()));
3304     // Use T_BOOLEAN for InstanceKlass::_init_state so the compiler
3305     // can generate code to load it as unsigned byte.
3306     Node* inst = make_load(nullptr, insp, TypeInt::UBYTE, T_BOOLEAN, MemNode::acquire);
3307     Node* bits = intcon(InstanceKlass::fully_initialized);
3308     test = _gvn.transform(new SubINode(inst, bits));
3309     // The 'test' is non-zero if we need to take a slow path.
3310   }
3311   Node* obj = new_instance(kls, test);
3312   set_result(obj);
3313   return true;
3314 }
3315 
3316 //------------------------inline_native_time_funcs--------------
3317 // inline code for System.currentTimeMillis() and System.nanoTime()
3318 // these have the same type and signature
3319 bool LibraryCallKit::inline_native_time_funcs(address funcAddr, const char* funcName) {
3320   const TypeFunc* tf = OptoRuntime::void_long_Type();
3321   const TypePtr* no_memory_effects = nullptr;
3322   Node* time = make_runtime_call(RC_LEAF, tf, funcAddr, funcName, no_memory_effects);
3323   Node* value = _gvn.transform(new ProjNode(time, TypeFunc::Parms+0));
3324 #ifdef ASSERT
3325   Node* value_top = _gvn.transform(new ProjNode(time, TypeFunc::Parms+1));
3326   assert(value_top == top(), "second value must be top");
3327 #endif
3328   set_result(value);
3329   return true;
3330 }
3331 
3332 //--------------------inline_native_vthread_start_transition--------------------
3333 // inline void startTransition(boolean is_mount);
3334 // inline void startFinalTransition();
3335 // Pseudocode of implementation:
3336 //
3337 // java_lang_Thread::set_is_in_vthread_transition(vthread, true);
3338 // carrier->set_is_in_vthread_transition(true);
3339 // OrderAccess::storeload();
3340 // int disable_requests = java_lang_Thread::vthread_transition_disable_count(vthread)
3341 //                        + global_vthread_transition_disable_count();
3342 // if (disable_requests > 0) {
3343 //   slow path: runtime call
3344 // }
3345 bool LibraryCallKit::inline_native_vthread_start_transition(address funcAddr, const char* funcName, bool is_final_transition) {
3346   Node* vt_oop = must_be_not_null(argument(0), true); // VirtualThread this argument
3347   IdealKit ideal(this);
3348 
3349   Node* thread = ideal.thread();
3350   Node* jt_addr = off_heap_plus_addr(thread, in_bytes(JavaThread::is_in_vthread_transition_offset()));
3351   Node* vt_addr = basic_plus_adr(vt_oop, java_lang_Thread::is_in_vthread_transition_offset());
3352   access_store_at(nullptr, jt_addr, _gvn.type(jt_addr)->is_ptr(), ideal.ConI(1), TypeInt::BOOL, T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
3353   access_store_at(nullptr, vt_addr, _gvn.type(vt_addr)->is_ptr(), ideal.ConI(1), TypeInt::BOOL, T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
3354   insert_mem_bar(Op_MemBarStoreLoad);
3355   ideal.sync_kit(this);
3356 
3357   Node* global_disable_addr = makecon(TypeRawPtr::make((address)MountUnmountDisabler::global_vthread_transition_disable_count_address()));
3358   Node* global_disable = ideal.load(ideal.ctrl(), global_disable_addr, TypeInt::INT, T_INT, Compile::AliasIdxRaw, true /*require_atomic_access*/);
3359   Node* vt_disable_addr = basic_plus_adr(vt_oop, java_lang_Thread::vthread_transition_disable_count_offset());
3360   const TypePtr* vt_disable_addr_t = _gvn.type(vt_disable_addr)->is_ptr();
3361   Node* vt_disable = ideal.load(ideal.ctrl(), vt_disable_addr, TypeInt::INT, T_INT, C->get_alias_index(vt_disable_addr_t), true /*require_atomic_access*/);
3362   Node* disabled = _gvn.transform(new AddINode(global_disable, vt_disable));
3363 
3364   ideal.if_then(disabled, BoolTest::ne, ideal.ConI(0)); {
3365     sync_kit(ideal);
3366     Node* is_mount = is_final_transition ? ideal.ConI(0) : argument(1);
3367     const TypeFunc* tf = OptoRuntime::vthread_transition_Type();
3368     make_runtime_call(RC_NO_LEAF, tf, funcAddr, funcName, TypePtr::BOTTOM, vt_oop, is_mount);
3369     ideal.sync_kit(this);
3370   }
3371   ideal.end_if();
3372 
3373   final_sync(ideal);
3374   return true;
3375 }
3376 
3377 bool LibraryCallKit::inline_native_vthread_end_transition(address funcAddr, const char* funcName, bool is_first_transition) {
3378   Node* vt_oop = must_be_not_null(argument(0), true); // VirtualThread this argument
3379   IdealKit ideal(this);
3380 
3381   Node* _notify_jvmti_addr = makecon(TypeRawPtr::make((address)MountUnmountDisabler::notify_jvmti_events_address()));
3382   Node* _notify_jvmti = ideal.load(ideal.ctrl(), _notify_jvmti_addr, TypeInt::BOOL, T_BOOLEAN, Compile::AliasIdxRaw);
3383 
3384   ideal.if_then(_notify_jvmti, BoolTest::eq, ideal.ConI(1)); {
3385     sync_kit(ideal);
3386     Node* is_mount = is_first_transition ? ideal.ConI(1) : argument(1);
3387     const TypeFunc* tf = OptoRuntime::vthread_transition_Type();
3388     make_runtime_call(RC_NO_LEAF, tf, funcAddr, funcName, TypePtr::BOTTOM, vt_oop, is_mount);
3389     ideal.sync_kit(this);
3390   } ideal.else_(); {
3391     Node* thread = ideal.thread();
3392     Node* jt_addr = off_heap_plus_addr(thread, in_bytes(JavaThread::is_in_vthread_transition_offset()));
3393     Node* vt_addr = basic_plus_adr(vt_oop, java_lang_Thread::is_in_vthread_transition_offset());
3394 
3395     sync_kit(ideal);
3396     access_store_at(nullptr, jt_addr, _gvn.type(jt_addr)->is_ptr(), ideal.ConI(0), TypeInt::BOOL, T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
3397     access_store_at(nullptr, vt_addr, _gvn.type(vt_addr)->is_ptr(), ideal.ConI(0), TypeInt::BOOL, T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
3398     ideal.sync_kit(this);
3399   } ideal.end_if();
3400 
3401   final_sync(ideal);
3402   return true;
3403 }
3404 
3405 #if INCLUDE_JVMTI
3406 
3407 // Always update the is_disable_suspend bit.
3408 bool LibraryCallKit::inline_native_notify_jvmti_sync() {
3409   if (!DoJVMTIVirtualThreadTransitions) {
3410     return true;
3411   }
3412   IdealKit ideal(this);
3413 
3414   {
3415     // unconditionally update the is_disable_suspend bit in current JavaThread
3416     Node* thread = ideal.thread();
3417     Node* arg = argument(0); // argument for notification
3418     Node* addr = off_heap_plus_addr(thread, in_bytes(JavaThread::is_disable_suspend_offset()));
3419     const TypePtr *addr_type = _gvn.type(addr)->isa_ptr();
3420 
3421     sync_kit(ideal);
3422     access_store_at(nullptr, addr, addr_type, arg, _gvn.type(arg), T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
3423     ideal.sync_kit(this);
3424   }
3425   final_sync(ideal);
3426 
3427   return true;
3428 }
3429 
3430 #endif // INCLUDE_JVMTI
3431 
3432 #ifdef JFR_HAVE_INTRINSICS
3433 
3434 /**
3435  * if oop->klass != null
3436  *   // normal class
3437  *   epoch = _epoch_state ? 2 : 1
3438  *   if oop->klass->trace_id & ((epoch << META_SHIFT) | epoch)) != epoch {
3439  *     ... // enter slow path when the klass is first recorded or the epoch of JFR shifts
3440  *   }
3441  *   id = oop->klass->trace_id >> TRACE_ID_SHIFT // normal class path
3442  * else
3443  *   // primitive class
3444  *   if oop->array_klass != null
3445  *     id = (oop->array_klass->trace_id >> TRACE_ID_SHIFT) + 1 // primitive class path
3446  *   else
3447  *     id = LAST_TYPE_ID + 1 // void class path
3448  *   if (!signaled)
3449  *     signaled = true
3450  */
3451 bool LibraryCallKit::inline_native_classID() {
3452   Node* cls = argument(0);
3453 
3454   IdealKit ideal(this);
3455 #define __ ideal.
3456   IdealVariable result(ideal); __ declarations_done();
3457   Node* kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(),
3458                                                  basic_plus_adr(cls, java_lang_Class::klass_offset()),
3459                                                  TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
3460 
3461 
3462   __ if_then(kls, BoolTest::ne, null()); {
3463     Node* kls_trace_id_addr = basic_plus_adr(kls, in_bytes(KLASS_TRACE_ID_OFFSET));
3464     Node* kls_trace_id_raw = ideal.load(ideal.ctrl(), kls_trace_id_addr,TypeLong::LONG, T_LONG, Compile::AliasIdxRaw);
3465 
3466     Node* epoch_address = makecon(TypeRawPtr::make(JfrIntrinsicSupport::epoch_address()));
3467     Node* epoch = ideal.load(ideal.ctrl(), epoch_address, TypeInt::BOOL, T_BOOLEAN, Compile::AliasIdxRaw);
3468     epoch = _gvn.transform(new LShiftLNode(longcon(1), epoch));
3469     Node* mask = _gvn.transform(new LShiftLNode(epoch, intcon(META_SHIFT)));
3470     mask = _gvn.transform(new OrLNode(mask, epoch));
3471     Node* kls_trace_id_raw_and_mask = _gvn.transform(new AndLNode(kls_trace_id_raw, mask));
3472 
3473     float unlikely  = PROB_UNLIKELY(0.999);
3474     __ if_then(kls_trace_id_raw_and_mask, BoolTest::ne, epoch, unlikely); {
3475       sync_kit(ideal);
3476       make_runtime_call(RC_LEAF,
3477                         OptoRuntime::class_id_load_barrier_Type(),
3478                         CAST_FROM_FN_PTR(address, JfrIntrinsicSupport::load_barrier),
3479                         "class id load barrier",
3480                         TypePtr::BOTTOM,
3481                         kls);
3482       ideal.sync_kit(this);
3483     } __ end_if();
3484 
3485     ideal.set(result,  _gvn.transform(new URShiftLNode(kls_trace_id_raw, ideal.ConI(TRACE_ID_SHIFT))));
3486   } __ else_(); {
3487     Node* array_kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(),
3488                                                    basic_plus_adr(cls, java_lang_Class::array_klass_offset()),
3489                                                    TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
3490     __ if_then(array_kls, BoolTest::ne, null()); {
3491       Node* array_kls_trace_id_addr = basic_plus_adr(array_kls, in_bytes(KLASS_TRACE_ID_OFFSET));
3492       Node* array_kls_trace_id_raw = ideal.load(ideal.ctrl(), array_kls_trace_id_addr, TypeLong::LONG, T_LONG, Compile::AliasIdxRaw);
3493       Node* array_kls_trace_id = _gvn.transform(new URShiftLNode(array_kls_trace_id_raw, ideal.ConI(TRACE_ID_SHIFT)));
3494       ideal.set(result, _gvn.transform(new AddLNode(array_kls_trace_id, longcon(1))));
3495     } __ else_(); {
3496       // void class case
3497       ideal.set(result, longcon(LAST_TYPE_ID + 1));
3498     } __ end_if();
3499 
3500     Node* signaled_flag_address = makecon(TypeRawPtr::make(JfrIntrinsicSupport::signal_address()));
3501     Node* signaled = ideal.load(ideal.ctrl(), signaled_flag_address, TypeInt::BOOL, T_BOOLEAN, Compile::AliasIdxRaw, true, MemNode::acquire);
3502     __ if_then(signaled, BoolTest::ne, ideal.ConI(1)); {
3503       ideal.store(ideal.ctrl(), signaled_flag_address, ideal.ConI(1), T_BOOLEAN, Compile::AliasIdxRaw, MemNode::release, true);
3504     } __ end_if();
3505   } __ end_if();
3506 
3507   final_sync(ideal);
3508   set_result(ideal.value(result));
3509 #undef __
3510   return true;
3511 }
3512 
3513 //------------------------inline_native_jvm_commit------------------
3514 bool LibraryCallKit::inline_native_jvm_commit() {
3515   enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
3516 
3517   // Save input memory and i_o state.
3518   Node* input_memory_state = reset_memory();
3519   set_all_memory(input_memory_state);
3520   Node* input_io_state = i_o();
3521 
3522   // TLS.
3523   Node* tls_ptr = _gvn.transform(new ThreadLocalNode());
3524   // Jfr java buffer.
3525   Node* java_buffer_offset = _gvn.transform(AddPNode::make_off_heap(tls_ptr, MakeConX(in_bytes(JAVA_BUFFER_OFFSET_JFR))));
3526   Node* java_buffer = _gvn.transform(new LoadPNode(control(), input_memory_state, java_buffer_offset, TypePtr::BOTTOM, TypeRawPtr::NOTNULL, MemNode::unordered));
3527   Node* java_buffer_pos_offset = _gvn.transform(AddPNode::make_off_heap(java_buffer, MakeConX(in_bytes(JFR_BUFFER_POS_OFFSET))));
3528 
3529   // Load the current value of the notified field in the JfrThreadLocal.
3530   Node* notified_offset = off_heap_plus_addr(tls_ptr, in_bytes(NOTIFY_OFFSET_JFR));
3531   Node* notified = make_load(control(), notified_offset, TypeInt::BOOL, T_BOOLEAN, MemNode::unordered);
3532 
3533   // Test for notification.
3534   Node* notified_cmp = _gvn.transform(new CmpINode(notified, _gvn.intcon(1)));
3535   Node* test_notified = _gvn.transform(new BoolNode(notified_cmp, BoolTest::eq));
3536   IfNode* iff_notified = create_and_map_if(control(), test_notified, PROB_MIN, COUNT_UNKNOWN);
3537 
3538   // True branch, is notified.
3539   Node* is_notified = _gvn.transform(new IfTrueNode(iff_notified));
3540   set_control(is_notified);
3541 
3542   // Reset notified state.
3543   store_to_memory(control(), notified_offset, _gvn.intcon(0), T_BOOLEAN, MemNode::unordered);
3544   Node* notified_reset_memory = reset_memory();
3545 
3546   // Iff notified, the return address of the commit method is the current position of the backing java buffer. This is used to reset the event writer.
3547   Node* current_pos_X = _gvn.transform(new LoadXNode(control(), input_memory_state, java_buffer_pos_offset, TypeRawPtr::NOTNULL, TypeX_X, MemNode::unordered));
3548   // Convert the machine-word to a long.
3549   Node* current_pos = ConvX2L(current_pos_X);
3550 
3551   // False branch, not notified.
3552   Node* not_notified = _gvn.transform(new IfFalseNode(iff_notified));
3553   set_control(not_notified);
3554   set_all_memory(input_memory_state);
3555 
3556   // Arg is the next position as a long.
3557   Node* arg = argument(0);
3558   // Convert long to machine-word.
3559   Node* next_pos_X = ConvL2X(arg);
3560 
3561   // Store the next_position to the underlying jfr java buffer.
3562   store_to_memory(control(), java_buffer_pos_offset, next_pos_X, LP64_ONLY(T_LONG) NOT_LP64(T_INT), MemNode::release);
3563 
3564   Node* commit_memory = reset_memory();
3565   set_all_memory(commit_memory);
3566 
3567   // Now load the flags from off the java buffer and decide if the buffer is a lease. If so, it needs to be returned post-commit.
3568   Node* java_buffer_flags_offset = _gvn.transform(AddPNode::make_off_heap(java_buffer, MakeConX(in_bytes(JFR_BUFFER_FLAGS_OFFSET))));
3569   Node* flags = make_load(control(), java_buffer_flags_offset, TypeInt::UBYTE, T_BYTE, MemNode::unordered);
3570   Node* lease_constant = _gvn.intcon(4);
3571 
3572   // And flags with lease constant.
3573   Node* lease = _gvn.transform(new AndINode(flags, lease_constant));
3574 
3575   // Branch on lease to conditionalize returning the leased java buffer.
3576   Node* lease_cmp = _gvn.transform(new CmpINode(lease, lease_constant));
3577   Node* test_lease = _gvn.transform(new BoolNode(lease_cmp, BoolTest::eq));
3578   IfNode* iff_lease = create_and_map_if(control(), test_lease, PROB_MIN, COUNT_UNKNOWN);
3579 
3580   // False branch, not a lease.
3581   Node* not_lease = _gvn.transform(new IfFalseNode(iff_lease));
3582 
3583   // True branch, is lease.
3584   Node* is_lease = _gvn.transform(new IfTrueNode(iff_lease));
3585   set_control(is_lease);
3586 
3587   // Make a runtime call, which can safepoint, to return the leased buffer. This updates both the JfrThreadLocal and the Java event writer oop.
3588   Node* call_return_lease = make_runtime_call(RC_NO_LEAF,
3589                                               OptoRuntime::void_void_Type(),
3590                                               SharedRuntime::jfr_return_lease(),
3591                                               "return_lease", TypePtr::BOTTOM);
3592   Node* call_return_lease_control = _gvn.transform(new ProjNode(call_return_lease, TypeFunc::Control));
3593 
3594   RegionNode* lease_compare_rgn = new RegionNode(PATH_LIMIT);
3595   record_for_igvn(lease_compare_rgn);
3596   PhiNode* lease_compare_mem = new PhiNode(lease_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3597   record_for_igvn(lease_compare_mem);
3598   PhiNode* lease_compare_io = new PhiNode(lease_compare_rgn, Type::ABIO);
3599   record_for_igvn(lease_compare_io);
3600   PhiNode* lease_result_value = new PhiNode(lease_compare_rgn, TypeLong::LONG);
3601   record_for_igvn(lease_result_value);
3602 
3603   // Update control and phi nodes.
3604   lease_compare_rgn->init_req(_true_path, call_return_lease_control);
3605   lease_compare_rgn->init_req(_false_path, not_lease);
3606 
3607   lease_compare_mem->init_req(_true_path, reset_memory());
3608   lease_compare_mem->init_req(_false_path, commit_memory);
3609 
3610   lease_compare_io->init_req(_true_path, i_o());
3611   lease_compare_io->init_req(_false_path, input_io_state);
3612 
3613   lease_result_value->init_req(_true_path, _gvn.longcon(0)); // if the lease was returned, return 0L.
3614   lease_result_value->init_req(_false_path, arg); // if not lease, return new updated position.
3615 
3616   RegionNode* result_rgn = new RegionNode(PATH_LIMIT);
3617   PhiNode* result_mem = new PhiNode(result_rgn, Type::MEMORY, TypePtr::BOTTOM);
3618   PhiNode* result_io = new PhiNode(result_rgn, Type::ABIO);
3619   PhiNode* result_value = new PhiNode(result_rgn, TypeLong::LONG);
3620 
3621   // Update control and phi nodes.
3622   result_rgn->init_req(_true_path, is_notified);
3623   result_rgn->init_req(_false_path, _gvn.transform(lease_compare_rgn));
3624 
3625   result_mem->init_req(_true_path, notified_reset_memory);
3626   result_mem->init_req(_false_path, _gvn.transform(lease_compare_mem));
3627 
3628   result_io->init_req(_true_path, input_io_state);
3629   result_io->init_req(_false_path, _gvn.transform(lease_compare_io));
3630 
3631   result_value->init_req(_true_path, current_pos);
3632   result_value->init_req(_false_path, _gvn.transform(lease_result_value));
3633 
3634   // Set output state.
3635   set_control(_gvn.transform(result_rgn));
3636   set_all_memory(_gvn.transform(result_mem));
3637   set_i_o(_gvn.transform(result_io));
3638   set_result(result_rgn, result_value);
3639   return true;
3640 }
3641 
3642 /*
3643  * The intrinsic is a model of this pseudo-code:
3644  *
3645  * JfrThreadLocal* const tl = Thread::jfr_thread_local()
3646  * jobject h_event_writer = tl->java_event_writer();
3647  * if (h_event_writer == nullptr) {
3648  *   return nullptr;
3649  * }
3650  * oop threadObj = Thread::threadObj();
3651  * oop vthread = java_lang_Thread::vthread(threadObj);
3652  * traceid tid;
3653  * bool pinVirtualThread;
3654  * bool excluded;
3655  * if (vthread != threadObj) {  // i.e. current thread is virtual
3656  *   tid = java_lang_Thread::tid(vthread);
3657  *   u2 vthread_epoch_raw = java_lang_Thread::jfr_epoch(vthread);
3658  *   pinVirtualThread = VMContinuations;
3659  *   excluded = vthread_epoch_raw & excluded_mask;
3660  *   if (!excluded) {
3661  *     traceid current_epoch = JfrTraceIdEpoch::current_generation();
3662  *     u2 vthread_epoch = vthread_epoch_raw & epoch_mask;
3663  *     if (vthread_epoch != current_epoch) {
3664  *       write_checkpoint();
3665  *     }
3666  *   }
3667  * } else {
3668  *   tid = java_lang_Thread::tid(threadObj);
3669  *   u2 thread_epoch_raw = java_lang_Thread::jfr_epoch(threadObj);
3670  *   pinVirtualThread = false;
3671  *   excluded = thread_epoch_raw & excluded_mask;
3672  * }
3673  * oop event_writer = JNIHandles::resolve_non_null(h_event_writer);
3674  * traceid tid_in_event_writer = getField(event_writer, "threadID");
3675  * if (tid_in_event_writer != tid) {
3676  *   setField(event_writer, "pinVirtualThread", pinVirtualThread);
3677  *   setField(event_writer, "excluded", excluded);
3678  *   setField(event_writer, "threadID", tid);
3679  * }
3680  * return event_writer
3681  */
3682 bool LibraryCallKit::inline_native_getEventWriter() {
3683   enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
3684 
3685   // Save input memory and i_o state.
3686   Node* input_memory_state = reset_memory();
3687   set_all_memory(input_memory_state);
3688   Node* input_io_state = i_o();
3689 
3690   // The most significant bit of the u2 is used to denote thread exclusion
3691   Node* excluded_shift = _gvn.intcon(15);
3692   Node* excluded_mask = _gvn.intcon(1 << 15);
3693   // The epoch generation is the range [1-32767]
3694   Node* epoch_mask = _gvn.intcon(32767);
3695 
3696   // TLS
3697   Node* tls_ptr = _gvn.transform(new ThreadLocalNode());
3698 
3699   // Load the address of java event writer jobject handle from the jfr_thread_local structure.
3700   Node* jobj_ptr = off_heap_plus_addr(tls_ptr, in_bytes(THREAD_LOCAL_WRITER_OFFSET_JFR));
3701 
3702   // Load the eventwriter jobject handle.
3703   Node* jobj = make_load(control(), jobj_ptr, TypeRawPtr::BOTTOM, T_ADDRESS, MemNode::unordered);
3704 
3705   // Null check the jobject handle.
3706   Node* jobj_cmp_null = _gvn.transform(new CmpPNode(jobj, null()));
3707   Node* test_jobj_not_equal_null = _gvn.transform(new BoolNode(jobj_cmp_null, BoolTest::ne));
3708   IfNode* iff_jobj_not_equal_null = create_and_map_if(control(), test_jobj_not_equal_null, PROB_MAX, COUNT_UNKNOWN);
3709 
3710   // False path, jobj is null.
3711   Node* jobj_is_null = _gvn.transform(new IfFalseNode(iff_jobj_not_equal_null));
3712 
3713   // True path, jobj is not null.
3714   Node* jobj_is_not_null = _gvn.transform(new IfTrueNode(iff_jobj_not_equal_null));
3715 
3716   set_control(jobj_is_not_null);
3717 
3718   // Load the threadObj for the CarrierThread.
3719   Node* threadObj = generate_current_thread(tls_ptr);
3720 
3721   // Load the vthread.
3722   Node* vthread = generate_virtual_thread(tls_ptr);
3723 
3724   // If vthread != threadObj, this is a virtual thread.
3725   Node* vthread_cmp_threadObj = _gvn.transform(new CmpPNode(vthread, threadObj));
3726   Node* test_vthread_not_equal_threadObj = _gvn.transform(new BoolNode(vthread_cmp_threadObj, BoolTest::ne));
3727   IfNode* iff_vthread_not_equal_threadObj =
3728     create_and_map_if(jobj_is_not_null, test_vthread_not_equal_threadObj, PROB_FAIR, COUNT_UNKNOWN);
3729 
3730   // False branch, fallback to threadObj.
3731   Node* vthread_equal_threadObj = _gvn.transform(new IfFalseNode(iff_vthread_not_equal_threadObj));
3732   set_control(vthread_equal_threadObj);
3733 
3734   // Load the tid field from the vthread object.
3735   Node* thread_obj_tid = load_field_from_object(threadObj, "tid", "J");
3736 
3737   // Load the raw epoch value from the threadObj.
3738   Node* threadObj_epoch_offset = basic_plus_adr(threadObj, java_lang_Thread::jfr_epoch_offset());
3739   Node* threadObj_epoch_raw = access_load_at(threadObj, threadObj_epoch_offset,
3740                                              _gvn.type(threadObj_epoch_offset)->isa_ptr(),
3741                                              TypeInt::CHAR, T_CHAR,
3742                                              IN_HEAP | MO_UNORDERED | C2_MISMATCHED | C2_CONTROL_DEPENDENT_LOAD);
3743 
3744   // Mask off the excluded information from the epoch.
3745   Node * threadObj_is_excluded = _gvn.transform(new AndINode(threadObj_epoch_raw, excluded_mask));
3746 
3747   // True branch, this is a virtual thread.
3748   Node* vthread_not_equal_threadObj = _gvn.transform(new IfTrueNode(iff_vthread_not_equal_threadObj));
3749   set_control(vthread_not_equal_threadObj);
3750 
3751   // Load the tid field from the vthread object.
3752   Node* vthread_tid = load_field_from_object(vthread, "tid", "J");
3753 
3754   // Continuation support determines if a virtual thread should be pinned.
3755   Node* global_addr = makecon(TypeRawPtr::make((address)&VMContinuations));
3756   Node* continuation_support = make_load(control(), global_addr, TypeInt::BOOL, T_BOOLEAN, MemNode::unordered);
3757 
3758   // Load the raw epoch value from the vthread.
3759   Node* vthread_epoch_offset = basic_plus_adr(vthread, java_lang_Thread::jfr_epoch_offset());
3760   Node* vthread_epoch_raw = access_load_at(vthread, vthread_epoch_offset, _gvn.type(vthread_epoch_offset)->is_ptr(),
3761                                            TypeInt::CHAR, T_CHAR,
3762                                            IN_HEAP | MO_UNORDERED | C2_MISMATCHED | C2_CONTROL_DEPENDENT_LOAD);
3763 
3764   // Mask off the excluded information from the epoch.
3765   Node * vthread_is_excluded = _gvn.transform(new AndINode(vthread_epoch_raw, excluded_mask));
3766 
3767   // Branch on excluded to conditionalize updating the epoch for the virtual thread.
3768   Node* is_excluded_cmp = _gvn.transform(new CmpINode(vthread_is_excluded, excluded_mask));
3769   Node* test_not_excluded = _gvn.transform(new BoolNode(is_excluded_cmp, BoolTest::ne));
3770   IfNode* iff_not_excluded = create_and_map_if(control(), test_not_excluded, PROB_MAX, COUNT_UNKNOWN);
3771 
3772   // False branch, vthread is excluded, no need to write epoch info.
3773   Node* excluded = _gvn.transform(new IfFalseNode(iff_not_excluded));
3774 
3775   // True branch, vthread is included, update epoch info.
3776   Node* included = _gvn.transform(new IfTrueNode(iff_not_excluded));
3777   set_control(included);
3778 
3779   // Get epoch value.
3780   Node* epoch = _gvn.transform(new AndINode(vthread_epoch_raw, epoch_mask));
3781 
3782   // Load the current epoch generation. The value is unsigned 16-bit, so we type it as T_CHAR.
3783   Node* epoch_generation_address = makecon(TypeRawPtr::make(JfrIntrinsicSupport::epoch_generation_address()));
3784   Node* current_epoch_generation = make_load(control(), epoch_generation_address, TypeInt::CHAR, T_CHAR, MemNode::unordered);
3785 
3786   // Compare the epoch in the vthread to the current epoch generation.
3787   Node* const epoch_cmp = _gvn.transform(new CmpUNode(current_epoch_generation, epoch));
3788   Node* test_epoch_not_equal = _gvn.transform(new BoolNode(epoch_cmp, BoolTest::ne));
3789   IfNode* iff_epoch_not_equal = create_and_map_if(control(), test_epoch_not_equal, PROB_FAIR, COUNT_UNKNOWN);
3790 
3791   // False path, epoch is equal, checkpoint information is valid.
3792   Node* epoch_is_equal = _gvn.transform(new IfFalseNode(iff_epoch_not_equal));
3793 
3794   // True path, epoch is not equal, write a checkpoint for the vthread.
3795   Node* epoch_is_not_equal = _gvn.transform(new IfTrueNode(iff_epoch_not_equal));
3796 
3797   set_control(epoch_is_not_equal);
3798 
3799   // Make a runtime call, which can safepoint, to write a checkpoint for the vthread for this epoch.
3800   // The call also updates the native thread local thread id and the vthread with the current epoch.
3801   Node* call_write_checkpoint = make_runtime_call(RC_NO_LEAF,
3802                                                   OptoRuntime::jfr_write_checkpoint_Type(),
3803                                                   SharedRuntime::jfr_write_checkpoint(),
3804                                                   "write_checkpoint", TypePtr::BOTTOM);
3805   Node* call_write_checkpoint_control = _gvn.transform(new ProjNode(call_write_checkpoint, TypeFunc::Control));
3806 
3807   // vthread epoch != current epoch
3808   RegionNode* epoch_compare_rgn = new RegionNode(PATH_LIMIT);
3809   record_for_igvn(epoch_compare_rgn);
3810   PhiNode* epoch_compare_mem = new PhiNode(epoch_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3811   record_for_igvn(epoch_compare_mem);
3812   PhiNode* epoch_compare_io = new PhiNode(epoch_compare_rgn, Type::ABIO);
3813   record_for_igvn(epoch_compare_io);
3814 
3815   // Update control and phi nodes.
3816   epoch_compare_rgn->init_req(_true_path, call_write_checkpoint_control);
3817   epoch_compare_rgn->init_req(_false_path, epoch_is_equal);
3818   epoch_compare_mem->init_req(_true_path, reset_memory());
3819   epoch_compare_mem->init_req(_false_path, input_memory_state);
3820   epoch_compare_io->init_req(_true_path, i_o());
3821   epoch_compare_io->init_req(_false_path, input_io_state);
3822 
3823   // excluded != true
3824   RegionNode* exclude_compare_rgn = new RegionNode(PATH_LIMIT);
3825   record_for_igvn(exclude_compare_rgn);
3826   PhiNode* exclude_compare_mem = new PhiNode(exclude_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3827   record_for_igvn(exclude_compare_mem);
3828   PhiNode* exclude_compare_io = new PhiNode(exclude_compare_rgn, Type::ABIO);
3829   record_for_igvn(exclude_compare_io);
3830 
3831   // Update control and phi nodes.
3832   exclude_compare_rgn->init_req(_true_path, _gvn.transform(epoch_compare_rgn));
3833   exclude_compare_rgn->init_req(_false_path, excluded);
3834   exclude_compare_mem->init_req(_true_path, _gvn.transform(epoch_compare_mem));
3835   exclude_compare_mem->init_req(_false_path, input_memory_state);
3836   exclude_compare_io->init_req(_true_path, _gvn.transform(epoch_compare_io));
3837   exclude_compare_io->init_req(_false_path, input_io_state);
3838 
3839   // vthread != threadObj
3840   RegionNode* vthread_compare_rgn = new RegionNode(PATH_LIMIT);
3841   record_for_igvn(vthread_compare_rgn);
3842   PhiNode* vthread_compare_mem = new PhiNode(vthread_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3843   PhiNode* vthread_compare_io = new PhiNode(vthread_compare_rgn, Type::ABIO);
3844   record_for_igvn(vthread_compare_io);
3845   PhiNode* tid = new PhiNode(vthread_compare_rgn, TypeLong::LONG);
3846   record_for_igvn(tid);
3847   PhiNode* exclusion = new PhiNode(vthread_compare_rgn, TypeInt::CHAR);
3848   record_for_igvn(exclusion);
3849   PhiNode* pinVirtualThread = new PhiNode(vthread_compare_rgn, TypeInt::BOOL);
3850   record_for_igvn(pinVirtualThread);
3851 
3852   // Update control and phi nodes.
3853   vthread_compare_rgn->init_req(_true_path, _gvn.transform(exclude_compare_rgn));
3854   vthread_compare_rgn->init_req(_false_path, vthread_equal_threadObj);
3855   vthread_compare_mem->init_req(_true_path, _gvn.transform(exclude_compare_mem));
3856   vthread_compare_mem->init_req(_false_path, input_memory_state);
3857   vthread_compare_io->init_req(_true_path, _gvn.transform(exclude_compare_io));
3858   vthread_compare_io->init_req(_false_path, input_io_state);
3859   tid->init_req(_true_path, vthread_tid);
3860   tid->init_req(_false_path, thread_obj_tid);
3861   exclusion->init_req(_true_path, vthread_is_excluded);
3862   exclusion->init_req(_false_path, threadObj_is_excluded);
3863   pinVirtualThread->init_req(_true_path, continuation_support);
3864   pinVirtualThread->init_req(_false_path, _gvn.intcon(0));
3865 
3866   // Update branch state.
3867   set_control(_gvn.transform(vthread_compare_rgn));
3868   set_all_memory(_gvn.transform(vthread_compare_mem));
3869   set_i_o(_gvn.transform(vthread_compare_io));
3870 
3871   // Load the event writer oop by dereferencing the jobject handle.
3872   ciKlass* klass_EventWriter = env()->find_system_klass(ciSymbol::make("jdk/jfr/internal/event/EventWriter"));
3873   assert(klass_EventWriter->is_loaded(), "invariant");
3874   ciInstanceKlass* const instklass_EventWriter = klass_EventWriter->as_instance_klass();
3875   const TypeKlassPtr* const aklass = TypeKlassPtr::make(instklass_EventWriter);
3876   const TypeOopPtr* const xtype = aklass->as_instance_type();
3877   Node* jobj_untagged = _gvn.transform(AddPNode::make_off_heap(jobj, _gvn.MakeConX(-JNIHandles::TypeTag::global)));
3878   Node* event_writer = access_load(jobj_untagged, xtype, T_OBJECT, IN_NATIVE | C2_CONTROL_DEPENDENT_LOAD);
3879 
3880   // Load the current thread id from the event writer object.
3881   Node* const event_writer_tid = load_field_from_object(event_writer, "threadID", "J");
3882   // Get the field offset to, conditionally, store an updated tid value later.
3883   Node* const event_writer_tid_field = field_address_from_object(event_writer, "threadID", "J", false);
3884   // Get the field offset to, conditionally, store an updated exclusion value later.
3885   Node* const event_writer_excluded_field = field_address_from_object(event_writer, "excluded", "Z", false);
3886   // Get the field offset to, conditionally, store an updated pinVirtualThread value later.
3887   Node* const event_writer_pin_field = field_address_from_object(event_writer, "pinVirtualThread", "Z", false);
3888 
3889   RegionNode* event_writer_tid_compare_rgn = new RegionNode(PATH_LIMIT);
3890   record_for_igvn(event_writer_tid_compare_rgn);
3891   PhiNode* event_writer_tid_compare_mem = new PhiNode(event_writer_tid_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3892   record_for_igvn(event_writer_tid_compare_mem);
3893   PhiNode* event_writer_tid_compare_io = new PhiNode(event_writer_tid_compare_rgn, Type::ABIO);
3894   record_for_igvn(event_writer_tid_compare_io);
3895 
3896   // Compare the current tid from the thread object to what is currently stored in the event writer object.
3897   Node* const tid_cmp = _gvn.transform(new CmpLNode(event_writer_tid, _gvn.transform(tid)));
3898   Node* test_tid_not_equal = _gvn.transform(new BoolNode(tid_cmp, BoolTest::ne));
3899   IfNode* iff_tid_not_equal = create_and_map_if(_gvn.transform(vthread_compare_rgn), test_tid_not_equal, PROB_FAIR, COUNT_UNKNOWN);
3900 
3901   // False path, tids are the same.
3902   Node* tid_is_equal = _gvn.transform(new IfFalseNode(iff_tid_not_equal));
3903 
3904   // True path, tid is not equal, need to update the tid in the event writer.
3905   Node* tid_is_not_equal = _gvn.transform(new IfTrueNode(iff_tid_not_equal));
3906   record_for_igvn(tid_is_not_equal);
3907 
3908   // Store the pin state to the event writer.
3909   store_to_memory(tid_is_not_equal, event_writer_pin_field, _gvn.transform(pinVirtualThread), T_BOOLEAN, MemNode::unordered);
3910 
3911   // Store the exclusion state to the event writer.
3912   Node* excluded_bool = _gvn.transform(new URShiftINode(_gvn.transform(exclusion), excluded_shift));
3913   store_to_memory(tid_is_not_equal, event_writer_excluded_field, excluded_bool, T_BOOLEAN, MemNode::unordered);
3914 
3915   // Store the tid to the event writer.
3916   store_to_memory(tid_is_not_equal, event_writer_tid_field, tid, T_LONG, MemNode::unordered);
3917 
3918   // Update control and phi nodes.
3919   event_writer_tid_compare_rgn->init_req(_true_path, tid_is_not_equal);
3920   event_writer_tid_compare_rgn->init_req(_false_path, tid_is_equal);
3921   event_writer_tid_compare_mem->init_req(_true_path, reset_memory());
3922   event_writer_tid_compare_mem->init_req(_false_path, _gvn.transform(vthread_compare_mem));
3923   event_writer_tid_compare_io->init_req(_true_path, i_o());
3924   event_writer_tid_compare_io->init_req(_false_path, _gvn.transform(vthread_compare_io));
3925 
3926   // Result of top level CFG, Memory, IO and Value.
3927   RegionNode* result_rgn = new RegionNode(PATH_LIMIT);
3928   PhiNode* result_mem = new PhiNode(result_rgn, Type::MEMORY, TypePtr::BOTTOM);
3929   PhiNode* result_io = new PhiNode(result_rgn, Type::ABIO);
3930   PhiNode* result_value = new PhiNode(result_rgn, TypeInstPtr::BOTTOM);
3931 
3932   // Result control.
3933   result_rgn->init_req(_true_path, _gvn.transform(event_writer_tid_compare_rgn));
3934   result_rgn->init_req(_false_path, jobj_is_null);
3935 
3936   // Result memory.
3937   result_mem->init_req(_true_path, _gvn.transform(event_writer_tid_compare_mem));
3938   result_mem->init_req(_false_path, input_memory_state);
3939 
3940   // Result IO.
3941   result_io->init_req(_true_path, _gvn.transform(event_writer_tid_compare_io));
3942   result_io->init_req(_false_path, input_io_state);
3943 
3944   // Result value.
3945   result_value->init_req(_true_path, event_writer); // return event writer oop
3946   result_value->init_req(_false_path, null()); // return null
3947 
3948   // Set output state.
3949   set_control(_gvn.transform(result_rgn));
3950   set_all_memory(_gvn.transform(result_mem));
3951   set_i_o(_gvn.transform(result_io));
3952   set_result(result_rgn, result_value);
3953   return true;
3954 }
3955 
3956 /*
3957  * The intrinsic is a model of this pseudo-code:
3958  *
3959  * JfrThreadLocal* const tl = thread->jfr_thread_local();
3960  * if (carrierThread != thread) { // is virtual thread
3961  *   const u2 vthread_epoch_raw = java_lang_Thread::jfr_epoch(thread);
3962  *   bool excluded = vthread_epoch_raw & excluded_mask;
3963  *   AtomicAccess::store(&tl->_contextual_tid, java_lang_Thread::tid(thread));
3964  *   AtomicAccess::store(&tl->_contextual_thread_excluded, is_excluded);
3965  *   if (!excluded) {
3966  *     const u2 vthread_epoch = vthread_epoch_raw & epoch_mask;
3967  *     AtomicAccess::store(&tl->_vthread_epoch, vthread_epoch);
3968  *   }
3969  *   AtomicAccess::release_store(&tl->_vthread, true);
3970  *   return;
3971  * }
3972  * AtomicAccess::release_store(&tl->_vthread, false);
3973  */
3974 void LibraryCallKit::extend_setCurrentThread(Node* jt, Node* thread) {
3975   enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
3976 
3977   Node* input_memory_state = reset_memory();
3978   set_all_memory(input_memory_state);
3979 
3980   // The most significant bit of the u2 is used to denote thread exclusion
3981   Node* excluded_mask = _gvn.intcon(1 << 15);
3982   // The epoch generation is the range [1-32767]
3983   Node* epoch_mask = _gvn.intcon(32767);
3984 
3985   Node* const carrierThread = generate_current_thread(jt);
3986   // If thread != carrierThread, this is a virtual thread.
3987   Node* thread_cmp_carrierThread = _gvn.transform(new CmpPNode(thread, carrierThread));
3988   Node* test_thread_not_equal_carrierThread = _gvn.transform(new BoolNode(thread_cmp_carrierThread, BoolTest::ne));
3989   IfNode* iff_thread_not_equal_carrierThread =
3990     create_and_map_if(control(), test_thread_not_equal_carrierThread, PROB_FAIR, COUNT_UNKNOWN);
3991 
3992   Node* vthread_offset = off_heap_plus_addr(jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_OFFSET_JFR));
3993 
3994   // False branch, is carrierThread.
3995   Node* thread_equal_carrierThread = _gvn.transform(new IfFalseNode(iff_thread_not_equal_carrierThread));
3996   // Store release
3997   Node* vthread_false_memory = store_to_memory(thread_equal_carrierThread, vthread_offset, _gvn.intcon(0), T_BOOLEAN, MemNode::release, true);
3998 
3999   set_all_memory(input_memory_state);
4000 
4001   // True branch, is virtual thread.
4002   Node* thread_not_equal_carrierThread = _gvn.transform(new IfTrueNode(iff_thread_not_equal_carrierThread));
4003   set_control(thread_not_equal_carrierThread);
4004 
4005   // Load the raw epoch value from the vthread.
4006   Node* epoch_offset = basic_plus_adr(thread, java_lang_Thread::jfr_epoch_offset());
4007   Node* epoch_raw = access_load_at(thread, epoch_offset, _gvn.type(epoch_offset)->is_ptr(), TypeInt::CHAR, T_CHAR,
4008                                    IN_HEAP | MO_UNORDERED | C2_MISMATCHED | C2_CONTROL_DEPENDENT_LOAD);
4009 
4010   // Mask off the excluded information from the epoch.
4011   Node * const is_excluded = _gvn.transform(new AndINode(epoch_raw, excluded_mask));
4012 
4013   // Load the tid field from the thread.
4014   Node* tid = load_field_from_object(thread, "tid", "J");
4015 
4016   // Store the vthread tid to the jfr thread local.
4017   Node* thread_id_offset = off_heap_plus_addr(jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_ID_OFFSET_JFR));
4018   Node* tid_memory = store_to_memory(control(), thread_id_offset, tid, T_LONG, MemNode::unordered, true);
4019 
4020   // Branch is_excluded to conditionalize updating the epoch .
4021   Node* excluded_cmp = _gvn.transform(new CmpINode(is_excluded, excluded_mask));
4022   Node* test_excluded = _gvn.transform(new BoolNode(excluded_cmp, BoolTest::eq));
4023   IfNode* iff_excluded = create_and_map_if(control(), test_excluded, PROB_MIN, COUNT_UNKNOWN);
4024 
4025   // True branch, vthread is excluded, no need to write epoch info.
4026   Node* excluded = _gvn.transform(new IfTrueNode(iff_excluded));
4027   set_control(excluded);
4028   Node* vthread_is_excluded = _gvn.intcon(1);
4029 
4030   // False branch, vthread is included, update epoch info.
4031   Node* included = _gvn.transform(new IfFalseNode(iff_excluded));
4032   set_control(included);
4033   Node* vthread_is_included = _gvn.intcon(0);
4034 
4035   // Get epoch value.
4036   Node* epoch = _gvn.transform(new AndINode(epoch_raw, epoch_mask));
4037 
4038   // Store the vthread epoch to the jfr thread local.
4039   Node* vthread_epoch_offset = off_heap_plus_addr(jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_EPOCH_OFFSET_JFR));
4040   Node* included_memory = store_to_memory(control(), vthread_epoch_offset, epoch, T_CHAR, MemNode::unordered, true);
4041 
4042   RegionNode* excluded_rgn = new RegionNode(PATH_LIMIT);
4043   record_for_igvn(excluded_rgn);
4044   PhiNode* excluded_mem = new PhiNode(excluded_rgn, Type::MEMORY, TypePtr::BOTTOM);
4045   record_for_igvn(excluded_mem);
4046   PhiNode* exclusion = new PhiNode(excluded_rgn, TypeInt::BOOL);
4047   record_for_igvn(exclusion);
4048 
4049   // Merge the excluded control and memory.
4050   excluded_rgn->init_req(_true_path, excluded);
4051   excluded_rgn->init_req(_false_path, included);
4052   excluded_mem->init_req(_true_path, tid_memory);
4053   excluded_mem->init_req(_false_path, included_memory);
4054   exclusion->init_req(_true_path, vthread_is_excluded);
4055   exclusion->init_req(_false_path, vthread_is_included);
4056 
4057   // Set intermediate state.
4058   set_control(_gvn.transform(excluded_rgn));
4059   set_all_memory(excluded_mem);
4060 
4061   // Store the vthread exclusion state to the jfr thread local.
4062   Node* thread_local_excluded_offset = off_heap_plus_addr(jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_EXCLUDED_OFFSET_JFR));
4063   store_to_memory(control(), thread_local_excluded_offset, _gvn.transform(exclusion), T_BOOLEAN, MemNode::unordered, true);
4064 
4065   // Store release
4066   Node * vthread_true_memory = store_to_memory(control(), vthread_offset, _gvn.intcon(1), T_BOOLEAN, MemNode::release, true);
4067 
4068   RegionNode* thread_compare_rgn = new RegionNode(PATH_LIMIT);
4069   record_for_igvn(thread_compare_rgn);
4070   PhiNode* thread_compare_mem = new PhiNode(thread_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
4071   record_for_igvn(thread_compare_mem);
4072   PhiNode* vthread = new PhiNode(thread_compare_rgn, TypeInt::BOOL);
4073   record_for_igvn(vthread);
4074 
4075   // Merge the thread_compare control and memory.
4076   thread_compare_rgn->init_req(_true_path, control());
4077   thread_compare_rgn->init_req(_false_path, thread_equal_carrierThread);
4078   thread_compare_mem->init_req(_true_path, vthread_true_memory);
4079   thread_compare_mem->init_req(_false_path, vthread_false_memory);
4080 
4081   // Set output state.
4082   set_control(_gvn.transform(thread_compare_rgn));
4083   set_all_memory(_gvn.transform(thread_compare_mem));
4084 }
4085 
4086 //------------------------inline_native_try_update_epoch------------------
4087 //
4088 // The generated code is a function of the argument type.
4089 //
4090 bool LibraryCallKit::inline_native_try_update_epoch() {
4091   enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
4092 
4093   // Save input memory.
4094   Node* input_memory_state = reset_memory();
4095   set_all_memory(input_memory_state);
4096 
4097   // Argument is an oop whose class has an injected instance field,
4098   // called 'jfr_epoch' of type T_INT, used for holding a jfr epoch value.
4099   Node* oop = argument(0);
4100   const TypeInstPtr* tinst = _gvn.type(oop)->isa_instptr();
4101   assert(tinst != nullptr, "oop is null");
4102   assert(tinst->is_loaded(), "klass is not loaded");
4103   ciInstanceKlass* const ik = tinst->instance_klass();
4104 
4105   ciField* const field = ik->get_injected_instance_field_by_name(ciSymbol::make("jfr_epoch"),
4106                                                                  ciSymbol::make("I"));
4107 
4108   assert(field != nullptr, "field 'jfr_epoch' of type I not injected in klass %s", ik->name()->as_utf8());
4109 
4110   const int jfr_epoch_field_offset = field->offset_in_bytes();
4111   Node* oop_epoch_field_offset = basic_plus_adr(oop, jfr_epoch_field_offset);
4112   const TypePtr* adr_type = _gvn.type(oop_epoch_field_offset)->isa_ptr();
4113   const int alias_idx = C->get_alias_index(adr_type);
4114   BasicType bt = field->layout_type();
4115   const Type * oop_epoch_field_type = Type::get_const_basic_type(bt);
4116 
4117   // Load the epoch value from the oop.
4118   Node* oop_epoch = access_load_at(oop,
4119                                    oop_epoch_field_offset,
4120                                    adr_type, oop_epoch_field_type,
4121                                    bt, IN_HEAP | MO_UNORDERED);
4122 
4123   // Load the current JFR epoch generation. The value is unsigned 16-bit, so we type it as T_CHAR.
4124   Node* epoch_generation_address = makecon(TypeRawPtr::make(JfrIntrinsicSupport::epoch_generation_address()));
4125   Node* current_epoch_generation = make_load(control(), epoch_generation_address, TypeInt::CHAR, T_CHAR, MemNode::unordered);
4126 
4127   // Compare the epoch in the oop against the current JFR epoch generation.
4128   Node* const epochs_cmp = _gvn.transform(new CmpINode(current_epoch_generation, oop_epoch));
4129   Node* epochs_equal_test = _gvn.transform(new BoolNode(epochs_cmp, BoolTest::eq));
4130   IfNode* iff_epochs_equal = create_and_map_if(control(), epochs_equal_test, PROB_LIKELY(0.999), COUNT_UNKNOWN);
4131 
4132   // True path.
4133   Node* epochs_are_equal = _gvn.transform(new IfTrueNode(iff_epochs_equal));
4134 
4135   // False path.
4136   Node* epochs_are_not_equal = _gvn.transform(new IfFalseNode(iff_epochs_equal));
4137 
4138   set_control(_gvn.transform(epochs_are_not_equal));
4139 
4140   // Attempt to cas the current JFR epoch generation into the oop epoch field.
4141   DecoratorSet decorators = IN_HEAP;
4142   decorators |= mo_decorator_for_access_kind(Volatile);
4143 
4144   Node* result = access_atomic_cmpxchg_val_at(oop,
4145                                               oop_epoch_field_offset,
4146                                               adr_type, alias_idx,
4147                                               oop_epoch, // expected value
4148                                               current_epoch_generation, // new value
4149                                               oop_epoch_field_type,
4150                                               bt,
4151                                               decorators);
4152 
4153   // Compare the result of the cas operation to the expected value.
4154   Node* const cas_cmp_to_expected_value = _gvn.transform(new CmpINode(result, oop_epoch));
4155   Node* cas_operation_test = _gvn.transform(new BoolNode(cas_cmp_to_expected_value, BoolTest::eq));
4156   IfNode* iff_cas_success = create_and_map_if(control(), cas_operation_test, PROB_LIKELY(0.999), COUNT_UNKNOWN);
4157 
4158   // True path.
4159   Node* cas_success = _gvn.transform(new IfTrueNode(iff_cas_success));
4160 
4161   // False path.
4162   Node* cas_failure = _gvn.transform(new IfFalseNode(iff_cas_success));
4163 
4164   // Cas result region and phi nodes.
4165   RegionNode* cas_operation_rgn = new RegionNode(PATH_LIMIT);
4166   record_for_igvn(cas_operation_rgn);
4167   PhiNode* cas_operation_mem = new PhiNode(cas_operation_rgn, Type::MEMORY, TypePtr::BOTTOM);
4168   record_for_igvn(cas_operation_mem);
4169   PhiNode* cas_result = new PhiNode(cas_operation_rgn, TypeInt::BOOL);
4170   record_for_igvn(cas_result);
4171 
4172   cas_operation_rgn->init_req(_true_path, _gvn.transform(cas_success));
4173   cas_operation_rgn->init_req(_false_path, _gvn.transform(cas_failure));
4174   cas_operation_mem->init_req(_true_path, reset_memory());
4175   cas_operation_mem->init_req(_false_path, input_memory_state);
4176   cas_result->init_req(_true_path, _gvn.intcon(1));
4177   cas_result->init_req(_false_path, _gvn.intcon(0));
4178 
4179   // Epoch compare region and phi nodes.
4180   RegionNode* epoch_compare_rgn = new RegionNode(PATH_LIMIT);
4181   record_for_igvn(epoch_compare_rgn);
4182   PhiNode* epoch_compare_mem = new PhiNode(epoch_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
4183   record_for_igvn(epoch_compare_mem);
4184   PhiNode* result_value = new PhiNode(epoch_compare_rgn, TypeInt::BOOL);
4185   record_for_igvn(result_value);
4186 
4187   epoch_compare_rgn->init_req(_true_path, _gvn.transform(epochs_are_equal));
4188   epoch_compare_rgn->init_req(_false_path, _gvn.transform(cas_operation_rgn));
4189   epoch_compare_mem->init_req(_true_path, _gvn.transform(input_memory_state));
4190   epoch_compare_mem->init_req(_false_path, _gvn.transform(cas_operation_mem));
4191   result_value->init_req(_true_path, _gvn.intcon(0));
4192   result_value->init_req(_false_path, _gvn.transform(cas_result));
4193 
4194   // Set output state.
4195   set_result(epoch_compare_rgn, result_value);
4196   set_all_memory(_gvn.transform(epoch_compare_mem));
4197 
4198   return true;
4199 }
4200 
4201 #endif // JFR_HAVE_INTRINSICS
4202 
4203 //------------------------inline_native_currentCarrierThread------------------
4204 bool LibraryCallKit::inline_native_currentCarrierThread() {
4205   Node* junk = nullptr;
4206   set_result(generate_current_thread(junk));
4207   return true;
4208 }
4209 
4210 //------------------------inline_native_currentThread------------------
4211 bool LibraryCallKit::inline_native_currentThread() {
4212   Node* junk = nullptr;
4213   set_result(generate_virtual_thread(junk));
4214   return true;
4215 }
4216 
4217 //------------------------inline_native_setVthread------------------
4218 bool LibraryCallKit::inline_native_setCurrentThread() {
4219   assert(C->method()->changes_current_thread(),
4220          "method changes current Thread but is not annotated ChangesCurrentThread");
4221   Node* arr = argument(1);
4222   Node* thread = _gvn.transform(new ThreadLocalNode());
4223   Node* p = off_heap_plus_addr(thread, in_bytes(JavaThread::vthread_offset()));
4224   Node* thread_obj_handle
4225     = make_load(nullptr, p, p->bottom_type()->is_ptr(), T_OBJECT, MemNode::unordered);
4226   const TypePtr *adr_type = _gvn.type(thread_obj_handle)->isa_ptr();
4227   access_store_at(nullptr, thread_obj_handle, adr_type, arr, _gvn.type(arr), T_OBJECT, IN_NATIVE | MO_UNORDERED);
4228 
4229   // Change the _monitor_owner_id of the JavaThread
4230   Node* tid = load_field_from_object(arr, "tid", "J");
4231   Node* monitor_owner_id_offset = off_heap_plus_addr(thread, in_bytes(JavaThread::monitor_owner_id_offset()));
4232   store_to_memory(control(), monitor_owner_id_offset, tid, T_LONG, MemNode::unordered, true);
4233 
4234   JFR_ONLY(extend_setCurrentThread(thread, arr);)
4235   return true;
4236 }
4237 
4238 const Type* LibraryCallKit::scopedValueCache_type() {
4239   ciKlass* objects_klass = ciObjArrayKlass::make(env()->Object_klass());
4240   const TypeOopPtr* etype = TypeOopPtr::make_from_klass(env()->Object_klass());
4241   const TypeAry* arr0 = TypeAry::make(etype, TypeInt::POS, /* stable= */ false, /* flat= */ false, /* not_flat= */ true, /* not_null_free= */ true, true);
4242 
4243   // Because we create the scopedValue cache lazily we have to make the
4244   // type of the result BotPTR.
4245   bool xk = etype->klass_is_exact();
4246   const Type* objects_type = TypeAryPtr::make(TypePtr::BotPTR, arr0, objects_klass, xk, TypeAryPtr::Offset(0));
4247   return objects_type;
4248 }
4249 
4250 Node* LibraryCallKit::scopedValueCache_helper() {
4251   Node* thread = _gvn.transform(new ThreadLocalNode());
4252   Node* p = off_heap_plus_addr(thread, in_bytes(JavaThread::scopedValueCache_offset()));
4253   // We cannot use immutable_memory() because we might flip onto a
4254   // different carrier thread, at which point we'll need to use that
4255   // carrier thread's cache.
4256   // return _gvn.transform(LoadNode::make(_gvn, nullptr, immutable_memory(), p, p->bottom_type()->is_ptr(),
4257   //       TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered));
4258   return make_load(nullptr, p, p->bottom_type()->is_ptr(), T_ADDRESS, MemNode::unordered);
4259 }
4260 
4261 //------------------------inline_native_scopedValueCache------------------
4262 bool LibraryCallKit::inline_native_scopedValueCache() {
4263   Node* cache_obj_handle = scopedValueCache_helper();
4264   const Type* objects_type = scopedValueCache_type();
4265   set_result(access_load(cache_obj_handle, objects_type, T_OBJECT, IN_NATIVE));
4266 
4267   return true;
4268 }
4269 
4270 //------------------------inline_native_setScopedValueCache------------------
4271 bool LibraryCallKit::inline_native_setScopedValueCache() {
4272   Node* arr = argument(0);
4273   Node* cache_obj_handle = scopedValueCache_helper();
4274   const Type* objects_type = scopedValueCache_type();
4275 
4276   const TypePtr *adr_type = _gvn.type(cache_obj_handle)->isa_ptr();
4277   access_store_at(nullptr, cache_obj_handle, adr_type, arr, objects_type, T_OBJECT, IN_NATIVE | MO_UNORDERED);
4278 
4279   return true;
4280 }
4281 
4282 //------------------------inline_native_Continuation_pin and unpin-----------
4283 
4284 // Shared implementation routine for both pin and unpin.
4285 bool LibraryCallKit::inline_native_Continuation_pinning(bool unpin) {
4286   enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
4287 
4288   // Save input memory.
4289   Node* input_memory_state = reset_memory();
4290   set_all_memory(input_memory_state);
4291 
4292   // TLS
4293   Node* tls_ptr = _gvn.transform(new ThreadLocalNode());
4294   Node* last_continuation_offset = off_heap_plus_addr(tls_ptr, in_bytes(JavaThread::cont_entry_offset()));
4295   Node* last_continuation = make_load(control(), last_continuation_offset, last_continuation_offset->get_ptr_type(), T_ADDRESS, MemNode::unordered);
4296 
4297   // Null check the last continuation object.
4298   Node* continuation_cmp_null = _gvn.transform(new CmpPNode(last_continuation, null()));
4299   Node* test_continuation_not_equal_null = _gvn.transform(new BoolNode(continuation_cmp_null, BoolTest::ne));
4300   IfNode* iff_continuation_not_equal_null = create_and_map_if(control(), test_continuation_not_equal_null, PROB_MAX, COUNT_UNKNOWN);
4301 
4302   // False path, last continuation is null.
4303   Node* continuation_is_null = _gvn.transform(new IfFalseNode(iff_continuation_not_equal_null));
4304 
4305   // True path, last continuation is not null.
4306   Node* continuation_is_not_null = _gvn.transform(new IfTrueNode(iff_continuation_not_equal_null));
4307 
4308   set_control(continuation_is_not_null);
4309 
4310   // Load the pin count from the last continuation.
4311   Node* pin_count_offset = off_heap_plus_addr(last_continuation, in_bytes(ContinuationEntry::pin_count_offset()));
4312   Node* pin_count = make_load(control(), pin_count_offset, TypeInt::INT, T_INT, MemNode::unordered);
4313 
4314   // The loaded pin count is compared against a context specific rhs for over/underflow detection.
4315   Node* pin_count_rhs;
4316   if (unpin) {
4317     pin_count_rhs = _gvn.intcon(0);
4318   } else {
4319     pin_count_rhs = _gvn.intcon(UINT32_MAX);
4320   }
4321   Node* pin_count_cmp = _gvn.transform(new CmpUNode(pin_count, pin_count_rhs));
4322   Node* test_pin_count_over_underflow = _gvn.transform(new BoolNode(pin_count_cmp, BoolTest::eq));
4323   IfNode* iff_pin_count_over_underflow = create_and_map_if(control(), test_pin_count_over_underflow, PROB_MIN, COUNT_UNKNOWN);
4324 
4325   // True branch, pin count over/underflow.
4326   Node* pin_count_over_underflow = _gvn.transform(new IfTrueNode(iff_pin_count_over_underflow));
4327   {
4328     // Trap (but not deoptimize (Action_none)) and continue in the interpreter
4329     // which will throw IllegalStateException for pin count over/underflow.
4330     // No memory changed so far - we can use memory create by reset_memory()
4331     // at the beginning of this intrinsic. No need to call reset_memory() again.
4332     PreserveJVMState pjvms(this);
4333     set_control(pin_count_over_underflow);
4334     uncommon_trap(Deoptimization::Reason_intrinsic,
4335                   Deoptimization::Action_none);
4336     assert(stopped(), "invariant");
4337   }
4338 
4339   // False branch, no pin count over/underflow. Increment or decrement pin count and store back.
4340   Node* valid_pin_count = _gvn.transform(new IfFalseNode(iff_pin_count_over_underflow));
4341   set_control(valid_pin_count);
4342 
4343   Node* next_pin_count;
4344   if (unpin) {
4345     next_pin_count = _gvn.transform(new SubINode(pin_count, _gvn.intcon(1)));
4346   } else {
4347     next_pin_count = _gvn.transform(new AddINode(pin_count, _gvn.intcon(1)));
4348   }
4349 
4350   store_to_memory(control(), pin_count_offset, next_pin_count, T_INT, MemNode::unordered);
4351 
4352   // Result of top level CFG and Memory.
4353   RegionNode* result_rgn = new RegionNode(PATH_LIMIT);
4354   record_for_igvn(result_rgn);
4355   PhiNode* result_mem = new PhiNode(result_rgn, Type::MEMORY, TypePtr::BOTTOM);
4356   record_for_igvn(result_mem);
4357 
4358   result_rgn->init_req(_true_path, valid_pin_count);
4359   result_rgn->init_req(_false_path, continuation_is_null);
4360   result_mem->init_req(_true_path, reset_memory());
4361   result_mem->init_req(_false_path, input_memory_state);
4362 
4363   // Set output state.
4364   set_control(_gvn.transform(result_rgn));
4365   set_all_memory(_gvn.transform(result_mem));
4366 
4367   return true;
4368 }
4369 
4370 //---------------------------load_mirror_from_klass----------------------------
4371 // Given a klass oop, load its java mirror (a java.lang.Class oop).
4372 Node* LibraryCallKit::load_mirror_from_klass(Node* klass) {
4373   Node* p = off_heap_plus_addr(klass, in_bytes(Klass::java_mirror_offset()));
4374   Node* load = make_load(nullptr, p, TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered);
4375   // mirror = ((OopHandle)mirror)->resolve();
4376   return access_load(load, TypeInstPtr::MIRROR, T_OBJECT, IN_NATIVE);
4377 }
4378 
4379 //-----------------------load_klass_from_mirror_common-------------------------
4380 // Given a java mirror (a java.lang.Class oop), load its corresponding klass oop.
4381 // Test the klass oop for null (signifying a primitive Class like Integer.TYPE),
4382 // and branch to the given path on the region.
4383 // If never_see_null, take an uncommon trap on null, so we can optimistically
4384 // compile for the non-null case.
4385 // If the region is null, force never_see_null = true.
4386 Node* LibraryCallKit::load_klass_from_mirror_common(Node* mirror,
4387                                                     bool never_see_null,
4388                                                     RegionNode* region,
4389                                                     int null_path,
4390                                                     int offset) {
4391   if (region == nullptr)  never_see_null = true;
4392   Node* p = basic_plus_adr(mirror, offset);
4393   const TypeKlassPtr*  kls_type = TypeInstKlassPtr::OBJECT_OR_NULL;
4394   Node* kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), p, TypeRawPtr::BOTTOM, kls_type));
4395   Node* null_ctl = top();
4396   kls = null_check_oop(kls, &null_ctl, never_see_null);
4397   if (region != nullptr) {
4398     // Set region->in(null_path) if the mirror is a primitive (e.g, int.class).
4399     region->init_req(null_path, null_ctl);
4400   } else {
4401     assert(null_ctl == top(), "no loose ends");
4402   }
4403   return kls;
4404 }
4405 
4406 //--------------------(inline_native_Class_query helpers)---------------------
4407 // Use this for JVM_ACC_INTERFACE.
4408 // Fall through if (mods & mask) == bits, take the guard otherwise.
4409 Node* LibraryCallKit::generate_klass_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region,
4410                                                  ByteSize offset, const Type* type, BasicType bt) {
4411   // Branch around if the given klass has the given modifier bit set.
4412   // Like generate_guard, adds a new path onto the region.
4413   Node* modp = off_heap_plus_addr(kls, in_bytes(offset));
4414   Node* mods = make_load(nullptr, modp, type, bt, MemNode::unordered);
4415   Node* mask = intcon(modifier_mask);
4416   Node* bits = intcon(modifier_bits);
4417   Node* mbit = _gvn.transform(new AndINode(mods, mask));
4418   Node* cmp  = _gvn.transform(new CmpINode(mbit, bits));
4419   Node* bol  = _gvn.transform(new BoolNode(cmp, BoolTest::ne));
4420   return generate_fair_guard(bol, region);
4421 }
4422 
4423 Node* LibraryCallKit::generate_interface_guard(Node* kls, RegionNode* region) {
4424   return generate_klass_flags_guard(kls, JVM_ACC_INTERFACE, 0, region,
4425                                     InstanceKlass::access_flags_offset(), TypeInt::CHAR, T_CHAR);
4426 }
4427 
4428 // Use this for testing if Klass is_hidden, has_finalizer, and is_cloneable_fast.
4429 Node* LibraryCallKit::generate_misc_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region) {
4430   return generate_klass_flags_guard(kls, modifier_mask, modifier_bits, region,
4431                                     Klass::misc_flags_offset(), TypeInt::UBYTE, T_BOOLEAN);
4432 }
4433 
4434 Node* LibraryCallKit::generate_hidden_class_guard(Node* kls, RegionNode* region) {
4435   return generate_misc_flags_guard(kls, KlassFlags::_misc_is_hidden_class, 0, region);
4436 }
4437 
4438 //-------------------------inline_native_Class_query-------------------
4439 bool LibraryCallKit::inline_native_Class_query(vmIntrinsics::ID id) {
4440   const Type* return_type = TypeInt::BOOL;
4441   Node* prim_return_value = top();  // what happens if it's a primitive class?
4442   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
4443   bool expect_prim = false;     // most of these guys expect to work on refs
4444 
4445   enum { _normal_path = 1, _prim_path = 2, PATH_LIMIT };
4446 
4447   Node* mirror = argument(0);
4448   Node* obj    = top();
4449 
4450   switch (id) {
4451   case vmIntrinsics::_isInstance:
4452     // nothing is an instance of a primitive type
4453     prim_return_value = intcon(0);
4454     obj = argument(1);
4455     break;
4456   case vmIntrinsics::_isHidden:
4457     prim_return_value = intcon(0);
4458     break;
4459   case vmIntrinsics::_getSuperclass:
4460     prim_return_value = null();
4461     return_type = TypeInstPtr::MIRROR->cast_to_ptr_type(TypePtr::BotPTR);
4462     break;
4463   default:
4464     fatal_unexpected_iid(id);
4465     break;
4466   }
4467 
4468   const TypeInstPtr* mirror_con = _gvn.type(mirror)->isa_instptr();
4469   if (mirror_con == nullptr)  return false;  // cannot happen?
4470 
4471 #ifndef PRODUCT
4472   if (C->print_intrinsics() || C->print_inlining()) {
4473     ciType* k = mirror_con->java_mirror_type();
4474     if (k) {
4475       tty->print("Inlining %s on constant Class ", vmIntrinsics::name_at(intrinsic_id()));
4476       k->print_name();
4477       tty->cr();
4478     }
4479   }
4480 #endif
4481 
4482   // Null-check the mirror, and the mirror's klass ptr (in case it is a primitive).
4483   RegionNode* region = new RegionNode(PATH_LIMIT);
4484   record_for_igvn(region);
4485   PhiNode* phi = new PhiNode(region, return_type);
4486 
4487   // The mirror will never be null of Reflection.getClassAccessFlags, however
4488   // it may be null for Class.isInstance or Class.getModifiers. Throw a NPE
4489   // if it is. See bug 4774291.
4490 
4491   // For Reflection.getClassAccessFlags(), the null check occurs in
4492   // the wrong place; see inline_unsafe_access(), above, for a similar
4493   // situation.
4494   mirror = null_check(mirror);
4495   // If mirror or obj is dead, only null-path is taken.
4496   if (stopped())  return true;
4497 
4498   if (expect_prim)  never_see_null = false;  // expect nulls (meaning prims)
4499 
4500   // Now load the mirror's klass metaobject, and null-check it.
4501   // Side-effects region with the control path if the klass is null.
4502   Node* kls = load_klass_from_mirror(mirror, never_see_null, region, _prim_path);
4503   // If kls is null, we have a primitive mirror.
4504   phi->init_req(_prim_path, prim_return_value);
4505   if (stopped()) { set_result(region, phi); return true; }
4506   bool safe_for_replace = (region->in(_prim_path) == top());
4507 
4508   Node* p;  // handy temp
4509   Node* null_ctl;
4510 
4511   // Now that we have the non-null klass, we can perform the real query.
4512   // For constant classes, the query will constant-fold in LoadNode::Value.
4513   Node* query_value = top();
4514   switch (id) {
4515   case vmIntrinsics::_isInstance:
4516     // nothing is an instance of a primitive type
4517     query_value = gen_instanceof(obj, kls, safe_for_replace);
4518     break;
4519 
4520   case vmIntrinsics::_isHidden:
4521     // (To verify this code sequence, check the asserts in JVM_IsHiddenClass.)
4522     if (generate_hidden_class_guard(kls, region) != nullptr)
4523       // A guard was added.  If the guard is taken, it was an hidden class.
4524       phi->add_req(intcon(1));
4525     // If we fall through, it's a plain class.
4526     query_value = intcon(0);
4527     break;
4528 
4529 
4530   case vmIntrinsics::_getSuperclass:
4531     // The rules here are somewhat unfortunate, but we can still do better
4532     // with random logic than with a JNI call.
4533     // Interfaces store null or Object as _super, but must report null.
4534     // Arrays store an intermediate super as _super, but must report Object.
4535     // Other types can report the actual _super.
4536     // (To verify this code sequence, check the asserts in JVM_IsInterface.)
4537     if (generate_array_guard(kls, region) != nullptr) {
4538       // A guard was added.  If the guard is taken, it was an array.
4539       phi->add_req(makecon(TypeInstPtr::make(env()->Object_klass()->java_mirror())));
4540     }
4541     // Check for interface after array since this checks AccessFlags offset into InstanceKlass.
4542     // In other words, we are accessing subtype-specific information, so we need to determine the subtype first.
4543     if (generate_interface_guard(kls, region) != nullptr) {
4544       // A guard was added.  If the guard is taken, it was an interface.
4545       phi->add_req(null());
4546     }
4547     // If we fall through, it's a plain class.  Get its _super.
4548     if (!stopped()) {
4549       p = basic_plus_adr(top(), kls, in_bytes(Klass::super_offset()));
4550       kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), p, TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
4551       null_ctl = top();
4552       kls = null_check_oop(kls, &null_ctl);
4553       if (null_ctl != top()) {
4554         // If the guard is taken, Object.superClass is null (both klass and mirror).
4555         region->add_req(null_ctl);
4556         phi   ->add_req(null());
4557       }
4558       if (!stopped()) {
4559         query_value = load_mirror_from_klass(kls);
4560       }
4561     }
4562     break;
4563 
4564   default:
4565     fatal_unexpected_iid(id);
4566     break;
4567   }
4568 
4569   // Fall-through is the normal case of a query to a real class.
4570   phi->init_req(1, query_value);
4571   region->init_req(1, control());
4572 
4573   C->set_has_split_ifs(true); // Has chance for split-if optimization
4574   set_result(region, phi);
4575   return true;
4576 }
4577 
4578 
4579 //-------------------------inline_Class_cast-------------------
4580 bool LibraryCallKit::inline_Class_cast() {
4581   Node* mirror = argument(0); // Class
4582   Node* obj    = argument(1);
4583   const TypeInstPtr* mirror_con = _gvn.type(mirror)->isa_instptr();
4584   if (mirror_con == nullptr) {
4585     return false;  // dead path (mirror->is_top()).
4586   }
4587   if (obj == nullptr || obj->is_top()) {
4588     return false;  // dead path
4589   }
4590   const TypeOopPtr* tp = _gvn.type(obj)->isa_oopptr();
4591 
4592   // First, see if Class.cast() can be folded statically.
4593   // java_mirror_type() returns non-null for compile-time Class constants.
4594   ciType* tm = mirror_con->java_mirror_type();
4595   if (tm != nullptr && tm->is_klass() &&
4596       tp != nullptr) {
4597     if (!tp->is_loaded()) {
4598       // Don't use intrinsic when class is not loaded.
4599       return false;
4600     } else {
4601       const TypeKlassPtr* tklass = TypeKlassPtr::make(tm->as_klass(), Type::trust_interfaces);
4602       int static_res = C->static_subtype_check(tklass, tp->as_klass_type());
4603       if (static_res == Compile::SSC_always_true) {
4604         // isInstance() is true - fold the code.
4605         set_result(obj);
4606         return true;
4607       } else if (static_res == Compile::SSC_always_false) {
4608         // Don't use intrinsic, have to throw ClassCastException.
4609         // If the reference is null, the non-intrinsic bytecode will
4610         // be optimized appropriately.
4611         return false;
4612       }
4613     }
4614   }
4615 
4616   // Bailout intrinsic and do normal inlining if exception path is frequent.
4617   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
4618     return false;
4619   }
4620 
4621   // Generate dynamic checks.
4622   // Class.cast() is java implementation of _checkcast bytecode.
4623   // Do checkcast (Parse::do_checkcast()) optimizations here.
4624 
4625   mirror = null_check(mirror);
4626   // If mirror is dead, only null-path is taken.
4627   if (stopped()) {
4628     return true;
4629   }
4630 
4631   // Not-subtype or the mirror's klass ptr is nullptr (in case it is a primitive).
4632   enum { _bad_type_path = 1, _prim_path = 2, _npe_path = 3, PATH_LIMIT };
4633   RegionNode* region = new RegionNode(PATH_LIMIT);
4634   record_for_igvn(region);
4635 
4636   // Now load the mirror's klass metaobject, and null-check it.
4637   // If kls is null, we have a primitive mirror and
4638   // nothing is an instance of a primitive type.
4639   Node* kls = load_klass_from_mirror(mirror, false, region, _prim_path);
4640 
4641   Node* res = top();
4642   Node* io = i_o();
4643   Node* mem = merged_memory();
4644   SafePointNode* new_cast_failure_map = nullptr;
4645 
4646   if (!stopped()) {
4647 
4648     Node* bad_type_ctrl = top();
4649     // Do checkcast optimizations.
4650     res = gen_checkcast(obj, kls, &bad_type_ctrl, &new_cast_failure_map);
4651     region->init_req(_bad_type_path, bad_type_ctrl);
4652   }
4653   if (region->in(_prim_path) != top() ||
4654       region->in(_bad_type_path) != top() ||
4655       region->in(_npe_path) != top()) {
4656     // Let Interpreter throw ClassCastException.
4657     PreserveJVMState pjvms(this);
4658     if (new_cast_failure_map != nullptr) {
4659       // The current map on the success path could have been modified. Use the dedicated failure path map.
4660       set_map(new_cast_failure_map);
4661     }
4662     set_control(_gvn.transform(region));
4663     // Set IO and memory because gen_checkcast may override them when buffering inline types
4664     set_i_o(io);
4665     set_all_memory(mem);
4666     uncommon_trap(Deoptimization::Reason_intrinsic,
4667                   Deoptimization::Action_maybe_recompile);
4668   }
4669   if (!stopped()) {
4670     set_result(res);
4671   }
4672   return true;
4673 }
4674 
4675 
4676 //--------------------------inline_native_subtype_check------------------------
4677 // This intrinsic takes the JNI calls out of the heart of
4678 // UnsafeFieldAccessorImpl.set, which improves Field.set, readObject, etc.
4679 bool LibraryCallKit::inline_native_subtype_check() {
4680   // Pull both arguments off the stack.
4681   Node* args[2];                // two java.lang.Class mirrors: superc, subc
4682   args[0] = argument(0);
4683   args[1] = argument(1);
4684   Node* klasses[2];             // corresponding Klasses: superk, subk
4685   klasses[0] = klasses[1] = top();
4686 
4687   enum {
4688     // A full decision tree on {superc is prim, subc is prim}:
4689     _prim_0_path = 1,           // {P,N} => false
4690                                 // {P,P} & superc!=subc => false
4691     _prim_same_path,            // {P,P} & superc==subc => true
4692     _prim_1_path,               // {N,P} => false
4693     _ref_subtype_path,          // {N,N} & subtype check wins => true
4694     _both_ref_path,             // {N,N} & subtype check loses => false
4695     PATH_LIMIT
4696   };
4697 
4698   RegionNode* region = new RegionNode(PATH_LIMIT);
4699   RegionNode* prim_region = new RegionNode(2);
4700   Node*       phi    = new PhiNode(region, TypeInt::BOOL);
4701   record_for_igvn(region);
4702   record_for_igvn(prim_region);
4703 
4704   const TypePtr* adr_type = TypeRawPtr::BOTTOM;   // memory type of loads
4705   const TypeKlassPtr* kls_type = TypeInstKlassPtr::OBJECT_OR_NULL;
4706   int class_klass_offset = java_lang_Class::klass_offset();
4707 
4708   // First null-check both mirrors and load each mirror's klass metaobject.
4709   int which_arg;
4710   for (which_arg = 0; which_arg <= 1; which_arg++) {
4711     Node* arg = args[which_arg];
4712     arg = null_check(arg);
4713     if (stopped())  break;
4714     args[which_arg] = arg;
4715 
4716     Node* p = basic_plus_adr(arg, class_klass_offset);
4717     Node* kls = LoadKlassNode::make(_gvn, immutable_memory(), p, adr_type, kls_type);
4718     klasses[which_arg] = _gvn.transform(kls);
4719   }
4720 
4721   // Having loaded both klasses, test each for null.
4722   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
4723   for (which_arg = 0; which_arg <= 1; which_arg++) {
4724     Node* kls = klasses[which_arg];
4725     Node* null_ctl = top();
4726     kls = null_check_oop(kls, &null_ctl, never_see_null);
4727     if (which_arg == 0) {
4728       prim_region->init_req(1, null_ctl);
4729     } else {
4730       region->init_req(_prim_1_path, null_ctl);
4731     }
4732     if (stopped())  break;
4733     klasses[which_arg] = kls;
4734   }
4735 
4736   if (!stopped()) {
4737     // now we have two reference types, in klasses[0..1]
4738     Node* subk   = klasses[1];  // the argument to isAssignableFrom
4739     Node* superk = klasses[0];  // the receiver
4740     region->set_req(_both_ref_path, gen_subtype_check(subk, superk));
4741     region->set_req(_ref_subtype_path, control());
4742   }
4743 
4744   // If both operands are primitive (both klasses null), then
4745   // we must return true when they are identical primitives.
4746   // It is convenient to test this after the first null klass check.
4747   // This path is also used if superc is a value mirror.
4748   set_control(_gvn.transform(prim_region));
4749   if (!stopped()) {
4750     // Since superc is primitive, make a guard for the superc==subc case.
4751     Node* cmp_eq = _gvn.transform(new CmpPNode(args[0], args[1]));
4752     Node* bol_eq = _gvn.transform(new BoolNode(cmp_eq, BoolTest::eq));
4753     generate_fair_guard(bol_eq, region);
4754     if (region->req() == PATH_LIMIT+1) {
4755       // A guard was added.  If the added guard is taken, superc==subc.
4756       region->swap_edges(PATH_LIMIT, _prim_same_path);
4757       region->del_req(PATH_LIMIT);
4758     }
4759     region->set_req(_prim_0_path, control()); // Not equal after all.
4760   }
4761 
4762   // these are the only paths that produce 'true':
4763   phi->set_req(_prim_same_path,   intcon(1));
4764   phi->set_req(_ref_subtype_path, intcon(1));
4765 
4766   // pull together the cases:
4767   assert(region->req() == PATH_LIMIT, "sane region");
4768   for (uint i = 1; i < region->req(); i++) {
4769     Node* ctl = region->in(i);
4770     if (ctl == nullptr || ctl == top()) {
4771       region->set_req(i, top());
4772       phi   ->set_req(i, top());
4773     } else if (phi->in(i) == nullptr) {
4774       phi->set_req(i, intcon(0)); // all other paths produce 'false'
4775     }
4776   }
4777 
4778   set_control(_gvn.transform(region));
4779   set_result(_gvn.transform(phi));
4780   return true;
4781 }
4782 
4783 //---------------------generate_array_guard_common------------------------
4784 Node* LibraryCallKit::generate_array_guard_common(Node* kls, RegionNode* region, ArrayKind kind, Node** obj) {
4785 
4786   if (stopped()) {
4787     return nullptr;
4788   }
4789 
4790   // Like generate_guard, adds a new path onto the region.
4791   jint  layout_con = 0;
4792   Node* layout_val = get_layout_helper(kls, layout_con);
4793   if (layout_val == nullptr) {
4794     bool query = 0;
4795     switch(kind) {
4796       case RefArray:       query = Klass::layout_helper_is_refArray(layout_con); break;
4797       case NonRefArray:    query = !Klass::layout_helper_is_refArray(layout_con); break;
4798       case TypeArray:      query = Klass::layout_helper_is_typeArray(layout_con); break;
4799       case AnyArray:       query = Klass::layout_helper_is_array(layout_con); break;
4800       case NonArray:       query = !Klass::layout_helper_is_array(layout_con); break;
4801       default:
4802         ShouldNotReachHere();
4803     }
4804     if (!query) {
4805       return nullptr;                       // never a branch
4806     } else {                             // always a branch
4807       Node* always_branch = control();
4808       if (region != nullptr)
4809         region->add_req(always_branch);
4810       set_control(top());
4811       return always_branch;
4812     }
4813   }
4814   unsigned int value = 0;
4815   BoolTest::mask btest = BoolTest::illegal;
4816   switch(kind) {
4817     case RefArray:
4818     case NonRefArray: {
4819       value = Klass::_lh_array_tag_ref_value;
4820       layout_val = _gvn.transform(new RShiftINode(layout_val, intcon(Klass::_lh_array_tag_shift)));
4821       btest = (kind == RefArray) ? BoolTest::eq : BoolTest::ne;
4822       break;
4823     }
4824     case TypeArray: {
4825       value = Klass::_lh_array_tag_type_value;
4826       layout_val = _gvn.transform(new RShiftINode(layout_val, intcon(Klass::_lh_array_tag_shift)));
4827       btest = BoolTest::eq;
4828       break;
4829     }
4830     case AnyArray:    value = Klass::_lh_neutral_value; btest = BoolTest::lt; break;
4831     case NonArray:    value = Klass::_lh_neutral_value; btest = BoolTest::gt; break;
4832     default:
4833       ShouldNotReachHere();
4834   }
4835   // Now test the correct condition.
4836   jint nval = (jint)value;
4837   Node* cmp = _gvn.transform(new CmpINode(layout_val, intcon(nval)));
4838   Node* bol = _gvn.transform(new BoolNode(cmp, btest));
4839   Node* ctrl = generate_fair_guard(bol, region);
4840   Node* is_array_ctrl = kind == NonArray ? control() : ctrl;
4841   if (obj != nullptr && is_array_ctrl != nullptr && is_array_ctrl != top()) {
4842     // Keep track of the fact that 'obj' is an array to prevent
4843     // array specific accesses from floating above the guard.
4844     *obj = _gvn.transform(new CheckCastPPNode(is_array_ctrl, *obj, TypeAryPtr::BOTTOM));
4845   }
4846   return ctrl;
4847 }
4848 
4849 // public static native Object[] ValueClass::newNullRestrictedAtomicArray(Class<?> componentType, int length, Object initVal);
4850 // public static native Object[] ValueClass::newNullRestrictedNonAtomicArray(Class<?> componentType, int length, Object initVal);
4851 // public static native Object[] ValueClass::newNullableAtomicArray(Class<?> componentType, int length);
4852 bool LibraryCallKit::inline_newArray(bool null_free, bool atomic) {
4853   assert(null_free || atomic, "nullable implies atomic");
4854   Node* componentType = argument(0);
4855   Node* length = argument(1);
4856   Node* init_val = null_free ? argument(2) : nullptr;
4857 
4858   const TypeInstPtr* tp = _gvn.type(componentType)->isa_instptr();
4859   if (tp != nullptr) {
4860     ciInstanceKlass* ik = tp->instance_klass();
4861     if (ik == C->env()->Class_klass()) {
4862       ciType* t = tp->java_mirror_type();
4863       if (t != nullptr && t->is_inlinetype()) {
4864 
4865         ciArrayKlass* array_klass = ciArrayKlass::make(t, null_free, atomic, true);
4866         assert(array_klass->is_elem_null_free() == null_free, "inconsistency");
4867 
4868         // TOOD 8350865 ZGC needs card marks on initializing oop stores
4869         if (UseZGC && null_free && !array_klass->is_flat_array_klass()) {
4870           return false;
4871         }
4872 
4873         if (array_klass->is_loaded() && array_klass->element_klass()->as_inline_klass()->is_initialized()) {
4874           const TypeAryKlassPtr* array_klass_type = TypeAryKlassPtr::make(array_klass, Type::trust_interfaces);
4875           if (null_free) {
4876             if (init_val->is_InlineType()) {
4877               if (array_klass_type->is_flat() && init_val->as_InlineType()->is_all_zero(&gvn(), /* flat */ true)) {
4878                 // Zeroing is enough because the init value is the all-zero value
4879                 init_val = nullptr;
4880               } else {
4881                 init_val = init_val->as_InlineType()->buffer(this);
4882               }
4883             }
4884             if (init_val != nullptr) {
4885 #ifdef ASSERT
4886               init_val = null_check(init_val);
4887               Node* wrong_type_ctl = gen_subtype_check(init_val, makecon(TypeKlassPtr::make(array_klass->element_klass())));
4888               {
4889                 PreserveJVMState pjvms(this);
4890                 set_control(wrong_type_ctl);
4891                 halt(control(), frameptr(), "incompatible type for initVal in newArray");
4892                 stop_and_kill_map();
4893               }
4894 #endif
4895               init_val = _gvn.transform(new CheckCastPPNode(control(), init_val, TypeOopPtr::make_from_klass(array_klass->element_klass()), ConstraintCastNode::DependencyType::NonFloatingNarrowing));
4896             }
4897           }
4898           Node* obj = new_array(makecon(array_klass_type), length, 0, nullptr, false, init_val);
4899           const TypeAryPtr* arytype = gvn().type(obj)->is_aryptr();
4900           assert(arytype->is_null_free() == null_free, "inconsistency");
4901           assert(arytype->is_not_null_free() == !null_free, "inconsistency");
4902           set_result(obj);
4903           return true;
4904         }
4905       }
4906     }
4907   }
4908   return false;
4909 }
4910 
4911 // public static native boolean ValueClass::isFlatArray(Object array);
4912 // public static native boolean ValueClass::isNullRestrictedArray(Object array);
4913 // public static native boolean ValueClass::isAtomicArray(Object array);
4914 bool LibraryCallKit::inline_getArrayProperties(ArrayPropertiesCheck check) {
4915   Node* array = argument(0);
4916 
4917   Node* bol;
4918   switch(check) {
4919     case IsFlat:
4920       bol = flat_array_test(load_object_klass(array));
4921       break;
4922     case IsNullRestricted:
4923       bol = null_free_array_test(array);
4924       break;
4925     case IsAtomic: {
4926       // See conditions in JVM_IsAtomicArray
4927       // 1. If not flat, then atomic, or else...
4928       RegionNode* atomic_region = new RegionNode(1);
4929       RegionNode* non_atomic_region = new RegionNode(1);
4930       Node* array_klass = load_object_klass(array);
4931       Node* is_flat_bol = flat_array_test(array_klass);
4932       IfNode* iff_is_flat = create_and_xform_if(control(), is_flat_bol, PROB_FAIR, COUNT_UNKNOWN);
4933       atomic_region->add_req(_gvn.transform(new IfFalseNode(iff_is_flat)));
4934       set_control(_gvn.transform(new IfTrueNode(iff_is_flat)));
4935 
4936       // 2. ...if the layout is atomic, then atomic, or else...
4937       Node* layout_kind = atomic_layout_array_test_and_get_layout_kind(array, atomic_region);
4938 
4939       // 3. ...if the element type is naturally atomic and null-free OR empty and nullable, then atomic, or else...
4940       int element_klass_offset = in_bytes(ObjArrayKlass::element_klass_offset());
4941       Node* array_element_klass_addr = off_heap_plus_addr(array_klass, element_klass_offset);
4942       Node* array_element_klass = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), array_element_klass_addr, _gvn.type(array_klass)->is_klassptr()));
4943       int klass_flags_offset = in_bytes(InstanceKlass::misc_flags_offset() + InstanceKlassFlags::flags_offset());
4944       Node* array_element_klass_flags_addr = off_heap_plus_addr(array_element_klass, klass_flags_offset);
4945       Node* array_element_klass_flags = make_load(control(), array_element_klass_flags_addr, TypeInt::INT, T_INT, MemNode::unordered);
4946 
4947       // Here, layout can only be non-atomic, otherwise atomic_layout_array_test_and_get_layout_kind already decides the array to be atomic.
4948       Node* is_null_free_cmp = _gvn.transform(new CmpINode(layout_kind, intcon(static_cast<jint>(LayoutKind::NULL_FREE_NON_ATOMIC_FLAT))));
4949       Node* is_null_free_bol = _gvn.transform(new BoolNode(is_null_free_cmp, BoolTest::eq));
4950       IfNode* iff_is_null_free_bol = create_and_xform_if(control(), is_null_free_bol, PROB_FAIR, COUNT_UNKNOWN);
4951       Node* is_null_free_ctl = _gvn.transform(new IfTrueNode(iff_is_null_free_bol));
4952       Node* is_nullable_ctl = _gvn.transform(new IfFalseNode(iff_is_null_free_bol));
4953 
4954       Node* is_naturally_atomic_flag = _gvn.transform(new AndINode(array_element_klass_flags, intcon(InstanceKlassFlags::_misc_is_naturally_atomic)));
4955       Node* is_naturally_atomic_cmp = _gvn.transform(new CmpINode(is_naturally_atomic_flag, intcon(0)));
4956       Node* is_naturally_atomic_bol = _gvn.transform(new BoolNode(is_naturally_atomic_cmp, BoolTest::ne));
4957       IfNode* iff_is_naturally_atomic = create_and_xform_if(is_null_free_ctl, is_naturally_atomic_bol, PROB_FAIR, COUNT_UNKNOWN);
4958       Node* is_naturally_atomic_ctl = _gvn.transform(new IfTrueNode(iff_is_naturally_atomic));
4959       Node* is_not_naturally_atomic_ctl = _gvn.transform(new IfFalseNode(iff_is_naturally_atomic));
4960       atomic_region->add_req(is_naturally_atomic_ctl);
4961       non_atomic_region->add_req(is_not_naturally_atomic_ctl);
4962 
4963       Node* is_empty_inline_type_flag = _gvn.transform(new AndINode(array_element_klass_flags, intcon(InstanceKlassFlags::_misc_is_empty_inline_type)));
4964       Node* is_empty_inline_type_cmp = _gvn.transform(new CmpINode(is_empty_inline_type_flag, intcon(0)));
4965       Node* is_empty_inline_type_bol = _gvn.transform(new BoolNode(is_empty_inline_type_cmp, BoolTest::ne));
4966       IfNode* iff_is_empty_inline_type = create_and_xform_if(is_nullable_ctl, is_empty_inline_type_bol, PROB_FAIR, COUNT_UNKNOWN);
4967       Node* is_empty_inline_type_ctl = _gvn.transform(new IfTrueNode(iff_is_empty_inline_type));
4968       Node* is_nonempty_inline_type_ctl = _gvn.transform(new IfFalseNode(iff_is_empty_inline_type));
4969       atomic_region->add_req(is_empty_inline_type_ctl);
4970       non_atomic_region->add_req(is_nonempty_inline_type_ctl);
4971 
4972       // ...non-atomic, but we tried everything.
4973       RegionNode* decision = new RegionNode(3);
4974       decision->set_req(1, _gvn.transform(atomic_region));
4975       decision->set_req(2, _gvn.transform(non_atomic_region));
4976       PhiNode* result = PhiNode::make(decision, intcon(1), TypeInt::BOOL);
4977       result->set_req(2, intcon(0));
4978       set_control(_gvn.transform(decision));
4979       set_result(_gvn.transform(result));
4980       return true;
4981     }
4982     default:
4983       ShouldNotReachHere();
4984   }
4985 
4986   Node* res = gvn().transform(new CMoveINode(bol, intcon(0), intcon(1), TypeInt::BOOL));
4987   set_result(res);
4988   return true;
4989 }
4990 
4991 // Load the default refined array klass from an ObjArrayKlass. This relies on the first entry in the
4992 // '_next_refined_array_klass' linked list being the default (see ObjArrayKlass::klass_with_properties).
4993 Node* LibraryCallKit::load_default_refined_array_klass(Node* klass_node, bool type_array_guard) {
4994   RegionNode* region = new RegionNode(2);
4995   Node* phi = new PhiNode(region, TypeInstKlassPtr::OBJECT_OR_NULL);
4996 
4997   if (type_array_guard) {
4998     generate_typeArray_guard(klass_node, region);
4999     if (region->req() == 3) {
5000       phi->add_req(klass_node);
5001     }
5002   }
5003   Node* adr_refined_klass = basic_plus_adr(top(), klass_node, in_bytes(ObjArrayKlass::next_refined_array_klass_offset()));
5004   Node* refined_klass = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), adr_refined_klass, TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
5005 
5006   // Can be null if not initialized yet, just deopt
5007   Node* null_ctl = top();
5008   refined_klass = null_check_oop(refined_klass, &null_ctl, /* never_see_null= */ true);
5009 
5010   region->init_req(1, control());
5011   phi->init_req(1, refined_klass);
5012 
5013   set_control(_gvn.transform(region));
5014   return _gvn.transform(phi);
5015 }
5016 
5017 // Load the non-refined array klass from an ObjArrayKlass.
5018 Node* LibraryCallKit::load_non_refined_array_klass(Node* klass_node) {
5019   const TypeAryKlassPtr* ary_klass_ptr = _gvn.type(klass_node)->isa_aryklassptr();
5020   if (ary_klass_ptr != nullptr && ary_klass_ptr->klass_is_exact()) {
5021     return _gvn.makecon(ary_klass_ptr->cast_to_refined_array_klass_ptr(false));
5022   }
5023 
5024   RegionNode* region = new RegionNode(2);
5025   Node* phi = new PhiNode(region, TypeInstKlassPtr::OBJECT);
5026 
5027   generate_typeArray_guard(klass_node, region);
5028   if (region->req() == 3) {
5029     phi->add_req(klass_node);
5030   }
5031   Node* super_adr = basic_plus_adr(top(), klass_node, in_bytes(Klass::super_offset()));
5032   Node* super_klass = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), super_adr, TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT));
5033 
5034   region->init_req(1, control());
5035   phi->init_req(1, super_klass);
5036 
5037   set_control(_gvn.transform(region));
5038   return _gvn.transform(phi);
5039 }
5040 
5041 //-----------------------inline_native_newArray--------------------------
5042 // private static native Object java.lang.reflect.Array.newArray(Class<?> componentType, int length);
5043 // private        native Object Unsafe.allocateUninitializedArray0(Class<?> cls, int size);
5044 bool LibraryCallKit::inline_unsafe_newArray(bool uninitialized) {
5045   Node* mirror;
5046   Node* count_val;
5047   if (uninitialized) {
5048     null_check_receiver();
5049     mirror    = argument(1);
5050     count_val = argument(2);
5051   } else {
5052     mirror    = argument(0);
5053     count_val = argument(1);
5054   }
5055 
5056   mirror = null_check(mirror);
5057   // If mirror or obj is dead, only null-path is taken.
5058   if (stopped())  return true;
5059 
5060   enum { _normal_path = 1, _slow_path = 2, PATH_LIMIT };
5061   RegionNode* result_reg = new RegionNode(PATH_LIMIT);
5062   PhiNode*    result_val = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
5063   PhiNode*    result_io  = new PhiNode(result_reg, Type::ABIO);
5064   PhiNode*    result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
5065 
5066   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
5067   Node* klass_node = load_array_klass_from_mirror(mirror, never_see_null,
5068                                                   result_reg, _slow_path);
5069   Node* normal_ctl   = control();
5070   Node* no_array_ctl = result_reg->in(_slow_path);
5071 
5072   // Generate code for the slow case.  We make a call to newArray().
5073   set_control(no_array_ctl);
5074   if (!stopped()) {
5075     // Either the input type is void.class, or else the
5076     // array klass has not yet been cached.  Either the
5077     // ensuing call will throw an exception, or else it
5078     // will cache the array klass for next time.
5079     PreserveJVMState pjvms(this);
5080     CallJavaNode* slow_call = nullptr;
5081     if (uninitialized) {
5082       // Generate optimized virtual call (holder class 'Unsafe' is final)
5083       slow_call = generate_method_call(vmIntrinsics::_allocateUninitializedArray, false, false, true);
5084     } else {
5085       slow_call = generate_method_call_static(vmIntrinsics::_newArray, true);
5086     }
5087     Node* slow_result = set_results_for_java_call(slow_call);
5088     // this->control() comes from set_results_for_java_call
5089     result_reg->set_req(_slow_path, control());
5090     result_val->set_req(_slow_path, slow_result);
5091     result_io ->set_req(_slow_path, i_o());
5092     result_mem->set_req(_slow_path, reset_memory());
5093   }
5094 
5095   set_control(normal_ctl);
5096   if (!stopped()) {
5097     // Normal case:  The array type has been cached in the java.lang.Class.
5098     // The following call works fine even if the array type is polymorphic.
5099     // It could be a dynamic mix of int[], boolean[], Object[], etc.
5100 
5101     klass_node = load_default_refined_array_klass(klass_node);
5102 
5103     Node* obj = new_array(klass_node, count_val, 0);  // no arguments to push
5104     result_reg->init_req(_normal_path, control());
5105     result_val->init_req(_normal_path, obj);
5106     result_io ->init_req(_normal_path, i_o());
5107     result_mem->init_req(_normal_path, reset_memory());
5108 
5109     if (uninitialized) {
5110       // Mark the allocation so that zeroing is skipped
5111       AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(obj);
5112       alloc->maybe_set_complete(&_gvn);
5113     }
5114   }
5115 
5116   // Return the combined state.
5117   set_i_o(        _gvn.transform(result_io)  );
5118   set_all_memory( _gvn.transform(result_mem));
5119 
5120   C->set_has_split_ifs(true); // Has chance for split-if optimization
5121   set_result(result_reg, result_val);
5122   return true;
5123 }
5124 
5125 //----------------------inline_native_getLength--------------------------
5126 // public static native int java.lang.reflect.Array.getLength(Object array);
5127 bool LibraryCallKit::inline_native_getLength() {
5128   if (too_many_traps(Deoptimization::Reason_intrinsic))  return false;
5129 
5130   Node* array = null_check(argument(0));
5131   // If array is dead, only null-path is taken.
5132   if (stopped())  return true;
5133 
5134   // Deoptimize if it is a non-array.
5135   Node* non_array = generate_non_array_guard(load_object_klass(array), nullptr, &array);
5136 
5137   if (non_array != nullptr) {
5138     PreserveJVMState pjvms(this);
5139     set_control(non_array);
5140     uncommon_trap(Deoptimization::Reason_intrinsic,
5141                   Deoptimization::Action_maybe_recompile);
5142   }
5143 
5144   // If control is dead, only non-array-path is taken.
5145   if (stopped())  return true;
5146 
5147   // The works fine even if the array type is polymorphic.
5148   // It could be a dynamic mix of int[], boolean[], Object[], etc.
5149   Node* result = load_array_length(array);
5150 
5151   C->set_has_split_ifs(true);  // Has chance for split-if optimization
5152   set_result(result);
5153   return true;
5154 }
5155 
5156 //------------------------inline_array_copyOf----------------------------
5157 // public static <T,U> T[] java.util.Arrays.copyOf(     U[] original, int newLength,         Class<? extends T[]> newType);
5158 // public static <T,U> T[] java.util.Arrays.copyOfRange(U[] original, int from,      int to, Class<? extends T[]> newType);
5159 bool LibraryCallKit::inline_array_copyOf(bool is_copyOfRange) {
5160   if (too_many_traps(Deoptimization::Reason_intrinsic))  return false;
5161 
5162   // Get the arguments.
5163   Node* original          = argument(0);
5164   Node* start             = is_copyOfRange? argument(1): intcon(0);
5165   Node* end               = is_copyOfRange? argument(2): argument(1);
5166   Node* array_type_mirror = is_copyOfRange? argument(3): argument(2);
5167 
5168   Node* newcopy = nullptr;
5169 
5170   // Set the original stack and the reexecute bit for the interpreter to reexecute
5171   // the bytecode that invokes Arrays.copyOf if deoptimization happens.
5172   { PreserveReexecuteState preexecs(this);
5173     jvms()->set_should_reexecute(true);
5174 
5175     array_type_mirror = null_check(array_type_mirror);
5176     original          = null_check(original);
5177 
5178     // Check if a null path was taken unconditionally.
5179     if (stopped())  return true;
5180 
5181     Node* orig_length = load_array_length(original);
5182 
5183     Node* klass_node = load_klass_from_mirror(array_type_mirror, false, nullptr, 0);
5184     klass_node = null_check(klass_node);
5185 
5186     RegionNode* bailout = new RegionNode(1);
5187     record_for_igvn(bailout);
5188 
5189     // Despite the generic type of Arrays.copyOf, the mirror might be int, int[], etc.
5190     // Bail out if that is so.
5191     // Inline type array may have object field that would require a
5192     // write barrier. Conservatively, go to slow path.
5193     // TODO 8251971: Optimize for the case when flat src/dst are later found
5194     // to not contain oops (i.e., move this check to the macro expansion phase).
5195     // TODO 8382226: Revisit for flat abstract value class arrays
5196     BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
5197     const TypeAryPtr* orig_t = _gvn.type(original)->isa_aryptr();
5198     const TypeKlassPtr* tklass = _gvn.type(klass_node)->is_klassptr();
5199     bool exclude_flat = UseArrayFlattening && bs->array_copy_requires_gc_barriers(true, T_OBJECT, false, false, BarrierSetC2::Parsing) &&
5200                         // Can src array be flat and contain oops?
5201                         (orig_t == nullptr || (!orig_t->is_not_flat() && (!orig_t->is_flat() || orig_t->elem()->inline_klass()->contains_oops()))) &&
5202                         // Can dest array be flat and contain oops?
5203                         tklass->can_be_inline_array() && (!tklass->is_flat() || tklass->is_aryklassptr()->elem()->is_instklassptr()->instance_klass()->as_inline_klass()->contains_oops());
5204     Node* not_objArray = exclude_flat ? generate_non_refArray_guard(klass_node, bailout) : generate_typeArray_guard(klass_node, bailout);
5205 
5206     Node* refined_klass_node = load_default_refined_array_klass(klass_node, /* type_array_guard= */ false);
5207 
5208     if (not_objArray != nullptr) {
5209       // Improve the klass node's type from the new optimistic assumption:
5210       ciKlass* ak = ciArrayKlass::make(env()->Object_klass());
5211       bool not_flat = !UseArrayFlattening;
5212       bool not_null_free = !Arguments::is_valhalla_enabled();
5213       const Type* akls = TypeAryKlassPtr::make(TypePtr::NotNull, ak, Type::Offset(0), Type::trust_interfaces, not_flat, not_null_free, false, false, not_flat, true);
5214       Node* cast = new CastPPNode(control(), refined_klass_node, akls);
5215       refined_klass_node = _gvn.transform(cast);
5216     }
5217 
5218     // Bail out if either start or end is negative.
5219     generate_negative_guard(start, bailout, &start);
5220     generate_negative_guard(end,   bailout, &end);
5221 
5222     Node* length = end;
5223     if (_gvn.type(start) != TypeInt::ZERO) {
5224       length = _gvn.transform(new SubINode(end, start));
5225     }
5226 
5227     // Bail out if length is negative (i.e., if start > end).
5228     // Without this the new_array would throw
5229     // NegativeArraySizeException but IllegalArgumentException is what
5230     // should be thrown
5231     generate_negative_guard(length, bailout, &length);
5232 
5233     // Handle inline type arrays
5234     // TODO 8251971 This is too strong
5235     generate_fair_guard(flat_array_test(load_object_klass(original)), bailout);
5236     generate_fair_guard(flat_array_test(refined_klass_node), bailout);
5237     generate_fair_guard(null_free_array_test(original), bailout);
5238 
5239     // Bail out if start is larger than the original length
5240     Node* orig_tail = _gvn.transform(new SubINode(orig_length, start));
5241     generate_negative_guard(orig_tail, bailout, &orig_tail);
5242 
5243     if (bailout->req() > 1) {
5244       PreserveJVMState pjvms(this);
5245       set_control(_gvn.transform(bailout));
5246       uncommon_trap(Deoptimization::Reason_intrinsic,
5247                     Deoptimization::Action_maybe_recompile);
5248     }
5249 
5250     if (!stopped()) {
5251       // How many elements will we copy from the original?
5252       // The answer is MinI(orig_tail, length).
5253       Node* moved = _gvn.transform(new MinINode(orig_tail, length));
5254 
5255       // Generate a direct call to the right arraycopy function(s).
5256       // We know the copy is disjoint but we might not know if the
5257       // oop stores need checking.
5258       // Extreme case:  Arrays.copyOf((Integer[])x, 10, String[].class).
5259       // This will fail a store-check if x contains any non-nulls.
5260 
5261       // ArrayCopyNode:Ideal may transform the ArrayCopyNode to
5262       // loads/stores but it is legal only if we're sure the
5263       // Arrays.copyOf would succeed. So we need all input arguments
5264       // to the copyOf to be validated, including that the copy to the
5265       // new array won't trigger an ArrayStoreException. That subtype
5266       // check can be optimized if we know something on the type of
5267       // the input array from type speculation.
5268       if (_gvn.type(klass_node)->singleton()) {
5269         const TypeKlassPtr* subk = _gvn.type(load_object_klass(original))->is_klassptr();
5270         const TypeKlassPtr* superk = _gvn.type(klass_node)->is_klassptr();
5271 
5272         int test = C->static_subtype_check(superk, subk);
5273         if (test != Compile::SSC_always_true && test != Compile::SSC_always_false) {
5274           const TypeOopPtr* t_original = _gvn.type(original)->is_oopptr();
5275           if (t_original->speculative_type() != nullptr) {
5276             original = maybe_cast_profiled_obj(original, t_original->speculative_type(), true);
5277           }
5278         }
5279       }
5280 
5281       bool validated = false;
5282       // Reason_class_check rather than Reason_intrinsic because we
5283       // want to intrinsify even if this traps.
5284       if (!too_many_traps(Deoptimization::Reason_class_check)) {
5285         Node* not_subtype_ctrl = gen_subtype_check(original, klass_node);
5286 
5287         if (not_subtype_ctrl != top()) {
5288           PreserveJVMState pjvms(this);
5289           set_control(not_subtype_ctrl);
5290           uncommon_trap(Deoptimization::Reason_class_check,
5291                         Deoptimization::Action_make_not_entrant);
5292           assert(stopped(), "Should be stopped");
5293         }
5294         validated = true;
5295       }
5296 
5297       if (!stopped()) {
5298         newcopy = new_array(refined_klass_node, length, 0);  // no arguments to push
5299 
5300         ArrayCopyNode* ac = ArrayCopyNode::make(this, true, original, start, newcopy, intcon(0), moved, true, true,
5301                                                 load_object_klass(original), klass_node);
5302         if (!is_copyOfRange) {
5303           ac->set_copyof(validated);
5304         } else {
5305           ac->set_copyofrange(validated);
5306         }
5307         Node* n = _gvn.transform(ac);
5308         if (n == ac) {
5309           ac->connect_outputs(this);
5310         } else {
5311           assert(validated, "shouldn't transform if all arguments not validated");
5312           set_all_memory(n);
5313         }
5314       }
5315     }
5316   } // original reexecute is set back here
5317 
5318   C->set_has_split_ifs(true); // Has chance for split-if optimization
5319   if (!stopped()) {
5320     set_result(newcopy);
5321   }
5322   return true;
5323 }
5324 
5325 
5326 //----------------------generate_virtual_guard---------------------------
5327 // Helper for hashCode and clone.  Peeks inside the vtable to avoid a call.
5328 Node* LibraryCallKit::generate_virtual_guard(Node* obj_klass,
5329                                              RegionNode* slow_region) {
5330   ciMethod* method = callee();
5331   int vtable_index = method->vtable_index();
5332   assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index,
5333          "bad index %d", vtable_index);
5334   // Get the Method* out of the appropriate vtable entry.
5335   int entry_offset = in_bytes(Klass::vtable_start_offset()) +
5336                      vtable_index*vtableEntry::size_in_bytes() +
5337                      in_bytes(vtableEntry::method_offset());
5338   Node* entry_addr = off_heap_plus_addr(obj_klass, entry_offset);
5339   Node* target_call = make_load(nullptr, entry_addr, TypePtr::NOTNULL, T_ADDRESS, MemNode::unordered);
5340 
5341   // Compare the target method with the expected method (e.g., Object.hashCode).
5342   const TypePtr* native_call_addr = TypeMetadataPtr::make(method);
5343 
5344   Node* native_call = makecon(native_call_addr);
5345   Node* chk_native  = _gvn.transform(new CmpPNode(target_call, native_call));
5346   Node* test_native = _gvn.transform(new BoolNode(chk_native, BoolTest::ne));
5347 
5348   return generate_slow_guard(test_native, slow_region);
5349 }
5350 
5351 //-----------------------generate_method_call----------------------------
5352 // Use generate_method_call to make a slow-call to the real
5353 // method if the fast path fails.  An alternative would be to
5354 // use a stub like OptoRuntime::slow_arraycopy_Java.
5355 // This only works for expanding the current library call,
5356 // not another intrinsic.  (E.g., don't use this for making an
5357 // arraycopy call inside of the copyOf intrinsic.)
5358 CallJavaNode*
5359 LibraryCallKit::generate_method_call(vmIntrinsicID method_id, bool is_virtual, bool is_static, bool res_not_null) {
5360   // When compiling the intrinsic method itself, do not use this technique.
5361   guarantee(callee() != C->method(), "cannot make slow-call to self");
5362 
5363   ciMethod* method = callee();
5364   // ensure the JVMS we have will be correct for this call
5365   guarantee(method_id == method->intrinsic_id(), "must match");
5366 
5367   const TypeFunc* tf = TypeFunc::make(method);
5368   if (res_not_null) {
5369     assert(tf->return_type() == T_OBJECT, "");
5370     const TypeTuple* range = tf->range_cc();
5371     const Type** fields = TypeTuple::fields(range->cnt());
5372     fields[TypeFunc::Parms] = range->field_at(TypeFunc::Parms)->filter_speculative(TypePtr::NOTNULL);
5373     const TypeTuple* new_range = TypeTuple::make(range->cnt(), fields);
5374     tf = TypeFunc::make(tf->domain_cc(), new_range);
5375   }
5376   CallJavaNode* slow_call;
5377   if (is_static) {
5378     assert(!is_virtual, "");
5379     slow_call = new CallStaticJavaNode(C, tf,
5380                            SharedRuntime::get_resolve_static_call_stub(), method);
5381   } else if (is_virtual) {
5382     assert(!gvn().type(argument(0))->maybe_null(), "should not be null");
5383     int vtable_index = Method::invalid_vtable_index;
5384     if (UseInlineCaches) {
5385       // Suppress the vtable call
5386     } else {
5387       // hashCode and clone are not a miranda methods,
5388       // so the vtable index is fixed.
5389       // No need to use the linkResolver to get it.
5390        vtable_index = method->vtable_index();
5391        assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index,
5392               "bad index %d", vtable_index);
5393     }
5394     slow_call = new CallDynamicJavaNode(tf,
5395                           SharedRuntime::get_resolve_virtual_call_stub(),
5396                           method, vtable_index);
5397   } else {  // neither virtual nor static:  opt_virtual
5398     assert(!gvn().type(argument(0))->maybe_null(), "should not be null");
5399     slow_call = new CallStaticJavaNode(C, tf,
5400                                 SharedRuntime::get_resolve_opt_virtual_call_stub(), method);
5401     slow_call->set_optimized_virtual(true);
5402   }
5403   if (CallGenerator::is_inlined_method_handle_intrinsic(this->method(), bci(), callee())) {
5404     // To be able to issue a direct call (optimized virtual or virtual)
5405     // and skip a call to MH.linkTo*/invokeBasic adapter, additional information
5406     // about the method being invoked should be attached to the call site to
5407     // make resolution logic work (see SharedRuntime::resolve_{virtual,opt_virtual}_call_C).
5408     slow_call->set_override_symbolic_info(true);
5409   }
5410   set_arguments_for_java_call(slow_call);
5411   set_edges_for_java_call(slow_call);
5412   return slow_call;
5413 }
5414 
5415 
5416 /**
5417  * Build special case code for calls to hashCode on an object. This call may
5418  * be virtual (invokevirtual) or bound (invokespecial). For each case we generate
5419  * slightly different code.
5420  */
5421 bool LibraryCallKit::inline_native_hashcode(bool is_virtual, bool is_static) {
5422   assert(is_static == callee()->is_static(), "correct intrinsic selection");
5423   assert(!(is_virtual && is_static), "either virtual, special, or static");
5424 
5425   enum { _slow_path = 1, _fast_path, _null_path, PATH_LIMIT };
5426 
5427   RegionNode* result_reg = new RegionNode(PATH_LIMIT);
5428   PhiNode*    result_val = new PhiNode(result_reg, TypeInt::INT);
5429   PhiNode*    result_io  = new PhiNode(result_reg, Type::ABIO);
5430   PhiNode*    result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
5431   Node* obj = argument(0);
5432 
5433   // Don't intrinsify hashcode on inline types for now.
5434   // The "is locked" runtime check also subsumes the inline type check (as inline types cannot be locked) and goes to the slow path.
5435   if (gvn().type(obj)->is_inlinetypeptr()) {
5436     return false;
5437   }
5438 
5439   if (!is_static) {
5440     // Check for hashing null object
5441     obj = null_check_receiver();
5442     if (stopped())  return true;        // unconditionally null
5443     result_reg->init_req(_null_path, top());
5444     result_val->init_req(_null_path, top());
5445   } else {
5446     // Do a null check, and return zero if null.
5447     // System.identityHashCode(null) == 0
5448     Node* null_ctl = top();
5449     obj = null_check_oop(obj, &null_ctl);
5450     result_reg->init_req(_null_path, null_ctl);
5451     result_val->init_req(_null_path, _gvn.intcon(0));
5452   }
5453 
5454   // Unconditionally null?  Then return right away.
5455   if (stopped()) {
5456     set_control( result_reg->in(_null_path));
5457     if (!stopped())
5458       set_result(result_val->in(_null_path));
5459     return true;
5460   }
5461 
5462   // We only go to the fast case code if we pass a number of guards.  The
5463   // paths which do not pass are accumulated in the slow_region.
5464   RegionNode* slow_region = new RegionNode(1);
5465   record_for_igvn(slow_region);
5466 
5467   // If this is a virtual call, we generate a funny guard.  We pull out
5468   // the vtable entry corresponding to hashCode() from the target object.
5469   // If the target method which we are calling happens to be the native
5470   // Object hashCode() method, we pass the guard.  We do not need this
5471   // guard for non-virtual calls -- the caller is known to be the native
5472   // Object hashCode().
5473   if (is_virtual) {
5474     // After null check, get the object's klass.
5475     Node* obj_klass = load_object_klass(obj);
5476     generate_virtual_guard(obj_klass, slow_region);
5477   }
5478 
5479   // Get the header out of the object, use LoadMarkNode when available
5480   Node* header_addr = basic_plus_adr(obj, oopDesc::mark_offset_in_bytes());
5481   // The control of the load must be null. Otherwise, the load can move before
5482   // the null check after castPP removal.
5483   Node* no_ctrl = nullptr;
5484   Node* header = make_load(no_ctrl, header_addr, TypeX_X, TypeX_X->basic_type(), MemNode::unordered);
5485 
5486   if (!UseObjectMonitorTable) {
5487     // Test the header to see if it is safe to read w.r.t. locking.
5488     // We cannot use the inline type mask as this may check bits that are overridden
5489     // by an object monitor's pointer when inflating locking.
5490     Node *lock_mask      = _gvn.MakeConX(markWord::lock_mask_in_place);
5491     Node *lmasked_header = _gvn.transform(new AndXNode(header, lock_mask));
5492     Node *monitor_val   = _gvn.MakeConX(markWord::monitor_value);
5493     Node *chk_monitor   = _gvn.transform(new CmpXNode(lmasked_header, monitor_val));
5494     Node *test_monitor  = _gvn.transform(new BoolNode(chk_monitor, BoolTest::eq));
5495 
5496     generate_slow_guard(test_monitor, slow_region);
5497   }
5498 
5499   // Get the hash value and check to see that it has been properly assigned.
5500   // We depend on hash_mask being at most 32 bits and avoid the use of
5501   // hash_mask_in_place because it could be larger than 32 bits in a 64-bit
5502   // vm: see markWord.hpp.
5503   Node *hash_mask      = _gvn.intcon(markWord::hash_mask);
5504   Node *hash_shift     = _gvn.intcon(markWord::hash_shift);
5505   Node *hshifted_header= _gvn.transform(new URShiftXNode(header, hash_shift));
5506   // This hack lets the hash bits live anywhere in the mark object now, as long
5507   // as the shift drops the relevant bits into the low 32 bits.  Note that
5508   // Java spec says that HashCode is an int so there's no point in capturing
5509   // an 'X'-sized hashcode (32 in 32-bit build or 64 in 64-bit build).
5510   hshifted_header      = ConvX2I(hshifted_header);
5511   Node *hash_val       = _gvn.transform(new AndINode(hshifted_header, hash_mask));
5512 
5513   Node *no_hash_val    = _gvn.intcon(markWord::no_hash);
5514   Node *chk_assigned   = _gvn.transform(new CmpINode( hash_val, no_hash_val));
5515   Node *test_assigned  = _gvn.transform(new BoolNode( chk_assigned, BoolTest::eq));
5516 
5517   generate_slow_guard(test_assigned, slow_region);
5518 
5519   Node* init_mem = reset_memory();
5520   // fill in the rest of the null path:
5521   result_io ->init_req(_null_path, i_o());
5522   result_mem->init_req(_null_path, init_mem);
5523 
5524   result_val->init_req(_fast_path, hash_val);
5525   result_reg->init_req(_fast_path, control());
5526   result_io ->init_req(_fast_path, i_o());
5527   result_mem->init_req(_fast_path, init_mem);
5528 
5529   // Generate code for the slow case.  We make a call to hashCode().
5530   set_control(_gvn.transform(slow_region));
5531   if (!stopped()) {
5532     // No need for PreserveJVMState, because we're using up the present state.
5533     set_all_memory(init_mem);
5534     vmIntrinsics::ID hashCode_id = is_static ? vmIntrinsics::_identityHashCode : vmIntrinsics::_hashCode;
5535     CallJavaNode* slow_call = generate_method_call(hashCode_id, is_virtual, is_static, false);
5536     Node* slow_result = set_results_for_java_call(slow_call);
5537     // this->control() comes from set_results_for_java_call
5538     result_reg->init_req(_slow_path, control());
5539     result_val->init_req(_slow_path, slow_result);
5540     result_io  ->set_req(_slow_path, i_o());
5541     result_mem ->set_req(_slow_path, reset_memory());
5542   }
5543 
5544   // Return the combined state.
5545   set_i_o(        _gvn.transform(result_io)  );
5546   set_all_memory( _gvn.transform(result_mem));
5547 
5548   set_result(result_reg, result_val);
5549   return true;
5550 }
5551 
5552 //---------------------------inline_native_getClass----------------------------
5553 // public final native Class<?> java.lang.Object.getClass();
5554 //
5555 // Build special case code for calls to getClass on an object.
5556 bool LibraryCallKit::inline_native_getClass() {
5557   Node* obj = argument(0);
5558   if (obj->is_InlineType()) {
5559     const Type* t = _gvn.type(obj);
5560     if (t->maybe_null()) {
5561       null_check(obj);
5562     }
5563     set_result(makecon(TypeInstPtr::make(t->inline_klass()->java_mirror())));
5564     return true;
5565   }
5566   obj = null_check_receiver();
5567   if (stopped())  return true;
5568   set_result(load_mirror_from_klass(load_object_klass(obj)));
5569   return true;
5570 }
5571 
5572 //-----------------inline_native_Reflection_getCallerClass---------------------
5573 // public static native Class<?> sun.reflect.Reflection.getCallerClass();
5574 //
5575 // In the presence of deep enough inlining, getCallerClass() becomes a no-op.
5576 //
5577 // NOTE: This code must perform the same logic as JVM_GetCallerClass
5578 // in that it must skip particular security frames and checks for
5579 // caller sensitive methods.
5580 bool LibraryCallKit::inline_native_Reflection_getCallerClass() {
5581 #ifndef PRODUCT
5582   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5583     tty->print_cr("Attempting to inline sun.reflect.Reflection.getCallerClass");
5584   }
5585 #endif
5586 
5587   if (!jvms()->has_method()) {
5588 #ifndef PRODUCT
5589     if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5590       tty->print_cr("  Bailing out because intrinsic was inlined at top level");
5591     }
5592 #endif
5593     return false;
5594   }
5595 
5596   // Walk back up the JVM state to find the caller at the required
5597   // depth.
5598   JVMState* caller_jvms = jvms();
5599 
5600   // Cf. JVM_GetCallerClass
5601   // NOTE: Start the loop at depth 1 because the current JVM state does
5602   // not include the Reflection.getCallerClass() frame.
5603   for (int n = 1; caller_jvms != nullptr; caller_jvms = caller_jvms->caller(), n++) {
5604     ciMethod* m = caller_jvms->method();
5605     switch (n) {
5606     case 0:
5607       fatal("current JVM state does not include the Reflection.getCallerClass frame");
5608       break;
5609     case 1:
5610       // Frame 0 and 1 must be caller sensitive (see JVM_GetCallerClass).
5611       if (!m->caller_sensitive()) {
5612 #ifndef PRODUCT
5613         if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5614           tty->print_cr("  Bailing out: CallerSensitive annotation expected at frame %d", n);
5615         }
5616 #endif
5617         return false;  // bail-out; let JVM_GetCallerClass do the work
5618       }
5619       break;
5620     default:
5621       if (!m->is_ignored_by_security_stack_walk()) {
5622         // We have reached the desired frame; return the holder class.
5623         // Acquire method holder as java.lang.Class and push as constant.
5624         ciInstanceKlass* caller_klass = caller_jvms->method()->holder();
5625         ciInstance* caller_mirror = caller_klass->java_mirror();
5626         set_result(makecon(TypeInstPtr::make(caller_mirror)));
5627 
5628 #ifndef PRODUCT
5629         if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5630           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());
5631           tty->print_cr("  JVM state at this point:");
5632           for (int i = jvms()->depth(), n = 1; i >= 1; i--, n++) {
5633             ciMethod* m = jvms()->of_depth(i)->method();
5634             tty->print_cr("   %d) %s.%s", n, m->holder()->name()->as_utf8(), m->name()->as_utf8());
5635           }
5636         }
5637 #endif
5638         return true;
5639       }
5640       break;
5641     }
5642   }
5643 
5644 #ifndef PRODUCT
5645   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5646     tty->print_cr("  Bailing out because caller depth exceeded inlining depth = %d", jvms()->depth());
5647     tty->print_cr("  JVM state at this point:");
5648     for (int i = jvms()->depth(), n = 1; i >= 1; i--, n++) {
5649       ciMethod* m = jvms()->of_depth(i)->method();
5650       tty->print_cr("   %d) %s.%s", n, m->holder()->name()->as_utf8(), m->name()->as_utf8());
5651     }
5652   }
5653 #endif
5654 
5655   return false;  // bail-out; let JVM_GetCallerClass do the work
5656 }
5657 
5658 bool LibraryCallKit::inline_fp_conversions(vmIntrinsics::ID id) {
5659   Node* arg = argument(0);
5660   Node* result = nullptr;
5661 
5662   switch (id) {
5663   case vmIntrinsics::_floatToRawIntBits:    result = new MoveF2INode(arg);  break;
5664   case vmIntrinsics::_intBitsToFloat:       result = new MoveI2FNode(arg);  break;
5665   case vmIntrinsics::_doubleToRawLongBits:  result = new MoveD2LNode(arg);  break;
5666   case vmIntrinsics::_longBitsToDouble:     result = new MoveL2DNode(arg);  break;
5667   case vmIntrinsics::_floatToFloat16:       result = new ConvF2HFNode(arg); break;
5668   case vmIntrinsics::_float16ToFloat:       result = new ConvHF2FNode(arg); break;
5669 
5670   case vmIntrinsics::_doubleToLongBits: {
5671     // two paths (plus control) merge in a wood
5672     RegionNode *r = new RegionNode(3);
5673     Node *phi = new PhiNode(r, TypeLong::LONG);
5674 
5675     Node *cmpisnan = _gvn.transform(new CmpDNode(arg, arg));
5676     // Build the boolean node
5677     Node *bolisnan = _gvn.transform(new BoolNode(cmpisnan, BoolTest::ne));
5678 
5679     // Branch either way.
5680     // NaN case is less traveled, which makes all the difference.
5681     IfNode *ifisnan = create_and_xform_if(control(), bolisnan, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
5682     Node *opt_isnan = _gvn.transform(ifisnan);
5683     assert( opt_isnan->is_If(), "Expect an IfNode");
5684     IfNode *opt_ifisnan = (IfNode*)opt_isnan;
5685     Node *iftrue = _gvn.transform(new IfTrueNode(opt_ifisnan));
5686 
5687     set_control(iftrue);
5688 
5689     static const jlong nan_bits = CONST64(0x7ff8000000000000);
5690     Node *slow_result = longcon(nan_bits); // return NaN
5691     phi->init_req(1, _gvn.transform( slow_result ));
5692     r->init_req(1, iftrue);
5693 
5694     // Else fall through
5695     Node *iffalse = _gvn.transform(new IfFalseNode(opt_ifisnan));
5696     set_control(iffalse);
5697 
5698     phi->init_req(2, _gvn.transform(new MoveD2LNode(arg)));
5699     r->init_req(2, iffalse);
5700 
5701     // Post merge
5702     set_control(_gvn.transform(r));
5703     record_for_igvn(r);
5704 
5705     C->set_has_split_ifs(true); // Has chance for split-if optimization
5706     result = phi;
5707     assert(result->bottom_type()->isa_long(), "must be");
5708     break;
5709   }
5710 
5711   case vmIntrinsics::_floatToIntBits: {
5712     // two paths (plus control) merge in a wood
5713     RegionNode *r = new RegionNode(3);
5714     Node *phi = new PhiNode(r, TypeInt::INT);
5715 
5716     Node *cmpisnan = _gvn.transform(new CmpFNode(arg, arg));
5717     // Build the boolean node
5718     Node *bolisnan = _gvn.transform(new BoolNode(cmpisnan, BoolTest::ne));
5719 
5720     // Branch either way.
5721     // NaN case is less traveled, which makes all the difference.
5722     IfNode *ifisnan = create_and_xform_if(control(), bolisnan, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
5723     Node *opt_isnan = _gvn.transform(ifisnan);
5724     assert( opt_isnan->is_If(), "Expect an IfNode");
5725     IfNode *opt_ifisnan = (IfNode*)opt_isnan;
5726     Node *iftrue = _gvn.transform(new IfTrueNode(opt_ifisnan));
5727 
5728     set_control(iftrue);
5729 
5730     static const jint nan_bits = 0x7fc00000;
5731     Node *slow_result = makecon(TypeInt::make(nan_bits)); // return NaN
5732     phi->init_req(1, _gvn.transform( slow_result ));
5733     r->init_req(1, iftrue);
5734 
5735     // Else fall through
5736     Node *iffalse = _gvn.transform(new IfFalseNode(opt_ifisnan));
5737     set_control(iffalse);
5738 
5739     phi->init_req(2, _gvn.transform(new MoveF2INode(arg)));
5740     r->init_req(2, iffalse);
5741 
5742     // Post merge
5743     set_control(_gvn.transform(r));
5744     record_for_igvn(r);
5745 
5746     C->set_has_split_ifs(true); // Has chance for split-if optimization
5747     result = phi;
5748     assert(result->bottom_type()->isa_int(), "must be");
5749     break;
5750   }
5751 
5752   default:
5753     fatal_unexpected_iid(id);
5754     break;
5755   }
5756   set_result(_gvn.transform(result));
5757   return true;
5758 }
5759 
5760 bool LibraryCallKit::inline_fp_range_check(vmIntrinsics::ID id) {
5761   Node* arg = argument(0);
5762   Node* result = nullptr;
5763 
5764   switch (id) {
5765   case vmIntrinsics::_floatIsInfinite:
5766     result = new IsInfiniteFNode(arg);
5767     break;
5768   case vmIntrinsics::_floatIsFinite:
5769     result = new IsFiniteFNode(arg);
5770     break;
5771   case vmIntrinsics::_doubleIsInfinite:
5772     result = new IsInfiniteDNode(arg);
5773     break;
5774   case vmIntrinsics::_doubleIsFinite:
5775     result = new IsFiniteDNode(arg);
5776     break;
5777   default:
5778     fatal_unexpected_iid(id);
5779     break;
5780   }
5781   set_result(_gvn.transform(result));
5782   return true;
5783 }
5784 
5785 //----------------------inline_unsafe_copyMemory-------------------------
5786 // public native void Unsafe.copyMemory0(Object srcBase, long srcOffset, Object destBase, long destOffset, long bytes);
5787 
5788 static bool has_wide_mem(PhaseGVN& gvn, Node* addr, Node* base) {
5789   const TypeAryPtr* addr_t = gvn.type(addr)->isa_aryptr();
5790   const Type*       base_t = gvn.type(base);
5791 
5792   bool in_native = (base_t == TypePtr::NULL_PTR);
5793   bool in_heap   = !TypePtr::NULL_PTR->higher_equal(base_t);
5794   bool is_mixed  = !in_heap && !in_native;
5795 
5796   if (is_mixed) {
5797     return true; // mixed accesses can touch both on-heap and off-heap memory
5798   }
5799   if (in_heap) {
5800     bool is_prim_array = (addr_t != nullptr) && (addr_t->elem() != Type::BOTTOM);
5801     if (!is_prim_array) {
5802       // Though Unsafe.copyMemory() ensures at runtime for on-heap accesses that base is a primitive array,
5803       // there's not enough type information available to determine proper memory slice for it.
5804       return true;
5805     }
5806   }
5807   return false;
5808 }
5809 
5810 bool LibraryCallKit::inline_unsafe_copyMemory() {
5811   if (callee()->is_static())  return false;  // caller must have the capability!
5812   null_check_receiver();  // null-check receiver
5813   if (stopped())  return true;
5814 
5815   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
5816 
5817   Node* src_base =         argument(1);  // type: oop
5818   Node* src_off  = ConvL2X(argument(2)); // type: long
5819   Node* dst_base =         argument(4);  // type: oop
5820   Node* dst_off  = ConvL2X(argument(5)); // type: long
5821   Node* size     = ConvL2X(argument(7)); // type: long
5822 
5823   assert(Unsafe_field_offset_to_byte_offset(11) == 11,
5824          "fieldOffset must be byte-scaled");
5825 
5826   Node* src_addr = make_unsafe_address(src_base, src_off);
5827   Node* dst_addr = make_unsafe_address(dst_base, dst_off);
5828 
5829   Node* thread = _gvn.transform(new ThreadLocalNode());
5830   Node* doing_unsafe_access_addr = off_heap_plus_addr(thread, in_bytes(JavaThread::doing_unsafe_access_offset()));
5831   BasicType doing_unsafe_access_bt = T_BYTE;
5832   assert((sizeof(bool) * CHAR_BIT) == 8, "not implemented");
5833 
5834   // update volatile field
5835   store_to_memory(control(), doing_unsafe_access_addr, intcon(1), doing_unsafe_access_bt, MemNode::unordered);
5836 
5837   int flags = RC_LEAF | RC_NO_FP;
5838 
5839   const TypePtr* dst_type = TypePtr::BOTTOM;
5840 
5841   // Adjust memory effects of the runtime call based on input values.
5842   if (!has_wide_mem(_gvn, src_addr, src_base) &&
5843       !has_wide_mem(_gvn, dst_addr, dst_base)) {
5844     dst_type = _gvn.type(dst_addr)->is_ptr(); // narrow out memory
5845 
5846     const TypePtr* src_type = _gvn.type(src_addr)->is_ptr();
5847     if (C->get_alias_index(src_type) == C->get_alias_index(dst_type)) {
5848       flags |= RC_NARROW_MEM; // narrow in memory
5849     }
5850   }
5851 
5852   // Call it.  Note that the length argument is not scaled.
5853   make_runtime_call(flags,
5854                     OptoRuntime::fast_arraycopy_Type(),
5855                     StubRoutines::unsafe_arraycopy(),
5856                     "unsafe_arraycopy",
5857                     dst_type,
5858                     src_addr, dst_addr, size XTOP);
5859 
5860   store_to_memory(control(), doing_unsafe_access_addr, intcon(0), doing_unsafe_access_bt, MemNode::unordered);
5861 
5862   return true;
5863 }
5864 
5865 // unsafe_setmemory(void *base, ulong offset, size_t length, char fill_value);
5866 // Fill 'length' bytes starting from 'base[offset]' with 'fill_value'
5867 bool LibraryCallKit::inline_unsafe_setMemory() {
5868   if (callee()->is_static())  return false;  // caller must have the capability!
5869   null_check_receiver();  // null-check receiver
5870   if (stopped())  return true;
5871 
5872   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
5873 
5874   Node* dst_base =         argument(1);  // type: oop
5875   Node* dst_off  = ConvL2X(argument(2)); // type: long
5876   Node* size     = ConvL2X(argument(4)); // type: long
5877   Node* byte     =         argument(6);  // type: byte
5878 
5879   assert(Unsafe_field_offset_to_byte_offset(11) == 11,
5880          "fieldOffset must be byte-scaled");
5881 
5882   Node* dst_addr = make_unsafe_address(dst_base, dst_off);
5883 
5884   Node* thread = _gvn.transform(new ThreadLocalNode());
5885   Node* doing_unsafe_access_addr = off_heap_plus_addr(thread, in_bytes(JavaThread::doing_unsafe_access_offset()));
5886   BasicType doing_unsafe_access_bt = T_BYTE;
5887   assert((sizeof(bool) * CHAR_BIT) == 8, "not implemented");
5888 
5889   // update volatile field
5890   store_to_memory(control(), doing_unsafe_access_addr, intcon(1), doing_unsafe_access_bt, MemNode::unordered);
5891 
5892   int flags = RC_LEAF | RC_NO_FP;
5893 
5894   const TypePtr* dst_type = TypePtr::BOTTOM;
5895 
5896   // Adjust memory effects of the runtime call based on input values.
5897   if (!has_wide_mem(_gvn, dst_addr, dst_base)) {
5898     dst_type = _gvn.type(dst_addr)->is_ptr(); // narrow out memory
5899 
5900     flags |= RC_NARROW_MEM; // narrow in memory
5901   }
5902 
5903   // Call it.  Note that the length argument is not scaled.
5904   make_runtime_call(flags,
5905                     OptoRuntime::unsafe_setmemory_Type(),
5906                     StubRoutines::unsafe_setmemory(),
5907                     "unsafe_setmemory",
5908                     dst_type,
5909                     dst_addr, size XTOP, byte);
5910 
5911   store_to_memory(control(), doing_unsafe_access_addr, intcon(0), doing_unsafe_access_bt, MemNode::unordered);
5912 
5913   return true;
5914 }
5915 
5916 #undef XTOP
5917 
5918 //------------------------clone_coping-----------------------------------
5919 // Helper function for inline_native_clone.
5920 void LibraryCallKit::copy_to_clone(Node* obj, Node* alloc_obj, Node* obj_size, bool is_array) {
5921   assert(obj_size != nullptr, "");
5922   Node* raw_obj = alloc_obj->in(1);
5923   assert(alloc_obj->is_CheckCastPP() && raw_obj->is_Proj() && raw_obj->in(0)->is_Allocate(), "");
5924 
5925   AllocateNode* alloc = nullptr;
5926   if (ReduceBulkZeroing &&
5927       // If we are implementing an array clone without knowing its source type
5928       // (can happen when compiling the array-guarded branch of a reflective
5929       // Object.clone() invocation), initialize the array within the allocation.
5930       // This is needed because some GCs (e.g. ZGC) might fall back in this case
5931       // to a runtime clone call that assumes fully initialized source arrays.
5932       (!is_array || obj->get_ptr_type()->isa_aryptr() != nullptr)) {
5933     // We will be completely responsible for initializing this object -
5934     // mark Initialize node as complete.
5935     alloc = AllocateNode::Ideal_allocation(alloc_obj);
5936     // The object was just allocated - there should be no any stores!
5937     guarantee(alloc != nullptr && alloc->maybe_set_complete(&_gvn), "");
5938     // Mark as complete_with_arraycopy so that on AllocateNode
5939     // expansion, we know this AllocateNode is initialized by an array
5940     // copy and a StoreStore barrier exists after the array copy.
5941     alloc->initialization()->set_complete_with_arraycopy();
5942   }
5943 
5944   Node* size = _gvn.transform(obj_size);
5945   access_clone(obj, alloc_obj, size, is_array);
5946 
5947   // Do not let reads from the cloned object float above the arraycopy.
5948   if (alloc != nullptr) {
5949     // Do not let stores that initialize this object be reordered with
5950     // a subsequent store that would make this object accessible by
5951     // other threads.
5952     // Record what AllocateNode this StoreStore protects so that
5953     // escape analysis can go from the MemBarStoreStoreNode to the
5954     // AllocateNode and eliminate the MemBarStoreStoreNode if possible
5955     // based on the escape status of the AllocateNode.
5956     insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
5957   } else {
5958     insert_mem_bar(Op_MemBarCPUOrder);
5959   }
5960 }
5961 
5962 //------------------------inline_native_clone----------------------------
5963 // protected native Object java.lang.Object.clone();
5964 //
5965 // Here are the simple edge cases:
5966 //  null receiver => normal trap
5967 //  virtual and clone was overridden => slow path to out-of-line clone
5968 //  not cloneable or finalizer => slow path to out-of-line Object.clone
5969 //
5970 // The general case has two steps, allocation and copying.
5971 // Allocation has two cases, and uses GraphKit::new_instance or new_array.
5972 //
5973 // Copying also has two cases, oop arrays and everything else.
5974 // Oop arrays use arrayof_oop_arraycopy (same as System.arraycopy).
5975 // Everything else uses the tight inline loop supplied by CopyArrayNode.
5976 //
5977 // These steps fold up nicely if and when the cloned object's klass
5978 // can be sharply typed as an object array, a type array, or an instance.
5979 //
5980 bool LibraryCallKit::inline_native_clone(bool is_virtual) {
5981   PhiNode* result_val;
5982 
5983   // Set the reexecute bit for the interpreter to reexecute
5984   // the bytecode that invokes Object.clone if deoptimization happens.
5985   { PreserveReexecuteState preexecs(this);
5986     jvms()->set_should_reexecute(true);
5987 
5988     Node* obj = argument(0);
5989     obj = null_check_receiver();
5990     if (stopped())  return true;
5991 
5992     const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
5993     if (obj_type->is_inlinetypeptr()) {
5994       // If the object to clone is an inline type, we can simply return it (i.e. a nop) since inline types have
5995       // no identity.
5996       set_result(obj);
5997       return true;
5998     }
5999 
6000     // If we are going to clone an instance, we need its exact type to
6001     // know the number and types of fields to convert the clone to
6002     // loads/stores. Maybe a speculative type can help us.
6003     if (!obj_type->klass_is_exact() &&
6004         obj_type->speculative_type() != nullptr &&
6005         obj_type->speculative_type()->is_instance_klass() &&
6006         !obj_type->speculative_type()->is_inlinetype()) {
6007       ciInstanceKlass* spec_ik = obj_type->speculative_type()->as_instance_klass();
6008       if (spec_ik->nof_nonstatic_fields() <= ArrayCopyLoadStoreMaxElem &&
6009           !spec_ik->has_injected_fields()) {
6010         if (!obj_type->isa_instptr() ||
6011             obj_type->is_instptr()->instance_klass()->has_subklass()) {
6012           obj = maybe_cast_profiled_obj(obj, obj_type->speculative_type(), false);
6013         }
6014       }
6015     }
6016 
6017     // Conservatively insert a memory barrier on all memory slices.
6018     // Do not let writes into the original float below the clone.
6019     insert_mem_bar(Op_MemBarCPUOrder);
6020 
6021     // paths into result_reg:
6022     enum {
6023       _slow_path = 1,     // out-of-line call to clone method (virtual or not)
6024       _objArray_path,     // plain array allocation, plus arrayof_oop_arraycopy
6025       _array_path,        // plain array allocation, plus arrayof_long_arraycopy
6026       _instance_path,     // plain instance allocation, plus arrayof_long_arraycopy
6027       PATH_LIMIT
6028     };
6029     RegionNode* result_reg = new RegionNode(PATH_LIMIT);
6030     result_val             = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
6031     PhiNode*    result_i_o = new PhiNode(result_reg, Type::ABIO);
6032     PhiNode*    result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
6033     record_for_igvn(result_reg);
6034 
6035     Node* obj_klass = load_object_klass(obj);
6036     // We only go to the fast case code if we pass a number of guards.
6037     // The paths which do not pass are accumulated in the slow_region.
6038     RegionNode* slow_region = new RegionNode(1);
6039     record_for_igvn(slow_region);
6040 
6041     Node* array_obj = obj;
6042     Node* array_ctl = generate_array_guard(obj_klass, (RegionNode*)nullptr, &array_obj);
6043     if (array_ctl != nullptr) {
6044       // It's an array.
6045       PreserveJVMState pjvms(this);
6046       set_control(array_ctl);
6047 
6048       BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
6049       const TypeAryPtr* ary_ptr = obj_type->isa_aryptr();
6050       if (UseArrayFlattening && bs->array_copy_requires_gc_barriers(true, T_OBJECT, true, false, BarrierSetC2::Expansion) &&
6051           obj_type->can_be_inline_array() &&
6052           (ary_ptr == nullptr || (!ary_ptr->is_not_flat() && (!ary_ptr->is_flat() || ary_ptr->elem()->inline_klass()->contains_oops())))) {
6053         // Flat inline type array may have object field that would require a
6054         // write barrier. Conservatively, go to slow path.
6055         generate_fair_guard(flat_array_test(obj_klass), slow_region);
6056       }
6057 
6058       if (!stopped()) {
6059         Node* obj_length = load_array_length(array_obj);
6060         Node* array_size = nullptr; // Size of the array without object alignment padding.
6061         Node* alloc_obj = new_array(obj_klass, obj_length, 0, &array_size, /*deoptimize_on_exception=*/true);
6062 
6063         BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
6064         if (bs->array_copy_requires_gc_barriers(true, T_OBJECT, true, false, BarrierSetC2::Parsing)) {
6065           // If it is an oop array, it requires very special treatment,
6066           // because gc barriers are required when accessing the array.
6067           Node* is_obja = generate_refArray_guard(obj_klass, (RegionNode*)nullptr);
6068           if (is_obja != nullptr) {
6069             PreserveJVMState pjvms2(this);
6070             set_control(is_obja);
6071             // Generate a direct call to the right arraycopy function(s).
6072             // Clones are always tightly coupled.
6073             ArrayCopyNode* ac = ArrayCopyNode::make(this, true, array_obj, intcon(0), alloc_obj, intcon(0), obj_length, true, false);
6074             ac->set_clone_oop_array();
6075             Node* n = _gvn.transform(ac);
6076             assert(n == ac, "cannot disappear");
6077             ac->connect_outputs(this, /*deoptimize_on_exception=*/true);
6078 
6079             result_reg->init_req(_objArray_path, control());
6080             result_val->init_req(_objArray_path, alloc_obj);
6081             result_i_o ->set_req(_objArray_path, i_o());
6082             result_mem ->set_req(_objArray_path, reset_memory());
6083           }
6084         }
6085         // Otherwise, there are no barriers to worry about.
6086         // (We can dispense with card marks if we know the allocation
6087         //  comes out of eden (TLAB)...  In fact, ReduceInitialCardMarks
6088         //  causes the non-eden paths to take compensating steps to
6089         //  simulate a fresh allocation, so that no further
6090         //  card marks are required in compiled code to initialize
6091         //  the object.)
6092 
6093         if (!stopped()) {
6094           copy_to_clone(obj, alloc_obj, array_size, true);
6095 
6096           // Present the results of the copy.
6097           result_reg->init_req(_array_path, control());
6098           result_val->init_req(_array_path, alloc_obj);
6099           result_i_o ->set_req(_array_path, i_o());
6100           result_mem ->set_req(_array_path, reset_memory());
6101         }
6102       }
6103     }
6104 
6105     if (!stopped()) {
6106       // It's an instance (we did array above).  Make the slow-path tests.
6107       // If this is a virtual call, we generate a funny guard.  We grab
6108       // the vtable entry corresponding to clone() from the target object.
6109       // If the target method which we are calling happens to be the
6110       // Object clone() method, we pass the guard.  We do not need this
6111       // guard for non-virtual calls; the caller is known to be the native
6112       // Object clone().
6113       if (is_virtual) {
6114         generate_virtual_guard(obj_klass, slow_region);
6115       }
6116 
6117       // The object must be easily cloneable and must not have a finalizer.
6118       // Both of these conditions may be checked in a single test.
6119       // We could optimize the test further, but we don't care.
6120       generate_misc_flags_guard(obj_klass,
6121                                 // Test both conditions:
6122                                 KlassFlags::_misc_is_cloneable_fast | KlassFlags::_misc_has_finalizer,
6123                                 // Must be cloneable but not finalizer:
6124                                 KlassFlags::_misc_is_cloneable_fast,
6125                                 slow_region);
6126     }
6127 
6128     if (!stopped()) {
6129       // It's an instance, and it passed the slow-path tests.
6130       PreserveJVMState pjvms(this);
6131       Node* obj_size = nullptr; // Total object size, including object alignment padding.
6132       // Need to deoptimize on exception from allocation since Object.clone intrinsic
6133       // is reexecuted if deoptimization occurs and there could be problems when merging
6134       // exception state between multiple Object.clone versions (reexecute=true vs reexecute=false).
6135       Node* alloc_obj = new_instance(obj_klass, nullptr, &obj_size, /*deoptimize_on_exception=*/true);
6136 
6137       copy_to_clone(obj, alloc_obj, obj_size, false);
6138 
6139       // Present the results of the slow call.
6140       result_reg->init_req(_instance_path, control());
6141       result_val->init_req(_instance_path, alloc_obj);
6142       result_i_o ->set_req(_instance_path, i_o());
6143       result_mem ->set_req(_instance_path, reset_memory());
6144     }
6145 
6146     // Generate code for the slow case.  We make a call to clone().
6147     set_control(_gvn.transform(slow_region));
6148     if (!stopped()) {
6149       PreserveJVMState pjvms(this);
6150       CallJavaNode* slow_call = generate_method_call(vmIntrinsics::_clone, is_virtual, false, true);
6151       // We need to deoptimize on exception (see comment above)
6152       Node* slow_result = set_results_for_java_call(slow_call, false, /* deoptimize */ true);
6153       // this->control() comes from set_results_for_java_call
6154       result_reg->init_req(_slow_path, control());
6155       result_val->init_req(_slow_path, slow_result);
6156       result_i_o ->set_req(_slow_path, i_o());
6157       result_mem ->set_req(_slow_path, reset_memory());
6158     }
6159 
6160     // Return the combined state.
6161     set_control(    _gvn.transform(result_reg));
6162     set_i_o(        _gvn.transform(result_i_o));
6163     set_all_memory( _gvn.transform(result_mem));
6164   } // original reexecute is set back here
6165 
6166   set_result(_gvn.transform(result_val));
6167   return true;
6168 }
6169 
6170 // If we have a tightly coupled allocation, the arraycopy may take care
6171 // of the array initialization. If one of the guards we insert between
6172 // the allocation and the arraycopy causes a deoptimization, an
6173 // uninitialized array will escape the compiled method. To prevent that
6174 // we set the JVM state for uncommon traps between the allocation and
6175 // the arraycopy to the state before the allocation so, in case of
6176 // deoptimization, we'll reexecute the allocation and the
6177 // initialization.
6178 JVMState* LibraryCallKit::arraycopy_restore_alloc_state(AllocateArrayNode* alloc, int& saved_reexecute_sp) {
6179   if (alloc != nullptr) {
6180     ciMethod* trap_method = alloc->jvms()->method();
6181     int trap_bci = alloc->jvms()->bci();
6182 
6183     if (!C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_intrinsic) &&
6184         !C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_null_check)) {
6185       // Make sure there's no store between the allocation and the
6186       // arraycopy otherwise visible side effects could be rexecuted
6187       // in case of deoptimization and cause incorrect execution.
6188       bool no_interfering_store = true;
6189       Node* mem = alloc->in(TypeFunc::Memory);
6190       if (mem->is_MergeMem()) {
6191         for (MergeMemStream mms(merged_memory(), mem->as_MergeMem()); mms.next_non_empty2(); ) {
6192           Node* n = mms.memory();
6193           if (n != mms.memory2() && !(n->is_Proj() && n->in(0) == alloc->initialization())) {
6194             assert(n->is_Store(), "what else?");
6195             no_interfering_store = false;
6196             break;
6197           }
6198         }
6199       } else {
6200         for (MergeMemStream mms(merged_memory()); mms.next_non_empty(); ) {
6201           Node* n = mms.memory();
6202           if (n != mem && !(n->is_Proj() && n->in(0) == alloc->initialization())) {
6203             assert(n->is_Store(), "what else?");
6204             no_interfering_store = false;
6205             break;
6206           }
6207         }
6208       }
6209 
6210       if (no_interfering_store) {
6211         SafePointNode* sfpt = create_safepoint_with_state_before_array_allocation(alloc);
6212 
6213         JVMState* saved_jvms = jvms();
6214         saved_reexecute_sp = _reexecute_sp;
6215 
6216         set_jvms(sfpt->jvms());
6217         _reexecute_sp = jvms()->sp();
6218 
6219         return saved_jvms;
6220       }
6221     }
6222   }
6223   return nullptr;
6224 }
6225 
6226 // Clone the JVMState of the array allocation and create a new safepoint with it. Re-push the array length to the stack
6227 // such that uncommon traps can be emitted to re-execute the array allocation in the interpreter.
6228 SafePointNode* LibraryCallKit::create_safepoint_with_state_before_array_allocation(const AllocateArrayNode* alloc) const {
6229   JVMState* old_jvms = alloc->jvms()->clone_shallow(C);
6230   uint size = alloc->req();
6231   SafePointNode* sfpt = new SafePointNode(size, old_jvms);
6232   old_jvms->set_map(sfpt);
6233   for (uint i = 0; i < size; i++) {
6234     sfpt->init_req(i, alloc->in(i));
6235   }
6236   int adjustment = 1;
6237   const TypeAryKlassPtr* ary_klass_ptr = alloc->in(AllocateNode::KlassNode)->bottom_type()->is_aryklassptr();
6238   if (ary_klass_ptr->is_null_free()) {
6239     // A null-free, tightly coupled array allocation can only come from LibraryCallKit::inline_newArray which
6240     // also requires the componentType and initVal on stack for re-execution.
6241     // Re-create and push the componentType.
6242     ciArrayKlass* klass = ary_klass_ptr->exact_klass()->as_array_klass();
6243     ciInstance* instance = klass->component_mirror_instance();
6244     const TypeInstPtr* t_instance = TypeInstPtr::make(instance);
6245     sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp(), makecon(t_instance));
6246     adjustment++;
6247   }
6248   // re-push array length for deoptimization
6249   sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp() + adjustment - 1, alloc->in(AllocateNode::ALength));
6250   if (ary_klass_ptr->is_null_free()) {
6251     // Re-create and push the initVal.
6252     Node* init_val = alloc->in(AllocateNode::InitValue);
6253     if (init_val == nullptr) {
6254       init_val = InlineTypeNode::make_all_zero(_gvn, ary_klass_ptr->elem()->is_instklassptr()->instance_klass()->as_inline_klass());
6255     } else if (UseCompressedOops) {
6256       init_val = _gvn.transform(new DecodeNNode(init_val, init_val->bottom_type()->make_ptr()));
6257     }
6258     sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp() + adjustment, init_val);
6259     adjustment++;
6260   }
6261   old_jvms->set_sp(old_jvms->sp() + adjustment);
6262   old_jvms->set_monoff(old_jvms->monoff() + adjustment);
6263   old_jvms->set_scloff(old_jvms->scloff() + adjustment);
6264   old_jvms->set_endoff(old_jvms->endoff() + adjustment);
6265   old_jvms->set_should_reexecute(true);
6266 
6267   sfpt->set_i_o(map()->i_o());
6268   sfpt->set_memory(map()->memory());
6269   sfpt->set_control(map()->control());
6270   return sfpt;
6271 }
6272 
6273 // In case of a deoptimization, we restart execution at the
6274 // allocation, allocating a new array. We would leave an uninitialized
6275 // array in the heap that GCs wouldn't expect. Move the allocation
6276 // after the traps so we don't allocate the array if we
6277 // deoptimize. This is possible because tightly_coupled_allocation()
6278 // guarantees there's no observer of the allocated array at this point
6279 // and the control flow is simple enough.
6280 void LibraryCallKit::arraycopy_move_allocation_here(AllocateArrayNode* alloc, Node* dest, JVMState* saved_jvms_before_guards,
6281                                                     int saved_reexecute_sp, uint new_idx) {
6282   if (saved_jvms_before_guards != nullptr && !stopped()) {
6283     replace_unrelated_uncommon_traps_with_alloc_state(alloc, saved_jvms_before_guards);
6284 
6285     assert(alloc != nullptr, "only with a tightly coupled allocation");
6286     // restore JVM state to the state at the arraycopy
6287     saved_jvms_before_guards->map()->set_control(map()->control());
6288     assert(saved_jvms_before_guards->map()->memory() == map()->memory(), "memory state changed?");
6289     assert(saved_jvms_before_guards->map()->i_o() == map()->i_o(), "IO state changed?");
6290     // If we've improved the types of some nodes (null check) while
6291     // emitting the guards, propagate them to the current state
6292     map()->replaced_nodes().apply(saved_jvms_before_guards->map(), new_idx);
6293     set_jvms(saved_jvms_before_guards);
6294     _reexecute_sp = saved_reexecute_sp;
6295 
6296     // Remove the allocation from above the guards
6297     CallProjections* callprojs = alloc->extract_projections(true);
6298     InitializeNode* init = alloc->initialization();
6299     Node* alloc_mem = alloc->in(TypeFunc::Memory);
6300     C->gvn_replace_by(callprojs->fallthrough_ioproj, alloc->in(TypeFunc::I_O));
6301     init->replace_mem_projs_by(alloc_mem, C);
6302 
6303     // The CastIINode created in GraphKit::new_array (in AllocateArrayNode::make_ideal_length) must stay below
6304     // the allocation (i.e. is only valid if the allocation succeeds):
6305     // 1) replace CastIINode with AllocateArrayNode's length here
6306     // 2) Create CastIINode again once allocation has moved (see below) at the end of this method
6307     //
6308     // Multiple identical CastIINodes might exist here. Each GraphKit::load_array_length() call will generate
6309     // new separate CastIINode (arraycopy guard checks or any array length use between array allocation and ararycopy)
6310     Node* init_control = init->proj_out(TypeFunc::Control);
6311     Node* alloc_length = alloc->Ideal_length();
6312 #ifdef ASSERT
6313     Node* prev_cast = nullptr;
6314 #endif
6315     for (uint i = 0; i < init_control->outcnt(); i++) {
6316       Node* init_out = init_control->raw_out(i);
6317       if (init_out->is_CastII() && init_out->in(TypeFunc::Control) == init_control && init_out->in(1) == alloc_length) {
6318 #ifdef ASSERT
6319         if (prev_cast == nullptr) {
6320           prev_cast = init_out;
6321         } else {
6322           if (prev_cast->cmp(*init_out) == false) {
6323             prev_cast->dump();
6324             init_out->dump();
6325             assert(false, "not equal CastIINode");
6326           }
6327         }
6328 #endif
6329         C->gvn_replace_by(init_out, alloc_length);
6330       }
6331     }
6332     C->gvn_replace_by(init->proj_out(TypeFunc::Control), alloc->in(0));
6333 
6334     // move the allocation here (after the guards)
6335     _gvn.hash_delete(alloc);
6336     alloc->set_req(TypeFunc::Control, control());
6337     alloc->set_req(TypeFunc::I_O, i_o());
6338     Node *mem = reset_memory();
6339     set_all_memory(mem);
6340     alloc->set_req(TypeFunc::Memory, mem);
6341     set_control(init->proj_out_or_null(TypeFunc::Control));
6342     set_i_o(callprojs->fallthrough_ioproj);
6343 
6344     // Update memory as done in GraphKit::set_output_for_allocation()
6345     const TypeInt* length_type = _gvn.find_int_type(alloc->in(AllocateNode::ALength));
6346     const TypeOopPtr* ary_type = _gvn.type(alloc->in(AllocateNode::KlassNode))->is_klassptr()->as_instance_type();
6347     if (ary_type->isa_aryptr() && length_type != nullptr) {
6348       ary_type = ary_type->is_aryptr()->cast_to_size(length_type);
6349     }
6350     const TypePtr* telemref = ary_type->add_offset(Type::OffsetBot);
6351     int            elemidx  = C->get_alias_index(telemref);
6352     // Need to properly move every memory projection for the Initialize
6353 #ifdef ASSERT
6354     int mark_idx = C->get_alias_index(ary_type->add_offset(oopDesc::mark_offset_in_bytes()));
6355     int klass_idx = C->get_alias_index(ary_type->add_offset(oopDesc::klass_offset_in_bytes()));
6356 #endif
6357     auto move_proj = [&](ProjNode* proj) {
6358       int alias_idx = C->get_alias_index(proj->adr_type());
6359       assert(alias_idx == Compile::AliasIdxRaw ||
6360              alias_idx == elemidx ||
6361              alias_idx == mark_idx ||
6362              alias_idx == klass_idx, "should be raw memory or array element type");
6363       set_memory(proj, alias_idx);
6364     };
6365     init->for_each_proj(move_proj, TypeFunc::Memory);
6366 
6367     Node* allocx = _gvn.transform(alloc);
6368     assert(allocx == alloc, "where has the allocation gone?");
6369     assert(dest->is_CheckCastPP(), "not an allocation result?");
6370 
6371     _gvn.hash_delete(dest);
6372     dest->set_req(0, control());
6373     Node* destx = _gvn.transform(dest);
6374     assert(destx == dest, "where has the allocation result gone?");
6375 
6376     array_ideal_length(alloc, ary_type, true);
6377   }
6378 }
6379 
6380 // Unrelated UCTs between the array allocation and the array copy, which are considered safe by tightly_coupled_allocation(),
6381 // need to be replaced by an UCT with a state before the array allocation (including the array length). This is necessary
6382 // because we could hit one of these UCTs (which are executed before the emitted array copy guards and the actual array
6383 // allocation which is moved down in arraycopy_move_allocation_here()). When later resuming execution in the interpreter,
6384 // we would have wrongly skipped the array allocation. To prevent this, we resume execution at the array allocation in
6385 // the interpreter similar to what we are doing for the newly emitted guards for the array copy.
6386 void LibraryCallKit::replace_unrelated_uncommon_traps_with_alloc_state(AllocateArrayNode* alloc,
6387                                                                        JVMState* saved_jvms_before_guards) {
6388   if (saved_jvms_before_guards->map()->control()->is_IfProj()) {
6389     // There is at least one unrelated uncommon trap which needs to be replaced.
6390     SafePointNode* sfpt = create_safepoint_with_state_before_array_allocation(alloc);
6391 
6392     JVMState* saved_jvms = jvms();
6393     const int saved_reexecute_sp = _reexecute_sp;
6394     set_jvms(sfpt->jvms());
6395     _reexecute_sp = jvms()->sp();
6396 
6397     replace_unrelated_uncommon_traps_with_alloc_state(saved_jvms_before_guards);
6398 
6399     // Restore state
6400     set_jvms(saved_jvms);
6401     _reexecute_sp = saved_reexecute_sp;
6402   }
6403 }
6404 
6405 // Replace the unrelated uncommon traps with new uncommon trap nodes by reusing the action and reason. The new uncommon
6406 // traps will have the state of the array allocation. Let the old uncommon trap nodes die.
6407 void LibraryCallKit::replace_unrelated_uncommon_traps_with_alloc_state(JVMState* saved_jvms_before_guards) {
6408   Node* if_proj = saved_jvms_before_guards->map()->control(); // Start the search right before the newly emitted guards
6409   while (if_proj->is_IfProj()) {
6410     CallStaticJavaNode* uncommon_trap = get_uncommon_trap_from_success_proj(if_proj);
6411     if (uncommon_trap != nullptr) {
6412       create_new_uncommon_trap(uncommon_trap);
6413     }
6414     assert(if_proj->in(0)->is_If(), "must be If");
6415     if_proj = if_proj->in(0)->in(0);
6416   }
6417   assert(if_proj->is_Proj() && if_proj->in(0)->is_Initialize(),
6418          "must have reached control projection of init node");
6419 }
6420 
6421 void LibraryCallKit::create_new_uncommon_trap(CallStaticJavaNode* uncommon_trap_call) {
6422   const int trap_request = uncommon_trap_call->uncommon_trap_request();
6423   assert(trap_request != 0, "no valid UCT trap request");
6424   PreserveJVMState pjvms(this);
6425   set_control(uncommon_trap_call->in(0));
6426   uncommon_trap(Deoptimization::trap_request_reason(trap_request),
6427                 Deoptimization::trap_request_action(trap_request));
6428   assert(stopped(), "Should be stopped");
6429   _gvn.hash_delete(uncommon_trap_call);
6430   uncommon_trap_call->set_req(0, top()); // not used anymore, kill it
6431 }
6432 
6433 // Common checks for array sorting intrinsics arguments.
6434 // Returns `true` if checks passed.
6435 bool LibraryCallKit::check_array_sort_arguments(Node* elementType, Node* obj, BasicType& bt) {
6436   // check address of the class
6437   if (elementType == nullptr || elementType->is_top()) {
6438     return false;  // dead path
6439   }
6440   const TypeInstPtr* elem_klass = gvn().type(elementType)->isa_instptr();
6441   if (elem_klass == nullptr) {
6442     return false;  // dead path
6443   }
6444   // java_mirror_type() returns non-null for compile-time Class constants only
6445   ciType* elem_type = elem_klass->java_mirror_type();
6446   if (elem_type == nullptr) {
6447     return false;
6448   }
6449   bt = elem_type->basic_type();
6450   // Disable the intrinsic if the CPU does not support SIMD sort
6451   if (!Matcher::supports_simd_sort(bt)) {
6452     return false;
6453   }
6454   // check address of the array
6455   if (obj == nullptr || obj->is_top()) {
6456     return false;  // dead path
6457   }
6458   const TypeAryPtr* obj_t = _gvn.type(obj)->isa_aryptr();
6459   if (obj_t == nullptr || obj_t->elem() == Type::BOTTOM) {
6460     return false; // failed input validation
6461   }
6462   return true;
6463 }
6464 
6465 //------------------------------inline_array_partition-----------------------
6466 bool LibraryCallKit::inline_array_partition() {
6467   address stubAddr = StubRoutines::select_array_partition_function();
6468   if (stubAddr == nullptr) {
6469     return false; // Intrinsic's stub is not implemented on this platform
6470   }
6471   assert(callee()->signature()->size() == 9, "arrayPartition has 8 parameters (one long)");
6472 
6473   // no receiver because it is a static method
6474   Node* elementType     = argument(0);
6475   Node* obj             = argument(1);
6476   Node* offset          = argument(2); // long
6477   Node* fromIndex       = argument(4);
6478   Node* toIndex         = argument(5);
6479   Node* indexPivot1     = argument(6);
6480   Node* indexPivot2     = argument(7);
6481   // PartitionOperation:  argument(8) is ignored
6482 
6483   Node* pivotIndices = nullptr;
6484   BasicType bt = T_ILLEGAL;
6485 
6486   if (!check_array_sort_arguments(elementType, obj, bt)) {
6487     return false;
6488   }
6489   null_check(obj);
6490   // If obj is dead, only null-path is taken.
6491   if (stopped()) {
6492     return true;
6493   }
6494   // Set the original stack and the reexecute bit for the interpreter to reexecute
6495   // the bytecode that invokes DualPivotQuicksort.partition() if deoptimization happens.
6496   { PreserveReexecuteState preexecs(this);
6497     jvms()->set_should_reexecute(true);
6498 
6499     Node* obj_adr = make_unsafe_address(obj, offset);
6500 
6501     // create the pivotIndices array of type int and size = 2
6502     Node* size = intcon(2);
6503     Node* klass_node = makecon(TypeKlassPtr::make(ciTypeArrayKlass::make(T_INT)));
6504     pivotIndices = new_array(klass_node, size, 0);  // no arguments to push
6505     AllocateArrayNode* alloc = tightly_coupled_allocation(pivotIndices);
6506     guarantee(alloc != nullptr, "created above");
6507     Node* pivotIndices_adr = basic_plus_adr(pivotIndices, arrayOopDesc::base_offset_in_bytes(T_INT));
6508 
6509     // pass the basic type enum to the stub
6510     Node* elemType = intcon(bt);
6511 
6512     // Call the stub
6513     const char *stubName = "array_partition_stub";
6514     make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::array_partition_Type(),
6515                       stubAddr, stubName, TypePtr::BOTTOM,
6516                       obj_adr, elemType, fromIndex, toIndex, pivotIndices_adr,
6517                       indexPivot1, indexPivot2);
6518 
6519   } // original reexecute is set back here
6520 
6521   if (!stopped()) {
6522     set_result(pivotIndices);
6523   }
6524 
6525   return true;
6526 }
6527 
6528 
6529 //------------------------------inline_array_sort-----------------------
6530 bool LibraryCallKit::inline_array_sort() {
6531   address stubAddr = StubRoutines::select_arraysort_function();
6532   if (stubAddr == nullptr) {
6533     return false; // Intrinsic's stub is not implemented on this platform
6534   }
6535   assert(callee()->signature()->size() == 7, "arraySort has 6 parameters (one long)");
6536 
6537   // no receiver because it is a static method
6538   Node* elementType     = argument(0);
6539   Node* obj             = argument(1);
6540   Node* offset          = argument(2); // long
6541   Node* fromIndex       = argument(4);
6542   Node* toIndex         = argument(5);
6543   // SortOperation:       argument(6) is ignored
6544 
6545   BasicType bt = T_ILLEGAL;
6546 
6547   if (!check_array_sort_arguments(elementType, obj, bt)) {
6548     return false;
6549   }
6550   null_check(obj);
6551   // If obj is dead, only null-path is taken.
6552   if (stopped()) {
6553     return true;
6554   }
6555   Node* obj_adr = make_unsafe_address(obj, offset);
6556 
6557   // pass the basic type enum to the stub
6558   Node* elemType = intcon(bt);
6559 
6560   // Call the stub.
6561   const char *stubName = "arraysort_stub";
6562   make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::array_sort_Type(),
6563                     stubAddr, stubName, TypePtr::BOTTOM,
6564                     obj_adr, elemType, fromIndex, toIndex);
6565 
6566   return true;
6567 }
6568 
6569 
6570 //------------------------------inline_arraycopy-----------------------
6571 // public static native void java.lang.System.arraycopy(Object src,  int  srcPos,
6572 //                                                      Object dest, int destPos,
6573 //                                                      int length);
6574 bool LibraryCallKit::inline_arraycopy() {
6575   // Get the arguments.
6576   Node* src         = argument(0);  // type: oop
6577   Node* src_offset  = argument(1);  // type: int
6578   Node* dest        = argument(2);  // type: oop
6579   Node* dest_offset = argument(3);  // type: int
6580   Node* length      = argument(4);  // type: int
6581 
6582   uint new_idx = C->unique();
6583 
6584   // Check for allocation before we add nodes that would confuse
6585   // tightly_coupled_allocation()
6586   AllocateArrayNode* alloc = tightly_coupled_allocation(dest);
6587 
6588   int saved_reexecute_sp = -1;
6589   JVMState* saved_jvms_before_guards = arraycopy_restore_alloc_state(alloc, saved_reexecute_sp);
6590   // See arraycopy_restore_alloc_state() comment
6591   // if alloc == null we don't have to worry about a tightly coupled allocation so we can emit all needed guards
6592   // if saved_jvms_before_guards is not null (then alloc is not null) then we can handle guards and a tightly coupled allocation
6593   // if saved_jvms_before_guards is null and alloc is not null, we can't emit any guards
6594   bool can_emit_guards = (alloc == nullptr || saved_jvms_before_guards != nullptr);
6595 
6596   // The following tests must be performed
6597   // (1) src and dest are arrays.
6598   // (2) src and dest arrays must have elements of the same BasicType
6599   // (3) src and dest must not be null.
6600   // (4) src_offset must not be negative.
6601   // (5) dest_offset must not be negative.
6602   // (6) length must not be negative.
6603   // (7) src_offset + length must not exceed length of src.
6604   // (8) dest_offset + length must not exceed length of dest.
6605   // (9) each element of an oop array must be assignable
6606 
6607   // (3) src and dest must not be null.
6608   // always do this here because we need the JVM state for uncommon traps
6609   Node* null_ctl = top();
6610   src  = saved_jvms_before_guards != nullptr ? null_check_oop(src, &null_ctl, true, true) : null_check(src, T_ARRAY);
6611   assert(null_ctl->is_top(), "no null control here");
6612   dest = null_check(dest, T_ARRAY);
6613 
6614   if (!can_emit_guards) {
6615     // if saved_jvms_before_guards is null and alloc is not null, we don't emit any
6616     // guards but the arraycopy node could still take advantage of a
6617     // tightly allocated allocation. tightly_coupled_allocation() is
6618     // called again to make sure it takes the null check above into
6619     // account: the null check is mandatory and if it caused an
6620     // uncommon trap to be emitted then the allocation can't be
6621     // considered tightly coupled in this context.
6622     alloc = tightly_coupled_allocation(dest);
6623   }
6624 
6625   bool validated = false;
6626 
6627   const Type* src_type  = _gvn.type(src);
6628   const Type* dest_type = _gvn.type(dest);
6629   const TypeAryPtr* top_src  = src_type->isa_aryptr();
6630   const TypeAryPtr* top_dest = dest_type->isa_aryptr();
6631 
6632   // Do we have the type of src?
6633   bool has_src = (top_src != nullptr && top_src->elem() != Type::BOTTOM);
6634   // Do we have the type of dest?
6635   bool has_dest = (top_dest != nullptr && top_dest->elem() != Type::BOTTOM);
6636   // Is the type for src from speculation?
6637   bool src_spec = false;
6638   // Is the type for dest from speculation?
6639   bool dest_spec = false;
6640 
6641   if ((!has_src || !has_dest) && can_emit_guards) {
6642     // We don't have sufficient type information, let's see if
6643     // speculative types can help. We need to have types for both src
6644     // and dest so that it pays off.
6645 
6646     // Do we already have or could we have type information for src
6647     bool could_have_src = has_src;
6648     // Do we already have or could we have type information for dest
6649     bool could_have_dest = has_dest;
6650 
6651     ciKlass* src_k = nullptr;
6652     if (!has_src) {
6653       src_k = src_type->speculative_type_not_null();
6654       if (src_k != nullptr && src_k->is_array_klass()) {
6655         could_have_src = true;
6656       }
6657     }
6658 
6659     ciKlass* dest_k = nullptr;
6660     if (!has_dest) {
6661       dest_k = dest_type->speculative_type_not_null();
6662       if (dest_k != nullptr && dest_k->is_array_klass()) {
6663         could_have_dest = true;
6664       }
6665     }
6666 
6667     if (could_have_src && could_have_dest) {
6668       // This is going to pay off so emit the required guards
6669       if (!has_src) {
6670         src = maybe_cast_profiled_obj(src, src_k, true);
6671         src_type  = _gvn.type(src);
6672         top_src  = src_type->isa_aryptr();
6673         has_src = (top_src != nullptr && top_src->elem() != Type::BOTTOM);
6674         src_spec = true;
6675       }
6676       if (!has_dest) {
6677         dest = maybe_cast_profiled_obj(dest, dest_k, true);
6678         dest_type  = _gvn.type(dest);
6679         top_dest  = dest_type->isa_aryptr();
6680         has_dest = (top_dest != nullptr && top_dest->elem() != Type::BOTTOM);
6681         dest_spec = true;
6682       }
6683     }
6684   }
6685 
6686   if (has_src && has_dest && can_emit_guards) {
6687     BasicType src_elem = top_src->isa_aryptr()->elem()->array_element_basic_type();
6688     BasicType dest_elem = top_dest->isa_aryptr()->elem()->array_element_basic_type();
6689     if (is_reference_type(src_elem, true)) src_elem = T_OBJECT;
6690     if (is_reference_type(dest_elem, true)) dest_elem = T_OBJECT;
6691 
6692     if (src_elem == dest_elem && top_src->is_flat() == top_dest->is_flat() && src_elem == T_OBJECT) {
6693       // If both arrays are object arrays then having the exact types
6694       // for both will remove the need for a subtype check at runtime
6695       // before the call and may make it possible to pick a faster copy
6696       // routine (without a subtype check on every element)
6697       // Do we have the exact type of src?
6698       bool could_have_src = src_spec;
6699       // Do we have the exact type of dest?
6700       bool could_have_dest = dest_spec;
6701       ciKlass* src_k = nullptr;
6702       ciKlass* dest_k = nullptr;
6703       if (!src_spec) {
6704         src_k = src_type->speculative_type_not_null();
6705         if (src_k != nullptr && src_k->is_array_klass()) {
6706           could_have_src = true;
6707         }
6708       }
6709       if (!dest_spec) {
6710         dest_k = dest_type->speculative_type_not_null();
6711         if (dest_k != nullptr && dest_k->is_array_klass()) {
6712           could_have_dest = true;
6713         }
6714       }
6715       if (could_have_src && could_have_dest) {
6716         // If we can have both exact types, emit the missing guards
6717         if (could_have_src && !src_spec) {
6718           src = maybe_cast_profiled_obj(src, src_k, true);
6719           src_type = _gvn.type(src);
6720           top_src = src_type->isa_aryptr();
6721         }
6722         if (could_have_dest && !dest_spec) {
6723           dest = maybe_cast_profiled_obj(dest, dest_k, true);
6724           dest_type = _gvn.type(dest);
6725           top_dest = dest_type->isa_aryptr();
6726         }
6727       }
6728     }
6729   }
6730 
6731   ciMethod* trap_method = method();
6732   int trap_bci = bci();
6733   if (saved_jvms_before_guards != nullptr) {
6734     trap_method = alloc->jvms()->method();
6735     trap_bci = alloc->jvms()->bci();
6736   }
6737 
6738   bool negative_length_guard_generated = false;
6739 
6740   if (!C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_intrinsic) &&
6741       can_emit_guards && !src->is_top() && !dest->is_top()) {
6742     // validate arguments: enables transformation the ArrayCopyNode
6743     validated = true;
6744 
6745     RegionNode* slow_region = new RegionNode(1);
6746     record_for_igvn(slow_region);
6747 
6748     // (1) src and dest are arrays.
6749     generate_non_array_guard(load_object_klass(src), slow_region, &src);
6750     generate_non_array_guard(load_object_klass(dest), slow_region, &dest);
6751 
6752     // (2) src and dest arrays must have elements of the same BasicType
6753     // done at macro expansion or at Ideal transformation time
6754 
6755     // (4) src_offset must not be negative.
6756     generate_negative_guard(src_offset, slow_region);
6757 
6758     // (5) dest_offset must not be negative.
6759     generate_negative_guard(dest_offset, slow_region);
6760 
6761     // (7) src_offset + length must not exceed length of src.
6762     generate_limit_guard(src_offset, length,
6763                          load_array_length(src),
6764                          slow_region);
6765 
6766     // (8) dest_offset + length must not exceed length of dest.
6767     generate_limit_guard(dest_offset, length,
6768                          load_array_length(dest),
6769                          slow_region);
6770 
6771     // (6) length must not be negative.
6772     // This is also checked in generate_arraycopy() during macro expansion, but
6773     // we also have to check it here for the case where the ArrayCopyNode will
6774     // be eliminated by Escape Analysis.
6775     if (EliminateAllocations) {
6776       generate_negative_guard(length, slow_region);
6777       negative_length_guard_generated = true;
6778     }
6779 
6780     // (9) each element of an oop array must be assignable
6781     Node* dest_klass = load_object_klass(dest);
6782     Node* refined_dest_klass = dest_klass;
6783     if (src != dest) {
6784       dest_klass = load_non_refined_array_klass(refined_dest_klass);
6785       Node* not_subtype_ctrl = gen_subtype_check(src, dest_klass);
6786       slow_region->add_req(not_subtype_ctrl);
6787     }
6788 
6789     // TODO 8251971 Improve this. What about atomicity? Make sure this is always folded for type arrays.
6790     // If destination is null-restricted, source must be null-restricted as well: src_null_restricted || !dst_null_restricted
6791     Node* src_klass = load_object_klass(src);
6792     Node* adr_prop_src = basic_plus_adr(top(), src_klass, in_bytes(ArrayKlass::properties_offset()));
6793     Node* prop_src = _gvn.transform(LoadNode::make(_gvn, control(), immutable_memory(), adr_prop_src,
6794                                                    _gvn.type(adr_prop_src)->is_ptr(), TypeInt::INT, T_INT,
6795                                                    MemNode::unordered));
6796     Node* adr_prop_dest = basic_plus_adr(top(), refined_dest_klass, in_bytes(ArrayKlass::properties_offset()));
6797     Node* prop_dest = _gvn.transform(LoadNode::make(_gvn, control(), immutable_memory(), adr_prop_dest,
6798                                                     _gvn.type(adr_prop_dest)->is_ptr(), TypeInt::INT, T_INT,
6799                                                     MemNode::unordered));
6800 
6801     const ArrayProperties props_null_restricted = ArrayProperties::Default().with_null_restricted();
6802     jint props_value = (jint)props_null_restricted.value();
6803 
6804     prop_dest = _gvn.transform(new XorINode(prop_dest, intcon(props_value)));
6805     prop_src = _gvn.transform(new OrINode(prop_dest, prop_src));
6806     prop_src = _gvn.transform(new AndINode(prop_src, intcon(props_value)));
6807 
6808     Node* chk = _gvn.transform(new CmpINode(prop_src, intcon(props_value)));
6809     Node* tst = _gvn.transform(new BoolNode(chk, BoolTest::ne));
6810     generate_fair_guard(tst, slow_region);
6811 
6812     // TODO 8251971 This is too strong
6813     generate_fair_guard(flat_array_test(src), slow_region);
6814     generate_fair_guard(flat_array_test(dest), slow_region);
6815 
6816     {
6817       PreserveJVMState pjvms(this);
6818       set_control(_gvn.transform(slow_region));
6819       uncommon_trap(Deoptimization::Reason_intrinsic,
6820                     Deoptimization::Action_make_not_entrant);
6821       assert(stopped(), "Should be stopped");
6822     }
6823 
6824     const TypeKlassPtr* dest_klass_t = _gvn.type(dest_klass)->isa_klassptr();
6825     if (dest_klass_t == nullptr) {
6826       // refined_dest_klass may not be an array, which leads to dest_klass being top. This means we
6827       // are in a dead path.
6828       uncommon_trap(Deoptimization::Reason_intrinsic,
6829                     Deoptimization::Action_make_not_entrant);
6830       return true;
6831     }
6832 
6833     const Type* toop = dest_klass_t->cast_to_exactness(false)->as_instance_type();
6834     src = _gvn.transform(new CheckCastPPNode(control(), src, toop));
6835     arraycopy_move_allocation_here(alloc, dest, saved_jvms_before_guards, saved_reexecute_sp, new_idx);
6836   }
6837 
6838   if (stopped()) {
6839     return true;
6840   }
6841 
6842   Node* dest_klass = load_object_klass(dest);
6843   dest_klass = load_non_refined_array_klass(dest_klass);
6844 
6845   ArrayCopyNode* ac = ArrayCopyNode::make(this, true, src, src_offset, dest, dest_offset, length, alloc != nullptr, negative_length_guard_generated,
6846                                           // Create LoadRange and LoadKlass nodes for use during macro expansion here
6847                                           // so the compiler has a chance to eliminate them: during macro expansion,
6848                                           // we have to set their control (CastPP nodes are eliminated).
6849                                           load_object_klass(src), dest_klass,
6850                                           load_array_length(src), load_array_length(dest));
6851 
6852   ac->set_arraycopy(validated);
6853 
6854   Node* n = _gvn.transform(ac);
6855   if (n == ac) {
6856     ac->connect_outputs(this);
6857   } else {
6858     assert(validated, "shouldn't transform if all arguments not validated");
6859     set_all_memory(n);
6860   }
6861   clear_upper_avx();
6862 
6863 
6864   return true;
6865 }
6866 
6867 
6868 // Helper function which determines if an arraycopy immediately follows
6869 // an allocation, with no intervening tests or other escapes for the object.
6870 AllocateArrayNode*
6871 LibraryCallKit::tightly_coupled_allocation(Node* ptr) {
6872   if (stopped())             return nullptr;  // no fast path
6873   if (!C->do_aliasing())     return nullptr;  // no MergeMems around
6874 
6875   AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(ptr);
6876   if (alloc == nullptr)  return nullptr;
6877 
6878   Node* rawmem = memory(Compile::AliasIdxRaw);
6879   // Is the allocation's memory state untouched?
6880   if (!(rawmem->is_Proj() && rawmem->in(0)->is_Initialize())) {
6881     // Bail out if there have been raw-memory effects since the allocation.
6882     // (Example:  There might have been a call or safepoint.)
6883     return nullptr;
6884   }
6885   rawmem = rawmem->in(0)->as_Initialize()->memory(Compile::AliasIdxRaw);
6886   if (!(rawmem->is_Proj() && rawmem->in(0) == alloc)) {
6887     return nullptr;
6888   }
6889 
6890   // There must be no unexpected observers of this allocation.
6891   for (DUIterator_Fast imax, i = ptr->fast_outs(imax); i < imax; i++) {
6892     Node* obs = ptr->fast_out(i);
6893     if (obs != this->map()) {
6894       return nullptr;
6895     }
6896   }
6897 
6898   // This arraycopy must unconditionally follow the allocation of the ptr.
6899   Node* alloc_ctl = ptr->in(0);
6900   Node* ctl = control();
6901   while (ctl != alloc_ctl) {
6902     // There may be guards which feed into the slow_region.
6903     // Any other control flow means that we might not get a chance
6904     // to finish initializing the allocated object.
6905     // Various low-level checks bottom out in uncommon traps. These
6906     // are considered safe since we've already checked above that
6907     // there is no unexpected observer of this allocation.
6908     if (get_uncommon_trap_from_success_proj(ctl) != nullptr) {
6909       assert(ctl->in(0)->is_If(), "must be If");
6910       ctl = ctl->in(0)->in(0);
6911     } else {
6912       return nullptr;
6913     }
6914   }
6915 
6916   // If we get this far, we have an allocation which immediately
6917   // precedes the arraycopy, and we can take over zeroing the new object.
6918   // The arraycopy will finish the initialization, and provide
6919   // a new control state to which we will anchor the destination pointer.
6920 
6921   return alloc;
6922 }
6923 
6924 CallStaticJavaNode* LibraryCallKit::get_uncommon_trap_from_success_proj(Node* node) {
6925   if (node->is_IfProj()) {
6926     IfProjNode* other_proj = node->as_IfProj()->other_if_proj();
6927     for (DUIterator_Fast jmax, j = other_proj->fast_outs(jmax); j < jmax; j++) {
6928       Node* obs = other_proj->fast_out(j);
6929       if (obs->in(0) == other_proj && obs->is_CallStaticJava() &&
6930           (obs->as_CallStaticJava()->entry_point() == OptoRuntime::uncommon_trap_blob()->entry_point())) {
6931         return obs->as_CallStaticJava();
6932       }
6933     }
6934   }
6935   return nullptr;
6936 }
6937 
6938 //-------------inline_encodeISOArray-----------------------------------
6939 // int sun.nio.cs.ISO_8859_1.Encoder#encodeISOArray0(byte[] sa, int sp, byte[] da, int dp, int len)
6940 // int java.lang.StringCoding#encodeISOArray0(byte[] sa, int sp, byte[] da, int dp, int len)
6941 // int java.lang.StringCoding#encodeAsciiArray0(char[] sa, int sp, byte[] da, int dp, int len)
6942 // encode char[] to byte[] in ISO_8859_1 or ASCII
6943 bool LibraryCallKit::inline_encodeISOArray(bool ascii) {
6944   assert(callee()->signature()->size() == 5, "encodeISOArray has 5 parameters");
6945   // no receiver since it is static method
6946   Node *src         = argument(0);
6947   Node *src_offset  = argument(1);
6948   Node *dst         = argument(2);
6949   Node *dst_offset  = argument(3);
6950   Node *length      = argument(4);
6951 
6952   // Cast source & target arrays to not-null
6953   src = must_be_not_null(src, true);
6954   dst = must_be_not_null(dst, true);
6955   if (stopped()) {
6956     return true;
6957   }
6958 
6959   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
6960   const TypeAryPtr* dst_type = dst->Value(&_gvn)->isa_aryptr();
6961   if (src_type == nullptr || src_type->elem() == Type::BOTTOM ||
6962       dst_type == nullptr || dst_type->elem() == Type::BOTTOM) {
6963     // failed array check
6964     return false;
6965   }
6966 
6967   // Figure out the size and type of the elements we will be copying.
6968   BasicType src_elem = src_type->elem()->array_element_basic_type();
6969   BasicType dst_elem = dst_type->elem()->array_element_basic_type();
6970   if (!((src_elem == T_CHAR) || (src_elem== T_BYTE)) || dst_elem != T_BYTE) {
6971     return false;
6972   }
6973 
6974   // Check source & target bounds
6975   RegionNode* bailout = create_bailout();
6976   generate_string_range_check(src, src_offset, length, src_elem == T_BYTE, bailout);
6977   generate_string_range_check(dst, dst_offset, length, false, bailout);
6978   if (check_bailout(bailout)) {
6979     return true;
6980   }
6981 
6982   Node* src_start = array_element_address(src, src_offset, T_CHAR);
6983   Node* dst_start = array_element_address(dst, dst_offset, dst_elem);
6984   // 'src_start' points to src array + scaled offset
6985   // 'dst_start' points to dst array + scaled offset
6986 
6987   // See GraphKit::compress_string
6988   const TypePtr* adr_type;
6989   Node* mem = capture_memory(adr_type, src_type, dst_type);
6990   Node* enc = new EncodeISOArrayNode(control(), mem, adr_type, src_start, dst_start, length, ascii);
6991   enc = _gvn.transform(enc);
6992   Node* res_mem = _gvn.transform(new SCMemProjNode(enc));
6993   memory_effect(res_mem, src_type, dst_type);
6994 
6995   set_result(enc);
6996   clear_upper_avx();
6997 
6998   return true;
6999 }
7000 
7001 //-------------inline_multiplyToLen-----------------------------------
7002 bool LibraryCallKit::inline_multiplyToLen() {
7003   assert(UseMultiplyToLenIntrinsic, "not implemented on this platform");
7004 
7005   address stubAddr = StubRoutines::multiplyToLen();
7006   if (stubAddr == nullptr) {
7007     return false; // Intrinsic's stub is not implemented on this platform
7008   }
7009   const char* stubName = "multiplyToLen";
7010 
7011   assert(callee()->signature()->size() == 5, "multiplyToLen has 5 parameters");
7012 
7013   // no receiver because it is a static method
7014   Node* x    = argument(0);
7015   Node* xlen = argument(1);
7016   Node* y    = argument(2);
7017   Node* ylen = argument(3);
7018   Node* z    = argument(4);
7019 
7020   x = must_be_not_null(x, true);
7021   y = must_be_not_null(y, true);
7022 
7023   const TypeAryPtr* x_type = x->Value(&_gvn)->isa_aryptr();
7024   const TypeAryPtr* y_type = y->Value(&_gvn)->isa_aryptr();
7025   if (x_type == nullptr || x_type->elem() == Type::BOTTOM ||
7026       y_type == nullptr || y_type->elem() == Type::BOTTOM) {
7027     // failed array check
7028     return false;
7029   }
7030 
7031   BasicType x_elem = x_type->elem()->array_element_basic_type();
7032   BasicType y_elem = y_type->elem()->array_element_basic_type();
7033   if (x_elem != T_INT || y_elem != T_INT) {
7034     return false;
7035   }
7036 
7037   Node* x_start = array_element_address(x, intcon(0), x_elem);
7038   Node* y_start = array_element_address(y, intcon(0), y_elem);
7039   // 'x_start' points to x array + scaled xlen
7040   // 'y_start' points to y array + scaled ylen
7041 
7042   Node* z_start = array_element_address(z, intcon(0), T_INT);
7043 
7044   Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
7045                                  OptoRuntime::multiplyToLen_Type(),
7046                                  stubAddr, stubName, TypePtr::BOTTOM,
7047                                  x_start, xlen, y_start, ylen, z_start);
7048 
7049   C->set_has_split_ifs(true); // Has chance for split-if optimization
7050   set_result(z);
7051   return true;
7052 }
7053 
7054 //-------------inline_squareToLen------------------------------------
7055 bool LibraryCallKit::inline_squareToLen() {
7056   assert(UseSquareToLenIntrinsic, "not implemented on this platform");
7057 
7058   address stubAddr = StubRoutines::squareToLen();
7059   if (stubAddr == nullptr) {
7060     return false; // Intrinsic's stub is not implemented on this platform
7061   }
7062   const char* stubName = "squareToLen";
7063 
7064   assert(callee()->signature()->size() == 4, "implSquareToLen has 4 parameters");
7065 
7066   Node* x    = argument(0);
7067   Node* len  = argument(1);
7068   Node* z    = argument(2);
7069   Node* zlen = argument(3);
7070 
7071   x = must_be_not_null(x, true);
7072   z = must_be_not_null(z, true);
7073 
7074   const TypeAryPtr* x_type = x->Value(&_gvn)->isa_aryptr();
7075   const TypeAryPtr* z_type = z->Value(&_gvn)->isa_aryptr();
7076   if (x_type == nullptr || x_type->elem() == Type::BOTTOM ||
7077       z_type == nullptr || z_type->elem() == Type::BOTTOM) {
7078     // failed array check
7079     return false;
7080   }
7081 
7082   BasicType x_elem = x_type->elem()->array_element_basic_type();
7083   BasicType z_elem = z_type->elem()->array_element_basic_type();
7084   if (x_elem != T_INT || z_elem != T_INT) {
7085     return false;
7086   }
7087 
7088 
7089   Node* x_start = array_element_address(x, intcon(0), x_elem);
7090   Node* z_start = array_element_address(z, intcon(0), z_elem);
7091 
7092   Node*  call = make_runtime_call(RC_LEAF|RC_NO_FP,
7093                                   OptoRuntime::squareToLen_Type(),
7094                                   stubAddr, stubName, TypePtr::BOTTOM,
7095                                   x_start, len, z_start, zlen);
7096 
7097   set_result(z);
7098   return true;
7099 }
7100 
7101 //-------------inline_mulAdd------------------------------------------
7102 bool LibraryCallKit::inline_mulAdd() {
7103   assert(UseMulAddIntrinsic, "not implemented on this platform");
7104 
7105   address stubAddr = StubRoutines::mulAdd();
7106   if (stubAddr == nullptr) {
7107     return false; // Intrinsic's stub is not implemented on this platform
7108   }
7109   const char* stubName = "mulAdd";
7110 
7111   assert(callee()->signature()->size() == 5, "mulAdd has 5 parameters");
7112 
7113   Node* out      = argument(0);
7114   Node* in       = argument(1);
7115   Node* offset   = argument(2);
7116   Node* len      = argument(3);
7117   Node* k        = argument(4);
7118 
7119   in = must_be_not_null(in, true);
7120   out = must_be_not_null(out, true);
7121 
7122   const TypeAryPtr* out_type = out->Value(&_gvn)->isa_aryptr();
7123   const TypeAryPtr* in_type = in->Value(&_gvn)->isa_aryptr();
7124   if (out_type == nullptr || out_type->elem() == Type::BOTTOM ||
7125        in_type == nullptr ||  in_type->elem() == Type::BOTTOM) {
7126     // failed array check
7127     return false;
7128   }
7129 
7130   BasicType out_elem = out_type->elem()->array_element_basic_type();
7131   BasicType in_elem = in_type->elem()->array_element_basic_type();
7132   if (out_elem != T_INT || in_elem != T_INT) {
7133     return false;
7134   }
7135 
7136   Node* outlen = load_array_length(out);
7137   Node* new_offset = _gvn.transform(new SubINode(outlen, offset));
7138   Node* out_start = array_element_address(out, intcon(0), out_elem);
7139   Node* in_start = array_element_address(in, intcon(0), in_elem);
7140 
7141   Node*  call = make_runtime_call(RC_LEAF|RC_NO_FP,
7142                                   OptoRuntime::mulAdd_Type(),
7143                                   stubAddr, stubName, TypePtr::BOTTOM,
7144                                   out_start,in_start, new_offset, len, k);
7145   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7146   set_result(result);
7147   return true;
7148 }
7149 
7150 //-------------inline_montgomeryMultiply-----------------------------------
7151 bool LibraryCallKit::inline_montgomeryMultiply() {
7152   address stubAddr = StubRoutines::montgomeryMultiply();
7153   if (stubAddr == nullptr) {
7154     return false; // Intrinsic's stub is not implemented on this platform
7155   }
7156 
7157   assert(UseMontgomeryMultiplyIntrinsic, "not implemented on this platform");
7158   const char* stubName = "montgomery_multiply";
7159 
7160   assert(callee()->signature()->size() == 7, "montgomeryMultiply has 7 parameters");
7161 
7162   Node* a    = argument(0);
7163   Node* b    = argument(1);
7164   Node* n    = argument(2);
7165   Node* len  = argument(3);
7166   Node* inv  = argument(4);
7167   Node* m    = argument(6);
7168 
7169   const TypeAryPtr* a_type = a->Value(&_gvn)->isa_aryptr();
7170   const TypeAryPtr* b_type = b->Value(&_gvn)->isa_aryptr();
7171   const TypeAryPtr* n_type = n->Value(&_gvn)->isa_aryptr();
7172   const TypeAryPtr* m_type = m->Value(&_gvn)->isa_aryptr();
7173   if (a_type == nullptr || a_type->elem() == Type::BOTTOM ||
7174       b_type == nullptr || b_type->elem() == Type::BOTTOM ||
7175       n_type == nullptr || n_type->elem() == Type::BOTTOM ||
7176       m_type == nullptr || m_type->elem() == Type::BOTTOM) {
7177     // failed array check
7178     return false;
7179   }
7180 
7181   BasicType a_elem = a_type->elem()->array_element_basic_type();
7182   BasicType b_elem = b_type->elem()->array_element_basic_type();
7183   BasicType n_elem = n_type->elem()->array_element_basic_type();
7184   BasicType m_elem = m_type->elem()->array_element_basic_type();
7185   if (a_elem != T_INT || b_elem != T_INT || n_elem != T_INT || m_elem != T_INT) {
7186     return false;
7187   }
7188 
7189   // Make the call
7190   {
7191     Node* a_start = array_element_address(a, intcon(0), a_elem);
7192     Node* b_start = array_element_address(b, intcon(0), b_elem);
7193     Node* n_start = array_element_address(n, intcon(0), n_elem);
7194     Node* m_start = array_element_address(m, intcon(0), m_elem);
7195 
7196     Node* call = make_runtime_call(RC_LEAF,
7197                                    OptoRuntime::montgomeryMultiply_Type(),
7198                                    stubAddr, stubName, TypePtr::BOTTOM,
7199                                    a_start, b_start, n_start, len, inv, top(),
7200                                    m_start);
7201     set_result(m);
7202   }
7203 
7204   return true;
7205 }
7206 
7207 bool LibraryCallKit::inline_montgomerySquare() {
7208   address stubAddr = StubRoutines::montgomerySquare();
7209   if (stubAddr == nullptr) {
7210     return false; // Intrinsic's stub is not implemented on this platform
7211   }
7212 
7213   assert(UseMontgomerySquareIntrinsic, "not implemented on this platform");
7214   const char* stubName = "montgomery_square";
7215 
7216   assert(callee()->signature()->size() == 6, "montgomerySquare has 6 parameters");
7217 
7218   Node* a    = argument(0);
7219   Node* n    = argument(1);
7220   Node* len  = argument(2);
7221   Node* inv  = argument(3);
7222   Node* m    = argument(5);
7223 
7224   const TypeAryPtr* a_type = a->Value(&_gvn)->isa_aryptr();
7225   const TypeAryPtr* n_type = n->Value(&_gvn)->isa_aryptr();
7226   const TypeAryPtr* m_type = m->Value(&_gvn)->isa_aryptr();
7227   if (a_type == nullptr || a_type->elem() == Type::BOTTOM ||
7228       n_type == nullptr || n_type->elem() == Type::BOTTOM ||
7229       m_type == nullptr || m_type->elem() == Type::BOTTOM) {
7230     // failed array check
7231     return false;
7232   }
7233 
7234   BasicType a_elem = a_type->elem()->array_element_basic_type();
7235   BasicType n_elem = n_type->elem()->array_element_basic_type();
7236   BasicType m_elem = m_type->elem()->array_element_basic_type();
7237   if (a_elem != T_INT || n_elem != T_INT || m_elem != T_INT) {
7238     return false;
7239   }
7240 
7241   // Make the call
7242   {
7243     Node* a_start = array_element_address(a, intcon(0), a_elem);
7244     Node* n_start = array_element_address(n, intcon(0), n_elem);
7245     Node* m_start = array_element_address(m, intcon(0), m_elem);
7246 
7247     Node* call = make_runtime_call(RC_LEAF,
7248                                    OptoRuntime::montgomerySquare_Type(),
7249                                    stubAddr, stubName, TypePtr::BOTTOM,
7250                                    a_start, n_start, len, inv, top(),
7251                                    m_start);
7252     set_result(m);
7253   }
7254 
7255   return true;
7256 }
7257 
7258 bool LibraryCallKit::inline_bigIntegerShift(bool isRightShift) {
7259   address stubAddr = nullptr;
7260   const char* stubName = nullptr;
7261 
7262   stubAddr = isRightShift? StubRoutines::bigIntegerRightShift(): StubRoutines::bigIntegerLeftShift();
7263   if (stubAddr == nullptr) {
7264     return false; // Intrinsic's stub is not implemented on this platform
7265   }
7266 
7267   stubName = isRightShift? "bigIntegerRightShiftWorker" : "bigIntegerLeftShiftWorker";
7268 
7269   assert(callee()->signature()->size() == 5, "expected 5 arguments");
7270 
7271   Node* newArr = argument(0);
7272   Node* oldArr = argument(1);
7273   Node* newIdx = argument(2);
7274   Node* shiftCount = argument(3);
7275   Node* numIter = argument(4);
7276 
7277   const TypeAryPtr* newArr_type = newArr->Value(&_gvn)->isa_aryptr();
7278   const TypeAryPtr* oldArr_type = oldArr->Value(&_gvn)->isa_aryptr();
7279   if (newArr_type == nullptr || newArr_type->elem() == Type::BOTTOM ||
7280       oldArr_type == nullptr || oldArr_type->elem() == Type::BOTTOM) {
7281     return false;
7282   }
7283 
7284   BasicType newArr_elem = newArr_type->elem()->array_element_basic_type();
7285   BasicType oldArr_elem = oldArr_type->elem()->array_element_basic_type();
7286   if (newArr_elem != T_INT || oldArr_elem != T_INT) {
7287     return false;
7288   }
7289 
7290   // Make the call
7291   {
7292     Node* newArr_start = array_element_address(newArr, intcon(0), newArr_elem);
7293     Node* oldArr_start = array_element_address(oldArr, intcon(0), oldArr_elem);
7294 
7295     Node* call = make_runtime_call(RC_LEAF,
7296                                    OptoRuntime::bigIntegerShift_Type(),
7297                                    stubAddr,
7298                                    stubName,
7299                                    TypePtr::BOTTOM,
7300                                    newArr_start,
7301                                    oldArr_start,
7302                                    newIdx,
7303                                    shiftCount,
7304                                    numIter);
7305   }
7306 
7307   return true;
7308 }
7309 
7310 //-------------inline_vectorizedMismatch------------------------------
7311 bool LibraryCallKit::inline_vectorizedMismatch() {
7312   assert(UseVectorizedMismatchIntrinsic, "not implemented on this platform");
7313 
7314   assert(callee()->signature()->size() == 8, "vectorizedMismatch has 6 parameters");
7315   Node* obja    = argument(0); // Object
7316   Node* aoffset = argument(1); // long
7317   Node* objb    = argument(3); // Object
7318   Node* boffset = argument(4); // long
7319   Node* length  = argument(6); // int
7320   Node* scale   = argument(7); // int
7321 
7322   const TypeAryPtr* obja_t = _gvn.type(obja)->isa_aryptr();
7323   const TypeAryPtr* objb_t = _gvn.type(objb)->isa_aryptr();
7324   if (obja_t == nullptr || obja_t->elem() == Type::BOTTOM ||
7325       objb_t == nullptr || objb_t->elem() == Type::BOTTOM ||
7326       scale == top()) {
7327     return false; // failed input validation
7328   }
7329 
7330   Node* obja_adr = make_unsafe_address(obja, aoffset);
7331   Node* objb_adr = make_unsafe_address(objb, boffset);
7332 
7333   // Partial inlining handling for inputs smaller than ArrayOperationPartialInlineSize bytes in size.
7334   //
7335   //    inline_limit = ArrayOperationPartialInlineSize / element_size;
7336   //    if (length <= inline_limit) {
7337   //      inline_path:
7338   //        vmask   = VectorMaskGen length
7339   //        vload1  = LoadVectorMasked obja, vmask
7340   //        vload2  = LoadVectorMasked objb, vmask
7341   //        result1 = VectorCmpMasked vload1, vload2, vmask
7342   //    } else {
7343   //      call_stub_path:
7344   //        result2 = call vectorizedMismatch_stub(obja, objb, length, scale)
7345   //    }
7346   //    exit_block:
7347   //      return Phi(result1, result2);
7348   //
7349   enum { inline_path = 1,  // input is small enough to process it all at once
7350          stub_path   = 2,  // input is too large; call into the VM
7351          PATH_LIMIT  = 3
7352   };
7353 
7354   Node* exit_block = new RegionNode(PATH_LIMIT);
7355   Node* result_phi = new PhiNode(exit_block, TypeInt::INT);
7356   Node* memory_phi = new PhiNode(exit_block, Type::MEMORY, TypePtr::BOTTOM);
7357 
7358   Node* call_stub_path = control();
7359 
7360   BasicType elem_bt = T_ILLEGAL;
7361 
7362   const TypeInt* scale_t = _gvn.type(scale)->is_int();
7363   if (scale_t->is_con()) {
7364     switch (scale_t->get_con()) {
7365       case 0: elem_bt = T_BYTE;  break;
7366       case 1: elem_bt = T_SHORT; break;
7367       case 2: elem_bt = T_INT;   break;
7368       case 3: elem_bt = T_LONG;  break;
7369 
7370       default: elem_bt = T_ILLEGAL; break; // not supported
7371     }
7372   }
7373 
7374   int inline_limit = 0;
7375   bool do_partial_inline = false;
7376 
7377   if (elem_bt != T_ILLEGAL && ArrayOperationPartialInlineSize > 0) {
7378     inline_limit = ArrayOperationPartialInlineSize / type2aelembytes(elem_bt);
7379     do_partial_inline = inline_limit >= 16;
7380   }
7381 
7382   if (do_partial_inline) {
7383     assert(elem_bt != T_ILLEGAL, "sanity");
7384 
7385     if (Matcher::match_rule_supported_vector(Op_VectorMaskGen,    inline_limit, elem_bt) &&
7386         Matcher::match_rule_supported_vector(Op_LoadVectorMasked, inline_limit, elem_bt) &&
7387         Matcher::match_rule_supported_vector(Op_VectorCmpMasked,  inline_limit, elem_bt)) {
7388 
7389       const TypeVect* vt = TypeVect::make(elem_bt, inline_limit);
7390       Node* cmp_length = _gvn.transform(new CmpINode(length, intcon(inline_limit)));
7391       Node* bol_gt     = _gvn.transform(new BoolNode(cmp_length, BoolTest::gt));
7392 
7393       call_stub_path = generate_guard(bol_gt, nullptr, PROB_MIN);
7394 
7395       if (!stopped()) {
7396         Node* casted_length = _gvn.transform(new CastIINode(control(), length, TypeInt::make(0, inline_limit, Type::WidenMin)));
7397 
7398         const TypePtr* obja_adr_t = _gvn.type(obja_adr)->isa_ptr();
7399         const TypePtr* objb_adr_t = _gvn.type(objb_adr)->isa_ptr();
7400         Node* obja_adr_mem = memory(C->get_alias_index(obja_adr_t));
7401         Node* objb_adr_mem = memory(C->get_alias_index(objb_adr_t));
7402 
7403         Node* vmask      = _gvn.transform(VectorMaskGenNode::make(ConvI2X(casted_length), elem_bt));
7404         Node* vload_obja = _gvn.transform(new LoadVectorMaskedNode(control(), obja_adr_mem, obja_adr, obja_adr_t, vt, vmask));
7405         Node* vload_objb = _gvn.transform(new LoadVectorMaskedNode(control(), objb_adr_mem, objb_adr, objb_adr_t, vt, vmask));
7406         Node* result     = _gvn.transform(new VectorCmpMaskedNode(vload_obja, vload_objb, vmask, TypeInt::INT));
7407 
7408         exit_block->init_req(inline_path, control());
7409         memory_phi->init_req(inline_path, map()->memory());
7410         result_phi->init_req(inline_path, result);
7411 
7412         C->set_max_vector_size(MAX2((uint)ArrayOperationPartialInlineSize, C->max_vector_size()));
7413         clear_upper_avx();
7414       }
7415     }
7416   }
7417 
7418   if (call_stub_path != nullptr) {
7419     set_control(call_stub_path);
7420 
7421     Node* call = make_runtime_call(RC_LEAF,
7422                                    OptoRuntime::vectorizedMismatch_Type(),
7423                                    StubRoutines::vectorizedMismatch(), "vectorizedMismatch", TypePtr::BOTTOM,
7424                                    obja_adr, objb_adr, length, scale);
7425 
7426     exit_block->init_req(stub_path, control());
7427     memory_phi->init_req(stub_path, map()->memory());
7428     result_phi->init_req(stub_path, _gvn.transform(new ProjNode(call, TypeFunc::Parms)));
7429   }
7430 
7431   exit_block = _gvn.transform(exit_block);
7432   memory_phi = _gvn.transform(memory_phi);
7433   result_phi = _gvn.transform(result_phi);
7434 
7435   record_for_igvn(exit_block);
7436   record_for_igvn(memory_phi);
7437   record_for_igvn(result_phi);
7438 
7439   set_control(exit_block);
7440   set_all_memory(memory_phi);
7441   set_result(result_phi);
7442 
7443   return true;
7444 }
7445 
7446 //------------------------------inline_vectorizedHashcode----------------------------
7447 bool LibraryCallKit::inline_vectorizedHashCode() {
7448   assert(UseVectorizedHashCodeIntrinsic, "not implemented on this platform");
7449 
7450   assert(callee()->signature()->size() == 5, "vectorizedHashCode has 5 parameters");
7451   Node* array          = argument(0);
7452   Node* offset         = argument(1);
7453   Node* length         = argument(2);
7454   Node* initialValue   = argument(3);
7455   Node* basic_type     = argument(4);
7456 
7457   if (basic_type == top()) {
7458     return false; // failed input validation
7459   }
7460 
7461   const TypeInt* basic_type_t = _gvn.type(basic_type)->is_int();
7462   if (!basic_type_t->is_con()) {
7463     return false; // Only intrinsify if mode argument is constant
7464   }
7465 
7466   array = must_be_not_null(array, true);
7467 
7468   BasicType bt = (BasicType)basic_type_t->get_con();
7469 
7470   // Resolve address of first element
7471   Node* array_start = array_element_address(array, offset, bt);
7472 
7473   const TypeAryPtr* in_adr_type = TypeAryPtr::get_array_body_type(bt);
7474   set_result(_gvn.transform(new VectorizedHashCodeNode(control(), memory(in_adr_type), in_adr_type,
7475     array_start, length, initialValue, basic_type)));
7476   clear_upper_avx();
7477 
7478   return true;
7479 }
7480 
7481 /**
7482  * Calculate CRC32 for byte.
7483  * int java.util.zip.CRC32.update(int crc, int b)
7484  */
7485 bool LibraryCallKit::inline_updateCRC32() {
7486   assert(UseCRC32Intrinsics, "need AVX and CLMUL instructions support");
7487   assert(callee()->signature()->size() == 2, "update has 2 parameters");
7488   // no receiver since it is static method
7489   Node* crc  = argument(0); // type: int
7490   Node* b    = argument(1); // type: int
7491 
7492   /*
7493    *    int c = ~ crc;
7494    *    b = timesXtoThe32[(b ^ c) & 0xFF];
7495    *    b = b ^ (c >>> 8);
7496    *    crc = ~b;
7497    */
7498 
7499   Node* M1 = intcon(-1);
7500   crc = _gvn.transform(new XorINode(crc, M1));
7501   Node* result = _gvn.transform(new XorINode(crc, b));
7502   result = _gvn.transform(new AndINode(result, intcon(0xFF)));
7503 
7504   Node* base = makecon(TypeRawPtr::make(StubRoutines::crc_table_addr()));
7505   Node* offset = _gvn.transform(new LShiftINode(result, intcon(0x2)));
7506   Node* adr = off_heap_plus_addr(base, ConvI2X(offset));
7507   result = make_load(control(), adr, TypeInt::INT, T_INT, MemNode::unordered);
7508 
7509   crc = _gvn.transform(new URShiftINode(crc, intcon(8)));
7510   result = _gvn.transform(new XorINode(crc, result));
7511   result = _gvn.transform(new XorINode(result, M1));
7512   set_result(result);
7513   return true;
7514 }
7515 
7516 /**
7517  * Calculate CRC32 for byte[] array.
7518  * int java.util.zip.CRC32.updateBytes(int crc, byte[] buf, int off, int len)
7519  */
7520 bool LibraryCallKit::inline_updateBytesCRC32() {
7521   assert(UseCRC32Intrinsics, "need AVX and CLMUL instructions support");
7522   assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
7523   // no receiver since it is static method
7524   Node* crc     = argument(0); // type: int
7525   Node* src     = argument(1); // type: oop
7526   Node* offset  = argument(2); // type: int
7527   Node* length  = argument(3); // type: int
7528 
7529   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7530   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
7531     // failed array check
7532     return false;
7533   }
7534 
7535   // Figure out the size and type of the elements we will be copying.
7536   BasicType src_elem = src_type->elem()->array_element_basic_type();
7537   if (src_elem != T_BYTE) {
7538     return false;
7539   }
7540 
7541   // 'src_start' points to src array + scaled offset
7542   src = must_be_not_null(src, true);
7543   Node* src_start = array_element_address(src, offset, src_elem);
7544 
7545   // We assume that range check is done by caller.
7546   // TODO: generate range check (offset+length < src.length) in debug VM.
7547 
7548   // Call the stub.
7549   address stubAddr = StubRoutines::updateBytesCRC32();
7550   const char *stubName = "updateBytesCRC32";
7551 
7552   Node* call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::updateBytesCRC32_Type(),
7553                                  stubAddr, stubName, TypePtr::BOTTOM,
7554                                  crc, src_start, length);
7555   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7556   set_result(result);
7557   return true;
7558 }
7559 
7560 /**
7561  * Calculate CRC32 for ByteBuffer.
7562  * int java.util.zip.CRC32.updateByteBuffer(int crc, long buf, int off, int len)
7563  */
7564 bool LibraryCallKit::inline_updateByteBufferCRC32() {
7565   assert(UseCRC32Intrinsics, "need AVX and CLMUL instructions support");
7566   assert(callee()->signature()->size() == 5, "updateByteBuffer has 4 parameters and one is long");
7567   // no receiver since it is static method
7568   Node* crc     = argument(0); // type: int
7569   Node* src     = argument(1); // type: long
7570   Node* offset  = argument(3); // type: int
7571   Node* length  = argument(4); // type: int
7572 
7573   src = ConvL2X(src);  // adjust Java long to machine word
7574   Node* base = _gvn.transform(new CastX2PNode(src));
7575   offset = ConvI2X(offset);
7576 
7577   // 'src_start' points to src array + scaled offset
7578   Node* src_start = off_heap_plus_addr(base, offset);
7579 
7580   // Call the stub.
7581   address stubAddr = StubRoutines::updateBytesCRC32();
7582   const char *stubName = "updateBytesCRC32";
7583 
7584   Node* call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::updateBytesCRC32_Type(),
7585                                  stubAddr, stubName, TypePtr::BOTTOM,
7586                                  crc, src_start, length);
7587   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7588   set_result(result);
7589   return true;
7590 }
7591 
7592 //------------------------------get_table_from_crc32c_class-----------------------
7593 Node * LibraryCallKit::get_table_from_crc32c_class(ciInstanceKlass *crc32c_class) {
7594   Node* table = load_field_from_object(nullptr, "byteTable", "[I", /*decorators*/ IN_HEAP, /*is_static*/ true, crc32c_class);
7595   assert (table != nullptr, "wrong version of java.util.zip.CRC32C");
7596 
7597   return table;
7598 }
7599 
7600 //------------------------------inline_updateBytesCRC32C-----------------------
7601 //
7602 // Calculate CRC32C for byte[] array.
7603 // int java.util.zip.CRC32C.updateBytes(int crc, byte[] buf, int off, int end)
7604 //
7605 bool LibraryCallKit::inline_updateBytesCRC32C() {
7606   assert(UseCRC32CIntrinsics, "need CRC32C instruction support");
7607   assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
7608   assert(callee()->holder()->is_loaded(), "CRC32C class must be loaded");
7609   // no receiver since it is a static method
7610   Node* crc     = argument(0); // type: int
7611   Node* src     = argument(1); // type: oop
7612   Node* offset  = argument(2); // type: int
7613   Node* end     = argument(3); // type: int
7614 
7615   Node* length = _gvn.transform(new SubINode(end, offset));
7616 
7617   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7618   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
7619     // failed array check
7620     return false;
7621   }
7622 
7623   // Figure out the size and type of the elements we will be copying.
7624   BasicType src_elem = src_type->elem()->array_element_basic_type();
7625   if (src_elem != T_BYTE) {
7626     return false;
7627   }
7628 
7629   // 'src_start' points to src array + scaled offset
7630   src = must_be_not_null(src, true);
7631   Node* src_start = array_element_address(src, offset, src_elem);
7632 
7633   // static final int[] byteTable in class CRC32C
7634   Node* table = get_table_from_crc32c_class(callee()->holder());
7635   table = must_be_not_null(table, true);
7636   Node* table_start = array_element_address(table, intcon(0), T_INT);
7637 
7638   // We assume that range check is done by caller.
7639   // TODO: generate range check (offset+length < src.length) in debug VM.
7640 
7641   // Call the stub.
7642   address stubAddr = StubRoutines::updateBytesCRC32C();
7643   const char *stubName = "updateBytesCRC32C";
7644 
7645   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesCRC32C_Type(),
7646                                  stubAddr, stubName, TypePtr::BOTTOM,
7647                                  crc, src_start, length, table_start);
7648   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7649   set_result(result);
7650   return true;
7651 }
7652 
7653 //------------------------------inline_updateDirectByteBufferCRC32C-----------------------
7654 //
7655 // Calculate CRC32C for DirectByteBuffer.
7656 // int java.util.zip.CRC32C.updateDirectByteBuffer(int crc, long buf, int off, int end)
7657 //
7658 bool LibraryCallKit::inline_updateDirectByteBufferCRC32C() {
7659   assert(UseCRC32CIntrinsics, "need CRC32C instruction support");
7660   assert(callee()->signature()->size() == 5, "updateDirectByteBuffer has 4 parameters and one is long");
7661   assert(callee()->holder()->is_loaded(), "CRC32C class must be loaded");
7662   // no receiver since it is a static method
7663   Node* crc     = argument(0); // type: int
7664   Node* src     = argument(1); // type: long
7665   Node* offset  = argument(3); // type: int
7666   Node* end     = argument(4); // type: int
7667 
7668   Node* length = _gvn.transform(new SubINode(end, offset));
7669 
7670   src = ConvL2X(src);  // adjust Java long to machine word
7671   Node* base = _gvn.transform(new CastX2PNode(src));
7672   offset = ConvI2X(offset);
7673 
7674   // 'src_start' points to src array + scaled offset
7675   Node* src_start = off_heap_plus_addr(base, offset);
7676 
7677   // static final int[] byteTable in class CRC32C
7678   Node* table = get_table_from_crc32c_class(callee()->holder());
7679   table = must_be_not_null(table, true);
7680   Node* table_start = array_element_address(table, intcon(0), T_INT);
7681 
7682   // Call the stub.
7683   address stubAddr = StubRoutines::updateBytesCRC32C();
7684   const char *stubName = "updateBytesCRC32C";
7685 
7686   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesCRC32C_Type(),
7687                                  stubAddr, stubName, TypePtr::BOTTOM,
7688                                  crc, src_start, length, table_start);
7689   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7690   set_result(result);
7691   return true;
7692 }
7693 
7694 //------------------------------inline_updateBytesAdler32----------------------
7695 //
7696 // Calculate Adler32 checksum for byte[] array.
7697 // int java.util.zip.Adler32.updateBytes(int crc, byte[] buf, int off, int len)
7698 //
7699 bool LibraryCallKit::inline_updateBytesAdler32() {
7700   assert(UseAdler32Intrinsics, "Adler32 Intrinsic support need"); // check if we actually need to check this flag or check a different one
7701   assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
7702   assert(callee()->holder()->is_loaded(), "Adler32 class must be loaded");
7703   // no receiver since it is static method
7704   Node* crc     = argument(0); // type: int
7705   Node* src     = argument(1); // type: oop
7706   Node* offset  = argument(2); // type: int
7707   Node* length  = argument(3); // type: int
7708 
7709   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7710   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
7711     // failed array check
7712     return false;
7713   }
7714 
7715   // Figure out the size and type of the elements we will be copying.
7716   BasicType src_elem = src_type->elem()->array_element_basic_type();
7717   if (src_elem != T_BYTE) {
7718     return false;
7719   }
7720 
7721   // 'src_start' points to src array + scaled offset
7722   Node* src_start = array_element_address(src, offset, src_elem);
7723 
7724   // We assume that range check is done by caller.
7725   // TODO: generate range check (offset+length < src.length) in debug VM.
7726 
7727   // Call the stub.
7728   address stubAddr = StubRoutines::updateBytesAdler32();
7729   const char *stubName = "updateBytesAdler32";
7730 
7731   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesAdler32_Type(),
7732                                  stubAddr, stubName, TypePtr::BOTTOM,
7733                                  crc, src_start, length);
7734   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7735   set_result(result);
7736   return true;
7737 }
7738 
7739 //------------------------------inline_updateByteBufferAdler32---------------
7740 //
7741 // Calculate Adler32 checksum for DirectByteBuffer.
7742 // int java.util.zip.Adler32.updateByteBuffer(int crc, long buf, int off, int len)
7743 //
7744 bool LibraryCallKit::inline_updateByteBufferAdler32() {
7745   assert(UseAdler32Intrinsics, "Adler32 Intrinsic support need"); // check if we actually need to check this flag or check a different one
7746   assert(callee()->signature()->size() == 5, "updateByteBuffer has 4 parameters and one is long");
7747   assert(callee()->holder()->is_loaded(), "Adler32 class must be loaded");
7748   // no receiver since it is static method
7749   Node* crc     = argument(0); // type: int
7750   Node* src     = argument(1); // type: long
7751   Node* offset  = argument(3); // type: int
7752   Node* length  = argument(4); // type: int
7753 
7754   src = ConvL2X(src);  // adjust Java long to machine word
7755   Node* base = _gvn.transform(new CastX2PNode(src));
7756   offset = ConvI2X(offset);
7757 
7758   // 'src_start' points to src array + scaled offset
7759   Node* src_start = off_heap_plus_addr(base, offset);
7760 
7761   // Call the stub.
7762   address stubAddr = StubRoutines::updateBytesAdler32();
7763   const char *stubName = "updateBytesAdler32";
7764 
7765   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesAdler32_Type(),
7766                                  stubAddr, stubName, TypePtr::BOTTOM,
7767                                  crc, src_start, length);
7768 
7769   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7770   set_result(result);
7771   return true;
7772 }
7773 
7774 //----------------------------inline_reference_get0----------------------------
7775 // public T java.lang.ref.Reference.get();
7776 bool LibraryCallKit::inline_reference_get0() {
7777   const int referent_offset = java_lang_ref_Reference::referent_offset();
7778 
7779   // Get the argument:
7780   Node* reference_obj = null_check_receiver();
7781   if (stopped()) return true;
7782 
7783   DecoratorSet decorators = IN_HEAP | ON_WEAK_OOP_REF;
7784   Node* result = load_field_from_object(reference_obj, "referent", "Ljava/lang/Object;",
7785                                         decorators, /*is_static*/ false,
7786                                         env()->Reference_klass());
7787   if (result == nullptr) return false;
7788 
7789   // Add memory barrier to prevent commoning reads from this field
7790   // across safepoint since GC can change its value.
7791   insert_mem_bar(Op_MemBarCPUOrder);
7792 
7793   set_result(result);
7794   return true;
7795 }
7796 
7797 //----------------------------inline_reference_refersTo0----------------------------
7798 // bool java.lang.ref.Reference.refersTo0();
7799 // bool java.lang.ref.PhantomReference.refersTo0();
7800 bool LibraryCallKit::inline_reference_refersTo0(bool is_phantom) {
7801   // Get arguments:
7802   Node* reference_obj = null_check_receiver();
7803   Node* other_obj = argument(1);
7804   if (stopped()) return true;
7805 
7806   DecoratorSet decorators = IN_HEAP | AS_NO_KEEPALIVE;
7807   decorators |= (is_phantom ? ON_PHANTOM_OOP_REF : ON_WEAK_OOP_REF);
7808   Node* referent = load_field_from_object(reference_obj, "referent", "Ljava/lang/Object;",
7809                                           decorators, /*is_static*/ false,
7810                                           env()->Reference_klass());
7811   if (referent == nullptr) return false;
7812 
7813   // Add memory barrier to prevent commoning reads from this field
7814   // across safepoint since GC can change its value.
7815   insert_mem_bar(Op_MemBarCPUOrder);
7816 
7817   Node* cmp = _gvn.transform(new CmpPNode(referent, other_obj));
7818   Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
7819   IfNode* if_node = create_and_map_if(control(), bol, PROB_FAIR, COUNT_UNKNOWN);
7820 
7821   RegionNode* region = new RegionNode(3);
7822   PhiNode* phi = new PhiNode(region, TypeInt::BOOL);
7823 
7824   Node* if_true = _gvn.transform(new IfTrueNode(if_node));
7825   region->init_req(1, if_true);
7826   phi->init_req(1, intcon(1));
7827 
7828   Node* if_false = _gvn.transform(new IfFalseNode(if_node));
7829   region->init_req(2, if_false);
7830   phi->init_req(2, intcon(0));
7831 
7832   set_control(_gvn.transform(region));
7833   record_for_igvn(region);
7834   set_result(_gvn.transform(phi));
7835   return true;
7836 }
7837 
7838 //----------------------------inline_reference_clear0----------------------------
7839 // void java.lang.ref.Reference.clear0();
7840 // void java.lang.ref.PhantomReference.clear0();
7841 bool LibraryCallKit::inline_reference_clear0(bool is_phantom) {
7842   // This matches the implementation in JVM_ReferenceClear, see the comments there.
7843 
7844   // Get arguments
7845   Node* reference_obj = null_check_receiver();
7846   if (stopped()) return true;
7847 
7848   // Common access parameters
7849   DecoratorSet decorators = IN_HEAP | AS_NO_KEEPALIVE;
7850   decorators |= (is_phantom ? ON_PHANTOM_OOP_REF : ON_WEAK_OOP_REF);
7851   Node* referent_field_addr = basic_plus_adr(reference_obj, java_lang_ref_Reference::referent_offset());
7852   const TypePtr* referent_field_addr_type = _gvn.type(referent_field_addr)->isa_ptr();
7853   const Type* val_type = TypeOopPtr::make_from_klass(env()->Object_klass());
7854 
7855   Node* referent = access_load_at(reference_obj,
7856                                   referent_field_addr,
7857                                   referent_field_addr_type,
7858                                   val_type,
7859                                   T_OBJECT,
7860                                   decorators);
7861 
7862   IdealKit ideal(this);
7863 #define __ ideal.
7864   __ if_then(referent, BoolTest::ne, null());
7865     sync_kit(ideal);
7866     access_store_at(reference_obj,
7867                     referent_field_addr,
7868                     referent_field_addr_type,
7869                     null(),
7870                     val_type,
7871                     T_OBJECT,
7872                     decorators);
7873     __ sync_kit(this);
7874   __ end_if();
7875   final_sync(ideal);
7876 #undef __
7877 
7878   return true;
7879 }
7880 
7881 //-----------------------inline_reference_reachabilityFence-----------------
7882 // bool java.lang.ref.Reference.reachabilityFence();
7883 bool LibraryCallKit::inline_reference_reachabilityFence() {
7884   Node* referent = argument(0);
7885   insert_reachability_fence(referent);
7886   return true;
7887 }
7888 
7889 Node* LibraryCallKit::load_field_from_object(Node* fromObj, const char* fieldName, const char* fieldTypeString,
7890                                              DecoratorSet decorators, bool is_static,
7891                                              ciInstanceKlass* fromKls) {
7892   if (fromKls == nullptr) {
7893     const TypeInstPtr* tinst = _gvn.type(fromObj)->isa_instptr();
7894     assert(tinst != nullptr, "obj is null");
7895     assert(tinst->is_loaded(), "obj is not loaded");
7896     fromKls = tinst->instance_klass();
7897   }
7898   ciField* field = fromKls->get_field_by_name(ciSymbol::make(fieldName),
7899                                               ciSymbol::make(fieldTypeString),
7900                                               is_static);
7901 
7902   assert(field != nullptr, "undefined field %s %s %s", fieldTypeString, fromKls->name()->as_utf8(), fieldName);
7903   if (field == nullptr) return (Node *) nullptr;
7904 
7905   if (is_static) {
7906     const TypeInstPtr* tip = TypeInstPtr::make(fromKls->java_mirror());
7907     fromObj = makecon(tip);
7908   }
7909 
7910   // Next code  copied from Parse::do_get_xxx():
7911 
7912   // Compute address and memory type.
7913   int offset  = field->offset_in_bytes();
7914   bool is_vol = field->is_volatile();
7915   ciType* field_klass = field->type();
7916   assert(field_klass->is_loaded(), "should be loaded");
7917   const TypePtr* adr_type = C->alias_type(field)->adr_type();
7918   Node *adr = basic_plus_adr(fromObj, fromObj, offset);
7919   assert(C->get_alias_index(adr_type) == C->get_alias_index(_gvn.type(adr)->isa_ptr()),
7920     "slice of address and input slice don't match");
7921   BasicType bt = field->layout_type();
7922 
7923   // Build the resultant type of the load
7924   const Type *type;
7925   if (bt == T_OBJECT) {
7926     type = TypeOopPtr::make_from_klass(field_klass->as_klass());
7927   } else {
7928     type = Type::get_const_basic_type(bt);
7929   }
7930 
7931   if (is_vol) {
7932     decorators |= MO_SEQ_CST;
7933   }
7934 
7935   return access_load_at(fromObj, adr, adr_type, type, bt, decorators);
7936 }
7937 
7938 Node * LibraryCallKit::field_address_from_object(Node * fromObj, const char * fieldName, const char * fieldTypeString,
7939                                                  bool is_exact /* true */, bool is_static /* false */,
7940                                                  ciInstanceKlass * fromKls /* nullptr */) {
7941   if (fromKls == nullptr) {
7942     const TypeInstPtr* tinst = _gvn.type(fromObj)->isa_instptr();
7943     assert(tinst != nullptr, "obj is null");
7944     assert(tinst->is_loaded(), "obj is not loaded");
7945     assert(!is_exact || tinst->klass_is_exact(), "klass not exact");
7946     fromKls = tinst->instance_klass();
7947   }
7948   else {
7949     assert(is_static, "only for static field access");
7950   }
7951   ciField* field = fromKls->get_field_by_name(ciSymbol::make(fieldName),
7952     ciSymbol::make(fieldTypeString),
7953     is_static);
7954 
7955   assert(field != nullptr, "undefined field");
7956   assert(!field->is_volatile(), "not defined for volatile fields");
7957 
7958   if (is_static) {
7959     const TypeInstPtr* tip = TypeInstPtr::make(fromKls->java_mirror());
7960     fromObj = makecon(tip);
7961   }
7962 
7963   // Next code  copied from Parse::do_get_xxx():
7964 
7965   // Compute address and memory type.
7966   int offset = field->offset_in_bytes();
7967   Node *adr = basic_plus_adr(fromObj, fromObj, offset);
7968 
7969   return adr;
7970 }
7971 
7972 //------------------------------inline_aescrypt_Block-----------------------
7973 bool LibraryCallKit::inline_aescrypt_Block(vmIntrinsics::ID id) {
7974   address stubAddr = nullptr;
7975   const char *stubName;
7976   bool is_decrypt = false;
7977   assert(UseAES, "need AES instruction support");
7978 
7979   switch(id) {
7980   case vmIntrinsics::_aescrypt_encryptBlock:
7981     stubAddr = StubRoutines::aescrypt_encryptBlock();
7982     stubName = "aescrypt_encryptBlock";
7983     break;
7984   case vmIntrinsics::_aescrypt_decryptBlock:
7985     stubAddr = StubRoutines::aescrypt_decryptBlock();
7986     stubName = "aescrypt_decryptBlock";
7987     is_decrypt = true;
7988     break;
7989   default:
7990     break;
7991   }
7992   if (stubAddr == nullptr) return false;
7993 
7994   Node* aescrypt_object = argument(0);
7995   Node* src             = argument(1);
7996   Node* src_offset      = argument(2);
7997   Node* dest            = argument(3);
7998   Node* dest_offset     = argument(4);
7999 
8000   src = must_be_not_null(src, true);
8001   dest = must_be_not_null(dest, true);
8002 
8003   // (1) src and dest are arrays.
8004   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
8005   const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
8006   assert( src_type != nullptr &&  src_type->elem() != Type::BOTTOM &&
8007          dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
8008 
8009   // for the quick and dirty code we will skip all the checks.
8010   // we are just trying to get the call to be generated.
8011   Node* src_start  = src;
8012   Node* dest_start = dest;
8013   if (src_offset != nullptr || dest_offset != nullptr) {
8014     assert(src_offset != nullptr && dest_offset != nullptr, "");
8015     src_start  = array_element_address(src,  src_offset,  T_BYTE);
8016     dest_start = array_element_address(dest, dest_offset, T_BYTE);
8017   }
8018 
8019   // now need to get the start of its expanded key array
8020   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
8021   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object, is_decrypt);
8022   if (k_start == nullptr) return false;
8023 
8024   // Call the stub.
8025   make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::aescrypt_block_Type(),
8026                     stubAddr, stubName, TypePtr::BOTTOM,
8027                     src_start, dest_start, k_start);
8028 
8029   return true;
8030 }
8031 
8032 //------------------------------inline_cipherBlockChaining_AESCrypt-----------------------
8033 bool LibraryCallKit::inline_cipherBlockChaining_AESCrypt(vmIntrinsics::ID id) {
8034   address stubAddr = nullptr;
8035   const char *stubName = nullptr;
8036   bool is_decrypt = false;
8037   assert(UseAES, "need AES instruction support");
8038 
8039   switch(id) {
8040   case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
8041     stubAddr = StubRoutines::cipherBlockChaining_encryptAESCrypt();
8042     stubName = "cipherBlockChaining_encryptAESCrypt";
8043     break;
8044   case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
8045     stubAddr = StubRoutines::cipherBlockChaining_decryptAESCrypt();
8046     stubName = "cipherBlockChaining_decryptAESCrypt";
8047     is_decrypt = true;
8048     break;
8049   default:
8050     break;
8051   }
8052   if (stubAddr == nullptr) return false;
8053 
8054   Node* cipherBlockChaining_object = argument(0);
8055   Node* src                        = argument(1);
8056   Node* src_offset                 = argument(2);
8057   Node* len                        = argument(3);
8058   Node* dest                       = argument(4);
8059   Node* dest_offset                = argument(5);
8060 
8061   src = must_be_not_null(src, false);
8062   dest = must_be_not_null(dest, false);
8063 
8064   // (1) src and dest are arrays.
8065   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
8066   const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
8067   assert( src_type != nullptr &&  src_type->elem() != Type::BOTTOM &&
8068          dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
8069 
8070   // checks are the responsibility of the caller
8071   Node* src_start  = src;
8072   Node* dest_start = dest;
8073   if (src_offset != nullptr || dest_offset != nullptr) {
8074     assert(src_offset != nullptr && dest_offset != nullptr, "");
8075     src_start  = array_element_address(src,  src_offset,  T_BYTE);
8076     dest_start = array_element_address(dest, dest_offset, T_BYTE);
8077   }
8078 
8079   // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
8080   // (because of the predicated logic executed earlier).
8081   // so we cast it here safely.
8082   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
8083 
8084   Node* embeddedCipherObj = load_field_from_object(cipherBlockChaining_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8085   if (embeddedCipherObj == nullptr) return false;
8086 
8087   // cast it to what we know it will be at runtime
8088   const TypeInstPtr* tinst = _gvn.type(cipherBlockChaining_object)->isa_instptr();
8089   assert(tinst != nullptr, "CBC obj is null");
8090   assert(tinst->is_loaded(), "CBC obj is not loaded");
8091   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8092   assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
8093 
8094   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8095   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
8096   const TypeOopPtr* xtype = aklass->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
8097   Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
8098   aescrypt_object = _gvn.transform(aescrypt_object);
8099 
8100   // we need to get the start of the aescrypt_object's expanded key array
8101   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object, is_decrypt);
8102   if (k_start == nullptr) return false;
8103 
8104   // similarly, get the start address of the r vector
8105   Node* objRvec = load_field_from_object(cipherBlockChaining_object, "r", "[B");
8106   if (objRvec == nullptr) return false;
8107   Node* r_start = array_element_address(objRvec, intcon(0), T_BYTE);
8108 
8109   // Call the stub, passing src_start, dest_start, k_start, r_start and src_len
8110   Node* cbcCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
8111                                      OptoRuntime::cipherBlockChaining_aescrypt_Type(),
8112                                      stubAddr, stubName, TypePtr::BOTTOM,
8113                                      src_start, dest_start, k_start, r_start, len);
8114 
8115   // return cipher length (int)
8116   Node* retvalue = _gvn.transform(new ProjNode(cbcCrypt, TypeFunc::Parms));
8117   set_result(retvalue);
8118   return true;
8119 }
8120 
8121 //------------------------------inline_electronicCodeBook_AESCrypt-----------------------
8122 bool LibraryCallKit::inline_electronicCodeBook_AESCrypt(vmIntrinsics::ID id) {
8123   address stubAddr = nullptr;
8124   const char *stubName = nullptr;
8125   bool is_decrypt = false;
8126   assert(UseAES, "need AES instruction support");
8127 
8128   switch (id) {
8129   case vmIntrinsics::_electronicCodeBook_encryptAESCrypt:
8130     stubAddr = StubRoutines::electronicCodeBook_encryptAESCrypt();
8131     stubName = "electronicCodeBook_encryptAESCrypt";
8132     break;
8133   case vmIntrinsics::_electronicCodeBook_decryptAESCrypt:
8134     stubAddr = StubRoutines::electronicCodeBook_decryptAESCrypt();
8135     stubName = "electronicCodeBook_decryptAESCrypt";
8136     is_decrypt = true;
8137     break;
8138   default:
8139     break;
8140   }
8141 
8142   if (stubAddr == nullptr) return false;
8143 
8144   Node* electronicCodeBook_object = argument(0);
8145   Node* src                       = argument(1);
8146   Node* src_offset                = argument(2);
8147   Node* len                       = argument(3);
8148   Node* dest                      = argument(4);
8149   Node* dest_offset               = argument(5);
8150 
8151   // (1) src and dest are arrays.
8152   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
8153   const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
8154   assert( src_type != nullptr &&  src_type->elem() != Type::BOTTOM &&
8155          dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
8156 
8157   // checks are the responsibility of the caller
8158   Node* src_start = src;
8159   Node* dest_start = dest;
8160   if (src_offset != nullptr || dest_offset != nullptr) {
8161     assert(src_offset != nullptr && dest_offset != nullptr, "");
8162     src_start = array_element_address(src, src_offset, T_BYTE);
8163     dest_start = array_element_address(dest, dest_offset, T_BYTE);
8164   }
8165 
8166   // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
8167   // (because of the predicated logic executed earlier).
8168   // so we cast it here safely.
8169   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
8170 
8171   Node* embeddedCipherObj = load_field_from_object(electronicCodeBook_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8172   if (embeddedCipherObj == nullptr) return false;
8173 
8174   // cast it to what we know it will be at runtime
8175   const TypeInstPtr* tinst = _gvn.type(electronicCodeBook_object)->isa_instptr();
8176   assert(tinst != nullptr, "ECB obj is null");
8177   assert(tinst->is_loaded(), "ECB obj is not loaded");
8178   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8179   assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
8180 
8181   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8182   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
8183   const TypeOopPtr* xtype = aklass->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
8184   Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
8185   aescrypt_object = _gvn.transform(aescrypt_object);
8186 
8187   // we need to get the start of the aescrypt_object's expanded key array
8188   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object, is_decrypt);
8189   if (k_start == nullptr) return false;
8190 
8191   // Call the stub, passing src_start, dest_start, k_start, r_start and src_len
8192   Node* ecbCrypt = make_runtime_call(RC_LEAF | RC_NO_FP,
8193                                      OptoRuntime::electronicCodeBook_aescrypt_Type(),
8194                                      stubAddr, stubName, TypePtr::BOTTOM,
8195                                      src_start, dest_start, k_start, len);
8196 
8197   // return cipher length (int)
8198   Node* retvalue = _gvn.transform(new ProjNode(ecbCrypt, TypeFunc::Parms));
8199   set_result(retvalue);
8200   return true;
8201 }
8202 
8203 //------------------------------inline_counterMode_AESCrypt-----------------------
8204 bool LibraryCallKit::inline_counterMode_AESCrypt(vmIntrinsics::ID id) {
8205   assert(UseAES, "need AES instruction support");
8206   if (!UseAESCTRIntrinsics) return false;
8207 
8208   address stubAddr = nullptr;
8209   const char *stubName = nullptr;
8210   if (id == vmIntrinsics::_counterMode_AESCrypt) {
8211     stubAddr = StubRoutines::counterMode_AESCrypt();
8212     stubName = "counterMode_AESCrypt";
8213   }
8214   if (stubAddr == nullptr) return false;
8215 
8216   Node* counterMode_object = argument(0);
8217   Node* src = argument(1);
8218   Node* src_offset = argument(2);
8219   Node* len = argument(3);
8220   Node* dest = argument(4);
8221   Node* dest_offset = argument(5);
8222 
8223   // (1) src and dest are arrays.
8224   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
8225   const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
8226   assert( src_type != nullptr &&  src_type->elem() != Type::BOTTOM &&
8227          dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
8228 
8229   // checks are the responsibility of the caller
8230   Node* src_start = src;
8231   Node* dest_start = dest;
8232   if (src_offset != nullptr || dest_offset != nullptr) {
8233     assert(src_offset != nullptr && dest_offset != nullptr, "");
8234     src_start = array_element_address(src, src_offset, T_BYTE);
8235     dest_start = array_element_address(dest, dest_offset, T_BYTE);
8236   }
8237 
8238   // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
8239   // (because of the predicated logic executed earlier).
8240   // so we cast it here safely.
8241   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
8242   Node* embeddedCipherObj = load_field_from_object(counterMode_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8243   if (embeddedCipherObj == nullptr) return false;
8244   // cast it to what we know it will be at runtime
8245   const TypeInstPtr* tinst = _gvn.type(counterMode_object)->isa_instptr();
8246   assert(tinst != nullptr, "CTR obj is null");
8247   assert(tinst->is_loaded(), "CTR obj is not loaded");
8248   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8249   assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
8250   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8251   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
8252   const TypeOopPtr* xtype = aklass->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
8253   Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
8254   aescrypt_object = _gvn.transform(aescrypt_object);
8255   // we need to get the start of the aescrypt_object's expanded key array
8256   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object, /* is_decrypt */ false);
8257   if (k_start == nullptr) return false;
8258   // similarly, get the start address of the r vector
8259   Node* obj_counter = load_field_from_object(counterMode_object, "counter", "[B");
8260   if (obj_counter == nullptr) return false;
8261   Node* cnt_start = array_element_address(obj_counter, intcon(0), T_BYTE);
8262 
8263   Node* saved_encCounter = load_field_from_object(counterMode_object, "encryptedCounter", "[B");
8264   if (saved_encCounter == nullptr) return false;
8265   Node* saved_encCounter_start = array_element_address(saved_encCounter, intcon(0), T_BYTE);
8266   Node* used = field_address_from_object(counterMode_object, "used", "I", /*is_exact*/ false);
8267 
8268   // Call the stub, passing src_start, dest_start, k_start, r_start and src_len
8269   Node* ctrCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
8270                                      OptoRuntime::counterMode_aescrypt_Type(),
8271                                      stubAddr, stubName, TypePtr::BOTTOM,
8272                                      src_start, dest_start, k_start, cnt_start, len, saved_encCounter_start, used);
8273 
8274   // return cipher length (int)
8275   Node* retvalue = _gvn.transform(new ProjNode(ctrCrypt, TypeFunc::Parms));
8276   set_result(retvalue);
8277   return true;
8278 }
8279 
8280 //------------------------------get_key_start_from_aescrypt_object-----------------------
8281 Node* LibraryCallKit::get_key_start_from_aescrypt_object(Node* aescrypt_object, bool is_decrypt) {
8282   // MixColumns for decryption can be reduced by preprocessing MixColumns with round keys.
8283   // Intel's extension is based on this optimization and AESCrypt generates round keys by preprocessing MixColumns.
8284   // However, ppc64 vncipher processes MixColumns and requires the same round keys with encryption.
8285   // The following platform specific stubs of encryption and decryption use the same round keys.
8286 #if defined(PPC64) || defined(S390) || defined(RISCV64)
8287   bool use_decryption_key = false;
8288 #else
8289   bool use_decryption_key = is_decrypt;
8290 #endif
8291   Node* objAESCryptKey = load_field_from_object(aescrypt_object, use_decryption_key ? "sessionKd" : "sessionKe", "[I");
8292   assert(objAESCryptKey != nullptr, "wrong version of com.sun.crypto.provider.AES_Crypt");
8293   if (objAESCryptKey == nullptr) return (Node *) nullptr;
8294 
8295   // now have the array, need to get the start address of the selected key array
8296   Node* k_start = array_element_address(objAESCryptKey, intcon(0), T_INT);
8297   return k_start;
8298 }
8299 
8300 //----------------------------inline_cipherBlockChaining_AESCrypt_predicate----------------------------
8301 // Return node representing slow path of predicate check.
8302 // the pseudo code we want to emulate with this predicate is:
8303 // for encryption:
8304 //    if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
8305 // for decryption:
8306 //    if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
8307 //    note cipher==plain is more conservative than the original java code but that's OK
8308 //
8309 Node* LibraryCallKit::inline_cipherBlockChaining_AESCrypt_predicate(bool decrypting) {
8310   // The receiver was checked for null already.
8311   Node* objCBC = argument(0);
8312 
8313   Node* src = argument(1);
8314   Node* dest = argument(4);
8315 
8316   // Load embeddedCipher field of CipherBlockChaining object.
8317   Node* embeddedCipherObj = load_field_from_object(objCBC, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8318 
8319   // get AESCrypt klass for instanceOf check
8320   // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
8321   // will have same classloader as CipherBlockChaining object
8322   const TypeInstPtr* tinst = _gvn.type(objCBC)->isa_instptr();
8323   assert(tinst != nullptr, "CBCobj is null");
8324   assert(tinst->is_loaded(), "CBCobj is not loaded");
8325 
8326   // we want to do an instanceof comparison against the AESCrypt class
8327   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8328   if (!klass_AESCrypt->is_loaded()) {
8329     // if AESCrypt is not even loaded, we never take the intrinsic fast path
8330     Node* ctrl = control();
8331     set_control(top()); // no regular fast path
8332     return ctrl;
8333   }
8334 
8335   src = must_be_not_null(src, true);
8336   dest = must_be_not_null(dest, true);
8337 
8338   // Resolve oops to stable for CmpP below.
8339   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8340 
8341   Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
8342   Node* cmp_instof  = _gvn.transform(new CmpINode(instof, intcon(1)));
8343   Node* bool_instof  = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
8344 
8345   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
8346 
8347   // for encryption, we are done
8348   if (!decrypting)
8349     return instof_false;  // even if it is null
8350 
8351   // for decryption, we need to add a further check to avoid
8352   // taking the intrinsic path when cipher and plain are the same
8353   // see the original java code for why.
8354   RegionNode* region = new RegionNode(3);
8355   region->init_req(1, instof_false);
8356 
8357   Node* cmp_src_dest = _gvn.transform(new CmpPNode(src, dest));
8358   Node* bool_src_dest = _gvn.transform(new BoolNode(cmp_src_dest, BoolTest::eq));
8359   Node* src_dest_conjoint = generate_guard(bool_src_dest, nullptr, PROB_MIN);
8360   region->init_req(2, src_dest_conjoint);
8361 
8362   record_for_igvn(region);
8363   return _gvn.transform(region);
8364 }
8365 
8366 //----------------------------inline_electronicCodeBook_AESCrypt_predicate----------------------------
8367 // Return node representing slow path of predicate check.
8368 // the pseudo code we want to emulate with this predicate is:
8369 // for encryption:
8370 //    if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
8371 // for decryption:
8372 //    if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
8373 //    note cipher==plain is more conservative than the original java code but that's OK
8374 //
8375 Node* LibraryCallKit::inline_electronicCodeBook_AESCrypt_predicate(bool decrypting) {
8376   // The receiver was checked for null already.
8377   Node* objECB = argument(0);
8378 
8379   // Load embeddedCipher field of ElectronicCodeBook object.
8380   Node* embeddedCipherObj = load_field_from_object(objECB, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8381 
8382   // get AESCrypt klass for instanceOf check
8383   // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
8384   // will have same classloader as ElectronicCodeBook object
8385   const TypeInstPtr* tinst = _gvn.type(objECB)->isa_instptr();
8386   assert(tinst != nullptr, "ECBobj is null");
8387   assert(tinst->is_loaded(), "ECBobj is not loaded");
8388 
8389   // we want to do an instanceof comparison against the AESCrypt class
8390   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8391   if (!klass_AESCrypt->is_loaded()) {
8392     // if AESCrypt is not even loaded, we never take the intrinsic fast path
8393     Node* ctrl = control();
8394     set_control(top()); // no regular fast path
8395     return ctrl;
8396   }
8397   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8398 
8399   Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
8400   Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
8401   Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
8402 
8403   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
8404 
8405   // for encryption, we are done
8406   if (!decrypting)
8407     return instof_false;  // even if it is null
8408 
8409   // for decryption, we need to add a further check to avoid
8410   // taking the intrinsic path when cipher and plain are the same
8411   // see the original java code for why.
8412   RegionNode* region = new RegionNode(3);
8413   region->init_req(1, instof_false);
8414   Node* src = argument(1);
8415   Node* dest = argument(4);
8416   Node* cmp_src_dest = _gvn.transform(new CmpPNode(src, dest));
8417   Node* bool_src_dest = _gvn.transform(new BoolNode(cmp_src_dest, BoolTest::eq));
8418   Node* src_dest_conjoint = generate_guard(bool_src_dest, nullptr, PROB_MIN);
8419   region->init_req(2, src_dest_conjoint);
8420 
8421   record_for_igvn(region);
8422   return _gvn.transform(region);
8423 }
8424 
8425 //----------------------------inline_counterMode_AESCrypt_predicate----------------------------
8426 // Return node representing slow path of predicate check.
8427 // the pseudo code we want to emulate with this predicate is:
8428 // for encryption:
8429 //    if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
8430 // for decryption:
8431 //    if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
8432 //    note cipher==plain is more conservative than the original java code but that's OK
8433 //
8434 
8435 Node* LibraryCallKit::inline_counterMode_AESCrypt_predicate() {
8436   // The receiver was checked for null already.
8437   Node* objCTR = argument(0);
8438 
8439   // Load embeddedCipher field of CipherBlockChaining object.
8440   Node* embeddedCipherObj = load_field_from_object(objCTR, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8441 
8442   // get AESCrypt klass for instanceOf check
8443   // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
8444   // will have same classloader as CipherBlockChaining object
8445   const TypeInstPtr* tinst = _gvn.type(objCTR)->isa_instptr();
8446   assert(tinst != nullptr, "CTRobj is null");
8447   assert(tinst->is_loaded(), "CTRobj is not loaded");
8448 
8449   // we want to do an instanceof comparison against the AESCrypt class
8450   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8451   if (!klass_AESCrypt->is_loaded()) {
8452     // if AESCrypt is not even loaded, we never take the intrinsic fast path
8453     Node* ctrl = control();
8454     set_control(top()); // no regular fast path
8455     return ctrl;
8456   }
8457 
8458   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8459   Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
8460   Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
8461   Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
8462   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
8463 
8464   return instof_false; // even if it is null
8465 }
8466 
8467 //------------------------------inline_ghash_processBlocks
8468 bool LibraryCallKit::inline_ghash_processBlocks() {
8469   address stubAddr;
8470   const char *stubName;
8471   assert(UseGHASHIntrinsics, "need GHASH intrinsics support");
8472 
8473   stubAddr = StubRoutines::ghash_processBlocks();
8474   stubName = "ghash_processBlocks";
8475 
8476   Node* data           = argument(0);
8477   Node* offset         = argument(1);
8478   Node* len            = argument(2);
8479   Node* state          = argument(3);
8480   Node* subkeyH        = argument(4);
8481 
8482   state = must_be_not_null(state, true);
8483   subkeyH = must_be_not_null(subkeyH, true);
8484   data = must_be_not_null(data, true);
8485 
8486   Node* state_start  = array_element_address(state, intcon(0), T_LONG);
8487   assert(state_start, "state is null");
8488   Node* subkeyH_start  = array_element_address(subkeyH, intcon(0), T_LONG);
8489   assert(subkeyH_start, "subkeyH is null");
8490   Node* data_start  = array_element_address(data, offset, T_BYTE);
8491   assert(data_start, "data is null");
8492 
8493   Node* ghash = make_runtime_call(RC_LEAF|RC_NO_FP,
8494                                   OptoRuntime::ghash_processBlocks_Type(),
8495                                   stubAddr, stubName, TypePtr::BOTTOM,
8496                                   state_start, subkeyH_start, data_start, len);
8497   return true;
8498 }
8499 
8500 //------------------------------inline_chacha20Block
8501 bool LibraryCallKit::inline_chacha20Block() {
8502   address stubAddr;
8503   const char *stubName;
8504   assert(UseChaCha20Intrinsics, "need ChaCha20 intrinsics support");
8505 
8506   stubAddr = StubRoutines::chacha20Block();
8507   stubName = "chacha20Block";
8508 
8509   Node* state          = argument(0);
8510   Node* result         = argument(1);
8511 
8512   state = must_be_not_null(state, true);
8513   result = must_be_not_null(result, true);
8514 
8515   Node* state_start  = array_element_address(state, intcon(0), T_INT);
8516   assert(state_start, "state is null");
8517   Node* result_start  = array_element_address(result, intcon(0), T_BYTE);
8518   assert(result_start, "result is null");
8519 
8520   Node* cc20Blk = make_runtime_call(RC_LEAF|RC_NO_FP,
8521                                   OptoRuntime::chacha20Block_Type(),
8522                                   stubAddr, stubName, TypePtr::BOTTOM,
8523                                   state_start, result_start);
8524   // return key stream length (int)
8525   Node* retvalue = _gvn.transform(new ProjNode(cc20Blk, TypeFunc::Parms));
8526   set_result(retvalue);
8527   return true;
8528 }
8529 
8530 //------------------------------inline_kyberNtt
8531 bool LibraryCallKit::inline_kyberNtt() {
8532   address stubAddr;
8533   const char *stubName;
8534   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8535   assert(callee()->signature()->size() == 2, "kyberNtt has 2 parameters");
8536 
8537   stubAddr = StubRoutines::kyberNtt();
8538   stubName = "kyberNtt";
8539   if (!stubAddr) return false;
8540 
8541   Node* coeffs          = argument(0);
8542   Node* ntt_zetas        = argument(1);
8543 
8544   coeffs = must_be_not_null(coeffs, true);
8545   ntt_zetas = must_be_not_null(ntt_zetas, true);
8546 
8547   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_SHORT);
8548   assert(coeffs_start, "coeffs is null");
8549   Node* ntt_zetas_start  = array_element_address(ntt_zetas, intcon(0), T_SHORT);
8550   assert(ntt_zetas_start, "ntt_zetas is null");
8551   Node* kyberNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
8552                                   OptoRuntime::kyberNtt_Type(),
8553                                   stubAddr, stubName, TypePtr::BOTTOM,
8554                                   coeffs_start, ntt_zetas_start);
8555   // return an int
8556   Node* retvalue = _gvn.transform(new ProjNode(kyberNtt, TypeFunc::Parms));
8557   set_result(retvalue);
8558   return true;
8559 }
8560 
8561 //------------------------------inline_kyberInverseNtt
8562 bool LibraryCallKit::inline_kyberInverseNtt() {
8563   address stubAddr;
8564   const char *stubName;
8565   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8566   assert(callee()->signature()->size() == 2, "kyberInverseNtt has 2 parameters");
8567 
8568   stubAddr = StubRoutines::kyberInverseNtt();
8569   stubName = "kyberInverseNtt";
8570   if (!stubAddr) return false;
8571 
8572   Node* coeffs          = argument(0);
8573   Node* zetas           = argument(1);
8574 
8575   coeffs = must_be_not_null(coeffs, true);
8576   zetas = must_be_not_null(zetas, true);
8577 
8578   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_SHORT);
8579   assert(coeffs_start, "coeffs is null");
8580   Node* zetas_start  = array_element_address(zetas, intcon(0), T_SHORT);
8581   assert(zetas_start, "inverseNtt_zetas is null");
8582   Node* kyberInverseNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
8583                                   OptoRuntime::kyberInverseNtt_Type(),
8584                                   stubAddr, stubName, TypePtr::BOTTOM,
8585                                   coeffs_start, zetas_start);
8586 
8587   // return an int
8588   Node* retvalue = _gvn.transform(new ProjNode(kyberInverseNtt, TypeFunc::Parms));
8589   set_result(retvalue);
8590   return true;
8591 }
8592 
8593 //------------------------------inline_kyberNttMult
8594 bool LibraryCallKit::inline_kyberNttMult() {
8595   address stubAddr;
8596   const char *stubName;
8597   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8598   assert(callee()->signature()->size() == 4, "kyberNttMult has 4 parameters");
8599 
8600   stubAddr = StubRoutines::kyberNttMult();
8601   stubName = "kyberNttMult";
8602   if (!stubAddr) return false;
8603 
8604   Node* result          = argument(0);
8605   Node* ntta            = argument(1);
8606   Node* nttb            = argument(2);
8607   Node* zetas           = argument(3);
8608 
8609   result = must_be_not_null(result, true);
8610   ntta = must_be_not_null(ntta, true);
8611   nttb = must_be_not_null(nttb, true);
8612   zetas = must_be_not_null(zetas, true);
8613 
8614   Node* result_start  = array_element_address(result, intcon(0), T_SHORT);
8615   assert(result_start, "result is null");
8616   Node* ntta_start  = array_element_address(ntta, intcon(0), T_SHORT);
8617   assert(ntta_start, "ntta is null");
8618   Node* nttb_start  = array_element_address(nttb, intcon(0), T_SHORT);
8619   assert(nttb_start, "nttb is null");
8620   Node* zetas_start  = array_element_address(zetas, intcon(0), T_SHORT);
8621   assert(zetas_start, "nttMult_zetas is null");
8622   Node* kyberNttMult = make_runtime_call(RC_LEAF|RC_NO_FP,
8623                                   OptoRuntime::kyberNttMult_Type(),
8624                                   stubAddr, stubName, TypePtr::BOTTOM,
8625                                   result_start, ntta_start, nttb_start,
8626                                   zetas_start);
8627 
8628   // return an int
8629   Node* retvalue = _gvn.transform(new ProjNode(kyberNttMult, TypeFunc::Parms));
8630   set_result(retvalue);
8631 
8632   return true;
8633 }
8634 
8635 //------------------------------inline_kyberAddPoly_2
8636 bool LibraryCallKit::inline_kyberAddPoly_2() {
8637   address stubAddr;
8638   const char *stubName;
8639   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8640   assert(callee()->signature()->size() == 3, "kyberAddPoly_2 has 3 parameters");
8641 
8642   stubAddr = StubRoutines::kyberAddPoly_2();
8643   stubName = "kyberAddPoly_2";
8644   if (!stubAddr) return false;
8645 
8646   Node* result          = argument(0);
8647   Node* a               = argument(1);
8648   Node* b               = argument(2);
8649 
8650   result = must_be_not_null(result, true);
8651   a = must_be_not_null(a, true);
8652   b = must_be_not_null(b, 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* kyberAddPoly_2 = make_runtime_call(RC_LEAF|RC_NO_FP,
8661                                   OptoRuntime::kyberAddPoly_2_Type(),
8662                                   stubAddr, stubName, TypePtr::BOTTOM,
8663                                   result_start, a_start, b_start);
8664   // return an int
8665   Node* retvalue = _gvn.transform(new ProjNode(kyberAddPoly_2, TypeFunc::Parms));
8666   set_result(retvalue);
8667   return true;
8668 }
8669 
8670 //------------------------------inline_kyberAddPoly_3
8671 bool LibraryCallKit::inline_kyberAddPoly_3() {
8672   address stubAddr;
8673   const char *stubName;
8674   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8675   assert(callee()->signature()->size() == 4, "kyberAddPoly_3 has 4 parameters");
8676 
8677   stubAddr = StubRoutines::kyberAddPoly_3();
8678   stubName = "kyberAddPoly_3";
8679   if (!stubAddr) return false;
8680 
8681   Node* result          = argument(0);
8682   Node* a               = argument(1);
8683   Node* b               = argument(2);
8684   Node* c               = argument(3);
8685 
8686   result = must_be_not_null(result, true);
8687   a = must_be_not_null(a, true);
8688   b = must_be_not_null(b, true);
8689   c = must_be_not_null(c, true);
8690 
8691   Node* result_start  = array_element_address(result, intcon(0), T_SHORT);
8692   assert(result_start, "result is null");
8693   Node* a_start  = array_element_address(a, intcon(0), T_SHORT);
8694   assert(a_start, "a is null");
8695   Node* b_start  = array_element_address(b, intcon(0), T_SHORT);
8696   assert(b_start, "b is null");
8697   Node* c_start  = array_element_address(c, intcon(0), T_SHORT);
8698   assert(c_start, "c is null");
8699   Node* kyberAddPoly_3 = make_runtime_call(RC_LEAF|RC_NO_FP,
8700                                   OptoRuntime::kyberAddPoly_3_Type(),
8701                                   stubAddr, stubName, TypePtr::BOTTOM,
8702                                   result_start, a_start, b_start, c_start);
8703   // return an int
8704   Node* retvalue = _gvn.transform(new ProjNode(kyberAddPoly_3, TypeFunc::Parms));
8705   set_result(retvalue);
8706   return true;
8707 }
8708 
8709 //------------------------------inline_kyber12To16
8710 bool LibraryCallKit::inline_kyber12To16() {
8711   address stubAddr;
8712   const char *stubName;
8713   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8714   assert(callee()->signature()->size() == 4, "kyber12To16 has 4 parameters");
8715 
8716   stubAddr = StubRoutines::kyber12To16();
8717   stubName = "kyber12To16";
8718   if (!stubAddr) return false;
8719 
8720   Node* condensed       = argument(0);
8721   Node* condensedOffs   = argument(1);
8722   Node* parsed          = argument(2);
8723   Node* parsedLength    = argument(3);
8724 
8725   condensed = must_be_not_null(condensed, true);
8726   parsed = must_be_not_null(parsed, true);
8727 
8728   Node* condensed_start  = array_element_address(condensed, intcon(0), T_BYTE);
8729   assert(condensed_start, "condensed is null");
8730   Node* parsed_start  = array_element_address(parsed, intcon(0), T_SHORT);
8731   assert(parsed_start, "parsed is null");
8732   Node* kyber12To16 = make_runtime_call(RC_LEAF|RC_NO_FP,
8733                                   OptoRuntime::kyber12To16_Type(),
8734                                   stubAddr, stubName, TypePtr::BOTTOM,
8735                                   condensed_start, condensedOffs, parsed_start, parsedLength);
8736   // return an int
8737   Node* retvalue = _gvn.transform(new ProjNode(kyber12To16, TypeFunc::Parms));
8738   set_result(retvalue);
8739   return true;
8740 
8741 }
8742 
8743 //------------------------------inline_kyberBarrettReduce
8744 bool LibraryCallKit::inline_kyberBarrettReduce() {
8745   address stubAddr;
8746   const char *stubName;
8747   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8748   assert(callee()->signature()->size() == 1, "kyberBarrettReduce has 1 parameters");
8749 
8750   stubAddr = StubRoutines::kyberBarrettReduce();
8751   stubName = "kyberBarrettReduce";
8752   if (!stubAddr) return false;
8753 
8754   Node* coeffs          = argument(0);
8755 
8756   coeffs = must_be_not_null(coeffs, true);
8757 
8758   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_SHORT);
8759   assert(coeffs_start, "coeffs is null");
8760   Node* kyberBarrettReduce = make_runtime_call(RC_LEAF|RC_NO_FP,
8761                                   OptoRuntime::kyberBarrettReduce_Type(),
8762                                   stubAddr, stubName, TypePtr::BOTTOM,
8763                                   coeffs_start);
8764   // return an int
8765   Node* retvalue = _gvn.transform(new ProjNode(kyberBarrettReduce, TypeFunc::Parms));
8766   set_result(retvalue);
8767   return true;
8768 }
8769 
8770 //------------------------------inline_dilithiumAlmostNtt
8771 bool LibraryCallKit::inline_dilithiumAlmostNtt() {
8772   address stubAddr;
8773   const char *stubName;
8774   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8775   assert(callee()->signature()->size() == 2, "dilithiumAlmostNtt has 2 parameters");
8776 
8777   stubAddr = StubRoutines::dilithiumAlmostNtt();
8778   stubName = "dilithiumAlmostNtt";
8779   if (!stubAddr) return false;
8780 
8781   Node* coeffs          = argument(0);
8782   Node* ntt_zetas        = argument(1);
8783 
8784   coeffs = must_be_not_null(coeffs, true);
8785   ntt_zetas = must_be_not_null(ntt_zetas, true);
8786 
8787   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_INT);
8788   assert(coeffs_start, "coeffs is null");
8789   Node* ntt_zetas_start  = array_element_address(ntt_zetas, intcon(0), T_INT);
8790   assert(ntt_zetas_start, "ntt_zetas is null");
8791   Node* dilithiumAlmostNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
8792                                   OptoRuntime::dilithiumAlmostNtt_Type(),
8793                                   stubAddr, stubName, TypePtr::BOTTOM,
8794                                   coeffs_start, ntt_zetas_start);
8795   // return an int
8796   Node* retvalue = _gvn.transform(new ProjNode(dilithiumAlmostNtt, TypeFunc::Parms));
8797   set_result(retvalue);
8798   return true;
8799 }
8800 
8801 //------------------------------inline_dilithiumAlmostInverseNtt
8802 bool LibraryCallKit::inline_dilithiumAlmostInverseNtt() {
8803   address stubAddr;
8804   const char *stubName;
8805   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8806   assert(callee()->signature()->size() == 2, "dilithiumAlmostInverseNtt has 2 parameters");
8807 
8808   stubAddr = StubRoutines::dilithiumAlmostInverseNtt();
8809   stubName = "dilithiumAlmostInverseNtt";
8810   if (!stubAddr) return false;
8811 
8812   Node* coeffs          = argument(0);
8813   Node* zetas           = argument(1);
8814 
8815   coeffs = must_be_not_null(coeffs, true);
8816   zetas = must_be_not_null(zetas, true);
8817 
8818   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_INT);
8819   assert(coeffs_start, "coeffs is null");
8820   Node* zetas_start  = array_element_address(zetas, intcon(0), T_INT);
8821   assert(zetas_start, "inverseNtt_zetas is null");
8822   Node* dilithiumAlmostInverseNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
8823                                   OptoRuntime::dilithiumAlmostInverseNtt_Type(),
8824                                   stubAddr, stubName, TypePtr::BOTTOM,
8825                                   coeffs_start, zetas_start);
8826   // return an int
8827   Node* retvalue = _gvn.transform(new ProjNode(dilithiumAlmostInverseNtt, TypeFunc::Parms));
8828   set_result(retvalue);
8829   return true;
8830 }
8831 
8832 //------------------------------inline_dilithiumNttMult
8833 bool LibraryCallKit::inline_dilithiumNttMult() {
8834   address stubAddr;
8835   const char *stubName;
8836   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8837   assert(callee()->signature()->size() == 3, "dilithiumNttMult has 3 parameters");
8838 
8839   stubAddr = StubRoutines::dilithiumNttMult();
8840   stubName = "dilithiumNttMult";
8841   if (!stubAddr) return false;
8842 
8843   Node* result          = argument(0);
8844   Node* ntta            = argument(1);
8845   Node* nttb            = argument(2);
8846   Node* zetas           = argument(3);
8847 
8848   result = must_be_not_null(result, true);
8849   ntta = must_be_not_null(ntta, true);
8850   nttb = must_be_not_null(nttb, true);
8851   zetas = must_be_not_null(zetas, true);
8852 
8853   Node* result_start  = array_element_address(result, intcon(0), T_INT);
8854   assert(result_start, "result is null");
8855   Node* ntta_start  = array_element_address(ntta, intcon(0), T_INT);
8856   assert(ntta_start, "ntta is null");
8857   Node* nttb_start  = array_element_address(nttb, intcon(0), T_INT);
8858   assert(nttb_start, "nttb is null");
8859   Node* dilithiumNttMult = make_runtime_call(RC_LEAF|RC_NO_FP,
8860                                   OptoRuntime::dilithiumNttMult_Type(),
8861                                   stubAddr, stubName, TypePtr::BOTTOM,
8862                                   result_start, ntta_start, nttb_start);
8863 
8864   // return an int
8865   Node* retvalue = _gvn.transform(new ProjNode(dilithiumNttMult, TypeFunc::Parms));
8866   set_result(retvalue);
8867 
8868   return true;
8869 }
8870 
8871 //------------------------------inline_dilithiumMontMulByConstant
8872 bool LibraryCallKit::inline_dilithiumMontMulByConstant() {
8873   address stubAddr;
8874   const char *stubName;
8875   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8876   assert(callee()->signature()->size() == 2, "dilithiumMontMulByConstant has 2 parameters");
8877 
8878   stubAddr = StubRoutines::dilithiumMontMulByConstant();
8879   stubName = "dilithiumMontMulByConstant";
8880   if (!stubAddr) return false;
8881 
8882   Node* coeffs          = argument(0);
8883   Node* constant        = argument(1);
8884 
8885   coeffs = must_be_not_null(coeffs, true);
8886 
8887   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_INT);
8888   assert(coeffs_start, "coeffs is null");
8889   Node* dilithiumMontMulByConstant = make_runtime_call(RC_LEAF|RC_NO_FP,
8890                                   OptoRuntime::dilithiumMontMulByConstant_Type(),
8891                                   stubAddr, stubName, TypePtr::BOTTOM,
8892                                   coeffs_start, constant);
8893 
8894   // return an int
8895   Node* retvalue = _gvn.transform(new ProjNode(dilithiumMontMulByConstant, TypeFunc::Parms));
8896   set_result(retvalue);
8897   return true;
8898 }
8899 
8900 
8901 //------------------------------inline_dilithiumDecomposePoly
8902 bool LibraryCallKit::inline_dilithiumDecomposePoly() {
8903   address stubAddr;
8904   const char *stubName;
8905   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8906   assert(callee()->signature()->size() == 5, "dilithiumDecomposePoly has 5 parameters");
8907 
8908   stubAddr = StubRoutines::dilithiumDecomposePoly();
8909   stubName = "dilithiumDecomposePoly";
8910   if (!stubAddr) return false;
8911 
8912   Node* input          = argument(0);
8913   Node* lowPart        = argument(1);
8914   Node* highPart       = argument(2);
8915   Node* twoGamma2      = argument(3);
8916   Node* multiplier     = argument(4);
8917 
8918   input = must_be_not_null(input, true);
8919   lowPart = must_be_not_null(lowPart, true);
8920   highPart = must_be_not_null(highPart, true);
8921 
8922   Node* input_start  = array_element_address(input, intcon(0), T_INT);
8923   assert(input_start, "input is null");
8924   Node* lowPart_start  = array_element_address(lowPart, intcon(0), T_INT);
8925   assert(lowPart_start, "lowPart is null");
8926   Node* highPart_start  = array_element_address(highPart, intcon(0), T_INT);
8927   assert(highPart_start, "highPart is null");
8928 
8929   Node* dilithiumDecomposePoly = make_runtime_call(RC_LEAF|RC_NO_FP,
8930                                   OptoRuntime::dilithiumDecomposePoly_Type(),
8931                                   stubAddr, stubName, TypePtr::BOTTOM,
8932                                   input_start, lowPart_start, highPart_start,
8933                                   twoGamma2, multiplier);
8934 
8935   // return an int
8936   Node* retvalue = _gvn.transform(new ProjNode(dilithiumDecomposePoly, TypeFunc::Parms));
8937   set_result(retvalue);
8938   return true;
8939 }
8940 
8941 bool LibraryCallKit::inline_base64_encodeBlock() {
8942   address stubAddr;
8943   const char *stubName;
8944   assert(UseBASE64Intrinsics, "need Base64 intrinsics support");
8945   assert(callee()->signature()->size() == 6, "base64_encodeBlock has 6 parameters");
8946   stubAddr = StubRoutines::base64_encodeBlock();
8947   stubName = "encodeBlock";
8948 
8949   if (!stubAddr) return false;
8950   Node* base64obj = argument(0);
8951   Node* src = argument(1);
8952   Node* offset = argument(2);
8953   Node* len = argument(3);
8954   Node* dest = argument(4);
8955   Node* dp = argument(5);
8956   Node* isURL = argument(6);
8957 
8958   src = must_be_not_null(src, true);
8959   dest = must_be_not_null(dest, true);
8960 
8961   Node* src_start = array_element_address(src, intcon(0), T_BYTE);
8962   assert(src_start, "source array is null");
8963   Node* dest_start = array_element_address(dest, intcon(0), T_BYTE);
8964   assert(dest_start, "destination array is null");
8965 
8966   Node* base64 = make_runtime_call(RC_LEAF,
8967                                    OptoRuntime::base64_encodeBlock_Type(),
8968                                    stubAddr, stubName, TypePtr::BOTTOM,
8969                                    src_start, offset, len, dest_start, dp, isURL);
8970   return true;
8971 }
8972 
8973 bool LibraryCallKit::inline_base64_decodeBlock() {
8974   address stubAddr;
8975   const char *stubName;
8976   assert(UseBASE64Intrinsics, "need Base64 intrinsics support");
8977   assert(callee()->signature()->size() == 7, "base64_decodeBlock has 7 parameters");
8978   stubAddr = StubRoutines::base64_decodeBlock();
8979   stubName = "decodeBlock";
8980 
8981   if (!stubAddr) return false;
8982   Node* base64obj = argument(0);
8983   Node* src = argument(1);
8984   Node* src_offset = argument(2);
8985   Node* len = argument(3);
8986   Node* dest = argument(4);
8987   Node* dest_offset = argument(5);
8988   Node* isURL = argument(6);
8989   Node* isMIME = argument(7);
8990 
8991   src = must_be_not_null(src, true);
8992   dest = must_be_not_null(dest, true);
8993 
8994   Node* src_start = array_element_address(src, intcon(0), T_BYTE);
8995   assert(src_start, "source array is null");
8996   Node* dest_start = array_element_address(dest, intcon(0), T_BYTE);
8997   assert(dest_start, "destination array is null");
8998 
8999   Node* call = make_runtime_call(RC_LEAF,
9000                                  OptoRuntime::base64_decodeBlock_Type(),
9001                                  stubAddr, stubName, TypePtr::BOTTOM,
9002                                  src_start, src_offset, len, dest_start, dest_offset, isURL, isMIME);
9003   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
9004   set_result(result);
9005   return true;
9006 }
9007 
9008 bool LibraryCallKit::inline_poly1305_processBlocks() {
9009   address stubAddr;
9010   const char *stubName;
9011   assert(UsePoly1305Intrinsics, "need Poly intrinsics support");
9012   assert(callee()->signature()->size() == 5, "poly1305_processBlocks has %d parameters", callee()->signature()->size());
9013   stubAddr = StubRoutines::poly1305_processBlocks();
9014   stubName = "poly1305_processBlocks";
9015 
9016   if (!stubAddr) return false;
9017   null_check_receiver();  // null-check receiver
9018   if (stopped())  return true;
9019 
9020   Node* input = argument(1);
9021   Node* input_offset = argument(2);
9022   Node* len = argument(3);
9023   Node* alimbs = argument(4);
9024   Node* rlimbs = argument(5);
9025 
9026   input = must_be_not_null(input, true);
9027   alimbs = must_be_not_null(alimbs, true);
9028   rlimbs = must_be_not_null(rlimbs, true);
9029 
9030   Node* input_start = array_element_address(input, input_offset, T_BYTE);
9031   assert(input_start, "input array is null");
9032   Node* acc_start = array_element_address(alimbs, intcon(0), T_LONG);
9033   assert(acc_start, "acc array is null");
9034   Node* r_start = array_element_address(rlimbs, intcon(0), T_LONG);
9035   assert(r_start, "r array is null");
9036 
9037   Node* call = make_runtime_call(RC_LEAF | RC_NO_FP,
9038                                  OptoRuntime::poly1305_processBlocks_Type(),
9039                                  stubAddr, stubName, TypePtr::BOTTOM,
9040                                  input_start, len, acc_start, r_start);
9041   return true;
9042 }
9043 
9044 bool LibraryCallKit::inline_intpoly_montgomeryMult_P256() {
9045   address stubAddr;
9046   const char *stubName;
9047   assert(UseIntPolyIntrinsics, "need intpoly intrinsics support");
9048   assert(callee()->signature()->size() == 3, "intpoly_montgomeryMult_P256 has %d parameters", callee()->signature()->size());
9049   stubAddr = StubRoutines::intpoly_montgomeryMult_P256();
9050   stubName = "intpoly_montgomeryMult_P256";
9051 
9052   if (!stubAddr) return false;
9053   null_check_receiver();  // null-check receiver
9054   if (stopped())  return true;
9055 
9056   Node* a = argument(1);
9057   Node* b = argument(2);
9058   Node* r = argument(3);
9059 
9060   a = must_be_not_null(a, true);
9061   b = must_be_not_null(b, true);
9062   r = must_be_not_null(r, true);
9063 
9064   Node* a_start = array_element_address(a, intcon(0), T_LONG);
9065   assert(a_start, "a array is null");
9066   Node* b_start = array_element_address(b, intcon(0), T_LONG);
9067   assert(b_start, "b array is null");
9068   Node* r_start = array_element_address(r, intcon(0), T_LONG);
9069   assert(r_start, "r array is null");
9070 
9071   Node* call = make_runtime_call(RC_LEAF | RC_NO_FP,
9072                                  OptoRuntime::intpoly_montgomeryMult_P256_Type(),
9073                                  stubAddr, stubName, TypePtr::BOTTOM,
9074                                  a_start, b_start, r_start);
9075   return true;
9076 }
9077 
9078 bool LibraryCallKit::inline_intpoly_assign() {
9079   assert(UseIntPolyIntrinsics, "need intpoly intrinsics support");
9080   assert(callee()->signature()->size() == 3, "intpoly_assign has %d parameters", callee()->signature()->size());
9081   const char *stubName = "intpoly_assign";
9082   address stubAddr = StubRoutines::intpoly_assign();
9083   if (!stubAddr) return false;
9084 
9085   Node* set = argument(0);
9086   Node* a = argument(1);
9087   Node* b = argument(2);
9088   Node* arr_length = load_array_length(a);
9089 
9090   a = must_be_not_null(a, true);
9091   b = must_be_not_null(b, true);
9092 
9093   Node* a_start = array_element_address(a, intcon(0), T_LONG);
9094   assert(a_start, "a array is null");
9095   Node* b_start = array_element_address(b, intcon(0), T_LONG);
9096   assert(b_start, "b array is null");
9097 
9098   Node* call = make_runtime_call(RC_LEAF | RC_NO_FP,
9099                                  OptoRuntime::intpoly_assign_Type(),
9100                                  stubAddr, stubName, TypePtr::BOTTOM,
9101                                  set, a_start, b_start, arr_length);
9102   return true;
9103 }
9104 
9105 //------------------------------inline_digestBase_implCompress-----------------------
9106 //
9107 // Calculate MD5 for single-block byte[] array.
9108 // void com.sun.security.provider.MD5.implCompress(byte[] buf, int ofs)
9109 //
9110 // Calculate SHA (i.e., SHA-1) for single-block byte[] array.
9111 // void com.sun.security.provider.SHA.implCompress(byte[] buf, int ofs)
9112 //
9113 // Calculate SHA2 (i.e., SHA-244 or SHA-256) for single-block byte[] array.
9114 // void com.sun.security.provider.SHA2.implCompress(byte[] buf, int ofs)
9115 //
9116 // Calculate SHA5 (i.e., SHA-384 or SHA-512) for single-block byte[] array.
9117 // void com.sun.security.provider.SHA5.implCompress(byte[] buf, int ofs)
9118 //
9119 // Calculate SHA3 (i.e., SHA3-224 or SHA3-256 or SHA3-384 or SHA3-512) for single-block byte[] array.
9120 // void com.sun.security.provider.SHA3.implCompress(byte[] buf, int ofs)
9121 //
9122 bool LibraryCallKit::inline_digestBase_implCompress(vmIntrinsics::ID id) {
9123   assert(callee()->signature()->size() == 2, "sha_implCompress has 2 parameters");
9124 
9125   Node* digestBase_obj = argument(0);
9126   Node* src            = argument(1); // type oop
9127   Node* ofs            = argument(2); // type int
9128 
9129   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
9130   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
9131     // failed array check
9132     return false;
9133   }
9134   // Figure out the size and type of the elements we will be copying.
9135   BasicType src_elem = src_type->elem()->array_element_basic_type();
9136   if (src_elem != T_BYTE) {
9137     return false;
9138   }
9139   // 'src_start' points to src array + offset
9140   src = must_be_not_null(src, true);
9141   Node* src_start = array_element_address(src, ofs, src_elem);
9142   Node* state = nullptr;
9143   Node* block_size = nullptr;
9144   address stubAddr;
9145   const char *stubName;
9146 
9147   switch(id) {
9148   case vmIntrinsics::_md5_implCompress:
9149     assert(UseMD5Intrinsics, "need MD5 instruction support");
9150     state = get_state_from_digest_object(digestBase_obj, T_INT);
9151     stubAddr = StubRoutines::md5_implCompress();
9152     stubName = "md5_implCompress";
9153     break;
9154   case vmIntrinsics::_sha_implCompress:
9155     assert(UseSHA1Intrinsics, "need SHA1 instruction support");
9156     state = get_state_from_digest_object(digestBase_obj, T_INT);
9157     stubAddr = StubRoutines::sha1_implCompress();
9158     stubName = "sha1_implCompress";
9159     break;
9160   case vmIntrinsics::_sha2_implCompress:
9161     assert(UseSHA256Intrinsics, "need SHA256 instruction support");
9162     state = get_state_from_digest_object(digestBase_obj, T_INT);
9163     stubAddr = StubRoutines::sha256_implCompress();
9164     stubName = "sha256_implCompress";
9165     break;
9166   case vmIntrinsics::_sha5_implCompress:
9167     assert(UseSHA512Intrinsics, "need SHA512 instruction support");
9168     state = get_state_from_digest_object(digestBase_obj, T_LONG);
9169     stubAddr = StubRoutines::sha512_implCompress();
9170     stubName = "sha512_implCompress";
9171     break;
9172   case vmIntrinsics::_sha3_implCompress:
9173     assert(UseSHA3Intrinsics, "need SHA3 instruction support");
9174     state = get_state_from_digest_object(digestBase_obj, T_LONG);
9175     stubAddr = StubRoutines::sha3_implCompress();
9176     stubName = "sha3_implCompress";
9177     block_size = get_block_size_from_digest_object(digestBase_obj);
9178     if (block_size == nullptr) return false;
9179     break;
9180   default:
9181     fatal_unexpected_iid(id);
9182     return false;
9183   }
9184   if (state == nullptr) return false;
9185 
9186   assert(stubAddr != nullptr, "Stub %s is not generated", stubName);
9187   if (stubAddr == nullptr) return false;
9188 
9189   // Call the stub.
9190   Node* call;
9191   if (block_size == nullptr) {
9192     call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::digestBase_implCompress_Type(false),
9193                              stubAddr, stubName, TypePtr::BOTTOM,
9194                              src_start, state);
9195   } else {
9196     call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::digestBase_implCompress_Type(true),
9197                              stubAddr, stubName, TypePtr::BOTTOM,
9198                              src_start, state, block_size);
9199   }
9200 
9201   return true;
9202 }
9203 
9204 //------------------------------inline_double_keccak
9205 bool LibraryCallKit::inline_double_keccak() {
9206   address stubAddr;
9207   const char *stubName;
9208   assert(UseSHA3Intrinsics, "need SHA3 intrinsics support");
9209   assert(callee()->signature()->size() == 2, "double_keccak has 2 parameters");
9210 
9211   stubAddr = StubRoutines::double_keccak();
9212   stubName = "double_keccak";
9213   if (!stubAddr) return false;
9214 
9215   Node* status0        = argument(0);
9216   Node* status1        = argument(1);
9217 
9218   status0 = must_be_not_null(status0, true);
9219   status1 = must_be_not_null(status1, true);
9220 
9221   Node* status0_start  = array_element_address(status0, intcon(0), T_LONG);
9222   assert(status0_start, "status0 is null");
9223   Node* status1_start  = array_element_address(status1, intcon(0), T_LONG);
9224   assert(status1_start, "status1 is null");
9225   Node* double_keccak = make_runtime_call(RC_LEAF|RC_NO_FP,
9226                                   OptoRuntime::double_keccak_Type(),
9227                                   stubAddr, stubName, TypePtr::BOTTOM,
9228                                   status0_start, status1_start);
9229   // return an int
9230   Node* retvalue = _gvn.transform(new ProjNode(double_keccak, TypeFunc::Parms));
9231   set_result(retvalue);
9232   return true;
9233 }
9234 
9235 
9236 //------------------------------inline_digestBase_implCompressMB-----------------------
9237 //
9238 // Calculate MD5/SHA/SHA2/SHA5/SHA3 for multi-block byte[] array.
9239 // int com.sun.security.provider.DigestBase.implCompressMultiBlock(byte[] b, int ofs, int limit)
9240 //
9241 bool LibraryCallKit::inline_digestBase_implCompressMB(int predicate) {
9242   assert(UseMD5Intrinsics || UseSHA1Intrinsics || UseSHA256Intrinsics || UseSHA512Intrinsics || UseSHA3Intrinsics,
9243          "need MD5/SHA1/SHA256/SHA512/SHA3 instruction support");
9244   assert((uint)predicate < 5, "sanity");
9245   assert(callee()->signature()->size() == 3, "digestBase_implCompressMB has 3 parameters");
9246 
9247   Node* digestBase_obj = argument(0); // The receiver was checked for null already.
9248   Node* src            = argument(1); // byte[] array
9249   Node* ofs            = argument(2); // type int
9250   Node* limit          = argument(3); // type int
9251 
9252   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
9253   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
9254     // failed array check
9255     return false;
9256   }
9257   // Figure out the size and type of the elements we will be copying.
9258   BasicType src_elem = src_type->elem()->array_element_basic_type();
9259   if (src_elem != T_BYTE) {
9260     return false;
9261   }
9262   // 'src_start' points to src array + offset
9263   src = must_be_not_null(src, false);
9264   Node* src_start = array_element_address(src, ofs, src_elem);
9265 
9266   const char* klass_digestBase_name = nullptr;
9267   const char* stub_name = nullptr;
9268   address     stub_addr = nullptr;
9269   BasicType elem_type = T_INT;
9270 
9271   switch (predicate) {
9272   case 0:
9273     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_md5_implCompress)) {
9274       klass_digestBase_name = "sun/security/provider/MD5";
9275       stub_name = "md5_implCompressMB";
9276       stub_addr = StubRoutines::md5_implCompressMB();
9277     }
9278     break;
9279   case 1:
9280     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha_implCompress)) {
9281       klass_digestBase_name = "sun/security/provider/SHA";
9282       stub_name = "sha1_implCompressMB";
9283       stub_addr = StubRoutines::sha1_implCompressMB();
9284     }
9285     break;
9286   case 2:
9287     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha2_implCompress)) {
9288       klass_digestBase_name = "sun/security/provider/SHA2";
9289       stub_name = "sha256_implCompressMB";
9290       stub_addr = StubRoutines::sha256_implCompressMB();
9291     }
9292     break;
9293   case 3:
9294     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha5_implCompress)) {
9295       klass_digestBase_name = "sun/security/provider/SHA5";
9296       stub_name = "sha512_implCompressMB";
9297       stub_addr = StubRoutines::sha512_implCompressMB();
9298       elem_type = T_LONG;
9299     }
9300     break;
9301   case 4:
9302     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha3_implCompress)) {
9303       klass_digestBase_name = "sun/security/provider/SHA3";
9304       stub_name = "sha3_implCompressMB";
9305       stub_addr = StubRoutines::sha3_implCompressMB();
9306       elem_type = T_LONG;
9307     }
9308     break;
9309   default:
9310     fatal("unknown DigestBase intrinsic predicate: %d", predicate);
9311   }
9312   if (klass_digestBase_name != nullptr) {
9313     assert(stub_addr != nullptr, "Stub is generated");
9314     if (stub_addr == nullptr) return false;
9315 
9316     // get DigestBase klass to lookup for SHA klass
9317     const TypeInstPtr* tinst = _gvn.type(digestBase_obj)->isa_instptr();
9318     assert(tinst != nullptr, "digestBase_obj is not instance???");
9319     assert(tinst->is_loaded(), "DigestBase is not loaded");
9320 
9321     ciKlass* klass_digestBase = tinst->instance_klass()->find_klass(ciSymbol::make(klass_digestBase_name));
9322     assert(klass_digestBase->is_loaded(), "predicate checks that this class is loaded");
9323     ciInstanceKlass* instklass_digestBase = klass_digestBase->as_instance_klass();
9324     return inline_digestBase_implCompressMB(digestBase_obj, instklass_digestBase, elem_type, stub_addr, stub_name, src_start, ofs, limit);
9325   }
9326   return false;
9327 }
9328 
9329 //------------------------------inline_digestBase_implCompressMB-----------------------
9330 bool LibraryCallKit::inline_digestBase_implCompressMB(Node* digestBase_obj, ciInstanceKlass* instklass_digestBase,
9331                                                       BasicType elem_type, address stubAddr, const char *stubName,
9332                                                       Node* src_start, Node* ofs, Node* limit) {
9333   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_digestBase);
9334   const TypeOopPtr* xtype = aklass->cast_to_exactness(false)->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
9335   Node* digest_obj = new CheckCastPPNode(control(), digestBase_obj, xtype);
9336   digest_obj = _gvn.transform(digest_obj);
9337 
9338   Node* state = get_state_from_digest_object(digest_obj, elem_type);
9339   if (state == nullptr) return false;
9340 
9341   Node* block_size = nullptr;
9342   if (strcmp("sha3_implCompressMB", stubName) == 0) {
9343     block_size = get_block_size_from_digest_object(digest_obj);
9344     if (block_size == nullptr) return false;
9345   }
9346 
9347   // Call the stub.
9348   Node* call;
9349   if (block_size == nullptr) {
9350     call = make_runtime_call(RC_LEAF|RC_NO_FP,
9351                              OptoRuntime::digestBase_implCompressMB_Type(false),
9352                              stubAddr, stubName, TypePtr::BOTTOM,
9353                              src_start, state, ofs, limit);
9354   } else {
9355      call = make_runtime_call(RC_LEAF|RC_NO_FP,
9356                              OptoRuntime::digestBase_implCompressMB_Type(true),
9357                              stubAddr, stubName, TypePtr::BOTTOM,
9358                              src_start, state, block_size, ofs, limit);
9359   }
9360 
9361   // return ofs (int)
9362   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
9363   set_result(result);
9364 
9365   return true;
9366 }
9367 
9368 //------------------------------inline_galoisCounterMode_AESCrypt-----------------------
9369 bool LibraryCallKit::inline_galoisCounterMode_AESCrypt() {
9370   assert(UseAES, "need AES instruction support");
9371   address stubAddr = nullptr;
9372   const char *stubName = nullptr;
9373   stubAddr = StubRoutines::galoisCounterMode_AESCrypt();
9374   stubName = "galoisCounterMode_AESCrypt";
9375 
9376   if (stubAddr == nullptr) return false;
9377 
9378   Node* in      = argument(0);
9379   Node* inOfs   = argument(1);
9380   Node* len     = argument(2);
9381   Node* ct      = argument(3);
9382   Node* ctOfs   = argument(4);
9383   Node* out     = argument(5);
9384   Node* outOfs  = argument(6);
9385   Node* gctr_object = argument(7);
9386   Node* ghash_object = argument(8);
9387 
9388   // (1) in, ct and out are arrays.
9389   const TypeAryPtr* in_type = in->Value(&_gvn)->isa_aryptr();
9390   const TypeAryPtr* ct_type = ct->Value(&_gvn)->isa_aryptr();
9391   const TypeAryPtr* out_type = out->Value(&_gvn)->isa_aryptr();
9392   assert( in_type != nullptr &&  in_type->elem() != Type::BOTTOM &&
9393           ct_type != nullptr &&  ct_type->elem() != Type::BOTTOM &&
9394          out_type != nullptr && out_type->elem() != Type::BOTTOM, "args are strange");
9395 
9396   // checks are the responsibility of the caller
9397   Node* in_start = in;
9398   Node* ct_start = ct;
9399   Node* out_start = out;
9400   if (inOfs != nullptr || ctOfs != nullptr || outOfs != nullptr) {
9401     assert(inOfs != nullptr && ctOfs != nullptr && outOfs != nullptr, "");
9402     in_start = array_element_address(in, inOfs, T_BYTE);
9403     ct_start = array_element_address(ct, ctOfs, T_BYTE);
9404     out_start = array_element_address(out, outOfs, T_BYTE);
9405   }
9406 
9407   // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
9408   // (because of the predicated logic executed earlier).
9409   // so we cast it here safely.
9410   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
9411   Node* embeddedCipherObj = load_field_from_object(gctr_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
9412   Node* counter = load_field_from_object(gctr_object, "counter", "[B");
9413   Node* subkeyHtbl = load_field_from_object(ghash_object, "subkeyHtbl", "[J");
9414   Node* state = load_field_from_object(ghash_object, "state", "[J");
9415 
9416   if (embeddedCipherObj == nullptr || counter == nullptr || subkeyHtbl == nullptr || state == nullptr) {
9417     return false;
9418   }
9419   // cast it to what we know it will be at runtime
9420   const TypeInstPtr* tinst = _gvn.type(gctr_object)->isa_instptr();
9421   assert(tinst != nullptr, "GCTR obj is null");
9422   assert(tinst->is_loaded(), "GCTR obj is not loaded");
9423   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
9424   assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
9425   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
9426   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
9427   const TypeOopPtr* xtype = aklass->as_instance_type();
9428   Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
9429   aescrypt_object = _gvn.transform(aescrypt_object);
9430   // we need to get the start of the aescrypt_object's expanded key array
9431   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object, /* is_decrypt */ false);
9432   if (k_start == nullptr) return false;
9433   // similarly, get the start address of the r vector
9434   Node* cnt_start = array_element_address(counter, intcon(0), T_BYTE);
9435   Node* state_start = array_element_address(state, intcon(0), T_LONG);
9436   Node* subkeyHtbl_start = array_element_address(subkeyHtbl, intcon(0), T_LONG);
9437 
9438 
9439   // Call the stub, passing params
9440   Node* gcmCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
9441                                OptoRuntime::galoisCounterMode_aescrypt_Type(),
9442                                stubAddr, stubName, TypePtr::BOTTOM,
9443                                in_start, len, ct_start, out_start, k_start, state_start, subkeyHtbl_start, cnt_start);
9444 
9445   // return cipher length (int)
9446   Node* retvalue = _gvn.transform(new ProjNode(gcmCrypt, TypeFunc::Parms));
9447   set_result(retvalue);
9448 
9449   return true;
9450 }
9451 
9452 //----------------------------inline_galoisCounterMode_AESCrypt_predicate----------------------------
9453 // Return node representing slow path of predicate check.
9454 // the pseudo code we want to emulate with this predicate is:
9455 // for encryption:
9456 //    if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
9457 // for decryption:
9458 //    if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
9459 //    note cipher==plain is more conservative than the original java code but that's OK
9460 //
9461 
9462 Node* LibraryCallKit::inline_galoisCounterMode_AESCrypt_predicate() {
9463   // The receiver was checked for null already.
9464   Node* objGCTR = argument(7);
9465   // Load embeddedCipher field of GCTR object.
9466   Node* embeddedCipherObj = load_field_from_object(objGCTR, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
9467   assert(embeddedCipherObj != nullptr, "embeddedCipherObj is null");
9468 
9469   // get AESCrypt klass for instanceOf check
9470   // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
9471   // will have same classloader as CipherBlockChaining object
9472   const TypeInstPtr* tinst = _gvn.type(objGCTR)->isa_instptr();
9473   assert(tinst != nullptr, "GCTR obj is null");
9474   assert(tinst->is_loaded(), "GCTR obj is not loaded");
9475 
9476   // we want to do an instanceof comparison against the AESCrypt class
9477   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
9478   if (!klass_AESCrypt->is_loaded()) {
9479     // if AESCrypt is not even loaded, we never take the intrinsic fast path
9480     Node* ctrl = control();
9481     set_control(top()); // no regular fast path
9482     return ctrl;
9483   }
9484 
9485   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
9486   Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
9487   Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
9488   Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
9489   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
9490 
9491   return instof_false; // even if it is null
9492 }
9493 
9494 //------------------------------get_state_from_digest_object-----------------------
9495 Node * LibraryCallKit::get_state_from_digest_object(Node *digest_object, BasicType elem_type) {
9496   const char* state_type;
9497   switch (elem_type) {
9498     case T_BYTE: state_type = "[B"; break;
9499     case T_INT:  state_type = "[I"; break;
9500     case T_LONG: state_type = "[J"; break;
9501     default: ShouldNotReachHere();
9502   }
9503   Node* digest_state = load_field_from_object(digest_object, "state", state_type);
9504   assert (digest_state != nullptr, "wrong version of sun.security.provider.MD5/SHA/SHA2/SHA5/SHA3");
9505   if (digest_state == nullptr) return (Node *) nullptr;
9506 
9507   // now have the array, need to get the start address of the state array
9508   Node* state = array_element_address(digest_state, intcon(0), elem_type);
9509   return state;
9510 }
9511 
9512 //------------------------------get_block_size_from_sha3_object----------------------------------
9513 Node * LibraryCallKit::get_block_size_from_digest_object(Node *digest_object) {
9514   Node* block_size = load_field_from_object(digest_object, "blockSize", "I");
9515   assert (block_size != nullptr, "sanity");
9516   return block_size;
9517 }
9518 
9519 //----------------------------inline_digestBase_implCompressMB_predicate----------------------------
9520 // Return node representing slow path of predicate check.
9521 // the pseudo code we want to emulate with this predicate is:
9522 //    if (digestBaseObj instanceof MD5/SHA/SHA2/SHA5/SHA3) do_intrinsic, else do_javapath
9523 //
9524 Node* LibraryCallKit::inline_digestBase_implCompressMB_predicate(int predicate) {
9525   assert(UseMD5Intrinsics || UseSHA1Intrinsics || UseSHA256Intrinsics || UseSHA512Intrinsics || UseSHA3Intrinsics,
9526          "need MD5/SHA1/SHA256/SHA512/SHA3 instruction support");
9527   assert((uint)predicate < 5, "sanity");
9528 
9529   // The receiver was checked for null already.
9530   Node* digestBaseObj = argument(0);
9531 
9532   // get DigestBase klass for instanceOf check
9533   const TypeInstPtr* tinst = _gvn.type(digestBaseObj)->isa_instptr();
9534   assert(tinst != nullptr, "digestBaseObj is null");
9535   assert(tinst->is_loaded(), "DigestBase is not loaded");
9536 
9537   const char* klass_name = nullptr;
9538   switch (predicate) {
9539   case 0:
9540     if (UseMD5Intrinsics) {
9541       // we want to do an instanceof comparison against the MD5 class
9542       klass_name = "sun/security/provider/MD5";
9543     }
9544     break;
9545   case 1:
9546     if (UseSHA1Intrinsics) {
9547       // we want to do an instanceof comparison against the SHA class
9548       klass_name = "sun/security/provider/SHA";
9549     }
9550     break;
9551   case 2:
9552     if (UseSHA256Intrinsics) {
9553       // we want to do an instanceof comparison against the SHA2 class
9554       klass_name = "sun/security/provider/SHA2";
9555     }
9556     break;
9557   case 3:
9558     if (UseSHA512Intrinsics) {
9559       // we want to do an instanceof comparison against the SHA5 class
9560       klass_name = "sun/security/provider/SHA5";
9561     }
9562     break;
9563   case 4:
9564     if (UseSHA3Intrinsics) {
9565       // we want to do an instanceof comparison against the SHA3 class
9566       klass_name = "sun/security/provider/SHA3";
9567     }
9568     break;
9569   default:
9570     fatal("unknown SHA intrinsic predicate: %d", predicate);
9571   }
9572 
9573   ciKlass* klass = nullptr;
9574   if (klass_name != nullptr) {
9575     klass = tinst->instance_klass()->find_klass(ciSymbol::make(klass_name));
9576   }
9577   if ((klass == nullptr) || !klass->is_loaded()) {
9578     // if none of MD5/SHA/SHA2/SHA5 is loaded, we never take the intrinsic fast path
9579     Node* ctrl = control();
9580     set_control(top()); // no intrinsic path
9581     return ctrl;
9582   }
9583   ciInstanceKlass* instklass = klass->as_instance_klass();
9584 
9585   Node* instof = gen_instanceof(digestBaseObj, makecon(TypeKlassPtr::make(instklass)));
9586   Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
9587   Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
9588   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
9589 
9590   return instof_false;  // even if it is null
9591 }
9592 
9593 //-------------inline_fma-----------------------------------
9594 bool LibraryCallKit::inline_fma(vmIntrinsics::ID id) {
9595   Node *a = nullptr;
9596   Node *b = nullptr;
9597   Node *c = nullptr;
9598   Node* result = nullptr;
9599   switch (id) {
9600   case vmIntrinsics::_fmaD:
9601     assert(callee()->signature()->size() == 6, "fma has 3 parameters of size 2 each.");
9602     // no receiver since it is static method
9603     a = argument(0);
9604     b = argument(2);
9605     c = argument(4);
9606     result = _gvn.transform(new FmaDNode(a, b, c));
9607     break;
9608   case vmIntrinsics::_fmaF:
9609     assert(callee()->signature()->size() == 3, "fma has 3 parameters of size 1 each.");
9610     a = argument(0);
9611     b = argument(1);
9612     c = argument(2);
9613     result = _gvn.transform(new FmaFNode(a, b, c));
9614     break;
9615   default:
9616     fatal_unexpected_iid(id);  break;
9617   }
9618   set_result(result);
9619   return true;
9620 }
9621 
9622 bool LibraryCallKit::inline_character_compare(vmIntrinsics::ID id) {
9623   // argument(0) is receiver
9624   Node* codePoint = argument(1);
9625   Node* n = nullptr;
9626 
9627   switch (id) {
9628     case vmIntrinsics::_isDigit :
9629       n = new DigitNode(control(), codePoint);
9630       break;
9631     case vmIntrinsics::_isLowerCase :
9632       n = new LowerCaseNode(control(), codePoint);
9633       break;
9634     case vmIntrinsics::_isUpperCase :
9635       n = new UpperCaseNode(control(), codePoint);
9636       break;
9637     case vmIntrinsics::_isWhitespace :
9638       n = new WhitespaceNode(control(), codePoint);
9639       break;
9640     default:
9641       fatal_unexpected_iid(id);
9642   }
9643 
9644   set_result(_gvn.transform(n));
9645   return true;
9646 }
9647 
9648 bool LibraryCallKit::inline_profileBoolean() {
9649   Node* counts = argument(1);
9650   const TypeAryPtr* ary = nullptr;
9651   ciArray* aobj = nullptr;
9652   if (counts->is_Con()
9653       && (ary = counts->bottom_type()->isa_aryptr()) != nullptr
9654       && (aobj = ary->const_oop()->as_array()) != nullptr
9655       && (aobj->length() == 2)) {
9656     // Profile is int[2] where [0] and [1] correspond to false and true value occurrences respectively.
9657     jint false_cnt = aobj->element_value(0).as_int();
9658     jint  true_cnt = aobj->element_value(1).as_int();
9659 
9660     if (C->log() != nullptr) {
9661       C->log()->elem("observe source='profileBoolean' false='%d' true='%d'",
9662                      false_cnt, true_cnt);
9663     }
9664 
9665     if (false_cnt + true_cnt == 0) {
9666       // According to profile, never executed.
9667       uncommon_trap_exact(Deoptimization::Reason_intrinsic,
9668                           Deoptimization::Action_reinterpret);
9669       return true;
9670     }
9671 
9672     // result is a boolean (0 or 1) and its profile (false_cnt & true_cnt)
9673     // is a number of each value occurrences.
9674     Node* result = argument(0);
9675     if (false_cnt == 0 || true_cnt == 0) {
9676       // According to profile, one value has been never seen.
9677       int expected_val = (false_cnt == 0) ? 1 : 0;
9678 
9679       Node* cmp  = _gvn.transform(new CmpINode(result, intcon(expected_val)));
9680       Node* test = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
9681 
9682       IfNode* check = create_and_map_if(control(), test, PROB_ALWAYS, COUNT_UNKNOWN);
9683       Node* fast_path = _gvn.transform(new IfTrueNode(check));
9684       Node* slow_path = _gvn.transform(new IfFalseNode(check));
9685 
9686       { // Slow path: uncommon trap for never seen value and then reexecute
9687         // MethodHandleImpl::profileBoolean() to bump the count, so JIT knows
9688         // the value has been seen at least once.
9689         PreserveJVMState pjvms(this);
9690         PreserveReexecuteState preexecs(this);
9691         jvms()->set_should_reexecute(true);
9692 
9693         set_control(slow_path);
9694         set_i_o(i_o());
9695 
9696         uncommon_trap_exact(Deoptimization::Reason_intrinsic,
9697                             Deoptimization::Action_reinterpret);
9698       }
9699       // The guard for never seen value enables sharpening of the result and
9700       // returning a constant. It allows to eliminate branches on the same value
9701       // later on.
9702       set_control(fast_path);
9703       result = intcon(expected_val);
9704     }
9705     // Stop profiling.
9706     // MethodHandleImpl::profileBoolean() has profiling logic in its bytecode.
9707     // By replacing method body with profile data (represented as ProfileBooleanNode
9708     // on IR level) we effectively disable profiling.
9709     // It enables full speed execution once optimized code is generated.
9710     Node* profile = _gvn.transform(new ProfileBooleanNode(result, false_cnt, true_cnt));
9711     C->record_for_igvn(profile);
9712     set_result(profile);
9713     return true;
9714   } else {
9715     // Continue profiling.
9716     // Profile data isn't available at the moment. So, execute method's bytecode version.
9717     // Usually, when GWT LambdaForms are profiled it means that a stand-alone nmethod
9718     // is compiled and counters aren't available since corresponding MethodHandle
9719     // isn't a compile-time constant.
9720     return false;
9721   }
9722 }
9723 
9724 bool LibraryCallKit::inline_isCompileConstant() {
9725   Node* n = argument(0);
9726   set_result(n->is_Con() ? intcon(1) : intcon(0));
9727   return true;
9728 }
9729 
9730 //------------------------------- inline_getObjectSize --------------------------------------
9731 //
9732 // Calculate the runtime size of the object/array.
9733 //   native long sun.instrument.InstrumentationImpl.getObjectSize0(long nativeAgent, Object objectToSize);
9734 //
9735 bool LibraryCallKit::inline_getObjectSize() {
9736   Node* obj = argument(3);
9737   Node* klass_node = load_object_klass(obj);
9738 
9739   jint  layout_con = Klass::_lh_neutral_value;
9740   Node* layout_val = get_layout_helper(klass_node, layout_con);
9741   int   layout_is_con = (layout_val == nullptr);
9742 
9743   if (layout_is_con) {
9744     // Layout helper is constant, can figure out things at compile time.
9745 
9746     if (Klass::layout_helper_is_instance(layout_con)) {
9747       // Instance case:  layout_con contains the size itself.
9748       Node *size = longcon(Klass::layout_helper_size_in_bytes(layout_con));
9749       set_result(size);
9750     } else {
9751       // Array case: size is round(header + element_size*arraylength).
9752       // Since arraylength is different for every array instance, we have to
9753       // compute the whole thing at runtime.
9754 
9755       Node* arr_length = load_array_length(obj);
9756 
9757       int round_mask = MinObjAlignmentInBytes - 1;
9758       int hsize  = Klass::layout_helper_header_size(layout_con);
9759       int eshift = Klass::layout_helper_log2_element_size(layout_con);
9760 
9761       if ((round_mask & ~right_n_bits(eshift)) == 0) {
9762         round_mask = 0;  // strength-reduce it if it goes away completely
9763       }
9764       assert((hsize & right_n_bits(eshift)) == 0, "hsize is pre-rounded");
9765       Node* header_size = intcon(hsize + round_mask);
9766 
9767       Node* lengthx = ConvI2X(arr_length);
9768       Node* headerx = ConvI2X(header_size);
9769 
9770       Node* abody = lengthx;
9771       if (eshift != 0) {
9772         abody = _gvn.transform(new LShiftXNode(lengthx, intcon(eshift)));
9773       }
9774       Node* size = _gvn.transform( new AddXNode(headerx, abody) );
9775       if (round_mask != 0) {
9776         size = _gvn.transform( new AndXNode(size, MakeConX(~round_mask)) );
9777       }
9778       size = ConvX2L(size);
9779       set_result(size);
9780     }
9781   } else {
9782     // Layout helper is not constant, need to test for array-ness at runtime.
9783 
9784     enum { _instance_path = 1, _array_path, PATH_LIMIT };
9785     RegionNode* result_reg = new RegionNode(PATH_LIMIT);
9786     PhiNode* result_val = new PhiNode(result_reg, TypeLong::LONG);
9787     record_for_igvn(result_reg);
9788 
9789     Node* array_ctl = generate_array_guard(klass_node, nullptr, &obj);
9790     if (array_ctl != nullptr) {
9791       // Array case: size is round(header + element_size*arraylength).
9792       // Since arraylength is different for every array instance, we have to
9793       // compute the whole thing at runtime.
9794 
9795       PreserveJVMState pjvms(this);
9796       set_control(array_ctl);
9797       Node* arr_length = load_array_length(obj);
9798 
9799       int round_mask = MinObjAlignmentInBytes - 1;
9800       Node* mask = intcon(round_mask);
9801 
9802       Node* hss = intcon(Klass::_lh_header_size_shift);
9803       Node* hsm = intcon(Klass::_lh_header_size_mask);
9804       Node* header_size = _gvn.transform(new URShiftINode(layout_val, hss));
9805       header_size = _gvn.transform(new AndINode(header_size, hsm));
9806       header_size = _gvn.transform(new AddINode(header_size, mask));
9807 
9808       // There is no need to mask or shift this value.
9809       // The semantics of LShiftINode include an implicit mask to 0x1F.
9810       assert(Klass::_lh_log2_element_size_shift == 0, "use shift in place");
9811       Node* elem_shift = layout_val;
9812 
9813       Node* lengthx = ConvI2X(arr_length);
9814       Node* headerx = ConvI2X(header_size);
9815 
9816       Node* abody = _gvn.transform(new LShiftXNode(lengthx, elem_shift));
9817       Node* size = _gvn.transform(new AddXNode(headerx, abody));
9818       if (round_mask != 0) {
9819         size = _gvn.transform(new AndXNode(size, MakeConX(~round_mask)));
9820       }
9821       size = ConvX2L(size);
9822 
9823       result_reg->init_req(_array_path, control());
9824       result_val->init_req(_array_path, size);
9825     }
9826 
9827     if (!stopped()) {
9828       // Instance case: the layout helper gives us instance size almost directly,
9829       // but we need to mask out the _lh_instance_slow_path_bit.
9830       Node* size = ConvI2X(layout_val);
9831       assert((int) Klass::_lh_instance_slow_path_bit < BytesPerLong, "clear bit");
9832       Node* mask = MakeConX(~(intptr_t) right_n_bits(LogBytesPerLong));
9833       size = _gvn.transform(new AndXNode(size, mask));
9834       size = ConvX2L(size);
9835 
9836       result_reg->init_req(_instance_path, control());
9837       result_val->init_req(_instance_path, size);
9838     }
9839 
9840     set_result(result_reg, result_val);
9841   }
9842 
9843   return true;
9844 }
9845 
9846 //------------------------------- inline_blackhole --------------------------------------
9847 //
9848 // Make sure all arguments to this node are alive.
9849 // This matches methods that were requested to be blackholed through compile commands.
9850 //
9851 bool LibraryCallKit::inline_blackhole() {
9852   assert(callee()->is_static(), "Should have been checked before: only static methods here");
9853   assert(callee()->is_empty(), "Should have been checked before: only empty methods here");
9854   assert(callee()->holder()->is_loaded(), "Should have been checked before: only methods for loaded classes here");
9855 
9856   // Blackhole node pinches only the control, not memory. This allows
9857   // the blackhole to be pinned in the loop that computes blackholed
9858   // values, but have no other side effects, like breaking the optimizations
9859   // across the blackhole.
9860 
9861   Node* bh = _gvn.transform(new BlackholeNode(control()));
9862   set_control(_gvn.transform(new ProjNode(bh, TypeFunc::Control)));
9863 
9864   // Bind call arguments as blackhole arguments to keep them alive
9865   uint nargs = callee()->arg_size();
9866   for (uint i = 0; i < nargs; i++) {
9867     bh->add_req(argument(i));
9868   }
9869 
9870   return true;
9871 }
9872 
9873 Node* LibraryCallKit::unbox_fp16_value(const TypeInstPtr* float16_box_type, ciField* field, Node* box) {
9874   const TypeInstPtr* box_type = _gvn.type(box)->isa_instptr();
9875   if (box_type == nullptr || box_type->instance_klass() != float16_box_type->instance_klass()) {
9876     return nullptr; // box klass is not Float16
9877   }
9878 
9879   // Null check; get notnull casted pointer
9880   Node* null_ctl = top();
9881   Node* not_null_box = null_check_oop(box, &null_ctl, true);
9882   // If not_null_box is dead, only null-path is taken
9883   if (stopped()) {
9884     set_control(null_ctl);
9885     return nullptr;
9886   }
9887   assert(not_null_box->bottom_type()->is_instptr()->maybe_null() == false, "");
9888   const TypePtr* adr_type = C->alias_type(field)->adr_type();
9889   Node* adr = basic_plus_adr(not_null_box, field->offset_in_bytes());
9890   return access_load_at(not_null_box, adr, adr_type, TypeInt::SHORT, T_SHORT, IN_HEAP);
9891 }
9892 
9893 Node* LibraryCallKit::box_fp16_value(const TypeInstPtr* float16_box_type, ciField* field, Node* value) {
9894   PreserveReexecuteState preexecs(this);
9895   jvms()->set_should_reexecute(true);
9896 
9897   const TypeKlassPtr* klass_type = float16_box_type->as_klass_type();
9898   Node* klass_node = makecon(klass_type);
9899   Node* box = new_instance(klass_node);
9900 
9901   Node* value_field = basic_plus_adr(box, field->offset_in_bytes());
9902   const TypePtr* value_adr_type = value_field->bottom_type()->is_ptr();
9903 
9904   Node* field_store = _gvn.transform(access_store_at(box,
9905                                                      value_field,
9906                                                      value_adr_type,
9907                                                      value,
9908                                                      TypeInt::SHORT,
9909                                                      T_SHORT,
9910                                                      IN_HEAP));
9911   set_memory(field_store, value_adr_type);
9912   return box;
9913 }
9914 
9915 bool LibraryCallKit::inline_fp16_operations(vmIntrinsics::ID id, int num_args) {
9916   if (!Matcher::match_rule_supported(Op_ReinterpretS2HF) ||
9917       !Matcher::match_rule_supported(Op_ReinterpretHF2S)) {
9918     return false;
9919   }
9920 
9921   const TypeInstPtr* box_type = _gvn.type(argument(0))->isa_instptr();
9922   if (box_type == nullptr || box_type->const_oop() == nullptr) {
9923     return false;
9924   }
9925 
9926   ciInstanceKlass* float16_klass = box_type->const_oop()->as_instance()->java_lang_Class_klass()->as_instance_klass();
9927   const TypeInstPtr* float16_box_type = TypeInstPtr::make_exact(TypePtr::NotNull, float16_klass);
9928   ciField* field = float16_klass->get_field_by_name(ciSymbols::value_name(),
9929                                                     ciSymbols::short_signature(),
9930                                                     false);
9931   assert(field != nullptr, "");
9932 
9933   // Transformed nodes
9934   Node* fld1 = nullptr;
9935   Node* fld2 = nullptr;
9936   Node* fld3 = nullptr;
9937   switch(num_args) {
9938     case 3:
9939       fld3 = unbox_fp16_value(float16_box_type, field, argument(3));
9940       if (fld3 == nullptr) {
9941         return false;
9942       }
9943       fld3 = _gvn.transform(new ReinterpretS2HFNode(fld3));
9944     // fall-through
9945     case 2:
9946       fld2 = unbox_fp16_value(float16_box_type, field, argument(2));
9947       if (fld2 == nullptr) {
9948         return false;
9949       }
9950       fld2 = _gvn.transform(new ReinterpretS2HFNode(fld2));
9951     // fall-through
9952     case 1:
9953       fld1 = unbox_fp16_value(float16_box_type, field, argument(1));
9954       if (fld1 == nullptr) {
9955         return false;
9956       }
9957       fld1 = _gvn.transform(new ReinterpretS2HFNode(fld1));
9958       break;
9959     default: fatal("Unsupported number of arguments %d", num_args);
9960   }
9961 
9962   Node* result = nullptr;
9963   switch (id) {
9964     // Unary operations
9965     case vmIntrinsics::_sqrt_float16:
9966       result = _gvn.transform(new SqrtHFNode(C, control(), fld1));
9967       break;
9968     // Ternary operations
9969     case vmIntrinsics::_fma_float16:
9970       result = _gvn.transform(new FmaHFNode(fld1, fld2, fld3));
9971       break;
9972     default:
9973       fatal_unexpected_iid(id);
9974       break;
9975   }
9976   result = _gvn.transform(new ReinterpretHF2SNode(result));
9977   set_result(box_fp16_value(float16_box_type, field, result));
9978   return true;
9979 }
9980