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::_makePrivateBuffer:        return inline_unsafe_make_private_buffer();
 335   case vmIntrinsics::_finishPrivateBuffer:      return inline_unsafe_finish_private_buffer();
 336   case vmIntrinsics::_getReference:             return inline_unsafe_access(!is_store, T_OBJECT,   Relaxed, false);
 337   case vmIntrinsics::_getBoolean:               return inline_unsafe_access(!is_store, T_BOOLEAN,  Relaxed, false);
 338   case vmIntrinsics::_getByte:                  return inline_unsafe_access(!is_store, T_BYTE,     Relaxed, false);
 339   case vmIntrinsics::_getShort:                 return inline_unsafe_access(!is_store, T_SHORT,    Relaxed, false);
 340   case vmIntrinsics::_getChar:                  return inline_unsafe_access(!is_store, T_CHAR,     Relaxed, false);
 341   case vmIntrinsics::_getInt:                   return inline_unsafe_access(!is_store, T_INT,      Relaxed, false);
 342   case vmIntrinsics::_getLong:                  return inline_unsafe_access(!is_store, T_LONG,     Relaxed, false);
 343   case vmIntrinsics::_getFloat:                 return inline_unsafe_access(!is_store, T_FLOAT,    Relaxed, false);
 344   case vmIntrinsics::_getDouble:                return inline_unsafe_access(!is_store, T_DOUBLE,   Relaxed, false);
 345 
 346   case vmIntrinsics::_putReference:             return inline_unsafe_access( is_store, T_OBJECT,   Relaxed, false);
 347   case vmIntrinsics::_putBoolean:               return inline_unsafe_access( is_store, T_BOOLEAN,  Relaxed, false);
 348   case vmIntrinsics::_putByte:                  return inline_unsafe_access( is_store, T_BYTE,     Relaxed, false);
 349   case vmIntrinsics::_putShort:                 return inline_unsafe_access( is_store, T_SHORT,    Relaxed, false);
 350   case vmIntrinsics::_putChar:                  return inline_unsafe_access( is_store, T_CHAR,     Relaxed, false);
 351   case vmIntrinsics::_putInt:                   return inline_unsafe_access( is_store, T_INT,      Relaxed, false);
 352   case vmIntrinsics::_putLong:                  return inline_unsafe_access( is_store, T_LONG,     Relaxed, false);
 353   case vmIntrinsics::_putFloat:                 return inline_unsafe_access( is_store, T_FLOAT,    Relaxed, false);
 354   case vmIntrinsics::_putDouble:                return inline_unsafe_access( is_store, T_DOUBLE,   Relaxed, false);
 355 
 356   case vmIntrinsics::_getReferenceVolatile:     return inline_unsafe_access(!is_store, T_OBJECT,   Volatile, false);
 357   case vmIntrinsics::_getBooleanVolatile:       return inline_unsafe_access(!is_store, T_BOOLEAN,  Volatile, false);
 358   case vmIntrinsics::_getByteVolatile:          return inline_unsafe_access(!is_store, T_BYTE,     Volatile, false);
 359   case vmIntrinsics::_getShortVolatile:         return inline_unsafe_access(!is_store, T_SHORT,    Volatile, false);
 360   case vmIntrinsics::_getCharVolatile:          return inline_unsafe_access(!is_store, T_CHAR,     Volatile, false);
 361   case vmIntrinsics::_getIntVolatile:           return inline_unsafe_access(!is_store, T_INT,      Volatile, false);
 362   case vmIntrinsics::_getLongVolatile:          return inline_unsafe_access(!is_store, T_LONG,     Volatile, false);
 363   case vmIntrinsics::_getFloatVolatile:         return inline_unsafe_access(!is_store, T_FLOAT,    Volatile, false);
 364   case vmIntrinsics::_getDoubleVolatile:        return inline_unsafe_access(!is_store, T_DOUBLE,   Volatile, false);
 365 
 366   case vmIntrinsics::_putReferenceVolatile:     return inline_unsafe_access( is_store, T_OBJECT,   Volatile, false);
 367   case vmIntrinsics::_putBooleanVolatile:       return inline_unsafe_access( is_store, T_BOOLEAN,  Volatile, false);
 368   case vmIntrinsics::_putByteVolatile:          return inline_unsafe_access( is_store, T_BYTE,     Volatile, false);
 369   case vmIntrinsics::_putShortVolatile:         return inline_unsafe_access( is_store, T_SHORT,    Volatile, false);
 370   case vmIntrinsics::_putCharVolatile:          return inline_unsafe_access( is_store, T_CHAR,     Volatile, false);
 371   case vmIntrinsics::_putIntVolatile:           return inline_unsafe_access( is_store, T_INT,      Volatile, false);
 372   case vmIntrinsics::_putLongVolatile:          return inline_unsafe_access( is_store, T_LONG,     Volatile, false);
 373   case vmIntrinsics::_putFloatVolatile:         return inline_unsafe_access( is_store, T_FLOAT,    Volatile, false);
 374   case vmIntrinsics::_putDoubleVolatile:        return inline_unsafe_access( is_store, T_DOUBLE,   Volatile, false);
 375 
 376   case vmIntrinsics::_getShortUnaligned:        return inline_unsafe_access(!is_store, T_SHORT,    Relaxed, true);
 377   case vmIntrinsics::_getCharUnaligned:         return inline_unsafe_access(!is_store, T_CHAR,     Relaxed, true);
 378   case vmIntrinsics::_getIntUnaligned:          return inline_unsafe_access(!is_store, T_INT,      Relaxed, true);
 379   case vmIntrinsics::_getLongUnaligned:         return inline_unsafe_access(!is_store, T_LONG,     Relaxed, true);
 380 
 381   case vmIntrinsics::_putShortUnaligned:        return inline_unsafe_access( is_store, T_SHORT,    Relaxed, true);
 382   case vmIntrinsics::_putCharUnaligned:         return inline_unsafe_access( is_store, T_CHAR,     Relaxed, true);
 383   case vmIntrinsics::_putIntUnaligned:          return inline_unsafe_access( is_store, T_INT,      Relaxed, true);
 384   case vmIntrinsics::_putLongUnaligned:         return inline_unsafe_access( is_store, T_LONG,     Relaxed, true);
 385 
 386   case vmIntrinsics::_getReferenceAcquire:      return inline_unsafe_access(!is_store, T_OBJECT,   Acquire, false);
 387   case vmIntrinsics::_getBooleanAcquire:        return inline_unsafe_access(!is_store, T_BOOLEAN,  Acquire, false);
 388   case vmIntrinsics::_getByteAcquire:           return inline_unsafe_access(!is_store, T_BYTE,     Acquire, false);
 389   case vmIntrinsics::_getShortAcquire:          return inline_unsafe_access(!is_store, T_SHORT,    Acquire, false);
 390   case vmIntrinsics::_getCharAcquire:           return inline_unsafe_access(!is_store, T_CHAR,     Acquire, false);
 391   case vmIntrinsics::_getIntAcquire:            return inline_unsafe_access(!is_store, T_INT,      Acquire, false);
 392   case vmIntrinsics::_getLongAcquire:           return inline_unsafe_access(!is_store, T_LONG,     Acquire, false);
 393   case vmIntrinsics::_getFloatAcquire:          return inline_unsafe_access(!is_store, T_FLOAT,    Acquire, false);
 394   case vmIntrinsics::_getDoubleAcquire:         return inline_unsafe_access(!is_store, T_DOUBLE,   Acquire, false);
 395 
 396   case vmIntrinsics::_putReferenceRelease:      return inline_unsafe_access( is_store, T_OBJECT,   Release, false);
 397   case vmIntrinsics::_putBooleanRelease:        return inline_unsafe_access( is_store, T_BOOLEAN,  Release, false);
 398   case vmIntrinsics::_putByteRelease:           return inline_unsafe_access( is_store, T_BYTE,     Release, false);
 399   case vmIntrinsics::_putShortRelease:          return inline_unsafe_access( is_store, T_SHORT,    Release, false);
 400   case vmIntrinsics::_putCharRelease:           return inline_unsafe_access( is_store, T_CHAR,     Release, false);
 401   case vmIntrinsics::_putIntRelease:            return inline_unsafe_access( is_store, T_INT,      Release, false);
 402   case vmIntrinsics::_putLongRelease:           return inline_unsafe_access( is_store, T_LONG,     Release, false);
 403   case vmIntrinsics::_putFloatRelease:          return inline_unsafe_access( is_store, T_FLOAT,    Release, false);
 404   case vmIntrinsics::_putDoubleRelease:         return inline_unsafe_access( is_store, T_DOUBLE,   Release, false);
 405 
 406   case vmIntrinsics::_getReferenceOpaque:       return inline_unsafe_access(!is_store, T_OBJECT,   Opaque, false);
 407   case vmIntrinsics::_getBooleanOpaque:         return inline_unsafe_access(!is_store, T_BOOLEAN,  Opaque, false);
 408   case vmIntrinsics::_getByteOpaque:            return inline_unsafe_access(!is_store, T_BYTE,     Opaque, false);
 409   case vmIntrinsics::_getShortOpaque:           return inline_unsafe_access(!is_store, T_SHORT,    Opaque, false);
 410   case vmIntrinsics::_getCharOpaque:            return inline_unsafe_access(!is_store, T_CHAR,     Opaque, false);
 411   case vmIntrinsics::_getIntOpaque:             return inline_unsafe_access(!is_store, T_INT,      Opaque, false);
 412   case vmIntrinsics::_getLongOpaque:            return inline_unsafe_access(!is_store, T_LONG,     Opaque, false);
 413   case vmIntrinsics::_getFloatOpaque:           return inline_unsafe_access(!is_store, T_FLOAT,    Opaque, false);
 414   case vmIntrinsics::_getDoubleOpaque:          return inline_unsafe_access(!is_store, T_DOUBLE,   Opaque, false);
 415 
 416   case vmIntrinsics::_putReferenceOpaque:       return inline_unsafe_access( is_store, T_OBJECT,   Opaque, false);
 417   case vmIntrinsics::_putBooleanOpaque:         return inline_unsafe_access( is_store, T_BOOLEAN,  Opaque, false);
 418   case vmIntrinsics::_putByteOpaque:            return inline_unsafe_access( is_store, T_BYTE,     Opaque, false);
 419   case vmIntrinsics::_putShortOpaque:           return inline_unsafe_access( is_store, T_SHORT,    Opaque, false);
 420   case vmIntrinsics::_putCharOpaque:            return inline_unsafe_access( is_store, T_CHAR,     Opaque, false);
 421   case vmIntrinsics::_putIntOpaque:             return inline_unsafe_access( is_store, T_INT,      Opaque, false);
 422   case vmIntrinsics::_putLongOpaque:            return inline_unsafe_access( is_store, T_LONG,     Opaque, false);
 423   case vmIntrinsics::_putFloatOpaque:           return inline_unsafe_access( is_store, T_FLOAT,    Opaque, false);
 424   case vmIntrinsics::_putDoubleOpaque:          return inline_unsafe_access( is_store, T_DOUBLE,   Opaque, false);
 425 
 426   case vmIntrinsics::_getFlatValue:             return inline_unsafe_flat_access(!is_store, Relaxed);
 427   case vmIntrinsics::_putFlatValue:             return inline_unsafe_flat_access( is_store, Relaxed);
 428 
 429   case vmIntrinsics::_compareAndSetReference:   return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap,      Volatile);
 430   case vmIntrinsics::_compareAndSetByte:        return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap,      Volatile);
 431   case vmIntrinsics::_compareAndSetShort:       return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap,      Volatile);
 432   case vmIntrinsics::_compareAndSetInt:         return inline_unsafe_load_store(T_INT,    LS_cmp_swap,      Volatile);
 433   case vmIntrinsics::_compareAndSetLong:        return inline_unsafe_load_store(T_LONG,   LS_cmp_swap,      Volatile);
 434 
 435   case vmIntrinsics::_weakCompareAndSetReferencePlain:     return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Relaxed);
 436   case vmIntrinsics::_weakCompareAndSetReferenceAcquire:   return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Acquire);
 437   case vmIntrinsics::_weakCompareAndSetReferenceRelease:   return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Release);
 438   case vmIntrinsics::_weakCompareAndSetReference:          return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Volatile);
 439   case vmIntrinsics::_weakCompareAndSetBytePlain:          return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap_weak, Relaxed);
 440   case vmIntrinsics::_weakCompareAndSetByteAcquire:        return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap_weak, Acquire);
 441   case vmIntrinsics::_weakCompareAndSetByteRelease:        return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap_weak, Release);
 442   case vmIntrinsics::_weakCompareAndSetByte:               return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap_weak, Volatile);
 443   case vmIntrinsics::_weakCompareAndSetShortPlain:         return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap_weak, Relaxed);
 444   case vmIntrinsics::_weakCompareAndSetShortAcquire:       return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap_weak, Acquire);
 445   case vmIntrinsics::_weakCompareAndSetShortRelease:       return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap_weak, Release);
 446   case vmIntrinsics::_weakCompareAndSetShort:              return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap_weak, Volatile);
 447   case vmIntrinsics::_weakCompareAndSetIntPlain:           return inline_unsafe_load_store(T_INT,    LS_cmp_swap_weak, Relaxed);
 448   case vmIntrinsics::_weakCompareAndSetIntAcquire:         return inline_unsafe_load_store(T_INT,    LS_cmp_swap_weak, Acquire);
 449   case vmIntrinsics::_weakCompareAndSetIntRelease:         return inline_unsafe_load_store(T_INT,    LS_cmp_swap_weak, Release);
 450   case vmIntrinsics::_weakCompareAndSetInt:                return inline_unsafe_load_store(T_INT,    LS_cmp_swap_weak, Volatile);
 451   case vmIntrinsics::_weakCompareAndSetLongPlain:          return inline_unsafe_load_store(T_LONG,   LS_cmp_swap_weak, Relaxed);
 452   case vmIntrinsics::_weakCompareAndSetLongAcquire:        return inline_unsafe_load_store(T_LONG,   LS_cmp_swap_weak, Acquire);
 453   case vmIntrinsics::_weakCompareAndSetLongRelease:        return inline_unsafe_load_store(T_LONG,   LS_cmp_swap_weak, Release);
 454   case vmIntrinsics::_weakCompareAndSetLong:               return inline_unsafe_load_store(T_LONG,   LS_cmp_swap_weak, Volatile);
 455 
 456   case vmIntrinsics::_compareAndExchangeReference:         return inline_unsafe_load_store(T_OBJECT, LS_cmp_exchange,  Volatile);
 457   case vmIntrinsics::_compareAndExchangeReferenceAcquire:  return inline_unsafe_load_store(T_OBJECT, LS_cmp_exchange,  Acquire);
 458   case vmIntrinsics::_compareAndExchangeReferenceRelease:  return inline_unsafe_load_store(T_OBJECT, LS_cmp_exchange,  Release);
 459   case vmIntrinsics::_compareAndExchangeByte:              return inline_unsafe_load_store(T_BYTE,   LS_cmp_exchange,  Volatile);
 460   case vmIntrinsics::_compareAndExchangeByteAcquire:       return inline_unsafe_load_store(T_BYTE,   LS_cmp_exchange,  Acquire);
 461   case vmIntrinsics::_compareAndExchangeByteRelease:       return inline_unsafe_load_store(T_BYTE,   LS_cmp_exchange,  Release);
 462   case vmIntrinsics::_compareAndExchangeShort:             return inline_unsafe_load_store(T_SHORT,  LS_cmp_exchange,  Volatile);
 463   case vmIntrinsics::_compareAndExchangeShortAcquire:      return inline_unsafe_load_store(T_SHORT,  LS_cmp_exchange,  Acquire);
 464   case vmIntrinsics::_compareAndExchangeShortRelease:      return inline_unsafe_load_store(T_SHORT,  LS_cmp_exchange,  Release);
 465   case vmIntrinsics::_compareAndExchangeInt:               return inline_unsafe_load_store(T_INT,    LS_cmp_exchange,  Volatile);
 466   case vmIntrinsics::_compareAndExchangeIntAcquire:        return inline_unsafe_load_store(T_INT,    LS_cmp_exchange,  Acquire);
 467   case vmIntrinsics::_compareAndExchangeIntRelease:        return inline_unsafe_load_store(T_INT,    LS_cmp_exchange,  Release);
 468   case vmIntrinsics::_compareAndExchangeLong:              return inline_unsafe_load_store(T_LONG,   LS_cmp_exchange,  Volatile);
 469   case vmIntrinsics::_compareAndExchangeLongAcquire:       return inline_unsafe_load_store(T_LONG,   LS_cmp_exchange,  Acquire);
 470   case vmIntrinsics::_compareAndExchangeLongRelease:       return inline_unsafe_load_store(T_LONG,   LS_cmp_exchange,  Release);
 471 
 472   case vmIntrinsics::_getAndAddByte:                    return inline_unsafe_load_store(T_BYTE,   LS_get_add,       Volatile);
 473   case vmIntrinsics::_getAndAddShort:                   return inline_unsafe_load_store(T_SHORT,  LS_get_add,       Volatile);
 474   case vmIntrinsics::_getAndAddInt:                     return inline_unsafe_load_store(T_INT,    LS_get_add,       Volatile);
 475   case vmIntrinsics::_getAndAddLong:                    return inline_unsafe_load_store(T_LONG,   LS_get_add,       Volatile);
 476 
 477   case vmIntrinsics::_getAndSetByte:                    return inline_unsafe_load_store(T_BYTE,   LS_get_set,       Volatile);
 478   case vmIntrinsics::_getAndSetShort:                   return inline_unsafe_load_store(T_SHORT,  LS_get_set,       Volatile);
 479   case vmIntrinsics::_getAndSetInt:                     return inline_unsafe_load_store(T_INT,    LS_get_set,       Volatile);
 480   case vmIntrinsics::_getAndSetLong:                    return inline_unsafe_load_store(T_LONG,   LS_get_set,       Volatile);
 481   case vmIntrinsics::_getAndSetReference:               return inline_unsafe_load_store(T_OBJECT, LS_get_set,       Volatile);
 482 
 483   case vmIntrinsics::_loadFence:
 484   case vmIntrinsics::_storeFence:
 485   case vmIntrinsics::_storeStoreFence:
 486   case vmIntrinsics::_fullFence:                return inline_unsafe_fence(intrinsic_id());
 487 
 488   case vmIntrinsics::_arrayInstanceBaseOffset:  return inline_arrayInstanceBaseOffset();
 489   case vmIntrinsics::_arrayInstanceIndexScale:  return inline_arrayInstanceIndexScale();
 490   case vmIntrinsics::_arrayLayout:              return inline_arrayLayout();
 491   case vmIntrinsics::_getFieldMap:              return inline_getFieldMap();
 492 
 493   case vmIntrinsics::_onSpinWait:               return inline_onspinwait();
 494 
 495   case vmIntrinsics::_currentCarrierThread:     return inline_native_currentCarrierThread();
 496   case vmIntrinsics::_currentThread:            return inline_native_currentThread();
 497   case vmIntrinsics::_setCurrentThread:         return inline_native_setCurrentThread();
 498 
 499   case vmIntrinsics::_scopedValueCache:          return inline_native_scopedValueCache();
 500   case vmIntrinsics::_setScopedValueCache:       return inline_native_setScopedValueCache();
 501 
 502   case vmIntrinsics::_Continuation_pin:          return inline_native_Continuation_pinning(false);
 503   case vmIntrinsics::_Continuation_unpin:        return inline_native_Continuation_pinning(true);
 504 
 505   case vmIntrinsics::_vthreadEndFirstTransition:    return inline_native_vthread_end_transition(CAST_FROM_FN_PTR(address, OptoRuntime::vthread_end_first_transition_Java()),
 506                                                                                                 "endFirstTransition", true);
 507   case vmIntrinsics::_vthreadStartFinalTransition:  return inline_native_vthread_start_transition(CAST_FROM_FN_PTR(address, OptoRuntime::vthread_start_final_transition_Java()),
 508                                                                                                   "startFinalTransition", true);
 509   case vmIntrinsics::_vthreadStartTransition:       return inline_native_vthread_start_transition(CAST_FROM_FN_PTR(address, OptoRuntime::vthread_start_transition_Java()),
 510                                                                                                   "startTransition", false);
 511   case vmIntrinsics::_vthreadEndTransition:         return inline_native_vthread_end_transition(CAST_FROM_FN_PTR(address, OptoRuntime::vthread_end_transition_Java()),
 512                                                                                                 "endTransition", false);
 513 #if INCLUDE_JVMTI
 514   case vmIntrinsics::_notifyJvmtiVThreadDisableSuspend: return inline_native_notify_jvmti_sync();
 515 #endif
 516 
 517 #ifdef JFR_HAVE_INTRINSICS
 518   case vmIntrinsics::_counterTime:              return inline_native_time_funcs(CAST_FROM_FN_PTR(address, JfrTime::time_function()), "counterTime");
 519   case vmIntrinsics::_getEventWriter:           return inline_native_getEventWriter();
 520   case vmIntrinsics::_jvm_commit:               return inline_native_jvm_commit();
 521 #endif
 522   case vmIntrinsics::_currentTimeMillis:        return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeMillis), "currentTimeMillis");
 523   case vmIntrinsics::_nanoTime:                 return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeNanos), "nanoTime");
 524   case vmIntrinsics::_writeback0:               return inline_unsafe_writeback0();
 525   case vmIntrinsics::_writebackPreSync0:        return inline_unsafe_writebackSync0(true);
 526   case vmIntrinsics::_writebackPostSync0:       return inline_unsafe_writebackSync0(false);
 527   case vmIntrinsics::_allocateInstance:         return inline_unsafe_allocate();
 528   case vmIntrinsics::_copyMemory:               return inline_unsafe_copyMemory();
 529   case vmIntrinsics::_setMemory:                return inline_unsafe_setMemory();
 530   case vmIntrinsics::_getLength:                return inline_native_getLength();
 531   case vmIntrinsics::_copyOf:                   return inline_array_copyOf(false);
 532   case vmIntrinsics::_copyOfRange:              return inline_array_copyOf(true);
 533   case vmIntrinsics::_equalsB:                  return inline_array_equals(StrIntrinsicNode::LL);
 534   case vmIntrinsics::_equalsC:                  return inline_array_equals(StrIntrinsicNode::UU);
 535   case vmIntrinsics::_Preconditions_checkIndex: return inline_preconditions_checkIndex(T_INT);
 536   case vmIntrinsics::_Preconditions_checkLongIndex: return inline_preconditions_checkIndex(T_LONG);
 537   case vmIntrinsics::_clone:                    return inline_native_clone(intrinsic()->is_virtual());
 538 
 539   case vmIntrinsics::_allocateUninitializedArray: return inline_unsafe_newArray(true);
 540   case vmIntrinsics::_newArray:                   return inline_unsafe_newArray(false);
 541   case vmIntrinsics::_newNullRestrictedNonAtomicArray: return inline_newArray(/* null_free */ true, /* atomic */ false);
 542   case vmIntrinsics::_newNullRestrictedAtomicArray: return inline_newArray(/* null_free */ true, /* atomic */ true);
 543   case vmIntrinsics::_newNullableAtomicArray:     return inline_newArray(/* null_free */ false, /* atomic */ true);
 544   case vmIntrinsics::_isFlatArray:              return inline_getArrayProperties(IsFlat);
 545   case vmIntrinsics::_isNullRestrictedArray:    return inline_getArrayProperties(IsNullRestricted);
 546   case vmIntrinsics::_isAtomicArray:            return inline_getArrayProperties(IsAtomic);
 547 
 548   case vmIntrinsics::_isAssignableFrom:         return inline_native_subtype_check();
 549 
 550   case vmIntrinsics::_isInstance:
 551   case vmIntrinsics::_isHidden:
 552   case vmIntrinsics::_getSuperclass:            return inline_native_Class_query(intrinsic_id());
 553 
 554   case vmIntrinsics::_floatToRawIntBits:
 555   case vmIntrinsics::_floatToIntBits:
 556   case vmIntrinsics::_intBitsToFloat:
 557   case vmIntrinsics::_doubleToRawLongBits:
 558   case vmIntrinsics::_doubleToLongBits:
 559   case vmIntrinsics::_longBitsToDouble:
 560   case vmIntrinsics::_floatToFloat16:
 561   case vmIntrinsics::_float16ToFloat:           return inline_fp_conversions(intrinsic_id());
 562   case vmIntrinsics::_sqrt_float16:             return inline_fp16_operations(intrinsic_id(), 1);
 563   case vmIntrinsics::_fma_float16:              return inline_fp16_operations(intrinsic_id(), 3);
 564   case vmIntrinsics::_floatIsFinite:
 565   case vmIntrinsics::_floatIsInfinite:
 566   case vmIntrinsics::_doubleIsFinite:
 567   case vmIntrinsics::_doubleIsInfinite:         return inline_fp_range_check(intrinsic_id());
 568 
 569   case vmIntrinsics::_numberOfLeadingZeros_i:
 570   case vmIntrinsics::_numberOfLeadingZeros_l:
 571   case vmIntrinsics::_numberOfTrailingZeros_i:
 572   case vmIntrinsics::_numberOfTrailingZeros_l:
 573   case vmIntrinsics::_bitCount_i:
 574   case vmIntrinsics::_bitCount_l:
 575   case vmIntrinsics::_reverse_i:
 576   case vmIntrinsics::_reverse_l:
 577   case vmIntrinsics::_reverseBytes_i:
 578   case vmIntrinsics::_reverseBytes_l:
 579   case vmIntrinsics::_reverseBytes_s:
 580   case vmIntrinsics::_reverseBytes_c:           return inline_number_methods(intrinsic_id());
 581 
 582   case vmIntrinsics::_compress_i:
 583   case vmIntrinsics::_compress_l:
 584   case vmIntrinsics::_expand_i:
 585   case vmIntrinsics::_expand_l:                 return inline_bitshuffle_methods(intrinsic_id());
 586 
 587   case vmIntrinsics::_compareUnsigned_i:
 588   case vmIntrinsics::_compareUnsigned_l:        return inline_compare_unsigned(intrinsic_id());
 589 
 590   case vmIntrinsics::_divideUnsigned_i:
 591   case vmIntrinsics::_divideUnsigned_l:
 592   case vmIntrinsics::_remainderUnsigned_i:
 593   case vmIntrinsics::_remainderUnsigned_l:      return inline_divmod_methods(intrinsic_id());
 594 
 595   case vmIntrinsics::_getCallerClass:           return inline_native_Reflection_getCallerClass();
 596 
 597   case vmIntrinsics::_Reference_get0:           return inline_reference_get0();
 598   case vmIntrinsics::_Reference_refersTo0:      return inline_reference_refersTo0(false);
 599   case vmIntrinsics::_PhantomReference_refersTo0: return inline_reference_refersTo0(true);
 600   case vmIntrinsics::_Reference_clear0:         return inline_reference_clear0(false);
 601   case vmIntrinsics::_PhantomReference_clear0:  return inline_reference_clear0(true);
 602 
 603   case vmIntrinsics::_Class_cast:               return inline_Class_cast();
 604 
 605   case vmIntrinsics::_aescrypt_encryptBlock:
 606   case vmIntrinsics::_aescrypt_decryptBlock:    return inline_aescrypt_Block(intrinsic_id());
 607 
 608   case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
 609   case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
 610     return inline_cipherBlockChaining_AESCrypt(intrinsic_id());
 611 
 612   case vmIntrinsics::_electronicCodeBook_encryptAESCrypt:
 613   case vmIntrinsics::_electronicCodeBook_decryptAESCrypt:
 614     return inline_electronicCodeBook_AESCrypt(intrinsic_id());
 615 
 616   case vmIntrinsics::_counterMode_AESCrypt:
 617     return inline_counterMode_AESCrypt(intrinsic_id());
 618 
 619   case vmIntrinsics::_galoisCounterMode_AESCrypt:
 620     return inline_galoisCounterMode_AESCrypt();
 621 
 622   case vmIntrinsics::_md5_implCompress:
 623   case vmIntrinsics::_sha_implCompress:
 624   case vmIntrinsics::_sha2_implCompress:
 625   case vmIntrinsics::_sha5_implCompress:
 626   case vmIntrinsics::_sha3_implCompress:
 627     return inline_digestBase_implCompress(intrinsic_id());
 628   case vmIntrinsics::_double_keccak:
 629     return inline_double_keccak();
 630 
 631   case vmIntrinsics::_digestBase_implCompressMB:
 632     return inline_digestBase_implCompressMB(predicate);
 633 
 634   case vmIntrinsics::_multiplyToLen:
 635     return inline_multiplyToLen();
 636 
 637   case vmIntrinsics::_squareToLen:
 638     return inline_squareToLen();
 639 
 640   case vmIntrinsics::_mulAdd:
 641     return inline_mulAdd();
 642 
 643   case vmIntrinsics::_montgomeryMultiply:
 644     return inline_montgomeryMultiply();
 645   case vmIntrinsics::_montgomerySquare:
 646     return inline_montgomerySquare();
 647 
 648   case vmIntrinsics::_bigIntegerRightShiftWorker:
 649     return inline_bigIntegerShift(true);
 650   case vmIntrinsics::_bigIntegerLeftShiftWorker:
 651     return inline_bigIntegerShift(false);
 652 
 653   case vmIntrinsics::_vectorizedMismatch:
 654     return inline_vectorizedMismatch();
 655 
 656   case vmIntrinsics::_ghash_processBlocks:
 657     return inline_ghash_processBlocks();
 658   case vmIntrinsics::_chacha20Block:
 659     return inline_chacha20Block();
 660   case vmIntrinsics::_kyberNtt:
 661     return inline_kyberNtt();
 662   case vmIntrinsics::_kyberInverseNtt:
 663     return inline_kyberInverseNtt();
 664   case vmIntrinsics::_kyberNttMult:
 665     return inline_kyberNttMult();
 666   case vmIntrinsics::_kyberAddPoly_2:
 667     return inline_kyberAddPoly_2();
 668   case vmIntrinsics::_kyberAddPoly_3:
 669     return inline_kyberAddPoly_3();
 670   case vmIntrinsics::_kyber12To16:
 671     return inline_kyber12To16();
 672   case vmIntrinsics::_kyberBarrettReduce:
 673     return inline_kyberBarrettReduce();
 674   case vmIntrinsics::_dilithiumAlmostNtt:
 675     return inline_dilithiumAlmostNtt();
 676   case vmIntrinsics::_dilithiumAlmostInverseNtt:
 677     return inline_dilithiumAlmostInverseNtt();
 678   case vmIntrinsics::_dilithiumNttMult:
 679     return inline_dilithiumNttMult();
 680   case vmIntrinsics::_dilithiumMontMulByConstant:
 681     return inline_dilithiumMontMulByConstant();
 682   case vmIntrinsics::_dilithiumDecomposePoly:
 683     return inline_dilithiumDecomposePoly();
 684   case vmIntrinsics::_base64_encodeBlock:
 685     return inline_base64_encodeBlock();
 686   case vmIntrinsics::_base64_decodeBlock:
 687     return inline_base64_decodeBlock();
 688   case vmIntrinsics::_poly1305_processBlocks:
 689     return inline_poly1305_processBlocks();
 690   case vmIntrinsics::_intpoly_montgomeryMult_P256:
 691     return inline_intpoly_montgomeryMult_P256();
 692   case vmIntrinsics::_intpoly_assign:
 693     return inline_intpoly_assign();
 694   case vmIntrinsics::_encodeISOArray:
 695   case vmIntrinsics::_encodeByteISOArray:
 696     return inline_encodeISOArray(false);
 697   case vmIntrinsics::_encodeAsciiArray:
 698     return inline_encodeISOArray(true);
 699 
 700   case vmIntrinsics::_updateCRC32:
 701     return inline_updateCRC32();
 702   case vmIntrinsics::_updateBytesCRC32:
 703     return inline_updateBytesCRC32();
 704   case vmIntrinsics::_updateByteBufferCRC32:
 705     return inline_updateByteBufferCRC32();
 706 
 707   case vmIntrinsics::_updateBytesCRC32C:
 708     return inline_updateBytesCRC32C();
 709   case vmIntrinsics::_updateDirectByteBufferCRC32C:
 710     return inline_updateDirectByteBufferCRC32C();
 711 
 712   case vmIntrinsics::_updateBytesAdler32:
 713     return inline_updateBytesAdler32();
 714   case vmIntrinsics::_updateByteBufferAdler32:
 715     return inline_updateByteBufferAdler32();
 716 
 717   case vmIntrinsics::_profileBoolean:
 718     return inline_profileBoolean();
 719   case vmIntrinsics::_isCompileConstant:
 720     return inline_isCompileConstant();
 721 
 722   case vmIntrinsics::_countPositives:
 723     return inline_countPositives();
 724 
 725   case vmIntrinsics::_fmaD:
 726   case vmIntrinsics::_fmaF:
 727     return inline_fma(intrinsic_id());
 728 
 729   case vmIntrinsics::_isDigit:
 730   case vmIntrinsics::_isLowerCase:
 731   case vmIntrinsics::_isUpperCase:
 732   case vmIntrinsics::_isWhitespace:
 733     return inline_character_compare(intrinsic_id());
 734 
 735   case vmIntrinsics::_min:
 736   case vmIntrinsics::_max:
 737   case vmIntrinsics::_min_strict:
 738   case vmIntrinsics::_max_strict:
 739   case vmIntrinsics::_minL:
 740   case vmIntrinsics::_maxL:
 741   case vmIntrinsics::_minF:
 742   case vmIntrinsics::_maxF:
 743   case vmIntrinsics::_minD:
 744   case vmIntrinsics::_maxD:
 745   case vmIntrinsics::_minF_strict:
 746   case vmIntrinsics::_maxF_strict:
 747   case vmIntrinsics::_minD_strict:
 748   case vmIntrinsics::_maxD_strict:
 749     return inline_min_max(intrinsic_id());
 750 
 751   case vmIntrinsics::_VectorUnaryOp:
 752     return inline_vector_nary_operation(1);
 753   case vmIntrinsics::_VectorBinaryOp:
 754     return inline_vector_nary_operation(2);
 755   case vmIntrinsics::_VectorUnaryLibOp:
 756     return inline_vector_call(1);
 757   case vmIntrinsics::_VectorBinaryLibOp:
 758     return inline_vector_call(2);
 759   case vmIntrinsics::_VectorTernaryOp:
 760     return inline_vector_nary_operation(3);
 761   case vmIntrinsics::_VectorFromBitsCoerced:
 762     return inline_vector_frombits_coerced();
 763   case vmIntrinsics::_VectorMaskOp:
 764     return inline_vector_mask_operation();
 765   case vmIntrinsics::_VectorLoadOp:
 766     return inline_vector_mem_operation(/*is_store=*/false);
 767   case vmIntrinsics::_VectorLoadMaskedOp:
 768     return inline_vector_mem_masked_operation(/*is_store*/false);
 769   case vmIntrinsics::_VectorStoreOp:
 770     return inline_vector_mem_operation(/*is_store=*/true);
 771   case vmIntrinsics::_VectorStoreMaskedOp:
 772     return inline_vector_mem_masked_operation(/*is_store=*/true);
 773   case vmIntrinsics::_VectorGatherOp:
 774     return inline_vector_gather_scatter(/*is_scatter*/ false);
 775   case vmIntrinsics::_VectorScatterOp:
 776     return inline_vector_gather_scatter(/*is_scatter*/ true);
 777   case vmIntrinsics::_VectorReductionCoerced:
 778     return inline_vector_reduction();
 779   case vmIntrinsics::_VectorTest:
 780     return inline_vector_test();
 781   case vmIntrinsics::_VectorBlend:
 782     return inline_vector_blend();
 783   case vmIntrinsics::_VectorRearrange:
 784     return inline_vector_rearrange();
 785   case vmIntrinsics::_VectorSelectFrom:
 786     return inline_vector_select_from();
 787   case vmIntrinsics::_VectorCompare:
 788     return inline_vector_compare();
 789   case vmIntrinsics::_VectorBroadcastInt:
 790     return inline_vector_broadcast_int();
 791   case vmIntrinsics::_VectorConvert:
 792     return inline_vector_convert();
 793   case vmIntrinsics::_VectorInsert:
 794     return inline_vector_insert();
 795   case vmIntrinsics::_VectorExtract:
 796     return inline_vector_extract();
 797   case vmIntrinsics::_VectorCompressExpand:
 798     return inline_vector_compress_expand();
 799   case vmIntrinsics::_VectorSelectFromTwoVectorOp:
 800     return inline_vector_select_from_two_vectors();
 801   case vmIntrinsics::_IndexVector:
 802     return inline_index_vector();
 803   case vmIntrinsics::_IndexPartiallyInUpperRange:
 804     return inline_index_partially_in_upper_range();
 805 
 806   case vmIntrinsics::_getObjectSize:
 807     return inline_getObjectSize();
 808 
 809   case vmIntrinsics::_blackhole:
 810     return inline_blackhole();
 811 
 812   default:
 813     // If you get here, it may be that someone has added a new intrinsic
 814     // to the list in vmIntrinsics.hpp without implementing it here.
 815 #ifndef PRODUCT
 816     if ((PrintMiscellaneous && (Verbose || WizardMode)) || PrintOpto) {
 817       tty->print_cr("*** Warning: Unimplemented intrinsic %s(%d)",
 818                     vmIntrinsics::name_at(intrinsic_id()), vmIntrinsics::as_int(intrinsic_id()));
 819     }
 820 #endif
 821     return false;
 822   }
 823 }
 824 
 825 Node* LibraryCallKit::try_to_predicate(int predicate) {
 826   if (!jvms()->has_method()) {
 827     // Root JVMState has a null method.
 828     assert(map()->memory()->Opcode() == Op_Parm, "");
 829     // Insert the memory aliasing node
 830     set_all_memory(reset_memory());
 831   }
 832   assert(merged_memory(), "");
 833 
 834   switch (intrinsic_id()) {
 835   case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
 836     return inline_cipherBlockChaining_AESCrypt_predicate(false);
 837   case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
 838     return inline_cipherBlockChaining_AESCrypt_predicate(true);
 839   case vmIntrinsics::_electronicCodeBook_encryptAESCrypt:
 840     return inline_electronicCodeBook_AESCrypt_predicate(false);
 841   case vmIntrinsics::_electronicCodeBook_decryptAESCrypt:
 842     return inline_electronicCodeBook_AESCrypt_predicate(true);
 843   case vmIntrinsics::_counterMode_AESCrypt:
 844     return inline_counterMode_AESCrypt_predicate();
 845   case vmIntrinsics::_digestBase_implCompressMB:
 846     return inline_digestBase_implCompressMB_predicate(predicate);
 847   case vmIntrinsics::_galoisCounterMode_AESCrypt:
 848     return inline_galoisCounterMode_AESCrypt_predicate();
 849 
 850   default:
 851     // If you get here, it may be that someone has added a new intrinsic
 852     // to the list in vmIntrinsics.hpp without implementing it here.
 853 #ifndef PRODUCT
 854     if ((PrintMiscellaneous && (Verbose || WizardMode)) || PrintOpto) {
 855       tty->print_cr("*** Warning: Unimplemented predicate for intrinsic %s(%d)",
 856                     vmIntrinsics::name_at(intrinsic_id()), vmIntrinsics::as_int(intrinsic_id()));
 857     }
 858 #endif
 859     Node* slow_ctl = control();
 860     set_control(top()); // No fast path intrinsic
 861     return slow_ctl;
 862   }
 863 }
 864 
 865 //------------------------------set_result-------------------------------
 866 // Helper function for finishing intrinsics.
 867 void LibraryCallKit::set_result(RegionNode* region, PhiNode* value) {
 868   record_for_igvn(region);
 869   set_control(_gvn.transform(region));
 870   set_result( _gvn.transform(value));
 871   assert(value->type()->basic_type() == result()->bottom_type()->basic_type(), "sanity");
 872 }
 873 
 874 //------------------------------generate_guard---------------------------
 875 // Helper function for generating guarded fast-slow graph structures.
 876 // The given 'test', if true, guards a slow path.  If the test fails
 877 // then a fast path can be taken.  (We generally hope it fails.)
 878 // In all cases, GraphKit::control() is updated to the fast path.
 879 // The returned value represents the control for the slow path.
 880 // The return value is never 'top'; it is either a valid control
 881 // or null if it is obvious that the slow path can never be taken.
 882 // Also, if region and the slow control are not null, the slow edge
 883 // is appended to the region.
 884 Node* LibraryCallKit::generate_guard(Node* test, RegionNode* region, float true_prob) {
 885   if (stopped()) {
 886     // Already short circuited.
 887     return nullptr;
 888   }
 889 
 890   // Build an if node and its projections.
 891   // If test is true we take the slow path, which we assume is uncommon.
 892   if (_gvn.type(test) == TypeInt::ZERO) {
 893     // The slow branch is never taken.  No need to build this guard.
 894     return nullptr;
 895   }
 896 
 897   IfNode* iff = create_and_map_if(control(), test, true_prob, COUNT_UNKNOWN);
 898 
 899   Node* if_slow = _gvn.transform(new IfTrueNode(iff));
 900   if (if_slow == top()) {
 901     // The slow branch is never taken.  No need to build this guard.
 902     return nullptr;
 903   }
 904 
 905   if (region != nullptr)
 906     region->add_req(if_slow);
 907 
 908   Node* if_fast = _gvn.transform(new IfFalseNode(iff));
 909   set_control(if_fast);
 910 
 911   return if_slow;
 912 }
 913 
 914 inline Node* LibraryCallKit::generate_slow_guard(Node* test, RegionNode* region) {
 915   return generate_guard(test, region, PROB_UNLIKELY_MAG(3));
 916 }
 917 inline Node* LibraryCallKit::generate_fair_guard(Node* test, RegionNode* region) {
 918   return generate_guard(test, region, PROB_FAIR);
 919 }
 920 
 921 inline Node* LibraryCallKit::generate_negative_guard(Node* index, RegionNode* region,
 922                                                      Node* *pos_index) {
 923   if (stopped())
 924     return nullptr;                // already stopped
 925   if (_gvn.type(index)->higher_equal(TypeInt::POS)) // [0,maxint]
 926     return nullptr;                // index is already adequately typed
 927   Node* cmp_lt = _gvn.transform(new CmpINode(index, intcon(0)));
 928   Node* bol_lt = _gvn.transform(new BoolNode(cmp_lt, BoolTest::lt));
 929   Node* is_neg = generate_guard(bol_lt, region, PROB_MIN);
 930   if (is_neg != nullptr && pos_index != nullptr) {
 931     // Emulate effect of Parse::adjust_map_after_if.
 932     Node* ccast = new CastIINode(control(), index, TypeInt::POS);
 933     (*pos_index) = _gvn.transform(ccast);
 934   }
 935   return is_neg;
 936 }
 937 
 938 // Make sure that 'position' is a valid limit index, in [0..length].
 939 // There are two equivalent plans for checking this:
 940 //   A. (offset + copyLength)  unsigned<=  arrayLength
 941 //   B. offset  <=  (arrayLength - copyLength)
 942 // We require that all of the values above, except for the sum and
 943 // difference, are already known to be non-negative.
 944 // Plan A is robust in the face of overflow, if offset and copyLength
 945 // are both hugely positive.
 946 //
 947 // Plan B is less direct and intuitive, but it does not overflow at
 948 // all, since the difference of two non-negatives is always
 949 // representable.  Whenever Java methods must perform the equivalent
 950 // check they generally use Plan B instead of Plan A.
 951 // For the moment we use Plan A.
 952 inline Node* LibraryCallKit::generate_limit_guard(Node* offset,
 953                                                   Node* subseq_length,
 954                                                   Node* array_length,
 955                                                   RegionNode* region) {
 956   if (stopped())
 957     return nullptr;                // already stopped
 958   bool zero_offset = _gvn.type(offset) == TypeInt::ZERO;
 959   if (zero_offset && subseq_length->eqv_uncast(array_length))
 960     return nullptr;                // common case of whole-array copy
 961   Node* last = subseq_length;
 962   if (!zero_offset)             // last += offset
 963     last = _gvn.transform(new AddINode(last, offset));
 964   Node* cmp_lt = _gvn.transform(new CmpUNode(array_length, last));
 965   Node* bol_lt = _gvn.transform(new BoolNode(cmp_lt, BoolTest::lt));
 966   Node* is_over = generate_guard(bol_lt, region, PROB_MIN);
 967   return is_over;
 968 }
 969 
 970 // Emit range checks for the given String.value byte array
 971 void LibraryCallKit::generate_string_range_check(Node* array, Node* offset, Node* count, bool char_count) {
 972   if (stopped()) {
 973     return; // already stopped
 974   }
 975   RegionNode* bailout = new RegionNode(1);
 976   record_for_igvn(bailout);
 977   if (char_count) {
 978     // Convert char count to byte count
 979     count = _gvn.transform(new LShiftINode(count, intcon(1)));
 980   }
 981 
 982   // Offset and count must not be negative
 983   generate_negative_guard(offset, bailout);
 984   generate_negative_guard(count, bailout);
 985   // Offset + count must not exceed length of array
 986   generate_limit_guard(offset, count, load_array_length(array), bailout);
 987 
 988   if (bailout->req() > 1) {
 989     PreserveJVMState pjvms(this);
 990     set_control(_gvn.transform(bailout));
 991     uncommon_trap(Deoptimization::Reason_intrinsic,
 992                   Deoptimization::Action_maybe_recompile);
 993   }
 994 }
 995 
 996 Node* LibraryCallKit::current_thread_helper(Node*& tls_output, ByteSize handle_offset,
 997                                             bool is_immutable) {
 998   ciKlass* thread_klass = env()->Thread_klass();
 999   const Type* thread_type
1000     = TypeOopPtr::make_from_klass(thread_klass)->cast_to_ptr_type(TypePtr::NotNull);
1001 
1002   Node* thread = _gvn.transform(new ThreadLocalNode());
1003   Node* p = basic_plus_adr(top()/*!oop*/, thread, in_bytes(handle_offset));
1004   tls_output = thread;
1005 
1006   Node* thread_obj_handle
1007     = (is_immutable
1008       ? LoadNode::make(_gvn, nullptr, immutable_memory(), p, p->bottom_type()->is_ptr(),
1009         TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered)
1010       : make_load(nullptr, p, p->bottom_type()->is_ptr(), T_ADDRESS, MemNode::unordered));
1011   thread_obj_handle = _gvn.transform(thread_obj_handle);
1012 
1013   DecoratorSet decorators = IN_NATIVE;
1014   if (is_immutable) {
1015     decorators |= C2_IMMUTABLE_MEMORY;
1016   }
1017   return access_load(thread_obj_handle, thread_type, T_OBJECT, decorators);
1018 }
1019 
1020 //--------------------------generate_current_thread--------------------
1021 Node* LibraryCallKit::generate_current_thread(Node* &tls_output) {
1022   return current_thread_helper(tls_output, JavaThread::threadObj_offset(),
1023                                /*is_immutable*/false);
1024 }
1025 
1026 //--------------------------generate_virtual_thread--------------------
1027 Node* LibraryCallKit::generate_virtual_thread(Node* tls_output) {
1028   return current_thread_helper(tls_output, JavaThread::vthread_offset(),
1029                                !C->method()->changes_current_thread());
1030 }
1031 
1032 //------------------------------make_string_method_node------------------------
1033 // Helper method for String intrinsic functions. This version is called with
1034 // str1 and str2 pointing to byte[] nodes containing Latin1 or UTF16 encoded
1035 // characters (depending on 'is_byte'). cnt1 and cnt2 are pointing to Int nodes
1036 // containing the lengths of str1 and str2.
1037 Node* LibraryCallKit::make_string_method_node(int opcode, Node* str1_start, Node* cnt1, Node* str2_start, Node* cnt2, StrIntrinsicNode::ArgEnc ae) {
1038   Node* result = nullptr;
1039   switch (opcode) {
1040   case Op_StrIndexOf:
1041     result = new StrIndexOfNode(control(), memory(TypeAryPtr::BYTES),
1042                                 str1_start, cnt1, str2_start, cnt2, ae);
1043     break;
1044   case Op_StrComp:
1045     result = new StrCompNode(control(), memory(TypeAryPtr::BYTES),
1046                              str1_start, cnt1, str2_start, cnt2, ae);
1047     break;
1048   case Op_StrEquals:
1049     // We already know that cnt1 == cnt2 here (checked in 'inline_string_equals').
1050     // Use the constant length if there is one because optimized match rule may exist.
1051     result = new StrEqualsNode(control(), memory(TypeAryPtr::BYTES),
1052                                str1_start, str2_start, cnt2->is_Con() ? cnt2 : cnt1, ae);
1053     break;
1054   default:
1055     ShouldNotReachHere();
1056     return nullptr;
1057   }
1058 
1059   // All these intrinsics have checks.
1060   C->set_has_split_ifs(true); // Has chance for split-if optimization
1061   clear_upper_avx();
1062 
1063   return _gvn.transform(result);
1064 }
1065 
1066 //------------------------------inline_string_compareTo------------------------
1067 bool LibraryCallKit::inline_string_compareTo(StrIntrinsicNode::ArgEnc ae) {
1068   Node* arg1 = argument(0);
1069   Node* arg2 = argument(1);
1070 
1071   arg1 = must_be_not_null(arg1, true);
1072   arg2 = must_be_not_null(arg2, true);
1073 
1074   // Get start addr and length of first argument
1075   Node* arg1_start  = array_element_address(arg1, intcon(0), T_BYTE);
1076   Node* arg1_cnt    = load_array_length(arg1);
1077 
1078   // Get start addr and length of second argument
1079   Node* arg2_start  = array_element_address(arg2, intcon(0), T_BYTE);
1080   Node* arg2_cnt    = load_array_length(arg2);
1081 
1082   Node* result = make_string_method_node(Op_StrComp, arg1_start, arg1_cnt, arg2_start, arg2_cnt, ae);
1083   set_result(result);
1084   return true;
1085 }
1086 
1087 //------------------------------inline_string_equals------------------------
1088 bool LibraryCallKit::inline_string_equals(StrIntrinsicNode::ArgEnc ae) {
1089   Node* arg1 = argument(0);
1090   Node* arg2 = argument(1);
1091 
1092   // paths (plus control) merge
1093   RegionNode* region = new RegionNode(3);
1094   Node* phi = new PhiNode(region, TypeInt::BOOL);
1095 
1096   if (!stopped()) {
1097 
1098     arg1 = must_be_not_null(arg1, true);
1099     arg2 = must_be_not_null(arg2, true);
1100 
1101     // Get start addr and length of first argument
1102     Node* arg1_start  = array_element_address(arg1, intcon(0), T_BYTE);
1103     Node* arg1_cnt    = load_array_length(arg1);
1104 
1105     // Get start addr and length of second argument
1106     Node* arg2_start  = array_element_address(arg2, intcon(0), T_BYTE);
1107     Node* arg2_cnt    = load_array_length(arg2);
1108 
1109     // Check for arg1_cnt != arg2_cnt
1110     Node* cmp = _gvn.transform(new CmpINode(arg1_cnt, arg2_cnt));
1111     Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::ne));
1112     Node* if_ne = generate_slow_guard(bol, nullptr);
1113     if (if_ne != nullptr) {
1114       phi->init_req(2, intcon(0));
1115       region->init_req(2, if_ne);
1116     }
1117 
1118     // Check for count == 0 is done by assembler code for StrEquals.
1119 
1120     if (!stopped()) {
1121       Node* equals = make_string_method_node(Op_StrEquals, arg1_start, arg1_cnt, arg2_start, arg2_cnt, ae);
1122       phi->init_req(1, equals);
1123       region->init_req(1, control());
1124     }
1125   }
1126 
1127   // post merge
1128   set_control(_gvn.transform(region));
1129   record_for_igvn(region);
1130 
1131   set_result(_gvn.transform(phi));
1132   return true;
1133 }
1134 
1135 //------------------------------inline_array_equals----------------------------
1136 bool LibraryCallKit::inline_array_equals(StrIntrinsicNode::ArgEnc ae) {
1137   assert(ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::LL, "unsupported array types");
1138   Node* arg1 = argument(0);
1139   Node* arg2 = argument(1);
1140 
1141   const TypeAryPtr* mtype = (ae == StrIntrinsicNode::UU) ? TypeAryPtr::CHARS : TypeAryPtr::BYTES;
1142   set_result(_gvn.transform(new AryEqNode(control(), memory(mtype), arg1, arg2, ae)));
1143   clear_upper_avx();
1144 
1145   return true;
1146 }
1147 
1148 
1149 //------------------------------inline_countPositives------------------------------
1150 bool LibraryCallKit::inline_countPositives() {
1151   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1152     return false;
1153   }
1154 
1155   assert(callee()->signature()->size() == 3, "countPositives has 3 parameters");
1156   // no receiver since it is static method
1157   Node* ba         = argument(0);
1158   Node* offset     = argument(1);
1159   Node* len        = argument(2);
1160 
1161   ba = must_be_not_null(ba, true);
1162 
1163   // Range checks
1164   generate_string_range_check(ba, offset, len, false);
1165   if (stopped()) {
1166     return true;
1167   }
1168   Node* ba_start = array_element_address(ba, offset, T_BYTE);
1169   Node* result = new CountPositivesNode(control(), memory(TypeAryPtr::BYTES), ba_start, len);
1170   set_result(_gvn.transform(result));
1171   clear_upper_avx();
1172   return true;
1173 }
1174 
1175 bool LibraryCallKit::inline_preconditions_checkIndex(BasicType bt) {
1176   Node* index = argument(0);
1177   Node* length = bt == T_INT ? argument(1) : argument(2);
1178   if (too_many_traps(Deoptimization::Reason_intrinsic) || too_many_traps(Deoptimization::Reason_range_check)) {
1179     return false;
1180   }
1181 
1182   // check that length is positive
1183   Node* len_pos_cmp = _gvn.transform(CmpNode::make(length, integercon(0, bt), bt));
1184   Node* len_pos_bol = _gvn.transform(new BoolNode(len_pos_cmp, BoolTest::ge));
1185 
1186   {
1187     BuildCutout unless(this, len_pos_bol, PROB_MAX);
1188     uncommon_trap(Deoptimization::Reason_intrinsic,
1189                   Deoptimization::Action_make_not_entrant);
1190   }
1191 
1192   if (stopped()) {
1193     // Length is known to be always negative during compilation and the IR graph so far constructed is good so return success
1194     return true;
1195   }
1196 
1197   // length is now known positive, add a cast node to make this explicit
1198   jlong upper_bound = _gvn.type(length)->is_integer(bt)->hi_as_long();
1199   Node* casted_length = ConstraintCastNode::make_cast_for_basic_type(
1200       control(), length, TypeInteger::make(0, upper_bound, Type::WidenMax, bt),
1201       ConstraintCastNode::DependencyType::FloatingNarrowing, bt);
1202   casted_length = _gvn.transform(casted_length);
1203   replace_in_map(length, casted_length);
1204   length = casted_length;
1205 
1206   // Use an unsigned comparison for the range check itself
1207   Node* rc_cmp = _gvn.transform(CmpNode::make(index, length, bt, true));
1208   BoolTest::mask btest = BoolTest::lt;
1209   Node* rc_bool = _gvn.transform(new BoolNode(rc_cmp, btest));
1210   RangeCheckNode* rc = new RangeCheckNode(control(), rc_bool, PROB_MAX, COUNT_UNKNOWN);
1211   _gvn.set_type(rc, rc->Value(&_gvn));
1212   if (!rc_bool->is_Con()) {
1213     record_for_igvn(rc);
1214   }
1215   set_control(_gvn.transform(new IfTrueNode(rc)));
1216   {
1217     PreserveJVMState pjvms(this);
1218     set_control(_gvn.transform(new IfFalseNode(rc)));
1219     uncommon_trap(Deoptimization::Reason_range_check,
1220                   Deoptimization::Action_make_not_entrant);
1221   }
1222 
1223   if (stopped()) {
1224     // Range check is known to always fail during compilation and the IR graph so far constructed is good so return success
1225     return true;
1226   }
1227 
1228   // index is now known to be >= 0 and < length, cast it
1229   Node* result = ConstraintCastNode::make_cast_for_basic_type(
1230       control(), index, TypeInteger::make(0, upper_bound, Type::WidenMax, bt),
1231       ConstraintCastNode::DependencyType::FloatingNarrowing, bt);
1232   result = _gvn.transform(result);
1233   set_result(result);
1234   replace_in_map(index, result);
1235   return true;
1236 }
1237 
1238 //------------------------------inline_string_indexOf------------------------
1239 bool LibraryCallKit::inline_string_indexOf(StrIntrinsicNode::ArgEnc ae) {
1240   if (!Matcher::match_rule_supported(Op_StrIndexOf)) {
1241     return false;
1242   }
1243   Node* src = argument(0);
1244   Node* tgt = argument(1);
1245 
1246   // Make the merge point
1247   RegionNode* result_rgn = new RegionNode(4);
1248   Node*       result_phi = new PhiNode(result_rgn, TypeInt::INT);
1249 
1250   src = must_be_not_null(src, true);
1251   tgt = must_be_not_null(tgt, true);
1252 
1253   // Get start addr and length of source string
1254   Node* src_start = array_element_address(src, intcon(0), T_BYTE);
1255   Node* src_count = load_array_length(src);
1256 
1257   // Get start addr and length of substring
1258   Node* tgt_start = array_element_address(tgt, intcon(0), T_BYTE);
1259   Node* tgt_count = load_array_length(tgt);
1260 
1261   Node* result = nullptr;
1262   bool call_opt_stub = (StubRoutines::_string_indexof_array[ae] != nullptr);
1263 
1264   if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
1265     // Divide src size by 2 if String is UTF16 encoded
1266     src_count = _gvn.transform(new RShiftINode(src_count, intcon(1)));
1267   }
1268   if (ae == StrIntrinsicNode::UU) {
1269     // Divide substring size by 2 if String is UTF16 encoded
1270     tgt_count = _gvn.transform(new RShiftINode(tgt_count, intcon(1)));
1271   }
1272 
1273   if (call_opt_stub) {
1274     Node* call = make_runtime_call(RC_LEAF, OptoRuntime::string_IndexOf_Type(),
1275                                    StubRoutines::_string_indexof_array[ae],
1276                                    "stringIndexOf", TypePtr::BOTTOM, src_start,
1277                                    src_count, tgt_start, tgt_count);
1278     result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
1279   } else {
1280     result = make_indexOf_node(src_start, src_count, tgt_start, tgt_count,
1281                                result_rgn, result_phi, ae);
1282   }
1283   if (result != nullptr) {
1284     result_phi->init_req(3, result);
1285     result_rgn->init_req(3, control());
1286   }
1287   set_control(_gvn.transform(result_rgn));
1288   record_for_igvn(result_rgn);
1289   set_result(_gvn.transform(result_phi));
1290 
1291   return true;
1292 }
1293 
1294 //-----------------------------inline_string_indexOfI-----------------------
1295 bool LibraryCallKit::inline_string_indexOfI(StrIntrinsicNode::ArgEnc ae) {
1296   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1297     return false;
1298   }
1299   if (!Matcher::match_rule_supported(Op_StrIndexOf)) {
1300     return false;
1301   }
1302 
1303   assert(callee()->signature()->size() == 5, "String.indexOf() has 5 arguments");
1304   Node* src         = argument(0); // byte[]
1305   Node* src_count   = argument(1); // char count
1306   Node* tgt         = argument(2); // byte[]
1307   Node* tgt_count   = argument(3); // char count
1308   Node* from_index  = argument(4); // char index
1309 
1310   src = must_be_not_null(src, true);
1311   tgt = must_be_not_null(tgt, true);
1312 
1313   // Multiply byte array index by 2 if String is UTF16 encoded
1314   Node* src_offset = (ae == StrIntrinsicNode::LL) ? from_index : _gvn.transform(new LShiftINode(from_index, intcon(1)));
1315   src_count = _gvn.transform(new SubINode(src_count, from_index));
1316   Node* src_start = array_element_address(src, src_offset, T_BYTE);
1317   Node* tgt_start = array_element_address(tgt, intcon(0), T_BYTE);
1318 
1319   // Range checks
1320   generate_string_range_check(src, src_offset, src_count, ae != StrIntrinsicNode::LL);
1321   generate_string_range_check(tgt, intcon(0), tgt_count, ae == StrIntrinsicNode::UU);
1322   if (stopped()) {
1323     return true;
1324   }
1325 
1326   RegionNode* region = new RegionNode(5);
1327   Node* phi = new PhiNode(region, TypeInt::INT);
1328   Node* result = nullptr;
1329 
1330   bool call_opt_stub = (StubRoutines::_string_indexof_array[ae] != nullptr);
1331 
1332   if (call_opt_stub) {
1333     Node* call = make_runtime_call(RC_LEAF, OptoRuntime::string_IndexOf_Type(),
1334                                    StubRoutines::_string_indexof_array[ae],
1335                                    "stringIndexOf", TypePtr::BOTTOM, src_start,
1336                                    src_count, tgt_start, tgt_count);
1337     result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
1338   } else {
1339     result = make_indexOf_node(src_start, src_count, tgt_start, tgt_count,
1340                                region, phi, ae);
1341   }
1342   if (result != nullptr) {
1343     // The result is index relative to from_index if substring was found, -1 otherwise.
1344     // Generate code which will fold into cmove.
1345     Node* cmp = _gvn.transform(new CmpINode(result, intcon(0)));
1346     Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::lt));
1347 
1348     Node* if_lt = generate_slow_guard(bol, nullptr);
1349     if (if_lt != nullptr) {
1350       // result == -1
1351       phi->init_req(3, result);
1352       region->init_req(3, if_lt);
1353     }
1354     if (!stopped()) {
1355       result = _gvn.transform(new AddINode(result, from_index));
1356       phi->init_req(4, result);
1357       region->init_req(4, control());
1358     }
1359   }
1360 
1361   set_control(_gvn.transform(region));
1362   record_for_igvn(region);
1363   set_result(_gvn.transform(phi));
1364   clear_upper_avx();
1365 
1366   return true;
1367 }
1368 
1369 // Create StrIndexOfNode with fast path checks
1370 Node* LibraryCallKit::make_indexOf_node(Node* src_start, Node* src_count, Node* tgt_start, Node* tgt_count,
1371                                         RegionNode* region, Node* phi, StrIntrinsicNode::ArgEnc ae) {
1372   // Check for substr count > string count
1373   Node* cmp = _gvn.transform(new CmpINode(tgt_count, src_count));
1374   Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::gt));
1375   Node* if_gt = generate_slow_guard(bol, nullptr);
1376   if (if_gt != nullptr) {
1377     phi->init_req(1, intcon(-1));
1378     region->init_req(1, if_gt);
1379   }
1380   if (!stopped()) {
1381     // Check for substr count == 0
1382     cmp = _gvn.transform(new CmpINode(tgt_count, intcon(0)));
1383     bol = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
1384     Node* if_zero = generate_slow_guard(bol, nullptr);
1385     if (if_zero != nullptr) {
1386       phi->init_req(2, intcon(0));
1387       region->init_req(2, if_zero);
1388     }
1389   }
1390   if (!stopped()) {
1391     return make_string_method_node(Op_StrIndexOf, src_start, src_count, tgt_start, tgt_count, ae);
1392   }
1393   return nullptr;
1394 }
1395 
1396 //-----------------------------inline_string_indexOfChar-----------------------
1397 bool LibraryCallKit::inline_string_indexOfChar(StrIntrinsicNode::ArgEnc ae) {
1398   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1399     return false;
1400   }
1401   if (!Matcher::match_rule_supported(Op_StrIndexOfChar)) {
1402     return false;
1403   }
1404   assert(callee()->signature()->size() == 4, "String.indexOfChar() has 4 arguments");
1405   Node* src         = argument(0); // byte[]
1406   Node* int_ch      = argument(1);
1407   Node* from_index  = argument(2);
1408   Node* max         = argument(3);
1409 
1410   src = must_be_not_null(src, true);
1411 
1412   Node* src_offset = ae == StrIntrinsicNode::L ? from_index : _gvn.transform(new LShiftINode(from_index, intcon(1)));
1413   Node* src_start = array_element_address(src, src_offset, T_BYTE);
1414   Node* src_count = _gvn.transform(new SubINode(max, from_index));
1415 
1416   // Range checks
1417   generate_string_range_check(src, src_offset, src_count, ae == StrIntrinsicNode::U);
1418 
1419   // Check for int_ch >= 0
1420   Node* int_ch_cmp = _gvn.transform(new CmpINode(int_ch, intcon(0)));
1421   Node* int_ch_bol = _gvn.transform(new BoolNode(int_ch_cmp, BoolTest::ge));
1422   {
1423     BuildCutout unless(this, int_ch_bol, PROB_MAX);
1424     uncommon_trap(Deoptimization::Reason_intrinsic,
1425                   Deoptimization::Action_maybe_recompile);
1426   }
1427   if (stopped()) {
1428     return true;
1429   }
1430 
1431   RegionNode* region = new RegionNode(3);
1432   Node* phi = new PhiNode(region, TypeInt::INT);
1433 
1434   Node* result = new StrIndexOfCharNode(control(), memory(TypeAryPtr::BYTES), src_start, src_count, int_ch, ae);
1435   C->set_has_split_ifs(true); // Has chance for split-if optimization
1436   _gvn.transform(result);
1437 
1438   Node* cmp = _gvn.transform(new CmpINode(result, intcon(0)));
1439   Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::lt));
1440 
1441   Node* if_lt = generate_slow_guard(bol, nullptr);
1442   if (if_lt != nullptr) {
1443     // result == -1
1444     phi->init_req(2, result);
1445     region->init_req(2, if_lt);
1446   }
1447   if (!stopped()) {
1448     result = _gvn.transform(new AddINode(result, from_index));
1449     phi->init_req(1, result);
1450     region->init_req(1, control());
1451   }
1452   set_control(_gvn.transform(region));
1453   record_for_igvn(region);
1454   set_result(_gvn.transform(phi));
1455   clear_upper_avx();
1456 
1457   return true;
1458 }
1459 //---------------------------inline_string_copy---------------------
1460 // compressIt == true --> generate a compressed copy operation (compress char[]/byte[] to byte[])
1461 //   int StringUTF16.compress(char[] src, int srcOff, byte[] dst, int dstOff, int len)
1462 //   int StringUTF16.compress(byte[] src, int srcOff, byte[] dst, int dstOff, int len)
1463 // compressIt == false --> generate an inflated copy operation (inflate byte[] to char[]/byte[])
1464 //   void StringLatin1.inflate(byte[] src, int srcOff, char[] dst, int dstOff, int len)
1465 //   void StringLatin1.inflate(byte[] src, int srcOff, byte[] dst, int dstOff, int len)
1466 bool LibraryCallKit::inline_string_copy(bool compress) {
1467   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1468     return false;
1469   }
1470   int nargs = 5;  // 2 oops, 3 ints
1471   assert(callee()->signature()->size() == nargs, "string copy has 5 arguments");
1472 
1473   Node* src         = argument(0);
1474   Node* src_offset  = argument(1);
1475   Node* dst         = argument(2);
1476   Node* dst_offset  = argument(3);
1477   Node* length      = argument(4);
1478 
1479   // Check for allocation before we add nodes that would confuse
1480   // tightly_coupled_allocation()
1481   AllocateArrayNode* alloc = tightly_coupled_allocation(dst);
1482 
1483   // Figure out the size and type of the elements we will be copying.
1484   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
1485   const TypeAryPtr* dst_type = dst->Value(&_gvn)->isa_aryptr();
1486   if (src_type == nullptr || dst_type == nullptr) {
1487     return false;
1488   }
1489   BasicType src_elem = src_type->elem()->array_element_basic_type();
1490   BasicType dst_elem = dst_type->elem()->array_element_basic_type();
1491   assert((compress && dst_elem == T_BYTE && (src_elem == T_BYTE || src_elem == T_CHAR)) ||
1492          (!compress && src_elem == T_BYTE && (dst_elem == T_BYTE || dst_elem == T_CHAR)),
1493          "Unsupported array types for inline_string_copy");
1494 
1495   src = must_be_not_null(src, true);
1496   dst = must_be_not_null(dst, true);
1497 
1498   // Convert char[] offsets to byte[] offsets
1499   bool convert_src = (compress && src_elem == T_BYTE);
1500   bool convert_dst = (!compress && dst_elem == T_BYTE);
1501   if (convert_src) {
1502     src_offset = _gvn.transform(new LShiftINode(src_offset, intcon(1)));
1503   } else if (convert_dst) {
1504     dst_offset = _gvn.transform(new LShiftINode(dst_offset, intcon(1)));
1505   }
1506 
1507   // Range checks
1508   generate_string_range_check(src, src_offset, length, convert_src);
1509   generate_string_range_check(dst, dst_offset, length, convert_dst);
1510   if (stopped()) {
1511     return true;
1512   }
1513 
1514   Node* src_start = array_element_address(src, src_offset, src_elem);
1515   Node* dst_start = array_element_address(dst, dst_offset, dst_elem);
1516   // 'src_start' points to src array + scaled offset
1517   // 'dst_start' points to dst array + scaled offset
1518   Node* count = nullptr;
1519   if (compress) {
1520     count = compress_string(src_start, TypeAryPtr::get_array_body_type(src_elem), dst_start, length);
1521   } else {
1522     inflate_string(src_start, dst_start, TypeAryPtr::get_array_body_type(dst_elem), length);
1523   }
1524 
1525   if (alloc != nullptr) {
1526     if (alloc->maybe_set_complete(&_gvn)) {
1527       // "You break it, you buy it."
1528       InitializeNode* init = alloc->initialization();
1529       assert(init->is_complete(), "we just did this");
1530       init->set_complete_with_arraycopy();
1531       assert(dst->is_CheckCastPP(), "sanity");
1532       assert(dst->in(0)->in(0) == init, "dest pinned");
1533     }
1534     // Do not let stores that initialize this object be reordered with
1535     // a subsequent store that would make this object accessible by
1536     // other threads.
1537     // Record what AllocateNode this StoreStore protects so that
1538     // escape analysis can go from the MemBarStoreStoreNode to the
1539     // AllocateNode and eliminate the MemBarStoreStoreNode if possible
1540     // based on the escape status of the AllocateNode.
1541     insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
1542   }
1543   if (compress) {
1544     set_result(_gvn.transform(count));
1545   }
1546   clear_upper_avx();
1547 
1548   return true;
1549 }
1550 
1551 #ifdef _LP64
1552 #define XTOP ,top() /*additional argument*/
1553 #else  //_LP64
1554 #define XTOP        /*no additional argument*/
1555 #endif //_LP64
1556 
1557 //------------------------inline_string_toBytesU--------------------------
1558 // public static byte[] StringUTF16.toBytes(char[] value, int off, int len)
1559 bool LibraryCallKit::inline_string_toBytesU() {
1560   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1561     return false;
1562   }
1563   // Get the arguments.
1564   Node* value     = argument(0);
1565   Node* offset    = argument(1);
1566   Node* length    = argument(2);
1567 
1568   Node* newcopy = nullptr;
1569 
1570   // Set the original stack and the reexecute bit for the interpreter to reexecute
1571   // the bytecode that invokes StringUTF16.toBytes() if deoptimization happens.
1572   { PreserveReexecuteState preexecs(this);
1573     jvms()->set_should_reexecute(true);
1574 
1575     // Check if a null path was taken unconditionally.
1576     value = null_check(value);
1577 
1578     RegionNode* bailout = new RegionNode(1);
1579     record_for_igvn(bailout);
1580 
1581     // Range checks
1582     generate_negative_guard(offset, bailout);
1583     generate_negative_guard(length, bailout);
1584     generate_limit_guard(offset, length, load_array_length(value), bailout);
1585     // Make sure that resulting byte[] length does not overflow Integer.MAX_VALUE
1586     generate_limit_guard(length, intcon(0), intcon(max_jint/2), bailout);
1587 
1588     if (bailout->req() > 1) {
1589       PreserveJVMState pjvms(this);
1590       set_control(_gvn.transform(bailout));
1591       uncommon_trap(Deoptimization::Reason_intrinsic,
1592                     Deoptimization::Action_maybe_recompile);
1593     }
1594     if (stopped()) {
1595       return true;
1596     }
1597 
1598     Node* size = _gvn.transform(new LShiftINode(length, intcon(1)));
1599     Node* klass_node = makecon(TypeKlassPtr::make(ciTypeArrayKlass::make(T_BYTE)));
1600     newcopy = new_array(klass_node, size, 0);  // no arguments to push
1601     AllocateArrayNode* alloc = tightly_coupled_allocation(newcopy);
1602     guarantee(alloc != nullptr, "created above");
1603 
1604     // Calculate starting addresses.
1605     Node* src_start = array_element_address(value, offset, T_CHAR);
1606     Node* dst_start = basic_plus_adr(newcopy, arrayOopDesc::base_offset_in_bytes(T_BYTE));
1607 
1608     // Check if dst array address is aligned to HeapWordSize
1609     bool aligned = (arrayOopDesc::base_offset_in_bytes(T_BYTE) % HeapWordSize == 0);
1610     // If true, then check if src array address is aligned to HeapWordSize
1611     if (aligned) {
1612       const TypeInt* toffset = gvn().type(offset)->is_int();
1613       aligned = toffset->is_con() && ((arrayOopDesc::base_offset_in_bytes(T_CHAR) +
1614                                        toffset->get_con() * type2aelembytes(T_CHAR)) % HeapWordSize == 0);
1615     }
1616 
1617     // Figure out which arraycopy runtime method to call (disjoint, uninitialized).
1618     const char* copyfunc_name = "arraycopy";
1619     address     copyfunc_addr = StubRoutines::select_arraycopy_function(T_CHAR, aligned, true, copyfunc_name, true);
1620     Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
1621                       OptoRuntime::fast_arraycopy_Type(),
1622                       copyfunc_addr, copyfunc_name, TypeRawPtr::BOTTOM,
1623                       src_start, dst_start, ConvI2X(length) XTOP);
1624     // Do not let reads from the cloned object float above the arraycopy.
1625     if (alloc->maybe_set_complete(&_gvn)) {
1626       // "You break it, you buy it."
1627       InitializeNode* init = alloc->initialization();
1628       assert(init->is_complete(), "we just did this");
1629       init->set_complete_with_arraycopy();
1630       assert(newcopy->is_CheckCastPP(), "sanity");
1631       assert(newcopy->in(0)->in(0) == init, "dest pinned");
1632     }
1633     // Do not let stores that initialize this object be reordered with
1634     // a subsequent store that would make this object accessible by
1635     // other threads.
1636     // Record what AllocateNode this StoreStore protects so that
1637     // escape analysis can go from the MemBarStoreStoreNode to the
1638     // AllocateNode and eliminate the MemBarStoreStoreNode if possible
1639     // based on the escape status of the AllocateNode.
1640     insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
1641   } // original reexecute is set back here
1642 
1643   C->set_has_split_ifs(true); // Has chance for split-if optimization
1644   if (!stopped()) {
1645     set_result(newcopy);
1646   }
1647   clear_upper_avx();
1648 
1649   return true;
1650 }
1651 
1652 //------------------------inline_string_getCharsU--------------------------
1653 // public void StringUTF16.getChars(byte[] src, int srcBegin, int srcEnd, char dst[], int dstBegin)
1654 bool LibraryCallKit::inline_string_getCharsU() {
1655   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1656     return false;
1657   }
1658 
1659   // Get the arguments.
1660   Node* src       = argument(0);
1661   Node* src_begin = argument(1);
1662   Node* src_end   = argument(2); // exclusive offset (i < src_end)
1663   Node* dst       = argument(3);
1664   Node* dst_begin = argument(4);
1665 
1666   // Check for allocation before we add nodes that would confuse
1667   // tightly_coupled_allocation()
1668   AllocateArrayNode* alloc = tightly_coupled_allocation(dst);
1669 
1670   // Check if a null path was taken unconditionally.
1671   src = null_check(src);
1672   dst = null_check(dst);
1673   if (stopped()) {
1674     return true;
1675   }
1676 
1677   // Get length and convert char[] offset to byte[] offset
1678   Node* length = _gvn.transform(new SubINode(src_end, src_begin));
1679   src_begin = _gvn.transform(new LShiftINode(src_begin, intcon(1)));
1680 
1681   // Range checks
1682   generate_string_range_check(src, src_begin, length, true);
1683   generate_string_range_check(dst, dst_begin, length, false);
1684   if (stopped()) {
1685     return true;
1686   }
1687 
1688   if (!stopped()) {
1689     // Calculate starting addresses.
1690     Node* src_start = array_element_address(src, src_begin, T_BYTE);
1691     Node* dst_start = array_element_address(dst, dst_begin, T_CHAR);
1692 
1693     // Check if array addresses are aligned to HeapWordSize
1694     const TypeInt* tsrc = gvn().type(src_begin)->is_int();
1695     const TypeInt* tdst = gvn().type(dst_begin)->is_int();
1696     bool aligned = tsrc->is_con() && ((arrayOopDesc::base_offset_in_bytes(T_BYTE) + tsrc->get_con() * type2aelembytes(T_BYTE)) % HeapWordSize == 0) &&
1697                    tdst->is_con() && ((arrayOopDesc::base_offset_in_bytes(T_CHAR) + tdst->get_con() * type2aelembytes(T_CHAR)) % HeapWordSize == 0);
1698 
1699     // Figure out which arraycopy runtime method to call (disjoint, uninitialized).
1700     const char* copyfunc_name = "arraycopy";
1701     address     copyfunc_addr = StubRoutines::select_arraycopy_function(T_CHAR, aligned, true, copyfunc_name, true);
1702     Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
1703                       OptoRuntime::fast_arraycopy_Type(),
1704                       copyfunc_addr, copyfunc_name, TypeRawPtr::BOTTOM,
1705                       src_start, dst_start, ConvI2X(length) XTOP);
1706     // Do not let reads from the cloned object float above the arraycopy.
1707     if (alloc != nullptr) {
1708       if (alloc->maybe_set_complete(&_gvn)) {
1709         // "You break it, you buy it."
1710         InitializeNode* init = alloc->initialization();
1711         assert(init->is_complete(), "we just did this");
1712         init->set_complete_with_arraycopy();
1713         assert(dst->is_CheckCastPP(), "sanity");
1714         assert(dst->in(0)->in(0) == init, "dest pinned");
1715       }
1716       // Do not let stores that initialize this object be reordered with
1717       // a subsequent store that would make this object accessible by
1718       // other threads.
1719       // Record what AllocateNode this StoreStore protects so that
1720       // escape analysis can go from the MemBarStoreStoreNode to the
1721       // AllocateNode and eliminate the MemBarStoreStoreNode if possible
1722       // based on the escape status of the AllocateNode.
1723       insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
1724     } else {
1725       insert_mem_bar(Op_MemBarCPUOrder);
1726     }
1727   }
1728 
1729   C->set_has_split_ifs(true); // Has chance for split-if optimization
1730   return true;
1731 }
1732 
1733 //----------------------inline_string_char_access----------------------------
1734 // Store/Load char to/from byte[] array.
1735 // static void StringUTF16.putChar(byte[] val, int index, int c)
1736 // static char StringUTF16.getChar(byte[] val, int index)
1737 bool LibraryCallKit::inline_string_char_access(bool is_store) {
1738   Node* value  = argument(0);
1739   Node* index  = argument(1);
1740   Node* ch = is_store ? argument(2) : nullptr;
1741 
1742   // This intrinsic accesses byte[] array as char[] array. Computing the offsets
1743   // correctly requires matched array shapes.
1744   assert (arrayOopDesc::base_offset_in_bytes(T_CHAR) == arrayOopDesc::base_offset_in_bytes(T_BYTE),
1745           "sanity: byte[] and char[] bases agree");
1746   assert (type2aelembytes(T_CHAR) == type2aelembytes(T_BYTE)*2,
1747           "sanity: byte[] and char[] scales agree");
1748 
1749   // Bail when getChar over constants is requested: constant folding would
1750   // reject folding mismatched char access over byte[]. A normal inlining for getChar
1751   // Java method would constant fold nicely instead.
1752   if (!is_store && value->is_Con() && index->is_Con()) {
1753     return false;
1754   }
1755 
1756   // Save state and restore on bailout
1757   SavedState old_state(this);
1758 
1759   value = must_be_not_null(value, true);
1760 
1761   Node* adr = array_element_address(value, index, T_CHAR);
1762   if (adr->is_top()) {
1763     return false;
1764   }
1765   old_state.discard();
1766   if (is_store) {
1767     access_store_at(value, adr, TypeAryPtr::BYTES, ch, TypeInt::CHAR, T_CHAR, IN_HEAP | MO_UNORDERED | C2_MISMATCHED);
1768   } else {
1769     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);
1770     set_result(ch);
1771   }
1772   return true;
1773 }
1774 
1775 
1776 //------------------------------inline_math-----------------------------------
1777 // public static double Math.abs(double)
1778 // public static double Math.sqrt(double)
1779 // public static double Math.log(double)
1780 // public static double Math.log10(double)
1781 // public static double Math.round(double)
1782 bool LibraryCallKit::inline_double_math(vmIntrinsics::ID id) {
1783   Node* arg = argument(0);
1784   Node* n = nullptr;
1785   switch (id) {
1786   case vmIntrinsics::_dabs:   n = new AbsDNode(                arg);  break;
1787   case vmIntrinsics::_dsqrt:
1788   case vmIntrinsics::_dsqrt_strict:
1789                               n = new SqrtDNode(C, control(),  arg);  break;
1790   case vmIntrinsics::_ceil:   n = RoundDoubleModeNode::make(_gvn, arg, RoundDoubleModeNode::rmode_ceil); break;
1791   case vmIntrinsics::_floor:  n = RoundDoubleModeNode::make(_gvn, arg, RoundDoubleModeNode::rmode_floor); break;
1792   case vmIntrinsics::_rint:   n = RoundDoubleModeNode::make(_gvn, arg, RoundDoubleModeNode::rmode_rint); break;
1793   case vmIntrinsics::_roundD: n = new RoundDNode(arg); break;
1794   case vmIntrinsics::_dcopySign: n = CopySignDNode::make(_gvn, arg, argument(2)); break;
1795   case vmIntrinsics::_dsignum: n = SignumDNode::make(_gvn, arg); break;
1796   default:  fatal_unexpected_iid(id);  break;
1797   }
1798   set_result(_gvn.transform(n));
1799   return true;
1800 }
1801 
1802 //------------------------------inline_math-----------------------------------
1803 // public static float Math.abs(float)
1804 // public static int Math.abs(int)
1805 // public static long Math.abs(long)
1806 bool LibraryCallKit::inline_math(vmIntrinsics::ID id) {
1807   Node* arg = argument(0);
1808   Node* n = nullptr;
1809   switch (id) {
1810   case vmIntrinsics::_fabs:   n = new AbsFNode(                arg);  break;
1811   case vmIntrinsics::_iabs:   n = new AbsINode(                arg);  break;
1812   case vmIntrinsics::_labs:   n = new AbsLNode(                arg);  break;
1813   case vmIntrinsics::_fcopySign: n = new CopySignFNode(arg, argument(1)); break;
1814   case vmIntrinsics::_fsignum: n = SignumFNode::make(_gvn, arg); break;
1815   case vmIntrinsics::_roundF: n = new RoundFNode(arg); break;
1816   default:  fatal_unexpected_iid(id);  break;
1817   }
1818   set_result(_gvn.transform(n));
1819   return true;
1820 }
1821 
1822 //------------------------------runtime_math-----------------------------
1823 bool LibraryCallKit::runtime_math(const TypeFunc* call_type, address funcAddr, const char* funcName) {
1824   assert(call_type == OptoRuntime::Math_DD_D_Type() || call_type == OptoRuntime::Math_D_D_Type(),
1825          "must be (DD)D or (D)D type");
1826 
1827   // Inputs
1828   Node* a = argument(0);
1829   Node* b = (call_type == OptoRuntime::Math_DD_D_Type()) ? argument(2) : nullptr;
1830 
1831   const TypePtr* no_memory_effects = nullptr;
1832   Node* trig = make_runtime_call(RC_LEAF | RC_PURE, call_type, funcAddr, funcName,
1833                                  no_memory_effects,
1834                                  a, top(), b, b ? top() : nullptr);
1835   Node* value = _gvn.transform(new ProjNode(trig, TypeFunc::Parms+0));
1836 #ifdef ASSERT
1837   Node* value_top = _gvn.transform(new ProjNode(trig, TypeFunc::Parms+1));
1838   assert(value_top == top(), "second value must be top");
1839 #endif
1840 
1841   set_result(value);
1842   return true;
1843 }
1844 
1845 //------------------------------inline_math_pow-----------------------------
1846 bool LibraryCallKit::inline_math_pow() {
1847   Node* exp = argument(2);
1848   const TypeD* d = _gvn.type(exp)->isa_double_constant();
1849   if (d != nullptr) {
1850     if (d->getd() == 2.0) {
1851       // Special case: pow(x, 2.0) => x * x
1852       Node* base = argument(0);
1853       set_result(_gvn.transform(new MulDNode(base, base)));
1854       return true;
1855     } else if (d->getd() == 0.5 && Matcher::match_rule_supported(Op_SqrtD)) {
1856       // Special case: pow(x, 0.5) => sqrt(x)
1857       Node* base = argument(0);
1858       Node* zero = _gvn.zerocon(T_DOUBLE);
1859 
1860       RegionNode* region = new RegionNode(3);
1861       Node* phi = new PhiNode(region, Type::DOUBLE);
1862 
1863       Node* cmp  = _gvn.transform(new CmpDNode(base, zero));
1864       // According to the API specs, pow(-0.0, 0.5) = 0.0 and sqrt(-0.0) = -0.0.
1865       // So pow(-0.0, 0.5) shouldn't be replaced with sqrt(-0.0).
1866       // -0.0/+0.0 are both excluded since floating-point comparison doesn't distinguish -0.0 from +0.0.
1867       Node* test = _gvn.transform(new BoolNode(cmp, BoolTest::le));
1868 
1869       Node* if_pow = generate_slow_guard(test, nullptr);
1870       Node* value_sqrt = _gvn.transform(new SqrtDNode(C, control(), base));
1871       phi->init_req(1, value_sqrt);
1872       region->init_req(1, control());
1873 
1874       if (if_pow != nullptr) {
1875         set_control(if_pow);
1876         address target = StubRoutines::dpow() != nullptr ? StubRoutines::dpow() :
1877                                                         CAST_FROM_FN_PTR(address, SharedRuntime::dpow);
1878         const TypePtr* no_memory_effects = nullptr;
1879         Node* trig = make_runtime_call(RC_LEAF, OptoRuntime::Math_DD_D_Type(), target, "POW",
1880                                        no_memory_effects, base, top(), exp, top());
1881         Node* value_pow = _gvn.transform(new ProjNode(trig, TypeFunc::Parms+0));
1882 #ifdef ASSERT
1883         Node* value_top = _gvn.transform(new ProjNode(trig, TypeFunc::Parms+1));
1884         assert(value_top == top(), "second value must be top");
1885 #endif
1886         phi->init_req(2, value_pow);
1887         region->init_req(2, _gvn.transform(new ProjNode(trig, TypeFunc::Control)));
1888       }
1889 
1890       C->set_has_split_ifs(true); // Has chance for split-if optimization
1891       set_control(_gvn.transform(region));
1892       record_for_igvn(region);
1893       set_result(_gvn.transform(phi));
1894 
1895       return true;
1896     }
1897   }
1898 
1899   return StubRoutines::dpow() != nullptr ?
1900     runtime_math(OptoRuntime::Math_DD_D_Type(), StubRoutines::dpow(),  "dpow") :
1901     runtime_math(OptoRuntime::Math_DD_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dpow),  "POW");
1902 }
1903 
1904 //------------------------------inline_math_native-----------------------------
1905 bool LibraryCallKit::inline_math_native(vmIntrinsics::ID id) {
1906   switch (id) {
1907   case vmIntrinsics::_dsin:
1908     return StubRoutines::dsin() != nullptr ?
1909       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dsin(), "dsin") :
1910       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dsin),   "SIN");
1911   case vmIntrinsics::_dcos:
1912     return StubRoutines::dcos() != nullptr ?
1913       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dcos(), "dcos") :
1914       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dcos),   "COS");
1915   case vmIntrinsics::_dtan:
1916     return StubRoutines::dtan() != nullptr ?
1917       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dtan(), "dtan") :
1918       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dtan), "TAN");
1919   case vmIntrinsics::_dsinh:
1920     return StubRoutines::dsinh() != nullptr ?
1921       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dsinh(), "dsinh") : false;
1922   case vmIntrinsics::_dtanh:
1923     return StubRoutines::dtanh() != nullptr ?
1924       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dtanh(), "dtanh") : false;
1925   case vmIntrinsics::_dcbrt:
1926     return StubRoutines::dcbrt() != nullptr ?
1927       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dcbrt(), "dcbrt") : false;
1928   case vmIntrinsics::_dexp:
1929     return StubRoutines::dexp() != nullptr ?
1930       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dexp(),  "dexp") :
1931       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dexp),  "EXP");
1932   case vmIntrinsics::_dlog:
1933     return StubRoutines::dlog() != nullptr ?
1934       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dlog(), "dlog") :
1935       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dlog),   "LOG");
1936   case vmIntrinsics::_dlog10:
1937     return StubRoutines::dlog10() != nullptr ?
1938       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dlog10(), "dlog10") :
1939       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dlog10), "LOG10");
1940 
1941   case vmIntrinsics::_roundD: return Matcher::match_rule_supported(Op_RoundD) ? inline_double_math(id) : false;
1942   case vmIntrinsics::_ceil:
1943   case vmIntrinsics::_floor:
1944   case vmIntrinsics::_rint:   return Matcher::match_rule_supported(Op_RoundDoubleMode) ? inline_double_math(id) : false;
1945 
1946   case vmIntrinsics::_dsqrt:
1947   case vmIntrinsics::_dsqrt_strict:
1948                               return Matcher::match_rule_supported(Op_SqrtD) ? inline_double_math(id) : false;
1949   case vmIntrinsics::_dabs:   return Matcher::has_match_rule(Op_AbsD)   ? inline_double_math(id) : false;
1950   case vmIntrinsics::_fabs:   return Matcher::match_rule_supported(Op_AbsF)   ? inline_math(id) : false;
1951   case vmIntrinsics::_iabs:   return Matcher::match_rule_supported(Op_AbsI)   ? inline_math(id) : false;
1952   case vmIntrinsics::_labs:   return Matcher::match_rule_supported(Op_AbsL)   ? inline_math(id) : false;
1953 
1954   case vmIntrinsics::_dpow:      return inline_math_pow();
1955   case vmIntrinsics::_dcopySign: return inline_double_math(id);
1956   case vmIntrinsics::_fcopySign: return inline_math(id);
1957   case vmIntrinsics::_dsignum: return Matcher::match_rule_supported(Op_SignumD) ? inline_double_math(id) : false;
1958   case vmIntrinsics::_fsignum: return Matcher::match_rule_supported(Op_SignumF) ? inline_math(id) : false;
1959   case vmIntrinsics::_roundF: return Matcher::match_rule_supported(Op_RoundF) ? inline_math(id) : false;
1960 
1961    // These intrinsics are not yet correctly implemented
1962   case vmIntrinsics::_datan2:
1963     return false;
1964 
1965   default:
1966     fatal_unexpected_iid(id);
1967     return false;
1968   }
1969 }
1970 
1971 //----------------------------inline_notify-----------------------------------*
1972 bool LibraryCallKit::inline_notify(vmIntrinsics::ID id) {
1973   const TypeFunc* ftype = OptoRuntime::monitor_notify_Type();
1974   address func;
1975   if (id == vmIntrinsics::_notify) {
1976     func = OptoRuntime::monitor_notify_Java();
1977   } else {
1978     func = OptoRuntime::monitor_notifyAll_Java();
1979   }
1980   Node* call = make_runtime_call(RC_NO_LEAF, ftype, func, nullptr, TypeRawPtr::BOTTOM, argument(0));
1981   make_slow_call_ex(call, env()->Throwable_klass(), false);
1982   return true;
1983 }
1984 
1985 
1986 //----------------------------inline_min_max-----------------------------------
1987 bool LibraryCallKit::inline_min_max(vmIntrinsics::ID id) {
1988   Node* a = nullptr;
1989   Node* b = nullptr;
1990   Node* n = nullptr;
1991   switch (id) {
1992     case vmIntrinsics::_min:
1993     case vmIntrinsics::_max:
1994     case vmIntrinsics::_minF:
1995     case vmIntrinsics::_maxF:
1996     case vmIntrinsics::_minF_strict:
1997     case vmIntrinsics::_maxF_strict:
1998     case vmIntrinsics::_min_strict:
1999     case vmIntrinsics::_max_strict:
2000       assert(callee()->signature()->size() == 2, "minF/maxF has 2 parameters of size 1 each.");
2001       a = argument(0);
2002       b = argument(1);
2003       break;
2004     case vmIntrinsics::_minD:
2005     case vmIntrinsics::_maxD:
2006     case vmIntrinsics::_minD_strict:
2007     case vmIntrinsics::_maxD_strict:
2008       assert(callee()->signature()->size() == 4, "minD/maxD has 2 parameters of size 2 each.");
2009       a = argument(0);
2010       b = argument(2);
2011       break;
2012     case vmIntrinsics::_minL:
2013     case vmIntrinsics::_maxL:
2014       assert(callee()->signature()->size() == 4, "minL/maxL has 2 parameters of size 2 each.");
2015       a = argument(0);
2016       b = argument(2);
2017       break;
2018     default:
2019       fatal_unexpected_iid(id);
2020       break;
2021   }
2022 
2023   switch (id) {
2024     case vmIntrinsics::_min:
2025     case vmIntrinsics::_min_strict:
2026       n = new MinINode(a, b);
2027       break;
2028     case vmIntrinsics::_max:
2029     case vmIntrinsics::_max_strict:
2030       n = new MaxINode(a, b);
2031       break;
2032     case vmIntrinsics::_minF:
2033     case vmIntrinsics::_minF_strict:
2034       n = new MinFNode(a, b);
2035       break;
2036     case vmIntrinsics::_maxF:
2037     case vmIntrinsics::_maxF_strict:
2038       n = new MaxFNode(a, b);
2039       break;
2040     case vmIntrinsics::_minD:
2041     case vmIntrinsics::_minD_strict:
2042       n = new MinDNode(a, b);
2043       break;
2044     case vmIntrinsics::_maxD:
2045     case vmIntrinsics::_maxD_strict:
2046       n = new MaxDNode(a, b);
2047       break;
2048     case vmIntrinsics::_minL:
2049       n = new MinLNode(_gvn.C, a, b);
2050       break;
2051     case vmIntrinsics::_maxL:
2052       n = new MaxLNode(_gvn.C, a, b);
2053       break;
2054     default:
2055       fatal_unexpected_iid(id);
2056       break;
2057   }
2058 
2059   set_result(_gvn.transform(n));
2060   return true;
2061 }
2062 
2063 bool LibraryCallKit::inline_math_mathExact(Node* math, Node* test) {
2064   if (builtin_throw_too_many_traps(Deoptimization::Reason_intrinsic,
2065                                    env()->ArithmeticException_instance())) {
2066     // It has been already too many times, but we cannot use builtin_throw (e.g. we care about backtraces),
2067     // so let's bail out intrinsic rather than risking deopting again.
2068     return false;
2069   }
2070 
2071   Node* bol = _gvn.transform( new BoolNode(test, BoolTest::overflow) );
2072   IfNode* check = create_and_map_if(control(), bol, PROB_UNLIKELY_MAG(3), COUNT_UNKNOWN);
2073   Node* fast_path = _gvn.transform( new IfFalseNode(check));
2074   Node* slow_path = _gvn.transform( new IfTrueNode(check) );
2075 
2076   {
2077     PreserveJVMState pjvms(this);
2078     PreserveReexecuteState preexecs(this);
2079     jvms()->set_should_reexecute(true);
2080 
2081     set_control(slow_path);
2082     set_i_o(i_o());
2083 
2084     builtin_throw(Deoptimization::Reason_intrinsic,
2085                   env()->ArithmeticException_instance(),
2086                   /*allow_too_many_traps*/ false);
2087   }
2088 
2089   set_control(fast_path);
2090   set_result(math);
2091   return true;
2092 }
2093 
2094 template <typename OverflowOp>
2095 bool LibraryCallKit::inline_math_overflow(Node* arg1, Node* arg2) {
2096   typedef typename OverflowOp::MathOp MathOp;
2097 
2098   MathOp* mathOp = new MathOp(arg1, arg2);
2099   Node* operation = _gvn.transform( mathOp );
2100   Node* ofcheck = _gvn.transform( new OverflowOp(arg1, arg2) );
2101   return inline_math_mathExact(operation, ofcheck);
2102 }
2103 
2104 bool LibraryCallKit::inline_math_addExactI(bool is_increment) {
2105   return inline_math_overflow<OverflowAddINode>(argument(0), is_increment ? intcon(1) : argument(1));
2106 }
2107 
2108 bool LibraryCallKit::inline_math_addExactL(bool is_increment) {
2109   return inline_math_overflow<OverflowAddLNode>(argument(0), is_increment ? longcon(1) : argument(2));
2110 }
2111 
2112 bool LibraryCallKit::inline_math_subtractExactI(bool is_decrement) {
2113   return inline_math_overflow<OverflowSubINode>(argument(0), is_decrement ? intcon(1) : argument(1));
2114 }
2115 
2116 bool LibraryCallKit::inline_math_subtractExactL(bool is_decrement) {
2117   return inline_math_overflow<OverflowSubLNode>(argument(0), is_decrement ? longcon(1) : argument(2));
2118 }
2119 
2120 bool LibraryCallKit::inline_math_negateExactI() {
2121   return inline_math_overflow<OverflowSubINode>(intcon(0), argument(0));
2122 }
2123 
2124 bool LibraryCallKit::inline_math_negateExactL() {
2125   return inline_math_overflow<OverflowSubLNode>(longcon(0), argument(0));
2126 }
2127 
2128 bool LibraryCallKit::inline_math_multiplyExactI() {
2129   return inline_math_overflow<OverflowMulINode>(argument(0), argument(1));
2130 }
2131 
2132 bool LibraryCallKit::inline_math_multiplyExactL() {
2133   return inline_math_overflow<OverflowMulLNode>(argument(0), argument(2));
2134 }
2135 
2136 bool LibraryCallKit::inline_math_multiplyHigh() {
2137   set_result(_gvn.transform(new MulHiLNode(argument(0), argument(2))));
2138   return true;
2139 }
2140 
2141 bool LibraryCallKit::inline_math_unsignedMultiplyHigh() {
2142   set_result(_gvn.transform(new UMulHiLNode(argument(0), argument(2))));
2143   return true;
2144 }
2145 
2146 inline int
2147 LibraryCallKit::classify_unsafe_addr(Node* &base, Node* &offset, BasicType type) {
2148   const TypePtr* base_type = TypePtr::NULL_PTR;
2149   if (base != nullptr)  base_type = _gvn.type(base)->isa_ptr();
2150   if (base_type == nullptr) {
2151     // Unknown type.
2152     return Type::AnyPtr;
2153   } else if (_gvn.type(base->uncast()) == TypePtr::NULL_PTR) {
2154     // Since this is a null+long form, we have to switch to a rawptr.
2155     base   = _gvn.transform(new CastX2PNode(offset));
2156     offset = MakeConX(0);
2157     return Type::RawPtr;
2158   } else if (base_type->base() == Type::RawPtr) {
2159     return Type::RawPtr;
2160   } else if (base_type->isa_oopptr()) {
2161     // Base is never null => always a heap address.
2162     if (!TypePtr::NULL_PTR->higher_equal(base_type)) {
2163       return Type::OopPtr;
2164     }
2165     // Offset is small => always a heap address.
2166     const TypeX* offset_type = _gvn.type(offset)->isa_intptr_t();
2167     if (offset_type != nullptr &&
2168         base_type->offset() == 0 &&     // (should always be?)
2169         offset_type->_lo >= 0 &&
2170         !MacroAssembler::needs_explicit_null_check(offset_type->_hi)) {
2171       return Type::OopPtr;
2172     } else if (type == T_OBJECT) {
2173       // off heap access to an oop doesn't make any sense. Has to be on
2174       // heap.
2175       return Type::OopPtr;
2176     }
2177     // Otherwise, it might either be oop+off or null+addr.
2178     return Type::AnyPtr;
2179   } else {
2180     // No information:
2181     return Type::AnyPtr;
2182   }
2183 }
2184 
2185 Node* LibraryCallKit::make_unsafe_address(Node*& base, Node* offset, BasicType type, bool can_cast) {
2186   Node* uncasted_base = base;
2187   int kind = classify_unsafe_addr(uncasted_base, offset, type);
2188   if (kind == Type::RawPtr) {
2189     return basic_plus_adr(top(), uncasted_base, offset);
2190   } else if (kind == Type::AnyPtr) {
2191     assert(base == uncasted_base, "unexpected base change");
2192     if (can_cast) {
2193       if (!_gvn.type(base)->speculative_maybe_null() &&
2194           !too_many_traps(Deoptimization::Reason_speculate_null_check)) {
2195         // According to profiling, this access is always on
2196         // heap. Casting the base to not null and thus avoiding membars
2197         // around the access should allow better optimizations
2198         Node* null_ctl = top();
2199         base = null_check_oop(base, &null_ctl, true, true, true);
2200         assert(null_ctl->is_top(), "no null control here");
2201         return basic_plus_adr(base, offset);
2202       } else if (_gvn.type(base)->speculative_always_null() &&
2203                  !too_many_traps(Deoptimization::Reason_speculate_null_assert)) {
2204         // According to profiling, this access is always off
2205         // heap.
2206         base = null_assert(base);
2207         Node* raw_base = _gvn.transform(new CastX2PNode(offset));
2208         offset = MakeConX(0);
2209         return basic_plus_adr(top(), raw_base, offset);
2210       }
2211     }
2212     // We don't know if it's an on heap or off heap access. Fall back
2213     // to raw memory access.
2214     Node* raw = _gvn.transform(new CheckCastPPNode(control(), base, TypeRawPtr::BOTTOM));
2215     return basic_plus_adr(top(), raw, offset);
2216   } else {
2217     assert(base == uncasted_base, "unexpected base change");
2218     // We know it's an on heap access so base can't be null
2219     if (TypePtr::NULL_PTR->higher_equal(_gvn.type(base))) {
2220       base = must_be_not_null(base, true);
2221     }
2222     return basic_plus_adr(base, offset);
2223   }
2224 }
2225 
2226 //--------------------------inline_number_methods-----------------------------
2227 // inline int     Integer.numberOfLeadingZeros(int)
2228 // inline int        Long.numberOfLeadingZeros(long)
2229 //
2230 // inline int     Integer.numberOfTrailingZeros(int)
2231 // inline int        Long.numberOfTrailingZeros(long)
2232 //
2233 // inline int     Integer.bitCount(int)
2234 // inline int        Long.bitCount(long)
2235 //
2236 // inline char  Character.reverseBytes(char)
2237 // inline short     Short.reverseBytes(short)
2238 // inline int     Integer.reverseBytes(int)
2239 // inline long       Long.reverseBytes(long)
2240 bool LibraryCallKit::inline_number_methods(vmIntrinsics::ID id) {
2241   Node* arg = argument(0);
2242   Node* n = nullptr;
2243   switch (id) {
2244   case vmIntrinsics::_numberOfLeadingZeros_i:   n = new CountLeadingZerosINode( arg); break;
2245   case vmIntrinsics::_numberOfLeadingZeros_l:   n = new CountLeadingZerosLNode( arg); break;
2246   case vmIntrinsics::_numberOfTrailingZeros_i:  n = new CountTrailingZerosINode(arg); break;
2247   case vmIntrinsics::_numberOfTrailingZeros_l:  n = new CountTrailingZerosLNode(arg); break;
2248   case vmIntrinsics::_bitCount_i:               n = new PopCountINode(          arg); break;
2249   case vmIntrinsics::_bitCount_l:               n = new PopCountLNode(          arg); break;
2250   case vmIntrinsics::_reverseBytes_c:           n = new ReverseBytesUSNode(     arg); break;
2251   case vmIntrinsics::_reverseBytes_s:           n = new ReverseBytesSNode(      arg); break;
2252   case vmIntrinsics::_reverseBytes_i:           n = new ReverseBytesINode(      arg); break;
2253   case vmIntrinsics::_reverseBytes_l:           n = new ReverseBytesLNode(      arg); break;
2254   case vmIntrinsics::_reverse_i:                n = new ReverseINode(           arg); break;
2255   case vmIntrinsics::_reverse_l:                n = new ReverseLNode(           arg); break;
2256   default:  fatal_unexpected_iid(id);  break;
2257   }
2258   set_result(_gvn.transform(n));
2259   return true;
2260 }
2261 
2262 //--------------------------inline_bitshuffle_methods-----------------------------
2263 // inline int Integer.compress(int, int)
2264 // inline int Integer.expand(int, int)
2265 // inline long Long.compress(long, long)
2266 // inline long Long.expand(long, long)
2267 bool LibraryCallKit::inline_bitshuffle_methods(vmIntrinsics::ID id) {
2268   Node* n = nullptr;
2269   switch (id) {
2270     case vmIntrinsics::_compress_i:  n = new CompressBitsNode(argument(0), argument(1), TypeInt::INT); break;
2271     case vmIntrinsics::_expand_i:    n = new ExpandBitsNode(argument(0),  argument(1), TypeInt::INT); break;
2272     case vmIntrinsics::_compress_l:  n = new CompressBitsNode(argument(0), argument(2), TypeLong::LONG); break;
2273     case vmIntrinsics::_expand_l:    n = new ExpandBitsNode(argument(0), argument(2), TypeLong::LONG); break;
2274     default:  fatal_unexpected_iid(id);  break;
2275   }
2276   set_result(_gvn.transform(n));
2277   return true;
2278 }
2279 
2280 //--------------------------inline_number_methods-----------------------------
2281 // inline int Integer.compareUnsigned(int, int)
2282 // inline int    Long.compareUnsigned(long, long)
2283 bool LibraryCallKit::inline_compare_unsigned(vmIntrinsics::ID id) {
2284   Node* arg1 = argument(0);
2285   Node* arg2 = (id == vmIntrinsics::_compareUnsigned_l) ? argument(2) : argument(1);
2286   Node* n = nullptr;
2287   switch (id) {
2288     case vmIntrinsics::_compareUnsigned_i:   n = new CmpU3Node(arg1, arg2);  break;
2289     case vmIntrinsics::_compareUnsigned_l:   n = new CmpUL3Node(arg1, arg2); break;
2290     default:  fatal_unexpected_iid(id);  break;
2291   }
2292   set_result(_gvn.transform(n));
2293   return true;
2294 }
2295 
2296 //--------------------------inline_unsigned_divmod_methods-----------------------------
2297 // inline int Integer.divideUnsigned(int, int)
2298 // inline int Integer.remainderUnsigned(int, int)
2299 // inline long Long.divideUnsigned(long, long)
2300 // inline long Long.remainderUnsigned(long, long)
2301 bool LibraryCallKit::inline_divmod_methods(vmIntrinsics::ID id) {
2302   Node* n = nullptr;
2303   switch (id) {
2304     case vmIntrinsics::_divideUnsigned_i: {
2305       zero_check_int(argument(1));
2306       // Compile-time detect of null-exception
2307       if (stopped()) {
2308         return true; // keep the graph constructed so far
2309       }
2310       n = new UDivINode(control(), argument(0), argument(1));
2311       break;
2312     }
2313     case vmIntrinsics::_divideUnsigned_l: {
2314       zero_check_long(argument(2));
2315       // Compile-time detect of null-exception
2316       if (stopped()) {
2317         return true; // keep the graph constructed so far
2318       }
2319       n = new UDivLNode(control(), argument(0), argument(2));
2320       break;
2321     }
2322     case vmIntrinsics::_remainderUnsigned_i: {
2323       zero_check_int(argument(1));
2324       // Compile-time detect of null-exception
2325       if (stopped()) {
2326         return true; // keep the graph constructed so far
2327       }
2328       n = new UModINode(control(), argument(0), argument(1));
2329       break;
2330     }
2331     case vmIntrinsics::_remainderUnsigned_l: {
2332       zero_check_long(argument(2));
2333       // Compile-time detect of null-exception
2334       if (stopped()) {
2335         return true; // keep the graph constructed so far
2336       }
2337       n = new UModLNode(control(), argument(0), argument(2));
2338       break;
2339     }
2340     default:  fatal_unexpected_iid(id);  break;
2341   }
2342   set_result(_gvn.transform(n));
2343   return true;
2344 }
2345 
2346 //----------------------------inline_unsafe_access----------------------------
2347 
2348 const TypeOopPtr* LibraryCallKit::sharpen_unsafe_type(Compile::AliasType* alias_type, const TypePtr *adr_type) {
2349   // Attempt to infer a sharper value type from the offset and base type.
2350   ciKlass* sharpened_klass = nullptr;
2351   bool null_free = false;
2352 
2353   // See if it is an instance field, with an object type.
2354   if (alias_type->field() != nullptr) {
2355     if (alias_type->field()->type()->is_klass()) {
2356       sharpened_klass = alias_type->field()->type()->as_klass();
2357       null_free = alias_type->field()->is_null_free();
2358     }
2359   }
2360 
2361   const TypeOopPtr* result = nullptr;
2362   // See if it is a narrow oop array.
2363   if (adr_type->isa_aryptr()) {
2364     if (adr_type->offset() >= refArrayOopDesc::base_offset_in_bytes()) {
2365       const TypeOopPtr* elem_type = adr_type->is_aryptr()->elem()->make_oopptr();
2366       null_free = adr_type->is_aryptr()->is_null_free();
2367       if (elem_type != nullptr && elem_type->is_loaded()) {
2368         // Sharpen the value type.
2369         result = elem_type;
2370       }
2371     }
2372   }
2373 
2374   // The sharpened class might be unloaded if there is no class loader
2375   // contraint in place.
2376   if (result == nullptr && sharpened_klass != nullptr && sharpened_klass->is_loaded()) {
2377     // Sharpen the value type.
2378     result = TypeOopPtr::make_from_klass(sharpened_klass);
2379     if (null_free) {
2380       result = result->join_speculative(TypePtr::NOTNULL)->is_oopptr();
2381     }
2382   }
2383   if (result != nullptr) {
2384 #ifndef PRODUCT
2385     if (C->print_intrinsics() || C->print_inlining()) {
2386       tty->print("  from base type:  ");  adr_type->dump(); tty->cr();
2387       tty->print("  sharpened value: ");  result->dump();    tty->cr();
2388     }
2389 #endif
2390   }
2391   return result;
2392 }
2393 
2394 DecoratorSet LibraryCallKit::mo_decorator_for_access_kind(AccessKind kind) {
2395   switch (kind) {
2396       case Relaxed:
2397         return MO_UNORDERED;
2398       case Opaque:
2399         return MO_RELAXED;
2400       case Acquire:
2401         return MO_ACQUIRE;
2402       case Release:
2403         return MO_RELEASE;
2404       case Volatile:
2405         return MO_SEQ_CST;
2406       default:
2407         ShouldNotReachHere();
2408         return 0;
2409   }
2410 }
2411 
2412 LibraryCallKit::SavedState::SavedState(LibraryCallKit* kit) :
2413   _kit(kit),
2414   _sp(kit->sp()),
2415   _jvms(kit->jvms()),
2416   _map(kit->clone_map()),
2417   _discarded(false)
2418 {
2419   for (DUIterator_Fast imax, i = kit->control()->fast_outs(imax); i < imax; i++) {
2420     Node* out = kit->control()->fast_out(i);
2421     if (out->is_CFG()) {
2422       _ctrl_succ.push(out);
2423     }
2424   }
2425 }
2426 
2427 LibraryCallKit::SavedState::~SavedState() {
2428   if (_discarded) {
2429     _kit->destruct_map_clone(_map);
2430     return;
2431   }
2432   _kit->jvms()->set_map(_map);
2433   _kit->jvms()->set_sp(_sp);
2434   _map->set_jvms(_kit->jvms());
2435   _kit->set_map(_map);
2436   _kit->set_sp(_sp);
2437   for (DUIterator_Fast imax, i = _kit->control()->fast_outs(imax); i < imax; i++) {
2438     Node* out = _kit->control()->fast_out(i);
2439     if (out->is_CFG() && out->in(0) == _kit->control() && out != _kit->map() && !_ctrl_succ.member(out)) {
2440       _kit->_gvn.hash_delete(out);
2441       out->set_req(0, _kit->C->top());
2442       _kit->C->record_for_igvn(out);
2443       --i; --imax;
2444       _kit->_gvn.hash_find_insert(out);
2445     }
2446   }
2447 }
2448 
2449 void LibraryCallKit::SavedState::discard() {
2450   _discarded = true;
2451 }
2452 
2453 bool LibraryCallKit::inline_unsafe_access(bool is_store, const BasicType type, const AccessKind kind, const bool unaligned) {
2454   if (callee()->is_static())  return false;  // caller must have the capability!
2455   DecoratorSet decorators = C2_UNSAFE_ACCESS;
2456   guarantee(!is_store || kind != Acquire, "Acquire accesses can be produced only for loads");
2457   guarantee( is_store || kind != Release, "Release accesses can be produced only for stores");
2458   assert(type != T_OBJECT || !unaligned, "unaligned access not supported with object type");
2459 
2460   if (is_reference_type(type)) {
2461     decorators |= ON_UNKNOWN_OOP_REF;
2462   }
2463 
2464   if (unaligned) {
2465     decorators |= C2_UNALIGNED;
2466   }
2467 
2468 #ifndef PRODUCT
2469   {
2470     ResourceMark rm;
2471     // Check the signatures.
2472     ciSignature* sig = callee()->signature();
2473 #ifdef ASSERT
2474     if (!is_store) {
2475       // Object getReference(Object base, int/long offset), etc.
2476       BasicType rtype = sig->return_type()->basic_type();
2477       assert(rtype == type, "getter must return the expected value");
2478       assert(sig->count() == 2, "oop getter has 2 arguments");
2479       assert(sig->type_at(0)->basic_type() == T_OBJECT, "getter base is object");
2480       assert(sig->type_at(1)->basic_type() == T_LONG, "getter offset is correct");
2481     } else {
2482       // void putReference(Object base, int/long offset, Object x), etc.
2483       assert(sig->return_type()->basic_type() == T_VOID, "putter must not return a value");
2484       assert(sig->count() == 3, "oop putter has 3 arguments");
2485       assert(sig->type_at(0)->basic_type() == T_OBJECT, "putter base is object");
2486       assert(sig->type_at(1)->basic_type() == T_LONG, "putter offset is correct");
2487       BasicType vtype = sig->type_at(sig->count()-1)->basic_type();
2488       assert(vtype == type, "putter must accept the expected value");
2489     }
2490 #endif // ASSERT
2491  }
2492 #endif //PRODUCT
2493 
2494   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
2495 
2496   Node* receiver = argument(0);  // type: oop
2497 
2498   // Build address expression.
2499   Node* heap_base_oop = top();
2500 
2501   // The base is either a Java object or a value produced by Unsafe.staticFieldBase
2502   Node* base = argument(1);  // type: oop
2503   // The offset is a value produced by Unsafe.staticFieldOffset or Unsafe.objectFieldOffset
2504   Node* offset = argument(2);  // type: long
2505   // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
2506   // to be plain byte offsets, which are also the same as those accepted
2507   // by oopDesc::field_addr.
2508   assert(Unsafe_field_offset_to_byte_offset(11) == 11,
2509          "fieldOffset must be byte-scaled");
2510 
2511   if (base->is_InlineType()) {
2512     assert(!is_store, "InlineTypeNodes are non-larval value objects");
2513     InlineTypeNode* vt = base->as_InlineType();
2514     if (offset->is_Con()) {
2515       long off = find_long_con(offset, 0);
2516       ciInlineKlass* vk = vt->type()->inline_klass();
2517       if ((long)(int)off != off || !vk->contains_field_offset(off)) {
2518         return false;
2519       }
2520 
2521       ciField* field = vk->get_non_flat_field_by_offset(off);
2522       if (field != nullptr) {
2523         BasicType bt = type2field[field->type()->basic_type()];
2524         if (bt == T_ARRAY || bt == T_NARROWOOP) {
2525           bt = T_OBJECT;
2526         }
2527         if (bt == type && !field->is_flat()) {
2528           Node* value = vt->field_value_by_offset(off, false);
2529           if (value->is_InlineType()) {
2530             value = value->as_InlineType()->adjust_scalarization_depth(this);
2531           }
2532           set_result(value);
2533           return true;
2534         }
2535       }
2536     }
2537     {
2538       // Re-execute the unsafe access if allocation triggers deoptimization.
2539       PreserveReexecuteState preexecs(this);
2540       jvms()->set_should_reexecute(true);
2541       vt = vt->buffer(this);
2542     }
2543     base = vt->get_oop();
2544   }
2545 
2546   // 32-bit machines ignore the high half!
2547   offset = ConvL2X(offset);
2548 
2549   // Save state and restore on bailout
2550   SavedState old_state(this);
2551 
2552   Node* adr = make_unsafe_address(base, offset, type, kind == Relaxed);
2553   assert(!stopped(), "Inlining of unsafe access failed: address construction stopped unexpectedly");
2554 
2555   if (_gvn.type(base->uncast())->isa_ptr() == TypePtr::NULL_PTR) {
2556     if (type != T_OBJECT) {
2557       decorators |= IN_NATIVE; // off-heap primitive access
2558     } else {
2559       return false; // off-heap oop accesses are not supported
2560     }
2561   } else {
2562     heap_base_oop = base; // on-heap or mixed access
2563   }
2564 
2565   // Can base be null? Otherwise, always on-heap access.
2566   bool can_access_non_heap = TypePtr::NULL_PTR->higher_equal(_gvn.type(base));
2567 
2568   if (!can_access_non_heap) {
2569     decorators |= IN_HEAP;
2570   }
2571 
2572   Node* val = is_store ? argument(4) : nullptr;
2573 
2574   const TypePtr* adr_type = _gvn.type(adr)->isa_ptr();
2575   if (adr_type == TypePtr::NULL_PTR) {
2576     return false; // off-heap access with zero address
2577   }
2578 
2579   // Try to categorize the address.
2580   Compile::AliasType* alias_type = C->alias_type(adr_type);
2581   assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
2582 
2583   if (alias_type->adr_type() == TypeInstPtr::KLASS ||
2584       alias_type->adr_type() == TypeAryPtr::RANGE) {
2585     return false; // not supported
2586   }
2587 
2588   bool mismatched = false;
2589   BasicType bt = T_ILLEGAL;
2590   ciField* field = nullptr;
2591   if (adr_type->isa_instptr()) {
2592     const TypeInstPtr* instptr = adr_type->is_instptr();
2593     ciInstanceKlass* k = instptr->instance_klass();
2594     int off = instptr->offset();
2595     if (instptr->const_oop() != nullptr &&
2596         k == ciEnv::current()->Class_klass() &&
2597         instptr->offset() >= (k->size_helper() * wordSize)) {
2598       k = instptr->const_oop()->as_instance()->java_lang_Class_klass()->as_instance_klass();
2599       field = k->get_field_by_offset(off, true);
2600     } else {
2601       field = k->get_non_flat_field_by_offset(off);
2602     }
2603     if (field != nullptr) {
2604       bt = type2field[field->type()->basic_type()];
2605     }
2606     if (bt != alias_type->basic_type()) {
2607       // Type mismatch. Is it an access to a nested flat field?
2608       field = k->get_field_by_offset(off, false);
2609       if (field != nullptr) {
2610         bt = type2field[field->type()->basic_type()];
2611       }
2612     }
2613     assert(bt == alias_type->basic_type(), "should match");
2614   } else {
2615     bt = alias_type->basic_type();
2616   }
2617 
2618   if (bt != T_ILLEGAL) {
2619     assert(alias_type->adr_type()->is_oopptr(), "should be on-heap access");
2620     if (bt == T_BYTE && adr_type->isa_aryptr()) {
2621       // Alias type doesn't differentiate between byte[] and boolean[]).
2622       // Use address type to get the element type.
2623       bt = adr_type->is_aryptr()->elem()->array_element_basic_type();
2624     }
2625     if (is_reference_type(bt, true)) {
2626       // accessing an array field with getReference is not a mismatch
2627       bt = T_OBJECT;
2628     }
2629     if ((bt == T_OBJECT) != (type == T_OBJECT)) {
2630       // Don't intrinsify mismatched object accesses
2631       return false;
2632     }
2633     mismatched = (bt != type);
2634   } else if (alias_type->adr_type()->isa_oopptr()) {
2635     mismatched = true; // conservatively mark all "wide" on-heap accesses as mismatched
2636   }
2637 
2638   old_state.discard();
2639   assert(!mismatched || alias_type->adr_type()->is_oopptr(), "off-heap access can't be mismatched");
2640 
2641   if (mismatched) {
2642     decorators |= C2_MISMATCHED;
2643   }
2644 
2645   // First guess at the value type.
2646   const Type *value_type = Type::get_const_basic_type(type);
2647 
2648   // Figure out the memory ordering.
2649   decorators |= mo_decorator_for_access_kind(kind);
2650 
2651   if (!is_store) {
2652     if (type == T_OBJECT) {
2653       const TypeOopPtr* tjp = sharpen_unsafe_type(alias_type, adr_type);
2654       if (tjp != nullptr) {
2655         value_type = tjp;
2656       }
2657     }
2658   }
2659 
2660   receiver = null_check(receiver);
2661   if (stopped()) {
2662     return true;
2663   }
2664   // Heap pointers get a null-check from the interpreter,
2665   // as a courtesy.  However, this is not guaranteed by Unsafe,
2666   // and it is not possible to fully distinguish unintended nulls
2667   // from intended ones in this API.
2668 
2669   if (!is_store) {
2670     Node* p = nullptr;
2671     // Try to constant fold a load from a constant field
2672 
2673     if (heap_base_oop != top() && field != nullptr && field->is_constant() && !field->is_flat() && !mismatched) {
2674       // final or stable field
2675       p = make_constant_from_field(field, heap_base_oop);
2676     }
2677 
2678     if (p == nullptr) { // Could not constant fold the load
2679       p = access_load_at(heap_base_oop, adr, adr_type, value_type, type, decorators);
2680       const TypeOopPtr* ptr = value_type->make_oopptr();
2681       if (ptr != nullptr && ptr->is_inlinetypeptr()) {
2682         // Load a non-flattened inline type from memory
2683         p = InlineTypeNode::make_from_oop(this, p, ptr->inline_klass());
2684       }
2685       // Normalize the value returned by getBoolean in the following cases
2686       if (type == T_BOOLEAN &&
2687           (mismatched ||
2688            heap_base_oop == top() ||                  // - heap_base_oop is null or
2689            (can_access_non_heap && field == nullptr)) // - heap_base_oop is potentially null
2690                                                       //   and the unsafe access is made to large offset
2691                                                       //   (i.e., larger than the maximum offset necessary for any
2692                                                       //   field access)
2693             ) {
2694           IdealKit ideal = IdealKit(this);
2695 #define __ ideal.
2696           IdealVariable normalized_result(ideal);
2697           __ declarations_done();
2698           __ set(normalized_result, p);
2699           __ if_then(p, BoolTest::ne, ideal.ConI(0));
2700           __ set(normalized_result, ideal.ConI(1));
2701           ideal.end_if();
2702           final_sync(ideal);
2703           p = __ value(normalized_result);
2704 #undef __
2705       }
2706     }
2707     if (type == T_ADDRESS) {
2708       p = gvn().transform(new CastP2XNode(nullptr, p));
2709       p = ConvX2UL(p);
2710     }
2711     // The load node has the control of the preceding MemBarCPUOrder.  All
2712     // following nodes will have the control of the MemBarCPUOrder inserted at
2713     // the end of this method.  So, pushing the load onto the stack at a later
2714     // point is fine.
2715     set_result(p);
2716   } else {
2717     if (bt == T_ADDRESS) {
2718       // Repackage the long as a pointer.
2719       val = ConvL2X(val);
2720       val = gvn().transform(new CastX2PNode(val));
2721     }
2722     access_store_at(heap_base_oop, adr, adr_type, val, value_type, type, decorators);
2723   }
2724 
2725   return true;
2726 }
2727 
2728 bool LibraryCallKit::inline_unsafe_flat_access(bool is_store, AccessKind kind) {
2729 #ifdef ASSERT
2730   {
2731     ResourceMark rm;
2732     // Check the signatures.
2733     ciSignature* sig = callee()->signature();
2734     assert(sig->type_at(0)->basic_type() == T_OBJECT, "base should be object, but is %s", type2name(sig->type_at(0)->basic_type()));
2735     assert(sig->type_at(1)->basic_type() == T_LONG, "offset should be long, but is %s", type2name(sig->type_at(1)->basic_type()));
2736     assert(sig->type_at(2)->basic_type() == T_INT, "layout kind should be int, but is %s", type2name(sig->type_at(3)->basic_type()));
2737     assert(sig->type_at(3)->basic_type() == T_OBJECT, "value klass should be object, but is %s", type2name(sig->type_at(4)->basic_type()));
2738     if (is_store) {
2739       assert(sig->return_type()->basic_type() == T_VOID, "putter must not return a value, but returns %s", type2name(sig->return_type()->basic_type()));
2740       assert(sig->count() == 5, "flat putter should have 5 arguments, but has %d", sig->count());
2741       assert(sig->type_at(4)->basic_type() == T_OBJECT, "put value should be object, but is %s", type2name(sig->type_at(5)->basic_type()));
2742     } else {
2743       assert(sig->return_type()->basic_type() == T_OBJECT, "getter must return an object, but returns %s", type2name(sig->return_type()->basic_type()));
2744       assert(sig->count() == 4, "flat getter should have 4 arguments, but has %d", sig->count());
2745     }
2746  }
2747 #endif // ASSERT
2748 
2749   assert(kind == Relaxed, "Only plain accesses for now");
2750   if (callee()->is_static()) {
2751     // caller must have the capability!
2752     return false;
2753   }
2754   C->set_has_unsafe_access(true);
2755 
2756   const TypeInstPtr* value_klass_node = _gvn.type(argument(5))->isa_instptr();
2757   if (value_klass_node == nullptr || value_klass_node->const_oop() == nullptr) {
2758     // parameter valueType is not a constant
2759     return false;
2760   }
2761   ciType* mirror_type = value_klass_node->const_oop()->as_instance()->java_mirror_type();
2762   if (!mirror_type->is_inlinetype()) {
2763     // Dead code
2764     return false;
2765   }
2766   ciInlineKlass* value_klass = mirror_type->as_inline_klass();
2767 
2768   const TypeInt* layout_type = _gvn.type(argument(4))->isa_int();
2769   if (layout_type == nullptr || !layout_type->is_con()) {
2770     // parameter layoutKind is not a constant
2771     return false;
2772   }
2773   assert(layout_type->get_con() >= static_cast<int>(LayoutKind::REFERENCE) &&
2774          layout_type->get_con() <= static_cast<int>(LayoutKind::UNKNOWN),
2775          "invalid layoutKind %d", layout_type->get_con());
2776   LayoutKind layout = static_cast<LayoutKind>(layout_type->get_con());
2777   assert(layout == LayoutKind::REFERENCE || layout == LayoutKind::NULL_FREE_NON_ATOMIC_FLAT ||
2778          layout == LayoutKind::NULL_FREE_ATOMIC_FLAT || layout == LayoutKind::NULLABLE_ATOMIC_FLAT,
2779          "unexpected layoutKind %d", layout_type->get_con());
2780 
2781   null_check(argument(0));
2782   if (stopped()) {
2783     return true;
2784   }
2785 
2786   Node* base = must_be_not_null(argument(1), true);
2787   Node* offset = argument(2);
2788   const Type* base_type = _gvn.type(base);
2789 
2790   Node* ptr;
2791   bool immutable_memory = false;
2792   DecoratorSet decorators = C2_UNSAFE_ACCESS | IN_HEAP | MO_UNORDERED;
2793   if (base_type->isa_instptr()) {
2794     const TypeLong* offset_type = _gvn.type(offset)->isa_long();
2795     if (offset_type == nullptr || !offset_type->is_con()) {
2796       // Offset into a non-array should be a constant
2797       decorators |= C2_MISMATCHED;
2798     } else {
2799       int offset_con = checked_cast<int>(offset_type->get_con());
2800       ciInstanceKlass* base_klass = base_type->is_instptr()->instance_klass();
2801       ciField* field = base_klass->get_non_flat_field_by_offset(offset_con);
2802       if (field == nullptr) {
2803         assert(!base_klass->is_final(), "non-existence field at offset %d of class %s", offset_con, base_klass->name()->as_utf8());
2804         decorators |= C2_MISMATCHED;
2805       } else {
2806         assert(field->type() == value_klass, "field at offset %d of %s is of type %s, but valueType is %s",
2807                offset_con, base_klass->name()->as_utf8(), field->type()->name(), value_klass->name()->as_utf8());
2808         immutable_memory = field->is_strict() && field->is_final();
2809 
2810         if (base->is_InlineType()) {
2811           assert(!is_store, "Cannot store into a non-larval value object");
2812           set_result(base->as_InlineType()->field_value_by_offset(offset_con, false));
2813           return true;
2814         }
2815       }
2816     }
2817 
2818     if (base->is_InlineType()) {
2819       assert(!is_store, "Cannot store into a non-larval value object");
2820       base = base->as_InlineType()->buffer(this, true);
2821     }
2822     ptr = basic_plus_adr(base, ConvL2X(offset));
2823   } else if (base_type->isa_aryptr()) {
2824     decorators |= IS_ARRAY;
2825     if (layout == LayoutKind::REFERENCE) {
2826       if (!base_type->is_aryptr()->is_not_flat()) {
2827         const TypeAryPtr* array_type = base_type->is_aryptr()->cast_to_not_flat();
2828         Node* new_base = _gvn.transform(new CastPPNode(control(), base, array_type, ConstraintCastNode::DependencyType::NonFloatingNarrowing));
2829         replace_in_map(base, new_base);
2830         base = new_base;
2831       }
2832       ptr = basic_plus_adr(base, ConvL2X(offset));
2833     } else {
2834       if (UseArrayFlattening) {
2835         // Flat array must have an exact type
2836         bool is_null_free = !LayoutKindHelper::is_nullable_flat(layout);
2837         bool is_atomic = LayoutKindHelper::is_atomic_flat(layout);
2838         Node* new_base = cast_to_flat_array_exact(base, value_klass, is_null_free, is_atomic);
2839         replace_in_map(base, new_base);
2840         base = new_base;
2841         ptr = basic_plus_adr(base, ConvL2X(offset));
2842         const TypeAryPtr* ptr_type = _gvn.type(ptr)->is_aryptr();
2843         if (ptr_type->field_offset().get() != 0) {
2844           ptr = _gvn.transform(new CastPPNode(control(), ptr, ptr_type->with_field_offset(0), ConstraintCastNode::DependencyType::NonFloatingNarrowing));
2845         }
2846       } else {
2847         uncommon_trap(Deoptimization::Reason_intrinsic,
2848                       Deoptimization::Action_none);
2849         return true;
2850       }
2851     }
2852   } else {
2853     decorators |= C2_MISMATCHED;
2854     ptr = basic_plus_adr(base, ConvL2X(offset));
2855   }
2856 
2857   if (is_store) {
2858     Node* value = argument(6);
2859     const Type* value_type = _gvn.type(value);
2860     if (!value_type->is_inlinetypeptr()) {
2861       value_type = Type::get_const_type(value_klass)->filter_speculative(value_type);
2862       Node* new_value = _gvn.transform(new CastPPNode(control(), value, value_type, ConstraintCastNode::DependencyType::NonFloatingNarrowing));
2863       new_value = InlineTypeNode::make_from_oop(this, new_value, value_klass);
2864       replace_in_map(value, new_value);
2865       value = new_value;
2866     }
2867 
2868     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());
2869     if (layout == LayoutKind::REFERENCE) {
2870       const TypePtr* ptr_type = (decorators & C2_MISMATCHED) != 0 ? TypeRawPtr::BOTTOM : _gvn.type(ptr)->is_ptr();
2871       access_store_at(base, ptr, ptr_type, value, value_type, T_OBJECT, decorators);
2872     } else {
2873       bool atomic = LayoutKindHelper::is_atomic_flat(layout);
2874       bool null_free = !LayoutKindHelper::is_nullable_flat(layout);
2875       value->as_InlineType()->store_flat(this, base, ptr, atomic, immutable_memory, null_free, decorators);
2876     }
2877 
2878     return true;
2879   } else {
2880     decorators |= (C2_CONTROL_DEPENDENT_LOAD | C2_UNKNOWN_CONTROL_LOAD);
2881     InlineTypeNode* result;
2882     if (layout == LayoutKind::REFERENCE) {
2883       const TypePtr* ptr_type = (decorators & C2_MISMATCHED) != 0 ? TypeRawPtr::BOTTOM : _gvn.type(ptr)->is_ptr();
2884       Node* oop = access_load_at(base, ptr, ptr_type, Type::get_const_type(value_klass), T_OBJECT, decorators);
2885       result = InlineTypeNode::make_from_oop(this, oop, value_klass);
2886     } else {
2887       bool atomic = LayoutKindHelper::is_atomic_flat(layout);
2888       bool null_free = !LayoutKindHelper::is_nullable_flat(layout);
2889       result = InlineTypeNode::make_from_flat(this, value_klass, base, ptr, atomic, immutable_memory, null_free, decorators);
2890     }
2891 
2892     set_result(result);
2893     return true;
2894   }
2895 }
2896 
2897 bool LibraryCallKit::inline_unsafe_make_private_buffer() {
2898   Node* receiver = argument(0);
2899   Node* value = argument(1);
2900 
2901   const Type* type = gvn().type(value);
2902   if (!type->is_inlinetypeptr()) {
2903     C->record_method_not_compilable("value passed to Unsafe::makePrivateBuffer is not of a constant value type");
2904     return false;
2905   }
2906 
2907   null_check(receiver);
2908   if (stopped()) {
2909     return true;
2910   }
2911 
2912   value = null_check(value);
2913   if (stopped()) {
2914     return true;
2915   }
2916 
2917   ciInlineKlass* vk = type->inline_klass();
2918   Node* klass = makecon(TypeKlassPtr::make(vk));
2919   Node* obj = new_instance(klass);
2920   AllocateNode::Ideal_allocation(obj)->_larval = true;
2921 
2922   assert(value->is_InlineType(), "must be an InlineTypeNode");
2923   Node* payload_ptr = basic_plus_adr(obj, vk->payload_offset());
2924   value->as_InlineType()->store_flat(this, obj, payload_ptr, false, true, true, IN_HEAP | MO_UNORDERED);
2925 
2926   set_result(obj);
2927   return true;
2928 }
2929 
2930 bool LibraryCallKit::inline_unsafe_finish_private_buffer() {
2931   Node* receiver = argument(0);
2932   Node* buffer = argument(1);
2933 
2934   const Type* type = gvn().type(buffer);
2935   if (!type->is_inlinetypeptr()) {
2936     C->record_method_not_compilable("value passed to Unsafe::finishPrivateBuffer is not of a constant value type");
2937     return false;
2938   }
2939 
2940   AllocateNode* alloc = AllocateNode::Ideal_allocation(buffer);
2941   if (alloc == nullptr) {
2942     C->record_method_not_compilable("value passed to Unsafe::finishPrivateBuffer must be allocated by Unsafe::makePrivateBuffer");
2943     return false;
2944   }
2945 
2946   null_check(receiver);
2947   if (stopped()) {
2948     return true;
2949   }
2950 
2951   // Unset the larval bit in the object header
2952   Node* old_header = make_load(control(), buffer, TypeX_X, TypeX_X->basic_type(), MemNode::unordered, LoadNode::Pinned);
2953   Node* new_header = gvn().transform(new AndXNode(old_header, MakeConX(~markWord::larval_bit_in_place)));
2954   access_store_at(buffer, buffer, type->is_ptr(), new_header, TypeX_X, TypeX_X->basic_type(), MO_UNORDERED | IN_HEAP);
2955 
2956   // We must ensure that the buffer is properly published
2957   insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out(AllocateNode::RawAddress));
2958   assert(!type->maybe_null(), "result of an allocation should not be null");
2959   set_result(InlineTypeNode::make_from_oop(this, buffer, type->inline_klass()));
2960   return true;
2961 }
2962 
2963 //----------------------------inline_unsafe_load_store----------------------------
2964 // This method serves a couple of different customers (depending on LoadStoreKind):
2965 //
2966 // LS_cmp_swap:
2967 //
2968 //   boolean compareAndSetReference(Object o, long offset, Object expected, Object x);
2969 //   boolean compareAndSetInt(   Object o, long offset, int    expected, int    x);
2970 //   boolean compareAndSetLong(  Object o, long offset, long   expected, long   x);
2971 //
2972 // LS_cmp_swap_weak:
2973 //
2974 //   boolean weakCompareAndSetReference(       Object o, long offset, Object expected, Object x);
2975 //   boolean weakCompareAndSetReferencePlain(  Object o, long offset, Object expected, Object x);
2976 //   boolean weakCompareAndSetReferenceAcquire(Object o, long offset, Object expected, Object x);
2977 //   boolean weakCompareAndSetReferenceRelease(Object o, long offset, Object expected, Object x);
2978 //
2979 //   boolean weakCompareAndSetInt(          Object o, long offset, int    expected, int    x);
2980 //   boolean weakCompareAndSetIntPlain(     Object o, long offset, int    expected, int    x);
2981 //   boolean weakCompareAndSetIntAcquire(   Object o, long offset, int    expected, int    x);
2982 //   boolean weakCompareAndSetIntRelease(   Object o, long offset, int    expected, int    x);
2983 //
2984 //   boolean weakCompareAndSetLong(         Object o, long offset, long   expected, long   x);
2985 //   boolean weakCompareAndSetLongPlain(    Object o, long offset, long   expected, long   x);
2986 //   boolean weakCompareAndSetLongAcquire(  Object o, long offset, long   expected, long   x);
2987 //   boolean weakCompareAndSetLongRelease(  Object o, long offset, long   expected, long   x);
2988 //
2989 // LS_cmp_exchange:
2990 //
2991 //   Object compareAndExchangeReferenceVolatile(Object o, long offset, Object expected, Object x);
2992 //   Object compareAndExchangeReferenceAcquire( Object o, long offset, Object expected, Object x);
2993 //   Object compareAndExchangeReferenceRelease( Object o, long offset, Object expected, Object x);
2994 //
2995 //   Object compareAndExchangeIntVolatile(   Object o, long offset, Object expected, Object x);
2996 //   Object compareAndExchangeIntAcquire(    Object o, long offset, Object expected, Object x);
2997 //   Object compareAndExchangeIntRelease(    Object o, long offset, Object expected, Object x);
2998 //
2999 //   Object compareAndExchangeLongVolatile(  Object o, long offset, Object expected, Object x);
3000 //   Object compareAndExchangeLongAcquire(   Object o, long offset, Object expected, Object x);
3001 //   Object compareAndExchangeLongRelease(   Object o, long offset, Object expected, Object x);
3002 //
3003 // LS_get_add:
3004 //
3005 //   int  getAndAddInt( Object o, long offset, int  delta)
3006 //   long getAndAddLong(Object o, long offset, long delta)
3007 //
3008 // LS_get_set:
3009 //
3010 //   int    getAndSet(Object o, long offset, int    newValue)
3011 //   long   getAndSet(Object o, long offset, long   newValue)
3012 //   Object getAndSet(Object o, long offset, Object newValue)
3013 //
3014 bool LibraryCallKit::inline_unsafe_load_store(const BasicType type, const LoadStoreKind kind, const AccessKind access_kind) {
3015   // This basic scheme here is the same as inline_unsafe_access, but
3016   // differs in enough details that combining them would make the code
3017   // overly confusing.  (This is a true fact! I originally combined
3018   // them, but even I was confused by it!) As much code/comments as
3019   // possible are retained from inline_unsafe_access though to make
3020   // the correspondences clearer. - dl
3021 
3022   if (callee()->is_static())  return false;  // caller must have the capability!
3023 
3024   DecoratorSet decorators = C2_UNSAFE_ACCESS;
3025   decorators |= mo_decorator_for_access_kind(access_kind);
3026 
3027 #ifndef PRODUCT
3028   BasicType rtype;
3029   {
3030     ResourceMark rm;
3031     // Check the signatures.
3032     ciSignature* sig = callee()->signature();
3033     rtype = sig->return_type()->basic_type();
3034     switch(kind) {
3035       case LS_get_add:
3036       case LS_get_set: {
3037       // Check the signatures.
3038 #ifdef ASSERT
3039       assert(rtype == type, "get and set must return the expected type");
3040       assert(sig->count() == 3, "get and set has 3 arguments");
3041       assert(sig->type_at(0)->basic_type() == T_OBJECT, "get and set base is object");
3042       assert(sig->type_at(1)->basic_type() == T_LONG, "get and set offset is long");
3043       assert(sig->type_at(2)->basic_type() == type, "get and set must take expected type as new value/delta");
3044       assert(access_kind == Volatile, "mo is not passed to intrinsic nodes in current implementation");
3045 #endif // ASSERT
3046         break;
3047       }
3048       case LS_cmp_swap:
3049       case LS_cmp_swap_weak: {
3050       // Check the signatures.
3051 #ifdef ASSERT
3052       assert(rtype == T_BOOLEAN, "CAS must return boolean");
3053       assert(sig->count() == 4, "CAS has 4 arguments");
3054       assert(sig->type_at(0)->basic_type() == T_OBJECT, "CAS base is object");
3055       assert(sig->type_at(1)->basic_type() == T_LONG, "CAS offset is long");
3056 #endif // ASSERT
3057         break;
3058       }
3059       case LS_cmp_exchange: {
3060       // Check the signatures.
3061 #ifdef ASSERT
3062       assert(rtype == type, "CAS must return the expected type");
3063       assert(sig->count() == 4, "CAS has 4 arguments");
3064       assert(sig->type_at(0)->basic_type() == T_OBJECT, "CAS base is object");
3065       assert(sig->type_at(1)->basic_type() == T_LONG, "CAS offset is long");
3066 #endif // ASSERT
3067         break;
3068       }
3069       default:
3070         ShouldNotReachHere();
3071     }
3072   }
3073 #endif //PRODUCT
3074 
3075   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
3076 
3077   // Get arguments:
3078   Node* receiver = nullptr;
3079   Node* base     = nullptr;
3080   Node* offset   = nullptr;
3081   Node* oldval   = nullptr;
3082   Node* newval   = nullptr;
3083   switch(kind) {
3084     case LS_cmp_swap:
3085     case LS_cmp_swap_weak:
3086     case LS_cmp_exchange: {
3087       const bool two_slot_type = type2size[type] == 2;
3088       receiver = argument(0);  // type: oop
3089       base     = argument(1);  // type: oop
3090       offset   = argument(2);  // type: long
3091       oldval   = argument(4);  // type: oop, int, or long
3092       newval   = argument(two_slot_type ? 6 : 5);  // type: oop, int, or long
3093       break;
3094     }
3095     case LS_get_add:
3096     case LS_get_set: {
3097       receiver = argument(0);  // type: oop
3098       base     = argument(1);  // type: oop
3099       offset   = argument(2);  // type: long
3100       oldval   = nullptr;
3101       newval   = argument(4);  // type: oop, int, or long
3102       break;
3103     }
3104     default:
3105       ShouldNotReachHere();
3106   }
3107 
3108   // Build field offset expression.
3109   // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
3110   // to be plain byte offsets, which are also the same as those accepted
3111   // by oopDesc::field_addr.
3112   assert(Unsafe_field_offset_to_byte_offset(11) == 11, "fieldOffset must be byte-scaled");
3113   // 32-bit machines ignore the high half of long offsets
3114   offset = ConvL2X(offset);
3115   // Save state and restore on bailout
3116   SavedState old_state(this);
3117   Node* adr = make_unsafe_address(base, offset,type, false);
3118   const TypePtr *adr_type = _gvn.type(adr)->isa_ptr();
3119 
3120   Compile::AliasType* alias_type = C->alias_type(adr_type);
3121   BasicType bt = alias_type->basic_type();
3122   if (bt != T_ILLEGAL &&
3123       (is_reference_type(bt) != (type == T_OBJECT))) {
3124     // Don't intrinsify mismatched object accesses.
3125     return false;
3126   }
3127 
3128   old_state.discard();
3129 
3130   // For CAS, unlike inline_unsafe_access, there seems no point in
3131   // trying to refine types. Just use the coarse types here.
3132   assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
3133   const Type *value_type = Type::get_const_basic_type(type);
3134 
3135   switch (kind) {
3136     case LS_get_set:
3137     case LS_cmp_exchange: {
3138       if (type == T_OBJECT) {
3139         const TypeOopPtr* tjp = sharpen_unsafe_type(alias_type, adr_type);
3140         if (tjp != nullptr) {
3141           value_type = tjp;
3142         }
3143       }
3144       break;
3145     }
3146     case LS_cmp_swap:
3147     case LS_cmp_swap_weak:
3148     case LS_get_add:
3149       break;
3150     default:
3151       ShouldNotReachHere();
3152   }
3153 
3154   // Null check receiver.
3155   receiver = null_check(receiver);
3156   if (stopped()) {
3157     return true;
3158   }
3159 
3160   int alias_idx = C->get_alias_index(adr_type);
3161 
3162   if (is_reference_type(type)) {
3163     decorators |= IN_HEAP | ON_UNKNOWN_OOP_REF;
3164 
3165     if (oldval != nullptr && oldval->is_InlineType()) {
3166       // Re-execute the unsafe access if allocation triggers deoptimization.
3167       PreserveReexecuteState preexecs(this);
3168       jvms()->set_should_reexecute(true);
3169       oldval = oldval->as_InlineType()->buffer(this)->get_oop();
3170     }
3171     if (newval != nullptr && newval->is_InlineType()) {
3172       // Re-execute the unsafe access if allocation triggers deoptimization.
3173       PreserveReexecuteState preexecs(this);
3174       jvms()->set_should_reexecute(true);
3175       newval = newval->as_InlineType()->buffer(this)->get_oop();
3176     }
3177 
3178     // Transformation of a value which could be null pointer (CastPP #null)
3179     // could be delayed during Parse (for example, in adjust_map_after_if()).
3180     // Execute transformation here to avoid barrier generation in such case.
3181     if (_gvn.type(newval) == TypePtr::NULL_PTR)
3182       newval = _gvn.makecon(TypePtr::NULL_PTR);
3183 
3184     if (oldval != nullptr && _gvn.type(oldval) == TypePtr::NULL_PTR) {
3185       // Refine the value to a null constant, when it is known to be null
3186       oldval = _gvn.makecon(TypePtr::NULL_PTR);
3187     }
3188   }
3189 
3190   Node* result = nullptr;
3191   switch (kind) {
3192     case LS_cmp_exchange: {
3193       result = access_atomic_cmpxchg_val_at(base, adr, adr_type, alias_idx,
3194                                             oldval, newval, value_type, type, decorators);
3195       break;
3196     }
3197     case LS_cmp_swap_weak:
3198       decorators |= C2_WEAK_CMPXCHG;
3199     case LS_cmp_swap: {
3200       result = access_atomic_cmpxchg_bool_at(base, adr, adr_type, alias_idx,
3201                                              oldval, newval, value_type, type, decorators);
3202       break;
3203     }
3204     case LS_get_set: {
3205       result = access_atomic_xchg_at(base, adr, adr_type, alias_idx,
3206                                      newval, value_type, type, decorators);
3207       break;
3208     }
3209     case LS_get_add: {
3210       result = access_atomic_add_at(base, adr, adr_type, alias_idx,
3211                                     newval, value_type, type, decorators);
3212       break;
3213     }
3214     default:
3215       ShouldNotReachHere();
3216   }
3217 
3218   assert(type2size[result->bottom_type()->basic_type()] == type2size[rtype], "result type should match");
3219   set_result(result);
3220   return true;
3221 }
3222 
3223 bool LibraryCallKit::inline_unsafe_fence(vmIntrinsics::ID id) {
3224   // Regardless of form, don't allow previous ld/st to move down,
3225   // then issue acquire, release, or volatile mem_bar.
3226   insert_mem_bar(Op_MemBarCPUOrder);
3227   switch(id) {
3228     case vmIntrinsics::_loadFence:
3229       insert_mem_bar(Op_LoadFence);
3230       return true;
3231     case vmIntrinsics::_storeFence:
3232       insert_mem_bar(Op_StoreFence);
3233       return true;
3234     case vmIntrinsics::_storeStoreFence:
3235       insert_mem_bar(Op_StoreStoreFence);
3236       return true;
3237     case vmIntrinsics::_fullFence:
3238       insert_mem_bar(Op_MemBarVolatile);
3239       return true;
3240     default:
3241       fatal_unexpected_iid(id);
3242       return false;
3243   }
3244 }
3245 
3246 // private native int arrayInstanceBaseOffset0(Object[] array);
3247 bool LibraryCallKit::inline_arrayInstanceBaseOffset() {
3248   Node* array = argument(1);
3249   Node* klass_node = load_object_klass(array);
3250 
3251   jint  layout_con = Klass::_lh_neutral_value;
3252   Node* layout_val = get_layout_helper(klass_node, layout_con);
3253   int   layout_is_con = (layout_val == nullptr);
3254 
3255   Node* header_size = nullptr;
3256   if (layout_is_con) {
3257     int hsize = Klass::layout_helper_header_size(layout_con);
3258     header_size = intcon(hsize);
3259   } else {
3260     Node* hss = intcon(Klass::_lh_header_size_shift);
3261     Node* hsm = intcon(Klass::_lh_header_size_mask);
3262     header_size = _gvn.transform(new URShiftINode(layout_val, hss));
3263     header_size = _gvn.transform(new AndINode(header_size, hsm));
3264   }
3265   set_result(header_size);
3266   return true;
3267 }
3268 
3269 // private native int arrayInstanceIndexScale0(Object[] array);
3270 bool LibraryCallKit::inline_arrayInstanceIndexScale() {
3271   Node* array = argument(1);
3272   Node* klass_node = load_object_klass(array);
3273 
3274   jint  layout_con = Klass::_lh_neutral_value;
3275   Node* layout_val = get_layout_helper(klass_node, layout_con);
3276   int   layout_is_con = (layout_val == nullptr);
3277 
3278   Node* element_size = nullptr;
3279   if (layout_is_con) {
3280     int log_element_size  = Klass::layout_helper_log2_element_size(layout_con);
3281     int elem_size = 1 << log_element_size;
3282     element_size = intcon(elem_size);
3283   } else {
3284     Node* ess = intcon(Klass::_lh_log2_element_size_shift);
3285     Node* esm = intcon(Klass::_lh_log2_element_size_mask);
3286     Node* log_element_size = _gvn.transform(new URShiftINode(layout_val, ess));
3287     log_element_size = _gvn.transform(new AndINode(log_element_size, esm));
3288     element_size = _gvn.transform(new LShiftINode(intcon(1), log_element_size));
3289   }
3290   set_result(element_size);
3291   return true;
3292 }
3293 
3294 // private native int arrayLayout0(Object[] array);
3295 bool LibraryCallKit::inline_arrayLayout() {
3296   RegionNode* region = new RegionNode(2);
3297   Node* phi = new PhiNode(region, TypeInt::POS);
3298 
3299   Node* array = argument(1);
3300   Node* klass_node = load_object_klass(array);
3301   generate_refArray_guard(klass_node, region);
3302   if (region->req() == 3) {
3303     phi->add_req(intcon((jint)LayoutKind::REFERENCE));
3304   }
3305 
3306   int layout_kind_offset = in_bytes(FlatArrayKlass::layout_kind_offset());
3307   Node* layout_kind_addr = basic_plus_adr(klass_node, layout_kind_offset);
3308   Node* layout_kind = make_load(nullptr, layout_kind_addr, TypeInt::POS, T_INT, MemNode::unordered);
3309 
3310   region->init_req(1, control());
3311   phi->init_req(1, layout_kind);
3312 
3313   set_control(_gvn.transform(region));
3314   set_result(_gvn.transform(phi));
3315   return true;
3316 }
3317 
3318 // private native int[] getFieldMap0(Class <?> c);
3319 //   int offset = c._klass._acmp_maps_offset;
3320 //   return (int[])c.obj_field(offset);
3321 bool LibraryCallKit::inline_getFieldMap() {
3322   Node* mirror = argument(1);
3323   Node* klass = load_klass_from_mirror(mirror, false, nullptr, 0);
3324 
3325   int field_map_offset_offset = in_bytes(InstanceKlass::acmp_maps_offset_offset());
3326   Node* field_map_offset_addr = basic_plus_adr(klass, field_map_offset_offset);
3327   Node* field_map_offset = make_load(nullptr, field_map_offset_addr, TypeInt::INT, T_INT, MemNode::unordered);
3328   field_map_offset = _gvn.transform(ConvI2L(field_map_offset));
3329 
3330   Node* map_addr = basic_plus_adr(mirror, field_map_offset);
3331   const TypeAryPtr* val_type = TypeAryPtr::INTS->cast_to_ptr_type(TypePtr::NotNull)->with_offset(0);
3332   // TODO 8350865 Remove this
3333   val_type = val_type->cast_to_not_flat(true)->cast_to_not_null_free(true);
3334   Node* map = access_load_at(mirror, map_addr, TypeAryPtr::INTS, val_type, T_ARRAY, IN_HEAP | MO_UNORDERED);
3335 
3336   set_result(map);
3337   return true;
3338 }
3339 
3340 bool LibraryCallKit::inline_onspinwait() {
3341   insert_mem_bar(Op_OnSpinWait);
3342   return true;
3343 }
3344 
3345 bool LibraryCallKit::klass_needs_init_guard(Node* kls) {
3346   if (!kls->is_Con()) {
3347     return true;
3348   }
3349   const TypeInstKlassPtr* klsptr = kls->bottom_type()->isa_instklassptr();
3350   if (klsptr == nullptr) {
3351     return true;
3352   }
3353   ciInstanceKlass* ik = klsptr->instance_klass();
3354   // don't need a guard for a klass that is already initialized
3355   return !ik->is_initialized();
3356 }
3357 
3358 //----------------------------inline_unsafe_writeback0-------------------------
3359 // public native void Unsafe.writeback0(long address)
3360 bool LibraryCallKit::inline_unsafe_writeback0() {
3361   if (!Matcher::has_match_rule(Op_CacheWB)) {
3362     return false;
3363   }
3364 #ifndef PRODUCT
3365   assert(Matcher::has_match_rule(Op_CacheWBPreSync), "found match rule for CacheWB but not CacheWBPreSync");
3366   assert(Matcher::has_match_rule(Op_CacheWBPostSync), "found match rule for CacheWB but not CacheWBPostSync");
3367   ciSignature* sig = callee()->signature();
3368   assert(sig->type_at(0)->basic_type() == T_LONG, "Unsafe_writeback0 address is long!");
3369 #endif
3370   null_check_receiver();  // null-check, then ignore
3371   Node *addr = argument(1);
3372   addr = new CastX2PNode(addr);
3373   addr = _gvn.transform(addr);
3374   Node *flush = new CacheWBNode(control(), memory(TypeRawPtr::BOTTOM), addr);
3375   flush = _gvn.transform(flush);
3376   set_memory(flush, TypeRawPtr::BOTTOM);
3377   return true;
3378 }
3379 
3380 //----------------------------inline_unsafe_writeback0-------------------------
3381 // public native void Unsafe.writeback0(long address)
3382 bool LibraryCallKit::inline_unsafe_writebackSync0(bool is_pre) {
3383   if (is_pre && !Matcher::has_match_rule(Op_CacheWBPreSync)) {
3384     return false;
3385   }
3386   if (!is_pre && !Matcher::has_match_rule(Op_CacheWBPostSync)) {
3387     return false;
3388   }
3389 #ifndef PRODUCT
3390   assert(Matcher::has_match_rule(Op_CacheWB),
3391          (is_pre ? "found match rule for CacheWBPreSync but not CacheWB"
3392                 : "found match rule for CacheWBPostSync but not CacheWB"));
3393 
3394 #endif
3395   null_check_receiver();  // null-check, then ignore
3396   Node *sync;
3397   if (is_pre) {
3398     sync = new CacheWBPreSyncNode(control(), memory(TypeRawPtr::BOTTOM));
3399   } else {
3400     sync = new CacheWBPostSyncNode(control(), memory(TypeRawPtr::BOTTOM));
3401   }
3402   sync = _gvn.transform(sync);
3403   set_memory(sync, TypeRawPtr::BOTTOM);
3404   return true;
3405 }
3406 
3407 //----------------------------inline_unsafe_allocate---------------------------
3408 // public native Object Unsafe.allocateInstance(Class<?> cls);
3409 bool LibraryCallKit::inline_unsafe_allocate() {
3410 
3411 #if INCLUDE_JVMTI
3412   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
3413     return false;
3414   }
3415 #endif //INCLUDE_JVMTI
3416 
3417   if (callee()->is_static())  return false;  // caller must have the capability!
3418 
3419   null_check_receiver();  // null-check, then ignore
3420   Node* cls = null_check(argument(1));
3421   if (stopped())  return true;
3422 
3423   Node* kls = load_klass_from_mirror(cls, false, nullptr, 0);
3424   kls = null_check(kls);
3425   if (stopped())  return true;  // argument was like int.class
3426 
3427 #if INCLUDE_JVMTI
3428     // Don't try to access new allocated obj in the intrinsic.
3429     // It causes perfomance issues even when jvmti event VmObjectAlloc is disabled.
3430     // Deoptimize and allocate in interpreter instead.
3431     Node* addr = makecon(TypeRawPtr::make((address) &JvmtiExport::_should_notify_object_alloc));
3432     Node* should_post_vm_object_alloc = make_load(this->control(), addr, TypeInt::INT, T_INT, MemNode::unordered);
3433     Node* chk = _gvn.transform(new CmpINode(should_post_vm_object_alloc, intcon(0)));
3434     Node* tst = _gvn.transform(new BoolNode(chk, BoolTest::eq));
3435     {
3436       BuildCutout unless(this, tst, PROB_MAX);
3437       uncommon_trap(Deoptimization::Reason_intrinsic,
3438                     Deoptimization::Action_make_not_entrant);
3439     }
3440     if (stopped()) {
3441       return true;
3442     }
3443 #endif //INCLUDE_JVMTI
3444 
3445   Node* test = nullptr;
3446   if (LibraryCallKit::klass_needs_init_guard(kls)) {
3447     // Note:  The argument might still be an illegal value like
3448     // Serializable.class or Object[].class.   The runtime will handle it.
3449     // But we must make an explicit check for initialization.
3450     Node* insp = basic_plus_adr(kls, in_bytes(InstanceKlass::init_state_offset()));
3451     // Use T_BOOLEAN for InstanceKlass::_init_state so the compiler
3452     // can generate code to load it as unsigned byte.
3453     Node* inst = make_load(nullptr, insp, TypeInt::UBYTE, T_BOOLEAN, MemNode::acquire);
3454     Node* bits = intcon(InstanceKlass::fully_initialized);
3455     test = _gvn.transform(new SubINode(inst, bits));
3456     // The 'test' is non-zero if we need to take a slow path.
3457   }
3458   Node* obj = nullptr;
3459   const TypeInstKlassPtr* tkls = _gvn.type(kls)->isa_instklassptr();
3460   if (tkls != nullptr && tkls->instance_klass()->is_inlinetype()) {
3461     obj = InlineTypeNode::make_all_zero(_gvn, tkls->instance_klass()->as_inline_klass())->buffer(this);
3462   } else {
3463     obj = new_instance(kls, test);
3464   }
3465   set_result(obj);
3466   return true;
3467 }
3468 
3469 //------------------------inline_native_time_funcs--------------
3470 // inline code for System.currentTimeMillis() and System.nanoTime()
3471 // these have the same type and signature
3472 bool LibraryCallKit::inline_native_time_funcs(address funcAddr, const char* funcName) {
3473   const TypeFunc* tf = OptoRuntime::void_long_Type();
3474   const TypePtr* no_memory_effects = nullptr;
3475   Node* time = make_runtime_call(RC_LEAF, tf, funcAddr, funcName, no_memory_effects);
3476   Node* value = _gvn.transform(new ProjNode(time, TypeFunc::Parms+0));
3477 #ifdef ASSERT
3478   Node* value_top = _gvn.transform(new ProjNode(time, TypeFunc::Parms+1));
3479   assert(value_top == top(), "second value must be top");
3480 #endif
3481   set_result(value);
3482   return true;
3483 }
3484 
3485 //--------------------inline_native_vthread_start_transition--------------------
3486 // inline void startTransition(boolean is_mount);
3487 // inline void startFinalTransition();
3488 // Pseudocode of implementation:
3489 //
3490 // java_lang_Thread::set_is_in_vthread_transition(vthread, true);
3491 // carrier->set_is_in_vthread_transition(true);
3492 // OrderAccess::storeload();
3493 // int disable_requests = java_lang_Thread::vthread_transition_disable_count(vthread)
3494 //                        + global_vthread_transition_disable_count();
3495 // if (disable_requests > 0) {
3496 //   slow path: runtime call
3497 // }
3498 bool LibraryCallKit::inline_native_vthread_start_transition(address funcAddr, const char* funcName, bool is_final_transition) {
3499   Node* vt_oop = _gvn.transform(must_be_not_null(argument(0), true)); // VirtualThread this argument
3500   IdealKit ideal(this);
3501 
3502   Node* thread = ideal.thread();
3503   Node* jt_addr = basic_plus_adr(thread, in_bytes(JavaThread::is_in_vthread_transition_offset()));
3504   Node* vt_addr = basic_plus_adr(vt_oop, java_lang_Thread::is_in_vthread_transition_offset());
3505   access_store_at(nullptr, jt_addr, _gvn.type(jt_addr)->is_ptr(), ideal.ConI(1), TypeInt::BOOL, T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
3506   access_store_at(nullptr, vt_addr, _gvn.type(vt_addr)->is_ptr(), ideal.ConI(1), TypeInt::BOOL, T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
3507   insert_mem_bar(Op_MemBarVolatile);
3508   ideal.sync_kit(this);
3509 
3510   Node* global_disable_addr = makecon(TypeRawPtr::make((address)MountUnmountDisabler::global_vthread_transition_disable_count_address()));
3511   Node* global_disable = ideal.load(ideal.ctrl(), global_disable_addr, TypeInt::INT, T_INT, Compile::AliasIdxRaw, true /*require_atomic_access*/);
3512   Node* vt_disable_addr = basic_plus_adr(vt_oop, java_lang_Thread::vthread_transition_disable_count_offset());
3513   Node* vt_disable = ideal.load(ideal.ctrl(), vt_disable_addr, TypeInt::INT, T_INT, Compile::AliasIdxRaw, true /*require_atomic_access*/);
3514   Node* disabled = _gvn.transform(new AddINode(global_disable, vt_disable));
3515 
3516   ideal.if_then(disabled, BoolTest::ne, ideal.ConI(0)); {
3517     sync_kit(ideal);
3518     Node* is_mount = is_final_transition ? ideal.ConI(0) : _gvn.transform(argument(1));
3519     const TypeFunc* tf = OptoRuntime::vthread_transition_Type();
3520     make_runtime_call(RC_NO_LEAF, tf, funcAddr, funcName, TypePtr::BOTTOM, vt_oop, is_mount);
3521     ideal.sync_kit(this);
3522   }
3523   ideal.end_if();
3524 
3525   final_sync(ideal);
3526   return true;
3527 }
3528 
3529 bool LibraryCallKit::inline_native_vthread_end_transition(address funcAddr, const char* funcName, bool is_first_transition) {
3530   Node* vt_oop = _gvn.transform(must_be_not_null(argument(0), true)); // VirtualThread this argument
3531   IdealKit ideal(this);
3532 
3533   Node* _notify_jvmti_addr = makecon(TypeRawPtr::make((address)MountUnmountDisabler::notify_jvmti_events_address()));
3534   Node* _notify_jvmti = ideal.load(ideal.ctrl(), _notify_jvmti_addr, TypeInt::BOOL, T_BOOLEAN, Compile::AliasIdxRaw);
3535 
3536   ideal.if_then(_notify_jvmti, BoolTest::eq, ideal.ConI(1)); {
3537     sync_kit(ideal);
3538     Node* is_mount = is_first_transition ? ideal.ConI(1) : _gvn.transform(argument(1));
3539     const TypeFunc* tf = OptoRuntime::vthread_transition_Type();
3540     make_runtime_call(RC_NO_LEAF, tf, funcAddr, funcName, TypePtr::BOTTOM, vt_oop, is_mount);
3541     ideal.sync_kit(this);
3542   } ideal.else_(); {
3543     Node* thread = ideal.thread();
3544     Node* jt_addr = basic_plus_adr(thread, in_bytes(JavaThread::is_in_vthread_transition_offset()));
3545     Node* vt_addr = basic_plus_adr(vt_oop, java_lang_Thread::is_in_vthread_transition_offset());
3546 
3547     sync_kit(ideal);
3548     access_store_at(nullptr, jt_addr, _gvn.type(jt_addr)->is_ptr(), ideal.ConI(0), TypeInt::BOOL, T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
3549     access_store_at(nullptr, vt_addr, _gvn.type(vt_addr)->is_ptr(), ideal.ConI(0), TypeInt::BOOL, T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
3550     ideal.sync_kit(this);
3551   } ideal.end_if();
3552 
3553   final_sync(ideal);
3554   return true;
3555 }
3556 
3557 #if INCLUDE_JVMTI
3558 
3559 // Always update the is_disable_suspend bit.
3560 bool LibraryCallKit::inline_native_notify_jvmti_sync() {
3561   if (!DoJVMTIVirtualThreadTransitions) {
3562     return true;
3563   }
3564   IdealKit ideal(this);
3565 
3566   {
3567     // unconditionally update the is_disable_suspend bit in current JavaThread
3568     Node* thread = ideal.thread();
3569     Node* arg = _gvn.transform(argument(0)); // argument for notification
3570     Node* addr = basic_plus_adr(thread, in_bytes(JavaThread::is_disable_suspend_offset()));
3571     const TypePtr *addr_type = _gvn.type(addr)->isa_ptr();
3572 
3573     sync_kit(ideal);
3574     access_store_at(nullptr, addr, addr_type, arg, _gvn.type(arg), T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
3575     ideal.sync_kit(this);
3576   }
3577   final_sync(ideal);
3578 
3579   return true;
3580 }
3581 
3582 #endif // INCLUDE_JVMTI
3583 
3584 #ifdef JFR_HAVE_INTRINSICS
3585 
3586 /**
3587  * if oop->klass != null
3588  *   // normal class
3589  *   epoch = _epoch_state ? 2 : 1
3590  *   if oop->klass->trace_id & ((epoch << META_SHIFT) | epoch)) != epoch {
3591  *     ... // enter slow path when the klass is first recorded or the epoch of JFR shifts
3592  *   }
3593  *   id = oop->klass->trace_id >> TRACE_ID_SHIFT // normal class path
3594  * else
3595  *   // primitive class
3596  *   if oop->array_klass != null
3597  *     id = (oop->array_klass->trace_id >> TRACE_ID_SHIFT) + 1 // primitive class path
3598  *   else
3599  *     id = LAST_TYPE_ID + 1 // void class path
3600  *   if (!signaled)
3601  *     signaled = true
3602  */
3603 bool LibraryCallKit::inline_native_classID() {
3604   Node* cls = argument(0);
3605 
3606   IdealKit ideal(this);
3607 #define __ ideal.
3608   IdealVariable result(ideal); __ declarations_done();
3609   Node* kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(),
3610                                                  basic_plus_adr(cls, java_lang_Class::klass_offset()),
3611                                                  TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
3612 
3613 
3614   __ if_then(kls, BoolTest::ne, null()); {
3615     Node* kls_trace_id_addr = basic_plus_adr(kls, in_bytes(KLASS_TRACE_ID_OFFSET));
3616     Node* kls_trace_id_raw = ideal.load(ideal.ctrl(), kls_trace_id_addr,TypeLong::LONG, T_LONG, Compile::AliasIdxRaw);
3617 
3618     Node* epoch_address = makecon(TypeRawPtr::make(JfrIntrinsicSupport::epoch_address()));
3619     Node* epoch = ideal.load(ideal.ctrl(), epoch_address, TypeInt::BOOL, T_BOOLEAN, Compile::AliasIdxRaw);
3620     epoch = _gvn.transform(new LShiftLNode(longcon(1), epoch));
3621     Node* mask = _gvn.transform(new LShiftLNode(epoch, intcon(META_SHIFT)));
3622     mask = _gvn.transform(new OrLNode(mask, epoch));
3623     Node* kls_trace_id_raw_and_mask = _gvn.transform(new AndLNode(kls_trace_id_raw, mask));
3624 
3625     float unlikely  = PROB_UNLIKELY(0.999);
3626     __ if_then(kls_trace_id_raw_and_mask, BoolTest::ne, epoch, unlikely); {
3627       sync_kit(ideal);
3628       make_runtime_call(RC_LEAF,
3629                         OptoRuntime::class_id_load_barrier_Type(),
3630                         CAST_FROM_FN_PTR(address, JfrIntrinsicSupport::load_barrier),
3631                         "class id load barrier",
3632                         TypePtr::BOTTOM,
3633                         kls);
3634       ideal.sync_kit(this);
3635     } __ end_if();
3636 
3637     ideal.set(result,  _gvn.transform(new URShiftLNode(kls_trace_id_raw, ideal.ConI(TRACE_ID_SHIFT))));
3638   } __ else_(); {
3639     Node* array_kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(),
3640                                                    basic_plus_adr(cls, java_lang_Class::array_klass_offset()),
3641                                                    TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
3642     __ if_then(array_kls, BoolTest::ne, null()); {
3643       Node* array_kls_trace_id_addr = basic_plus_adr(array_kls, in_bytes(KLASS_TRACE_ID_OFFSET));
3644       Node* array_kls_trace_id_raw = ideal.load(ideal.ctrl(), array_kls_trace_id_addr, TypeLong::LONG, T_LONG, Compile::AliasIdxRaw);
3645       Node* array_kls_trace_id = _gvn.transform(new URShiftLNode(array_kls_trace_id_raw, ideal.ConI(TRACE_ID_SHIFT)));
3646       ideal.set(result, _gvn.transform(new AddLNode(array_kls_trace_id, longcon(1))));
3647     } __ else_(); {
3648       // void class case
3649       ideal.set(result, _gvn.transform(longcon(LAST_TYPE_ID + 1)));
3650     } __ end_if();
3651 
3652     Node* signaled_flag_address = makecon(TypeRawPtr::make(JfrIntrinsicSupport::signal_address()));
3653     Node* signaled = ideal.load(ideal.ctrl(), signaled_flag_address, TypeInt::BOOL, T_BOOLEAN, Compile::AliasIdxRaw, true, MemNode::acquire);
3654     __ if_then(signaled, BoolTest::ne, ideal.ConI(1)); {
3655       ideal.store(ideal.ctrl(), signaled_flag_address, ideal.ConI(1), T_BOOLEAN, Compile::AliasIdxRaw, MemNode::release, true);
3656     } __ end_if();
3657   } __ end_if();
3658 
3659   final_sync(ideal);
3660   set_result(ideal.value(result));
3661 #undef __
3662   return true;
3663 }
3664 
3665 //------------------------inline_native_jvm_commit------------------
3666 bool LibraryCallKit::inline_native_jvm_commit() {
3667   enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
3668 
3669   // Save input memory and i_o state.
3670   Node* input_memory_state = reset_memory();
3671   set_all_memory(input_memory_state);
3672   Node* input_io_state = i_o();
3673 
3674   // TLS.
3675   Node* tls_ptr = _gvn.transform(new ThreadLocalNode());
3676   // Jfr java buffer.
3677   Node* java_buffer_offset = _gvn.transform(new AddPNode(top(), tls_ptr, _gvn.transform(MakeConX(in_bytes(JAVA_BUFFER_OFFSET_JFR)))));
3678   Node* java_buffer = _gvn.transform(new LoadPNode(control(), input_memory_state, java_buffer_offset, TypePtr::BOTTOM, TypeRawPtr::NOTNULL, MemNode::unordered));
3679   Node* java_buffer_pos_offset = _gvn.transform(new AddPNode(top(), java_buffer, _gvn.transform(MakeConX(in_bytes(JFR_BUFFER_POS_OFFSET)))));
3680 
3681   // Load the current value of the notified field in the JfrThreadLocal.
3682   Node* notified_offset = basic_plus_adr(top(), tls_ptr, in_bytes(NOTIFY_OFFSET_JFR));
3683   Node* notified = make_load(control(), notified_offset, TypeInt::BOOL, T_BOOLEAN, MemNode::unordered);
3684 
3685   // Test for notification.
3686   Node* notified_cmp = _gvn.transform(new CmpINode(notified, _gvn.intcon(1)));
3687   Node* test_notified = _gvn.transform(new BoolNode(notified_cmp, BoolTest::eq));
3688   IfNode* iff_notified = create_and_map_if(control(), test_notified, PROB_MIN, COUNT_UNKNOWN);
3689 
3690   // True branch, is notified.
3691   Node* is_notified = _gvn.transform(new IfTrueNode(iff_notified));
3692   set_control(is_notified);
3693 
3694   // Reset notified state.
3695   store_to_memory(control(), notified_offset, _gvn.intcon(0), T_BOOLEAN, MemNode::unordered);
3696   Node* notified_reset_memory = reset_memory();
3697 
3698   // 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.
3699   Node* current_pos_X = _gvn.transform(new LoadXNode(control(), input_memory_state, java_buffer_pos_offset, TypeRawPtr::NOTNULL, TypeX_X, MemNode::unordered));
3700   // Convert the machine-word to a long.
3701   Node* current_pos = _gvn.transform(ConvX2L(current_pos_X));
3702 
3703   // False branch, not notified.
3704   Node* not_notified = _gvn.transform(new IfFalseNode(iff_notified));
3705   set_control(not_notified);
3706   set_all_memory(input_memory_state);
3707 
3708   // Arg is the next position as a long.
3709   Node* arg = argument(0);
3710   // Convert long to machine-word.
3711   Node* next_pos_X = _gvn.transform(ConvL2X(arg));
3712 
3713   // Store the next_position to the underlying jfr java buffer.
3714   store_to_memory(control(), java_buffer_pos_offset, next_pos_X, LP64_ONLY(T_LONG) NOT_LP64(T_INT), MemNode::release);
3715 
3716   Node* commit_memory = reset_memory();
3717   set_all_memory(commit_memory);
3718 
3719   // 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.
3720   Node* java_buffer_flags_offset = _gvn.transform(new AddPNode(top(), java_buffer, _gvn.transform(MakeConX(in_bytes(JFR_BUFFER_FLAGS_OFFSET)))));
3721   Node* flags = make_load(control(), java_buffer_flags_offset, TypeInt::UBYTE, T_BYTE, MemNode::unordered);
3722   Node* lease_constant = _gvn.transform(_gvn.intcon(4));
3723 
3724   // And flags with lease constant.
3725   Node* lease = _gvn.transform(new AndINode(flags, lease_constant));
3726 
3727   // Branch on lease to conditionalize returning the leased java buffer.
3728   Node* lease_cmp = _gvn.transform(new CmpINode(lease, lease_constant));
3729   Node* test_lease = _gvn.transform(new BoolNode(lease_cmp, BoolTest::eq));
3730   IfNode* iff_lease = create_and_map_if(control(), test_lease, PROB_MIN, COUNT_UNKNOWN);
3731 
3732   // False branch, not a lease.
3733   Node* not_lease = _gvn.transform(new IfFalseNode(iff_lease));
3734 
3735   // True branch, is lease.
3736   Node* is_lease = _gvn.transform(new IfTrueNode(iff_lease));
3737   set_control(is_lease);
3738 
3739   // Make a runtime call, which can safepoint, to return the leased buffer. This updates both the JfrThreadLocal and the Java event writer oop.
3740   Node* call_return_lease = make_runtime_call(RC_NO_LEAF,
3741                                               OptoRuntime::void_void_Type(),
3742                                               SharedRuntime::jfr_return_lease(),
3743                                               "return_lease", TypePtr::BOTTOM);
3744   Node* call_return_lease_control = _gvn.transform(new ProjNode(call_return_lease, TypeFunc::Control));
3745 
3746   RegionNode* lease_compare_rgn = new RegionNode(PATH_LIMIT);
3747   record_for_igvn(lease_compare_rgn);
3748   PhiNode* lease_compare_mem = new PhiNode(lease_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3749   record_for_igvn(lease_compare_mem);
3750   PhiNode* lease_compare_io = new PhiNode(lease_compare_rgn, Type::ABIO);
3751   record_for_igvn(lease_compare_io);
3752   PhiNode* lease_result_value = new PhiNode(lease_compare_rgn, TypeLong::LONG);
3753   record_for_igvn(lease_result_value);
3754 
3755   // Update control and phi nodes.
3756   lease_compare_rgn->init_req(_true_path, call_return_lease_control);
3757   lease_compare_rgn->init_req(_false_path, not_lease);
3758 
3759   lease_compare_mem->init_req(_true_path, _gvn.transform(reset_memory()));
3760   lease_compare_mem->init_req(_false_path, commit_memory);
3761 
3762   lease_compare_io->init_req(_true_path, i_o());
3763   lease_compare_io->init_req(_false_path, input_io_state);
3764 
3765   lease_result_value->init_req(_true_path, _gvn.longcon(0)); // if the lease was returned, return 0L.
3766   lease_result_value->init_req(_false_path, arg); // if not lease, return new updated position.
3767 
3768   RegionNode* result_rgn = new RegionNode(PATH_LIMIT);
3769   PhiNode* result_mem = new PhiNode(result_rgn, Type::MEMORY, TypePtr::BOTTOM);
3770   PhiNode* result_io = new PhiNode(result_rgn, Type::ABIO);
3771   PhiNode* result_value = new PhiNode(result_rgn, TypeLong::LONG);
3772 
3773   // Update control and phi nodes.
3774   result_rgn->init_req(_true_path, is_notified);
3775   result_rgn->init_req(_false_path, _gvn.transform(lease_compare_rgn));
3776 
3777   result_mem->init_req(_true_path, notified_reset_memory);
3778   result_mem->init_req(_false_path, _gvn.transform(lease_compare_mem));
3779 
3780   result_io->init_req(_true_path, input_io_state);
3781   result_io->init_req(_false_path, _gvn.transform(lease_compare_io));
3782 
3783   result_value->init_req(_true_path, current_pos);
3784   result_value->init_req(_false_path, _gvn.transform(lease_result_value));
3785 
3786   // Set output state.
3787   set_control(_gvn.transform(result_rgn));
3788   set_all_memory(_gvn.transform(result_mem));
3789   set_i_o(_gvn.transform(result_io));
3790   set_result(result_rgn, result_value);
3791   return true;
3792 }
3793 
3794 /*
3795  * The intrinsic is a model of this pseudo-code:
3796  *
3797  * JfrThreadLocal* const tl = Thread::jfr_thread_local()
3798  * jobject h_event_writer = tl->java_event_writer();
3799  * if (h_event_writer == nullptr) {
3800  *   return nullptr;
3801  * }
3802  * oop threadObj = Thread::threadObj();
3803  * oop vthread = java_lang_Thread::vthread(threadObj);
3804  * traceid tid;
3805  * bool pinVirtualThread;
3806  * bool excluded;
3807  * if (vthread != threadObj) {  // i.e. current thread is virtual
3808  *   tid = java_lang_Thread::tid(vthread);
3809  *   u2 vthread_epoch_raw = java_lang_Thread::jfr_epoch(vthread);
3810  *   pinVirtualThread = VMContinuations;
3811  *   excluded = vthread_epoch_raw & excluded_mask;
3812  *   if (!excluded) {
3813  *     traceid current_epoch = JfrTraceIdEpoch::current_generation();
3814  *     u2 vthread_epoch = vthread_epoch_raw & epoch_mask;
3815  *     if (vthread_epoch != current_epoch) {
3816  *       write_checkpoint();
3817  *     }
3818  *   }
3819  * } else {
3820  *   tid = java_lang_Thread::tid(threadObj);
3821  *   u2 thread_epoch_raw = java_lang_Thread::jfr_epoch(threadObj);
3822  *   pinVirtualThread = false;
3823  *   excluded = thread_epoch_raw & excluded_mask;
3824  * }
3825  * oop event_writer = JNIHandles::resolve_non_null(h_event_writer);
3826  * traceid tid_in_event_writer = getField(event_writer, "threadID");
3827  * if (tid_in_event_writer != tid) {
3828  *   setField(event_writer, "pinVirtualThread", pinVirtualThread);
3829  *   setField(event_writer, "excluded", excluded);
3830  *   setField(event_writer, "threadID", tid);
3831  * }
3832  * return event_writer
3833  */
3834 bool LibraryCallKit::inline_native_getEventWriter() {
3835   enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
3836 
3837   // Save input memory and i_o state.
3838   Node* input_memory_state = reset_memory();
3839   set_all_memory(input_memory_state);
3840   Node* input_io_state = i_o();
3841 
3842   // The most significant bit of the u2 is used to denote thread exclusion
3843   Node* excluded_shift = _gvn.intcon(15);
3844   Node* excluded_mask = _gvn.intcon(1 << 15);
3845   // The epoch generation is the range [1-32767]
3846   Node* epoch_mask = _gvn.intcon(32767);
3847 
3848   // TLS
3849   Node* tls_ptr = _gvn.transform(new ThreadLocalNode());
3850 
3851   // Load the address of java event writer jobject handle from the jfr_thread_local structure.
3852   Node* jobj_ptr = basic_plus_adr(top(), tls_ptr, in_bytes(THREAD_LOCAL_WRITER_OFFSET_JFR));
3853 
3854   // Load the eventwriter jobject handle.
3855   Node* jobj = make_load(control(), jobj_ptr, TypeRawPtr::BOTTOM, T_ADDRESS, MemNode::unordered);
3856 
3857   // Null check the jobject handle.
3858   Node* jobj_cmp_null = _gvn.transform(new CmpPNode(jobj, null()));
3859   Node* test_jobj_not_equal_null = _gvn.transform(new BoolNode(jobj_cmp_null, BoolTest::ne));
3860   IfNode* iff_jobj_not_equal_null = create_and_map_if(control(), test_jobj_not_equal_null, PROB_MAX, COUNT_UNKNOWN);
3861 
3862   // False path, jobj is null.
3863   Node* jobj_is_null = _gvn.transform(new IfFalseNode(iff_jobj_not_equal_null));
3864 
3865   // True path, jobj is not null.
3866   Node* jobj_is_not_null = _gvn.transform(new IfTrueNode(iff_jobj_not_equal_null));
3867 
3868   set_control(jobj_is_not_null);
3869 
3870   // Load the threadObj for the CarrierThread.
3871   Node* threadObj = generate_current_thread(tls_ptr);
3872 
3873   // Load the vthread.
3874   Node* vthread = generate_virtual_thread(tls_ptr);
3875 
3876   // If vthread != threadObj, this is a virtual thread.
3877   Node* vthread_cmp_threadObj = _gvn.transform(new CmpPNode(vthread, threadObj));
3878   Node* test_vthread_not_equal_threadObj = _gvn.transform(new BoolNode(vthread_cmp_threadObj, BoolTest::ne));
3879   IfNode* iff_vthread_not_equal_threadObj =
3880     create_and_map_if(jobj_is_not_null, test_vthread_not_equal_threadObj, PROB_FAIR, COUNT_UNKNOWN);
3881 
3882   // False branch, fallback to threadObj.
3883   Node* vthread_equal_threadObj = _gvn.transform(new IfFalseNode(iff_vthread_not_equal_threadObj));
3884   set_control(vthread_equal_threadObj);
3885 
3886   // Load the tid field from the vthread object.
3887   Node* thread_obj_tid = load_field_from_object(threadObj, "tid", "J");
3888 
3889   // Load the raw epoch value from the threadObj.
3890   Node* threadObj_epoch_offset = basic_plus_adr(threadObj, java_lang_Thread::jfr_epoch_offset());
3891   Node* threadObj_epoch_raw = access_load_at(threadObj, threadObj_epoch_offset,
3892                                              _gvn.type(threadObj_epoch_offset)->isa_ptr(),
3893                                              TypeInt::CHAR, T_CHAR,
3894                                              IN_HEAP | MO_UNORDERED | C2_MISMATCHED | C2_CONTROL_DEPENDENT_LOAD);
3895 
3896   // Mask off the excluded information from the epoch.
3897   Node * threadObj_is_excluded = _gvn.transform(new AndINode(threadObj_epoch_raw, excluded_mask));
3898 
3899   // True branch, this is a virtual thread.
3900   Node* vthread_not_equal_threadObj = _gvn.transform(new IfTrueNode(iff_vthread_not_equal_threadObj));
3901   set_control(vthread_not_equal_threadObj);
3902 
3903   // Load the tid field from the vthread object.
3904   Node* vthread_tid = load_field_from_object(vthread, "tid", "J");
3905 
3906   // Continuation support determines if a virtual thread should be pinned.
3907   Node* global_addr = makecon(TypeRawPtr::make((address)&VMContinuations));
3908   Node* continuation_support = make_load(control(), global_addr, TypeInt::BOOL, T_BOOLEAN, MemNode::unordered);
3909 
3910   // Load the raw epoch value from the vthread.
3911   Node* vthread_epoch_offset = basic_plus_adr(vthread, java_lang_Thread::jfr_epoch_offset());
3912   Node* vthread_epoch_raw = access_load_at(vthread, vthread_epoch_offset, _gvn.type(vthread_epoch_offset)->is_ptr(),
3913                                            TypeInt::CHAR, T_CHAR,
3914                                            IN_HEAP | MO_UNORDERED | C2_MISMATCHED | C2_CONTROL_DEPENDENT_LOAD);
3915 
3916   // Mask off the excluded information from the epoch.
3917   Node * vthread_is_excluded = _gvn.transform(new AndINode(vthread_epoch_raw, _gvn.transform(excluded_mask)));
3918 
3919   // Branch on excluded to conditionalize updating the epoch for the virtual thread.
3920   Node* is_excluded_cmp = _gvn.transform(new CmpINode(vthread_is_excluded, _gvn.transform(excluded_mask)));
3921   Node* test_not_excluded = _gvn.transform(new BoolNode(is_excluded_cmp, BoolTest::ne));
3922   IfNode* iff_not_excluded = create_and_map_if(control(), test_not_excluded, PROB_MAX, COUNT_UNKNOWN);
3923 
3924   // False branch, vthread is excluded, no need to write epoch info.
3925   Node* excluded = _gvn.transform(new IfFalseNode(iff_not_excluded));
3926 
3927   // True branch, vthread is included, update epoch info.
3928   Node* included = _gvn.transform(new IfTrueNode(iff_not_excluded));
3929   set_control(included);
3930 
3931   // Get epoch value.
3932   Node* epoch = _gvn.transform(new AndINode(vthread_epoch_raw, _gvn.transform(epoch_mask)));
3933 
3934   // Load the current epoch generation. The value is unsigned 16-bit, so we type it as T_CHAR.
3935   Node* epoch_generation_address = makecon(TypeRawPtr::make(JfrIntrinsicSupport::epoch_generation_address()));
3936   Node* current_epoch_generation = make_load(control(), epoch_generation_address, TypeInt::CHAR, T_CHAR, MemNode::unordered);
3937 
3938   // Compare the epoch in the vthread to the current epoch generation.
3939   Node* const epoch_cmp = _gvn.transform(new CmpUNode(current_epoch_generation, epoch));
3940   Node* test_epoch_not_equal = _gvn.transform(new BoolNode(epoch_cmp, BoolTest::ne));
3941   IfNode* iff_epoch_not_equal = create_and_map_if(control(), test_epoch_not_equal, PROB_FAIR, COUNT_UNKNOWN);
3942 
3943   // False path, epoch is equal, checkpoint information is valid.
3944   Node* epoch_is_equal = _gvn.transform(new IfFalseNode(iff_epoch_not_equal));
3945 
3946   // True path, epoch is not equal, write a checkpoint for the vthread.
3947   Node* epoch_is_not_equal = _gvn.transform(new IfTrueNode(iff_epoch_not_equal));
3948 
3949   set_control(epoch_is_not_equal);
3950 
3951   // Make a runtime call, which can safepoint, to write a checkpoint for the vthread for this epoch.
3952   // The call also updates the native thread local thread id and the vthread with the current epoch.
3953   Node* call_write_checkpoint = make_runtime_call(RC_NO_LEAF,
3954                                                   OptoRuntime::jfr_write_checkpoint_Type(),
3955                                                   SharedRuntime::jfr_write_checkpoint(),
3956                                                   "write_checkpoint", TypePtr::BOTTOM);
3957   Node* call_write_checkpoint_control = _gvn.transform(new ProjNode(call_write_checkpoint, TypeFunc::Control));
3958 
3959   // vthread epoch != current epoch
3960   RegionNode* epoch_compare_rgn = new RegionNode(PATH_LIMIT);
3961   record_for_igvn(epoch_compare_rgn);
3962   PhiNode* epoch_compare_mem = new PhiNode(epoch_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3963   record_for_igvn(epoch_compare_mem);
3964   PhiNode* epoch_compare_io = new PhiNode(epoch_compare_rgn, Type::ABIO);
3965   record_for_igvn(epoch_compare_io);
3966 
3967   // Update control and phi nodes.
3968   epoch_compare_rgn->init_req(_true_path, call_write_checkpoint_control);
3969   epoch_compare_rgn->init_req(_false_path, epoch_is_equal);
3970   epoch_compare_mem->init_req(_true_path, _gvn.transform(reset_memory()));
3971   epoch_compare_mem->init_req(_false_path, input_memory_state);
3972   epoch_compare_io->init_req(_true_path, i_o());
3973   epoch_compare_io->init_req(_false_path, input_io_state);
3974 
3975   // excluded != true
3976   RegionNode* exclude_compare_rgn = new RegionNode(PATH_LIMIT);
3977   record_for_igvn(exclude_compare_rgn);
3978   PhiNode* exclude_compare_mem = new PhiNode(exclude_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3979   record_for_igvn(exclude_compare_mem);
3980   PhiNode* exclude_compare_io = new PhiNode(exclude_compare_rgn, Type::ABIO);
3981   record_for_igvn(exclude_compare_io);
3982 
3983   // Update control and phi nodes.
3984   exclude_compare_rgn->init_req(_true_path, _gvn.transform(epoch_compare_rgn));
3985   exclude_compare_rgn->init_req(_false_path, excluded);
3986   exclude_compare_mem->init_req(_true_path, _gvn.transform(epoch_compare_mem));
3987   exclude_compare_mem->init_req(_false_path, input_memory_state);
3988   exclude_compare_io->init_req(_true_path, _gvn.transform(epoch_compare_io));
3989   exclude_compare_io->init_req(_false_path, input_io_state);
3990 
3991   // vthread != threadObj
3992   RegionNode* vthread_compare_rgn = new RegionNode(PATH_LIMIT);
3993   record_for_igvn(vthread_compare_rgn);
3994   PhiNode* vthread_compare_mem = new PhiNode(vthread_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3995   PhiNode* vthread_compare_io = new PhiNode(vthread_compare_rgn, Type::ABIO);
3996   record_for_igvn(vthread_compare_io);
3997   PhiNode* tid = new PhiNode(vthread_compare_rgn, TypeLong::LONG);
3998   record_for_igvn(tid);
3999   PhiNode* exclusion = new PhiNode(vthread_compare_rgn, TypeInt::CHAR);
4000   record_for_igvn(exclusion);
4001   PhiNode* pinVirtualThread = new PhiNode(vthread_compare_rgn, TypeInt::BOOL);
4002   record_for_igvn(pinVirtualThread);
4003 
4004   // Update control and phi nodes.
4005   vthread_compare_rgn->init_req(_true_path, _gvn.transform(exclude_compare_rgn));
4006   vthread_compare_rgn->init_req(_false_path, vthread_equal_threadObj);
4007   vthread_compare_mem->init_req(_true_path, _gvn.transform(exclude_compare_mem));
4008   vthread_compare_mem->init_req(_false_path, input_memory_state);
4009   vthread_compare_io->init_req(_true_path, _gvn.transform(exclude_compare_io));
4010   vthread_compare_io->init_req(_false_path, input_io_state);
4011   tid->init_req(_true_path, _gvn.transform(vthread_tid));
4012   tid->init_req(_false_path, _gvn.transform(thread_obj_tid));
4013   exclusion->init_req(_true_path, _gvn.transform(vthread_is_excluded));
4014   exclusion->init_req(_false_path, _gvn.transform(threadObj_is_excluded));
4015   pinVirtualThread->init_req(_true_path, _gvn.transform(continuation_support));
4016   pinVirtualThread->init_req(_false_path, _gvn.intcon(0));
4017 
4018   // Update branch state.
4019   set_control(_gvn.transform(vthread_compare_rgn));
4020   set_all_memory(_gvn.transform(vthread_compare_mem));
4021   set_i_o(_gvn.transform(vthread_compare_io));
4022 
4023   // Load the event writer oop by dereferencing the jobject handle.
4024   ciKlass* klass_EventWriter = env()->find_system_klass(ciSymbol::make("jdk/jfr/internal/event/EventWriter"));
4025   assert(klass_EventWriter->is_loaded(), "invariant");
4026   ciInstanceKlass* const instklass_EventWriter = klass_EventWriter->as_instance_klass();
4027   const TypeKlassPtr* const aklass = TypeKlassPtr::make(instklass_EventWriter);
4028   const TypeOopPtr* const xtype = aklass->as_instance_type();
4029   Node* jobj_untagged = _gvn.transform(new AddPNode(top(), jobj, _gvn.MakeConX(-JNIHandles::TypeTag::global)));
4030   Node* event_writer = access_load(jobj_untagged, xtype, T_OBJECT, IN_NATIVE | C2_CONTROL_DEPENDENT_LOAD);
4031 
4032   // Load the current thread id from the event writer object.
4033   Node* const event_writer_tid = load_field_from_object(event_writer, "threadID", "J");
4034   // Get the field offset to, conditionally, store an updated tid value later.
4035   Node* const event_writer_tid_field = field_address_from_object(event_writer, "threadID", "J", false);
4036   // Get the field offset to, conditionally, store an updated exclusion value later.
4037   Node* const event_writer_excluded_field = field_address_from_object(event_writer, "excluded", "Z", false);
4038   // Get the field offset to, conditionally, store an updated pinVirtualThread value later.
4039   Node* const event_writer_pin_field = field_address_from_object(event_writer, "pinVirtualThread", "Z", false);
4040 
4041   RegionNode* event_writer_tid_compare_rgn = new RegionNode(PATH_LIMIT);
4042   record_for_igvn(event_writer_tid_compare_rgn);
4043   PhiNode* event_writer_tid_compare_mem = new PhiNode(event_writer_tid_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
4044   record_for_igvn(event_writer_tid_compare_mem);
4045   PhiNode* event_writer_tid_compare_io = new PhiNode(event_writer_tid_compare_rgn, Type::ABIO);
4046   record_for_igvn(event_writer_tid_compare_io);
4047 
4048   // Compare the current tid from the thread object to what is currently stored in the event writer object.
4049   Node* const tid_cmp = _gvn.transform(new CmpLNode(event_writer_tid, _gvn.transform(tid)));
4050   Node* test_tid_not_equal = _gvn.transform(new BoolNode(tid_cmp, BoolTest::ne));
4051   IfNode* iff_tid_not_equal = create_and_map_if(_gvn.transform(vthread_compare_rgn), test_tid_not_equal, PROB_FAIR, COUNT_UNKNOWN);
4052 
4053   // False path, tids are the same.
4054   Node* tid_is_equal = _gvn.transform(new IfFalseNode(iff_tid_not_equal));
4055 
4056   // True path, tid is not equal, need to update the tid in the event writer.
4057   Node* tid_is_not_equal = _gvn.transform(new IfTrueNode(iff_tid_not_equal));
4058   record_for_igvn(tid_is_not_equal);
4059 
4060   // Store the pin state to the event writer.
4061   store_to_memory(tid_is_not_equal, event_writer_pin_field, _gvn.transform(pinVirtualThread), T_BOOLEAN, MemNode::unordered);
4062 
4063   // Store the exclusion state to the event writer.
4064   Node* excluded_bool = _gvn.transform(new URShiftINode(_gvn.transform(exclusion), excluded_shift));
4065   store_to_memory(tid_is_not_equal, event_writer_excluded_field, excluded_bool, T_BOOLEAN, MemNode::unordered);
4066 
4067   // Store the tid to the event writer.
4068   store_to_memory(tid_is_not_equal, event_writer_tid_field, tid, T_LONG, MemNode::unordered);
4069 
4070   // Update control and phi nodes.
4071   event_writer_tid_compare_rgn->init_req(_true_path, tid_is_not_equal);
4072   event_writer_tid_compare_rgn->init_req(_false_path, tid_is_equal);
4073   event_writer_tid_compare_mem->init_req(_true_path, _gvn.transform(reset_memory()));
4074   event_writer_tid_compare_mem->init_req(_false_path, _gvn.transform(vthread_compare_mem));
4075   event_writer_tid_compare_io->init_req(_true_path, _gvn.transform(i_o()));
4076   event_writer_tid_compare_io->init_req(_false_path, _gvn.transform(vthread_compare_io));
4077 
4078   // Result of top level CFG, Memory, IO and Value.
4079   RegionNode* result_rgn = new RegionNode(PATH_LIMIT);
4080   PhiNode* result_mem = new PhiNode(result_rgn, Type::MEMORY, TypePtr::BOTTOM);
4081   PhiNode* result_io = new PhiNode(result_rgn, Type::ABIO);
4082   PhiNode* result_value = new PhiNode(result_rgn, TypeInstPtr::BOTTOM);
4083 
4084   // Result control.
4085   result_rgn->init_req(_true_path, _gvn.transform(event_writer_tid_compare_rgn));
4086   result_rgn->init_req(_false_path, jobj_is_null);
4087 
4088   // Result memory.
4089   result_mem->init_req(_true_path, _gvn.transform(event_writer_tid_compare_mem));
4090   result_mem->init_req(_false_path, _gvn.transform(input_memory_state));
4091 
4092   // Result IO.
4093   result_io->init_req(_true_path, _gvn.transform(event_writer_tid_compare_io));
4094   result_io->init_req(_false_path, _gvn.transform(input_io_state));
4095 
4096   // Result value.
4097   result_value->init_req(_true_path, _gvn.transform(event_writer)); // return event writer oop
4098   result_value->init_req(_false_path, null()); // return null
4099 
4100   // Set output state.
4101   set_control(_gvn.transform(result_rgn));
4102   set_all_memory(_gvn.transform(result_mem));
4103   set_i_o(_gvn.transform(result_io));
4104   set_result(result_rgn, result_value);
4105   return true;
4106 }
4107 
4108 /*
4109  * The intrinsic is a model of this pseudo-code:
4110  *
4111  * JfrThreadLocal* const tl = thread->jfr_thread_local();
4112  * if (carrierThread != thread) { // is virtual thread
4113  *   const u2 vthread_epoch_raw = java_lang_Thread::jfr_epoch(thread);
4114  *   bool excluded = vthread_epoch_raw & excluded_mask;
4115  *   AtomicAccess::store(&tl->_contextual_tid, java_lang_Thread::tid(thread));
4116  *   AtomicAccess::store(&tl->_contextual_thread_excluded, is_excluded);
4117  *   if (!excluded) {
4118  *     const u2 vthread_epoch = vthread_epoch_raw & epoch_mask;
4119  *     AtomicAccess::store(&tl->_vthread_epoch, vthread_epoch);
4120  *   }
4121  *   AtomicAccess::release_store(&tl->_vthread, true);
4122  *   return;
4123  * }
4124  * AtomicAccess::release_store(&tl->_vthread, false);
4125  */
4126 void LibraryCallKit::extend_setCurrentThread(Node* jt, Node* thread) {
4127   enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
4128 
4129   Node* input_memory_state = reset_memory();
4130   set_all_memory(input_memory_state);
4131 
4132   // The most significant bit of the u2 is used to denote thread exclusion
4133   Node* excluded_mask = _gvn.intcon(1 << 15);
4134   // The epoch generation is the range [1-32767]
4135   Node* epoch_mask = _gvn.intcon(32767);
4136 
4137   Node* const carrierThread = generate_current_thread(jt);
4138   // If thread != carrierThread, this is a virtual thread.
4139   Node* thread_cmp_carrierThread = _gvn.transform(new CmpPNode(thread, carrierThread));
4140   Node* test_thread_not_equal_carrierThread = _gvn.transform(new BoolNode(thread_cmp_carrierThread, BoolTest::ne));
4141   IfNode* iff_thread_not_equal_carrierThread =
4142     create_and_map_if(control(), test_thread_not_equal_carrierThread, PROB_FAIR, COUNT_UNKNOWN);
4143 
4144   Node* vthread_offset = basic_plus_adr(jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_OFFSET_JFR));
4145 
4146   // False branch, is carrierThread.
4147   Node* thread_equal_carrierThread = _gvn.transform(new IfFalseNode(iff_thread_not_equal_carrierThread));
4148   // Store release
4149   Node* vthread_false_memory = store_to_memory(thread_equal_carrierThread, vthread_offset, _gvn.intcon(0), T_BOOLEAN, MemNode::release, true);
4150 
4151   set_all_memory(input_memory_state);
4152 
4153   // True branch, is virtual thread.
4154   Node* thread_not_equal_carrierThread = _gvn.transform(new IfTrueNode(iff_thread_not_equal_carrierThread));
4155   set_control(thread_not_equal_carrierThread);
4156 
4157   // Load the raw epoch value from the vthread.
4158   Node* epoch_offset = basic_plus_adr(thread, java_lang_Thread::jfr_epoch_offset());
4159   Node* epoch_raw = access_load_at(thread, epoch_offset, _gvn.type(epoch_offset)->is_ptr(), TypeInt::CHAR, T_CHAR,
4160                                    IN_HEAP | MO_UNORDERED | C2_MISMATCHED | C2_CONTROL_DEPENDENT_LOAD);
4161 
4162   // Mask off the excluded information from the epoch.
4163   Node * const is_excluded = _gvn.transform(new AndINode(epoch_raw, _gvn.transform(excluded_mask)));
4164 
4165   // Load the tid field from the thread.
4166   Node* tid = load_field_from_object(thread, "tid", "J");
4167 
4168   // Store the vthread tid to the jfr thread local.
4169   Node* thread_id_offset = basic_plus_adr(jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_ID_OFFSET_JFR));
4170   Node* tid_memory = store_to_memory(control(), thread_id_offset, tid, T_LONG, MemNode::unordered, true);
4171 
4172   // Branch is_excluded to conditionalize updating the epoch .
4173   Node* excluded_cmp = _gvn.transform(new CmpINode(is_excluded, _gvn.transform(excluded_mask)));
4174   Node* test_excluded = _gvn.transform(new BoolNode(excluded_cmp, BoolTest::eq));
4175   IfNode* iff_excluded = create_and_map_if(control(), test_excluded, PROB_MIN, COUNT_UNKNOWN);
4176 
4177   // True branch, vthread is excluded, no need to write epoch info.
4178   Node* excluded = _gvn.transform(new IfTrueNode(iff_excluded));
4179   set_control(excluded);
4180   Node* vthread_is_excluded = _gvn.intcon(1);
4181 
4182   // False branch, vthread is included, update epoch info.
4183   Node* included = _gvn.transform(new IfFalseNode(iff_excluded));
4184   set_control(included);
4185   Node* vthread_is_included = _gvn.intcon(0);
4186 
4187   // Get epoch value.
4188   Node* epoch = _gvn.transform(new AndINode(epoch_raw, _gvn.transform(epoch_mask)));
4189 
4190   // Store the vthread epoch to the jfr thread local.
4191   Node* vthread_epoch_offset = basic_plus_adr(jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_EPOCH_OFFSET_JFR));
4192   Node* included_memory = store_to_memory(control(), vthread_epoch_offset, epoch, T_CHAR, MemNode::unordered, true);
4193 
4194   RegionNode* excluded_rgn = new RegionNode(PATH_LIMIT);
4195   record_for_igvn(excluded_rgn);
4196   PhiNode* excluded_mem = new PhiNode(excluded_rgn, Type::MEMORY, TypePtr::BOTTOM);
4197   record_for_igvn(excluded_mem);
4198   PhiNode* exclusion = new PhiNode(excluded_rgn, TypeInt::BOOL);
4199   record_for_igvn(exclusion);
4200 
4201   // Merge the excluded control and memory.
4202   excluded_rgn->init_req(_true_path, excluded);
4203   excluded_rgn->init_req(_false_path, included);
4204   excluded_mem->init_req(_true_path, tid_memory);
4205   excluded_mem->init_req(_false_path, included_memory);
4206   exclusion->init_req(_true_path, _gvn.transform(vthread_is_excluded));
4207   exclusion->init_req(_false_path, _gvn.transform(vthread_is_included));
4208 
4209   // Set intermediate state.
4210   set_control(_gvn.transform(excluded_rgn));
4211   set_all_memory(excluded_mem);
4212 
4213   // Store the vthread exclusion state to the jfr thread local.
4214   Node* thread_local_excluded_offset = basic_plus_adr(jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_EXCLUDED_OFFSET_JFR));
4215   store_to_memory(control(), thread_local_excluded_offset, _gvn.transform(exclusion), T_BOOLEAN, MemNode::unordered, true);
4216 
4217   // Store release
4218   Node * vthread_true_memory = store_to_memory(control(), vthread_offset, _gvn.intcon(1), T_BOOLEAN, MemNode::release, true);
4219 
4220   RegionNode* thread_compare_rgn = new RegionNode(PATH_LIMIT);
4221   record_for_igvn(thread_compare_rgn);
4222   PhiNode* thread_compare_mem = new PhiNode(thread_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
4223   record_for_igvn(thread_compare_mem);
4224   PhiNode* vthread = new PhiNode(thread_compare_rgn, TypeInt::BOOL);
4225   record_for_igvn(vthread);
4226 
4227   // Merge the thread_compare control and memory.
4228   thread_compare_rgn->init_req(_true_path, control());
4229   thread_compare_rgn->init_req(_false_path, thread_equal_carrierThread);
4230   thread_compare_mem->init_req(_true_path, vthread_true_memory);
4231   thread_compare_mem->init_req(_false_path, vthread_false_memory);
4232 
4233   // Set output state.
4234   set_control(_gvn.transform(thread_compare_rgn));
4235   set_all_memory(_gvn.transform(thread_compare_mem));
4236 }
4237 
4238 #endif // JFR_HAVE_INTRINSICS
4239 
4240 //------------------------inline_native_currentCarrierThread------------------
4241 bool LibraryCallKit::inline_native_currentCarrierThread() {
4242   Node* junk = nullptr;
4243   set_result(generate_current_thread(junk));
4244   return true;
4245 }
4246 
4247 //------------------------inline_native_currentThread------------------
4248 bool LibraryCallKit::inline_native_currentThread() {
4249   Node* junk = nullptr;
4250   set_result(generate_virtual_thread(junk));
4251   return true;
4252 }
4253 
4254 //------------------------inline_native_setVthread------------------
4255 bool LibraryCallKit::inline_native_setCurrentThread() {
4256   assert(C->method()->changes_current_thread(),
4257          "method changes current Thread but is not annotated ChangesCurrentThread");
4258   Node* arr = argument(1);
4259   Node* thread = _gvn.transform(new ThreadLocalNode());
4260   Node* p = basic_plus_adr(top()/*!oop*/, thread, in_bytes(JavaThread::vthread_offset()));
4261   Node* thread_obj_handle
4262     = make_load(nullptr, p, p->bottom_type()->is_ptr(), T_OBJECT, MemNode::unordered);
4263   thread_obj_handle = _gvn.transform(thread_obj_handle);
4264   const TypePtr *adr_type = _gvn.type(thread_obj_handle)->isa_ptr();
4265   access_store_at(nullptr, thread_obj_handle, adr_type, arr, _gvn.type(arr), T_OBJECT, IN_NATIVE | MO_UNORDERED);
4266 
4267   // Change the _monitor_owner_id of the JavaThread
4268   Node* tid = load_field_from_object(arr, "tid", "J");
4269   Node* monitor_owner_id_offset = basic_plus_adr(thread, in_bytes(JavaThread::monitor_owner_id_offset()));
4270   store_to_memory(control(), monitor_owner_id_offset, tid, T_LONG, MemNode::unordered, true);
4271 
4272   JFR_ONLY(extend_setCurrentThread(thread, arr);)
4273   return true;
4274 }
4275 
4276 const Type* LibraryCallKit::scopedValueCache_type() {
4277   ciKlass* objects_klass = ciObjArrayKlass::make(env()->Object_klass());
4278   const TypeOopPtr* etype = TypeOopPtr::make_from_klass(env()->Object_klass());
4279   const TypeAry* arr0 = TypeAry::make(etype, TypeInt::POS, /* stable= */ false, /* flat= */ false, /* not_flat= */ true, /* not_null_free= */ true, true);
4280 
4281   // Because we create the scopedValue cache lazily we have to make the
4282   // type of the result BotPTR.
4283   bool xk = etype->klass_is_exact();
4284   const Type* objects_type = TypeAryPtr::make(TypePtr::BotPTR, arr0, objects_klass, xk, TypeAryPtr::Offset(0));
4285   return objects_type;
4286 }
4287 
4288 Node* LibraryCallKit::scopedValueCache_helper() {
4289   Node* thread = _gvn.transform(new ThreadLocalNode());
4290   Node* p = basic_plus_adr(top()/*!oop*/, thread, in_bytes(JavaThread::scopedValueCache_offset()));
4291   // We cannot use immutable_memory() because we might flip onto a
4292   // different carrier thread, at which point we'll need to use that
4293   // carrier thread's cache.
4294   // return _gvn.transform(LoadNode::make(_gvn, nullptr, immutable_memory(), p, p->bottom_type()->is_ptr(),
4295   //       TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered));
4296   return make_load(nullptr, p, p->bottom_type()->is_ptr(), T_ADDRESS, MemNode::unordered);
4297 }
4298 
4299 //------------------------inline_native_scopedValueCache------------------
4300 bool LibraryCallKit::inline_native_scopedValueCache() {
4301   Node* cache_obj_handle = scopedValueCache_helper();
4302   const Type* objects_type = scopedValueCache_type();
4303   set_result(access_load(cache_obj_handle, objects_type, T_OBJECT, IN_NATIVE));
4304 
4305   return true;
4306 }
4307 
4308 //------------------------inline_native_setScopedValueCache------------------
4309 bool LibraryCallKit::inline_native_setScopedValueCache() {
4310   Node* arr = argument(0);
4311   Node* cache_obj_handle = scopedValueCache_helper();
4312   const Type* objects_type = scopedValueCache_type();
4313 
4314   const TypePtr *adr_type = _gvn.type(cache_obj_handle)->isa_ptr();
4315   access_store_at(nullptr, cache_obj_handle, adr_type, arr, objects_type, T_OBJECT, IN_NATIVE | MO_UNORDERED);
4316 
4317   return true;
4318 }
4319 
4320 //------------------------inline_native_Continuation_pin and unpin-----------
4321 
4322 // Shared implementation routine for both pin and unpin.
4323 bool LibraryCallKit::inline_native_Continuation_pinning(bool unpin) {
4324   enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
4325 
4326   // Save input memory.
4327   Node* input_memory_state = reset_memory();
4328   set_all_memory(input_memory_state);
4329 
4330   // TLS
4331   Node* tls_ptr = _gvn.transform(new ThreadLocalNode());
4332   Node* last_continuation_offset = basic_plus_adr(top(), tls_ptr, in_bytes(JavaThread::cont_entry_offset()));
4333   Node* last_continuation = make_load(control(), last_continuation_offset, last_continuation_offset->get_ptr_type(), T_ADDRESS, MemNode::unordered);
4334 
4335   // Null check the last continuation object.
4336   Node* continuation_cmp_null = _gvn.transform(new CmpPNode(last_continuation, null()));
4337   Node* test_continuation_not_equal_null = _gvn.transform(new BoolNode(continuation_cmp_null, BoolTest::ne));
4338   IfNode* iff_continuation_not_equal_null = create_and_map_if(control(), test_continuation_not_equal_null, PROB_MAX, COUNT_UNKNOWN);
4339 
4340   // False path, last continuation is null.
4341   Node* continuation_is_null = _gvn.transform(new IfFalseNode(iff_continuation_not_equal_null));
4342 
4343   // True path, last continuation is not null.
4344   Node* continuation_is_not_null = _gvn.transform(new IfTrueNode(iff_continuation_not_equal_null));
4345 
4346   set_control(continuation_is_not_null);
4347 
4348   // Load the pin count from the last continuation.
4349   Node* pin_count_offset = basic_plus_adr(top(), last_continuation, in_bytes(ContinuationEntry::pin_count_offset()));
4350   Node* pin_count = make_load(control(), pin_count_offset, TypeInt::INT, T_INT, MemNode::unordered);
4351 
4352   // The loaded pin count is compared against a context specific rhs for over/underflow detection.
4353   Node* pin_count_rhs;
4354   if (unpin) {
4355     pin_count_rhs = _gvn.intcon(0);
4356   } else {
4357     pin_count_rhs = _gvn.intcon(UINT32_MAX);
4358   }
4359   Node* pin_count_cmp = _gvn.transform(new CmpUNode(_gvn.transform(pin_count), pin_count_rhs));
4360   Node* test_pin_count_over_underflow = _gvn.transform(new BoolNode(pin_count_cmp, BoolTest::eq));
4361   IfNode* iff_pin_count_over_underflow = create_and_map_if(control(), test_pin_count_over_underflow, PROB_MIN, COUNT_UNKNOWN);
4362 
4363   // True branch, pin count over/underflow.
4364   Node* pin_count_over_underflow = _gvn.transform(new IfTrueNode(iff_pin_count_over_underflow));
4365   {
4366     // Trap (but not deoptimize (Action_none)) and continue in the interpreter
4367     // which will throw IllegalStateException for pin count over/underflow.
4368     // No memory changed so far - we can use memory create by reset_memory()
4369     // at the beginning of this intrinsic. No need to call reset_memory() again.
4370     PreserveJVMState pjvms(this);
4371     set_control(pin_count_over_underflow);
4372     uncommon_trap(Deoptimization::Reason_intrinsic,
4373                   Deoptimization::Action_none);
4374     assert(stopped(), "invariant");
4375   }
4376 
4377   // False branch, no pin count over/underflow. Increment or decrement pin count and store back.
4378   Node* valid_pin_count = _gvn.transform(new IfFalseNode(iff_pin_count_over_underflow));
4379   set_control(valid_pin_count);
4380 
4381   Node* next_pin_count;
4382   if (unpin) {
4383     next_pin_count = _gvn.transform(new SubINode(pin_count, _gvn.intcon(1)));
4384   } else {
4385     next_pin_count = _gvn.transform(new AddINode(pin_count, _gvn.intcon(1)));
4386   }
4387 
4388   store_to_memory(control(), pin_count_offset, next_pin_count, T_INT, MemNode::unordered);
4389 
4390   // Result of top level CFG and Memory.
4391   RegionNode* result_rgn = new RegionNode(PATH_LIMIT);
4392   record_for_igvn(result_rgn);
4393   PhiNode* result_mem = new PhiNode(result_rgn, Type::MEMORY, TypePtr::BOTTOM);
4394   record_for_igvn(result_mem);
4395 
4396   result_rgn->init_req(_true_path, _gvn.transform(valid_pin_count));
4397   result_rgn->init_req(_false_path, _gvn.transform(continuation_is_null));
4398   result_mem->init_req(_true_path, _gvn.transform(reset_memory()));
4399   result_mem->init_req(_false_path, _gvn.transform(input_memory_state));
4400 
4401   // Set output state.
4402   set_control(_gvn.transform(result_rgn));
4403   set_all_memory(_gvn.transform(result_mem));
4404 
4405   return true;
4406 }
4407 
4408 //---------------------------load_mirror_from_klass----------------------------
4409 // Given a klass oop, load its java mirror (a java.lang.Class oop).
4410 Node* LibraryCallKit::load_mirror_from_klass(Node* klass) {
4411   Node* p = basic_plus_adr(klass, in_bytes(Klass::java_mirror_offset()));
4412   Node* load = make_load(nullptr, p, TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered);
4413   // mirror = ((OopHandle)mirror)->resolve();
4414   return access_load(load, TypeInstPtr::MIRROR, T_OBJECT, IN_NATIVE);
4415 }
4416 
4417 //-----------------------load_klass_from_mirror_common-------------------------
4418 // Given a java mirror (a java.lang.Class oop), load its corresponding klass oop.
4419 // Test the klass oop for null (signifying a primitive Class like Integer.TYPE),
4420 // and branch to the given path on the region.
4421 // If never_see_null, take an uncommon trap on null, so we can optimistically
4422 // compile for the non-null case.
4423 // If the region is null, force never_see_null = true.
4424 Node* LibraryCallKit::load_klass_from_mirror_common(Node* mirror,
4425                                                     bool never_see_null,
4426                                                     RegionNode* region,
4427                                                     int null_path,
4428                                                     int offset) {
4429   if (region == nullptr)  never_see_null = true;
4430   Node* p = basic_plus_adr(mirror, offset);
4431   const TypeKlassPtr*  kls_type = TypeInstKlassPtr::OBJECT_OR_NULL;
4432   Node* kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), p, TypeRawPtr::BOTTOM, kls_type));
4433   Node* null_ctl = top();
4434   kls = null_check_oop(kls, &null_ctl, never_see_null);
4435   if (region != nullptr) {
4436     // Set region->in(null_path) if the mirror is a primitive (e.g, int.class).
4437     region->init_req(null_path, null_ctl);
4438   } else {
4439     assert(null_ctl == top(), "no loose ends");
4440   }
4441   return kls;
4442 }
4443 
4444 //--------------------(inline_native_Class_query helpers)---------------------
4445 // Use this for JVM_ACC_INTERFACE.
4446 // Fall through if (mods & mask) == bits, take the guard otherwise.
4447 Node* LibraryCallKit::generate_klass_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region,
4448                                                  ByteSize offset, const Type* type, BasicType bt) {
4449   // Branch around if the given klass has the given modifier bit set.
4450   // Like generate_guard, adds a new path onto the region.
4451   Node* modp = basic_plus_adr(kls, in_bytes(offset));
4452   Node* mods = make_load(nullptr, modp, type, bt, MemNode::unordered);
4453   Node* mask = intcon(modifier_mask);
4454   Node* bits = intcon(modifier_bits);
4455   Node* mbit = _gvn.transform(new AndINode(mods, mask));
4456   Node* cmp  = _gvn.transform(new CmpINode(mbit, bits));
4457   Node* bol  = _gvn.transform(new BoolNode(cmp, BoolTest::ne));
4458   return generate_fair_guard(bol, region);
4459 }
4460 
4461 Node* LibraryCallKit::generate_interface_guard(Node* kls, RegionNode* region) {
4462   return generate_klass_flags_guard(kls, JVM_ACC_INTERFACE, 0, region,
4463                                     InstanceKlass::access_flags_offset(), TypeInt::CHAR, T_CHAR);
4464 }
4465 
4466 // Use this for testing if Klass is_hidden, has_finalizer, and is_cloneable_fast.
4467 Node* LibraryCallKit::generate_misc_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region) {
4468   return generate_klass_flags_guard(kls, modifier_mask, modifier_bits, region,
4469                                     Klass::misc_flags_offset(), TypeInt::UBYTE, T_BOOLEAN);
4470 }
4471 
4472 Node* LibraryCallKit::generate_hidden_class_guard(Node* kls, RegionNode* region) {
4473   return generate_misc_flags_guard(kls, KlassFlags::_misc_is_hidden_class, 0, region);
4474 }
4475 
4476 //-------------------------inline_native_Class_query-------------------
4477 bool LibraryCallKit::inline_native_Class_query(vmIntrinsics::ID id) {
4478   const Type* return_type = TypeInt::BOOL;
4479   Node* prim_return_value = top();  // what happens if it's a primitive class?
4480   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
4481   bool expect_prim = false;     // most of these guys expect to work on refs
4482 
4483   enum { _normal_path = 1, _prim_path = 2, PATH_LIMIT };
4484 
4485   Node* mirror = argument(0);
4486   Node* obj    = top();
4487 
4488   switch (id) {
4489   case vmIntrinsics::_isInstance:
4490     // nothing is an instance of a primitive type
4491     prim_return_value = intcon(0);
4492     obj = argument(1);
4493     break;
4494   case vmIntrinsics::_isHidden:
4495     prim_return_value = intcon(0);
4496     break;
4497   case vmIntrinsics::_getSuperclass:
4498     prim_return_value = null();
4499     return_type = TypeInstPtr::MIRROR->cast_to_ptr_type(TypePtr::BotPTR);
4500     break;
4501   default:
4502     fatal_unexpected_iid(id);
4503     break;
4504   }
4505 
4506   const TypeInstPtr* mirror_con = _gvn.type(mirror)->isa_instptr();
4507   if (mirror_con == nullptr)  return false;  // cannot happen?
4508 
4509 #ifndef PRODUCT
4510   if (C->print_intrinsics() || C->print_inlining()) {
4511     ciType* k = mirror_con->java_mirror_type();
4512     if (k) {
4513       tty->print("Inlining %s on constant Class ", vmIntrinsics::name_at(intrinsic_id()));
4514       k->print_name();
4515       tty->cr();
4516     }
4517   }
4518 #endif
4519 
4520   // Null-check the mirror, and the mirror's klass ptr (in case it is a primitive).
4521   RegionNode* region = new RegionNode(PATH_LIMIT);
4522   record_for_igvn(region);
4523   PhiNode* phi = new PhiNode(region, return_type);
4524 
4525   // The mirror will never be null of Reflection.getClassAccessFlags, however
4526   // it may be null for Class.isInstance or Class.getModifiers. Throw a NPE
4527   // if it is. See bug 4774291.
4528 
4529   // For Reflection.getClassAccessFlags(), the null check occurs in
4530   // the wrong place; see inline_unsafe_access(), above, for a similar
4531   // situation.
4532   mirror = null_check(mirror);
4533   // If mirror or obj is dead, only null-path is taken.
4534   if (stopped())  return true;
4535 
4536   if (expect_prim)  never_see_null = false;  // expect nulls (meaning prims)
4537 
4538   // Now load the mirror's klass metaobject, and null-check it.
4539   // Side-effects region with the control path if the klass is null.
4540   Node* kls = load_klass_from_mirror(mirror, never_see_null, region, _prim_path);
4541   // If kls is null, we have a primitive mirror.
4542   phi->init_req(_prim_path, prim_return_value);
4543   if (stopped()) { set_result(region, phi); return true; }
4544   bool safe_for_replace = (region->in(_prim_path) == top());
4545 
4546   Node* p;  // handy temp
4547   Node* null_ctl;
4548 
4549   // Now that we have the non-null klass, we can perform the real query.
4550   // For constant classes, the query will constant-fold in LoadNode::Value.
4551   Node* query_value = top();
4552   switch (id) {
4553   case vmIntrinsics::_isInstance:
4554     // nothing is an instance of a primitive type
4555     query_value = gen_instanceof(obj, kls, safe_for_replace);
4556     break;
4557 
4558   case vmIntrinsics::_isHidden:
4559     // (To verify this code sequence, check the asserts in JVM_IsHiddenClass.)
4560     if (generate_hidden_class_guard(kls, region) != nullptr)
4561       // A guard was added.  If the guard is taken, it was an hidden class.
4562       phi->add_req(intcon(1));
4563     // If we fall through, it's a plain class.
4564     query_value = intcon(0);
4565     break;
4566 
4567 
4568   case vmIntrinsics::_getSuperclass:
4569     // The rules here are somewhat unfortunate, but we can still do better
4570     // with random logic than with a JNI call.
4571     // Interfaces store null or Object as _super, but must report null.
4572     // Arrays store an intermediate super as _super, but must report Object.
4573     // Other types can report the actual _super.
4574     // (To verify this code sequence, check the asserts in JVM_IsInterface.)
4575     if (generate_array_guard(kls, region) != nullptr) {
4576       // A guard was added.  If the guard is taken, it was an array.
4577       phi->add_req(makecon(TypeInstPtr::make(env()->Object_klass()->java_mirror())));
4578     }
4579     // Check for interface after array since this checks AccessFlags offset into InstanceKlass.
4580     // In other words, we are accessing subtype-specific information, so we need to determine the subtype first.
4581     if (generate_interface_guard(kls, region) != nullptr) {
4582       // A guard was added.  If the guard is taken, it was an interface.
4583       phi->add_req(null());
4584     }
4585     // If we fall through, it's a plain class.  Get its _super.
4586     if (!stopped()) {
4587       p = basic_plus_adr(kls, in_bytes(Klass::super_offset()));
4588       kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), p, TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
4589       null_ctl = top();
4590       kls = null_check_oop(kls, &null_ctl);
4591       if (null_ctl != top()) {
4592         // If the guard is taken, Object.superClass is null (both klass and mirror).
4593         region->add_req(null_ctl);
4594         phi   ->add_req(null());
4595       }
4596       if (!stopped()) {
4597         query_value = load_mirror_from_klass(kls);
4598       }
4599     }
4600     break;
4601 
4602   default:
4603     fatal_unexpected_iid(id);
4604     break;
4605   }
4606 
4607   // Fall-through is the normal case of a query to a real class.
4608   phi->init_req(1, query_value);
4609   region->init_req(1, control());
4610 
4611   C->set_has_split_ifs(true); // Has chance for split-if optimization
4612   set_result(region, phi);
4613   return true;
4614 }
4615 
4616 
4617 //-------------------------inline_Class_cast-------------------
4618 bool LibraryCallKit::inline_Class_cast() {
4619   Node* mirror = argument(0); // Class
4620   Node* obj    = argument(1);
4621   const TypeInstPtr* mirror_con = _gvn.type(mirror)->isa_instptr();
4622   if (mirror_con == nullptr) {
4623     return false;  // dead path (mirror->is_top()).
4624   }
4625   if (obj == nullptr || obj->is_top()) {
4626     return false;  // dead path
4627   }
4628   const TypeOopPtr* tp = _gvn.type(obj)->isa_oopptr();
4629 
4630   // First, see if Class.cast() can be folded statically.
4631   // java_mirror_type() returns non-null for compile-time Class constants.
4632   ciType* tm = mirror_con->java_mirror_type();
4633   if (tm != nullptr && tm->is_klass() &&
4634       tp != nullptr) {
4635     if (!tp->is_loaded()) {
4636       // Don't use intrinsic when class is not loaded.
4637       return false;
4638     } else {
4639       const TypeKlassPtr* tklass = TypeKlassPtr::make(tm->as_klass(), Type::trust_interfaces);
4640       int static_res = C->static_subtype_check(tklass, tp->as_klass_type());
4641       if (static_res == Compile::SSC_always_true) {
4642         // isInstance() is true - fold the code.
4643         set_result(obj);
4644         return true;
4645       } else if (static_res == Compile::SSC_always_false) {
4646         // Don't use intrinsic, have to throw ClassCastException.
4647         // If the reference is null, the non-intrinsic bytecode will
4648         // be optimized appropriately.
4649         return false;
4650       }
4651     }
4652   }
4653 
4654   // Bailout intrinsic and do normal inlining if exception path is frequent.
4655   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
4656     return false;
4657   }
4658 
4659   // Generate dynamic checks.
4660   // Class.cast() is java implementation of _checkcast bytecode.
4661   // Do checkcast (Parse::do_checkcast()) optimizations here.
4662 
4663   mirror = null_check(mirror);
4664   // If mirror is dead, only null-path is taken.
4665   if (stopped()) {
4666     return true;
4667   }
4668 
4669   // Not-subtype or the mirror's klass ptr is nullptr (in case it is a primitive).
4670   enum { _bad_type_path = 1, _prim_path = 2, _npe_path = 3, PATH_LIMIT };
4671   RegionNode* region = new RegionNode(PATH_LIMIT);
4672   record_for_igvn(region);
4673 
4674   // Now load the mirror's klass metaobject, and null-check it.
4675   // If kls is null, we have a primitive mirror and
4676   // nothing is an instance of a primitive type.
4677   Node* kls = load_klass_from_mirror(mirror, false, region, _prim_path);
4678 
4679   Node* res = top();
4680   Node* io = i_o();
4681   Node* mem = merged_memory();
4682   if (!stopped()) {
4683 
4684     Node* bad_type_ctrl = top();
4685     // Do checkcast optimizations.
4686     res = gen_checkcast(obj, kls, &bad_type_ctrl);
4687     region->init_req(_bad_type_path, bad_type_ctrl);
4688   }
4689   if (region->in(_prim_path) != top() ||
4690       region->in(_bad_type_path) != top() ||
4691       region->in(_npe_path) != top()) {
4692     // Let Interpreter throw ClassCastException.
4693     PreserveJVMState pjvms(this);
4694     set_control(_gvn.transform(region));
4695     // Set IO and memory because gen_checkcast may override them when buffering inline types
4696     set_i_o(io);
4697     set_all_memory(mem);
4698     uncommon_trap(Deoptimization::Reason_intrinsic,
4699                   Deoptimization::Action_maybe_recompile);
4700   }
4701   if (!stopped()) {
4702     set_result(res);
4703   }
4704   return true;
4705 }
4706 
4707 
4708 //--------------------------inline_native_subtype_check------------------------
4709 // This intrinsic takes the JNI calls out of the heart of
4710 // UnsafeFieldAccessorImpl.set, which improves Field.set, readObject, etc.
4711 bool LibraryCallKit::inline_native_subtype_check() {
4712   // Pull both arguments off the stack.
4713   Node* args[2];                // two java.lang.Class mirrors: superc, subc
4714   args[0] = argument(0);
4715   args[1] = argument(1);
4716   Node* klasses[2];             // corresponding Klasses: superk, subk
4717   klasses[0] = klasses[1] = top();
4718 
4719   enum {
4720     // A full decision tree on {superc is prim, subc is prim}:
4721     _prim_0_path = 1,           // {P,N} => false
4722                                 // {P,P} & superc!=subc => false
4723     _prim_same_path,            // {P,P} & superc==subc => true
4724     _prim_1_path,               // {N,P} => false
4725     _ref_subtype_path,          // {N,N} & subtype check wins => true
4726     _both_ref_path,             // {N,N} & subtype check loses => false
4727     PATH_LIMIT
4728   };
4729 
4730   RegionNode* region = new RegionNode(PATH_LIMIT);
4731   RegionNode* prim_region = new RegionNode(2);
4732   Node*       phi    = new PhiNode(region, TypeInt::BOOL);
4733   record_for_igvn(region);
4734   record_for_igvn(prim_region);
4735 
4736   const TypePtr* adr_type = TypeRawPtr::BOTTOM;   // memory type of loads
4737   const TypeKlassPtr* kls_type = TypeInstKlassPtr::OBJECT_OR_NULL;
4738   int class_klass_offset = java_lang_Class::klass_offset();
4739 
4740   // First null-check both mirrors and load each mirror's klass metaobject.
4741   int which_arg;
4742   for (which_arg = 0; which_arg <= 1; which_arg++) {
4743     Node* arg = args[which_arg];
4744     arg = null_check(arg);
4745     if (stopped())  break;
4746     args[which_arg] = arg;
4747 
4748     Node* p = basic_plus_adr(arg, class_klass_offset);
4749     Node* kls = LoadKlassNode::make(_gvn, immutable_memory(), p, adr_type, kls_type);
4750     klasses[which_arg] = _gvn.transform(kls);
4751   }
4752 
4753   // Having loaded both klasses, test each for null.
4754   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
4755   for (which_arg = 0; which_arg <= 1; which_arg++) {
4756     Node* kls = klasses[which_arg];
4757     Node* null_ctl = top();
4758     kls = null_check_oop(kls, &null_ctl, never_see_null);
4759     if (which_arg == 0) {
4760       prim_region->init_req(1, null_ctl);
4761     } else {
4762       region->init_req(_prim_1_path, null_ctl);
4763     }
4764     if (stopped())  break;
4765     klasses[which_arg] = kls;
4766   }
4767 
4768   if (!stopped()) {
4769     // now we have two reference types, in klasses[0..1]
4770     Node* subk   = klasses[1];  // the argument to isAssignableFrom
4771     Node* superk = klasses[0];  // the receiver
4772     region->set_req(_both_ref_path, gen_subtype_check(subk, superk));
4773     region->set_req(_ref_subtype_path, control());
4774   }
4775 
4776   // If both operands are primitive (both klasses null), then
4777   // we must return true when they are identical primitives.
4778   // It is convenient to test this after the first null klass check.
4779   // This path is also used if superc is a value mirror.
4780   set_control(_gvn.transform(prim_region));
4781   if (!stopped()) {
4782     // Since superc is primitive, make a guard for the superc==subc case.
4783     Node* cmp_eq = _gvn.transform(new CmpPNode(args[0], args[1]));
4784     Node* bol_eq = _gvn.transform(new BoolNode(cmp_eq, BoolTest::eq));
4785     generate_fair_guard(bol_eq, region);
4786     if (region->req() == PATH_LIMIT+1) {
4787       // A guard was added.  If the added guard is taken, superc==subc.
4788       region->swap_edges(PATH_LIMIT, _prim_same_path);
4789       region->del_req(PATH_LIMIT);
4790     }
4791     region->set_req(_prim_0_path, control()); // Not equal after all.
4792   }
4793 
4794   // these are the only paths that produce 'true':
4795   phi->set_req(_prim_same_path,   intcon(1));
4796   phi->set_req(_ref_subtype_path, intcon(1));
4797 
4798   // pull together the cases:
4799   assert(region->req() == PATH_LIMIT, "sane region");
4800   for (uint i = 1; i < region->req(); i++) {
4801     Node* ctl = region->in(i);
4802     if (ctl == nullptr || ctl == top()) {
4803       region->set_req(i, top());
4804       phi   ->set_req(i, top());
4805     } else if (phi->in(i) == nullptr) {
4806       phi->set_req(i, intcon(0)); // all other paths produce 'false'
4807     }
4808   }
4809 
4810   set_control(_gvn.transform(region));
4811   set_result(_gvn.transform(phi));
4812   return true;
4813 }
4814 
4815 //---------------------generate_array_guard_common------------------------
4816 Node* LibraryCallKit::generate_array_guard_common(Node* kls, RegionNode* region, ArrayKind kind, Node** obj) {
4817 
4818   if (stopped()) {
4819     return nullptr;
4820   }
4821 
4822   // Like generate_guard, adds a new path onto the region.
4823   jint  layout_con = 0;
4824   Node* layout_val = get_layout_helper(kls, layout_con);
4825   if (layout_val == nullptr) {
4826     bool query = 0;
4827     switch(kind) {
4828       case RefArray:       query = Klass::layout_helper_is_refArray(layout_con); break;
4829       case NonRefArray:    query = !Klass::layout_helper_is_refArray(layout_con); break;
4830       case TypeArray:      query = Klass::layout_helper_is_typeArray(layout_con); break;
4831       case AnyArray:       query = Klass::layout_helper_is_array(layout_con); break;
4832       case NonArray:       query = !Klass::layout_helper_is_array(layout_con); break;
4833       default:
4834         ShouldNotReachHere();
4835     }
4836     if (!query) {
4837       return nullptr;                       // never a branch
4838     } else {                             // always a branch
4839       Node* always_branch = control();
4840       if (region != nullptr)
4841         region->add_req(always_branch);
4842       set_control(top());
4843       return always_branch;
4844     }
4845   }
4846   unsigned int value = 0;
4847   BoolTest::mask btest = BoolTest::illegal;
4848   switch(kind) {
4849     case RefArray:
4850     case NonRefArray: {
4851       value = Klass::_lh_array_tag_ref_value;
4852       layout_val = _gvn.transform(new RShiftINode(layout_val, intcon(Klass::_lh_array_tag_shift)));
4853       btest = (kind == RefArray) ? BoolTest::eq : BoolTest::ne;
4854       break;
4855     }
4856     case TypeArray: {
4857       value = Klass::_lh_array_tag_type_value;
4858       layout_val = _gvn.transform(new RShiftINode(layout_val, intcon(Klass::_lh_array_tag_shift)));
4859       btest = BoolTest::eq;
4860       break;
4861     }
4862     case AnyArray:    value = Klass::_lh_neutral_value; btest = BoolTest::lt; break;
4863     case NonArray:    value = Klass::_lh_neutral_value; btest = BoolTest::gt; break;
4864     default:
4865       ShouldNotReachHere();
4866   }
4867   // Now test the correct condition.
4868   jint nval = (jint)value;
4869   Node* cmp = _gvn.transform(new CmpINode(layout_val, intcon(nval)));
4870   Node* bol = _gvn.transform(new BoolNode(cmp, btest));
4871   Node* ctrl = generate_fair_guard(bol, region);
4872   Node* is_array_ctrl = kind == NonArray ? control() : ctrl;
4873   if (obj != nullptr && is_array_ctrl != nullptr && is_array_ctrl != top()) {
4874     // Keep track of the fact that 'obj' is an array to prevent
4875     // array specific accesses from floating above the guard.
4876     *obj = _gvn.transform(new CastPPNode(is_array_ctrl, *obj, TypeAryPtr::BOTTOM));
4877   }
4878   return ctrl;
4879 }
4880 
4881 // public static native Object[] ValueClass::newNullRestrictedAtomicArray(Class<?> componentType, int length, Object initVal);
4882 // public static native Object[] ValueClass::newNullRestrictedNonAtomicArray(Class<?> componentType, int length, Object initVal);
4883 // public static native Object[] ValueClass::newNullableAtomicArray(Class<?> componentType, int length);
4884 bool LibraryCallKit::inline_newArray(bool null_free, bool atomic) {
4885   assert(null_free || atomic, "nullable implies atomic");
4886   Node* componentType = argument(0);
4887   Node* length = argument(1);
4888   Node* init_val = null_free ? argument(2) : nullptr;
4889 
4890   const TypeInstPtr* tp = _gvn.type(componentType)->isa_instptr();
4891   if (tp != nullptr) {
4892     ciInstanceKlass* ik = tp->instance_klass();
4893     if (ik == C->env()->Class_klass()) {
4894       ciType* t = tp->java_mirror_type();
4895       if (t != nullptr && t->is_inlinetype()) {
4896 
4897         ciArrayKlass* array_klass = ciArrayKlass::make(t, null_free, atomic, true);
4898         assert(array_klass->is_elem_null_free() == null_free, "inconsistency");
4899 
4900         // TOOD 8350865 ZGC needs card marks on initializing oop stores
4901         if (UseZGC && null_free && !array_klass->is_flat_array_klass()) {
4902           return false;
4903         }
4904 
4905         if (array_klass->is_loaded() && array_klass->element_klass()->as_inline_klass()->is_initialized()) {
4906           const TypeAryKlassPtr* array_klass_type = TypeAryKlassPtr::make(array_klass, Type::trust_interfaces);
4907           if (null_free) {
4908             if (init_val->is_InlineType()) {
4909               if (array_klass_type->is_flat() && init_val->as_InlineType()->is_all_zero(&gvn(), /* flat */ true)) {
4910                 // Zeroing is enough because the init value is the all-zero value
4911                 init_val = nullptr;
4912               } else {
4913                 init_val = init_val->as_InlineType()->buffer(this);
4914               }
4915             }
4916             // TODO 8350865 Should we add a check of the init_val type (maybe in debug only + halt)?
4917             // If we insert a checkcast here, we can be sure that init_val is an InlineTypeNode, so
4918             // when we folded a field load from an allocation (e.g. during escape analysis), we can
4919             // remove the check init_val->is_InlineType().
4920           }
4921           Node* obj = new_array(makecon(array_klass_type), length, 0, nullptr, false, init_val);
4922           const TypeAryPtr* arytype = gvn().type(obj)->is_aryptr();
4923           assert(arytype->is_null_free() == null_free, "inconsistency");
4924           assert(arytype->is_not_null_free() == !null_free, "inconsistency");
4925           set_result(obj);
4926           return true;
4927         }
4928       }
4929     }
4930   }
4931   return false;
4932 }
4933 
4934 // public static native boolean ValueClass::isFlatArray(Object array);
4935 // public static native boolean ValueClass::isNullRestrictedArray(Object array);
4936 // public static native boolean ValueClass::isAtomicArray(Object array);
4937 bool LibraryCallKit::inline_getArrayProperties(ArrayPropertiesCheck check) {
4938   Node* array = argument(0);
4939 
4940   Node* bol;
4941   switch(check) {
4942     case IsFlat:
4943       // TODO 8350865 Use the object version here instead of loading the klass
4944       // 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
4945       bol = flat_array_test(load_object_klass(array));
4946       break;
4947     case IsNullRestricted:
4948       bol = null_free_array_test(array);
4949       break;
4950     case IsAtomic:
4951       // TODO 8350865 Implement this. It's a bit more complicated, see conditions in JVM_IsAtomicArray
4952       // Enable TestIntrinsics::test87/88 once this is implemented
4953       // bol = null_free_atomic_array_test
4954       return false;
4955     default:
4956       ShouldNotReachHere();
4957   }
4958 
4959   Node* res = gvn().transform(new CMoveINode(bol, intcon(0), intcon(1), TypeInt::BOOL));
4960   set_result(res);
4961   return true;
4962 }
4963 
4964 // Load the default refined array klass from an ObjArrayKlass. This relies on the first entry in the
4965 // '_next_refined_array_klass' linked list being the default (see ObjArrayKlass::klass_with_properties).
4966 Node* LibraryCallKit::load_default_refined_array_klass(Node* klass_node, bool type_array_guard) {
4967   RegionNode* region = new RegionNode(2);
4968   Node* phi = new PhiNode(region, TypeInstKlassPtr::OBJECT_OR_NULL);
4969 
4970   if (type_array_guard) {
4971     generate_typeArray_guard(klass_node, region);
4972     if (region->req() == 3) {
4973       phi->add_req(klass_node);
4974     }
4975   }
4976   Node* adr_refined_klass = basic_plus_adr(klass_node, in_bytes(ObjArrayKlass::next_refined_array_klass_offset()));
4977   Node* refined_klass = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), adr_refined_klass, TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
4978 
4979   // Can be null if not initialized yet, just deopt
4980   Node* null_ctl = top();
4981   refined_klass = null_check_oop(refined_klass, &null_ctl, /* never_see_null= */ true);
4982 
4983   region->init_req(1, control());
4984   phi->init_req(1, refined_klass);
4985 
4986   set_control(_gvn.transform(region));
4987   return _gvn.transform(phi);
4988 }
4989 
4990 // Load the non-refined array klass from an ObjArrayKlass.
4991 Node* LibraryCallKit::load_non_refined_array_klass(Node* klass_node) {
4992   const TypeAryKlassPtr* ary_klass_ptr = _gvn.type(klass_node)->isa_aryklassptr();
4993   if (ary_klass_ptr != nullptr && ary_klass_ptr->klass_is_exact()) {
4994     return _gvn.makecon(ary_klass_ptr->cast_to_refined_array_klass_ptr(false));
4995   }
4996 
4997   RegionNode* region = new RegionNode(2);
4998   Node* phi = new PhiNode(region, TypeInstKlassPtr::OBJECT);
4999 
5000   generate_typeArray_guard(klass_node, region);
5001   if (region->req() == 3) {
5002     phi->add_req(klass_node);
5003   }
5004   Node* super_adr = basic_plus_adr(klass_node, in_bytes(Klass::super_offset()));
5005   Node* super_klass = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), super_adr, TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT));
5006 
5007   region->init_req(1, control());
5008   phi->init_req(1, super_klass);
5009 
5010   set_control(_gvn.transform(region));
5011   return _gvn.transform(phi);
5012 }
5013 
5014 //-----------------------inline_native_newArray--------------------------
5015 // private static native Object java.lang.reflect.Array.newArray(Class<?> componentType, int length);
5016 // private        native Object Unsafe.allocateUninitializedArray0(Class<?> cls, int size);
5017 bool LibraryCallKit::inline_unsafe_newArray(bool uninitialized) {
5018   Node* mirror;
5019   Node* count_val;
5020   if (uninitialized) {
5021     null_check_receiver();
5022     mirror    = argument(1);
5023     count_val = argument(2);
5024   } else {
5025     mirror    = argument(0);
5026     count_val = argument(1);
5027   }
5028 
5029   mirror = null_check(mirror);
5030   // If mirror or obj is dead, only null-path is taken.
5031   if (stopped())  return true;
5032 
5033   enum { _normal_path = 1, _slow_path = 2, PATH_LIMIT };
5034   RegionNode* result_reg = new RegionNode(PATH_LIMIT);
5035   PhiNode*    result_val = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
5036   PhiNode*    result_io  = new PhiNode(result_reg, Type::ABIO);
5037   PhiNode*    result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
5038 
5039   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
5040   Node* klass_node = load_array_klass_from_mirror(mirror, never_see_null,
5041                                                   result_reg, _slow_path);
5042   Node* normal_ctl   = control();
5043   Node* no_array_ctl = result_reg->in(_slow_path);
5044 
5045   // Generate code for the slow case.  We make a call to newArray().
5046   set_control(no_array_ctl);
5047   if (!stopped()) {
5048     // Either the input type is void.class, or else the
5049     // array klass has not yet been cached.  Either the
5050     // ensuing call will throw an exception, or else it
5051     // will cache the array klass for next time.
5052     PreserveJVMState pjvms(this);
5053     CallJavaNode* slow_call = nullptr;
5054     if (uninitialized) {
5055       // Generate optimized virtual call (holder class 'Unsafe' is final)
5056       slow_call = generate_method_call(vmIntrinsics::_allocateUninitializedArray, false, false, true);
5057     } else {
5058       slow_call = generate_method_call_static(vmIntrinsics::_newArray, true);
5059     }
5060     Node* slow_result = set_results_for_java_call(slow_call);
5061     // this->control() comes from set_results_for_java_call
5062     result_reg->set_req(_slow_path, control());
5063     result_val->set_req(_slow_path, slow_result);
5064     result_io ->set_req(_slow_path, i_o());
5065     result_mem->set_req(_slow_path, reset_memory());
5066   }
5067 
5068   set_control(normal_ctl);
5069   if (!stopped()) {
5070     // Normal case:  The array type has been cached in the java.lang.Class.
5071     // The following call works fine even if the array type is polymorphic.
5072     // It could be a dynamic mix of int[], boolean[], Object[], etc.
5073 
5074     klass_node = load_default_refined_array_klass(klass_node);
5075 
5076     Node* obj = new_array(klass_node, count_val, 0);  // no arguments to push
5077     result_reg->init_req(_normal_path, control());
5078     result_val->init_req(_normal_path, obj);
5079     result_io ->init_req(_normal_path, i_o());
5080     result_mem->init_req(_normal_path, reset_memory());
5081 
5082     if (uninitialized) {
5083       // Mark the allocation so that zeroing is skipped
5084       AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(obj);
5085       alloc->maybe_set_complete(&_gvn);
5086     }
5087   }
5088 
5089   // Return the combined state.
5090   set_i_o(        _gvn.transform(result_io)  );
5091   set_all_memory( _gvn.transform(result_mem));
5092 
5093   C->set_has_split_ifs(true); // Has chance for split-if optimization
5094   set_result(result_reg, result_val);
5095   return true;
5096 }
5097 
5098 //----------------------inline_native_getLength--------------------------
5099 // public static native int java.lang.reflect.Array.getLength(Object array);
5100 bool LibraryCallKit::inline_native_getLength() {
5101   if (too_many_traps(Deoptimization::Reason_intrinsic))  return false;
5102 
5103   Node* array = null_check(argument(0));
5104   // If array is dead, only null-path is taken.
5105   if (stopped())  return true;
5106 
5107   // Deoptimize if it is a non-array.
5108   Node* non_array = generate_non_array_guard(load_object_klass(array), nullptr, &array);
5109 
5110   if (non_array != nullptr) {
5111     PreserveJVMState pjvms(this);
5112     set_control(non_array);
5113     uncommon_trap(Deoptimization::Reason_intrinsic,
5114                   Deoptimization::Action_maybe_recompile);
5115   }
5116 
5117   // If control is dead, only non-array-path is taken.
5118   if (stopped())  return true;
5119 
5120   // The works fine even if the array type is polymorphic.
5121   // It could be a dynamic mix of int[], boolean[], Object[], etc.
5122   Node* result = load_array_length(array);
5123 
5124   C->set_has_split_ifs(true);  // Has chance for split-if optimization
5125   set_result(result);
5126   return true;
5127 }
5128 
5129 //------------------------inline_array_copyOf----------------------------
5130 // public static <T,U> T[] java.util.Arrays.copyOf(     U[] original, int newLength,         Class<? extends T[]> newType);
5131 // public static <T,U> T[] java.util.Arrays.copyOfRange(U[] original, int from,      int to, Class<? extends T[]> newType);
5132 bool LibraryCallKit::inline_array_copyOf(bool is_copyOfRange) {
5133   if (too_many_traps(Deoptimization::Reason_intrinsic))  return false;
5134 
5135   // Get the arguments.
5136   Node* original          = argument(0);
5137   Node* start             = is_copyOfRange? argument(1): intcon(0);
5138   Node* end               = is_copyOfRange? argument(2): argument(1);
5139   Node* array_type_mirror = is_copyOfRange? argument(3): argument(2);
5140 
5141   Node* newcopy = nullptr;
5142 
5143   // Set the original stack and the reexecute bit for the interpreter to reexecute
5144   // the bytecode that invokes Arrays.copyOf if deoptimization happens.
5145   { PreserveReexecuteState preexecs(this);
5146     jvms()->set_should_reexecute(true);
5147 
5148     array_type_mirror = null_check(array_type_mirror);
5149     original          = null_check(original);
5150 
5151     // Check if a null path was taken unconditionally.
5152     if (stopped())  return true;
5153 
5154     Node* orig_length = load_array_length(original);
5155 
5156     Node* klass_node = load_klass_from_mirror(array_type_mirror, false, nullptr, 0);
5157     klass_node = null_check(klass_node);
5158 
5159     RegionNode* bailout = new RegionNode(1);
5160     record_for_igvn(bailout);
5161 
5162     // Despite the generic type of Arrays.copyOf, the mirror might be int, int[], etc.
5163     // Bail out if that is so.
5164     // Inline type array may have object field that would require a
5165     // write barrier. Conservatively, go to slow path.
5166     // TODO 8251971: Optimize for the case when flat src/dst are later found
5167     // to not contain oops (i.e., move this check to the macro expansion phase).
5168     BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
5169     const TypeAryPtr* orig_t = _gvn.type(original)->isa_aryptr();
5170     const TypeKlassPtr* tklass = _gvn.type(klass_node)->is_klassptr();
5171     bool exclude_flat = UseArrayFlattening && bs->array_copy_requires_gc_barriers(true, T_OBJECT, false, false, BarrierSetC2::Parsing) &&
5172                         // Can src array be flat and contain oops?
5173                         (orig_t == nullptr || (!orig_t->is_not_flat() && (!orig_t->is_flat() || orig_t->elem()->inline_klass()->contains_oops()))) &&
5174                         // Can dest array be flat and contain oops?
5175                         tklass->can_be_inline_array() && (!tklass->is_flat() || tklass->is_aryklassptr()->elem()->is_instklassptr()->instance_klass()->as_inline_klass()->contains_oops());
5176     Node* not_objArray = exclude_flat ? generate_non_refArray_guard(klass_node, bailout) : generate_typeArray_guard(klass_node, bailout);
5177 
5178     Node* refined_klass_node = load_default_refined_array_klass(klass_node, /* type_array_guard= */ false);
5179 
5180     if (not_objArray != nullptr) {
5181       // Improve the klass node's type from the new optimistic assumption:
5182       ciKlass* ak = ciArrayKlass::make(env()->Object_klass());
5183       bool not_flat = !UseArrayFlattening;
5184       bool not_null_free = !Arguments::is_valhalla_enabled();
5185       const Type* akls = TypeAryKlassPtr::make(TypePtr::NotNull, ak, Type::Offset(0), Type::trust_interfaces, not_flat, not_null_free, false, false, not_flat, true);
5186       Node* cast = new CastPPNode(control(), refined_klass_node, akls);
5187       refined_klass_node = _gvn.transform(cast);
5188     }
5189 
5190     // Bail out if either start or end is negative.
5191     generate_negative_guard(start, bailout, &start);
5192     generate_negative_guard(end,   bailout, &end);
5193 
5194     Node* length = end;
5195     if (_gvn.type(start) != TypeInt::ZERO) {
5196       length = _gvn.transform(new SubINode(end, start));
5197     }
5198 
5199     // Bail out if length is negative (i.e., if start > end).
5200     // Without this the new_array would throw
5201     // NegativeArraySizeException but IllegalArgumentException is what
5202     // should be thrown
5203     generate_negative_guard(length, bailout, &length);
5204 
5205     // Handle inline type arrays
5206     bool can_validate = !too_many_traps(Deoptimization::Reason_class_check);
5207     if (!stopped()) {
5208       // TODO 8251971
5209       if (!orig_t->is_null_free()) {
5210         // Not statically known to be null free, add a check
5211         generate_fair_guard(null_free_array_test(original), bailout);
5212       }
5213       orig_t = _gvn.type(original)->isa_aryptr();
5214       if (orig_t != nullptr && orig_t->is_flat()) {
5215         // Src is flat, check that dest is flat as well
5216         if (exclude_flat) {
5217           // Dest can't be flat, bail out
5218           bailout->add_req(control());
5219           set_control(top());
5220         } else {
5221           generate_fair_guard(flat_array_test(refined_klass_node, /* flat = */ false), bailout);
5222         }
5223         // TODO 8350865 This is not correct anymore. Write tests and fix logic similar to arraycopy.
5224       } else if (UseArrayFlattening && (orig_t == nullptr || !orig_t->is_not_flat()) &&
5225                  // If dest is flat, src must be flat as well (guaranteed by src <: dest check if validated).
5226                  ((!tklass->is_flat() && tklass->can_be_inline_array()) || !can_validate)) {
5227         // Src might be flat and dest might not be flat. Go to the slow path if src is flat.
5228         // TODO 8251971: Optimize for the case when src/dest are later found to be both flat.
5229         generate_fair_guard(flat_array_test(load_object_klass(original)), bailout);
5230         if (orig_t != nullptr) {
5231           orig_t = orig_t->cast_to_not_flat();
5232           original = _gvn.transform(new CheckCastPPNode(control(), original, orig_t));
5233         }
5234       }
5235       if (!can_validate) {
5236         // No validation. The subtype check emitted at macro expansion time will not go to the slow
5237         // path but call checkcast_arraycopy which can not handle flat/null-free inline type arrays.
5238         // TODO 8251971: Optimize for the case when src/dest are later found to be both flat/null-free.
5239         generate_fair_guard(flat_array_test(refined_klass_node), bailout);
5240         generate_fair_guard(null_free_array_test(original), bailout);
5241       }
5242     }
5243 
5244     // Bail out if start is larger than the original length
5245     Node* orig_tail = _gvn.transform(new SubINode(orig_length, start));
5246     generate_negative_guard(orig_tail, bailout, &orig_tail);
5247 
5248     if (bailout->req() > 1) {
5249       PreserveJVMState pjvms(this);
5250       set_control(_gvn.transform(bailout));
5251       uncommon_trap(Deoptimization::Reason_intrinsic,
5252                     Deoptimization::Action_maybe_recompile);
5253     }
5254 
5255     if (!stopped()) {
5256       // How many elements will we copy from the original?
5257       // The answer is MinI(orig_tail, length).
5258       Node* moved = _gvn.transform(new MinINode(orig_tail, length));
5259 
5260       // Generate a direct call to the right arraycopy function(s).
5261       // We know the copy is disjoint but we might not know if the
5262       // oop stores need checking.
5263       // Extreme case:  Arrays.copyOf((Integer[])x, 10, String[].class).
5264       // This will fail a store-check if x contains any non-nulls.
5265 
5266       // ArrayCopyNode:Ideal may transform the ArrayCopyNode to
5267       // loads/stores but it is legal only if we're sure the
5268       // Arrays.copyOf would succeed. So we need all input arguments
5269       // to the copyOf to be validated, including that the copy to the
5270       // new array won't trigger an ArrayStoreException. That subtype
5271       // check can be optimized if we know something on the type of
5272       // the input array from type speculation.
5273       if (_gvn.type(klass_node)->singleton()) {
5274         const TypeKlassPtr* subk = _gvn.type(load_object_klass(original))->is_klassptr();
5275         const TypeKlassPtr* superk = _gvn.type(klass_node)->is_klassptr();
5276 
5277         int test = C->static_subtype_check(superk, subk);
5278         if (test != Compile::SSC_always_true && test != Compile::SSC_always_false) {
5279           const TypeOopPtr* t_original = _gvn.type(original)->is_oopptr();
5280           if (t_original->speculative_type() != nullptr) {
5281             original = maybe_cast_profiled_obj(original, t_original->speculative_type(), true);
5282           }
5283         }
5284       }
5285 
5286       bool validated = false;
5287       // Reason_class_check rather than Reason_intrinsic because we
5288       // want to intrinsify even if this traps.
5289       if (can_validate) {
5290         Node* not_subtype_ctrl = gen_subtype_check(original, klass_node);
5291 
5292         if (not_subtype_ctrl != top()) {
5293           PreserveJVMState pjvms(this);
5294           set_control(not_subtype_ctrl);
5295           uncommon_trap(Deoptimization::Reason_class_check,
5296                         Deoptimization::Action_make_not_entrant);
5297           assert(stopped(), "Should be stopped");
5298         }
5299         validated = true;
5300       }
5301 
5302       if (!stopped()) {
5303         newcopy = new_array(refined_klass_node, length, 0);  // no arguments to push
5304 
5305         ArrayCopyNode* ac = ArrayCopyNode::make(this, true, original, start, newcopy, intcon(0), moved, true, true,
5306                                                 load_object_klass(original), klass_node);
5307         if (!is_copyOfRange) {
5308           ac->set_copyof(validated);
5309         } else {
5310           ac->set_copyofrange(validated);
5311         }
5312         Node* n = _gvn.transform(ac);
5313         if (n == ac) {
5314           ac->connect_outputs(this);
5315         } else {
5316           assert(validated, "shouldn't transform if all arguments not validated");
5317           set_all_memory(n);
5318         }
5319       }
5320     }
5321   } // original reexecute is set back here
5322 
5323   C->set_has_split_ifs(true); // Has chance for split-if optimization
5324   if (!stopped()) {
5325     set_result(newcopy);
5326   }
5327   return true;
5328 }
5329 
5330 
5331 //----------------------generate_virtual_guard---------------------------
5332 // Helper for hashCode and clone.  Peeks inside the vtable to avoid a call.
5333 Node* LibraryCallKit::generate_virtual_guard(Node* obj_klass,
5334                                              RegionNode* slow_region) {
5335   ciMethod* method = callee();
5336   int vtable_index = method->vtable_index();
5337   assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index,
5338          "bad index %d", vtable_index);
5339   // Get the Method* out of the appropriate vtable entry.
5340   int entry_offset  = in_bytes(Klass::vtable_start_offset()) +
5341                      vtable_index*vtableEntry::size_in_bytes() +
5342                      in_bytes(vtableEntry::method_offset());
5343   Node* entry_addr  = basic_plus_adr(obj_klass, entry_offset);
5344   Node* target_call = make_load(nullptr, entry_addr, TypePtr::NOTNULL, T_ADDRESS, MemNode::unordered);
5345 
5346   // Compare the target method with the expected method (e.g., Object.hashCode).
5347   const TypePtr* native_call_addr = TypeMetadataPtr::make(method);
5348 
5349   Node* native_call = makecon(native_call_addr);
5350   Node* chk_native  = _gvn.transform(new CmpPNode(target_call, native_call));
5351   Node* test_native = _gvn.transform(new BoolNode(chk_native, BoolTest::ne));
5352 
5353   return generate_slow_guard(test_native, slow_region);
5354 }
5355 
5356 //-----------------------generate_method_call----------------------------
5357 // Use generate_method_call to make a slow-call to the real
5358 // method if the fast path fails.  An alternative would be to
5359 // use a stub like OptoRuntime::slow_arraycopy_Java.
5360 // This only works for expanding the current library call,
5361 // not another intrinsic.  (E.g., don't use this for making an
5362 // arraycopy call inside of the copyOf intrinsic.)
5363 CallJavaNode*
5364 LibraryCallKit::generate_method_call(vmIntrinsicID method_id, bool is_virtual, bool is_static, bool res_not_null) {
5365   // When compiling the intrinsic method itself, do not use this technique.
5366   guarantee(callee() != C->method(), "cannot make slow-call to self");
5367 
5368   ciMethod* method = callee();
5369   // ensure the JVMS we have will be correct for this call
5370   guarantee(method_id == method->intrinsic_id(), "must match");
5371 
5372   const TypeFunc* tf = TypeFunc::make(method);
5373   if (res_not_null) {
5374     assert(tf->return_type() == T_OBJECT, "");
5375     const TypeTuple* range = tf->range_cc();
5376     const Type** fields = TypeTuple::fields(range->cnt());
5377     fields[TypeFunc::Parms] = range->field_at(TypeFunc::Parms)->filter_speculative(TypePtr::NOTNULL);
5378     const TypeTuple* new_range = TypeTuple::make(range->cnt(), fields);
5379     tf = TypeFunc::make(tf->domain_cc(), new_range);
5380   }
5381   CallJavaNode* slow_call;
5382   if (is_static) {
5383     assert(!is_virtual, "");
5384     slow_call = new CallStaticJavaNode(C, tf,
5385                            SharedRuntime::get_resolve_static_call_stub(), method);
5386   } else if (is_virtual) {
5387     assert(!gvn().type(argument(0))->maybe_null(), "should not be null");
5388     int vtable_index = Method::invalid_vtable_index;
5389     if (UseInlineCaches) {
5390       // Suppress the vtable call
5391     } else {
5392       // hashCode and clone are not a miranda methods,
5393       // so the vtable index is fixed.
5394       // No need to use the linkResolver to get it.
5395        vtable_index = method->vtable_index();
5396        assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index,
5397               "bad index %d", vtable_index);
5398     }
5399     slow_call = new CallDynamicJavaNode(tf,
5400                           SharedRuntime::get_resolve_virtual_call_stub(),
5401                           method, vtable_index);
5402   } else {  // neither virtual nor static:  opt_virtual
5403     assert(!gvn().type(argument(0))->maybe_null(), "should not be null");
5404     slow_call = new CallStaticJavaNode(C, tf,
5405                                 SharedRuntime::get_resolve_opt_virtual_call_stub(), method);
5406     slow_call->set_optimized_virtual(true);
5407   }
5408   if (CallGenerator::is_inlined_method_handle_intrinsic(this->method(), bci(), callee())) {
5409     // To be able to issue a direct call (optimized virtual or virtual)
5410     // and skip a call to MH.linkTo*/invokeBasic adapter, additional information
5411     // about the method being invoked should be attached to the call site to
5412     // make resolution logic work (see SharedRuntime::resolve_{virtual,opt_virtual}_call_C).
5413     slow_call->set_override_symbolic_info(true);
5414   }
5415   set_arguments_for_java_call(slow_call);
5416   set_edges_for_java_call(slow_call);
5417   return slow_call;
5418 }
5419 
5420 
5421 /**
5422  * Build special case code for calls to hashCode on an object. This call may
5423  * be virtual (invokevirtual) or bound (invokespecial). For each case we generate
5424  * slightly different code.
5425  */
5426 bool LibraryCallKit::inline_native_hashcode(bool is_virtual, bool is_static) {
5427   assert(is_static == callee()->is_static(), "correct intrinsic selection");
5428   assert(!(is_virtual && is_static), "either virtual, special, or static");
5429 
5430   enum { _slow_path = 1, _fast_path, _null_path, PATH_LIMIT };
5431 
5432   RegionNode* result_reg = new RegionNode(PATH_LIMIT);
5433   PhiNode*    result_val = new PhiNode(result_reg, TypeInt::INT);
5434   PhiNode*    result_io  = new PhiNode(result_reg, Type::ABIO);
5435   PhiNode*    result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
5436   Node* obj = argument(0);
5437 
5438   // Don't intrinsify hashcode on inline types for now.
5439   // The "is locked" runtime check also subsumes the inline type check (as inline types cannot be locked) and goes to the slow path.
5440   if (gvn().type(obj)->is_inlinetypeptr()) {
5441     return false;
5442   }
5443 
5444   if (!is_static) {
5445     // Check for hashing null object
5446     obj = null_check_receiver();
5447     if (stopped())  return true;        // unconditionally null
5448     result_reg->init_req(_null_path, top());
5449     result_val->init_req(_null_path, top());
5450   } else {
5451     // Do a null check, and return zero if null.
5452     // System.identityHashCode(null) == 0
5453     Node* null_ctl = top();
5454     obj = null_check_oop(obj, &null_ctl);
5455     result_reg->init_req(_null_path, null_ctl);
5456     result_val->init_req(_null_path, _gvn.intcon(0));
5457   }
5458 
5459   // Unconditionally null?  Then return right away.
5460   if (stopped()) {
5461     set_control( result_reg->in(_null_path));
5462     if (!stopped())
5463       set_result(result_val->in(_null_path));
5464     return true;
5465   }
5466 
5467   // We only go to the fast case code if we pass a number of guards.  The
5468   // paths which do not pass are accumulated in the slow_region.
5469   RegionNode* slow_region = new RegionNode(1);
5470   record_for_igvn(slow_region);
5471 
5472   // If this is a virtual call, we generate a funny guard.  We pull out
5473   // the vtable entry corresponding to hashCode() from the target object.
5474   // If the target method which we are calling happens to be the native
5475   // Object hashCode() method, we pass the guard.  We do not need this
5476   // guard for non-virtual calls -- the caller is known to be the native
5477   // Object hashCode().
5478   if (is_virtual) {
5479     // After null check, get the object's klass.
5480     Node* obj_klass = load_object_klass(obj);
5481     generate_virtual_guard(obj_klass, slow_region);
5482   }
5483 
5484   // Get the header out of the object, use LoadMarkNode when available
5485   Node* header_addr = basic_plus_adr(obj, oopDesc::mark_offset_in_bytes());
5486   // The control of the load must be null. Otherwise, the load can move before
5487   // the null check after castPP removal.
5488   Node* no_ctrl = nullptr;
5489   Node* header = make_load(no_ctrl, header_addr, TypeX_X, TypeX_X->basic_type(), MemNode::unordered);
5490 
5491   if (!UseObjectMonitorTable) {
5492     // Test the header to see if it is safe to read w.r.t. locking.
5493     // We cannot use the inline type mask as this may check bits that are overriden
5494     // by an object monitor's pointer when inflating locking.
5495     Node *lock_mask      = _gvn.MakeConX(markWord::lock_mask_in_place);
5496     Node *lmasked_header = _gvn.transform(new AndXNode(header, lock_mask));
5497     Node *monitor_val   = _gvn.MakeConX(markWord::monitor_value);
5498     Node *chk_monitor   = _gvn.transform(new CmpXNode(lmasked_header, monitor_val));
5499     Node *test_monitor  = _gvn.transform(new BoolNode(chk_monitor, BoolTest::eq));
5500 
5501     generate_slow_guard(test_monitor, slow_region);
5502   }
5503 
5504   // Get the hash value and check to see that it has been properly assigned.
5505   // We depend on hash_mask being at most 32 bits and avoid the use of
5506   // hash_mask_in_place because it could be larger than 32 bits in a 64-bit
5507   // vm: see markWord.hpp.
5508   Node *hash_mask      = _gvn.intcon(markWord::hash_mask);
5509   Node *hash_shift     = _gvn.intcon(markWord::hash_shift);
5510   Node *hshifted_header= _gvn.transform(new URShiftXNode(header, hash_shift));
5511   // This hack lets the hash bits live anywhere in the mark object now, as long
5512   // as the shift drops the relevant bits into the low 32 bits.  Note that
5513   // Java spec says that HashCode is an int so there's no point in capturing
5514   // an 'X'-sized hashcode (32 in 32-bit build or 64 in 64-bit build).
5515   hshifted_header      = ConvX2I(hshifted_header);
5516   Node *hash_val       = _gvn.transform(new AndINode(hshifted_header, hash_mask));
5517 
5518   Node *no_hash_val    = _gvn.intcon(markWord::no_hash);
5519   Node *chk_assigned   = _gvn.transform(new CmpINode( hash_val, no_hash_val));
5520   Node *test_assigned  = _gvn.transform(new BoolNode( chk_assigned, BoolTest::eq));
5521 
5522   generate_slow_guard(test_assigned, slow_region);
5523 
5524   Node* init_mem = reset_memory();
5525   // fill in the rest of the null path:
5526   result_io ->init_req(_null_path, i_o());
5527   result_mem->init_req(_null_path, init_mem);
5528 
5529   result_val->init_req(_fast_path, hash_val);
5530   result_reg->init_req(_fast_path, control());
5531   result_io ->init_req(_fast_path, i_o());
5532   result_mem->init_req(_fast_path, init_mem);
5533 
5534   // Generate code for the slow case.  We make a call to hashCode().
5535   set_control(_gvn.transform(slow_region));
5536   if (!stopped()) {
5537     // No need for PreserveJVMState, because we're using up the present state.
5538     set_all_memory(init_mem);
5539     vmIntrinsics::ID hashCode_id = is_static ? vmIntrinsics::_identityHashCode : vmIntrinsics::_hashCode;
5540     CallJavaNode* slow_call = generate_method_call(hashCode_id, is_virtual, is_static, false);
5541     Node* slow_result = set_results_for_java_call(slow_call);
5542     // this->control() comes from set_results_for_java_call
5543     result_reg->init_req(_slow_path, control());
5544     result_val->init_req(_slow_path, slow_result);
5545     result_io  ->set_req(_slow_path, i_o());
5546     result_mem ->set_req(_slow_path, reset_memory());
5547   }
5548 
5549   // Return the combined state.
5550   set_i_o(        _gvn.transform(result_io)  );
5551   set_all_memory( _gvn.transform(result_mem));
5552 
5553   set_result(result_reg, result_val);
5554   return true;
5555 }
5556 
5557 //---------------------------inline_native_getClass----------------------------
5558 // public final native Class<?> java.lang.Object.getClass();
5559 //
5560 // Build special case code for calls to getClass on an object.
5561 bool LibraryCallKit::inline_native_getClass() {
5562   Node* obj = argument(0);
5563   if (obj->is_InlineType()) {
5564     const Type* t = _gvn.type(obj);
5565     if (t->maybe_null()) {
5566       null_check(obj);
5567     }
5568     set_result(makecon(TypeInstPtr::make(t->inline_klass()->java_mirror())));
5569     return true;
5570   }
5571   obj = null_check_receiver();
5572   if (stopped())  return true;
5573   set_result(load_mirror_from_klass(load_object_klass(obj)));
5574   return true;
5575 }
5576 
5577 //-----------------inline_native_Reflection_getCallerClass---------------------
5578 // public static native Class<?> sun.reflect.Reflection.getCallerClass();
5579 //
5580 // In the presence of deep enough inlining, getCallerClass() becomes a no-op.
5581 //
5582 // NOTE: This code must perform the same logic as JVM_GetCallerClass
5583 // in that it must skip particular security frames and checks for
5584 // caller sensitive methods.
5585 bool LibraryCallKit::inline_native_Reflection_getCallerClass() {
5586 #ifndef PRODUCT
5587   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5588     tty->print_cr("Attempting to inline sun.reflect.Reflection.getCallerClass");
5589   }
5590 #endif
5591 
5592   if (!jvms()->has_method()) {
5593 #ifndef PRODUCT
5594     if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5595       tty->print_cr("  Bailing out because intrinsic was inlined at top level");
5596     }
5597 #endif
5598     return false;
5599   }
5600 
5601   // Walk back up the JVM state to find the caller at the required
5602   // depth.
5603   JVMState* caller_jvms = jvms();
5604 
5605   // Cf. JVM_GetCallerClass
5606   // NOTE: Start the loop at depth 1 because the current JVM state does
5607   // not include the Reflection.getCallerClass() frame.
5608   for (int n = 1; caller_jvms != nullptr; caller_jvms = caller_jvms->caller(), n++) {
5609     ciMethod* m = caller_jvms->method();
5610     switch (n) {
5611     case 0:
5612       fatal("current JVM state does not include the Reflection.getCallerClass frame");
5613       break;
5614     case 1:
5615       // Frame 0 and 1 must be caller sensitive (see JVM_GetCallerClass).
5616       if (!m->caller_sensitive()) {
5617 #ifndef PRODUCT
5618         if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5619           tty->print_cr("  Bailing out: CallerSensitive annotation expected at frame %d", n);
5620         }
5621 #endif
5622         return false;  // bail-out; let JVM_GetCallerClass do the work
5623       }
5624       break;
5625     default:
5626       if (!m->is_ignored_by_security_stack_walk()) {
5627         // We have reached the desired frame; return the holder class.
5628         // Acquire method holder as java.lang.Class and push as constant.
5629         ciInstanceKlass* caller_klass = caller_jvms->method()->holder();
5630         ciInstance* caller_mirror = caller_klass->java_mirror();
5631         set_result(makecon(TypeInstPtr::make(caller_mirror)));
5632 
5633 #ifndef PRODUCT
5634         if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5635           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());
5636           tty->print_cr("  JVM state at this point:");
5637           for (int i = jvms()->depth(), n = 1; i >= 1; i--, n++) {
5638             ciMethod* m = jvms()->of_depth(i)->method();
5639             tty->print_cr("   %d) %s.%s", n, m->holder()->name()->as_utf8(), m->name()->as_utf8());
5640           }
5641         }
5642 #endif
5643         return true;
5644       }
5645       break;
5646     }
5647   }
5648 
5649 #ifndef PRODUCT
5650   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5651     tty->print_cr("  Bailing out because caller depth exceeded inlining depth = %d", jvms()->depth());
5652     tty->print_cr("  JVM state at this point:");
5653     for (int i = jvms()->depth(), n = 1; i >= 1; i--, n++) {
5654       ciMethod* m = jvms()->of_depth(i)->method();
5655       tty->print_cr("   %d) %s.%s", n, m->holder()->name()->as_utf8(), m->name()->as_utf8());
5656     }
5657   }
5658 #endif
5659 
5660   return false;  // bail-out; let JVM_GetCallerClass do the work
5661 }
5662 
5663 bool LibraryCallKit::inline_fp_conversions(vmIntrinsics::ID id) {
5664   Node* arg = argument(0);
5665   Node* result = nullptr;
5666 
5667   switch (id) {
5668   case vmIntrinsics::_floatToRawIntBits:    result = new MoveF2INode(arg);  break;
5669   case vmIntrinsics::_intBitsToFloat:       result = new MoveI2FNode(arg);  break;
5670   case vmIntrinsics::_doubleToRawLongBits:  result = new MoveD2LNode(arg);  break;
5671   case vmIntrinsics::_longBitsToDouble:     result = new MoveL2DNode(arg);  break;
5672   case vmIntrinsics::_floatToFloat16:       result = new ConvF2HFNode(arg); break;
5673   case vmIntrinsics::_float16ToFloat:       result = new ConvHF2FNode(arg); break;
5674 
5675   case vmIntrinsics::_doubleToLongBits: {
5676     // two paths (plus control) merge in a wood
5677     RegionNode *r = new RegionNode(3);
5678     Node *phi = new PhiNode(r, TypeLong::LONG);
5679 
5680     Node *cmpisnan = _gvn.transform(new CmpDNode(arg, arg));
5681     // Build the boolean node
5682     Node *bolisnan = _gvn.transform(new BoolNode(cmpisnan, BoolTest::ne));
5683 
5684     // Branch either way.
5685     // NaN case is less traveled, which makes all the difference.
5686     IfNode *ifisnan = create_and_xform_if(control(), bolisnan, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
5687     Node *opt_isnan = _gvn.transform(ifisnan);
5688     assert( opt_isnan->is_If(), "Expect an IfNode");
5689     IfNode *opt_ifisnan = (IfNode*)opt_isnan;
5690     Node *iftrue = _gvn.transform(new IfTrueNode(opt_ifisnan));
5691 
5692     set_control(iftrue);
5693 
5694     static const jlong nan_bits = CONST64(0x7ff8000000000000);
5695     Node *slow_result = longcon(nan_bits); // return NaN
5696     phi->init_req(1, _gvn.transform( slow_result ));
5697     r->init_req(1, iftrue);
5698 
5699     // Else fall through
5700     Node *iffalse = _gvn.transform(new IfFalseNode(opt_ifisnan));
5701     set_control(iffalse);
5702 
5703     phi->init_req(2, _gvn.transform(new MoveD2LNode(arg)));
5704     r->init_req(2, iffalse);
5705 
5706     // Post merge
5707     set_control(_gvn.transform(r));
5708     record_for_igvn(r);
5709 
5710     C->set_has_split_ifs(true); // Has chance for split-if optimization
5711     result = phi;
5712     assert(result->bottom_type()->isa_long(), "must be");
5713     break;
5714   }
5715 
5716   case vmIntrinsics::_floatToIntBits: {
5717     // two paths (plus control) merge in a wood
5718     RegionNode *r = new RegionNode(3);
5719     Node *phi = new PhiNode(r, TypeInt::INT);
5720 
5721     Node *cmpisnan = _gvn.transform(new CmpFNode(arg, arg));
5722     // Build the boolean node
5723     Node *bolisnan = _gvn.transform(new BoolNode(cmpisnan, BoolTest::ne));
5724 
5725     // Branch either way.
5726     // NaN case is less traveled, which makes all the difference.
5727     IfNode *ifisnan = create_and_xform_if(control(), bolisnan, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
5728     Node *opt_isnan = _gvn.transform(ifisnan);
5729     assert( opt_isnan->is_If(), "Expect an IfNode");
5730     IfNode *opt_ifisnan = (IfNode*)opt_isnan;
5731     Node *iftrue = _gvn.transform(new IfTrueNode(opt_ifisnan));
5732 
5733     set_control(iftrue);
5734 
5735     static const jint nan_bits = 0x7fc00000;
5736     Node *slow_result = makecon(TypeInt::make(nan_bits)); // return NaN
5737     phi->init_req(1, _gvn.transform( slow_result ));
5738     r->init_req(1, iftrue);
5739 
5740     // Else fall through
5741     Node *iffalse = _gvn.transform(new IfFalseNode(opt_ifisnan));
5742     set_control(iffalse);
5743 
5744     phi->init_req(2, _gvn.transform(new MoveF2INode(arg)));
5745     r->init_req(2, iffalse);
5746 
5747     // Post merge
5748     set_control(_gvn.transform(r));
5749     record_for_igvn(r);
5750 
5751     C->set_has_split_ifs(true); // Has chance for split-if optimization
5752     result = phi;
5753     assert(result->bottom_type()->isa_int(), "must be");
5754     break;
5755   }
5756 
5757   default:
5758     fatal_unexpected_iid(id);
5759     break;
5760   }
5761   set_result(_gvn.transform(result));
5762   return true;
5763 }
5764 
5765 bool LibraryCallKit::inline_fp_range_check(vmIntrinsics::ID id) {
5766   Node* arg = argument(0);
5767   Node* result = nullptr;
5768 
5769   switch (id) {
5770   case vmIntrinsics::_floatIsInfinite:
5771     result = new IsInfiniteFNode(arg);
5772     break;
5773   case vmIntrinsics::_floatIsFinite:
5774     result = new IsFiniteFNode(arg);
5775     break;
5776   case vmIntrinsics::_doubleIsInfinite:
5777     result = new IsInfiniteDNode(arg);
5778     break;
5779   case vmIntrinsics::_doubleIsFinite:
5780     result = new IsFiniteDNode(arg);
5781     break;
5782   default:
5783     fatal_unexpected_iid(id);
5784     break;
5785   }
5786   set_result(_gvn.transform(result));
5787   return true;
5788 }
5789 
5790 //----------------------inline_unsafe_copyMemory-------------------------
5791 // public native void Unsafe.copyMemory0(Object srcBase, long srcOffset, Object destBase, long destOffset, long bytes);
5792 
5793 static bool has_wide_mem(PhaseGVN& gvn, Node* addr, Node* base) {
5794   const TypeAryPtr* addr_t = gvn.type(addr)->isa_aryptr();
5795   const Type*       base_t = gvn.type(base);
5796 
5797   bool in_native = (base_t == TypePtr::NULL_PTR);
5798   bool in_heap   = !TypePtr::NULL_PTR->higher_equal(base_t);
5799   bool is_mixed  = !in_heap && !in_native;
5800 
5801   if (is_mixed) {
5802     return true; // mixed accesses can touch both on-heap and off-heap memory
5803   }
5804   if (in_heap) {
5805     bool is_prim_array = (addr_t != nullptr) && (addr_t->elem() != Type::BOTTOM);
5806     if (!is_prim_array) {
5807       // Though Unsafe.copyMemory() ensures at runtime for on-heap accesses that base is a primitive array,
5808       // there's not enough type information available to determine proper memory slice for it.
5809       return true;
5810     }
5811   }
5812   return false;
5813 }
5814 
5815 bool LibraryCallKit::inline_unsafe_copyMemory() {
5816   if (callee()->is_static())  return false;  // caller must have the capability!
5817   null_check_receiver();  // null-check receiver
5818   if (stopped())  return true;
5819 
5820   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
5821 
5822   Node* src_base =         argument(1);  // type: oop
5823   Node* src_off  = ConvL2X(argument(2)); // type: long
5824   Node* dst_base =         argument(4);  // type: oop
5825   Node* dst_off  = ConvL2X(argument(5)); // type: long
5826   Node* size     = ConvL2X(argument(7)); // type: long
5827 
5828   assert(Unsafe_field_offset_to_byte_offset(11) == 11,
5829          "fieldOffset must be byte-scaled");
5830 
5831   Node* src_addr = make_unsafe_address(src_base, src_off);
5832   Node* dst_addr = make_unsafe_address(dst_base, dst_off);
5833 
5834   Node* thread = _gvn.transform(new ThreadLocalNode());
5835   Node* doing_unsafe_access_addr = basic_plus_adr(top(), thread, in_bytes(JavaThread::doing_unsafe_access_offset()));
5836   BasicType doing_unsafe_access_bt = T_BYTE;
5837   assert((sizeof(bool) * CHAR_BIT) == 8, "not implemented");
5838 
5839   // update volatile field
5840   store_to_memory(control(), doing_unsafe_access_addr, intcon(1), doing_unsafe_access_bt, MemNode::unordered);
5841 
5842   int flags = RC_LEAF | RC_NO_FP;
5843 
5844   const TypePtr* dst_type = TypePtr::BOTTOM;
5845 
5846   // Adjust memory effects of the runtime call based on input values.
5847   if (!has_wide_mem(_gvn, src_addr, src_base) &&
5848       !has_wide_mem(_gvn, dst_addr, dst_base)) {
5849     dst_type = _gvn.type(dst_addr)->is_ptr(); // narrow out memory
5850 
5851     const TypePtr* src_type = _gvn.type(src_addr)->is_ptr();
5852     if (C->get_alias_index(src_type) == C->get_alias_index(dst_type)) {
5853       flags |= RC_NARROW_MEM; // narrow in memory
5854     }
5855   }
5856 
5857   // Call it.  Note that the length argument is not scaled.
5858   make_runtime_call(flags,
5859                     OptoRuntime::fast_arraycopy_Type(),
5860                     StubRoutines::unsafe_arraycopy(),
5861                     "unsafe_arraycopy",
5862                     dst_type,
5863                     src_addr, dst_addr, size XTOP);
5864 
5865   store_to_memory(control(), doing_unsafe_access_addr, intcon(0), doing_unsafe_access_bt, MemNode::unordered);
5866 
5867   return true;
5868 }
5869 
5870 // unsafe_setmemory(void *base, ulong offset, size_t length, char fill_value);
5871 // Fill 'length' bytes starting from 'base[offset]' with 'fill_value'
5872 bool LibraryCallKit::inline_unsafe_setMemory() {
5873   if (callee()->is_static())  return false;  // caller must have the capability!
5874   null_check_receiver();  // null-check receiver
5875   if (stopped())  return true;
5876 
5877   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
5878 
5879   Node* dst_base =         argument(1);  // type: oop
5880   Node* dst_off  = ConvL2X(argument(2)); // type: long
5881   Node* size     = ConvL2X(argument(4)); // type: long
5882   Node* byte     =         argument(6);  // type: byte
5883 
5884   assert(Unsafe_field_offset_to_byte_offset(11) == 11,
5885          "fieldOffset must be byte-scaled");
5886 
5887   Node* dst_addr = make_unsafe_address(dst_base, dst_off);
5888 
5889   Node* thread = _gvn.transform(new ThreadLocalNode());
5890   Node* doing_unsafe_access_addr = basic_plus_adr(top(), thread, in_bytes(JavaThread::doing_unsafe_access_offset()));
5891   BasicType doing_unsafe_access_bt = T_BYTE;
5892   assert((sizeof(bool) * CHAR_BIT) == 8, "not implemented");
5893 
5894   // update volatile field
5895   store_to_memory(control(), doing_unsafe_access_addr, intcon(1), doing_unsafe_access_bt, MemNode::unordered);
5896 
5897   int flags = RC_LEAF | RC_NO_FP;
5898 
5899   const TypePtr* dst_type = TypePtr::BOTTOM;
5900 
5901   // Adjust memory effects of the runtime call based on input values.
5902   if (!has_wide_mem(_gvn, dst_addr, dst_base)) {
5903     dst_type = _gvn.type(dst_addr)->is_ptr(); // narrow out memory
5904 
5905     flags |= RC_NARROW_MEM; // narrow in memory
5906   }
5907 
5908   // Call it.  Note that the length argument is not scaled.
5909   make_runtime_call(flags,
5910                     OptoRuntime::unsafe_setmemory_Type(),
5911                     StubRoutines::unsafe_setmemory(),
5912                     "unsafe_setmemory",
5913                     dst_type,
5914                     dst_addr, size XTOP, byte);
5915 
5916   store_to_memory(control(), doing_unsafe_access_addr, intcon(0), doing_unsafe_access_bt, MemNode::unordered);
5917 
5918   return true;
5919 }
5920 
5921 #undef XTOP
5922 
5923 //------------------------clone_coping-----------------------------------
5924 // Helper function for inline_native_clone.
5925 void LibraryCallKit::copy_to_clone(Node* obj, Node* alloc_obj, Node* obj_size, bool is_array) {
5926   assert(obj_size != nullptr, "");
5927   Node* raw_obj = alloc_obj->in(1);
5928   assert(alloc_obj->is_CheckCastPP() && raw_obj->is_Proj() && raw_obj->in(0)->is_Allocate(), "");
5929 
5930   AllocateNode* alloc = nullptr;
5931   if (ReduceBulkZeroing &&
5932       // If we are implementing an array clone without knowing its source type
5933       // (can happen when compiling the array-guarded branch of a reflective
5934       // Object.clone() invocation), initialize the array within the allocation.
5935       // This is needed because some GCs (e.g. ZGC) might fall back in this case
5936       // to a runtime clone call that assumes fully initialized source arrays.
5937       (!is_array || obj->get_ptr_type()->isa_aryptr() != nullptr)) {
5938     // We will be completely responsible for initializing this object -
5939     // mark Initialize node as complete.
5940     alloc = AllocateNode::Ideal_allocation(alloc_obj);
5941     // The object was just allocated - there should be no any stores!
5942     guarantee(alloc != nullptr && alloc->maybe_set_complete(&_gvn), "");
5943     // Mark as complete_with_arraycopy so that on AllocateNode
5944     // expansion, we know this AllocateNode is initialized by an array
5945     // copy and a StoreStore barrier exists after the array copy.
5946     alloc->initialization()->set_complete_with_arraycopy();
5947   }
5948 
5949   Node* size = _gvn.transform(obj_size);
5950   access_clone(obj, alloc_obj, size, is_array);
5951 
5952   // Do not let reads from the cloned object float above the arraycopy.
5953   if (alloc != nullptr) {
5954     // Do not let stores that initialize this object be reordered with
5955     // a subsequent store that would make this object accessible by
5956     // other threads.
5957     // Record what AllocateNode this StoreStore protects so that
5958     // escape analysis can go from the MemBarStoreStoreNode to the
5959     // AllocateNode and eliminate the MemBarStoreStoreNode if possible
5960     // based on the escape status of the AllocateNode.
5961     insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
5962   } else {
5963     insert_mem_bar(Op_MemBarCPUOrder);
5964   }
5965 }
5966 
5967 //------------------------inline_native_clone----------------------------
5968 // protected native Object java.lang.Object.clone();
5969 //
5970 // Here are the simple edge cases:
5971 //  null receiver => normal trap
5972 //  virtual and clone was overridden => slow path to out-of-line clone
5973 //  not cloneable or finalizer => slow path to out-of-line Object.clone
5974 //
5975 // The general case has two steps, allocation and copying.
5976 // Allocation has two cases, and uses GraphKit::new_instance or new_array.
5977 //
5978 // Copying also has two cases, oop arrays and everything else.
5979 // Oop arrays use arrayof_oop_arraycopy (same as System.arraycopy).
5980 // Everything else uses the tight inline loop supplied by CopyArrayNode.
5981 //
5982 // These steps fold up nicely if and when the cloned object's klass
5983 // can be sharply typed as an object array, a type array, or an instance.
5984 //
5985 bool LibraryCallKit::inline_native_clone(bool is_virtual) {
5986   PhiNode* result_val;
5987 
5988   // Set the reexecute bit for the interpreter to reexecute
5989   // the bytecode that invokes Object.clone if deoptimization happens.
5990   { PreserveReexecuteState preexecs(this);
5991     jvms()->set_should_reexecute(true);
5992 
5993     Node* obj = argument(0);
5994     obj = null_check_receiver();
5995     if (stopped())  return true;
5996 
5997     const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
5998     if (obj_type->is_inlinetypeptr()) {
5999       // If the object to clone is an inline type, we can simply return it (i.e. a nop) since inline types have
6000       // no identity.
6001       set_result(obj);
6002       return true;
6003     }
6004 
6005     // If we are going to clone an instance, we need its exact type to
6006     // know the number and types of fields to convert the clone to
6007     // loads/stores. Maybe a speculative type can help us.
6008     if (!obj_type->klass_is_exact() &&
6009         obj_type->speculative_type() != nullptr &&
6010         obj_type->speculative_type()->is_instance_klass() &&
6011         !obj_type->speculative_type()->is_inlinetype()) {
6012       ciInstanceKlass* spec_ik = obj_type->speculative_type()->as_instance_klass();
6013       if (spec_ik->nof_nonstatic_fields() <= ArrayCopyLoadStoreMaxElem &&
6014           !spec_ik->has_injected_fields()) {
6015         if (!obj_type->isa_instptr() ||
6016             obj_type->is_instptr()->instance_klass()->has_subklass()) {
6017           obj = maybe_cast_profiled_obj(obj, obj_type->speculative_type(), false);
6018         }
6019       }
6020     }
6021 
6022     // Conservatively insert a memory barrier on all memory slices.
6023     // Do not let writes into the original float below the clone.
6024     insert_mem_bar(Op_MemBarCPUOrder);
6025 
6026     // paths into result_reg:
6027     enum {
6028       _slow_path = 1,     // out-of-line call to clone method (virtual or not)
6029       _objArray_path,     // plain array allocation, plus arrayof_oop_arraycopy
6030       _array_path,        // plain array allocation, plus arrayof_long_arraycopy
6031       _instance_path,     // plain instance allocation, plus arrayof_long_arraycopy
6032       PATH_LIMIT
6033     };
6034     RegionNode* result_reg = new RegionNode(PATH_LIMIT);
6035     result_val             = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
6036     PhiNode*    result_i_o = new PhiNode(result_reg, Type::ABIO);
6037     PhiNode*    result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
6038     record_for_igvn(result_reg);
6039 
6040     Node* obj_klass = load_object_klass(obj);
6041     // We only go to the fast case code if we pass a number of guards.
6042     // The paths which do not pass are accumulated in the slow_region.
6043     RegionNode* slow_region = new RegionNode(1);
6044     record_for_igvn(slow_region);
6045 
6046     Node* array_obj = obj;
6047     Node* array_ctl = generate_array_guard(obj_klass, (RegionNode*)nullptr, &array_obj);
6048     if (array_ctl != nullptr) {
6049       // It's an array.
6050       PreserveJVMState pjvms(this);
6051       set_control(array_ctl);
6052 
6053       BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
6054       const TypeAryPtr* ary_ptr = obj_type->isa_aryptr();
6055       if (UseArrayFlattening && bs->array_copy_requires_gc_barriers(true, T_OBJECT, true, false, BarrierSetC2::Expansion) &&
6056           obj_type->can_be_inline_array() &&
6057           (ary_ptr == nullptr || (!ary_ptr->is_not_flat() && (!ary_ptr->is_flat() || ary_ptr->elem()->inline_klass()->contains_oops())))) {
6058         // Flat inline type array may have object field that would require a
6059         // write barrier. Conservatively, go to slow path.
6060         generate_fair_guard(flat_array_test(obj_klass), slow_region);
6061       }
6062 
6063       if (!stopped()) {
6064         Node* obj_length = load_array_length(array_obj);
6065         Node* array_size = nullptr; // Size of the array without object alignment padding.
6066         Node* alloc_obj = new_array(obj_klass, obj_length, 0, &array_size, /*deoptimize_on_exception=*/true);
6067 
6068         BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
6069         if (bs->array_copy_requires_gc_barriers(true, T_OBJECT, true, false, BarrierSetC2::Parsing)) {
6070           // If it is an oop array, it requires very special treatment,
6071           // because gc barriers are required when accessing the array.
6072           Node* is_obja = generate_refArray_guard(obj_klass, (RegionNode*)nullptr);
6073           if (is_obja != nullptr) {
6074             PreserveJVMState pjvms2(this);
6075             set_control(is_obja);
6076             // Generate a direct call to the right arraycopy function(s).
6077             // Clones are always tightly coupled.
6078             ArrayCopyNode* ac = ArrayCopyNode::make(this, true, array_obj, intcon(0), alloc_obj, intcon(0), obj_length, true, false);
6079             ac->set_clone_oop_array();
6080             Node* n = _gvn.transform(ac);
6081             assert(n == ac, "cannot disappear");
6082             ac->connect_outputs(this, /*deoptimize_on_exception=*/true);
6083 
6084             result_reg->init_req(_objArray_path, control());
6085             result_val->init_req(_objArray_path, alloc_obj);
6086             result_i_o ->set_req(_objArray_path, i_o());
6087             result_mem ->set_req(_objArray_path, reset_memory());
6088           }
6089         }
6090         // Otherwise, there are no barriers to worry about.
6091         // (We can dispense with card marks if we know the allocation
6092         //  comes out of eden (TLAB)...  In fact, ReduceInitialCardMarks
6093         //  causes the non-eden paths to take compensating steps to
6094         //  simulate a fresh allocation, so that no further
6095         //  card marks are required in compiled code to initialize
6096         //  the object.)
6097 
6098         if (!stopped()) {
6099           copy_to_clone(obj, alloc_obj, array_size, true);
6100 
6101           // Present the results of the copy.
6102           result_reg->init_req(_array_path, control());
6103           result_val->init_req(_array_path, alloc_obj);
6104           result_i_o ->set_req(_array_path, i_o());
6105           result_mem ->set_req(_array_path, reset_memory());
6106         }
6107       }
6108     }
6109 
6110     if (!stopped()) {
6111       // It's an instance (we did array above).  Make the slow-path tests.
6112       // If this is a virtual call, we generate a funny guard.  We grab
6113       // the vtable entry corresponding to clone() from the target object.
6114       // If the target method which we are calling happens to be the
6115       // Object clone() method, we pass the guard.  We do not need this
6116       // guard for non-virtual calls; the caller is known to be the native
6117       // Object clone().
6118       if (is_virtual) {
6119         generate_virtual_guard(obj_klass, slow_region);
6120       }
6121 
6122       // The object must be easily cloneable and must not have a finalizer.
6123       // Both of these conditions may be checked in a single test.
6124       // We could optimize the test further, but we don't care.
6125       generate_misc_flags_guard(obj_klass,
6126                                 // Test both conditions:
6127                                 KlassFlags::_misc_is_cloneable_fast | KlassFlags::_misc_has_finalizer,
6128                                 // Must be cloneable but not finalizer:
6129                                 KlassFlags::_misc_is_cloneable_fast,
6130                                 slow_region);
6131     }
6132 
6133     if (!stopped()) {
6134       // It's an instance, and it passed the slow-path tests.
6135       PreserveJVMState pjvms(this);
6136       Node* obj_size = nullptr; // Total object size, including object alignment padding.
6137       // Need to deoptimize on exception from allocation since Object.clone intrinsic
6138       // is reexecuted if deoptimization occurs and there could be problems when merging
6139       // exception state between multiple Object.clone versions (reexecute=true vs reexecute=false).
6140       Node* alloc_obj = new_instance(obj_klass, nullptr, &obj_size, /*deoptimize_on_exception=*/true);
6141 
6142       copy_to_clone(obj, alloc_obj, obj_size, false);
6143 
6144       // Present the results of the slow call.
6145       result_reg->init_req(_instance_path, control());
6146       result_val->init_req(_instance_path, alloc_obj);
6147       result_i_o ->set_req(_instance_path, i_o());
6148       result_mem ->set_req(_instance_path, reset_memory());
6149     }
6150 
6151     // Generate code for the slow case.  We make a call to clone().
6152     set_control(_gvn.transform(slow_region));
6153     if (!stopped()) {
6154       PreserveJVMState pjvms(this);
6155       CallJavaNode* slow_call = generate_method_call(vmIntrinsics::_clone, is_virtual, false, true);
6156       // We need to deoptimize on exception (see comment above)
6157       Node* slow_result = set_results_for_java_call(slow_call, false, /* deoptimize */ true);
6158       // this->control() comes from set_results_for_java_call
6159       result_reg->init_req(_slow_path, control());
6160       result_val->init_req(_slow_path, slow_result);
6161       result_i_o ->set_req(_slow_path, i_o());
6162       result_mem ->set_req(_slow_path, reset_memory());
6163     }
6164 
6165     // Return the combined state.
6166     set_control(    _gvn.transform(result_reg));
6167     set_i_o(        _gvn.transform(result_i_o));
6168     set_all_memory( _gvn.transform(result_mem));
6169   } // original reexecute is set back here
6170 
6171   set_result(_gvn.transform(result_val));
6172   return true;
6173 }
6174 
6175 // If we have a tightly coupled allocation, the arraycopy may take care
6176 // of the array initialization. If one of the guards we insert between
6177 // the allocation and the arraycopy causes a deoptimization, an
6178 // uninitialized array will escape the compiled method. To prevent that
6179 // we set the JVM state for uncommon traps between the allocation and
6180 // the arraycopy to the state before the allocation so, in case of
6181 // deoptimization, we'll reexecute the allocation and the
6182 // initialization.
6183 JVMState* LibraryCallKit::arraycopy_restore_alloc_state(AllocateArrayNode* alloc, int& saved_reexecute_sp) {
6184   if (alloc != nullptr) {
6185     ciMethod* trap_method = alloc->jvms()->method();
6186     int trap_bci = alloc->jvms()->bci();
6187 
6188     if (!C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_intrinsic) &&
6189         !C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_null_check)) {
6190       // Make sure there's no store between the allocation and the
6191       // arraycopy otherwise visible side effects could be rexecuted
6192       // in case of deoptimization and cause incorrect execution.
6193       bool no_interfering_store = true;
6194       Node* mem = alloc->in(TypeFunc::Memory);
6195       if (mem->is_MergeMem()) {
6196         for (MergeMemStream mms(merged_memory(), mem->as_MergeMem()); mms.next_non_empty2(); ) {
6197           Node* n = mms.memory();
6198           if (n != mms.memory2() && !(n->is_Proj() && n->in(0) == alloc->initialization())) {
6199             assert(n->is_Store(), "what else?");
6200             no_interfering_store = false;
6201             break;
6202           }
6203         }
6204       } else {
6205         for (MergeMemStream mms(merged_memory()); mms.next_non_empty(); ) {
6206           Node* n = mms.memory();
6207           if (n != mem && !(n->is_Proj() && n->in(0) == alloc->initialization())) {
6208             assert(n->is_Store(), "what else?");
6209             no_interfering_store = false;
6210             break;
6211           }
6212         }
6213       }
6214 
6215       if (no_interfering_store) {
6216         SafePointNode* sfpt = create_safepoint_with_state_before_array_allocation(alloc);
6217 
6218         JVMState* saved_jvms = jvms();
6219         saved_reexecute_sp = _reexecute_sp;
6220 
6221         set_jvms(sfpt->jvms());
6222         _reexecute_sp = jvms()->sp();
6223 
6224         return saved_jvms;
6225       }
6226     }
6227   }
6228   return nullptr;
6229 }
6230 
6231 // Clone the JVMState of the array allocation and create a new safepoint with it. Re-push the array length to the stack
6232 // such that uncommon traps can be emitted to re-execute the array allocation in the interpreter.
6233 SafePointNode* LibraryCallKit::create_safepoint_with_state_before_array_allocation(const AllocateArrayNode* alloc) const {
6234   JVMState* old_jvms = alloc->jvms()->clone_shallow(C);
6235   uint size = alloc->req();
6236   SafePointNode* sfpt = new SafePointNode(size, old_jvms);
6237   old_jvms->set_map(sfpt);
6238   for (uint i = 0; i < size; i++) {
6239     sfpt->init_req(i, alloc->in(i));
6240   }
6241   int adjustment = 1;
6242   const TypeAryKlassPtr* ary_klass_ptr = alloc->in(AllocateNode::KlassNode)->bottom_type()->is_aryklassptr();
6243   if (ary_klass_ptr->is_null_free()) {
6244     // A null-free, tightly coupled array allocation can only come from LibraryCallKit::inline_newArray which
6245     // also requires the componentType and initVal on stack for re-execution.
6246     // Re-create and push the componentType.
6247     ciArrayKlass* klass = ary_klass_ptr->exact_klass()->as_array_klass();
6248     ciInstance* instance = klass->component_mirror_instance();
6249     const TypeInstPtr* t_instance = TypeInstPtr::make(instance);
6250     sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp(), makecon(t_instance));
6251     adjustment++;
6252   }
6253   // re-push array length for deoptimization
6254   sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp() + adjustment - 1, alloc->in(AllocateNode::ALength));
6255   if (ary_klass_ptr->is_null_free()) {
6256     // Re-create and push the initVal.
6257     Node* init_val = alloc->in(AllocateNode::InitValue);
6258     if (init_val == nullptr) {
6259       init_val = InlineTypeNode::make_all_zero(_gvn, ary_klass_ptr->elem()->is_instklassptr()->instance_klass()->as_inline_klass());
6260     } else if (UseCompressedOops) {
6261       init_val = _gvn.transform(new DecodeNNode(init_val, init_val->bottom_type()->make_ptr()));
6262     }
6263     sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp() + adjustment, init_val);
6264     adjustment++;
6265   }
6266   old_jvms->set_sp(old_jvms->sp() + adjustment);
6267   old_jvms->set_monoff(old_jvms->monoff() + adjustment);
6268   old_jvms->set_scloff(old_jvms->scloff() + adjustment);
6269   old_jvms->set_endoff(old_jvms->endoff() + adjustment);
6270   old_jvms->set_should_reexecute(true);
6271 
6272   sfpt->set_i_o(map()->i_o());
6273   sfpt->set_memory(map()->memory());
6274   sfpt->set_control(map()->control());
6275   return sfpt;
6276 }
6277 
6278 // In case of a deoptimization, we restart execution at the
6279 // allocation, allocating a new array. We would leave an uninitialized
6280 // array in the heap that GCs wouldn't expect. Move the allocation
6281 // after the traps so we don't allocate the array if we
6282 // deoptimize. This is possible because tightly_coupled_allocation()
6283 // guarantees there's no observer of the allocated array at this point
6284 // and the control flow is simple enough.
6285 void LibraryCallKit::arraycopy_move_allocation_here(AllocateArrayNode* alloc, Node* dest, JVMState* saved_jvms_before_guards,
6286                                                     int saved_reexecute_sp, uint new_idx) {
6287   if (saved_jvms_before_guards != nullptr && !stopped()) {
6288     replace_unrelated_uncommon_traps_with_alloc_state(alloc, saved_jvms_before_guards);
6289 
6290     assert(alloc != nullptr, "only with a tightly coupled allocation");
6291     // restore JVM state to the state at the arraycopy
6292     saved_jvms_before_guards->map()->set_control(map()->control());
6293     assert(saved_jvms_before_guards->map()->memory() == map()->memory(), "memory state changed?");
6294     assert(saved_jvms_before_guards->map()->i_o() == map()->i_o(), "IO state changed?");
6295     // If we've improved the types of some nodes (null check) while
6296     // emitting the guards, propagate them to the current state
6297     map()->replaced_nodes().apply(saved_jvms_before_guards->map(), new_idx);
6298     set_jvms(saved_jvms_before_guards);
6299     _reexecute_sp = saved_reexecute_sp;
6300 
6301     // Remove the allocation from above the guards
6302     CallProjections* callprojs = alloc->extract_projections(true);
6303     InitializeNode* init = alloc->initialization();
6304     Node* alloc_mem = alloc->in(TypeFunc::Memory);
6305     C->gvn_replace_by(callprojs->fallthrough_ioproj, alloc->in(TypeFunc::I_O));
6306     init->replace_mem_projs_by(alloc_mem, C);
6307 
6308     // The CastIINode created in GraphKit::new_array (in AllocateArrayNode::make_ideal_length) must stay below
6309     // the allocation (i.e. is only valid if the allocation succeeds):
6310     // 1) replace CastIINode with AllocateArrayNode's length here
6311     // 2) Create CastIINode again once allocation has moved (see below) at the end of this method
6312     //
6313     // Multiple identical CastIINodes might exist here. Each GraphKit::load_array_length() call will generate
6314     // new separate CastIINode (arraycopy guard checks or any array length use between array allocation and ararycopy)
6315     Node* init_control = init->proj_out(TypeFunc::Control);
6316     Node* alloc_length = alloc->Ideal_length();
6317 #ifdef ASSERT
6318     Node* prev_cast = nullptr;
6319 #endif
6320     for (uint i = 0; i < init_control->outcnt(); i++) {
6321       Node* init_out = init_control->raw_out(i);
6322       if (init_out->is_CastII() && init_out->in(TypeFunc::Control) == init_control && init_out->in(1) == alloc_length) {
6323 #ifdef ASSERT
6324         if (prev_cast == nullptr) {
6325           prev_cast = init_out;
6326         } else {
6327           if (prev_cast->cmp(*init_out) == false) {
6328             prev_cast->dump();
6329             init_out->dump();
6330             assert(false, "not equal CastIINode");
6331           }
6332         }
6333 #endif
6334         C->gvn_replace_by(init_out, alloc_length);
6335       }
6336     }
6337     C->gvn_replace_by(init->proj_out(TypeFunc::Control), alloc->in(0));
6338 
6339     // move the allocation here (after the guards)
6340     _gvn.hash_delete(alloc);
6341     alloc->set_req(TypeFunc::Control, control());
6342     alloc->set_req(TypeFunc::I_O, i_o());
6343     Node *mem = reset_memory();
6344     set_all_memory(mem);
6345     alloc->set_req(TypeFunc::Memory, mem);
6346     set_control(init->proj_out_or_null(TypeFunc::Control));
6347     set_i_o(callprojs->fallthrough_ioproj);
6348 
6349     // Update memory as done in GraphKit::set_output_for_allocation()
6350     const TypeInt* length_type = _gvn.find_int_type(alloc->in(AllocateNode::ALength));
6351     const TypeOopPtr* ary_type = _gvn.type(alloc->in(AllocateNode::KlassNode))->is_klassptr()->as_instance_type();
6352     if (ary_type->isa_aryptr() && length_type != nullptr) {
6353       ary_type = ary_type->is_aryptr()->cast_to_size(length_type);
6354     }
6355     const TypePtr* telemref = ary_type->add_offset(Type::OffsetBot);
6356     int            elemidx  = C->get_alias_index(telemref);
6357     // Need to properly move every memory projection for the Initialize
6358 #ifdef ASSERT
6359     int mark_idx = C->get_alias_index(ary_type->add_offset(oopDesc::mark_offset_in_bytes()));
6360     int klass_idx = C->get_alias_index(ary_type->add_offset(oopDesc::klass_offset_in_bytes()));
6361 #endif
6362     auto move_proj = [&](ProjNode* proj) {
6363       int alias_idx = C->get_alias_index(proj->adr_type());
6364       assert(alias_idx == Compile::AliasIdxRaw ||
6365              alias_idx == elemidx ||
6366              alias_idx == mark_idx ||
6367              alias_idx == klass_idx, "should be raw memory or array element type");
6368       set_memory(proj, alias_idx);
6369     };
6370     init->for_each_proj(move_proj, TypeFunc::Memory);
6371 
6372     Node* allocx = _gvn.transform(alloc);
6373     assert(allocx == alloc, "where has the allocation gone?");
6374     assert(dest->is_CheckCastPP(), "not an allocation result?");
6375 
6376     _gvn.hash_delete(dest);
6377     dest->set_req(0, control());
6378     Node* destx = _gvn.transform(dest);
6379     assert(destx == dest, "where has the allocation result gone?");
6380 
6381     array_ideal_length(alloc, ary_type, true);
6382   }
6383 }
6384 
6385 // Unrelated UCTs between the array allocation and the array copy, which are considered safe by tightly_coupled_allocation(),
6386 // need to be replaced by an UCT with a state before the array allocation (including the array length). This is necessary
6387 // because we could hit one of these UCTs (which are executed before the emitted array copy guards and the actual array
6388 // allocation which is moved down in arraycopy_move_allocation_here()). When later resuming execution in the interpreter,
6389 // we would have wrongly skipped the array allocation. To prevent this, we resume execution at the array allocation in
6390 // the interpreter similar to what we are doing for the newly emitted guards for the array copy.
6391 void LibraryCallKit::replace_unrelated_uncommon_traps_with_alloc_state(AllocateArrayNode* alloc,
6392                                                                        JVMState* saved_jvms_before_guards) {
6393   if (saved_jvms_before_guards->map()->control()->is_IfProj()) {
6394     // There is at least one unrelated uncommon trap which needs to be replaced.
6395     SafePointNode* sfpt = create_safepoint_with_state_before_array_allocation(alloc);
6396 
6397     JVMState* saved_jvms = jvms();
6398     const int saved_reexecute_sp = _reexecute_sp;
6399     set_jvms(sfpt->jvms());
6400     _reexecute_sp = jvms()->sp();
6401 
6402     replace_unrelated_uncommon_traps_with_alloc_state(saved_jvms_before_guards);
6403 
6404     // Restore state
6405     set_jvms(saved_jvms);
6406     _reexecute_sp = saved_reexecute_sp;
6407   }
6408 }
6409 
6410 // Replace the unrelated uncommon traps with new uncommon trap nodes by reusing the action and reason. The new uncommon
6411 // traps will have the state of the array allocation. Let the old uncommon trap nodes die.
6412 void LibraryCallKit::replace_unrelated_uncommon_traps_with_alloc_state(JVMState* saved_jvms_before_guards) {
6413   Node* if_proj = saved_jvms_before_guards->map()->control(); // Start the search right before the newly emitted guards
6414   while (if_proj->is_IfProj()) {
6415     CallStaticJavaNode* uncommon_trap = get_uncommon_trap_from_success_proj(if_proj);
6416     if (uncommon_trap != nullptr) {
6417       create_new_uncommon_trap(uncommon_trap);
6418     }
6419     assert(if_proj->in(0)->is_If(), "must be If");
6420     if_proj = if_proj->in(0)->in(0);
6421   }
6422   assert(if_proj->is_Proj() && if_proj->in(0)->is_Initialize(),
6423          "must have reached control projection of init node");
6424 }
6425 
6426 void LibraryCallKit::create_new_uncommon_trap(CallStaticJavaNode* uncommon_trap_call) {
6427   const int trap_request = uncommon_trap_call->uncommon_trap_request();
6428   assert(trap_request != 0, "no valid UCT trap request");
6429   PreserveJVMState pjvms(this);
6430   set_control(uncommon_trap_call->in(0));
6431   uncommon_trap(Deoptimization::trap_request_reason(trap_request),
6432                 Deoptimization::trap_request_action(trap_request));
6433   assert(stopped(), "Should be stopped");
6434   _gvn.hash_delete(uncommon_trap_call);
6435   uncommon_trap_call->set_req(0, top()); // not used anymore, kill it
6436 }
6437 
6438 // Common checks for array sorting intrinsics arguments.
6439 // Returns `true` if checks passed.
6440 bool LibraryCallKit::check_array_sort_arguments(Node* elementType, Node* obj, BasicType& bt) {
6441   // check address of the class
6442   if (elementType == nullptr || elementType->is_top()) {
6443     return false;  // dead path
6444   }
6445   const TypeInstPtr* elem_klass = gvn().type(elementType)->isa_instptr();
6446   if (elem_klass == nullptr) {
6447     return false;  // dead path
6448   }
6449   // java_mirror_type() returns non-null for compile-time Class constants only
6450   ciType* elem_type = elem_klass->java_mirror_type();
6451   if (elem_type == nullptr) {
6452     return false;
6453   }
6454   bt = elem_type->basic_type();
6455   // Disable the intrinsic if the CPU does not support SIMD sort
6456   if (!Matcher::supports_simd_sort(bt)) {
6457     return false;
6458   }
6459   // check address of the array
6460   if (obj == nullptr || obj->is_top()) {
6461     return false;  // dead path
6462   }
6463   const TypeAryPtr* obj_t = _gvn.type(obj)->isa_aryptr();
6464   if (obj_t == nullptr || obj_t->elem() == Type::BOTTOM) {
6465     return false; // failed input validation
6466   }
6467   return true;
6468 }
6469 
6470 //------------------------------inline_array_partition-----------------------
6471 bool LibraryCallKit::inline_array_partition() {
6472   address stubAddr = StubRoutines::select_array_partition_function();
6473   if (stubAddr == nullptr) {
6474     return false; // Intrinsic's stub is not implemented on this platform
6475   }
6476   assert(callee()->signature()->size() == 9, "arrayPartition has 8 parameters (one long)");
6477 
6478   // no receiver because it is a static method
6479   Node* elementType     = argument(0);
6480   Node* obj             = argument(1);
6481   Node* offset          = argument(2); // long
6482   Node* fromIndex       = argument(4);
6483   Node* toIndex         = argument(5);
6484   Node* indexPivot1     = argument(6);
6485   Node* indexPivot2     = argument(7);
6486   // PartitionOperation:  argument(8) is ignored
6487 
6488   Node* pivotIndices = nullptr;
6489   BasicType bt = T_ILLEGAL;
6490 
6491   if (!check_array_sort_arguments(elementType, obj, bt)) {
6492     return false;
6493   }
6494   null_check(obj);
6495   // If obj is dead, only null-path is taken.
6496   if (stopped()) {
6497     return true;
6498   }
6499   // Set the original stack and the reexecute bit for the interpreter to reexecute
6500   // the bytecode that invokes DualPivotQuicksort.partition() if deoptimization happens.
6501   { PreserveReexecuteState preexecs(this);
6502     jvms()->set_should_reexecute(true);
6503 
6504     Node* obj_adr = make_unsafe_address(obj, offset);
6505 
6506     // create the pivotIndices array of type int and size = 2
6507     Node* size = intcon(2);
6508     Node* klass_node = makecon(TypeKlassPtr::make(ciTypeArrayKlass::make(T_INT)));
6509     pivotIndices = new_array(klass_node, size, 0);  // no arguments to push
6510     AllocateArrayNode* alloc = tightly_coupled_allocation(pivotIndices);
6511     guarantee(alloc != nullptr, "created above");
6512     Node* pivotIndices_adr = basic_plus_adr(pivotIndices, arrayOopDesc::base_offset_in_bytes(T_INT));
6513 
6514     // pass the basic type enum to the stub
6515     Node* elemType = intcon(bt);
6516 
6517     // Call the stub
6518     const char *stubName = "array_partition_stub";
6519     make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::array_partition_Type(),
6520                       stubAddr, stubName, TypePtr::BOTTOM,
6521                       obj_adr, elemType, fromIndex, toIndex, pivotIndices_adr,
6522                       indexPivot1, indexPivot2);
6523 
6524   } // original reexecute is set back here
6525 
6526   if (!stopped()) {
6527     set_result(pivotIndices);
6528   }
6529 
6530   return true;
6531 }
6532 
6533 
6534 //------------------------------inline_array_sort-----------------------
6535 bool LibraryCallKit::inline_array_sort() {
6536   address stubAddr = StubRoutines::select_arraysort_function();
6537   if (stubAddr == nullptr) {
6538     return false; // Intrinsic's stub is not implemented on this platform
6539   }
6540   assert(callee()->signature()->size() == 7, "arraySort has 6 parameters (one long)");
6541 
6542   // no receiver because it is a static method
6543   Node* elementType     = argument(0);
6544   Node* obj             = argument(1);
6545   Node* offset          = argument(2); // long
6546   Node* fromIndex       = argument(4);
6547   Node* toIndex         = argument(5);
6548   // SortOperation:       argument(6) is ignored
6549 
6550   BasicType bt = T_ILLEGAL;
6551 
6552   if (!check_array_sort_arguments(elementType, obj, bt)) {
6553     return false;
6554   }
6555   null_check(obj);
6556   // If obj is dead, only null-path is taken.
6557   if (stopped()) {
6558     return true;
6559   }
6560   Node* obj_adr = make_unsafe_address(obj, offset);
6561 
6562   // pass the basic type enum to the stub
6563   Node* elemType = intcon(bt);
6564 
6565   // Call the stub.
6566   const char *stubName = "arraysort_stub";
6567   make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::array_sort_Type(),
6568                     stubAddr, stubName, TypePtr::BOTTOM,
6569                     obj_adr, elemType, fromIndex, toIndex);
6570 
6571   return true;
6572 }
6573 
6574 
6575 //------------------------------inline_arraycopy-----------------------
6576 // public static native void java.lang.System.arraycopy(Object src,  int  srcPos,
6577 //                                                      Object dest, int destPos,
6578 //                                                      int length);
6579 bool LibraryCallKit::inline_arraycopy() {
6580   // Get the arguments.
6581   Node* src         = argument(0);  // type: oop
6582   Node* src_offset  = argument(1);  // type: int
6583   Node* dest        = argument(2);  // type: oop
6584   Node* dest_offset = argument(3);  // type: int
6585   Node* length      = argument(4);  // type: int
6586 
6587   uint new_idx = C->unique();
6588 
6589   // Check for allocation before we add nodes that would confuse
6590   // tightly_coupled_allocation()
6591   AllocateArrayNode* alloc = tightly_coupled_allocation(dest);
6592 
6593   int saved_reexecute_sp = -1;
6594   JVMState* saved_jvms_before_guards = arraycopy_restore_alloc_state(alloc, saved_reexecute_sp);
6595   // See arraycopy_restore_alloc_state() comment
6596   // if alloc == null we don't have to worry about a tightly coupled allocation so we can emit all needed guards
6597   // if saved_jvms_before_guards is not null (then alloc is not null) then we can handle guards and a tightly coupled allocation
6598   // if saved_jvms_before_guards is null and alloc is not null, we can't emit any guards
6599   bool can_emit_guards = (alloc == nullptr || saved_jvms_before_guards != nullptr);
6600 
6601   // The following tests must be performed
6602   // (1) src and dest are arrays.
6603   // (2) src and dest arrays must have elements of the same BasicType
6604   // (3) src and dest must not be null.
6605   // (4) src_offset must not be negative.
6606   // (5) dest_offset must not be negative.
6607   // (6) length must not be negative.
6608   // (7) src_offset + length must not exceed length of src.
6609   // (8) dest_offset + length must not exceed length of dest.
6610   // (9) each element of an oop array must be assignable
6611 
6612   // (3) src and dest must not be null.
6613   // always do this here because we need the JVM state for uncommon traps
6614   Node* null_ctl = top();
6615   src  = saved_jvms_before_guards != nullptr ? null_check_oop(src, &null_ctl, true, true) : null_check(src, T_ARRAY);
6616   assert(null_ctl->is_top(), "no null control here");
6617   dest = null_check(dest, T_ARRAY);
6618 
6619   if (!can_emit_guards) {
6620     // if saved_jvms_before_guards is null and alloc is not null, we don't emit any
6621     // guards but the arraycopy node could still take advantage of a
6622     // tightly allocated allocation. tightly_coupled_allocation() is
6623     // called again to make sure it takes the null check above into
6624     // account: the null check is mandatory and if it caused an
6625     // uncommon trap to be emitted then the allocation can't be
6626     // considered tightly coupled in this context.
6627     alloc = tightly_coupled_allocation(dest);
6628   }
6629 
6630   bool validated = false;
6631 
6632   const Type* src_type  = _gvn.type(src);
6633   const Type* dest_type = _gvn.type(dest);
6634   const TypeAryPtr* top_src  = src_type->isa_aryptr();
6635   const TypeAryPtr* top_dest = dest_type->isa_aryptr();
6636 
6637   // Do we have the type of src?
6638   bool has_src = (top_src != nullptr && top_src->elem() != Type::BOTTOM);
6639   // Do we have the type of dest?
6640   bool has_dest = (top_dest != nullptr && top_dest->elem() != Type::BOTTOM);
6641   // Is the type for src from speculation?
6642   bool src_spec = false;
6643   // Is the type for dest from speculation?
6644   bool dest_spec = false;
6645 
6646   if ((!has_src || !has_dest) && can_emit_guards) {
6647     // We don't have sufficient type information, let's see if
6648     // speculative types can help. We need to have types for both src
6649     // and dest so that it pays off.
6650 
6651     // Do we already have or could we have type information for src
6652     bool could_have_src = has_src;
6653     // Do we already have or could we have type information for dest
6654     bool could_have_dest = has_dest;
6655 
6656     ciKlass* src_k = nullptr;
6657     if (!has_src) {
6658       src_k = src_type->speculative_type_not_null();
6659       if (src_k != nullptr && src_k->is_array_klass()) {
6660         could_have_src = true;
6661       }
6662     }
6663 
6664     ciKlass* dest_k = nullptr;
6665     if (!has_dest) {
6666       dest_k = dest_type->speculative_type_not_null();
6667       if (dest_k != nullptr && dest_k->is_array_klass()) {
6668         could_have_dest = true;
6669       }
6670     }
6671 
6672     if (could_have_src && could_have_dest) {
6673       // This is going to pay off so emit the required guards
6674       if (!has_src) {
6675         src = maybe_cast_profiled_obj(src, src_k, true);
6676         src_type  = _gvn.type(src);
6677         top_src  = src_type->isa_aryptr();
6678         has_src = (top_src != nullptr && top_src->elem() != Type::BOTTOM);
6679         src_spec = true;
6680       }
6681       if (!has_dest) {
6682         dest = maybe_cast_profiled_obj(dest, dest_k, true);
6683         dest_type  = _gvn.type(dest);
6684         top_dest  = dest_type->isa_aryptr();
6685         has_dest = (top_dest != nullptr && top_dest->elem() != Type::BOTTOM);
6686         dest_spec = true;
6687       }
6688     }
6689   }
6690 
6691   if (has_src && has_dest && can_emit_guards) {
6692     BasicType src_elem = top_src->isa_aryptr()->elem()->array_element_basic_type();
6693     BasicType dest_elem = top_dest->isa_aryptr()->elem()->array_element_basic_type();
6694     if (is_reference_type(src_elem, true)) src_elem = T_OBJECT;
6695     if (is_reference_type(dest_elem, true)) dest_elem = T_OBJECT;
6696 
6697     if (src_elem == dest_elem && top_src->is_flat() == top_dest->is_flat() && src_elem == T_OBJECT) {
6698       // If both arrays are object arrays then having the exact types
6699       // for both will remove the need for a subtype check at runtime
6700       // before the call and may make it possible to pick a faster copy
6701       // routine (without a subtype check on every element)
6702       // Do we have the exact type of src?
6703       bool could_have_src = src_spec;
6704       // Do we have the exact type of dest?
6705       bool could_have_dest = dest_spec;
6706       ciKlass* src_k = nullptr;
6707       ciKlass* dest_k = nullptr;
6708       if (!src_spec) {
6709         src_k = src_type->speculative_type_not_null();
6710         if (src_k != nullptr && src_k->is_array_klass()) {
6711           could_have_src = true;
6712         }
6713       }
6714       if (!dest_spec) {
6715         dest_k = dest_type->speculative_type_not_null();
6716         if (dest_k != nullptr && dest_k->is_array_klass()) {
6717           could_have_dest = true;
6718         }
6719       }
6720       if (could_have_src && could_have_dest) {
6721         // If we can have both exact types, emit the missing guards
6722         if (could_have_src && !src_spec) {
6723           src = maybe_cast_profiled_obj(src, src_k, true);
6724           src_type = _gvn.type(src);
6725           top_src = src_type->isa_aryptr();
6726         }
6727         if (could_have_dest && !dest_spec) {
6728           dest = maybe_cast_profiled_obj(dest, dest_k, true);
6729           dest_type = _gvn.type(dest);
6730           top_dest = dest_type->isa_aryptr();
6731         }
6732       }
6733     }
6734   }
6735 
6736   ciMethod* trap_method = method();
6737   int trap_bci = bci();
6738   if (saved_jvms_before_guards != nullptr) {
6739     trap_method = alloc->jvms()->method();
6740     trap_bci = alloc->jvms()->bci();
6741   }
6742 
6743   bool negative_length_guard_generated = false;
6744 
6745   if (!C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_intrinsic) &&
6746       can_emit_guards && !src->is_top() && !dest->is_top()) {
6747     // validate arguments: enables transformation the ArrayCopyNode
6748     validated = true;
6749 
6750     RegionNode* slow_region = new RegionNode(1);
6751     record_for_igvn(slow_region);
6752 
6753     // (1) src and dest are arrays.
6754     generate_non_array_guard(load_object_klass(src), slow_region, &src);
6755     generate_non_array_guard(load_object_klass(dest), slow_region, &dest);
6756 
6757     // (2) src and dest arrays must have elements of the same BasicType
6758     // done at macro expansion or at Ideal transformation time
6759 
6760     // (4) src_offset must not be negative.
6761     generate_negative_guard(src_offset, slow_region);
6762 
6763     // (5) dest_offset must not be negative.
6764     generate_negative_guard(dest_offset, slow_region);
6765 
6766     // (7) src_offset + length must not exceed length of src.
6767     generate_limit_guard(src_offset, length,
6768                          load_array_length(src),
6769                          slow_region);
6770 
6771     // (8) dest_offset + length must not exceed length of dest.
6772     generate_limit_guard(dest_offset, length,
6773                          load_array_length(dest),
6774                          slow_region);
6775 
6776     // (6) length must not be negative.
6777     // This is also checked in generate_arraycopy() during macro expansion, but
6778     // we also have to check it here for the case where the ArrayCopyNode will
6779     // be eliminated by Escape Analysis.
6780     if (EliminateAllocations) {
6781       generate_negative_guard(length, slow_region);
6782       negative_length_guard_generated = true;
6783     }
6784 
6785     // (9) each element of an oop array must be assignable
6786     Node* dest_klass = load_object_klass(dest);
6787     Node* refined_dest_klass = dest_klass;
6788     if (src != dest) {
6789       dest_klass = load_non_refined_array_klass(refined_dest_klass);
6790       Node* not_subtype_ctrl = gen_subtype_check(src, dest_klass);
6791       slow_region->add_req(not_subtype_ctrl);
6792     }
6793 
6794     // TODO 8350865 Improve this. What about atomicity? Make sure this is always folded for type arrays.
6795     // If destination is null-restricted, source must be null-restricted as well: src_null_restricted || !dst_null_restricted
6796     Node* src_klass = load_object_klass(src);
6797     Node* adr_prop_src = basic_plus_adr(src_klass, in_bytes(ArrayKlass::properties_offset()));
6798     Node* prop_src = _gvn.transform(LoadNode::make(_gvn, control(), immutable_memory(), adr_prop_src, TypeRawPtr::BOTTOM, TypeInt::INT, T_INT, MemNode::unordered));
6799     Node* adr_prop_dest = basic_plus_adr(refined_dest_klass, in_bytes(ArrayKlass::properties_offset()));
6800     Node* prop_dest = _gvn.transform(LoadNode::make(_gvn, control(), immutable_memory(), adr_prop_dest, TypeRawPtr::BOTTOM, TypeInt::INT, T_INT, MemNode::unordered));
6801 
6802     prop_dest = _gvn.transform(new XorINode(prop_dest, intcon(ArrayKlass::ArrayProperties::NULL_RESTRICTED)));
6803     prop_src = _gvn.transform(new OrINode(prop_dest, prop_src));
6804     prop_src = _gvn.transform(new AndINode(prop_src, intcon(ArrayKlass::ArrayProperties::NULL_RESTRICTED)));
6805 
6806     Node* chk = _gvn.transform(new CmpINode(prop_src, intcon(ArrayKlass::ArrayProperties::NULL_RESTRICTED)));
6807     Node* tst = _gvn.transform(new BoolNode(chk, BoolTest::ne));
6808     generate_fair_guard(tst, slow_region);
6809 
6810     // TODO 8350865 This is too strong
6811     generate_fair_guard(flat_array_test(src), slow_region);
6812     generate_fair_guard(flat_array_test(dest), slow_region);
6813 
6814     {
6815       PreserveJVMState pjvms(this);
6816       set_control(_gvn.transform(slow_region));
6817       uncommon_trap(Deoptimization::Reason_intrinsic,
6818                     Deoptimization::Action_make_not_entrant);
6819       assert(stopped(), "Should be stopped");
6820     }
6821 
6822     const TypeKlassPtr* dest_klass_t = _gvn.type(dest_klass)->isa_klassptr();
6823     if (dest_klass_t == nullptr) {
6824       // refined_dest_klass may not be an array, which leads to dest_klass being top. This means we
6825       // are in a dead path.
6826       uncommon_trap(Deoptimization::Reason_intrinsic,
6827                     Deoptimization::Action_make_not_entrant);
6828       return true;
6829     }
6830 
6831     const Type* toop = dest_klass_t->cast_to_exactness(false)->as_instance_type();
6832     src = _gvn.transform(new CheckCastPPNode(control(), src, toop));
6833     arraycopy_move_allocation_here(alloc, dest, saved_jvms_before_guards, saved_reexecute_sp, new_idx);
6834   }
6835 
6836   if (stopped()) {
6837     return true;
6838   }
6839 
6840   Node* dest_klass = load_object_klass(dest);
6841   dest_klass = load_non_refined_array_klass(dest_klass);
6842 
6843   ArrayCopyNode* ac = ArrayCopyNode::make(this, true, src, src_offset, dest, dest_offset, length, alloc != nullptr, negative_length_guard_generated,
6844                                           // Create LoadRange and LoadKlass nodes for use during macro expansion here
6845                                           // so the compiler has a chance to eliminate them: during macro expansion,
6846                                           // we have to set their control (CastPP nodes are eliminated).
6847                                           load_object_klass(src), dest_klass,
6848                                           load_array_length(src), load_array_length(dest));
6849 
6850   ac->set_arraycopy(validated);
6851 
6852   Node* n = _gvn.transform(ac);
6853   if (n == ac) {
6854     ac->connect_outputs(this);
6855   } else {
6856     assert(validated, "shouldn't transform if all arguments not validated");
6857     set_all_memory(n);
6858   }
6859   clear_upper_avx();
6860 
6861 
6862   return true;
6863 }
6864 
6865 
6866 // Helper function which determines if an arraycopy immediately follows
6867 // an allocation, with no intervening tests or other escapes for the object.
6868 AllocateArrayNode*
6869 LibraryCallKit::tightly_coupled_allocation(Node* ptr) {
6870   if (stopped())             return nullptr;  // no fast path
6871   if (!C->do_aliasing())     return nullptr;  // no MergeMems around
6872 
6873   AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(ptr);
6874   if (alloc == nullptr)  return nullptr;
6875 
6876   Node* rawmem = memory(Compile::AliasIdxRaw);
6877   // Is the allocation's memory state untouched?
6878   if (!(rawmem->is_Proj() && rawmem->in(0)->is_Initialize())) {
6879     // Bail out if there have been raw-memory effects since the allocation.
6880     // (Example:  There might have been a call or safepoint.)
6881     return nullptr;
6882   }
6883   rawmem = rawmem->in(0)->as_Initialize()->memory(Compile::AliasIdxRaw);
6884   if (!(rawmem->is_Proj() && rawmem->in(0) == alloc)) {
6885     return nullptr;
6886   }
6887 
6888   // There must be no unexpected observers of this allocation.
6889   for (DUIterator_Fast imax, i = ptr->fast_outs(imax); i < imax; i++) {
6890     Node* obs = ptr->fast_out(i);
6891     if (obs != this->map()) {
6892       return nullptr;
6893     }
6894   }
6895 
6896   // This arraycopy must unconditionally follow the allocation of the ptr.
6897   Node* alloc_ctl = ptr->in(0);
6898   Node* ctl = control();
6899   while (ctl != alloc_ctl) {
6900     // There may be guards which feed into the slow_region.
6901     // Any other control flow means that we might not get a chance
6902     // to finish initializing the allocated object.
6903     // Various low-level checks bottom out in uncommon traps. These
6904     // are considered safe since we've already checked above that
6905     // there is no unexpected observer of this allocation.
6906     if (get_uncommon_trap_from_success_proj(ctl) != nullptr) {
6907       assert(ctl->in(0)->is_If(), "must be If");
6908       ctl = ctl->in(0)->in(0);
6909     } else {
6910       return nullptr;
6911     }
6912   }
6913 
6914   // If we get this far, we have an allocation which immediately
6915   // precedes the arraycopy, and we can take over zeroing the new object.
6916   // The arraycopy will finish the initialization, and provide
6917   // a new control state to which we will anchor the destination pointer.
6918 
6919   return alloc;
6920 }
6921 
6922 CallStaticJavaNode* LibraryCallKit::get_uncommon_trap_from_success_proj(Node* node) {
6923   if (node->is_IfProj()) {
6924     IfProjNode* other_proj = node->as_IfProj()->other_if_proj();
6925     for (DUIterator_Fast jmax, j = other_proj->fast_outs(jmax); j < jmax; j++) {
6926       Node* obs = other_proj->fast_out(j);
6927       if (obs->in(0) == other_proj && obs->is_CallStaticJava() &&
6928           (obs->as_CallStaticJava()->entry_point() == OptoRuntime::uncommon_trap_blob()->entry_point())) {
6929         return obs->as_CallStaticJava();
6930       }
6931     }
6932   }
6933   return nullptr;
6934 }
6935 
6936 //-------------inline_encodeISOArray-----------------------------------
6937 // encode char[] to byte[] in ISO_8859_1 or ASCII
6938 bool LibraryCallKit::inline_encodeISOArray(bool ascii) {
6939   assert(callee()->signature()->size() == 5, "encodeISOArray has 5 parameters");
6940   // no receiver since it is static method
6941   Node *src         = argument(0);
6942   Node *src_offset  = argument(1);
6943   Node *dst         = argument(2);
6944   Node *dst_offset  = argument(3);
6945   Node *length      = argument(4);
6946 
6947   src = must_be_not_null(src, true);
6948   dst = must_be_not_null(dst, true);
6949 
6950   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
6951   const TypeAryPtr* dst_type = dst->Value(&_gvn)->isa_aryptr();
6952   if (src_type == nullptr || src_type->elem() == Type::BOTTOM ||
6953       dst_type == nullptr || dst_type->elem() == Type::BOTTOM) {
6954     // failed array check
6955     return false;
6956   }
6957 
6958   // Figure out the size and type of the elements we will be copying.
6959   BasicType src_elem = src_type->elem()->array_element_basic_type();
6960   BasicType dst_elem = dst_type->elem()->array_element_basic_type();
6961   if (!((src_elem == T_CHAR) || (src_elem== T_BYTE)) || dst_elem != T_BYTE) {
6962     return false;
6963   }
6964 
6965   Node* src_start = array_element_address(src, src_offset, T_CHAR);
6966   Node* dst_start = array_element_address(dst, dst_offset, dst_elem);
6967   // 'src_start' points to src array + scaled offset
6968   // 'dst_start' points to dst array + scaled offset
6969 
6970   const TypeAryPtr* mtype = TypeAryPtr::BYTES;
6971   Node* enc = new EncodeISOArrayNode(control(), memory(mtype), src_start, dst_start, length, ascii);
6972   enc = _gvn.transform(enc);
6973   Node* res_mem = _gvn.transform(new SCMemProjNode(enc));
6974   set_memory(res_mem, mtype);
6975   set_result(enc);
6976   clear_upper_avx();
6977 
6978   return true;
6979 }
6980 
6981 //-------------inline_multiplyToLen-----------------------------------
6982 bool LibraryCallKit::inline_multiplyToLen() {
6983   assert(UseMultiplyToLenIntrinsic, "not implemented on this platform");
6984 
6985   address stubAddr = StubRoutines::multiplyToLen();
6986   if (stubAddr == nullptr) {
6987     return false; // Intrinsic's stub is not implemented on this platform
6988   }
6989   const char* stubName = "multiplyToLen";
6990 
6991   assert(callee()->signature()->size() == 5, "multiplyToLen has 5 parameters");
6992 
6993   // no receiver because it is a static method
6994   Node* x    = argument(0);
6995   Node* xlen = argument(1);
6996   Node* y    = argument(2);
6997   Node* ylen = argument(3);
6998   Node* z    = argument(4);
6999 
7000   x = must_be_not_null(x, true);
7001   y = must_be_not_null(y, true);
7002 
7003   const TypeAryPtr* x_type = x->Value(&_gvn)->isa_aryptr();
7004   const TypeAryPtr* y_type = y->Value(&_gvn)->isa_aryptr();
7005   if (x_type == nullptr || x_type->elem() == Type::BOTTOM ||
7006       y_type == nullptr || y_type->elem() == Type::BOTTOM) {
7007     // failed array check
7008     return false;
7009   }
7010 
7011   BasicType x_elem = x_type->elem()->array_element_basic_type();
7012   BasicType y_elem = y_type->elem()->array_element_basic_type();
7013   if (x_elem != T_INT || y_elem != T_INT) {
7014     return false;
7015   }
7016 
7017   Node* x_start = array_element_address(x, intcon(0), x_elem);
7018   Node* y_start = array_element_address(y, intcon(0), y_elem);
7019   // 'x_start' points to x array + scaled xlen
7020   // 'y_start' points to y array + scaled ylen
7021 
7022   Node* z_start = array_element_address(z, intcon(0), T_INT);
7023 
7024   Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
7025                                  OptoRuntime::multiplyToLen_Type(),
7026                                  stubAddr, stubName, TypePtr::BOTTOM,
7027                                  x_start, xlen, y_start, ylen, z_start);
7028 
7029   C->set_has_split_ifs(true); // Has chance for split-if optimization
7030   set_result(z);
7031   return true;
7032 }
7033 
7034 //-------------inline_squareToLen------------------------------------
7035 bool LibraryCallKit::inline_squareToLen() {
7036   assert(UseSquareToLenIntrinsic, "not implemented on this platform");
7037 
7038   address stubAddr = StubRoutines::squareToLen();
7039   if (stubAddr == nullptr) {
7040     return false; // Intrinsic's stub is not implemented on this platform
7041   }
7042   const char* stubName = "squareToLen";
7043 
7044   assert(callee()->signature()->size() == 4, "implSquareToLen has 4 parameters");
7045 
7046   Node* x    = argument(0);
7047   Node* len  = argument(1);
7048   Node* z    = argument(2);
7049   Node* zlen = argument(3);
7050 
7051   x = must_be_not_null(x, true);
7052   z = must_be_not_null(z, true);
7053 
7054   const TypeAryPtr* x_type = x->Value(&_gvn)->isa_aryptr();
7055   const TypeAryPtr* z_type = z->Value(&_gvn)->isa_aryptr();
7056   if (x_type == nullptr || x_type->elem() == Type::BOTTOM ||
7057       z_type == nullptr || z_type->elem() == Type::BOTTOM) {
7058     // failed array check
7059     return false;
7060   }
7061 
7062   BasicType x_elem = x_type->elem()->array_element_basic_type();
7063   BasicType z_elem = z_type->elem()->array_element_basic_type();
7064   if (x_elem != T_INT || z_elem != T_INT) {
7065     return false;
7066   }
7067 
7068 
7069   Node* x_start = array_element_address(x, intcon(0), x_elem);
7070   Node* z_start = array_element_address(z, intcon(0), z_elem);
7071 
7072   Node*  call = make_runtime_call(RC_LEAF|RC_NO_FP,
7073                                   OptoRuntime::squareToLen_Type(),
7074                                   stubAddr, stubName, TypePtr::BOTTOM,
7075                                   x_start, len, z_start, zlen);
7076 
7077   set_result(z);
7078   return true;
7079 }
7080 
7081 //-------------inline_mulAdd------------------------------------------
7082 bool LibraryCallKit::inline_mulAdd() {
7083   assert(UseMulAddIntrinsic, "not implemented on this platform");
7084 
7085   address stubAddr = StubRoutines::mulAdd();
7086   if (stubAddr == nullptr) {
7087     return false; // Intrinsic's stub is not implemented on this platform
7088   }
7089   const char* stubName = "mulAdd";
7090 
7091   assert(callee()->signature()->size() == 5, "mulAdd has 5 parameters");
7092 
7093   Node* out      = argument(0);
7094   Node* in       = argument(1);
7095   Node* offset   = argument(2);
7096   Node* len      = argument(3);
7097   Node* k        = argument(4);
7098 
7099   in = must_be_not_null(in, true);
7100   out = must_be_not_null(out, true);
7101 
7102   const TypeAryPtr* out_type = out->Value(&_gvn)->isa_aryptr();
7103   const TypeAryPtr* in_type = in->Value(&_gvn)->isa_aryptr();
7104   if (out_type == nullptr || out_type->elem() == Type::BOTTOM ||
7105        in_type == nullptr ||  in_type->elem() == Type::BOTTOM) {
7106     // failed array check
7107     return false;
7108   }
7109 
7110   BasicType out_elem = out_type->elem()->array_element_basic_type();
7111   BasicType in_elem = in_type->elem()->array_element_basic_type();
7112   if (out_elem != T_INT || in_elem != T_INT) {
7113     return false;
7114   }
7115 
7116   Node* outlen = load_array_length(out);
7117   Node* new_offset = _gvn.transform(new SubINode(outlen, offset));
7118   Node* out_start = array_element_address(out, intcon(0), out_elem);
7119   Node* in_start = array_element_address(in, intcon(0), in_elem);
7120 
7121   Node*  call = make_runtime_call(RC_LEAF|RC_NO_FP,
7122                                   OptoRuntime::mulAdd_Type(),
7123                                   stubAddr, stubName, TypePtr::BOTTOM,
7124                                   out_start,in_start, new_offset, len, k);
7125   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7126   set_result(result);
7127   return true;
7128 }
7129 
7130 //-------------inline_montgomeryMultiply-----------------------------------
7131 bool LibraryCallKit::inline_montgomeryMultiply() {
7132   address stubAddr = StubRoutines::montgomeryMultiply();
7133   if (stubAddr == nullptr) {
7134     return false; // Intrinsic's stub is not implemented on this platform
7135   }
7136 
7137   assert(UseMontgomeryMultiplyIntrinsic, "not implemented on this platform");
7138   const char* stubName = "montgomery_multiply";
7139 
7140   assert(callee()->signature()->size() == 7, "montgomeryMultiply has 7 parameters");
7141 
7142   Node* a    = argument(0);
7143   Node* b    = argument(1);
7144   Node* n    = argument(2);
7145   Node* len  = argument(3);
7146   Node* inv  = argument(4);
7147   Node* m    = argument(6);
7148 
7149   const TypeAryPtr* a_type = a->Value(&_gvn)->isa_aryptr();
7150   const TypeAryPtr* b_type = b->Value(&_gvn)->isa_aryptr();
7151   const TypeAryPtr* n_type = n->Value(&_gvn)->isa_aryptr();
7152   const TypeAryPtr* m_type = m->Value(&_gvn)->isa_aryptr();
7153   if (a_type == nullptr || a_type->elem() == Type::BOTTOM ||
7154       b_type == nullptr || b_type->elem() == Type::BOTTOM ||
7155       n_type == nullptr || n_type->elem() == Type::BOTTOM ||
7156       m_type == nullptr || m_type->elem() == Type::BOTTOM) {
7157     // failed array check
7158     return false;
7159   }
7160 
7161   BasicType a_elem = a_type->elem()->array_element_basic_type();
7162   BasicType b_elem = b_type->elem()->array_element_basic_type();
7163   BasicType n_elem = n_type->elem()->array_element_basic_type();
7164   BasicType m_elem = m_type->elem()->array_element_basic_type();
7165   if (a_elem != T_INT || b_elem != T_INT || n_elem != T_INT || m_elem != T_INT) {
7166     return false;
7167   }
7168 
7169   // Make the call
7170   {
7171     Node* a_start = array_element_address(a, intcon(0), a_elem);
7172     Node* b_start = array_element_address(b, intcon(0), b_elem);
7173     Node* n_start = array_element_address(n, intcon(0), n_elem);
7174     Node* m_start = array_element_address(m, intcon(0), m_elem);
7175 
7176     Node* call = make_runtime_call(RC_LEAF,
7177                                    OptoRuntime::montgomeryMultiply_Type(),
7178                                    stubAddr, stubName, TypePtr::BOTTOM,
7179                                    a_start, b_start, n_start, len, inv, top(),
7180                                    m_start);
7181     set_result(m);
7182   }
7183 
7184   return true;
7185 }
7186 
7187 bool LibraryCallKit::inline_montgomerySquare() {
7188   address stubAddr = StubRoutines::montgomerySquare();
7189   if (stubAddr == nullptr) {
7190     return false; // Intrinsic's stub is not implemented on this platform
7191   }
7192 
7193   assert(UseMontgomerySquareIntrinsic, "not implemented on this platform");
7194   const char* stubName = "montgomery_square";
7195 
7196   assert(callee()->signature()->size() == 6, "montgomerySquare has 6 parameters");
7197 
7198   Node* a    = argument(0);
7199   Node* n    = argument(1);
7200   Node* len  = argument(2);
7201   Node* inv  = argument(3);
7202   Node* m    = argument(5);
7203 
7204   const TypeAryPtr* a_type = a->Value(&_gvn)->isa_aryptr();
7205   const TypeAryPtr* n_type = n->Value(&_gvn)->isa_aryptr();
7206   const TypeAryPtr* m_type = m->Value(&_gvn)->isa_aryptr();
7207   if (a_type == nullptr || a_type->elem() == Type::BOTTOM ||
7208       n_type == nullptr || n_type->elem() == Type::BOTTOM ||
7209       m_type == nullptr || m_type->elem() == Type::BOTTOM) {
7210     // failed array check
7211     return false;
7212   }
7213 
7214   BasicType a_elem = a_type->elem()->array_element_basic_type();
7215   BasicType n_elem = n_type->elem()->array_element_basic_type();
7216   BasicType m_elem = m_type->elem()->array_element_basic_type();
7217   if (a_elem != T_INT || n_elem != T_INT || m_elem != T_INT) {
7218     return false;
7219   }
7220 
7221   // Make the call
7222   {
7223     Node* a_start = array_element_address(a, intcon(0), a_elem);
7224     Node* n_start = array_element_address(n, intcon(0), n_elem);
7225     Node* m_start = array_element_address(m, intcon(0), m_elem);
7226 
7227     Node* call = make_runtime_call(RC_LEAF,
7228                                    OptoRuntime::montgomerySquare_Type(),
7229                                    stubAddr, stubName, TypePtr::BOTTOM,
7230                                    a_start, n_start, len, inv, top(),
7231                                    m_start);
7232     set_result(m);
7233   }
7234 
7235   return true;
7236 }
7237 
7238 bool LibraryCallKit::inline_bigIntegerShift(bool isRightShift) {
7239   address stubAddr = nullptr;
7240   const char* stubName = nullptr;
7241 
7242   stubAddr = isRightShift? StubRoutines::bigIntegerRightShift(): StubRoutines::bigIntegerLeftShift();
7243   if (stubAddr == nullptr) {
7244     return false; // Intrinsic's stub is not implemented on this platform
7245   }
7246 
7247   stubName = isRightShift? "bigIntegerRightShiftWorker" : "bigIntegerLeftShiftWorker";
7248 
7249   assert(callee()->signature()->size() == 5, "expected 5 arguments");
7250 
7251   Node* newArr = argument(0);
7252   Node* oldArr = argument(1);
7253   Node* newIdx = argument(2);
7254   Node* shiftCount = argument(3);
7255   Node* numIter = argument(4);
7256 
7257   const TypeAryPtr* newArr_type = newArr->Value(&_gvn)->isa_aryptr();
7258   const TypeAryPtr* oldArr_type = oldArr->Value(&_gvn)->isa_aryptr();
7259   if (newArr_type == nullptr || newArr_type->elem() == Type::BOTTOM ||
7260       oldArr_type == nullptr || oldArr_type->elem() == Type::BOTTOM) {
7261     return false;
7262   }
7263 
7264   BasicType newArr_elem = newArr_type->elem()->array_element_basic_type();
7265   BasicType oldArr_elem = oldArr_type->elem()->array_element_basic_type();
7266   if (newArr_elem != T_INT || oldArr_elem != T_INT) {
7267     return false;
7268   }
7269 
7270   // Make the call
7271   {
7272     Node* newArr_start = array_element_address(newArr, intcon(0), newArr_elem);
7273     Node* oldArr_start = array_element_address(oldArr, intcon(0), oldArr_elem);
7274 
7275     Node* call = make_runtime_call(RC_LEAF,
7276                                    OptoRuntime::bigIntegerShift_Type(),
7277                                    stubAddr,
7278                                    stubName,
7279                                    TypePtr::BOTTOM,
7280                                    newArr_start,
7281                                    oldArr_start,
7282                                    newIdx,
7283                                    shiftCount,
7284                                    numIter);
7285   }
7286 
7287   return true;
7288 }
7289 
7290 //-------------inline_vectorizedMismatch------------------------------
7291 bool LibraryCallKit::inline_vectorizedMismatch() {
7292   assert(UseVectorizedMismatchIntrinsic, "not implemented on this platform");
7293 
7294   assert(callee()->signature()->size() == 8, "vectorizedMismatch has 6 parameters");
7295   Node* obja    = argument(0); // Object
7296   Node* aoffset = argument(1); // long
7297   Node* objb    = argument(3); // Object
7298   Node* boffset = argument(4); // long
7299   Node* length  = argument(6); // int
7300   Node* scale   = argument(7); // int
7301 
7302   const TypeAryPtr* obja_t = _gvn.type(obja)->isa_aryptr();
7303   const TypeAryPtr* objb_t = _gvn.type(objb)->isa_aryptr();
7304   if (obja_t == nullptr || obja_t->elem() == Type::BOTTOM ||
7305       objb_t == nullptr || objb_t->elem() == Type::BOTTOM ||
7306       scale == top()) {
7307     return false; // failed input validation
7308   }
7309 
7310   Node* obja_adr = make_unsafe_address(obja, aoffset);
7311   Node* objb_adr = make_unsafe_address(objb, boffset);
7312 
7313   // Partial inlining handling for inputs smaller than ArrayOperationPartialInlineSize bytes in size.
7314   //
7315   //    inline_limit = ArrayOperationPartialInlineSize / element_size;
7316   //    if (length <= inline_limit) {
7317   //      inline_path:
7318   //        vmask   = VectorMaskGen length
7319   //        vload1  = LoadVectorMasked obja, vmask
7320   //        vload2  = LoadVectorMasked objb, vmask
7321   //        result1 = VectorCmpMasked vload1, vload2, vmask
7322   //    } else {
7323   //      call_stub_path:
7324   //        result2 = call vectorizedMismatch_stub(obja, objb, length, scale)
7325   //    }
7326   //    exit_block:
7327   //      return Phi(result1, result2);
7328   //
7329   enum { inline_path = 1,  // input is small enough to process it all at once
7330          stub_path   = 2,  // input is too large; call into the VM
7331          PATH_LIMIT  = 3
7332   };
7333 
7334   Node* exit_block = new RegionNode(PATH_LIMIT);
7335   Node* result_phi = new PhiNode(exit_block, TypeInt::INT);
7336   Node* memory_phi = new PhiNode(exit_block, Type::MEMORY, TypePtr::BOTTOM);
7337 
7338   Node* call_stub_path = control();
7339 
7340   BasicType elem_bt = T_ILLEGAL;
7341 
7342   const TypeInt* scale_t = _gvn.type(scale)->is_int();
7343   if (scale_t->is_con()) {
7344     switch (scale_t->get_con()) {
7345       case 0: elem_bt = T_BYTE;  break;
7346       case 1: elem_bt = T_SHORT; break;
7347       case 2: elem_bt = T_INT;   break;
7348       case 3: elem_bt = T_LONG;  break;
7349 
7350       default: elem_bt = T_ILLEGAL; break; // not supported
7351     }
7352   }
7353 
7354   int inline_limit = 0;
7355   bool do_partial_inline = false;
7356 
7357   if (elem_bt != T_ILLEGAL && ArrayOperationPartialInlineSize > 0) {
7358     inline_limit = ArrayOperationPartialInlineSize / type2aelembytes(elem_bt);
7359     do_partial_inline = inline_limit >= 16;
7360   }
7361 
7362   if (do_partial_inline) {
7363     assert(elem_bt != T_ILLEGAL, "sanity");
7364 
7365     if (Matcher::match_rule_supported_vector(Op_VectorMaskGen,    inline_limit, elem_bt) &&
7366         Matcher::match_rule_supported_vector(Op_LoadVectorMasked, inline_limit, elem_bt) &&
7367         Matcher::match_rule_supported_vector(Op_VectorCmpMasked,  inline_limit, elem_bt)) {
7368 
7369       const TypeVect* vt = TypeVect::make(elem_bt, inline_limit);
7370       Node* cmp_length = _gvn.transform(new CmpINode(length, intcon(inline_limit)));
7371       Node* bol_gt     = _gvn.transform(new BoolNode(cmp_length, BoolTest::gt));
7372 
7373       call_stub_path = generate_guard(bol_gt, nullptr, PROB_MIN);
7374 
7375       if (!stopped()) {
7376         Node* casted_length = _gvn.transform(new CastIINode(control(), length, TypeInt::make(0, inline_limit, Type::WidenMin)));
7377 
7378         const TypePtr* obja_adr_t = _gvn.type(obja_adr)->isa_ptr();
7379         const TypePtr* objb_adr_t = _gvn.type(objb_adr)->isa_ptr();
7380         Node* obja_adr_mem = memory(C->get_alias_index(obja_adr_t));
7381         Node* objb_adr_mem = memory(C->get_alias_index(objb_adr_t));
7382 
7383         Node* vmask      = _gvn.transform(VectorMaskGenNode::make(ConvI2X(casted_length), elem_bt));
7384         Node* vload_obja = _gvn.transform(new LoadVectorMaskedNode(control(), obja_adr_mem, obja_adr, obja_adr_t, vt, vmask));
7385         Node* vload_objb = _gvn.transform(new LoadVectorMaskedNode(control(), objb_adr_mem, objb_adr, objb_adr_t, vt, vmask));
7386         Node* result     = _gvn.transform(new VectorCmpMaskedNode(vload_obja, vload_objb, vmask, TypeInt::INT));
7387 
7388         exit_block->init_req(inline_path, control());
7389         memory_phi->init_req(inline_path, map()->memory());
7390         result_phi->init_req(inline_path, result);
7391 
7392         C->set_max_vector_size(MAX2((uint)ArrayOperationPartialInlineSize, C->max_vector_size()));
7393         clear_upper_avx();
7394       }
7395     }
7396   }
7397 
7398   if (call_stub_path != nullptr) {
7399     set_control(call_stub_path);
7400 
7401     Node* call = make_runtime_call(RC_LEAF,
7402                                    OptoRuntime::vectorizedMismatch_Type(),
7403                                    StubRoutines::vectorizedMismatch(), "vectorizedMismatch", TypePtr::BOTTOM,
7404                                    obja_adr, objb_adr, length, scale);
7405 
7406     exit_block->init_req(stub_path, control());
7407     memory_phi->init_req(stub_path, map()->memory());
7408     result_phi->init_req(stub_path, _gvn.transform(new ProjNode(call, TypeFunc::Parms)));
7409   }
7410 
7411   exit_block = _gvn.transform(exit_block);
7412   memory_phi = _gvn.transform(memory_phi);
7413   result_phi = _gvn.transform(result_phi);
7414 
7415   record_for_igvn(exit_block);
7416   record_for_igvn(memory_phi);
7417   record_for_igvn(result_phi);
7418 
7419   set_control(exit_block);
7420   set_all_memory(memory_phi);
7421   set_result(result_phi);
7422 
7423   return true;
7424 }
7425 
7426 //------------------------------inline_vectorizedHashcode----------------------------
7427 bool LibraryCallKit::inline_vectorizedHashCode() {
7428   assert(UseVectorizedHashCodeIntrinsic, "not implemented on this platform");
7429 
7430   assert(callee()->signature()->size() == 5, "vectorizedHashCode has 5 parameters");
7431   Node* array          = argument(0);
7432   Node* offset         = argument(1);
7433   Node* length         = argument(2);
7434   Node* initialValue   = argument(3);
7435   Node* basic_type     = argument(4);
7436 
7437   if (basic_type == top()) {
7438     return false; // failed input validation
7439   }
7440 
7441   const TypeInt* basic_type_t = _gvn.type(basic_type)->is_int();
7442   if (!basic_type_t->is_con()) {
7443     return false; // Only intrinsify if mode argument is constant
7444   }
7445 
7446   array = must_be_not_null(array, true);
7447 
7448   BasicType bt = (BasicType)basic_type_t->get_con();
7449 
7450   // Resolve address of first element
7451   Node* array_start = array_element_address(array, offset, bt);
7452 
7453   set_result(_gvn.transform(new VectorizedHashCodeNode(control(), memory(TypeAryPtr::get_array_body_type(bt)),
7454     array_start, length, initialValue, basic_type)));
7455   clear_upper_avx();
7456 
7457   return true;
7458 }
7459 
7460 /**
7461  * Calculate CRC32 for byte.
7462  * int java.util.zip.CRC32.update(int crc, int b)
7463  */
7464 bool LibraryCallKit::inline_updateCRC32() {
7465   assert(UseCRC32Intrinsics, "need AVX and CLMUL instructions support");
7466   assert(callee()->signature()->size() == 2, "update has 2 parameters");
7467   // no receiver since it is static method
7468   Node* crc  = argument(0); // type: int
7469   Node* b    = argument(1); // type: int
7470 
7471   /*
7472    *    int c = ~ crc;
7473    *    b = timesXtoThe32[(b ^ c) & 0xFF];
7474    *    b = b ^ (c >>> 8);
7475    *    crc = ~b;
7476    */
7477 
7478   Node* M1 = intcon(-1);
7479   crc = _gvn.transform(new XorINode(crc, M1));
7480   Node* result = _gvn.transform(new XorINode(crc, b));
7481   result = _gvn.transform(new AndINode(result, intcon(0xFF)));
7482 
7483   Node* base = makecon(TypeRawPtr::make(StubRoutines::crc_table_addr()));
7484   Node* offset = _gvn.transform(new LShiftINode(result, intcon(0x2)));
7485   Node* adr = basic_plus_adr(top(), base, ConvI2X(offset));
7486   result = make_load(control(), adr, TypeInt::INT, T_INT, MemNode::unordered);
7487 
7488   crc = _gvn.transform(new URShiftINode(crc, intcon(8)));
7489   result = _gvn.transform(new XorINode(crc, result));
7490   result = _gvn.transform(new XorINode(result, M1));
7491   set_result(result);
7492   return true;
7493 }
7494 
7495 /**
7496  * Calculate CRC32 for byte[] array.
7497  * int java.util.zip.CRC32.updateBytes(int crc, byte[] buf, int off, int len)
7498  */
7499 bool LibraryCallKit::inline_updateBytesCRC32() {
7500   assert(UseCRC32Intrinsics, "need AVX and CLMUL instructions support");
7501   assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
7502   // no receiver since it is static method
7503   Node* crc     = argument(0); // type: int
7504   Node* src     = argument(1); // type: oop
7505   Node* offset  = argument(2); // type: int
7506   Node* length  = argument(3); // type: int
7507 
7508   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7509   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
7510     // failed array check
7511     return false;
7512   }
7513 
7514   // Figure out the size and type of the elements we will be copying.
7515   BasicType src_elem = src_type->elem()->array_element_basic_type();
7516   if (src_elem != T_BYTE) {
7517     return false;
7518   }
7519 
7520   // 'src_start' points to src array + scaled offset
7521   src = must_be_not_null(src, true);
7522   Node* src_start = array_element_address(src, offset, src_elem);
7523 
7524   // We assume that range check is done by caller.
7525   // TODO: generate range check (offset+length < src.length) in debug VM.
7526 
7527   // Call the stub.
7528   address stubAddr = StubRoutines::updateBytesCRC32();
7529   const char *stubName = "updateBytesCRC32";
7530 
7531   Node* call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::updateBytesCRC32_Type(),
7532                                  stubAddr, stubName, TypePtr::BOTTOM,
7533                                  crc, src_start, length);
7534   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7535   set_result(result);
7536   return true;
7537 }
7538 
7539 /**
7540  * Calculate CRC32 for ByteBuffer.
7541  * int java.util.zip.CRC32.updateByteBuffer(int crc, long buf, int off, int len)
7542  */
7543 bool LibraryCallKit::inline_updateByteBufferCRC32() {
7544   assert(UseCRC32Intrinsics, "need AVX and CLMUL instructions support");
7545   assert(callee()->signature()->size() == 5, "updateByteBuffer has 4 parameters and one is long");
7546   // no receiver since it is static method
7547   Node* crc     = argument(0); // type: int
7548   Node* src     = argument(1); // type: long
7549   Node* offset  = argument(3); // type: int
7550   Node* length  = argument(4); // type: int
7551 
7552   src = ConvL2X(src);  // adjust Java long to machine word
7553   Node* base = _gvn.transform(new CastX2PNode(src));
7554   offset = ConvI2X(offset);
7555 
7556   // 'src_start' points to src array + scaled offset
7557   Node* src_start = basic_plus_adr(top(), base, offset);
7558 
7559   // Call the stub.
7560   address stubAddr = StubRoutines::updateBytesCRC32();
7561   const char *stubName = "updateBytesCRC32";
7562 
7563   Node* call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::updateBytesCRC32_Type(),
7564                                  stubAddr, stubName, TypePtr::BOTTOM,
7565                                  crc, src_start, length);
7566   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7567   set_result(result);
7568   return true;
7569 }
7570 
7571 //------------------------------get_table_from_crc32c_class-----------------------
7572 Node * LibraryCallKit::get_table_from_crc32c_class(ciInstanceKlass *crc32c_class) {
7573   Node* table = load_field_from_object(nullptr, "byteTable", "[I", /*decorators*/ IN_HEAP, /*is_static*/ true, crc32c_class);
7574   assert (table != nullptr, "wrong version of java.util.zip.CRC32C");
7575 
7576   return table;
7577 }
7578 
7579 //------------------------------inline_updateBytesCRC32C-----------------------
7580 //
7581 // Calculate CRC32C for byte[] array.
7582 // int java.util.zip.CRC32C.updateBytes(int crc, byte[] buf, int off, int end)
7583 //
7584 bool LibraryCallKit::inline_updateBytesCRC32C() {
7585   assert(UseCRC32CIntrinsics, "need CRC32C instruction support");
7586   assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
7587   assert(callee()->holder()->is_loaded(), "CRC32C class must be loaded");
7588   // no receiver since it is a static method
7589   Node* crc     = argument(0); // type: int
7590   Node* src     = argument(1); // type: oop
7591   Node* offset  = argument(2); // type: int
7592   Node* end     = argument(3); // type: int
7593 
7594   Node* length = _gvn.transform(new SubINode(end, offset));
7595 
7596   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7597   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
7598     // failed array check
7599     return false;
7600   }
7601 
7602   // Figure out the size and type of the elements we will be copying.
7603   BasicType src_elem = src_type->elem()->array_element_basic_type();
7604   if (src_elem != T_BYTE) {
7605     return false;
7606   }
7607 
7608   // 'src_start' points to src array + scaled offset
7609   src = must_be_not_null(src, true);
7610   Node* src_start = array_element_address(src, offset, src_elem);
7611 
7612   // static final int[] byteTable in class CRC32C
7613   Node* table = get_table_from_crc32c_class(callee()->holder());
7614   table = must_be_not_null(table, true);
7615   Node* table_start = array_element_address(table, intcon(0), T_INT);
7616 
7617   // We assume that range check is done by caller.
7618   // TODO: generate range check (offset+length < src.length) in debug VM.
7619 
7620   // Call the stub.
7621   address stubAddr = StubRoutines::updateBytesCRC32C();
7622   const char *stubName = "updateBytesCRC32C";
7623 
7624   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesCRC32C_Type(),
7625                                  stubAddr, stubName, TypePtr::BOTTOM,
7626                                  crc, src_start, length, table_start);
7627   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7628   set_result(result);
7629   return true;
7630 }
7631 
7632 //------------------------------inline_updateDirectByteBufferCRC32C-----------------------
7633 //
7634 // Calculate CRC32C for DirectByteBuffer.
7635 // int java.util.zip.CRC32C.updateDirectByteBuffer(int crc, long buf, int off, int end)
7636 //
7637 bool LibraryCallKit::inline_updateDirectByteBufferCRC32C() {
7638   assert(UseCRC32CIntrinsics, "need CRC32C instruction support");
7639   assert(callee()->signature()->size() == 5, "updateDirectByteBuffer has 4 parameters and one is long");
7640   assert(callee()->holder()->is_loaded(), "CRC32C class must be loaded");
7641   // no receiver since it is a static method
7642   Node* crc     = argument(0); // type: int
7643   Node* src     = argument(1); // type: long
7644   Node* offset  = argument(3); // type: int
7645   Node* end     = argument(4); // type: int
7646 
7647   Node* length = _gvn.transform(new SubINode(end, offset));
7648 
7649   src = ConvL2X(src);  // adjust Java long to machine word
7650   Node* base = _gvn.transform(new CastX2PNode(src));
7651   offset = ConvI2X(offset);
7652 
7653   // 'src_start' points to src array + scaled offset
7654   Node* src_start = basic_plus_adr(top(), base, offset);
7655 
7656   // static final int[] byteTable in class CRC32C
7657   Node* table = get_table_from_crc32c_class(callee()->holder());
7658   table = must_be_not_null(table, true);
7659   Node* table_start = array_element_address(table, intcon(0), T_INT);
7660 
7661   // Call the stub.
7662   address stubAddr = StubRoutines::updateBytesCRC32C();
7663   const char *stubName = "updateBytesCRC32C";
7664 
7665   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesCRC32C_Type(),
7666                                  stubAddr, stubName, TypePtr::BOTTOM,
7667                                  crc, src_start, length, table_start);
7668   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7669   set_result(result);
7670   return true;
7671 }
7672 
7673 //------------------------------inline_updateBytesAdler32----------------------
7674 //
7675 // Calculate Adler32 checksum for byte[] array.
7676 // int java.util.zip.Adler32.updateBytes(int crc, byte[] buf, int off, int len)
7677 //
7678 bool LibraryCallKit::inline_updateBytesAdler32() {
7679   assert(UseAdler32Intrinsics, "Adler32 Intrinsic support need"); // check if we actually need to check this flag or check a different one
7680   assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
7681   assert(callee()->holder()->is_loaded(), "Adler32 class must be loaded");
7682   // no receiver since it is static method
7683   Node* crc     = argument(0); // type: int
7684   Node* src     = argument(1); // type: oop
7685   Node* offset  = argument(2); // type: int
7686   Node* length  = argument(3); // type: int
7687 
7688   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7689   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
7690     // failed array check
7691     return false;
7692   }
7693 
7694   // Figure out the size and type of the elements we will be copying.
7695   BasicType src_elem = src_type->elem()->array_element_basic_type();
7696   if (src_elem != T_BYTE) {
7697     return false;
7698   }
7699 
7700   // 'src_start' points to src array + scaled offset
7701   Node* src_start = array_element_address(src, offset, src_elem);
7702 
7703   // We assume that range check is done by caller.
7704   // TODO: generate range check (offset+length < src.length) in debug VM.
7705 
7706   // Call the stub.
7707   address stubAddr = StubRoutines::updateBytesAdler32();
7708   const char *stubName = "updateBytesAdler32";
7709 
7710   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesAdler32_Type(),
7711                                  stubAddr, stubName, TypePtr::BOTTOM,
7712                                  crc, src_start, length);
7713   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7714   set_result(result);
7715   return true;
7716 }
7717 
7718 //------------------------------inline_updateByteBufferAdler32---------------
7719 //
7720 // Calculate Adler32 checksum for DirectByteBuffer.
7721 // int java.util.zip.Adler32.updateByteBuffer(int crc, long buf, int off, int len)
7722 //
7723 bool LibraryCallKit::inline_updateByteBufferAdler32() {
7724   assert(UseAdler32Intrinsics, "Adler32 Intrinsic support need"); // check if we actually need to check this flag or check a different one
7725   assert(callee()->signature()->size() == 5, "updateByteBuffer has 4 parameters and one is long");
7726   assert(callee()->holder()->is_loaded(), "Adler32 class must be loaded");
7727   // no receiver since it is static method
7728   Node* crc     = argument(0); // type: int
7729   Node* src     = argument(1); // type: long
7730   Node* offset  = argument(3); // type: int
7731   Node* length  = argument(4); // type: int
7732 
7733   src = ConvL2X(src);  // adjust Java long to machine word
7734   Node* base = _gvn.transform(new CastX2PNode(src));
7735   offset = ConvI2X(offset);
7736 
7737   // 'src_start' points to src array + scaled offset
7738   Node* src_start = basic_plus_adr(top(), base, offset);
7739 
7740   // Call the stub.
7741   address stubAddr = StubRoutines::updateBytesAdler32();
7742   const char *stubName = "updateBytesAdler32";
7743 
7744   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesAdler32_Type(),
7745                                  stubAddr, stubName, TypePtr::BOTTOM,
7746                                  crc, src_start, length);
7747 
7748   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7749   set_result(result);
7750   return true;
7751 }
7752 
7753 //----------------------------inline_reference_get0----------------------------
7754 // public T java.lang.ref.Reference.get();
7755 bool LibraryCallKit::inline_reference_get0() {
7756   const int referent_offset = java_lang_ref_Reference::referent_offset();
7757 
7758   // Get the argument:
7759   Node* reference_obj = null_check_receiver();
7760   if (stopped()) return true;
7761 
7762   DecoratorSet decorators = IN_HEAP | ON_WEAK_OOP_REF;
7763   Node* result = load_field_from_object(reference_obj, "referent", "Ljava/lang/Object;",
7764                                         decorators, /*is_static*/ false, nullptr);
7765   if (result == nullptr) return false;
7766 
7767   // Add memory barrier to prevent commoning reads from this field
7768   // across safepoint since GC can change its value.
7769   insert_mem_bar(Op_MemBarCPUOrder);
7770 
7771   set_result(result);
7772   return true;
7773 }
7774 
7775 //----------------------------inline_reference_refersTo0----------------------------
7776 // bool java.lang.ref.Reference.refersTo0();
7777 // bool java.lang.ref.PhantomReference.refersTo0();
7778 bool LibraryCallKit::inline_reference_refersTo0(bool is_phantom) {
7779   // Get arguments:
7780   Node* reference_obj = null_check_receiver();
7781   Node* other_obj = argument(1);
7782   if (stopped()) return true;
7783 
7784   DecoratorSet decorators = IN_HEAP | AS_NO_KEEPALIVE;
7785   decorators |= (is_phantom ? ON_PHANTOM_OOP_REF : ON_WEAK_OOP_REF);
7786   Node* referent = load_field_from_object(reference_obj, "referent", "Ljava/lang/Object;",
7787                                           decorators, /*is_static*/ false, nullptr);
7788   if (referent == nullptr) return false;
7789 
7790   // Add memory barrier to prevent commoning reads from this field
7791   // across safepoint since GC can change its value.
7792   insert_mem_bar(Op_MemBarCPUOrder);
7793 
7794   Node* cmp = _gvn.transform(new CmpPNode(referent, other_obj));
7795   Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
7796   IfNode* if_node = create_and_map_if(control(), bol, PROB_FAIR, COUNT_UNKNOWN);
7797 
7798   RegionNode* region = new RegionNode(3);
7799   PhiNode* phi = new PhiNode(region, TypeInt::BOOL);
7800 
7801   Node* if_true = _gvn.transform(new IfTrueNode(if_node));
7802   region->init_req(1, if_true);
7803   phi->init_req(1, intcon(1));
7804 
7805   Node* if_false = _gvn.transform(new IfFalseNode(if_node));
7806   region->init_req(2, if_false);
7807   phi->init_req(2, intcon(0));
7808 
7809   set_control(_gvn.transform(region));
7810   record_for_igvn(region);
7811   set_result(_gvn.transform(phi));
7812   return true;
7813 }
7814 
7815 //----------------------------inline_reference_clear0----------------------------
7816 // void java.lang.ref.Reference.clear0();
7817 // void java.lang.ref.PhantomReference.clear0();
7818 bool LibraryCallKit::inline_reference_clear0(bool is_phantom) {
7819   // This matches the implementation in JVM_ReferenceClear, see the comments there.
7820 
7821   // Get arguments
7822   Node* reference_obj = null_check_receiver();
7823   if (stopped()) return true;
7824 
7825   // Common access parameters
7826   DecoratorSet decorators = IN_HEAP | AS_NO_KEEPALIVE;
7827   decorators |= (is_phantom ? ON_PHANTOM_OOP_REF : ON_WEAK_OOP_REF);
7828   Node* referent_field_addr = basic_plus_adr(reference_obj, java_lang_ref_Reference::referent_offset());
7829   const TypePtr* referent_field_addr_type = _gvn.type(referent_field_addr)->isa_ptr();
7830   const Type* val_type = TypeOopPtr::make_from_klass(env()->Object_klass());
7831 
7832   Node* referent = access_load_at(reference_obj,
7833                                   referent_field_addr,
7834                                   referent_field_addr_type,
7835                                   val_type,
7836                                   T_OBJECT,
7837                                   decorators);
7838 
7839   IdealKit ideal(this);
7840 #define __ ideal.
7841   __ if_then(referent, BoolTest::ne, null());
7842     sync_kit(ideal);
7843     access_store_at(reference_obj,
7844                     referent_field_addr,
7845                     referent_field_addr_type,
7846                     null(),
7847                     val_type,
7848                     T_OBJECT,
7849                     decorators);
7850     __ sync_kit(this);
7851   __ end_if();
7852   final_sync(ideal);
7853 #undef __
7854 
7855   return true;
7856 }
7857 
7858 Node* LibraryCallKit::load_field_from_object(Node* fromObj, const char* fieldName, const char* fieldTypeString,
7859                                              DecoratorSet decorators, bool is_static,
7860                                              ciInstanceKlass* fromKls) {
7861   if (fromKls == nullptr) {
7862     const TypeInstPtr* tinst = _gvn.type(fromObj)->isa_instptr();
7863     assert(tinst != nullptr, "obj is null");
7864     assert(tinst->is_loaded(), "obj is not loaded");
7865     fromKls = tinst->instance_klass();
7866   } else {
7867     assert(is_static, "only for static field access");
7868   }
7869   ciField* field = fromKls->get_field_by_name(ciSymbol::make(fieldName),
7870                                               ciSymbol::make(fieldTypeString),
7871                                               is_static);
7872 
7873   assert(field != nullptr, "undefined field %s %s %s", fieldTypeString, fromKls->name()->as_utf8(), fieldName);
7874   if (field == nullptr) return (Node *) nullptr;
7875 
7876   if (is_static) {
7877     const TypeInstPtr* tip = TypeInstPtr::make(fromKls->java_mirror());
7878     fromObj = makecon(tip);
7879   }
7880 
7881   // Next code  copied from Parse::do_get_xxx():
7882 
7883   // Compute address and memory type.
7884   int offset  = field->offset_in_bytes();
7885   bool is_vol = field->is_volatile();
7886   ciType* field_klass = field->type();
7887   assert(field_klass->is_loaded(), "should be loaded");
7888   const TypePtr* adr_type = C->alias_type(field)->adr_type();
7889   Node *adr = basic_plus_adr(fromObj, fromObj, offset);
7890   assert(C->get_alias_index(adr_type) == C->get_alias_index(_gvn.type(adr)->isa_ptr()),
7891     "slice of address and input slice don't match");
7892   BasicType bt = field->layout_type();
7893 
7894   // Build the resultant type of the load
7895   const Type *type;
7896   if (bt == T_OBJECT) {
7897     type = TypeOopPtr::make_from_klass(field_klass->as_klass());
7898   } else {
7899     type = Type::get_const_basic_type(bt);
7900   }
7901 
7902   if (is_vol) {
7903     decorators |= MO_SEQ_CST;
7904   }
7905 
7906   return access_load_at(fromObj, adr, adr_type, type, bt, decorators);
7907 }
7908 
7909 Node * LibraryCallKit::field_address_from_object(Node * fromObj, const char * fieldName, const char * fieldTypeString,
7910                                                  bool is_exact /* true */, bool is_static /* false */,
7911                                                  ciInstanceKlass * fromKls /* nullptr */) {
7912   if (fromKls == nullptr) {
7913     const TypeInstPtr* tinst = _gvn.type(fromObj)->isa_instptr();
7914     assert(tinst != nullptr, "obj is null");
7915     assert(tinst->is_loaded(), "obj is not loaded");
7916     assert(!is_exact || tinst->klass_is_exact(), "klass not exact");
7917     fromKls = tinst->instance_klass();
7918   }
7919   else {
7920     assert(is_static, "only for static field access");
7921   }
7922   ciField* field = fromKls->get_field_by_name(ciSymbol::make(fieldName),
7923     ciSymbol::make(fieldTypeString),
7924     is_static);
7925 
7926   assert(field != nullptr, "undefined field");
7927   assert(!field->is_volatile(), "not defined for volatile fields");
7928 
7929   if (is_static) {
7930     const TypeInstPtr* tip = TypeInstPtr::make(fromKls->java_mirror());
7931     fromObj = makecon(tip);
7932   }
7933 
7934   // Next code  copied from Parse::do_get_xxx():
7935 
7936   // Compute address and memory type.
7937   int offset = field->offset_in_bytes();
7938   Node *adr = basic_plus_adr(fromObj, fromObj, offset);
7939 
7940   return adr;
7941 }
7942 
7943 //------------------------------inline_aescrypt_Block-----------------------
7944 bool LibraryCallKit::inline_aescrypt_Block(vmIntrinsics::ID id) {
7945   address stubAddr = nullptr;
7946   const char *stubName;
7947   bool is_decrypt = false;
7948   assert(UseAES, "need AES instruction support");
7949 
7950   switch(id) {
7951   case vmIntrinsics::_aescrypt_encryptBlock:
7952     stubAddr = StubRoutines::aescrypt_encryptBlock();
7953     stubName = "aescrypt_encryptBlock";
7954     break;
7955   case vmIntrinsics::_aescrypt_decryptBlock:
7956     stubAddr = StubRoutines::aescrypt_decryptBlock();
7957     stubName = "aescrypt_decryptBlock";
7958     is_decrypt = true;
7959     break;
7960   default:
7961     break;
7962   }
7963   if (stubAddr == nullptr) return false;
7964 
7965   Node* aescrypt_object = argument(0);
7966   Node* src             = argument(1);
7967   Node* src_offset      = argument(2);
7968   Node* dest            = argument(3);
7969   Node* dest_offset     = argument(4);
7970 
7971   src = must_be_not_null(src, true);
7972   dest = must_be_not_null(dest, true);
7973 
7974   // (1) src and dest are arrays.
7975   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7976   const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
7977   assert( src_type != nullptr &&  src_type->elem() != Type::BOTTOM &&
7978          dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
7979 
7980   // for the quick and dirty code we will skip all the checks.
7981   // we are just trying to get the call to be generated.
7982   Node* src_start  = src;
7983   Node* dest_start = dest;
7984   if (src_offset != nullptr || dest_offset != nullptr) {
7985     assert(src_offset != nullptr && dest_offset != nullptr, "");
7986     src_start  = array_element_address(src,  src_offset,  T_BYTE);
7987     dest_start = array_element_address(dest, dest_offset, T_BYTE);
7988   }
7989 
7990   // now need to get the start of its expanded key array
7991   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
7992   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object, is_decrypt);
7993   if (k_start == nullptr) return false;
7994 
7995   // Call the stub.
7996   make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::aescrypt_block_Type(),
7997                     stubAddr, stubName, TypePtr::BOTTOM,
7998                     src_start, dest_start, k_start);
7999 
8000   return true;
8001 }
8002 
8003 //------------------------------inline_cipherBlockChaining_AESCrypt-----------------------
8004 bool LibraryCallKit::inline_cipherBlockChaining_AESCrypt(vmIntrinsics::ID id) {
8005   address stubAddr = nullptr;
8006   const char *stubName = nullptr;
8007   bool is_decrypt = false;
8008   assert(UseAES, "need AES instruction support");
8009 
8010   switch(id) {
8011   case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
8012     stubAddr = StubRoutines::cipherBlockChaining_encryptAESCrypt();
8013     stubName = "cipherBlockChaining_encryptAESCrypt";
8014     break;
8015   case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
8016     stubAddr = StubRoutines::cipherBlockChaining_decryptAESCrypt();
8017     stubName = "cipherBlockChaining_decryptAESCrypt";
8018     is_decrypt = true;
8019     break;
8020   default:
8021     break;
8022   }
8023   if (stubAddr == nullptr) return false;
8024 
8025   Node* cipherBlockChaining_object = argument(0);
8026   Node* src                        = argument(1);
8027   Node* src_offset                 = argument(2);
8028   Node* len                        = argument(3);
8029   Node* dest                       = argument(4);
8030   Node* dest_offset                = argument(5);
8031 
8032   src = must_be_not_null(src, false);
8033   dest = must_be_not_null(dest, false);
8034 
8035   // (1) src and dest are arrays.
8036   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
8037   const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
8038   assert( src_type != nullptr &&  src_type->elem() != Type::BOTTOM &&
8039          dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
8040 
8041   // checks are the responsibility of the caller
8042   Node* src_start  = src;
8043   Node* dest_start = dest;
8044   if (src_offset != nullptr || dest_offset != nullptr) {
8045     assert(src_offset != nullptr && dest_offset != nullptr, "");
8046     src_start  = array_element_address(src,  src_offset,  T_BYTE);
8047     dest_start = array_element_address(dest, dest_offset, T_BYTE);
8048   }
8049 
8050   // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
8051   // (because of the predicated logic executed earlier).
8052   // so we cast it here safely.
8053   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
8054 
8055   Node* embeddedCipherObj = load_field_from_object(cipherBlockChaining_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8056   if (embeddedCipherObj == nullptr) return false;
8057 
8058   // cast it to what we know it will be at runtime
8059   const TypeInstPtr* tinst = _gvn.type(cipherBlockChaining_object)->isa_instptr();
8060   assert(tinst != nullptr, "CBC obj is null");
8061   assert(tinst->is_loaded(), "CBC obj is not loaded");
8062   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8063   assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
8064 
8065   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8066   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
8067   const TypeOopPtr* xtype = aklass->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
8068   Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
8069   aescrypt_object = _gvn.transform(aescrypt_object);
8070 
8071   // we need to get the start of the aescrypt_object's expanded key array
8072   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object, is_decrypt);
8073   if (k_start == nullptr) return false;
8074 
8075   // similarly, get the start address of the r vector
8076   Node* objRvec = load_field_from_object(cipherBlockChaining_object, "r", "[B");
8077   if (objRvec == nullptr) return false;
8078   Node* r_start = array_element_address(objRvec, intcon(0), T_BYTE);
8079 
8080   // Call the stub, passing src_start, dest_start, k_start, r_start and src_len
8081   Node* cbcCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
8082                                      OptoRuntime::cipherBlockChaining_aescrypt_Type(),
8083                                      stubAddr, stubName, TypePtr::BOTTOM,
8084                                      src_start, dest_start, k_start, r_start, len);
8085 
8086   // return cipher length (int)
8087   Node* retvalue = _gvn.transform(new ProjNode(cbcCrypt, TypeFunc::Parms));
8088   set_result(retvalue);
8089   return true;
8090 }
8091 
8092 //------------------------------inline_electronicCodeBook_AESCrypt-----------------------
8093 bool LibraryCallKit::inline_electronicCodeBook_AESCrypt(vmIntrinsics::ID id) {
8094   address stubAddr = nullptr;
8095   const char *stubName = nullptr;
8096   bool is_decrypt = false;
8097   assert(UseAES, "need AES instruction support");
8098 
8099   switch (id) {
8100   case vmIntrinsics::_electronicCodeBook_encryptAESCrypt:
8101     stubAddr = StubRoutines::electronicCodeBook_encryptAESCrypt();
8102     stubName = "electronicCodeBook_encryptAESCrypt";
8103     break;
8104   case vmIntrinsics::_electronicCodeBook_decryptAESCrypt:
8105     stubAddr = StubRoutines::electronicCodeBook_decryptAESCrypt();
8106     stubName = "electronicCodeBook_decryptAESCrypt";
8107     is_decrypt = true;
8108     break;
8109   default:
8110     break;
8111   }
8112 
8113   if (stubAddr == nullptr) return false;
8114 
8115   Node* electronicCodeBook_object = argument(0);
8116   Node* src                       = argument(1);
8117   Node* src_offset                = argument(2);
8118   Node* len                       = argument(3);
8119   Node* dest                      = argument(4);
8120   Node* dest_offset               = argument(5);
8121 
8122   // (1) src and dest are arrays.
8123   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
8124   const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
8125   assert( src_type != nullptr &&  src_type->elem() != Type::BOTTOM &&
8126          dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
8127 
8128   // checks are the responsibility of the caller
8129   Node* src_start = src;
8130   Node* dest_start = dest;
8131   if (src_offset != nullptr || dest_offset != nullptr) {
8132     assert(src_offset != nullptr && dest_offset != nullptr, "");
8133     src_start = array_element_address(src, src_offset, T_BYTE);
8134     dest_start = array_element_address(dest, dest_offset, T_BYTE);
8135   }
8136 
8137   // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
8138   // (because of the predicated logic executed earlier).
8139   // so we cast it here safely.
8140   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
8141 
8142   Node* embeddedCipherObj = load_field_from_object(electronicCodeBook_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8143   if (embeddedCipherObj == nullptr) return false;
8144 
8145   // cast it to what we know it will be at runtime
8146   const TypeInstPtr* tinst = _gvn.type(electronicCodeBook_object)->isa_instptr();
8147   assert(tinst != nullptr, "ECB obj is null");
8148   assert(tinst->is_loaded(), "ECB obj is not loaded");
8149   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8150   assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
8151 
8152   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8153   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
8154   const TypeOopPtr* xtype = aklass->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
8155   Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
8156   aescrypt_object = _gvn.transform(aescrypt_object);
8157 
8158   // we need to get the start of the aescrypt_object's expanded key array
8159   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object, is_decrypt);
8160   if (k_start == nullptr) return false;
8161 
8162   // Call the stub, passing src_start, dest_start, k_start, r_start and src_len
8163   Node* ecbCrypt = make_runtime_call(RC_LEAF | RC_NO_FP,
8164                                      OptoRuntime::electronicCodeBook_aescrypt_Type(),
8165                                      stubAddr, stubName, TypePtr::BOTTOM,
8166                                      src_start, dest_start, k_start, len);
8167 
8168   // return cipher length (int)
8169   Node* retvalue = _gvn.transform(new ProjNode(ecbCrypt, TypeFunc::Parms));
8170   set_result(retvalue);
8171   return true;
8172 }
8173 
8174 //------------------------------inline_counterMode_AESCrypt-----------------------
8175 bool LibraryCallKit::inline_counterMode_AESCrypt(vmIntrinsics::ID id) {
8176   assert(UseAES, "need AES instruction support");
8177   if (!UseAESCTRIntrinsics) return false;
8178 
8179   address stubAddr = nullptr;
8180   const char *stubName = nullptr;
8181   if (id == vmIntrinsics::_counterMode_AESCrypt) {
8182     stubAddr = StubRoutines::counterMode_AESCrypt();
8183     stubName = "counterMode_AESCrypt";
8184   }
8185   if (stubAddr == nullptr) return false;
8186 
8187   Node* counterMode_object = argument(0);
8188   Node* src = argument(1);
8189   Node* src_offset = argument(2);
8190   Node* len = argument(3);
8191   Node* dest = argument(4);
8192   Node* dest_offset = argument(5);
8193 
8194   // (1) src and dest are arrays.
8195   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
8196   const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
8197   assert( src_type != nullptr &&  src_type->elem() != Type::BOTTOM &&
8198          dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
8199 
8200   // checks are the responsibility of the caller
8201   Node* src_start = src;
8202   Node* dest_start = dest;
8203   if (src_offset != nullptr || dest_offset != nullptr) {
8204     assert(src_offset != nullptr && dest_offset != nullptr, "");
8205     src_start = array_element_address(src, src_offset, T_BYTE);
8206     dest_start = array_element_address(dest, dest_offset, T_BYTE);
8207   }
8208 
8209   // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
8210   // (because of the predicated logic executed earlier).
8211   // so we cast it here safely.
8212   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
8213   Node* embeddedCipherObj = load_field_from_object(counterMode_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8214   if (embeddedCipherObj == nullptr) return false;
8215   // cast it to what we know it will be at runtime
8216   const TypeInstPtr* tinst = _gvn.type(counterMode_object)->isa_instptr();
8217   assert(tinst != nullptr, "CTR obj is null");
8218   assert(tinst->is_loaded(), "CTR obj is not loaded");
8219   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8220   assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
8221   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8222   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
8223   const TypeOopPtr* xtype = aklass->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
8224   Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
8225   aescrypt_object = _gvn.transform(aescrypt_object);
8226   // we need to get the start of the aescrypt_object's expanded key array
8227   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object, /* is_decrypt */ false);
8228   if (k_start == nullptr) return false;
8229   // similarly, get the start address of the r vector
8230   Node* obj_counter = load_field_from_object(counterMode_object, "counter", "[B");
8231   if (obj_counter == nullptr) return false;
8232   Node* cnt_start = array_element_address(obj_counter, intcon(0), T_BYTE);
8233 
8234   Node* saved_encCounter = load_field_from_object(counterMode_object, "encryptedCounter", "[B");
8235   if (saved_encCounter == nullptr) return false;
8236   Node* saved_encCounter_start = array_element_address(saved_encCounter, intcon(0), T_BYTE);
8237   Node* used = field_address_from_object(counterMode_object, "used", "I", /*is_exact*/ false);
8238 
8239   // Call the stub, passing src_start, dest_start, k_start, r_start and src_len
8240   Node* ctrCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
8241                                      OptoRuntime::counterMode_aescrypt_Type(),
8242                                      stubAddr, stubName, TypePtr::BOTTOM,
8243                                      src_start, dest_start, k_start, cnt_start, len, saved_encCounter_start, used);
8244 
8245   // return cipher length (int)
8246   Node* retvalue = _gvn.transform(new ProjNode(ctrCrypt, TypeFunc::Parms));
8247   set_result(retvalue);
8248   return true;
8249 }
8250 
8251 //------------------------------get_key_start_from_aescrypt_object-----------------------
8252 Node* LibraryCallKit::get_key_start_from_aescrypt_object(Node* aescrypt_object, bool is_decrypt) {
8253   // MixColumns for decryption can be reduced by preprocessing MixColumns with round keys.
8254   // Intel's extension is based on this optimization and AESCrypt generates round keys by preprocessing MixColumns.
8255   // However, ppc64 vncipher processes MixColumns and requires the same round keys with encryption.
8256   // The following platform specific stubs of encryption and decryption use the same round keys.
8257 #if defined(PPC64) || defined(S390) || defined(RISCV64)
8258   bool use_decryption_key = false;
8259 #else
8260   bool use_decryption_key = is_decrypt;
8261 #endif
8262   Node* objAESCryptKey = load_field_from_object(aescrypt_object, use_decryption_key ? "sessionKd" : "sessionKe", "[I");
8263   assert(objAESCryptKey != nullptr, "wrong version of com.sun.crypto.provider.AES_Crypt");
8264   if (objAESCryptKey == nullptr) return (Node *) nullptr;
8265 
8266   // now have the array, need to get the start address of the selected key array
8267   Node* k_start = array_element_address(objAESCryptKey, intcon(0), T_INT);
8268   return k_start;
8269 }
8270 
8271 //----------------------------inline_cipherBlockChaining_AESCrypt_predicate----------------------------
8272 // Return node representing slow path of predicate check.
8273 // the pseudo code we want to emulate with this predicate is:
8274 // for encryption:
8275 //    if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
8276 // for decryption:
8277 //    if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
8278 //    note cipher==plain is more conservative than the original java code but that's OK
8279 //
8280 Node* LibraryCallKit::inline_cipherBlockChaining_AESCrypt_predicate(bool decrypting) {
8281   // The receiver was checked for null already.
8282   Node* objCBC = argument(0);
8283 
8284   Node* src = argument(1);
8285   Node* dest = argument(4);
8286 
8287   // Load embeddedCipher field of CipherBlockChaining object.
8288   Node* embeddedCipherObj = load_field_from_object(objCBC, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8289 
8290   // get AESCrypt klass for instanceOf check
8291   // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
8292   // will have same classloader as CipherBlockChaining object
8293   const TypeInstPtr* tinst = _gvn.type(objCBC)->isa_instptr();
8294   assert(tinst != nullptr, "CBCobj is null");
8295   assert(tinst->is_loaded(), "CBCobj is not loaded");
8296 
8297   // we want to do an instanceof comparison against the AESCrypt class
8298   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8299   if (!klass_AESCrypt->is_loaded()) {
8300     // if AESCrypt is not even loaded, we never take the intrinsic fast path
8301     Node* ctrl = control();
8302     set_control(top()); // no regular fast path
8303     return ctrl;
8304   }
8305 
8306   src = must_be_not_null(src, true);
8307   dest = must_be_not_null(dest, true);
8308 
8309   // Resolve oops to stable for CmpP below.
8310   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8311 
8312   Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
8313   Node* cmp_instof  = _gvn.transform(new CmpINode(instof, intcon(1)));
8314   Node* bool_instof  = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
8315 
8316   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
8317 
8318   // for encryption, we are done
8319   if (!decrypting)
8320     return instof_false;  // even if it is null
8321 
8322   // for decryption, we need to add a further check to avoid
8323   // taking the intrinsic path when cipher and plain are the same
8324   // see the original java code for why.
8325   RegionNode* region = new RegionNode(3);
8326   region->init_req(1, instof_false);
8327 
8328   Node* cmp_src_dest = _gvn.transform(new CmpPNode(src, dest));
8329   Node* bool_src_dest = _gvn.transform(new BoolNode(cmp_src_dest, BoolTest::eq));
8330   Node* src_dest_conjoint = generate_guard(bool_src_dest, nullptr, PROB_MIN);
8331   region->init_req(2, src_dest_conjoint);
8332 
8333   record_for_igvn(region);
8334   return _gvn.transform(region);
8335 }
8336 
8337 //----------------------------inline_electronicCodeBook_AESCrypt_predicate----------------------------
8338 // Return node representing slow path of predicate check.
8339 // the pseudo code we want to emulate with this predicate is:
8340 // for encryption:
8341 //    if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
8342 // for decryption:
8343 //    if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
8344 //    note cipher==plain is more conservative than the original java code but that's OK
8345 //
8346 Node* LibraryCallKit::inline_electronicCodeBook_AESCrypt_predicate(bool decrypting) {
8347   // The receiver was checked for null already.
8348   Node* objECB = argument(0);
8349 
8350   // Load embeddedCipher field of ElectronicCodeBook object.
8351   Node* embeddedCipherObj = load_field_from_object(objECB, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8352 
8353   // get AESCrypt klass for instanceOf check
8354   // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
8355   // will have same classloader as ElectronicCodeBook object
8356   const TypeInstPtr* tinst = _gvn.type(objECB)->isa_instptr();
8357   assert(tinst != nullptr, "ECBobj is null");
8358   assert(tinst->is_loaded(), "ECBobj is not loaded");
8359 
8360   // we want to do an instanceof comparison against the AESCrypt class
8361   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8362   if (!klass_AESCrypt->is_loaded()) {
8363     // if AESCrypt is not even loaded, we never take the intrinsic fast path
8364     Node* ctrl = control();
8365     set_control(top()); // no regular fast path
8366     return ctrl;
8367   }
8368   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8369 
8370   Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
8371   Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
8372   Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
8373 
8374   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
8375 
8376   // for encryption, we are done
8377   if (!decrypting)
8378     return instof_false;  // even if it is null
8379 
8380   // for decryption, we need to add a further check to avoid
8381   // taking the intrinsic path when cipher and plain are the same
8382   // see the original java code for why.
8383   RegionNode* region = new RegionNode(3);
8384   region->init_req(1, instof_false);
8385   Node* src = argument(1);
8386   Node* dest = argument(4);
8387   Node* cmp_src_dest = _gvn.transform(new CmpPNode(src, dest));
8388   Node* bool_src_dest = _gvn.transform(new BoolNode(cmp_src_dest, BoolTest::eq));
8389   Node* src_dest_conjoint = generate_guard(bool_src_dest, nullptr, PROB_MIN);
8390   region->init_req(2, src_dest_conjoint);
8391 
8392   record_for_igvn(region);
8393   return _gvn.transform(region);
8394 }
8395 
8396 //----------------------------inline_counterMode_AESCrypt_predicate----------------------------
8397 // Return node representing slow path of predicate check.
8398 // the pseudo code we want to emulate with this predicate is:
8399 // for encryption:
8400 //    if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
8401 // for decryption:
8402 //    if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
8403 //    note cipher==plain is more conservative than the original java code but that's OK
8404 //
8405 
8406 Node* LibraryCallKit::inline_counterMode_AESCrypt_predicate() {
8407   // The receiver was checked for null already.
8408   Node* objCTR = argument(0);
8409 
8410   // Load embeddedCipher field of CipherBlockChaining object.
8411   Node* embeddedCipherObj = load_field_from_object(objCTR, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8412 
8413   // get AESCrypt klass for instanceOf check
8414   // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
8415   // will have same classloader as CipherBlockChaining object
8416   const TypeInstPtr* tinst = _gvn.type(objCTR)->isa_instptr();
8417   assert(tinst != nullptr, "CTRobj is null");
8418   assert(tinst->is_loaded(), "CTRobj is not loaded");
8419 
8420   // we want to do an instanceof comparison against the AESCrypt class
8421   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8422   if (!klass_AESCrypt->is_loaded()) {
8423     // if AESCrypt is not even loaded, we never take the intrinsic fast path
8424     Node* ctrl = control();
8425     set_control(top()); // no regular fast path
8426     return ctrl;
8427   }
8428 
8429   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8430   Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
8431   Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
8432   Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
8433   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
8434 
8435   return instof_false; // even if it is null
8436 }
8437 
8438 //------------------------------inline_ghash_processBlocks
8439 bool LibraryCallKit::inline_ghash_processBlocks() {
8440   address stubAddr;
8441   const char *stubName;
8442   assert(UseGHASHIntrinsics, "need GHASH intrinsics support");
8443 
8444   stubAddr = StubRoutines::ghash_processBlocks();
8445   stubName = "ghash_processBlocks";
8446 
8447   Node* data           = argument(0);
8448   Node* offset         = argument(1);
8449   Node* len            = argument(2);
8450   Node* state          = argument(3);
8451   Node* subkeyH        = argument(4);
8452 
8453   state = must_be_not_null(state, true);
8454   subkeyH = must_be_not_null(subkeyH, true);
8455   data = must_be_not_null(data, true);
8456 
8457   Node* state_start  = array_element_address(state, intcon(0), T_LONG);
8458   assert(state_start, "state is null");
8459   Node* subkeyH_start  = array_element_address(subkeyH, intcon(0), T_LONG);
8460   assert(subkeyH_start, "subkeyH is null");
8461   Node* data_start  = array_element_address(data, offset, T_BYTE);
8462   assert(data_start, "data is null");
8463 
8464   Node* ghash = make_runtime_call(RC_LEAF|RC_NO_FP,
8465                                   OptoRuntime::ghash_processBlocks_Type(),
8466                                   stubAddr, stubName, TypePtr::BOTTOM,
8467                                   state_start, subkeyH_start, data_start, len);
8468   return true;
8469 }
8470 
8471 //------------------------------inline_chacha20Block
8472 bool LibraryCallKit::inline_chacha20Block() {
8473   address stubAddr;
8474   const char *stubName;
8475   assert(UseChaCha20Intrinsics, "need ChaCha20 intrinsics support");
8476 
8477   stubAddr = StubRoutines::chacha20Block();
8478   stubName = "chacha20Block";
8479 
8480   Node* state          = argument(0);
8481   Node* result         = argument(1);
8482 
8483   state = must_be_not_null(state, true);
8484   result = must_be_not_null(result, true);
8485 
8486   Node* state_start  = array_element_address(state, intcon(0), T_INT);
8487   assert(state_start, "state is null");
8488   Node* result_start  = array_element_address(result, intcon(0), T_BYTE);
8489   assert(result_start, "result is null");
8490 
8491   Node* cc20Blk = make_runtime_call(RC_LEAF|RC_NO_FP,
8492                                   OptoRuntime::chacha20Block_Type(),
8493                                   stubAddr, stubName, TypePtr::BOTTOM,
8494                                   state_start, result_start);
8495   // return key stream length (int)
8496   Node* retvalue = _gvn.transform(new ProjNode(cc20Blk, TypeFunc::Parms));
8497   set_result(retvalue);
8498   return true;
8499 }
8500 
8501 //------------------------------inline_kyberNtt
8502 bool LibraryCallKit::inline_kyberNtt() {
8503   address stubAddr;
8504   const char *stubName;
8505   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8506   assert(callee()->signature()->size() == 2, "kyberNtt has 2 parameters");
8507 
8508   stubAddr = StubRoutines::kyberNtt();
8509   stubName = "kyberNtt";
8510   if (!stubAddr) return false;
8511 
8512   Node* coeffs          = argument(0);
8513   Node* ntt_zetas        = argument(1);
8514 
8515   coeffs = must_be_not_null(coeffs, true);
8516   ntt_zetas = must_be_not_null(ntt_zetas, true);
8517 
8518   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_SHORT);
8519   assert(coeffs_start, "coeffs is null");
8520   Node* ntt_zetas_start  = array_element_address(ntt_zetas, intcon(0), T_SHORT);
8521   assert(ntt_zetas_start, "ntt_zetas is null");
8522   Node* kyberNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
8523                                   OptoRuntime::kyberNtt_Type(),
8524                                   stubAddr, stubName, TypePtr::BOTTOM,
8525                                   coeffs_start, ntt_zetas_start);
8526   // return an int
8527   Node* retvalue = _gvn.transform(new ProjNode(kyberNtt, TypeFunc::Parms));
8528   set_result(retvalue);
8529   return true;
8530 }
8531 
8532 //------------------------------inline_kyberInverseNtt
8533 bool LibraryCallKit::inline_kyberInverseNtt() {
8534   address stubAddr;
8535   const char *stubName;
8536   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8537   assert(callee()->signature()->size() == 2, "kyberInverseNtt has 2 parameters");
8538 
8539   stubAddr = StubRoutines::kyberInverseNtt();
8540   stubName = "kyberInverseNtt";
8541   if (!stubAddr) return false;
8542 
8543   Node* coeffs          = argument(0);
8544   Node* zetas           = argument(1);
8545 
8546   coeffs = must_be_not_null(coeffs, true);
8547   zetas = must_be_not_null(zetas, true);
8548 
8549   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_SHORT);
8550   assert(coeffs_start, "coeffs is null");
8551   Node* zetas_start  = array_element_address(zetas, intcon(0), T_SHORT);
8552   assert(zetas_start, "inverseNtt_zetas is null");
8553   Node* kyberInverseNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
8554                                   OptoRuntime::kyberInverseNtt_Type(),
8555                                   stubAddr, stubName, TypePtr::BOTTOM,
8556                                   coeffs_start, zetas_start);
8557 
8558   // return an int
8559   Node* retvalue = _gvn.transform(new ProjNode(kyberInverseNtt, TypeFunc::Parms));
8560   set_result(retvalue);
8561   return true;
8562 }
8563 
8564 //------------------------------inline_kyberNttMult
8565 bool LibraryCallKit::inline_kyberNttMult() {
8566   address stubAddr;
8567   const char *stubName;
8568   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8569   assert(callee()->signature()->size() == 4, "kyberNttMult has 4 parameters");
8570 
8571   stubAddr = StubRoutines::kyberNttMult();
8572   stubName = "kyberNttMult";
8573   if (!stubAddr) return false;
8574 
8575   Node* result          = argument(0);
8576   Node* ntta            = argument(1);
8577   Node* nttb            = argument(2);
8578   Node* zetas           = argument(3);
8579 
8580   result = must_be_not_null(result, true);
8581   ntta = must_be_not_null(ntta, true);
8582   nttb = must_be_not_null(nttb, true);
8583   zetas = must_be_not_null(zetas, true);
8584 
8585   Node* result_start  = array_element_address(result, intcon(0), T_SHORT);
8586   assert(result_start, "result is null");
8587   Node* ntta_start  = array_element_address(ntta, intcon(0), T_SHORT);
8588   assert(ntta_start, "ntta is null");
8589   Node* nttb_start  = array_element_address(nttb, intcon(0), T_SHORT);
8590   assert(nttb_start, "nttb is null");
8591   Node* zetas_start  = array_element_address(zetas, intcon(0), T_SHORT);
8592   assert(zetas_start, "nttMult_zetas is null");
8593   Node* kyberNttMult = make_runtime_call(RC_LEAF|RC_NO_FP,
8594                                   OptoRuntime::kyberNttMult_Type(),
8595                                   stubAddr, stubName, TypePtr::BOTTOM,
8596                                   result_start, ntta_start, nttb_start,
8597                                   zetas_start);
8598 
8599   // return an int
8600   Node* retvalue = _gvn.transform(new ProjNode(kyberNttMult, TypeFunc::Parms));
8601   set_result(retvalue);
8602 
8603   return true;
8604 }
8605 
8606 //------------------------------inline_kyberAddPoly_2
8607 bool LibraryCallKit::inline_kyberAddPoly_2() {
8608   address stubAddr;
8609   const char *stubName;
8610   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8611   assert(callee()->signature()->size() == 3, "kyberAddPoly_2 has 3 parameters");
8612 
8613   stubAddr = StubRoutines::kyberAddPoly_2();
8614   stubName = "kyberAddPoly_2";
8615   if (!stubAddr) return false;
8616 
8617   Node* result          = argument(0);
8618   Node* a               = argument(1);
8619   Node* b               = argument(2);
8620 
8621   result = must_be_not_null(result, true);
8622   a = must_be_not_null(a, true);
8623   b = must_be_not_null(b, true);
8624 
8625   Node* result_start  = array_element_address(result, intcon(0), T_SHORT);
8626   assert(result_start, "result is null");
8627   Node* a_start  = array_element_address(a, intcon(0), T_SHORT);
8628   assert(a_start, "a is null");
8629   Node* b_start  = array_element_address(b, intcon(0), T_SHORT);
8630   assert(b_start, "b is null");
8631   Node* kyberAddPoly_2 = make_runtime_call(RC_LEAF|RC_NO_FP,
8632                                   OptoRuntime::kyberAddPoly_2_Type(),
8633                                   stubAddr, stubName, TypePtr::BOTTOM,
8634                                   result_start, a_start, b_start);
8635   // return an int
8636   Node* retvalue = _gvn.transform(new ProjNode(kyberAddPoly_2, TypeFunc::Parms));
8637   set_result(retvalue);
8638   return true;
8639 }
8640 
8641 //------------------------------inline_kyberAddPoly_3
8642 bool LibraryCallKit::inline_kyberAddPoly_3() {
8643   address stubAddr;
8644   const char *stubName;
8645   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8646   assert(callee()->signature()->size() == 4, "kyberAddPoly_3 has 4 parameters");
8647 
8648   stubAddr = StubRoutines::kyberAddPoly_3();
8649   stubName = "kyberAddPoly_3";
8650   if (!stubAddr) return false;
8651 
8652   Node* result          = argument(0);
8653   Node* a               = argument(1);
8654   Node* b               = argument(2);
8655   Node* c               = argument(3);
8656 
8657   result = must_be_not_null(result, true);
8658   a = must_be_not_null(a, true);
8659   b = must_be_not_null(b, true);
8660   c = must_be_not_null(c, true);
8661 
8662   Node* result_start  = array_element_address(result, intcon(0), T_SHORT);
8663   assert(result_start, "result is null");
8664   Node* a_start  = array_element_address(a, intcon(0), T_SHORT);
8665   assert(a_start, "a is null");
8666   Node* b_start  = array_element_address(b, intcon(0), T_SHORT);
8667   assert(b_start, "b is null");
8668   Node* c_start  = array_element_address(c, intcon(0), T_SHORT);
8669   assert(c_start, "c is null");
8670   Node* kyberAddPoly_3 = make_runtime_call(RC_LEAF|RC_NO_FP,
8671                                   OptoRuntime::kyberAddPoly_3_Type(),
8672                                   stubAddr, stubName, TypePtr::BOTTOM,
8673                                   result_start, a_start, b_start, c_start);
8674   // return an int
8675   Node* retvalue = _gvn.transform(new ProjNode(kyberAddPoly_3, TypeFunc::Parms));
8676   set_result(retvalue);
8677   return true;
8678 }
8679 
8680 //------------------------------inline_kyber12To16
8681 bool LibraryCallKit::inline_kyber12To16() {
8682   address stubAddr;
8683   const char *stubName;
8684   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8685   assert(callee()->signature()->size() == 4, "kyber12To16 has 4 parameters");
8686 
8687   stubAddr = StubRoutines::kyber12To16();
8688   stubName = "kyber12To16";
8689   if (!stubAddr) return false;
8690 
8691   Node* condensed       = argument(0);
8692   Node* condensedOffs   = argument(1);
8693   Node* parsed          = argument(2);
8694   Node* parsedLength    = argument(3);
8695 
8696   condensed = must_be_not_null(condensed, true);
8697   parsed = must_be_not_null(parsed, true);
8698 
8699   Node* condensed_start  = array_element_address(condensed, intcon(0), T_BYTE);
8700   assert(condensed_start, "condensed is null");
8701   Node* parsed_start  = array_element_address(parsed, intcon(0), T_SHORT);
8702   assert(parsed_start, "parsed is null");
8703   Node* kyber12To16 = make_runtime_call(RC_LEAF|RC_NO_FP,
8704                                   OptoRuntime::kyber12To16_Type(),
8705                                   stubAddr, stubName, TypePtr::BOTTOM,
8706                                   condensed_start, condensedOffs, parsed_start, parsedLength);
8707   // return an int
8708   Node* retvalue = _gvn.transform(new ProjNode(kyber12To16, TypeFunc::Parms));
8709   set_result(retvalue);
8710   return true;
8711 
8712 }
8713 
8714 //------------------------------inline_kyberBarrettReduce
8715 bool LibraryCallKit::inline_kyberBarrettReduce() {
8716   address stubAddr;
8717   const char *stubName;
8718   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8719   assert(callee()->signature()->size() == 1, "kyberBarrettReduce has 1 parameters");
8720 
8721   stubAddr = StubRoutines::kyberBarrettReduce();
8722   stubName = "kyberBarrettReduce";
8723   if (!stubAddr) return false;
8724 
8725   Node* coeffs          = argument(0);
8726 
8727   coeffs = must_be_not_null(coeffs, true);
8728 
8729   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_SHORT);
8730   assert(coeffs_start, "coeffs is null");
8731   Node* kyberBarrettReduce = make_runtime_call(RC_LEAF|RC_NO_FP,
8732                                   OptoRuntime::kyberBarrettReduce_Type(),
8733                                   stubAddr, stubName, TypePtr::BOTTOM,
8734                                   coeffs_start);
8735   // return an int
8736   Node* retvalue = _gvn.transform(new ProjNode(kyberBarrettReduce, TypeFunc::Parms));
8737   set_result(retvalue);
8738   return true;
8739 }
8740 
8741 //------------------------------inline_dilithiumAlmostNtt
8742 bool LibraryCallKit::inline_dilithiumAlmostNtt() {
8743   address stubAddr;
8744   const char *stubName;
8745   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8746   assert(callee()->signature()->size() == 2, "dilithiumAlmostNtt has 2 parameters");
8747 
8748   stubAddr = StubRoutines::dilithiumAlmostNtt();
8749   stubName = "dilithiumAlmostNtt";
8750   if (!stubAddr) return false;
8751 
8752   Node* coeffs          = argument(0);
8753   Node* ntt_zetas        = argument(1);
8754 
8755   coeffs = must_be_not_null(coeffs, true);
8756   ntt_zetas = must_be_not_null(ntt_zetas, true);
8757 
8758   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_INT);
8759   assert(coeffs_start, "coeffs is null");
8760   Node* ntt_zetas_start  = array_element_address(ntt_zetas, intcon(0), T_INT);
8761   assert(ntt_zetas_start, "ntt_zetas is null");
8762   Node* dilithiumAlmostNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
8763                                   OptoRuntime::dilithiumAlmostNtt_Type(),
8764                                   stubAddr, stubName, TypePtr::BOTTOM,
8765                                   coeffs_start, ntt_zetas_start);
8766   // return an int
8767   Node* retvalue = _gvn.transform(new ProjNode(dilithiumAlmostNtt, TypeFunc::Parms));
8768   set_result(retvalue);
8769   return true;
8770 }
8771 
8772 //------------------------------inline_dilithiumAlmostInverseNtt
8773 bool LibraryCallKit::inline_dilithiumAlmostInverseNtt() {
8774   address stubAddr;
8775   const char *stubName;
8776   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8777   assert(callee()->signature()->size() == 2, "dilithiumAlmostInverseNtt has 2 parameters");
8778 
8779   stubAddr = StubRoutines::dilithiumAlmostInverseNtt();
8780   stubName = "dilithiumAlmostInverseNtt";
8781   if (!stubAddr) return false;
8782 
8783   Node* coeffs          = argument(0);
8784   Node* zetas           = argument(1);
8785 
8786   coeffs = must_be_not_null(coeffs, true);
8787   zetas = must_be_not_null(zetas, true);
8788 
8789   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_INT);
8790   assert(coeffs_start, "coeffs is null");
8791   Node* zetas_start  = array_element_address(zetas, intcon(0), T_INT);
8792   assert(zetas_start, "inverseNtt_zetas is null");
8793   Node* dilithiumAlmostInverseNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
8794                                   OptoRuntime::dilithiumAlmostInverseNtt_Type(),
8795                                   stubAddr, stubName, TypePtr::BOTTOM,
8796                                   coeffs_start, zetas_start);
8797   // return an int
8798   Node* retvalue = _gvn.transform(new ProjNode(dilithiumAlmostInverseNtt, TypeFunc::Parms));
8799   set_result(retvalue);
8800   return true;
8801 }
8802 
8803 //------------------------------inline_dilithiumNttMult
8804 bool LibraryCallKit::inline_dilithiumNttMult() {
8805   address stubAddr;
8806   const char *stubName;
8807   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8808   assert(callee()->signature()->size() == 3, "dilithiumNttMult has 3 parameters");
8809 
8810   stubAddr = StubRoutines::dilithiumNttMult();
8811   stubName = "dilithiumNttMult";
8812   if (!stubAddr) return false;
8813 
8814   Node* result          = argument(0);
8815   Node* ntta            = argument(1);
8816   Node* nttb            = argument(2);
8817   Node* zetas           = argument(3);
8818 
8819   result = must_be_not_null(result, true);
8820   ntta = must_be_not_null(ntta, true);
8821   nttb = must_be_not_null(nttb, true);
8822   zetas = must_be_not_null(zetas, true);
8823 
8824   Node* result_start  = array_element_address(result, intcon(0), T_INT);
8825   assert(result_start, "result is null");
8826   Node* ntta_start  = array_element_address(ntta, intcon(0), T_INT);
8827   assert(ntta_start, "ntta is null");
8828   Node* nttb_start  = array_element_address(nttb, intcon(0), T_INT);
8829   assert(nttb_start, "nttb is null");
8830   Node* dilithiumNttMult = make_runtime_call(RC_LEAF|RC_NO_FP,
8831                                   OptoRuntime::dilithiumNttMult_Type(),
8832                                   stubAddr, stubName, TypePtr::BOTTOM,
8833                                   result_start, ntta_start, nttb_start);
8834 
8835   // return an int
8836   Node* retvalue = _gvn.transform(new ProjNode(dilithiumNttMult, TypeFunc::Parms));
8837   set_result(retvalue);
8838 
8839   return true;
8840 }
8841 
8842 //------------------------------inline_dilithiumMontMulByConstant
8843 bool LibraryCallKit::inline_dilithiumMontMulByConstant() {
8844   address stubAddr;
8845   const char *stubName;
8846   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8847   assert(callee()->signature()->size() == 2, "dilithiumMontMulByConstant has 2 parameters");
8848 
8849   stubAddr = StubRoutines::dilithiumMontMulByConstant();
8850   stubName = "dilithiumMontMulByConstant";
8851   if (!stubAddr) return false;
8852 
8853   Node* coeffs          = argument(0);
8854   Node* constant        = argument(1);
8855 
8856   coeffs = must_be_not_null(coeffs, true);
8857 
8858   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_INT);
8859   assert(coeffs_start, "coeffs is null");
8860   Node* dilithiumMontMulByConstant = make_runtime_call(RC_LEAF|RC_NO_FP,
8861                                   OptoRuntime::dilithiumMontMulByConstant_Type(),
8862                                   stubAddr, stubName, TypePtr::BOTTOM,
8863                                   coeffs_start, constant);
8864 
8865   // return an int
8866   Node* retvalue = _gvn.transform(new ProjNode(dilithiumMontMulByConstant, TypeFunc::Parms));
8867   set_result(retvalue);
8868   return true;
8869 }
8870 
8871 
8872 //------------------------------inline_dilithiumDecomposePoly
8873 bool LibraryCallKit::inline_dilithiumDecomposePoly() {
8874   address stubAddr;
8875   const char *stubName;
8876   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8877   assert(callee()->signature()->size() == 5, "dilithiumDecomposePoly has 5 parameters");
8878 
8879   stubAddr = StubRoutines::dilithiumDecomposePoly();
8880   stubName = "dilithiumDecomposePoly";
8881   if (!stubAddr) return false;
8882 
8883   Node* input          = argument(0);
8884   Node* lowPart        = argument(1);
8885   Node* highPart       = argument(2);
8886   Node* twoGamma2      = argument(3);
8887   Node* multiplier     = argument(4);
8888 
8889   input = must_be_not_null(input, true);
8890   lowPart = must_be_not_null(lowPart, true);
8891   highPart = must_be_not_null(highPart, true);
8892 
8893   Node* input_start  = array_element_address(input, intcon(0), T_INT);
8894   assert(input_start, "input is null");
8895   Node* lowPart_start  = array_element_address(lowPart, intcon(0), T_INT);
8896   assert(lowPart_start, "lowPart is null");
8897   Node* highPart_start  = array_element_address(highPart, intcon(0), T_INT);
8898   assert(highPart_start, "highPart is null");
8899 
8900   Node* dilithiumDecomposePoly = make_runtime_call(RC_LEAF|RC_NO_FP,
8901                                   OptoRuntime::dilithiumDecomposePoly_Type(),
8902                                   stubAddr, stubName, TypePtr::BOTTOM,
8903                                   input_start, lowPart_start, highPart_start,
8904                                   twoGamma2, multiplier);
8905 
8906   // return an int
8907   Node* retvalue = _gvn.transform(new ProjNode(dilithiumDecomposePoly, TypeFunc::Parms));
8908   set_result(retvalue);
8909   return true;
8910 }
8911 
8912 bool LibraryCallKit::inline_base64_encodeBlock() {
8913   address stubAddr;
8914   const char *stubName;
8915   assert(UseBASE64Intrinsics, "need Base64 intrinsics support");
8916   assert(callee()->signature()->size() == 6, "base64_encodeBlock has 6 parameters");
8917   stubAddr = StubRoutines::base64_encodeBlock();
8918   stubName = "encodeBlock";
8919 
8920   if (!stubAddr) return false;
8921   Node* base64obj = argument(0);
8922   Node* src = argument(1);
8923   Node* offset = argument(2);
8924   Node* len = argument(3);
8925   Node* dest = argument(4);
8926   Node* dp = argument(5);
8927   Node* isURL = argument(6);
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* base64 = make_runtime_call(RC_LEAF,
8938                                    OptoRuntime::base64_encodeBlock_Type(),
8939                                    stubAddr, stubName, TypePtr::BOTTOM,
8940                                    src_start, offset, len, dest_start, dp, isURL);
8941   return true;
8942 }
8943 
8944 bool LibraryCallKit::inline_base64_decodeBlock() {
8945   address stubAddr;
8946   const char *stubName;
8947   assert(UseBASE64Intrinsics, "need Base64 intrinsics support");
8948   assert(callee()->signature()->size() == 7, "base64_decodeBlock has 7 parameters");
8949   stubAddr = StubRoutines::base64_decodeBlock();
8950   stubName = "decodeBlock";
8951 
8952   if (!stubAddr) return false;
8953   Node* base64obj = argument(0);
8954   Node* src = argument(1);
8955   Node* src_offset = argument(2);
8956   Node* len = argument(3);
8957   Node* dest = argument(4);
8958   Node* dest_offset = argument(5);
8959   Node* isURL = argument(6);
8960   Node* isMIME = argument(7);
8961 
8962   src = must_be_not_null(src, true);
8963   dest = must_be_not_null(dest, true);
8964 
8965   Node* src_start = array_element_address(src, intcon(0), T_BYTE);
8966   assert(src_start, "source array is null");
8967   Node* dest_start = array_element_address(dest, intcon(0), T_BYTE);
8968   assert(dest_start, "destination array is null");
8969 
8970   Node* call = make_runtime_call(RC_LEAF,
8971                                  OptoRuntime::base64_decodeBlock_Type(),
8972                                  stubAddr, stubName, TypePtr::BOTTOM,
8973                                  src_start, src_offset, len, dest_start, dest_offset, isURL, isMIME);
8974   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
8975   set_result(result);
8976   return true;
8977 }
8978 
8979 bool LibraryCallKit::inline_poly1305_processBlocks() {
8980   address stubAddr;
8981   const char *stubName;
8982   assert(UsePoly1305Intrinsics, "need Poly intrinsics support");
8983   assert(callee()->signature()->size() == 5, "poly1305_processBlocks has %d parameters", callee()->signature()->size());
8984   stubAddr = StubRoutines::poly1305_processBlocks();
8985   stubName = "poly1305_processBlocks";
8986 
8987   if (!stubAddr) return false;
8988   null_check_receiver();  // null-check receiver
8989   if (stopped())  return true;
8990 
8991   Node* input = argument(1);
8992   Node* input_offset = argument(2);
8993   Node* len = argument(3);
8994   Node* alimbs = argument(4);
8995   Node* rlimbs = argument(5);
8996 
8997   input = must_be_not_null(input, true);
8998   alimbs = must_be_not_null(alimbs, true);
8999   rlimbs = must_be_not_null(rlimbs, true);
9000 
9001   Node* input_start = array_element_address(input, input_offset, T_BYTE);
9002   assert(input_start, "input array is null");
9003   Node* acc_start = array_element_address(alimbs, intcon(0), T_LONG);
9004   assert(acc_start, "acc array is null");
9005   Node* r_start = array_element_address(rlimbs, intcon(0), T_LONG);
9006   assert(r_start, "r array is null");
9007 
9008   Node* call = make_runtime_call(RC_LEAF | RC_NO_FP,
9009                                  OptoRuntime::poly1305_processBlocks_Type(),
9010                                  stubAddr, stubName, TypePtr::BOTTOM,
9011                                  input_start, len, acc_start, r_start);
9012   return true;
9013 }
9014 
9015 bool LibraryCallKit::inline_intpoly_montgomeryMult_P256() {
9016   address stubAddr;
9017   const char *stubName;
9018   assert(UseIntPolyIntrinsics, "need intpoly intrinsics support");
9019   assert(callee()->signature()->size() == 3, "intpoly_montgomeryMult_P256 has %d parameters", callee()->signature()->size());
9020   stubAddr = StubRoutines::intpoly_montgomeryMult_P256();
9021   stubName = "intpoly_montgomeryMult_P256";
9022 
9023   if (!stubAddr) return false;
9024   null_check_receiver();  // null-check receiver
9025   if (stopped())  return true;
9026 
9027   Node* a = argument(1);
9028   Node* b = argument(2);
9029   Node* r = argument(3);
9030 
9031   a = must_be_not_null(a, true);
9032   b = must_be_not_null(b, true);
9033   r = must_be_not_null(r, true);
9034 
9035   Node* a_start = array_element_address(a, intcon(0), T_LONG);
9036   assert(a_start, "a array is null");
9037   Node* b_start = array_element_address(b, intcon(0), T_LONG);
9038   assert(b_start, "b array is null");
9039   Node* r_start = array_element_address(r, intcon(0), T_LONG);
9040   assert(r_start, "r array is null");
9041 
9042   Node* call = make_runtime_call(RC_LEAF | RC_NO_FP,
9043                                  OptoRuntime::intpoly_montgomeryMult_P256_Type(),
9044                                  stubAddr, stubName, TypePtr::BOTTOM,
9045                                  a_start, b_start, r_start);
9046   return true;
9047 }
9048 
9049 bool LibraryCallKit::inline_intpoly_assign() {
9050   assert(UseIntPolyIntrinsics, "need intpoly intrinsics support");
9051   assert(callee()->signature()->size() == 3, "intpoly_assign has %d parameters", callee()->signature()->size());
9052   const char *stubName = "intpoly_assign";
9053   address stubAddr = StubRoutines::intpoly_assign();
9054   if (!stubAddr) return false;
9055 
9056   Node* set = argument(0);
9057   Node* a = argument(1);
9058   Node* b = argument(2);
9059   Node* arr_length = load_array_length(a);
9060 
9061   a = must_be_not_null(a, true);
9062   b = must_be_not_null(b, true);
9063 
9064   Node* a_start = array_element_address(a, intcon(0), T_LONG);
9065   assert(a_start, "a array is null");
9066   Node* b_start = array_element_address(b, intcon(0), T_LONG);
9067   assert(b_start, "b array is null");
9068 
9069   Node* call = make_runtime_call(RC_LEAF | RC_NO_FP,
9070                                  OptoRuntime::intpoly_assign_Type(),
9071                                  stubAddr, stubName, TypePtr::BOTTOM,
9072                                  set, a_start, b_start, arr_length);
9073   return true;
9074 }
9075 
9076 //------------------------------inline_digestBase_implCompress-----------------------
9077 //
9078 // Calculate MD5 for single-block byte[] array.
9079 // void com.sun.security.provider.MD5.implCompress(byte[] buf, int ofs)
9080 //
9081 // Calculate SHA (i.e., SHA-1) for single-block byte[] array.
9082 // void com.sun.security.provider.SHA.implCompress(byte[] buf, int ofs)
9083 //
9084 // Calculate SHA2 (i.e., SHA-244 or SHA-256) for single-block byte[] array.
9085 // void com.sun.security.provider.SHA2.implCompress(byte[] buf, int ofs)
9086 //
9087 // Calculate SHA5 (i.e., SHA-384 or SHA-512) for single-block byte[] array.
9088 // void com.sun.security.provider.SHA5.implCompress(byte[] buf, int ofs)
9089 //
9090 // Calculate SHA3 (i.e., SHA3-224 or SHA3-256 or SHA3-384 or SHA3-512) for single-block byte[] array.
9091 // void com.sun.security.provider.SHA3.implCompress(byte[] buf, int ofs)
9092 //
9093 bool LibraryCallKit::inline_digestBase_implCompress(vmIntrinsics::ID id) {
9094   assert(callee()->signature()->size() == 2, "sha_implCompress has 2 parameters");
9095 
9096   Node* digestBase_obj = argument(0);
9097   Node* src            = argument(1); // type oop
9098   Node* ofs            = argument(2); // type int
9099 
9100   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
9101   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
9102     // failed array check
9103     return false;
9104   }
9105   // Figure out the size and type of the elements we will be copying.
9106   BasicType src_elem = src_type->elem()->array_element_basic_type();
9107   if (src_elem != T_BYTE) {
9108     return false;
9109   }
9110   // 'src_start' points to src array + offset
9111   src = must_be_not_null(src, true);
9112   Node* src_start = array_element_address(src, ofs, src_elem);
9113   Node* state = nullptr;
9114   Node* block_size = nullptr;
9115   address stubAddr;
9116   const char *stubName;
9117 
9118   switch(id) {
9119   case vmIntrinsics::_md5_implCompress:
9120     assert(UseMD5Intrinsics, "need MD5 instruction support");
9121     state = get_state_from_digest_object(digestBase_obj, T_INT);
9122     stubAddr = StubRoutines::md5_implCompress();
9123     stubName = "md5_implCompress";
9124     break;
9125   case vmIntrinsics::_sha_implCompress:
9126     assert(UseSHA1Intrinsics, "need SHA1 instruction support");
9127     state = get_state_from_digest_object(digestBase_obj, T_INT);
9128     stubAddr = StubRoutines::sha1_implCompress();
9129     stubName = "sha1_implCompress";
9130     break;
9131   case vmIntrinsics::_sha2_implCompress:
9132     assert(UseSHA256Intrinsics, "need SHA256 instruction support");
9133     state = get_state_from_digest_object(digestBase_obj, T_INT);
9134     stubAddr = StubRoutines::sha256_implCompress();
9135     stubName = "sha256_implCompress";
9136     break;
9137   case vmIntrinsics::_sha5_implCompress:
9138     assert(UseSHA512Intrinsics, "need SHA512 instruction support");
9139     state = get_state_from_digest_object(digestBase_obj, T_LONG);
9140     stubAddr = StubRoutines::sha512_implCompress();
9141     stubName = "sha512_implCompress";
9142     break;
9143   case vmIntrinsics::_sha3_implCompress:
9144     assert(UseSHA3Intrinsics, "need SHA3 instruction support");
9145     state = get_state_from_digest_object(digestBase_obj, T_LONG);
9146     stubAddr = StubRoutines::sha3_implCompress();
9147     stubName = "sha3_implCompress";
9148     block_size = get_block_size_from_digest_object(digestBase_obj);
9149     if (block_size == nullptr) return false;
9150     break;
9151   default:
9152     fatal_unexpected_iid(id);
9153     return false;
9154   }
9155   if (state == nullptr) return false;
9156 
9157   assert(stubAddr != nullptr, "Stub %s is not generated", stubName);
9158   if (stubAddr == nullptr) return false;
9159 
9160   // Call the stub.
9161   Node* call;
9162   if (block_size == nullptr) {
9163     call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::digestBase_implCompress_Type(false),
9164                              stubAddr, stubName, TypePtr::BOTTOM,
9165                              src_start, state);
9166   } else {
9167     call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::digestBase_implCompress_Type(true),
9168                              stubAddr, stubName, TypePtr::BOTTOM,
9169                              src_start, state, block_size);
9170   }
9171 
9172   return true;
9173 }
9174 
9175 //------------------------------inline_double_keccak
9176 bool LibraryCallKit::inline_double_keccak() {
9177   address stubAddr;
9178   const char *stubName;
9179   assert(UseSHA3Intrinsics, "need SHA3 intrinsics support");
9180   assert(callee()->signature()->size() == 2, "double_keccak has 2 parameters");
9181 
9182   stubAddr = StubRoutines::double_keccak();
9183   stubName = "double_keccak";
9184   if (!stubAddr) return false;
9185 
9186   Node* status0        = argument(0);
9187   Node* status1        = argument(1);
9188 
9189   status0 = must_be_not_null(status0, true);
9190   status1 = must_be_not_null(status1, true);
9191 
9192   Node* status0_start  = array_element_address(status0, intcon(0), T_LONG);
9193   assert(status0_start, "status0 is null");
9194   Node* status1_start  = array_element_address(status1, intcon(0), T_LONG);
9195   assert(status1_start, "status1 is null");
9196   Node* double_keccak = make_runtime_call(RC_LEAF|RC_NO_FP,
9197                                   OptoRuntime::double_keccak_Type(),
9198                                   stubAddr, stubName, TypePtr::BOTTOM,
9199                                   status0_start, status1_start);
9200   // return an int
9201   Node* retvalue = _gvn.transform(new ProjNode(double_keccak, TypeFunc::Parms));
9202   set_result(retvalue);
9203   return true;
9204 }
9205 
9206 
9207 //------------------------------inline_digestBase_implCompressMB-----------------------
9208 //
9209 // Calculate MD5/SHA/SHA2/SHA5/SHA3 for multi-block byte[] array.
9210 // int com.sun.security.provider.DigestBase.implCompressMultiBlock(byte[] b, int ofs, int limit)
9211 //
9212 bool LibraryCallKit::inline_digestBase_implCompressMB(int predicate) {
9213   assert(UseMD5Intrinsics || UseSHA1Intrinsics || UseSHA256Intrinsics || UseSHA512Intrinsics || UseSHA3Intrinsics,
9214          "need MD5/SHA1/SHA256/SHA512/SHA3 instruction support");
9215   assert((uint)predicate < 5, "sanity");
9216   assert(callee()->signature()->size() == 3, "digestBase_implCompressMB has 3 parameters");
9217 
9218   Node* digestBase_obj = argument(0); // The receiver was checked for null already.
9219   Node* src            = argument(1); // byte[] array
9220   Node* ofs            = argument(2); // type int
9221   Node* limit          = argument(3); // type int
9222 
9223   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
9224   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
9225     // failed array check
9226     return false;
9227   }
9228   // Figure out the size and type of the elements we will be copying.
9229   BasicType src_elem = src_type->elem()->array_element_basic_type();
9230   if (src_elem != T_BYTE) {
9231     return false;
9232   }
9233   // 'src_start' points to src array + offset
9234   src = must_be_not_null(src, false);
9235   Node* src_start = array_element_address(src, ofs, src_elem);
9236 
9237   const char* klass_digestBase_name = nullptr;
9238   const char* stub_name = nullptr;
9239   address     stub_addr = nullptr;
9240   BasicType elem_type = T_INT;
9241 
9242   switch (predicate) {
9243   case 0:
9244     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_md5_implCompress)) {
9245       klass_digestBase_name = "sun/security/provider/MD5";
9246       stub_name = "md5_implCompressMB";
9247       stub_addr = StubRoutines::md5_implCompressMB();
9248     }
9249     break;
9250   case 1:
9251     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha_implCompress)) {
9252       klass_digestBase_name = "sun/security/provider/SHA";
9253       stub_name = "sha1_implCompressMB";
9254       stub_addr = StubRoutines::sha1_implCompressMB();
9255     }
9256     break;
9257   case 2:
9258     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha2_implCompress)) {
9259       klass_digestBase_name = "sun/security/provider/SHA2";
9260       stub_name = "sha256_implCompressMB";
9261       stub_addr = StubRoutines::sha256_implCompressMB();
9262     }
9263     break;
9264   case 3:
9265     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha5_implCompress)) {
9266       klass_digestBase_name = "sun/security/provider/SHA5";
9267       stub_name = "sha512_implCompressMB";
9268       stub_addr = StubRoutines::sha512_implCompressMB();
9269       elem_type = T_LONG;
9270     }
9271     break;
9272   case 4:
9273     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha3_implCompress)) {
9274       klass_digestBase_name = "sun/security/provider/SHA3";
9275       stub_name = "sha3_implCompressMB";
9276       stub_addr = StubRoutines::sha3_implCompressMB();
9277       elem_type = T_LONG;
9278     }
9279     break;
9280   default:
9281     fatal("unknown DigestBase intrinsic predicate: %d", predicate);
9282   }
9283   if (klass_digestBase_name != nullptr) {
9284     assert(stub_addr != nullptr, "Stub is generated");
9285     if (stub_addr == nullptr) return false;
9286 
9287     // get DigestBase klass to lookup for SHA klass
9288     const TypeInstPtr* tinst = _gvn.type(digestBase_obj)->isa_instptr();
9289     assert(tinst != nullptr, "digestBase_obj is not instance???");
9290     assert(tinst->is_loaded(), "DigestBase is not loaded");
9291 
9292     ciKlass* klass_digestBase = tinst->instance_klass()->find_klass(ciSymbol::make(klass_digestBase_name));
9293     assert(klass_digestBase->is_loaded(), "predicate checks that this class is loaded");
9294     ciInstanceKlass* instklass_digestBase = klass_digestBase->as_instance_klass();
9295     return inline_digestBase_implCompressMB(digestBase_obj, instklass_digestBase, elem_type, stub_addr, stub_name, src_start, ofs, limit);
9296   }
9297   return false;
9298 }
9299 
9300 //------------------------------inline_digestBase_implCompressMB-----------------------
9301 bool LibraryCallKit::inline_digestBase_implCompressMB(Node* digestBase_obj, ciInstanceKlass* instklass_digestBase,
9302                                                       BasicType elem_type, address stubAddr, const char *stubName,
9303                                                       Node* src_start, Node* ofs, Node* limit) {
9304   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_digestBase);
9305   const TypeOopPtr* xtype = aklass->cast_to_exactness(false)->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
9306   Node* digest_obj = new CheckCastPPNode(control(), digestBase_obj, xtype);
9307   digest_obj = _gvn.transform(digest_obj);
9308 
9309   Node* state = get_state_from_digest_object(digest_obj, elem_type);
9310   if (state == nullptr) return false;
9311 
9312   Node* block_size = nullptr;
9313   if (strcmp("sha3_implCompressMB", stubName) == 0) {
9314     block_size = get_block_size_from_digest_object(digest_obj);
9315     if (block_size == nullptr) return false;
9316   }
9317 
9318   // Call the stub.
9319   Node* call;
9320   if (block_size == nullptr) {
9321     call = make_runtime_call(RC_LEAF|RC_NO_FP,
9322                              OptoRuntime::digestBase_implCompressMB_Type(false),
9323                              stubAddr, stubName, TypePtr::BOTTOM,
9324                              src_start, state, ofs, limit);
9325   } else {
9326      call = make_runtime_call(RC_LEAF|RC_NO_FP,
9327                              OptoRuntime::digestBase_implCompressMB_Type(true),
9328                              stubAddr, stubName, TypePtr::BOTTOM,
9329                              src_start, state, block_size, ofs, limit);
9330   }
9331 
9332   // return ofs (int)
9333   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
9334   set_result(result);
9335 
9336   return true;
9337 }
9338 
9339 //------------------------------inline_galoisCounterMode_AESCrypt-----------------------
9340 bool LibraryCallKit::inline_galoisCounterMode_AESCrypt() {
9341   assert(UseAES, "need AES instruction support");
9342   address stubAddr = nullptr;
9343   const char *stubName = nullptr;
9344   stubAddr = StubRoutines::galoisCounterMode_AESCrypt();
9345   stubName = "galoisCounterMode_AESCrypt";
9346 
9347   if (stubAddr == nullptr) return false;
9348 
9349   Node* in      = argument(0);
9350   Node* inOfs   = argument(1);
9351   Node* len     = argument(2);
9352   Node* ct      = argument(3);
9353   Node* ctOfs   = argument(4);
9354   Node* out     = argument(5);
9355   Node* outOfs  = argument(6);
9356   Node* gctr_object = argument(7);
9357   Node* ghash_object = argument(8);
9358 
9359   // (1) in, ct and out are arrays.
9360   const TypeAryPtr* in_type = in->Value(&_gvn)->isa_aryptr();
9361   const TypeAryPtr* ct_type = ct->Value(&_gvn)->isa_aryptr();
9362   const TypeAryPtr* out_type = out->Value(&_gvn)->isa_aryptr();
9363   assert( in_type != nullptr &&  in_type->elem() != Type::BOTTOM &&
9364           ct_type != nullptr &&  ct_type->elem() != Type::BOTTOM &&
9365          out_type != nullptr && out_type->elem() != Type::BOTTOM, "args are strange");
9366 
9367   // checks are the responsibility of the caller
9368   Node* in_start = in;
9369   Node* ct_start = ct;
9370   Node* out_start = out;
9371   if (inOfs != nullptr || ctOfs != nullptr || outOfs != nullptr) {
9372     assert(inOfs != nullptr && ctOfs != nullptr && outOfs != nullptr, "");
9373     in_start = array_element_address(in, inOfs, T_BYTE);
9374     ct_start = array_element_address(ct, ctOfs, T_BYTE);
9375     out_start = array_element_address(out, outOfs, T_BYTE);
9376   }
9377 
9378   // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
9379   // (because of the predicated logic executed earlier).
9380   // so we cast it here safely.
9381   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
9382   Node* embeddedCipherObj = load_field_from_object(gctr_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
9383   Node* counter = load_field_from_object(gctr_object, "counter", "[B");
9384   Node* subkeyHtbl = load_field_from_object(ghash_object, "subkeyHtbl", "[J");
9385   Node* state = load_field_from_object(ghash_object, "state", "[J");
9386 
9387   if (embeddedCipherObj == nullptr || counter == nullptr || subkeyHtbl == nullptr || state == nullptr) {
9388     return false;
9389   }
9390   // cast it to what we know it will be at runtime
9391   const TypeInstPtr* tinst = _gvn.type(gctr_object)->isa_instptr();
9392   assert(tinst != nullptr, "GCTR obj is null");
9393   assert(tinst->is_loaded(), "GCTR obj is not loaded");
9394   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
9395   assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
9396   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
9397   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
9398   const TypeOopPtr* xtype = aklass->as_instance_type();
9399   Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
9400   aescrypt_object = _gvn.transform(aescrypt_object);
9401   // we need to get the start of the aescrypt_object's expanded key array
9402   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object, /* is_decrypt */ false);
9403   if (k_start == nullptr) return false;
9404   // similarly, get the start address of the r vector
9405   Node* cnt_start = array_element_address(counter, intcon(0), T_BYTE);
9406   Node* state_start = array_element_address(state, intcon(0), T_LONG);
9407   Node* subkeyHtbl_start = array_element_address(subkeyHtbl, intcon(0), T_LONG);
9408 
9409 
9410   // Call the stub, passing params
9411   Node* gcmCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
9412                                OptoRuntime::galoisCounterMode_aescrypt_Type(),
9413                                stubAddr, stubName, TypePtr::BOTTOM,
9414                                in_start, len, ct_start, out_start, k_start, state_start, subkeyHtbl_start, cnt_start);
9415 
9416   // return cipher length (int)
9417   Node* retvalue = _gvn.transform(new ProjNode(gcmCrypt, TypeFunc::Parms));
9418   set_result(retvalue);
9419 
9420   return true;
9421 }
9422 
9423 //----------------------------inline_galoisCounterMode_AESCrypt_predicate----------------------------
9424 // Return node representing slow path of predicate check.
9425 // the pseudo code we want to emulate with this predicate is:
9426 // for encryption:
9427 //    if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
9428 // for decryption:
9429 //    if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
9430 //    note cipher==plain is more conservative than the original java code but that's OK
9431 //
9432 
9433 Node* LibraryCallKit::inline_galoisCounterMode_AESCrypt_predicate() {
9434   // The receiver was checked for null already.
9435   Node* objGCTR = argument(7);
9436   // Load embeddedCipher field of GCTR object.
9437   Node* embeddedCipherObj = load_field_from_object(objGCTR, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
9438   assert(embeddedCipherObj != nullptr, "embeddedCipherObj is null");
9439 
9440   // get AESCrypt klass for instanceOf check
9441   // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
9442   // will have same classloader as CipherBlockChaining object
9443   const TypeInstPtr* tinst = _gvn.type(objGCTR)->isa_instptr();
9444   assert(tinst != nullptr, "GCTR obj is null");
9445   assert(tinst->is_loaded(), "GCTR obj is not loaded");
9446 
9447   // we want to do an instanceof comparison against the AESCrypt class
9448   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
9449   if (!klass_AESCrypt->is_loaded()) {
9450     // if AESCrypt is not even loaded, we never take the intrinsic fast path
9451     Node* ctrl = control();
9452     set_control(top()); // no regular fast path
9453     return ctrl;
9454   }
9455 
9456   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
9457   Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
9458   Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
9459   Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
9460   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
9461 
9462   return instof_false; // even if it is null
9463 }
9464 
9465 //------------------------------get_state_from_digest_object-----------------------
9466 Node * LibraryCallKit::get_state_from_digest_object(Node *digest_object, BasicType elem_type) {
9467   const char* state_type;
9468   switch (elem_type) {
9469     case T_BYTE: state_type = "[B"; break;
9470     case T_INT:  state_type = "[I"; break;
9471     case T_LONG: state_type = "[J"; break;
9472     default: ShouldNotReachHere();
9473   }
9474   Node* digest_state = load_field_from_object(digest_object, "state", state_type);
9475   assert (digest_state != nullptr, "wrong version of sun.security.provider.MD5/SHA/SHA2/SHA5/SHA3");
9476   if (digest_state == nullptr) return (Node *) nullptr;
9477 
9478   // now have the array, need to get the start address of the state array
9479   Node* state = array_element_address(digest_state, intcon(0), elem_type);
9480   return state;
9481 }
9482 
9483 //------------------------------get_block_size_from_sha3_object----------------------------------
9484 Node * LibraryCallKit::get_block_size_from_digest_object(Node *digest_object) {
9485   Node* block_size = load_field_from_object(digest_object, "blockSize", "I");
9486   assert (block_size != nullptr, "sanity");
9487   return block_size;
9488 }
9489 
9490 //----------------------------inline_digestBase_implCompressMB_predicate----------------------------
9491 // Return node representing slow path of predicate check.
9492 // the pseudo code we want to emulate with this predicate is:
9493 //    if (digestBaseObj instanceof MD5/SHA/SHA2/SHA5/SHA3) do_intrinsic, else do_javapath
9494 //
9495 Node* LibraryCallKit::inline_digestBase_implCompressMB_predicate(int predicate) {
9496   assert(UseMD5Intrinsics || UseSHA1Intrinsics || UseSHA256Intrinsics || UseSHA512Intrinsics || UseSHA3Intrinsics,
9497          "need MD5/SHA1/SHA256/SHA512/SHA3 instruction support");
9498   assert((uint)predicate < 5, "sanity");
9499 
9500   // The receiver was checked for null already.
9501   Node* digestBaseObj = argument(0);
9502 
9503   // get DigestBase klass for instanceOf check
9504   const TypeInstPtr* tinst = _gvn.type(digestBaseObj)->isa_instptr();
9505   assert(tinst != nullptr, "digestBaseObj is null");
9506   assert(tinst->is_loaded(), "DigestBase is not loaded");
9507 
9508   const char* klass_name = nullptr;
9509   switch (predicate) {
9510   case 0:
9511     if (UseMD5Intrinsics) {
9512       // we want to do an instanceof comparison against the MD5 class
9513       klass_name = "sun/security/provider/MD5";
9514     }
9515     break;
9516   case 1:
9517     if (UseSHA1Intrinsics) {
9518       // we want to do an instanceof comparison against the SHA class
9519       klass_name = "sun/security/provider/SHA";
9520     }
9521     break;
9522   case 2:
9523     if (UseSHA256Intrinsics) {
9524       // we want to do an instanceof comparison against the SHA2 class
9525       klass_name = "sun/security/provider/SHA2";
9526     }
9527     break;
9528   case 3:
9529     if (UseSHA512Intrinsics) {
9530       // we want to do an instanceof comparison against the SHA5 class
9531       klass_name = "sun/security/provider/SHA5";
9532     }
9533     break;
9534   case 4:
9535     if (UseSHA3Intrinsics) {
9536       // we want to do an instanceof comparison against the SHA3 class
9537       klass_name = "sun/security/provider/SHA3";
9538     }
9539     break;
9540   default:
9541     fatal("unknown SHA intrinsic predicate: %d", predicate);
9542   }
9543 
9544   ciKlass* klass = nullptr;
9545   if (klass_name != nullptr) {
9546     klass = tinst->instance_klass()->find_klass(ciSymbol::make(klass_name));
9547   }
9548   if ((klass == nullptr) || !klass->is_loaded()) {
9549     // if none of MD5/SHA/SHA2/SHA5 is loaded, we never take the intrinsic fast path
9550     Node* ctrl = control();
9551     set_control(top()); // no intrinsic path
9552     return ctrl;
9553   }
9554   ciInstanceKlass* instklass = klass->as_instance_klass();
9555 
9556   Node* instof = gen_instanceof(digestBaseObj, makecon(TypeKlassPtr::make(instklass)));
9557   Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
9558   Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
9559   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
9560 
9561   return instof_false;  // even if it is null
9562 }
9563 
9564 //-------------inline_fma-----------------------------------
9565 bool LibraryCallKit::inline_fma(vmIntrinsics::ID id) {
9566   Node *a = nullptr;
9567   Node *b = nullptr;
9568   Node *c = nullptr;
9569   Node* result = nullptr;
9570   switch (id) {
9571   case vmIntrinsics::_fmaD:
9572     assert(callee()->signature()->size() == 6, "fma has 3 parameters of size 2 each.");
9573     // no receiver since it is static method
9574     a = argument(0);
9575     b = argument(2);
9576     c = argument(4);
9577     result = _gvn.transform(new FmaDNode(a, b, c));
9578     break;
9579   case vmIntrinsics::_fmaF:
9580     assert(callee()->signature()->size() == 3, "fma has 3 parameters of size 1 each.");
9581     a = argument(0);
9582     b = argument(1);
9583     c = argument(2);
9584     result = _gvn.transform(new FmaFNode(a, b, c));
9585     break;
9586   default:
9587     fatal_unexpected_iid(id);  break;
9588   }
9589   set_result(result);
9590   return true;
9591 }
9592 
9593 bool LibraryCallKit::inline_character_compare(vmIntrinsics::ID id) {
9594   // argument(0) is receiver
9595   Node* codePoint = argument(1);
9596   Node* n = nullptr;
9597 
9598   switch (id) {
9599     case vmIntrinsics::_isDigit :
9600       n = new DigitNode(control(), codePoint);
9601       break;
9602     case vmIntrinsics::_isLowerCase :
9603       n = new LowerCaseNode(control(), codePoint);
9604       break;
9605     case vmIntrinsics::_isUpperCase :
9606       n = new UpperCaseNode(control(), codePoint);
9607       break;
9608     case vmIntrinsics::_isWhitespace :
9609       n = new WhitespaceNode(control(), codePoint);
9610       break;
9611     default:
9612       fatal_unexpected_iid(id);
9613   }
9614 
9615   set_result(_gvn.transform(n));
9616   return true;
9617 }
9618 
9619 bool LibraryCallKit::inline_profileBoolean() {
9620   Node* counts = argument(1);
9621   const TypeAryPtr* ary = nullptr;
9622   ciArray* aobj = nullptr;
9623   if (counts->is_Con()
9624       && (ary = counts->bottom_type()->isa_aryptr()) != nullptr
9625       && (aobj = ary->const_oop()->as_array()) != nullptr
9626       && (aobj->length() == 2)) {
9627     // Profile is int[2] where [0] and [1] correspond to false and true value occurrences respectively.
9628     jint false_cnt = aobj->element_value(0).as_int();
9629     jint  true_cnt = aobj->element_value(1).as_int();
9630 
9631     if (C->log() != nullptr) {
9632       C->log()->elem("observe source='profileBoolean' false='%d' true='%d'",
9633                      false_cnt, true_cnt);
9634     }
9635 
9636     if (false_cnt + true_cnt == 0) {
9637       // According to profile, never executed.
9638       uncommon_trap_exact(Deoptimization::Reason_intrinsic,
9639                           Deoptimization::Action_reinterpret);
9640       return true;
9641     }
9642 
9643     // result is a boolean (0 or 1) and its profile (false_cnt & true_cnt)
9644     // is a number of each value occurrences.
9645     Node* result = argument(0);
9646     if (false_cnt == 0 || true_cnt == 0) {
9647       // According to profile, one value has been never seen.
9648       int expected_val = (false_cnt == 0) ? 1 : 0;
9649 
9650       Node* cmp  = _gvn.transform(new CmpINode(result, intcon(expected_val)));
9651       Node* test = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
9652 
9653       IfNode* check = create_and_map_if(control(), test, PROB_ALWAYS, COUNT_UNKNOWN);
9654       Node* fast_path = _gvn.transform(new IfTrueNode(check));
9655       Node* slow_path = _gvn.transform(new IfFalseNode(check));
9656 
9657       { // Slow path: uncommon trap for never seen value and then reexecute
9658         // MethodHandleImpl::profileBoolean() to bump the count, so JIT knows
9659         // the value has been seen at least once.
9660         PreserveJVMState pjvms(this);
9661         PreserveReexecuteState preexecs(this);
9662         jvms()->set_should_reexecute(true);
9663 
9664         set_control(slow_path);
9665         set_i_o(i_o());
9666 
9667         uncommon_trap_exact(Deoptimization::Reason_intrinsic,
9668                             Deoptimization::Action_reinterpret);
9669       }
9670       // The guard for never seen value enables sharpening of the result and
9671       // returning a constant. It allows to eliminate branches on the same value
9672       // later on.
9673       set_control(fast_path);
9674       result = intcon(expected_val);
9675     }
9676     // Stop profiling.
9677     // MethodHandleImpl::profileBoolean() has profiling logic in its bytecode.
9678     // By replacing method body with profile data (represented as ProfileBooleanNode
9679     // on IR level) we effectively disable profiling.
9680     // It enables full speed execution once optimized code is generated.
9681     Node* profile = _gvn.transform(new ProfileBooleanNode(result, false_cnt, true_cnt));
9682     C->record_for_igvn(profile);
9683     set_result(profile);
9684     return true;
9685   } else {
9686     // Continue profiling.
9687     // Profile data isn't available at the moment. So, execute method's bytecode version.
9688     // Usually, when GWT LambdaForms are profiled it means that a stand-alone nmethod
9689     // is compiled and counters aren't available since corresponding MethodHandle
9690     // isn't a compile-time constant.
9691     return false;
9692   }
9693 }
9694 
9695 bool LibraryCallKit::inline_isCompileConstant() {
9696   Node* n = argument(0);
9697   set_result(n->is_Con() ? intcon(1) : intcon(0));
9698   return true;
9699 }
9700 
9701 //------------------------------- inline_getObjectSize --------------------------------------
9702 //
9703 // Calculate the runtime size of the object/array.
9704 //   native long sun.instrument.InstrumentationImpl.getObjectSize0(long nativeAgent, Object objectToSize);
9705 //
9706 bool LibraryCallKit::inline_getObjectSize() {
9707   Node* obj = argument(3);
9708   Node* klass_node = load_object_klass(obj);
9709 
9710   jint  layout_con = Klass::_lh_neutral_value;
9711   Node* layout_val = get_layout_helper(klass_node, layout_con);
9712   int   layout_is_con = (layout_val == nullptr);
9713 
9714   if (layout_is_con) {
9715     // Layout helper is constant, can figure out things at compile time.
9716 
9717     if (Klass::layout_helper_is_instance(layout_con)) {
9718       // Instance case:  layout_con contains the size itself.
9719       Node *size = longcon(Klass::layout_helper_size_in_bytes(layout_con));
9720       set_result(size);
9721     } else {
9722       // Array case: size is round(header + element_size*arraylength).
9723       // Since arraylength is different for every array instance, we have to
9724       // compute the whole thing at runtime.
9725 
9726       Node* arr_length = load_array_length(obj);
9727 
9728       int round_mask = MinObjAlignmentInBytes - 1;
9729       int hsize  = Klass::layout_helper_header_size(layout_con);
9730       int eshift = Klass::layout_helper_log2_element_size(layout_con);
9731 
9732       if ((round_mask & ~right_n_bits(eshift)) == 0) {
9733         round_mask = 0;  // strength-reduce it if it goes away completely
9734       }
9735       assert((hsize & right_n_bits(eshift)) == 0, "hsize is pre-rounded");
9736       Node* header_size = intcon(hsize + round_mask);
9737 
9738       Node* lengthx = ConvI2X(arr_length);
9739       Node* headerx = ConvI2X(header_size);
9740 
9741       Node* abody = lengthx;
9742       if (eshift != 0) {
9743         abody = _gvn.transform(new LShiftXNode(lengthx, intcon(eshift)));
9744       }
9745       Node* size = _gvn.transform( new AddXNode(headerx, abody) );
9746       if (round_mask != 0) {
9747         size = _gvn.transform( new AndXNode(size, MakeConX(~round_mask)) );
9748       }
9749       size = ConvX2L(size);
9750       set_result(size);
9751     }
9752   } else {
9753     // Layout helper is not constant, need to test for array-ness at runtime.
9754 
9755     enum { _instance_path = 1, _array_path, PATH_LIMIT };
9756     RegionNode* result_reg = new RegionNode(PATH_LIMIT);
9757     PhiNode* result_val = new PhiNode(result_reg, TypeLong::LONG);
9758     record_for_igvn(result_reg);
9759 
9760     Node* array_ctl = generate_array_guard(klass_node, nullptr, &obj);
9761     if (array_ctl != nullptr) {
9762       // Array case: size is round(header + element_size*arraylength).
9763       // Since arraylength is different for every array instance, we have to
9764       // compute the whole thing at runtime.
9765 
9766       PreserveJVMState pjvms(this);
9767       set_control(array_ctl);
9768       Node* arr_length = load_array_length(obj);
9769 
9770       int round_mask = MinObjAlignmentInBytes - 1;
9771       Node* mask = intcon(round_mask);
9772 
9773       Node* hss = intcon(Klass::_lh_header_size_shift);
9774       Node* hsm = intcon(Klass::_lh_header_size_mask);
9775       Node* header_size = _gvn.transform(new URShiftINode(layout_val, hss));
9776       header_size = _gvn.transform(new AndINode(header_size, hsm));
9777       header_size = _gvn.transform(new AddINode(header_size, mask));
9778 
9779       // There is no need to mask or shift this value.
9780       // The semantics of LShiftINode include an implicit mask to 0x1F.
9781       assert(Klass::_lh_log2_element_size_shift == 0, "use shift in place");
9782       Node* elem_shift = layout_val;
9783 
9784       Node* lengthx = ConvI2X(arr_length);
9785       Node* headerx = ConvI2X(header_size);
9786 
9787       Node* abody = _gvn.transform(new LShiftXNode(lengthx, elem_shift));
9788       Node* size = _gvn.transform(new AddXNode(headerx, abody));
9789       if (round_mask != 0) {
9790         size = _gvn.transform(new AndXNode(size, MakeConX(~round_mask)));
9791       }
9792       size = ConvX2L(size);
9793 
9794       result_reg->init_req(_array_path, control());
9795       result_val->init_req(_array_path, size);
9796     }
9797 
9798     if (!stopped()) {
9799       // Instance case: the layout helper gives us instance size almost directly,
9800       // but we need to mask out the _lh_instance_slow_path_bit.
9801       Node* size = ConvI2X(layout_val);
9802       assert((int) Klass::_lh_instance_slow_path_bit < BytesPerLong, "clear bit");
9803       Node* mask = MakeConX(~(intptr_t) right_n_bits(LogBytesPerLong));
9804       size = _gvn.transform(new AndXNode(size, mask));
9805       size = ConvX2L(size);
9806 
9807       result_reg->init_req(_instance_path, control());
9808       result_val->init_req(_instance_path, size);
9809     }
9810 
9811     set_result(result_reg, result_val);
9812   }
9813 
9814   return true;
9815 }
9816 
9817 //------------------------------- inline_blackhole --------------------------------------
9818 //
9819 // Make sure all arguments to this node are alive.
9820 // This matches methods that were requested to be blackholed through compile commands.
9821 //
9822 bool LibraryCallKit::inline_blackhole() {
9823   assert(callee()->is_static(), "Should have been checked before: only static methods here");
9824   assert(callee()->is_empty(), "Should have been checked before: only empty methods here");
9825   assert(callee()->holder()->is_loaded(), "Should have been checked before: only methods for loaded classes here");
9826 
9827   // Blackhole node pinches only the control, not memory. This allows
9828   // the blackhole to be pinned in the loop that computes blackholed
9829   // values, but have no other side effects, like breaking the optimizations
9830   // across the blackhole.
9831 
9832   Node* bh = _gvn.transform(new BlackholeNode(control()));
9833   set_control(_gvn.transform(new ProjNode(bh, TypeFunc::Control)));
9834 
9835   // Bind call arguments as blackhole arguments to keep them alive
9836   uint nargs = callee()->arg_size();
9837   for (uint i = 0; i < nargs; i++) {
9838     bh->add_req(argument(i));
9839   }
9840 
9841   return true;
9842 }
9843 
9844 Node* LibraryCallKit::unbox_fp16_value(const TypeInstPtr* float16_box_type, ciField* field, Node* box) {
9845   const TypeInstPtr* box_type = _gvn.type(box)->isa_instptr();
9846   if (box_type == nullptr || box_type->instance_klass() != float16_box_type->instance_klass()) {
9847     return nullptr; // box klass is not Float16
9848   }
9849 
9850   // Null check; get notnull casted pointer
9851   Node* null_ctl = top();
9852   Node* not_null_box = null_check_oop(box, &null_ctl, true);
9853   // If not_null_box is dead, only null-path is taken
9854   if (stopped()) {
9855     set_control(null_ctl);
9856     return nullptr;
9857   }
9858   assert(not_null_box->bottom_type()->is_instptr()->maybe_null() == false, "");
9859   const TypePtr* adr_type = C->alias_type(field)->adr_type();
9860   Node* adr = basic_plus_adr(not_null_box, field->offset_in_bytes());
9861   return access_load_at(not_null_box, adr, adr_type, TypeInt::SHORT, T_SHORT, IN_HEAP);
9862 }
9863 
9864 Node* LibraryCallKit::box_fp16_value(const TypeInstPtr* float16_box_type, ciField* field, Node* value) {
9865   PreserveReexecuteState preexecs(this);
9866   jvms()->set_should_reexecute(true);
9867 
9868   const TypeKlassPtr* klass_type = float16_box_type->as_klass_type();
9869   Node* klass_node = makecon(klass_type);
9870   Node* box = new_instance(klass_node);
9871 
9872   Node* value_field = basic_plus_adr(box, field->offset_in_bytes());
9873   const TypePtr* value_adr_type = value_field->bottom_type()->is_ptr();
9874 
9875   Node* field_store = _gvn.transform(access_store_at(box,
9876                                                      value_field,
9877                                                      value_adr_type,
9878                                                      value,
9879                                                      TypeInt::SHORT,
9880                                                      T_SHORT,
9881                                                      IN_HEAP));
9882   set_memory(field_store, value_adr_type);
9883   return box;
9884 }
9885 
9886 bool LibraryCallKit::inline_fp16_operations(vmIntrinsics::ID id, int num_args) {
9887   if (!Matcher::match_rule_supported(Op_ReinterpretS2HF) ||
9888       !Matcher::match_rule_supported(Op_ReinterpretHF2S)) {
9889     return false;
9890   }
9891 
9892   const TypeInstPtr* box_type = _gvn.type(argument(0))->isa_instptr();
9893   if (box_type == nullptr || box_type->const_oop() == nullptr) {
9894     return false;
9895   }
9896 
9897   ciInstanceKlass* float16_klass = box_type->const_oop()->as_instance()->java_lang_Class_klass()->as_instance_klass();
9898   const TypeInstPtr* float16_box_type = TypeInstPtr::make_exact(TypePtr::NotNull, float16_klass);
9899   ciField* field = float16_klass->get_field_by_name(ciSymbols::value_name(),
9900                                                     ciSymbols::short_signature(),
9901                                                     false);
9902   assert(field != nullptr, "");
9903 
9904   // Transformed nodes
9905   Node* fld1 = nullptr;
9906   Node* fld2 = nullptr;
9907   Node* fld3 = nullptr;
9908   switch(num_args) {
9909     case 3:
9910       fld3 = unbox_fp16_value(float16_box_type, field, argument(3));
9911       if (fld3 == nullptr) {
9912         return false;
9913       }
9914       fld3 = _gvn.transform(new ReinterpretS2HFNode(fld3));
9915     // fall-through
9916     case 2:
9917       fld2 = unbox_fp16_value(float16_box_type, field, argument(2));
9918       if (fld2 == nullptr) {
9919         return false;
9920       }
9921       fld2 = _gvn.transform(new ReinterpretS2HFNode(fld2));
9922     // fall-through
9923     case 1:
9924       fld1 = unbox_fp16_value(float16_box_type, field, argument(1));
9925       if (fld1 == nullptr) {
9926         return false;
9927       }
9928       fld1 = _gvn.transform(new ReinterpretS2HFNode(fld1));
9929       break;
9930     default: fatal("Unsupported number of arguments %d", num_args);
9931   }
9932 
9933   Node* result = nullptr;
9934   switch (id) {
9935     // Unary operations
9936     case vmIntrinsics::_sqrt_float16:
9937       result = _gvn.transform(new SqrtHFNode(C, control(), fld1));
9938       break;
9939     // Ternary operations
9940     case vmIntrinsics::_fma_float16:
9941       result = _gvn.transform(new FmaHFNode(fld1, fld2, fld3));
9942       break;
9943     default:
9944       fatal_unexpected_iid(id);
9945       break;
9946   }
9947   result = _gvn.transform(new ReinterpretHF2SNode(result));
9948   set_result(box_fp16_value(float16_box_type, field, result));
9949   return true;
9950 }
9951