1 /*
   2  * Copyright (c) 1999, 2026, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "asm/macroAssembler.hpp"
  26 #include "ci/ciArrayKlass.hpp"
  27 #include "ci/ciFlatArrayKlass.hpp"
  28 #include "ci/ciInstanceKlass.hpp"
  29 #include "ci/ciSymbols.hpp"
  30 #include "ci/ciUtilities.inline.hpp"
  31 #include "classfile/vmIntrinsics.hpp"
  32 #include "compiler/compileBroker.hpp"
  33 #include "compiler/compileLog.hpp"
  34 #include "gc/shared/barrierSet.hpp"
  35 #include "gc/shared/c2/barrierSetC2.hpp"
  36 #include "jfr/support/jfrIntrinsics.hpp"
  37 #include "memory/resourceArea.hpp"
  38 #include "oops/accessDecorators.hpp"
  39 #include "oops/klass.inline.hpp"
  40 #include "oops/layoutKind.hpp"
  41 #include "oops/objArrayKlass.hpp"
  42 #include "opto/addnode.hpp"
  43 #include "opto/arraycopynode.hpp"
  44 #include "opto/c2compiler.hpp"
  45 #include "opto/castnode.hpp"
  46 #include "opto/cfgnode.hpp"
  47 #include "opto/convertnode.hpp"
  48 #include "opto/countbitsnode.hpp"
  49 #include "opto/graphKit.hpp"
  50 #include "opto/idealKit.hpp"
  51 #include "opto/inlinetypenode.hpp"
  52 #include "opto/library_call.hpp"
  53 #include "opto/mathexactnode.hpp"
  54 #include "opto/mulnode.hpp"
  55 #include "opto/narrowptrnode.hpp"
  56 #include "opto/opaquenode.hpp"
  57 #include "opto/opcodes.hpp"
  58 #include "opto/parse.hpp"
  59 #include "opto/rootnode.hpp"
  60 #include "opto/runtime.hpp"
  61 #include "opto/subnode.hpp"
  62 #include "opto/type.hpp"
  63 #include "opto/vectornode.hpp"
  64 #include "prims/jvmtiExport.hpp"
  65 #include "prims/jvmtiThreadState.hpp"
  66 #include "prims/unsafe.hpp"
  67 #include "runtime/globals.hpp"
  68 #include "runtime/jniHandles.inline.hpp"
  69 #include "runtime/mountUnmountDisabler.hpp"
  70 #include "runtime/objectMonitor.hpp"
  71 #include "runtime/sharedRuntime.hpp"
  72 #include "runtime/stubRoutines.hpp"
  73 #include "utilities/globalDefinitions.hpp"
  74 #include "utilities/macros.hpp"
  75 #include "utilities/powerOfTwo.hpp"
  76 
  77 //---------------------------make_vm_intrinsic----------------------------
  78 CallGenerator* Compile::make_vm_intrinsic(ciMethod* m, bool is_virtual) {
  79   vmIntrinsicID id = m->intrinsic_id();
  80   assert(id != vmIntrinsics::_none, "must be a VM intrinsic");
  81 
  82   if (!m->is_loaded()) {
  83     // Do not attempt to inline unloaded methods.
  84     return nullptr;
  85   }
  86 
  87   C2Compiler* compiler = (C2Compiler*)CompileBroker::compiler(CompLevel_full_optimization);
  88   bool is_available = false;
  89 
  90   {
  91     // For calling is_intrinsic_supported and is_intrinsic_disabled_by_flag
  92     // the compiler must transition to '_thread_in_vm' state because both
  93     // methods access VM-internal data.
  94     VM_ENTRY_MARK;
  95     methodHandle mh(THREAD, m->get_Method());
  96     is_available = compiler != nullptr && compiler->is_intrinsic_available(mh, C->directive());
  97     if (is_available && is_virtual) {
  98       is_available = vmIntrinsics::does_virtual_dispatch(id);
  99     }
 100   }
 101 
 102   if (is_available) {
 103     assert(id <= vmIntrinsics::LAST_COMPILER_INLINE, "caller responsibility");
 104     assert(id != vmIntrinsics::_Object_init && id != vmIntrinsics::_invoke, "enum out of order?");
 105     return new LibraryIntrinsic(m, is_virtual,
 106                                 vmIntrinsics::predicates_needed(id),
 107                                 vmIntrinsics::does_virtual_dispatch(id),
 108                                 id);
 109   } else {
 110     return nullptr;
 111   }
 112 }
 113 
 114 JVMState* LibraryIntrinsic::generate(JVMState* jvms) {
 115   LibraryCallKit kit(jvms, this);
 116   Compile* C = kit.C;
 117   int nodes = C->unique();
 118 #ifndef PRODUCT
 119   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
 120     char buf[1000];
 121     const char* str = vmIntrinsics::short_name_as_C_string(intrinsic_id(), buf, sizeof(buf));
 122     tty->print_cr("Intrinsic %s", str);
 123   }
 124 #endif
 125   ciMethod* callee = kit.callee();
 126   const int bci    = kit.bci();
 127 #ifdef ASSERT
 128   Node* ctrl = kit.control();
 129 #endif
 130   // Try to inline the intrinsic.
 131   if (callee->check_intrinsic_candidate() &&
 132       kit.try_to_inline(_last_predicate)) {
 133     const char *inline_msg = is_virtual() ? "(intrinsic, virtual)"
 134                                           : "(intrinsic)";
 135     CompileTask::print_inlining_ul(callee, jvms->depth() - 1, bci, InliningResult::SUCCESS, inline_msg);
 136     C->inline_printer()->record(callee, jvms, InliningResult::SUCCESS, inline_msg);
 137     C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_worked);
 138     if (C->log()) {
 139       C->log()->elem("intrinsic id='%s'%s nodes='%d'",
 140                      vmIntrinsics::name_at(intrinsic_id()),
 141                      (is_virtual() ? " virtual='1'" : ""),
 142                      C->unique() - nodes);
 143     }
 144     // Push the result from the inlined method onto the stack.
 145     kit.push_result();
 146     return kit.transfer_exceptions_into_jvms();
 147   }
 148 
 149   // The intrinsic bailed out
 150   assert(ctrl == kit.control(), "Control flow was added although the intrinsic bailed out");
 151   assert(jvms->map() == kit.map(), "Out of sync JVM state");
 152   if (jvms->has_method()) {
 153     // Not a root compile.
 154     const char* msg;
 155     if (callee->intrinsic_candidate()) {
 156       msg = is_virtual() ? "failed to inline (intrinsic, virtual)" : "failed to inline (intrinsic)";
 157     } else {
 158       msg = is_virtual() ? "failed to inline (intrinsic, virtual), method not annotated"
 159                          : "failed to inline (intrinsic), method not annotated";
 160     }
 161     CompileTask::print_inlining_ul(callee, jvms->depth() - 1, bci, InliningResult::FAILURE, msg);
 162     C->inline_printer()->record(callee, jvms, InliningResult::FAILURE, msg);
 163   } else {
 164     // Root compile
 165     ResourceMark rm;
 166     stringStream msg_stream;
 167     msg_stream.print("Did not generate intrinsic %s%s at bci:%d in",
 168                      vmIntrinsics::name_at(intrinsic_id()),
 169                      is_virtual() ? " (virtual)" : "", bci);
 170     const char *msg = msg_stream.freeze();
 171     log_debug(jit, inlining)("%s", msg);
 172     if (C->print_intrinsics() || C->print_inlining()) {
 173       tty->print("%s", msg);
 174     }
 175   }
 176   C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_failed);
 177 
 178   return nullptr;
 179 }
 180 
 181 Node* LibraryIntrinsic::generate_predicate(JVMState* jvms, int predicate) {
 182   LibraryCallKit kit(jvms, this);
 183   Compile* C = kit.C;
 184   int nodes = C->unique();
 185   _last_predicate = predicate;
 186 #ifndef PRODUCT
 187   assert(is_predicated() && predicate < predicates_count(), "sanity");
 188   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
 189     char buf[1000];
 190     const char* str = vmIntrinsics::short_name_as_C_string(intrinsic_id(), buf, sizeof(buf));
 191     tty->print_cr("Predicate for intrinsic %s", str);
 192   }
 193 #endif
 194   ciMethod* callee = kit.callee();
 195   const int bci    = kit.bci();
 196 
 197   Node* slow_ctl = kit.try_to_predicate(predicate);
 198   if (!kit.failing()) {
 199     const char *inline_msg = is_virtual() ? "(intrinsic, virtual, predicate)"
 200                                           : "(intrinsic, predicate)";
 201     CompileTask::print_inlining_ul(callee, jvms->depth() - 1, bci, InliningResult::SUCCESS, inline_msg);
 202     C->inline_printer()->record(callee, jvms, InliningResult::SUCCESS, inline_msg);
 203 
 204     C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_worked);
 205     if (C->log()) {
 206       C->log()->elem("predicate_intrinsic id='%s'%s nodes='%d'",
 207                      vmIntrinsics::name_at(intrinsic_id()),
 208                      (is_virtual() ? " virtual='1'" : ""),
 209                      C->unique() - nodes);
 210     }
 211     return slow_ctl; // Could be null if the check folds.
 212   }
 213 
 214   // The intrinsic bailed out
 215   if (jvms->has_method()) {
 216     // Not a root compile.
 217     const char* msg = "failed to generate predicate for intrinsic";
 218     CompileTask::print_inlining_ul(kit.callee(), jvms->depth() - 1, bci, InliningResult::FAILURE, msg);
 219     C->inline_printer()->record(kit.callee(), jvms, InliningResult::FAILURE, msg);
 220   } else {
 221     // Root compile
 222     ResourceMark rm;
 223     stringStream msg_stream;
 224     msg_stream.print("Did not generate intrinsic %s%s at bci:%d in",
 225                      vmIntrinsics::name_at(intrinsic_id()),
 226                      is_virtual() ? " (virtual)" : "", bci);
 227     const char *msg = msg_stream.freeze();
 228     log_debug(jit, inlining)("%s", msg);
 229     C->inline_printer()->record(kit.callee(), jvms, InliningResult::FAILURE, msg);
 230   }
 231   C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_failed);
 232   return nullptr;
 233 }
 234 
 235 bool LibraryCallKit::try_to_inline(int predicate) {
 236   // Handle symbolic names for otherwise undistinguished boolean switches:
 237   const bool is_store       = true;
 238   const bool is_compress    = true;
 239   const bool is_static      = true;
 240   const bool is_volatile    = true;
 241 
 242   if (!jvms()->has_method()) {
 243     // Root JVMState has a null method.
 244     assert(map()->memory()->Opcode() == Op_Parm, "");
 245     // Insert the memory aliasing node
 246     set_all_memory(reset_memory());
 247   }
 248   assert(merged_memory(), "");
 249 
 250   switch (intrinsic_id()) {
 251   case vmIntrinsics::_hashCode:                 return inline_native_hashcode(intrinsic()->is_virtual(), !is_static);
 252   case vmIntrinsics::_identityHashCode:         return inline_native_hashcode(/*!virtual*/ false,         is_static);
 253   case vmIntrinsics::_getClass:                 return inline_native_getClass();
 254 
 255   case vmIntrinsics::_ceil:
 256   case vmIntrinsics::_floor:
 257   case vmIntrinsics::_rint:
 258   case vmIntrinsics::_dsin:
 259   case vmIntrinsics::_dcos:
 260   case vmIntrinsics::_dtan:
 261   case vmIntrinsics::_dsinh:
 262   case vmIntrinsics::_dtanh:
 263   case vmIntrinsics::_dcbrt:
 264   case vmIntrinsics::_dabs:
 265   case vmIntrinsics::_fabs:
 266   case vmIntrinsics::_iabs:
 267   case vmIntrinsics::_labs:
 268   case vmIntrinsics::_datan2:
 269   case vmIntrinsics::_dsqrt:
 270   case vmIntrinsics::_dsqrt_strict:
 271   case vmIntrinsics::_dexp:
 272   case vmIntrinsics::_dlog:
 273   case vmIntrinsics::_dlog10:
 274   case vmIntrinsics::_dpow:
 275   case vmIntrinsics::_dcopySign:
 276   case vmIntrinsics::_fcopySign:
 277   case vmIntrinsics::_dsignum:
 278   case vmIntrinsics::_roundF:
 279   case vmIntrinsics::_roundD:
 280   case vmIntrinsics::_fsignum:                  return inline_math_native(intrinsic_id());
 281 
 282   case vmIntrinsics::_notify:
 283   case vmIntrinsics::_notifyAll:
 284     return inline_notify(intrinsic_id());
 285 
 286   case vmIntrinsics::_addExactI:                return inline_math_addExactI(false /* add */);
 287   case vmIntrinsics::_addExactL:                return inline_math_addExactL(false /* add */);
 288   case vmIntrinsics::_decrementExactI:          return inline_math_subtractExactI(true /* decrement */);
 289   case vmIntrinsics::_decrementExactL:          return inline_math_subtractExactL(true /* decrement */);
 290   case vmIntrinsics::_incrementExactI:          return inline_math_addExactI(true /* increment */);
 291   case vmIntrinsics::_incrementExactL:          return inline_math_addExactL(true /* increment */);
 292   case vmIntrinsics::_multiplyExactI:           return inline_math_multiplyExactI();
 293   case vmIntrinsics::_multiplyExactL:           return inline_math_multiplyExactL();
 294   case vmIntrinsics::_multiplyHigh:             return inline_math_multiplyHigh();
 295   case vmIntrinsics::_unsignedMultiplyHigh:     return inline_math_unsignedMultiplyHigh();
 296   case vmIntrinsics::_negateExactI:             return inline_math_negateExactI();
 297   case vmIntrinsics::_negateExactL:             return inline_math_negateExactL();
 298   case vmIntrinsics::_subtractExactI:           return inline_math_subtractExactI(false /* subtract */);
 299   case vmIntrinsics::_subtractExactL:           return inline_math_subtractExactL(false /* subtract */);
 300 
 301   case vmIntrinsics::_arraycopy:                return inline_arraycopy();
 302 
 303   case vmIntrinsics::_arraySort:                return inline_array_sort();
 304   case vmIntrinsics::_arrayPartition:           return inline_array_partition();
 305 
 306   case vmIntrinsics::_compareToL:               return inline_string_compareTo(StrIntrinsicNode::LL);
 307   case vmIntrinsics::_compareToU:               return inline_string_compareTo(StrIntrinsicNode::UU);
 308   case vmIntrinsics::_compareToLU:              return inline_string_compareTo(StrIntrinsicNode::LU);
 309   case vmIntrinsics::_compareToUL:              return inline_string_compareTo(StrIntrinsicNode::UL);
 310 
 311   case vmIntrinsics::_indexOfL:                 return inline_string_indexOf(StrIntrinsicNode::LL);
 312   case vmIntrinsics::_indexOfU:                 return inline_string_indexOf(StrIntrinsicNode::UU);
 313   case vmIntrinsics::_indexOfUL:                return inline_string_indexOf(StrIntrinsicNode::UL);
 314   case vmIntrinsics::_indexOfIL:                return inline_string_indexOfI(StrIntrinsicNode::LL);
 315   case vmIntrinsics::_indexOfIU:                return inline_string_indexOfI(StrIntrinsicNode::UU);
 316   case vmIntrinsics::_indexOfIUL:               return inline_string_indexOfI(StrIntrinsicNode::UL);
 317   case vmIntrinsics::_indexOfU_char:            return inline_string_indexOfChar(StrIntrinsicNode::U);
 318   case vmIntrinsics::_indexOfL_char:            return inline_string_indexOfChar(StrIntrinsicNode::L);
 319 
 320   case vmIntrinsics::_equalsL:                  return inline_string_equals(StrIntrinsicNode::LL);
 321 
 322   case vmIntrinsics::_vectorizedHashCode:       return inline_vectorizedHashCode();
 323 
 324   case vmIntrinsics::_toBytesStringU:           return inline_string_toBytesU();
 325   case vmIntrinsics::_getCharsStringU:          return inline_string_getCharsU();
 326   case vmIntrinsics::_getCharStringU:           return inline_string_char_access(!is_store);
 327   case vmIntrinsics::_putCharStringU:           return inline_string_char_access( is_store);
 328 
 329   case vmIntrinsics::_compressStringC:
 330   case vmIntrinsics::_compressStringB:          return inline_string_copy( is_compress);
 331   case vmIntrinsics::_inflateStringC:
 332   case vmIntrinsics::_inflateStringB:           return inline_string_copy(!is_compress);
 333 
 334   case vmIntrinsics::_getReference:             return inline_unsafe_access(!is_store, T_OBJECT,   Relaxed, false);
 335   case vmIntrinsics::_getBoolean:               return inline_unsafe_access(!is_store, T_BOOLEAN,  Relaxed, false);
 336   case vmIntrinsics::_getByte:                  return inline_unsafe_access(!is_store, T_BYTE,     Relaxed, false);
 337   case vmIntrinsics::_getShort:                 return inline_unsafe_access(!is_store, T_SHORT,    Relaxed, false);
 338   case vmIntrinsics::_getChar:                  return inline_unsafe_access(!is_store, T_CHAR,     Relaxed, false);
 339   case vmIntrinsics::_getInt:                   return inline_unsafe_access(!is_store, T_INT,      Relaxed, false);
 340   case vmIntrinsics::_getLong:                  return inline_unsafe_access(!is_store, T_LONG,     Relaxed, false);
 341   case vmIntrinsics::_getFloat:                 return inline_unsafe_access(!is_store, T_FLOAT,    Relaxed, false);
 342   case vmIntrinsics::_getDouble:                return inline_unsafe_access(!is_store, T_DOUBLE,   Relaxed, false);
 343 
 344   case vmIntrinsics::_putReference:             return inline_unsafe_access( is_store, T_OBJECT,   Relaxed, false);
 345   case vmIntrinsics::_putBoolean:               return inline_unsafe_access( is_store, T_BOOLEAN,  Relaxed, false);
 346   case vmIntrinsics::_putByte:                  return inline_unsafe_access( is_store, T_BYTE,     Relaxed, false);
 347   case vmIntrinsics::_putShort:                 return inline_unsafe_access( is_store, T_SHORT,    Relaxed, false);
 348   case vmIntrinsics::_putChar:                  return inline_unsafe_access( is_store, T_CHAR,     Relaxed, false);
 349   case vmIntrinsics::_putInt:                   return inline_unsafe_access( is_store, T_INT,      Relaxed, false);
 350   case vmIntrinsics::_putLong:                  return inline_unsafe_access( is_store, T_LONG,     Relaxed, false);
 351   case vmIntrinsics::_putFloat:                 return inline_unsafe_access( is_store, T_FLOAT,    Relaxed, false);
 352   case vmIntrinsics::_putDouble:                return inline_unsafe_access( is_store, T_DOUBLE,   Relaxed, false);
 353 
 354   case vmIntrinsics::_getReferenceVolatile:     return inline_unsafe_access(!is_store, T_OBJECT,   Volatile, false);
 355   case vmIntrinsics::_getBooleanVolatile:       return inline_unsafe_access(!is_store, T_BOOLEAN,  Volatile, false);
 356   case vmIntrinsics::_getByteVolatile:          return inline_unsafe_access(!is_store, T_BYTE,     Volatile, false);
 357   case vmIntrinsics::_getShortVolatile:         return inline_unsafe_access(!is_store, T_SHORT,    Volatile, false);
 358   case vmIntrinsics::_getCharVolatile:          return inline_unsafe_access(!is_store, T_CHAR,     Volatile, false);
 359   case vmIntrinsics::_getIntVolatile:           return inline_unsafe_access(!is_store, T_INT,      Volatile, false);
 360   case vmIntrinsics::_getLongVolatile:          return inline_unsafe_access(!is_store, T_LONG,     Volatile, false);
 361   case vmIntrinsics::_getFloatVolatile:         return inline_unsafe_access(!is_store, T_FLOAT,    Volatile, false);
 362   case vmIntrinsics::_getDoubleVolatile:        return inline_unsafe_access(!is_store, T_DOUBLE,   Volatile, false);
 363 
 364   case vmIntrinsics::_putReferenceVolatile:     return inline_unsafe_access( is_store, T_OBJECT,   Volatile, false);
 365   case vmIntrinsics::_putBooleanVolatile:       return inline_unsafe_access( is_store, T_BOOLEAN,  Volatile, false);
 366   case vmIntrinsics::_putByteVolatile:          return inline_unsafe_access( is_store, T_BYTE,     Volatile, false);
 367   case vmIntrinsics::_putShortVolatile:         return inline_unsafe_access( is_store, T_SHORT,    Volatile, false);
 368   case vmIntrinsics::_putCharVolatile:          return inline_unsafe_access( is_store, T_CHAR,     Volatile, false);
 369   case vmIntrinsics::_putIntVolatile:           return inline_unsafe_access( is_store, T_INT,      Volatile, false);
 370   case vmIntrinsics::_putLongVolatile:          return inline_unsafe_access( is_store, T_LONG,     Volatile, false);
 371   case vmIntrinsics::_putFloatVolatile:         return inline_unsafe_access( is_store, T_FLOAT,    Volatile, false);
 372   case vmIntrinsics::_putDoubleVolatile:        return inline_unsafe_access( is_store, T_DOUBLE,   Volatile, false);
 373 
 374   case vmIntrinsics::_getShortUnaligned:        return inline_unsafe_access(!is_store, T_SHORT,    Relaxed, true);
 375   case vmIntrinsics::_getCharUnaligned:         return inline_unsafe_access(!is_store, T_CHAR,     Relaxed, true);
 376   case vmIntrinsics::_getIntUnaligned:          return inline_unsafe_access(!is_store, T_INT,      Relaxed, true);
 377   case vmIntrinsics::_getLongUnaligned:         return inline_unsafe_access(!is_store, T_LONG,     Relaxed, true);
 378 
 379   case vmIntrinsics::_putShortUnaligned:        return inline_unsafe_access( is_store, T_SHORT,    Relaxed, true);
 380   case vmIntrinsics::_putCharUnaligned:         return inline_unsafe_access( is_store, T_CHAR,     Relaxed, true);
 381   case vmIntrinsics::_putIntUnaligned:          return inline_unsafe_access( is_store, T_INT,      Relaxed, true);
 382   case vmIntrinsics::_putLongUnaligned:         return inline_unsafe_access( is_store, T_LONG,     Relaxed, true);
 383 
 384   case vmIntrinsics::_getReferenceAcquire:      return inline_unsafe_access(!is_store, T_OBJECT,   Acquire, false);
 385   case vmIntrinsics::_getBooleanAcquire:        return inline_unsafe_access(!is_store, T_BOOLEAN,  Acquire, false);
 386   case vmIntrinsics::_getByteAcquire:           return inline_unsafe_access(!is_store, T_BYTE,     Acquire, false);
 387   case vmIntrinsics::_getShortAcquire:          return inline_unsafe_access(!is_store, T_SHORT,    Acquire, false);
 388   case vmIntrinsics::_getCharAcquire:           return inline_unsafe_access(!is_store, T_CHAR,     Acquire, false);
 389   case vmIntrinsics::_getIntAcquire:            return inline_unsafe_access(!is_store, T_INT,      Acquire, false);
 390   case vmIntrinsics::_getLongAcquire:           return inline_unsafe_access(!is_store, T_LONG,     Acquire, false);
 391   case vmIntrinsics::_getFloatAcquire:          return inline_unsafe_access(!is_store, T_FLOAT,    Acquire, false);
 392   case vmIntrinsics::_getDoubleAcquire:         return inline_unsafe_access(!is_store, T_DOUBLE,   Acquire, false);
 393 
 394   case vmIntrinsics::_putReferenceRelease:      return inline_unsafe_access( is_store, T_OBJECT,   Release, false);
 395   case vmIntrinsics::_putBooleanRelease:        return inline_unsafe_access( is_store, T_BOOLEAN,  Release, false);
 396   case vmIntrinsics::_putByteRelease:           return inline_unsafe_access( is_store, T_BYTE,     Release, false);
 397   case vmIntrinsics::_putShortRelease:          return inline_unsafe_access( is_store, T_SHORT,    Release, false);
 398   case vmIntrinsics::_putCharRelease:           return inline_unsafe_access( is_store, T_CHAR,     Release, false);
 399   case vmIntrinsics::_putIntRelease:            return inline_unsafe_access( is_store, T_INT,      Release, false);
 400   case vmIntrinsics::_putLongRelease:           return inline_unsafe_access( is_store, T_LONG,     Release, false);
 401   case vmIntrinsics::_putFloatRelease:          return inline_unsafe_access( is_store, T_FLOAT,    Release, false);
 402   case vmIntrinsics::_putDoubleRelease:         return inline_unsafe_access( is_store, T_DOUBLE,   Release, false);
 403 
 404   case vmIntrinsics::_getReferenceOpaque:       return inline_unsafe_access(!is_store, T_OBJECT,   Opaque, false);
 405   case vmIntrinsics::_getBooleanOpaque:         return inline_unsafe_access(!is_store, T_BOOLEAN,  Opaque, false);
 406   case vmIntrinsics::_getByteOpaque:            return inline_unsafe_access(!is_store, T_BYTE,     Opaque, false);
 407   case vmIntrinsics::_getShortOpaque:           return inline_unsafe_access(!is_store, T_SHORT,    Opaque, false);
 408   case vmIntrinsics::_getCharOpaque:            return inline_unsafe_access(!is_store, T_CHAR,     Opaque, false);
 409   case vmIntrinsics::_getIntOpaque:             return inline_unsafe_access(!is_store, T_INT,      Opaque, false);
 410   case vmIntrinsics::_getLongOpaque:            return inline_unsafe_access(!is_store, T_LONG,     Opaque, false);
 411   case vmIntrinsics::_getFloatOpaque:           return inline_unsafe_access(!is_store, T_FLOAT,    Opaque, false);
 412   case vmIntrinsics::_getDoubleOpaque:          return inline_unsafe_access(!is_store, T_DOUBLE,   Opaque, false);
 413 
 414   case vmIntrinsics::_putReferenceOpaque:       return inline_unsafe_access( is_store, T_OBJECT,   Opaque, false);
 415   case vmIntrinsics::_putBooleanOpaque:         return inline_unsafe_access( is_store, T_BOOLEAN,  Opaque, false);
 416   case vmIntrinsics::_putByteOpaque:            return inline_unsafe_access( is_store, T_BYTE,     Opaque, false);
 417   case vmIntrinsics::_putShortOpaque:           return inline_unsafe_access( is_store, T_SHORT,    Opaque, false);
 418   case vmIntrinsics::_putCharOpaque:            return inline_unsafe_access( is_store, T_CHAR,     Opaque, false);
 419   case vmIntrinsics::_putIntOpaque:             return inline_unsafe_access( is_store, T_INT,      Opaque, false);
 420   case vmIntrinsics::_putLongOpaque:            return inline_unsafe_access( is_store, T_LONG,     Opaque, false);
 421   case vmIntrinsics::_putFloatOpaque:           return inline_unsafe_access( is_store, T_FLOAT,    Opaque, false);
 422   case vmIntrinsics::_putDoubleOpaque:          return inline_unsafe_access( is_store, T_DOUBLE,   Opaque, false);
 423 
 424   case vmIntrinsics::_getFlatValue:             return inline_unsafe_flat_access(!is_store, Relaxed);
 425   case vmIntrinsics::_putFlatValue:             return inline_unsafe_flat_access( is_store, Relaxed);
 426 
 427   case vmIntrinsics::_compareAndSetReference:   return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap,      Volatile);
 428   case vmIntrinsics::_compareAndSetByte:        return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap,      Volatile);
 429   case vmIntrinsics::_compareAndSetShort:       return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap,      Volatile);
 430   case vmIntrinsics::_compareAndSetInt:         return inline_unsafe_load_store(T_INT,    LS_cmp_swap,      Volatile);
 431   case vmIntrinsics::_compareAndSetLong:        return inline_unsafe_load_store(T_LONG,   LS_cmp_swap,      Volatile);
 432 
 433   case vmIntrinsics::_weakCompareAndSetReferencePlain:     return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Relaxed);
 434   case vmIntrinsics::_weakCompareAndSetReferenceAcquire:   return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Acquire);
 435   case vmIntrinsics::_weakCompareAndSetReferenceRelease:   return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Release);
 436   case vmIntrinsics::_weakCompareAndSetReference:          return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Volatile);
 437   case vmIntrinsics::_weakCompareAndSetBytePlain:          return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap_weak, Relaxed);
 438   case vmIntrinsics::_weakCompareAndSetByteAcquire:        return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap_weak, Acquire);
 439   case vmIntrinsics::_weakCompareAndSetByteRelease:        return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap_weak, Release);
 440   case vmIntrinsics::_weakCompareAndSetByte:               return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap_weak, Volatile);
 441   case vmIntrinsics::_weakCompareAndSetShortPlain:         return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap_weak, Relaxed);
 442   case vmIntrinsics::_weakCompareAndSetShortAcquire:       return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap_weak, Acquire);
 443   case vmIntrinsics::_weakCompareAndSetShortRelease:       return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap_weak, Release);
 444   case vmIntrinsics::_weakCompareAndSetShort:              return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap_weak, Volatile);
 445   case vmIntrinsics::_weakCompareAndSetIntPlain:           return inline_unsafe_load_store(T_INT,    LS_cmp_swap_weak, Relaxed);
 446   case vmIntrinsics::_weakCompareAndSetIntAcquire:         return inline_unsafe_load_store(T_INT,    LS_cmp_swap_weak, Acquire);
 447   case vmIntrinsics::_weakCompareAndSetIntRelease:         return inline_unsafe_load_store(T_INT,    LS_cmp_swap_weak, Release);
 448   case vmIntrinsics::_weakCompareAndSetInt:                return inline_unsafe_load_store(T_INT,    LS_cmp_swap_weak, Volatile);
 449   case vmIntrinsics::_weakCompareAndSetLongPlain:          return inline_unsafe_load_store(T_LONG,   LS_cmp_swap_weak, Relaxed);
 450   case vmIntrinsics::_weakCompareAndSetLongAcquire:        return inline_unsafe_load_store(T_LONG,   LS_cmp_swap_weak, Acquire);
 451   case vmIntrinsics::_weakCompareAndSetLongRelease:        return inline_unsafe_load_store(T_LONG,   LS_cmp_swap_weak, Release);
 452   case vmIntrinsics::_weakCompareAndSetLong:               return inline_unsafe_load_store(T_LONG,   LS_cmp_swap_weak, Volatile);
 453 
 454   case vmIntrinsics::_compareAndExchangeReference:         return inline_unsafe_load_store(T_OBJECT, LS_cmp_exchange,  Volatile);
 455   case vmIntrinsics::_compareAndExchangeReferenceAcquire:  return inline_unsafe_load_store(T_OBJECT, LS_cmp_exchange,  Acquire);
 456   case vmIntrinsics::_compareAndExchangeReferenceRelease:  return inline_unsafe_load_store(T_OBJECT, LS_cmp_exchange,  Release);
 457   case vmIntrinsics::_compareAndExchangeByte:              return inline_unsafe_load_store(T_BYTE,   LS_cmp_exchange,  Volatile);
 458   case vmIntrinsics::_compareAndExchangeByteAcquire:       return inline_unsafe_load_store(T_BYTE,   LS_cmp_exchange,  Acquire);
 459   case vmIntrinsics::_compareAndExchangeByteRelease:       return inline_unsafe_load_store(T_BYTE,   LS_cmp_exchange,  Release);
 460   case vmIntrinsics::_compareAndExchangeShort:             return inline_unsafe_load_store(T_SHORT,  LS_cmp_exchange,  Volatile);
 461   case vmIntrinsics::_compareAndExchangeShortAcquire:      return inline_unsafe_load_store(T_SHORT,  LS_cmp_exchange,  Acquire);
 462   case vmIntrinsics::_compareAndExchangeShortRelease:      return inline_unsafe_load_store(T_SHORT,  LS_cmp_exchange,  Release);
 463   case vmIntrinsics::_compareAndExchangeInt:               return inline_unsafe_load_store(T_INT,    LS_cmp_exchange,  Volatile);
 464   case vmIntrinsics::_compareAndExchangeIntAcquire:        return inline_unsafe_load_store(T_INT,    LS_cmp_exchange,  Acquire);
 465   case vmIntrinsics::_compareAndExchangeIntRelease:        return inline_unsafe_load_store(T_INT,    LS_cmp_exchange,  Release);
 466   case vmIntrinsics::_compareAndExchangeLong:              return inline_unsafe_load_store(T_LONG,   LS_cmp_exchange,  Volatile);
 467   case vmIntrinsics::_compareAndExchangeLongAcquire:       return inline_unsafe_load_store(T_LONG,   LS_cmp_exchange,  Acquire);
 468   case vmIntrinsics::_compareAndExchangeLongRelease:       return inline_unsafe_load_store(T_LONG,   LS_cmp_exchange,  Release);
 469 
 470   case vmIntrinsics::_getAndAddByte:                    return inline_unsafe_load_store(T_BYTE,   LS_get_add,       Volatile);
 471   case vmIntrinsics::_getAndAddShort:                   return inline_unsafe_load_store(T_SHORT,  LS_get_add,       Volatile);
 472   case vmIntrinsics::_getAndAddInt:                     return inline_unsafe_load_store(T_INT,    LS_get_add,       Volatile);
 473   case vmIntrinsics::_getAndAddLong:                    return inline_unsafe_load_store(T_LONG,   LS_get_add,       Volatile);
 474 
 475   case vmIntrinsics::_getAndSetByte:                    return inline_unsafe_load_store(T_BYTE,   LS_get_set,       Volatile);
 476   case vmIntrinsics::_getAndSetShort:                   return inline_unsafe_load_store(T_SHORT,  LS_get_set,       Volatile);
 477   case vmIntrinsics::_getAndSetInt:                     return inline_unsafe_load_store(T_INT,    LS_get_set,       Volatile);
 478   case vmIntrinsics::_getAndSetLong:                    return inline_unsafe_load_store(T_LONG,   LS_get_set,       Volatile);
 479   case vmIntrinsics::_getAndSetReference:               return inline_unsafe_load_store(T_OBJECT, LS_get_set,       Volatile);
 480 
 481   case vmIntrinsics::_loadFence:
 482   case vmIntrinsics::_storeFence:
 483   case vmIntrinsics::_storeStoreFence:
 484   case vmIntrinsics::_fullFence:                return inline_unsafe_fence(intrinsic_id());
 485 
 486   case vmIntrinsics::_arrayInstanceBaseOffset:  return inline_arrayInstanceBaseOffset();
 487   case vmIntrinsics::_arrayInstanceIndexScale:  return inline_arrayInstanceIndexScale();
 488   case vmIntrinsics::_arrayLayout:              return inline_arrayLayout();
 489   case vmIntrinsics::_getFieldMap:              return inline_getFieldMap();
 490 
 491   case vmIntrinsics::_onSpinWait:               return inline_onspinwait();
 492 
 493   case vmIntrinsics::_currentCarrierThread:     return inline_native_currentCarrierThread();
 494   case vmIntrinsics::_currentThread:            return inline_native_currentThread();
 495   case vmIntrinsics::_setCurrentThread:         return inline_native_setCurrentThread();
 496 
 497   case vmIntrinsics::_scopedValueCache:          return inline_native_scopedValueCache();
 498   case vmIntrinsics::_setScopedValueCache:       return inline_native_setScopedValueCache();
 499 
 500   case vmIntrinsics::_Continuation_pin:          return inline_native_Continuation_pinning(false);
 501   case vmIntrinsics::_Continuation_unpin:        return inline_native_Continuation_pinning(true);
 502 
 503   case vmIntrinsics::_vthreadEndFirstTransition:    return inline_native_vthread_end_transition(CAST_FROM_FN_PTR(address, OptoRuntime::vthread_end_first_transition_Java()),
 504                                                                                                 "endFirstTransition", true);
 505   case vmIntrinsics::_vthreadStartFinalTransition:  return inline_native_vthread_start_transition(CAST_FROM_FN_PTR(address, OptoRuntime::vthread_start_final_transition_Java()),
 506                                                                                                   "startFinalTransition", true);
 507   case vmIntrinsics::_vthreadStartTransition:       return inline_native_vthread_start_transition(CAST_FROM_FN_PTR(address, OptoRuntime::vthread_start_transition_Java()),
 508                                                                                                   "startTransition", false);
 509   case vmIntrinsics::_vthreadEndTransition:         return inline_native_vthread_end_transition(CAST_FROM_FN_PTR(address, OptoRuntime::vthread_end_transition_Java()),
 510                                                                                                 "endTransition", false);
 511 #if INCLUDE_JVMTI
 512   case vmIntrinsics::_notifyJvmtiVThreadDisableSuspend: return inline_native_notify_jvmti_sync();
 513 #endif
 514 
 515 #ifdef JFR_HAVE_INTRINSICS
 516   case vmIntrinsics::_counterTime:              return inline_native_time_funcs(CAST_FROM_FN_PTR(address, JfrTime::time_function()), "counterTime");
 517   case vmIntrinsics::_getEventWriter:           return inline_native_getEventWriter();
 518   case vmIntrinsics::_jvm_commit:               return inline_native_jvm_commit();
 519 #endif
 520   case vmIntrinsics::_currentTimeMillis:        return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeMillis), "currentTimeMillis");
 521   case vmIntrinsics::_nanoTime:                 return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeNanos), "nanoTime");
 522   case vmIntrinsics::_writeback0:               return inline_unsafe_writeback0();
 523   case vmIntrinsics::_writebackPreSync0:        return inline_unsafe_writebackSync0(true);
 524   case vmIntrinsics::_writebackPostSync0:       return inline_unsafe_writebackSync0(false);
 525   case vmIntrinsics::_allocateInstance:         return inline_unsafe_allocate();
 526   case vmIntrinsics::_copyMemory:               return inline_unsafe_copyMemory();
 527   case vmIntrinsics::_setMemory:                return inline_unsafe_setMemory();
 528   case vmIntrinsics::_getLength:                return inline_native_getLength();
 529   case vmIntrinsics::_copyOf:                   return inline_array_copyOf(false);
 530   case vmIntrinsics::_copyOfRange:              return inline_array_copyOf(true);
 531   case vmIntrinsics::_equalsB:                  return inline_array_equals(StrIntrinsicNode::LL);
 532   case vmIntrinsics::_equalsC:                  return inline_array_equals(StrIntrinsicNode::UU);
 533   case vmIntrinsics::_Preconditions_checkIndex: return inline_preconditions_checkIndex(T_INT);
 534   case vmIntrinsics::_Preconditions_checkLongIndex: return inline_preconditions_checkIndex(T_LONG);
 535   case vmIntrinsics::_clone:                    return inline_native_clone(intrinsic()->is_virtual());
 536 
 537   case vmIntrinsics::_allocateUninitializedArray: return inline_unsafe_newArray(true);
 538   case vmIntrinsics::_newArray:                   return inline_unsafe_newArray(false);
 539   case vmIntrinsics::_newNullRestrictedNonAtomicArray: return inline_newArray(/* null_free */ true, /* atomic */ false);
 540   case vmIntrinsics::_newNullRestrictedAtomicArray: return inline_newArray(/* null_free */ true, /* atomic */ true);
 541   case vmIntrinsics::_newNullableAtomicArray:     return inline_newArray(/* null_free */ false, /* atomic */ true);
 542   case vmIntrinsics::_isFlatArray:              return inline_getArrayProperties(IsFlat);
 543   case vmIntrinsics::_isNullRestrictedArray:    return inline_getArrayProperties(IsNullRestricted);
 544   case vmIntrinsics::_isAtomicArray:            return inline_getArrayProperties(IsAtomic);
 545 
 546   case vmIntrinsics::_isAssignableFrom:         return inline_native_subtype_check();
 547 
 548   case vmIntrinsics::_isInstance:
 549   case vmIntrinsics::_isHidden:
 550   case vmIntrinsics::_getSuperclass:            return inline_native_Class_query(intrinsic_id());
 551 
 552   case vmIntrinsics::_floatToRawIntBits:
 553   case vmIntrinsics::_floatToIntBits:
 554   case vmIntrinsics::_intBitsToFloat:
 555   case vmIntrinsics::_doubleToRawLongBits:
 556   case vmIntrinsics::_doubleToLongBits:
 557   case vmIntrinsics::_longBitsToDouble:
 558   case vmIntrinsics::_floatToFloat16:
 559   case vmIntrinsics::_float16ToFloat:           return inline_fp_conversions(intrinsic_id());
 560   case vmIntrinsics::_sqrt_float16:             return inline_fp16_operations(intrinsic_id(), 1);
 561   case vmIntrinsics::_fma_float16:              return inline_fp16_operations(intrinsic_id(), 3);
 562   case vmIntrinsics::_floatIsFinite:
 563   case vmIntrinsics::_floatIsInfinite:
 564   case vmIntrinsics::_doubleIsFinite:
 565   case vmIntrinsics::_doubleIsInfinite:         return inline_fp_range_check(intrinsic_id());
 566 
 567   case vmIntrinsics::_numberOfLeadingZeros_i:
 568   case vmIntrinsics::_numberOfLeadingZeros_l:
 569   case vmIntrinsics::_numberOfTrailingZeros_i:
 570   case vmIntrinsics::_numberOfTrailingZeros_l:
 571   case vmIntrinsics::_bitCount_i:
 572   case vmIntrinsics::_bitCount_l:
 573   case vmIntrinsics::_reverse_i:
 574   case vmIntrinsics::_reverse_l:
 575   case vmIntrinsics::_reverseBytes_i:
 576   case vmIntrinsics::_reverseBytes_l:
 577   case vmIntrinsics::_reverseBytes_s:
 578   case vmIntrinsics::_reverseBytes_c:           return inline_number_methods(intrinsic_id());
 579 
 580   case vmIntrinsics::_compress_i:
 581   case vmIntrinsics::_compress_l:
 582   case vmIntrinsics::_expand_i:
 583   case vmIntrinsics::_expand_l:                 return inline_bitshuffle_methods(intrinsic_id());
 584 
 585   case vmIntrinsics::_compareUnsigned_i:
 586   case vmIntrinsics::_compareUnsigned_l:        return inline_compare_unsigned(intrinsic_id());
 587 
 588   case vmIntrinsics::_divideUnsigned_i:
 589   case vmIntrinsics::_divideUnsigned_l:
 590   case vmIntrinsics::_remainderUnsigned_i:
 591   case vmIntrinsics::_remainderUnsigned_l:      return inline_divmod_methods(intrinsic_id());
 592 
 593   case vmIntrinsics::_getCallerClass:           return inline_native_Reflection_getCallerClass();
 594 
 595   case vmIntrinsics::_Reference_get0:           return inline_reference_get0();
 596   case vmIntrinsics::_Reference_refersTo0:      return inline_reference_refersTo0(false);
 597   case vmIntrinsics::_PhantomReference_refersTo0: return inline_reference_refersTo0(true);
 598   case vmIntrinsics::_Reference_clear0:         return inline_reference_clear0(false);
 599   case vmIntrinsics::_PhantomReference_clear0:  return inline_reference_clear0(true);
 600 
 601   case vmIntrinsics::_Class_cast:               return inline_Class_cast();
 602 
 603   case vmIntrinsics::_aescrypt_encryptBlock:
 604   case vmIntrinsics::_aescrypt_decryptBlock:    return inline_aescrypt_Block(intrinsic_id());
 605 
 606   case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
 607   case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
 608     return inline_cipherBlockChaining_AESCrypt(intrinsic_id());
 609 
 610   case vmIntrinsics::_electronicCodeBook_encryptAESCrypt:
 611   case vmIntrinsics::_electronicCodeBook_decryptAESCrypt:
 612     return inline_electronicCodeBook_AESCrypt(intrinsic_id());
 613 
 614   case vmIntrinsics::_counterMode_AESCrypt:
 615     return inline_counterMode_AESCrypt(intrinsic_id());
 616 
 617   case vmIntrinsics::_galoisCounterMode_AESCrypt:
 618     return inline_galoisCounterMode_AESCrypt();
 619 
 620   case vmIntrinsics::_md5_implCompress:
 621   case vmIntrinsics::_sha_implCompress:
 622   case vmIntrinsics::_sha2_implCompress:
 623   case vmIntrinsics::_sha5_implCompress:
 624   case vmIntrinsics::_sha3_implCompress:
 625     return inline_digestBase_implCompress(intrinsic_id());
 626   case vmIntrinsics::_double_keccak:
 627     return inline_double_keccak();
 628 
 629   case vmIntrinsics::_digestBase_implCompressMB:
 630     return inline_digestBase_implCompressMB(predicate);
 631 
 632   case vmIntrinsics::_multiplyToLen:
 633     return inline_multiplyToLen();
 634 
 635   case vmIntrinsics::_squareToLen:
 636     return inline_squareToLen();
 637 
 638   case vmIntrinsics::_mulAdd:
 639     return inline_mulAdd();
 640 
 641   case vmIntrinsics::_montgomeryMultiply:
 642     return inline_montgomeryMultiply();
 643   case vmIntrinsics::_montgomerySquare:
 644     return inline_montgomerySquare();
 645 
 646   case vmIntrinsics::_bigIntegerRightShiftWorker:
 647     return inline_bigIntegerShift(true);
 648   case vmIntrinsics::_bigIntegerLeftShiftWorker:
 649     return inline_bigIntegerShift(false);
 650 
 651   case vmIntrinsics::_vectorizedMismatch:
 652     return inline_vectorizedMismatch();
 653 
 654   case vmIntrinsics::_ghash_processBlocks:
 655     return inline_ghash_processBlocks();
 656   case vmIntrinsics::_chacha20Block:
 657     return inline_chacha20Block();
 658   case vmIntrinsics::_kyberNtt:
 659     return inline_kyberNtt();
 660   case vmIntrinsics::_kyberInverseNtt:
 661     return inline_kyberInverseNtt();
 662   case vmIntrinsics::_kyberNttMult:
 663     return inline_kyberNttMult();
 664   case vmIntrinsics::_kyberAddPoly_2:
 665     return inline_kyberAddPoly_2();
 666   case vmIntrinsics::_kyberAddPoly_3:
 667     return inline_kyberAddPoly_3();
 668   case vmIntrinsics::_kyber12To16:
 669     return inline_kyber12To16();
 670   case vmIntrinsics::_kyberBarrettReduce:
 671     return inline_kyberBarrettReduce();
 672   case vmIntrinsics::_dilithiumAlmostNtt:
 673     return inline_dilithiumAlmostNtt();
 674   case vmIntrinsics::_dilithiumAlmostInverseNtt:
 675     return inline_dilithiumAlmostInverseNtt();
 676   case vmIntrinsics::_dilithiumNttMult:
 677     return inline_dilithiumNttMult();
 678   case vmIntrinsics::_dilithiumMontMulByConstant:
 679     return inline_dilithiumMontMulByConstant();
 680   case vmIntrinsics::_dilithiumDecomposePoly:
 681     return inline_dilithiumDecomposePoly();
 682   case vmIntrinsics::_base64_encodeBlock:
 683     return inline_base64_encodeBlock();
 684   case vmIntrinsics::_base64_decodeBlock:
 685     return inline_base64_decodeBlock();
 686   case vmIntrinsics::_poly1305_processBlocks:
 687     return inline_poly1305_processBlocks();
 688   case vmIntrinsics::_intpoly_montgomeryMult_P256:
 689     return inline_intpoly_montgomeryMult_P256();
 690   case vmIntrinsics::_intpoly_assign:
 691     return inline_intpoly_assign();
 692   case vmIntrinsics::_encodeISOArray:
 693   case vmIntrinsics::_encodeByteISOArray:
 694     return inline_encodeISOArray(false);
 695   case vmIntrinsics::_encodeAsciiArray:
 696     return inline_encodeISOArray(true);
 697 
 698   case vmIntrinsics::_updateCRC32:
 699     return inline_updateCRC32();
 700   case vmIntrinsics::_updateBytesCRC32:
 701     return inline_updateBytesCRC32();
 702   case vmIntrinsics::_updateByteBufferCRC32:
 703     return inline_updateByteBufferCRC32();
 704 
 705   case vmIntrinsics::_updateBytesCRC32C:
 706     return inline_updateBytesCRC32C();
 707   case vmIntrinsics::_updateDirectByteBufferCRC32C:
 708     return inline_updateDirectByteBufferCRC32C();
 709 
 710   case vmIntrinsics::_updateBytesAdler32:
 711     return inline_updateBytesAdler32();
 712   case vmIntrinsics::_updateByteBufferAdler32:
 713     return inline_updateByteBufferAdler32();
 714 
 715   case vmIntrinsics::_profileBoolean:
 716     return inline_profileBoolean();
 717   case vmIntrinsics::_isCompileConstant:
 718     return inline_isCompileConstant();
 719 
 720   case vmIntrinsics::_countPositives:
 721     return inline_countPositives();
 722 
 723   case vmIntrinsics::_fmaD:
 724   case vmIntrinsics::_fmaF:
 725     return inline_fma(intrinsic_id());
 726 
 727   case vmIntrinsics::_isDigit:
 728   case vmIntrinsics::_isLowerCase:
 729   case vmIntrinsics::_isUpperCase:
 730   case vmIntrinsics::_isWhitespace:
 731     return inline_character_compare(intrinsic_id());
 732 
 733   case vmIntrinsics::_min:
 734   case vmIntrinsics::_max:
 735   case vmIntrinsics::_min_strict:
 736   case vmIntrinsics::_max_strict:
 737   case vmIntrinsics::_minL:
 738   case vmIntrinsics::_maxL:
 739   case vmIntrinsics::_minF:
 740   case vmIntrinsics::_maxF:
 741   case vmIntrinsics::_minD:
 742   case vmIntrinsics::_maxD:
 743   case vmIntrinsics::_minF_strict:
 744   case vmIntrinsics::_maxF_strict:
 745   case vmIntrinsics::_minD_strict:
 746   case vmIntrinsics::_maxD_strict:
 747     return inline_min_max(intrinsic_id());
 748 
 749   case vmIntrinsics::_VectorUnaryOp:
 750     return inline_vector_nary_operation(1);
 751   case vmIntrinsics::_VectorBinaryOp:
 752     return inline_vector_nary_operation(2);
 753   case vmIntrinsics::_VectorUnaryLibOp:
 754     return inline_vector_call(1);
 755   case vmIntrinsics::_VectorBinaryLibOp:
 756     return inline_vector_call(2);
 757   case vmIntrinsics::_VectorTernaryOp:
 758     return inline_vector_nary_operation(3);
 759   case vmIntrinsics::_VectorFromBitsCoerced:
 760     return inline_vector_frombits_coerced();
 761   case vmIntrinsics::_VectorMaskOp:
 762     return inline_vector_mask_operation();
 763   case vmIntrinsics::_VectorLoadOp:
 764     return inline_vector_mem_operation(/*is_store=*/false);
 765   case vmIntrinsics::_VectorLoadMaskedOp:
 766     return inline_vector_mem_masked_operation(/*is_store*/false);
 767   case vmIntrinsics::_VectorStoreOp:
 768     return inline_vector_mem_operation(/*is_store=*/true);
 769   case vmIntrinsics::_VectorStoreMaskedOp:
 770     return inline_vector_mem_masked_operation(/*is_store=*/true);
 771   case vmIntrinsics::_VectorGatherOp:
 772     return inline_vector_gather_scatter(/*is_scatter*/ false);
 773   case vmIntrinsics::_VectorScatterOp:
 774     return inline_vector_gather_scatter(/*is_scatter*/ true);
 775   case vmIntrinsics::_VectorReductionCoerced:
 776     return inline_vector_reduction();
 777   case vmIntrinsics::_VectorTest:
 778     return inline_vector_test();
 779   case vmIntrinsics::_VectorBlend:
 780     return inline_vector_blend();
 781   case vmIntrinsics::_VectorRearrange:
 782     return inline_vector_rearrange();
 783   case vmIntrinsics::_VectorSelectFrom:
 784     return inline_vector_select_from();
 785   case vmIntrinsics::_VectorCompare:
 786     return inline_vector_compare();
 787   case vmIntrinsics::_VectorBroadcastInt:
 788     return inline_vector_broadcast_int();
 789   case vmIntrinsics::_VectorConvert:
 790     return inline_vector_convert();
 791   case vmIntrinsics::_VectorInsert:
 792     return inline_vector_insert();
 793   case vmIntrinsics::_VectorExtract:
 794     return inline_vector_extract();
 795   case vmIntrinsics::_VectorCompressExpand:
 796     return inline_vector_compress_expand();
 797   case vmIntrinsics::_VectorSelectFromTwoVectorOp:
 798     return inline_vector_select_from_two_vectors();
 799   case vmIntrinsics::_IndexVector:
 800     return inline_index_vector();
 801   case vmIntrinsics::_IndexPartiallyInUpperRange:
 802     return inline_index_partially_in_upper_range();
 803 
 804   case vmIntrinsics::_getObjectSize:
 805     return inline_getObjectSize();
 806 
 807   case vmIntrinsics::_blackhole:
 808     return inline_blackhole();
 809 
 810   default:
 811     // If you get here, it may be that someone has added a new intrinsic
 812     // to the list in vmIntrinsics.hpp without implementing it here.
 813 #ifndef PRODUCT
 814     if ((PrintMiscellaneous && (Verbose || WizardMode)) || PrintOpto) {
 815       tty->print_cr("*** Warning: Unimplemented intrinsic %s(%d)",
 816                     vmIntrinsics::name_at(intrinsic_id()), vmIntrinsics::as_int(intrinsic_id()));
 817     }
 818 #endif
 819     return false;
 820   }
 821 }
 822 
 823 Node* LibraryCallKit::try_to_predicate(int predicate) {
 824   if (!jvms()->has_method()) {
 825     // Root JVMState has a null method.
 826     assert(map()->memory()->Opcode() == Op_Parm, "");
 827     // Insert the memory aliasing node
 828     set_all_memory(reset_memory());
 829   }
 830   assert(merged_memory(), "");
 831 
 832   switch (intrinsic_id()) {
 833   case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
 834     return inline_cipherBlockChaining_AESCrypt_predicate(false);
 835   case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
 836     return inline_cipherBlockChaining_AESCrypt_predicate(true);
 837   case vmIntrinsics::_electronicCodeBook_encryptAESCrypt:
 838     return inline_electronicCodeBook_AESCrypt_predicate(false);
 839   case vmIntrinsics::_electronicCodeBook_decryptAESCrypt:
 840     return inline_electronicCodeBook_AESCrypt_predicate(true);
 841   case vmIntrinsics::_counterMode_AESCrypt:
 842     return inline_counterMode_AESCrypt_predicate();
 843   case vmIntrinsics::_digestBase_implCompressMB:
 844     return inline_digestBase_implCompressMB_predicate(predicate);
 845   case vmIntrinsics::_galoisCounterMode_AESCrypt:
 846     return inline_galoisCounterMode_AESCrypt_predicate();
 847 
 848   default:
 849     // If you get here, it may be that someone has added a new intrinsic
 850     // to the list in vmIntrinsics.hpp without implementing it here.
 851 #ifndef PRODUCT
 852     if ((PrintMiscellaneous && (Verbose || WizardMode)) || PrintOpto) {
 853       tty->print_cr("*** Warning: Unimplemented predicate for intrinsic %s(%d)",
 854                     vmIntrinsics::name_at(intrinsic_id()), vmIntrinsics::as_int(intrinsic_id()));
 855     }
 856 #endif
 857     Node* slow_ctl = control();
 858     set_control(top()); // No fast path intrinsic
 859     return slow_ctl;
 860   }
 861 }
 862 
 863 //------------------------------set_result-------------------------------
 864 // Helper function for finishing intrinsics.
 865 void LibraryCallKit::set_result(RegionNode* region, PhiNode* value) {
 866   record_for_igvn(region);
 867   set_control(_gvn.transform(region));
 868   set_result( _gvn.transform(value));
 869   assert(value->type()->basic_type() == result()->bottom_type()->basic_type(), "sanity");
 870 }
 871 
 872 //------------------------------generate_guard---------------------------
 873 // Helper function for generating guarded fast-slow graph structures.
 874 // The given 'test', if true, guards a slow path.  If the test fails
 875 // then a fast path can be taken.  (We generally hope it fails.)
 876 // In all cases, GraphKit::control() is updated to the fast path.
 877 // The returned value represents the control for the slow path.
 878 // The return value is never 'top'; it is either a valid control
 879 // or null if it is obvious that the slow path can never be taken.
 880 // Also, if region and the slow control are not null, the slow edge
 881 // is appended to the region.
 882 Node* LibraryCallKit::generate_guard(Node* test, RegionNode* region, float true_prob) {
 883   if (stopped()) {
 884     // Already short circuited.
 885     return nullptr;
 886   }
 887 
 888   // Build an if node and its projections.
 889   // If test is true we take the slow path, which we assume is uncommon.
 890   if (_gvn.type(test) == TypeInt::ZERO) {
 891     // The slow branch is never taken.  No need to build this guard.
 892     return nullptr;
 893   }
 894 
 895   IfNode* iff = create_and_map_if(control(), test, true_prob, COUNT_UNKNOWN);
 896 
 897   Node* if_slow = _gvn.transform(new IfTrueNode(iff));
 898   if (if_slow == top()) {
 899     // The slow branch is never taken.  No need to build this guard.
 900     return nullptr;
 901   }
 902 
 903   if (region != nullptr)
 904     region->add_req(if_slow);
 905 
 906   Node* if_fast = _gvn.transform(new IfFalseNode(iff));
 907   set_control(if_fast);
 908 
 909   return if_slow;
 910 }
 911 
 912 inline Node* LibraryCallKit::generate_slow_guard(Node* test, RegionNode* region) {
 913   return generate_guard(test, region, PROB_UNLIKELY_MAG(3));
 914 }
 915 inline Node* LibraryCallKit::generate_fair_guard(Node* test, RegionNode* region) {
 916   return generate_guard(test, region, PROB_FAIR);
 917 }
 918 
 919 inline Node* LibraryCallKit::generate_negative_guard(Node* index, RegionNode* region,
 920                                                      Node** pos_index, bool with_opaque) {
 921   if (stopped())
 922     return nullptr;                // already stopped
 923   if (_gvn.type(index)->higher_equal(TypeInt::POS)) // [0,maxint]
 924     return nullptr;                // index is already adequately typed
 925   Node* cmp_lt = _gvn.transform(new CmpINode(index, intcon(0)));
 926   Node* bol_lt = _gvn.transform(new BoolNode(cmp_lt, BoolTest::lt));
 927   if (with_opaque) {
 928     bol_lt = _gvn.transform(new OpaqueConstantBoolNode(C, bol_lt, false));
 929   }
 930   Node* is_neg = generate_guard(bol_lt, region, PROB_MIN);
 931   if (is_neg != nullptr && pos_index != nullptr) {
 932     // Emulate effect of Parse::adjust_map_after_if.
 933     Node* ccast = new CastIINode(control(), index, TypeInt::POS);
 934     (*pos_index) = _gvn.transform(ccast);
 935   }
 936   return is_neg;
 937 }
 938 
 939 // Make sure that 'position' is a valid limit index, in [0..length].
 940 // There are two equivalent plans for checking this:
 941 //   A. (offset + copyLength)  unsigned<=  arrayLength
 942 //   B. offset  <=  (arrayLength - copyLength)
 943 // We require that all of the values above, except for the sum and
 944 // difference, are already known to be non-negative.
 945 // Plan A is robust in the face of overflow, if offset and copyLength
 946 // are both hugely positive.
 947 //
 948 // Plan B is less direct and intuitive, but it does not overflow at
 949 // all, since the difference of two non-negatives is always
 950 // representable.  Whenever Java methods must perform the equivalent
 951 // check they generally use Plan B instead of Plan A.
 952 // For the moment we use Plan A.
 953 inline Node* LibraryCallKit::generate_limit_guard(Node* offset,
 954                                                   Node* subseq_length,
 955                                                   Node* array_length,
 956                                                   RegionNode* region,
 957                                                   bool with_opaque) {
 958   if (stopped())
 959     return nullptr;                // already stopped
 960   bool zero_offset = _gvn.type(offset) == TypeInt::ZERO;
 961   if (zero_offset && subseq_length->eqv_uncast(array_length))
 962     return nullptr;                // common case of whole-array copy
 963   Node* last = subseq_length;
 964   if (!zero_offset)             // last += offset
 965     last = _gvn.transform(new AddINode(last, offset));
 966   Node* cmp_lt = _gvn.transform(new CmpUNode(array_length, last));
 967   Node* bol_lt = _gvn.transform(new BoolNode(cmp_lt, BoolTest::lt));
 968   if (with_opaque) {
 969     bol_lt = _gvn.transform(new OpaqueConstantBoolNode(C, bol_lt, false));
 970   }
 971   Node* is_over = generate_guard(bol_lt, region, PROB_MIN);
 972   return is_over;
 973 }
 974 
 975 // Emit range checks for the given String.value byte array
 976 void LibraryCallKit::generate_string_range_check(Node* array,
 977                                                  Node* offset,
 978                                                  Node* count,
 979                                                  bool char_count,
 980                                                  bool halt_on_oob) {
 981   if (stopped()) {
 982     return; // already stopped
 983   }
 984   RegionNode* bailout = new RegionNode(1);
 985   record_for_igvn(bailout);
 986   if (char_count) {
 987     // Convert char count to byte count
 988     count = _gvn.transform(new LShiftINode(count, intcon(1)));
 989   }
 990 
 991   // Offset and count must not be negative
 992   generate_negative_guard(offset, bailout, nullptr, halt_on_oob);
 993   generate_negative_guard(count, bailout, nullptr, halt_on_oob);
 994   // Offset + count must not exceed length of array
 995   generate_limit_guard(offset, count, load_array_length(array), bailout, halt_on_oob);
 996 
 997   if (bailout->req() > 1) {
 998     if (halt_on_oob) {
 999       bailout = _gvn.transform(bailout)->as_Region();
1000       Node* frame = _gvn.transform(new ParmNode(C->start(), TypeFunc::FramePtr));
1001       Node* halt = _gvn.transform(new HaltNode(bailout, frame, "unexpected guard failure in intrinsic"));
1002       C->root()->add_req(halt);
1003     } else {
1004       PreserveJVMState pjvms(this);
1005       set_control(_gvn.transform(bailout));
1006       uncommon_trap(Deoptimization::Reason_intrinsic,
1007                     Deoptimization::Action_maybe_recompile);
1008     }
1009   }
1010 }
1011 
1012 Node* LibraryCallKit::current_thread_helper(Node*& tls_output, ByteSize handle_offset,
1013                                             bool is_immutable) {
1014   ciKlass* thread_klass = env()->Thread_klass();
1015   const Type* thread_type
1016     = TypeOopPtr::make_from_klass(thread_klass)->cast_to_ptr_type(TypePtr::NotNull);
1017 
1018   Node* thread = _gvn.transform(new ThreadLocalNode());
1019   Node* p = basic_plus_adr(top()/*!oop*/, thread, in_bytes(handle_offset));
1020   tls_output = thread;
1021 
1022   Node* thread_obj_handle
1023     = (is_immutable
1024       ? LoadNode::make(_gvn, nullptr, immutable_memory(), p, p->bottom_type()->is_ptr(),
1025         TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered)
1026       : make_load(nullptr, p, p->bottom_type()->is_ptr(), T_ADDRESS, MemNode::unordered));
1027   thread_obj_handle = _gvn.transform(thread_obj_handle);
1028 
1029   DecoratorSet decorators = IN_NATIVE;
1030   if (is_immutable) {
1031     decorators |= C2_IMMUTABLE_MEMORY;
1032   }
1033   return access_load(thread_obj_handle, thread_type, T_OBJECT, decorators);
1034 }
1035 
1036 //--------------------------generate_current_thread--------------------
1037 Node* LibraryCallKit::generate_current_thread(Node* &tls_output) {
1038   return current_thread_helper(tls_output, JavaThread::threadObj_offset(),
1039                                /*is_immutable*/false);
1040 }
1041 
1042 //--------------------------generate_virtual_thread--------------------
1043 Node* LibraryCallKit::generate_virtual_thread(Node* tls_output) {
1044   return current_thread_helper(tls_output, JavaThread::vthread_offset(),
1045                                !C->method()->changes_current_thread());
1046 }
1047 
1048 //------------------------------make_string_method_node------------------------
1049 // Helper method for String intrinsic functions. This version is called with
1050 // str1 and str2 pointing to byte[] nodes containing Latin1 or UTF16 encoded
1051 // characters (depending on 'is_byte'). cnt1 and cnt2 are pointing to Int nodes
1052 // containing the lengths of str1 and str2.
1053 Node* LibraryCallKit::make_string_method_node(int opcode, Node* str1_start, Node* cnt1, Node* str2_start, Node* cnt2, StrIntrinsicNode::ArgEnc ae) {
1054   Node* result = nullptr;
1055   switch (opcode) {
1056   case Op_StrIndexOf:
1057     result = new StrIndexOfNode(control(), memory(TypeAryPtr::BYTES),
1058                                 str1_start, cnt1, str2_start, cnt2, ae);
1059     break;
1060   case Op_StrComp:
1061     result = new StrCompNode(control(), memory(TypeAryPtr::BYTES),
1062                              str1_start, cnt1, str2_start, cnt2, ae);
1063     break;
1064   case Op_StrEquals:
1065     // We already know that cnt1 == cnt2 here (checked in 'inline_string_equals').
1066     // Use the constant length if there is one because optimized match rule may exist.
1067     result = new StrEqualsNode(control(), memory(TypeAryPtr::BYTES),
1068                                str1_start, str2_start, cnt2->is_Con() ? cnt2 : cnt1, ae);
1069     break;
1070   default:
1071     ShouldNotReachHere();
1072     return nullptr;
1073   }
1074 
1075   // All these intrinsics have checks.
1076   C->set_has_split_ifs(true); // Has chance for split-if optimization
1077   clear_upper_avx();
1078 
1079   return _gvn.transform(result);
1080 }
1081 
1082 //------------------------------inline_string_compareTo------------------------
1083 bool LibraryCallKit::inline_string_compareTo(StrIntrinsicNode::ArgEnc ae) {
1084   Node* arg1 = argument(0);
1085   Node* arg2 = argument(1);
1086 
1087   arg1 = must_be_not_null(arg1, true);
1088   arg2 = must_be_not_null(arg2, true);
1089 
1090   // Get start addr and length of first argument
1091   Node* arg1_start  = array_element_address(arg1, intcon(0), T_BYTE);
1092   Node* arg1_cnt    = load_array_length(arg1);
1093 
1094   // Get start addr and length of second argument
1095   Node* arg2_start  = array_element_address(arg2, intcon(0), T_BYTE);
1096   Node* arg2_cnt    = load_array_length(arg2);
1097 
1098   Node* result = make_string_method_node(Op_StrComp, arg1_start, arg1_cnt, arg2_start, arg2_cnt, ae);
1099   set_result(result);
1100   return true;
1101 }
1102 
1103 //------------------------------inline_string_equals------------------------
1104 bool LibraryCallKit::inline_string_equals(StrIntrinsicNode::ArgEnc ae) {
1105   Node* arg1 = argument(0);
1106   Node* arg2 = argument(1);
1107 
1108   // paths (plus control) merge
1109   RegionNode* region = new RegionNode(3);
1110   Node* phi = new PhiNode(region, TypeInt::BOOL);
1111 
1112   if (!stopped()) {
1113 
1114     arg1 = must_be_not_null(arg1, true);
1115     arg2 = must_be_not_null(arg2, true);
1116 
1117     // Get start addr and length of first argument
1118     Node* arg1_start  = array_element_address(arg1, intcon(0), T_BYTE);
1119     Node* arg1_cnt    = load_array_length(arg1);
1120 
1121     // Get start addr and length of second argument
1122     Node* arg2_start  = array_element_address(arg2, intcon(0), T_BYTE);
1123     Node* arg2_cnt    = load_array_length(arg2);
1124 
1125     // Check for arg1_cnt != arg2_cnt
1126     Node* cmp = _gvn.transform(new CmpINode(arg1_cnt, arg2_cnt));
1127     Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::ne));
1128     Node* if_ne = generate_slow_guard(bol, nullptr);
1129     if (if_ne != nullptr) {
1130       phi->init_req(2, intcon(0));
1131       region->init_req(2, if_ne);
1132     }
1133 
1134     // Check for count == 0 is done by assembler code for StrEquals.
1135 
1136     if (!stopped()) {
1137       Node* equals = make_string_method_node(Op_StrEquals, arg1_start, arg1_cnt, arg2_start, arg2_cnt, ae);
1138       phi->init_req(1, equals);
1139       region->init_req(1, control());
1140     }
1141   }
1142 
1143   // post merge
1144   set_control(_gvn.transform(region));
1145   record_for_igvn(region);
1146 
1147   set_result(_gvn.transform(phi));
1148   return true;
1149 }
1150 
1151 //------------------------------inline_array_equals----------------------------
1152 bool LibraryCallKit::inline_array_equals(StrIntrinsicNode::ArgEnc ae) {
1153   assert(ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::LL, "unsupported array types");
1154   Node* arg1 = argument(0);
1155   Node* arg2 = argument(1);
1156 
1157   const TypeAryPtr* mtype = (ae == StrIntrinsicNode::UU) ? TypeAryPtr::CHARS : TypeAryPtr::BYTES;
1158   set_result(_gvn.transform(new AryEqNode(control(), memory(mtype), arg1, arg2, ae)));
1159   clear_upper_avx();
1160 
1161   return true;
1162 }
1163 
1164 
1165 //------------------------------inline_countPositives------------------------------
1166 // int java.lang.StringCoding#countPositives0(byte[] ba, int off, int len)
1167 bool LibraryCallKit::inline_countPositives() {
1168   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1169     return false;
1170   }
1171 
1172   assert(callee()->signature()->size() == 3, "countPositives has 3 parameters");
1173   // no receiver since it is static method
1174   Node* ba         = argument(0);
1175   Node* offset     = argument(1);
1176   Node* len        = argument(2);
1177 
1178   ba = must_be_not_null(ba, true);
1179   generate_string_range_check(ba, offset, len, false, true);
1180   if (stopped()) {
1181     return true;
1182   }
1183 
1184   Node* ba_start = array_element_address(ba, offset, T_BYTE);
1185   Node* result = new CountPositivesNode(control(), memory(TypeAryPtr::BYTES), ba_start, len);
1186   set_result(_gvn.transform(result));
1187   clear_upper_avx();
1188   return true;
1189 }
1190 
1191 bool LibraryCallKit::inline_preconditions_checkIndex(BasicType bt) {
1192   Node* index = argument(0);
1193   Node* length = bt == T_INT ? argument(1) : argument(2);
1194   if (too_many_traps(Deoptimization::Reason_intrinsic) || too_many_traps(Deoptimization::Reason_range_check)) {
1195     return false;
1196   }
1197 
1198   // check that length is positive
1199   Node* len_pos_cmp = _gvn.transform(CmpNode::make(length, integercon(0, bt), bt));
1200   Node* len_pos_bol = _gvn.transform(new BoolNode(len_pos_cmp, BoolTest::ge));
1201 
1202   {
1203     BuildCutout unless(this, len_pos_bol, PROB_MAX);
1204     uncommon_trap(Deoptimization::Reason_intrinsic,
1205                   Deoptimization::Action_make_not_entrant);
1206   }
1207 
1208   if (stopped()) {
1209     // Length is known to be always negative during compilation and the IR graph so far constructed is good so return success
1210     return true;
1211   }
1212 
1213   // length is now known positive, add a cast node to make this explicit
1214   jlong upper_bound = _gvn.type(length)->is_integer(bt)->hi_as_long();
1215   Node* casted_length = ConstraintCastNode::make_cast_for_basic_type(
1216       control(), length, TypeInteger::make(0, upper_bound, Type::WidenMax, bt),
1217       ConstraintCastNode::DependencyType::FloatingNarrowing, bt);
1218   casted_length = _gvn.transform(casted_length);
1219   replace_in_map(length, casted_length);
1220   length = casted_length;
1221 
1222   // Use an unsigned comparison for the range check itself
1223   Node* rc_cmp = _gvn.transform(CmpNode::make(index, length, bt, true));
1224   BoolTest::mask btest = BoolTest::lt;
1225   Node* rc_bool = _gvn.transform(new BoolNode(rc_cmp, btest));
1226   RangeCheckNode* rc = new RangeCheckNode(control(), rc_bool, PROB_MAX, COUNT_UNKNOWN);
1227   _gvn.set_type(rc, rc->Value(&_gvn));
1228   if (!rc_bool->is_Con()) {
1229     record_for_igvn(rc);
1230   }
1231   set_control(_gvn.transform(new IfTrueNode(rc)));
1232   {
1233     PreserveJVMState pjvms(this);
1234     set_control(_gvn.transform(new IfFalseNode(rc)));
1235     uncommon_trap(Deoptimization::Reason_range_check,
1236                   Deoptimization::Action_make_not_entrant);
1237   }
1238 
1239   if (stopped()) {
1240     // Range check is known to always fail during compilation and the IR graph so far constructed is good so return success
1241     return true;
1242   }
1243 
1244   // index is now known to be >= 0 and < length, cast it
1245   Node* result = ConstraintCastNode::make_cast_for_basic_type(
1246       control(), index, TypeInteger::make(0, upper_bound, Type::WidenMax, bt),
1247       ConstraintCastNode::DependencyType::FloatingNarrowing, bt);
1248   result = _gvn.transform(result);
1249   set_result(result);
1250   replace_in_map(index, result);
1251   return true;
1252 }
1253 
1254 //------------------------------inline_string_indexOf------------------------
1255 bool LibraryCallKit::inline_string_indexOf(StrIntrinsicNode::ArgEnc ae) {
1256   if (!Matcher::match_rule_supported(Op_StrIndexOf)) {
1257     return false;
1258   }
1259   Node* src = argument(0);
1260   Node* tgt = argument(1);
1261 
1262   // Make the merge point
1263   RegionNode* result_rgn = new RegionNode(4);
1264   Node*       result_phi = new PhiNode(result_rgn, TypeInt::INT);
1265 
1266   src = must_be_not_null(src, true);
1267   tgt = must_be_not_null(tgt, true);
1268 
1269   // Get start addr and length of source string
1270   Node* src_start = array_element_address(src, intcon(0), T_BYTE);
1271   Node* src_count = load_array_length(src);
1272 
1273   // Get start addr and length of substring
1274   Node* tgt_start = array_element_address(tgt, intcon(0), T_BYTE);
1275   Node* tgt_count = load_array_length(tgt);
1276 
1277   Node* result = nullptr;
1278   bool call_opt_stub = (StubRoutines::_string_indexof_array[ae] != nullptr);
1279 
1280   if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
1281     // Divide src size by 2 if String is UTF16 encoded
1282     src_count = _gvn.transform(new RShiftINode(src_count, intcon(1)));
1283   }
1284   if (ae == StrIntrinsicNode::UU) {
1285     // Divide substring size by 2 if String is UTF16 encoded
1286     tgt_count = _gvn.transform(new RShiftINode(tgt_count, intcon(1)));
1287   }
1288 
1289   if (call_opt_stub) {
1290     Node* call = make_runtime_call(RC_LEAF, OptoRuntime::string_IndexOf_Type(),
1291                                    StubRoutines::_string_indexof_array[ae],
1292                                    "stringIndexOf", TypePtr::BOTTOM, src_start,
1293                                    src_count, tgt_start, tgt_count);
1294     result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
1295   } else {
1296     result = make_indexOf_node(src_start, src_count, tgt_start, tgt_count,
1297                                result_rgn, result_phi, ae);
1298   }
1299   if (result != nullptr) {
1300     result_phi->init_req(3, result);
1301     result_rgn->init_req(3, control());
1302   }
1303   set_control(_gvn.transform(result_rgn));
1304   record_for_igvn(result_rgn);
1305   set_result(_gvn.transform(result_phi));
1306 
1307   return true;
1308 }
1309 
1310 //-----------------------------inline_string_indexOfI-----------------------
1311 bool LibraryCallKit::inline_string_indexOfI(StrIntrinsicNode::ArgEnc ae) {
1312   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1313     return false;
1314   }
1315   if (!Matcher::match_rule_supported(Op_StrIndexOf)) {
1316     return false;
1317   }
1318 
1319   assert(callee()->signature()->size() == 5, "String.indexOf() has 5 arguments");
1320   Node* src         = argument(0); // byte[]
1321   Node* src_count   = argument(1); // char count
1322   Node* tgt         = argument(2); // byte[]
1323   Node* tgt_count   = argument(3); // char count
1324   Node* from_index  = argument(4); // char index
1325 
1326   src = must_be_not_null(src, true);
1327   tgt = must_be_not_null(tgt, true);
1328 
1329   // Multiply byte array index by 2 if String is UTF16 encoded
1330   Node* src_offset = (ae == StrIntrinsicNode::LL) ? from_index : _gvn.transform(new LShiftINode(from_index, intcon(1)));
1331   src_count = _gvn.transform(new SubINode(src_count, from_index));
1332   Node* src_start = array_element_address(src, src_offset, T_BYTE);
1333   Node* tgt_start = array_element_address(tgt, intcon(0), T_BYTE);
1334 
1335   // Range checks
1336   generate_string_range_check(src, src_offset, src_count, ae != StrIntrinsicNode::LL);
1337   generate_string_range_check(tgt, intcon(0), tgt_count, ae == StrIntrinsicNode::UU);
1338   if (stopped()) {
1339     return true;
1340   }
1341 
1342   RegionNode* region = new RegionNode(5);
1343   Node* phi = new PhiNode(region, TypeInt::INT);
1344   Node* result = nullptr;
1345 
1346   bool call_opt_stub = (StubRoutines::_string_indexof_array[ae] != nullptr);
1347 
1348   if (call_opt_stub) {
1349     Node* call = make_runtime_call(RC_LEAF, OptoRuntime::string_IndexOf_Type(),
1350                                    StubRoutines::_string_indexof_array[ae],
1351                                    "stringIndexOf", TypePtr::BOTTOM, src_start,
1352                                    src_count, tgt_start, tgt_count);
1353     result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
1354   } else {
1355     result = make_indexOf_node(src_start, src_count, tgt_start, tgt_count,
1356                                region, phi, ae);
1357   }
1358   if (result != nullptr) {
1359     // The result is index relative to from_index if substring was found, -1 otherwise.
1360     // Generate code which will fold into cmove.
1361     Node* cmp = _gvn.transform(new CmpINode(result, intcon(0)));
1362     Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::lt));
1363 
1364     Node* if_lt = generate_slow_guard(bol, nullptr);
1365     if (if_lt != nullptr) {
1366       // result == -1
1367       phi->init_req(3, result);
1368       region->init_req(3, if_lt);
1369     }
1370     if (!stopped()) {
1371       result = _gvn.transform(new AddINode(result, from_index));
1372       phi->init_req(4, result);
1373       region->init_req(4, control());
1374     }
1375   }
1376 
1377   set_control(_gvn.transform(region));
1378   record_for_igvn(region);
1379   set_result(_gvn.transform(phi));
1380   clear_upper_avx();
1381 
1382   return true;
1383 }
1384 
1385 // Create StrIndexOfNode with fast path checks
1386 Node* LibraryCallKit::make_indexOf_node(Node* src_start, Node* src_count, Node* tgt_start, Node* tgt_count,
1387                                         RegionNode* region, Node* phi, StrIntrinsicNode::ArgEnc ae) {
1388   // Check for substr count > string count
1389   Node* cmp = _gvn.transform(new CmpINode(tgt_count, src_count));
1390   Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::gt));
1391   Node* if_gt = generate_slow_guard(bol, nullptr);
1392   if (if_gt != nullptr) {
1393     phi->init_req(1, intcon(-1));
1394     region->init_req(1, if_gt);
1395   }
1396   if (!stopped()) {
1397     // Check for substr count == 0
1398     cmp = _gvn.transform(new CmpINode(tgt_count, intcon(0)));
1399     bol = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
1400     Node* if_zero = generate_slow_guard(bol, nullptr);
1401     if (if_zero != nullptr) {
1402       phi->init_req(2, intcon(0));
1403       region->init_req(2, if_zero);
1404     }
1405   }
1406   if (!stopped()) {
1407     return make_string_method_node(Op_StrIndexOf, src_start, src_count, tgt_start, tgt_count, ae);
1408   }
1409   return nullptr;
1410 }
1411 
1412 //-----------------------------inline_string_indexOfChar-----------------------
1413 bool LibraryCallKit::inline_string_indexOfChar(StrIntrinsicNode::ArgEnc ae) {
1414   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1415     return false;
1416   }
1417   if (!Matcher::match_rule_supported(Op_StrIndexOfChar)) {
1418     return false;
1419   }
1420   assert(callee()->signature()->size() == 4, "String.indexOfChar() has 4 arguments");
1421   Node* src         = argument(0); // byte[]
1422   Node* int_ch      = argument(1);
1423   Node* from_index  = argument(2);
1424   Node* max         = argument(3);
1425 
1426   src = must_be_not_null(src, true);
1427 
1428   Node* src_offset = ae == StrIntrinsicNode::L ? from_index : _gvn.transform(new LShiftINode(from_index, intcon(1)));
1429   Node* src_start = array_element_address(src, src_offset, T_BYTE);
1430   Node* src_count = _gvn.transform(new SubINode(max, from_index));
1431 
1432   // Range checks
1433   generate_string_range_check(src, src_offset, src_count, ae == StrIntrinsicNode::U);
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.compress(char[] src, int srcOff, byte[] dst, int dstOff, int len)
1478 //   int StringUTF16.compress(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.inflate(byte[] src, int srcOff, char[] dst, int dstOff, int len)
1481 //   void StringLatin1.inflate(byte[] src, int srcOff, byte[] dst, int dstOff, int len)
1482 bool LibraryCallKit::inline_string_copy(bool compress) {
1483   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1484     return false;
1485   }
1486   int nargs = 5;  // 2 oops, 3 ints
1487   assert(callee()->signature()->size() == nargs, "string copy has 5 arguments");
1488 
1489   Node* src         = argument(0);
1490   Node* src_offset  = argument(1);
1491   Node* dst         = argument(2);
1492   Node* dst_offset  = argument(3);
1493   Node* length      = argument(4);
1494 
1495   // Check for allocation before we add nodes that would confuse
1496   // tightly_coupled_allocation()
1497   AllocateArrayNode* alloc = tightly_coupled_allocation(dst);
1498 
1499   // Figure out the size and type of the elements we will be copying.
1500   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
1501   const TypeAryPtr* dst_type = dst->Value(&_gvn)->isa_aryptr();
1502   if (src_type == nullptr || dst_type == nullptr) {
1503     return false;
1504   }
1505   BasicType src_elem = src_type->elem()->array_element_basic_type();
1506   BasicType dst_elem = dst_type->elem()->array_element_basic_type();
1507   assert((compress && dst_elem == T_BYTE && (src_elem == T_BYTE || src_elem == T_CHAR)) ||
1508          (!compress && src_elem == T_BYTE && (dst_elem == T_BYTE || dst_elem == T_CHAR)),
1509          "Unsupported array types for inline_string_copy");
1510 
1511   src = must_be_not_null(src, true);
1512   dst = must_be_not_null(dst, true);
1513 
1514   // Convert char[] offsets to byte[] offsets
1515   bool convert_src = (compress && src_elem == T_BYTE);
1516   bool convert_dst = (!compress && dst_elem == T_BYTE);
1517   if (convert_src) {
1518     src_offset = _gvn.transform(new LShiftINode(src_offset, intcon(1)));
1519   } else if (convert_dst) {
1520     dst_offset = _gvn.transform(new LShiftINode(dst_offset, intcon(1)));
1521   }
1522 
1523   // Range checks
1524   generate_string_range_check(src, src_offset, length, convert_src);
1525   generate_string_range_check(dst, dst_offset, length, convert_dst);
1526   if (stopped()) {
1527     return true;
1528   }
1529 
1530   Node* src_start = array_element_address(src, src_offset, src_elem);
1531   Node* dst_start = array_element_address(dst, dst_offset, dst_elem);
1532   // 'src_start' points to src array + scaled offset
1533   // 'dst_start' points to dst array + scaled offset
1534   Node* count = nullptr;
1535   if (compress) {
1536     count = compress_string(src_start, TypeAryPtr::get_array_body_type(src_elem), dst_start, length);
1537   } else {
1538     inflate_string(src_start, dst_start, TypeAryPtr::get_array_body_type(dst_elem), length);
1539   }
1540 
1541   if (alloc != nullptr) {
1542     if (alloc->maybe_set_complete(&_gvn)) {
1543       // "You break it, you buy it."
1544       InitializeNode* init = alloc->initialization();
1545       assert(init->is_complete(), "we just did this");
1546       init->set_complete_with_arraycopy();
1547       assert(dst->is_CheckCastPP(), "sanity");
1548       assert(dst->in(0)->in(0) == init, "dest pinned");
1549     }
1550     // Do not let stores that initialize this object be reordered with
1551     // a subsequent store that would make this object accessible by
1552     // other threads.
1553     // Record what AllocateNode this StoreStore protects so that
1554     // escape analysis can go from the MemBarStoreStoreNode to the
1555     // AllocateNode and eliminate the MemBarStoreStoreNode if possible
1556     // based on the escape status of the AllocateNode.
1557     insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
1558   }
1559   if (compress) {
1560     set_result(_gvn.transform(count));
1561   }
1562   clear_upper_avx();
1563 
1564   return true;
1565 }
1566 
1567 #ifdef _LP64
1568 #define XTOP ,top() /*additional argument*/
1569 #else  //_LP64
1570 #define XTOP        /*no additional argument*/
1571 #endif //_LP64
1572 
1573 //------------------------inline_string_toBytesU--------------------------
1574 // public static byte[] StringUTF16.toBytes(char[] value, int off, int len)
1575 bool LibraryCallKit::inline_string_toBytesU() {
1576   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1577     return false;
1578   }
1579   // Get the arguments.
1580   Node* value     = argument(0);
1581   Node* offset    = argument(1);
1582   Node* length    = argument(2);
1583 
1584   Node* newcopy = nullptr;
1585 
1586   // Set the original stack and the reexecute bit for the interpreter to reexecute
1587   // the bytecode that invokes StringUTF16.toBytes() if deoptimization happens.
1588   { PreserveReexecuteState preexecs(this);
1589     jvms()->set_should_reexecute(true);
1590 
1591     // Check if a null path was taken unconditionally.
1592     value = null_check(value);
1593 
1594     RegionNode* bailout = new RegionNode(1);
1595     record_for_igvn(bailout);
1596 
1597     // Range checks
1598     generate_negative_guard(offset, bailout);
1599     generate_negative_guard(length, bailout);
1600     generate_limit_guard(offset, length, load_array_length(value), bailout);
1601     // Make sure that resulting byte[] length does not overflow Integer.MAX_VALUE
1602     generate_limit_guard(length, intcon(0), intcon(max_jint/2), bailout);
1603 
1604     if (bailout->req() > 1) {
1605       PreserveJVMState pjvms(this);
1606       set_control(_gvn.transform(bailout));
1607       uncommon_trap(Deoptimization::Reason_intrinsic,
1608                     Deoptimization::Action_maybe_recompile);
1609     }
1610     if (stopped()) {
1611       return true;
1612     }
1613 
1614     Node* size = _gvn.transform(new LShiftINode(length, intcon(1)));
1615     Node* klass_node = makecon(TypeKlassPtr::make(ciTypeArrayKlass::make(T_BYTE)));
1616     newcopy = new_array(klass_node, size, 0);  // no arguments to push
1617     AllocateArrayNode* alloc = tightly_coupled_allocation(newcopy);
1618     guarantee(alloc != nullptr, "created above");
1619 
1620     // Calculate starting addresses.
1621     Node* src_start = array_element_address(value, offset, T_CHAR);
1622     Node* dst_start = basic_plus_adr(newcopy, arrayOopDesc::base_offset_in_bytes(T_BYTE));
1623 
1624     // Check if dst array address is aligned to HeapWordSize
1625     bool aligned = (arrayOopDesc::base_offset_in_bytes(T_BYTE) % HeapWordSize == 0);
1626     // If true, then check if src array address is aligned to HeapWordSize
1627     if (aligned) {
1628       const TypeInt* toffset = gvn().type(offset)->is_int();
1629       aligned = toffset->is_con() && ((arrayOopDesc::base_offset_in_bytes(T_CHAR) +
1630                                        toffset->get_con() * type2aelembytes(T_CHAR)) % HeapWordSize == 0);
1631     }
1632 
1633     // Figure out which arraycopy runtime method to call (disjoint, uninitialized).
1634     const char* copyfunc_name = "arraycopy";
1635     address     copyfunc_addr = StubRoutines::select_arraycopy_function(T_CHAR, aligned, true, copyfunc_name, true);
1636     Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
1637                       OptoRuntime::fast_arraycopy_Type(),
1638                       copyfunc_addr, copyfunc_name, TypeRawPtr::BOTTOM,
1639                       src_start, dst_start, ConvI2X(length) XTOP);
1640     // Do not let reads from the cloned object float above the arraycopy.
1641     if (alloc->maybe_set_complete(&_gvn)) {
1642       // "You break it, you buy it."
1643       InitializeNode* init = alloc->initialization();
1644       assert(init->is_complete(), "we just did this");
1645       init->set_complete_with_arraycopy();
1646       assert(newcopy->is_CheckCastPP(), "sanity");
1647       assert(newcopy->in(0)->in(0) == init, "dest pinned");
1648     }
1649     // Do not let stores that initialize this object be reordered with
1650     // a subsequent store that would make this object accessible by
1651     // other threads.
1652     // Record what AllocateNode this StoreStore protects so that
1653     // escape analysis can go from the MemBarStoreStoreNode to the
1654     // AllocateNode and eliminate the MemBarStoreStoreNode if possible
1655     // based on the escape status of the AllocateNode.
1656     insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
1657   } // original reexecute is set back here
1658 
1659   C->set_has_split_ifs(true); // Has chance for split-if optimization
1660   if (!stopped()) {
1661     set_result(newcopy);
1662   }
1663   clear_upper_avx();
1664 
1665   return true;
1666 }
1667 
1668 //------------------------inline_string_getCharsU--------------------------
1669 // public void StringUTF16.getChars(byte[] src, int srcBegin, int srcEnd, char dst[], int dstBegin)
1670 bool LibraryCallKit::inline_string_getCharsU() {
1671   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1672     return false;
1673   }
1674 
1675   // Get the arguments.
1676   Node* src       = argument(0);
1677   Node* src_begin = argument(1);
1678   Node* src_end   = argument(2); // exclusive offset (i < src_end)
1679   Node* dst       = argument(3);
1680   Node* dst_begin = argument(4);
1681 
1682   // Check for allocation before we add nodes that would confuse
1683   // tightly_coupled_allocation()
1684   AllocateArrayNode* alloc = tightly_coupled_allocation(dst);
1685 
1686   // Check if a null path was taken unconditionally.
1687   src = null_check(src);
1688   dst = null_check(dst);
1689   if (stopped()) {
1690     return true;
1691   }
1692 
1693   // Get length and convert char[] offset to byte[] offset
1694   Node* length = _gvn.transform(new SubINode(src_end, src_begin));
1695   src_begin = _gvn.transform(new LShiftINode(src_begin, intcon(1)));
1696 
1697   // Range checks
1698   generate_string_range_check(src, src_begin, length, true);
1699   generate_string_range_check(dst, dst_begin, length, false);
1700   if (stopped()) {
1701     return true;
1702   }
1703 
1704   if (!stopped()) {
1705     // Calculate starting addresses.
1706     Node* src_start = array_element_address(src, src_begin, T_BYTE);
1707     Node* dst_start = array_element_address(dst, dst_begin, T_CHAR);
1708 
1709     // Check if array addresses are aligned to HeapWordSize
1710     const TypeInt* tsrc = gvn().type(src_begin)->is_int();
1711     const TypeInt* tdst = gvn().type(dst_begin)->is_int();
1712     bool aligned = tsrc->is_con() && ((arrayOopDesc::base_offset_in_bytes(T_BYTE) + tsrc->get_con() * type2aelembytes(T_BYTE)) % HeapWordSize == 0) &&
1713                    tdst->is_con() && ((arrayOopDesc::base_offset_in_bytes(T_CHAR) + tdst->get_con() * type2aelembytes(T_CHAR)) % HeapWordSize == 0);
1714 
1715     // Figure out which arraycopy runtime method to call (disjoint, uninitialized).
1716     const char* copyfunc_name = "arraycopy";
1717     address     copyfunc_addr = StubRoutines::select_arraycopy_function(T_CHAR, aligned, true, copyfunc_name, true);
1718     Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
1719                       OptoRuntime::fast_arraycopy_Type(),
1720                       copyfunc_addr, copyfunc_name, TypeRawPtr::BOTTOM,
1721                       src_start, dst_start, ConvI2X(length) XTOP);
1722     // Do not let reads from the cloned object float above the arraycopy.
1723     if (alloc != nullptr) {
1724       if (alloc->maybe_set_complete(&_gvn)) {
1725         // "You break it, you buy it."
1726         InitializeNode* init = alloc->initialization();
1727         assert(init->is_complete(), "we just did this");
1728         init->set_complete_with_arraycopy();
1729         assert(dst->is_CheckCastPP(), "sanity");
1730         assert(dst->in(0)->in(0) == init, "dest pinned");
1731       }
1732       // Do not let stores that initialize this object be reordered with
1733       // a subsequent store that would make this object accessible by
1734       // other threads.
1735       // Record what AllocateNode this StoreStore protects so that
1736       // escape analysis can go from the MemBarStoreStoreNode to the
1737       // AllocateNode and eliminate the MemBarStoreStoreNode if possible
1738       // based on the escape status of the AllocateNode.
1739       insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
1740     } else {
1741       insert_mem_bar(Op_MemBarCPUOrder);
1742     }
1743   }
1744 
1745   C->set_has_split_ifs(true); // Has chance for split-if optimization
1746   return true;
1747 }
1748 
1749 //----------------------inline_string_char_access----------------------------
1750 // Store/Load char to/from byte[] array.
1751 // static void StringUTF16.putChar(byte[] val, int index, int c)
1752 // static char StringUTF16.getChar(byte[] val, int index)
1753 bool LibraryCallKit::inline_string_char_access(bool is_store) {
1754   Node* value  = argument(0);
1755   Node* index  = argument(1);
1756   Node* ch = is_store ? argument(2) : nullptr;
1757 
1758   // This intrinsic accesses byte[] array as char[] array. Computing the offsets
1759   // correctly requires matched array shapes.
1760   assert (arrayOopDesc::base_offset_in_bytes(T_CHAR) == arrayOopDesc::base_offset_in_bytes(T_BYTE),
1761           "sanity: byte[] and char[] bases agree");
1762   assert (type2aelembytes(T_CHAR) == type2aelembytes(T_BYTE)*2,
1763           "sanity: byte[] and char[] scales agree");
1764 
1765   // Bail when getChar over constants is requested: constant folding would
1766   // reject folding mismatched char access over byte[]. A normal inlining for getChar
1767   // Java method would constant fold nicely instead.
1768   if (!is_store && value->is_Con() && index->is_Con()) {
1769     return false;
1770   }
1771 
1772   // Save state and restore on bailout
1773   SavedState old_state(this);
1774 
1775   value = must_be_not_null(value, true);
1776 
1777   Node* adr = array_element_address(value, index, T_CHAR);
1778   if (adr->is_top()) {
1779     return false;
1780   }
1781   old_state.discard();
1782   if (is_store) {
1783     access_store_at(value, adr, TypeAryPtr::BYTES, ch, TypeInt::CHAR, T_CHAR, IN_HEAP | MO_UNORDERED | C2_MISMATCHED);
1784   } else {
1785     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);
1786     set_result(ch);
1787   }
1788   return true;
1789 }
1790 
1791 
1792 //------------------------------inline_math-----------------------------------
1793 // public static double Math.abs(double)
1794 // public static double Math.sqrt(double)
1795 // public static double Math.log(double)
1796 // public static double Math.log10(double)
1797 // public static double Math.round(double)
1798 bool LibraryCallKit::inline_double_math(vmIntrinsics::ID id) {
1799   Node* arg = argument(0);
1800   Node* n = nullptr;
1801   switch (id) {
1802   case vmIntrinsics::_dabs:   n = new AbsDNode(                arg);  break;
1803   case vmIntrinsics::_dsqrt:
1804   case vmIntrinsics::_dsqrt_strict:
1805                               n = new SqrtDNode(C, control(),  arg);  break;
1806   case vmIntrinsics::_ceil:   n = RoundDoubleModeNode::make(_gvn, arg, RoundDoubleModeNode::rmode_ceil); break;
1807   case vmIntrinsics::_floor:  n = RoundDoubleModeNode::make(_gvn, arg, RoundDoubleModeNode::rmode_floor); break;
1808   case vmIntrinsics::_rint:   n = RoundDoubleModeNode::make(_gvn, arg, RoundDoubleModeNode::rmode_rint); break;
1809   case vmIntrinsics::_roundD: n = new RoundDNode(arg); break;
1810   case vmIntrinsics::_dcopySign: n = CopySignDNode::make(_gvn, arg, argument(2)); break;
1811   case vmIntrinsics::_dsignum: n = SignumDNode::make(_gvn, arg); break;
1812   default:  fatal_unexpected_iid(id);  break;
1813   }
1814   set_result(_gvn.transform(n));
1815   return true;
1816 }
1817 
1818 //------------------------------inline_math-----------------------------------
1819 // public static float Math.abs(float)
1820 // public static int Math.abs(int)
1821 // public static long Math.abs(long)
1822 bool LibraryCallKit::inline_math(vmIntrinsics::ID id) {
1823   Node* arg = argument(0);
1824   Node* n = nullptr;
1825   switch (id) {
1826   case vmIntrinsics::_fabs:   n = new AbsFNode(                arg);  break;
1827   case vmIntrinsics::_iabs:   n = new AbsINode(                arg);  break;
1828   case vmIntrinsics::_labs:   n = new AbsLNode(                arg);  break;
1829   case vmIntrinsics::_fcopySign: n = new CopySignFNode(arg, argument(1)); break;
1830   case vmIntrinsics::_fsignum: n = SignumFNode::make(_gvn, arg); break;
1831   case vmIntrinsics::_roundF: n = new RoundFNode(arg); break;
1832   default:  fatal_unexpected_iid(id);  break;
1833   }
1834   set_result(_gvn.transform(n));
1835   return true;
1836 }
1837 
1838 //------------------------------runtime_math-----------------------------
1839 bool LibraryCallKit::runtime_math(const TypeFunc* call_type, address funcAddr, const char* funcName) {
1840   assert(call_type == OptoRuntime::Math_DD_D_Type() || call_type == OptoRuntime::Math_D_D_Type(),
1841          "must be (DD)D or (D)D type");
1842 
1843   // Inputs
1844   Node* a = argument(0);
1845   Node* b = (call_type == OptoRuntime::Math_DD_D_Type()) ? argument(2) : nullptr;
1846 
1847   const TypePtr* no_memory_effects = nullptr;
1848   Node* trig = make_runtime_call(RC_LEAF | RC_PURE, call_type, funcAddr, funcName,
1849                                  no_memory_effects,
1850                                  a, top(), b, b ? top() : nullptr);
1851   Node* value = _gvn.transform(new ProjNode(trig, TypeFunc::Parms+0));
1852 #ifdef ASSERT
1853   Node* value_top = _gvn.transform(new ProjNode(trig, TypeFunc::Parms+1));
1854   assert(value_top == top(), "second value must be top");
1855 #endif
1856 
1857   set_result(value);
1858   return true;
1859 }
1860 
1861 //------------------------------inline_math_pow-----------------------------
1862 bool LibraryCallKit::inline_math_pow() {
1863   Node* exp = argument(2);
1864   const TypeD* d = _gvn.type(exp)->isa_double_constant();
1865   if (d != nullptr) {
1866     if (d->getd() == 2.0) {
1867       // Special case: pow(x, 2.0) => x * x
1868       Node* base = argument(0);
1869       set_result(_gvn.transform(new MulDNode(base, base)));
1870       return true;
1871     } else if (d->getd() == 0.5 && Matcher::match_rule_supported(Op_SqrtD)) {
1872       // Special case: pow(x, 0.5) => sqrt(x)
1873       Node* base = argument(0);
1874       Node* zero = _gvn.zerocon(T_DOUBLE);
1875 
1876       RegionNode* region = new RegionNode(3);
1877       Node* phi = new PhiNode(region, Type::DOUBLE);
1878 
1879       Node* cmp  = _gvn.transform(new CmpDNode(base, zero));
1880       // According to the API specs, pow(-0.0, 0.5) = 0.0 and sqrt(-0.0) = -0.0.
1881       // So pow(-0.0, 0.5) shouldn't be replaced with sqrt(-0.0).
1882       // -0.0/+0.0 are both excluded since floating-point comparison doesn't distinguish -0.0 from +0.0.
1883       Node* test = _gvn.transform(new BoolNode(cmp, BoolTest::le));
1884 
1885       Node* if_pow = generate_slow_guard(test, nullptr);
1886       Node* value_sqrt = _gvn.transform(new SqrtDNode(C, control(), base));
1887       phi->init_req(1, value_sqrt);
1888       region->init_req(1, control());
1889 
1890       if (if_pow != nullptr) {
1891         set_control(if_pow);
1892         address target = StubRoutines::dpow() != nullptr ? StubRoutines::dpow() :
1893                                                         CAST_FROM_FN_PTR(address, SharedRuntime::dpow);
1894         const TypePtr* no_memory_effects = nullptr;
1895         Node* trig = make_runtime_call(RC_LEAF, OptoRuntime::Math_DD_D_Type(), target, "POW",
1896                                        no_memory_effects, base, top(), exp, top());
1897         Node* value_pow = _gvn.transform(new ProjNode(trig, TypeFunc::Parms+0));
1898 #ifdef ASSERT
1899         Node* value_top = _gvn.transform(new ProjNode(trig, TypeFunc::Parms+1));
1900         assert(value_top == top(), "second value must be top");
1901 #endif
1902         phi->init_req(2, value_pow);
1903         region->init_req(2, _gvn.transform(new ProjNode(trig, TypeFunc::Control)));
1904       }
1905 
1906       C->set_has_split_ifs(true); // Has chance for split-if optimization
1907       set_control(_gvn.transform(region));
1908       record_for_igvn(region);
1909       set_result(_gvn.transform(phi));
1910 
1911       return true;
1912     }
1913   }
1914 
1915   return StubRoutines::dpow() != nullptr ?
1916     runtime_math(OptoRuntime::Math_DD_D_Type(), StubRoutines::dpow(),  "dpow") :
1917     runtime_math(OptoRuntime::Math_DD_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dpow),  "POW");
1918 }
1919 
1920 //------------------------------inline_math_native-----------------------------
1921 bool LibraryCallKit::inline_math_native(vmIntrinsics::ID id) {
1922   switch (id) {
1923   case vmIntrinsics::_dsin:
1924     return StubRoutines::dsin() != nullptr ?
1925       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dsin(), "dsin") :
1926       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dsin),   "SIN");
1927   case vmIntrinsics::_dcos:
1928     return StubRoutines::dcos() != nullptr ?
1929       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dcos(), "dcos") :
1930       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dcos),   "COS");
1931   case vmIntrinsics::_dtan:
1932     return StubRoutines::dtan() != nullptr ?
1933       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dtan(), "dtan") :
1934       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dtan), "TAN");
1935   case vmIntrinsics::_dsinh:
1936     return StubRoutines::dsinh() != nullptr ?
1937       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dsinh(), "dsinh") : false;
1938   case vmIntrinsics::_dtanh:
1939     return StubRoutines::dtanh() != nullptr ?
1940       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dtanh(), "dtanh") : false;
1941   case vmIntrinsics::_dcbrt:
1942     return StubRoutines::dcbrt() != nullptr ?
1943       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dcbrt(), "dcbrt") : false;
1944   case vmIntrinsics::_dexp:
1945     return StubRoutines::dexp() != nullptr ?
1946       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dexp(),  "dexp") :
1947       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dexp),  "EXP");
1948   case vmIntrinsics::_dlog:
1949     return StubRoutines::dlog() != nullptr ?
1950       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dlog(), "dlog") :
1951       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dlog),   "LOG");
1952   case vmIntrinsics::_dlog10:
1953     return StubRoutines::dlog10() != nullptr ?
1954       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dlog10(), "dlog10") :
1955       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dlog10), "LOG10");
1956 
1957   case vmIntrinsics::_roundD: return Matcher::match_rule_supported(Op_RoundD) ? inline_double_math(id) : false;
1958   case vmIntrinsics::_ceil:
1959   case vmIntrinsics::_floor:
1960   case vmIntrinsics::_rint:   return Matcher::match_rule_supported(Op_RoundDoubleMode) ? inline_double_math(id) : false;
1961 
1962   case vmIntrinsics::_dsqrt:
1963   case vmIntrinsics::_dsqrt_strict:
1964                               return Matcher::match_rule_supported(Op_SqrtD) ? inline_double_math(id) : false;
1965   case vmIntrinsics::_dabs:   return Matcher::has_match_rule(Op_AbsD)   ? inline_double_math(id) : false;
1966   case vmIntrinsics::_fabs:   return Matcher::match_rule_supported(Op_AbsF)   ? inline_math(id) : false;
1967   case vmIntrinsics::_iabs:   return Matcher::match_rule_supported(Op_AbsI)   ? inline_math(id) : false;
1968   case vmIntrinsics::_labs:   return Matcher::match_rule_supported(Op_AbsL)   ? inline_math(id) : false;
1969 
1970   case vmIntrinsics::_dpow:      return inline_math_pow();
1971   case vmIntrinsics::_dcopySign: return inline_double_math(id);
1972   case vmIntrinsics::_fcopySign: return inline_math(id);
1973   case vmIntrinsics::_dsignum: return Matcher::match_rule_supported(Op_SignumD) ? inline_double_math(id) : false;
1974   case vmIntrinsics::_fsignum: return Matcher::match_rule_supported(Op_SignumF) ? inline_math(id) : false;
1975   case vmIntrinsics::_roundF: return Matcher::match_rule_supported(Op_RoundF) ? inline_math(id) : false;
1976 
1977    // These intrinsics are not yet correctly implemented
1978   case vmIntrinsics::_datan2:
1979     return false;
1980 
1981   default:
1982     fatal_unexpected_iid(id);
1983     return false;
1984   }
1985 }
1986 
1987 //----------------------------inline_notify-----------------------------------*
1988 bool LibraryCallKit::inline_notify(vmIntrinsics::ID id) {
1989   const TypeFunc* ftype = OptoRuntime::monitor_notify_Type();
1990   address func;
1991   if (id == vmIntrinsics::_notify) {
1992     func = OptoRuntime::monitor_notify_Java();
1993   } else {
1994     func = OptoRuntime::monitor_notifyAll_Java();
1995   }
1996   Node* call = make_runtime_call(RC_NO_LEAF, ftype, func, nullptr, TypeRawPtr::BOTTOM, argument(0));
1997   make_slow_call_ex(call, env()->Throwable_klass(), false);
1998   return true;
1999 }
2000 
2001 
2002 //----------------------------inline_min_max-----------------------------------
2003 bool LibraryCallKit::inline_min_max(vmIntrinsics::ID id) {
2004   Node* a = nullptr;
2005   Node* b = nullptr;
2006   Node* n = nullptr;
2007   switch (id) {
2008     case vmIntrinsics::_min:
2009     case vmIntrinsics::_max:
2010     case vmIntrinsics::_minF:
2011     case vmIntrinsics::_maxF:
2012     case vmIntrinsics::_minF_strict:
2013     case vmIntrinsics::_maxF_strict:
2014     case vmIntrinsics::_min_strict:
2015     case vmIntrinsics::_max_strict:
2016       assert(callee()->signature()->size() == 2, "minF/maxF has 2 parameters of size 1 each.");
2017       a = argument(0);
2018       b = argument(1);
2019       break;
2020     case vmIntrinsics::_minD:
2021     case vmIntrinsics::_maxD:
2022     case vmIntrinsics::_minD_strict:
2023     case vmIntrinsics::_maxD_strict:
2024       assert(callee()->signature()->size() == 4, "minD/maxD has 2 parameters of size 2 each.");
2025       a = argument(0);
2026       b = argument(2);
2027       break;
2028     case vmIntrinsics::_minL:
2029     case vmIntrinsics::_maxL:
2030       assert(callee()->signature()->size() == 4, "minL/maxL has 2 parameters of size 2 each.");
2031       a = argument(0);
2032       b = argument(2);
2033       break;
2034     default:
2035       fatal_unexpected_iid(id);
2036       break;
2037   }
2038 
2039   switch (id) {
2040     case vmIntrinsics::_min:
2041     case vmIntrinsics::_min_strict:
2042       n = new MinINode(a, b);
2043       break;
2044     case vmIntrinsics::_max:
2045     case vmIntrinsics::_max_strict:
2046       n = new MaxINode(a, b);
2047       break;
2048     case vmIntrinsics::_minF:
2049     case vmIntrinsics::_minF_strict:
2050       n = new MinFNode(a, b);
2051       break;
2052     case vmIntrinsics::_maxF:
2053     case vmIntrinsics::_maxF_strict:
2054       n = new MaxFNode(a, b);
2055       break;
2056     case vmIntrinsics::_minD:
2057     case vmIntrinsics::_minD_strict:
2058       n = new MinDNode(a, b);
2059       break;
2060     case vmIntrinsics::_maxD:
2061     case vmIntrinsics::_maxD_strict:
2062       n = new MaxDNode(a, b);
2063       break;
2064     case vmIntrinsics::_minL:
2065       n = new MinLNode(_gvn.C, a, b);
2066       break;
2067     case vmIntrinsics::_maxL:
2068       n = new MaxLNode(_gvn.C, a, b);
2069       break;
2070     default:
2071       fatal_unexpected_iid(id);
2072       break;
2073   }
2074 
2075   set_result(_gvn.transform(n));
2076   return true;
2077 }
2078 
2079 bool LibraryCallKit::inline_math_mathExact(Node* math, Node* test) {
2080   if (builtin_throw_too_many_traps(Deoptimization::Reason_intrinsic,
2081                                    env()->ArithmeticException_instance())) {
2082     // It has been already too many times, but we cannot use builtin_throw (e.g. we care about backtraces),
2083     // so let's bail out intrinsic rather than risking deopting again.
2084     return false;
2085   }
2086 
2087   Node* bol = _gvn.transform( new BoolNode(test, BoolTest::overflow) );
2088   IfNode* check = create_and_map_if(control(), bol, PROB_UNLIKELY_MAG(3), COUNT_UNKNOWN);
2089   Node* fast_path = _gvn.transform( new IfFalseNode(check));
2090   Node* slow_path = _gvn.transform( new IfTrueNode(check) );
2091 
2092   {
2093     PreserveJVMState pjvms(this);
2094     PreserveReexecuteState preexecs(this);
2095     jvms()->set_should_reexecute(true);
2096 
2097     set_control(slow_path);
2098     set_i_o(i_o());
2099 
2100     builtin_throw(Deoptimization::Reason_intrinsic,
2101                   env()->ArithmeticException_instance(),
2102                   /*allow_too_many_traps*/ false);
2103   }
2104 
2105   set_control(fast_path);
2106   set_result(math);
2107   return true;
2108 }
2109 
2110 template <typename OverflowOp>
2111 bool LibraryCallKit::inline_math_overflow(Node* arg1, Node* arg2) {
2112   typedef typename OverflowOp::MathOp MathOp;
2113 
2114   MathOp* mathOp = new MathOp(arg1, arg2);
2115   Node* operation = _gvn.transform( mathOp );
2116   Node* ofcheck = _gvn.transform( new OverflowOp(arg1, arg2) );
2117   return inline_math_mathExact(operation, ofcheck);
2118 }
2119 
2120 bool LibraryCallKit::inline_math_addExactI(bool is_increment) {
2121   return inline_math_overflow<OverflowAddINode>(argument(0), is_increment ? intcon(1) : argument(1));
2122 }
2123 
2124 bool LibraryCallKit::inline_math_addExactL(bool is_increment) {
2125   return inline_math_overflow<OverflowAddLNode>(argument(0), is_increment ? longcon(1) : argument(2));
2126 }
2127 
2128 bool LibraryCallKit::inline_math_subtractExactI(bool is_decrement) {
2129   return inline_math_overflow<OverflowSubINode>(argument(0), is_decrement ? intcon(1) : argument(1));
2130 }
2131 
2132 bool LibraryCallKit::inline_math_subtractExactL(bool is_decrement) {
2133   return inline_math_overflow<OverflowSubLNode>(argument(0), is_decrement ? longcon(1) : argument(2));
2134 }
2135 
2136 bool LibraryCallKit::inline_math_negateExactI() {
2137   return inline_math_overflow<OverflowSubINode>(intcon(0), argument(0));
2138 }
2139 
2140 bool LibraryCallKit::inline_math_negateExactL() {
2141   return inline_math_overflow<OverflowSubLNode>(longcon(0), argument(0));
2142 }
2143 
2144 bool LibraryCallKit::inline_math_multiplyExactI() {
2145   return inline_math_overflow<OverflowMulINode>(argument(0), argument(1));
2146 }
2147 
2148 bool LibraryCallKit::inline_math_multiplyExactL() {
2149   return inline_math_overflow<OverflowMulLNode>(argument(0), argument(2));
2150 }
2151 
2152 bool LibraryCallKit::inline_math_multiplyHigh() {
2153   set_result(_gvn.transform(new MulHiLNode(argument(0), argument(2))));
2154   return true;
2155 }
2156 
2157 bool LibraryCallKit::inline_math_unsignedMultiplyHigh() {
2158   set_result(_gvn.transform(new UMulHiLNode(argument(0), argument(2))));
2159   return true;
2160 }
2161 
2162 inline int
2163 LibraryCallKit::classify_unsafe_addr(Node* &base, Node* &offset, BasicType type) {
2164   const TypePtr* base_type = TypePtr::NULL_PTR;
2165   if (base != nullptr)  base_type = _gvn.type(base)->isa_ptr();
2166   if (base_type == nullptr) {
2167     // Unknown type.
2168     return Type::AnyPtr;
2169   } else if (_gvn.type(base->uncast()) == TypePtr::NULL_PTR) {
2170     // Since this is a null+long form, we have to switch to a rawptr.
2171     base   = _gvn.transform(new CastX2PNode(offset));
2172     offset = MakeConX(0);
2173     return Type::RawPtr;
2174   } else if (base_type->base() == Type::RawPtr) {
2175     return Type::RawPtr;
2176   } else if (base_type->isa_oopptr()) {
2177     // Base is never null => always a heap address.
2178     if (!TypePtr::NULL_PTR->higher_equal(base_type)) {
2179       return Type::OopPtr;
2180     }
2181     // Offset is small => always a heap address.
2182     const TypeX* offset_type = _gvn.type(offset)->isa_intptr_t();
2183     if (offset_type != nullptr &&
2184         base_type->offset() == 0 &&     // (should always be?)
2185         offset_type->_lo >= 0 &&
2186         !MacroAssembler::needs_explicit_null_check(offset_type->_hi)) {
2187       return Type::OopPtr;
2188     } else if (type == T_OBJECT) {
2189       // off heap access to an oop doesn't make any sense. Has to be on
2190       // heap.
2191       return Type::OopPtr;
2192     }
2193     // Otherwise, it might either be oop+off or null+addr.
2194     return Type::AnyPtr;
2195   } else {
2196     // No information:
2197     return Type::AnyPtr;
2198   }
2199 }
2200 
2201 Node* LibraryCallKit::make_unsafe_address(Node*& base, Node* offset, BasicType type, bool can_cast) {
2202   Node* uncasted_base = base;
2203   int kind = classify_unsafe_addr(uncasted_base, offset, type);
2204   if (kind == Type::RawPtr) {
2205     return basic_plus_adr(top(), uncasted_base, offset);
2206   } else if (kind == Type::AnyPtr) {
2207     assert(base == uncasted_base, "unexpected base change");
2208     if (can_cast) {
2209       if (!_gvn.type(base)->speculative_maybe_null() &&
2210           !too_many_traps(Deoptimization::Reason_speculate_null_check)) {
2211         // According to profiling, this access is always on
2212         // heap. Casting the base to not null and thus avoiding membars
2213         // around the access should allow better optimizations
2214         Node* null_ctl = top();
2215         base = null_check_oop(base, &null_ctl, true, true, true);
2216         assert(null_ctl->is_top(), "no null control here");
2217         return basic_plus_adr(base, offset);
2218       } else if (_gvn.type(base)->speculative_always_null() &&
2219                  !too_many_traps(Deoptimization::Reason_speculate_null_assert)) {
2220         // According to profiling, this access is always off
2221         // heap.
2222         base = null_assert(base);
2223         Node* raw_base = _gvn.transform(new CastX2PNode(offset));
2224         offset = MakeConX(0);
2225         return basic_plus_adr(top(), raw_base, offset);
2226       }
2227     }
2228     // We don't know if it's an on heap or off heap access. Fall back
2229     // to raw memory access.
2230     Node* raw = _gvn.transform(new CheckCastPPNode(control(), base, TypeRawPtr::BOTTOM));
2231     return basic_plus_adr(top(), raw, offset);
2232   } else {
2233     assert(base == uncasted_base, "unexpected base change");
2234     // We know it's an on heap access so base can't be null
2235     if (TypePtr::NULL_PTR->higher_equal(_gvn.type(base))) {
2236       base = must_be_not_null(base, true);
2237     }
2238     return basic_plus_adr(base, offset);
2239   }
2240 }
2241 
2242 //--------------------------inline_number_methods-----------------------------
2243 // inline int     Integer.numberOfLeadingZeros(int)
2244 // inline int        Long.numberOfLeadingZeros(long)
2245 //
2246 // inline int     Integer.numberOfTrailingZeros(int)
2247 // inline int        Long.numberOfTrailingZeros(long)
2248 //
2249 // inline int     Integer.bitCount(int)
2250 // inline int        Long.bitCount(long)
2251 //
2252 // inline char  Character.reverseBytes(char)
2253 // inline short     Short.reverseBytes(short)
2254 // inline int     Integer.reverseBytes(int)
2255 // inline long       Long.reverseBytes(long)
2256 bool LibraryCallKit::inline_number_methods(vmIntrinsics::ID id) {
2257   Node* arg = argument(0);
2258   Node* n = nullptr;
2259   switch (id) {
2260   case vmIntrinsics::_numberOfLeadingZeros_i:   n = new CountLeadingZerosINode( arg); break;
2261   case vmIntrinsics::_numberOfLeadingZeros_l:   n = new CountLeadingZerosLNode( arg); break;
2262   case vmIntrinsics::_numberOfTrailingZeros_i:  n = new CountTrailingZerosINode(arg); break;
2263   case vmIntrinsics::_numberOfTrailingZeros_l:  n = new CountTrailingZerosLNode(arg); break;
2264   case vmIntrinsics::_bitCount_i:               n = new PopCountINode(          arg); break;
2265   case vmIntrinsics::_bitCount_l:               n = new PopCountLNode(          arg); break;
2266   case vmIntrinsics::_reverseBytes_c:           n = new ReverseBytesUSNode(     arg); break;
2267   case vmIntrinsics::_reverseBytes_s:           n = new ReverseBytesSNode(      arg); break;
2268   case vmIntrinsics::_reverseBytes_i:           n = new ReverseBytesINode(      arg); break;
2269   case vmIntrinsics::_reverseBytes_l:           n = new ReverseBytesLNode(      arg); break;
2270   case vmIntrinsics::_reverse_i:                n = new ReverseINode(           arg); break;
2271   case vmIntrinsics::_reverse_l:                n = new ReverseLNode(           arg); break;
2272   default:  fatal_unexpected_iid(id);  break;
2273   }
2274   set_result(_gvn.transform(n));
2275   return true;
2276 }
2277 
2278 //--------------------------inline_bitshuffle_methods-----------------------------
2279 // inline int Integer.compress(int, int)
2280 // inline int Integer.expand(int, int)
2281 // inline long Long.compress(long, long)
2282 // inline long Long.expand(long, long)
2283 bool LibraryCallKit::inline_bitshuffle_methods(vmIntrinsics::ID id) {
2284   Node* n = nullptr;
2285   switch (id) {
2286     case vmIntrinsics::_compress_i:  n = new CompressBitsNode(argument(0), argument(1), TypeInt::INT); break;
2287     case vmIntrinsics::_expand_i:    n = new ExpandBitsNode(argument(0),  argument(1), TypeInt::INT); break;
2288     case vmIntrinsics::_compress_l:  n = new CompressBitsNode(argument(0), argument(2), TypeLong::LONG); break;
2289     case vmIntrinsics::_expand_l:    n = new ExpandBitsNode(argument(0), argument(2), TypeLong::LONG); break;
2290     default:  fatal_unexpected_iid(id);  break;
2291   }
2292   set_result(_gvn.transform(n));
2293   return true;
2294 }
2295 
2296 //--------------------------inline_number_methods-----------------------------
2297 // inline int Integer.compareUnsigned(int, int)
2298 // inline int    Long.compareUnsigned(long, long)
2299 bool LibraryCallKit::inline_compare_unsigned(vmIntrinsics::ID id) {
2300   Node* arg1 = argument(0);
2301   Node* arg2 = (id == vmIntrinsics::_compareUnsigned_l) ? argument(2) : argument(1);
2302   Node* n = nullptr;
2303   switch (id) {
2304     case vmIntrinsics::_compareUnsigned_i:   n = new CmpU3Node(arg1, arg2);  break;
2305     case vmIntrinsics::_compareUnsigned_l:   n = new CmpUL3Node(arg1, arg2); break;
2306     default:  fatal_unexpected_iid(id);  break;
2307   }
2308   set_result(_gvn.transform(n));
2309   return true;
2310 }
2311 
2312 //--------------------------inline_unsigned_divmod_methods-----------------------------
2313 // inline int Integer.divideUnsigned(int, int)
2314 // inline int Integer.remainderUnsigned(int, int)
2315 // inline long Long.divideUnsigned(long, long)
2316 // inline long Long.remainderUnsigned(long, long)
2317 bool LibraryCallKit::inline_divmod_methods(vmIntrinsics::ID id) {
2318   Node* n = nullptr;
2319   switch (id) {
2320     case vmIntrinsics::_divideUnsigned_i: {
2321       zero_check_int(argument(1));
2322       // Compile-time detect of null-exception
2323       if (stopped()) {
2324         return true; // keep the graph constructed so far
2325       }
2326       n = new UDivINode(control(), argument(0), argument(1));
2327       break;
2328     }
2329     case vmIntrinsics::_divideUnsigned_l: {
2330       zero_check_long(argument(2));
2331       // Compile-time detect of null-exception
2332       if (stopped()) {
2333         return true; // keep the graph constructed so far
2334       }
2335       n = new UDivLNode(control(), argument(0), argument(2));
2336       break;
2337     }
2338     case vmIntrinsics::_remainderUnsigned_i: {
2339       zero_check_int(argument(1));
2340       // Compile-time detect of null-exception
2341       if (stopped()) {
2342         return true; // keep the graph constructed so far
2343       }
2344       n = new UModINode(control(), argument(0), argument(1));
2345       break;
2346     }
2347     case vmIntrinsics::_remainderUnsigned_l: {
2348       zero_check_long(argument(2));
2349       // Compile-time detect of null-exception
2350       if (stopped()) {
2351         return true; // keep the graph constructed so far
2352       }
2353       n = new UModLNode(control(), argument(0), argument(2));
2354       break;
2355     }
2356     default:  fatal_unexpected_iid(id);  break;
2357   }
2358   set_result(_gvn.transform(n));
2359   return true;
2360 }
2361 
2362 //----------------------------inline_unsafe_access----------------------------
2363 
2364 const TypeOopPtr* LibraryCallKit::sharpen_unsafe_type(Compile::AliasType* alias_type, const TypePtr *adr_type) {
2365   // Attempt to infer a sharper value type from the offset and base type.
2366   ciKlass* sharpened_klass = nullptr;
2367   bool null_free = false;
2368 
2369   // See if it is an instance field, with an object type.
2370   if (alias_type->field() != nullptr) {
2371     if (alias_type->field()->type()->is_klass()) {
2372       sharpened_klass = alias_type->field()->type()->as_klass();
2373       null_free = alias_type->field()->is_null_free();
2374     }
2375   }
2376 
2377   const TypeOopPtr* result = nullptr;
2378   // See if it is a narrow oop array.
2379   if (adr_type->isa_aryptr()) {
2380     if (adr_type->offset() >= refArrayOopDesc::base_offset_in_bytes()) {
2381       const TypeOopPtr* elem_type = adr_type->is_aryptr()->elem()->make_oopptr();
2382       null_free = adr_type->is_aryptr()->is_null_free();
2383       if (elem_type != nullptr && elem_type->is_loaded()) {
2384         // Sharpen the value type.
2385         result = elem_type;
2386       }
2387     }
2388   }
2389 
2390   // The sharpened class might be unloaded if there is no class loader
2391   // contraint in place.
2392   if (result == nullptr && sharpened_klass != nullptr && sharpened_klass->is_loaded()) {
2393     // Sharpen the value type.
2394     result = TypeOopPtr::make_from_klass(sharpened_klass);
2395     if (null_free) {
2396       result = result->join_speculative(TypePtr::NOTNULL)->is_oopptr();
2397     }
2398   }
2399   if (result != nullptr) {
2400 #ifndef PRODUCT
2401     if (C->print_intrinsics() || C->print_inlining()) {
2402       tty->print("  from base type:  ");  adr_type->dump(); tty->cr();
2403       tty->print("  sharpened value: ");  result->dump();    tty->cr();
2404     }
2405 #endif
2406   }
2407   return result;
2408 }
2409 
2410 DecoratorSet LibraryCallKit::mo_decorator_for_access_kind(AccessKind kind) {
2411   switch (kind) {
2412       case Relaxed:
2413         return MO_UNORDERED;
2414       case Opaque:
2415         return MO_RELAXED;
2416       case Acquire:
2417         return MO_ACQUIRE;
2418       case Release:
2419         return MO_RELEASE;
2420       case Volatile:
2421         return MO_SEQ_CST;
2422       default:
2423         ShouldNotReachHere();
2424         return 0;
2425   }
2426 }
2427 
2428 LibraryCallKit::SavedState::SavedState(LibraryCallKit* kit) :
2429   _kit(kit),
2430   _sp(kit->sp()),
2431   _jvms(kit->jvms()),
2432   _map(kit->clone_map()),
2433   _discarded(false)
2434 {
2435   for (DUIterator_Fast imax, i = kit->control()->fast_outs(imax); i < imax; i++) {
2436     Node* out = kit->control()->fast_out(i);
2437     if (out->is_CFG()) {
2438       _ctrl_succ.push(out);
2439     }
2440   }
2441 }
2442 
2443 LibraryCallKit::SavedState::~SavedState() {
2444   if (_discarded) {
2445     _kit->destruct_map_clone(_map);
2446     return;
2447   }
2448   _kit->jvms()->set_map(_map);
2449   _kit->jvms()->set_sp(_sp);
2450   _map->set_jvms(_kit->jvms());
2451   _kit->set_map(_map);
2452   _kit->set_sp(_sp);
2453   for (DUIterator_Fast imax, i = _kit->control()->fast_outs(imax); i < imax; i++) {
2454     Node* out = _kit->control()->fast_out(i);
2455     if (out->is_CFG() && out->in(0) == _kit->control() && out != _kit->map() && !_ctrl_succ.member(out)) {
2456       _kit->_gvn.hash_delete(out);
2457       out->set_req(0, _kit->C->top());
2458       _kit->C->record_for_igvn(out);
2459       --i; --imax;
2460       _kit->_gvn.hash_find_insert(out);
2461     }
2462   }
2463 }
2464 
2465 void LibraryCallKit::SavedState::discard() {
2466   _discarded = true;
2467 }
2468 
2469 bool LibraryCallKit::inline_unsafe_access(bool is_store, const BasicType type, const AccessKind kind, const bool unaligned) {
2470   if (callee()->is_static())  return false;  // caller must have the capability!
2471   DecoratorSet decorators = C2_UNSAFE_ACCESS;
2472   guarantee(!is_store || kind != Acquire, "Acquire accesses can be produced only for loads");
2473   guarantee( is_store || kind != Release, "Release accesses can be produced only for stores");
2474   assert(type != T_OBJECT || !unaligned, "unaligned access not supported with object type");
2475 
2476   if (is_reference_type(type)) {
2477     decorators |= ON_UNKNOWN_OOP_REF;
2478   }
2479 
2480   if (unaligned) {
2481     decorators |= C2_UNALIGNED;
2482   }
2483 
2484 #ifndef PRODUCT
2485   {
2486     ResourceMark rm;
2487     // Check the signatures.
2488     ciSignature* sig = callee()->signature();
2489 #ifdef ASSERT
2490     if (!is_store) {
2491       // Object getReference(Object base, int/long offset), etc.
2492       BasicType rtype = sig->return_type()->basic_type();
2493       assert(rtype == type, "getter must return the expected value");
2494       assert(sig->count() == 2, "oop getter has 2 arguments");
2495       assert(sig->type_at(0)->basic_type() == T_OBJECT, "getter base is object");
2496       assert(sig->type_at(1)->basic_type() == T_LONG, "getter offset is correct");
2497     } else {
2498       // void putReference(Object base, int/long offset, Object x), etc.
2499       assert(sig->return_type()->basic_type() == T_VOID, "putter must not return a value");
2500       assert(sig->count() == 3, "oop putter has 3 arguments");
2501       assert(sig->type_at(0)->basic_type() == T_OBJECT, "putter base is object");
2502       assert(sig->type_at(1)->basic_type() == T_LONG, "putter offset is correct");
2503       BasicType vtype = sig->type_at(sig->count()-1)->basic_type();
2504       assert(vtype == type, "putter must accept the expected value");
2505     }
2506 #endif // ASSERT
2507  }
2508 #endif //PRODUCT
2509 
2510   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
2511 
2512   Node* receiver = argument(0);  // type: oop
2513 
2514   // Build address expression.
2515   Node* heap_base_oop = top();
2516 
2517   // The base is either a Java object or a value produced by Unsafe.staticFieldBase
2518   Node* base = argument(1);  // type: oop
2519   // The offset is a value produced by Unsafe.staticFieldOffset or Unsafe.objectFieldOffset
2520   Node* offset = argument(2);  // type: long
2521   // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
2522   // to be plain byte offsets, which are also the same as those accepted
2523   // by oopDesc::field_addr.
2524   assert(Unsafe_field_offset_to_byte_offset(11) == 11,
2525          "fieldOffset must be byte-scaled");
2526 
2527   if (base->is_InlineType()) {
2528     assert(!is_store, "InlineTypeNodes are non-larval value objects");
2529     InlineTypeNode* vt = base->as_InlineType();
2530     if (offset->is_Con()) {
2531       long off = find_long_con(offset, 0);
2532       ciInlineKlass* vk = vt->type()->inline_klass();
2533       if ((long)(int)off != off || !vk->contains_field_offset(off)) {
2534         return false;
2535       }
2536 
2537       ciField* field = vk->get_non_flat_field_by_offset(off);
2538       if (field != nullptr) {
2539         BasicType bt = type2field[field->type()->basic_type()];
2540         if (bt == T_ARRAY || bt == T_NARROWOOP) {
2541           bt = T_OBJECT;
2542         }
2543         if (bt == type && !field->is_flat()) {
2544           Node* value = vt->field_value_by_offset(off, false);
2545           const Type* value_type = _gvn.type(value);
2546           if (value->is_InlineType()) {
2547             value = value->as_InlineType()->adjust_scalarization_depth(this);
2548           } else if (value_type->is_inlinetypeptr()) {
2549             value = InlineTypeNode::make_from_oop(this, value, value_type->inline_klass());
2550           }
2551           set_result(value);
2552           return true;
2553         }
2554       }
2555     }
2556     {
2557       // Re-execute the unsafe access if allocation triggers deoptimization.
2558       PreserveReexecuteState preexecs(this);
2559       jvms()->set_should_reexecute(true);
2560       vt = vt->buffer(this);
2561     }
2562     base = vt->get_oop();
2563   }
2564 
2565   // 32-bit machines ignore the high half!
2566   offset = ConvL2X(offset);
2567 
2568   // Save state and restore on bailout
2569   SavedState old_state(this);
2570 
2571   Node* adr = make_unsafe_address(base, offset, type, kind == Relaxed);
2572   assert(!stopped(), "Inlining of unsafe access failed: address construction stopped unexpectedly");
2573 
2574   if (_gvn.type(base->uncast())->isa_ptr() == TypePtr::NULL_PTR) {
2575     if (type != T_OBJECT) {
2576       decorators |= IN_NATIVE; // off-heap primitive access
2577     } else {
2578       return false; // off-heap oop accesses are not supported
2579     }
2580   } else {
2581     heap_base_oop = base; // on-heap or mixed access
2582   }
2583 
2584   // Can base be null? Otherwise, always on-heap access.
2585   bool can_access_non_heap = TypePtr::NULL_PTR->higher_equal(_gvn.type(base));
2586 
2587   if (!can_access_non_heap) {
2588     decorators |= IN_HEAP;
2589   }
2590 
2591   Node* val = is_store ? argument(4) : nullptr;
2592 
2593   const TypePtr* adr_type = _gvn.type(adr)->isa_ptr();
2594   if (adr_type == TypePtr::NULL_PTR) {
2595     return false; // off-heap access with zero address
2596   }
2597 
2598   // Try to categorize the address.
2599   Compile::AliasType* alias_type = C->alias_type(adr_type);
2600   assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
2601 
2602   if (alias_type->adr_type() == TypeInstPtr::KLASS ||
2603       alias_type->adr_type() == TypeAryPtr::RANGE) {
2604     return false; // not supported
2605   }
2606 
2607   bool mismatched = false;
2608   BasicType bt = T_ILLEGAL;
2609   ciField* field = nullptr;
2610   if (adr_type->isa_instptr()) {
2611     const TypeInstPtr* instptr = adr_type->is_instptr();
2612     ciInstanceKlass* k = instptr->instance_klass();
2613     int off = instptr->offset();
2614     if (instptr->const_oop() != nullptr &&
2615         k == ciEnv::current()->Class_klass() &&
2616         instptr->offset() >= (k->size_helper() * wordSize)) {
2617       k = instptr->const_oop()->as_instance()->java_lang_Class_klass()->as_instance_klass();
2618       field = k->get_field_by_offset(off, true);
2619     } else {
2620       field = k->get_non_flat_field_by_offset(off);
2621     }
2622     if (field != nullptr) {
2623       bt = type2field[field->type()->basic_type()];
2624     }
2625     if (bt != alias_type->basic_type()) {
2626       // Type mismatch. Is it an access to a nested flat field?
2627       field = k->get_field_by_offset(off, false);
2628       if (field != nullptr) {
2629         bt = type2field[field->type()->basic_type()];
2630       }
2631     }
2632     assert(bt == alias_type->basic_type(), "should match");
2633   } else {
2634     bt = alias_type->basic_type();
2635   }
2636 
2637   if (bt != T_ILLEGAL) {
2638     assert(alias_type->adr_type()->is_oopptr(), "should be on-heap access");
2639     if (bt == T_BYTE && adr_type->isa_aryptr()) {
2640       // Alias type doesn't differentiate between byte[] and boolean[]).
2641       // Use address type to get the element type.
2642       bt = adr_type->is_aryptr()->elem()->array_element_basic_type();
2643     }
2644     if (is_reference_type(bt, true)) {
2645       // accessing an array field with getReference is not a mismatch
2646       bt = T_OBJECT;
2647     }
2648     if ((bt == T_OBJECT) != (type == T_OBJECT)) {
2649       // Don't intrinsify mismatched object accesses
2650       return false;
2651     }
2652     mismatched = (bt != type);
2653   } else if (alias_type->adr_type()->isa_oopptr()) {
2654     mismatched = true; // conservatively mark all "wide" on-heap accesses as mismatched
2655   }
2656 
2657   old_state.discard();
2658   assert(!mismatched || alias_type->adr_type()->is_oopptr(), "off-heap access can't be mismatched");
2659 
2660   if (mismatched) {
2661     decorators |= C2_MISMATCHED;
2662   }
2663 
2664   // First guess at the value type.
2665   const Type *value_type = Type::get_const_basic_type(type);
2666 
2667   // Figure out the memory ordering.
2668   decorators |= mo_decorator_for_access_kind(kind);
2669 
2670   if (!is_store) {
2671     if (type == T_OBJECT) {
2672       const TypeOopPtr* tjp = sharpen_unsafe_type(alias_type, adr_type);
2673       if (tjp != nullptr) {
2674         value_type = tjp;
2675       }
2676     }
2677   }
2678 
2679   receiver = null_check(receiver);
2680   if (stopped()) {
2681     return true;
2682   }
2683   // Heap pointers get a null-check from the interpreter,
2684   // as a courtesy.  However, this is not guaranteed by Unsafe,
2685   // and it is not possible to fully distinguish unintended nulls
2686   // from intended ones in this API.
2687 
2688   if (!is_store) {
2689     Node* p = nullptr;
2690     // Try to constant fold a load from a constant field
2691 
2692     if (heap_base_oop != top() && field != nullptr && field->is_constant() && !field->is_flat() && !mismatched) {
2693       // final or stable field
2694       p = make_constant_from_field(field, heap_base_oop);
2695     }
2696 
2697     if (p == nullptr) { // Could not constant fold the load
2698       p = access_load_at(heap_base_oop, adr, adr_type, value_type, type, decorators);
2699       const TypeOopPtr* ptr = value_type->make_oopptr();
2700       if (ptr != nullptr && ptr->is_inlinetypeptr()) {
2701         // Load a non-flattened inline type from memory
2702         p = InlineTypeNode::make_from_oop(this, p, ptr->inline_klass());
2703       }
2704       // Normalize the value returned by getBoolean in the following cases
2705       if (type == T_BOOLEAN &&
2706           (mismatched ||
2707            heap_base_oop == top() ||                  // - heap_base_oop is null or
2708            (can_access_non_heap && field == nullptr)) // - heap_base_oop is potentially null
2709                                                       //   and the unsafe access is made to large offset
2710                                                       //   (i.e., larger than the maximum offset necessary for any
2711                                                       //   field access)
2712             ) {
2713           IdealKit ideal = IdealKit(this);
2714 #define __ ideal.
2715           IdealVariable normalized_result(ideal);
2716           __ declarations_done();
2717           __ set(normalized_result, p);
2718           __ if_then(p, BoolTest::ne, ideal.ConI(0));
2719           __ set(normalized_result, ideal.ConI(1));
2720           ideal.end_if();
2721           final_sync(ideal);
2722           p = __ value(normalized_result);
2723 #undef __
2724       }
2725     }
2726     if (type == T_ADDRESS) {
2727       p = gvn().transform(new CastP2XNode(nullptr, p));
2728       p = ConvX2UL(p);
2729     }
2730     // The load node has the control of the preceding MemBarCPUOrder.  All
2731     // following nodes will have the control of the MemBarCPUOrder inserted at
2732     // the end of this method.  So, pushing the load onto the stack at a later
2733     // point is fine.
2734     set_result(p);
2735   } else {
2736     if (bt == T_ADDRESS) {
2737       // Repackage the long as a pointer.
2738       val = ConvL2X(val);
2739       val = gvn().transform(new CastX2PNode(val));
2740     }
2741     access_store_at(heap_base_oop, adr, adr_type, val, value_type, type, decorators);
2742   }
2743 
2744   return true;
2745 }
2746 
2747 bool LibraryCallKit::inline_unsafe_flat_access(bool is_store, AccessKind kind) {
2748 #ifdef ASSERT
2749   {
2750     ResourceMark rm;
2751     // Check the signatures.
2752     ciSignature* sig = callee()->signature();
2753     assert(sig->type_at(0)->basic_type() == T_OBJECT, "base should be object, but is %s", type2name(sig->type_at(0)->basic_type()));
2754     assert(sig->type_at(1)->basic_type() == T_LONG, "offset should be long, but is %s", type2name(sig->type_at(1)->basic_type()));
2755     assert(sig->type_at(2)->basic_type() == T_INT, "layout kind should be int, but is %s", type2name(sig->type_at(3)->basic_type()));
2756     assert(sig->type_at(3)->basic_type() == T_OBJECT, "value klass should be object, but is %s", type2name(sig->type_at(4)->basic_type()));
2757     if (is_store) {
2758       assert(sig->return_type()->basic_type() == T_VOID, "putter must not return a value, but returns %s", type2name(sig->return_type()->basic_type()));
2759       assert(sig->count() == 5, "flat putter should have 5 arguments, but has %d", sig->count());
2760       assert(sig->type_at(4)->basic_type() == T_OBJECT, "put value should be object, but is %s", type2name(sig->type_at(5)->basic_type()));
2761     } else {
2762       assert(sig->return_type()->basic_type() == T_OBJECT, "getter must return an object, but returns %s", type2name(sig->return_type()->basic_type()));
2763       assert(sig->count() == 4, "flat getter should have 4 arguments, but has %d", sig->count());
2764     }
2765  }
2766 #endif // ASSERT
2767 
2768   assert(kind == Relaxed, "Only plain accesses for now");
2769   if (callee()->is_static()) {
2770     // caller must have the capability!
2771     return false;
2772   }
2773   C->set_has_unsafe_access(true);
2774 
2775   const TypeInstPtr* value_klass_node = _gvn.type(argument(5))->isa_instptr();
2776   if (value_klass_node == nullptr || value_klass_node->const_oop() == nullptr) {
2777     // parameter valueType is not a constant
2778     return false;
2779   }
2780   ciType* mirror_type = value_klass_node->const_oop()->as_instance()->java_mirror_type();
2781   if (!mirror_type->is_inlinetype()) {
2782     // Dead code
2783     return false;
2784   }
2785   ciInlineKlass* value_klass = mirror_type->as_inline_klass();
2786 
2787   const TypeInt* layout_type = _gvn.type(argument(4))->isa_int();
2788   if (layout_type == nullptr || !layout_type->is_con()) {
2789     // parameter layoutKind is not a constant
2790     return false;
2791   }
2792   assert(layout_type->get_con() >= static_cast<int>(LayoutKind::REFERENCE) &&
2793          layout_type->get_con() < static_cast<int>(LayoutKind::UNKNOWN),
2794          "invalid layoutKind %d", layout_type->get_con());
2795   LayoutKind layout = static_cast<LayoutKind>(layout_type->get_con());
2796   assert(layout == LayoutKind::REFERENCE || layout == LayoutKind::NULL_FREE_NON_ATOMIC_FLAT ||
2797          layout == LayoutKind::NULL_FREE_ATOMIC_FLAT || layout == LayoutKind::NULLABLE_ATOMIC_FLAT,
2798          "unexpected layoutKind %d", layout_type->get_con());
2799 
2800   null_check(argument(0));
2801   if (stopped()) {
2802     return true;
2803   }
2804 
2805   Node* base = must_be_not_null(argument(1), true);
2806   Node* offset = argument(2);
2807   const Type* base_type = _gvn.type(base);
2808 
2809   Node* ptr;
2810   bool immutable_memory = false;
2811   DecoratorSet decorators = C2_UNSAFE_ACCESS | IN_HEAP | MO_UNORDERED;
2812   if (base_type->isa_instptr()) {
2813     const TypeLong* offset_type = _gvn.type(offset)->isa_long();
2814     if (offset_type == nullptr || !offset_type->is_con()) {
2815       // Offset into a non-array should be a constant
2816       decorators |= C2_MISMATCHED;
2817     } else {
2818       int offset_con = checked_cast<int>(offset_type->get_con());
2819       ciInstanceKlass* base_klass = base_type->is_instptr()->instance_klass();
2820       ciField* field = base_klass->get_non_flat_field_by_offset(offset_con);
2821       if (field == nullptr) {
2822         assert(!base_klass->is_final(), "non-existence field at offset %d of class %s", offset_con, base_klass->name()->as_utf8());
2823         decorators |= C2_MISMATCHED;
2824       } else {
2825         assert(field->type() == value_klass, "field at offset %d of %s is of type %s, but valueType is %s",
2826                offset_con, base_klass->name()->as_utf8(), field->type()->name(), value_klass->name()->as_utf8());
2827         immutable_memory = field->is_strict() && field->is_final();
2828 
2829         if (base->is_InlineType()) {
2830           assert(!is_store, "Cannot store into a non-larval value object");
2831           set_result(base->as_InlineType()->field_value_by_offset(offset_con, false));
2832           return true;
2833         }
2834       }
2835     }
2836 
2837     if (base->is_InlineType()) {
2838       assert(!is_store, "Cannot store into a non-larval value object");
2839       base = base->as_InlineType()->buffer(this, true);
2840     }
2841     ptr = basic_plus_adr(base, ConvL2X(offset));
2842   } else if (base_type->isa_aryptr()) {
2843     decorators |= IS_ARRAY;
2844     if (layout == LayoutKind::REFERENCE) {
2845       if (!base_type->is_aryptr()->is_not_flat()) {
2846         const TypeAryPtr* array_type = base_type->is_aryptr()->cast_to_not_flat();
2847         Node* new_base = _gvn.transform(new CastPPNode(control(), base, array_type, ConstraintCastNode::DependencyType::NonFloatingNarrowing));
2848         replace_in_map(base, new_base);
2849         base = new_base;
2850       }
2851       ptr = basic_plus_adr(base, ConvL2X(offset));
2852     } else {
2853       if (UseArrayFlattening) {
2854         // Flat array must have an exact type
2855         bool is_null_free = !LayoutKindHelper::is_nullable_flat(layout);
2856         bool is_atomic = LayoutKindHelper::is_atomic_flat(layout);
2857         Node* new_base = cast_to_flat_array_exact(base, value_klass, is_null_free, is_atomic);
2858         replace_in_map(base, new_base);
2859         base = new_base;
2860         ptr = basic_plus_adr(base, ConvL2X(offset));
2861         const TypeAryPtr* ptr_type = _gvn.type(ptr)->is_aryptr();
2862         if (ptr_type->field_offset().get() != 0) {
2863           ptr = _gvn.transform(new CastPPNode(control(), ptr, ptr_type->with_field_offset(0), ConstraintCastNode::DependencyType::NonFloatingNarrowing));
2864         }
2865       } else {
2866         uncommon_trap(Deoptimization::Reason_intrinsic,
2867                       Deoptimization::Action_none);
2868         return true;
2869       }
2870     }
2871   } else {
2872     decorators |= C2_MISMATCHED;
2873     ptr = basic_plus_adr(base, ConvL2X(offset));
2874   }
2875 
2876   if (is_store) {
2877     Node* value = argument(6);
2878     const Type* value_type = _gvn.type(value);
2879     if (!value_type->is_inlinetypeptr()) {
2880       value_type = Type::get_const_type(value_klass)->filter_speculative(value_type);
2881       Node* new_value = _gvn.transform(new CastPPNode(control(), value, value_type, ConstraintCastNode::DependencyType::NonFloatingNarrowing));
2882       new_value = InlineTypeNode::make_from_oop(this, new_value, value_klass);
2883       replace_in_map(value, new_value);
2884       value = new_value;
2885     }
2886 
2887     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());
2888     if (layout == LayoutKind::REFERENCE) {
2889       const TypePtr* ptr_type = (decorators & C2_MISMATCHED) != 0 ? TypeRawPtr::BOTTOM : _gvn.type(ptr)->is_ptr();
2890       access_store_at(base, ptr, ptr_type, value, value_type, T_OBJECT, decorators);
2891     } else {
2892       bool atomic = LayoutKindHelper::is_atomic_flat(layout);
2893       bool null_free = !LayoutKindHelper::is_nullable_flat(layout);
2894       value->as_InlineType()->store_flat(this, base, ptr, atomic, immutable_memory, null_free, decorators);
2895     }
2896 
2897     return true;
2898   } else {
2899     decorators |= (C2_CONTROL_DEPENDENT_LOAD | C2_UNKNOWN_CONTROL_LOAD);
2900     InlineTypeNode* result;
2901     if (layout == LayoutKind::REFERENCE) {
2902       const TypePtr* ptr_type = (decorators & C2_MISMATCHED) != 0 ? TypeRawPtr::BOTTOM : _gvn.type(ptr)->is_ptr();
2903       Node* oop = access_load_at(base, ptr, ptr_type, Type::get_const_type(value_klass), T_OBJECT, decorators);
2904       result = InlineTypeNode::make_from_oop(this, oop, value_klass);
2905     } else {
2906       bool atomic = LayoutKindHelper::is_atomic_flat(layout);
2907       bool null_free = !LayoutKindHelper::is_nullable_flat(layout);
2908       result = InlineTypeNode::make_from_flat(this, value_klass, base, ptr, atomic, immutable_memory, null_free, decorators);
2909     }
2910 
2911     set_result(result);
2912     return true;
2913   }
2914 }
2915 
2916 //----------------------------inline_unsafe_load_store----------------------------
2917 // This method serves a couple of different customers (depending on LoadStoreKind):
2918 //
2919 // LS_cmp_swap:
2920 //
2921 //   boolean compareAndSetReference(Object o, long offset, Object expected, Object x);
2922 //   boolean compareAndSetInt(   Object o, long offset, int    expected, int    x);
2923 //   boolean compareAndSetLong(  Object o, long offset, long   expected, long   x);
2924 //
2925 // LS_cmp_swap_weak:
2926 //
2927 //   boolean weakCompareAndSetReference(       Object o, long offset, Object expected, Object x);
2928 //   boolean weakCompareAndSetReferencePlain(  Object o, long offset, Object expected, Object x);
2929 //   boolean weakCompareAndSetReferenceAcquire(Object o, long offset, Object expected, Object x);
2930 //   boolean weakCompareAndSetReferenceRelease(Object o, long offset, Object expected, Object x);
2931 //
2932 //   boolean weakCompareAndSetInt(          Object o, long offset, int    expected, int    x);
2933 //   boolean weakCompareAndSetIntPlain(     Object o, long offset, int    expected, int    x);
2934 //   boolean weakCompareAndSetIntAcquire(   Object o, long offset, int    expected, int    x);
2935 //   boolean weakCompareAndSetIntRelease(   Object o, long offset, int    expected, int    x);
2936 //
2937 //   boolean weakCompareAndSetLong(         Object o, long offset, long   expected, long   x);
2938 //   boolean weakCompareAndSetLongPlain(    Object o, long offset, long   expected, long   x);
2939 //   boolean weakCompareAndSetLongAcquire(  Object o, long offset, long   expected, long   x);
2940 //   boolean weakCompareAndSetLongRelease(  Object o, long offset, long   expected, long   x);
2941 //
2942 // LS_cmp_exchange:
2943 //
2944 //   Object compareAndExchangeReferenceVolatile(Object o, long offset, Object expected, Object x);
2945 //   Object compareAndExchangeReferenceAcquire( Object o, long offset, Object expected, Object x);
2946 //   Object compareAndExchangeReferenceRelease( Object o, long offset, Object expected, Object x);
2947 //
2948 //   Object compareAndExchangeIntVolatile(   Object o, long offset, Object expected, Object x);
2949 //   Object compareAndExchangeIntAcquire(    Object o, long offset, Object expected, Object x);
2950 //   Object compareAndExchangeIntRelease(    Object o, long offset, Object expected, Object x);
2951 //
2952 //   Object compareAndExchangeLongVolatile(  Object o, long offset, Object expected, Object x);
2953 //   Object compareAndExchangeLongAcquire(   Object o, long offset, Object expected, Object x);
2954 //   Object compareAndExchangeLongRelease(   Object o, long offset, Object expected, Object x);
2955 //
2956 // LS_get_add:
2957 //
2958 //   int  getAndAddInt( Object o, long offset, int  delta)
2959 //   long getAndAddLong(Object o, long offset, long delta)
2960 //
2961 // LS_get_set:
2962 //
2963 //   int    getAndSet(Object o, long offset, int    newValue)
2964 //   long   getAndSet(Object o, long offset, long   newValue)
2965 //   Object getAndSet(Object o, long offset, Object newValue)
2966 //
2967 bool LibraryCallKit::inline_unsafe_load_store(const BasicType type, const LoadStoreKind kind, const AccessKind access_kind) {
2968   // This basic scheme here is the same as inline_unsafe_access, but
2969   // differs in enough details that combining them would make the code
2970   // overly confusing.  (This is a true fact! I originally combined
2971   // them, but even I was confused by it!) As much code/comments as
2972   // possible are retained from inline_unsafe_access though to make
2973   // the correspondences clearer. - dl
2974 
2975   if (callee()->is_static())  return false;  // caller must have the capability!
2976 
2977   DecoratorSet decorators = C2_UNSAFE_ACCESS;
2978   decorators |= mo_decorator_for_access_kind(access_kind);
2979 
2980 #ifndef PRODUCT
2981   BasicType rtype;
2982   {
2983     ResourceMark rm;
2984     // Check the signatures.
2985     ciSignature* sig = callee()->signature();
2986     rtype = sig->return_type()->basic_type();
2987     switch(kind) {
2988       case LS_get_add:
2989       case LS_get_set: {
2990       // Check the signatures.
2991 #ifdef ASSERT
2992       assert(rtype == type, "get and set must return the expected type");
2993       assert(sig->count() == 3, "get and set has 3 arguments");
2994       assert(sig->type_at(0)->basic_type() == T_OBJECT, "get and set base is object");
2995       assert(sig->type_at(1)->basic_type() == T_LONG, "get and set offset is long");
2996       assert(sig->type_at(2)->basic_type() == type, "get and set must take expected type as new value/delta");
2997       assert(access_kind == Volatile, "mo is not passed to intrinsic nodes in current implementation");
2998 #endif // ASSERT
2999         break;
3000       }
3001       case LS_cmp_swap:
3002       case LS_cmp_swap_weak: {
3003       // Check the signatures.
3004 #ifdef ASSERT
3005       assert(rtype == T_BOOLEAN, "CAS must return boolean");
3006       assert(sig->count() == 4, "CAS has 4 arguments");
3007       assert(sig->type_at(0)->basic_type() == T_OBJECT, "CAS base is object");
3008       assert(sig->type_at(1)->basic_type() == T_LONG, "CAS offset is long");
3009 #endif // ASSERT
3010         break;
3011       }
3012       case LS_cmp_exchange: {
3013       // Check the signatures.
3014 #ifdef ASSERT
3015       assert(rtype == type, "CAS must return the expected type");
3016       assert(sig->count() == 4, "CAS has 4 arguments");
3017       assert(sig->type_at(0)->basic_type() == T_OBJECT, "CAS base is object");
3018       assert(sig->type_at(1)->basic_type() == T_LONG, "CAS offset is long");
3019 #endif // ASSERT
3020         break;
3021       }
3022       default:
3023         ShouldNotReachHere();
3024     }
3025   }
3026 #endif //PRODUCT
3027 
3028   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
3029 
3030   // Get arguments:
3031   Node* receiver = nullptr;
3032   Node* base     = nullptr;
3033   Node* offset   = nullptr;
3034   Node* oldval   = nullptr;
3035   Node* newval   = nullptr;
3036   switch(kind) {
3037     case LS_cmp_swap:
3038     case LS_cmp_swap_weak:
3039     case LS_cmp_exchange: {
3040       const bool two_slot_type = type2size[type] == 2;
3041       receiver = argument(0);  // type: oop
3042       base     = argument(1);  // type: oop
3043       offset   = argument(2);  // type: long
3044       oldval   = argument(4);  // type: oop, int, or long
3045       newval   = argument(two_slot_type ? 6 : 5);  // type: oop, int, or long
3046       break;
3047     }
3048     case LS_get_add:
3049     case LS_get_set: {
3050       receiver = argument(0);  // type: oop
3051       base     = argument(1);  // type: oop
3052       offset   = argument(2);  // type: long
3053       oldval   = nullptr;
3054       newval   = argument(4);  // type: oop, int, or long
3055       break;
3056     }
3057     default:
3058       ShouldNotReachHere();
3059   }
3060 
3061   // Build field offset expression.
3062   // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
3063   // to be plain byte offsets, which are also the same as those accepted
3064   // by oopDesc::field_addr.
3065   assert(Unsafe_field_offset_to_byte_offset(11) == 11, "fieldOffset must be byte-scaled");
3066   // 32-bit machines ignore the high half of long offsets
3067   offset = ConvL2X(offset);
3068   // Save state and restore on bailout
3069   SavedState old_state(this);
3070   Node* adr = make_unsafe_address(base, offset,type, false);
3071   const TypePtr *adr_type = _gvn.type(adr)->isa_ptr();
3072 
3073   Compile::AliasType* alias_type = C->alias_type(adr_type);
3074   BasicType bt = alias_type->basic_type();
3075   if (bt != T_ILLEGAL &&
3076       (is_reference_type(bt) != (type == T_OBJECT))) {
3077     // Don't intrinsify mismatched object accesses.
3078     return false;
3079   }
3080 
3081   old_state.discard();
3082 
3083   // For CAS, unlike inline_unsafe_access, there seems no point in
3084   // trying to refine types. Just use the coarse types here.
3085   assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
3086   const Type *value_type = Type::get_const_basic_type(type);
3087 
3088   switch (kind) {
3089     case LS_get_set:
3090     case LS_cmp_exchange: {
3091       if (type == T_OBJECT) {
3092         const TypeOopPtr* tjp = sharpen_unsafe_type(alias_type, adr_type);
3093         if (tjp != nullptr) {
3094           value_type = tjp;
3095         }
3096       }
3097       break;
3098     }
3099     case LS_cmp_swap:
3100     case LS_cmp_swap_weak:
3101     case LS_get_add:
3102       break;
3103     default:
3104       ShouldNotReachHere();
3105   }
3106 
3107   // Null check receiver.
3108   receiver = null_check(receiver);
3109   if (stopped()) {
3110     return true;
3111   }
3112 
3113   int alias_idx = C->get_alias_index(adr_type);
3114 
3115   if (is_reference_type(type)) {
3116     decorators |= IN_HEAP | ON_UNKNOWN_OOP_REF;
3117 
3118     if (oldval != nullptr && oldval->is_InlineType()) {
3119       // Re-execute the unsafe access if allocation triggers deoptimization.
3120       PreserveReexecuteState preexecs(this);
3121       jvms()->set_should_reexecute(true);
3122       oldval = oldval->as_InlineType()->buffer(this)->get_oop();
3123     }
3124     if (newval != nullptr && newval->is_InlineType()) {
3125       // Re-execute the unsafe access if allocation triggers deoptimization.
3126       PreserveReexecuteState preexecs(this);
3127       jvms()->set_should_reexecute(true);
3128       newval = newval->as_InlineType()->buffer(this)->get_oop();
3129     }
3130 
3131     // Transformation of a value which could be null pointer (CastPP #null)
3132     // could be delayed during Parse (for example, in adjust_map_after_if()).
3133     // Execute transformation here to avoid barrier generation in such case.
3134     if (_gvn.type(newval) == TypePtr::NULL_PTR)
3135       newval = _gvn.makecon(TypePtr::NULL_PTR);
3136 
3137     if (oldval != nullptr && _gvn.type(oldval) == TypePtr::NULL_PTR) {
3138       // Refine the value to a null constant, when it is known to be null
3139       oldval = _gvn.makecon(TypePtr::NULL_PTR);
3140     }
3141   }
3142 
3143   Node* result = nullptr;
3144   switch (kind) {
3145     case LS_cmp_exchange: {
3146       result = access_atomic_cmpxchg_val_at(base, adr, adr_type, alias_idx,
3147                                             oldval, newval, value_type, type, decorators);
3148       break;
3149     }
3150     case LS_cmp_swap_weak:
3151       decorators |= C2_WEAK_CMPXCHG;
3152     case LS_cmp_swap: {
3153       result = access_atomic_cmpxchg_bool_at(base, adr, adr_type, alias_idx,
3154                                              oldval, newval, value_type, type, decorators);
3155       break;
3156     }
3157     case LS_get_set: {
3158       result = access_atomic_xchg_at(base, adr, adr_type, alias_idx,
3159                                      newval, value_type, type, decorators);
3160       break;
3161     }
3162     case LS_get_add: {
3163       result = access_atomic_add_at(base, adr, adr_type, alias_idx,
3164                                     newval, value_type, type, decorators);
3165       break;
3166     }
3167     default:
3168       ShouldNotReachHere();
3169   }
3170 
3171   assert(type2size[result->bottom_type()->basic_type()] == type2size[rtype], "result type should match");
3172   set_result(result);
3173   return true;
3174 }
3175 
3176 bool LibraryCallKit::inline_unsafe_fence(vmIntrinsics::ID id) {
3177   // Regardless of form, don't allow previous ld/st to move down,
3178   // then issue acquire, release, or volatile mem_bar.
3179   insert_mem_bar(Op_MemBarCPUOrder);
3180   switch(id) {
3181     case vmIntrinsics::_loadFence:
3182       insert_mem_bar(Op_LoadFence);
3183       return true;
3184     case vmIntrinsics::_storeFence:
3185       insert_mem_bar(Op_StoreFence);
3186       return true;
3187     case vmIntrinsics::_storeStoreFence:
3188       insert_mem_bar(Op_StoreStoreFence);
3189       return true;
3190     case vmIntrinsics::_fullFence:
3191       insert_mem_bar(Op_MemBarVolatile);
3192       return true;
3193     default:
3194       fatal_unexpected_iid(id);
3195       return false;
3196   }
3197 }
3198 
3199 // private native int arrayInstanceBaseOffset0(Object[] array);
3200 bool LibraryCallKit::inline_arrayInstanceBaseOffset() {
3201   Node* array = argument(1);
3202   Node* klass_node = load_object_klass(array);
3203 
3204   jint  layout_con = Klass::_lh_neutral_value;
3205   Node* layout_val = get_layout_helper(klass_node, layout_con);
3206   int   layout_is_con = (layout_val == nullptr);
3207 
3208   Node* header_size = nullptr;
3209   if (layout_is_con) {
3210     int hsize = Klass::layout_helper_header_size(layout_con);
3211     header_size = intcon(hsize);
3212   } else {
3213     Node* hss = intcon(Klass::_lh_header_size_shift);
3214     Node* hsm = intcon(Klass::_lh_header_size_mask);
3215     header_size = _gvn.transform(new URShiftINode(layout_val, hss));
3216     header_size = _gvn.transform(new AndINode(header_size, hsm));
3217   }
3218   set_result(header_size);
3219   return true;
3220 }
3221 
3222 // private native int arrayInstanceIndexScale0(Object[] array);
3223 bool LibraryCallKit::inline_arrayInstanceIndexScale() {
3224   Node* array = argument(1);
3225   Node* klass_node = load_object_klass(array);
3226 
3227   jint  layout_con = Klass::_lh_neutral_value;
3228   Node* layout_val = get_layout_helper(klass_node, layout_con);
3229   int   layout_is_con = (layout_val == nullptr);
3230 
3231   Node* element_size = nullptr;
3232   if (layout_is_con) {
3233     int log_element_size  = Klass::layout_helper_log2_element_size(layout_con);
3234     int elem_size = 1 << log_element_size;
3235     element_size = intcon(elem_size);
3236   } else {
3237     Node* ess = intcon(Klass::_lh_log2_element_size_shift);
3238     Node* esm = intcon(Klass::_lh_log2_element_size_mask);
3239     Node* log_element_size = _gvn.transform(new URShiftINode(layout_val, ess));
3240     log_element_size = _gvn.transform(new AndINode(log_element_size, esm));
3241     element_size = _gvn.transform(new LShiftINode(intcon(1), log_element_size));
3242   }
3243   set_result(element_size);
3244   return true;
3245 }
3246 
3247 // private native int arrayLayout0(Object[] array);
3248 bool LibraryCallKit::inline_arrayLayout() {
3249   RegionNode* region = new RegionNode(2);
3250   Node* phi = new PhiNode(region, TypeInt::POS);
3251 
3252   Node* array = argument(1);
3253   Node* klass_node = load_object_klass(array);
3254   generate_refArray_guard(klass_node, region);
3255   if (region->req() == 3) {
3256     phi->add_req(intcon((jint)LayoutKind::REFERENCE));
3257   }
3258 
3259   int layout_kind_offset = in_bytes(FlatArrayKlass::layout_kind_offset());
3260   Node* layout_kind_addr = basic_plus_adr(top(), klass_node, layout_kind_offset);
3261   Node* layout_kind = make_load(nullptr, layout_kind_addr, TypeInt::POS, T_INT, MemNode::unordered);
3262 
3263   region->init_req(1, control());
3264   phi->init_req(1, layout_kind);
3265 
3266   set_control(_gvn.transform(region));
3267   set_result(_gvn.transform(phi));
3268   return true;
3269 }
3270 
3271 // private native int[] getFieldMap0(Class <?> c);
3272 //   int offset = c._klass._acmp_maps_offset;
3273 //   return (int[])c.obj_field(offset);
3274 bool LibraryCallKit::inline_getFieldMap() {
3275   Node* mirror = argument(1);
3276   Node* klass = load_klass_from_mirror(mirror, false, nullptr, 0);
3277 
3278   int field_map_offset_offset = in_bytes(InstanceKlass::acmp_maps_offset_offset());
3279   Node* field_map_offset_addr = basic_plus_adr(top(), klass, field_map_offset_offset);
3280   Node* field_map_offset = make_load(nullptr, field_map_offset_addr, TypeInt::INT, T_INT, MemNode::unordered);
3281   field_map_offset = _gvn.transform(ConvI2L(field_map_offset));
3282 
3283   Node* map_addr = basic_plus_adr(mirror, field_map_offset);
3284   const TypeAryPtr* val_type = TypeAryPtr::INTS->cast_to_ptr_type(TypePtr::NotNull)->with_offset(0);
3285   // TODO 8350865 Remove this
3286   val_type = val_type->cast_to_not_flat(true)->cast_to_not_null_free(true);
3287   Node* map = access_load_at(mirror, map_addr, TypeAryPtr::INTS, val_type, T_ARRAY, IN_HEAP | MO_UNORDERED);
3288 
3289   set_result(map);
3290   return true;
3291 }
3292 
3293 bool LibraryCallKit::inline_onspinwait() {
3294   insert_mem_bar(Op_OnSpinWait);
3295   return true;
3296 }
3297 
3298 bool LibraryCallKit::klass_needs_init_guard(Node* kls) {
3299   if (!kls->is_Con()) {
3300     return true;
3301   }
3302   const TypeInstKlassPtr* klsptr = kls->bottom_type()->isa_instklassptr();
3303   if (klsptr == nullptr) {
3304     return true;
3305   }
3306   ciInstanceKlass* ik = klsptr->instance_klass();
3307   // don't need a guard for a klass that is already initialized
3308   return !ik->is_initialized();
3309 }
3310 
3311 //----------------------------inline_unsafe_writeback0-------------------------
3312 // public native void Unsafe.writeback0(long address)
3313 bool LibraryCallKit::inline_unsafe_writeback0() {
3314   if (!Matcher::has_match_rule(Op_CacheWB)) {
3315     return false;
3316   }
3317 #ifndef PRODUCT
3318   assert(Matcher::has_match_rule(Op_CacheWBPreSync), "found match rule for CacheWB but not CacheWBPreSync");
3319   assert(Matcher::has_match_rule(Op_CacheWBPostSync), "found match rule for CacheWB but not CacheWBPostSync");
3320   ciSignature* sig = callee()->signature();
3321   assert(sig->type_at(0)->basic_type() == T_LONG, "Unsafe_writeback0 address is long!");
3322 #endif
3323   null_check_receiver();  // null-check, then ignore
3324   Node *addr = argument(1);
3325   addr = new CastX2PNode(addr);
3326   addr = _gvn.transform(addr);
3327   Node *flush = new CacheWBNode(control(), memory(TypeRawPtr::BOTTOM), addr);
3328   flush = _gvn.transform(flush);
3329   set_memory(flush, TypeRawPtr::BOTTOM);
3330   return true;
3331 }
3332 
3333 //----------------------------inline_unsafe_writeback0-------------------------
3334 // public native void Unsafe.writeback0(long address)
3335 bool LibraryCallKit::inline_unsafe_writebackSync0(bool is_pre) {
3336   if (is_pre && !Matcher::has_match_rule(Op_CacheWBPreSync)) {
3337     return false;
3338   }
3339   if (!is_pre && !Matcher::has_match_rule(Op_CacheWBPostSync)) {
3340     return false;
3341   }
3342 #ifndef PRODUCT
3343   assert(Matcher::has_match_rule(Op_CacheWB),
3344          (is_pre ? "found match rule for CacheWBPreSync but not CacheWB"
3345                 : "found match rule for CacheWBPostSync but not CacheWB"));
3346 
3347 #endif
3348   null_check_receiver();  // null-check, then ignore
3349   Node *sync;
3350   if (is_pre) {
3351     sync = new CacheWBPreSyncNode(control(), memory(TypeRawPtr::BOTTOM));
3352   } else {
3353     sync = new CacheWBPostSyncNode(control(), memory(TypeRawPtr::BOTTOM));
3354   }
3355   sync = _gvn.transform(sync);
3356   set_memory(sync, TypeRawPtr::BOTTOM);
3357   return true;
3358 }
3359 
3360 //----------------------------inline_unsafe_allocate---------------------------
3361 // public native Object Unsafe.allocateInstance(Class<?> cls);
3362 bool LibraryCallKit::inline_unsafe_allocate() {
3363 
3364 #if INCLUDE_JVMTI
3365   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
3366     return false;
3367   }
3368 #endif //INCLUDE_JVMTI
3369 
3370   if (callee()->is_static())  return false;  // caller must have the capability!
3371 
3372   null_check_receiver();  // null-check, then ignore
3373   Node* cls = null_check(argument(1));
3374   if (stopped())  return true;
3375 
3376   Node* kls = load_klass_from_mirror(cls, false, nullptr, 0);
3377   kls = null_check(kls);
3378   if (stopped())  return true;  // argument was like int.class
3379 
3380 #if INCLUDE_JVMTI
3381     // Don't try to access new allocated obj in the intrinsic.
3382     // It causes perfomance issues even when jvmti event VmObjectAlloc is disabled.
3383     // Deoptimize and allocate in interpreter instead.
3384     Node* addr = makecon(TypeRawPtr::make((address) &JvmtiExport::_should_notify_object_alloc));
3385     Node* should_post_vm_object_alloc = make_load(this->control(), addr, TypeInt::INT, T_INT, MemNode::unordered);
3386     Node* chk = _gvn.transform(new CmpINode(should_post_vm_object_alloc, intcon(0)));
3387     Node* tst = _gvn.transform(new BoolNode(chk, BoolTest::eq));
3388     {
3389       BuildCutout unless(this, tst, PROB_MAX);
3390       uncommon_trap(Deoptimization::Reason_intrinsic,
3391                     Deoptimization::Action_make_not_entrant);
3392     }
3393     if (stopped()) {
3394       return true;
3395     }
3396 #endif //INCLUDE_JVMTI
3397 
3398   Node* test = nullptr;
3399   if (LibraryCallKit::klass_needs_init_guard(kls)) {
3400     // Note:  The argument might still be an illegal value like
3401     // Serializable.class or Object[].class.   The runtime will handle it.
3402     // But we must make an explicit check for initialization.
3403     Node* insp = basic_plus_adr(top(), kls, in_bytes(InstanceKlass::init_state_offset()));
3404     // Use T_BOOLEAN for InstanceKlass::_init_state so the compiler
3405     // can generate code to load it as unsigned byte.
3406     Node* inst = make_load(nullptr, insp, TypeInt::UBYTE, T_BOOLEAN, MemNode::acquire);
3407     Node* bits = intcon(InstanceKlass::fully_initialized);
3408     test = _gvn.transform(new SubINode(inst, bits));
3409     // The 'test' is non-zero if we need to take a slow path.
3410   }
3411   Node* obj = nullptr;
3412   const TypeInstKlassPtr* tkls = _gvn.type(kls)->isa_instklassptr();
3413   if (tkls != nullptr && tkls->instance_klass()->is_inlinetype()) {
3414     obj = InlineTypeNode::make_all_zero(_gvn, tkls->instance_klass()->as_inline_klass())->buffer(this);
3415   } else {
3416     obj = new_instance(kls, test);
3417   }
3418   set_result(obj);
3419   return true;
3420 }
3421 
3422 //------------------------inline_native_time_funcs--------------
3423 // inline code for System.currentTimeMillis() and System.nanoTime()
3424 // these have the same type and signature
3425 bool LibraryCallKit::inline_native_time_funcs(address funcAddr, const char* funcName) {
3426   const TypeFunc* tf = OptoRuntime::void_long_Type();
3427   const TypePtr* no_memory_effects = nullptr;
3428   Node* time = make_runtime_call(RC_LEAF, tf, funcAddr, funcName, no_memory_effects);
3429   Node* value = _gvn.transform(new ProjNode(time, TypeFunc::Parms+0));
3430 #ifdef ASSERT
3431   Node* value_top = _gvn.transform(new ProjNode(time, TypeFunc::Parms+1));
3432   assert(value_top == top(), "second value must be top");
3433 #endif
3434   set_result(value);
3435   return true;
3436 }
3437 
3438 //--------------------inline_native_vthread_start_transition--------------------
3439 // inline void startTransition(boolean is_mount);
3440 // inline void startFinalTransition();
3441 // Pseudocode of implementation:
3442 //
3443 // java_lang_Thread::set_is_in_vthread_transition(vthread, true);
3444 // carrier->set_is_in_vthread_transition(true);
3445 // OrderAccess::storeload();
3446 // int disable_requests = java_lang_Thread::vthread_transition_disable_count(vthread)
3447 //                        + global_vthread_transition_disable_count();
3448 // if (disable_requests > 0) {
3449 //   slow path: runtime call
3450 // }
3451 bool LibraryCallKit::inline_native_vthread_start_transition(address funcAddr, const char* funcName, bool is_final_transition) {
3452   Node* vt_oop = _gvn.transform(must_be_not_null(argument(0), true)); // VirtualThread this argument
3453   IdealKit ideal(this);
3454 
3455   Node* thread = ideal.thread();
3456   Node* jt_addr = basic_plus_adr(top(), thread, in_bytes(JavaThread::is_in_vthread_transition_offset()));
3457   Node* vt_addr = basic_plus_adr(vt_oop, java_lang_Thread::is_in_vthread_transition_offset());
3458   access_store_at(nullptr, jt_addr, _gvn.type(jt_addr)->is_ptr(), ideal.ConI(1), TypeInt::BOOL, T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
3459   access_store_at(nullptr, vt_addr, _gvn.type(vt_addr)->is_ptr(), ideal.ConI(1), TypeInt::BOOL, T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
3460   insert_mem_bar(Op_MemBarVolatile);
3461   ideal.sync_kit(this);
3462 
3463   Node* global_disable_addr = makecon(TypeRawPtr::make((address)MountUnmountDisabler::global_vthread_transition_disable_count_address()));
3464   Node* global_disable = ideal.load(ideal.ctrl(), global_disable_addr, TypeInt::INT, T_INT, Compile::AliasIdxRaw, true /*require_atomic_access*/);
3465   Node* vt_disable_addr = basic_plus_adr(vt_oop, java_lang_Thread::vthread_transition_disable_count_offset());
3466   Node* vt_disable = ideal.load(ideal.ctrl(), vt_disable_addr, TypeInt::INT, T_INT, Compile::AliasIdxRaw, true /*require_atomic_access*/);
3467   Node* disabled = _gvn.transform(new AddINode(global_disable, vt_disable));
3468 
3469   ideal.if_then(disabled, BoolTest::ne, ideal.ConI(0)); {
3470     sync_kit(ideal);
3471     Node* is_mount = is_final_transition ? ideal.ConI(0) : _gvn.transform(argument(1));
3472     const TypeFunc* tf = OptoRuntime::vthread_transition_Type();
3473     make_runtime_call(RC_NO_LEAF, tf, funcAddr, funcName, TypePtr::BOTTOM, vt_oop, is_mount);
3474     ideal.sync_kit(this);
3475   }
3476   ideal.end_if();
3477 
3478   final_sync(ideal);
3479   return true;
3480 }
3481 
3482 bool LibraryCallKit::inline_native_vthread_end_transition(address funcAddr, const char* funcName, bool is_first_transition) {
3483   Node* vt_oop = _gvn.transform(must_be_not_null(argument(0), true)); // VirtualThread this argument
3484   IdealKit ideal(this);
3485 
3486   Node* _notify_jvmti_addr = makecon(TypeRawPtr::make((address)MountUnmountDisabler::notify_jvmti_events_address()));
3487   Node* _notify_jvmti = ideal.load(ideal.ctrl(), _notify_jvmti_addr, TypeInt::BOOL, T_BOOLEAN, Compile::AliasIdxRaw);
3488 
3489   ideal.if_then(_notify_jvmti, BoolTest::eq, ideal.ConI(1)); {
3490     sync_kit(ideal);
3491     Node* is_mount = is_first_transition ? ideal.ConI(1) : _gvn.transform(argument(1));
3492     const TypeFunc* tf = OptoRuntime::vthread_transition_Type();
3493     make_runtime_call(RC_NO_LEAF, tf, funcAddr, funcName, TypePtr::BOTTOM, vt_oop, is_mount);
3494     ideal.sync_kit(this);
3495   } ideal.else_(); {
3496     Node* thread = ideal.thread();
3497     Node* jt_addr = basic_plus_adr(top(), thread, in_bytes(JavaThread::is_in_vthread_transition_offset()));
3498     Node* vt_addr = basic_plus_adr(vt_oop, java_lang_Thread::is_in_vthread_transition_offset());
3499 
3500     sync_kit(ideal);
3501     access_store_at(nullptr, jt_addr, _gvn.type(jt_addr)->is_ptr(), ideal.ConI(0), TypeInt::BOOL, T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
3502     access_store_at(nullptr, vt_addr, _gvn.type(vt_addr)->is_ptr(), ideal.ConI(0), TypeInt::BOOL, T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
3503     ideal.sync_kit(this);
3504   } ideal.end_if();
3505 
3506   final_sync(ideal);
3507   return true;
3508 }
3509 
3510 #if INCLUDE_JVMTI
3511 
3512 // Always update the is_disable_suspend bit.
3513 bool LibraryCallKit::inline_native_notify_jvmti_sync() {
3514   if (!DoJVMTIVirtualThreadTransitions) {
3515     return true;
3516   }
3517   IdealKit ideal(this);
3518 
3519   {
3520     // unconditionally update the is_disable_suspend bit in current JavaThread
3521     Node* thread = ideal.thread();
3522     Node* arg = _gvn.transform(argument(0)); // argument for notification
3523     Node* addr = basic_plus_adr(top(), thread, in_bytes(JavaThread::is_disable_suspend_offset()));
3524     const TypePtr *addr_type = _gvn.type(addr)->isa_ptr();
3525 
3526     sync_kit(ideal);
3527     access_store_at(nullptr, addr, addr_type, arg, _gvn.type(arg), T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
3528     ideal.sync_kit(this);
3529   }
3530   final_sync(ideal);
3531 
3532   return true;
3533 }
3534 
3535 #endif // INCLUDE_JVMTI
3536 
3537 #ifdef JFR_HAVE_INTRINSICS
3538 
3539 /**
3540  * if oop->klass != null
3541  *   // normal class
3542  *   epoch = _epoch_state ? 2 : 1
3543  *   if oop->klass->trace_id & ((epoch << META_SHIFT) | epoch)) != epoch {
3544  *     ... // enter slow path when the klass is first recorded or the epoch of JFR shifts
3545  *   }
3546  *   id = oop->klass->trace_id >> TRACE_ID_SHIFT // normal class path
3547  * else
3548  *   // primitive class
3549  *   if oop->array_klass != null
3550  *     id = (oop->array_klass->trace_id >> TRACE_ID_SHIFT) + 1 // primitive class path
3551  *   else
3552  *     id = LAST_TYPE_ID + 1 // void class path
3553  *   if (!signaled)
3554  *     signaled = true
3555  */
3556 bool LibraryCallKit::inline_native_classID() {
3557   Node* cls = argument(0);
3558 
3559   IdealKit ideal(this);
3560 #define __ ideal.
3561   IdealVariable result(ideal); __ declarations_done();
3562   Node* kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(),
3563                                                  basic_plus_adr(cls, java_lang_Class::klass_offset()),
3564                                                  TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
3565 
3566 
3567   __ if_then(kls, BoolTest::ne, null()); {
3568     Node* kls_trace_id_addr = basic_plus_adr(kls, in_bytes(KLASS_TRACE_ID_OFFSET));
3569     Node* kls_trace_id_raw = ideal.load(ideal.ctrl(), kls_trace_id_addr,TypeLong::LONG, T_LONG, Compile::AliasIdxRaw);
3570 
3571     Node* epoch_address = makecon(TypeRawPtr::make(JfrIntrinsicSupport::epoch_address()));
3572     Node* epoch = ideal.load(ideal.ctrl(), epoch_address, TypeInt::BOOL, T_BOOLEAN, Compile::AliasIdxRaw);
3573     epoch = _gvn.transform(new LShiftLNode(longcon(1), epoch));
3574     Node* mask = _gvn.transform(new LShiftLNode(epoch, intcon(META_SHIFT)));
3575     mask = _gvn.transform(new OrLNode(mask, epoch));
3576     Node* kls_trace_id_raw_and_mask = _gvn.transform(new AndLNode(kls_trace_id_raw, mask));
3577 
3578     float unlikely  = PROB_UNLIKELY(0.999);
3579     __ if_then(kls_trace_id_raw_and_mask, BoolTest::ne, epoch, unlikely); {
3580       sync_kit(ideal);
3581       make_runtime_call(RC_LEAF,
3582                         OptoRuntime::class_id_load_barrier_Type(),
3583                         CAST_FROM_FN_PTR(address, JfrIntrinsicSupport::load_barrier),
3584                         "class id load barrier",
3585                         TypePtr::BOTTOM,
3586                         kls);
3587       ideal.sync_kit(this);
3588     } __ end_if();
3589 
3590     ideal.set(result,  _gvn.transform(new URShiftLNode(kls_trace_id_raw, ideal.ConI(TRACE_ID_SHIFT))));
3591   } __ else_(); {
3592     Node* array_kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(),
3593                                                    basic_plus_adr(cls, java_lang_Class::array_klass_offset()),
3594                                                    TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
3595     __ if_then(array_kls, BoolTest::ne, null()); {
3596       Node* array_kls_trace_id_addr = basic_plus_adr(array_kls, in_bytes(KLASS_TRACE_ID_OFFSET));
3597       Node* array_kls_trace_id_raw = ideal.load(ideal.ctrl(), array_kls_trace_id_addr, TypeLong::LONG, T_LONG, Compile::AliasIdxRaw);
3598       Node* array_kls_trace_id = _gvn.transform(new URShiftLNode(array_kls_trace_id_raw, ideal.ConI(TRACE_ID_SHIFT)));
3599       ideal.set(result, _gvn.transform(new AddLNode(array_kls_trace_id, longcon(1))));
3600     } __ else_(); {
3601       // void class case
3602       ideal.set(result, _gvn.transform(longcon(LAST_TYPE_ID + 1)));
3603     } __ end_if();
3604 
3605     Node* signaled_flag_address = makecon(TypeRawPtr::make(JfrIntrinsicSupport::signal_address()));
3606     Node* signaled = ideal.load(ideal.ctrl(), signaled_flag_address, TypeInt::BOOL, T_BOOLEAN, Compile::AliasIdxRaw, true, MemNode::acquire);
3607     __ if_then(signaled, BoolTest::ne, ideal.ConI(1)); {
3608       ideal.store(ideal.ctrl(), signaled_flag_address, ideal.ConI(1), T_BOOLEAN, Compile::AliasIdxRaw, MemNode::release, true);
3609     } __ end_if();
3610   } __ end_if();
3611 
3612   final_sync(ideal);
3613   set_result(ideal.value(result));
3614 #undef __
3615   return true;
3616 }
3617 
3618 //------------------------inline_native_jvm_commit------------------
3619 bool LibraryCallKit::inline_native_jvm_commit() {
3620   enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
3621 
3622   // Save input memory and i_o state.
3623   Node* input_memory_state = reset_memory();
3624   set_all_memory(input_memory_state);
3625   Node* input_io_state = i_o();
3626 
3627   // TLS.
3628   Node* tls_ptr = _gvn.transform(new ThreadLocalNode());
3629   // Jfr java buffer.
3630   Node* java_buffer_offset = _gvn.transform(new AddPNode(top(), tls_ptr, _gvn.transform(MakeConX(in_bytes(JAVA_BUFFER_OFFSET_JFR)))));
3631   Node* java_buffer = _gvn.transform(new LoadPNode(control(), input_memory_state, java_buffer_offset, TypePtr::BOTTOM, TypeRawPtr::NOTNULL, MemNode::unordered));
3632   Node* java_buffer_pos_offset = _gvn.transform(new AddPNode(top(), java_buffer, _gvn.transform(MakeConX(in_bytes(JFR_BUFFER_POS_OFFSET)))));
3633 
3634   // Load the current value of the notified field in the JfrThreadLocal.
3635   Node* notified_offset = basic_plus_adr(top(), tls_ptr, in_bytes(NOTIFY_OFFSET_JFR));
3636   Node* notified = make_load(control(), notified_offset, TypeInt::BOOL, T_BOOLEAN, MemNode::unordered);
3637 
3638   // Test for notification.
3639   Node* notified_cmp = _gvn.transform(new CmpINode(notified, _gvn.intcon(1)));
3640   Node* test_notified = _gvn.transform(new BoolNode(notified_cmp, BoolTest::eq));
3641   IfNode* iff_notified = create_and_map_if(control(), test_notified, PROB_MIN, COUNT_UNKNOWN);
3642 
3643   // True branch, is notified.
3644   Node* is_notified = _gvn.transform(new IfTrueNode(iff_notified));
3645   set_control(is_notified);
3646 
3647   // Reset notified state.
3648   store_to_memory(control(), notified_offset, _gvn.intcon(0), T_BOOLEAN, MemNode::unordered);
3649   Node* notified_reset_memory = reset_memory();
3650 
3651   // 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.
3652   Node* current_pos_X = _gvn.transform(new LoadXNode(control(), input_memory_state, java_buffer_pos_offset, TypeRawPtr::NOTNULL, TypeX_X, MemNode::unordered));
3653   // Convert the machine-word to a long.
3654   Node* current_pos = _gvn.transform(ConvX2L(current_pos_X));
3655 
3656   // False branch, not notified.
3657   Node* not_notified = _gvn.transform(new IfFalseNode(iff_notified));
3658   set_control(not_notified);
3659   set_all_memory(input_memory_state);
3660 
3661   // Arg is the next position as a long.
3662   Node* arg = argument(0);
3663   // Convert long to machine-word.
3664   Node* next_pos_X = _gvn.transform(ConvL2X(arg));
3665 
3666   // Store the next_position to the underlying jfr java buffer.
3667   store_to_memory(control(), java_buffer_pos_offset, next_pos_X, LP64_ONLY(T_LONG) NOT_LP64(T_INT), MemNode::release);
3668 
3669   Node* commit_memory = reset_memory();
3670   set_all_memory(commit_memory);
3671 
3672   // 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.
3673   Node* java_buffer_flags_offset = _gvn.transform(new AddPNode(top(), java_buffer, _gvn.transform(MakeConX(in_bytes(JFR_BUFFER_FLAGS_OFFSET)))));
3674   Node* flags = make_load(control(), java_buffer_flags_offset, TypeInt::UBYTE, T_BYTE, MemNode::unordered);
3675   Node* lease_constant = _gvn.transform(_gvn.intcon(4));
3676 
3677   // And flags with lease constant.
3678   Node* lease = _gvn.transform(new AndINode(flags, lease_constant));
3679 
3680   // Branch on lease to conditionalize returning the leased java buffer.
3681   Node* lease_cmp = _gvn.transform(new CmpINode(lease, lease_constant));
3682   Node* test_lease = _gvn.transform(new BoolNode(lease_cmp, BoolTest::eq));
3683   IfNode* iff_lease = create_and_map_if(control(), test_lease, PROB_MIN, COUNT_UNKNOWN);
3684 
3685   // False branch, not a lease.
3686   Node* not_lease = _gvn.transform(new IfFalseNode(iff_lease));
3687 
3688   // True branch, is lease.
3689   Node* is_lease = _gvn.transform(new IfTrueNode(iff_lease));
3690   set_control(is_lease);
3691 
3692   // Make a runtime call, which can safepoint, to return the leased buffer. This updates both the JfrThreadLocal and the Java event writer oop.
3693   Node* call_return_lease = make_runtime_call(RC_NO_LEAF,
3694                                               OptoRuntime::void_void_Type(),
3695                                               SharedRuntime::jfr_return_lease(),
3696                                               "return_lease", TypePtr::BOTTOM);
3697   Node* call_return_lease_control = _gvn.transform(new ProjNode(call_return_lease, TypeFunc::Control));
3698 
3699   RegionNode* lease_compare_rgn = new RegionNode(PATH_LIMIT);
3700   record_for_igvn(lease_compare_rgn);
3701   PhiNode* lease_compare_mem = new PhiNode(lease_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3702   record_for_igvn(lease_compare_mem);
3703   PhiNode* lease_compare_io = new PhiNode(lease_compare_rgn, Type::ABIO);
3704   record_for_igvn(lease_compare_io);
3705   PhiNode* lease_result_value = new PhiNode(lease_compare_rgn, TypeLong::LONG);
3706   record_for_igvn(lease_result_value);
3707 
3708   // Update control and phi nodes.
3709   lease_compare_rgn->init_req(_true_path, call_return_lease_control);
3710   lease_compare_rgn->init_req(_false_path, not_lease);
3711 
3712   lease_compare_mem->init_req(_true_path, _gvn.transform(reset_memory()));
3713   lease_compare_mem->init_req(_false_path, commit_memory);
3714 
3715   lease_compare_io->init_req(_true_path, i_o());
3716   lease_compare_io->init_req(_false_path, input_io_state);
3717 
3718   lease_result_value->init_req(_true_path, _gvn.longcon(0)); // if the lease was returned, return 0L.
3719   lease_result_value->init_req(_false_path, arg); // if not lease, return new updated position.
3720 
3721   RegionNode* result_rgn = new RegionNode(PATH_LIMIT);
3722   PhiNode* result_mem = new PhiNode(result_rgn, Type::MEMORY, TypePtr::BOTTOM);
3723   PhiNode* result_io = new PhiNode(result_rgn, Type::ABIO);
3724   PhiNode* result_value = new PhiNode(result_rgn, TypeLong::LONG);
3725 
3726   // Update control and phi nodes.
3727   result_rgn->init_req(_true_path, is_notified);
3728   result_rgn->init_req(_false_path, _gvn.transform(lease_compare_rgn));
3729 
3730   result_mem->init_req(_true_path, notified_reset_memory);
3731   result_mem->init_req(_false_path, _gvn.transform(lease_compare_mem));
3732 
3733   result_io->init_req(_true_path, input_io_state);
3734   result_io->init_req(_false_path, _gvn.transform(lease_compare_io));
3735 
3736   result_value->init_req(_true_path, current_pos);
3737   result_value->init_req(_false_path, _gvn.transform(lease_result_value));
3738 
3739   // Set output state.
3740   set_control(_gvn.transform(result_rgn));
3741   set_all_memory(_gvn.transform(result_mem));
3742   set_i_o(_gvn.transform(result_io));
3743   set_result(result_rgn, result_value);
3744   return true;
3745 }
3746 
3747 /*
3748  * The intrinsic is a model of this pseudo-code:
3749  *
3750  * JfrThreadLocal* const tl = Thread::jfr_thread_local()
3751  * jobject h_event_writer = tl->java_event_writer();
3752  * if (h_event_writer == nullptr) {
3753  *   return nullptr;
3754  * }
3755  * oop threadObj = Thread::threadObj();
3756  * oop vthread = java_lang_Thread::vthread(threadObj);
3757  * traceid tid;
3758  * bool pinVirtualThread;
3759  * bool excluded;
3760  * if (vthread != threadObj) {  // i.e. current thread is virtual
3761  *   tid = java_lang_Thread::tid(vthread);
3762  *   u2 vthread_epoch_raw = java_lang_Thread::jfr_epoch(vthread);
3763  *   pinVirtualThread = VMContinuations;
3764  *   excluded = vthread_epoch_raw & excluded_mask;
3765  *   if (!excluded) {
3766  *     traceid current_epoch = JfrTraceIdEpoch::current_generation();
3767  *     u2 vthread_epoch = vthread_epoch_raw & epoch_mask;
3768  *     if (vthread_epoch != current_epoch) {
3769  *       write_checkpoint();
3770  *     }
3771  *   }
3772  * } else {
3773  *   tid = java_lang_Thread::tid(threadObj);
3774  *   u2 thread_epoch_raw = java_lang_Thread::jfr_epoch(threadObj);
3775  *   pinVirtualThread = false;
3776  *   excluded = thread_epoch_raw & excluded_mask;
3777  * }
3778  * oop event_writer = JNIHandles::resolve_non_null(h_event_writer);
3779  * traceid tid_in_event_writer = getField(event_writer, "threadID");
3780  * if (tid_in_event_writer != tid) {
3781  *   setField(event_writer, "pinVirtualThread", pinVirtualThread);
3782  *   setField(event_writer, "excluded", excluded);
3783  *   setField(event_writer, "threadID", tid);
3784  * }
3785  * return event_writer
3786  */
3787 bool LibraryCallKit::inline_native_getEventWriter() {
3788   enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
3789 
3790   // Save input memory and i_o state.
3791   Node* input_memory_state = reset_memory();
3792   set_all_memory(input_memory_state);
3793   Node* input_io_state = i_o();
3794 
3795   // The most significant bit of the u2 is used to denote thread exclusion
3796   Node* excluded_shift = _gvn.intcon(15);
3797   Node* excluded_mask = _gvn.intcon(1 << 15);
3798   // The epoch generation is the range [1-32767]
3799   Node* epoch_mask = _gvn.intcon(32767);
3800 
3801   // TLS
3802   Node* tls_ptr = _gvn.transform(new ThreadLocalNode());
3803 
3804   // Load the address of java event writer jobject handle from the jfr_thread_local structure.
3805   Node* jobj_ptr = basic_plus_adr(top(), tls_ptr, in_bytes(THREAD_LOCAL_WRITER_OFFSET_JFR));
3806 
3807   // Load the eventwriter jobject handle.
3808   Node* jobj = make_load(control(), jobj_ptr, TypeRawPtr::BOTTOM, T_ADDRESS, MemNode::unordered);
3809 
3810   // Null check the jobject handle.
3811   Node* jobj_cmp_null = _gvn.transform(new CmpPNode(jobj, null()));
3812   Node* test_jobj_not_equal_null = _gvn.transform(new BoolNode(jobj_cmp_null, BoolTest::ne));
3813   IfNode* iff_jobj_not_equal_null = create_and_map_if(control(), test_jobj_not_equal_null, PROB_MAX, COUNT_UNKNOWN);
3814 
3815   // False path, jobj is null.
3816   Node* jobj_is_null = _gvn.transform(new IfFalseNode(iff_jobj_not_equal_null));
3817 
3818   // True path, jobj is not null.
3819   Node* jobj_is_not_null = _gvn.transform(new IfTrueNode(iff_jobj_not_equal_null));
3820 
3821   set_control(jobj_is_not_null);
3822 
3823   // Load the threadObj for the CarrierThread.
3824   Node* threadObj = generate_current_thread(tls_ptr);
3825 
3826   // Load the vthread.
3827   Node* vthread = generate_virtual_thread(tls_ptr);
3828 
3829   // If vthread != threadObj, this is a virtual thread.
3830   Node* vthread_cmp_threadObj = _gvn.transform(new CmpPNode(vthread, threadObj));
3831   Node* test_vthread_not_equal_threadObj = _gvn.transform(new BoolNode(vthread_cmp_threadObj, BoolTest::ne));
3832   IfNode* iff_vthread_not_equal_threadObj =
3833     create_and_map_if(jobj_is_not_null, test_vthread_not_equal_threadObj, PROB_FAIR, COUNT_UNKNOWN);
3834 
3835   // False branch, fallback to threadObj.
3836   Node* vthread_equal_threadObj = _gvn.transform(new IfFalseNode(iff_vthread_not_equal_threadObj));
3837   set_control(vthread_equal_threadObj);
3838 
3839   // Load the tid field from the vthread object.
3840   Node* thread_obj_tid = load_field_from_object(threadObj, "tid", "J");
3841 
3842   // Load the raw epoch value from the threadObj.
3843   Node* threadObj_epoch_offset = basic_plus_adr(threadObj, java_lang_Thread::jfr_epoch_offset());
3844   Node* threadObj_epoch_raw = access_load_at(threadObj, threadObj_epoch_offset,
3845                                              _gvn.type(threadObj_epoch_offset)->isa_ptr(),
3846                                              TypeInt::CHAR, T_CHAR,
3847                                              IN_HEAP | MO_UNORDERED | C2_MISMATCHED | C2_CONTROL_DEPENDENT_LOAD);
3848 
3849   // Mask off the excluded information from the epoch.
3850   Node * threadObj_is_excluded = _gvn.transform(new AndINode(threadObj_epoch_raw, excluded_mask));
3851 
3852   // True branch, this is a virtual thread.
3853   Node* vthread_not_equal_threadObj = _gvn.transform(new IfTrueNode(iff_vthread_not_equal_threadObj));
3854   set_control(vthread_not_equal_threadObj);
3855 
3856   // Load the tid field from the vthread object.
3857   Node* vthread_tid = load_field_from_object(vthread, "tid", "J");
3858 
3859   // Continuation support determines if a virtual thread should be pinned.
3860   Node* global_addr = makecon(TypeRawPtr::make((address)&VMContinuations));
3861   Node* continuation_support = make_load(control(), global_addr, TypeInt::BOOL, T_BOOLEAN, MemNode::unordered);
3862 
3863   // Load the raw epoch value from the vthread.
3864   Node* vthread_epoch_offset = basic_plus_adr(vthread, java_lang_Thread::jfr_epoch_offset());
3865   Node* vthread_epoch_raw = access_load_at(vthread, vthread_epoch_offset, _gvn.type(vthread_epoch_offset)->is_ptr(),
3866                                            TypeInt::CHAR, T_CHAR,
3867                                            IN_HEAP | MO_UNORDERED | C2_MISMATCHED | C2_CONTROL_DEPENDENT_LOAD);
3868 
3869   // Mask off the excluded information from the epoch.
3870   Node * vthread_is_excluded = _gvn.transform(new AndINode(vthread_epoch_raw, _gvn.transform(excluded_mask)));
3871 
3872   // Branch on excluded to conditionalize updating the epoch for the virtual thread.
3873   Node* is_excluded_cmp = _gvn.transform(new CmpINode(vthread_is_excluded, _gvn.transform(excluded_mask)));
3874   Node* test_not_excluded = _gvn.transform(new BoolNode(is_excluded_cmp, BoolTest::ne));
3875   IfNode* iff_not_excluded = create_and_map_if(control(), test_not_excluded, PROB_MAX, COUNT_UNKNOWN);
3876 
3877   // False branch, vthread is excluded, no need to write epoch info.
3878   Node* excluded = _gvn.transform(new IfFalseNode(iff_not_excluded));
3879 
3880   // True branch, vthread is included, update epoch info.
3881   Node* included = _gvn.transform(new IfTrueNode(iff_not_excluded));
3882   set_control(included);
3883 
3884   // Get epoch value.
3885   Node* epoch = _gvn.transform(new AndINode(vthread_epoch_raw, _gvn.transform(epoch_mask)));
3886 
3887   // Load the current epoch generation. The value is unsigned 16-bit, so we type it as T_CHAR.
3888   Node* epoch_generation_address = makecon(TypeRawPtr::make(JfrIntrinsicSupport::epoch_generation_address()));
3889   Node* current_epoch_generation = make_load(control(), epoch_generation_address, TypeInt::CHAR, T_CHAR, MemNode::unordered);
3890 
3891   // Compare the epoch in the vthread to the current epoch generation.
3892   Node* const epoch_cmp = _gvn.transform(new CmpUNode(current_epoch_generation, epoch));
3893   Node* test_epoch_not_equal = _gvn.transform(new BoolNode(epoch_cmp, BoolTest::ne));
3894   IfNode* iff_epoch_not_equal = create_and_map_if(control(), test_epoch_not_equal, PROB_FAIR, COUNT_UNKNOWN);
3895 
3896   // False path, epoch is equal, checkpoint information is valid.
3897   Node* epoch_is_equal = _gvn.transform(new IfFalseNode(iff_epoch_not_equal));
3898 
3899   // True path, epoch is not equal, write a checkpoint for the vthread.
3900   Node* epoch_is_not_equal = _gvn.transform(new IfTrueNode(iff_epoch_not_equal));
3901 
3902   set_control(epoch_is_not_equal);
3903 
3904   // Make a runtime call, which can safepoint, to write a checkpoint for the vthread for this epoch.
3905   // The call also updates the native thread local thread id and the vthread with the current epoch.
3906   Node* call_write_checkpoint = make_runtime_call(RC_NO_LEAF,
3907                                                   OptoRuntime::jfr_write_checkpoint_Type(),
3908                                                   SharedRuntime::jfr_write_checkpoint(),
3909                                                   "write_checkpoint", TypePtr::BOTTOM);
3910   Node* call_write_checkpoint_control = _gvn.transform(new ProjNode(call_write_checkpoint, TypeFunc::Control));
3911 
3912   // vthread epoch != current epoch
3913   RegionNode* epoch_compare_rgn = new RegionNode(PATH_LIMIT);
3914   record_for_igvn(epoch_compare_rgn);
3915   PhiNode* epoch_compare_mem = new PhiNode(epoch_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3916   record_for_igvn(epoch_compare_mem);
3917   PhiNode* epoch_compare_io = new PhiNode(epoch_compare_rgn, Type::ABIO);
3918   record_for_igvn(epoch_compare_io);
3919 
3920   // Update control and phi nodes.
3921   epoch_compare_rgn->init_req(_true_path, call_write_checkpoint_control);
3922   epoch_compare_rgn->init_req(_false_path, epoch_is_equal);
3923   epoch_compare_mem->init_req(_true_path, _gvn.transform(reset_memory()));
3924   epoch_compare_mem->init_req(_false_path, input_memory_state);
3925   epoch_compare_io->init_req(_true_path, i_o());
3926   epoch_compare_io->init_req(_false_path, input_io_state);
3927 
3928   // excluded != true
3929   RegionNode* exclude_compare_rgn = new RegionNode(PATH_LIMIT);
3930   record_for_igvn(exclude_compare_rgn);
3931   PhiNode* exclude_compare_mem = new PhiNode(exclude_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3932   record_for_igvn(exclude_compare_mem);
3933   PhiNode* exclude_compare_io = new PhiNode(exclude_compare_rgn, Type::ABIO);
3934   record_for_igvn(exclude_compare_io);
3935 
3936   // Update control and phi nodes.
3937   exclude_compare_rgn->init_req(_true_path, _gvn.transform(epoch_compare_rgn));
3938   exclude_compare_rgn->init_req(_false_path, excluded);
3939   exclude_compare_mem->init_req(_true_path, _gvn.transform(epoch_compare_mem));
3940   exclude_compare_mem->init_req(_false_path, input_memory_state);
3941   exclude_compare_io->init_req(_true_path, _gvn.transform(epoch_compare_io));
3942   exclude_compare_io->init_req(_false_path, input_io_state);
3943 
3944   // vthread != threadObj
3945   RegionNode* vthread_compare_rgn = new RegionNode(PATH_LIMIT);
3946   record_for_igvn(vthread_compare_rgn);
3947   PhiNode* vthread_compare_mem = new PhiNode(vthread_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3948   PhiNode* vthread_compare_io = new PhiNode(vthread_compare_rgn, Type::ABIO);
3949   record_for_igvn(vthread_compare_io);
3950   PhiNode* tid = new PhiNode(vthread_compare_rgn, TypeLong::LONG);
3951   record_for_igvn(tid);
3952   PhiNode* exclusion = new PhiNode(vthread_compare_rgn, TypeInt::CHAR);
3953   record_for_igvn(exclusion);
3954   PhiNode* pinVirtualThread = new PhiNode(vthread_compare_rgn, TypeInt::BOOL);
3955   record_for_igvn(pinVirtualThread);
3956 
3957   // Update control and phi nodes.
3958   vthread_compare_rgn->init_req(_true_path, _gvn.transform(exclude_compare_rgn));
3959   vthread_compare_rgn->init_req(_false_path, vthread_equal_threadObj);
3960   vthread_compare_mem->init_req(_true_path, _gvn.transform(exclude_compare_mem));
3961   vthread_compare_mem->init_req(_false_path, input_memory_state);
3962   vthread_compare_io->init_req(_true_path, _gvn.transform(exclude_compare_io));
3963   vthread_compare_io->init_req(_false_path, input_io_state);
3964   tid->init_req(_true_path, _gvn.transform(vthread_tid));
3965   tid->init_req(_false_path, _gvn.transform(thread_obj_tid));
3966   exclusion->init_req(_true_path, _gvn.transform(vthread_is_excluded));
3967   exclusion->init_req(_false_path, _gvn.transform(threadObj_is_excluded));
3968   pinVirtualThread->init_req(_true_path, _gvn.transform(continuation_support));
3969   pinVirtualThread->init_req(_false_path, _gvn.intcon(0));
3970 
3971   // Update branch state.
3972   set_control(_gvn.transform(vthread_compare_rgn));
3973   set_all_memory(_gvn.transform(vthread_compare_mem));
3974   set_i_o(_gvn.transform(vthread_compare_io));
3975 
3976   // Load the event writer oop by dereferencing the jobject handle.
3977   ciKlass* klass_EventWriter = env()->find_system_klass(ciSymbol::make("jdk/jfr/internal/event/EventWriter"));
3978   assert(klass_EventWriter->is_loaded(), "invariant");
3979   ciInstanceKlass* const instklass_EventWriter = klass_EventWriter->as_instance_klass();
3980   const TypeKlassPtr* const aklass = TypeKlassPtr::make(instklass_EventWriter);
3981   const TypeOopPtr* const xtype = aklass->as_instance_type();
3982   Node* jobj_untagged = _gvn.transform(new AddPNode(top(), jobj, _gvn.MakeConX(-JNIHandles::TypeTag::global)));
3983   Node* event_writer = access_load(jobj_untagged, xtype, T_OBJECT, IN_NATIVE | C2_CONTROL_DEPENDENT_LOAD);
3984 
3985   // Load the current thread id from the event writer object.
3986   Node* const event_writer_tid = load_field_from_object(event_writer, "threadID", "J");
3987   // Get the field offset to, conditionally, store an updated tid value later.
3988   Node* const event_writer_tid_field = field_address_from_object(event_writer, "threadID", "J", false);
3989   // Get the field offset to, conditionally, store an updated exclusion value later.
3990   Node* const event_writer_excluded_field = field_address_from_object(event_writer, "excluded", "Z", false);
3991   // Get the field offset to, conditionally, store an updated pinVirtualThread value later.
3992   Node* const event_writer_pin_field = field_address_from_object(event_writer, "pinVirtualThread", "Z", false);
3993 
3994   RegionNode* event_writer_tid_compare_rgn = new RegionNode(PATH_LIMIT);
3995   record_for_igvn(event_writer_tid_compare_rgn);
3996   PhiNode* event_writer_tid_compare_mem = new PhiNode(event_writer_tid_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3997   record_for_igvn(event_writer_tid_compare_mem);
3998   PhiNode* event_writer_tid_compare_io = new PhiNode(event_writer_tid_compare_rgn, Type::ABIO);
3999   record_for_igvn(event_writer_tid_compare_io);
4000 
4001   // Compare the current tid from the thread object to what is currently stored in the event writer object.
4002   Node* const tid_cmp = _gvn.transform(new CmpLNode(event_writer_tid, _gvn.transform(tid)));
4003   Node* test_tid_not_equal = _gvn.transform(new BoolNode(tid_cmp, BoolTest::ne));
4004   IfNode* iff_tid_not_equal = create_and_map_if(_gvn.transform(vthread_compare_rgn), test_tid_not_equal, PROB_FAIR, COUNT_UNKNOWN);
4005 
4006   // False path, tids are the same.
4007   Node* tid_is_equal = _gvn.transform(new IfFalseNode(iff_tid_not_equal));
4008 
4009   // True path, tid is not equal, need to update the tid in the event writer.
4010   Node* tid_is_not_equal = _gvn.transform(new IfTrueNode(iff_tid_not_equal));
4011   record_for_igvn(tid_is_not_equal);
4012 
4013   // Store the pin state to the event writer.
4014   store_to_memory(tid_is_not_equal, event_writer_pin_field, _gvn.transform(pinVirtualThread), T_BOOLEAN, MemNode::unordered);
4015 
4016   // Store the exclusion state to the event writer.
4017   Node* excluded_bool = _gvn.transform(new URShiftINode(_gvn.transform(exclusion), excluded_shift));
4018   store_to_memory(tid_is_not_equal, event_writer_excluded_field, excluded_bool, T_BOOLEAN, MemNode::unordered);
4019 
4020   // Store the tid to the event writer.
4021   store_to_memory(tid_is_not_equal, event_writer_tid_field, tid, T_LONG, MemNode::unordered);
4022 
4023   // Update control and phi nodes.
4024   event_writer_tid_compare_rgn->init_req(_true_path, tid_is_not_equal);
4025   event_writer_tid_compare_rgn->init_req(_false_path, tid_is_equal);
4026   event_writer_tid_compare_mem->init_req(_true_path, _gvn.transform(reset_memory()));
4027   event_writer_tid_compare_mem->init_req(_false_path, _gvn.transform(vthread_compare_mem));
4028   event_writer_tid_compare_io->init_req(_true_path, _gvn.transform(i_o()));
4029   event_writer_tid_compare_io->init_req(_false_path, _gvn.transform(vthread_compare_io));
4030 
4031   // Result of top level CFG, Memory, IO and Value.
4032   RegionNode* result_rgn = new RegionNode(PATH_LIMIT);
4033   PhiNode* result_mem = new PhiNode(result_rgn, Type::MEMORY, TypePtr::BOTTOM);
4034   PhiNode* result_io = new PhiNode(result_rgn, Type::ABIO);
4035   PhiNode* result_value = new PhiNode(result_rgn, TypeInstPtr::BOTTOM);
4036 
4037   // Result control.
4038   result_rgn->init_req(_true_path, _gvn.transform(event_writer_tid_compare_rgn));
4039   result_rgn->init_req(_false_path, jobj_is_null);
4040 
4041   // Result memory.
4042   result_mem->init_req(_true_path, _gvn.transform(event_writer_tid_compare_mem));
4043   result_mem->init_req(_false_path, _gvn.transform(input_memory_state));
4044 
4045   // Result IO.
4046   result_io->init_req(_true_path, _gvn.transform(event_writer_tid_compare_io));
4047   result_io->init_req(_false_path, _gvn.transform(input_io_state));
4048 
4049   // Result value.
4050   result_value->init_req(_true_path, _gvn.transform(event_writer)); // return event writer oop
4051   result_value->init_req(_false_path, null()); // return null
4052 
4053   // Set output state.
4054   set_control(_gvn.transform(result_rgn));
4055   set_all_memory(_gvn.transform(result_mem));
4056   set_i_o(_gvn.transform(result_io));
4057   set_result(result_rgn, result_value);
4058   return true;
4059 }
4060 
4061 /*
4062  * The intrinsic is a model of this pseudo-code:
4063  *
4064  * JfrThreadLocal* const tl = thread->jfr_thread_local();
4065  * if (carrierThread != thread) { // is virtual thread
4066  *   const u2 vthread_epoch_raw = java_lang_Thread::jfr_epoch(thread);
4067  *   bool excluded = vthread_epoch_raw & excluded_mask;
4068  *   AtomicAccess::store(&tl->_contextual_tid, java_lang_Thread::tid(thread));
4069  *   AtomicAccess::store(&tl->_contextual_thread_excluded, is_excluded);
4070  *   if (!excluded) {
4071  *     const u2 vthread_epoch = vthread_epoch_raw & epoch_mask;
4072  *     AtomicAccess::store(&tl->_vthread_epoch, vthread_epoch);
4073  *   }
4074  *   AtomicAccess::release_store(&tl->_vthread, true);
4075  *   return;
4076  * }
4077  * AtomicAccess::release_store(&tl->_vthread, false);
4078  */
4079 void LibraryCallKit::extend_setCurrentThread(Node* jt, Node* thread) {
4080   enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
4081 
4082   Node* input_memory_state = reset_memory();
4083   set_all_memory(input_memory_state);
4084 
4085   // The most significant bit of the u2 is used to denote thread exclusion
4086   Node* excluded_mask = _gvn.intcon(1 << 15);
4087   // The epoch generation is the range [1-32767]
4088   Node* epoch_mask = _gvn.intcon(32767);
4089 
4090   Node* const carrierThread = generate_current_thread(jt);
4091   // If thread != carrierThread, this is a virtual thread.
4092   Node* thread_cmp_carrierThread = _gvn.transform(new CmpPNode(thread, carrierThread));
4093   Node* test_thread_not_equal_carrierThread = _gvn.transform(new BoolNode(thread_cmp_carrierThread, BoolTest::ne));
4094   IfNode* iff_thread_not_equal_carrierThread =
4095     create_and_map_if(control(), test_thread_not_equal_carrierThread, PROB_FAIR, COUNT_UNKNOWN);
4096 
4097   Node* vthread_offset = basic_plus_adr(top(), jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_OFFSET_JFR));
4098 
4099   // False branch, is carrierThread.
4100   Node* thread_equal_carrierThread = _gvn.transform(new IfFalseNode(iff_thread_not_equal_carrierThread));
4101   // Store release
4102   Node* vthread_false_memory = store_to_memory(thread_equal_carrierThread, vthread_offset, _gvn.intcon(0), T_BOOLEAN, MemNode::release, true);
4103 
4104   set_all_memory(input_memory_state);
4105 
4106   // True branch, is virtual thread.
4107   Node* thread_not_equal_carrierThread = _gvn.transform(new IfTrueNode(iff_thread_not_equal_carrierThread));
4108   set_control(thread_not_equal_carrierThread);
4109 
4110   // Load the raw epoch value from the vthread.
4111   Node* epoch_offset = basic_plus_adr(thread, java_lang_Thread::jfr_epoch_offset());
4112   Node* epoch_raw = access_load_at(thread, epoch_offset, _gvn.type(epoch_offset)->is_ptr(), TypeInt::CHAR, T_CHAR,
4113                                    IN_HEAP | MO_UNORDERED | C2_MISMATCHED | C2_CONTROL_DEPENDENT_LOAD);
4114 
4115   // Mask off the excluded information from the epoch.
4116   Node * const is_excluded = _gvn.transform(new AndINode(epoch_raw, _gvn.transform(excluded_mask)));
4117 
4118   // Load the tid field from the thread.
4119   Node* tid = load_field_from_object(thread, "tid", "J");
4120 
4121   // Store the vthread tid to the jfr thread local.
4122   Node* thread_id_offset = basic_plus_adr(top(), jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_ID_OFFSET_JFR));
4123   Node* tid_memory = store_to_memory(control(), thread_id_offset, tid, T_LONG, MemNode::unordered, true);
4124 
4125   // Branch is_excluded to conditionalize updating the epoch .
4126   Node* excluded_cmp = _gvn.transform(new CmpINode(is_excluded, _gvn.transform(excluded_mask)));
4127   Node* test_excluded = _gvn.transform(new BoolNode(excluded_cmp, BoolTest::eq));
4128   IfNode* iff_excluded = create_and_map_if(control(), test_excluded, PROB_MIN, COUNT_UNKNOWN);
4129 
4130   // True branch, vthread is excluded, no need to write epoch info.
4131   Node* excluded = _gvn.transform(new IfTrueNode(iff_excluded));
4132   set_control(excluded);
4133   Node* vthread_is_excluded = _gvn.intcon(1);
4134 
4135   // False branch, vthread is included, update epoch info.
4136   Node* included = _gvn.transform(new IfFalseNode(iff_excluded));
4137   set_control(included);
4138   Node* vthread_is_included = _gvn.intcon(0);
4139 
4140   // Get epoch value.
4141   Node* epoch = _gvn.transform(new AndINode(epoch_raw, _gvn.transform(epoch_mask)));
4142 
4143   // Store the vthread epoch to the jfr thread local.
4144   Node* vthread_epoch_offset = basic_plus_adr(top(), jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_EPOCH_OFFSET_JFR));
4145   Node* included_memory = store_to_memory(control(), vthread_epoch_offset, epoch, T_CHAR, MemNode::unordered, true);
4146 
4147   RegionNode* excluded_rgn = new RegionNode(PATH_LIMIT);
4148   record_for_igvn(excluded_rgn);
4149   PhiNode* excluded_mem = new PhiNode(excluded_rgn, Type::MEMORY, TypePtr::BOTTOM);
4150   record_for_igvn(excluded_mem);
4151   PhiNode* exclusion = new PhiNode(excluded_rgn, TypeInt::BOOL);
4152   record_for_igvn(exclusion);
4153 
4154   // Merge the excluded control and memory.
4155   excluded_rgn->init_req(_true_path, excluded);
4156   excluded_rgn->init_req(_false_path, included);
4157   excluded_mem->init_req(_true_path, tid_memory);
4158   excluded_mem->init_req(_false_path, included_memory);
4159   exclusion->init_req(_true_path, _gvn.transform(vthread_is_excluded));
4160   exclusion->init_req(_false_path, _gvn.transform(vthread_is_included));
4161 
4162   // Set intermediate state.
4163   set_control(_gvn.transform(excluded_rgn));
4164   set_all_memory(excluded_mem);
4165 
4166   // Store the vthread exclusion state to the jfr thread local.
4167   Node* thread_local_excluded_offset = basic_plus_adr(top(), jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_EXCLUDED_OFFSET_JFR));
4168   store_to_memory(control(), thread_local_excluded_offset, _gvn.transform(exclusion), T_BOOLEAN, MemNode::unordered, true);
4169 
4170   // Store release
4171   Node * vthread_true_memory = store_to_memory(control(), vthread_offset, _gvn.intcon(1), T_BOOLEAN, MemNode::release, true);
4172 
4173   RegionNode* thread_compare_rgn = new RegionNode(PATH_LIMIT);
4174   record_for_igvn(thread_compare_rgn);
4175   PhiNode* thread_compare_mem = new PhiNode(thread_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
4176   record_for_igvn(thread_compare_mem);
4177   PhiNode* vthread = new PhiNode(thread_compare_rgn, TypeInt::BOOL);
4178   record_for_igvn(vthread);
4179 
4180   // Merge the thread_compare control and memory.
4181   thread_compare_rgn->init_req(_true_path, control());
4182   thread_compare_rgn->init_req(_false_path, thread_equal_carrierThread);
4183   thread_compare_mem->init_req(_true_path, vthread_true_memory);
4184   thread_compare_mem->init_req(_false_path, vthread_false_memory);
4185 
4186   // Set output state.
4187   set_control(_gvn.transform(thread_compare_rgn));
4188   set_all_memory(_gvn.transform(thread_compare_mem));
4189 }
4190 
4191 #endif // JFR_HAVE_INTRINSICS
4192 
4193 //------------------------inline_native_currentCarrierThread------------------
4194 bool LibraryCallKit::inline_native_currentCarrierThread() {
4195   Node* junk = nullptr;
4196   set_result(generate_current_thread(junk));
4197   return true;
4198 }
4199 
4200 //------------------------inline_native_currentThread------------------
4201 bool LibraryCallKit::inline_native_currentThread() {
4202   Node* junk = nullptr;
4203   set_result(generate_virtual_thread(junk));
4204   return true;
4205 }
4206 
4207 //------------------------inline_native_setVthread------------------
4208 bool LibraryCallKit::inline_native_setCurrentThread() {
4209   assert(C->method()->changes_current_thread(),
4210          "method changes current Thread but is not annotated ChangesCurrentThread");
4211   Node* arr = argument(1);
4212   Node* thread = _gvn.transform(new ThreadLocalNode());
4213   Node* p = basic_plus_adr(top()/*!oop*/, thread, in_bytes(JavaThread::vthread_offset()));
4214   Node* thread_obj_handle
4215     = make_load(nullptr, p, p->bottom_type()->is_ptr(), T_OBJECT, MemNode::unordered);
4216   thread_obj_handle = _gvn.transform(thread_obj_handle);
4217   const TypePtr *adr_type = _gvn.type(thread_obj_handle)->isa_ptr();
4218   access_store_at(nullptr, thread_obj_handle, adr_type, arr, _gvn.type(arr), T_OBJECT, IN_NATIVE | MO_UNORDERED);
4219 
4220   // Change the _monitor_owner_id of the JavaThread
4221   Node* tid = load_field_from_object(arr, "tid", "J");
4222   Node* monitor_owner_id_offset = basic_plus_adr(top(), thread, in_bytes(JavaThread::monitor_owner_id_offset()));
4223   store_to_memory(control(), monitor_owner_id_offset, tid, T_LONG, MemNode::unordered, true);
4224 
4225   JFR_ONLY(extend_setCurrentThread(thread, arr);)
4226   return true;
4227 }
4228 
4229 const Type* LibraryCallKit::scopedValueCache_type() {
4230   ciKlass* objects_klass = ciObjArrayKlass::make(env()->Object_klass());
4231   const TypeOopPtr* etype = TypeOopPtr::make_from_klass(env()->Object_klass());
4232   const TypeAry* arr0 = TypeAry::make(etype, TypeInt::POS, /* stable= */ false, /* flat= */ false, /* not_flat= */ true, /* not_null_free= */ true, true);
4233 
4234   // Because we create the scopedValue cache lazily we have to make the
4235   // type of the result BotPTR.
4236   bool xk = etype->klass_is_exact();
4237   const Type* objects_type = TypeAryPtr::make(TypePtr::BotPTR, arr0, objects_klass, xk, TypeAryPtr::Offset(0));
4238   return objects_type;
4239 }
4240 
4241 Node* LibraryCallKit::scopedValueCache_helper() {
4242   Node* thread = _gvn.transform(new ThreadLocalNode());
4243   Node* p = basic_plus_adr(top()/*!oop*/, thread, in_bytes(JavaThread::scopedValueCache_offset()));
4244   // We cannot use immutable_memory() because we might flip onto a
4245   // different carrier thread, at which point we'll need to use that
4246   // carrier thread's cache.
4247   // return _gvn.transform(LoadNode::make(_gvn, nullptr, immutable_memory(), p, p->bottom_type()->is_ptr(),
4248   //       TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered));
4249   return make_load(nullptr, p, p->bottom_type()->is_ptr(), T_ADDRESS, MemNode::unordered);
4250 }
4251 
4252 //------------------------inline_native_scopedValueCache------------------
4253 bool LibraryCallKit::inline_native_scopedValueCache() {
4254   Node* cache_obj_handle = scopedValueCache_helper();
4255   const Type* objects_type = scopedValueCache_type();
4256   set_result(access_load(cache_obj_handle, objects_type, T_OBJECT, IN_NATIVE));
4257 
4258   return true;
4259 }
4260 
4261 //------------------------inline_native_setScopedValueCache------------------
4262 bool LibraryCallKit::inline_native_setScopedValueCache() {
4263   Node* arr = argument(0);
4264   Node* cache_obj_handle = scopedValueCache_helper();
4265   const Type* objects_type = scopedValueCache_type();
4266 
4267   const TypePtr *adr_type = _gvn.type(cache_obj_handle)->isa_ptr();
4268   access_store_at(nullptr, cache_obj_handle, adr_type, arr, objects_type, T_OBJECT, IN_NATIVE | MO_UNORDERED);
4269 
4270   return true;
4271 }
4272 
4273 //------------------------inline_native_Continuation_pin and unpin-----------
4274 
4275 // Shared implementation routine for both pin and unpin.
4276 bool LibraryCallKit::inline_native_Continuation_pinning(bool unpin) {
4277   enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
4278 
4279   // Save input memory.
4280   Node* input_memory_state = reset_memory();
4281   set_all_memory(input_memory_state);
4282 
4283   // TLS
4284   Node* tls_ptr = _gvn.transform(new ThreadLocalNode());
4285   Node* last_continuation_offset = basic_plus_adr(top(), tls_ptr, in_bytes(JavaThread::cont_entry_offset()));
4286   Node* last_continuation = make_load(control(), last_continuation_offset, last_continuation_offset->get_ptr_type(), T_ADDRESS, MemNode::unordered);
4287 
4288   // Null check the last continuation object.
4289   Node* continuation_cmp_null = _gvn.transform(new CmpPNode(last_continuation, null()));
4290   Node* test_continuation_not_equal_null = _gvn.transform(new BoolNode(continuation_cmp_null, BoolTest::ne));
4291   IfNode* iff_continuation_not_equal_null = create_and_map_if(control(), test_continuation_not_equal_null, PROB_MAX, COUNT_UNKNOWN);
4292 
4293   // False path, last continuation is null.
4294   Node* continuation_is_null = _gvn.transform(new IfFalseNode(iff_continuation_not_equal_null));
4295 
4296   // True path, last continuation is not null.
4297   Node* continuation_is_not_null = _gvn.transform(new IfTrueNode(iff_continuation_not_equal_null));
4298 
4299   set_control(continuation_is_not_null);
4300 
4301   // Load the pin count from the last continuation.
4302   Node* pin_count_offset = basic_plus_adr(top(), last_continuation, in_bytes(ContinuationEntry::pin_count_offset()));
4303   Node* pin_count = make_load(control(), pin_count_offset, TypeInt::INT, T_INT, MemNode::unordered);
4304 
4305   // The loaded pin count is compared against a context specific rhs for over/underflow detection.
4306   Node* pin_count_rhs;
4307   if (unpin) {
4308     pin_count_rhs = _gvn.intcon(0);
4309   } else {
4310     pin_count_rhs = _gvn.intcon(UINT32_MAX);
4311   }
4312   Node* pin_count_cmp = _gvn.transform(new CmpUNode(_gvn.transform(pin_count), pin_count_rhs));
4313   Node* test_pin_count_over_underflow = _gvn.transform(new BoolNode(pin_count_cmp, BoolTest::eq));
4314   IfNode* iff_pin_count_over_underflow = create_and_map_if(control(), test_pin_count_over_underflow, PROB_MIN, COUNT_UNKNOWN);
4315 
4316   // True branch, pin count over/underflow.
4317   Node* pin_count_over_underflow = _gvn.transform(new IfTrueNode(iff_pin_count_over_underflow));
4318   {
4319     // Trap (but not deoptimize (Action_none)) and continue in the interpreter
4320     // which will throw IllegalStateException for pin count over/underflow.
4321     // No memory changed so far - we can use memory create by reset_memory()
4322     // at the beginning of this intrinsic. No need to call reset_memory() again.
4323     PreserveJVMState pjvms(this);
4324     set_control(pin_count_over_underflow);
4325     uncommon_trap(Deoptimization::Reason_intrinsic,
4326                   Deoptimization::Action_none);
4327     assert(stopped(), "invariant");
4328   }
4329 
4330   // False branch, no pin count over/underflow. Increment or decrement pin count and store back.
4331   Node* valid_pin_count = _gvn.transform(new IfFalseNode(iff_pin_count_over_underflow));
4332   set_control(valid_pin_count);
4333 
4334   Node* next_pin_count;
4335   if (unpin) {
4336     next_pin_count = _gvn.transform(new SubINode(pin_count, _gvn.intcon(1)));
4337   } else {
4338     next_pin_count = _gvn.transform(new AddINode(pin_count, _gvn.intcon(1)));
4339   }
4340 
4341   store_to_memory(control(), pin_count_offset, next_pin_count, T_INT, MemNode::unordered);
4342 
4343   // Result of top level CFG and Memory.
4344   RegionNode* result_rgn = new RegionNode(PATH_LIMIT);
4345   record_for_igvn(result_rgn);
4346   PhiNode* result_mem = new PhiNode(result_rgn, Type::MEMORY, TypePtr::BOTTOM);
4347   record_for_igvn(result_mem);
4348 
4349   result_rgn->init_req(_true_path, _gvn.transform(valid_pin_count));
4350   result_rgn->init_req(_false_path, _gvn.transform(continuation_is_null));
4351   result_mem->init_req(_true_path, _gvn.transform(reset_memory()));
4352   result_mem->init_req(_false_path, _gvn.transform(input_memory_state));
4353 
4354   // Set output state.
4355   set_control(_gvn.transform(result_rgn));
4356   set_all_memory(_gvn.transform(result_mem));
4357 
4358   return true;
4359 }
4360 
4361 //---------------------------load_mirror_from_klass----------------------------
4362 // Given a klass oop, load its java mirror (a java.lang.Class oop).
4363 Node* LibraryCallKit::load_mirror_from_klass(Node* klass) {
4364   Node* p = basic_plus_adr(top(), klass, in_bytes(Klass::java_mirror_offset()));
4365   Node* load = make_load(nullptr, p, TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered);
4366   // mirror = ((OopHandle)mirror)->resolve();
4367   return access_load(load, TypeInstPtr::MIRROR, T_OBJECT, IN_NATIVE);
4368 }
4369 
4370 //-----------------------load_klass_from_mirror_common-------------------------
4371 // Given a java mirror (a java.lang.Class oop), load its corresponding klass oop.
4372 // Test the klass oop for null (signifying a primitive Class like Integer.TYPE),
4373 // and branch to the given path on the region.
4374 // If never_see_null, take an uncommon trap on null, so we can optimistically
4375 // compile for the non-null case.
4376 // If the region is null, force never_see_null = true.
4377 Node* LibraryCallKit::load_klass_from_mirror_common(Node* mirror,
4378                                                     bool never_see_null,
4379                                                     RegionNode* region,
4380                                                     int null_path,
4381                                                     int offset) {
4382   if (region == nullptr)  never_see_null = true;
4383   Node* p = basic_plus_adr(mirror, offset);
4384   const TypeKlassPtr*  kls_type = TypeInstKlassPtr::OBJECT_OR_NULL;
4385   Node* kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), p, TypeRawPtr::BOTTOM, kls_type));
4386   Node* null_ctl = top();
4387   kls = null_check_oop(kls, &null_ctl, never_see_null);
4388   if (region != nullptr) {
4389     // Set region->in(null_path) if the mirror is a primitive (e.g, int.class).
4390     region->init_req(null_path, null_ctl);
4391   } else {
4392     assert(null_ctl == top(), "no loose ends");
4393   }
4394   return kls;
4395 }
4396 
4397 //--------------------(inline_native_Class_query helpers)---------------------
4398 // Use this for JVM_ACC_INTERFACE.
4399 // Fall through if (mods & mask) == bits, take the guard otherwise.
4400 Node* LibraryCallKit::generate_klass_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region,
4401                                                  ByteSize offset, const Type* type, BasicType bt) {
4402   // Branch around if the given klass has the given modifier bit set.
4403   // Like generate_guard, adds a new path onto the region.
4404   Node* modp = basic_plus_adr(top(), kls, in_bytes(offset));
4405   Node* mods = make_load(nullptr, modp, type, bt, MemNode::unordered);
4406   Node* mask = intcon(modifier_mask);
4407   Node* bits = intcon(modifier_bits);
4408   Node* mbit = _gvn.transform(new AndINode(mods, mask));
4409   Node* cmp  = _gvn.transform(new CmpINode(mbit, bits));
4410   Node* bol  = _gvn.transform(new BoolNode(cmp, BoolTest::ne));
4411   return generate_fair_guard(bol, region);
4412 }
4413 
4414 Node* LibraryCallKit::generate_interface_guard(Node* kls, RegionNode* region) {
4415   return generate_klass_flags_guard(kls, JVM_ACC_INTERFACE, 0, region,
4416                                     InstanceKlass::access_flags_offset(), TypeInt::CHAR, T_CHAR);
4417 }
4418 
4419 // Use this for testing if Klass is_hidden, has_finalizer, and is_cloneable_fast.
4420 Node* LibraryCallKit::generate_misc_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region) {
4421   return generate_klass_flags_guard(kls, modifier_mask, modifier_bits, region,
4422                                     Klass::misc_flags_offset(), TypeInt::UBYTE, T_BOOLEAN);
4423 }
4424 
4425 Node* LibraryCallKit::generate_hidden_class_guard(Node* kls, RegionNode* region) {
4426   return generate_misc_flags_guard(kls, KlassFlags::_misc_is_hidden_class, 0, region);
4427 }
4428 
4429 //-------------------------inline_native_Class_query-------------------
4430 bool LibraryCallKit::inline_native_Class_query(vmIntrinsics::ID id) {
4431   const Type* return_type = TypeInt::BOOL;
4432   Node* prim_return_value = top();  // what happens if it's a primitive class?
4433   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
4434   bool expect_prim = false;     // most of these guys expect to work on refs
4435 
4436   enum { _normal_path = 1, _prim_path = 2, PATH_LIMIT };
4437 
4438   Node* mirror = argument(0);
4439   Node* obj    = top();
4440 
4441   switch (id) {
4442   case vmIntrinsics::_isInstance:
4443     // nothing is an instance of a primitive type
4444     prim_return_value = intcon(0);
4445     obj = argument(1);
4446     break;
4447   case vmIntrinsics::_isHidden:
4448     prim_return_value = intcon(0);
4449     break;
4450   case vmIntrinsics::_getSuperclass:
4451     prim_return_value = null();
4452     return_type = TypeInstPtr::MIRROR->cast_to_ptr_type(TypePtr::BotPTR);
4453     break;
4454   default:
4455     fatal_unexpected_iid(id);
4456     break;
4457   }
4458 
4459   const TypeInstPtr* mirror_con = _gvn.type(mirror)->isa_instptr();
4460   if (mirror_con == nullptr)  return false;  // cannot happen?
4461 
4462 #ifndef PRODUCT
4463   if (C->print_intrinsics() || C->print_inlining()) {
4464     ciType* k = mirror_con->java_mirror_type();
4465     if (k) {
4466       tty->print("Inlining %s on constant Class ", vmIntrinsics::name_at(intrinsic_id()));
4467       k->print_name();
4468       tty->cr();
4469     }
4470   }
4471 #endif
4472 
4473   // Null-check the mirror, and the mirror's klass ptr (in case it is a primitive).
4474   RegionNode* region = new RegionNode(PATH_LIMIT);
4475   record_for_igvn(region);
4476   PhiNode* phi = new PhiNode(region, return_type);
4477 
4478   // The mirror will never be null of Reflection.getClassAccessFlags, however
4479   // it may be null for Class.isInstance or Class.getModifiers. Throw a NPE
4480   // if it is. See bug 4774291.
4481 
4482   // For Reflection.getClassAccessFlags(), the null check occurs in
4483   // the wrong place; see inline_unsafe_access(), above, for a similar
4484   // situation.
4485   mirror = null_check(mirror);
4486   // If mirror or obj is dead, only null-path is taken.
4487   if (stopped())  return true;
4488 
4489   if (expect_prim)  never_see_null = false;  // expect nulls (meaning prims)
4490 
4491   // Now load the mirror's klass metaobject, and null-check it.
4492   // Side-effects region with the control path if the klass is null.
4493   Node* kls = load_klass_from_mirror(mirror, never_see_null, region, _prim_path);
4494   // If kls is null, we have a primitive mirror.
4495   phi->init_req(_prim_path, prim_return_value);
4496   if (stopped()) { set_result(region, phi); return true; }
4497   bool safe_for_replace = (region->in(_prim_path) == top());
4498 
4499   Node* p;  // handy temp
4500   Node* null_ctl;
4501 
4502   // Now that we have the non-null klass, we can perform the real query.
4503   // For constant classes, the query will constant-fold in LoadNode::Value.
4504   Node* query_value = top();
4505   switch (id) {
4506   case vmIntrinsics::_isInstance:
4507     // nothing is an instance of a primitive type
4508     query_value = gen_instanceof(obj, kls, safe_for_replace);
4509     break;
4510 
4511   case vmIntrinsics::_isHidden:
4512     // (To verify this code sequence, check the asserts in JVM_IsHiddenClass.)
4513     if (generate_hidden_class_guard(kls, region) != nullptr)
4514       // A guard was added.  If the guard is taken, it was an hidden class.
4515       phi->add_req(intcon(1));
4516     // If we fall through, it's a plain class.
4517     query_value = intcon(0);
4518     break;
4519 
4520 
4521   case vmIntrinsics::_getSuperclass:
4522     // The rules here are somewhat unfortunate, but we can still do better
4523     // with random logic than with a JNI call.
4524     // Interfaces store null or Object as _super, but must report null.
4525     // Arrays store an intermediate super as _super, but must report Object.
4526     // Other types can report the actual _super.
4527     // (To verify this code sequence, check the asserts in JVM_IsInterface.)
4528     if (generate_array_guard(kls, region) != nullptr) {
4529       // A guard was added.  If the guard is taken, it was an array.
4530       phi->add_req(makecon(TypeInstPtr::make(env()->Object_klass()->java_mirror())));
4531     }
4532     // Check for interface after array since this checks AccessFlags offset into InstanceKlass.
4533     // In other words, we are accessing subtype-specific information, so we need to determine the subtype first.
4534     if (generate_interface_guard(kls, region) != nullptr) {
4535       // A guard was added.  If the guard is taken, it was an interface.
4536       phi->add_req(null());
4537     }
4538     // If we fall through, it's a plain class.  Get its _super.
4539     if (!stopped()) {
4540       p = basic_plus_adr(top(), kls, in_bytes(Klass::super_offset()));
4541       kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), p, TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
4542       null_ctl = top();
4543       kls = null_check_oop(kls, &null_ctl);
4544       if (null_ctl != top()) {
4545         // If the guard is taken, Object.superClass is null (both klass and mirror).
4546         region->add_req(null_ctl);
4547         phi   ->add_req(null());
4548       }
4549       if (!stopped()) {
4550         query_value = load_mirror_from_klass(kls);
4551       }
4552     }
4553     break;
4554 
4555   default:
4556     fatal_unexpected_iid(id);
4557     break;
4558   }
4559 
4560   // Fall-through is the normal case of a query to a real class.
4561   phi->init_req(1, query_value);
4562   region->init_req(1, control());
4563 
4564   C->set_has_split_ifs(true); // Has chance for split-if optimization
4565   set_result(region, phi);
4566   return true;
4567 }
4568 
4569 
4570 //-------------------------inline_Class_cast-------------------
4571 bool LibraryCallKit::inline_Class_cast() {
4572   Node* mirror = argument(0); // Class
4573   Node* obj    = argument(1);
4574   const TypeInstPtr* mirror_con = _gvn.type(mirror)->isa_instptr();
4575   if (mirror_con == nullptr) {
4576     return false;  // dead path (mirror->is_top()).
4577   }
4578   if (obj == nullptr || obj->is_top()) {
4579     return false;  // dead path
4580   }
4581   const TypeOopPtr* tp = _gvn.type(obj)->isa_oopptr();
4582 
4583   // First, see if Class.cast() can be folded statically.
4584   // java_mirror_type() returns non-null for compile-time Class constants.
4585   ciType* tm = mirror_con->java_mirror_type();
4586   if (tm != nullptr && tm->is_klass() &&
4587       tp != nullptr) {
4588     if (!tp->is_loaded()) {
4589       // Don't use intrinsic when class is not loaded.
4590       return false;
4591     } else {
4592       const TypeKlassPtr* tklass = TypeKlassPtr::make(tm->as_klass(), Type::trust_interfaces);
4593       int static_res = C->static_subtype_check(tklass, tp->as_klass_type());
4594       if (static_res == Compile::SSC_always_true) {
4595         // isInstance() is true - fold the code.
4596         set_result(obj);
4597         return true;
4598       } else if (static_res == Compile::SSC_always_false) {
4599         // Don't use intrinsic, have to throw ClassCastException.
4600         // If the reference is null, the non-intrinsic bytecode will
4601         // be optimized appropriately.
4602         return false;
4603       }
4604     }
4605   }
4606 
4607   // Bailout intrinsic and do normal inlining if exception path is frequent.
4608   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
4609     return false;
4610   }
4611 
4612   // Generate dynamic checks.
4613   // Class.cast() is java implementation of _checkcast bytecode.
4614   // Do checkcast (Parse::do_checkcast()) optimizations here.
4615 
4616   mirror = null_check(mirror);
4617   // If mirror is dead, only null-path is taken.
4618   if (stopped()) {
4619     return true;
4620   }
4621 
4622   // Not-subtype or the mirror's klass ptr is nullptr (in case it is a primitive).
4623   enum { _bad_type_path = 1, _prim_path = 2, _npe_path = 3, PATH_LIMIT };
4624   RegionNode* region = new RegionNode(PATH_LIMIT);
4625   record_for_igvn(region);
4626 
4627   // Now load the mirror's klass metaobject, and null-check it.
4628   // If kls is null, we have a primitive mirror and
4629   // nothing is an instance of a primitive type.
4630   Node* kls = load_klass_from_mirror(mirror, false, region, _prim_path);
4631 
4632   Node* res = top();
4633   Node* io = i_o();
4634   Node* mem = merged_memory();
4635   if (!stopped()) {
4636 
4637     Node* bad_type_ctrl = top();
4638     // Do checkcast optimizations.
4639     res = gen_checkcast(obj, kls, &bad_type_ctrl);
4640     region->init_req(_bad_type_path, bad_type_ctrl);
4641   }
4642   if (region->in(_prim_path) != top() ||
4643       region->in(_bad_type_path) != top() ||
4644       region->in(_npe_path) != top()) {
4645     // Let Interpreter throw ClassCastException.
4646     PreserveJVMState pjvms(this);
4647     set_control(_gvn.transform(region));
4648     // Set IO and memory because gen_checkcast may override them when buffering inline types
4649     set_i_o(io);
4650     set_all_memory(mem);
4651     uncommon_trap(Deoptimization::Reason_intrinsic,
4652                   Deoptimization::Action_maybe_recompile);
4653   }
4654   if (!stopped()) {
4655     set_result(res);
4656   }
4657   return true;
4658 }
4659 
4660 
4661 //--------------------------inline_native_subtype_check------------------------
4662 // This intrinsic takes the JNI calls out of the heart of
4663 // UnsafeFieldAccessorImpl.set, which improves Field.set, readObject, etc.
4664 bool LibraryCallKit::inline_native_subtype_check() {
4665   // Pull both arguments off the stack.
4666   Node* args[2];                // two java.lang.Class mirrors: superc, subc
4667   args[0] = argument(0);
4668   args[1] = argument(1);
4669   Node* klasses[2];             // corresponding Klasses: superk, subk
4670   klasses[0] = klasses[1] = top();
4671 
4672   enum {
4673     // A full decision tree on {superc is prim, subc is prim}:
4674     _prim_0_path = 1,           // {P,N} => false
4675                                 // {P,P} & superc!=subc => false
4676     _prim_same_path,            // {P,P} & superc==subc => true
4677     _prim_1_path,               // {N,P} => false
4678     _ref_subtype_path,          // {N,N} & subtype check wins => true
4679     _both_ref_path,             // {N,N} & subtype check loses => false
4680     PATH_LIMIT
4681   };
4682 
4683   RegionNode* region = new RegionNode(PATH_LIMIT);
4684   RegionNode* prim_region = new RegionNode(2);
4685   Node*       phi    = new PhiNode(region, TypeInt::BOOL);
4686   record_for_igvn(region);
4687   record_for_igvn(prim_region);
4688 
4689   const TypePtr* adr_type = TypeRawPtr::BOTTOM;   // memory type of loads
4690   const TypeKlassPtr* kls_type = TypeInstKlassPtr::OBJECT_OR_NULL;
4691   int class_klass_offset = java_lang_Class::klass_offset();
4692 
4693   // First null-check both mirrors and load each mirror's klass metaobject.
4694   int which_arg;
4695   for (which_arg = 0; which_arg <= 1; which_arg++) {
4696     Node* arg = args[which_arg];
4697     arg = null_check(arg);
4698     if (stopped())  break;
4699     args[which_arg] = arg;
4700 
4701     Node* p = basic_plus_adr(arg, class_klass_offset);
4702     Node* kls = LoadKlassNode::make(_gvn, immutable_memory(), p, adr_type, kls_type);
4703     klasses[which_arg] = _gvn.transform(kls);
4704   }
4705 
4706   // Having loaded both klasses, test each for null.
4707   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
4708   for (which_arg = 0; which_arg <= 1; which_arg++) {
4709     Node* kls = klasses[which_arg];
4710     Node* null_ctl = top();
4711     kls = null_check_oop(kls, &null_ctl, never_see_null);
4712     if (which_arg == 0) {
4713       prim_region->init_req(1, null_ctl);
4714     } else {
4715       region->init_req(_prim_1_path, null_ctl);
4716     }
4717     if (stopped())  break;
4718     klasses[which_arg] = kls;
4719   }
4720 
4721   if (!stopped()) {
4722     // now we have two reference types, in klasses[0..1]
4723     Node* subk   = klasses[1];  // the argument to isAssignableFrom
4724     Node* superk = klasses[0];  // the receiver
4725     region->set_req(_both_ref_path, gen_subtype_check(subk, superk));
4726     region->set_req(_ref_subtype_path, control());
4727   }
4728 
4729   // If both operands are primitive (both klasses null), then
4730   // we must return true when they are identical primitives.
4731   // It is convenient to test this after the first null klass check.
4732   // This path is also used if superc is a value mirror.
4733   set_control(_gvn.transform(prim_region));
4734   if (!stopped()) {
4735     // Since superc is primitive, make a guard for the superc==subc case.
4736     Node* cmp_eq = _gvn.transform(new CmpPNode(args[0], args[1]));
4737     Node* bol_eq = _gvn.transform(new BoolNode(cmp_eq, BoolTest::eq));
4738     generate_fair_guard(bol_eq, region);
4739     if (region->req() == PATH_LIMIT+1) {
4740       // A guard was added.  If the added guard is taken, superc==subc.
4741       region->swap_edges(PATH_LIMIT, _prim_same_path);
4742       region->del_req(PATH_LIMIT);
4743     }
4744     region->set_req(_prim_0_path, control()); // Not equal after all.
4745   }
4746 
4747   // these are the only paths that produce 'true':
4748   phi->set_req(_prim_same_path,   intcon(1));
4749   phi->set_req(_ref_subtype_path, intcon(1));
4750 
4751   // pull together the cases:
4752   assert(region->req() == PATH_LIMIT, "sane region");
4753   for (uint i = 1; i < region->req(); i++) {
4754     Node* ctl = region->in(i);
4755     if (ctl == nullptr || ctl == top()) {
4756       region->set_req(i, top());
4757       phi   ->set_req(i, top());
4758     } else if (phi->in(i) == nullptr) {
4759       phi->set_req(i, intcon(0)); // all other paths produce 'false'
4760     }
4761   }
4762 
4763   set_control(_gvn.transform(region));
4764   set_result(_gvn.transform(phi));
4765   return true;
4766 }
4767 
4768 //---------------------generate_array_guard_common------------------------
4769 Node* LibraryCallKit::generate_array_guard_common(Node* kls, RegionNode* region, ArrayKind kind, Node** obj) {
4770 
4771   if (stopped()) {
4772     return nullptr;
4773   }
4774 
4775   // Like generate_guard, adds a new path onto the region.
4776   jint  layout_con = 0;
4777   Node* layout_val = get_layout_helper(kls, layout_con);
4778   if (layout_val == nullptr) {
4779     bool query = 0;
4780     switch(kind) {
4781       case RefArray:       query = Klass::layout_helper_is_refArray(layout_con); break;
4782       case NonRefArray:    query = !Klass::layout_helper_is_refArray(layout_con); break;
4783       case TypeArray:      query = Klass::layout_helper_is_typeArray(layout_con); break;
4784       case AnyArray:       query = Klass::layout_helper_is_array(layout_con); break;
4785       case NonArray:       query = !Klass::layout_helper_is_array(layout_con); break;
4786       default:
4787         ShouldNotReachHere();
4788     }
4789     if (!query) {
4790       return nullptr;                       // never a branch
4791     } else {                             // always a branch
4792       Node* always_branch = control();
4793       if (region != nullptr)
4794         region->add_req(always_branch);
4795       set_control(top());
4796       return always_branch;
4797     }
4798   }
4799   unsigned int value = 0;
4800   BoolTest::mask btest = BoolTest::illegal;
4801   switch(kind) {
4802     case RefArray:
4803     case NonRefArray: {
4804       value = Klass::_lh_array_tag_ref_value;
4805       layout_val = _gvn.transform(new RShiftINode(layout_val, intcon(Klass::_lh_array_tag_shift)));
4806       btest = (kind == RefArray) ? BoolTest::eq : BoolTest::ne;
4807       break;
4808     }
4809     case TypeArray: {
4810       value = Klass::_lh_array_tag_type_value;
4811       layout_val = _gvn.transform(new RShiftINode(layout_val, intcon(Klass::_lh_array_tag_shift)));
4812       btest = BoolTest::eq;
4813       break;
4814     }
4815     case AnyArray:    value = Klass::_lh_neutral_value; btest = BoolTest::lt; break;
4816     case NonArray:    value = Klass::_lh_neutral_value; btest = BoolTest::gt; break;
4817     default:
4818       ShouldNotReachHere();
4819   }
4820   // Now test the correct condition.
4821   jint nval = (jint)value;
4822   Node* cmp = _gvn.transform(new CmpINode(layout_val, intcon(nval)));
4823   Node* bol = _gvn.transform(new BoolNode(cmp, btest));
4824   Node* ctrl = generate_fair_guard(bol, region);
4825   Node* is_array_ctrl = kind == NonArray ? control() : ctrl;
4826   if (obj != nullptr && is_array_ctrl != nullptr && is_array_ctrl != top()) {
4827     // Keep track of the fact that 'obj' is an array to prevent
4828     // array specific accesses from floating above the guard.
4829     *obj = _gvn.transform(new CastPPNode(is_array_ctrl, *obj, TypeAryPtr::BOTTOM));
4830   }
4831   return ctrl;
4832 }
4833 
4834 // public static native Object[] ValueClass::newNullRestrictedAtomicArray(Class<?> componentType, int length, Object initVal);
4835 // public static native Object[] ValueClass::newNullRestrictedNonAtomicArray(Class<?> componentType, int length, Object initVal);
4836 // public static native Object[] ValueClass::newNullableAtomicArray(Class<?> componentType, int length);
4837 bool LibraryCallKit::inline_newArray(bool null_free, bool atomic) {
4838   assert(null_free || atomic, "nullable implies atomic");
4839   Node* componentType = argument(0);
4840   Node* length = argument(1);
4841   Node* init_val = null_free ? argument(2) : nullptr;
4842 
4843   const TypeInstPtr* tp = _gvn.type(componentType)->isa_instptr();
4844   if (tp != nullptr) {
4845     ciInstanceKlass* ik = tp->instance_klass();
4846     if (ik == C->env()->Class_klass()) {
4847       ciType* t = tp->java_mirror_type();
4848       if (t != nullptr && t->is_inlinetype()) {
4849 
4850         ciArrayKlass* array_klass = ciArrayKlass::make(t, null_free, atomic, true);
4851         assert(array_klass->is_elem_null_free() == null_free, "inconsistency");
4852 
4853         // TOOD 8350865 ZGC needs card marks on initializing oop stores
4854         if (UseZGC && null_free && !array_klass->is_flat_array_klass()) {
4855           return false;
4856         }
4857 
4858         if (array_klass->is_loaded() && array_klass->element_klass()->as_inline_klass()->is_initialized()) {
4859           const TypeAryKlassPtr* array_klass_type = TypeAryKlassPtr::make(array_klass, Type::trust_interfaces);
4860           if (null_free) {
4861             if (init_val->is_InlineType()) {
4862               if (array_klass_type->is_flat() && init_val->as_InlineType()->is_all_zero(&gvn(), /* flat */ true)) {
4863                 // Zeroing is enough because the init value is the all-zero value
4864                 init_val = nullptr;
4865               } else {
4866                 init_val = init_val->as_InlineType()->buffer(this);
4867               }
4868             }
4869             // TODO 8350865 Should we add a check of the init_val type (maybe in debug only + halt)?
4870             // If we insert a checkcast here, we can be sure that init_val is an InlineTypeNode, so
4871             // when we folded a field load from an allocation (e.g. during escape analysis), we can
4872             // remove the check init_val->is_InlineType().
4873           }
4874           Node* obj = new_array(makecon(array_klass_type), length, 0, nullptr, false, init_val);
4875           const TypeAryPtr* arytype = gvn().type(obj)->is_aryptr();
4876           assert(arytype->is_null_free() == null_free, "inconsistency");
4877           assert(arytype->is_not_null_free() == !null_free, "inconsistency");
4878           set_result(obj);
4879           return true;
4880         }
4881       }
4882     }
4883   }
4884   return false;
4885 }
4886 
4887 // public static native boolean ValueClass::isFlatArray(Object array);
4888 // public static native boolean ValueClass::isNullRestrictedArray(Object array);
4889 // public static native boolean ValueClass::isAtomicArray(Object array);
4890 bool LibraryCallKit::inline_getArrayProperties(ArrayPropertiesCheck check) {
4891   Node* array = argument(0);
4892 
4893   Node* bol;
4894   switch(check) {
4895     case IsFlat:
4896       // TODO 8350865 Use the object version here instead of loading the klass
4897       // The problem is that PhaseMacroExpand::expand_flatarraycheck_node can only handle some IR shapes and will fail, for example, if the bol is directly wired to a ReturnNode
4898       bol = flat_array_test(load_object_klass(array));
4899       break;
4900     case IsNullRestricted:
4901       bol = null_free_array_test(array);
4902       break;
4903     case IsAtomic:
4904       // TODO 8350865 Implement this. It's a bit more complicated, see conditions in JVM_IsAtomicArray
4905       // Enable TestIntrinsics::test87/88 once this is implemented
4906       // bol = null_free_atomic_array_test
4907       return false;
4908     default:
4909       ShouldNotReachHere();
4910   }
4911 
4912   Node* res = gvn().transform(new CMoveINode(bol, intcon(0), intcon(1), TypeInt::BOOL));
4913   set_result(res);
4914   return true;
4915 }
4916 
4917 // Load the default refined array klass from an ObjArrayKlass. This relies on the first entry in the
4918 // '_next_refined_array_klass' linked list being the default (see ObjArrayKlass::klass_with_properties).
4919 Node* LibraryCallKit::load_default_refined_array_klass(Node* klass_node, bool type_array_guard) {
4920   RegionNode* region = new RegionNode(2);
4921   Node* phi = new PhiNode(region, TypeInstKlassPtr::OBJECT_OR_NULL);
4922 
4923   if (type_array_guard) {
4924     generate_typeArray_guard(klass_node, region);
4925     if (region->req() == 3) {
4926       phi->add_req(klass_node);
4927     }
4928   }
4929   Node* adr_refined_klass = basic_plus_adr(top(), klass_node, in_bytes(ObjArrayKlass::next_refined_array_klass_offset()));
4930   Node* refined_klass = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), adr_refined_klass, TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
4931 
4932   // Can be null if not initialized yet, just deopt
4933   Node* null_ctl = top();
4934   refined_klass = null_check_oop(refined_klass, &null_ctl, /* never_see_null= */ true);
4935 
4936   region->init_req(1, control());
4937   phi->init_req(1, refined_klass);
4938 
4939   set_control(_gvn.transform(region));
4940   return _gvn.transform(phi);
4941 }
4942 
4943 // Load the non-refined array klass from an ObjArrayKlass.
4944 Node* LibraryCallKit::load_non_refined_array_klass(Node* klass_node) {
4945   const TypeAryKlassPtr* ary_klass_ptr = _gvn.type(klass_node)->isa_aryklassptr();
4946   if (ary_klass_ptr != nullptr && ary_klass_ptr->klass_is_exact()) {
4947     return _gvn.makecon(ary_klass_ptr->cast_to_refined_array_klass_ptr(false));
4948   }
4949 
4950   RegionNode* region = new RegionNode(2);
4951   Node* phi = new PhiNode(region, TypeInstKlassPtr::OBJECT);
4952 
4953   generate_typeArray_guard(klass_node, region);
4954   if (region->req() == 3) {
4955     phi->add_req(klass_node);
4956   }
4957   Node* super_adr = basic_plus_adr(top(), klass_node, in_bytes(Klass::super_offset()));
4958   Node* super_klass = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), super_adr, TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT));
4959 
4960   region->init_req(1, control());
4961   phi->init_req(1, super_klass);
4962 
4963   set_control(_gvn.transform(region));
4964   return _gvn.transform(phi);
4965 }
4966 
4967 //-----------------------inline_native_newArray--------------------------
4968 // private static native Object java.lang.reflect.Array.newArray(Class<?> componentType, int length);
4969 // private        native Object Unsafe.allocateUninitializedArray0(Class<?> cls, int size);
4970 bool LibraryCallKit::inline_unsafe_newArray(bool uninitialized) {
4971   Node* mirror;
4972   Node* count_val;
4973   if (uninitialized) {
4974     null_check_receiver();
4975     mirror    = argument(1);
4976     count_val = argument(2);
4977   } else {
4978     mirror    = argument(0);
4979     count_val = argument(1);
4980   }
4981 
4982   mirror = null_check(mirror);
4983   // If mirror or obj is dead, only null-path is taken.
4984   if (stopped())  return true;
4985 
4986   enum { _normal_path = 1, _slow_path = 2, PATH_LIMIT };
4987   RegionNode* result_reg = new RegionNode(PATH_LIMIT);
4988   PhiNode*    result_val = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
4989   PhiNode*    result_io  = new PhiNode(result_reg, Type::ABIO);
4990   PhiNode*    result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
4991 
4992   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
4993   Node* klass_node = load_array_klass_from_mirror(mirror, never_see_null,
4994                                                   result_reg, _slow_path);
4995   Node* normal_ctl   = control();
4996   Node* no_array_ctl = result_reg->in(_slow_path);
4997 
4998   // Generate code for the slow case.  We make a call to newArray().
4999   set_control(no_array_ctl);
5000   if (!stopped()) {
5001     // Either the input type is void.class, or else the
5002     // array klass has not yet been cached.  Either the
5003     // ensuing call will throw an exception, or else it
5004     // will cache the array klass for next time.
5005     PreserveJVMState pjvms(this);
5006     CallJavaNode* slow_call = nullptr;
5007     if (uninitialized) {
5008       // Generate optimized virtual call (holder class 'Unsafe' is final)
5009       slow_call = generate_method_call(vmIntrinsics::_allocateUninitializedArray, false, false, true);
5010     } else {
5011       slow_call = generate_method_call_static(vmIntrinsics::_newArray, true);
5012     }
5013     Node* slow_result = set_results_for_java_call(slow_call);
5014     // this->control() comes from set_results_for_java_call
5015     result_reg->set_req(_slow_path, control());
5016     result_val->set_req(_slow_path, slow_result);
5017     result_io ->set_req(_slow_path, i_o());
5018     result_mem->set_req(_slow_path, reset_memory());
5019   }
5020 
5021   set_control(normal_ctl);
5022   if (!stopped()) {
5023     // Normal case:  The array type has been cached in the java.lang.Class.
5024     // The following call works fine even if the array type is polymorphic.
5025     // It could be a dynamic mix of int[], boolean[], Object[], etc.
5026 
5027     klass_node = load_default_refined_array_klass(klass_node);
5028 
5029     Node* obj = new_array(klass_node, count_val, 0);  // no arguments to push
5030     result_reg->init_req(_normal_path, control());
5031     result_val->init_req(_normal_path, obj);
5032     result_io ->init_req(_normal_path, i_o());
5033     result_mem->init_req(_normal_path, reset_memory());
5034 
5035     if (uninitialized) {
5036       // Mark the allocation so that zeroing is skipped
5037       AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(obj);
5038       alloc->maybe_set_complete(&_gvn);
5039     }
5040   }
5041 
5042   // Return the combined state.
5043   set_i_o(        _gvn.transform(result_io)  );
5044   set_all_memory( _gvn.transform(result_mem));
5045 
5046   C->set_has_split_ifs(true); // Has chance for split-if optimization
5047   set_result(result_reg, result_val);
5048   return true;
5049 }
5050 
5051 //----------------------inline_native_getLength--------------------------
5052 // public static native int java.lang.reflect.Array.getLength(Object array);
5053 bool LibraryCallKit::inline_native_getLength() {
5054   if (too_many_traps(Deoptimization::Reason_intrinsic))  return false;
5055 
5056   Node* array = null_check(argument(0));
5057   // If array is dead, only null-path is taken.
5058   if (stopped())  return true;
5059 
5060   // Deoptimize if it is a non-array.
5061   Node* non_array = generate_non_array_guard(load_object_klass(array), nullptr, &array);
5062 
5063   if (non_array != nullptr) {
5064     PreserveJVMState pjvms(this);
5065     set_control(non_array);
5066     uncommon_trap(Deoptimization::Reason_intrinsic,
5067                   Deoptimization::Action_maybe_recompile);
5068   }
5069 
5070   // If control is dead, only non-array-path is taken.
5071   if (stopped())  return true;
5072 
5073   // The works fine even if the array type is polymorphic.
5074   // It could be a dynamic mix of int[], boolean[], Object[], etc.
5075   Node* result = load_array_length(array);
5076 
5077   C->set_has_split_ifs(true);  // Has chance for split-if optimization
5078   set_result(result);
5079   return true;
5080 }
5081 
5082 //------------------------inline_array_copyOf----------------------------
5083 // public static <T,U> T[] java.util.Arrays.copyOf(     U[] original, int newLength,         Class<? extends T[]> newType);
5084 // public static <T,U> T[] java.util.Arrays.copyOfRange(U[] original, int from,      int to, Class<? extends T[]> newType);
5085 bool LibraryCallKit::inline_array_copyOf(bool is_copyOfRange) {
5086   if (too_many_traps(Deoptimization::Reason_intrinsic))  return false;
5087 
5088   // Get the arguments.
5089   Node* original          = argument(0);
5090   Node* start             = is_copyOfRange? argument(1): intcon(0);
5091   Node* end               = is_copyOfRange? argument(2): argument(1);
5092   Node* array_type_mirror = is_copyOfRange? argument(3): argument(2);
5093 
5094   Node* newcopy = nullptr;
5095 
5096   // Set the original stack and the reexecute bit for the interpreter to reexecute
5097   // the bytecode that invokes Arrays.copyOf if deoptimization happens.
5098   { PreserveReexecuteState preexecs(this);
5099     jvms()->set_should_reexecute(true);
5100 
5101     array_type_mirror = null_check(array_type_mirror);
5102     original          = null_check(original);
5103 
5104     // Check if a null path was taken unconditionally.
5105     if (stopped())  return true;
5106 
5107     Node* orig_length = load_array_length(original);
5108 
5109     Node* klass_node = load_klass_from_mirror(array_type_mirror, false, nullptr, 0);
5110     klass_node = null_check(klass_node);
5111 
5112     RegionNode* bailout = new RegionNode(1);
5113     record_for_igvn(bailout);
5114 
5115     // Despite the generic type of Arrays.copyOf, the mirror might be int, int[], etc.
5116     // Bail out if that is so.
5117     // Inline type array may have object field that would require a
5118     // write barrier. Conservatively, go to slow path.
5119     // TODO 8251971: Optimize for the case when flat src/dst are later found
5120     // to not contain oops (i.e., move this check to the macro expansion phase).
5121     BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
5122     const TypeAryPtr* orig_t = _gvn.type(original)->isa_aryptr();
5123     const TypeKlassPtr* tklass = _gvn.type(klass_node)->is_klassptr();
5124     bool exclude_flat = UseArrayFlattening && bs->array_copy_requires_gc_barriers(true, T_OBJECT, false, false, BarrierSetC2::Parsing) &&
5125                         // Can src array be flat and contain oops?
5126                         (orig_t == nullptr || (!orig_t->is_not_flat() && (!orig_t->is_flat() || orig_t->elem()->inline_klass()->contains_oops()))) &&
5127                         // Can dest array be flat and contain oops?
5128                         tklass->can_be_inline_array() && (!tklass->is_flat() || tklass->is_aryklassptr()->elem()->is_instklassptr()->instance_klass()->as_inline_klass()->contains_oops());
5129     Node* not_objArray = exclude_flat ? generate_non_refArray_guard(klass_node, bailout) : generate_typeArray_guard(klass_node, bailout);
5130 
5131     Node* refined_klass_node = load_default_refined_array_klass(klass_node, /* type_array_guard= */ false);
5132 
5133     if (not_objArray != nullptr) {
5134       // Improve the klass node's type from the new optimistic assumption:
5135       ciKlass* ak = ciArrayKlass::make(env()->Object_klass());
5136       bool not_flat = !UseArrayFlattening;
5137       bool not_null_free = !Arguments::is_valhalla_enabled();
5138       const Type* akls = TypeAryKlassPtr::make(TypePtr::NotNull, ak, Type::Offset(0), Type::trust_interfaces, not_flat, not_null_free, false, false, not_flat, true);
5139       Node* cast = new CastPPNode(control(), refined_klass_node, akls);
5140       refined_klass_node = _gvn.transform(cast);
5141     }
5142 
5143     // Bail out if either start or end is negative.
5144     generate_negative_guard(start, bailout, &start);
5145     generate_negative_guard(end,   bailout, &end);
5146 
5147     Node* length = end;
5148     if (_gvn.type(start) != TypeInt::ZERO) {
5149       length = _gvn.transform(new SubINode(end, start));
5150     }
5151 
5152     // Bail out if length is negative (i.e., if start > end).
5153     // Without this the new_array would throw
5154     // NegativeArraySizeException but IllegalArgumentException is what
5155     // should be thrown
5156     generate_negative_guard(length, bailout, &length);
5157 
5158     // Handle inline type arrays
5159     bool can_validate = !too_many_traps(Deoptimization::Reason_class_check);
5160     if (!stopped()) {
5161       // TODO 8251971
5162       if (!orig_t->is_null_free()) {
5163         // Not statically known to be null free, add a check
5164         generate_fair_guard(null_free_array_test(original), bailout);
5165       }
5166       orig_t = _gvn.type(original)->isa_aryptr();
5167       if (orig_t != nullptr && orig_t->is_flat()) {
5168         // Src is flat, check that dest is flat as well
5169         if (exclude_flat) {
5170           // Dest can't be flat, bail out
5171           bailout->add_req(control());
5172           set_control(top());
5173         } else {
5174           generate_fair_guard(flat_array_test(refined_klass_node, /* flat = */ false), bailout);
5175         }
5176         // TODO 8350865 This is not correct anymore. Write tests and fix logic similar to arraycopy.
5177       } else if (UseArrayFlattening && (orig_t == nullptr || !orig_t->is_not_flat()) &&
5178                  // If dest is flat, src must be flat as well (guaranteed by src <: dest check if validated).
5179                  ((!tklass->is_flat() && tklass->can_be_inline_array()) || !can_validate)) {
5180         // Src might be flat and dest might not be flat. Go to the slow path if src is flat.
5181         // TODO 8251971: Optimize for the case when src/dest are later found to be both flat.
5182         generate_fair_guard(flat_array_test(load_object_klass(original)), bailout);
5183         if (orig_t != nullptr) {
5184           orig_t = orig_t->cast_to_not_flat();
5185           original = _gvn.transform(new CheckCastPPNode(control(), original, orig_t));
5186         }
5187       }
5188       if (!can_validate) {
5189         // No validation. The subtype check emitted at macro expansion time will not go to the slow
5190         // path but call checkcast_arraycopy which can not handle flat/null-free inline type arrays.
5191         // TODO 8251971: Optimize for the case when src/dest are later found to be both flat/null-free.
5192         generate_fair_guard(flat_array_test(refined_klass_node), bailout);
5193         generate_fair_guard(null_free_array_test(original), bailout);
5194       }
5195     }
5196 
5197     // Bail out if start is larger than the original length
5198     Node* orig_tail = _gvn.transform(new SubINode(orig_length, start));
5199     generate_negative_guard(orig_tail, bailout, &orig_tail);
5200 
5201     if (bailout->req() > 1) {
5202       PreserveJVMState pjvms(this);
5203       set_control(_gvn.transform(bailout));
5204       uncommon_trap(Deoptimization::Reason_intrinsic,
5205                     Deoptimization::Action_maybe_recompile);
5206     }
5207 
5208     if (!stopped()) {
5209       // How many elements will we copy from the original?
5210       // The answer is MinI(orig_tail, length).
5211       Node* moved = _gvn.transform(new MinINode(orig_tail, length));
5212 
5213       // Generate a direct call to the right arraycopy function(s).
5214       // We know the copy is disjoint but we might not know if the
5215       // oop stores need checking.
5216       // Extreme case:  Arrays.copyOf((Integer[])x, 10, String[].class).
5217       // This will fail a store-check if x contains any non-nulls.
5218 
5219       // ArrayCopyNode:Ideal may transform the ArrayCopyNode to
5220       // loads/stores but it is legal only if we're sure the
5221       // Arrays.copyOf would succeed. So we need all input arguments
5222       // to the copyOf to be validated, including that the copy to the
5223       // new array won't trigger an ArrayStoreException. That subtype
5224       // check can be optimized if we know something on the type of
5225       // the input array from type speculation.
5226       if (_gvn.type(klass_node)->singleton()) {
5227         const TypeKlassPtr* subk = _gvn.type(load_object_klass(original))->is_klassptr();
5228         const TypeKlassPtr* superk = _gvn.type(klass_node)->is_klassptr();
5229 
5230         int test = C->static_subtype_check(superk, subk);
5231         if (test != Compile::SSC_always_true && test != Compile::SSC_always_false) {
5232           const TypeOopPtr* t_original = _gvn.type(original)->is_oopptr();
5233           if (t_original->speculative_type() != nullptr) {
5234             original = maybe_cast_profiled_obj(original, t_original->speculative_type(), true);
5235           }
5236         }
5237       }
5238 
5239       bool validated = false;
5240       // Reason_class_check rather than Reason_intrinsic because we
5241       // want to intrinsify even if this traps.
5242       if (can_validate) {
5243         Node* not_subtype_ctrl = gen_subtype_check(original, klass_node);
5244 
5245         if (not_subtype_ctrl != top()) {
5246           PreserveJVMState pjvms(this);
5247           set_control(not_subtype_ctrl);
5248           uncommon_trap(Deoptimization::Reason_class_check,
5249                         Deoptimization::Action_make_not_entrant);
5250           assert(stopped(), "Should be stopped");
5251         }
5252         validated = true;
5253       }
5254 
5255       if (!stopped()) {
5256         newcopy = new_array(refined_klass_node, length, 0);  // no arguments to push
5257 
5258         ArrayCopyNode* ac = ArrayCopyNode::make(this, true, original, start, newcopy, intcon(0), moved, true, true,
5259                                                 load_object_klass(original), klass_node);
5260         if (!is_copyOfRange) {
5261           ac->set_copyof(validated);
5262         } else {
5263           ac->set_copyofrange(validated);
5264         }
5265         Node* n = _gvn.transform(ac);
5266         if (n == ac) {
5267           ac->connect_outputs(this);
5268         } else {
5269           assert(validated, "shouldn't transform if all arguments not validated");
5270           set_all_memory(n);
5271         }
5272       }
5273     }
5274   } // original reexecute is set back here
5275 
5276   C->set_has_split_ifs(true); // Has chance for split-if optimization
5277   if (!stopped()) {
5278     set_result(newcopy);
5279   }
5280   return true;
5281 }
5282 
5283 
5284 //----------------------generate_virtual_guard---------------------------
5285 // Helper for hashCode and clone.  Peeks inside the vtable to avoid a call.
5286 Node* LibraryCallKit::generate_virtual_guard(Node* obj_klass,
5287                                              RegionNode* slow_region) {
5288   ciMethod* method = callee();
5289   int vtable_index = method->vtable_index();
5290   assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index,
5291          "bad index %d", vtable_index);
5292   // Get the Method* out of the appropriate vtable entry.
5293   int entry_offset  = in_bytes(Klass::vtable_start_offset()) +
5294                      vtable_index*vtableEntry::size_in_bytes() +
5295                      in_bytes(vtableEntry::method_offset());
5296   Node* entry_addr  = basic_plus_adr(top(), obj_klass, entry_offset);
5297   Node* target_call = make_load(nullptr, entry_addr, TypePtr::NOTNULL, T_ADDRESS, MemNode::unordered);
5298 
5299   // Compare the target method with the expected method (e.g., Object.hashCode).
5300   const TypePtr* native_call_addr = TypeMetadataPtr::make(method);
5301 
5302   Node* native_call = makecon(native_call_addr);
5303   Node* chk_native  = _gvn.transform(new CmpPNode(target_call, native_call));
5304   Node* test_native = _gvn.transform(new BoolNode(chk_native, BoolTest::ne));
5305 
5306   return generate_slow_guard(test_native, slow_region);
5307 }
5308 
5309 //-----------------------generate_method_call----------------------------
5310 // Use generate_method_call to make a slow-call to the real
5311 // method if the fast path fails.  An alternative would be to
5312 // use a stub like OptoRuntime::slow_arraycopy_Java.
5313 // This only works for expanding the current library call,
5314 // not another intrinsic.  (E.g., don't use this for making an
5315 // arraycopy call inside of the copyOf intrinsic.)
5316 CallJavaNode*
5317 LibraryCallKit::generate_method_call(vmIntrinsicID method_id, bool is_virtual, bool is_static, bool res_not_null) {
5318   // When compiling the intrinsic method itself, do not use this technique.
5319   guarantee(callee() != C->method(), "cannot make slow-call to self");
5320 
5321   ciMethod* method = callee();
5322   // ensure the JVMS we have will be correct for this call
5323   guarantee(method_id == method->intrinsic_id(), "must match");
5324 
5325   const TypeFunc* tf = TypeFunc::make(method);
5326   if (res_not_null) {
5327     assert(tf->return_type() == T_OBJECT, "");
5328     const TypeTuple* range = tf->range_cc();
5329     const Type** fields = TypeTuple::fields(range->cnt());
5330     fields[TypeFunc::Parms] = range->field_at(TypeFunc::Parms)->filter_speculative(TypePtr::NOTNULL);
5331     const TypeTuple* new_range = TypeTuple::make(range->cnt(), fields);
5332     tf = TypeFunc::make(tf->domain_cc(), new_range);
5333   }
5334   CallJavaNode* slow_call;
5335   if (is_static) {
5336     assert(!is_virtual, "");
5337     slow_call = new CallStaticJavaNode(C, tf,
5338                            SharedRuntime::get_resolve_static_call_stub(), method);
5339   } else if (is_virtual) {
5340     assert(!gvn().type(argument(0))->maybe_null(), "should not be null");
5341     int vtable_index = Method::invalid_vtable_index;
5342     if (UseInlineCaches) {
5343       // Suppress the vtable call
5344     } else {
5345       // hashCode and clone are not a miranda methods,
5346       // so the vtable index is fixed.
5347       // No need to use the linkResolver to get it.
5348        vtable_index = method->vtable_index();
5349        assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index,
5350               "bad index %d", vtable_index);
5351     }
5352     slow_call = new CallDynamicJavaNode(tf,
5353                           SharedRuntime::get_resolve_virtual_call_stub(),
5354                           method, vtable_index);
5355   } else {  // neither virtual nor static:  opt_virtual
5356     assert(!gvn().type(argument(0))->maybe_null(), "should not be null");
5357     slow_call = new CallStaticJavaNode(C, tf,
5358                                 SharedRuntime::get_resolve_opt_virtual_call_stub(), method);
5359     slow_call->set_optimized_virtual(true);
5360   }
5361   if (CallGenerator::is_inlined_method_handle_intrinsic(this->method(), bci(), callee())) {
5362     // To be able to issue a direct call (optimized virtual or virtual)
5363     // and skip a call to MH.linkTo*/invokeBasic adapter, additional information
5364     // about the method being invoked should be attached to the call site to
5365     // make resolution logic work (see SharedRuntime::resolve_{virtual,opt_virtual}_call_C).
5366     slow_call->set_override_symbolic_info(true);
5367   }
5368   set_arguments_for_java_call(slow_call);
5369   set_edges_for_java_call(slow_call);
5370   return slow_call;
5371 }
5372 
5373 
5374 /**
5375  * Build special case code for calls to hashCode on an object. This call may
5376  * be virtual (invokevirtual) or bound (invokespecial). For each case we generate
5377  * slightly different code.
5378  */
5379 bool LibraryCallKit::inline_native_hashcode(bool is_virtual, bool is_static) {
5380   assert(is_static == callee()->is_static(), "correct intrinsic selection");
5381   assert(!(is_virtual && is_static), "either virtual, special, or static");
5382 
5383   enum { _slow_path = 1, _fast_path, _null_path, PATH_LIMIT };
5384 
5385   RegionNode* result_reg = new RegionNode(PATH_LIMIT);
5386   PhiNode*    result_val = new PhiNode(result_reg, TypeInt::INT);
5387   PhiNode*    result_io  = new PhiNode(result_reg, Type::ABIO);
5388   PhiNode*    result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
5389   Node* obj = argument(0);
5390 
5391   // Don't intrinsify hashcode on inline types for now.
5392   // The "is locked" runtime check also subsumes the inline type check (as inline types cannot be locked) and goes to the slow path.
5393   if (gvn().type(obj)->is_inlinetypeptr()) {
5394     return false;
5395   }
5396 
5397   if (!is_static) {
5398     // Check for hashing null object
5399     obj = null_check_receiver();
5400     if (stopped())  return true;        // unconditionally null
5401     result_reg->init_req(_null_path, top());
5402     result_val->init_req(_null_path, top());
5403   } else {
5404     // Do a null check, and return zero if null.
5405     // System.identityHashCode(null) == 0
5406     Node* null_ctl = top();
5407     obj = null_check_oop(obj, &null_ctl);
5408     result_reg->init_req(_null_path, null_ctl);
5409     result_val->init_req(_null_path, _gvn.intcon(0));
5410   }
5411 
5412   // Unconditionally null?  Then return right away.
5413   if (stopped()) {
5414     set_control( result_reg->in(_null_path));
5415     if (!stopped())
5416       set_result(result_val->in(_null_path));
5417     return true;
5418   }
5419 
5420   // We only go to the fast case code if we pass a number of guards.  The
5421   // paths which do not pass are accumulated in the slow_region.
5422   RegionNode* slow_region = new RegionNode(1);
5423   record_for_igvn(slow_region);
5424 
5425   // If this is a virtual call, we generate a funny guard.  We pull out
5426   // the vtable entry corresponding to hashCode() from the target object.
5427   // If the target method which we are calling happens to be the native
5428   // Object hashCode() method, we pass the guard.  We do not need this
5429   // guard for non-virtual calls -- the caller is known to be the native
5430   // Object hashCode().
5431   if (is_virtual) {
5432     // After null check, get the object's klass.
5433     Node* obj_klass = load_object_klass(obj);
5434     generate_virtual_guard(obj_klass, slow_region);
5435   }
5436 
5437   // Get the header out of the object, use LoadMarkNode when available
5438   Node* header_addr = basic_plus_adr(obj, oopDesc::mark_offset_in_bytes());
5439   // The control of the load must be null. Otherwise, the load can move before
5440   // the null check after castPP removal.
5441   Node* no_ctrl = nullptr;
5442   Node* header = make_load(no_ctrl, header_addr, TypeX_X, TypeX_X->basic_type(), MemNode::unordered);
5443 
5444   if (!UseObjectMonitorTable) {
5445     // Test the header to see if it is safe to read w.r.t. locking.
5446     // We cannot use the inline type mask as this may check bits that are overriden
5447     // by an object monitor's pointer when inflating locking.
5448     Node *lock_mask      = _gvn.MakeConX(markWord::lock_mask_in_place);
5449     Node *lmasked_header = _gvn.transform(new AndXNode(header, lock_mask));
5450     Node *monitor_val   = _gvn.MakeConX(markWord::monitor_value);
5451     Node *chk_monitor   = _gvn.transform(new CmpXNode(lmasked_header, monitor_val));
5452     Node *test_monitor  = _gvn.transform(new BoolNode(chk_monitor, BoolTest::eq));
5453 
5454     generate_slow_guard(test_monitor, slow_region);
5455   }
5456 
5457   // Get the hash value and check to see that it has been properly assigned.
5458   // We depend on hash_mask being at most 32 bits and avoid the use of
5459   // hash_mask_in_place because it could be larger than 32 bits in a 64-bit
5460   // vm: see markWord.hpp.
5461   Node *hash_mask      = _gvn.intcon(markWord::hash_mask);
5462   Node *hash_shift     = _gvn.intcon(markWord::hash_shift);
5463   Node *hshifted_header= _gvn.transform(new URShiftXNode(header, hash_shift));
5464   // This hack lets the hash bits live anywhere in the mark object now, as long
5465   // as the shift drops the relevant bits into the low 32 bits.  Note that
5466   // Java spec says that HashCode is an int so there's no point in capturing
5467   // an 'X'-sized hashcode (32 in 32-bit build or 64 in 64-bit build).
5468   hshifted_header      = ConvX2I(hshifted_header);
5469   Node *hash_val       = _gvn.transform(new AndINode(hshifted_header, hash_mask));
5470 
5471   Node *no_hash_val    = _gvn.intcon(markWord::no_hash);
5472   Node *chk_assigned   = _gvn.transform(new CmpINode( hash_val, no_hash_val));
5473   Node *test_assigned  = _gvn.transform(new BoolNode( chk_assigned, BoolTest::eq));
5474 
5475   generate_slow_guard(test_assigned, slow_region);
5476 
5477   Node* init_mem = reset_memory();
5478   // fill in the rest of the null path:
5479   result_io ->init_req(_null_path, i_o());
5480   result_mem->init_req(_null_path, init_mem);
5481 
5482   result_val->init_req(_fast_path, hash_val);
5483   result_reg->init_req(_fast_path, control());
5484   result_io ->init_req(_fast_path, i_o());
5485   result_mem->init_req(_fast_path, init_mem);
5486 
5487   // Generate code for the slow case.  We make a call to hashCode().
5488   set_control(_gvn.transform(slow_region));
5489   if (!stopped()) {
5490     // No need for PreserveJVMState, because we're using up the present state.
5491     set_all_memory(init_mem);
5492     vmIntrinsics::ID hashCode_id = is_static ? vmIntrinsics::_identityHashCode : vmIntrinsics::_hashCode;
5493     CallJavaNode* slow_call = generate_method_call(hashCode_id, is_virtual, is_static, false);
5494     Node* slow_result = set_results_for_java_call(slow_call);
5495     // this->control() comes from set_results_for_java_call
5496     result_reg->init_req(_slow_path, control());
5497     result_val->init_req(_slow_path, slow_result);
5498     result_io  ->set_req(_slow_path, i_o());
5499     result_mem ->set_req(_slow_path, reset_memory());
5500   }
5501 
5502   // Return the combined state.
5503   set_i_o(        _gvn.transform(result_io)  );
5504   set_all_memory( _gvn.transform(result_mem));
5505 
5506   set_result(result_reg, result_val);
5507   return true;
5508 }
5509 
5510 //---------------------------inline_native_getClass----------------------------
5511 // public final native Class<?> java.lang.Object.getClass();
5512 //
5513 // Build special case code for calls to getClass on an object.
5514 bool LibraryCallKit::inline_native_getClass() {
5515   Node* obj = argument(0);
5516   if (obj->is_InlineType()) {
5517     const Type* t = _gvn.type(obj);
5518     if (t->maybe_null()) {
5519       null_check(obj);
5520     }
5521     set_result(makecon(TypeInstPtr::make(t->inline_klass()->java_mirror())));
5522     return true;
5523   }
5524   obj = null_check_receiver();
5525   if (stopped())  return true;
5526   set_result(load_mirror_from_klass(load_object_klass(obj)));
5527   return true;
5528 }
5529 
5530 //-----------------inline_native_Reflection_getCallerClass---------------------
5531 // public static native Class<?> sun.reflect.Reflection.getCallerClass();
5532 //
5533 // In the presence of deep enough inlining, getCallerClass() becomes a no-op.
5534 //
5535 // NOTE: This code must perform the same logic as JVM_GetCallerClass
5536 // in that it must skip particular security frames and checks for
5537 // caller sensitive methods.
5538 bool LibraryCallKit::inline_native_Reflection_getCallerClass() {
5539 #ifndef PRODUCT
5540   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5541     tty->print_cr("Attempting to inline sun.reflect.Reflection.getCallerClass");
5542   }
5543 #endif
5544 
5545   if (!jvms()->has_method()) {
5546 #ifndef PRODUCT
5547     if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5548       tty->print_cr("  Bailing out because intrinsic was inlined at top level");
5549     }
5550 #endif
5551     return false;
5552   }
5553 
5554   // Walk back up the JVM state to find the caller at the required
5555   // depth.
5556   JVMState* caller_jvms = jvms();
5557 
5558   // Cf. JVM_GetCallerClass
5559   // NOTE: Start the loop at depth 1 because the current JVM state does
5560   // not include the Reflection.getCallerClass() frame.
5561   for (int n = 1; caller_jvms != nullptr; caller_jvms = caller_jvms->caller(), n++) {
5562     ciMethod* m = caller_jvms->method();
5563     switch (n) {
5564     case 0:
5565       fatal("current JVM state does not include the Reflection.getCallerClass frame");
5566       break;
5567     case 1:
5568       // Frame 0 and 1 must be caller sensitive (see JVM_GetCallerClass).
5569       if (!m->caller_sensitive()) {
5570 #ifndef PRODUCT
5571         if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5572           tty->print_cr("  Bailing out: CallerSensitive annotation expected at frame %d", n);
5573         }
5574 #endif
5575         return false;  // bail-out; let JVM_GetCallerClass do the work
5576       }
5577       break;
5578     default:
5579       if (!m->is_ignored_by_security_stack_walk()) {
5580         // We have reached the desired frame; return the holder class.
5581         // Acquire method holder as java.lang.Class and push as constant.
5582         ciInstanceKlass* caller_klass = caller_jvms->method()->holder();
5583         ciInstance* caller_mirror = caller_klass->java_mirror();
5584         set_result(makecon(TypeInstPtr::make(caller_mirror)));
5585 
5586 #ifndef PRODUCT
5587         if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5588           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());
5589           tty->print_cr("  JVM state at this point:");
5590           for (int i = jvms()->depth(), n = 1; i >= 1; i--, n++) {
5591             ciMethod* m = jvms()->of_depth(i)->method();
5592             tty->print_cr("   %d) %s.%s", n, m->holder()->name()->as_utf8(), m->name()->as_utf8());
5593           }
5594         }
5595 #endif
5596         return true;
5597       }
5598       break;
5599     }
5600   }
5601 
5602 #ifndef PRODUCT
5603   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5604     tty->print_cr("  Bailing out because caller depth exceeded inlining depth = %d", jvms()->depth());
5605     tty->print_cr("  JVM state at this point:");
5606     for (int i = jvms()->depth(), n = 1; i >= 1; i--, n++) {
5607       ciMethod* m = jvms()->of_depth(i)->method();
5608       tty->print_cr("   %d) %s.%s", n, m->holder()->name()->as_utf8(), m->name()->as_utf8());
5609     }
5610   }
5611 #endif
5612 
5613   return false;  // bail-out; let JVM_GetCallerClass do the work
5614 }
5615 
5616 bool LibraryCallKit::inline_fp_conversions(vmIntrinsics::ID id) {
5617   Node* arg = argument(0);
5618   Node* result = nullptr;
5619 
5620   switch (id) {
5621   case vmIntrinsics::_floatToRawIntBits:    result = new MoveF2INode(arg);  break;
5622   case vmIntrinsics::_intBitsToFloat:       result = new MoveI2FNode(arg);  break;
5623   case vmIntrinsics::_doubleToRawLongBits:  result = new MoveD2LNode(arg);  break;
5624   case vmIntrinsics::_longBitsToDouble:     result = new MoveL2DNode(arg);  break;
5625   case vmIntrinsics::_floatToFloat16:       result = new ConvF2HFNode(arg); break;
5626   case vmIntrinsics::_float16ToFloat:       result = new ConvHF2FNode(arg); break;
5627 
5628   case vmIntrinsics::_doubleToLongBits: {
5629     // two paths (plus control) merge in a wood
5630     RegionNode *r = new RegionNode(3);
5631     Node *phi = new PhiNode(r, TypeLong::LONG);
5632 
5633     Node *cmpisnan = _gvn.transform(new CmpDNode(arg, arg));
5634     // Build the boolean node
5635     Node *bolisnan = _gvn.transform(new BoolNode(cmpisnan, BoolTest::ne));
5636 
5637     // Branch either way.
5638     // NaN case is less traveled, which makes all the difference.
5639     IfNode *ifisnan = create_and_xform_if(control(), bolisnan, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
5640     Node *opt_isnan = _gvn.transform(ifisnan);
5641     assert( opt_isnan->is_If(), "Expect an IfNode");
5642     IfNode *opt_ifisnan = (IfNode*)opt_isnan;
5643     Node *iftrue = _gvn.transform(new IfTrueNode(opt_ifisnan));
5644 
5645     set_control(iftrue);
5646 
5647     static const jlong nan_bits = CONST64(0x7ff8000000000000);
5648     Node *slow_result = longcon(nan_bits); // return NaN
5649     phi->init_req(1, _gvn.transform( slow_result ));
5650     r->init_req(1, iftrue);
5651 
5652     // Else fall through
5653     Node *iffalse = _gvn.transform(new IfFalseNode(opt_ifisnan));
5654     set_control(iffalse);
5655 
5656     phi->init_req(2, _gvn.transform(new MoveD2LNode(arg)));
5657     r->init_req(2, iffalse);
5658 
5659     // Post merge
5660     set_control(_gvn.transform(r));
5661     record_for_igvn(r);
5662 
5663     C->set_has_split_ifs(true); // Has chance for split-if optimization
5664     result = phi;
5665     assert(result->bottom_type()->isa_long(), "must be");
5666     break;
5667   }
5668 
5669   case vmIntrinsics::_floatToIntBits: {
5670     // two paths (plus control) merge in a wood
5671     RegionNode *r = new RegionNode(3);
5672     Node *phi = new PhiNode(r, TypeInt::INT);
5673 
5674     Node *cmpisnan = _gvn.transform(new CmpFNode(arg, arg));
5675     // Build the boolean node
5676     Node *bolisnan = _gvn.transform(new BoolNode(cmpisnan, BoolTest::ne));
5677 
5678     // Branch either way.
5679     // NaN case is less traveled, which makes all the difference.
5680     IfNode *ifisnan = create_and_xform_if(control(), bolisnan, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
5681     Node *opt_isnan = _gvn.transform(ifisnan);
5682     assert( opt_isnan->is_If(), "Expect an IfNode");
5683     IfNode *opt_ifisnan = (IfNode*)opt_isnan;
5684     Node *iftrue = _gvn.transform(new IfTrueNode(opt_ifisnan));
5685 
5686     set_control(iftrue);
5687 
5688     static const jint nan_bits = 0x7fc00000;
5689     Node *slow_result = makecon(TypeInt::make(nan_bits)); // return NaN
5690     phi->init_req(1, _gvn.transform( slow_result ));
5691     r->init_req(1, iftrue);
5692 
5693     // Else fall through
5694     Node *iffalse = _gvn.transform(new IfFalseNode(opt_ifisnan));
5695     set_control(iffalse);
5696 
5697     phi->init_req(2, _gvn.transform(new MoveF2INode(arg)));
5698     r->init_req(2, iffalse);
5699 
5700     // Post merge
5701     set_control(_gvn.transform(r));
5702     record_for_igvn(r);
5703 
5704     C->set_has_split_ifs(true); // Has chance for split-if optimization
5705     result = phi;
5706     assert(result->bottom_type()->isa_int(), "must be");
5707     break;
5708   }
5709 
5710   default:
5711     fatal_unexpected_iid(id);
5712     break;
5713   }
5714   set_result(_gvn.transform(result));
5715   return true;
5716 }
5717 
5718 bool LibraryCallKit::inline_fp_range_check(vmIntrinsics::ID id) {
5719   Node* arg = argument(0);
5720   Node* result = nullptr;
5721 
5722   switch (id) {
5723   case vmIntrinsics::_floatIsInfinite:
5724     result = new IsInfiniteFNode(arg);
5725     break;
5726   case vmIntrinsics::_floatIsFinite:
5727     result = new IsFiniteFNode(arg);
5728     break;
5729   case vmIntrinsics::_doubleIsInfinite:
5730     result = new IsInfiniteDNode(arg);
5731     break;
5732   case vmIntrinsics::_doubleIsFinite:
5733     result = new IsFiniteDNode(arg);
5734     break;
5735   default:
5736     fatal_unexpected_iid(id);
5737     break;
5738   }
5739   set_result(_gvn.transform(result));
5740   return true;
5741 }
5742 
5743 //----------------------inline_unsafe_copyMemory-------------------------
5744 // public native void Unsafe.copyMemory0(Object srcBase, long srcOffset, Object destBase, long destOffset, long bytes);
5745 
5746 static bool has_wide_mem(PhaseGVN& gvn, Node* addr, Node* base) {
5747   const TypeAryPtr* addr_t = gvn.type(addr)->isa_aryptr();
5748   const Type*       base_t = gvn.type(base);
5749 
5750   bool in_native = (base_t == TypePtr::NULL_PTR);
5751   bool in_heap   = !TypePtr::NULL_PTR->higher_equal(base_t);
5752   bool is_mixed  = !in_heap && !in_native;
5753 
5754   if (is_mixed) {
5755     return true; // mixed accesses can touch both on-heap and off-heap memory
5756   }
5757   if (in_heap) {
5758     bool is_prim_array = (addr_t != nullptr) && (addr_t->elem() != Type::BOTTOM);
5759     if (!is_prim_array) {
5760       // Though Unsafe.copyMemory() ensures at runtime for on-heap accesses that base is a primitive array,
5761       // there's not enough type information available to determine proper memory slice for it.
5762       return true;
5763     }
5764   }
5765   return false;
5766 }
5767 
5768 bool LibraryCallKit::inline_unsafe_copyMemory() {
5769   if (callee()->is_static())  return false;  // caller must have the capability!
5770   null_check_receiver();  // null-check receiver
5771   if (stopped())  return true;
5772 
5773   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
5774 
5775   Node* src_base =         argument(1);  // type: oop
5776   Node* src_off  = ConvL2X(argument(2)); // type: long
5777   Node* dst_base =         argument(4);  // type: oop
5778   Node* dst_off  = ConvL2X(argument(5)); // type: long
5779   Node* size     = ConvL2X(argument(7)); // type: long
5780 
5781   assert(Unsafe_field_offset_to_byte_offset(11) == 11,
5782          "fieldOffset must be byte-scaled");
5783 
5784   Node* src_addr = make_unsafe_address(src_base, src_off);
5785   Node* dst_addr = make_unsafe_address(dst_base, dst_off);
5786 
5787   Node* thread = _gvn.transform(new ThreadLocalNode());
5788   Node* doing_unsafe_access_addr = basic_plus_adr(top(), thread, in_bytes(JavaThread::doing_unsafe_access_offset()));
5789   BasicType doing_unsafe_access_bt = T_BYTE;
5790   assert((sizeof(bool) * CHAR_BIT) == 8, "not implemented");
5791 
5792   // update volatile field
5793   store_to_memory(control(), doing_unsafe_access_addr, intcon(1), doing_unsafe_access_bt, MemNode::unordered);
5794 
5795   int flags = RC_LEAF | RC_NO_FP;
5796 
5797   const TypePtr* dst_type = TypePtr::BOTTOM;
5798 
5799   // Adjust memory effects of the runtime call based on input values.
5800   if (!has_wide_mem(_gvn, src_addr, src_base) &&
5801       !has_wide_mem(_gvn, dst_addr, dst_base)) {
5802     dst_type = _gvn.type(dst_addr)->is_ptr(); // narrow out memory
5803 
5804     const TypePtr* src_type = _gvn.type(src_addr)->is_ptr();
5805     if (C->get_alias_index(src_type) == C->get_alias_index(dst_type)) {
5806       flags |= RC_NARROW_MEM; // narrow in memory
5807     }
5808   }
5809 
5810   // Call it.  Note that the length argument is not scaled.
5811   make_runtime_call(flags,
5812                     OptoRuntime::fast_arraycopy_Type(),
5813                     StubRoutines::unsafe_arraycopy(),
5814                     "unsafe_arraycopy",
5815                     dst_type,
5816                     src_addr, dst_addr, size XTOP);
5817 
5818   store_to_memory(control(), doing_unsafe_access_addr, intcon(0), doing_unsafe_access_bt, MemNode::unordered);
5819 
5820   return true;
5821 }
5822 
5823 // unsafe_setmemory(void *base, ulong offset, size_t length, char fill_value);
5824 // Fill 'length' bytes starting from 'base[offset]' with 'fill_value'
5825 bool LibraryCallKit::inline_unsafe_setMemory() {
5826   if (callee()->is_static())  return false;  // caller must have the capability!
5827   null_check_receiver();  // null-check receiver
5828   if (stopped())  return true;
5829 
5830   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
5831 
5832   Node* dst_base =         argument(1);  // type: oop
5833   Node* dst_off  = ConvL2X(argument(2)); // type: long
5834   Node* size     = ConvL2X(argument(4)); // type: long
5835   Node* byte     =         argument(6);  // type: byte
5836 
5837   assert(Unsafe_field_offset_to_byte_offset(11) == 11,
5838          "fieldOffset must be byte-scaled");
5839 
5840   Node* dst_addr = make_unsafe_address(dst_base, dst_off);
5841 
5842   Node* thread = _gvn.transform(new ThreadLocalNode());
5843   Node* doing_unsafe_access_addr = basic_plus_adr(top(), thread, in_bytes(JavaThread::doing_unsafe_access_offset()));
5844   BasicType doing_unsafe_access_bt = T_BYTE;
5845   assert((sizeof(bool) * CHAR_BIT) == 8, "not implemented");
5846 
5847   // update volatile field
5848   store_to_memory(control(), doing_unsafe_access_addr, intcon(1), doing_unsafe_access_bt, MemNode::unordered);
5849 
5850   int flags = RC_LEAF | RC_NO_FP;
5851 
5852   const TypePtr* dst_type = TypePtr::BOTTOM;
5853 
5854   // Adjust memory effects of the runtime call based on input values.
5855   if (!has_wide_mem(_gvn, dst_addr, dst_base)) {
5856     dst_type = _gvn.type(dst_addr)->is_ptr(); // narrow out memory
5857 
5858     flags |= RC_NARROW_MEM; // narrow in memory
5859   }
5860 
5861   // Call it.  Note that the length argument is not scaled.
5862   make_runtime_call(flags,
5863                     OptoRuntime::unsafe_setmemory_Type(),
5864                     StubRoutines::unsafe_setmemory(),
5865                     "unsafe_setmemory",
5866                     dst_type,
5867                     dst_addr, size XTOP, byte);
5868 
5869   store_to_memory(control(), doing_unsafe_access_addr, intcon(0), doing_unsafe_access_bt, MemNode::unordered);
5870 
5871   return true;
5872 }
5873 
5874 #undef XTOP
5875 
5876 //------------------------clone_coping-----------------------------------
5877 // Helper function for inline_native_clone.
5878 void LibraryCallKit::copy_to_clone(Node* obj, Node* alloc_obj, Node* obj_size, bool is_array) {
5879   assert(obj_size != nullptr, "");
5880   Node* raw_obj = alloc_obj->in(1);
5881   assert(alloc_obj->is_CheckCastPP() && raw_obj->is_Proj() && raw_obj->in(0)->is_Allocate(), "");
5882 
5883   AllocateNode* alloc = nullptr;
5884   if (ReduceBulkZeroing &&
5885       // If we are implementing an array clone without knowing its source type
5886       // (can happen when compiling the array-guarded branch of a reflective
5887       // Object.clone() invocation), initialize the array within the allocation.
5888       // This is needed because some GCs (e.g. ZGC) might fall back in this case
5889       // to a runtime clone call that assumes fully initialized source arrays.
5890       (!is_array || obj->get_ptr_type()->isa_aryptr() != nullptr)) {
5891     // We will be completely responsible for initializing this object -
5892     // mark Initialize node as complete.
5893     alloc = AllocateNode::Ideal_allocation(alloc_obj);
5894     // The object was just allocated - there should be no any stores!
5895     guarantee(alloc != nullptr && alloc->maybe_set_complete(&_gvn), "");
5896     // Mark as complete_with_arraycopy so that on AllocateNode
5897     // expansion, we know this AllocateNode is initialized by an array
5898     // copy and a StoreStore barrier exists after the array copy.
5899     alloc->initialization()->set_complete_with_arraycopy();
5900   }
5901 
5902   Node* size = _gvn.transform(obj_size);
5903   access_clone(obj, alloc_obj, size, is_array);
5904 
5905   // Do not let reads from the cloned object float above the arraycopy.
5906   if (alloc != nullptr) {
5907     // Do not let stores that initialize this object be reordered with
5908     // a subsequent store that would make this object accessible by
5909     // other threads.
5910     // Record what AllocateNode this StoreStore protects so that
5911     // escape analysis can go from the MemBarStoreStoreNode to the
5912     // AllocateNode and eliminate the MemBarStoreStoreNode if possible
5913     // based on the escape status of the AllocateNode.
5914     insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
5915   } else {
5916     insert_mem_bar(Op_MemBarCPUOrder);
5917   }
5918 }
5919 
5920 //------------------------inline_native_clone----------------------------
5921 // protected native Object java.lang.Object.clone();
5922 //
5923 // Here are the simple edge cases:
5924 //  null receiver => normal trap
5925 //  virtual and clone was overridden => slow path to out-of-line clone
5926 //  not cloneable or finalizer => slow path to out-of-line Object.clone
5927 //
5928 // The general case has two steps, allocation and copying.
5929 // Allocation has two cases, and uses GraphKit::new_instance or new_array.
5930 //
5931 // Copying also has two cases, oop arrays and everything else.
5932 // Oop arrays use arrayof_oop_arraycopy (same as System.arraycopy).
5933 // Everything else uses the tight inline loop supplied by CopyArrayNode.
5934 //
5935 // These steps fold up nicely if and when the cloned object's klass
5936 // can be sharply typed as an object array, a type array, or an instance.
5937 //
5938 bool LibraryCallKit::inline_native_clone(bool is_virtual) {
5939   PhiNode* result_val;
5940 
5941   // Set the reexecute bit for the interpreter to reexecute
5942   // the bytecode that invokes Object.clone if deoptimization happens.
5943   { PreserveReexecuteState preexecs(this);
5944     jvms()->set_should_reexecute(true);
5945 
5946     Node* obj = argument(0);
5947     obj = null_check_receiver();
5948     if (stopped())  return true;
5949 
5950     const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
5951     if (obj_type->is_inlinetypeptr()) {
5952       // If the object to clone is an inline type, we can simply return it (i.e. a nop) since inline types have
5953       // no identity.
5954       set_result(obj);
5955       return true;
5956     }
5957 
5958     // If we are going to clone an instance, we need its exact type to
5959     // know the number and types of fields to convert the clone to
5960     // loads/stores. Maybe a speculative type can help us.
5961     if (!obj_type->klass_is_exact() &&
5962         obj_type->speculative_type() != nullptr &&
5963         obj_type->speculative_type()->is_instance_klass() &&
5964         !obj_type->speculative_type()->is_inlinetype()) {
5965       ciInstanceKlass* spec_ik = obj_type->speculative_type()->as_instance_klass();
5966       if (spec_ik->nof_nonstatic_fields() <= ArrayCopyLoadStoreMaxElem &&
5967           !spec_ik->has_injected_fields()) {
5968         if (!obj_type->isa_instptr() ||
5969             obj_type->is_instptr()->instance_klass()->has_subklass()) {
5970           obj = maybe_cast_profiled_obj(obj, obj_type->speculative_type(), false);
5971         }
5972       }
5973     }
5974 
5975     // Conservatively insert a memory barrier on all memory slices.
5976     // Do not let writes into the original float below the clone.
5977     insert_mem_bar(Op_MemBarCPUOrder);
5978 
5979     // paths into result_reg:
5980     enum {
5981       _slow_path = 1,     // out-of-line call to clone method (virtual or not)
5982       _objArray_path,     // plain array allocation, plus arrayof_oop_arraycopy
5983       _array_path,        // plain array allocation, plus arrayof_long_arraycopy
5984       _instance_path,     // plain instance allocation, plus arrayof_long_arraycopy
5985       PATH_LIMIT
5986     };
5987     RegionNode* result_reg = new RegionNode(PATH_LIMIT);
5988     result_val             = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
5989     PhiNode*    result_i_o = new PhiNode(result_reg, Type::ABIO);
5990     PhiNode*    result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
5991     record_for_igvn(result_reg);
5992 
5993     Node* obj_klass = load_object_klass(obj);
5994     // We only go to the fast case code if we pass a number of guards.
5995     // The paths which do not pass are accumulated in the slow_region.
5996     RegionNode* slow_region = new RegionNode(1);
5997     record_for_igvn(slow_region);
5998 
5999     Node* array_obj = obj;
6000     Node* array_ctl = generate_array_guard(obj_klass, (RegionNode*)nullptr, &array_obj);
6001     if (array_ctl != nullptr) {
6002       // It's an array.
6003       PreserveJVMState pjvms(this);
6004       set_control(array_ctl);
6005 
6006       BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
6007       const TypeAryPtr* ary_ptr = obj_type->isa_aryptr();
6008       if (UseArrayFlattening && bs->array_copy_requires_gc_barriers(true, T_OBJECT, true, false, BarrierSetC2::Expansion) &&
6009           obj_type->can_be_inline_array() &&
6010           (ary_ptr == nullptr || (!ary_ptr->is_not_flat() && (!ary_ptr->is_flat() || ary_ptr->elem()->inline_klass()->contains_oops())))) {
6011         // Flat inline type array may have object field that would require a
6012         // write barrier. Conservatively, go to slow path.
6013         generate_fair_guard(flat_array_test(obj_klass), slow_region);
6014       }
6015 
6016       if (!stopped()) {
6017         Node* obj_length = load_array_length(array_obj);
6018         Node* array_size = nullptr; // Size of the array without object alignment padding.
6019         Node* alloc_obj = new_array(obj_klass, obj_length, 0, &array_size, /*deoptimize_on_exception=*/true);
6020 
6021         BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
6022         if (bs->array_copy_requires_gc_barriers(true, T_OBJECT, true, false, BarrierSetC2::Parsing)) {
6023           // If it is an oop array, it requires very special treatment,
6024           // because gc barriers are required when accessing the array.
6025           Node* is_obja = generate_refArray_guard(obj_klass, (RegionNode*)nullptr);
6026           if (is_obja != nullptr) {
6027             PreserveJVMState pjvms2(this);
6028             set_control(is_obja);
6029             // Generate a direct call to the right arraycopy function(s).
6030             // Clones are always tightly coupled.
6031             ArrayCopyNode* ac = ArrayCopyNode::make(this, true, array_obj, intcon(0), alloc_obj, intcon(0), obj_length, true, false);
6032             ac->set_clone_oop_array();
6033             Node* n = _gvn.transform(ac);
6034             assert(n == ac, "cannot disappear");
6035             ac->connect_outputs(this, /*deoptimize_on_exception=*/true);
6036 
6037             result_reg->init_req(_objArray_path, control());
6038             result_val->init_req(_objArray_path, alloc_obj);
6039             result_i_o ->set_req(_objArray_path, i_o());
6040             result_mem ->set_req(_objArray_path, reset_memory());
6041           }
6042         }
6043         // Otherwise, there are no barriers to worry about.
6044         // (We can dispense with card marks if we know the allocation
6045         //  comes out of eden (TLAB)...  In fact, ReduceInitialCardMarks
6046         //  causes the non-eden paths to take compensating steps to
6047         //  simulate a fresh allocation, so that no further
6048         //  card marks are required in compiled code to initialize
6049         //  the object.)
6050 
6051         if (!stopped()) {
6052           copy_to_clone(obj, alloc_obj, array_size, true);
6053 
6054           // Present the results of the copy.
6055           result_reg->init_req(_array_path, control());
6056           result_val->init_req(_array_path, alloc_obj);
6057           result_i_o ->set_req(_array_path, i_o());
6058           result_mem ->set_req(_array_path, reset_memory());
6059         }
6060       }
6061     }
6062 
6063     if (!stopped()) {
6064       // It's an instance (we did array above).  Make the slow-path tests.
6065       // If this is a virtual call, we generate a funny guard.  We grab
6066       // the vtable entry corresponding to clone() from the target object.
6067       // If the target method which we are calling happens to be the
6068       // Object clone() method, we pass the guard.  We do not need this
6069       // guard for non-virtual calls; the caller is known to be the native
6070       // Object clone().
6071       if (is_virtual) {
6072         generate_virtual_guard(obj_klass, slow_region);
6073       }
6074 
6075       // The object must be easily cloneable and must not have a finalizer.
6076       // Both of these conditions may be checked in a single test.
6077       // We could optimize the test further, but we don't care.
6078       generate_misc_flags_guard(obj_klass,
6079                                 // Test both conditions:
6080                                 KlassFlags::_misc_is_cloneable_fast | KlassFlags::_misc_has_finalizer,
6081                                 // Must be cloneable but not finalizer:
6082                                 KlassFlags::_misc_is_cloneable_fast,
6083                                 slow_region);
6084     }
6085 
6086     if (!stopped()) {
6087       // It's an instance, and it passed the slow-path tests.
6088       PreserveJVMState pjvms(this);
6089       Node* obj_size = nullptr; // Total object size, including object alignment padding.
6090       // Need to deoptimize on exception from allocation since Object.clone intrinsic
6091       // is reexecuted if deoptimization occurs and there could be problems when merging
6092       // exception state between multiple Object.clone versions (reexecute=true vs reexecute=false).
6093       Node* alloc_obj = new_instance(obj_klass, nullptr, &obj_size, /*deoptimize_on_exception=*/true);
6094 
6095       copy_to_clone(obj, alloc_obj, obj_size, false);
6096 
6097       // Present the results of the slow call.
6098       result_reg->init_req(_instance_path, control());
6099       result_val->init_req(_instance_path, alloc_obj);
6100       result_i_o ->set_req(_instance_path, i_o());
6101       result_mem ->set_req(_instance_path, reset_memory());
6102     }
6103 
6104     // Generate code for the slow case.  We make a call to clone().
6105     set_control(_gvn.transform(slow_region));
6106     if (!stopped()) {
6107       PreserveJVMState pjvms(this);
6108       CallJavaNode* slow_call = generate_method_call(vmIntrinsics::_clone, is_virtual, false, true);
6109       // We need to deoptimize on exception (see comment above)
6110       Node* slow_result = set_results_for_java_call(slow_call, false, /* deoptimize */ true);
6111       // this->control() comes from set_results_for_java_call
6112       result_reg->init_req(_slow_path, control());
6113       result_val->init_req(_slow_path, slow_result);
6114       result_i_o ->set_req(_slow_path, i_o());
6115       result_mem ->set_req(_slow_path, reset_memory());
6116     }
6117 
6118     // Return the combined state.
6119     set_control(    _gvn.transform(result_reg));
6120     set_i_o(        _gvn.transform(result_i_o));
6121     set_all_memory( _gvn.transform(result_mem));
6122   } // original reexecute is set back here
6123 
6124   set_result(_gvn.transform(result_val));
6125   return true;
6126 }
6127 
6128 // If we have a tightly coupled allocation, the arraycopy may take care
6129 // of the array initialization. If one of the guards we insert between
6130 // the allocation and the arraycopy causes a deoptimization, an
6131 // uninitialized array will escape the compiled method. To prevent that
6132 // we set the JVM state for uncommon traps between the allocation and
6133 // the arraycopy to the state before the allocation so, in case of
6134 // deoptimization, we'll reexecute the allocation and the
6135 // initialization.
6136 JVMState* LibraryCallKit::arraycopy_restore_alloc_state(AllocateArrayNode* alloc, int& saved_reexecute_sp) {
6137   if (alloc != nullptr) {
6138     ciMethod* trap_method = alloc->jvms()->method();
6139     int trap_bci = alloc->jvms()->bci();
6140 
6141     if (!C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_intrinsic) &&
6142         !C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_null_check)) {
6143       // Make sure there's no store between the allocation and the
6144       // arraycopy otherwise visible side effects could be rexecuted
6145       // in case of deoptimization and cause incorrect execution.
6146       bool no_interfering_store = true;
6147       Node* mem = alloc->in(TypeFunc::Memory);
6148       if (mem->is_MergeMem()) {
6149         for (MergeMemStream mms(merged_memory(), mem->as_MergeMem()); mms.next_non_empty2(); ) {
6150           Node* n = mms.memory();
6151           if (n != mms.memory2() && !(n->is_Proj() && n->in(0) == alloc->initialization())) {
6152             assert(n->is_Store(), "what else?");
6153             no_interfering_store = false;
6154             break;
6155           }
6156         }
6157       } else {
6158         for (MergeMemStream mms(merged_memory()); mms.next_non_empty(); ) {
6159           Node* n = mms.memory();
6160           if (n != mem && !(n->is_Proj() && n->in(0) == alloc->initialization())) {
6161             assert(n->is_Store(), "what else?");
6162             no_interfering_store = false;
6163             break;
6164           }
6165         }
6166       }
6167 
6168       if (no_interfering_store) {
6169         SafePointNode* sfpt = create_safepoint_with_state_before_array_allocation(alloc);
6170 
6171         JVMState* saved_jvms = jvms();
6172         saved_reexecute_sp = _reexecute_sp;
6173 
6174         set_jvms(sfpt->jvms());
6175         _reexecute_sp = jvms()->sp();
6176 
6177         return saved_jvms;
6178       }
6179     }
6180   }
6181   return nullptr;
6182 }
6183 
6184 // Clone the JVMState of the array allocation and create a new safepoint with it. Re-push the array length to the stack
6185 // such that uncommon traps can be emitted to re-execute the array allocation in the interpreter.
6186 SafePointNode* LibraryCallKit::create_safepoint_with_state_before_array_allocation(const AllocateArrayNode* alloc) const {
6187   JVMState* old_jvms = alloc->jvms()->clone_shallow(C);
6188   uint size = alloc->req();
6189   SafePointNode* sfpt = new SafePointNode(size, old_jvms);
6190   old_jvms->set_map(sfpt);
6191   for (uint i = 0; i < size; i++) {
6192     sfpt->init_req(i, alloc->in(i));
6193   }
6194   int adjustment = 1;
6195   const TypeAryKlassPtr* ary_klass_ptr = alloc->in(AllocateNode::KlassNode)->bottom_type()->is_aryklassptr();
6196   if (ary_klass_ptr->is_null_free()) {
6197     // A null-free, tightly coupled array allocation can only come from LibraryCallKit::inline_newArray which
6198     // also requires the componentType and initVal on stack for re-execution.
6199     // Re-create and push the componentType.
6200     ciArrayKlass* klass = ary_klass_ptr->exact_klass()->as_array_klass();
6201     ciInstance* instance = klass->component_mirror_instance();
6202     const TypeInstPtr* t_instance = TypeInstPtr::make(instance);
6203     sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp(), makecon(t_instance));
6204     adjustment++;
6205   }
6206   // re-push array length for deoptimization
6207   sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp() + adjustment - 1, alloc->in(AllocateNode::ALength));
6208   if (ary_klass_ptr->is_null_free()) {
6209     // Re-create and push the initVal.
6210     Node* init_val = alloc->in(AllocateNode::InitValue);
6211     if (init_val == nullptr) {
6212       init_val = InlineTypeNode::make_all_zero(_gvn, ary_klass_ptr->elem()->is_instklassptr()->instance_klass()->as_inline_klass());
6213     } else if (UseCompressedOops) {
6214       init_val = _gvn.transform(new DecodeNNode(init_val, init_val->bottom_type()->make_ptr()));
6215     }
6216     sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp() + adjustment, init_val);
6217     adjustment++;
6218   }
6219   old_jvms->set_sp(old_jvms->sp() + adjustment);
6220   old_jvms->set_monoff(old_jvms->monoff() + adjustment);
6221   old_jvms->set_scloff(old_jvms->scloff() + adjustment);
6222   old_jvms->set_endoff(old_jvms->endoff() + adjustment);
6223   old_jvms->set_should_reexecute(true);
6224 
6225   sfpt->set_i_o(map()->i_o());
6226   sfpt->set_memory(map()->memory());
6227   sfpt->set_control(map()->control());
6228   return sfpt;
6229 }
6230 
6231 // In case of a deoptimization, we restart execution at the
6232 // allocation, allocating a new array. We would leave an uninitialized
6233 // array in the heap that GCs wouldn't expect. Move the allocation
6234 // after the traps so we don't allocate the array if we
6235 // deoptimize. This is possible because tightly_coupled_allocation()
6236 // guarantees there's no observer of the allocated array at this point
6237 // and the control flow is simple enough.
6238 void LibraryCallKit::arraycopy_move_allocation_here(AllocateArrayNode* alloc, Node* dest, JVMState* saved_jvms_before_guards,
6239                                                     int saved_reexecute_sp, uint new_idx) {
6240   if (saved_jvms_before_guards != nullptr && !stopped()) {
6241     replace_unrelated_uncommon_traps_with_alloc_state(alloc, saved_jvms_before_guards);
6242 
6243     assert(alloc != nullptr, "only with a tightly coupled allocation");
6244     // restore JVM state to the state at the arraycopy
6245     saved_jvms_before_guards->map()->set_control(map()->control());
6246     assert(saved_jvms_before_guards->map()->memory() == map()->memory(), "memory state changed?");
6247     assert(saved_jvms_before_guards->map()->i_o() == map()->i_o(), "IO state changed?");
6248     // If we've improved the types of some nodes (null check) while
6249     // emitting the guards, propagate them to the current state
6250     map()->replaced_nodes().apply(saved_jvms_before_guards->map(), new_idx);
6251     set_jvms(saved_jvms_before_guards);
6252     _reexecute_sp = saved_reexecute_sp;
6253 
6254     // Remove the allocation from above the guards
6255     CallProjections* callprojs = alloc->extract_projections(true);
6256     InitializeNode* init = alloc->initialization();
6257     Node* alloc_mem = alloc->in(TypeFunc::Memory);
6258     C->gvn_replace_by(callprojs->fallthrough_ioproj, alloc->in(TypeFunc::I_O));
6259     init->replace_mem_projs_by(alloc_mem, C);
6260 
6261     // The CastIINode created in GraphKit::new_array (in AllocateArrayNode::make_ideal_length) must stay below
6262     // the allocation (i.e. is only valid if the allocation succeeds):
6263     // 1) replace CastIINode with AllocateArrayNode's length here
6264     // 2) Create CastIINode again once allocation has moved (see below) at the end of this method
6265     //
6266     // Multiple identical CastIINodes might exist here. Each GraphKit::load_array_length() call will generate
6267     // new separate CastIINode (arraycopy guard checks or any array length use between array allocation and ararycopy)
6268     Node* init_control = init->proj_out(TypeFunc::Control);
6269     Node* alloc_length = alloc->Ideal_length();
6270 #ifdef ASSERT
6271     Node* prev_cast = nullptr;
6272 #endif
6273     for (uint i = 0; i < init_control->outcnt(); i++) {
6274       Node* init_out = init_control->raw_out(i);
6275       if (init_out->is_CastII() && init_out->in(TypeFunc::Control) == init_control && init_out->in(1) == alloc_length) {
6276 #ifdef ASSERT
6277         if (prev_cast == nullptr) {
6278           prev_cast = init_out;
6279         } else {
6280           if (prev_cast->cmp(*init_out) == false) {
6281             prev_cast->dump();
6282             init_out->dump();
6283             assert(false, "not equal CastIINode");
6284           }
6285         }
6286 #endif
6287         C->gvn_replace_by(init_out, alloc_length);
6288       }
6289     }
6290     C->gvn_replace_by(init->proj_out(TypeFunc::Control), alloc->in(0));
6291 
6292     // move the allocation here (after the guards)
6293     _gvn.hash_delete(alloc);
6294     alloc->set_req(TypeFunc::Control, control());
6295     alloc->set_req(TypeFunc::I_O, i_o());
6296     Node *mem = reset_memory();
6297     set_all_memory(mem);
6298     alloc->set_req(TypeFunc::Memory, mem);
6299     set_control(init->proj_out_or_null(TypeFunc::Control));
6300     set_i_o(callprojs->fallthrough_ioproj);
6301 
6302     // Update memory as done in GraphKit::set_output_for_allocation()
6303     const TypeInt* length_type = _gvn.find_int_type(alloc->in(AllocateNode::ALength));
6304     const TypeOopPtr* ary_type = _gvn.type(alloc->in(AllocateNode::KlassNode))->is_klassptr()->as_instance_type();
6305     if (ary_type->isa_aryptr() && length_type != nullptr) {
6306       ary_type = ary_type->is_aryptr()->cast_to_size(length_type);
6307     }
6308     const TypePtr* telemref = ary_type->add_offset(Type::OffsetBot);
6309     int            elemidx  = C->get_alias_index(telemref);
6310     // Need to properly move every memory projection for the Initialize
6311 #ifdef ASSERT
6312     int mark_idx = C->get_alias_index(ary_type->add_offset(oopDesc::mark_offset_in_bytes()));
6313     int klass_idx = C->get_alias_index(ary_type->add_offset(oopDesc::klass_offset_in_bytes()));
6314 #endif
6315     auto move_proj = [&](ProjNode* proj) {
6316       int alias_idx = C->get_alias_index(proj->adr_type());
6317       assert(alias_idx == Compile::AliasIdxRaw ||
6318              alias_idx == elemidx ||
6319              alias_idx == mark_idx ||
6320              alias_idx == klass_idx, "should be raw memory or array element type");
6321       set_memory(proj, alias_idx);
6322     };
6323     init->for_each_proj(move_proj, TypeFunc::Memory);
6324 
6325     Node* allocx = _gvn.transform(alloc);
6326     assert(allocx == alloc, "where has the allocation gone?");
6327     assert(dest->is_CheckCastPP(), "not an allocation result?");
6328 
6329     _gvn.hash_delete(dest);
6330     dest->set_req(0, control());
6331     Node* destx = _gvn.transform(dest);
6332     assert(destx == dest, "where has the allocation result gone?");
6333 
6334     array_ideal_length(alloc, ary_type, true);
6335   }
6336 }
6337 
6338 // Unrelated UCTs between the array allocation and the array copy, which are considered safe by tightly_coupled_allocation(),
6339 // need to be replaced by an UCT with a state before the array allocation (including the array length). This is necessary
6340 // because we could hit one of these UCTs (which are executed before the emitted array copy guards and the actual array
6341 // allocation which is moved down in arraycopy_move_allocation_here()). When later resuming execution in the interpreter,
6342 // we would have wrongly skipped the array allocation. To prevent this, we resume execution at the array allocation in
6343 // the interpreter similar to what we are doing for the newly emitted guards for the array copy.
6344 void LibraryCallKit::replace_unrelated_uncommon_traps_with_alloc_state(AllocateArrayNode* alloc,
6345                                                                        JVMState* saved_jvms_before_guards) {
6346   if (saved_jvms_before_guards->map()->control()->is_IfProj()) {
6347     // There is at least one unrelated uncommon trap which needs to be replaced.
6348     SafePointNode* sfpt = create_safepoint_with_state_before_array_allocation(alloc);
6349 
6350     JVMState* saved_jvms = jvms();
6351     const int saved_reexecute_sp = _reexecute_sp;
6352     set_jvms(sfpt->jvms());
6353     _reexecute_sp = jvms()->sp();
6354 
6355     replace_unrelated_uncommon_traps_with_alloc_state(saved_jvms_before_guards);
6356 
6357     // Restore state
6358     set_jvms(saved_jvms);
6359     _reexecute_sp = saved_reexecute_sp;
6360   }
6361 }
6362 
6363 // Replace the unrelated uncommon traps with new uncommon trap nodes by reusing the action and reason. The new uncommon
6364 // traps will have the state of the array allocation. Let the old uncommon trap nodes die.
6365 void LibraryCallKit::replace_unrelated_uncommon_traps_with_alloc_state(JVMState* saved_jvms_before_guards) {
6366   Node* if_proj = saved_jvms_before_guards->map()->control(); // Start the search right before the newly emitted guards
6367   while (if_proj->is_IfProj()) {
6368     CallStaticJavaNode* uncommon_trap = get_uncommon_trap_from_success_proj(if_proj);
6369     if (uncommon_trap != nullptr) {
6370       create_new_uncommon_trap(uncommon_trap);
6371     }
6372     assert(if_proj->in(0)->is_If(), "must be If");
6373     if_proj = if_proj->in(0)->in(0);
6374   }
6375   assert(if_proj->is_Proj() && if_proj->in(0)->is_Initialize(),
6376          "must have reached control projection of init node");
6377 }
6378 
6379 void LibraryCallKit::create_new_uncommon_trap(CallStaticJavaNode* uncommon_trap_call) {
6380   const int trap_request = uncommon_trap_call->uncommon_trap_request();
6381   assert(trap_request != 0, "no valid UCT trap request");
6382   PreserveJVMState pjvms(this);
6383   set_control(uncommon_trap_call->in(0));
6384   uncommon_trap(Deoptimization::trap_request_reason(trap_request),
6385                 Deoptimization::trap_request_action(trap_request));
6386   assert(stopped(), "Should be stopped");
6387   _gvn.hash_delete(uncommon_trap_call);
6388   uncommon_trap_call->set_req(0, top()); // not used anymore, kill it
6389 }
6390 
6391 // Common checks for array sorting intrinsics arguments.
6392 // Returns `true` if checks passed.
6393 bool LibraryCallKit::check_array_sort_arguments(Node* elementType, Node* obj, BasicType& bt) {
6394   // check address of the class
6395   if (elementType == nullptr || elementType->is_top()) {
6396     return false;  // dead path
6397   }
6398   const TypeInstPtr* elem_klass = gvn().type(elementType)->isa_instptr();
6399   if (elem_klass == nullptr) {
6400     return false;  // dead path
6401   }
6402   // java_mirror_type() returns non-null for compile-time Class constants only
6403   ciType* elem_type = elem_klass->java_mirror_type();
6404   if (elem_type == nullptr) {
6405     return false;
6406   }
6407   bt = elem_type->basic_type();
6408   // Disable the intrinsic if the CPU does not support SIMD sort
6409   if (!Matcher::supports_simd_sort(bt)) {
6410     return false;
6411   }
6412   // check address of the array
6413   if (obj == nullptr || obj->is_top()) {
6414     return false;  // dead path
6415   }
6416   const TypeAryPtr* obj_t = _gvn.type(obj)->isa_aryptr();
6417   if (obj_t == nullptr || obj_t->elem() == Type::BOTTOM) {
6418     return false; // failed input validation
6419   }
6420   return true;
6421 }
6422 
6423 //------------------------------inline_array_partition-----------------------
6424 bool LibraryCallKit::inline_array_partition() {
6425   address stubAddr = StubRoutines::select_array_partition_function();
6426   if (stubAddr == nullptr) {
6427     return false; // Intrinsic's stub is not implemented on this platform
6428   }
6429   assert(callee()->signature()->size() == 9, "arrayPartition has 8 parameters (one long)");
6430 
6431   // no receiver because it is a static method
6432   Node* elementType     = argument(0);
6433   Node* obj             = argument(1);
6434   Node* offset          = argument(2); // long
6435   Node* fromIndex       = argument(4);
6436   Node* toIndex         = argument(5);
6437   Node* indexPivot1     = argument(6);
6438   Node* indexPivot2     = argument(7);
6439   // PartitionOperation:  argument(8) is ignored
6440 
6441   Node* pivotIndices = nullptr;
6442   BasicType bt = T_ILLEGAL;
6443 
6444   if (!check_array_sort_arguments(elementType, obj, bt)) {
6445     return false;
6446   }
6447   null_check(obj);
6448   // If obj is dead, only null-path is taken.
6449   if (stopped()) {
6450     return true;
6451   }
6452   // Set the original stack and the reexecute bit for the interpreter to reexecute
6453   // the bytecode that invokes DualPivotQuicksort.partition() if deoptimization happens.
6454   { PreserveReexecuteState preexecs(this);
6455     jvms()->set_should_reexecute(true);
6456 
6457     Node* obj_adr = make_unsafe_address(obj, offset);
6458 
6459     // create the pivotIndices array of type int and size = 2
6460     Node* size = intcon(2);
6461     Node* klass_node = makecon(TypeKlassPtr::make(ciTypeArrayKlass::make(T_INT)));
6462     pivotIndices = new_array(klass_node, size, 0);  // no arguments to push
6463     AllocateArrayNode* alloc = tightly_coupled_allocation(pivotIndices);
6464     guarantee(alloc != nullptr, "created above");
6465     Node* pivotIndices_adr = basic_plus_adr(pivotIndices, arrayOopDesc::base_offset_in_bytes(T_INT));
6466 
6467     // pass the basic type enum to the stub
6468     Node* elemType = intcon(bt);
6469 
6470     // Call the stub
6471     const char *stubName = "array_partition_stub";
6472     make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::array_partition_Type(),
6473                       stubAddr, stubName, TypePtr::BOTTOM,
6474                       obj_adr, elemType, fromIndex, toIndex, pivotIndices_adr,
6475                       indexPivot1, indexPivot2);
6476 
6477   } // original reexecute is set back here
6478 
6479   if (!stopped()) {
6480     set_result(pivotIndices);
6481   }
6482 
6483   return true;
6484 }
6485 
6486 
6487 //------------------------------inline_array_sort-----------------------
6488 bool LibraryCallKit::inline_array_sort() {
6489   address stubAddr = StubRoutines::select_arraysort_function();
6490   if (stubAddr == nullptr) {
6491     return false; // Intrinsic's stub is not implemented on this platform
6492   }
6493   assert(callee()->signature()->size() == 7, "arraySort has 6 parameters (one long)");
6494 
6495   // no receiver because it is a static method
6496   Node* elementType     = argument(0);
6497   Node* obj             = argument(1);
6498   Node* offset          = argument(2); // long
6499   Node* fromIndex       = argument(4);
6500   Node* toIndex         = argument(5);
6501   // SortOperation:       argument(6) is ignored
6502 
6503   BasicType bt = T_ILLEGAL;
6504 
6505   if (!check_array_sort_arguments(elementType, obj, bt)) {
6506     return false;
6507   }
6508   null_check(obj);
6509   // If obj is dead, only null-path is taken.
6510   if (stopped()) {
6511     return true;
6512   }
6513   Node* obj_adr = make_unsafe_address(obj, offset);
6514 
6515   // pass the basic type enum to the stub
6516   Node* elemType = intcon(bt);
6517 
6518   // Call the stub.
6519   const char *stubName = "arraysort_stub";
6520   make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::array_sort_Type(),
6521                     stubAddr, stubName, TypePtr::BOTTOM,
6522                     obj_adr, elemType, fromIndex, toIndex);
6523 
6524   return true;
6525 }
6526 
6527 
6528 //------------------------------inline_arraycopy-----------------------
6529 // public static native void java.lang.System.arraycopy(Object src,  int  srcPos,
6530 //                                                      Object dest, int destPos,
6531 //                                                      int length);
6532 bool LibraryCallKit::inline_arraycopy() {
6533   // Get the arguments.
6534   Node* src         = argument(0);  // type: oop
6535   Node* src_offset  = argument(1);  // type: int
6536   Node* dest        = argument(2);  // type: oop
6537   Node* dest_offset = argument(3);  // type: int
6538   Node* length      = argument(4);  // type: int
6539 
6540   uint new_idx = C->unique();
6541 
6542   // Check for allocation before we add nodes that would confuse
6543   // tightly_coupled_allocation()
6544   AllocateArrayNode* alloc = tightly_coupled_allocation(dest);
6545 
6546   int saved_reexecute_sp = -1;
6547   JVMState* saved_jvms_before_guards = arraycopy_restore_alloc_state(alloc, saved_reexecute_sp);
6548   // See arraycopy_restore_alloc_state() comment
6549   // if alloc == null we don't have to worry about a tightly coupled allocation so we can emit all needed guards
6550   // if saved_jvms_before_guards is not null (then alloc is not null) then we can handle guards and a tightly coupled allocation
6551   // if saved_jvms_before_guards is null and alloc is not null, we can't emit any guards
6552   bool can_emit_guards = (alloc == nullptr || saved_jvms_before_guards != nullptr);
6553 
6554   // The following tests must be performed
6555   // (1) src and dest are arrays.
6556   // (2) src and dest arrays must have elements of the same BasicType
6557   // (3) src and dest must not be null.
6558   // (4) src_offset must not be negative.
6559   // (5) dest_offset must not be negative.
6560   // (6) length must not be negative.
6561   // (7) src_offset + length must not exceed length of src.
6562   // (8) dest_offset + length must not exceed length of dest.
6563   // (9) each element of an oop array must be assignable
6564 
6565   // (3) src and dest must not be null.
6566   // always do this here because we need the JVM state for uncommon traps
6567   Node* null_ctl = top();
6568   src  = saved_jvms_before_guards != nullptr ? null_check_oop(src, &null_ctl, true, true) : null_check(src, T_ARRAY);
6569   assert(null_ctl->is_top(), "no null control here");
6570   dest = null_check(dest, T_ARRAY);
6571 
6572   if (!can_emit_guards) {
6573     // if saved_jvms_before_guards is null and alloc is not null, we don't emit any
6574     // guards but the arraycopy node could still take advantage of a
6575     // tightly allocated allocation. tightly_coupled_allocation() is
6576     // called again to make sure it takes the null check above into
6577     // account: the null check is mandatory and if it caused an
6578     // uncommon trap to be emitted then the allocation can't be
6579     // considered tightly coupled in this context.
6580     alloc = tightly_coupled_allocation(dest);
6581   }
6582 
6583   bool validated = false;
6584 
6585   const Type* src_type  = _gvn.type(src);
6586   const Type* dest_type = _gvn.type(dest);
6587   const TypeAryPtr* top_src  = src_type->isa_aryptr();
6588   const TypeAryPtr* top_dest = dest_type->isa_aryptr();
6589 
6590   // Do we have the type of src?
6591   bool has_src = (top_src != nullptr && top_src->elem() != Type::BOTTOM);
6592   // Do we have the type of dest?
6593   bool has_dest = (top_dest != nullptr && top_dest->elem() != Type::BOTTOM);
6594   // Is the type for src from speculation?
6595   bool src_spec = false;
6596   // Is the type for dest from speculation?
6597   bool dest_spec = false;
6598 
6599   if ((!has_src || !has_dest) && can_emit_guards) {
6600     // We don't have sufficient type information, let's see if
6601     // speculative types can help. We need to have types for both src
6602     // and dest so that it pays off.
6603 
6604     // Do we already have or could we have type information for src
6605     bool could_have_src = has_src;
6606     // Do we already have or could we have type information for dest
6607     bool could_have_dest = has_dest;
6608 
6609     ciKlass* src_k = nullptr;
6610     if (!has_src) {
6611       src_k = src_type->speculative_type_not_null();
6612       if (src_k != nullptr && src_k->is_array_klass()) {
6613         could_have_src = true;
6614       }
6615     }
6616 
6617     ciKlass* dest_k = nullptr;
6618     if (!has_dest) {
6619       dest_k = dest_type->speculative_type_not_null();
6620       if (dest_k != nullptr && dest_k->is_array_klass()) {
6621         could_have_dest = true;
6622       }
6623     }
6624 
6625     if (could_have_src && could_have_dest) {
6626       // This is going to pay off so emit the required guards
6627       if (!has_src) {
6628         src = maybe_cast_profiled_obj(src, src_k, true);
6629         src_type  = _gvn.type(src);
6630         top_src  = src_type->isa_aryptr();
6631         has_src = (top_src != nullptr && top_src->elem() != Type::BOTTOM);
6632         src_spec = true;
6633       }
6634       if (!has_dest) {
6635         dest = maybe_cast_profiled_obj(dest, dest_k, true);
6636         dest_type  = _gvn.type(dest);
6637         top_dest  = dest_type->isa_aryptr();
6638         has_dest = (top_dest != nullptr && top_dest->elem() != Type::BOTTOM);
6639         dest_spec = true;
6640       }
6641     }
6642   }
6643 
6644   if (has_src && has_dest && can_emit_guards) {
6645     BasicType src_elem = top_src->isa_aryptr()->elem()->array_element_basic_type();
6646     BasicType dest_elem = top_dest->isa_aryptr()->elem()->array_element_basic_type();
6647     if (is_reference_type(src_elem, true)) src_elem = T_OBJECT;
6648     if (is_reference_type(dest_elem, true)) dest_elem = T_OBJECT;
6649 
6650     if (src_elem == dest_elem && top_src->is_flat() == top_dest->is_flat() && src_elem == T_OBJECT) {
6651       // If both arrays are object arrays then having the exact types
6652       // for both will remove the need for a subtype check at runtime
6653       // before the call and may make it possible to pick a faster copy
6654       // routine (without a subtype check on every element)
6655       // Do we have the exact type of src?
6656       bool could_have_src = src_spec;
6657       // Do we have the exact type of dest?
6658       bool could_have_dest = dest_spec;
6659       ciKlass* src_k = nullptr;
6660       ciKlass* dest_k = nullptr;
6661       if (!src_spec) {
6662         src_k = src_type->speculative_type_not_null();
6663         if (src_k != nullptr && src_k->is_array_klass()) {
6664           could_have_src = true;
6665         }
6666       }
6667       if (!dest_spec) {
6668         dest_k = dest_type->speculative_type_not_null();
6669         if (dest_k != nullptr && dest_k->is_array_klass()) {
6670           could_have_dest = true;
6671         }
6672       }
6673       if (could_have_src && could_have_dest) {
6674         // If we can have both exact types, emit the missing guards
6675         if (could_have_src && !src_spec) {
6676           src = maybe_cast_profiled_obj(src, src_k, true);
6677           src_type = _gvn.type(src);
6678           top_src = src_type->isa_aryptr();
6679         }
6680         if (could_have_dest && !dest_spec) {
6681           dest = maybe_cast_profiled_obj(dest, dest_k, true);
6682           dest_type = _gvn.type(dest);
6683           top_dest = dest_type->isa_aryptr();
6684         }
6685       }
6686     }
6687   }
6688 
6689   ciMethod* trap_method = method();
6690   int trap_bci = bci();
6691   if (saved_jvms_before_guards != nullptr) {
6692     trap_method = alloc->jvms()->method();
6693     trap_bci = alloc->jvms()->bci();
6694   }
6695 
6696   bool negative_length_guard_generated = false;
6697 
6698   if (!C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_intrinsic) &&
6699       can_emit_guards && !src->is_top() && !dest->is_top()) {
6700     // validate arguments: enables transformation the ArrayCopyNode
6701     validated = true;
6702 
6703     RegionNode* slow_region = new RegionNode(1);
6704     record_for_igvn(slow_region);
6705 
6706     // (1) src and dest are arrays.
6707     generate_non_array_guard(load_object_klass(src), slow_region, &src);
6708     generate_non_array_guard(load_object_klass(dest), slow_region, &dest);
6709 
6710     // (2) src and dest arrays must have elements of the same BasicType
6711     // done at macro expansion or at Ideal transformation time
6712 
6713     // (4) src_offset must not be negative.
6714     generate_negative_guard(src_offset, slow_region);
6715 
6716     // (5) dest_offset must not be negative.
6717     generate_negative_guard(dest_offset, slow_region);
6718 
6719     // (7) src_offset + length must not exceed length of src.
6720     generate_limit_guard(src_offset, length,
6721                          load_array_length(src),
6722                          slow_region);
6723 
6724     // (8) dest_offset + length must not exceed length of dest.
6725     generate_limit_guard(dest_offset, length,
6726                          load_array_length(dest),
6727                          slow_region);
6728 
6729     // (6) length must not be negative.
6730     // This is also checked in generate_arraycopy() during macro expansion, but
6731     // we also have to check it here for the case where the ArrayCopyNode will
6732     // be eliminated by Escape Analysis.
6733     if (EliminateAllocations) {
6734       generate_negative_guard(length, slow_region);
6735       negative_length_guard_generated = true;
6736     }
6737 
6738     // (9) each element of an oop array must be assignable
6739     Node* dest_klass = load_object_klass(dest);
6740     Node* refined_dest_klass = dest_klass;
6741     if (src != dest) {
6742       dest_klass = load_non_refined_array_klass(refined_dest_klass);
6743       Node* not_subtype_ctrl = gen_subtype_check(src, dest_klass);
6744       slow_region->add_req(not_subtype_ctrl);
6745     }
6746 
6747     // TODO 8350865 Improve this. What about atomicity? Make sure this is always folded for type arrays.
6748     // If destination is null-restricted, source must be null-restricted as well: src_null_restricted || !dst_null_restricted
6749     Node* src_klass = load_object_klass(src);
6750     Node* adr_prop_src = basic_plus_adr(top(), src_klass, in_bytes(ArrayKlass::properties_offset()));
6751     Node* prop_src = _gvn.transform(LoadNode::make(_gvn, control(), immutable_memory(), adr_prop_src, TypeRawPtr::BOTTOM, TypeInt::INT, T_INT, MemNode::unordered));
6752     Node* adr_prop_dest = basic_plus_adr(top(), refined_dest_klass, in_bytes(ArrayKlass::properties_offset()));
6753     Node* prop_dest = _gvn.transform(LoadNode::make(_gvn, control(), immutable_memory(), adr_prop_dest, TypeRawPtr::BOTTOM, TypeInt::INT, T_INT, MemNode::unordered));
6754 
6755     prop_dest = _gvn.transform(new XorINode(prop_dest, intcon(ArrayKlass::ArrayProperties::NULL_RESTRICTED)));
6756     prop_src = _gvn.transform(new OrINode(prop_dest, prop_src));
6757     prop_src = _gvn.transform(new AndINode(prop_src, intcon(ArrayKlass::ArrayProperties::NULL_RESTRICTED)));
6758 
6759     Node* chk = _gvn.transform(new CmpINode(prop_src, intcon(ArrayKlass::ArrayProperties::NULL_RESTRICTED)));
6760     Node* tst = _gvn.transform(new BoolNode(chk, BoolTest::ne));
6761     generate_fair_guard(tst, slow_region);
6762 
6763     // TODO 8350865 This is too strong
6764     generate_fair_guard(flat_array_test(src), slow_region);
6765     generate_fair_guard(flat_array_test(dest), slow_region);
6766 
6767     {
6768       PreserveJVMState pjvms(this);
6769       set_control(_gvn.transform(slow_region));
6770       uncommon_trap(Deoptimization::Reason_intrinsic,
6771                     Deoptimization::Action_make_not_entrant);
6772       assert(stopped(), "Should be stopped");
6773     }
6774 
6775     const TypeKlassPtr* dest_klass_t = _gvn.type(dest_klass)->isa_klassptr();
6776     if (dest_klass_t == nullptr) {
6777       // refined_dest_klass may not be an array, which leads to dest_klass being top. This means we
6778       // are in a dead path.
6779       uncommon_trap(Deoptimization::Reason_intrinsic,
6780                     Deoptimization::Action_make_not_entrant);
6781       return true;
6782     }
6783 
6784     const Type* toop = dest_klass_t->cast_to_exactness(false)->as_instance_type();
6785     src = _gvn.transform(new CheckCastPPNode(control(), src, toop));
6786     arraycopy_move_allocation_here(alloc, dest, saved_jvms_before_guards, saved_reexecute_sp, new_idx);
6787   }
6788 
6789   if (stopped()) {
6790     return true;
6791   }
6792 
6793   Node* dest_klass = load_object_klass(dest);
6794   dest_klass = load_non_refined_array_klass(dest_klass);
6795 
6796   ArrayCopyNode* ac = ArrayCopyNode::make(this, true, src, src_offset, dest, dest_offset, length, alloc != nullptr, negative_length_guard_generated,
6797                                           // Create LoadRange and LoadKlass nodes for use during macro expansion here
6798                                           // so the compiler has a chance to eliminate them: during macro expansion,
6799                                           // we have to set their control (CastPP nodes are eliminated).
6800                                           load_object_klass(src), dest_klass,
6801                                           load_array_length(src), load_array_length(dest));
6802 
6803   ac->set_arraycopy(validated);
6804 
6805   Node* n = _gvn.transform(ac);
6806   if (n == ac) {
6807     ac->connect_outputs(this);
6808   } else {
6809     assert(validated, "shouldn't transform if all arguments not validated");
6810     set_all_memory(n);
6811   }
6812   clear_upper_avx();
6813 
6814 
6815   return true;
6816 }
6817 
6818 
6819 // Helper function which determines if an arraycopy immediately follows
6820 // an allocation, with no intervening tests or other escapes for the object.
6821 AllocateArrayNode*
6822 LibraryCallKit::tightly_coupled_allocation(Node* ptr) {
6823   if (stopped())             return nullptr;  // no fast path
6824   if (!C->do_aliasing())     return nullptr;  // no MergeMems around
6825 
6826   AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(ptr);
6827   if (alloc == nullptr)  return nullptr;
6828 
6829   Node* rawmem = memory(Compile::AliasIdxRaw);
6830   // Is the allocation's memory state untouched?
6831   if (!(rawmem->is_Proj() && rawmem->in(0)->is_Initialize())) {
6832     // Bail out if there have been raw-memory effects since the allocation.
6833     // (Example:  There might have been a call or safepoint.)
6834     return nullptr;
6835   }
6836   rawmem = rawmem->in(0)->as_Initialize()->memory(Compile::AliasIdxRaw);
6837   if (!(rawmem->is_Proj() && rawmem->in(0) == alloc)) {
6838     return nullptr;
6839   }
6840 
6841   // There must be no unexpected observers of this allocation.
6842   for (DUIterator_Fast imax, i = ptr->fast_outs(imax); i < imax; i++) {
6843     Node* obs = ptr->fast_out(i);
6844     if (obs != this->map()) {
6845       return nullptr;
6846     }
6847   }
6848 
6849   // This arraycopy must unconditionally follow the allocation of the ptr.
6850   Node* alloc_ctl = ptr->in(0);
6851   Node* ctl = control();
6852   while (ctl != alloc_ctl) {
6853     // There may be guards which feed into the slow_region.
6854     // Any other control flow means that we might not get a chance
6855     // to finish initializing the allocated object.
6856     // Various low-level checks bottom out in uncommon traps. These
6857     // are considered safe since we've already checked above that
6858     // there is no unexpected observer of this allocation.
6859     if (get_uncommon_trap_from_success_proj(ctl) != nullptr) {
6860       assert(ctl->in(0)->is_If(), "must be If");
6861       ctl = ctl->in(0)->in(0);
6862     } else {
6863       return nullptr;
6864     }
6865   }
6866 
6867   // If we get this far, we have an allocation which immediately
6868   // precedes the arraycopy, and we can take over zeroing the new object.
6869   // The arraycopy will finish the initialization, and provide
6870   // a new control state to which we will anchor the destination pointer.
6871 
6872   return alloc;
6873 }
6874 
6875 CallStaticJavaNode* LibraryCallKit::get_uncommon_trap_from_success_proj(Node* node) {
6876   if (node->is_IfProj()) {
6877     IfProjNode* other_proj = node->as_IfProj()->other_if_proj();
6878     for (DUIterator_Fast jmax, j = other_proj->fast_outs(jmax); j < jmax; j++) {
6879       Node* obs = other_proj->fast_out(j);
6880       if (obs->in(0) == other_proj && obs->is_CallStaticJava() &&
6881           (obs->as_CallStaticJava()->entry_point() == OptoRuntime::uncommon_trap_blob()->entry_point())) {
6882         return obs->as_CallStaticJava();
6883       }
6884     }
6885   }
6886   return nullptr;
6887 }
6888 
6889 //-------------inline_encodeISOArray-----------------------------------
6890 // int sun.nio.cs.ISO_8859_1.Encoder#encodeISOArray0(byte[] sa, int sp, byte[] da, int dp, int len)
6891 // int java.lang.StringCoding#encodeISOArray0(byte[] sa, int sp, byte[] da, int dp, int len)
6892 // int java.lang.StringCoding#encodeAsciiArray0(char[] sa, int sp, byte[] da, int dp, int len)
6893 // encode char[] to byte[] in ISO_8859_1 or ASCII
6894 bool LibraryCallKit::inline_encodeISOArray(bool ascii) {
6895   assert(callee()->signature()->size() == 5, "encodeISOArray has 5 parameters");
6896   // no receiver since it is static method
6897   Node *src         = argument(0);
6898   Node *src_offset  = argument(1);
6899   Node *dst         = argument(2);
6900   Node *dst_offset  = argument(3);
6901   Node *length      = argument(4);
6902 
6903   // Cast source & target arrays to not-null
6904   src = must_be_not_null(src, true);
6905   dst = must_be_not_null(dst, true);
6906   if (stopped()) {
6907     return true;
6908   }
6909 
6910   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
6911   const TypeAryPtr* dst_type = dst->Value(&_gvn)->isa_aryptr();
6912   if (src_type == nullptr || src_type->elem() == Type::BOTTOM ||
6913       dst_type == nullptr || dst_type->elem() == Type::BOTTOM) {
6914     // failed array check
6915     return false;
6916   }
6917 
6918   // Figure out the size and type of the elements we will be copying.
6919   BasicType src_elem = src_type->elem()->array_element_basic_type();
6920   BasicType dst_elem = dst_type->elem()->array_element_basic_type();
6921   if (!((src_elem == T_CHAR) || (src_elem== T_BYTE)) || dst_elem != T_BYTE) {
6922     return false;
6923   }
6924 
6925   // Check source & target bounds
6926   generate_string_range_check(src, src_offset, length, src_elem == T_BYTE, true);
6927   generate_string_range_check(dst, dst_offset, length, false, true);
6928   if (stopped()) {
6929     return true;
6930   }
6931 
6932   Node* src_start = array_element_address(src, src_offset, T_CHAR);
6933   Node* dst_start = array_element_address(dst, dst_offset, dst_elem);
6934   // 'src_start' points to src array + scaled offset
6935   // 'dst_start' points to dst array + scaled offset
6936 
6937   const TypeAryPtr* mtype = TypeAryPtr::BYTES;
6938   Node* enc = new EncodeISOArrayNode(control(), memory(mtype), src_start, dst_start, length, ascii);
6939   enc = _gvn.transform(enc);
6940   Node* res_mem = _gvn.transform(new SCMemProjNode(enc));
6941   set_memory(res_mem, mtype);
6942   set_result(enc);
6943   clear_upper_avx();
6944 
6945   return true;
6946 }
6947 
6948 //-------------inline_multiplyToLen-----------------------------------
6949 bool LibraryCallKit::inline_multiplyToLen() {
6950   assert(UseMultiplyToLenIntrinsic, "not implemented on this platform");
6951 
6952   address stubAddr = StubRoutines::multiplyToLen();
6953   if (stubAddr == nullptr) {
6954     return false; // Intrinsic's stub is not implemented on this platform
6955   }
6956   const char* stubName = "multiplyToLen";
6957 
6958   assert(callee()->signature()->size() == 5, "multiplyToLen has 5 parameters");
6959 
6960   // no receiver because it is a static method
6961   Node* x    = argument(0);
6962   Node* xlen = argument(1);
6963   Node* y    = argument(2);
6964   Node* ylen = argument(3);
6965   Node* z    = argument(4);
6966 
6967   x = must_be_not_null(x, true);
6968   y = must_be_not_null(y, true);
6969 
6970   const TypeAryPtr* x_type = x->Value(&_gvn)->isa_aryptr();
6971   const TypeAryPtr* y_type = y->Value(&_gvn)->isa_aryptr();
6972   if (x_type == nullptr || x_type->elem() == Type::BOTTOM ||
6973       y_type == nullptr || y_type->elem() == Type::BOTTOM) {
6974     // failed array check
6975     return false;
6976   }
6977 
6978   BasicType x_elem = x_type->elem()->array_element_basic_type();
6979   BasicType y_elem = y_type->elem()->array_element_basic_type();
6980   if (x_elem != T_INT || y_elem != T_INT) {
6981     return false;
6982   }
6983 
6984   Node* x_start = array_element_address(x, intcon(0), x_elem);
6985   Node* y_start = array_element_address(y, intcon(0), y_elem);
6986   // 'x_start' points to x array + scaled xlen
6987   // 'y_start' points to y array + scaled ylen
6988 
6989   Node* z_start = array_element_address(z, intcon(0), T_INT);
6990 
6991   Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
6992                                  OptoRuntime::multiplyToLen_Type(),
6993                                  stubAddr, stubName, TypePtr::BOTTOM,
6994                                  x_start, xlen, y_start, ylen, z_start);
6995 
6996   C->set_has_split_ifs(true); // Has chance for split-if optimization
6997   set_result(z);
6998   return true;
6999 }
7000 
7001 //-------------inline_squareToLen------------------------------------
7002 bool LibraryCallKit::inline_squareToLen() {
7003   assert(UseSquareToLenIntrinsic, "not implemented on this platform");
7004 
7005   address stubAddr = StubRoutines::squareToLen();
7006   if (stubAddr == nullptr) {
7007     return false; // Intrinsic's stub is not implemented on this platform
7008   }
7009   const char* stubName = "squareToLen";
7010 
7011   assert(callee()->signature()->size() == 4, "implSquareToLen has 4 parameters");
7012 
7013   Node* x    = argument(0);
7014   Node* len  = argument(1);
7015   Node* z    = argument(2);
7016   Node* zlen = argument(3);
7017 
7018   x = must_be_not_null(x, true);
7019   z = must_be_not_null(z, true);
7020 
7021   const TypeAryPtr* x_type = x->Value(&_gvn)->isa_aryptr();
7022   const TypeAryPtr* z_type = z->Value(&_gvn)->isa_aryptr();
7023   if (x_type == nullptr || x_type->elem() == Type::BOTTOM ||
7024       z_type == nullptr || z_type->elem() == Type::BOTTOM) {
7025     // failed array check
7026     return false;
7027   }
7028 
7029   BasicType x_elem = x_type->elem()->array_element_basic_type();
7030   BasicType z_elem = z_type->elem()->array_element_basic_type();
7031   if (x_elem != T_INT || z_elem != T_INT) {
7032     return false;
7033   }
7034 
7035 
7036   Node* x_start = array_element_address(x, intcon(0), x_elem);
7037   Node* z_start = array_element_address(z, intcon(0), z_elem);
7038 
7039   Node*  call = make_runtime_call(RC_LEAF|RC_NO_FP,
7040                                   OptoRuntime::squareToLen_Type(),
7041                                   stubAddr, stubName, TypePtr::BOTTOM,
7042                                   x_start, len, z_start, zlen);
7043 
7044   set_result(z);
7045   return true;
7046 }
7047 
7048 //-------------inline_mulAdd------------------------------------------
7049 bool LibraryCallKit::inline_mulAdd() {
7050   assert(UseMulAddIntrinsic, "not implemented on this platform");
7051 
7052   address stubAddr = StubRoutines::mulAdd();
7053   if (stubAddr == nullptr) {
7054     return false; // Intrinsic's stub is not implemented on this platform
7055   }
7056   const char* stubName = "mulAdd";
7057 
7058   assert(callee()->signature()->size() == 5, "mulAdd has 5 parameters");
7059 
7060   Node* out      = argument(0);
7061   Node* in       = argument(1);
7062   Node* offset   = argument(2);
7063   Node* len      = argument(3);
7064   Node* k        = argument(4);
7065 
7066   in = must_be_not_null(in, true);
7067   out = must_be_not_null(out, true);
7068 
7069   const TypeAryPtr* out_type = out->Value(&_gvn)->isa_aryptr();
7070   const TypeAryPtr* in_type = in->Value(&_gvn)->isa_aryptr();
7071   if (out_type == nullptr || out_type->elem() == Type::BOTTOM ||
7072        in_type == nullptr ||  in_type->elem() == Type::BOTTOM) {
7073     // failed array check
7074     return false;
7075   }
7076 
7077   BasicType out_elem = out_type->elem()->array_element_basic_type();
7078   BasicType in_elem = in_type->elem()->array_element_basic_type();
7079   if (out_elem != T_INT || in_elem != T_INT) {
7080     return false;
7081   }
7082 
7083   Node* outlen = load_array_length(out);
7084   Node* new_offset = _gvn.transform(new SubINode(outlen, offset));
7085   Node* out_start = array_element_address(out, intcon(0), out_elem);
7086   Node* in_start = array_element_address(in, intcon(0), in_elem);
7087 
7088   Node*  call = make_runtime_call(RC_LEAF|RC_NO_FP,
7089                                   OptoRuntime::mulAdd_Type(),
7090                                   stubAddr, stubName, TypePtr::BOTTOM,
7091                                   out_start,in_start, new_offset, len, k);
7092   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7093   set_result(result);
7094   return true;
7095 }
7096 
7097 //-------------inline_montgomeryMultiply-----------------------------------
7098 bool LibraryCallKit::inline_montgomeryMultiply() {
7099   address stubAddr = StubRoutines::montgomeryMultiply();
7100   if (stubAddr == nullptr) {
7101     return false; // Intrinsic's stub is not implemented on this platform
7102   }
7103 
7104   assert(UseMontgomeryMultiplyIntrinsic, "not implemented on this platform");
7105   const char* stubName = "montgomery_multiply";
7106 
7107   assert(callee()->signature()->size() == 7, "montgomeryMultiply has 7 parameters");
7108 
7109   Node* a    = argument(0);
7110   Node* b    = argument(1);
7111   Node* n    = argument(2);
7112   Node* len  = argument(3);
7113   Node* inv  = argument(4);
7114   Node* m    = argument(6);
7115 
7116   const TypeAryPtr* a_type = a->Value(&_gvn)->isa_aryptr();
7117   const TypeAryPtr* b_type = b->Value(&_gvn)->isa_aryptr();
7118   const TypeAryPtr* n_type = n->Value(&_gvn)->isa_aryptr();
7119   const TypeAryPtr* m_type = m->Value(&_gvn)->isa_aryptr();
7120   if (a_type == nullptr || a_type->elem() == Type::BOTTOM ||
7121       b_type == nullptr || b_type->elem() == Type::BOTTOM ||
7122       n_type == nullptr || n_type->elem() == Type::BOTTOM ||
7123       m_type == nullptr || m_type->elem() == Type::BOTTOM) {
7124     // failed array check
7125     return false;
7126   }
7127 
7128   BasicType a_elem = a_type->elem()->array_element_basic_type();
7129   BasicType b_elem = b_type->elem()->array_element_basic_type();
7130   BasicType n_elem = n_type->elem()->array_element_basic_type();
7131   BasicType m_elem = m_type->elem()->array_element_basic_type();
7132   if (a_elem != T_INT || b_elem != T_INT || n_elem != T_INT || m_elem != T_INT) {
7133     return false;
7134   }
7135 
7136   // Make the call
7137   {
7138     Node* a_start = array_element_address(a, intcon(0), a_elem);
7139     Node* b_start = array_element_address(b, intcon(0), b_elem);
7140     Node* n_start = array_element_address(n, intcon(0), n_elem);
7141     Node* m_start = array_element_address(m, intcon(0), m_elem);
7142 
7143     Node* call = make_runtime_call(RC_LEAF,
7144                                    OptoRuntime::montgomeryMultiply_Type(),
7145                                    stubAddr, stubName, TypePtr::BOTTOM,
7146                                    a_start, b_start, n_start, len, inv, top(),
7147                                    m_start);
7148     set_result(m);
7149   }
7150 
7151   return true;
7152 }
7153 
7154 bool LibraryCallKit::inline_montgomerySquare() {
7155   address stubAddr = StubRoutines::montgomerySquare();
7156   if (stubAddr == nullptr) {
7157     return false; // Intrinsic's stub is not implemented on this platform
7158   }
7159 
7160   assert(UseMontgomerySquareIntrinsic, "not implemented on this platform");
7161   const char* stubName = "montgomery_square";
7162 
7163   assert(callee()->signature()->size() == 6, "montgomerySquare has 6 parameters");
7164 
7165   Node* a    = argument(0);
7166   Node* n    = argument(1);
7167   Node* len  = argument(2);
7168   Node* inv  = argument(3);
7169   Node* m    = argument(5);
7170 
7171   const TypeAryPtr* a_type = a->Value(&_gvn)->isa_aryptr();
7172   const TypeAryPtr* n_type = n->Value(&_gvn)->isa_aryptr();
7173   const TypeAryPtr* m_type = m->Value(&_gvn)->isa_aryptr();
7174   if (a_type == nullptr || a_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 n_elem = n_type->elem()->array_element_basic_type();
7183   BasicType m_elem = m_type->elem()->array_element_basic_type();
7184   if (a_elem != T_INT || n_elem != T_INT || m_elem != T_INT) {
7185     return false;
7186   }
7187 
7188   // Make the call
7189   {
7190     Node* a_start = array_element_address(a, intcon(0), a_elem);
7191     Node* n_start = array_element_address(n, intcon(0), n_elem);
7192     Node* m_start = array_element_address(m, intcon(0), m_elem);
7193 
7194     Node* call = make_runtime_call(RC_LEAF,
7195                                    OptoRuntime::montgomerySquare_Type(),
7196                                    stubAddr, stubName, TypePtr::BOTTOM,
7197                                    a_start, n_start, len, inv, top(),
7198                                    m_start);
7199     set_result(m);
7200   }
7201 
7202   return true;
7203 }
7204 
7205 bool LibraryCallKit::inline_bigIntegerShift(bool isRightShift) {
7206   address stubAddr = nullptr;
7207   const char* stubName = nullptr;
7208 
7209   stubAddr = isRightShift? StubRoutines::bigIntegerRightShift(): StubRoutines::bigIntegerLeftShift();
7210   if (stubAddr == nullptr) {
7211     return false; // Intrinsic's stub is not implemented on this platform
7212   }
7213 
7214   stubName = isRightShift? "bigIntegerRightShiftWorker" : "bigIntegerLeftShiftWorker";
7215 
7216   assert(callee()->signature()->size() == 5, "expected 5 arguments");
7217 
7218   Node* newArr = argument(0);
7219   Node* oldArr = argument(1);
7220   Node* newIdx = argument(2);
7221   Node* shiftCount = argument(3);
7222   Node* numIter = argument(4);
7223 
7224   const TypeAryPtr* newArr_type = newArr->Value(&_gvn)->isa_aryptr();
7225   const TypeAryPtr* oldArr_type = oldArr->Value(&_gvn)->isa_aryptr();
7226   if (newArr_type == nullptr || newArr_type->elem() == Type::BOTTOM ||
7227       oldArr_type == nullptr || oldArr_type->elem() == Type::BOTTOM) {
7228     return false;
7229   }
7230 
7231   BasicType newArr_elem = newArr_type->elem()->array_element_basic_type();
7232   BasicType oldArr_elem = oldArr_type->elem()->array_element_basic_type();
7233   if (newArr_elem != T_INT || oldArr_elem != T_INT) {
7234     return false;
7235   }
7236 
7237   // Make the call
7238   {
7239     Node* newArr_start = array_element_address(newArr, intcon(0), newArr_elem);
7240     Node* oldArr_start = array_element_address(oldArr, intcon(0), oldArr_elem);
7241 
7242     Node* call = make_runtime_call(RC_LEAF,
7243                                    OptoRuntime::bigIntegerShift_Type(),
7244                                    stubAddr,
7245                                    stubName,
7246                                    TypePtr::BOTTOM,
7247                                    newArr_start,
7248                                    oldArr_start,
7249                                    newIdx,
7250                                    shiftCount,
7251                                    numIter);
7252   }
7253 
7254   return true;
7255 }
7256 
7257 //-------------inline_vectorizedMismatch------------------------------
7258 bool LibraryCallKit::inline_vectorizedMismatch() {
7259   assert(UseVectorizedMismatchIntrinsic, "not implemented on this platform");
7260 
7261   assert(callee()->signature()->size() == 8, "vectorizedMismatch has 6 parameters");
7262   Node* obja    = argument(0); // Object
7263   Node* aoffset = argument(1); // long
7264   Node* objb    = argument(3); // Object
7265   Node* boffset = argument(4); // long
7266   Node* length  = argument(6); // int
7267   Node* scale   = argument(7); // int
7268 
7269   const TypeAryPtr* obja_t = _gvn.type(obja)->isa_aryptr();
7270   const TypeAryPtr* objb_t = _gvn.type(objb)->isa_aryptr();
7271   if (obja_t == nullptr || obja_t->elem() == Type::BOTTOM ||
7272       objb_t == nullptr || objb_t->elem() == Type::BOTTOM ||
7273       scale == top()) {
7274     return false; // failed input validation
7275   }
7276 
7277   Node* obja_adr = make_unsafe_address(obja, aoffset);
7278   Node* objb_adr = make_unsafe_address(objb, boffset);
7279 
7280   // Partial inlining handling for inputs smaller than ArrayOperationPartialInlineSize bytes in size.
7281   //
7282   //    inline_limit = ArrayOperationPartialInlineSize / element_size;
7283   //    if (length <= inline_limit) {
7284   //      inline_path:
7285   //        vmask   = VectorMaskGen length
7286   //        vload1  = LoadVectorMasked obja, vmask
7287   //        vload2  = LoadVectorMasked objb, vmask
7288   //        result1 = VectorCmpMasked vload1, vload2, vmask
7289   //    } else {
7290   //      call_stub_path:
7291   //        result2 = call vectorizedMismatch_stub(obja, objb, length, scale)
7292   //    }
7293   //    exit_block:
7294   //      return Phi(result1, result2);
7295   //
7296   enum { inline_path = 1,  // input is small enough to process it all at once
7297          stub_path   = 2,  // input is too large; call into the VM
7298          PATH_LIMIT  = 3
7299   };
7300 
7301   Node* exit_block = new RegionNode(PATH_LIMIT);
7302   Node* result_phi = new PhiNode(exit_block, TypeInt::INT);
7303   Node* memory_phi = new PhiNode(exit_block, Type::MEMORY, TypePtr::BOTTOM);
7304 
7305   Node* call_stub_path = control();
7306 
7307   BasicType elem_bt = T_ILLEGAL;
7308 
7309   const TypeInt* scale_t = _gvn.type(scale)->is_int();
7310   if (scale_t->is_con()) {
7311     switch (scale_t->get_con()) {
7312       case 0: elem_bt = T_BYTE;  break;
7313       case 1: elem_bt = T_SHORT; break;
7314       case 2: elem_bt = T_INT;   break;
7315       case 3: elem_bt = T_LONG;  break;
7316 
7317       default: elem_bt = T_ILLEGAL; break; // not supported
7318     }
7319   }
7320 
7321   int inline_limit = 0;
7322   bool do_partial_inline = false;
7323 
7324   if (elem_bt != T_ILLEGAL && ArrayOperationPartialInlineSize > 0) {
7325     inline_limit = ArrayOperationPartialInlineSize / type2aelembytes(elem_bt);
7326     do_partial_inline = inline_limit >= 16;
7327   }
7328 
7329   if (do_partial_inline) {
7330     assert(elem_bt != T_ILLEGAL, "sanity");
7331 
7332     if (Matcher::match_rule_supported_vector(Op_VectorMaskGen,    inline_limit, elem_bt) &&
7333         Matcher::match_rule_supported_vector(Op_LoadVectorMasked, inline_limit, elem_bt) &&
7334         Matcher::match_rule_supported_vector(Op_VectorCmpMasked,  inline_limit, elem_bt)) {
7335 
7336       const TypeVect* vt = TypeVect::make(elem_bt, inline_limit);
7337       Node* cmp_length = _gvn.transform(new CmpINode(length, intcon(inline_limit)));
7338       Node* bol_gt     = _gvn.transform(new BoolNode(cmp_length, BoolTest::gt));
7339 
7340       call_stub_path = generate_guard(bol_gt, nullptr, PROB_MIN);
7341 
7342       if (!stopped()) {
7343         Node* casted_length = _gvn.transform(new CastIINode(control(), length, TypeInt::make(0, inline_limit, Type::WidenMin)));
7344 
7345         const TypePtr* obja_adr_t = _gvn.type(obja_adr)->isa_ptr();
7346         const TypePtr* objb_adr_t = _gvn.type(objb_adr)->isa_ptr();
7347         Node* obja_adr_mem = memory(C->get_alias_index(obja_adr_t));
7348         Node* objb_adr_mem = memory(C->get_alias_index(objb_adr_t));
7349 
7350         Node* vmask      = _gvn.transform(VectorMaskGenNode::make(ConvI2X(casted_length), elem_bt));
7351         Node* vload_obja = _gvn.transform(new LoadVectorMaskedNode(control(), obja_adr_mem, obja_adr, obja_adr_t, vt, vmask));
7352         Node* vload_objb = _gvn.transform(new LoadVectorMaskedNode(control(), objb_adr_mem, objb_adr, objb_adr_t, vt, vmask));
7353         Node* result     = _gvn.transform(new VectorCmpMaskedNode(vload_obja, vload_objb, vmask, TypeInt::INT));
7354 
7355         exit_block->init_req(inline_path, control());
7356         memory_phi->init_req(inline_path, map()->memory());
7357         result_phi->init_req(inline_path, result);
7358 
7359         C->set_max_vector_size(MAX2((uint)ArrayOperationPartialInlineSize, C->max_vector_size()));
7360         clear_upper_avx();
7361       }
7362     }
7363   }
7364 
7365   if (call_stub_path != nullptr) {
7366     set_control(call_stub_path);
7367 
7368     Node* call = make_runtime_call(RC_LEAF,
7369                                    OptoRuntime::vectorizedMismatch_Type(),
7370                                    StubRoutines::vectorizedMismatch(), "vectorizedMismatch", TypePtr::BOTTOM,
7371                                    obja_adr, objb_adr, length, scale);
7372 
7373     exit_block->init_req(stub_path, control());
7374     memory_phi->init_req(stub_path, map()->memory());
7375     result_phi->init_req(stub_path, _gvn.transform(new ProjNode(call, TypeFunc::Parms)));
7376   }
7377 
7378   exit_block = _gvn.transform(exit_block);
7379   memory_phi = _gvn.transform(memory_phi);
7380   result_phi = _gvn.transform(result_phi);
7381 
7382   record_for_igvn(exit_block);
7383   record_for_igvn(memory_phi);
7384   record_for_igvn(result_phi);
7385 
7386   set_control(exit_block);
7387   set_all_memory(memory_phi);
7388   set_result(result_phi);
7389 
7390   return true;
7391 }
7392 
7393 //------------------------------inline_vectorizedHashcode----------------------------
7394 bool LibraryCallKit::inline_vectorizedHashCode() {
7395   assert(UseVectorizedHashCodeIntrinsic, "not implemented on this platform");
7396 
7397   assert(callee()->signature()->size() == 5, "vectorizedHashCode has 5 parameters");
7398   Node* array          = argument(0);
7399   Node* offset         = argument(1);
7400   Node* length         = argument(2);
7401   Node* initialValue   = argument(3);
7402   Node* basic_type     = argument(4);
7403 
7404   if (basic_type == top()) {
7405     return false; // failed input validation
7406   }
7407 
7408   const TypeInt* basic_type_t = _gvn.type(basic_type)->is_int();
7409   if (!basic_type_t->is_con()) {
7410     return false; // Only intrinsify if mode argument is constant
7411   }
7412 
7413   array = must_be_not_null(array, true);
7414 
7415   BasicType bt = (BasicType)basic_type_t->get_con();
7416 
7417   // Resolve address of first element
7418   Node* array_start = array_element_address(array, offset, bt);
7419 
7420   set_result(_gvn.transform(new VectorizedHashCodeNode(control(), memory(TypeAryPtr::get_array_body_type(bt)),
7421     array_start, length, initialValue, basic_type)));
7422   clear_upper_avx();
7423 
7424   return true;
7425 }
7426 
7427 /**
7428  * Calculate CRC32 for byte.
7429  * int java.util.zip.CRC32.update(int crc, int b)
7430  */
7431 bool LibraryCallKit::inline_updateCRC32() {
7432   assert(UseCRC32Intrinsics, "need AVX and CLMUL instructions support");
7433   assert(callee()->signature()->size() == 2, "update has 2 parameters");
7434   // no receiver since it is static method
7435   Node* crc  = argument(0); // type: int
7436   Node* b    = argument(1); // type: int
7437 
7438   /*
7439    *    int c = ~ crc;
7440    *    b = timesXtoThe32[(b ^ c) & 0xFF];
7441    *    b = b ^ (c >>> 8);
7442    *    crc = ~b;
7443    */
7444 
7445   Node* M1 = intcon(-1);
7446   crc = _gvn.transform(new XorINode(crc, M1));
7447   Node* result = _gvn.transform(new XorINode(crc, b));
7448   result = _gvn.transform(new AndINode(result, intcon(0xFF)));
7449 
7450   Node* base = makecon(TypeRawPtr::make(StubRoutines::crc_table_addr()));
7451   Node* offset = _gvn.transform(new LShiftINode(result, intcon(0x2)));
7452   Node* adr = basic_plus_adr(top(), base, ConvI2X(offset));
7453   result = make_load(control(), adr, TypeInt::INT, T_INT, MemNode::unordered);
7454 
7455   crc = _gvn.transform(new URShiftINode(crc, intcon(8)));
7456   result = _gvn.transform(new XorINode(crc, result));
7457   result = _gvn.transform(new XorINode(result, M1));
7458   set_result(result);
7459   return true;
7460 }
7461 
7462 /**
7463  * Calculate CRC32 for byte[] array.
7464  * int java.util.zip.CRC32.updateBytes(int crc, byte[] buf, int off, int len)
7465  */
7466 bool LibraryCallKit::inline_updateBytesCRC32() {
7467   assert(UseCRC32Intrinsics, "need AVX and CLMUL instructions support");
7468   assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
7469   // no receiver since it is static method
7470   Node* crc     = argument(0); // type: int
7471   Node* src     = argument(1); // type: oop
7472   Node* offset  = argument(2); // type: int
7473   Node* length  = argument(3); // type: int
7474 
7475   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7476   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
7477     // failed array check
7478     return false;
7479   }
7480 
7481   // Figure out the size and type of the elements we will be copying.
7482   BasicType src_elem = src_type->elem()->array_element_basic_type();
7483   if (src_elem != T_BYTE) {
7484     return false;
7485   }
7486 
7487   // 'src_start' points to src array + scaled offset
7488   src = must_be_not_null(src, true);
7489   Node* src_start = array_element_address(src, offset, src_elem);
7490 
7491   // We assume that range check is done by caller.
7492   // TODO: generate range check (offset+length < src.length) in debug VM.
7493 
7494   // Call the stub.
7495   address stubAddr = StubRoutines::updateBytesCRC32();
7496   const char *stubName = "updateBytesCRC32";
7497 
7498   Node* call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::updateBytesCRC32_Type(),
7499                                  stubAddr, stubName, TypePtr::BOTTOM,
7500                                  crc, src_start, length);
7501   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7502   set_result(result);
7503   return true;
7504 }
7505 
7506 /**
7507  * Calculate CRC32 for ByteBuffer.
7508  * int java.util.zip.CRC32.updateByteBuffer(int crc, long buf, int off, int len)
7509  */
7510 bool LibraryCallKit::inline_updateByteBufferCRC32() {
7511   assert(UseCRC32Intrinsics, "need AVX and CLMUL instructions support");
7512   assert(callee()->signature()->size() == 5, "updateByteBuffer has 4 parameters and one is long");
7513   // no receiver since it is static method
7514   Node* crc     = argument(0); // type: int
7515   Node* src     = argument(1); // type: long
7516   Node* offset  = argument(3); // type: int
7517   Node* length  = argument(4); // type: int
7518 
7519   src = ConvL2X(src);  // adjust Java long to machine word
7520   Node* base = _gvn.transform(new CastX2PNode(src));
7521   offset = ConvI2X(offset);
7522 
7523   // 'src_start' points to src array + scaled offset
7524   Node* src_start = basic_plus_adr(top(), base, offset);
7525 
7526   // Call the stub.
7527   address stubAddr = StubRoutines::updateBytesCRC32();
7528   const char *stubName = "updateBytesCRC32";
7529 
7530   Node* call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::updateBytesCRC32_Type(),
7531                                  stubAddr, stubName, TypePtr::BOTTOM,
7532                                  crc, src_start, length);
7533   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7534   set_result(result);
7535   return true;
7536 }
7537 
7538 //------------------------------get_table_from_crc32c_class-----------------------
7539 Node * LibraryCallKit::get_table_from_crc32c_class(ciInstanceKlass *crc32c_class) {
7540   Node* table = load_field_from_object(nullptr, "byteTable", "[I", /*decorators*/ IN_HEAP, /*is_static*/ true, crc32c_class);
7541   assert (table != nullptr, "wrong version of java.util.zip.CRC32C");
7542 
7543   return table;
7544 }
7545 
7546 //------------------------------inline_updateBytesCRC32C-----------------------
7547 //
7548 // Calculate CRC32C for byte[] array.
7549 // int java.util.zip.CRC32C.updateBytes(int crc, byte[] buf, int off, int end)
7550 //
7551 bool LibraryCallKit::inline_updateBytesCRC32C() {
7552   assert(UseCRC32CIntrinsics, "need CRC32C instruction support");
7553   assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
7554   assert(callee()->holder()->is_loaded(), "CRC32C class must be loaded");
7555   // no receiver since it is a static method
7556   Node* crc     = argument(0); // type: int
7557   Node* src     = argument(1); // type: oop
7558   Node* offset  = argument(2); // type: int
7559   Node* end     = argument(3); // type: int
7560 
7561   Node* length = _gvn.transform(new SubINode(end, offset));
7562 
7563   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7564   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
7565     // failed array check
7566     return false;
7567   }
7568 
7569   // Figure out the size and type of the elements we will be copying.
7570   BasicType src_elem = src_type->elem()->array_element_basic_type();
7571   if (src_elem != T_BYTE) {
7572     return false;
7573   }
7574 
7575   // 'src_start' points to src array + scaled offset
7576   src = must_be_not_null(src, true);
7577   Node* src_start = array_element_address(src, offset, src_elem);
7578 
7579   // static final int[] byteTable in class CRC32C
7580   Node* table = get_table_from_crc32c_class(callee()->holder());
7581   table = must_be_not_null(table, true);
7582   Node* table_start = array_element_address(table, intcon(0), T_INT);
7583 
7584   // We assume that range check is done by caller.
7585   // TODO: generate range check (offset+length < src.length) in debug VM.
7586 
7587   // Call the stub.
7588   address stubAddr = StubRoutines::updateBytesCRC32C();
7589   const char *stubName = "updateBytesCRC32C";
7590 
7591   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesCRC32C_Type(),
7592                                  stubAddr, stubName, TypePtr::BOTTOM,
7593                                  crc, src_start, length, table_start);
7594   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7595   set_result(result);
7596   return true;
7597 }
7598 
7599 //------------------------------inline_updateDirectByteBufferCRC32C-----------------------
7600 //
7601 // Calculate CRC32C for DirectByteBuffer.
7602 // int java.util.zip.CRC32C.updateDirectByteBuffer(int crc, long buf, int off, int end)
7603 //
7604 bool LibraryCallKit::inline_updateDirectByteBufferCRC32C() {
7605   assert(UseCRC32CIntrinsics, "need CRC32C instruction support");
7606   assert(callee()->signature()->size() == 5, "updateDirectByteBuffer has 4 parameters and one is long");
7607   assert(callee()->holder()->is_loaded(), "CRC32C class must be loaded");
7608   // no receiver since it is a static method
7609   Node* crc     = argument(0); // type: int
7610   Node* src     = argument(1); // type: long
7611   Node* offset  = argument(3); // type: int
7612   Node* end     = argument(4); // type: int
7613 
7614   Node* length = _gvn.transform(new SubINode(end, offset));
7615 
7616   src = ConvL2X(src);  // adjust Java long to machine word
7617   Node* base = _gvn.transform(new CastX2PNode(src));
7618   offset = ConvI2X(offset);
7619 
7620   // 'src_start' points to src array + scaled offset
7621   Node* src_start = basic_plus_adr(top(), base, offset);
7622 
7623   // static final int[] byteTable in class CRC32C
7624   Node* table = get_table_from_crc32c_class(callee()->holder());
7625   table = must_be_not_null(table, true);
7626   Node* table_start = array_element_address(table, intcon(0), T_INT);
7627 
7628   // Call the stub.
7629   address stubAddr = StubRoutines::updateBytesCRC32C();
7630   const char *stubName = "updateBytesCRC32C";
7631 
7632   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesCRC32C_Type(),
7633                                  stubAddr, stubName, TypePtr::BOTTOM,
7634                                  crc, src_start, length, table_start);
7635   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7636   set_result(result);
7637   return true;
7638 }
7639 
7640 //------------------------------inline_updateBytesAdler32----------------------
7641 //
7642 // Calculate Adler32 checksum for byte[] array.
7643 // int java.util.zip.Adler32.updateBytes(int crc, byte[] buf, int off, int len)
7644 //
7645 bool LibraryCallKit::inline_updateBytesAdler32() {
7646   assert(UseAdler32Intrinsics, "Adler32 Intrinsic support need"); // check if we actually need to check this flag or check a different one
7647   assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
7648   assert(callee()->holder()->is_loaded(), "Adler32 class must be loaded");
7649   // no receiver since it is static method
7650   Node* crc     = argument(0); // type: int
7651   Node* src     = argument(1); // type: oop
7652   Node* offset  = argument(2); // type: int
7653   Node* length  = argument(3); // type: int
7654 
7655   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7656   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
7657     // failed array check
7658     return false;
7659   }
7660 
7661   // Figure out the size and type of the elements we will be copying.
7662   BasicType src_elem = src_type->elem()->array_element_basic_type();
7663   if (src_elem != T_BYTE) {
7664     return false;
7665   }
7666 
7667   // 'src_start' points to src array + scaled offset
7668   Node* src_start = array_element_address(src, offset, src_elem);
7669 
7670   // We assume that range check is done by caller.
7671   // TODO: generate range check (offset+length < src.length) in debug VM.
7672 
7673   // Call the stub.
7674   address stubAddr = StubRoutines::updateBytesAdler32();
7675   const char *stubName = "updateBytesAdler32";
7676 
7677   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesAdler32_Type(),
7678                                  stubAddr, stubName, TypePtr::BOTTOM,
7679                                  crc, src_start, length);
7680   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7681   set_result(result);
7682   return true;
7683 }
7684 
7685 //------------------------------inline_updateByteBufferAdler32---------------
7686 //
7687 // Calculate Adler32 checksum for DirectByteBuffer.
7688 // int java.util.zip.Adler32.updateByteBuffer(int crc, long buf, int off, int len)
7689 //
7690 bool LibraryCallKit::inline_updateByteBufferAdler32() {
7691   assert(UseAdler32Intrinsics, "Adler32 Intrinsic support need"); // check if we actually need to check this flag or check a different one
7692   assert(callee()->signature()->size() == 5, "updateByteBuffer has 4 parameters and one is long");
7693   assert(callee()->holder()->is_loaded(), "Adler32 class must be loaded");
7694   // no receiver since it is static method
7695   Node* crc     = argument(0); // type: int
7696   Node* src     = argument(1); // type: long
7697   Node* offset  = argument(3); // type: int
7698   Node* length  = argument(4); // type: int
7699 
7700   src = ConvL2X(src);  // adjust Java long to machine word
7701   Node* base = _gvn.transform(new CastX2PNode(src));
7702   offset = ConvI2X(offset);
7703 
7704   // 'src_start' points to src array + scaled offset
7705   Node* src_start = basic_plus_adr(top(), base, offset);
7706 
7707   // Call the stub.
7708   address stubAddr = StubRoutines::updateBytesAdler32();
7709   const char *stubName = "updateBytesAdler32";
7710 
7711   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesAdler32_Type(),
7712                                  stubAddr, stubName, TypePtr::BOTTOM,
7713                                  crc, src_start, length);
7714 
7715   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7716   set_result(result);
7717   return true;
7718 }
7719 
7720 //----------------------------inline_reference_get0----------------------------
7721 // public T java.lang.ref.Reference.get();
7722 bool LibraryCallKit::inline_reference_get0() {
7723   const int referent_offset = java_lang_ref_Reference::referent_offset();
7724 
7725   // Get the argument:
7726   Node* reference_obj = null_check_receiver();
7727   if (stopped()) return true;
7728 
7729   DecoratorSet decorators = IN_HEAP | ON_WEAK_OOP_REF;
7730   Node* result = load_field_from_object(reference_obj, "referent", "Ljava/lang/Object;",
7731                                         decorators, /*is_static*/ false, nullptr);
7732   if (result == nullptr) return false;
7733 
7734   // Add memory barrier to prevent commoning reads from this field
7735   // across safepoint since GC can change its value.
7736   insert_mem_bar(Op_MemBarCPUOrder);
7737 
7738   set_result(result);
7739   return true;
7740 }
7741 
7742 //----------------------------inline_reference_refersTo0----------------------------
7743 // bool java.lang.ref.Reference.refersTo0();
7744 // bool java.lang.ref.PhantomReference.refersTo0();
7745 bool LibraryCallKit::inline_reference_refersTo0(bool is_phantom) {
7746   // Get arguments:
7747   Node* reference_obj = null_check_receiver();
7748   Node* other_obj = argument(1);
7749   if (stopped()) return true;
7750 
7751   DecoratorSet decorators = IN_HEAP | AS_NO_KEEPALIVE;
7752   decorators |= (is_phantom ? ON_PHANTOM_OOP_REF : ON_WEAK_OOP_REF);
7753   Node* referent = load_field_from_object(reference_obj, "referent", "Ljava/lang/Object;",
7754                                           decorators, /*is_static*/ false, nullptr);
7755   if (referent == nullptr) return false;
7756 
7757   // Add memory barrier to prevent commoning reads from this field
7758   // across safepoint since GC can change its value.
7759   insert_mem_bar(Op_MemBarCPUOrder);
7760 
7761   Node* cmp = _gvn.transform(new CmpPNode(referent, other_obj));
7762   Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
7763   IfNode* if_node = create_and_map_if(control(), bol, PROB_FAIR, COUNT_UNKNOWN);
7764 
7765   RegionNode* region = new RegionNode(3);
7766   PhiNode* phi = new PhiNode(region, TypeInt::BOOL);
7767 
7768   Node* if_true = _gvn.transform(new IfTrueNode(if_node));
7769   region->init_req(1, if_true);
7770   phi->init_req(1, intcon(1));
7771 
7772   Node* if_false = _gvn.transform(new IfFalseNode(if_node));
7773   region->init_req(2, if_false);
7774   phi->init_req(2, intcon(0));
7775 
7776   set_control(_gvn.transform(region));
7777   record_for_igvn(region);
7778   set_result(_gvn.transform(phi));
7779   return true;
7780 }
7781 
7782 //----------------------------inline_reference_clear0----------------------------
7783 // void java.lang.ref.Reference.clear0();
7784 // void java.lang.ref.PhantomReference.clear0();
7785 bool LibraryCallKit::inline_reference_clear0(bool is_phantom) {
7786   // This matches the implementation in JVM_ReferenceClear, see the comments there.
7787 
7788   // Get arguments
7789   Node* reference_obj = null_check_receiver();
7790   if (stopped()) return true;
7791 
7792   // Common access parameters
7793   DecoratorSet decorators = IN_HEAP | AS_NO_KEEPALIVE;
7794   decorators |= (is_phantom ? ON_PHANTOM_OOP_REF : ON_WEAK_OOP_REF);
7795   Node* referent_field_addr = basic_plus_adr(reference_obj, java_lang_ref_Reference::referent_offset());
7796   const TypePtr* referent_field_addr_type = _gvn.type(referent_field_addr)->isa_ptr();
7797   const Type* val_type = TypeOopPtr::make_from_klass(env()->Object_klass());
7798 
7799   Node* referent = access_load_at(reference_obj,
7800                                   referent_field_addr,
7801                                   referent_field_addr_type,
7802                                   val_type,
7803                                   T_OBJECT,
7804                                   decorators);
7805 
7806   IdealKit ideal(this);
7807 #define __ ideal.
7808   __ if_then(referent, BoolTest::ne, null());
7809     sync_kit(ideal);
7810     access_store_at(reference_obj,
7811                     referent_field_addr,
7812                     referent_field_addr_type,
7813                     null(),
7814                     val_type,
7815                     T_OBJECT,
7816                     decorators);
7817     __ sync_kit(this);
7818   __ end_if();
7819   final_sync(ideal);
7820 #undef __
7821 
7822   return true;
7823 }
7824 
7825 Node* LibraryCallKit::load_field_from_object(Node* fromObj, const char* fieldName, const char* fieldTypeString,
7826                                              DecoratorSet decorators, bool is_static,
7827                                              ciInstanceKlass* fromKls) {
7828   if (fromKls == nullptr) {
7829     const TypeInstPtr* tinst = _gvn.type(fromObj)->isa_instptr();
7830     assert(tinst != nullptr, "obj is null");
7831     assert(tinst->is_loaded(), "obj is not loaded");
7832     fromKls = tinst->instance_klass();
7833   } else {
7834     assert(is_static, "only for static field access");
7835   }
7836   ciField* field = fromKls->get_field_by_name(ciSymbol::make(fieldName),
7837                                               ciSymbol::make(fieldTypeString),
7838                                               is_static);
7839 
7840   assert(field != nullptr, "undefined field %s %s %s", fieldTypeString, fromKls->name()->as_utf8(), fieldName);
7841   if (field == nullptr) return (Node *) nullptr;
7842 
7843   if (is_static) {
7844     const TypeInstPtr* tip = TypeInstPtr::make(fromKls->java_mirror());
7845     fromObj = makecon(tip);
7846   }
7847 
7848   // Next code  copied from Parse::do_get_xxx():
7849 
7850   // Compute address and memory type.
7851   int offset  = field->offset_in_bytes();
7852   bool is_vol = field->is_volatile();
7853   ciType* field_klass = field->type();
7854   assert(field_klass->is_loaded(), "should be loaded");
7855   const TypePtr* adr_type = C->alias_type(field)->adr_type();
7856   Node *adr = basic_plus_adr(fromObj, fromObj, offset);
7857   assert(C->get_alias_index(adr_type) == C->get_alias_index(_gvn.type(adr)->isa_ptr()),
7858     "slice of address and input slice don't match");
7859   BasicType bt = field->layout_type();
7860 
7861   // Build the resultant type of the load
7862   const Type *type;
7863   if (bt == T_OBJECT) {
7864     type = TypeOopPtr::make_from_klass(field_klass->as_klass());
7865   } else {
7866     type = Type::get_const_basic_type(bt);
7867   }
7868 
7869   if (is_vol) {
7870     decorators |= MO_SEQ_CST;
7871   }
7872 
7873   return access_load_at(fromObj, adr, adr_type, type, bt, decorators);
7874 }
7875 
7876 Node * LibraryCallKit::field_address_from_object(Node * fromObj, const char * fieldName, const char * fieldTypeString,
7877                                                  bool is_exact /* true */, bool is_static /* false */,
7878                                                  ciInstanceKlass * fromKls /* nullptr */) {
7879   if (fromKls == nullptr) {
7880     const TypeInstPtr* tinst = _gvn.type(fromObj)->isa_instptr();
7881     assert(tinst != nullptr, "obj is null");
7882     assert(tinst->is_loaded(), "obj is not loaded");
7883     assert(!is_exact || tinst->klass_is_exact(), "klass not exact");
7884     fromKls = tinst->instance_klass();
7885   }
7886   else {
7887     assert(is_static, "only for static field access");
7888   }
7889   ciField* field = fromKls->get_field_by_name(ciSymbol::make(fieldName),
7890     ciSymbol::make(fieldTypeString),
7891     is_static);
7892 
7893   assert(field != nullptr, "undefined field");
7894   assert(!field->is_volatile(), "not defined for volatile fields");
7895 
7896   if (is_static) {
7897     const TypeInstPtr* tip = TypeInstPtr::make(fromKls->java_mirror());
7898     fromObj = makecon(tip);
7899   }
7900 
7901   // Next code  copied from Parse::do_get_xxx():
7902 
7903   // Compute address and memory type.
7904   int offset = field->offset_in_bytes();
7905   Node *adr = basic_plus_adr(fromObj, fromObj, offset);
7906 
7907   return adr;
7908 }
7909 
7910 //------------------------------inline_aescrypt_Block-----------------------
7911 bool LibraryCallKit::inline_aescrypt_Block(vmIntrinsics::ID id) {
7912   address stubAddr = nullptr;
7913   const char *stubName;
7914   bool is_decrypt = false;
7915   assert(UseAES, "need AES instruction support");
7916 
7917   switch(id) {
7918   case vmIntrinsics::_aescrypt_encryptBlock:
7919     stubAddr = StubRoutines::aescrypt_encryptBlock();
7920     stubName = "aescrypt_encryptBlock";
7921     break;
7922   case vmIntrinsics::_aescrypt_decryptBlock:
7923     stubAddr = StubRoutines::aescrypt_decryptBlock();
7924     stubName = "aescrypt_decryptBlock";
7925     is_decrypt = true;
7926     break;
7927   default:
7928     break;
7929   }
7930   if (stubAddr == nullptr) return false;
7931 
7932   Node* aescrypt_object = argument(0);
7933   Node* src             = argument(1);
7934   Node* src_offset      = argument(2);
7935   Node* dest            = argument(3);
7936   Node* dest_offset     = argument(4);
7937 
7938   src = must_be_not_null(src, true);
7939   dest = must_be_not_null(dest, true);
7940 
7941   // (1) src and dest are arrays.
7942   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7943   const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
7944   assert( src_type != nullptr &&  src_type->elem() != Type::BOTTOM &&
7945          dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
7946 
7947   // for the quick and dirty code we will skip all the checks.
7948   // we are just trying to get the call to be generated.
7949   Node* src_start  = src;
7950   Node* dest_start = dest;
7951   if (src_offset != nullptr || dest_offset != nullptr) {
7952     assert(src_offset != nullptr && dest_offset != nullptr, "");
7953     src_start  = array_element_address(src,  src_offset,  T_BYTE);
7954     dest_start = array_element_address(dest, dest_offset, T_BYTE);
7955   }
7956 
7957   // now need to get the start of its expanded key array
7958   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
7959   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object, is_decrypt);
7960   if (k_start == nullptr) return false;
7961 
7962   // Call the stub.
7963   make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::aescrypt_block_Type(),
7964                     stubAddr, stubName, TypePtr::BOTTOM,
7965                     src_start, dest_start, k_start);
7966 
7967   return true;
7968 }
7969 
7970 //------------------------------inline_cipherBlockChaining_AESCrypt-----------------------
7971 bool LibraryCallKit::inline_cipherBlockChaining_AESCrypt(vmIntrinsics::ID id) {
7972   address stubAddr = nullptr;
7973   const char *stubName = nullptr;
7974   bool is_decrypt = false;
7975   assert(UseAES, "need AES instruction support");
7976 
7977   switch(id) {
7978   case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
7979     stubAddr = StubRoutines::cipherBlockChaining_encryptAESCrypt();
7980     stubName = "cipherBlockChaining_encryptAESCrypt";
7981     break;
7982   case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
7983     stubAddr = StubRoutines::cipherBlockChaining_decryptAESCrypt();
7984     stubName = "cipherBlockChaining_decryptAESCrypt";
7985     is_decrypt = true;
7986     break;
7987   default:
7988     break;
7989   }
7990   if (stubAddr == nullptr) return false;
7991 
7992   Node* cipherBlockChaining_object = argument(0);
7993   Node* src                        = argument(1);
7994   Node* src_offset                 = argument(2);
7995   Node* len                        = argument(3);
7996   Node* dest                       = argument(4);
7997   Node* dest_offset                = argument(5);
7998 
7999   src = must_be_not_null(src, false);
8000   dest = must_be_not_null(dest, false);
8001 
8002   // (1) src and dest are arrays.
8003   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
8004   const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
8005   assert( src_type != nullptr &&  src_type->elem() != Type::BOTTOM &&
8006          dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
8007 
8008   // checks are the responsibility of the caller
8009   Node* src_start  = src;
8010   Node* dest_start = dest;
8011   if (src_offset != nullptr || dest_offset != nullptr) {
8012     assert(src_offset != nullptr && dest_offset != nullptr, "");
8013     src_start  = array_element_address(src,  src_offset,  T_BYTE);
8014     dest_start = array_element_address(dest, dest_offset, T_BYTE);
8015   }
8016 
8017   // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
8018   // (because of the predicated logic executed earlier).
8019   // so we cast it here safely.
8020   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
8021 
8022   Node* embeddedCipherObj = load_field_from_object(cipherBlockChaining_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8023   if (embeddedCipherObj == nullptr) return false;
8024 
8025   // cast it to what we know it will be at runtime
8026   const TypeInstPtr* tinst = _gvn.type(cipherBlockChaining_object)->isa_instptr();
8027   assert(tinst != nullptr, "CBC obj is null");
8028   assert(tinst->is_loaded(), "CBC obj is not loaded");
8029   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8030   assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
8031 
8032   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8033   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
8034   const TypeOopPtr* xtype = aklass->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
8035   Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
8036   aescrypt_object = _gvn.transform(aescrypt_object);
8037 
8038   // we need to get the start of the aescrypt_object's expanded key array
8039   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object, is_decrypt);
8040   if (k_start == nullptr) return false;
8041 
8042   // similarly, get the start address of the r vector
8043   Node* objRvec = load_field_from_object(cipherBlockChaining_object, "r", "[B");
8044   if (objRvec == nullptr) return false;
8045   Node* r_start = array_element_address(objRvec, intcon(0), T_BYTE);
8046 
8047   // Call the stub, passing src_start, dest_start, k_start, r_start and src_len
8048   Node* cbcCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
8049                                      OptoRuntime::cipherBlockChaining_aescrypt_Type(),
8050                                      stubAddr, stubName, TypePtr::BOTTOM,
8051                                      src_start, dest_start, k_start, r_start, len);
8052 
8053   // return cipher length (int)
8054   Node* retvalue = _gvn.transform(new ProjNode(cbcCrypt, TypeFunc::Parms));
8055   set_result(retvalue);
8056   return true;
8057 }
8058 
8059 //------------------------------inline_electronicCodeBook_AESCrypt-----------------------
8060 bool LibraryCallKit::inline_electronicCodeBook_AESCrypt(vmIntrinsics::ID id) {
8061   address stubAddr = nullptr;
8062   const char *stubName = nullptr;
8063   bool is_decrypt = false;
8064   assert(UseAES, "need AES instruction support");
8065 
8066   switch (id) {
8067   case vmIntrinsics::_electronicCodeBook_encryptAESCrypt:
8068     stubAddr = StubRoutines::electronicCodeBook_encryptAESCrypt();
8069     stubName = "electronicCodeBook_encryptAESCrypt";
8070     break;
8071   case vmIntrinsics::_electronicCodeBook_decryptAESCrypt:
8072     stubAddr = StubRoutines::electronicCodeBook_decryptAESCrypt();
8073     stubName = "electronicCodeBook_decryptAESCrypt";
8074     is_decrypt = true;
8075     break;
8076   default:
8077     break;
8078   }
8079 
8080   if (stubAddr == nullptr) return false;
8081 
8082   Node* electronicCodeBook_object = argument(0);
8083   Node* src                       = argument(1);
8084   Node* src_offset                = argument(2);
8085   Node* len                       = argument(3);
8086   Node* dest                      = argument(4);
8087   Node* dest_offset               = argument(5);
8088 
8089   // (1) src and dest are arrays.
8090   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
8091   const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
8092   assert( src_type != nullptr &&  src_type->elem() != Type::BOTTOM &&
8093          dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
8094 
8095   // checks are the responsibility of the caller
8096   Node* src_start = src;
8097   Node* dest_start = dest;
8098   if (src_offset != nullptr || dest_offset != nullptr) {
8099     assert(src_offset != nullptr && dest_offset != nullptr, "");
8100     src_start = array_element_address(src, src_offset, T_BYTE);
8101     dest_start = array_element_address(dest, dest_offset, T_BYTE);
8102   }
8103 
8104   // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
8105   // (because of the predicated logic executed earlier).
8106   // so we cast it here safely.
8107   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
8108 
8109   Node* embeddedCipherObj = load_field_from_object(electronicCodeBook_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8110   if (embeddedCipherObj == nullptr) return false;
8111 
8112   // cast it to what we know it will be at runtime
8113   const TypeInstPtr* tinst = _gvn.type(electronicCodeBook_object)->isa_instptr();
8114   assert(tinst != nullptr, "ECB obj is null");
8115   assert(tinst->is_loaded(), "ECB obj is not loaded");
8116   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8117   assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
8118 
8119   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8120   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
8121   const TypeOopPtr* xtype = aklass->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
8122   Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
8123   aescrypt_object = _gvn.transform(aescrypt_object);
8124 
8125   // we need to get the start of the aescrypt_object's expanded key array
8126   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object, is_decrypt);
8127   if (k_start == nullptr) return false;
8128 
8129   // Call the stub, passing src_start, dest_start, k_start, r_start and src_len
8130   Node* ecbCrypt = make_runtime_call(RC_LEAF | RC_NO_FP,
8131                                      OptoRuntime::electronicCodeBook_aescrypt_Type(),
8132                                      stubAddr, stubName, TypePtr::BOTTOM,
8133                                      src_start, dest_start, k_start, len);
8134 
8135   // return cipher length (int)
8136   Node* retvalue = _gvn.transform(new ProjNode(ecbCrypt, TypeFunc::Parms));
8137   set_result(retvalue);
8138   return true;
8139 }
8140 
8141 //------------------------------inline_counterMode_AESCrypt-----------------------
8142 bool LibraryCallKit::inline_counterMode_AESCrypt(vmIntrinsics::ID id) {
8143   assert(UseAES, "need AES instruction support");
8144   if (!UseAESCTRIntrinsics) return false;
8145 
8146   address stubAddr = nullptr;
8147   const char *stubName = nullptr;
8148   if (id == vmIntrinsics::_counterMode_AESCrypt) {
8149     stubAddr = StubRoutines::counterMode_AESCrypt();
8150     stubName = "counterMode_AESCrypt";
8151   }
8152   if (stubAddr == nullptr) return false;
8153 
8154   Node* counterMode_object = argument(0);
8155   Node* src = argument(1);
8156   Node* src_offset = argument(2);
8157   Node* len = argument(3);
8158   Node* dest = argument(4);
8159   Node* dest_offset = argument(5);
8160 
8161   // (1) src and dest are arrays.
8162   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
8163   const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
8164   assert( src_type != nullptr &&  src_type->elem() != Type::BOTTOM &&
8165          dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
8166 
8167   // checks are the responsibility of the caller
8168   Node* src_start = src;
8169   Node* dest_start = dest;
8170   if (src_offset != nullptr || dest_offset != nullptr) {
8171     assert(src_offset != nullptr && dest_offset != nullptr, "");
8172     src_start = array_element_address(src, src_offset, T_BYTE);
8173     dest_start = array_element_address(dest, dest_offset, T_BYTE);
8174   }
8175 
8176   // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
8177   // (because of the predicated logic executed earlier).
8178   // so we cast it here safely.
8179   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
8180   Node* embeddedCipherObj = load_field_from_object(counterMode_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8181   if (embeddedCipherObj == nullptr) return false;
8182   // cast it to what we know it will be at runtime
8183   const TypeInstPtr* tinst = _gvn.type(counterMode_object)->isa_instptr();
8184   assert(tinst != nullptr, "CTR obj is null");
8185   assert(tinst->is_loaded(), "CTR obj is not loaded");
8186   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8187   assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
8188   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8189   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
8190   const TypeOopPtr* xtype = aklass->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
8191   Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
8192   aescrypt_object = _gvn.transform(aescrypt_object);
8193   // we need to get the start of the aescrypt_object's expanded key array
8194   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object, /* is_decrypt */ false);
8195   if (k_start == nullptr) return false;
8196   // similarly, get the start address of the r vector
8197   Node* obj_counter = load_field_from_object(counterMode_object, "counter", "[B");
8198   if (obj_counter == nullptr) return false;
8199   Node* cnt_start = array_element_address(obj_counter, intcon(0), T_BYTE);
8200 
8201   Node* saved_encCounter = load_field_from_object(counterMode_object, "encryptedCounter", "[B");
8202   if (saved_encCounter == nullptr) return false;
8203   Node* saved_encCounter_start = array_element_address(saved_encCounter, intcon(0), T_BYTE);
8204   Node* used = field_address_from_object(counterMode_object, "used", "I", /*is_exact*/ false);
8205 
8206   // Call the stub, passing src_start, dest_start, k_start, r_start and src_len
8207   Node* ctrCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
8208                                      OptoRuntime::counterMode_aescrypt_Type(),
8209                                      stubAddr, stubName, TypePtr::BOTTOM,
8210                                      src_start, dest_start, k_start, cnt_start, len, saved_encCounter_start, used);
8211 
8212   // return cipher length (int)
8213   Node* retvalue = _gvn.transform(new ProjNode(ctrCrypt, TypeFunc::Parms));
8214   set_result(retvalue);
8215   return true;
8216 }
8217 
8218 //------------------------------get_key_start_from_aescrypt_object-----------------------
8219 Node* LibraryCallKit::get_key_start_from_aescrypt_object(Node* aescrypt_object, bool is_decrypt) {
8220   // MixColumns for decryption can be reduced by preprocessing MixColumns with round keys.
8221   // Intel's extension is based on this optimization and AESCrypt generates round keys by preprocessing MixColumns.
8222   // However, ppc64 vncipher processes MixColumns and requires the same round keys with encryption.
8223   // The following platform specific stubs of encryption and decryption use the same round keys.
8224 #if defined(PPC64) || defined(S390) || defined(RISCV64)
8225   bool use_decryption_key = false;
8226 #else
8227   bool use_decryption_key = is_decrypt;
8228 #endif
8229   Node* objAESCryptKey = load_field_from_object(aescrypt_object, use_decryption_key ? "sessionKd" : "sessionKe", "[I");
8230   assert(objAESCryptKey != nullptr, "wrong version of com.sun.crypto.provider.AES_Crypt");
8231   if (objAESCryptKey == nullptr) return (Node *) nullptr;
8232 
8233   // now have the array, need to get the start address of the selected key array
8234   Node* k_start = array_element_address(objAESCryptKey, intcon(0), T_INT);
8235   return k_start;
8236 }
8237 
8238 //----------------------------inline_cipherBlockChaining_AESCrypt_predicate----------------------------
8239 // Return node representing slow path of predicate check.
8240 // the pseudo code we want to emulate with this predicate is:
8241 // for encryption:
8242 //    if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
8243 // for decryption:
8244 //    if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
8245 //    note cipher==plain is more conservative than the original java code but that's OK
8246 //
8247 Node* LibraryCallKit::inline_cipherBlockChaining_AESCrypt_predicate(bool decrypting) {
8248   // The receiver was checked for null already.
8249   Node* objCBC = argument(0);
8250 
8251   Node* src = argument(1);
8252   Node* dest = argument(4);
8253 
8254   // Load embeddedCipher field of CipherBlockChaining object.
8255   Node* embeddedCipherObj = load_field_from_object(objCBC, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8256 
8257   // get AESCrypt klass for instanceOf check
8258   // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
8259   // will have same classloader as CipherBlockChaining object
8260   const TypeInstPtr* tinst = _gvn.type(objCBC)->isa_instptr();
8261   assert(tinst != nullptr, "CBCobj is null");
8262   assert(tinst->is_loaded(), "CBCobj is not loaded");
8263 
8264   // we want to do an instanceof comparison against the AESCrypt class
8265   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8266   if (!klass_AESCrypt->is_loaded()) {
8267     // if AESCrypt is not even loaded, we never take the intrinsic fast path
8268     Node* ctrl = control();
8269     set_control(top()); // no regular fast path
8270     return ctrl;
8271   }
8272 
8273   src = must_be_not_null(src, true);
8274   dest = must_be_not_null(dest, true);
8275 
8276   // Resolve oops to stable for CmpP below.
8277   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8278 
8279   Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
8280   Node* cmp_instof  = _gvn.transform(new CmpINode(instof, intcon(1)));
8281   Node* bool_instof  = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
8282 
8283   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
8284 
8285   // for encryption, we are done
8286   if (!decrypting)
8287     return instof_false;  // even if it is null
8288 
8289   // for decryption, we need to add a further check to avoid
8290   // taking the intrinsic path when cipher and plain are the same
8291   // see the original java code for why.
8292   RegionNode* region = new RegionNode(3);
8293   region->init_req(1, instof_false);
8294 
8295   Node* cmp_src_dest = _gvn.transform(new CmpPNode(src, dest));
8296   Node* bool_src_dest = _gvn.transform(new BoolNode(cmp_src_dest, BoolTest::eq));
8297   Node* src_dest_conjoint = generate_guard(bool_src_dest, nullptr, PROB_MIN);
8298   region->init_req(2, src_dest_conjoint);
8299 
8300   record_for_igvn(region);
8301   return _gvn.transform(region);
8302 }
8303 
8304 //----------------------------inline_electronicCodeBook_AESCrypt_predicate----------------------------
8305 // Return node representing slow path of predicate check.
8306 // the pseudo code we want to emulate with this predicate is:
8307 // for encryption:
8308 //    if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
8309 // for decryption:
8310 //    if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
8311 //    note cipher==plain is more conservative than the original java code but that's OK
8312 //
8313 Node* LibraryCallKit::inline_electronicCodeBook_AESCrypt_predicate(bool decrypting) {
8314   // The receiver was checked for null already.
8315   Node* objECB = argument(0);
8316 
8317   // Load embeddedCipher field of ElectronicCodeBook object.
8318   Node* embeddedCipherObj = load_field_from_object(objECB, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8319 
8320   // get AESCrypt klass for instanceOf check
8321   // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
8322   // will have same classloader as ElectronicCodeBook object
8323   const TypeInstPtr* tinst = _gvn.type(objECB)->isa_instptr();
8324   assert(tinst != nullptr, "ECBobj is null");
8325   assert(tinst->is_loaded(), "ECBobj is not loaded");
8326 
8327   // we want to do an instanceof comparison against the AESCrypt class
8328   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8329   if (!klass_AESCrypt->is_loaded()) {
8330     // if AESCrypt is not even loaded, we never take the intrinsic fast path
8331     Node* ctrl = control();
8332     set_control(top()); // no regular fast path
8333     return ctrl;
8334   }
8335   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8336 
8337   Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
8338   Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
8339   Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
8340 
8341   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
8342 
8343   // for encryption, we are done
8344   if (!decrypting)
8345     return instof_false;  // even if it is null
8346 
8347   // for decryption, we need to add a further check to avoid
8348   // taking the intrinsic path when cipher and plain are the same
8349   // see the original java code for why.
8350   RegionNode* region = new RegionNode(3);
8351   region->init_req(1, instof_false);
8352   Node* src = argument(1);
8353   Node* dest = argument(4);
8354   Node* cmp_src_dest = _gvn.transform(new CmpPNode(src, dest));
8355   Node* bool_src_dest = _gvn.transform(new BoolNode(cmp_src_dest, BoolTest::eq));
8356   Node* src_dest_conjoint = generate_guard(bool_src_dest, nullptr, PROB_MIN);
8357   region->init_req(2, src_dest_conjoint);
8358 
8359   record_for_igvn(region);
8360   return _gvn.transform(region);
8361 }
8362 
8363 //----------------------------inline_counterMode_AESCrypt_predicate----------------------------
8364 // Return node representing slow path of predicate check.
8365 // the pseudo code we want to emulate with this predicate is:
8366 // for encryption:
8367 //    if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
8368 // for decryption:
8369 //    if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
8370 //    note cipher==plain is more conservative than the original java code but that's OK
8371 //
8372 
8373 Node* LibraryCallKit::inline_counterMode_AESCrypt_predicate() {
8374   // The receiver was checked for null already.
8375   Node* objCTR = argument(0);
8376 
8377   // Load embeddedCipher field of CipherBlockChaining object.
8378   Node* embeddedCipherObj = load_field_from_object(objCTR, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8379 
8380   // get AESCrypt klass for instanceOf check
8381   // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
8382   // will have same classloader as CipherBlockChaining object
8383   const TypeInstPtr* tinst = _gvn.type(objCTR)->isa_instptr();
8384   assert(tinst != nullptr, "CTRobj is null");
8385   assert(tinst->is_loaded(), "CTRobj is not loaded");
8386 
8387   // we want to do an instanceof comparison against the AESCrypt class
8388   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8389   if (!klass_AESCrypt->is_loaded()) {
8390     // if AESCrypt is not even loaded, we never take the intrinsic fast path
8391     Node* ctrl = control();
8392     set_control(top()); // no regular fast path
8393     return ctrl;
8394   }
8395 
8396   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8397   Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
8398   Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
8399   Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
8400   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
8401 
8402   return instof_false; // even if it is null
8403 }
8404 
8405 //------------------------------inline_ghash_processBlocks
8406 bool LibraryCallKit::inline_ghash_processBlocks() {
8407   address stubAddr;
8408   const char *stubName;
8409   assert(UseGHASHIntrinsics, "need GHASH intrinsics support");
8410 
8411   stubAddr = StubRoutines::ghash_processBlocks();
8412   stubName = "ghash_processBlocks";
8413 
8414   Node* data           = argument(0);
8415   Node* offset         = argument(1);
8416   Node* len            = argument(2);
8417   Node* state          = argument(3);
8418   Node* subkeyH        = argument(4);
8419 
8420   state = must_be_not_null(state, true);
8421   subkeyH = must_be_not_null(subkeyH, true);
8422   data = must_be_not_null(data, true);
8423 
8424   Node* state_start  = array_element_address(state, intcon(0), T_LONG);
8425   assert(state_start, "state is null");
8426   Node* subkeyH_start  = array_element_address(subkeyH, intcon(0), T_LONG);
8427   assert(subkeyH_start, "subkeyH is null");
8428   Node* data_start  = array_element_address(data, offset, T_BYTE);
8429   assert(data_start, "data is null");
8430 
8431   Node* ghash = make_runtime_call(RC_LEAF|RC_NO_FP,
8432                                   OptoRuntime::ghash_processBlocks_Type(),
8433                                   stubAddr, stubName, TypePtr::BOTTOM,
8434                                   state_start, subkeyH_start, data_start, len);
8435   return true;
8436 }
8437 
8438 //------------------------------inline_chacha20Block
8439 bool LibraryCallKit::inline_chacha20Block() {
8440   address stubAddr;
8441   const char *stubName;
8442   assert(UseChaCha20Intrinsics, "need ChaCha20 intrinsics support");
8443 
8444   stubAddr = StubRoutines::chacha20Block();
8445   stubName = "chacha20Block";
8446 
8447   Node* state          = argument(0);
8448   Node* result         = argument(1);
8449 
8450   state = must_be_not_null(state, true);
8451   result = must_be_not_null(result, true);
8452 
8453   Node* state_start  = array_element_address(state, intcon(0), T_INT);
8454   assert(state_start, "state is null");
8455   Node* result_start  = array_element_address(result, intcon(0), T_BYTE);
8456   assert(result_start, "result is null");
8457 
8458   Node* cc20Blk = make_runtime_call(RC_LEAF|RC_NO_FP,
8459                                   OptoRuntime::chacha20Block_Type(),
8460                                   stubAddr, stubName, TypePtr::BOTTOM,
8461                                   state_start, result_start);
8462   // return key stream length (int)
8463   Node* retvalue = _gvn.transform(new ProjNode(cc20Blk, TypeFunc::Parms));
8464   set_result(retvalue);
8465   return true;
8466 }
8467 
8468 //------------------------------inline_kyberNtt
8469 bool LibraryCallKit::inline_kyberNtt() {
8470   address stubAddr;
8471   const char *stubName;
8472   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8473   assert(callee()->signature()->size() == 2, "kyberNtt has 2 parameters");
8474 
8475   stubAddr = StubRoutines::kyberNtt();
8476   stubName = "kyberNtt";
8477   if (!stubAddr) return false;
8478 
8479   Node* coeffs          = argument(0);
8480   Node* ntt_zetas        = argument(1);
8481 
8482   coeffs = must_be_not_null(coeffs, true);
8483   ntt_zetas = must_be_not_null(ntt_zetas, true);
8484 
8485   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_SHORT);
8486   assert(coeffs_start, "coeffs is null");
8487   Node* ntt_zetas_start  = array_element_address(ntt_zetas, intcon(0), T_SHORT);
8488   assert(ntt_zetas_start, "ntt_zetas is null");
8489   Node* kyberNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
8490                                   OptoRuntime::kyberNtt_Type(),
8491                                   stubAddr, stubName, TypePtr::BOTTOM,
8492                                   coeffs_start, ntt_zetas_start);
8493   // return an int
8494   Node* retvalue = _gvn.transform(new ProjNode(kyberNtt, TypeFunc::Parms));
8495   set_result(retvalue);
8496   return true;
8497 }
8498 
8499 //------------------------------inline_kyberInverseNtt
8500 bool LibraryCallKit::inline_kyberInverseNtt() {
8501   address stubAddr;
8502   const char *stubName;
8503   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8504   assert(callee()->signature()->size() == 2, "kyberInverseNtt has 2 parameters");
8505 
8506   stubAddr = StubRoutines::kyberInverseNtt();
8507   stubName = "kyberInverseNtt";
8508   if (!stubAddr) return false;
8509 
8510   Node* coeffs          = argument(0);
8511   Node* zetas           = argument(1);
8512 
8513   coeffs = must_be_not_null(coeffs, true);
8514   zetas = must_be_not_null(zetas, true);
8515 
8516   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_SHORT);
8517   assert(coeffs_start, "coeffs is null");
8518   Node* zetas_start  = array_element_address(zetas, intcon(0), T_SHORT);
8519   assert(zetas_start, "inverseNtt_zetas is null");
8520   Node* kyberInverseNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
8521                                   OptoRuntime::kyberInverseNtt_Type(),
8522                                   stubAddr, stubName, TypePtr::BOTTOM,
8523                                   coeffs_start, zetas_start);
8524 
8525   // return an int
8526   Node* retvalue = _gvn.transform(new ProjNode(kyberInverseNtt, TypeFunc::Parms));
8527   set_result(retvalue);
8528   return true;
8529 }
8530 
8531 //------------------------------inline_kyberNttMult
8532 bool LibraryCallKit::inline_kyberNttMult() {
8533   address stubAddr;
8534   const char *stubName;
8535   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8536   assert(callee()->signature()->size() == 4, "kyberNttMult has 4 parameters");
8537 
8538   stubAddr = StubRoutines::kyberNttMult();
8539   stubName = "kyberNttMult";
8540   if (!stubAddr) return false;
8541 
8542   Node* result          = argument(0);
8543   Node* ntta            = argument(1);
8544   Node* nttb            = argument(2);
8545   Node* zetas           = argument(3);
8546 
8547   result = must_be_not_null(result, true);
8548   ntta = must_be_not_null(ntta, true);
8549   nttb = must_be_not_null(nttb, true);
8550   zetas = must_be_not_null(zetas, true);
8551 
8552   Node* result_start  = array_element_address(result, intcon(0), T_SHORT);
8553   assert(result_start, "result is null");
8554   Node* ntta_start  = array_element_address(ntta, intcon(0), T_SHORT);
8555   assert(ntta_start, "ntta is null");
8556   Node* nttb_start  = array_element_address(nttb, intcon(0), T_SHORT);
8557   assert(nttb_start, "nttb is null");
8558   Node* zetas_start  = array_element_address(zetas, intcon(0), T_SHORT);
8559   assert(zetas_start, "nttMult_zetas is null");
8560   Node* kyberNttMult = make_runtime_call(RC_LEAF|RC_NO_FP,
8561                                   OptoRuntime::kyberNttMult_Type(),
8562                                   stubAddr, stubName, TypePtr::BOTTOM,
8563                                   result_start, ntta_start, nttb_start,
8564                                   zetas_start);
8565 
8566   // return an int
8567   Node* retvalue = _gvn.transform(new ProjNode(kyberNttMult, TypeFunc::Parms));
8568   set_result(retvalue);
8569 
8570   return true;
8571 }
8572 
8573 //------------------------------inline_kyberAddPoly_2
8574 bool LibraryCallKit::inline_kyberAddPoly_2() {
8575   address stubAddr;
8576   const char *stubName;
8577   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8578   assert(callee()->signature()->size() == 3, "kyberAddPoly_2 has 3 parameters");
8579 
8580   stubAddr = StubRoutines::kyberAddPoly_2();
8581   stubName = "kyberAddPoly_2";
8582   if (!stubAddr) return false;
8583 
8584   Node* result          = argument(0);
8585   Node* a               = argument(1);
8586   Node* b               = argument(2);
8587 
8588   result = must_be_not_null(result, true);
8589   a = must_be_not_null(a, true);
8590   b = must_be_not_null(b, true);
8591 
8592   Node* result_start  = array_element_address(result, intcon(0), T_SHORT);
8593   assert(result_start, "result is null");
8594   Node* a_start  = array_element_address(a, intcon(0), T_SHORT);
8595   assert(a_start, "a is null");
8596   Node* b_start  = array_element_address(b, intcon(0), T_SHORT);
8597   assert(b_start, "b is null");
8598   Node* kyberAddPoly_2 = make_runtime_call(RC_LEAF|RC_NO_FP,
8599                                   OptoRuntime::kyberAddPoly_2_Type(),
8600                                   stubAddr, stubName, TypePtr::BOTTOM,
8601                                   result_start, a_start, b_start);
8602   // return an int
8603   Node* retvalue = _gvn.transform(new ProjNode(kyberAddPoly_2, TypeFunc::Parms));
8604   set_result(retvalue);
8605   return true;
8606 }
8607 
8608 //------------------------------inline_kyberAddPoly_3
8609 bool LibraryCallKit::inline_kyberAddPoly_3() {
8610   address stubAddr;
8611   const char *stubName;
8612   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8613   assert(callee()->signature()->size() == 4, "kyberAddPoly_3 has 4 parameters");
8614 
8615   stubAddr = StubRoutines::kyberAddPoly_3();
8616   stubName = "kyberAddPoly_3";
8617   if (!stubAddr) return false;
8618 
8619   Node* result          = argument(0);
8620   Node* a               = argument(1);
8621   Node* b               = argument(2);
8622   Node* c               = argument(3);
8623 
8624   result = must_be_not_null(result, true);
8625   a = must_be_not_null(a, true);
8626   b = must_be_not_null(b, true);
8627   c = must_be_not_null(c, true);
8628 
8629   Node* result_start  = array_element_address(result, intcon(0), T_SHORT);
8630   assert(result_start, "result is null");
8631   Node* a_start  = array_element_address(a, intcon(0), T_SHORT);
8632   assert(a_start, "a is null");
8633   Node* b_start  = array_element_address(b, intcon(0), T_SHORT);
8634   assert(b_start, "b is null");
8635   Node* c_start  = array_element_address(c, intcon(0), T_SHORT);
8636   assert(c_start, "c is null");
8637   Node* kyberAddPoly_3 = make_runtime_call(RC_LEAF|RC_NO_FP,
8638                                   OptoRuntime::kyberAddPoly_3_Type(),
8639                                   stubAddr, stubName, TypePtr::BOTTOM,
8640                                   result_start, a_start, b_start, c_start);
8641   // return an int
8642   Node* retvalue = _gvn.transform(new ProjNode(kyberAddPoly_3, TypeFunc::Parms));
8643   set_result(retvalue);
8644   return true;
8645 }
8646 
8647 //------------------------------inline_kyber12To16
8648 bool LibraryCallKit::inline_kyber12To16() {
8649   address stubAddr;
8650   const char *stubName;
8651   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8652   assert(callee()->signature()->size() == 4, "kyber12To16 has 4 parameters");
8653 
8654   stubAddr = StubRoutines::kyber12To16();
8655   stubName = "kyber12To16";
8656   if (!stubAddr) return false;
8657 
8658   Node* condensed       = argument(0);
8659   Node* condensedOffs   = argument(1);
8660   Node* parsed          = argument(2);
8661   Node* parsedLength    = argument(3);
8662 
8663   condensed = must_be_not_null(condensed, true);
8664   parsed = must_be_not_null(parsed, true);
8665 
8666   Node* condensed_start  = array_element_address(condensed, intcon(0), T_BYTE);
8667   assert(condensed_start, "condensed is null");
8668   Node* parsed_start  = array_element_address(parsed, intcon(0), T_SHORT);
8669   assert(parsed_start, "parsed is null");
8670   Node* kyber12To16 = make_runtime_call(RC_LEAF|RC_NO_FP,
8671                                   OptoRuntime::kyber12To16_Type(),
8672                                   stubAddr, stubName, TypePtr::BOTTOM,
8673                                   condensed_start, condensedOffs, parsed_start, parsedLength);
8674   // return an int
8675   Node* retvalue = _gvn.transform(new ProjNode(kyber12To16, TypeFunc::Parms));
8676   set_result(retvalue);
8677   return true;
8678 
8679 }
8680 
8681 //------------------------------inline_kyberBarrettReduce
8682 bool LibraryCallKit::inline_kyberBarrettReduce() {
8683   address stubAddr;
8684   const char *stubName;
8685   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8686   assert(callee()->signature()->size() == 1, "kyberBarrettReduce has 1 parameters");
8687 
8688   stubAddr = StubRoutines::kyberBarrettReduce();
8689   stubName = "kyberBarrettReduce";
8690   if (!stubAddr) return false;
8691 
8692   Node* coeffs          = argument(0);
8693 
8694   coeffs = must_be_not_null(coeffs, true);
8695 
8696   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_SHORT);
8697   assert(coeffs_start, "coeffs is null");
8698   Node* kyberBarrettReduce = make_runtime_call(RC_LEAF|RC_NO_FP,
8699                                   OptoRuntime::kyberBarrettReduce_Type(),
8700                                   stubAddr, stubName, TypePtr::BOTTOM,
8701                                   coeffs_start);
8702   // return an int
8703   Node* retvalue = _gvn.transform(new ProjNode(kyberBarrettReduce, TypeFunc::Parms));
8704   set_result(retvalue);
8705   return true;
8706 }
8707 
8708 //------------------------------inline_dilithiumAlmostNtt
8709 bool LibraryCallKit::inline_dilithiumAlmostNtt() {
8710   address stubAddr;
8711   const char *stubName;
8712   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8713   assert(callee()->signature()->size() == 2, "dilithiumAlmostNtt has 2 parameters");
8714 
8715   stubAddr = StubRoutines::dilithiumAlmostNtt();
8716   stubName = "dilithiumAlmostNtt";
8717   if (!stubAddr) return false;
8718 
8719   Node* coeffs          = argument(0);
8720   Node* ntt_zetas        = argument(1);
8721 
8722   coeffs = must_be_not_null(coeffs, true);
8723   ntt_zetas = must_be_not_null(ntt_zetas, true);
8724 
8725   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_INT);
8726   assert(coeffs_start, "coeffs is null");
8727   Node* ntt_zetas_start  = array_element_address(ntt_zetas, intcon(0), T_INT);
8728   assert(ntt_zetas_start, "ntt_zetas is null");
8729   Node* dilithiumAlmostNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
8730                                   OptoRuntime::dilithiumAlmostNtt_Type(),
8731                                   stubAddr, stubName, TypePtr::BOTTOM,
8732                                   coeffs_start, ntt_zetas_start);
8733   // return an int
8734   Node* retvalue = _gvn.transform(new ProjNode(dilithiumAlmostNtt, TypeFunc::Parms));
8735   set_result(retvalue);
8736   return true;
8737 }
8738 
8739 //------------------------------inline_dilithiumAlmostInverseNtt
8740 bool LibraryCallKit::inline_dilithiumAlmostInverseNtt() {
8741   address stubAddr;
8742   const char *stubName;
8743   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8744   assert(callee()->signature()->size() == 2, "dilithiumAlmostInverseNtt has 2 parameters");
8745 
8746   stubAddr = StubRoutines::dilithiumAlmostInverseNtt();
8747   stubName = "dilithiumAlmostInverseNtt";
8748   if (!stubAddr) return false;
8749 
8750   Node* coeffs          = argument(0);
8751   Node* zetas           = argument(1);
8752 
8753   coeffs = must_be_not_null(coeffs, true);
8754   zetas = must_be_not_null(zetas, true);
8755 
8756   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_INT);
8757   assert(coeffs_start, "coeffs is null");
8758   Node* zetas_start  = array_element_address(zetas, intcon(0), T_INT);
8759   assert(zetas_start, "inverseNtt_zetas is null");
8760   Node* dilithiumAlmostInverseNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
8761                                   OptoRuntime::dilithiumAlmostInverseNtt_Type(),
8762                                   stubAddr, stubName, TypePtr::BOTTOM,
8763                                   coeffs_start, zetas_start);
8764   // return an int
8765   Node* retvalue = _gvn.transform(new ProjNode(dilithiumAlmostInverseNtt, TypeFunc::Parms));
8766   set_result(retvalue);
8767   return true;
8768 }
8769 
8770 //------------------------------inline_dilithiumNttMult
8771 bool LibraryCallKit::inline_dilithiumNttMult() {
8772   address stubAddr;
8773   const char *stubName;
8774   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8775   assert(callee()->signature()->size() == 3, "dilithiumNttMult has 3 parameters");
8776 
8777   stubAddr = StubRoutines::dilithiumNttMult();
8778   stubName = "dilithiumNttMult";
8779   if (!stubAddr) return false;
8780 
8781   Node* result          = argument(0);
8782   Node* ntta            = argument(1);
8783   Node* nttb            = argument(2);
8784   Node* zetas           = argument(3);
8785 
8786   result = must_be_not_null(result, true);
8787   ntta = must_be_not_null(ntta, true);
8788   nttb = must_be_not_null(nttb, true);
8789   zetas = must_be_not_null(zetas, true);
8790 
8791   Node* result_start  = array_element_address(result, intcon(0), T_INT);
8792   assert(result_start, "result is null");
8793   Node* ntta_start  = array_element_address(ntta, intcon(0), T_INT);
8794   assert(ntta_start, "ntta is null");
8795   Node* nttb_start  = array_element_address(nttb, intcon(0), T_INT);
8796   assert(nttb_start, "nttb is null");
8797   Node* dilithiumNttMult = make_runtime_call(RC_LEAF|RC_NO_FP,
8798                                   OptoRuntime::dilithiumNttMult_Type(),
8799                                   stubAddr, stubName, TypePtr::BOTTOM,
8800                                   result_start, ntta_start, nttb_start);
8801 
8802   // return an int
8803   Node* retvalue = _gvn.transform(new ProjNode(dilithiumNttMult, TypeFunc::Parms));
8804   set_result(retvalue);
8805 
8806   return true;
8807 }
8808 
8809 //------------------------------inline_dilithiumMontMulByConstant
8810 bool LibraryCallKit::inline_dilithiumMontMulByConstant() {
8811   address stubAddr;
8812   const char *stubName;
8813   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8814   assert(callee()->signature()->size() == 2, "dilithiumMontMulByConstant has 2 parameters");
8815 
8816   stubAddr = StubRoutines::dilithiumMontMulByConstant();
8817   stubName = "dilithiumMontMulByConstant";
8818   if (!stubAddr) return false;
8819 
8820   Node* coeffs          = argument(0);
8821   Node* constant        = argument(1);
8822 
8823   coeffs = must_be_not_null(coeffs, true);
8824 
8825   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_INT);
8826   assert(coeffs_start, "coeffs is null");
8827   Node* dilithiumMontMulByConstant = make_runtime_call(RC_LEAF|RC_NO_FP,
8828                                   OptoRuntime::dilithiumMontMulByConstant_Type(),
8829                                   stubAddr, stubName, TypePtr::BOTTOM,
8830                                   coeffs_start, constant);
8831 
8832   // return an int
8833   Node* retvalue = _gvn.transform(new ProjNode(dilithiumMontMulByConstant, TypeFunc::Parms));
8834   set_result(retvalue);
8835   return true;
8836 }
8837 
8838 
8839 //------------------------------inline_dilithiumDecomposePoly
8840 bool LibraryCallKit::inline_dilithiumDecomposePoly() {
8841   address stubAddr;
8842   const char *stubName;
8843   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8844   assert(callee()->signature()->size() == 5, "dilithiumDecomposePoly has 5 parameters");
8845 
8846   stubAddr = StubRoutines::dilithiumDecomposePoly();
8847   stubName = "dilithiumDecomposePoly";
8848   if (!stubAddr) return false;
8849 
8850   Node* input          = argument(0);
8851   Node* lowPart        = argument(1);
8852   Node* highPart       = argument(2);
8853   Node* twoGamma2      = argument(3);
8854   Node* multiplier     = argument(4);
8855 
8856   input = must_be_not_null(input, true);
8857   lowPart = must_be_not_null(lowPart, true);
8858   highPart = must_be_not_null(highPart, true);
8859 
8860   Node* input_start  = array_element_address(input, intcon(0), T_INT);
8861   assert(input_start, "input is null");
8862   Node* lowPart_start  = array_element_address(lowPart, intcon(0), T_INT);
8863   assert(lowPart_start, "lowPart is null");
8864   Node* highPart_start  = array_element_address(highPart, intcon(0), T_INT);
8865   assert(highPart_start, "highPart is null");
8866 
8867   Node* dilithiumDecomposePoly = make_runtime_call(RC_LEAF|RC_NO_FP,
8868                                   OptoRuntime::dilithiumDecomposePoly_Type(),
8869                                   stubAddr, stubName, TypePtr::BOTTOM,
8870                                   input_start, lowPart_start, highPart_start,
8871                                   twoGamma2, multiplier);
8872 
8873   // return an int
8874   Node* retvalue = _gvn.transform(new ProjNode(dilithiumDecomposePoly, TypeFunc::Parms));
8875   set_result(retvalue);
8876   return true;
8877 }
8878 
8879 bool LibraryCallKit::inline_base64_encodeBlock() {
8880   address stubAddr;
8881   const char *stubName;
8882   assert(UseBASE64Intrinsics, "need Base64 intrinsics support");
8883   assert(callee()->signature()->size() == 6, "base64_encodeBlock has 6 parameters");
8884   stubAddr = StubRoutines::base64_encodeBlock();
8885   stubName = "encodeBlock";
8886 
8887   if (!stubAddr) return false;
8888   Node* base64obj = argument(0);
8889   Node* src = argument(1);
8890   Node* offset = argument(2);
8891   Node* len = argument(3);
8892   Node* dest = argument(4);
8893   Node* dp = argument(5);
8894   Node* isURL = argument(6);
8895 
8896   src = must_be_not_null(src, true);
8897   dest = must_be_not_null(dest, true);
8898 
8899   Node* src_start = array_element_address(src, intcon(0), T_BYTE);
8900   assert(src_start, "source array is null");
8901   Node* dest_start = array_element_address(dest, intcon(0), T_BYTE);
8902   assert(dest_start, "destination array is null");
8903 
8904   Node* base64 = make_runtime_call(RC_LEAF,
8905                                    OptoRuntime::base64_encodeBlock_Type(),
8906                                    stubAddr, stubName, TypePtr::BOTTOM,
8907                                    src_start, offset, len, dest_start, dp, isURL);
8908   return true;
8909 }
8910 
8911 bool LibraryCallKit::inline_base64_decodeBlock() {
8912   address stubAddr;
8913   const char *stubName;
8914   assert(UseBASE64Intrinsics, "need Base64 intrinsics support");
8915   assert(callee()->signature()->size() == 7, "base64_decodeBlock has 7 parameters");
8916   stubAddr = StubRoutines::base64_decodeBlock();
8917   stubName = "decodeBlock";
8918 
8919   if (!stubAddr) return false;
8920   Node* base64obj = argument(0);
8921   Node* src = argument(1);
8922   Node* src_offset = argument(2);
8923   Node* len = argument(3);
8924   Node* dest = argument(4);
8925   Node* dest_offset = argument(5);
8926   Node* isURL = argument(6);
8927   Node* isMIME = argument(7);
8928 
8929   src = must_be_not_null(src, true);
8930   dest = must_be_not_null(dest, true);
8931 
8932   Node* src_start = array_element_address(src, intcon(0), T_BYTE);
8933   assert(src_start, "source array is null");
8934   Node* dest_start = array_element_address(dest, intcon(0), T_BYTE);
8935   assert(dest_start, "destination array is null");
8936 
8937   Node* call = make_runtime_call(RC_LEAF,
8938                                  OptoRuntime::base64_decodeBlock_Type(),
8939                                  stubAddr, stubName, TypePtr::BOTTOM,
8940                                  src_start, src_offset, len, dest_start, dest_offset, isURL, isMIME);
8941   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
8942   set_result(result);
8943   return true;
8944 }
8945 
8946 bool LibraryCallKit::inline_poly1305_processBlocks() {
8947   address stubAddr;
8948   const char *stubName;
8949   assert(UsePoly1305Intrinsics, "need Poly intrinsics support");
8950   assert(callee()->signature()->size() == 5, "poly1305_processBlocks has %d parameters", callee()->signature()->size());
8951   stubAddr = StubRoutines::poly1305_processBlocks();
8952   stubName = "poly1305_processBlocks";
8953 
8954   if (!stubAddr) return false;
8955   null_check_receiver();  // null-check receiver
8956   if (stopped())  return true;
8957 
8958   Node* input = argument(1);
8959   Node* input_offset = argument(2);
8960   Node* len = argument(3);
8961   Node* alimbs = argument(4);
8962   Node* rlimbs = argument(5);
8963 
8964   input = must_be_not_null(input, true);
8965   alimbs = must_be_not_null(alimbs, true);
8966   rlimbs = must_be_not_null(rlimbs, true);
8967 
8968   Node* input_start = array_element_address(input, input_offset, T_BYTE);
8969   assert(input_start, "input array is null");
8970   Node* acc_start = array_element_address(alimbs, intcon(0), T_LONG);
8971   assert(acc_start, "acc array is null");
8972   Node* r_start = array_element_address(rlimbs, intcon(0), T_LONG);
8973   assert(r_start, "r array is null");
8974 
8975   Node* call = make_runtime_call(RC_LEAF | RC_NO_FP,
8976                                  OptoRuntime::poly1305_processBlocks_Type(),
8977                                  stubAddr, stubName, TypePtr::BOTTOM,
8978                                  input_start, len, acc_start, r_start);
8979   return true;
8980 }
8981 
8982 bool LibraryCallKit::inline_intpoly_montgomeryMult_P256() {
8983   address stubAddr;
8984   const char *stubName;
8985   assert(UseIntPolyIntrinsics, "need intpoly intrinsics support");
8986   assert(callee()->signature()->size() == 3, "intpoly_montgomeryMult_P256 has %d parameters", callee()->signature()->size());
8987   stubAddr = StubRoutines::intpoly_montgomeryMult_P256();
8988   stubName = "intpoly_montgomeryMult_P256";
8989 
8990   if (!stubAddr) return false;
8991   null_check_receiver();  // null-check receiver
8992   if (stopped())  return true;
8993 
8994   Node* a = argument(1);
8995   Node* b = argument(2);
8996   Node* r = argument(3);
8997 
8998   a = must_be_not_null(a, true);
8999   b = must_be_not_null(b, true);
9000   r = must_be_not_null(r, true);
9001 
9002   Node* a_start = array_element_address(a, intcon(0), T_LONG);
9003   assert(a_start, "a array is null");
9004   Node* b_start = array_element_address(b, intcon(0), T_LONG);
9005   assert(b_start, "b array is null");
9006   Node* r_start = array_element_address(r, intcon(0), T_LONG);
9007   assert(r_start, "r array is null");
9008 
9009   Node* call = make_runtime_call(RC_LEAF | RC_NO_FP,
9010                                  OptoRuntime::intpoly_montgomeryMult_P256_Type(),
9011                                  stubAddr, stubName, TypePtr::BOTTOM,
9012                                  a_start, b_start, r_start);
9013   return true;
9014 }
9015 
9016 bool LibraryCallKit::inline_intpoly_assign() {
9017   assert(UseIntPolyIntrinsics, "need intpoly intrinsics support");
9018   assert(callee()->signature()->size() == 3, "intpoly_assign has %d parameters", callee()->signature()->size());
9019   const char *stubName = "intpoly_assign";
9020   address stubAddr = StubRoutines::intpoly_assign();
9021   if (!stubAddr) return false;
9022 
9023   Node* set = argument(0);
9024   Node* a = argument(1);
9025   Node* b = argument(2);
9026   Node* arr_length = load_array_length(a);
9027 
9028   a = must_be_not_null(a, true);
9029   b = must_be_not_null(b, true);
9030 
9031   Node* a_start = array_element_address(a, intcon(0), T_LONG);
9032   assert(a_start, "a array is null");
9033   Node* b_start = array_element_address(b, intcon(0), T_LONG);
9034   assert(b_start, "b array is null");
9035 
9036   Node* call = make_runtime_call(RC_LEAF | RC_NO_FP,
9037                                  OptoRuntime::intpoly_assign_Type(),
9038                                  stubAddr, stubName, TypePtr::BOTTOM,
9039                                  set, a_start, b_start, arr_length);
9040   return true;
9041 }
9042 
9043 //------------------------------inline_digestBase_implCompress-----------------------
9044 //
9045 // Calculate MD5 for single-block byte[] array.
9046 // void com.sun.security.provider.MD5.implCompress(byte[] buf, int ofs)
9047 //
9048 // Calculate SHA (i.e., SHA-1) for single-block byte[] array.
9049 // void com.sun.security.provider.SHA.implCompress(byte[] buf, int ofs)
9050 //
9051 // Calculate SHA2 (i.e., SHA-244 or SHA-256) for single-block byte[] array.
9052 // void com.sun.security.provider.SHA2.implCompress(byte[] buf, int ofs)
9053 //
9054 // Calculate SHA5 (i.e., SHA-384 or SHA-512) for single-block byte[] array.
9055 // void com.sun.security.provider.SHA5.implCompress(byte[] buf, int ofs)
9056 //
9057 // Calculate SHA3 (i.e., SHA3-224 or SHA3-256 or SHA3-384 or SHA3-512) for single-block byte[] array.
9058 // void com.sun.security.provider.SHA3.implCompress(byte[] buf, int ofs)
9059 //
9060 bool LibraryCallKit::inline_digestBase_implCompress(vmIntrinsics::ID id) {
9061   assert(callee()->signature()->size() == 2, "sha_implCompress has 2 parameters");
9062 
9063   Node* digestBase_obj = argument(0);
9064   Node* src            = argument(1); // type oop
9065   Node* ofs            = argument(2); // type int
9066 
9067   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
9068   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
9069     // failed array check
9070     return false;
9071   }
9072   // Figure out the size and type of the elements we will be copying.
9073   BasicType src_elem = src_type->elem()->array_element_basic_type();
9074   if (src_elem != T_BYTE) {
9075     return false;
9076   }
9077   // 'src_start' points to src array + offset
9078   src = must_be_not_null(src, true);
9079   Node* src_start = array_element_address(src, ofs, src_elem);
9080   Node* state = nullptr;
9081   Node* block_size = nullptr;
9082   address stubAddr;
9083   const char *stubName;
9084 
9085   switch(id) {
9086   case vmIntrinsics::_md5_implCompress:
9087     assert(UseMD5Intrinsics, "need MD5 instruction support");
9088     state = get_state_from_digest_object(digestBase_obj, T_INT);
9089     stubAddr = StubRoutines::md5_implCompress();
9090     stubName = "md5_implCompress";
9091     break;
9092   case vmIntrinsics::_sha_implCompress:
9093     assert(UseSHA1Intrinsics, "need SHA1 instruction support");
9094     state = get_state_from_digest_object(digestBase_obj, T_INT);
9095     stubAddr = StubRoutines::sha1_implCompress();
9096     stubName = "sha1_implCompress";
9097     break;
9098   case vmIntrinsics::_sha2_implCompress:
9099     assert(UseSHA256Intrinsics, "need SHA256 instruction support");
9100     state = get_state_from_digest_object(digestBase_obj, T_INT);
9101     stubAddr = StubRoutines::sha256_implCompress();
9102     stubName = "sha256_implCompress";
9103     break;
9104   case vmIntrinsics::_sha5_implCompress:
9105     assert(UseSHA512Intrinsics, "need SHA512 instruction support");
9106     state = get_state_from_digest_object(digestBase_obj, T_LONG);
9107     stubAddr = StubRoutines::sha512_implCompress();
9108     stubName = "sha512_implCompress";
9109     break;
9110   case vmIntrinsics::_sha3_implCompress:
9111     assert(UseSHA3Intrinsics, "need SHA3 instruction support");
9112     state = get_state_from_digest_object(digestBase_obj, T_LONG);
9113     stubAddr = StubRoutines::sha3_implCompress();
9114     stubName = "sha3_implCompress";
9115     block_size = get_block_size_from_digest_object(digestBase_obj);
9116     if (block_size == nullptr) return false;
9117     break;
9118   default:
9119     fatal_unexpected_iid(id);
9120     return false;
9121   }
9122   if (state == nullptr) return false;
9123 
9124   assert(stubAddr != nullptr, "Stub %s is not generated", stubName);
9125   if (stubAddr == nullptr) return false;
9126 
9127   // Call the stub.
9128   Node* call;
9129   if (block_size == nullptr) {
9130     call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::digestBase_implCompress_Type(false),
9131                              stubAddr, stubName, TypePtr::BOTTOM,
9132                              src_start, state);
9133   } else {
9134     call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::digestBase_implCompress_Type(true),
9135                              stubAddr, stubName, TypePtr::BOTTOM,
9136                              src_start, state, block_size);
9137   }
9138 
9139   return true;
9140 }
9141 
9142 //------------------------------inline_double_keccak
9143 bool LibraryCallKit::inline_double_keccak() {
9144   address stubAddr;
9145   const char *stubName;
9146   assert(UseSHA3Intrinsics, "need SHA3 intrinsics support");
9147   assert(callee()->signature()->size() == 2, "double_keccak has 2 parameters");
9148 
9149   stubAddr = StubRoutines::double_keccak();
9150   stubName = "double_keccak";
9151   if (!stubAddr) return false;
9152 
9153   Node* status0        = argument(0);
9154   Node* status1        = argument(1);
9155 
9156   status0 = must_be_not_null(status0, true);
9157   status1 = must_be_not_null(status1, true);
9158 
9159   Node* status0_start  = array_element_address(status0, intcon(0), T_LONG);
9160   assert(status0_start, "status0 is null");
9161   Node* status1_start  = array_element_address(status1, intcon(0), T_LONG);
9162   assert(status1_start, "status1 is null");
9163   Node* double_keccak = make_runtime_call(RC_LEAF|RC_NO_FP,
9164                                   OptoRuntime::double_keccak_Type(),
9165                                   stubAddr, stubName, TypePtr::BOTTOM,
9166                                   status0_start, status1_start);
9167   // return an int
9168   Node* retvalue = _gvn.transform(new ProjNode(double_keccak, TypeFunc::Parms));
9169   set_result(retvalue);
9170   return true;
9171 }
9172 
9173 
9174 //------------------------------inline_digestBase_implCompressMB-----------------------
9175 //
9176 // Calculate MD5/SHA/SHA2/SHA5/SHA3 for multi-block byte[] array.
9177 // int com.sun.security.provider.DigestBase.implCompressMultiBlock(byte[] b, int ofs, int limit)
9178 //
9179 bool LibraryCallKit::inline_digestBase_implCompressMB(int predicate) {
9180   assert(UseMD5Intrinsics || UseSHA1Intrinsics || UseSHA256Intrinsics || UseSHA512Intrinsics || UseSHA3Intrinsics,
9181          "need MD5/SHA1/SHA256/SHA512/SHA3 instruction support");
9182   assert((uint)predicate < 5, "sanity");
9183   assert(callee()->signature()->size() == 3, "digestBase_implCompressMB has 3 parameters");
9184 
9185   Node* digestBase_obj = argument(0); // The receiver was checked for null already.
9186   Node* src            = argument(1); // byte[] array
9187   Node* ofs            = argument(2); // type int
9188   Node* limit          = argument(3); // type int
9189 
9190   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
9191   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
9192     // failed array check
9193     return false;
9194   }
9195   // Figure out the size and type of the elements we will be copying.
9196   BasicType src_elem = src_type->elem()->array_element_basic_type();
9197   if (src_elem != T_BYTE) {
9198     return false;
9199   }
9200   // 'src_start' points to src array + offset
9201   src = must_be_not_null(src, false);
9202   Node* src_start = array_element_address(src, ofs, src_elem);
9203 
9204   const char* klass_digestBase_name = nullptr;
9205   const char* stub_name = nullptr;
9206   address     stub_addr = nullptr;
9207   BasicType elem_type = T_INT;
9208 
9209   switch (predicate) {
9210   case 0:
9211     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_md5_implCompress)) {
9212       klass_digestBase_name = "sun/security/provider/MD5";
9213       stub_name = "md5_implCompressMB";
9214       stub_addr = StubRoutines::md5_implCompressMB();
9215     }
9216     break;
9217   case 1:
9218     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha_implCompress)) {
9219       klass_digestBase_name = "sun/security/provider/SHA";
9220       stub_name = "sha1_implCompressMB";
9221       stub_addr = StubRoutines::sha1_implCompressMB();
9222     }
9223     break;
9224   case 2:
9225     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha2_implCompress)) {
9226       klass_digestBase_name = "sun/security/provider/SHA2";
9227       stub_name = "sha256_implCompressMB";
9228       stub_addr = StubRoutines::sha256_implCompressMB();
9229     }
9230     break;
9231   case 3:
9232     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha5_implCompress)) {
9233       klass_digestBase_name = "sun/security/provider/SHA5";
9234       stub_name = "sha512_implCompressMB";
9235       stub_addr = StubRoutines::sha512_implCompressMB();
9236       elem_type = T_LONG;
9237     }
9238     break;
9239   case 4:
9240     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha3_implCompress)) {
9241       klass_digestBase_name = "sun/security/provider/SHA3";
9242       stub_name = "sha3_implCompressMB";
9243       stub_addr = StubRoutines::sha3_implCompressMB();
9244       elem_type = T_LONG;
9245     }
9246     break;
9247   default:
9248     fatal("unknown DigestBase intrinsic predicate: %d", predicate);
9249   }
9250   if (klass_digestBase_name != nullptr) {
9251     assert(stub_addr != nullptr, "Stub is generated");
9252     if (stub_addr == nullptr) return false;
9253 
9254     // get DigestBase klass to lookup for SHA klass
9255     const TypeInstPtr* tinst = _gvn.type(digestBase_obj)->isa_instptr();
9256     assert(tinst != nullptr, "digestBase_obj is not instance???");
9257     assert(tinst->is_loaded(), "DigestBase is not loaded");
9258 
9259     ciKlass* klass_digestBase = tinst->instance_klass()->find_klass(ciSymbol::make(klass_digestBase_name));
9260     assert(klass_digestBase->is_loaded(), "predicate checks that this class is loaded");
9261     ciInstanceKlass* instklass_digestBase = klass_digestBase->as_instance_klass();
9262     return inline_digestBase_implCompressMB(digestBase_obj, instklass_digestBase, elem_type, stub_addr, stub_name, src_start, ofs, limit);
9263   }
9264   return false;
9265 }
9266 
9267 //------------------------------inline_digestBase_implCompressMB-----------------------
9268 bool LibraryCallKit::inline_digestBase_implCompressMB(Node* digestBase_obj, ciInstanceKlass* instklass_digestBase,
9269                                                       BasicType elem_type, address stubAddr, const char *stubName,
9270                                                       Node* src_start, Node* ofs, Node* limit) {
9271   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_digestBase);
9272   const TypeOopPtr* xtype = aklass->cast_to_exactness(false)->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
9273   Node* digest_obj = new CheckCastPPNode(control(), digestBase_obj, xtype);
9274   digest_obj = _gvn.transform(digest_obj);
9275 
9276   Node* state = get_state_from_digest_object(digest_obj, elem_type);
9277   if (state == nullptr) return false;
9278 
9279   Node* block_size = nullptr;
9280   if (strcmp("sha3_implCompressMB", stubName) == 0) {
9281     block_size = get_block_size_from_digest_object(digest_obj);
9282     if (block_size == nullptr) return false;
9283   }
9284 
9285   // Call the stub.
9286   Node* call;
9287   if (block_size == nullptr) {
9288     call = make_runtime_call(RC_LEAF|RC_NO_FP,
9289                              OptoRuntime::digestBase_implCompressMB_Type(false),
9290                              stubAddr, stubName, TypePtr::BOTTOM,
9291                              src_start, state, ofs, limit);
9292   } else {
9293      call = make_runtime_call(RC_LEAF|RC_NO_FP,
9294                              OptoRuntime::digestBase_implCompressMB_Type(true),
9295                              stubAddr, stubName, TypePtr::BOTTOM,
9296                              src_start, state, block_size, ofs, limit);
9297   }
9298 
9299   // return ofs (int)
9300   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
9301   set_result(result);
9302 
9303   return true;
9304 }
9305 
9306 //------------------------------inline_galoisCounterMode_AESCrypt-----------------------
9307 bool LibraryCallKit::inline_galoisCounterMode_AESCrypt() {
9308   assert(UseAES, "need AES instruction support");
9309   address stubAddr = nullptr;
9310   const char *stubName = nullptr;
9311   stubAddr = StubRoutines::galoisCounterMode_AESCrypt();
9312   stubName = "galoisCounterMode_AESCrypt";
9313 
9314   if (stubAddr == nullptr) return false;
9315 
9316   Node* in      = argument(0);
9317   Node* inOfs   = argument(1);
9318   Node* len     = argument(2);
9319   Node* ct      = argument(3);
9320   Node* ctOfs   = argument(4);
9321   Node* out     = argument(5);
9322   Node* outOfs  = argument(6);
9323   Node* gctr_object = argument(7);
9324   Node* ghash_object = argument(8);
9325 
9326   // (1) in, ct and out are arrays.
9327   const TypeAryPtr* in_type = in->Value(&_gvn)->isa_aryptr();
9328   const TypeAryPtr* ct_type = ct->Value(&_gvn)->isa_aryptr();
9329   const TypeAryPtr* out_type = out->Value(&_gvn)->isa_aryptr();
9330   assert( in_type != nullptr &&  in_type->elem() != Type::BOTTOM &&
9331           ct_type != nullptr &&  ct_type->elem() != Type::BOTTOM &&
9332          out_type != nullptr && out_type->elem() != Type::BOTTOM, "args are strange");
9333 
9334   // checks are the responsibility of the caller
9335   Node* in_start = in;
9336   Node* ct_start = ct;
9337   Node* out_start = out;
9338   if (inOfs != nullptr || ctOfs != nullptr || outOfs != nullptr) {
9339     assert(inOfs != nullptr && ctOfs != nullptr && outOfs != nullptr, "");
9340     in_start = array_element_address(in, inOfs, T_BYTE);
9341     ct_start = array_element_address(ct, ctOfs, T_BYTE);
9342     out_start = array_element_address(out, outOfs, T_BYTE);
9343   }
9344 
9345   // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
9346   // (because of the predicated logic executed earlier).
9347   // so we cast it here safely.
9348   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
9349   Node* embeddedCipherObj = load_field_from_object(gctr_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
9350   Node* counter = load_field_from_object(gctr_object, "counter", "[B");
9351   Node* subkeyHtbl = load_field_from_object(ghash_object, "subkeyHtbl", "[J");
9352   Node* state = load_field_from_object(ghash_object, "state", "[J");
9353 
9354   if (embeddedCipherObj == nullptr || counter == nullptr || subkeyHtbl == nullptr || state == nullptr) {
9355     return false;
9356   }
9357   // cast it to what we know it will be at runtime
9358   const TypeInstPtr* tinst = _gvn.type(gctr_object)->isa_instptr();
9359   assert(tinst != nullptr, "GCTR obj is null");
9360   assert(tinst->is_loaded(), "GCTR obj is not loaded");
9361   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
9362   assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
9363   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
9364   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
9365   const TypeOopPtr* xtype = aklass->as_instance_type();
9366   Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
9367   aescrypt_object = _gvn.transform(aescrypt_object);
9368   // we need to get the start of the aescrypt_object's expanded key array
9369   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object, /* is_decrypt */ false);
9370   if (k_start == nullptr) return false;
9371   // similarly, get the start address of the r vector
9372   Node* cnt_start = array_element_address(counter, intcon(0), T_BYTE);
9373   Node* state_start = array_element_address(state, intcon(0), T_LONG);
9374   Node* subkeyHtbl_start = array_element_address(subkeyHtbl, intcon(0), T_LONG);
9375 
9376 
9377   // Call the stub, passing params
9378   Node* gcmCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
9379                                OptoRuntime::galoisCounterMode_aescrypt_Type(),
9380                                stubAddr, stubName, TypePtr::BOTTOM,
9381                                in_start, len, ct_start, out_start, k_start, state_start, subkeyHtbl_start, cnt_start);
9382 
9383   // return cipher length (int)
9384   Node* retvalue = _gvn.transform(new ProjNode(gcmCrypt, TypeFunc::Parms));
9385   set_result(retvalue);
9386 
9387   return true;
9388 }
9389 
9390 //----------------------------inline_galoisCounterMode_AESCrypt_predicate----------------------------
9391 // Return node representing slow path of predicate check.
9392 // the pseudo code we want to emulate with this predicate is:
9393 // for encryption:
9394 //    if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
9395 // for decryption:
9396 //    if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
9397 //    note cipher==plain is more conservative than the original java code but that's OK
9398 //
9399 
9400 Node* LibraryCallKit::inline_galoisCounterMode_AESCrypt_predicate() {
9401   // The receiver was checked for null already.
9402   Node* objGCTR = argument(7);
9403   // Load embeddedCipher field of GCTR object.
9404   Node* embeddedCipherObj = load_field_from_object(objGCTR, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
9405   assert(embeddedCipherObj != nullptr, "embeddedCipherObj is null");
9406 
9407   // get AESCrypt klass for instanceOf check
9408   // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
9409   // will have same classloader as CipherBlockChaining object
9410   const TypeInstPtr* tinst = _gvn.type(objGCTR)->isa_instptr();
9411   assert(tinst != nullptr, "GCTR obj is null");
9412   assert(tinst->is_loaded(), "GCTR obj is not loaded");
9413 
9414   // we want to do an instanceof comparison against the AESCrypt class
9415   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
9416   if (!klass_AESCrypt->is_loaded()) {
9417     // if AESCrypt is not even loaded, we never take the intrinsic fast path
9418     Node* ctrl = control();
9419     set_control(top()); // no regular fast path
9420     return ctrl;
9421   }
9422 
9423   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
9424   Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
9425   Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
9426   Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
9427   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
9428 
9429   return instof_false; // even if it is null
9430 }
9431 
9432 //------------------------------get_state_from_digest_object-----------------------
9433 Node * LibraryCallKit::get_state_from_digest_object(Node *digest_object, BasicType elem_type) {
9434   const char* state_type;
9435   switch (elem_type) {
9436     case T_BYTE: state_type = "[B"; break;
9437     case T_INT:  state_type = "[I"; break;
9438     case T_LONG: state_type = "[J"; break;
9439     default: ShouldNotReachHere();
9440   }
9441   Node* digest_state = load_field_from_object(digest_object, "state", state_type);
9442   assert (digest_state != nullptr, "wrong version of sun.security.provider.MD5/SHA/SHA2/SHA5/SHA3");
9443   if (digest_state == nullptr) return (Node *) nullptr;
9444 
9445   // now have the array, need to get the start address of the state array
9446   Node* state = array_element_address(digest_state, intcon(0), elem_type);
9447   return state;
9448 }
9449 
9450 //------------------------------get_block_size_from_sha3_object----------------------------------
9451 Node * LibraryCallKit::get_block_size_from_digest_object(Node *digest_object) {
9452   Node* block_size = load_field_from_object(digest_object, "blockSize", "I");
9453   assert (block_size != nullptr, "sanity");
9454   return block_size;
9455 }
9456 
9457 //----------------------------inline_digestBase_implCompressMB_predicate----------------------------
9458 // Return node representing slow path of predicate check.
9459 // the pseudo code we want to emulate with this predicate is:
9460 //    if (digestBaseObj instanceof MD5/SHA/SHA2/SHA5/SHA3) do_intrinsic, else do_javapath
9461 //
9462 Node* LibraryCallKit::inline_digestBase_implCompressMB_predicate(int predicate) {
9463   assert(UseMD5Intrinsics || UseSHA1Intrinsics || UseSHA256Intrinsics || UseSHA512Intrinsics || UseSHA3Intrinsics,
9464          "need MD5/SHA1/SHA256/SHA512/SHA3 instruction support");
9465   assert((uint)predicate < 5, "sanity");
9466 
9467   // The receiver was checked for null already.
9468   Node* digestBaseObj = argument(0);
9469 
9470   // get DigestBase klass for instanceOf check
9471   const TypeInstPtr* tinst = _gvn.type(digestBaseObj)->isa_instptr();
9472   assert(tinst != nullptr, "digestBaseObj is null");
9473   assert(tinst->is_loaded(), "DigestBase is not loaded");
9474 
9475   const char* klass_name = nullptr;
9476   switch (predicate) {
9477   case 0:
9478     if (UseMD5Intrinsics) {
9479       // we want to do an instanceof comparison against the MD5 class
9480       klass_name = "sun/security/provider/MD5";
9481     }
9482     break;
9483   case 1:
9484     if (UseSHA1Intrinsics) {
9485       // we want to do an instanceof comparison against the SHA class
9486       klass_name = "sun/security/provider/SHA";
9487     }
9488     break;
9489   case 2:
9490     if (UseSHA256Intrinsics) {
9491       // we want to do an instanceof comparison against the SHA2 class
9492       klass_name = "sun/security/provider/SHA2";
9493     }
9494     break;
9495   case 3:
9496     if (UseSHA512Intrinsics) {
9497       // we want to do an instanceof comparison against the SHA5 class
9498       klass_name = "sun/security/provider/SHA5";
9499     }
9500     break;
9501   case 4:
9502     if (UseSHA3Intrinsics) {
9503       // we want to do an instanceof comparison against the SHA3 class
9504       klass_name = "sun/security/provider/SHA3";
9505     }
9506     break;
9507   default:
9508     fatal("unknown SHA intrinsic predicate: %d", predicate);
9509   }
9510 
9511   ciKlass* klass = nullptr;
9512   if (klass_name != nullptr) {
9513     klass = tinst->instance_klass()->find_klass(ciSymbol::make(klass_name));
9514   }
9515   if ((klass == nullptr) || !klass->is_loaded()) {
9516     // if none of MD5/SHA/SHA2/SHA5 is loaded, we never take the intrinsic fast path
9517     Node* ctrl = control();
9518     set_control(top()); // no intrinsic path
9519     return ctrl;
9520   }
9521   ciInstanceKlass* instklass = klass->as_instance_klass();
9522 
9523   Node* instof = gen_instanceof(digestBaseObj, makecon(TypeKlassPtr::make(instklass)));
9524   Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
9525   Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
9526   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
9527 
9528   return instof_false;  // even if it is null
9529 }
9530 
9531 //-------------inline_fma-----------------------------------
9532 bool LibraryCallKit::inline_fma(vmIntrinsics::ID id) {
9533   Node *a = nullptr;
9534   Node *b = nullptr;
9535   Node *c = nullptr;
9536   Node* result = nullptr;
9537   switch (id) {
9538   case vmIntrinsics::_fmaD:
9539     assert(callee()->signature()->size() == 6, "fma has 3 parameters of size 2 each.");
9540     // no receiver since it is static method
9541     a = argument(0);
9542     b = argument(2);
9543     c = argument(4);
9544     result = _gvn.transform(new FmaDNode(a, b, c));
9545     break;
9546   case vmIntrinsics::_fmaF:
9547     assert(callee()->signature()->size() == 3, "fma has 3 parameters of size 1 each.");
9548     a = argument(0);
9549     b = argument(1);
9550     c = argument(2);
9551     result = _gvn.transform(new FmaFNode(a, b, c));
9552     break;
9553   default:
9554     fatal_unexpected_iid(id);  break;
9555   }
9556   set_result(result);
9557   return true;
9558 }
9559 
9560 bool LibraryCallKit::inline_character_compare(vmIntrinsics::ID id) {
9561   // argument(0) is receiver
9562   Node* codePoint = argument(1);
9563   Node* n = nullptr;
9564 
9565   switch (id) {
9566     case vmIntrinsics::_isDigit :
9567       n = new DigitNode(control(), codePoint);
9568       break;
9569     case vmIntrinsics::_isLowerCase :
9570       n = new LowerCaseNode(control(), codePoint);
9571       break;
9572     case vmIntrinsics::_isUpperCase :
9573       n = new UpperCaseNode(control(), codePoint);
9574       break;
9575     case vmIntrinsics::_isWhitespace :
9576       n = new WhitespaceNode(control(), codePoint);
9577       break;
9578     default:
9579       fatal_unexpected_iid(id);
9580   }
9581 
9582   set_result(_gvn.transform(n));
9583   return true;
9584 }
9585 
9586 bool LibraryCallKit::inline_profileBoolean() {
9587   Node* counts = argument(1);
9588   const TypeAryPtr* ary = nullptr;
9589   ciArray* aobj = nullptr;
9590   if (counts->is_Con()
9591       && (ary = counts->bottom_type()->isa_aryptr()) != nullptr
9592       && (aobj = ary->const_oop()->as_array()) != nullptr
9593       && (aobj->length() == 2)) {
9594     // Profile is int[2] where [0] and [1] correspond to false and true value occurrences respectively.
9595     jint false_cnt = aobj->element_value(0).as_int();
9596     jint  true_cnt = aobj->element_value(1).as_int();
9597 
9598     if (C->log() != nullptr) {
9599       C->log()->elem("observe source='profileBoolean' false='%d' true='%d'",
9600                      false_cnt, true_cnt);
9601     }
9602 
9603     if (false_cnt + true_cnt == 0) {
9604       // According to profile, never executed.
9605       uncommon_trap_exact(Deoptimization::Reason_intrinsic,
9606                           Deoptimization::Action_reinterpret);
9607       return true;
9608     }
9609 
9610     // result is a boolean (0 or 1) and its profile (false_cnt & true_cnt)
9611     // is a number of each value occurrences.
9612     Node* result = argument(0);
9613     if (false_cnt == 0 || true_cnt == 0) {
9614       // According to profile, one value has been never seen.
9615       int expected_val = (false_cnt == 0) ? 1 : 0;
9616 
9617       Node* cmp  = _gvn.transform(new CmpINode(result, intcon(expected_val)));
9618       Node* test = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
9619 
9620       IfNode* check = create_and_map_if(control(), test, PROB_ALWAYS, COUNT_UNKNOWN);
9621       Node* fast_path = _gvn.transform(new IfTrueNode(check));
9622       Node* slow_path = _gvn.transform(new IfFalseNode(check));
9623 
9624       { // Slow path: uncommon trap for never seen value and then reexecute
9625         // MethodHandleImpl::profileBoolean() to bump the count, so JIT knows
9626         // the value has been seen at least once.
9627         PreserveJVMState pjvms(this);
9628         PreserveReexecuteState preexecs(this);
9629         jvms()->set_should_reexecute(true);
9630 
9631         set_control(slow_path);
9632         set_i_o(i_o());
9633 
9634         uncommon_trap_exact(Deoptimization::Reason_intrinsic,
9635                             Deoptimization::Action_reinterpret);
9636       }
9637       // The guard for never seen value enables sharpening of the result and
9638       // returning a constant. It allows to eliminate branches on the same value
9639       // later on.
9640       set_control(fast_path);
9641       result = intcon(expected_val);
9642     }
9643     // Stop profiling.
9644     // MethodHandleImpl::profileBoolean() has profiling logic in its bytecode.
9645     // By replacing method body with profile data (represented as ProfileBooleanNode
9646     // on IR level) we effectively disable profiling.
9647     // It enables full speed execution once optimized code is generated.
9648     Node* profile = _gvn.transform(new ProfileBooleanNode(result, false_cnt, true_cnt));
9649     C->record_for_igvn(profile);
9650     set_result(profile);
9651     return true;
9652   } else {
9653     // Continue profiling.
9654     // Profile data isn't available at the moment. So, execute method's bytecode version.
9655     // Usually, when GWT LambdaForms are profiled it means that a stand-alone nmethod
9656     // is compiled and counters aren't available since corresponding MethodHandle
9657     // isn't a compile-time constant.
9658     return false;
9659   }
9660 }
9661 
9662 bool LibraryCallKit::inline_isCompileConstant() {
9663   Node* n = argument(0);
9664   set_result(n->is_Con() ? intcon(1) : intcon(0));
9665   return true;
9666 }
9667 
9668 //------------------------------- inline_getObjectSize --------------------------------------
9669 //
9670 // Calculate the runtime size of the object/array.
9671 //   native long sun.instrument.InstrumentationImpl.getObjectSize0(long nativeAgent, Object objectToSize);
9672 //
9673 bool LibraryCallKit::inline_getObjectSize() {
9674   Node* obj = argument(3);
9675   Node* klass_node = load_object_klass(obj);
9676 
9677   jint  layout_con = Klass::_lh_neutral_value;
9678   Node* layout_val = get_layout_helper(klass_node, layout_con);
9679   int   layout_is_con = (layout_val == nullptr);
9680 
9681   if (layout_is_con) {
9682     // Layout helper is constant, can figure out things at compile time.
9683 
9684     if (Klass::layout_helper_is_instance(layout_con)) {
9685       // Instance case:  layout_con contains the size itself.
9686       Node *size = longcon(Klass::layout_helper_size_in_bytes(layout_con));
9687       set_result(size);
9688     } else {
9689       // Array case: size is round(header + element_size*arraylength).
9690       // Since arraylength is different for every array instance, we have to
9691       // compute the whole thing at runtime.
9692 
9693       Node* arr_length = load_array_length(obj);
9694 
9695       int round_mask = MinObjAlignmentInBytes - 1;
9696       int hsize  = Klass::layout_helper_header_size(layout_con);
9697       int eshift = Klass::layout_helper_log2_element_size(layout_con);
9698 
9699       if ((round_mask & ~right_n_bits(eshift)) == 0) {
9700         round_mask = 0;  // strength-reduce it if it goes away completely
9701       }
9702       assert((hsize & right_n_bits(eshift)) == 0, "hsize is pre-rounded");
9703       Node* header_size = intcon(hsize + round_mask);
9704 
9705       Node* lengthx = ConvI2X(arr_length);
9706       Node* headerx = ConvI2X(header_size);
9707 
9708       Node* abody = lengthx;
9709       if (eshift != 0) {
9710         abody = _gvn.transform(new LShiftXNode(lengthx, intcon(eshift)));
9711       }
9712       Node* size = _gvn.transform( new AddXNode(headerx, abody) );
9713       if (round_mask != 0) {
9714         size = _gvn.transform( new AndXNode(size, MakeConX(~round_mask)) );
9715       }
9716       size = ConvX2L(size);
9717       set_result(size);
9718     }
9719   } else {
9720     // Layout helper is not constant, need to test for array-ness at runtime.
9721 
9722     enum { _instance_path = 1, _array_path, PATH_LIMIT };
9723     RegionNode* result_reg = new RegionNode(PATH_LIMIT);
9724     PhiNode* result_val = new PhiNode(result_reg, TypeLong::LONG);
9725     record_for_igvn(result_reg);
9726 
9727     Node* array_ctl = generate_array_guard(klass_node, nullptr, &obj);
9728     if (array_ctl != nullptr) {
9729       // Array case: size is round(header + element_size*arraylength).
9730       // Since arraylength is different for every array instance, we have to
9731       // compute the whole thing at runtime.
9732 
9733       PreserveJVMState pjvms(this);
9734       set_control(array_ctl);
9735       Node* arr_length = load_array_length(obj);
9736 
9737       int round_mask = MinObjAlignmentInBytes - 1;
9738       Node* mask = intcon(round_mask);
9739 
9740       Node* hss = intcon(Klass::_lh_header_size_shift);
9741       Node* hsm = intcon(Klass::_lh_header_size_mask);
9742       Node* header_size = _gvn.transform(new URShiftINode(layout_val, hss));
9743       header_size = _gvn.transform(new AndINode(header_size, hsm));
9744       header_size = _gvn.transform(new AddINode(header_size, mask));
9745 
9746       // There is no need to mask or shift this value.
9747       // The semantics of LShiftINode include an implicit mask to 0x1F.
9748       assert(Klass::_lh_log2_element_size_shift == 0, "use shift in place");
9749       Node* elem_shift = layout_val;
9750 
9751       Node* lengthx = ConvI2X(arr_length);
9752       Node* headerx = ConvI2X(header_size);
9753 
9754       Node* abody = _gvn.transform(new LShiftXNode(lengthx, elem_shift));
9755       Node* size = _gvn.transform(new AddXNode(headerx, abody));
9756       if (round_mask != 0) {
9757         size = _gvn.transform(new AndXNode(size, MakeConX(~round_mask)));
9758       }
9759       size = ConvX2L(size);
9760 
9761       result_reg->init_req(_array_path, control());
9762       result_val->init_req(_array_path, size);
9763     }
9764 
9765     if (!stopped()) {
9766       // Instance case: the layout helper gives us instance size almost directly,
9767       // but we need to mask out the _lh_instance_slow_path_bit.
9768       Node* size = ConvI2X(layout_val);
9769       assert((int) Klass::_lh_instance_slow_path_bit < BytesPerLong, "clear bit");
9770       Node* mask = MakeConX(~(intptr_t) right_n_bits(LogBytesPerLong));
9771       size = _gvn.transform(new AndXNode(size, mask));
9772       size = ConvX2L(size);
9773 
9774       result_reg->init_req(_instance_path, control());
9775       result_val->init_req(_instance_path, size);
9776     }
9777 
9778     set_result(result_reg, result_val);
9779   }
9780 
9781   return true;
9782 }
9783 
9784 //------------------------------- inline_blackhole --------------------------------------
9785 //
9786 // Make sure all arguments to this node are alive.
9787 // This matches methods that were requested to be blackholed through compile commands.
9788 //
9789 bool LibraryCallKit::inline_blackhole() {
9790   assert(callee()->is_static(), "Should have been checked before: only static methods here");
9791   assert(callee()->is_empty(), "Should have been checked before: only empty methods here");
9792   assert(callee()->holder()->is_loaded(), "Should have been checked before: only methods for loaded classes here");
9793 
9794   // Blackhole node pinches only the control, not memory. This allows
9795   // the blackhole to be pinned in the loop that computes blackholed
9796   // values, but have no other side effects, like breaking the optimizations
9797   // across the blackhole.
9798 
9799   Node* bh = _gvn.transform(new BlackholeNode(control()));
9800   set_control(_gvn.transform(new ProjNode(bh, TypeFunc::Control)));
9801 
9802   // Bind call arguments as blackhole arguments to keep them alive
9803   uint nargs = callee()->arg_size();
9804   for (uint i = 0; i < nargs; i++) {
9805     bh->add_req(argument(i));
9806   }
9807 
9808   return true;
9809 }
9810 
9811 Node* LibraryCallKit::unbox_fp16_value(const TypeInstPtr* float16_box_type, ciField* field, Node* box) {
9812   const TypeInstPtr* box_type = _gvn.type(box)->isa_instptr();
9813   if (box_type == nullptr || box_type->instance_klass() != float16_box_type->instance_klass()) {
9814     return nullptr; // box klass is not Float16
9815   }
9816 
9817   // Null check; get notnull casted pointer
9818   Node* null_ctl = top();
9819   Node* not_null_box = null_check_oop(box, &null_ctl, true);
9820   // If not_null_box is dead, only null-path is taken
9821   if (stopped()) {
9822     set_control(null_ctl);
9823     return nullptr;
9824   }
9825   assert(not_null_box->bottom_type()->is_instptr()->maybe_null() == false, "");
9826   const TypePtr* adr_type = C->alias_type(field)->adr_type();
9827   Node* adr = basic_plus_adr(not_null_box, field->offset_in_bytes());
9828   return access_load_at(not_null_box, adr, adr_type, TypeInt::SHORT, T_SHORT, IN_HEAP);
9829 }
9830 
9831 Node* LibraryCallKit::box_fp16_value(const TypeInstPtr* float16_box_type, ciField* field, Node* value) {
9832   PreserveReexecuteState preexecs(this);
9833   jvms()->set_should_reexecute(true);
9834 
9835   const TypeKlassPtr* klass_type = float16_box_type->as_klass_type();
9836   Node* klass_node = makecon(klass_type);
9837   Node* box = new_instance(klass_node);
9838 
9839   Node* value_field = basic_plus_adr(box, field->offset_in_bytes());
9840   const TypePtr* value_adr_type = value_field->bottom_type()->is_ptr();
9841 
9842   Node* field_store = _gvn.transform(access_store_at(box,
9843                                                      value_field,
9844                                                      value_adr_type,
9845                                                      value,
9846                                                      TypeInt::SHORT,
9847                                                      T_SHORT,
9848                                                      IN_HEAP));
9849   set_memory(field_store, value_adr_type);
9850   return box;
9851 }
9852 
9853 bool LibraryCallKit::inline_fp16_operations(vmIntrinsics::ID id, int num_args) {
9854   if (!Matcher::match_rule_supported(Op_ReinterpretS2HF) ||
9855       !Matcher::match_rule_supported(Op_ReinterpretHF2S)) {
9856     return false;
9857   }
9858 
9859   const TypeInstPtr* box_type = _gvn.type(argument(0))->isa_instptr();
9860   if (box_type == nullptr || box_type->const_oop() == nullptr) {
9861     return false;
9862   }
9863 
9864   ciInstanceKlass* float16_klass = box_type->const_oop()->as_instance()->java_lang_Class_klass()->as_instance_klass();
9865   const TypeInstPtr* float16_box_type = TypeInstPtr::make_exact(TypePtr::NotNull, float16_klass);
9866   ciField* field = float16_klass->get_field_by_name(ciSymbols::value_name(),
9867                                                     ciSymbols::short_signature(),
9868                                                     false);
9869   assert(field != nullptr, "");
9870 
9871   // Transformed nodes
9872   Node* fld1 = nullptr;
9873   Node* fld2 = nullptr;
9874   Node* fld3 = nullptr;
9875   switch(num_args) {
9876     case 3:
9877       fld3 = unbox_fp16_value(float16_box_type, field, argument(3));
9878       if (fld3 == nullptr) {
9879         return false;
9880       }
9881       fld3 = _gvn.transform(new ReinterpretS2HFNode(fld3));
9882     // fall-through
9883     case 2:
9884       fld2 = unbox_fp16_value(float16_box_type, field, argument(2));
9885       if (fld2 == nullptr) {
9886         return false;
9887       }
9888       fld2 = _gvn.transform(new ReinterpretS2HFNode(fld2));
9889     // fall-through
9890     case 1:
9891       fld1 = unbox_fp16_value(float16_box_type, field, argument(1));
9892       if (fld1 == nullptr) {
9893         return false;
9894       }
9895       fld1 = _gvn.transform(new ReinterpretS2HFNode(fld1));
9896       break;
9897     default: fatal("Unsupported number of arguments %d", num_args);
9898   }
9899 
9900   Node* result = nullptr;
9901   switch (id) {
9902     // Unary operations
9903     case vmIntrinsics::_sqrt_float16:
9904       result = _gvn.transform(new SqrtHFNode(C, control(), fld1));
9905       break;
9906     // Ternary operations
9907     case vmIntrinsics::_fma_float16:
9908       result = _gvn.transform(new FmaHFNode(fld1, fld2, fld3));
9909       break;
9910     default:
9911       fatal_unexpected_iid(id);
9912       break;
9913   }
9914   result = _gvn.transform(new ReinterpretHF2SNode(result));
9915   set_result(box_fp16_value(float16_box_type, field, result));
9916   return true;
9917 }
9918