1 /*
   2  * Copyright (c) 1999, 2025, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "asm/macroAssembler.hpp"
  26 #include "ci/ciArrayKlass.hpp"
  27 #include "ci/ciFlatArrayKlass.hpp"
  28 #include "ci/ciInstanceKlass.hpp"
  29 #include "ci/ciSymbols.hpp"
  30 #include "ci/ciUtilities.inline.hpp"
  31 #include "classfile/vmIntrinsics.hpp"
  32 #include "compiler/compileBroker.hpp"
  33 #include "compiler/compileLog.hpp"
  34 #include "gc/shared/barrierSet.hpp"
  35 #include "gc/shared/c2/barrierSetC2.hpp"
  36 #include "jfr/support/jfrIntrinsics.hpp"
  37 #include "memory/resourceArea.hpp"
  38 #include "oops/accessDecorators.hpp"
  39 #include "oops/klass.inline.hpp"
  40 #include "oops/layoutKind.hpp"
  41 #include "oops/objArrayKlass.hpp"
  42 #include "opto/addnode.hpp"
  43 #include "opto/arraycopynode.hpp"
  44 #include "opto/c2compiler.hpp"
  45 #include "opto/castnode.hpp"
  46 #include "opto/cfgnode.hpp"
  47 #include "opto/convertnode.hpp"
  48 #include "opto/countbitsnode.hpp"
  49 #include "opto/graphKit.hpp"
  50 #include "opto/idealKit.hpp"
  51 #include "opto/inlinetypenode.hpp"
  52 #include "opto/library_call.hpp"
  53 #include "opto/mathexactnode.hpp"
  54 #include "opto/mulnode.hpp"
  55 #include "opto/narrowptrnode.hpp"
  56 #include "opto/opaquenode.hpp"
  57 #include "opto/opcodes.hpp"
  58 #include "opto/parse.hpp"
  59 #include "opto/rootnode.hpp"
  60 #include "opto/runtime.hpp"
  61 #include "opto/subnode.hpp"
  62 #include "opto/type.hpp"
  63 #include "opto/vectornode.hpp"
  64 #include "prims/jvmtiExport.hpp"
  65 #include "prims/jvmtiThreadState.hpp"
  66 #include "prims/unsafe.hpp"
  67 #include "runtime/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,
 972                                                  Node* offset,
 973                                                  Node* count,
 974                                                  bool char_count,
 975                                                  bool halt_on_oob) {
 976   if (stopped()) {
 977     return; // already stopped
 978   }
 979   RegionNode* bailout = new RegionNode(1);
 980   record_for_igvn(bailout);
 981   if (char_count) {
 982     // Convert char count to byte count
 983     count = _gvn.transform(new LShiftINode(count, intcon(1)));
 984   }
 985 
 986   // Offset and count must not be negative
 987   generate_negative_guard(offset, bailout);
 988   generate_negative_guard(count, bailout);
 989   // Offset + count must not exceed length of array
 990   generate_limit_guard(offset, count, load_array_length(array), bailout);
 991 
 992   if (bailout->req() > 1) {
 993     if (halt_on_oob) {
 994       bailout = _gvn.transform(bailout)->as_Region();
 995       Node* frame = _gvn.transform(new ParmNode(C->start(), TypeFunc::FramePtr));
 996       Node* halt = _gvn.transform(new HaltNode(bailout, frame, "unexpected guard failure in intrinsic"));
 997       C->root()->add_req(halt);
 998     } else {
 999       PreserveJVMState pjvms(this);
1000       set_control(_gvn.transform(bailout));
1001       uncommon_trap(Deoptimization::Reason_intrinsic,
1002                     Deoptimization::Action_maybe_recompile);
1003     }
1004   }
1005 }
1006 
1007 Node* LibraryCallKit::current_thread_helper(Node*& tls_output, ByteSize handle_offset,
1008                                             bool is_immutable) {
1009   ciKlass* thread_klass = env()->Thread_klass();
1010   const Type* thread_type
1011     = TypeOopPtr::make_from_klass(thread_klass)->cast_to_ptr_type(TypePtr::NotNull);
1012 
1013   Node* thread = _gvn.transform(new ThreadLocalNode());
1014   Node* p = basic_plus_adr(top()/*!oop*/, thread, in_bytes(handle_offset));
1015   tls_output = thread;
1016 
1017   Node* thread_obj_handle
1018     = (is_immutable
1019       ? LoadNode::make(_gvn, nullptr, immutable_memory(), p, p->bottom_type()->is_ptr(),
1020         TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered)
1021       : make_load(nullptr, p, p->bottom_type()->is_ptr(), T_ADDRESS, MemNode::unordered));
1022   thread_obj_handle = _gvn.transform(thread_obj_handle);
1023 
1024   DecoratorSet decorators = IN_NATIVE;
1025   if (is_immutable) {
1026     decorators |= C2_IMMUTABLE_MEMORY;
1027   }
1028   return access_load(thread_obj_handle, thread_type, T_OBJECT, decorators);
1029 }
1030 
1031 //--------------------------generate_current_thread--------------------
1032 Node* LibraryCallKit::generate_current_thread(Node* &tls_output) {
1033   return current_thread_helper(tls_output, JavaThread::threadObj_offset(),
1034                                /*is_immutable*/false);
1035 }
1036 
1037 //--------------------------generate_virtual_thread--------------------
1038 Node* LibraryCallKit::generate_virtual_thread(Node* tls_output) {
1039   return current_thread_helper(tls_output, JavaThread::vthread_offset(),
1040                                !C->method()->changes_current_thread());
1041 }
1042 
1043 //------------------------------make_string_method_node------------------------
1044 // Helper method for String intrinsic functions. This version is called with
1045 // str1 and str2 pointing to byte[] nodes containing Latin1 or UTF16 encoded
1046 // characters (depending on 'is_byte'). cnt1 and cnt2 are pointing to Int nodes
1047 // containing the lengths of str1 and str2.
1048 Node* LibraryCallKit::make_string_method_node(int opcode, Node* str1_start, Node* cnt1, Node* str2_start, Node* cnt2, StrIntrinsicNode::ArgEnc ae) {
1049   Node* result = nullptr;
1050   switch (opcode) {
1051   case Op_StrIndexOf:
1052     result = new StrIndexOfNode(control(), memory(TypeAryPtr::BYTES),
1053                                 str1_start, cnt1, str2_start, cnt2, ae);
1054     break;
1055   case Op_StrComp:
1056     result = new StrCompNode(control(), memory(TypeAryPtr::BYTES),
1057                              str1_start, cnt1, str2_start, cnt2, ae);
1058     break;
1059   case Op_StrEquals:
1060     // We already know that cnt1 == cnt2 here (checked in 'inline_string_equals').
1061     // Use the constant length if there is one because optimized match rule may exist.
1062     result = new StrEqualsNode(control(), memory(TypeAryPtr::BYTES),
1063                                str1_start, str2_start, cnt2->is_Con() ? cnt2 : cnt1, ae);
1064     break;
1065   default:
1066     ShouldNotReachHere();
1067     return nullptr;
1068   }
1069 
1070   // All these intrinsics have checks.
1071   C->set_has_split_ifs(true); // Has chance for split-if optimization
1072   clear_upper_avx();
1073 
1074   return _gvn.transform(result);
1075 }
1076 
1077 //------------------------------inline_string_compareTo------------------------
1078 bool LibraryCallKit::inline_string_compareTo(StrIntrinsicNode::ArgEnc ae) {
1079   Node* arg1 = argument(0);
1080   Node* arg2 = argument(1);
1081 
1082   arg1 = must_be_not_null(arg1, true);
1083   arg2 = must_be_not_null(arg2, true);
1084 
1085   // Get start addr and length of first argument
1086   Node* arg1_start  = array_element_address(arg1, intcon(0), T_BYTE);
1087   Node* arg1_cnt    = load_array_length(arg1);
1088 
1089   // Get start addr and length of second argument
1090   Node* arg2_start  = array_element_address(arg2, intcon(0), T_BYTE);
1091   Node* arg2_cnt    = load_array_length(arg2);
1092 
1093   Node* result = make_string_method_node(Op_StrComp, arg1_start, arg1_cnt, arg2_start, arg2_cnt, ae);
1094   set_result(result);
1095   return true;
1096 }
1097 
1098 //------------------------------inline_string_equals------------------------
1099 bool LibraryCallKit::inline_string_equals(StrIntrinsicNode::ArgEnc ae) {
1100   Node* arg1 = argument(0);
1101   Node* arg2 = argument(1);
1102 
1103   // paths (plus control) merge
1104   RegionNode* region = new RegionNode(3);
1105   Node* phi = new PhiNode(region, TypeInt::BOOL);
1106 
1107   if (!stopped()) {
1108 
1109     arg1 = must_be_not_null(arg1, true);
1110     arg2 = must_be_not_null(arg2, true);
1111 
1112     // Get start addr and length of first argument
1113     Node* arg1_start  = array_element_address(arg1, intcon(0), T_BYTE);
1114     Node* arg1_cnt    = load_array_length(arg1);
1115 
1116     // Get start addr and length of second argument
1117     Node* arg2_start  = array_element_address(arg2, intcon(0), T_BYTE);
1118     Node* arg2_cnt    = load_array_length(arg2);
1119 
1120     // Check for arg1_cnt != arg2_cnt
1121     Node* cmp = _gvn.transform(new CmpINode(arg1_cnt, arg2_cnt));
1122     Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::ne));
1123     Node* if_ne = generate_slow_guard(bol, nullptr);
1124     if (if_ne != nullptr) {
1125       phi->init_req(2, intcon(0));
1126       region->init_req(2, if_ne);
1127     }
1128 
1129     // Check for count == 0 is done by assembler code for StrEquals.
1130 
1131     if (!stopped()) {
1132       Node* equals = make_string_method_node(Op_StrEquals, arg1_start, arg1_cnt, arg2_start, arg2_cnt, ae);
1133       phi->init_req(1, equals);
1134       region->init_req(1, control());
1135     }
1136   }
1137 
1138   // post merge
1139   set_control(_gvn.transform(region));
1140   record_for_igvn(region);
1141 
1142   set_result(_gvn.transform(phi));
1143   return true;
1144 }
1145 
1146 //------------------------------inline_array_equals----------------------------
1147 bool LibraryCallKit::inline_array_equals(StrIntrinsicNode::ArgEnc ae) {
1148   assert(ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::LL, "unsupported array types");
1149   Node* arg1 = argument(0);
1150   Node* arg2 = argument(1);
1151 
1152   const TypeAryPtr* mtype = (ae == StrIntrinsicNode::UU) ? TypeAryPtr::CHARS : TypeAryPtr::BYTES;
1153   set_result(_gvn.transform(new AryEqNode(control(), memory(mtype), arg1, arg2, ae)));
1154   clear_upper_avx();
1155 
1156   return true;
1157 }
1158 
1159 
1160 //------------------------------inline_countPositives------------------------------
1161 // int java.lang.StringCoding#countPositives0(byte[] ba, int off, int len)
1162 bool LibraryCallKit::inline_countPositives() {
1163   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1164     return false;
1165   }
1166 
1167   assert(callee()->signature()->size() == 3, "countPositives has 3 parameters");
1168   // no receiver since it is static method
1169   Node* ba         = argument(0);
1170   Node* offset     = argument(1);
1171   Node* len        = argument(2);
1172 
1173   if (VerifyIntrinsicChecks) {
1174     ba = must_be_not_null(ba, true);
1175     generate_string_range_check(ba, offset, len, false, true);
1176     if (stopped()) {
1177       return true;
1178     }
1179   }
1180 
1181   Node* ba_start = array_element_address(ba, offset, T_BYTE);
1182   Node* result = new CountPositivesNode(control(), memory(TypeAryPtr::BYTES), ba_start, len);
1183   set_result(_gvn.transform(result));
1184   clear_upper_avx();
1185   return true;
1186 }
1187 
1188 bool LibraryCallKit::inline_preconditions_checkIndex(BasicType bt) {
1189   Node* index = argument(0);
1190   Node* length = bt == T_INT ? argument(1) : argument(2);
1191   if (too_many_traps(Deoptimization::Reason_intrinsic) || too_many_traps(Deoptimization::Reason_range_check)) {
1192     return false;
1193   }
1194 
1195   // check that length is positive
1196   Node* len_pos_cmp = _gvn.transform(CmpNode::make(length, integercon(0, bt), bt));
1197   Node* len_pos_bol = _gvn.transform(new BoolNode(len_pos_cmp, BoolTest::ge));
1198 
1199   {
1200     BuildCutout unless(this, len_pos_bol, PROB_MAX);
1201     uncommon_trap(Deoptimization::Reason_intrinsic,
1202                   Deoptimization::Action_make_not_entrant);
1203   }
1204 
1205   if (stopped()) {
1206     // Length is known to be always negative during compilation and the IR graph so far constructed is good so return success
1207     return true;
1208   }
1209 
1210   // length is now known positive, add a cast node to make this explicit
1211   jlong upper_bound = _gvn.type(length)->is_integer(bt)->hi_as_long();
1212   Node* casted_length = ConstraintCastNode::make_cast_for_basic_type(
1213       control(), length, TypeInteger::make(0, upper_bound, Type::WidenMax, bt),
1214       ConstraintCastNode::DependencyType::FloatingNarrowing, bt);
1215   casted_length = _gvn.transform(casted_length);
1216   replace_in_map(length, casted_length);
1217   length = casted_length;
1218 
1219   // Use an unsigned comparison for the range check itself
1220   Node* rc_cmp = _gvn.transform(CmpNode::make(index, length, bt, true));
1221   BoolTest::mask btest = BoolTest::lt;
1222   Node* rc_bool = _gvn.transform(new BoolNode(rc_cmp, btest));
1223   RangeCheckNode* rc = new RangeCheckNode(control(), rc_bool, PROB_MAX, COUNT_UNKNOWN);
1224   _gvn.set_type(rc, rc->Value(&_gvn));
1225   if (!rc_bool->is_Con()) {
1226     record_for_igvn(rc);
1227   }
1228   set_control(_gvn.transform(new IfTrueNode(rc)));
1229   {
1230     PreserveJVMState pjvms(this);
1231     set_control(_gvn.transform(new IfFalseNode(rc)));
1232     uncommon_trap(Deoptimization::Reason_range_check,
1233                   Deoptimization::Action_make_not_entrant);
1234   }
1235 
1236   if (stopped()) {
1237     // Range check is known to always fail during compilation and the IR graph so far constructed is good so return success
1238     return true;
1239   }
1240 
1241   // index is now known to be >= 0 and < length, cast it
1242   Node* result = ConstraintCastNode::make_cast_for_basic_type(
1243       control(), index, TypeInteger::make(0, upper_bound, Type::WidenMax, bt),
1244       ConstraintCastNode::DependencyType::FloatingNarrowing, bt);
1245   result = _gvn.transform(result);
1246   set_result(result);
1247   replace_in_map(index, result);
1248   return true;
1249 }
1250 
1251 //------------------------------inline_string_indexOf------------------------
1252 bool LibraryCallKit::inline_string_indexOf(StrIntrinsicNode::ArgEnc ae) {
1253   if (!Matcher::match_rule_supported(Op_StrIndexOf)) {
1254     return false;
1255   }
1256   Node* src = argument(0);
1257   Node* tgt = argument(1);
1258 
1259   // Make the merge point
1260   RegionNode* result_rgn = new RegionNode(4);
1261   Node*       result_phi = new PhiNode(result_rgn, TypeInt::INT);
1262 
1263   src = must_be_not_null(src, true);
1264   tgt = must_be_not_null(tgt, true);
1265 
1266   // Get start addr and length of source string
1267   Node* src_start = array_element_address(src, intcon(0), T_BYTE);
1268   Node* src_count = load_array_length(src);
1269 
1270   // Get start addr and length of substring
1271   Node* tgt_start = array_element_address(tgt, intcon(0), T_BYTE);
1272   Node* tgt_count = load_array_length(tgt);
1273 
1274   Node* result = nullptr;
1275   bool call_opt_stub = (StubRoutines::_string_indexof_array[ae] != nullptr);
1276 
1277   if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
1278     // Divide src size by 2 if String is UTF16 encoded
1279     src_count = _gvn.transform(new RShiftINode(src_count, intcon(1)));
1280   }
1281   if (ae == StrIntrinsicNode::UU) {
1282     // Divide substring size by 2 if String is UTF16 encoded
1283     tgt_count = _gvn.transform(new RShiftINode(tgt_count, intcon(1)));
1284   }
1285 
1286   if (call_opt_stub) {
1287     Node* call = make_runtime_call(RC_LEAF, OptoRuntime::string_IndexOf_Type(),
1288                                    StubRoutines::_string_indexof_array[ae],
1289                                    "stringIndexOf", TypePtr::BOTTOM, src_start,
1290                                    src_count, tgt_start, tgt_count);
1291     result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
1292   } else {
1293     result = make_indexOf_node(src_start, src_count, tgt_start, tgt_count,
1294                                result_rgn, result_phi, ae);
1295   }
1296   if (result != nullptr) {
1297     result_phi->init_req(3, result);
1298     result_rgn->init_req(3, control());
1299   }
1300   set_control(_gvn.transform(result_rgn));
1301   record_for_igvn(result_rgn);
1302   set_result(_gvn.transform(result_phi));
1303 
1304   return true;
1305 }
1306 
1307 //-----------------------------inline_string_indexOfI-----------------------
1308 bool LibraryCallKit::inline_string_indexOfI(StrIntrinsicNode::ArgEnc ae) {
1309   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1310     return false;
1311   }
1312   if (!Matcher::match_rule_supported(Op_StrIndexOf)) {
1313     return false;
1314   }
1315 
1316   assert(callee()->signature()->size() == 5, "String.indexOf() has 5 arguments");
1317   Node* src         = argument(0); // byte[]
1318   Node* src_count   = argument(1); // char count
1319   Node* tgt         = argument(2); // byte[]
1320   Node* tgt_count   = argument(3); // char count
1321   Node* from_index  = argument(4); // char index
1322 
1323   src = must_be_not_null(src, true);
1324   tgt = must_be_not_null(tgt, true);
1325 
1326   // Multiply byte array index by 2 if String is UTF16 encoded
1327   Node* src_offset = (ae == StrIntrinsicNode::LL) ? from_index : _gvn.transform(new LShiftINode(from_index, intcon(1)));
1328   src_count = _gvn.transform(new SubINode(src_count, from_index));
1329   Node* src_start = array_element_address(src, src_offset, T_BYTE);
1330   Node* tgt_start = array_element_address(tgt, intcon(0), T_BYTE);
1331 
1332   // Range checks
1333   generate_string_range_check(src, src_offset, src_count, ae != StrIntrinsicNode::LL);
1334   generate_string_range_check(tgt, intcon(0), tgt_count, ae == StrIntrinsicNode::UU);
1335   if (stopped()) {
1336     return true;
1337   }
1338 
1339   RegionNode* region = new RegionNode(5);
1340   Node* phi = new PhiNode(region, TypeInt::INT);
1341   Node* result = nullptr;
1342 
1343   bool call_opt_stub = (StubRoutines::_string_indexof_array[ae] != nullptr);
1344 
1345   if (call_opt_stub) {
1346     Node* call = make_runtime_call(RC_LEAF, OptoRuntime::string_IndexOf_Type(),
1347                                    StubRoutines::_string_indexof_array[ae],
1348                                    "stringIndexOf", TypePtr::BOTTOM, src_start,
1349                                    src_count, tgt_start, tgt_count);
1350     result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
1351   } else {
1352     result = make_indexOf_node(src_start, src_count, tgt_start, tgt_count,
1353                                region, phi, ae);
1354   }
1355   if (result != nullptr) {
1356     // The result is index relative to from_index if substring was found, -1 otherwise.
1357     // Generate code which will fold into cmove.
1358     Node* cmp = _gvn.transform(new CmpINode(result, intcon(0)));
1359     Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::lt));
1360 
1361     Node* if_lt = generate_slow_guard(bol, nullptr);
1362     if (if_lt != nullptr) {
1363       // result == -1
1364       phi->init_req(3, result);
1365       region->init_req(3, if_lt);
1366     }
1367     if (!stopped()) {
1368       result = _gvn.transform(new AddINode(result, from_index));
1369       phi->init_req(4, result);
1370       region->init_req(4, control());
1371     }
1372   }
1373 
1374   set_control(_gvn.transform(region));
1375   record_for_igvn(region);
1376   set_result(_gvn.transform(phi));
1377   clear_upper_avx();
1378 
1379   return true;
1380 }
1381 
1382 // Create StrIndexOfNode with fast path checks
1383 Node* LibraryCallKit::make_indexOf_node(Node* src_start, Node* src_count, Node* tgt_start, Node* tgt_count,
1384                                         RegionNode* region, Node* phi, StrIntrinsicNode::ArgEnc ae) {
1385   // Check for substr count > string count
1386   Node* cmp = _gvn.transform(new CmpINode(tgt_count, src_count));
1387   Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::gt));
1388   Node* if_gt = generate_slow_guard(bol, nullptr);
1389   if (if_gt != nullptr) {
1390     phi->init_req(1, intcon(-1));
1391     region->init_req(1, if_gt);
1392   }
1393   if (!stopped()) {
1394     // Check for substr count == 0
1395     cmp = _gvn.transform(new CmpINode(tgt_count, intcon(0)));
1396     bol = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
1397     Node* if_zero = generate_slow_guard(bol, nullptr);
1398     if (if_zero != nullptr) {
1399       phi->init_req(2, intcon(0));
1400       region->init_req(2, if_zero);
1401     }
1402   }
1403   if (!stopped()) {
1404     return make_string_method_node(Op_StrIndexOf, src_start, src_count, tgt_start, tgt_count, ae);
1405   }
1406   return nullptr;
1407 }
1408 
1409 //-----------------------------inline_string_indexOfChar-----------------------
1410 bool LibraryCallKit::inline_string_indexOfChar(StrIntrinsicNode::ArgEnc ae) {
1411   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1412     return false;
1413   }
1414   if (!Matcher::match_rule_supported(Op_StrIndexOfChar)) {
1415     return false;
1416   }
1417   assert(callee()->signature()->size() == 4, "String.indexOfChar() has 4 arguments");
1418   Node* src         = argument(0); // byte[]
1419   Node* int_ch      = argument(1);
1420   Node* from_index  = argument(2);
1421   Node* max         = argument(3);
1422 
1423   src = must_be_not_null(src, true);
1424 
1425   Node* src_offset = ae == StrIntrinsicNode::L ? from_index : _gvn.transform(new LShiftINode(from_index, intcon(1)));
1426   Node* src_start = array_element_address(src, src_offset, T_BYTE);
1427   Node* src_count = _gvn.transform(new SubINode(max, from_index));
1428 
1429   // Range checks
1430   generate_string_range_check(src, src_offset, src_count, ae == StrIntrinsicNode::U);
1431 
1432   // Check for int_ch >= 0
1433   Node* int_ch_cmp = _gvn.transform(new CmpINode(int_ch, intcon(0)));
1434   Node* int_ch_bol = _gvn.transform(new BoolNode(int_ch_cmp, BoolTest::ge));
1435   {
1436     BuildCutout unless(this, int_ch_bol, PROB_MAX);
1437     uncommon_trap(Deoptimization::Reason_intrinsic,
1438                   Deoptimization::Action_maybe_recompile);
1439   }
1440   if (stopped()) {
1441     return true;
1442   }
1443 
1444   RegionNode* region = new RegionNode(3);
1445   Node* phi = new PhiNode(region, TypeInt::INT);
1446 
1447   Node* result = new StrIndexOfCharNode(control(), memory(TypeAryPtr::BYTES), src_start, src_count, int_ch, ae);
1448   C->set_has_split_ifs(true); // Has chance for split-if optimization
1449   _gvn.transform(result);
1450 
1451   Node* cmp = _gvn.transform(new CmpINode(result, intcon(0)));
1452   Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::lt));
1453 
1454   Node* if_lt = generate_slow_guard(bol, nullptr);
1455   if (if_lt != nullptr) {
1456     // result == -1
1457     phi->init_req(2, result);
1458     region->init_req(2, if_lt);
1459   }
1460   if (!stopped()) {
1461     result = _gvn.transform(new AddINode(result, from_index));
1462     phi->init_req(1, result);
1463     region->init_req(1, control());
1464   }
1465   set_control(_gvn.transform(region));
1466   record_for_igvn(region);
1467   set_result(_gvn.transform(phi));
1468   clear_upper_avx();
1469 
1470   return true;
1471 }
1472 //---------------------------inline_string_copy---------------------
1473 // compressIt == true --> generate a compressed copy operation (compress char[]/byte[] to byte[])
1474 //   int StringUTF16.compress(char[] src, int srcOff, byte[] dst, int dstOff, int len)
1475 //   int StringUTF16.compress(byte[] src, int srcOff, byte[] dst, int dstOff, int len)
1476 // compressIt == false --> generate an inflated copy operation (inflate byte[] to char[]/byte[])
1477 //   void StringLatin1.inflate(byte[] src, int srcOff, char[] dst, int dstOff, int len)
1478 //   void StringLatin1.inflate(byte[] src, int srcOff, byte[] dst, int dstOff, int len)
1479 bool LibraryCallKit::inline_string_copy(bool compress) {
1480   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1481     return false;
1482   }
1483   int nargs = 5;  // 2 oops, 3 ints
1484   assert(callee()->signature()->size() == nargs, "string copy has 5 arguments");
1485 
1486   Node* src         = argument(0);
1487   Node* src_offset  = argument(1);
1488   Node* dst         = argument(2);
1489   Node* dst_offset  = argument(3);
1490   Node* length      = argument(4);
1491 
1492   // Check for allocation before we add nodes that would confuse
1493   // tightly_coupled_allocation()
1494   AllocateArrayNode* alloc = tightly_coupled_allocation(dst);
1495 
1496   // Figure out the size and type of the elements we will be copying.
1497   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
1498   const TypeAryPtr* dst_type = dst->Value(&_gvn)->isa_aryptr();
1499   if (src_type == nullptr || dst_type == nullptr) {
1500     return false;
1501   }
1502   BasicType src_elem = src_type->elem()->array_element_basic_type();
1503   BasicType dst_elem = dst_type->elem()->array_element_basic_type();
1504   assert((compress && dst_elem == T_BYTE && (src_elem == T_BYTE || src_elem == T_CHAR)) ||
1505          (!compress && src_elem == T_BYTE && (dst_elem == T_BYTE || dst_elem == T_CHAR)),
1506          "Unsupported array types for inline_string_copy");
1507 
1508   src = must_be_not_null(src, true);
1509   dst = must_be_not_null(dst, true);
1510 
1511   // Convert char[] offsets to byte[] offsets
1512   bool convert_src = (compress && src_elem == T_BYTE);
1513   bool convert_dst = (!compress && dst_elem == T_BYTE);
1514   if (convert_src) {
1515     src_offset = _gvn.transform(new LShiftINode(src_offset, intcon(1)));
1516   } else if (convert_dst) {
1517     dst_offset = _gvn.transform(new LShiftINode(dst_offset, intcon(1)));
1518   }
1519 
1520   // Range checks
1521   generate_string_range_check(src, src_offset, length, convert_src);
1522   generate_string_range_check(dst, dst_offset, length, convert_dst);
1523   if (stopped()) {
1524     return true;
1525   }
1526 
1527   Node* src_start = array_element_address(src, src_offset, src_elem);
1528   Node* dst_start = array_element_address(dst, dst_offset, dst_elem);
1529   // 'src_start' points to src array + scaled offset
1530   // 'dst_start' points to dst array + scaled offset
1531   Node* count = nullptr;
1532   if (compress) {
1533     count = compress_string(src_start, TypeAryPtr::get_array_body_type(src_elem), dst_start, length);
1534   } else {
1535     inflate_string(src_start, dst_start, TypeAryPtr::get_array_body_type(dst_elem), length);
1536   }
1537 
1538   if (alloc != nullptr) {
1539     if (alloc->maybe_set_complete(&_gvn)) {
1540       // "You break it, you buy it."
1541       InitializeNode* init = alloc->initialization();
1542       assert(init->is_complete(), "we just did this");
1543       init->set_complete_with_arraycopy();
1544       assert(dst->is_CheckCastPP(), "sanity");
1545       assert(dst->in(0)->in(0) == init, "dest pinned");
1546     }
1547     // Do not let stores that initialize this object be reordered with
1548     // a subsequent store that would make this object accessible by
1549     // other threads.
1550     // Record what AllocateNode this StoreStore protects so that
1551     // escape analysis can go from the MemBarStoreStoreNode to the
1552     // AllocateNode and eliminate the MemBarStoreStoreNode if possible
1553     // based on the escape status of the AllocateNode.
1554     insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
1555   }
1556   if (compress) {
1557     set_result(_gvn.transform(count));
1558   }
1559   clear_upper_avx();
1560 
1561   return true;
1562 }
1563 
1564 #ifdef _LP64
1565 #define XTOP ,top() /*additional argument*/
1566 #else  //_LP64
1567 #define XTOP        /*no additional argument*/
1568 #endif //_LP64
1569 
1570 //------------------------inline_string_toBytesU--------------------------
1571 // public static byte[] StringUTF16.toBytes(char[] value, int off, int len)
1572 bool LibraryCallKit::inline_string_toBytesU() {
1573   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1574     return false;
1575   }
1576   // Get the arguments.
1577   Node* value     = argument(0);
1578   Node* offset    = argument(1);
1579   Node* length    = argument(2);
1580 
1581   Node* newcopy = nullptr;
1582 
1583   // Set the original stack and the reexecute bit for the interpreter to reexecute
1584   // the bytecode that invokes StringUTF16.toBytes() if deoptimization happens.
1585   { PreserveReexecuteState preexecs(this);
1586     jvms()->set_should_reexecute(true);
1587 
1588     // Check if a null path was taken unconditionally.
1589     value = null_check(value);
1590 
1591     RegionNode* bailout = new RegionNode(1);
1592     record_for_igvn(bailout);
1593 
1594     // Range checks
1595     generate_negative_guard(offset, bailout);
1596     generate_negative_guard(length, bailout);
1597     generate_limit_guard(offset, length, load_array_length(value), bailout);
1598     // Make sure that resulting byte[] length does not overflow Integer.MAX_VALUE
1599     generate_limit_guard(length, intcon(0), intcon(max_jint/2), bailout);
1600 
1601     if (bailout->req() > 1) {
1602       PreserveJVMState pjvms(this);
1603       set_control(_gvn.transform(bailout));
1604       uncommon_trap(Deoptimization::Reason_intrinsic,
1605                     Deoptimization::Action_maybe_recompile);
1606     }
1607     if (stopped()) {
1608       return true;
1609     }
1610 
1611     Node* size = _gvn.transform(new LShiftINode(length, intcon(1)));
1612     Node* klass_node = makecon(TypeKlassPtr::make(ciTypeArrayKlass::make(T_BYTE)));
1613     newcopy = new_array(klass_node, size, 0);  // no arguments to push
1614     AllocateArrayNode* alloc = tightly_coupled_allocation(newcopy);
1615     guarantee(alloc != nullptr, "created above");
1616 
1617     // Calculate starting addresses.
1618     Node* src_start = array_element_address(value, offset, T_CHAR);
1619     Node* dst_start = basic_plus_adr(newcopy, arrayOopDesc::base_offset_in_bytes(T_BYTE));
1620 
1621     // Check if dst array address is aligned to HeapWordSize
1622     bool aligned = (arrayOopDesc::base_offset_in_bytes(T_BYTE) % HeapWordSize == 0);
1623     // If true, then check if src array address is aligned to HeapWordSize
1624     if (aligned) {
1625       const TypeInt* toffset = gvn().type(offset)->is_int();
1626       aligned = toffset->is_con() && ((arrayOopDesc::base_offset_in_bytes(T_CHAR) +
1627                                        toffset->get_con() * type2aelembytes(T_CHAR)) % HeapWordSize == 0);
1628     }
1629 
1630     // Figure out which arraycopy runtime method to call (disjoint, uninitialized).
1631     const char* copyfunc_name = "arraycopy";
1632     address     copyfunc_addr = StubRoutines::select_arraycopy_function(T_CHAR, aligned, true, copyfunc_name, true);
1633     Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
1634                       OptoRuntime::fast_arraycopy_Type(),
1635                       copyfunc_addr, copyfunc_name, TypeRawPtr::BOTTOM,
1636                       src_start, dst_start, ConvI2X(length) XTOP);
1637     // Do not let reads from the cloned object float above the arraycopy.
1638     if (alloc->maybe_set_complete(&_gvn)) {
1639       // "You break it, you buy it."
1640       InitializeNode* init = alloc->initialization();
1641       assert(init->is_complete(), "we just did this");
1642       init->set_complete_with_arraycopy();
1643       assert(newcopy->is_CheckCastPP(), "sanity");
1644       assert(newcopy->in(0)->in(0) == init, "dest pinned");
1645     }
1646     // Do not let stores that initialize this object be reordered with
1647     // a subsequent store that would make this object accessible by
1648     // other threads.
1649     // Record what AllocateNode this StoreStore protects so that
1650     // escape analysis can go from the MemBarStoreStoreNode to the
1651     // AllocateNode and eliminate the MemBarStoreStoreNode if possible
1652     // based on the escape status of the AllocateNode.
1653     insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
1654   } // original reexecute is set back here
1655 
1656   C->set_has_split_ifs(true); // Has chance for split-if optimization
1657   if (!stopped()) {
1658     set_result(newcopy);
1659   }
1660   clear_upper_avx();
1661 
1662   return true;
1663 }
1664 
1665 //------------------------inline_string_getCharsU--------------------------
1666 // public void StringUTF16.getChars(byte[] src, int srcBegin, int srcEnd, char dst[], int dstBegin)
1667 bool LibraryCallKit::inline_string_getCharsU() {
1668   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1669     return false;
1670   }
1671 
1672   // Get the arguments.
1673   Node* src       = argument(0);
1674   Node* src_begin = argument(1);
1675   Node* src_end   = argument(2); // exclusive offset (i < src_end)
1676   Node* dst       = argument(3);
1677   Node* dst_begin = argument(4);
1678 
1679   // Check for allocation before we add nodes that would confuse
1680   // tightly_coupled_allocation()
1681   AllocateArrayNode* alloc = tightly_coupled_allocation(dst);
1682 
1683   // Check if a null path was taken unconditionally.
1684   src = null_check(src);
1685   dst = null_check(dst);
1686   if (stopped()) {
1687     return true;
1688   }
1689 
1690   // Get length and convert char[] offset to byte[] offset
1691   Node* length = _gvn.transform(new SubINode(src_end, src_begin));
1692   src_begin = _gvn.transform(new LShiftINode(src_begin, intcon(1)));
1693 
1694   // Range checks
1695   generate_string_range_check(src, src_begin, length, true);
1696   generate_string_range_check(dst, dst_begin, length, false);
1697   if (stopped()) {
1698     return true;
1699   }
1700 
1701   if (!stopped()) {
1702     // Calculate starting addresses.
1703     Node* src_start = array_element_address(src, src_begin, T_BYTE);
1704     Node* dst_start = array_element_address(dst, dst_begin, T_CHAR);
1705 
1706     // Check if array addresses are aligned to HeapWordSize
1707     const TypeInt* tsrc = gvn().type(src_begin)->is_int();
1708     const TypeInt* tdst = gvn().type(dst_begin)->is_int();
1709     bool aligned = tsrc->is_con() && ((arrayOopDesc::base_offset_in_bytes(T_BYTE) + tsrc->get_con() * type2aelembytes(T_BYTE)) % HeapWordSize == 0) &&
1710                    tdst->is_con() && ((arrayOopDesc::base_offset_in_bytes(T_CHAR) + tdst->get_con() * type2aelembytes(T_CHAR)) % HeapWordSize == 0);
1711 
1712     // Figure out which arraycopy runtime method to call (disjoint, uninitialized).
1713     const char* copyfunc_name = "arraycopy";
1714     address     copyfunc_addr = StubRoutines::select_arraycopy_function(T_CHAR, aligned, true, copyfunc_name, true);
1715     Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
1716                       OptoRuntime::fast_arraycopy_Type(),
1717                       copyfunc_addr, copyfunc_name, TypeRawPtr::BOTTOM,
1718                       src_start, dst_start, ConvI2X(length) XTOP);
1719     // Do not let reads from the cloned object float above the arraycopy.
1720     if (alloc != nullptr) {
1721       if (alloc->maybe_set_complete(&_gvn)) {
1722         // "You break it, you buy it."
1723         InitializeNode* init = alloc->initialization();
1724         assert(init->is_complete(), "we just did this");
1725         init->set_complete_with_arraycopy();
1726         assert(dst->is_CheckCastPP(), "sanity");
1727         assert(dst->in(0)->in(0) == init, "dest pinned");
1728       }
1729       // Do not let stores that initialize this object be reordered with
1730       // a subsequent store that would make this object accessible by
1731       // other threads.
1732       // Record what AllocateNode this StoreStore protects so that
1733       // escape analysis can go from the MemBarStoreStoreNode to the
1734       // AllocateNode and eliminate the MemBarStoreStoreNode if possible
1735       // based on the escape status of the AllocateNode.
1736       insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
1737     } else {
1738       insert_mem_bar(Op_MemBarCPUOrder);
1739     }
1740   }
1741 
1742   C->set_has_split_ifs(true); // Has chance for split-if optimization
1743   return true;
1744 }
1745 
1746 //----------------------inline_string_char_access----------------------------
1747 // Store/Load char to/from byte[] array.
1748 // static void StringUTF16.putChar(byte[] val, int index, int c)
1749 // static char StringUTF16.getChar(byte[] val, int index)
1750 bool LibraryCallKit::inline_string_char_access(bool is_store) {
1751   Node* value  = argument(0);
1752   Node* index  = argument(1);
1753   Node* ch = is_store ? argument(2) : nullptr;
1754 
1755   // This intrinsic accesses byte[] array as char[] array. Computing the offsets
1756   // correctly requires matched array shapes.
1757   assert (arrayOopDesc::base_offset_in_bytes(T_CHAR) == arrayOopDesc::base_offset_in_bytes(T_BYTE),
1758           "sanity: byte[] and char[] bases agree");
1759   assert (type2aelembytes(T_CHAR) == type2aelembytes(T_BYTE)*2,
1760           "sanity: byte[] and char[] scales agree");
1761 
1762   // Bail when getChar over constants is requested: constant folding would
1763   // reject folding mismatched char access over byte[]. A normal inlining for getChar
1764   // Java method would constant fold nicely instead.
1765   if (!is_store && value->is_Con() && index->is_Con()) {
1766     return false;
1767   }
1768 
1769   // Save state and restore on bailout
1770   SavedState old_state(this);
1771 
1772   value = must_be_not_null(value, true);
1773 
1774   Node* adr = array_element_address(value, index, T_CHAR);
1775   if (adr->is_top()) {
1776     return false;
1777   }
1778   old_state.discard();
1779   if (is_store) {
1780     access_store_at(value, adr, TypeAryPtr::BYTES, ch, TypeInt::CHAR, T_CHAR, IN_HEAP | MO_UNORDERED | C2_MISMATCHED);
1781   } else {
1782     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);
1783     set_result(ch);
1784   }
1785   return true;
1786 }
1787 
1788 
1789 //------------------------------inline_math-----------------------------------
1790 // public static double Math.abs(double)
1791 // public static double Math.sqrt(double)
1792 // public static double Math.log(double)
1793 // public static double Math.log10(double)
1794 // public static double Math.round(double)
1795 bool LibraryCallKit::inline_double_math(vmIntrinsics::ID id) {
1796   Node* arg = argument(0);
1797   Node* n = nullptr;
1798   switch (id) {
1799   case vmIntrinsics::_dabs:   n = new AbsDNode(                arg);  break;
1800   case vmIntrinsics::_dsqrt:
1801   case vmIntrinsics::_dsqrt_strict:
1802                               n = new SqrtDNode(C, control(),  arg);  break;
1803   case vmIntrinsics::_ceil:   n = RoundDoubleModeNode::make(_gvn, arg, RoundDoubleModeNode::rmode_ceil); break;
1804   case vmIntrinsics::_floor:  n = RoundDoubleModeNode::make(_gvn, arg, RoundDoubleModeNode::rmode_floor); break;
1805   case vmIntrinsics::_rint:   n = RoundDoubleModeNode::make(_gvn, arg, RoundDoubleModeNode::rmode_rint); break;
1806   case vmIntrinsics::_roundD: n = new RoundDNode(arg); break;
1807   case vmIntrinsics::_dcopySign: n = CopySignDNode::make(_gvn, arg, argument(2)); break;
1808   case vmIntrinsics::_dsignum: n = SignumDNode::make(_gvn, arg); break;
1809   default:  fatal_unexpected_iid(id);  break;
1810   }
1811   set_result(_gvn.transform(n));
1812   return true;
1813 }
1814 
1815 //------------------------------inline_math-----------------------------------
1816 // public static float Math.abs(float)
1817 // public static int Math.abs(int)
1818 // public static long Math.abs(long)
1819 bool LibraryCallKit::inline_math(vmIntrinsics::ID id) {
1820   Node* arg = argument(0);
1821   Node* n = nullptr;
1822   switch (id) {
1823   case vmIntrinsics::_fabs:   n = new AbsFNode(                arg);  break;
1824   case vmIntrinsics::_iabs:   n = new AbsINode(                arg);  break;
1825   case vmIntrinsics::_labs:   n = new AbsLNode(                arg);  break;
1826   case vmIntrinsics::_fcopySign: n = new CopySignFNode(arg, argument(1)); break;
1827   case vmIntrinsics::_fsignum: n = SignumFNode::make(_gvn, arg); break;
1828   case vmIntrinsics::_roundF: n = new RoundFNode(arg); break;
1829   default:  fatal_unexpected_iid(id);  break;
1830   }
1831   set_result(_gvn.transform(n));
1832   return true;
1833 }
1834 
1835 //------------------------------runtime_math-----------------------------
1836 bool LibraryCallKit::runtime_math(const TypeFunc* call_type, address funcAddr, const char* funcName) {
1837   assert(call_type == OptoRuntime::Math_DD_D_Type() || call_type == OptoRuntime::Math_D_D_Type(),
1838          "must be (DD)D or (D)D type");
1839 
1840   // Inputs
1841   Node* a = argument(0);
1842   Node* b = (call_type == OptoRuntime::Math_DD_D_Type()) ? argument(2) : nullptr;
1843 
1844   const TypePtr* no_memory_effects = nullptr;
1845   Node* trig = make_runtime_call(RC_LEAF | RC_PURE, call_type, funcAddr, funcName,
1846                                  no_memory_effects,
1847                                  a, top(), b, b ? top() : nullptr);
1848   Node* value = _gvn.transform(new ProjNode(trig, TypeFunc::Parms+0));
1849 #ifdef ASSERT
1850   Node* value_top = _gvn.transform(new ProjNode(trig, TypeFunc::Parms+1));
1851   assert(value_top == top(), "second value must be top");
1852 #endif
1853 
1854   set_result(value);
1855   return true;
1856 }
1857 
1858 //------------------------------inline_math_pow-----------------------------
1859 bool LibraryCallKit::inline_math_pow() {
1860   Node* exp = argument(2);
1861   const TypeD* d = _gvn.type(exp)->isa_double_constant();
1862   if (d != nullptr) {
1863     if (d->getd() == 2.0) {
1864       // Special case: pow(x, 2.0) => x * x
1865       Node* base = argument(0);
1866       set_result(_gvn.transform(new MulDNode(base, base)));
1867       return true;
1868     } else if (d->getd() == 0.5 && Matcher::match_rule_supported(Op_SqrtD)) {
1869       // Special case: pow(x, 0.5) => sqrt(x)
1870       Node* base = argument(0);
1871       Node* zero = _gvn.zerocon(T_DOUBLE);
1872 
1873       RegionNode* region = new RegionNode(3);
1874       Node* phi = new PhiNode(region, Type::DOUBLE);
1875 
1876       Node* cmp  = _gvn.transform(new CmpDNode(base, zero));
1877       // According to the API specs, pow(-0.0, 0.5) = 0.0 and sqrt(-0.0) = -0.0.
1878       // So pow(-0.0, 0.5) shouldn't be replaced with sqrt(-0.0).
1879       // -0.0/+0.0 are both excluded since floating-point comparison doesn't distinguish -0.0 from +0.0.
1880       Node* test = _gvn.transform(new BoolNode(cmp, BoolTest::le));
1881 
1882       Node* if_pow = generate_slow_guard(test, nullptr);
1883       Node* value_sqrt = _gvn.transform(new SqrtDNode(C, control(), base));
1884       phi->init_req(1, value_sqrt);
1885       region->init_req(1, control());
1886 
1887       if (if_pow != nullptr) {
1888         set_control(if_pow);
1889         address target = StubRoutines::dpow() != nullptr ? StubRoutines::dpow() :
1890                                                         CAST_FROM_FN_PTR(address, SharedRuntime::dpow);
1891         const TypePtr* no_memory_effects = nullptr;
1892         Node* trig = make_runtime_call(RC_LEAF, OptoRuntime::Math_DD_D_Type(), target, "POW",
1893                                        no_memory_effects, base, top(), exp, top());
1894         Node* value_pow = _gvn.transform(new ProjNode(trig, TypeFunc::Parms+0));
1895 #ifdef ASSERT
1896         Node* value_top = _gvn.transform(new ProjNode(trig, TypeFunc::Parms+1));
1897         assert(value_top == top(), "second value must be top");
1898 #endif
1899         phi->init_req(2, value_pow);
1900         region->init_req(2, _gvn.transform(new ProjNode(trig, TypeFunc::Control)));
1901       }
1902 
1903       C->set_has_split_ifs(true); // Has chance for split-if optimization
1904       set_control(_gvn.transform(region));
1905       record_for_igvn(region);
1906       set_result(_gvn.transform(phi));
1907 
1908       return true;
1909     }
1910   }
1911 
1912   return StubRoutines::dpow() != nullptr ?
1913     runtime_math(OptoRuntime::Math_DD_D_Type(), StubRoutines::dpow(),  "dpow") :
1914     runtime_math(OptoRuntime::Math_DD_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dpow),  "POW");
1915 }
1916 
1917 //------------------------------inline_math_native-----------------------------
1918 bool LibraryCallKit::inline_math_native(vmIntrinsics::ID id) {
1919   switch (id) {
1920   case vmIntrinsics::_dsin:
1921     return StubRoutines::dsin() != nullptr ?
1922       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dsin(), "dsin") :
1923       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dsin),   "SIN");
1924   case vmIntrinsics::_dcos:
1925     return StubRoutines::dcos() != nullptr ?
1926       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dcos(), "dcos") :
1927       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dcos),   "COS");
1928   case vmIntrinsics::_dtan:
1929     return StubRoutines::dtan() != nullptr ?
1930       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dtan(), "dtan") :
1931       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dtan), "TAN");
1932   case vmIntrinsics::_dsinh:
1933     return StubRoutines::dsinh() != nullptr ?
1934       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dsinh(), "dsinh") : false;
1935   case vmIntrinsics::_dtanh:
1936     return StubRoutines::dtanh() != nullptr ?
1937       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dtanh(), "dtanh") : false;
1938   case vmIntrinsics::_dcbrt:
1939     return StubRoutines::dcbrt() != nullptr ?
1940       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dcbrt(), "dcbrt") : false;
1941   case vmIntrinsics::_dexp:
1942     return StubRoutines::dexp() != nullptr ?
1943       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dexp(),  "dexp") :
1944       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dexp),  "EXP");
1945   case vmIntrinsics::_dlog:
1946     return StubRoutines::dlog() != nullptr ?
1947       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dlog(), "dlog") :
1948       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dlog),   "LOG");
1949   case vmIntrinsics::_dlog10:
1950     return StubRoutines::dlog10() != nullptr ?
1951       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dlog10(), "dlog10") :
1952       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dlog10), "LOG10");
1953 
1954   case vmIntrinsics::_roundD: return Matcher::match_rule_supported(Op_RoundD) ? inline_double_math(id) : false;
1955   case vmIntrinsics::_ceil:
1956   case vmIntrinsics::_floor:
1957   case vmIntrinsics::_rint:   return Matcher::match_rule_supported(Op_RoundDoubleMode) ? inline_double_math(id) : false;
1958 
1959   case vmIntrinsics::_dsqrt:
1960   case vmIntrinsics::_dsqrt_strict:
1961                               return Matcher::match_rule_supported(Op_SqrtD) ? inline_double_math(id) : false;
1962   case vmIntrinsics::_dabs:   return Matcher::has_match_rule(Op_AbsD)   ? inline_double_math(id) : false;
1963   case vmIntrinsics::_fabs:   return Matcher::match_rule_supported(Op_AbsF)   ? inline_math(id) : false;
1964   case vmIntrinsics::_iabs:   return Matcher::match_rule_supported(Op_AbsI)   ? inline_math(id) : false;
1965   case vmIntrinsics::_labs:   return Matcher::match_rule_supported(Op_AbsL)   ? inline_math(id) : false;
1966 
1967   case vmIntrinsics::_dpow:      return inline_math_pow();
1968   case vmIntrinsics::_dcopySign: return inline_double_math(id);
1969   case vmIntrinsics::_fcopySign: return inline_math(id);
1970   case vmIntrinsics::_dsignum: return Matcher::match_rule_supported(Op_SignumD) ? inline_double_math(id) : false;
1971   case vmIntrinsics::_fsignum: return Matcher::match_rule_supported(Op_SignumF) ? inline_math(id) : false;
1972   case vmIntrinsics::_roundF: return Matcher::match_rule_supported(Op_RoundF) ? inline_math(id) : false;
1973 
1974    // These intrinsics are not yet correctly implemented
1975   case vmIntrinsics::_datan2:
1976     return false;
1977 
1978   default:
1979     fatal_unexpected_iid(id);
1980     return false;
1981   }
1982 }
1983 
1984 //----------------------------inline_notify-----------------------------------*
1985 bool LibraryCallKit::inline_notify(vmIntrinsics::ID id) {
1986   const TypeFunc* ftype = OptoRuntime::monitor_notify_Type();
1987   address func;
1988   if (id == vmIntrinsics::_notify) {
1989     func = OptoRuntime::monitor_notify_Java();
1990   } else {
1991     func = OptoRuntime::monitor_notifyAll_Java();
1992   }
1993   Node* call = make_runtime_call(RC_NO_LEAF, ftype, func, nullptr, TypeRawPtr::BOTTOM, argument(0));
1994   make_slow_call_ex(call, env()->Throwable_klass(), false);
1995   return true;
1996 }
1997 
1998 
1999 //----------------------------inline_min_max-----------------------------------
2000 bool LibraryCallKit::inline_min_max(vmIntrinsics::ID id) {
2001   Node* a = nullptr;
2002   Node* b = nullptr;
2003   Node* n = nullptr;
2004   switch (id) {
2005     case vmIntrinsics::_min:
2006     case vmIntrinsics::_max:
2007     case vmIntrinsics::_minF:
2008     case vmIntrinsics::_maxF:
2009     case vmIntrinsics::_minF_strict:
2010     case vmIntrinsics::_maxF_strict:
2011     case vmIntrinsics::_min_strict:
2012     case vmIntrinsics::_max_strict:
2013       assert(callee()->signature()->size() == 2, "minF/maxF has 2 parameters of size 1 each.");
2014       a = argument(0);
2015       b = argument(1);
2016       break;
2017     case vmIntrinsics::_minD:
2018     case vmIntrinsics::_maxD:
2019     case vmIntrinsics::_minD_strict:
2020     case vmIntrinsics::_maxD_strict:
2021       assert(callee()->signature()->size() == 4, "minD/maxD has 2 parameters of size 2 each.");
2022       a = argument(0);
2023       b = argument(2);
2024       break;
2025     case vmIntrinsics::_minL:
2026     case vmIntrinsics::_maxL:
2027       assert(callee()->signature()->size() == 4, "minL/maxL has 2 parameters of size 2 each.");
2028       a = argument(0);
2029       b = argument(2);
2030       break;
2031     default:
2032       fatal_unexpected_iid(id);
2033       break;
2034   }
2035 
2036   switch (id) {
2037     case vmIntrinsics::_min:
2038     case vmIntrinsics::_min_strict:
2039       n = new MinINode(a, b);
2040       break;
2041     case vmIntrinsics::_max:
2042     case vmIntrinsics::_max_strict:
2043       n = new MaxINode(a, b);
2044       break;
2045     case vmIntrinsics::_minF:
2046     case vmIntrinsics::_minF_strict:
2047       n = new MinFNode(a, b);
2048       break;
2049     case vmIntrinsics::_maxF:
2050     case vmIntrinsics::_maxF_strict:
2051       n = new MaxFNode(a, b);
2052       break;
2053     case vmIntrinsics::_minD:
2054     case vmIntrinsics::_minD_strict:
2055       n = new MinDNode(a, b);
2056       break;
2057     case vmIntrinsics::_maxD:
2058     case vmIntrinsics::_maxD_strict:
2059       n = new MaxDNode(a, b);
2060       break;
2061     case vmIntrinsics::_minL:
2062       n = new MinLNode(_gvn.C, a, b);
2063       break;
2064     case vmIntrinsics::_maxL:
2065       n = new MaxLNode(_gvn.C, a, b);
2066       break;
2067     default:
2068       fatal_unexpected_iid(id);
2069       break;
2070   }
2071 
2072   set_result(_gvn.transform(n));
2073   return true;
2074 }
2075 
2076 bool LibraryCallKit::inline_math_mathExact(Node* math, Node* test) {
2077   if (builtin_throw_too_many_traps(Deoptimization::Reason_intrinsic,
2078                                    env()->ArithmeticException_instance())) {
2079     // It has been already too many times, but we cannot use builtin_throw (e.g. we care about backtraces),
2080     // so let's bail out intrinsic rather than risking deopting again.
2081     return false;
2082   }
2083 
2084   Node* bol = _gvn.transform( new BoolNode(test, BoolTest::overflow) );
2085   IfNode* check = create_and_map_if(control(), bol, PROB_UNLIKELY_MAG(3), COUNT_UNKNOWN);
2086   Node* fast_path = _gvn.transform( new IfFalseNode(check));
2087   Node* slow_path = _gvn.transform( new IfTrueNode(check) );
2088 
2089   {
2090     PreserveJVMState pjvms(this);
2091     PreserveReexecuteState preexecs(this);
2092     jvms()->set_should_reexecute(true);
2093 
2094     set_control(slow_path);
2095     set_i_o(i_o());
2096 
2097     builtin_throw(Deoptimization::Reason_intrinsic,
2098                   env()->ArithmeticException_instance(),
2099                   /*allow_too_many_traps*/ false);
2100   }
2101 
2102   set_control(fast_path);
2103   set_result(math);
2104   return true;
2105 }
2106 
2107 template <typename OverflowOp>
2108 bool LibraryCallKit::inline_math_overflow(Node* arg1, Node* arg2) {
2109   typedef typename OverflowOp::MathOp MathOp;
2110 
2111   MathOp* mathOp = new MathOp(arg1, arg2);
2112   Node* operation = _gvn.transform( mathOp );
2113   Node* ofcheck = _gvn.transform( new OverflowOp(arg1, arg2) );
2114   return inline_math_mathExact(operation, ofcheck);
2115 }
2116 
2117 bool LibraryCallKit::inline_math_addExactI(bool is_increment) {
2118   return inline_math_overflow<OverflowAddINode>(argument(0), is_increment ? intcon(1) : argument(1));
2119 }
2120 
2121 bool LibraryCallKit::inline_math_addExactL(bool is_increment) {
2122   return inline_math_overflow<OverflowAddLNode>(argument(0), is_increment ? longcon(1) : argument(2));
2123 }
2124 
2125 bool LibraryCallKit::inline_math_subtractExactI(bool is_decrement) {
2126   return inline_math_overflow<OverflowSubINode>(argument(0), is_decrement ? intcon(1) : argument(1));
2127 }
2128 
2129 bool LibraryCallKit::inline_math_subtractExactL(bool is_decrement) {
2130   return inline_math_overflow<OverflowSubLNode>(argument(0), is_decrement ? longcon(1) : argument(2));
2131 }
2132 
2133 bool LibraryCallKit::inline_math_negateExactI() {
2134   return inline_math_overflow<OverflowSubINode>(intcon(0), argument(0));
2135 }
2136 
2137 bool LibraryCallKit::inline_math_negateExactL() {
2138   return inline_math_overflow<OverflowSubLNode>(longcon(0), argument(0));
2139 }
2140 
2141 bool LibraryCallKit::inline_math_multiplyExactI() {
2142   return inline_math_overflow<OverflowMulINode>(argument(0), argument(1));
2143 }
2144 
2145 bool LibraryCallKit::inline_math_multiplyExactL() {
2146   return inline_math_overflow<OverflowMulLNode>(argument(0), argument(2));
2147 }
2148 
2149 bool LibraryCallKit::inline_math_multiplyHigh() {
2150   set_result(_gvn.transform(new MulHiLNode(argument(0), argument(2))));
2151   return true;
2152 }
2153 
2154 bool LibraryCallKit::inline_math_unsignedMultiplyHigh() {
2155   set_result(_gvn.transform(new UMulHiLNode(argument(0), argument(2))));
2156   return true;
2157 }
2158 
2159 inline int
2160 LibraryCallKit::classify_unsafe_addr(Node* &base, Node* &offset, BasicType type) {
2161   const TypePtr* base_type = TypePtr::NULL_PTR;
2162   if (base != nullptr)  base_type = _gvn.type(base)->isa_ptr();
2163   if (base_type == nullptr) {
2164     // Unknown type.
2165     return Type::AnyPtr;
2166   } else if (_gvn.type(base->uncast()) == TypePtr::NULL_PTR) {
2167     // Since this is a null+long form, we have to switch to a rawptr.
2168     base   = _gvn.transform(new CastX2PNode(offset));
2169     offset = MakeConX(0);
2170     return Type::RawPtr;
2171   } else if (base_type->base() == Type::RawPtr) {
2172     return Type::RawPtr;
2173   } else if (base_type->isa_oopptr()) {
2174     // Base is never null => always a heap address.
2175     if (!TypePtr::NULL_PTR->higher_equal(base_type)) {
2176       return Type::OopPtr;
2177     }
2178     // Offset is small => always a heap address.
2179     const TypeX* offset_type = _gvn.type(offset)->isa_intptr_t();
2180     if (offset_type != nullptr &&
2181         base_type->offset() == 0 &&     // (should always be?)
2182         offset_type->_lo >= 0 &&
2183         !MacroAssembler::needs_explicit_null_check(offset_type->_hi)) {
2184       return Type::OopPtr;
2185     } else if (type == T_OBJECT) {
2186       // off heap access to an oop doesn't make any sense. Has to be on
2187       // heap.
2188       return Type::OopPtr;
2189     }
2190     // Otherwise, it might either be oop+off or null+addr.
2191     return Type::AnyPtr;
2192   } else {
2193     // No information:
2194     return Type::AnyPtr;
2195   }
2196 }
2197 
2198 Node* LibraryCallKit::make_unsafe_address(Node*& base, Node* offset, BasicType type, bool can_cast) {
2199   Node* uncasted_base = base;
2200   int kind = classify_unsafe_addr(uncasted_base, offset, type);
2201   if (kind == Type::RawPtr) {
2202     return basic_plus_adr(top(), uncasted_base, offset);
2203   } else if (kind == Type::AnyPtr) {
2204     assert(base == uncasted_base, "unexpected base change");
2205     if (can_cast) {
2206       if (!_gvn.type(base)->speculative_maybe_null() &&
2207           !too_many_traps(Deoptimization::Reason_speculate_null_check)) {
2208         // According to profiling, this access is always on
2209         // heap. Casting the base to not null and thus avoiding membars
2210         // around the access should allow better optimizations
2211         Node* null_ctl = top();
2212         base = null_check_oop(base, &null_ctl, true, true, true);
2213         assert(null_ctl->is_top(), "no null control here");
2214         return basic_plus_adr(base, offset);
2215       } else if (_gvn.type(base)->speculative_always_null() &&
2216                  !too_many_traps(Deoptimization::Reason_speculate_null_assert)) {
2217         // According to profiling, this access is always off
2218         // heap.
2219         base = null_assert(base);
2220         Node* raw_base = _gvn.transform(new CastX2PNode(offset));
2221         offset = MakeConX(0);
2222         return basic_plus_adr(top(), raw_base, offset);
2223       }
2224     }
2225     // We don't know if it's an on heap or off heap access. Fall back
2226     // to raw memory access.
2227     Node* raw = _gvn.transform(new CheckCastPPNode(control(), base, TypeRawPtr::BOTTOM));
2228     return basic_plus_adr(top(), raw, offset);
2229   } else {
2230     assert(base == uncasted_base, "unexpected base change");
2231     // We know it's an on heap access so base can't be null
2232     if (TypePtr::NULL_PTR->higher_equal(_gvn.type(base))) {
2233       base = must_be_not_null(base, true);
2234     }
2235     return basic_plus_adr(base, offset);
2236   }
2237 }
2238 
2239 //--------------------------inline_number_methods-----------------------------
2240 // inline int     Integer.numberOfLeadingZeros(int)
2241 // inline int        Long.numberOfLeadingZeros(long)
2242 //
2243 // inline int     Integer.numberOfTrailingZeros(int)
2244 // inline int        Long.numberOfTrailingZeros(long)
2245 //
2246 // inline int     Integer.bitCount(int)
2247 // inline int        Long.bitCount(long)
2248 //
2249 // inline char  Character.reverseBytes(char)
2250 // inline short     Short.reverseBytes(short)
2251 // inline int     Integer.reverseBytes(int)
2252 // inline long       Long.reverseBytes(long)
2253 bool LibraryCallKit::inline_number_methods(vmIntrinsics::ID id) {
2254   Node* arg = argument(0);
2255   Node* n = nullptr;
2256   switch (id) {
2257   case vmIntrinsics::_numberOfLeadingZeros_i:   n = new CountLeadingZerosINode( arg); break;
2258   case vmIntrinsics::_numberOfLeadingZeros_l:   n = new CountLeadingZerosLNode( arg); break;
2259   case vmIntrinsics::_numberOfTrailingZeros_i:  n = new CountTrailingZerosINode(arg); break;
2260   case vmIntrinsics::_numberOfTrailingZeros_l:  n = new CountTrailingZerosLNode(arg); break;
2261   case vmIntrinsics::_bitCount_i:               n = new PopCountINode(          arg); break;
2262   case vmIntrinsics::_bitCount_l:               n = new PopCountLNode(          arg); break;
2263   case vmIntrinsics::_reverseBytes_c:           n = new ReverseBytesUSNode(     arg); break;
2264   case vmIntrinsics::_reverseBytes_s:           n = new ReverseBytesSNode(      arg); break;
2265   case vmIntrinsics::_reverseBytes_i:           n = new ReverseBytesINode(      arg); break;
2266   case vmIntrinsics::_reverseBytes_l:           n = new ReverseBytesLNode(      arg); break;
2267   case vmIntrinsics::_reverse_i:                n = new ReverseINode(           arg); break;
2268   case vmIntrinsics::_reverse_l:                n = new ReverseLNode(           arg); break;
2269   default:  fatal_unexpected_iid(id);  break;
2270   }
2271   set_result(_gvn.transform(n));
2272   return true;
2273 }
2274 
2275 //--------------------------inline_bitshuffle_methods-----------------------------
2276 // inline int Integer.compress(int, int)
2277 // inline int Integer.expand(int, int)
2278 // inline long Long.compress(long, long)
2279 // inline long Long.expand(long, long)
2280 bool LibraryCallKit::inline_bitshuffle_methods(vmIntrinsics::ID id) {
2281   Node* n = nullptr;
2282   switch (id) {
2283     case vmIntrinsics::_compress_i:  n = new CompressBitsNode(argument(0), argument(1), TypeInt::INT); break;
2284     case vmIntrinsics::_expand_i:    n = new ExpandBitsNode(argument(0),  argument(1), TypeInt::INT); break;
2285     case vmIntrinsics::_compress_l:  n = new CompressBitsNode(argument(0), argument(2), TypeLong::LONG); break;
2286     case vmIntrinsics::_expand_l:    n = new ExpandBitsNode(argument(0), argument(2), TypeLong::LONG); break;
2287     default:  fatal_unexpected_iid(id);  break;
2288   }
2289   set_result(_gvn.transform(n));
2290   return true;
2291 }
2292 
2293 //--------------------------inline_number_methods-----------------------------
2294 // inline int Integer.compareUnsigned(int, int)
2295 // inline int    Long.compareUnsigned(long, long)
2296 bool LibraryCallKit::inline_compare_unsigned(vmIntrinsics::ID id) {
2297   Node* arg1 = argument(0);
2298   Node* arg2 = (id == vmIntrinsics::_compareUnsigned_l) ? argument(2) : argument(1);
2299   Node* n = nullptr;
2300   switch (id) {
2301     case vmIntrinsics::_compareUnsigned_i:   n = new CmpU3Node(arg1, arg2);  break;
2302     case vmIntrinsics::_compareUnsigned_l:   n = new CmpUL3Node(arg1, arg2); break;
2303     default:  fatal_unexpected_iid(id);  break;
2304   }
2305   set_result(_gvn.transform(n));
2306   return true;
2307 }
2308 
2309 //--------------------------inline_unsigned_divmod_methods-----------------------------
2310 // inline int Integer.divideUnsigned(int, int)
2311 // inline int Integer.remainderUnsigned(int, int)
2312 // inline long Long.divideUnsigned(long, long)
2313 // inline long Long.remainderUnsigned(long, long)
2314 bool LibraryCallKit::inline_divmod_methods(vmIntrinsics::ID id) {
2315   Node* n = nullptr;
2316   switch (id) {
2317     case vmIntrinsics::_divideUnsigned_i: {
2318       zero_check_int(argument(1));
2319       // Compile-time detect of null-exception
2320       if (stopped()) {
2321         return true; // keep the graph constructed so far
2322       }
2323       n = new UDivINode(control(), argument(0), argument(1));
2324       break;
2325     }
2326     case vmIntrinsics::_divideUnsigned_l: {
2327       zero_check_long(argument(2));
2328       // Compile-time detect of null-exception
2329       if (stopped()) {
2330         return true; // keep the graph constructed so far
2331       }
2332       n = new UDivLNode(control(), argument(0), argument(2));
2333       break;
2334     }
2335     case vmIntrinsics::_remainderUnsigned_i: {
2336       zero_check_int(argument(1));
2337       // Compile-time detect of null-exception
2338       if (stopped()) {
2339         return true; // keep the graph constructed so far
2340       }
2341       n = new UModINode(control(), argument(0), argument(1));
2342       break;
2343     }
2344     case vmIntrinsics::_remainderUnsigned_l: {
2345       zero_check_long(argument(2));
2346       // Compile-time detect of null-exception
2347       if (stopped()) {
2348         return true; // keep the graph constructed so far
2349       }
2350       n = new UModLNode(control(), argument(0), argument(2));
2351       break;
2352     }
2353     default:  fatal_unexpected_iid(id);  break;
2354   }
2355   set_result(_gvn.transform(n));
2356   return true;
2357 }
2358 
2359 //----------------------------inline_unsafe_access----------------------------
2360 
2361 const TypeOopPtr* LibraryCallKit::sharpen_unsafe_type(Compile::AliasType* alias_type, const TypePtr *adr_type) {
2362   // Attempt to infer a sharper value type from the offset and base type.
2363   ciKlass* sharpened_klass = nullptr;
2364   bool null_free = false;
2365 
2366   // See if it is an instance field, with an object type.
2367   if (alias_type->field() != nullptr) {
2368     if (alias_type->field()->type()->is_klass()) {
2369       sharpened_klass = alias_type->field()->type()->as_klass();
2370       null_free = alias_type->field()->is_null_free();
2371     }
2372   }
2373 
2374   const TypeOopPtr* result = nullptr;
2375   // See if it is a narrow oop array.
2376   if (adr_type->isa_aryptr()) {
2377     if (adr_type->offset() >= refArrayOopDesc::base_offset_in_bytes()) {
2378       const TypeOopPtr* elem_type = adr_type->is_aryptr()->elem()->make_oopptr();
2379       null_free = adr_type->is_aryptr()->is_null_free();
2380       if (elem_type != nullptr && elem_type->is_loaded()) {
2381         // Sharpen the value type.
2382         result = elem_type;
2383       }
2384     }
2385   }
2386 
2387   // The sharpened class might be unloaded if there is no class loader
2388   // contraint in place.
2389   if (result == nullptr && sharpened_klass != nullptr && sharpened_klass->is_loaded()) {
2390     // Sharpen the value type.
2391     result = TypeOopPtr::make_from_klass(sharpened_klass);
2392     if (null_free) {
2393       result = result->join_speculative(TypePtr::NOTNULL)->is_oopptr();
2394     }
2395   }
2396   if (result != nullptr) {
2397 #ifndef PRODUCT
2398     if (C->print_intrinsics() || C->print_inlining()) {
2399       tty->print("  from base type:  ");  adr_type->dump(); tty->cr();
2400       tty->print("  sharpened value: ");  result->dump();    tty->cr();
2401     }
2402 #endif
2403   }
2404   return result;
2405 }
2406 
2407 DecoratorSet LibraryCallKit::mo_decorator_for_access_kind(AccessKind kind) {
2408   switch (kind) {
2409       case Relaxed:
2410         return MO_UNORDERED;
2411       case Opaque:
2412         return MO_RELAXED;
2413       case Acquire:
2414         return MO_ACQUIRE;
2415       case Release:
2416         return MO_RELEASE;
2417       case Volatile:
2418         return MO_SEQ_CST;
2419       default:
2420         ShouldNotReachHere();
2421         return 0;
2422   }
2423 }
2424 
2425 LibraryCallKit::SavedState::SavedState(LibraryCallKit* kit) :
2426   _kit(kit),
2427   _sp(kit->sp()),
2428   _jvms(kit->jvms()),
2429   _map(kit->clone_map()),
2430   _discarded(false)
2431 {
2432   for (DUIterator_Fast imax, i = kit->control()->fast_outs(imax); i < imax; i++) {
2433     Node* out = kit->control()->fast_out(i);
2434     if (out->is_CFG()) {
2435       _ctrl_succ.push(out);
2436     }
2437   }
2438 }
2439 
2440 LibraryCallKit::SavedState::~SavedState() {
2441   if (_discarded) {
2442     _kit->destruct_map_clone(_map);
2443     return;
2444   }
2445   _kit->jvms()->set_map(_map);
2446   _kit->jvms()->set_sp(_sp);
2447   _map->set_jvms(_kit->jvms());
2448   _kit->set_map(_map);
2449   _kit->set_sp(_sp);
2450   for (DUIterator_Fast imax, i = _kit->control()->fast_outs(imax); i < imax; i++) {
2451     Node* out = _kit->control()->fast_out(i);
2452     if (out->is_CFG() && out->in(0) == _kit->control() && out != _kit->map() && !_ctrl_succ.member(out)) {
2453       _kit->_gvn.hash_delete(out);
2454       out->set_req(0, _kit->C->top());
2455       _kit->C->record_for_igvn(out);
2456       --i; --imax;
2457       _kit->_gvn.hash_find_insert(out);
2458     }
2459   }
2460 }
2461 
2462 void LibraryCallKit::SavedState::discard() {
2463   _discarded = true;
2464 }
2465 
2466 bool LibraryCallKit::inline_unsafe_access(bool is_store, const BasicType type, const AccessKind kind, const bool unaligned) {
2467   if (callee()->is_static())  return false;  // caller must have the capability!
2468   DecoratorSet decorators = C2_UNSAFE_ACCESS;
2469   guarantee(!is_store || kind != Acquire, "Acquire accesses can be produced only for loads");
2470   guarantee( is_store || kind != Release, "Release accesses can be produced only for stores");
2471   assert(type != T_OBJECT || !unaligned, "unaligned access not supported with object type");
2472 
2473   if (is_reference_type(type)) {
2474     decorators |= ON_UNKNOWN_OOP_REF;
2475   }
2476 
2477   if (unaligned) {
2478     decorators |= C2_UNALIGNED;
2479   }
2480 
2481 #ifndef PRODUCT
2482   {
2483     ResourceMark rm;
2484     // Check the signatures.
2485     ciSignature* sig = callee()->signature();
2486 #ifdef ASSERT
2487     if (!is_store) {
2488       // Object getReference(Object base, int/long offset), etc.
2489       BasicType rtype = sig->return_type()->basic_type();
2490       assert(rtype == type, "getter must return the expected value");
2491       assert(sig->count() == 2, "oop getter has 2 arguments");
2492       assert(sig->type_at(0)->basic_type() == T_OBJECT, "getter base is object");
2493       assert(sig->type_at(1)->basic_type() == T_LONG, "getter offset is correct");
2494     } else {
2495       // void putReference(Object base, int/long offset, Object x), etc.
2496       assert(sig->return_type()->basic_type() == T_VOID, "putter must not return a value");
2497       assert(sig->count() == 3, "oop putter has 3 arguments");
2498       assert(sig->type_at(0)->basic_type() == T_OBJECT, "putter base is object");
2499       assert(sig->type_at(1)->basic_type() == T_LONG, "putter offset is correct");
2500       BasicType vtype = sig->type_at(sig->count()-1)->basic_type();
2501       assert(vtype == type, "putter must accept the expected value");
2502     }
2503 #endif // ASSERT
2504  }
2505 #endif //PRODUCT
2506 
2507   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
2508 
2509   Node* receiver = argument(0);  // type: oop
2510 
2511   // Build address expression.
2512   Node* heap_base_oop = top();
2513 
2514   // The base is either a Java object or a value produced by Unsafe.staticFieldBase
2515   Node* base = argument(1);  // type: oop
2516   // The offset is a value produced by Unsafe.staticFieldOffset or Unsafe.objectFieldOffset
2517   Node* offset = argument(2);  // type: long
2518   // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
2519   // to be plain byte offsets, which are also the same as those accepted
2520   // by oopDesc::field_addr.
2521   assert(Unsafe_field_offset_to_byte_offset(11) == 11,
2522          "fieldOffset must be byte-scaled");
2523 
2524   if (base->is_InlineType()) {
2525     assert(!is_store, "InlineTypeNodes are non-larval value objects");
2526     InlineTypeNode* vt = base->as_InlineType();
2527     if (offset->is_Con()) {
2528       long off = find_long_con(offset, 0);
2529       ciInlineKlass* vk = vt->type()->inline_klass();
2530       if ((long)(int)off != off || !vk->contains_field_offset(off)) {
2531         return false;
2532       }
2533 
2534       ciField* field = vk->get_non_flat_field_by_offset(off);
2535       if (field != nullptr) {
2536         BasicType bt = type2field[field->type()->basic_type()];
2537         if (bt == T_ARRAY || bt == T_NARROWOOP) {
2538           bt = T_OBJECT;
2539         }
2540         if (bt == type && !field->is_flat()) {
2541           Node* value = vt->field_value_by_offset(off, false);
2542           if (value->is_InlineType()) {
2543             value = value->as_InlineType()->adjust_scalarization_depth(this);
2544           }
2545           set_result(value);
2546           return true;
2547         }
2548       }
2549     }
2550     {
2551       // Re-execute the unsafe access if allocation triggers deoptimization.
2552       PreserveReexecuteState preexecs(this);
2553       jvms()->set_should_reexecute(true);
2554       vt = vt->buffer(this);
2555     }
2556     base = vt->get_oop();
2557   }
2558 
2559   // 32-bit machines ignore the high half!
2560   offset = ConvL2X(offset);
2561 
2562   // Save state and restore on bailout
2563   SavedState old_state(this);
2564 
2565   Node* adr = make_unsafe_address(base, offset, type, kind == Relaxed);
2566   assert(!stopped(), "Inlining of unsafe access failed: address construction stopped unexpectedly");
2567 
2568   if (_gvn.type(base->uncast())->isa_ptr() == TypePtr::NULL_PTR) {
2569     if (type != T_OBJECT) {
2570       decorators |= IN_NATIVE; // off-heap primitive access
2571     } else {
2572       return false; // off-heap oop accesses are not supported
2573     }
2574   } else {
2575     heap_base_oop = base; // on-heap or mixed access
2576   }
2577 
2578   // Can base be null? Otherwise, always on-heap access.
2579   bool can_access_non_heap = TypePtr::NULL_PTR->higher_equal(_gvn.type(base));
2580 
2581   if (!can_access_non_heap) {
2582     decorators |= IN_HEAP;
2583   }
2584 
2585   Node* val = is_store ? argument(4) : nullptr;
2586 
2587   const TypePtr* adr_type = _gvn.type(adr)->isa_ptr();
2588   if (adr_type == TypePtr::NULL_PTR) {
2589     return false; // off-heap access with zero address
2590   }
2591 
2592   // Try to categorize the address.
2593   Compile::AliasType* alias_type = C->alias_type(adr_type);
2594   assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
2595 
2596   if (alias_type->adr_type() == TypeInstPtr::KLASS ||
2597       alias_type->adr_type() == TypeAryPtr::RANGE) {
2598     return false; // not supported
2599   }
2600 
2601   bool mismatched = false;
2602   BasicType bt = T_ILLEGAL;
2603   ciField* field = nullptr;
2604   if (adr_type->isa_instptr()) {
2605     const TypeInstPtr* instptr = adr_type->is_instptr();
2606     ciInstanceKlass* k = instptr->instance_klass();
2607     int off = instptr->offset();
2608     if (instptr->const_oop() != nullptr &&
2609         k == ciEnv::current()->Class_klass() &&
2610         instptr->offset() >= (k->size_helper() * wordSize)) {
2611       k = instptr->const_oop()->as_instance()->java_lang_Class_klass()->as_instance_klass();
2612       field = k->get_field_by_offset(off, true);
2613     } else {
2614       field = k->get_non_flat_field_by_offset(off);
2615     }
2616     if (field != nullptr) {
2617       bt = type2field[field->type()->basic_type()];
2618     }
2619     if (bt != alias_type->basic_type()) {
2620       // Type mismatch. Is it an access to a nested flat field?
2621       field = k->get_field_by_offset(off, false);
2622       if (field != nullptr) {
2623         bt = type2field[field->type()->basic_type()];
2624       }
2625     }
2626     assert(bt == alias_type->basic_type(), "should match");
2627   } else {
2628     bt = alias_type->basic_type();
2629   }
2630 
2631   if (bt != T_ILLEGAL) {
2632     assert(alias_type->adr_type()->is_oopptr(), "should be on-heap access");
2633     if (bt == T_BYTE && adr_type->isa_aryptr()) {
2634       // Alias type doesn't differentiate between byte[] and boolean[]).
2635       // Use address type to get the element type.
2636       bt = adr_type->is_aryptr()->elem()->array_element_basic_type();
2637     }
2638     if (is_reference_type(bt, true)) {
2639       // accessing an array field with getReference is not a mismatch
2640       bt = T_OBJECT;
2641     }
2642     if ((bt == T_OBJECT) != (type == T_OBJECT)) {
2643       // Don't intrinsify mismatched object accesses
2644       return false;
2645     }
2646     mismatched = (bt != type);
2647   } else if (alias_type->adr_type()->isa_oopptr()) {
2648     mismatched = true; // conservatively mark all "wide" on-heap accesses as mismatched
2649   }
2650 
2651   old_state.discard();
2652   assert(!mismatched || alias_type->adr_type()->is_oopptr(), "off-heap access can't be mismatched");
2653 
2654   if (mismatched) {
2655     decorators |= C2_MISMATCHED;
2656   }
2657 
2658   // First guess at the value type.
2659   const Type *value_type = Type::get_const_basic_type(type);
2660 
2661   // Figure out the memory ordering.
2662   decorators |= mo_decorator_for_access_kind(kind);
2663 
2664   if (!is_store) {
2665     if (type == T_OBJECT) {
2666       const TypeOopPtr* tjp = sharpen_unsafe_type(alias_type, adr_type);
2667       if (tjp != nullptr) {
2668         value_type = tjp;
2669       }
2670     }
2671   }
2672 
2673   receiver = null_check(receiver);
2674   if (stopped()) {
2675     return true;
2676   }
2677   // Heap pointers get a null-check from the interpreter,
2678   // as a courtesy.  However, this is not guaranteed by Unsafe,
2679   // and it is not possible to fully distinguish unintended nulls
2680   // from intended ones in this API.
2681 
2682   if (!is_store) {
2683     Node* p = nullptr;
2684     // Try to constant fold a load from a constant field
2685 
2686     if (heap_base_oop != top() && field != nullptr && field->is_constant() && !field->is_flat() && !mismatched) {
2687       // final or stable field
2688       p = make_constant_from_field(field, heap_base_oop);
2689     }
2690 
2691     if (p == nullptr) { // Could not constant fold the load
2692       p = access_load_at(heap_base_oop, adr, adr_type, value_type, type, decorators);
2693       const TypeOopPtr* ptr = value_type->make_oopptr();
2694       if (ptr != nullptr && ptr->is_inlinetypeptr()) {
2695         // Load a non-flattened inline type from memory
2696         p = InlineTypeNode::make_from_oop(this, p, ptr->inline_klass());
2697       }
2698       // Normalize the value returned by getBoolean in the following cases
2699       if (type == T_BOOLEAN &&
2700           (mismatched ||
2701            heap_base_oop == top() ||                  // - heap_base_oop is null or
2702            (can_access_non_heap && field == nullptr)) // - heap_base_oop is potentially null
2703                                                       //   and the unsafe access is made to large offset
2704                                                       //   (i.e., larger than the maximum offset necessary for any
2705                                                       //   field access)
2706             ) {
2707           IdealKit ideal = IdealKit(this);
2708 #define __ ideal.
2709           IdealVariable normalized_result(ideal);
2710           __ declarations_done();
2711           __ set(normalized_result, p);
2712           __ if_then(p, BoolTest::ne, ideal.ConI(0));
2713           __ set(normalized_result, ideal.ConI(1));
2714           ideal.end_if();
2715           final_sync(ideal);
2716           p = __ value(normalized_result);
2717 #undef __
2718       }
2719     }
2720     if (type == T_ADDRESS) {
2721       p = gvn().transform(new CastP2XNode(nullptr, p));
2722       p = ConvX2UL(p);
2723     }
2724     // The load node has the control of the preceding MemBarCPUOrder.  All
2725     // following nodes will have the control of the MemBarCPUOrder inserted at
2726     // the end of this method.  So, pushing the load onto the stack at a later
2727     // point is fine.
2728     set_result(p);
2729   } else {
2730     if (bt == T_ADDRESS) {
2731       // Repackage the long as a pointer.
2732       val = ConvL2X(val);
2733       val = gvn().transform(new CastX2PNode(val));
2734     }
2735     access_store_at(heap_base_oop, adr, adr_type, val, value_type, type, decorators);
2736   }
2737 
2738   return true;
2739 }
2740 
2741 bool LibraryCallKit::inline_unsafe_flat_access(bool is_store, AccessKind kind) {
2742 #ifdef ASSERT
2743   {
2744     ResourceMark rm;
2745     // Check the signatures.
2746     ciSignature* sig = callee()->signature();
2747     assert(sig->type_at(0)->basic_type() == T_OBJECT, "base should be object, but is %s", type2name(sig->type_at(0)->basic_type()));
2748     assert(sig->type_at(1)->basic_type() == T_LONG, "offset should be long, but is %s", type2name(sig->type_at(1)->basic_type()));
2749     assert(sig->type_at(2)->basic_type() == T_INT, "layout kind should be int, but is %s", type2name(sig->type_at(3)->basic_type()));
2750     assert(sig->type_at(3)->basic_type() == T_OBJECT, "value klass should be object, but is %s", type2name(sig->type_at(4)->basic_type()));
2751     if (is_store) {
2752       assert(sig->return_type()->basic_type() == T_VOID, "putter must not return a value, but returns %s", type2name(sig->return_type()->basic_type()));
2753       assert(sig->count() == 5, "flat putter should have 5 arguments, but has %d", sig->count());
2754       assert(sig->type_at(4)->basic_type() == T_OBJECT, "put value should be object, but is %s", type2name(sig->type_at(5)->basic_type()));
2755     } else {
2756       assert(sig->return_type()->basic_type() == T_OBJECT, "getter must return an object, but returns %s", type2name(sig->return_type()->basic_type()));
2757       assert(sig->count() == 4, "flat getter should have 4 arguments, but has %d", sig->count());
2758     }
2759  }
2760 #endif // ASSERT
2761 
2762   assert(kind == Relaxed, "Only plain accesses for now");
2763   if (callee()->is_static()) {
2764     // caller must have the capability!
2765     return false;
2766   }
2767   C->set_has_unsafe_access(true);
2768 
2769   const TypeInstPtr* value_klass_node = _gvn.type(argument(5))->isa_instptr();
2770   if (value_klass_node == nullptr || value_klass_node->const_oop() == nullptr) {
2771     // parameter valueType is not a constant
2772     return false;
2773   }
2774   ciType* mirror_type = value_klass_node->const_oop()->as_instance()->java_mirror_type();
2775   if (!mirror_type->is_inlinetype()) {
2776     // Dead code
2777     return false;
2778   }
2779   ciInlineKlass* value_klass = mirror_type->as_inline_klass();
2780 
2781   const TypeInt* layout_type = _gvn.type(argument(4))->isa_int();
2782   if (layout_type == nullptr || !layout_type->is_con()) {
2783     // parameter layoutKind is not a constant
2784     return false;
2785   }
2786   assert(layout_type->get_con() >= static_cast<int>(LayoutKind::REFERENCE) &&
2787          layout_type->get_con() <= static_cast<int>(LayoutKind::UNKNOWN),
2788          "invalid layoutKind %d", layout_type->get_con());
2789   LayoutKind layout = static_cast<LayoutKind>(layout_type->get_con());
2790   assert(layout == LayoutKind::REFERENCE || layout == LayoutKind::NULL_FREE_NON_ATOMIC_FLAT ||
2791          layout == LayoutKind::NULL_FREE_ATOMIC_FLAT || layout == LayoutKind::NULLABLE_ATOMIC_FLAT,
2792          "unexpected layoutKind %d", layout_type->get_con());
2793 
2794   null_check(argument(0));
2795   if (stopped()) {
2796     return true;
2797   }
2798 
2799   Node* base = must_be_not_null(argument(1), true);
2800   Node* offset = argument(2);
2801   const Type* base_type = _gvn.type(base);
2802 
2803   Node* ptr;
2804   bool immutable_memory = false;
2805   DecoratorSet decorators = C2_UNSAFE_ACCESS | IN_HEAP | MO_UNORDERED;
2806   if (base_type->isa_instptr()) {
2807     const TypeLong* offset_type = _gvn.type(offset)->isa_long();
2808     if (offset_type == nullptr || !offset_type->is_con()) {
2809       // Offset into a non-array should be a constant
2810       decorators |= C2_MISMATCHED;
2811     } else {
2812       int offset_con = checked_cast<int>(offset_type->get_con());
2813       ciInstanceKlass* base_klass = base_type->is_instptr()->instance_klass();
2814       ciField* field = base_klass->get_non_flat_field_by_offset(offset_con);
2815       if (field == nullptr) {
2816         assert(!base_klass->is_final(), "non-existence field at offset %d of class %s", offset_con, base_klass->name()->as_utf8());
2817         decorators |= C2_MISMATCHED;
2818       } else {
2819         assert(field->type() == value_klass, "field at offset %d of %s is of type %s, but valueType is %s",
2820                offset_con, base_klass->name()->as_utf8(), field->type()->name(), value_klass->name()->as_utf8());
2821         immutable_memory = field->is_strict() && field->is_final();
2822 
2823         if (base->is_InlineType()) {
2824           assert(!is_store, "Cannot store into a non-larval value object");
2825           set_result(base->as_InlineType()->field_value_by_offset(offset_con, false));
2826           return true;
2827         }
2828       }
2829     }
2830 
2831     if (base->is_InlineType()) {
2832       assert(!is_store, "Cannot store into a non-larval value object");
2833       base = base->as_InlineType()->buffer(this, true);
2834     }
2835     ptr = basic_plus_adr(base, ConvL2X(offset));
2836   } else if (base_type->isa_aryptr()) {
2837     decorators |= IS_ARRAY;
2838     if (layout == LayoutKind::REFERENCE) {
2839       if (!base_type->is_aryptr()->is_not_flat()) {
2840         const TypeAryPtr* array_type = base_type->is_aryptr()->cast_to_not_flat();
2841         Node* new_base = _gvn.transform(new CastPPNode(control(), base, array_type, ConstraintCastNode::DependencyType::NonFloatingNarrowing));
2842         replace_in_map(base, new_base);
2843         base = new_base;
2844       }
2845       ptr = basic_plus_adr(base, ConvL2X(offset));
2846     } else {
2847       if (UseArrayFlattening) {
2848         // Flat array must have an exact type
2849         bool is_null_free = !LayoutKindHelper::is_nullable_flat(layout);
2850         bool is_atomic = LayoutKindHelper::is_atomic_flat(layout);
2851         Node* new_base = cast_to_flat_array_exact(base, value_klass, is_null_free, is_atomic);
2852         replace_in_map(base, new_base);
2853         base = new_base;
2854         ptr = basic_plus_adr(base, ConvL2X(offset));
2855         const TypeAryPtr* ptr_type = _gvn.type(ptr)->is_aryptr();
2856         if (ptr_type->field_offset().get() != 0) {
2857           ptr = _gvn.transform(new CastPPNode(control(), ptr, ptr_type->with_field_offset(0), ConstraintCastNode::DependencyType::NonFloatingNarrowing));
2858         }
2859       } else {
2860         uncommon_trap(Deoptimization::Reason_intrinsic,
2861                       Deoptimization::Action_none);
2862         return true;
2863       }
2864     }
2865   } else {
2866     decorators |= C2_MISMATCHED;
2867     ptr = basic_plus_adr(base, ConvL2X(offset));
2868   }
2869 
2870   if (is_store) {
2871     Node* value = argument(6);
2872     const Type* value_type = _gvn.type(value);
2873     if (!value_type->is_inlinetypeptr()) {
2874       value_type = Type::get_const_type(value_klass)->filter_speculative(value_type);
2875       Node* new_value = _gvn.transform(new CastPPNode(control(), value, value_type, ConstraintCastNode::DependencyType::NonFloatingNarrowing));
2876       new_value = InlineTypeNode::make_from_oop(this, new_value, value_klass);
2877       replace_in_map(value, new_value);
2878       value = new_value;
2879     }
2880 
2881     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());
2882     if (layout == LayoutKind::REFERENCE) {
2883       const TypePtr* ptr_type = (decorators & C2_MISMATCHED) != 0 ? TypeRawPtr::BOTTOM : _gvn.type(ptr)->is_ptr();
2884       access_store_at(base, ptr, ptr_type, value, value_type, T_OBJECT, decorators);
2885     } else {
2886       bool atomic = LayoutKindHelper::is_atomic_flat(layout);
2887       bool null_free = !LayoutKindHelper::is_nullable_flat(layout);
2888       value->as_InlineType()->store_flat(this, base, ptr, atomic, immutable_memory, null_free, decorators);
2889     }
2890 
2891     return true;
2892   } else {
2893     decorators |= (C2_CONTROL_DEPENDENT_LOAD | C2_UNKNOWN_CONTROL_LOAD);
2894     InlineTypeNode* result;
2895     if (layout == LayoutKind::REFERENCE) {
2896       const TypePtr* ptr_type = (decorators & C2_MISMATCHED) != 0 ? TypeRawPtr::BOTTOM : _gvn.type(ptr)->is_ptr();
2897       Node* oop = access_load_at(base, ptr, ptr_type, Type::get_const_type(value_klass), T_OBJECT, decorators);
2898       result = InlineTypeNode::make_from_oop(this, oop, value_klass);
2899     } else {
2900       bool atomic = LayoutKindHelper::is_atomic_flat(layout);
2901       bool null_free = !LayoutKindHelper::is_nullable_flat(layout);
2902       result = InlineTypeNode::make_from_flat(this, value_klass, base, ptr, atomic, immutable_memory, null_free, decorators);
2903     }
2904 
2905     set_result(result);
2906     return true;
2907   }
2908 }
2909 
2910 bool LibraryCallKit::inline_unsafe_make_private_buffer() {
2911   Node* receiver = argument(0);
2912   Node* value = argument(1);
2913 
2914   const Type* type = gvn().type(value);
2915   if (!type->is_inlinetypeptr()) {
2916     C->record_method_not_compilable("value passed to Unsafe::makePrivateBuffer is not of a constant value type");
2917     return false;
2918   }
2919 
2920   null_check(receiver);
2921   if (stopped()) {
2922     return true;
2923   }
2924 
2925   value = null_check(value);
2926   if (stopped()) {
2927     return true;
2928   }
2929 
2930   ciInlineKlass* vk = type->inline_klass();
2931   Node* klass = makecon(TypeKlassPtr::make(vk));
2932   Node* obj = new_instance(klass);
2933   AllocateNode::Ideal_allocation(obj)->_larval = true;
2934 
2935   assert(value->is_InlineType(), "must be an InlineTypeNode");
2936   Node* payload_ptr = basic_plus_adr(obj, vk->payload_offset());
2937   value->as_InlineType()->store_flat(this, obj, payload_ptr, false, true, true, IN_HEAP | MO_UNORDERED);
2938 
2939   set_result(obj);
2940   return true;
2941 }
2942 
2943 bool LibraryCallKit::inline_unsafe_finish_private_buffer() {
2944   Node* receiver = argument(0);
2945   Node* buffer = argument(1);
2946 
2947   const Type* type = gvn().type(buffer);
2948   if (!type->is_inlinetypeptr()) {
2949     C->record_method_not_compilable("value passed to Unsafe::finishPrivateBuffer is not of a constant value type");
2950     return false;
2951   }
2952 
2953   AllocateNode* alloc = AllocateNode::Ideal_allocation(buffer);
2954   if (alloc == nullptr) {
2955     C->record_method_not_compilable("value passed to Unsafe::finishPrivateBuffer must be allocated by Unsafe::makePrivateBuffer");
2956     return false;
2957   }
2958 
2959   null_check(receiver);
2960   if (stopped()) {
2961     return true;
2962   }
2963 
2964   // Unset the larval bit in the object header
2965   Node* old_header = make_load(control(), buffer, TypeX_X, TypeX_X->basic_type(), MemNode::unordered, LoadNode::Pinned);
2966   Node* new_header = gvn().transform(new AndXNode(old_header, MakeConX(~markWord::larval_bit_in_place)));
2967   access_store_at(buffer, buffer, type->is_ptr(), new_header, TypeX_X, TypeX_X->basic_type(), MO_UNORDERED | IN_HEAP);
2968 
2969   // We must ensure that the buffer is properly published
2970   insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out(AllocateNode::RawAddress));
2971   assert(!type->maybe_null(), "result of an allocation should not be null");
2972   set_result(InlineTypeNode::make_from_oop(this, buffer, type->inline_klass()));
2973   return true;
2974 }
2975 
2976 //----------------------------inline_unsafe_load_store----------------------------
2977 // This method serves a couple of different customers (depending on LoadStoreKind):
2978 //
2979 // LS_cmp_swap:
2980 //
2981 //   boolean compareAndSetReference(Object o, long offset, Object expected, Object x);
2982 //   boolean compareAndSetInt(   Object o, long offset, int    expected, int    x);
2983 //   boolean compareAndSetLong(  Object o, long offset, long   expected, long   x);
2984 //
2985 // LS_cmp_swap_weak:
2986 //
2987 //   boolean weakCompareAndSetReference(       Object o, long offset, Object expected, Object x);
2988 //   boolean weakCompareAndSetReferencePlain(  Object o, long offset, Object expected, Object x);
2989 //   boolean weakCompareAndSetReferenceAcquire(Object o, long offset, Object expected, Object x);
2990 //   boolean weakCompareAndSetReferenceRelease(Object o, long offset, Object expected, Object x);
2991 //
2992 //   boolean weakCompareAndSetInt(          Object o, long offset, int    expected, int    x);
2993 //   boolean weakCompareAndSetIntPlain(     Object o, long offset, int    expected, int    x);
2994 //   boolean weakCompareAndSetIntAcquire(   Object o, long offset, int    expected, int    x);
2995 //   boolean weakCompareAndSetIntRelease(   Object o, long offset, int    expected, int    x);
2996 //
2997 //   boolean weakCompareAndSetLong(         Object o, long offset, long   expected, long   x);
2998 //   boolean weakCompareAndSetLongPlain(    Object o, long offset, long   expected, long   x);
2999 //   boolean weakCompareAndSetLongAcquire(  Object o, long offset, long   expected, long   x);
3000 //   boolean weakCompareAndSetLongRelease(  Object o, long offset, long   expected, long   x);
3001 //
3002 // LS_cmp_exchange:
3003 //
3004 //   Object compareAndExchangeReferenceVolatile(Object o, long offset, Object expected, Object x);
3005 //   Object compareAndExchangeReferenceAcquire( Object o, long offset, Object expected, Object x);
3006 //   Object compareAndExchangeReferenceRelease( Object o, long offset, Object expected, Object x);
3007 //
3008 //   Object compareAndExchangeIntVolatile(   Object o, long offset, Object expected, Object x);
3009 //   Object compareAndExchangeIntAcquire(    Object o, long offset, Object expected, Object x);
3010 //   Object compareAndExchangeIntRelease(    Object o, long offset, Object expected, Object x);
3011 //
3012 //   Object compareAndExchangeLongVolatile(  Object o, long offset, Object expected, Object x);
3013 //   Object compareAndExchangeLongAcquire(   Object o, long offset, Object expected, Object x);
3014 //   Object compareAndExchangeLongRelease(   Object o, long offset, Object expected, Object x);
3015 //
3016 // LS_get_add:
3017 //
3018 //   int  getAndAddInt( Object o, long offset, int  delta)
3019 //   long getAndAddLong(Object o, long offset, long delta)
3020 //
3021 // LS_get_set:
3022 //
3023 //   int    getAndSet(Object o, long offset, int    newValue)
3024 //   long   getAndSet(Object o, long offset, long   newValue)
3025 //   Object getAndSet(Object o, long offset, Object newValue)
3026 //
3027 bool LibraryCallKit::inline_unsafe_load_store(const BasicType type, const LoadStoreKind kind, const AccessKind access_kind) {
3028   // This basic scheme here is the same as inline_unsafe_access, but
3029   // differs in enough details that combining them would make the code
3030   // overly confusing.  (This is a true fact! I originally combined
3031   // them, but even I was confused by it!) As much code/comments as
3032   // possible are retained from inline_unsafe_access though to make
3033   // the correspondences clearer. - dl
3034 
3035   if (callee()->is_static())  return false;  // caller must have the capability!
3036 
3037   DecoratorSet decorators = C2_UNSAFE_ACCESS;
3038   decorators |= mo_decorator_for_access_kind(access_kind);
3039 
3040 #ifndef PRODUCT
3041   BasicType rtype;
3042   {
3043     ResourceMark rm;
3044     // Check the signatures.
3045     ciSignature* sig = callee()->signature();
3046     rtype = sig->return_type()->basic_type();
3047     switch(kind) {
3048       case LS_get_add:
3049       case LS_get_set: {
3050       // Check the signatures.
3051 #ifdef ASSERT
3052       assert(rtype == type, "get and set must return the expected type");
3053       assert(sig->count() == 3, "get and set has 3 arguments");
3054       assert(sig->type_at(0)->basic_type() == T_OBJECT, "get and set base is object");
3055       assert(sig->type_at(1)->basic_type() == T_LONG, "get and set offset is long");
3056       assert(sig->type_at(2)->basic_type() == type, "get and set must take expected type as new value/delta");
3057       assert(access_kind == Volatile, "mo is not passed to intrinsic nodes in current implementation");
3058 #endif // ASSERT
3059         break;
3060       }
3061       case LS_cmp_swap:
3062       case LS_cmp_swap_weak: {
3063       // Check the signatures.
3064 #ifdef ASSERT
3065       assert(rtype == T_BOOLEAN, "CAS must return boolean");
3066       assert(sig->count() == 4, "CAS has 4 arguments");
3067       assert(sig->type_at(0)->basic_type() == T_OBJECT, "CAS base is object");
3068       assert(sig->type_at(1)->basic_type() == T_LONG, "CAS offset is long");
3069 #endif // ASSERT
3070         break;
3071       }
3072       case LS_cmp_exchange: {
3073       // Check the signatures.
3074 #ifdef ASSERT
3075       assert(rtype == type, "CAS must return the expected type");
3076       assert(sig->count() == 4, "CAS has 4 arguments");
3077       assert(sig->type_at(0)->basic_type() == T_OBJECT, "CAS base is object");
3078       assert(sig->type_at(1)->basic_type() == T_LONG, "CAS offset is long");
3079 #endif // ASSERT
3080         break;
3081       }
3082       default:
3083         ShouldNotReachHere();
3084     }
3085   }
3086 #endif //PRODUCT
3087 
3088   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
3089 
3090   // Get arguments:
3091   Node* receiver = nullptr;
3092   Node* base     = nullptr;
3093   Node* offset   = nullptr;
3094   Node* oldval   = nullptr;
3095   Node* newval   = nullptr;
3096   switch(kind) {
3097     case LS_cmp_swap:
3098     case LS_cmp_swap_weak:
3099     case LS_cmp_exchange: {
3100       const bool two_slot_type = type2size[type] == 2;
3101       receiver = argument(0);  // type: oop
3102       base     = argument(1);  // type: oop
3103       offset   = argument(2);  // type: long
3104       oldval   = argument(4);  // type: oop, int, or long
3105       newval   = argument(two_slot_type ? 6 : 5);  // type: oop, int, or long
3106       break;
3107     }
3108     case LS_get_add:
3109     case LS_get_set: {
3110       receiver = argument(0);  // type: oop
3111       base     = argument(1);  // type: oop
3112       offset   = argument(2);  // type: long
3113       oldval   = nullptr;
3114       newval   = argument(4);  // type: oop, int, or long
3115       break;
3116     }
3117     default:
3118       ShouldNotReachHere();
3119   }
3120 
3121   // Build field offset expression.
3122   // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
3123   // to be plain byte offsets, which are also the same as those accepted
3124   // by oopDesc::field_addr.
3125   assert(Unsafe_field_offset_to_byte_offset(11) == 11, "fieldOffset must be byte-scaled");
3126   // 32-bit machines ignore the high half of long offsets
3127   offset = ConvL2X(offset);
3128   // Save state and restore on bailout
3129   SavedState old_state(this);
3130   Node* adr = make_unsafe_address(base, offset,type, false);
3131   const TypePtr *adr_type = _gvn.type(adr)->isa_ptr();
3132 
3133   Compile::AliasType* alias_type = C->alias_type(adr_type);
3134   BasicType bt = alias_type->basic_type();
3135   if (bt != T_ILLEGAL &&
3136       (is_reference_type(bt) != (type == T_OBJECT))) {
3137     // Don't intrinsify mismatched object accesses.
3138     return false;
3139   }
3140 
3141   old_state.discard();
3142 
3143   // For CAS, unlike inline_unsafe_access, there seems no point in
3144   // trying to refine types. Just use the coarse types here.
3145   assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
3146   const Type *value_type = Type::get_const_basic_type(type);
3147 
3148   switch (kind) {
3149     case LS_get_set:
3150     case LS_cmp_exchange: {
3151       if (type == T_OBJECT) {
3152         const TypeOopPtr* tjp = sharpen_unsafe_type(alias_type, adr_type);
3153         if (tjp != nullptr) {
3154           value_type = tjp;
3155         }
3156       }
3157       break;
3158     }
3159     case LS_cmp_swap:
3160     case LS_cmp_swap_weak:
3161     case LS_get_add:
3162       break;
3163     default:
3164       ShouldNotReachHere();
3165   }
3166 
3167   // Null check receiver.
3168   receiver = null_check(receiver);
3169   if (stopped()) {
3170     return true;
3171   }
3172 
3173   int alias_idx = C->get_alias_index(adr_type);
3174 
3175   if (is_reference_type(type)) {
3176     decorators |= IN_HEAP | ON_UNKNOWN_OOP_REF;
3177 
3178     if (oldval != nullptr && oldval->is_InlineType()) {
3179       // Re-execute the unsafe access if allocation triggers deoptimization.
3180       PreserveReexecuteState preexecs(this);
3181       jvms()->set_should_reexecute(true);
3182       oldval = oldval->as_InlineType()->buffer(this)->get_oop();
3183     }
3184     if (newval != nullptr && newval->is_InlineType()) {
3185       // Re-execute the unsafe access if allocation triggers deoptimization.
3186       PreserveReexecuteState preexecs(this);
3187       jvms()->set_should_reexecute(true);
3188       newval = newval->as_InlineType()->buffer(this)->get_oop();
3189     }
3190 
3191     // Transformation of a value which could be null pointer (CastPP #null)
3192     // could be delayed during Parse (for example, in adjust_map_after_if()).
3193     // Execute transformation here to avoid barrier generation in such case.
3194     if (_gvn.type(newval) == TypePtr::NULL_PTR)
3195       newval = _gvn.makecon(TypePtr::NULL_PTR);
3196 
3197     if (oldval != nullptr && _gvn.type(oldval) == TypePtr::NULL_PTR) {
3198       // Refine the value to a null constant, when it is known to be null
3199       oldval = _gvn.makecon(TypePtr::NULL_PTR);
3200     }
3201   }
3202 
3203   Node* result = nullptr;
3204   switch (kind) {
3205     case LS_cmp_exchange: {
3206       result = access_atomic_cmpxchg_val_at(base, adr, adr_type, alias_idx,
3207                                             oldval, newval, value_type, type, decorators);
3208       break;
3209     }
3210     case LS_cmp_swap_weak:
3211       decorators |= C2_WEAK_CMPXCHG;
3212     case LS_cmp_swap: {
3213       result = access_atomic_cmpxchg_bool_at(base, adr, adr_type, alias_idx,
3214                                              oldval, newval, value_type, type, decorators);
3215       break;
3216     }
3217     case LS_get_set: {
3218       result = access_atomic_xchg_at(base, adr, adr_type, alias_idx,
3219                                      newval, value_type, type, decorators);
3220       break;
3221     }
3222     case LS_get_add: {
3223       result = access_atomic_add_at(base, adr, adr_type, alias_idx,
3224                                     newval, value_type, type, decorators);
3225       break;
3226     }
3227     default:
3228       ShouldNotReachHere();
3229   }
3230 
3231   assert(type2size[result->bottom_type()->basic_type()] == type2size[rtype], "result type should match");
3232   set_result(result);
3233   return true;
3234 }
3235 
3236 bool LibraryCallKit::inline_unsafe_fence(vmIntrinsics::ID id) {
3237   // Regardless of form, don't allow previous ld/st to move down,
3238   // then issue acquire, release, or volatile mem_bar.
3239   insert_mem_bar(Op_MemBarCPUOrder);
3240   switch(id) {
3241     case vmIntrinsics::_loadFence:
3242       insert_mem_bar(Op_LoadFence);
3243       return true;
3244     case vmIntrinsics::_storeFence:
3245       insert_mem_bar(Op_StoreFence);
3246       return true;
3247     case vmIntrinsics::_storeStoreFence:
3248       insert_mem_bar(Op_StoreStoreFence);
3249       return true;
3250     case vmIntrinsics::_fullFence:
3251       insert_mem_bar(Op_MemBarVolatile);
3252       return true;
3253     default:
3254       fatal_unexpected_iid(id);
3255       return false;
3256   }
3257 }
3258 
3259 // private native int arrayInstanceBaseOffset0(Object[] array);
3260 bool LibraryCallKit::inline_arrayInstanceBaseOffset() {
3261   Node* array = argument(1);
3262   Node* klass_node = load_object_klass(array);
3263 
3264   jint  layout_con = Klass::_lh_neutral_value;
3265   Node* layout_val = get_layout_helper(klass_node, layout_con);
3266   int   layout_is_con = (layout_val == nullptr);
3267 
3268   Node* header_size = nullptr;
3269   if (layout_is_con) {
3270     int hsize = Klass::layout_helper_header_size(layout_con);
3271     header_size = intcon(hsize);
3272   } else {
3273     Node* hss = intcon(Klass::_lh_header_size_shift);
3274     Node* hsm = intcon(Klass::_lh_header_size_mask);
3275     header_size = _gvn.transform(new URShiftINode(layout_val, hss));
3276     header_size = _gvn.transform(new AndINode(header_size, hsm));
3277   }
3278   set_result(header_size);
3279   return true;
3280 }
3281 
3282 // private native int arrayInstanceIndexScale0(Object[] array);
3283 bool LibraryCallKit::inline_arrayInstanceIndexScale() {
3284   Node* array = argument(1);
3285   Node* klass_node = load_object_klass(array);
3286 
3287   jint  layout_con = Klass::_lh_neutral_value;
3288   Node* layout_val = get_layout_helper(klass_node, layout_con);
3289   int   layout_is_con = (layout_val == nullptr);
3290 
3291   Node* element_size = nullptr;
3292   if (layout_is_con) {
3293     int log_element_size  = Klass::layout_helper_log2_element_size(layout_con);
3294     int elem_size = 1 << log_element_size;
3295     element_size = intcon(elem_size);
3296   } else {
3297     Node* ess = intcon(Klass::_lh_log2_element_size_shift);
3298     Node* esm = intcon(Klass::_lh_log2_element_size_mask);
3299     Node* log_element_size = _gvn.transform(new URShiftINode(layout_val, ess));
3300     log_element_size = _gvn.transform(new AndINode(log_element_size, esm));
3301     element_size = _gvn.transform(new LShiftINode(intcon(1), log_element_size));
3302   }
3303   set_result(element_size);
3304   return true;
3305 }
3306 
3307 // private native int arrayLayout0(Object[] array);
3308 bool LibraryCallKit::inline_arrayLayout() {
3309   RegionNode* region = new RegionNode(2);
3310   Node* phi = new PhiNode(region, TypeInt::POS);
3311 
3312   Node* array = argument(1);
3313   Node* klass_node = load_object_klass(array);
3314   generate_refArray_guard(klass_node, region);
3315   if (region->req() == 3) {
3316     phi->add_req(intcon((jint)LayoutKind::REFERENCE));
3317   }
3318 
3319   int layout_kind_offset = in_bytes(FlatArrayKlass::layout_kind_offset());
3320   Node* layout_kind_addr = basic_plus_adr(klass_node, layout_kind_offset);
3321   Node* layout_kind = make_load(nullptr, layout_kind_addr, TypeInt::POS, T_INT, MemNode::unordered);
3322 
3323   region->init_req(1, control());
3324   phi->init_req(1, layout_kind);
3325 
3326   set_control(_gvn.transform(region));
3327   set_result(_gvn.transform(phi));
3328   return true;
3329 }
3330 
3331 // private native int[] getFieldMap0(Class <?> c);
3332 //   int offset = c._klass._acmp_maps_offset;
3333 //   return (int[])c.obj_field(offset);
3334 bool LibraryCallKit::inline_getFieldMap() {
3335   if (!UseAltSubstitutabilityMethod) {
3336     return false;
3337   }
3338 
3339   Node* mirror = argument(1);
3340   Node* klass = load_klass_from_mirror(mirror, false, nullptr, 0);
3341 
3342   int field_map_offset_offset = in_bytes(InstanceKlass::acmp_maps_offset_offset());
3343   Node* field_map_offset_addr = basic_plus_adr(klass, field_map_offset_offset);
3344   Node* field_map_offset = make_load(nullptr, field_map_offset_addr, TypeInt::INT, T_INT, MemNode::unordered);
3345   field_map_offset = _gvn.transform(ConvI2L(field_map_offset));
3346 
3347   Node* map_addr = basic_plus_adr(mirror, field_map_offset);
3348   const TypeAryPtr* val_type = TypeAryPtr::INTS->cast_to_ptr_type(TypePtr::NotNull)->with_offset(0);
3349   // TODO 8350865 Remove this
3350   val_type = val_type->cast_to_not_flat(true)->cast_to_not_null_free(true);
3351   Node* map = access_load_at(mirror, map_addr, TypeAryPtr::INTS, val_type, T_ARRAY, IN_HEAP | MO_UNORDERED);
3352 
3353   set_result(map);
3354   return true;
3355 }
3356 
3357 bool LibraryCallKit::inline_onspinwait() {
3358   insert_mem_bar(Op_OnSpinWait);
3359   return true;
3360 }
3361 
3362 bool LibraryCallKit::klass_needs_init_guard(Node* kls) {
3363   if (!kls->is_Con()) {
3364     return true;
3365   }
3366   const TypeInstKlassPtr* klsptr = kls->bottom_type()->isa_instklassptr();
3367   if (klsptr == nullptr) {
3368     return true;
3369   }
3370   ciInstanceKlass* ik = klsptr->instance_klass();
3371   // don't need a guard for a klass that is already initialized
3372   return !ik->is_initialized();
3373 }
3374 
3375 //----------------------------inline_unsafe_writeback0-------------------------
3376 // public native void Unsafe.writeback0(long address)
3377 bool LibraryCallKit::inline_unsafe_writeback0() {
3378   if (!Matcher::has_match_rule(Op_CacheWB)) {
3379     return false;
3380   }
3381 #ifndef PRODUCT
3382   assert(Matcher::has_match_rule(Op_CacheWBPreSync), "found match rule for CacheWB but not CacheWBPreSync");
3383   assert(Matcher::has_match_rule(Op_CacheWBPostSync), "found match rule for CacheWB but not CacheWBPostSync");
3384   ciSignature* sig = callee()->signature();
3385   assert(sig->type_at(0)->basic_type() == T_LONG, "Unsafe_writeback0 address is long!");
3386 #endif
3387   null_check_receiver();  // null-check, then ignore
3388   Node *addr = argument(1);
3389   addr = new CastX2PNode(addr);
3390   addr = _gvn.transform(addr);
3391   Node *flush = new CacheWBNode(control(), memory(TypeRawPtr::BOTTOM), addr);
3392   flush = _gvn.transform(flush);
3393   set_memory(flush, TypeRawPtr::BOTTOM);
3394   return true;
3395 }
3396 
3397 //----------------------------inline_unsafe_writeback0-------------------------
3398 // public native void Unsafe.writeback0(long address)
3399 bool LibraryCallKit::inline_unsafe_writebackSync0(bool is_pre) {
3400   if (is_pre && !Matcher::has_match_rule(Op_CacheWBPreSync)) {
3401     return false;
3402   }
3403   if (!is_pre && !Matcher::has_match_rule(Op_CacheWBPostSync)) {
3404     return false;
3405   }
3406 #ifndef PRODUCT
3407   assert(Matcher::has_match_rule(Op_CacheWB),
3408          (is_pre ? "found match rule for CacheWBPreSync but not CacheWB"
3409                 : "found match rule for CacheWBPostSync but not CacheWB"));
3410 
3411 #endif
3412   null_check_receiver();  // null-check, then ignore
3413   Node *sync;
3414   if (is_pre) {
3415     sync = new CacheWBPreSyncNode(control(), memory(TypeRawPtr::BOTTOM));
3416   } else {
3417     sync = new CacheWBPostSyncNode(control(), memory(TypeRawPtr::BOTTOM));
3418   }
3419   sync = _gvn.transform(sync);
3420   set_memory(sync, TypeRawPtr::BOTTOM);
3421   return true;
3422 }
3423 
3424 //----------------------------inline_unsafe_allocate---------------------------
3425 // public native Object Unsafe.allocateInstance(Class<?> cls);
3426 bool LibraryCallKit::inline_unsafe_allocate() {
3427 
3428 #if INCLUDE_JVMTI
3429   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
3430     return false;
3431   }
3432 #endif //INCLUDE_JVMTI
3433 
3434   if (callee()->is_static())  return false;  // caller must have the capability!
3435 
3436   null_check_receiver();  // null-check, then ignore
3437   Node* cls = null_check(argument(1));
3438   if (stopped())  return true;
3439 
3440   Node* kls = load_klass_from_mirror(cls, false, nullptr, 0);
3441   kls = null_check(kls);
3442   if (stopped())  return true;  // argument was like int.class
3443 
3444 #if INCLUDE_JVMTI
3445     // Don't try to access new allocated obj in the intrinsic.
3446     // It causes perfomance issues even when jvmti event VmObjectAlloc is disabled.
3447     // Deoptimize and allocate in interpreter instead.
3448     Node* addr = makecon(TypeRawPtr::make((address) &JvmtiExport::_should_notify_object_alloc));
3449     Node* should_post_vm_object_alloc = make_load(this->control(), addr, TypeInt::INT, T_INT, MemNode::unordered);
3450     Node* chk = _gvn.transform(new CmpINode(should_post_vm_object_alloc, intcon(0)));
3451     Node* tst = _gvn.transform(new BoolNode(chk, BoolTest::eq));
3452     {
3453       BuildCutout unless(this, tst, PROB_MAX);
3454       uncommon_trap(Deoptimization::Reason_intrinsic,
3455                     Deoptimization::Action_make_not_entrant);
3456     }
3457     if (stopped()) {
3458       return true;
3459     }
3460 #endif //INCLUDE_JVMTI
3461 
3462   Node* test = nullptr;
3463   if (LibraryCallKit::klass_needs_init_guard(kls)) {
3464     // Note:  The argument might still be an illegal value like
3465     // Serializable.class or Object[].class.   The runtime will handle it.
3466     // But we must make an explicit check for initialization.
3467     Node* insp = basic_plus_adr(kls, in_bytes(InstanceKlass::init_state_offset()));
3468     // Use T_BOOLEAN for InstanceKlass::_init_state so the compiler
3469     // can generate code to load it as unsigned byte.
3470     Node* inst = make_load(nullptr, insp, TypeInt::UBYTE, T_BOOLEAN, MemNode::acquire);
3471     Node* bits = intcon(InstanceKlass::fully_initialized);
3472     test = _gvn.transform(new SubINode(inst, bits));
3473     // The 'test' is non-zero if we need to take a slow path.
3474   }
3475   Node* obj = nullptr;
3476   const TypeInstKlassPtr* tkls = _gvn.type(kls)->isa_instklassptr();
3477   if (tkls != nullptr && tkls->instance_klass()->is_inlinetype()) {
3478     obj = InlineTypeNode::make_all_zero(_gvn, tkls->instance_klass()->as_inline_klass())->buffer(this);
3479   } else {
3480     obj = new_instance(kls, test);
3481   }
3482   set_result(obj);
3483   return true;
3484 }
3485 
3486 //------------------------inline_native_time_funcs--------------
3487 // inline code for System.currentTimeMillis() and System.nanoTime()
3488 // these have the same type and signature
3489 bool LibraryCallKit::inline_native_time_funcs(address funcAddr, const char* funcName) {
3490   const TypeFunc* tf = OptoRuntime::void_long_Type();
3491   const TypePtr* no_memory_effects = nullptr;
3492   Node* time = make_runtime_call(RC_LEAF, tf, funcAddr, funcName, no_memory_effects);
3493   Node* value = _gvn.transform(new ProjNode(time, TypeFunc::Parms+0));
3494 #ifdef ASSERT
3495   Node* value_top = _gvn.transform(new ProjNode(time, TypeFunc::Parms+1));
3496   assert(value_top == top(), "second value must be top");
3497 #endif
3498   set_result(value);
3499   return true;
3500 }
3501 
3502 //--------------------inline_native_vthread_start_transition--------------------
3503 // inline void startTransition(boolean is_mount);
3504 // inline void startFinalTransition();
3505 // Pseudocode of implementation:
3506 //
3507 // java_lang_Thread::set_is_in_vthread_transition(vthread, true);
3508 // carrier->set_is_in_vthread_transition(true);
3509 // OrderAccess::storeload();
3510 // int disable_requests = java_lang_Thread::vthread_transition_disable_count(vthread)
3511 //                        + global_vthread_transition_disable_count();
3512 // if (disable_requests > 0) {
3513 //   slow path: runtime call
3514 // }
3515 bool LibraryCallKit::inline_native_vthread_start_transition(address funcAddr, const char* funcName, bool is_final_transition) {
3516   Node* vt_oop = _gvn.transform(must_be_not_null(argument(0), true)); // VirtualThread this argument
3517   IdealKit ideal(this);
3518 
3519   Node* thread = ideal.thread();
3520   Node* jt_addr = basic_plus_adr(thread, in_bytes(JavaThread::is_in_vthread_transition_offset()));
3521   Node* vt_addr = basic_plus_adr(vt_oop, java_lang_Thread::is_in_vthread_transition_offset());
3522   access_store_at(nullptr, jt_addr, _gvn.type(jt_addr)->is_ptr(), ideal.ConI(1), TypeInt::BOOL, T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
3523   access_store_at(nullptr, vt_addr, _gvn.type(vt_addr)->is_ptr(), ideal.ConI(1), TypeInt::BOOL, T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
3524   insert_mem_bar(Op_MemBarVolatile);
3525   ideal.sync_kit(this);
3526 
3527   Node* global_disable_addr = makecon(TypeRawPtr::make((address)MountUnmountDisabler::global_vthread_transition_disable_count_address()));
3528   Node* global_disable = ideal.load(ideal.ctrl(), global_disable_addr, TypeInt::INT, T_INT, Compile::AliasIdxRaw, true /*require_atomic_access*/);
3529   Node* vt_disable_addr = basic_plus_adr(vt_oop, java_lang_Thread::vthread_transition_disable_count_offset());
3530   Node* vt_disable = ideal.load(ideal.ctrl(), vt_disable_addr, TypeInt::INT, T_INT, Compile::AliasIdxRaw, true /*require_atomic_access*/);
3531   Node* disabled = _gvn.transform(new AddINode(global_disable, vt_disable));
3532 
3533   ideal.if_then(disabled, BoolTest::ne, ideal.ConI(0)); {
3534     sync_kit(ideal);
3535     Node* is_mount = is_final_transition ? ideal.ConI(0) : _gvn.transform(argument(1));
3536     const TypeFunc* tf = OptoRuntime::vthread_transition_Type();
3537     make_runtime_call(RC_NO_LEAF, tf, funcAddr, funcName, TypePtr::BOTTOM, vt_oop, is_mount);
3538     ideal.sync_kit(this);
3539   }
3540   ideal.end_if();
3541 
3542   final_sync(ideal);
3543   return true;
3544 }
3545 
3546 bool LibraryCallKit::inline_native_vthread_end_transition(address funcAddr, const char* funcName, bool is_first_transition) {
3547   Node* vt_oop = _gvn.transform(must_be_not_null(argument(0), true)); // VirtualThread this argument
3548   IdealKit ideal(this);
3549 
3550   Node* _notify_jvmti_addr = makecon(TypeRawPtr::make((address)MountUnmountDisabler::notify_jvmti_events_address()));
3551   Node* _notify_jvmti = ideal.load(ideal.ctrl(), _notify_jvmti_addr, TypeInt::BOOL, T_BOOLEAN, Compile::AliasIdxRaw);
3552 
3553   ideal.if_then(_notify_jvmti, BoolTest::eq, ideal.ConI(1)); {
3554     sync_kit(ideal);
3555     Node* is_mount = is_first_transition ? ideal.ConI(1) : _gvn.transform(argument(1));
3556     const TypeFunc* tf = OptoRuntime::vthread_transition_Type();
3557     make_runtime_call(RC_NO_LEAF, tf, funcAddr, funcName, TypePtr::BOTTOM, vt_oop, is_mount);
3558     ideal.sync_kit(this);
3559   } ideal.else_(); {
3560     Node* thread = ideal.thread();
3561     Node* jt_addr = basic_plus_adr(thread, in_bytes(JavaThread::is_in_vthread_transition_offset()));
3562     Node* vt_addr = basic_plus_adr(vt_oop, java_lang_Thread::is_in_vthread_transition_offset());
3563 
3564     sync_kit(ideal);
3565     access_store_at(nullptr, jt_addr, _gvn.type(jt_addr)->is_ptr(), ideal.ConI(0), TypeInt::BOOL, T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
3566     access_store_at(nullptr, vt_addr, _gvn.type(vt_addr)->is_ptr(), ideal.ConI(0), TypeInt::BOOL, T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
3567     ideal.sync_kit(this);
3568   } ideal.end_if();
3569 
3570   final_sync(ideal);
3571   return true;
3572 }
3573 
3574 #if INCLUDE_JVMTI
3575 
3576 // Always update the is_disable_suspend bit.
3577 bool LibraryCallKit::inline_native_notify_jvmti_sync() {
3578   if (!DoJVMTIVirtualThreadTransitions) {
3579     return true;
3580   }
3581   IdealKit ideal(this);
3582 
3583   {
3584     // unconditionally update the is_disable_suspend bit in current JavaThread
3585     Node* thread = ideal.thread();
3586     Node* arg = _gvn.transform(argument(0)); // argument for notification
3587     Node* addr = basic_plus_adr(thread, in_bytes(JavaThread::is_disable_suspend_offset()));
3588     const TypePtr *addr_type = _gvn.type(addr)->isa_ptr();
3589 
3590     sync_kit(ideal);
3591     access_store_at(nullptr, addr, addr_type, arg, _gvn.type(arg), T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
3592     ideal.sync_kit(this);
3593   }
3594   final_sync(ideal);
3595 
3596   return true;
3597 }
3598 
3599 #endif // INCLUDE_JVMTI
3600 
3601 #ifdef JFR_HAVE_INTRINSICS
3602 
3603 /**
3604  * if oop->klass != null
3605  *   // normal class
3606  *   epoch = _epoch_state ? 2 : 1
3607  *   if oop->klass->trace_id & ((epoch << META_SHIFT) | epoch)) != epoch {
3608  *     ... // enter slow path when the klass is first recorded or the epoch of JFR shifts
3609  *   }
3610  *   id = oop->klass->trace_id >> TRACE_ID_SHIFT // normal class path
3611  * else
3612  *   // primitive class
3613  *   if oop->array_klass != null
3614  *     id = (oop->array_klass->trace_id >> TRACE_ID_SHIFT) + 1 // primitive class path
3615  *   else
3616  *     id = LAST_TYPE_ID + 1 // void class path
3617  *   if (!signaled)
3618  *     signaled = true
3619  */
3620 bool LibraryCallKit::inline_native_classID() {
3621   Node* cls = argument(0);
3622 
3623   IdealKit ideal(this);
3624 #define __ ideal.
3625   IdealVariable result(ideal); __ declarations_done();
3626   Node* kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(),
3627                                                  basic_plus_adr(cls, java_lang_Class::klass_offset()),
3628                                                  TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
3629 
3630 
3631   __ if_then(kls, BoolTest::ne, null()); {
3632     Node* kls_trace_id_addr = basic_plus_adr(kls, in_bytes(KLASS_TRACE_ID_OFFSET));
3633     Node* kls_trace_id_raw = ideal.load(ideal.ctrl(), kls_trace_id_addr,TypeLong::LONG, T_LONG, Compile::AliasIdxRaw);
3634 
3635     Node* epoch_address = makecon(TypeRawPtr::make(JfrIntrinsicSupport::epoch_address()));
3636     Node* epoch = ideal.load(ideal.ctrl(), epoch_address, TypeInt::BOOL, T_BOOLEAN, Compile::AliasIdxRaw);
3637     epoch = _gvn.transform(new LShiftLNode(longcon(1), epoch));
3638     Node* mask = _gvn.transform(new LShiftLNode(epoch, intcon(META_SHIFT)));
3639     mask = _gvn.transform(new OrLNode(mask, epoch));
3640     Node* kls_trace_id_raw_and_mask = _gvn.transform(new AndLNode(kls_trace_id_raw, mask));
3641 
3642     float unlikely  = PROB_UNLIKELY(0.999);
3643     __ if_then(kls_trace_id_raw_and_mask, BoolTest::ne, epoch, unlikely); {
3644       sync_kit(ideal);
3645       make_runtime_call(RC_LEAF,
3646                         OptoRuntime::class_id_load_barrier_Type(),
3647                         CAST_FROM_FN_PTR(address, JfrIntrinsicSupport::load_barrier),
3648                         "class id load barrier",
3649                         TypePtr::BOTTOM,
3650                         kls);
3651       ideal.sync_kit(this);
3652     } __ end_if();
3653 
3654     ideal.set(result,  _gvn.transform(new URShiftLNode(kls_trace_id_raw, ideal.ConI(TRACE_ID_SHIFT))));
3655   } __ else_(); {
3656     Node* array_kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(),
3657                                                    basic_plus_adr(cls, java_lang_Class::array_klass_offset()),
3658                                                    TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
3659     __ if_then(array_kls, BoolTest::ne, null()); {
3660       Node* array_kls_trace_id_addr = basic_plus_adr(array_kls, in_bytes(KLASS_TRACE_ID_OFFSET));
3661       Node* array_kls_trace_id_raw = ideal.load(ideal.ctrl(), array_kls_trace_id_addr, TypeLong::LONG, T_LONG, Compile::AliasIdxRaw);
3662       Node* array_kls_trace_id = _gvn.transform(new URShiftLNode(array_kls_trace_id_raw, ideal.ConI(TRACE_ID_SHIFT)));
3663       ideal.set(result, _gvn.transform(new AddLNode(array_kls_trace_id, longcon(1))));
3664     } __ else_(); {
3665       // void class case
3666       ideal.set(result, _gvn.transform(longcon(LAST_TYPE_ID + 1)));
3667     } __ end_if();
3668 
3669     Node* signaled_flag_address = makecon(TypeRawPtr::make(JfrIntrinsicSupport::signal_address()));
3670     Node* signaled = ideal.load(ideal.ctrl(), signaled_flag_address, TypeInt::BOOL, T_BOOLEAN, Compile::AliasIdxRaw, true, MemNode::acquire);
3671     __ if_then(signaled, BoolTest::ne, ideal.ConI(1)); {
3672       ideal.store(ideal.ctrl(), signaled_flag_address, ideal.ConI(1), T_BOOLEAN, Compile::AliasIdxRaw, MemNode::release, true);
3673     } __ end_if();
3674   } __ end_if();
3675 
3676   final_sync(ideal);
3677   set_result(ideal.value(result));
3678 #undef __
3679   return true;
3680 }
3681 
3682 //------------------------inline_native_jvm_commit------------------
3683 bool LibraryCallKit::inline_native_jvm_commit() {
3684   enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
3685 
3686   // Save input memory and i_o state.
3687   Node* input_memory_state = reset_memory();
3688   set_all_memory(input_memory_state);
3689   Node* input_io_state = i_o();
3690 
3691   // TLS.
3692   Node* tls_ptr = _gvn.transform(new ThreadLocalNode());
3693   // Jfr java buffer.
3694   Node* java_buffer_offset = _gvn.transform(new AddPNode(top(), tls_ptr, _gvn.transform(MakeConX(in_bytes(JAVA_BUFFER_OFFSET_JFR)))));
3695   Node* java_buffer = _gvn.transform(new LoadPNode(control(), input_memory_state, java_buffer_offset, TypePtr::BOTTOM, TypeRawPtr::NOTNULL, MemNode::unordered));
3696   Node* java_buffer_pos_offset = _gvn.transform(new AddPNode(top(), java_buffer, _gvn.transform(MakeConX(in_bytes(JFR_BUFFER_POS_OFFSET)))));
3697 
3698   // Load the current value of the notified field in the JfrThreadLocal.
3699   Node* notified_offset = basic_plus_adr(top(), tls_ptr, in_bytes(NOTIFY_OFFSET_JFR));
3700   Node* notified = make_load(control(), notified_offset, TypeInt::BOOL, T_BOOLEAN, MemNode::unordered);
3701 
3702   // Test for notification.
3703   Node* notified_cmp = _gvn.transform(new CmpINode(notified, _gvn.intcon(1)));
3704   Node* test_notified = _gvn.transform(new BoolNode(notified_cmp, BoolTest::eq));
3705   IfNode* iff_notified = create_and_map_if(control(), test_notified, PROB_MIN, COUNT_UNKNOWN);
3706 
3707   // True branch, is notified.
3708   Node* is_notified = _gvn.transform(new IfTrueNode(iff_notified));
3709   set_control(is_notified);
3710 
3711   // Reset notified state.
3712   store_to_memory(control(), notified_offset, _gvn.intcon(0), T_BOOLEAN, MemNode::unordered);
3713   Node* notified_reset_memory = reset_memory();
3714 
3715   // 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.
3716   Node* current_pos_X = _gvn.transform(new LoadXNode(control(), input_memory_state, java_buffer_pos_offset, TypeRawPtr::NOTNULL, TypeX_X, MemNode::unordered));
3717   // Convert the machine-word to a long.
3718   Node* current_pos = _gvn.transform(ConvX2L(current_pos_X));
3719 
3720   // False branch, not notified.
3721   Node* not_notified = _gvn.transform(new IfFalseNode(iff_notified));
3722   set_control(not_notified);
3723   set_all_memory(input_memory_state);
3724 
3725   // Arg is the next position as a long.
3726   Node* arg = argument(0);
3727   // Convert long to machine-word.
3728   Node* next_pos_X = _gvn.transform(ConvL2X(arg));
3729 
3730   // Store the next_position to the underlying jfr java buffer.
3731   store_to_memory(control(), java_buffer_pos_offset, next_pos_X, LP64_ONLY(T_LONG) NOT_LP64(T_INT), MemNode::release);
3732 
3733   Node* commit_memory = reset_memory();
3734   set_all_memory(commit_memory);
3735 
3736   // 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.
3737   Node* java_buffer_flags_offset = _gvn.transform(new AddPNode(top(), java_buffer, _gvn.transform(MakeConX(in_bytes(JFR_BUFFER_FLAGS_OFFSET)))));
3738   Node* flags = make_load(control(), java_buffer_flags_offset, TypeInt::UBYTE, T_BYTE, MemNode::unordered);
3739   Node* lease_constant = _gvn.transform(_gvn.intcon(4));
3740 
3741   // And flags with lease constant.
3742   Node* lease = _gvn.transform(new AndINode(flags, lease_constant));
3743 
3744   // Branch on lease to conditionalize returning the leased java buffer.
3745   Node* lease_cmp = _gvn.transform(new CmpINode(lease, lease_constant));
3746   Node* test_lease = _gvn.transform(new BoolNode(lease_cmp, BoolTest::eq));
3747   IfNode* iff_lease = create_and_map_if(control(), test_lease, PROB_MIN, COUNT_UNKNOWN);
3748 
3749   // False branch, not a lease.
3750   Node* not_lease = _gvn.transform(new IfFalseNode(iff_lease));
3751 
3752   // True branch, is lease.
3753   Node* is_lease = _gvn.transform(new IfTrueNode(iff_lease));
3754   set_control(is_lease);
3755 
3756   // Make a runtime call, which can safepoint, to return the leased buffer. This updates both the JfrThreadLocal and the Java event writer oop.
3757   Node* call_return_lease = make_runtime_call(RC_NO_LEAF,
3758                                               OptoRuntime::void_void_Type(),
3759                                               SharedRuntime::jfr_return_lease(),
3760                                               "return_lease", TypePtr::BOTTOM);
3761   Node* call_return_lease_control = _gvn.transform(new ProjNode(call_return_lease, TypeFunc::Control));
3762 
3763   RegionNode* lease_compare_rgn = new RegionNode(PATH_LIMIT);
3764   record_for_igvn(lease_compare_rgn);
3765   PhiNode* lease_compare_mem = new PhiNode(lease_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3766   record_for_igvn(lease_compare_mem);
3767   PhiNode* lease_compare_io = new PhiNode(lease_compare_rgn, Type::ABIO);
3768   record_for_igvn(lease_compare_io);
3769   PhiNode* lease_result_value = new PhiNode(lease_compare_rgn, TypeLong::LONG);
3770   record_for_igvn(lease_result_value);
3771 
3772   // Update control and phi nodes.
3773   lease_compare_rgn->init_req(_true_path, call_return_lease_control);
3774   lease_compare_rgn->init_req(_false_path, not_lease);
3775 
3776   lease_compare_mem->init_req(_true_path, _gvn.transform(reset_memory()));
3777   lease_compare_mem->init_req(_false_path, commit_memory);
3778 
3779   lease_compare_io->init_req(_true_path, i_o());
3780   lease_compare_io->init_req(_false_path, input_io_state);
3781 
3782   lease_result_value->init_req(_true_path, _gvn.longcon(0)); // if the lease was returned, return 0L.
3783   lease_result_value->init_req(_false_path, arg); // if not lease, return new updated position.
3784 
3785   RegionNode* result_rgn = new RegionNode(PATH_LIMIT);
3786   PhiNode* result_mem = new PhiNode(result_rgn, Type::MEMORY, TypePtr::BOTTOM);
3787   PhiNode* result_io = new PhiNode(result_rgn, Type::ABIO);
3788   PhiNode* result_value = new PhiNode(result_rgn, TypeLong::LONG);
3789 
3790   // Update control and phi nodes.
3791   result_rgn->init_req(_true_path, is_notified);
3792   result_rgn->init_req(_false_path, _gvn.transform(lease_compare_rgn));
3793 
3794   result_mem->init_req(_true_path, notified_reset_memory);
3795   result_mem->init_req(_false_path, _gvn.transform(lease_compare_mem));
3796 
3797   result_io->init_req(_true_path, input_io_state);
3798   result_io->init_req(_false_path, _gvn.transform(lease_compare_io));
3799 
3800   result_value->init_req(_true_path, current_pos);
3801   result_value->init_req(_false_path, _gvn.transform(lease_result_value));
3802 
3803   // Set output state.
3804   set_control(_gvn.transform(result_rgn));
3805   set_all_memory(_gvn.transform(result_mem));
3806   set_i_o(_gvn.transform(result_io));
3807   set_result(result_rgn, result_value);
3808   return true;
3809 }
3810 
3811 /*
3812  * The intrinsic is a model of this pseudo-code:
3813  *
3814  * JfrThreadLocal* const tl = Thread::jfr_thread_local()
3815  * jobject h_event_writer = tl->java_event_writer();
3816  * if (h_event_writer == nullptr) {
3817  *   return nullptr;
3818  * }
3819  * oop threadObj = Thread::threadObj();
3820  * oop vthread = java_lang_Thread::vthread(threadObj);
3821  * traceid tid;
3822  * bool pinVirtualThread;
3823  * bool excluded;
3824  * if (vthread != threadObj) {  // i.e. current thread is virtual
3825  *   tid = java_lang_Thread::tid(vthread);
3826  *   u2 vthread_epoch_raw = java_lang_Thread::jfr_epoch(vthread);
3827  *   pinVirtualThread = VMContinuations;
3828  *   excluded = vthread_epoch_raw & excluded_mask;
3829  *   if (!excluded) {
3830  *     traceid current_epoch = JfrTraceIdEpoch::current_generation();
3831  *     u2 vthread_epoch = vthread_epoch_raw & epoch_mask;
3832  *     if (vthread_epoch != current_epoch) {
3833  *       write_checkpoint();
3834  *     }
3835  *   }
3836  * } else {
3837  *   tid = java_lang_Thread::tid(threadObj);
3838  *   u2 thread_epoch_raw = java_lang_Thread::jfr_epoch(threadObj);
3839  *   pinVirtualThread = false;
3840  *   excluded = thread_epoch_raw & excluded_mask;
3841  * }
3842  * oop event_writer = JNIHandles::resolve_non_null(h_event_writer);
3843  * traceid tid_in_event_writer = getField(event_writer, "threadID");
3844  * if (tid_in_event_writer != tid) {
3845  *   setField(event_writer, "pinVirtualThread", pinVirtualThread);
3846  *   setField(event_writer, "excluded", excluded);
3847  *   setField(event_writer, "threadID", tid);
3848  * }
3849  * return event_writer
3850  */
3851 bool LibraryCallKit::inline_native_getEventWriter() {
3852   enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
3853 
3854   // Save input memory and i_o state.
3855   Node* input_memory_state = reset_memory();
3856   set_all_memory(input_memory_state);
3857   Node* input_io_state = i_o();
3858 
3859   // The most significant bit of the u2 is used to denote thread exclusion
3860   Node* excluded_shift = _gvn.intcon(15);
3861   Node* excluded_mask = _gvn.intcon(1 << 15);
3862   // The epoch generation is the range [1-32767]
3863   Node* epoch_mask = _gvn.intcon(32767);
3864 
3865   // TLS
3866   Node* tls_ptr = _gvn.transform(new ThreadLocalNode());
3867 
3868   // Load the address of java event writer jobject handle from the jfr_thread_local structure.
3869   Node* jobj_ptr = basic_plus_adr(top(), tls_ptr, in_bytes(THREAD_LOCAL_WRITER_OFFSET_JFR));
3870 
3871   // Load the eventwriter jobject handle.
3872   Node* jobj = make_load(control(), jobj_ptr, TypeRawPtr::BOTTOM, T_ADDRESS, MemNode::unordered);
3873 
3874   // Null check the jobject handle.
3875   Node* jobj_cmp_null = _gvn.transform(new CmpPNode(jobj, null()));
3876   Node* test_jobj_not_equal_null = _gvn.transform(new BoolNode(jobj_cmp_null, BoolTest::ne));
3877   IfNode* iff_jobj_not_equal_null = create_and_map_if(control(), test_jobj_not_equal_null, PROB_MAX, COUNT_UNKNOWN);
3878 
3879   // False path, jobj is null.
3880   Node* jobj_is_null = _gvn.transform(new IfFalseNode(iff_jobj_not_equal_null));
3881 
3882   // True path, jobj is not null.
3883   Node* jobj_is_not_null = _gvn.transform(new IfTrueNode(iff_jobj_not_equal_null));
3884 
3885   set_control(jobj_is_not_null);
3886 
3887   // Load the threadObj for the CarrierThread.
3888   Node* threadObj = generate_current_thread(tls_ptr);
3889 
3890   // Load the vthread.
3891   Node* vthread = generate_virtual_thread(tls_ptr);
3892 
3893   // If vthread != threadObj, this is a virtual thread.
3894   Node* vthread_cmp_threadObj = _gvn.transform(new CmpPNode(vthread, threadObj));
3895   Node* test_vthread_not_equal_threadObj = _gvn.transform(new BoolNode(vthread_cmp_threadObj, BoolTest::ne));
3896   IfNode* iff_vthread_not_equal_threadObj =
3897     create_and_map_if(jobj_is_not_null, test_vthread_not_equal_threadObj, PROB_FAIR, COUNT_UNKNOWN);
3898 
3899   // False branch, fallback to threadObj.
3900   Node* vthread_equal_threadObj = _gvn.transform(new IfFalseNode(iff_vthread_not_equal_threadObj));
3901   set_control(vthread_equal_threadObj);
3902 
3903   // Load the tid field from the vthread object.
3904   Node* thread_obj_tid = load_field_from_object(threadObj, "tid", "J");
3905 
3906   // Load the raw epoch value from the threadObj.
3907   Node* threadObj_epoch_offset = basic_plus_adr(threadObj, java_lang_Thread::jfr_epoch_offset());
3908   Node* threadObj_epoch_raw = access_load_at(threadObj, threadObj_epoch_offset,
3909                                              _gvn.type(threadObj_epoch_offset)->isa_ptr(),
3910                                              TypeInt::CHAR, T_CHAR,
3911                                              IN_HEAP | MO_UNORDERED | C2_MISMATCHED | C2_CONTROL_DEPENDENT_LOAD);
3912 
3913   // Mask off the excluded information from the epoch.
3914   Node * threadObj_is_excluded = _gvn.transform(new AndINode(threadObj_epoch_raw, excluded_mask));
3915 
3916   // True branch, this is a virtual thread.
3917   Node* vthread_not_equal_threadObj = _gvn.transform(new IfTrueNode(iff_vthread_not_equal_threadObj));
3918   set_control(vthread_not_equal_threadObj);
3919 
3920   // Load the tid field from the vthread object.
3921   Node* vthread_tid = load_field_from_object(vthread, "tid", "J");
3922 
3923   // Continuation support determines if a virtual thread should be pinned.
3924   Node* global_addr = makecon(TypeRawPtr::make((address)&VMContinuations));
3925   Node* continuation_support = make_load(control(), global_addr, TypeInt::BOOL, T_BOOLEAN, MemNode::unordered);
3926 
3927   // Load the raw epoch value from the vthread.
3928   Node* vthread_epoch_offset = basic_plus_adr(vthread, java_lang_Thread::jfr_epoch_offset());
3929   Node* vthread_epoch_raw = access_load_at(vthread, vthread_epoch_offset, _gvn.type(vthread_epoch_offset)->is_ptr(),
3930                                            TypeInt::CHAR, T_CHAR,
3931                                            IN_HEAP | MO_UNORDERED | C2_MISMATCHED | C2_CONTROL_DEPENDENT_LOAD);
3932 
3933   // Mask off the excluded information from the epoch.
3934   Node * vthread_is_excluded = _gvn.transform(new AndINode(vthread_epoch_raw, _gvn.transform(excluded_mask)));
3935 
3936   // Branch on excluded to conditionalize updating the epoch for the virtual thread.
3937   Node* is_excluded_cmp = _gvn.transform(new CmpINode(vthread_is_excluded, _gvn.transform(excluded_mask)));
3938   Node* test_not_excluded = _gvn.transform(new BoolNode(is_excluded_cmp, BoolTest::ne));
3939   IfNode* iff_not_excluded = create_and_map_if(control(), test_not_excluded, PROB_MAX, COUNT_UNKNOWN);
3940 
3941   // False branch, vthread is excluded, no need to write epoch info.
3942   Node* excluded = _gvn.transform(new IfFalseNode(iff_not_excluded));
3943 
3944   // True branch, vthread is included, update epoch info.
3945   Node* included = _gvn.transform(new IfTrueNode(iff_not_excluded));
3946   set_control(included);
3947 
3948   // Get epoch value.
3949   Node* epoch = _gvn.transform(new AndINode(vthread_epoch_raw, _gvn.transform(epoch_mask)));
3950 
3951   // Load the current epoch generation. The value is unsigned 16-bit, so we type it as T_CHAR.
3952   Node* epoch_generation_address = makecon(TypeRawPtr::make(JfrIntrinsicSupport::epoch_generation_address()));
3953   Node* current_epoch_generation = make_load(control(), epoch_generation_address, TypeInt::CHAR, T_CHAR, MemNode::unordered);
3954 
3955   // Compare the epoch in the vthread to the current epoch generation.
3956   Node* const epoch_cmp = _gvn.transform(new CmpUNode(current_epoch_generation, epoch));
3957   Node* test_epoch_not_equal = _gvn.transform(new BoolNode(epoch_cmp, BoolTest::ne));
3958   IfNode* iff_epoch_not_equal = create_and_map_if(control(), test_epoch_not_equal, PROB_FAIR, COUNT_UNKNOWN);
3959 
3960   // False path, epoch is equal, checkpoint information is valid.
3961   Node* epoch_is_equal = _gvn.transform(new IfFalseNode(iff_epoch_not_equal));
3962 
3963   // True path, epoch is not equal, write a checkpoint for the vthread.
3964   Node* epoch_is_not_equal = _gvn.transform(new IfTrueNode(iff_epoch_not_equal));
3965 
3966   set_control(epoch_is_not_equal);
3967 
3968   // Make a runtime call, which can safepoint, to write a checkpoint for the vthread for this epoch.
3969   // The call also updates the native thread local thread id and the vthread with the current epoch.
3970   Node* call_write_checkpoint = make_runtime_call(RC_NO_LEAF,
3971                                                   OptoRuntime::jfr_write_checkpoint_Type(),
3972                                                   SharedRuntime::jfr_write_checkpoint(),
3973                                                   "write_checkpoint", TypePtr::BOTTOM);
3974   Node* call_write_checkpoint_control = _gvn.transform(new ProjNode(call_write_checkpoint, TypeFunc::Control));
3975 
3976   // vthread epoch != current epoch
3977   RegionNode* epoch_compare_rgn = new RegionNode(PATH_LIMIT);
3978   record_for_igvn(epoch_compare_rgn);
3979   PhiNode* epoch_compare_mem = new PhiNode(epoch_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3980   record_for_igvn(epoch_compare_mem);
3981   PhiNode* epoch_compare_io = new PhiNode(epoch_compare_rgn, Type::ABIO);
3982   record_for_igvn(epoch_compare_io);
3983 
3984   // Update control and phi nodes.
3985   epoch_compare_rgn->init_req(_true_path, call_write_checkpoint_control);
3986   epoch_compare_rgn->init_req(_false_path, epoch_is_equal);
3987   epoch_compare_mem->init_req(_true_path, _gvn.transform(reset_memory()));
3988   epoch_compare_mem->init_req(_false_path, input_memory_state);
3989   epoch_compare_io->init_req(_true_path, i_o());
3990   epoch_compare_io->init_req(_false_path, input_io_state);
3991 
3992   // excluded != true
3993   RegionNode* exclude_compare_rgn = new RegionNode(PATH_LIMIT);
3994   record_for_igvn(exclude_compare_rgn);
3995   PhiNode* exclude_compare_mem = new PhiNode(exclude_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3996   record_for_igvn(exclude_compare_mem);
3997   PhiNode* exclude_compare_io = new PhiNode(exclude_compare_rgn, Type::ABIO);
3998   record_for_igvn(exclude_compare_io);
3999 
4000   // Update control and phi nodes.
4001   exclude_compare_rgn->init_req(_true_path, _gvn.transform(epoch_compare_rgn));
4002   exclude_compare_rgn->init_req(_false_path, excluded);
4003   exclude_compare_mem->init_req(_true_path, _gvn.transform(epoch_compare_mem));
4004   exclude_compare_mem->init_req(_false_path, input_memory_state);
4005   exclude_compare_io->init_req(_true_path, _gvn.transform(epoch_compare_io));
4006   exclude_compare_io->init_req(_false_path, input_io_state);
4007 
4008   // vthread != threadObj
4009   RegionNode* vthread_compare_rgn = new RegionNode(PATH_LIMIT);
4010   record_for_igvn(vthread_compare_rgn);
4011   PhiNode* vthread_compare_mem = new PhiNode(vthread_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
4012   PhiNode* vthread_compare_io = new PhiNode(vthread_compare_rgn, Type::ABIO);
4013   record_for_igvn(vthread_compare_io);
4014   PhiNode* tid = new PhiNode(vthread_compare_rgn, TypeLong::LONG);
4015   record_for_igvn(tid);
4016   PhiNode* exclusion = new PhiNode(vthread_compare_rgn, TypeInt::CHAR);
4017   record_for_igvn(exclusion);
4018   PhiNode* pinVirtualThread = new PhiNode(vthread_compare_rgn, TypeInt::BOOL);
4019   record_for_igvn(pinVirtualThread);
4020 
4021   // Update control and phi nodes.
4022   vthread_compare_rgn->init_req(_true_path, _gvn.transform(exclude_compare_rgn));
4023   vthread_compare_rgn->init_req(_false_path, vthread_equal_threadObj);
4024   vthread_compare_mem->init_req(_true_path, _gvn.transform(exclude_compare_mem));
4025   vthread_compare_mem->init_req(_false_path, input_memory_state);
4026   vthread_compare_io->init_req(_true_path, _gvn.transform(exclude_compare_io));
4027   vthread_compare_io->init_req(_false_path, input_io_state);
4028   tid->init_req(_true_path, _gvn.transform(vthread_tid));
4029   tid->init_req(_false_path, _gvn.transform(thread_obj_tid));
4030   exclusion->init_req(_true_path, _gvn.transform(vthread_is_excluded));
4031   exclusion->init_req(_false_path, _gvn.transform(threadObj_is_excluded));
4032   pinVirtualThread->init_req(_true_path, _gvn.transform(continuation_support));
4033   pinVirtualThread->init_req(_false_path, _gvn.intcon(0));
4034 
4035   // Update branch state.
4036   set_control(_gvn.transform(vthread_compare_rgn));
4037   set_all_memory(_gvn.transform(vthread_compare_mem));
4038   set_i_o(_gvn.transform(vthread_compare_io));
4039 
4040   // Load the event writer oop by dereferencing the jobject handle.
4041   ciKlass* klass_EventWriter = env()->find_system_klass(ciSymbol::make("jdk/jfr/internal/event/EventWriter"));
4042   assert(klass_EventWriter->is_loaded(), "invariant");
4043   ciInstanceKlass* const instklass_EventWriter = klass_EventWriter->as_instance_klass();
4044   const TypeKlassPtr* const aklass = TypeKlassPtr::make(instklass_EventWriter);
4045   const TypeOopPtr* const xtype = aklass->as_instance_type();
4046   Node* jobj_untagged = _gvn.transform(new AddPNode(top(), jobj, _gvn.MakeConX(-JNIHandles::TypeTag::global)));
4047   Node* event_writer = access_load(jobj_untagged, xtype, T_OBJECT, IN_NATIVE | C2_CONTROL_DEPENDENT_LOAD);
4048 
4049   // Load the current thread id from the event writer object.
4050   Node* const event_writer_tid = load_field_from_object(event_writer, "threadID", "J");
4051   // Get the field offset to, conditionally, store an updated tid value later.
4052   Node* const event_writer_tid_field = field_address_from_object(event_writer, "threadID", "J", false);
4053   // Get the field offset to, conditionally, store an updated exclusion value later.
4054   Node* const event_writer_excluded_field = field_address_from_object(event_writer, "excluded", "Z", false);
4055   // Get the field offset to, conditionally, store an updated pinVirtualThread value later.
4056   Node* const event_writer_pin_field = field_address_from_object(event_writer, "pinVirtualThread", "Z", false);
4057 
4058   RegionNode* event_writer_tid_compare_rgn = new RegionNode(PATH_LIMIT);
4059   record_for_igvn(event_writer_tid_compare_rgn);
4060   PhiNode* event_writer_tid_compare_mem = new PhiNode(event_writer_tid_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
4061   record_for_igvn(event_writer_tid_compare_mem);
4062   PhiNode* event_writer_tid_compare_io = new PhiNode(event_writer_tid_compare_rgn, Type::ABIO);
4063   record_for_igvn(event_writer_tid_compare_io);
4064 
4065   // Compare the current tid from the thread object to what is currently stored in the event writer object.
4066   Node* const tid_cmp = _gvn.transform(new CmpLNode(event_writer_tid, _gvn.transform(tid)));
4067   Node* test_tid_not_equal = _gvn.transform(new BoolNode(tid_cmp, BoolTest::ne));
4068   IfNode* iff_tid_not_equal = create_and_map_if(_gvn.transform(vthread_compare_rgn), test_tid_not_equal, PROB_FAIR, COUNT_UNKNOWN);
4069 
4070   // False path, tids are the same.
4071   Node* tid_is_equal = _gvn.transform(new IfFalseNode(iff_tid_not_equal));
4072 
4073   // True path, tid is not equal, need to update the tid in the event writer.
4074   Node* tid_is_not_equal = _gvn.transform(new IfTrueNode(iff_tid_not_equal));
4075   record_for_igvn(tid_is_not_equal);
4076 
4077   // Store the pin state to the event writer.
4078   store_to_memory(tid_is_not_equal, event_writer_pin_field, _gvn.transform(pinVirtualThread), T_BOOLEAN, MemNode::unordered);
4079 
4080   // Store the exclusion state to the event writer.
4081   Node* excluded_bool = _gvn.transform(new URShiftINode(_gvn.transform(exclusion), excluded_shift));
4082   store_to_memory(tid_is_not_equal, event_writer_excluded_field, excluded_bool, T_BOOLEAN, MemNode::unordered);
4083 
4084   // Store the tid to the event writer.
4085   store_to_memory(tid_is_not_equal, event_writer_tid_field, tid, T_LONG, MemNode::unordered);
4086 
4087   // Update control and phi nodes.
4088   event_writer_tid_compare_rgn->init_req(_true_path, tid_is_not_equal);
4089   event_writer_tid_compare_rgn->init_req(_false_path, tid_is_equal);
4090   event_writer_tid_compare_mem->init_req(_true_path, _gvn.transform(reset_memory()));
4091   event_writer_tid_compare_mem->init_req(_false_path, _gvn.transform(vthread_compare_mem));
4092   event_writer_tid_compare_io->init_req(_true_path, _gvn.transform(i_o()));
4093   event_writer_tid_compare_io->init_req(_false_path, _gvn.transform(vthread_compare_io));
4094 
4095   // Result of top level CFG, Memory, IO and Value.
4096   RegionNode* result_rgn = new RegionNode(PATH_LIMIT);
4097   PhiNode* result_mem = new PhiNode(result_rgn, Type::MEMORY, TypePtr::BOTTOM);
4098   PhiNode* result_io = new PhiNode(result_rgn, Type::ABIO);
4099   PhiNode* result_value = new PhiNode(result_rgn, TypeInstPtr::BOTTOM);
4100 
4101   // Result control.
4102   result_rgn->init_req(_true_path, _gvn.transform(event_writer_tid_compare_rgn));
4103   result_rgn->init_req(_false_path, jobj_is_null);
4104 
4105   // Result memory.
4106   result_mem->init_req(_true_path, _gvn.transform(event_writer_tid_compare_mem));
4107   result_mem->init_req(_false_path, _gvn.transform(input_memory_state));
4108 
4109   // Result IO.
4110   result_io->init_req(_true_path, _gvn.transform(event_writer_tid_compare_io));
4111   result_io->init_req(_false_path, _gvn.transform(input_io_state));
4112 
4113   // Result value.
4114   result_value->init_req(_true_path, _gvn.transform(event_writer)); // return event writer oop
4115   result_value->init_req(_false_path, null()); // return null
4116 
4117   // Set output state.
4118   set_control(_gvn.transform(result_rgn));
4119   set_all_memory(_gvn.transform(result_mem));
4120   set_i_o(_gvn.transform(result_io));
4121   set_result(result_rgn, result_value);
4122   return true;
4123 }
4124 
4125 /*
4126  * The intrinsic is a model of this pseudo-code:
4127  *
4128  * JfrThreadLocal* const tl = thread->jfr_thread_local();
4129  * if (carrierThread != thread) { // is virtual thread
4130  *   const u2 vthread_epoch_raw = java_lang_Thread::jfr_epoch(thread);
4131  *   bool excluded = vthread_epoch_raw & excluded_mask;
4132  *   AtomicAccess::store(&tl->_contextual_tid, java_lang_Thread::tid(thread));
4133  *   AtomicAccess::store(&tl->_contextual_thread_excluded, is_excluded);
4134  *   if (!excluded) {
4135  *     const u2 vthread_epoch = vthread_epoch_raw & epoch_mask;
4136  *     AtomicAccess::store(&tl->_vthread_epoch, vthread_epoch);
4137  *   }
4138  *   AtomicAccess::release_store(&tl->_vthread, true);
4139  *   return;
4140  * }
4141  * AtomicAccess::release_store(&tl->_vthread, false);
4142  */
4143 void LibraryCallKit::extend_setCurrentThread(Node* jt, Node* thread) {
4144   enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
4145 
4146   Node* input_memory_state = reset_memory();
4147   set_all_memory(input_memory_state);
4148 
4149   // The most significant bit of the u2 is used to denote thread exclusion
4150   Node* excluded_mask = _gvn.intcon(1 << 15);
4151   // The epoch generation is the range [1-32767]
4152   Node* epoch_mask = _gvn.intcon(32767);
4153 
4154   Node* const carrierThread = generate_current_thread(jt);
4155   // If thread != carrierThread, this is a virtual thread.
4156   Node* thread_cmp_carrierThread = _gvn.transform(new CmpPNode(thread, carrierThread));
4157   Node* test_thread_not_equal_carrierThread = _gvn.transform(new BoolNode(thread_cmp_carrierThread, BoolTest::ne));
4158   IfNode* iff_thread_not_equal_carrierThread =
4159     create_and_map_if(control(), test_thread_not_equal_carrierThread, PROB_FAIR, COUNT_UNKNOWN);
4160 
4161   Node* vthread_offset = basic_plus_adr(jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_OFFSET_JFR));
4162 
4163   // False branch, is carrierThread.
4164   Node* thread_equal_carrierThread = _gvn.transform(new IfFalseNode(iff_thread_not_equal_carrierThread));
4165   // Store release
4166   Node* vthread_false_memory = store_to_memory(thread_equal_carrierThread, vthread_offset, _gvn.intcon(0), T_BOOLEAN, MemNode::release, true);
4167 
4168   set_all_memory(input_memory_state);
4169 
4170   // True branch, is virtual thread.
4171   Node* thread_not_equal_carrierThread = _gvn.transform(new IfTrueNode(iff_thread_not_equal_carrierThread));
4172   set_control(thread_not_equal_carrierThread);
4173 
4174   // Load the raw epoch value from the vthread.
4175   Node* epoch_offset = basic_plus_adr(thread, java_lang_Thread::jfr_epoch_offset());
4176   Node* epoch_raw = access_load_at(thread, epoch_offset, _gvn.type(epoch_offset)->is_ptr(), TypeInt::CHAR, T_CHAR,
4177                                    IN_HEAP | MO_UNORDERED | C2_MISMATCHED | C2_CONTROL_DEPENDENT_LOAD);
4178 
4179   // Mask off the excluded information from the epoch.
4180   Node * const is_excluded = _gvn.transform(new AndINode(epoch_raw, _gvn.transform(excluded_mask)));
4181 
4182   // Load the tid field from the thread.
4183   Node* tid = load_field_from_object(thread, "tid", "J");
4184 
4185   // Store the vthread tid to the jfr thread local.
4186   Node* thread_id_offset = basic_plus_adr(jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_ID_OFFSET_JFR));
4187   Node* tid_memory = store_to_memory(control(), thread_id_offset, tid, T_LONG, MemNode::unordered, true);
4188 
4189   // Branch is_excluded to conditionalize updating the epoch .
4190   Node* excluded_cmp = _gvn.transform(new CmpINode(is_excluded, _gvn.transform(excluded_mask)));
4191   Node* test_excluded = _gvn.transform(new BoolNode(excluded_cmp, BoolTest::eq));
4192   IfNode* iff_excluded = create_and_map_if(control(), test_excluded, PROB_MIN, COUNT_UNKNOWN);
4193 
4194   // True branch, vthread is excluded, no need to write epoch info.
4195   Node* excluded = _gvn.transform(new IfTrueNode(iff_excluded));
4196   set_control(excluded);
4197   Node* vthread_is_excluded = _gvn.intcon(1);
4198 
4199   // False branch, vthread is included, update epoch info.
4200   Node* included = _gvn.transform(new IfFalseNode(iff_excluded));
4201   set_control(included);
4202   Node* vthread_is_included = _gvn.intcon(0);
4203 
4204   // Get epoch value.
4205   Node* epoch = _gvn.transform(new AndINode(epoch_raw, _gvn.transform(epoch_mask)));
4206 
4207   // Store the vthread epoch to the jfr thread local.
4208   Node* vthread_epoch_offset = basic_plus_adr(jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_EPOCH_OFFSET_JFR));
4209   Node* included_memory = store_to_memory(control(), vthread_epoch_offset, epoch, T_CHAR, MemNode::unordered, true);
4210 
4211   RegionNode* excluded_rgn = new RegionNode(PATH_LIMIT);
4212   record_for_igvn(excluded_rgn);
4213   PhiNode* excluded_mem = new PhiNode(excluded_rgn, Type::MEMORY, TypePtr::BOTTOM);
4214   record_for_igvn(excluded_mem);
4215   PhiNode* exclusion = new PhiNode(excluded_rgn, TypeInt::BOOL);
4216   record_for_igvn(exclusion);
4217 
4218   // Merge the excluded control and memory.
4219   excluded_rgn->init_req(_true_path, excluded);
4220   excluded_rgn->init_req(_false_path, included);
4221   excluded_mem->init_req(_true_path, tid_memory);
4222   excluded_mem->init_req(_false_path, included_memory);
4223   exclusion->init_req(_true_path, _gvn.transform(vthread_is_excluded));
4224   exclusion->init_req(_false_path, _gvn.transform(vthread_is_included));
4225 
4226   // Set intermediate state.
4227   set_control(_gvn.transform(excluded_rgn));
4228   set_all_memory(excluded_mem);
4229 
4230   // Store the vthread exclusion state to the jfr thread local.
4231   Node* thread_local_excluded_offset = basic_plus_adr(jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_EXCLUDED_OFFSET_JFR));
4232   store_to_memory(control(), thread_local_excluded_offset, _gvn.transform(exclusion), T_BOOLEAN, MemNode::unordered, true);
4233 
4234   // Store release
4235   Node * vthread_true_memory = store_to_memory(control(), vthread_offset, _gvn.intcon(1), T_BOOLEAN, MemNode::release, true);
4236 
4237   RegionNode* thread_compare_rgn = new RegionNode(PATH_LIMIT);
4238   record_for_igvn(thread_compare_rgn);
4239   PhiNode* thread_compare_mem = new PhiNode(thread_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
4240   record_for_igvn(thread_compare_mem);
4241   PhiNode* vthread = new PhiNode(thread_compare_rgn, TypeInt::BOOL);
4242   record_for_igvn(vthread);
4243 
4244   // Merge the thread_compare control and memory.
4245   thread_compare_rgn->init_req(_true_path, control());
4246   thread_compare_rgn->init_req(_false_path, thread_equal_carrierThread);
4247   thread_compare_mem->init_req(_true_path, vthread_true_memory);
4248   thread_compare_mem->init_req(_false_path, vthread_false_memory);
4249 
4250   // Set output state.
4251   set_control(_gvn.transform(thread_compare_rgn));
4252   set_all_memory(_gvn.transform(thread_compare_mem));
4253 }
4254 
4255 #endif // JFR_HAVE_INTRINSICS
4256 
4257 //------------------------inline_native_currentCarrierThread------------------
4258 bool LibraryCallKit::inline_native_currentCarrierThread() {
4259   Node* junk = nullptr;
4260   set_result(generate_current_thread(junk));
4261   return true;
4262 }
4263 
4264 //------------------------inline_native_currentThread------------------
4265 bool LibraryCallKit::inline_native_currentThread() {
4266   Node* junk = nullptr;
4267   set_result(generate_virtual_thread(junk));
4268   return true;
4269 }
4270 
4271 //------------------------inline_native_setVthread------------------
4272 bool LibraryCallKit::inline_native_setCurrentThread() {
4273   assert(C->method()->changes_current_thread(),
4274          "method changes current Thread but is not annotated ChangesCurrentThread");
4275   Node* arr = argument(1);
4276   Node* thread = _gvn.transform(new ThreadLocalNode());
4277   Node* p = basic_plus_adr(top()/*!oop*/, thread, in_bytes(JavaThread::vthread_offset()));
4278   Node* thread_obj_handle
4279     = make_load(nullptr, p, p->bottom_type()->is_ptr(), T_OBJECT, MemNode::unordered);
4280   thread_obj_handle = _gvn.transform(thread_obj_handle);
4281   const TypePtr *adr_type = _gvn.type(thread_obj_handle)->isa_ptr();
4282   access_store_at(nullptr, thread_obj_handle, adr_type, arr, _gvn.type(arr), T_OBJECT, IN_NATIVE | MO_UNORDERED);
4283 
4284   // Change the _monitor_owner_id of the JavaThread
4285   Node* tid = load_field_from_object(arr, "tid", "J");
4286   Node* monitor_owner_id_offset = basic_plus_adr(thread, in_bytes(JavaThread::monitor_owner_id_offset()));
4287   store_to_memory(control(), monitor_owner_id_offset, tid, T_LONG, MemNode::unordered, true);
4288 
4289   JFR_ONLY(extend_setCurrentThread(thread, arr);)
4290   return true;
4291 }
4292 
4293 const Type* LibraryCallKit::scopedValueCache_type() {
4294   ciKlass* objects_klass = ciObjArrayKlass::make(env()->Object_klass());
4295   const TypeOopPtr* etype = TypeOopPtr::make_from_klass(env()->Object_klass());
4296   const TypeAry* arr0 = TypeAry::make(etype, TypeInt::POS, /* stable= */ false, /* flat= */ false, /* not_flat= */ true, /* not_null_free= */ true, true);
4297 
4298   // Because we create the scopedValue cache lazily we have to make the
4299   // type of the result BotPTR.
4300   bool xk = etype->klass_is_exact();
4301   const Type* objects_type = TypeAryPtr::make(TypePtr::BotPTR, arr0, objects_klass, xk, TypeAryPtr::Offset(0));
4302   return objects_type;
4303 }
4304 
4305 Node* LibraryCallKit::scopedValueCache_helper() {
4306   Node* thread = _gvn.transform(new ThreadLocalNode());
4307   Node* p = basic_plus_adr(top()/*!oop*/, thread, in_bytes(JavaThread::scopedValueCache_offset()));
4308   // We cannot use immutable_memory() because we might flip onto a
4309   // different carrier thread, at which point we'll need to use that
4310   // carrier thread's cache.
4311   // return _gvn.transform(LoadNode::make(_gvn, nullptr, immutable_memory(), p, p->bottom_type()->is_ptr(),
4312   //       TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered));
4313   return make_load(nullptr, p, p->bottom_type()->is_ptr(), T_ADDRESS, MemNode::unordered);
4314 }
4315 
4316 //------------------------inline_native_scopedValueCache------------------
4317 bool LibraryCallKit::inline_native_scopedValueCache() {
4318   Node* cache_obj_handle = scopedValueCache_helper();
4319   const Type* objects_type = scopedValueCache_type();
4320   set_result(access_load(cache_obj_handle, objects_type, T_OBJECT, IN_NATIVE));
4321 
4322   return true;
4323 }
4324 
4325 //------------------------inline_native_setScopedValueCache------------------
4326 bool LibraryCallKit::inline_native_setScopedValueCache() {
4327   Node* arr = argument(0);
4328   Node* cache_obj_handle = scopedValueCache_helper();
4329   const Type* objects_type = scopedValueCache_type();
4330 
4331   const TypePtr *adr_type = _gvn.type(cache_obj_handle)->isa_ptr();
4332   access_store_at(nullptr, cache_obj_handle, adr_type, arr, objects_type, T_OBJECT, IN_NATIVE | MO_UNORDERED);
4333 
4334   return true;
4335 }
4336 
4337 //------------------------inline_native_Continuation_pin and unpin-----------
4338 
4339 // Shared implementation routine for both pin and unpin.
4340 bool LibraryCallKit::inline_native_Continuation_pinning(bool unpin) {
4341   enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
4342 
4343   // Save input memory.
4344   Node* input_memory_state = reset_memory();
4345   set_all_memory(input_memory_state);
4346 
4347   // TLS
4348   Node* tls_ptr = _gvn.transform(new ThreadLocalNode());
4349   Node* last_continuation_offset = basic_plus_adr(top(), tls_ptr, in_bytes(JavaThread::cont_entry_offset()));
4350   Node* last_continuation = make_load(control(), last_continuation_offset, last_continuation_offset->get_ptr_type(), T_ADDRESS, MemNode::unordered);
4351 
4352   // Null check the last continuation object.
4353   Node* continuation_cmp_null = _gvn.transform(new CmpPNode(last_continuation, null()));
4354   Node* test_continuation_not_equal_null = _gvn.transform(new BoolNode(continuation_cmp_null, BoolTest::ne));
4355   IfNode* iff_continuation_not_equal_null = create_and_map_if(control(), test_continuation_not_equal_null, PROB_MAX, COUNT_UNKNOWN);
4356 
4357   // False path, last continuation is null.
4358   Node* continuation_is_null = _gvn.transform(new IfFalseNode(iff_continuation_not_equal_null));
4359 
4360   // True path, last continuation is not null.
4361   Node* continuation_is_not_null = _gvn.transform(new IfTrueNode(iff_continuation_not_equal_null));
4362 
4363   set_control(continuation_is_not_null);
4364 
4365   // Load the pin count from the last continuation.
4366   Node* pin_count_offset = basic_plus_adr(top(), last_continuation, in_bytes(ContinuationEntry::pin_count_offset()));
4367   Node* pin_count = make_load(control(), pin_count_offset, TypeInt::INT, T_INT, MemNode::unordered);
4368 
4369   // The loaded pin count is compared against a context specific rhs for over/underflow detection.
4370   Node* pin_count_rhs;
4371   if (unpin) {
4372     pin_count_rhs = _gvn.intcon(0);
4373   } else {
4374     pin_count_rhs = _gvn.intcon(UINT32_MAX);
4375   }
4376   Node* pin_count_cmp = _gvn.transform(new CmpUNode(_gvn.transform(pin_count), pin_count_rhs));
4377   Node* test_pin_count_over_underflow = _gvn.transform(new BoolNode(pin_count_cmp, BoolTest::eq));
4378   IfNode* iff_pin_count_over_underflow = create_and_map_if(control(), test_pin_count_over_underflow, PROB_MIN, COUNT_UNKNOWN);
4379 
4380   // True branch, pin count over/underflow.
4381   Node* pin_count_over_underflow = _gvn.transform(new IfTrueNode(iff_pin_count_over_underflow));
4382   {
4383     // Trap (but not deoptimize (Action_none)) and continue in the interpreter
4384     // which will throw IllegalStateException for pin count over/underflow.
4385     // No memory changed so far - we can use memory create by reset_memory()
4386     // at the beginning of this intrinsic. No need to call reset_memory() again.
4387     PreserveJVMState pjvms(this);
4388     set_control(pin_count_over_underflow);
4389     uncommon_trap(Deoptimization::Reason_intrinsic,
4390                   Deoptimization::Action_none);
4391     assert(stopped(), "invariant");
4392   }
4393 
4394   // False branch, no pin count over/underflow. Increment or decrement pin count and store back.
4395   Node* valid_pin_count = _gvn.transform(new IfFalseNode(iff_pin_count_over_underflow));
4396   set_control(valid_pin_count);
4397 
4398   Node* next_pin_count;
4399   if (unpin) {
4400     next_pin_count = _gvn.transform(new SubINode(pin_count, _gvn.intcon(1)));
4401   } else {
4402     next_pin_count = _gvn.transform(new AddINode(pin_count, _gvn.intcon(1)));
4403   }
4404 
4405   store_to_memory(control(), pin_count_offset, next_pin_count, T_INT, MemNode::unordered);
4406 
4407   // Result of top level CFG and Memory.
4408   RegionNode* result_rgn = new RegionNode(PATH_LIMIT);
4409   record_for_igvn(result_rgn);
4410   PhiNode* result_mem = new PhiNode(result_rgn, Type::MEMORY, TypePtr::BOTTOM);
4411   record_for_igvn(result_mem);
4412 
4413   result_rgn->init_req(_true_path, _gvn.transform(valid_pin_count));
4414   result_rgn->init_req(_false_path, _gvn.transform(continuation_is_null));
4415   result_mem->init_req(_true_path, _gvn.transform(reset_memory()));
4416   result_mem->init_req(_false_path, _gvn.transform(input_memory_state));
4417 
4418   // Set output state.
4419   set_control(_gvn.transform(result_rgn));
4420   set_all_memory(_gvn.transform(result_mem));
4421 
4422   return true;
4423 }
4424 
4425 //---------------------------load_mirror_from_klass----------------------------
4426 // Given a klass oop, load its java mirror (a java.lang.Class oop).
4427 Node* LibraryCallKit::load_mirror_from_klass(Node* klass) {
4428   Node* p = basic_plus_adr(klass, in_bytes(Klass::java_mirror_offset()));
4429   Node* load = make_load(nullptr, p, TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered);
4430   // mirror = ((OopHandle)mirror)->resolve();
4431   return access_load(load, TypeInstPtr::MIRROR, T_OBJECT, IN_NATIVE);
4432 }
4433 
4434 //-----------------------load_klass_from_mirror_common-------------------------
4435 // Given a java mirror (a java.lang.Class oop), load its corresponding klass oop.
4436 // Test the klass oop for null (signifying a primitive Class like Integer.TYPE),
4437 // and branch to the given path on the region.
4438 // If never_see_null, take an uncommon trap on null, so we can optimistically
4439 // compile for the non-null case.
4440 // If the region is null, force never_see_null = true.
4441 Node* LibraryCallKit::load_klass_from_mirror_common(Node* mirror,
4442                                                     bool never_see_null,
4443                                                     RegionNode* region,
4444                                                     int null_path,
4445                                                     int offset) {
4446   if (region == nullptr)  never_see_null = true;
4447   Node* p = basic_plus_adr(mirror, offset);
4448   const TypeKlassPtr*  kls_type = TypeInstKlassPtr::OBJECT_OR_NULL;
4449   Node* kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), p, TypeRawPtr::BOTTOM, kls_type));
4450   Node* null_ctl = top();
4451   kls = null_check_oop(kls, &null_ctl, never_see_null);
4452   if (region != nullptr) {
4453     // Set region->in(null_path) if the mirror is a primitive (e.g, int.class).
4454     region->init_req(null_path, null_ctl);
4455   } else {
4456     assert(null_ctl == top(), "no loose ends");
4457   }
4458   return kls;
4459 }
4460 
4461 //--------------------(inline_native_Class_query helpers)---------------------
4462 // Use this for JVM_ACC_INTERFACE.
4463 // Fall through if (mods & mask) == bits, take the guard otherwise.
4464 Node* LibraryCallKit::generate_klass_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region,
4465                                                  ByteSize offset, const Type* type, BasicType bt) {
4466   // Branch around if the given klass has the given modifier bit set.
4467   // Like generate_guard, adds a new path onto the region.
4468   Node* modp = basic_plus_adr(kls, in_bytes(offset));
4469   Node* mods = make_load(nullptr, modp, type, bt, MemNode::unordered);
4470   Node* mask = intcon(modifier_mask);
4471   Node* bits = intcon(modifier_bits);
4472   Node* mbit = _gvn.transform(new AndINode(mods, mask));
4473   Node* cmp  = _gvn.transform(new CmpINode(mbit, bits));
4474   Node* bol  = _gvn.transform(new BoolNode(cmp, BoolTest::ne));
4475   return generate_fair_guard(bol, region);
4476 }
4477 
4478 Node* LibraryCallKit::generate_interface_guard(Node* kls, RegionNode* region) {
4479   return generate_klass_flags_guard(kls, JVM_ACC_INTERFACE, 0, region,
4480                                     InstanceKlass::access_flags_offset(), TypeInt::CHAR, T_CHAR);
4481 }
4482 
4483 // Use this for testing if Klass is_hidden, has_finalizer, and is_cloneable_fast.
4484 Node* LibraryCallKit::generate_misc_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region) {
4485   return generate_klass_flags_guard(kls, modifier_mask, modifier_bits, region,
4486                                     Klass::misc_flags_offset(), TypeInt::UBYTE, T_BOOLEAN);
4487 }
4488 
4489 Node* LibraryCallKit::generate_hidden_class_guard(Node* kls, RegionNode* region) {
4490   return generate_misc_flags_guard(kls, KlassFlags::_misc_is_hidden_class, 0, region);
4491 }
4492 
4493 //-------------------------inline_native_Class_query-------------------
4494 bool LibraryCallKit::inline_native_Class_query(vmIntrinsics::ID id) {
4495   const Type* return_type = TypeInt::BOOL;
4496   Node* prim_return_value = top();  // what happens if it's a primitive class?
4497   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
4498   bool expect_prim = false;     // most of these guys expect to work on refs
4499 
4500   enum { _normal_path = 1, _prim_path = 2, PATH_LIMIT };
4501 
4502   Node* mirror = argument(0);
4503   Node* obj    = top();
4504 
4505   switch (id) {
4506   case vmIntrinsics::_isInstance:
4507     // nothing is an instance of a primitive type
4508     prim_return_value = intcon(0);
4509     obj = argument(1);
4510     break;
4511   case vmIntrinsics::_isHidden:
4512     prim_return_value = intcon(0);
4513     break;
4514   case vmIntrinsics::_getSuperclass:
4515     prim_return_value = null();
4516     return_type = TypeInstPtr::MIRROR->cast_to_ptr_type(TypePtr::BotPTR);
4517     break;
4518   default:
4519     fatal_unexpected_iid(id);
4520     break;
4521   }
4522 
4523   const TypeInstPtr* mirror_con = _gvn.type(mirror)->isa_instptr();
4524   if (mirror_con == nullptr)  return false;  // cannot happen?
4525 
4526 #ifndef PRODUCT
4527   if (C->print_intrinsics() || C->print_inlining()) {
4528     ciType* k = mirror_con->java_mirror_type();
4529     if (k) {
4530       tty->print("Inlining %s on constant Class ", vmIntrinsics::name_at(intrinsic_id()));
4531       k->print_name();
4532       tty->cr();
4533     }
4534   }
4535 #endif
4536 
4537   // Null-check the mirror, and the mirror's klass ptr (in case it is a primitive).
4538   RegionNode* region = new RegionNode(PATH_LIMIT);
4539   record_for_igvn(region);
4540   PhiNode* phi = new PhiNode(region, return_type);
4541 
4542   // The mirror will never be null of Reflection.getClassAccessFlags, however
4543   // it may be null for Class.isInstance or Class.getModifiers. Throw a NPE
4544   // if it is. See bug 4774291.
4545 
4546   // For Reflection.getClassAccessFlags(), the null check occurs in
4547   // the wrong place; see inline_unsafe_access(), above, for a similar
4548   // situation.
4549   mirror = null_check(mirror);
4550   // If mirror or obj is dead, only null-path is taken.
4551   if (stopped())  return true;
4552 
4553   if (expect_prim)  never_see_null = false;  // expect nulls (meaning prims)
4554 
4555   // Now load the mirror's klass metaobject, and null-check it.
4556   // Side-effects region with the control path if the klass is null.
4557   Node* kls = load_klass_from_mirror(mirror, never_see_null, region, _prim_path);
4558   // If kls is null, we have a primitive mirror.
4559   phi->init_req(_prim_path, prim_return_value);
4560   if (stopped()) { set_result(region, phi); return true; }
4561   bool safe_for_replace = (region->in(_prim_path) == top());
4562 
4563   Node* p;  // handy temp
4564   Node* null_ctl;
4565 
4566   // Now that we have the non-null klass, we can perform the real query.
4567   // For constant classes, the query will constant-fold in LoadNode::Value.
4568   Node* query_value = top();
4569   switch (id) {
4570   case vmIntrinsics::_isInstance:
4571     // nothing is an instance of a primitive type
4572     query_value = gen_instanceof(obj, kls, safe_for_replace);
4573     break;
4574 
4575   case vmIntrinsics::_isHidden:
4576     // (To verify this code sequence, check the asserts in JVM_IsHiddenClass.)
4577     if (generate_hidden_class_guard(kls, region) != nullptr)
4578       // A guard was added.  If the guard is taken, it was an hidden class.
4579       phi->add_req(intcon(1));
4580     // If we fall through, it's a plain class.
4581     query_value = intcon(0);
4582     break;
4583 
4584 
4585   case vmIntrinsics::_getSuperclass:
4586     // The rules here are somewhat unfortunate, but we can still do better
4587     // with random logic than with a JNI call.
4588     // Interfaces store null or Object as _super, but must report null.
4589     // Arrays store an intermediate super as _super, but must report Object.
4590     // Other types can report the actual _super.
4591     // (To verify this code sequence, check the asserts in JVM_IsInterface.)
4592     if (generate_array_guard(kls, region) != nullptr) {
4593       // A guard was added.  If the guard is taken, it was an array.
4594       phi->add_req(makecon(TypeInstPtr::make(env()->Object_klass()->java_mirror())));
4595     }
4596     // Check for interface after array since this checks AccessFlags offset into InstanceKlass.
4597     // In other words, we are accessing subtype-specific information, so we need to determine the subtype first.
4598     if (generate_interface_guard(kls, region) != nullptr) {
4599       // A guard was added.  If the guard is taken, it was an interface.
4600       phi->add_req(null());
4601     }
4602     // If we fall through, it's a plain class.  Get its _super.
4603     if (!stopped()) {
4604       p = basic_plus_adr(kls, in_bytes(Klass::super_offset()));
4605       kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), p, TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
4606       null_ctl = top();
4607       kls = null_check_oop(kls, &null_ctl);
4608       if (null_ctl != top()) {
4609         // If the guard is taken, Object.superClass is null (both klass and mirror).
4610         region->add_req(null_ctl);
4611         phi   ->add_req(null());
4612       }
4613       if (!stopped()) {
4614         query_value = load_mirror_from_klass(kls);
4615       }
4616     }
4617     break;
4618 
4619   default:
4620     fatal_unexpected_iid(id);
4621     break;
4622   }
4623 
4624   // Fall-through is the normal case of a query to a real class.
4625   phi->init_req(1, query_value);
4626   region->init_req(1, control());
4627 
4628   C->set_has_split_ifs(true); // Has chance for split-if optimization
4629   set_result(region, phi);
4630   return true;
4631 }
4632 
4633 
4634 //-------------------------inline_Class_cast-------------------
4635 bool LibraryCallKit::inline_Class_cast() {
4636   Node* mirror = argument(0); // Class
4637   Node* obj    = argument(1);
4638   const TypeInstPtr* mirror_con = _gvn.type(mirror)->isa_instptr();
4639   if (mirror_con == nullptr) {
4640     return false;  // dead path (mirror->is_top()).
4641   }
4642   if (obj == nullptr || obj->is_top()) {
4643     return false;  // dead path
4644   }
4645   const TypeOopPtr* tp = _gvn.type(obj)->isa_oopptr();
4646 
4647   // First, see if Class.cast() can be folded statically.
4648   // java_mirror_type() returns non-null for compile-time Class constants.
4649   ciType* tm = mirror_con->java_mirror_type();
4650   if (tm != nullptr && tm->is_klass() &&
4651       tp != nullptr) {
4652     if (!tp->is_loaded()) {
4653       // Don't use intrinsic when class is not loaded.
4654       return false;
4655     } else {
4656       const TypeKlassPtr* tklass = TypeKlassPtr::make(tm->as_klass(), Type::trust_interfaces);
4657       int static_res = C->static_subtype_check(tklass, tp->as_klass_type());
4658       if (static_res == Compile::SSC_always_true) {
4659         // isInstance() is true - fold the code.
4660         set_result(obj);
4661         return true;
4662       } else if (static_res == Compile::SSC_always_false) {
4663         // Don't use intrinsic, have to throw ClassCastException.
4664         // If the reference is null, the non-intrinsic bytecode will
4665         // be optimized appropriately.
4666         return false;
4667       }
4668     }
4669   }
4670 
4671   // Bailout intrinsic and do normal inlining if exception path is frequent.
4672   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
4673     return false;
4674   }
4675 
4676   // Generate dynamic checks.
4677   // Class.cast() is java implementation of _checkcast bytecode.
4678   // Do checkcast (Parse::do_checkcast()) optimizations here.
4679 
4680   mirror = null_check(mirror);
4681   // If mirror is dead, only null-path is taken.
4682   if (stopped()) {
4683     return true;
4684   }
4685 
4686   // Not-subtype or the mirror's klass ptr is nullptr (in case it is a primitive).
4687   enum { _bad_type_path = 1, _prim_path = 2, _npe_path = 3, PATH_LIMIT };
4688   RegionNode* region = new RegionNode(PATH_LIMIT);
4689   record_for_igvn(region);
4690 
4691   // Now load the mirror's klass metaobject, and null-check it.
4692   // If kls is null, we have a primitive mirror and
4693   // nothing is an instance of a primitive type.
4694   Node* kls = load_klass_from_mirror(mirror, false, region, _prim_path);
4695 
4696   Node* res = top();
4697   Node* io = i_o();
4698   Node* mem = merged_memory();
4699   if (!stopped()) {
4700 
4701     Node* bad_type_ctrl = top();
4702     // Do checkcast optimizations.
4703     res = gen_checkcast(obj, kls, &bad_type_ctrl);
4704     region->init_req(_bad_type_path, bad_type_ctrl);
4705   }
4706   if (region->in(_prim_path) != top() ||
4707       region->in(_bad_type_path) != top() ||
4708       region->in(_npe_path) != top()) {
4709     // Let Interpreter throw ClassCastException.
4710     PreserveJVMState pjvms(this);
4711     set_control(_gvn.transform(region));
4712     // Set IO and memory because gen_checkcast may override them when buffering inline types
4713     set_i_o(io);
4714     set_all_memory(mem);
4715     uncommon_trap(Deoptimization::Reason_intrinsic,
4716                   Deoptimization::Action_maybe_recompile);
4717   }
4718   if (!stopped()) {
4719     set_result(res);
4720   }
4721   return true;
4722 }
4723 
4724 
4725 //--------------------------inline_native_subtype_check------------------------
4726 // This intrinsic takes the JNI calls out of the heart of
4727 // UnsafeFieldAccessorImpl.set, which improves Field.set, readObject, etc.
4728 bool LibraryCallKit::inline_native_subtype_check() {
4729   // Pull both arguments off the stack.
4730   Node* args[2];                // two java.lang.Class mirrors: superc, subc
4731   args[0] = argument(0);
4732   args[1] = argument(1);
4733   Node* klasses[2];             // corresponding Klasses: superk, subk
4734   klasses[0] = klasses[1] = top();
4735 
4736   enum {
4737     // A full decision tree on {superc is prim, subc is prim}:
4738     _prim_0_path = 1,           // {P,N} => false
4739                                 // {P,P} & superc!=subc => false
4740     _prim_same_path,            // {P,P} & superc==subc => true
4741     _prim_1_path,               // {N,P} => false
4742     _ref_subtype_path,          // {N,N} & subtype check wins => true
4743     _both_ref_path,             // {N,N} & subtype check loses => false
4744     PATH_LIMIT
4745   };
4746 
4747   RegionNode* region = new RegionNode(PATH_LIMIT);
4748   RegionNode* prim_region = new RegionNode(2);
4749   Node*       phi    = new PhiNode(region, TypeInt::BOOL);
4750   record_for_igvn(region);
4751   record_for_igvn(prim_region);
4752 
4753   const TypePtr* adr_type = TypeRawPtr::BOTTOM;   // memory type of loads
4754   const TypeKlassPtr* kls_type = TypeInstKlassPtr::OBJECT_OR_NULL;
4755   int class_klass_offset = java_lang_Class::klass_offset();
4756 
4757   // First null-check both mirrors and load each mirror's klass metaobject.
4758   int which_arg;
4759   for (which_arg = 0; which_arg <= 1; which_arg++) {
4760     Node* arg = args[which_arg];
4761     arg = null_check(arg);
4762     if (stopped())  break;
4763     args[which_arg] = arg;
4764 
4765     Node* p = basic_plus_adr(arg, class_klass_offset);
4766     Node* kls = LoadKlassNode::make(_gvn, immutable_memory(), p, adr_type, kls_type);
4767     klasses[which_arg] = _gvn.transform(kls);
4768   }
4769 
4770   // Having loaded both klasses, test each for null.
4771   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
4772   for (which_arg = 0; which_arg <= 1; which_arg++) {
4773     Node* kls = klasses[which_arg];
4774     Node* null_ctl = top();
4775     kls = null_check_oop(kls, &null_ctl, never_see_null);
4776     if (which_arg == 0) {
4777       prim_region->init_req(1, null_ctl);
4778     } else {
4779       region->init_req(_prim_1_path, null_ctl);
4780     }
4781     if (stopped())  break;
4782     klasses[which_arg] = kls;
4783   }
4784 
4785   if (!stopped()) {
4786     // now we have two reference types, in klasses[0..1]
4787     Node* subk   = klasses[1];  // the argument to isAssignableFrom
4788     Node* superk = klasses[0];  // the receiver
4789     region->set_req(_both_ref_path, gen_subtype_check(subk, superk));
4790     region->set_req(_ref_subtype_path, control());
4791   }
4792 
4793   // If both operands are primitive (both klasses null), then
4794   // we must return true when they are identical primitives.
4795   // It is convenient to test this after the first null klass check.
4796   // This path is also used if superc is a value mirror.
4797   set_control(_gvn.transform(prim_region));
4798   if (!stopped()) {
4799     // Since superc is primitive, make a guard for the superc==subc case.
4800     Node* cmp_eq = _gvn.transform(new CmpPNode(args[0], args[1]));
4801     Node* bol_eq = _gvn.transform(new BoolNode(cmp_eq, BoolTest::eq));
4802     generate_fair_guard(bol_eq, region);
4803     if (region->req() == PATH_LIMIT+1) {
4804       // A guard was added.  If the added guard is taken, superc==subc.
4805       region->swap_edges(PATH_LIMIT, _prim_same_path);
4806       region->del_req(PATH_LIMIT);
4807     }
4808     region->set_req(_prim_0_path, control()); // Not equal after all.
4809   }
4810 
4811   // these are the only paths that produce 'true':
4812   phi->set_req(_prim_same_path,   intcon(1));
4813   phi->set_req(_ref_subtype_path, intcon(1));
4814 
4815   // pull together the cases:
4816   assert(region->req() == PATH_LIMIT, "sane region");
4817   for (uint i = 1; i < region->req(); i++) {
4818     Node* ctl = region->in(i);
4819     if (ctl == nullptr || ctl == top()) {
4820       region->set_req(i, top());
4821       phi   ->set_req(i, top());
4822     } else if (phi->in(i) == nullptr) {
4823       phi->set_req(i, intcon(0)); // all other paths produce 'false'
4824     }
4825   }
4826 
4827   set_control(_gvn.transform(region));
4828   set_result(_gvn.transform(phi));
4829   return true;
4830 }
4831 
4832 //---------------------generate_array_guard_common------------------------
4833 Node* LibraryCallKit::generate_array_guard_common(Node* kls, RegionNode* region, ArrayKind kind, Node** obj) {
4834 
4835   if (stopped()) {
4836     return nullptr;
4837   }
4838 
4839   // Like generate_guard, adds a new path onto the region.
4840   jint  layout_con = 0;
4841   Node* layout_val = get_layout_helper(kls, layout_con);
4842   if (layout_val == nullptr) {
4843     bool query = 0;
4844     switch(kind) {
4845       case RefArray:       query = Klass::layout_helper_is_refArray(layout_con); break;
4846       case NonRefArray:    query = !Klass::layout_helper_is_refArray(layout_con); break;
4847       case TypeArray:      query = Klass::layout_helper_is_typeArray(layout_con); break;
4848       case AnyArray:       query = Klass::layout_helper_is_array(layout_con); break;
4849       case NonArray:       query = !Klass::layout_helper_is_array(layout_con); break;
4850       default:
4851         ShouldNotReachHere();
4852     }
4853     if (!query) {
4854       return nullptr;                       // never a branch
4855     } else {                             // always a branch
4856       Node* always_branch = control();
4857       if (region != nullptr)
4858         region->add_req(always_branch);
4859       set_control(top());
4860       return always_branch;
4861     }
4862   }
4863   unsigned int value = 0;
4864   BoolTest::mask btest = BoolTest::illegal;
4865   switch(kind) {
4866     case RefArray:
4867     case NonRefArray: {
4868       value = Klass::_lh_array_tag_ref_value;
4869       layout_val = _gvn.transform(new RShiftINode(layout_val, intcon(Klass::_lh_array_tag_shift)));
4870       btest = (kind == RefArray) ? BoolTest::eq : BoolTest::ne;
4871       break;
4872     }
4873     case TypeArray: {
4874       value = Klass::_lh_array_tag_type_value;
4875       layout_val = _gvn.transform(new RShiftINode(layout_val, intcon(Klass::_lh_array_tag_shift)));
4876       btest = BoolTest::eq;
4877       break;
4878     }
4879     case AnyArray:    value = Klass::_lh_neutral_value; btest = BoolTest::lt; break;
4880     case NonArray:    value = Klass::_lh_neutral_value; btest = BoolTest::gt; break;
4881     default:
4882       ShouldNotReachHere();
4883   }
4884   // Now test the correct condition.
4885   jint nval = (jint)value;
4886   Node* cmp = _gvn.transform(new CmpINode(layout_val, intcon(nval)));
4887   Node* bol = _gvn.transform(new BoolNode(cmp, btest));
4888   Node* ctrl = generate_fair_guard(bol, region);
4889   Node* is_array_ctrl = kind == NonArray ? control() : ctrl;
4890   if (obj != nullptr && is_array_ctrl != nullptr && is_array_ctrl != top()) {
4891     // Keep track of the fact that 'obj' is an array to prevent
4892     // array specific accesses from floating above the guard.
4893     *obj = _gvn.transform(new CastPPNode(is_array_ctrl, *obj, TypeAryPtr::BOTTOM));
4894   }
4895   return ctrl;
4896 }
4897 
4898 // public static native Object[] ValueClass::newNullRestrictedAtomicArray(Class<?> componentType, int length, Object initVal);
4899 // public static native Object[] ValueClass::newNullRestrictedNonAtomicArray(Class<?> componentType, int length, Object initVal);
4900 // public static native Object[] ValueClass::newNullableAtomicArray(Class<?> componentType, int length);
4901 bool LibraryCallKit::inline_newArray(bool null_free, bool atomic) {
4902   assert(null_free || atomic, "nullable implies atomic");
4903   Node* componentType = argument(0);
4904   Node* length = argument(1);
4905   Node* init_val = null_free ? argument(2) : nullptr;
4906 
4907   const TypeInstPtr* tp = _gvn.type(componentType)->isa_instptr();
4908   if (tp != nullptr) {
4909     ciInstanceKlass* ik = tp->instance_klass();
4910     if (ik == C->env()->Class_klass()) {
4911       ciType* t = tp->java_mirror_type();
4912       if (t != nullptr && t->is_inlinetype()) {
4913 
4914         ciArrayKlass* array_klass = ciArrayKlass::make(t, null_free, atomic, true);
4915         assert(array_klass->is_elem_null_free() == null_free, "inconsistency");
4916 
4917         // TOOD 8350865 ZGC needs card marks on initializing oop stores
4918         if (UseZGC && null_free && !array_klass->is_flat_array_klass()) {
4919           return false;
4920         }
4921 
4922         if (array_klass->is_loaded() && array_klass->element_klass()->as_inline_klass()->is_initialized()) {
4923           const TypeAryKlassPtr* array_klass_type = TypeAryKlassPtr::make(array_klass, Type::trust_interfaces);
4924           if (null_free) {
4925             if (init_val->is_InlineType()) {
4926               if (array_klass_type->is_flat() && init_val->as_InlineType()->is_all_zero(&gvn(), /* flat */ true)) {
4927                 // Zeroing is enough because the init value is the all-zero value
4928                 init_val = nullptr;
4929               } else {
4930                 init_val = init_val->as_InlineType()->buffer(this);
4931               }
4932             }
4933             // TODO 8350865 Should we add a check of the init_val type (maybe in debug only + halt)?
4934           }
4935           Node* obj = new_array(makecon(array_klass_type), length, 0, nullptr, false, init_val);
4936           const TypeAryPtr* arytype = gvn().type(obj)->is_aryptr();
4937           assert(arytype->is_null_free() == null_free, "inconsistency");
4938           assert(arytype->is_not_null_free() == !null_free, "inconsistency");
4939           set_result(obj);
4940           return true;
4941         }
4942       }
4943     }
4944   }
4945   return false;
4946 }
4947 
4948 // public static native boolean ValueClass::isFlatArray(Object array);
4949 // public static native boolean ValueClass::isNullRestrictedArray(Object array);
4950 // public static native boolean ValueClass::isAtomicArray(Object array);
4951 bool LibraryCallKit::inline_getArrayProperties(ArrayPropertiesCheck check) {
4952   Node* array = argument(0);
4953 
4954   Node* bol;
4955   switch(check) {
4956     case IsFlat:
4957       // TODO 8350865 Use the object version here instead of loading the klass
4958       // 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
4959       bol = flat_array_test(load_object_klass(array));
4960       break;
4961     case IsNullRestricted:
4962       bol = null_free_array_test(array);
4963       break;
4964     case IsAtomic:
4965       // TODO 8350865 Implement this. It's a bit more complicated, see conditions in JVM_IsAtomicArray
4966       // Enable TestIntrinsics::test87/88 once this is implemented
4967       // bol = null_free_atomic_array_test
4968       return false;
4969     default:
4970       ShouldNotReachHere();
4971   }
4972 
4973   Node* res = gvn().transform(new CMoveINode(bol, intcon(0), intcon(1), TypeInt::BOOL));
4974   set_result(res);
4975   return true;
4976 }
4977 
4978 // Load the default refined array klass from an ObjArrayKlass. This relies on the first entry in the
4979 // '_next_refined_array_klass' linked list being the default (see ObjArrayKlass::klass_with_properties).
4980 Node* LibraryCallKit::load_default_refined_array_klass(Node* klass_node, bool type_array_guard) {
4981   RegionNode* region = new RegionNode(2);
4982   Node* phi = new PhiNode(region, TypeInstKlassPtr::OBJECT_OR_NULL);
4983 
4984   if (type_array_guard) {
4985     generate_typeArray_guard(klass_node, region);
4986     if (region->req() == 3) {
4987       phi->add_req(klass_node);
4988     }
4989   }
4990   Node* adr_refined_klass = basic_plus_adr(klass_node, in_bytes(ObjArrayKlass::next_refined_array_klass_offset()));
4991   Node* refined_klass = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), adr_refined_klass, TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
4992 
4993   // Can be null if not initialized yet, just deopt
4994   Node* null_ctl = top();
4995   refined_klass = null_check_oop(refined_klass, &null_ctl, /* never_see_null= */ true);
4996 
4997   region->init_req(1, control());
4998   phi->init_req(1, refined_klass);
4999 
5000   set_control(_gvn.transform(region));
5001   return _gvn.transform(phi);
5002 }
5003 
5004 // Load the non-refined array klass from an ObjArrayKlass.
5005 Node* LibraryCallKit::load_non_refined_array_klass(Node* klass_node) {
5006   const TypeAryKlassPtr* ary_klass_ptr = _gvn.type(klass_node)->isa_aryklassptr();
5007   if (ary_klass_ptr != nullptr && ary_klass_ptr->klass_is_exact()) {
5008     return _gvn.makecon(ary_klass_ptr->cast_to_refined_array_klass_ptr(false));
5009   }
5010 
5011   RegionNode* region = new RegionNode(2);
5012   Node* phi = new PhiNode(region, TypeInstKlassPtr::OBJECT);
5013 
5014   generate_typeArray_guard(klass_node, region);
5015   if (region->req() == 3) {
5016     phi->add_req(klass_node);
5017   }
5018   Node* super_adr = basic_plus_adr(klass_node, in_bytes(Klass::super_offset()));
5019   Node* super_klass = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), super_adr, TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT));
5020 
5021   region->init_req(1, control());
5022   phi->init_req(1, super_klass);
5023 
5024   set_control(_gvn.transform(region));
5025   return _gvn.transform(phi);
5026 }
5027 
5028 //-----------------------inline_native_newArray--------------------------
5029 // private static native Object java.lang.reflect.Array.newArray(Class<?> componentType, int length);
5030 // private        native Object Unsafe.allocateUninitializedArray0(Class<?> cls, int size);
5031 bool LibraryCallKit::inline_unsafe_newArray(bool uninitialized) {
5032   Node* mirror;
5033   Node* count_val;
5034   if (uninitialized) {
5035     null_check_receiver();
5036     mirror    = argument(1);
5037     count_val = argument(2);
5038   } else {
5039     mirror    = argument(0);
5040     count_val = argument(1);
5041   }
5042 
5043   mirror = null_check(mirror);
5044   // If mirror or obj is dead, only null-path is taken.
5045   if (stopped())  return true;
5046 
5047   enum { _normal_path = 1, _slow_path = 2, PATH_LIMIT };
5048   RegionNode* result_reg = new RegionNode(PATH_LIMIT);
5049   PhiNode*    result_val = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
5050   PhiNode*    result_io  = new PhiNode(result_reg, Type::ABIO);
5051   PhiNode*    result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
5052 
5053   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
5054   Node* klass_node = load_array_klass_from_mirror(mirror, never_see_null,
5055                                                   result_reg, _slow_path);
5056   Node* normal_ctl   = control();
5057   Node* no_array_ctl = result_reg->in(_slow_path);
5058 
5059   // Generate code for the slow case.  We make a call to newArray().
5060   set_control(no_array_ctl);
5061   if (!stopped()) {
5062     // Either the input type is void.class, or else the
5063     // array klass has not yet been cached.  Either the
5064     // ensuing call will throw an exception, or else it
5065     // will cache the array klass for next time.
5066     PreserveJVMState pjvms(this);
5067     CallJavaNode* slow_call = nullptr;
5068     if (uninitialized) {
5069       // Generate optimized virtual call (holder class 'Unsafe' is final)
5070       slow_call = generate_method_call(vmIntrinsics::_allocateUninitializedArray, false, false, true);
5071     } else {
5072       slow_call = generate_method_call_static(vmIntrinsics::_newArray, true);
5073     }
5074     Node* slow_result = set_results_for_java_call(slow_call);
5075     // this->control() comes from set_results_for_java_call
5076     result_reg->set_req(_slow_path, control());
5077     result_val->set_req(_slow_path, slow_result);
5078     result_io ->set_req(_slow_path, i_o());
5079     result_mem->set_req(_slow_path, reset_memory());
5080   }
5081 
5082   set_control(normal_ctl);
5083   if (!stopped()) {
5084     // Normal case:  The array type has been cached in the java.lang.Class.
5085     // The following call works fine even if the array type is polymorphic.
5086     // It could be a dynamic mix of int[], boolean[], Object[], etc.
5087 
5088     klass_node = load_default_refined_array_klass(klass_node);
5089 
5090     Node* obj = new_array(klass_node, count_val, 0);  // no arguments to push
5091     result_reg->init_req(_normal_path, control());
5092     result_val->init_req(_normal_path, obj);
5093     result_io ->init_req(_normal_path, i_o());
5094     result_mem->init_req(_normal_path, reset_memory());
5095 
5096     if (uninitialized) {
5097       // Mark the allocation so that zeroing is skipped
5098       AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(obj);
5099       alloc->maybe_set_complete(&_gvn);
5100     }
5101   }
5102 
5103   // Return the combined state.
5104   set_i_o(        _gvn.transform(result_io)  );
5105   set_all_memory( _gvn.transform(result_mem));
5106 
5107   C->set_has_split_ifs(true); // Has chance for split-if optimization
5108   set_result(result_reg, result_val);
5109   return true;
5110 }
5111 
5112 //----------------------inline_native_getLength--------------------------
5113 // public static native int java.lang.reflect.Array.getLength(Object array);
5114 bool LibraryCallKit::inline_native_getLength() {
5115   if (too_many_traps(Deoptimization::Reason_intrinsic))  return false;
5116 
5117   Node* array = null_check(argument(0));
5118   // If array is dead, only null-path is taken.
5119   if (stopped())  return true;
5120 
5121   // Deoptimize if it is a non-array.
5122   Node* non_array = generate_non_array_guard(load_object_klass(array), nullptr, &array);
5123 
5124   if (non_array != nullptr) {
5125     PreserveJVMState pjvms(this);
5126     set_control(non_array);
5127     uncommon_trap(Deoptimization::Reason_intrinsic,
5128                   Deoptimization::Action_maybe_recompile);
5129   }
5130 
5131   // If control is dead, only non-array-path is taken.
5132   if (stopped())  return true;
5133 
5134   // The works fine even if the array type is polymorphic.
5135   // It could be a dynamic mix of int[], boolean[], Object[], etc.
5136   Node* result = load_array_length(array);
5137 
5138   C->set_has_split_ifs(true);  // Has chance for split-if optimization
5139   set_result(result);
5140   return true;
5141 }
5142 
5143 //------------------------inline_array_copyOf----------------------------
5144 // public static <T,U> T[] java.util.Arrays.copyOf(     U[] original, int newLength,         Class<? extends T[]> newType);
5145 // public static <T,U> T[] java.util.Arrays.copyOfRange(U[] original, int from,      int to, Class<? extends T[]> newType);
5146 bool LibraryCallKit::inline_array_copyOf(bool is_copyOfRange) {
5147   if (too_many_traps(Deoptimization::Reason_intrinsic))  return false;
5148 
5149   // Get the arguments.
5150   Node* original          = argument(0);
5151   Node* start             = is_copyOfRange? argument(1): intcon(0);
5152   Node* end               = is_copyOfRange? argument(2): argument(1);
5153   Node* array_type_mirror = is_copyOfRange? argument(3): argument(2);
5154 
5155   Node* newcopy = nullptr;
5156 
5157   // Set the original stack and the reexecute bit for the interpreter to reexecute
5158   // the bytecode that invokes Arrays.copyOf if deoptimization happens.
5159   { PreserveReexecuteState preexecs(this);
5160     jvms()->set_should_reexecute(true);
5161 
5162     array_type_mirror = null_check(array_type_mirror);
5163     original          = null_check(original);
5164 
5165     // Check if a null path was taken unconditionally.
5166     if (stopped())  return true;
5167 
5168     Node* orig_length = load_array_length(original);
5169 
5170     Node* klass_node = load_klass_from_mirror(array_type_mirror, false, nullptr, 0);
5171     klass_node = null_check(klass_node);
5172 
5173     RegionNode* bailout = new RegionNode(1);
5174     record_for_igvn(bailout);
5175 
5176     // Despite the generic type of Arrays.copyOf, the mirror might be int, int[], etc.
5177     // Bail out if that is so.
5178     // Inline type array may have object field that would require a
5179     // write barrier. Conservatively, go to slow path.
5180     // TODO 8251971: Optimize for the case when flat src/dst are later found
5181     // to not contain oops (i.e., move this check to the macro expansion phase).
5182     BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
5183     const TypeAryPtr* orig_t = _gvn.type(original)->isa_aryptr();
5184     const TypeKlassPtr* tklass = _gvn.type(klass_node)->is_klassptr();
5185     bool exclude_flat = UseArrayFlattening && bs->array_copy_requires_gc_barriers(true, T_OBJECT, false, false, BarrierSetC2::Parsing) &&
5186                         // Can src array be flat and contain oops?
5187                         (orig_t == nullptr || (!orig_t->is_not_flat() && (!orig_t->is_flat() || orig_t->elem()->inline_klass()->contains_oops()))) &&
5188                         // Can dest array be flat and contain oops?
5189                         tklass->can_be_inline_array() && (!tklass->is_flat() || tklass->is_aryklassptr()->elem()->is_instklassptr()->instance_klass()->as_inline_klass()->contains_oops());
5190     Node* not_objArray = exclude_flat ? generate_non_refArray_guard(klass_node, bailout) : generate_typeArray_guard(klass_node, bailout);
5191 
5192     Node* refined_klass_node = load_default_refined_array_klass(klass_node, /* type_array_guard= */ false);
5193 
5194     if (not_objArray != nullptr) {
5195       // Improve the klass node's type from the new optimistic assumption:
5196       ciKlass* ak = ciArrayKlass::make(env()->Object_klass());
5197       bool not_flat = !UseArrayFlattening;
5198       bool not_null_free = !Arguments::is_valhalla_enabled();
5199       const Type* akls = TypeAryKlassPtr::make(TypePtr::NotNull, ak, Type::Offset(0), Type::trust_interfaces, not_flat, not_null_free, false, false, not_flat, true);
5200       Node* cast = new CastPPNode(control(), refined_klass_node, akls);
5201       refined_klass_node = _gvn.transform(cast);
5202     }
5203 
5204     // Bail out if either start or end is negative.
5205     generate_negative_guard(start, bailout, &start);
5206     generate_negative_guard(end,   bailout, &end);
5207 
5208     Node* length = end;
5209     if (_gvn.type(start) != TypeInt::ZERO) {
5210       length = _gvn.transform(new SubINode(end, start));
5211     }
5212 
5213     // Bail out if length is negative (i.e., if start > end).
5214     // Without this the new_array would throw
5215     // NegativeArraySizeException but IllegalArgumentException is what
5216     // should be thrown
5217     generate_negative_guard(length, bailout, &length);
5218 
5219     // Handle inline type arrays
5220     bool can_validate = !too_many_traps(Deoptimization::Reason_class_check);
5221     if (!stopped()) {
5222       // TODO 8251971
5223       if (!orig_t->is_null_free()) {
5224         // Not statically known to be null free, add a check
5225         generate_fair_guard(null_free_array_test(original), bailout);
5226       }
5227       orig_t = _gvn.type(original)->isa_aryptr();
5228       if (orig_t != nullptr && orig_t->is_flat()) {
5229         // Src is flat, check that dest is flat as well
5230         if (exclude_flat) {
5231           // Dest can't be flat, bail out
5232           bailout->add_req(control());
5233           set_control(top());
5234         } else {
5235           generate_fair_guard(flat_array_test(refined_klass_node, /* flat = */ false), bailout);
5236         }
5237         // TODO 8350865 This is not correct anymore. Write tests and fix logic similar to arraycopy.
5238       } else if (UseArrayFlattening && (orig_t == nullptr || !orig_t->is_not_flat()) &&
5239                  // If dest is flat, src must be flat as well (guaranteed by src <: dest check if validated).
5240                  ((!tklass->is_flat() && tklass->can_be_inline_array()) || !can_validate)) {
5241         // Src might be flat and dest might not be flat. Go to the slow path if src is flat.
5242         // TODO 8251971: Optimize for the case when src/dest are later found to be both flat.
5243         generate_fair_guard(flat_array_test(load_object_klass(original)), bailout);
5244         if (orig_t != nullptr) {
5245           orig_t = orig_t->cast_to_not_flat();
5246           original = _gvn.transform(new CheckCastPPNode(control(), original, orig_t));
5247         }
5248       }
5249       if (!can_validate) {
5250         // No validation. The subtype check emitted at macro expansion time will not go to the slow
5251         // path but call checkcast_arraycopy which can not handle flat/null-free inline type arrays.
5252         // TODO 8251971: Optimize for the case when src/dest are later found to be both flat/null-free.
5253         generate_fair_guard(flat_array_test(refined_klass_node), bailout);
5254         generate_fair_guard(null_free_array_test(original), bailout);
5255       }
5256     }
5257 
5258     // Bail out if start is larger than the original length
5259     Node* orig_tail = _gvn.transform(new SubINode(orig_length, start));
5260     generate_negative_guard(orig_tail, bailout, &orig_tail);
5261 
5262     if (bailout->req() > 1) {
5263       PreserveJVMState pjvms(this);
5264       set_control(_gvn.transform(bailout));
5265       uncommon_trap(Deoptimization::Reason_intrinsic,
5266                     Deoptimization::Action_maybe_recompile);
5267     }
5268 
5269     if (!stopped()) {
5270       // How many elements will we copy from the original?
5271       // The answer is MinI(orig_tail, length).
5272       Node* moved = _gvn.transform(new MinINode(orig_tail, length));
5273 
5274       // Generate a direct call to the right arraycopy function(s).
5275       // We know the copy is disjoint but we might not know if the
5276       // oop stores need checking.
5277       // Extreme case:  Arrays.copyOf((Integer[])x, 10, String[].class).
5278       // This will fail a store-check if x contains any non-nulls.
5279 
5280       // ArrayCopyNode:Ideal may transform the ArrayCopyNode to
5281       // loads/stores but it is legal only if we're sure the
5282       // Arrays.copyOf would succeed. So we need all input arguments
5283       // to the copyOf to be validated, including that the copy to the
5284       // new array won't trigger an ArrayStoreException. That subtype
5285       // check can be optimized if we know something on the type of
5286       // the input array from type speculation.
5287       if (_gvn.type(klass_node)->singleton()) {
5288         const TypeKlassPtr* subk = _gvn.type(load_object_klass(original))->is_klassptr();
5289         const TypeKlassPtr* superk = _gvn.type(klass_node)->is_klassptr();
5290 
5291         int test = C->static_subtype_check(superk, subk);
5292         if (test != Compile::SSC_always_true && test != Compile::SSC_always_false) {
5293           const TypeOopPtr* t_original = _gvn.type(original)->is_oopptr();
5294           if (t_original->speculative_type() != nullptr) {
5295             original = maybe_cast_profiled_obj(original, t_original->speculative_type(), true);
5296           }
5297         }
5298       }
5299 
5300       bool validated = false;
5301       // Reason_class_check rather than Reason_intrinsic because we
5302       // want to intrinsify even if this traps.
5303       if (can_validate) {
5304         Node* not_subtype_ctrl = gen_subtype_check(original, klass_node);
5305 
5306         if (not_subtype_ctrl != top()) {
5307           PreserveJVMState pjvms(this);
5308           set_control(not_subtype_ctrl);
5309           uncommon_trap(Deoptimization::Reason_class_check,
5310                         Deoptimization::Action_make_not_entrant);
5311           assert(stopped(), "Should be stopped");
5312         }
5313         validated = true;
5314       }
5315 
5316       if (!stopped()) {
5317         newcopy = new_array(refined_klass_node, length, 0);  // no arguments to push
5318 
5319         ArrayCopyNode* ac = ArrayCopyNode::make(this, true, original, start, newcopy, intcon(0), moved, true, true,
5320                                                 load_object_klass(original), klass_node);
5321         if (!is_copyOfRange) {
5322           ac->set_copyof(validated);
5323         } else {
5324           ac->set_copyofrange(validated);
5325         }
5326         Node* n = _gvn.transform(ac);
5327         if (n == ac) {
5328           ac->connect_outputs(this);
5329         } else {
5330           assert(validated, "shouldn't transform if all arguments not validated");
5331           set_all_memory(n);
5332         }
5333       }
5334     }
5335   } // original reexecute is set back here
5336 
5337   C->set_has_split_ifs(true); // Has chance for split-if optimization
5338   if (!stopped()) {
5339     set_result(newcopy);
5340   }
5341   return true;
5342 }
5343 
5344 
5345 //----------------------generate_virtual_guard---------------------------
5346 // Helper for hashCode and clone.  Peeks inside the vtable to avoid a call.
5347 Node* LibraryCallKit::generate_virtual_guard(Node* obj_klass,
5348                                              RegionNode* slow_region) {
5349   ciMethod* method = callee();
5350   int vtable_index = method->vtable_index();
5351   assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index,
5352          "bad index %d", vtable_index);
5353   // Get the Method* out of the appropriate vtable entry.
5354   int entry_offset  = in_bytes(Klass::vtable_start_offset()) +
5355                      vtable_index*vtableEntry::size_in_bytes() +
5356                      in_bytes(vtableEntry::method_offset());
5357   Node* entry_addr  = basic_plus_adr(obj_klass, entry_offset);
5358   Node* target_call = make_load(nullptr, entry_addr, TypePtr::NOTNULL, T_ADDRESS, MemNode::unordered);
5359 
5360   // Compare the target method with the expected method (e.g., Object.hashCode).
5361   const TypePtr* native_call_addr = TypeMetadataPtr::make(method);
5362 
5363   Node* native_call = makecon(native_call_addr);
5364   Node* chk_native  = _gvn.transform(new CmpPNode(target_call, native_call));
5365   Node* test_native = _gvn.transform(new BoolNode(chk_native, BoolTest::ne));
5366 
5367   return generate_slow_guard(test_native, slow_region);
5368 }
5369 
5370 //-----------------------generate_method_call----------------------------
5371 // Use generate_method_call to make a slow-call to the real
5372 // method if the fast path fails.  An alternative would be to
5373 // use a stub like OptoRuntime::slow_arraycopy_Java.
5374 // This only works for expanding the current library call,
5375 // not another intrinsic.  (E.g., don't use this for making an
5376 // arraycopy call inside of the copyOf intrinsic.)
5377 CallJavaNode*
5378 LibraryCallKit::generate_method_call(vmIntrinsicID method_id, bool is_virtual, bool is_static, bool res_not_null) {
5379   // When compiling the intrinsic method itself, do not use this technique.
5380   guarantee(callee() != C->method(), "cannot make slow-call to self");
5381 
5382   ciMethod* method = callee();
5383   // ensure the JVMS we have will be correct for this call
5384   guarantee(method_id == method->intrinsic_id(), "must match");
5385 
5386   const TypeFunc* tf = TypeFunc::make(method);
5387   if (res_not_null) {
5388     assert(tf->return_type() == T_OBJECT, "");
5389     const TypeTuple* range = tf->range_cc();
5390     const Type** fields = TypeTuple::fields(range->cnt());
5391     fields[TypeFunc::Parms] = range->field_at(TypeFunc::Parms)->filter_speculative(TypePtr::NOTNULL);
5392     const TypeTuple* new_range = TypeTuple::make(range->cnt(), fields);
5393     tf = TypeFunc::make(tf->domain_cc(), new_range);
5394   }
5395   CallJavaNode* slow_call;
5396   if (is_static) {
5397     assert(!is_virtual, "");
5398     slow_call = new CallStaticJavaNode(C, tf,
5399                            SharedRuntime::get_resolve_static_call_stub(), method);
5400   } else if (is_virtual) {
5401     assert(!gvn().type(argument(0))->maybe_null(), "should not be null");
5402     int vtable_index = Method::invalid_vtable_index;
5403     if (UseInlineCaches) {
5404       // Suppress the vtable call
5405     } else {
5406       // hashCode and clone are not a miranda methods,
5407       // so the vtable index is fixed.
5408       // No need to use the linkResolver to get it.
5409        vtable_index = method->vtable_index();
5410        assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index,
5411               "bad index %d", vtable_index);
5412     }
5413     slow_call = new CallDynamicJavaNode(tf,
5414                           SharedRuntime::get_resolve_virtual_call_stub(),
5415                           method, vtable_index);
5416   } else {  // neither virtual nor static:  opt_virtual
5417     assert(!gvn().type(argument(0))->maybe_null(), "should not be null");
5418     slow_call = new CallStaticJavaNode(C, tf,
5419                                 SharedRuntime::get_resolve_opt_virtual_call_stub(), method);
5420     slow_call->set_optimized_virtual(true);
5421   }
5422   if (CallGenerator::is_inlined_method_handle_intrinsic(this->method(), bci(), callee())) {
5423     // To be able to issue a direct call (optimized virtual or virtual)
5424     // and skip a call to MH.linkTo*/invokeBasic adapter, additional information
5425     // about the method being invoked should be attached to the call site to
5426     // make resolution logic work (see SharedRuntime::resolve_{virtual,opt_virtual}_call_C).
5427     slow_call->set_override_symbolic_info(true);
5428   }
5429   set_arguments_for_java_call(slow_call);
5430   set_edges_for_java_call(slow_call);
5431   return slow_call;
5432 }
5433 
5434 
5435 /**
5436  * Build special case code for calls to hashCode on an object. This call may
5437  * be virtual (invokevirtual) or bound (invokespecial). For each case we generate
5438  * slightly different code.
5439  */
5440 bool LibraryCallKit::inline_native_hashcode(bool is_virtual, bool is_static) {
5441   assert(is_static == callee()->is_static(), "correct intrinsic selection");
5442   assert(!(is_virtual && is_static), "either virtual, special, or static");
5443 
5444   enum { _slow_path = 1, _fast_path, _null_path, PATH_LIMIT };
5445 
5446   RegionNode* result_reg = new RegionNode(PATH_LIMIT);
5447   PhiNode*    result_val = new PhiNode(result_reg, TypeInt::INT);
5448   PhiNode*    result_io  = new PhiNode(result_reg, Type::ABIO);
5449   PhiNode*    result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
5450   Node* obj = argument(0);
5451 
5452   // Don't intrinsify hashcode on inline types for now.
5453   // The "is locked" runtime check also subsumes the inline type check (as inline types cannot be locked) and goes to the slow path.
5454   if (gvn().type(obj)->is_inlinetypeptr()) {
5455     return false;
5456   }
5457 
5458   if (!is_static) {
5459     // Check for hashing null object
5460     obj = null_check_receiver();
5461     if (stopped())  return true;        // unconditionally null
5462     result_reg->init_req(_null_path, top());
5463     result_val->init_req(_null_path, top());
5464   } else {
5465     // Do a null check, and return zero if null.
5466     // System.identityHashCode(null) == 0
5467     Node* null_ctl = top();
5468     obj = null_check_oop(obj, &null_ctl);
5469     result_reg->init_req(_null_path, null_ctl);
5470     result_val->init_req(_null_path, _gvn.intcon(0));
5471   }
5472 
5473   // Unconditionally null?  Then return right away.
5474   if (stopped()) {
5475     set_control( result_reg->in(_null_path));
5476     if (!stopped())
5477       set_result(result_val->in(_null_path));
5478     return true;
5479   }
5480 
5481   // We only go to the fast case code if we pass a number of guards.  The
5482   // paths which do not pass are accumulated in the slow_region.
5483   RegionNode* slow_region = new RegionNode(1);
5484   record_for_igvn(slow_region);
5485 
5486   // If this is a virtual call, we generate a funny guard.  We pull out
5487   // the vtable entry corresponding to hashCode() from the target object.
5488   // If the target method which we are calling happens to be the native
5489   // Object hashCode() method, we pass the guard.  We do not need this
5490   // guard for non-virtual calls -- the caller is known to be the native
5491   // Object hashCode().
5492   if (is_virtual) {
5493     // After null check, get the object's klass.
5494     Node* obj_klass = load_object_klass(obj);
5495     generate_virtual_guard(obj_klass, slow_region);
5496   }
5497 
5498   // Get the header out of the object, use LoadMarkNode when available
5499   Node* header_addr = basic_plus_adr(obj, oopDesc::mark_offset_in_bytes());
5500   // The control of the load must be null. Otherwise, the load can move before
5501   // the null check after castPP removal.
5502   Node* no_ctrl = nullptr;
5503   Node* header = make_load(no_ctrl, header_addr, TypeX_X, TypeX_X->basic_type(), MemNode::unordered);
5504 
5505   if (!UseObjectMonitorTable) {
5506     // Test the header to see if it is safe to read w.r.t. locking.
5507     // We cannot use the inline type mask as this may check bits that are overriden
5508     // by an object monitor's pointer when inflating locking.
5509     Node *lock_mask      = _gvn.MakeConX(markWord::lock_mask_in_place);
5510     Node *lmasked_header = _gvn.transform(new AndXNode(header, lock_mask));
5511     Node *monitor_val   = _gvn.MakeConX(markWord::monitor_value);
5512     Node *chk_monitor   = _gvn.transform(new CmpXNode(lmasked_header, monitor_val));
5513     Node *test_monitor  = _gvn.transform(new BoolNode(chk_monitor, BoolTest::eq));
5514 
5515     generate_slow_guard(test_monitor, slow_region);
5516   }
5517 
5518   // Get the hash value and check to see that it has been properly assigned.
5519   // We depend on hash_mask being at most 32 bits and avoid the use of
5520   // hash_mask_in_place because it could be larger than 32 bits in a 64-bit
5521   // vm: see markWord.hpp.
5522   Node *hash_mask      = _gvn.intcon(markWord::hash_mask);
5523   Node *hash_shift     = _gvn.intcon(markWord::hash_shift);
5524   Node *hshifted_header= _gvn.transform(new URShiftXNode(header, hash_shift));
5525   // This hack lets the hash bits live anywhere in the mark object now, as long
5526   // as the shift drops the relevant bits into the low 32 bits.  Note that
5527   // Java spec says that HashCode is an int so there's no point in capturing
5528   // an 'X'-sized hashcode (32 in 32-bit build or 64 in 64-bit build).
5529   hshifted_header      = ConvX2I(hshifted_header);
5530   Node *hash_val       = _gvn.transform(new AndINode(hshifted_header, hash_mask));
5531 
5532   Node *no_hash_val    = _gvn.intcon(markWord::no_hash);
5533   Node *chk_assigned   = _gvn.transform(new CmpINode( hash_val, no_hash_val));
5534   Node *test_assigned  = _gvn.transform(new BoolNode( chk_assigned, BoolTest::eq));
5535 
5536   generate_slow_guard(test_assigned, slow_region);
5537 
5538   Node* init_mem = reset_memory();
5539   // fill in the rest of the null path:
5540   result_io ->init_req(_null_path, i_o());
5541   result_mem->init_req(_null_path, init_mem);
5542 
5543   result_val->init_req(_fast_path, hash_val);
5544   result_reg->init_req(_fast_path, control());
5545   result_io ->init_req(_fast_path, i_o());
5546   result_mem->init_req(_fast_path, init_mem);
5547 
5548   // Generate code for the slow case.  We make a call to hashCode().
5549   set_control(_gvn.transform(slow_region));
5550   if (!stopped()) {
5551     // No need for PreserveJVMState, because we're using up the present state.
5552     set_all_memory(init_mem);
5553     vmIntrinsics::ID hashCode_id = is_static ? vmIntrinsics::_identityHashCode : vmIntrinsics::_hashCode;
5554     CallJavaNode* slow_call = generate_method_call(hashCode_id, is_virtual, is_static, false);
5555     Node* slow_result = set_results_for_java_call(slow_call);
5556     // this->control() comes from set_results_for_java_call
5557     result_reg->init_req(_slow_path, control());
5558     result_val->init_req(_slow_path, slow_result);
5559     result_io  ->set_req(_slow_path, i_o());
5560     result_mem ->set_req(_slow_path, reset_memory());
5561   }
5562 
5563   // Return the combined state.
5564   set_i_o(        _gvn.transform(result_io)  );
5565   set_all_memory( _gvn.transform(result_mem));
5566 
5567   set_result(result_reg, result_val);
5568   return true;
5569 }
5570 
5571 //---------------------------inline_native_getClass----------------------------
5572 // public final native Class<?> java.lang.Object.getClass();
5573 //
5574 // Build special case code for calls to getClass on an object.
5575 bool LibraryCallKit::inline_native_getClass() {
5576   Node* obj = argument(0);
5577   if (obj->is_InlineType()) {
5578     const Type* t = _gvn.type(obj);
5579     if (t->maybe_null()) {
5580       null_check(obj);
5581     }
5582     set_result(makecon(TypeInstPtr::make(t->inline_klass()->java_mirror())));
5583     return true;
5584   }
5585   obj = null_check_receiver();
5586   if (stopped())  return true;
5587   set_result(load_mirror_from_klass(load_object_klass(obj)));
5588   return true;
5589 }
5590 
5591 //-----------------inline_native_Reflection_getCallerClass---------------------
5592 // public static native Class<?> sun.reflect.Reflection.getCallerClass();
5593 //
5594 // In the presence of deep enough inlining, getCallerClass() becomes a no-op.
5595 //
5596 // NOTE: This code must perform the same logic as JVM_GetCallerClass
5597 // in that it must skip particular security frames and checks for
5598 // caller sensitive methods.
5599 bool LibraryCallKit::inline_native_Reflection_getCallerClass() {
5600 #ifndef PRODUCT
5601   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5602     tty->print_cr("Attempting to inline sun.reflect.Reflection.getCallerClass");
5603   }
5604 #endif
5605 
5606   if (!jvms()->has_method()) {
5607 #ifndef PRODUCT
5608     if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5609       tty->print_cr("  Bailing out because intrinsic was inlined at top level");
5610     }
5611 #endif
5612     return false;
5613   }
5614 
5615   // Walk back up the JVM state to find the caller at the required
5616   // depth.
5617   JVMState* caller_jvms = jvms();
5618 
5619   // Cf. JVM_GetCallerClass
5620   // NOTE: Start the loop at depth 1 because the current JVM state does
5621   // not include the Reflection.getCallerClass() frame.
5622   for (int n = 1; caller_jvms != nullptr; caller_jvms = caller_jvms->caller(), n++) {
5623     ciMethod* m = caller_jvms->method();
5624     switch (n) {
5625     case 0:
5626       fatal("current JVM state does not include the Reflection.getCallerClass frame");
5627       break;
5628     case 1:
5629       // Frame 0 and 1 must be caller sensitive (see JVM_GetCallerClass).
5630       if (!m->caller_sensitive()) {
5631 #ifndef PRODUCT
5632         if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5633           tty->print_cr("  Bailing out: CallerSensitive annotation expected at frame %d", n);
5634         }
5635 #endif
5636         return false;  // bail-out; let JVM_GetCallerClass do the work
5637       }
5638       break;
5639     default:
5640       if (!m->is_ignored_by_security_stack_walk()) {
5641         // We have reached the desired frame; return the holder class.
5642         // Acquire method holder as java.lang.Class and push as constant.
5643         ciInstanceKlass* caller_klass = caller_jvms->method()->holder();
5644         ciInstance* caller_mirror = caller_klass->java_mirror();
5645         set_result(makecon(TypeInstPtr::make(caller_mirror)));
5646 
5647 #ifndef PRODUCT
5648         if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5649           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());
5650           tty->print_cr("  JVM state at this point:");
5651           for (int i = jvms()->depth(), n = 1; i >= 1; i--, n++) {
5652             ciMethod* m = jvms()->of_depth(i)->method();
5653             tty->print_cr("   %d) %s.%s", n, m->holder()->name()->as_utf8(), m->name()->as_utf8());
5654           }
5655         }
5656 #endif
5657         return true;
5658       }
5659       break;
5660     }
5661   }
5662 
5663 #ifndef PRODUCT
5664   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5665     tty->print_cr("  Bailing out because caller depth exceeded inlining depth = %d", jvms()->depth());
5666     tty->print_cr("  JVM state at this point:");
5667     for (int i = jvms()->depth(), n = 1; i >= 1; i--, n++) {
5668       ciMethod* m = jvms()->of_depth(i)->method();
5669       tty->print_cr("   %d) %s.%s", n, m->holder()->name()->as_utf8(), m->name()->as_utf8());
5670     }
5671   }
5672 #endif
5673 
5674   return false;  // bail-out; let JVM_GetCallerClass do the work
5675 }
5676 
5677 bool LibraryCallKit::inline_fp_conversions(vmIntrinsics::ID id) {
5678   Node* arg = argument(0);
5679   Node* result = nullptr;
5680 
5681   switch (id) {
5682   case vmIntrinsics::_floatToRawIntBits:    result = new MoveF2INode(arg);  break;
5683   case vmIntrinsics::_intBitsToFloat:       result = new MoveI2FNode(arg);  break;
5684   case vmIntrinsics::_doubleToRawLongBits:  result = new MoveD2LNode(arg);  break;
5685   case vmIntrinsics::_longBitsToDouble:     result = new MoveL2DNode(arg);  break;
5686   case vmIntrinsics::_floatToFloat16:       result = new ConvF2HFNode(arg); break;
5687   case vmIntrinsics::_float16ToFloat:       result = new ConvHF2FNode(arg); break;
5688 
5689   case vmIntrinsics::_doubleToLongBits: {
5690     // two paths (plus control) merge in a wood
5691     RegionNode *r = new RegionNode(3);
5692     Node *phi = new PhiNode(r, TypeLong::LONG);
5693 
5694     Node *cmpisnan = _gvn.transform(new CmpDNode(arg, arg));
5695     // Build the boolean node
5696     Node *bolisnan = _gvn.transform(new BoolNode(cmpisnan, BoolTest::ne));
5697 
5698     // Branch either way.
5699     // NaN case is less traveled, which makes all the difference.
5700     IfNode *ifisnan = create_and_xform_if(control(), bolisnan, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
5701     Node *opt_isnan = _gvn.transform(ifisnan);
5702     assert( opt_isnan->is_If(), "Expect an IfNode");
5703     IfNode *opt_ifisnan = (IfNode*)opt_isnan;
5704     Node *iftrue = _gvn.transform(new IfTrueNode(opt_ifisnan));
5705 
5706     set_control(iftrue);
5707 
5708     static const jlong nan_bits = CONST64(0x7ff8000000000000);
5709     Node *slow_result = longcon(nan_bits); // return NaN
5710     phi->init_req(1, _gvn.transform( slow_result ));
5711     r->init_req(1, iftrue);
5712 
5713     // Else fall through
5714     Node *iffalse = _gvn.transform(new IfFalseNode(opt_ifisnan));
5715     set_control(iffalse);
5716 
5717     phi->init_req(2, _gvn.transform(new MoveD2LNode(arg)));
5718     r->init_req(2, iffalse);
5719 
5720     // Post merge
5721     set_control(_gvn.transform(r));
5722     record_for_igvn(r);
5723 
5724     C->set_has_split_ifs(true); // Has chance for split-if optimization
5725     result = phi;
5726     assert(result->bottom_type()->isa_long(), "must be");
5727     break;
5728   }
5729 
5730   case vmIntrinsics::_floatToIntBits: {
5731     // two paths (plus control) merge in a wood
5732     RegionNode *r = new RegionNode(3);
5733     Node *phi = new PhiNode(r, TypeInt::INT);
5734 
5735     Node *cmpisnan = _gvn.transform(new CmpFNode(arg, arg));
5736     // Build the boolean node
5737     Node *bolisnan = _gvn.transform(new BoolNode(cmpisnan, BoolTest::ne));
5738 
5739     // Branch either way.
5740     // NaN case is less traveled, which makes all the difference.
5741     IfNode *ifisnan = create_and_xform_if(control(), bolisnan, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
5742     Node *opt_isnan = _gvn.transform(ifisnan);
5743     assert( opt_isnan->is_If(), "Expect an IfNode");
5744     IfNode *opt_ifisnan = (IfNode*)opt_isnan;
5745     Node *iftrue = _gvn.transform(new IfTrueNode(opt_ifisnan));
5746 
5747     set_control(iftrue);
5748 
5749     static const jint nan_bits = 0x7fc00000;
5750     Node *slow_result = makecon(TypeInt::make(nan_bits)); // return NaN
5751     phi->init_req(1, _gvn.transform( slow_result ));
5752     r->init_req(1, iftrue);
5753 
5754     // Else fall through
5755     Node *iffalse = _gvn.transform(new IfFalseNode(opt_ifisnan));
5756     set_control(iffalse);
5757 
5758     phi->init_req(2, _gvn.transform(new MoveF2INode(arg)));
5759     r->init_req(2, iffalse);
5760 
5761     // Post merge
5762     set_control(_gvn.transform(r));
5763     record_for_igvn(r);
5764 
5765     C->set_has_split_ifs(true); // Has chance for split-if optimization
5766     result = phi;
5767     assert(result->bottom_type()->isa_int(), "must be");
5768     break;
5769   }
5770 
5771   default:
5772     fatal_unexpected_iid(id);
5773     break;
5774   }
5775   set_result(_gvn.transform(result));
5776   return true;
5777 }
5778 
5779 bool LibraryCallKit::inline_fp_range_check(vmIntrinsics::ID id) {
5780   Node* arg = argument(0);
5781   Node* result = nullptr;
5782 
5783   switch (id) {
5784   case vmIntrinsics::_floatIsInfinite:
5785     result = new IsInfiniteFNode(arg);
5786     break;
5787   case vmIntrinsics::_floatIsFinite:
5788     result = new IsFiniteFNode(arg);
5789     break;
5790   case vmIntrinsics::_doubleIsInfinite:
5791     result = new IsInfiniteDNode(arg);
5792     break;
5793   case vmIntrinsics::_doubleIsFinite:
5794     result = new IsFiniteDNode(arg);
5795     break;
5796   default:
5797     fatal_unexpected_iid(id);
5798     break;
5799   }
5800   set_result(_gvn.transform(result));
5801   return true;
5802 }
5803 
5804 //----------------------inline_unsafe_copyMemory-------------------------
5805 // public native void Unsafe.copyMemory0(Object srcBase, long srcOffset, Object destBase, long destOffset, long bytes);
5806 
5807 static bool has_wide_mem(PhaseGVN& gvn, Node* addr, Node* base) {
5808   const TypeAryPtr* addr_t = gvn.type(addr)->isa_aryptr();
5809   const Type*       base_t = gvn.type(base);
5810 
5811   bool in_native = (base_t == TypePtr::NULL_PTR);
5812   bool in_heap   = !TypePtr::NULL_PTR->higher_equal(base_t);
5813   bool is_mixed  = !in_heap && !in_native;
5814 
5815   if (is_mixed) {
5816     return true; // mixed accesses can touch both on-heap and off-heap memory
5817   }
5818   if (in_heap) {
5819     bool is_prim_array = (addr_t != nullptr) && (addr_t->elem() != Type::BOTTOM);
5820     if (!is_prim_array) {
5821       // Though Unsafe.copyMemory() ensures at runtime for on-heap accesses that base is a primitive array,
5822       // there's not enough type information available to determine proper memory slice for it.
5823       return true;
5824     }
5825   }
5826   return false;
5827 }
5828 
5829 bool LibraryCallKit::inline_unsafe_copyMemory() {
5830   if (callee()->is_static())  return false;  // caller must have the capability!
5831   null_check_receiver();  // null-check receiver
5832   if (stopped())  return true;
5833 
5834   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
5835 
5836   Node* src_base =         argument(1);  // type: oop
5837   Node* src_off  = ConvL2X(argument(2)); // type: long
5838   Node* dst_base =         argument(4);  // type: oop
5839   Node* dst_off  = ConvL2X(argument(5)); // type: long
5840   Node* size     = ConvL2X(argument(7)); // type: long
5841 
5842   assert(Unsafe_field_offset_to_byte_offset(11) == 11,
5843          "fieldOffset must be byte-scaled");
5844 
5845   Node* src_addr = make_unsafe_address(src_base, src_off);
5846   Node* dst_addr = make_unsafe_address(dst_base, dst_off);
5847 
5848   Node* thread = _gvn.transform(new ThreadLocalNode());
5849   Node* doing_unsafe_access_addr = basic_plus_adr(top(), thread, in_bytes(JavaThread::doing_unsafe_access_offset()));
5850   BasicType doing_unsafe_access_bt = T_BYTE;
5851   assert((sizeof(bool) * CHAR_BIT) == 8, "not implemented");
5852 
5853   // update volatile field
5854   store_to_memory(control(), doing_unsafe_access_addr, intcon(1), doing_unsafe_access_bt, MemNode::unordered);
5855 
5856   int flags = RC_LEAF | RC_NO_FP;
5857 
5858   const TypePtr* dst_type = TypePtr::BOTTOM;
5859 
5860   // Adjust memory effects of the runtime call based on input values.
5861   if (!has_wide_mem(_gvn, src_addr, src_base) &&
5862       !has_wide_mem(_gvn, dst_addr, dst_base)) {
5863     dst_type = _gvn.type(dst_addr)->is_ptr(); // narrow out memory
5864 
5865     const TypePtr* src_type = _gvn.type(src_addr)->is_ptr();
5866     if (C->get_alias_index(src_type) == C->get_alias_index(dst_type)) {
5867       flags |= RC_NARROW_MEM; // narrow in memory
5868     }
5869   }
5870 
5871   // Call it.  Note that the length argument is not scaled.
5872   make_runtime_call(flags,
5873                     OptoRuntime::fast_arraycopy_Type(),
5874                     StubRoutines::unsafe_arraycopy(),
5875                     "unsafe_arraycopy",
5876                     dst_type,
5877                     src_addr, dst_addr, size XTOP);
5878 
5879   store_to_memory(control(), doing_unsafe_access_addr, intcon(0), doing_unsafe_access_bt, MemNode::unordered);
5880 
5881   return true;
5882 }
5883 
5884 // unsafe_setmemory(void *base, ulong offset, size_t length, char fill_value);
5885 // Fill 'length' bytes starting from 'base[offset]' with 'fill_value'
5886 bool LibraryCallKit::inline_unsafe_setMemory() {
5887   if (callee()->is_static())  return false;  // caller must have the capability!
5888   null_check_receiver();  // null-check receiver
5889   if (stopped())  return true;
5890 
5891   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
5892 
5893   Node* dst_base =         argument(1);  // type: oop
5894   Node* dst_off  = ConvL2X(argument(2)); // type: long
5895   Node* size     = ConvL2X(argument(4)); // type: long
5896   Node* byte     =         argument(6);  // type: byte
5897 
5898   assert(Unsafe_field_offset_to_byte_offset(11) == 11,
5899          "fieldOffset must be byte-scaled");
5900 
5901   Node* dst_addr = make_unsafe_address(dst_base, dst_off);
5902 
5903   Node* thread = _gvn.transform(new ThreadLocalNode());
5904   Node* doing_unsafe_access_addr = basic_plus_adr(top(), thread, in_bytes(JavaThread::doing_unsafe_access_offset()));
5905   BasicType doing_unsafe_access_bt = T_BYTE;
5906   assert((sizeof(bool) * CHAR_BIT) == 8, "not implemented");
5907 
5908   // update volatile field
5909   store_to_memory(control(), doing_unsafe_access_addr, intcon(1), doing_unsafe_access_bt, MemNode::unordered);
5910 
5911   int flags = RC_LEAF | RC_NO_FP;
5912 
5913   const TypePtr* dst_type = TypePtr::BOTTOM;
5914 
5915   // Adjust memory effects of the runtime call based on input values.
5916   if (!has_wide_mem(_gvn, dst_addr, dst_base)) {
5917     dst_type = _gvn.type(dst_addr)->is_ptr(); // narrow out memory
5918 
5919     flags |= RC_NARROW_MEM; // narrow in memory
5920   }
5921 
5922   // Call it.  Note that the length argument is not scaled.
5923   make_runtime_call(flags,
5924                     OptoRuntime::unsafe_setmemory_Type(),
5925                     StubRoutines::unsafe_setmemory(),
5926                     "unsafe_setmemory",
5927                     dst_type,
5928                     dst_addr, size XTOP, byte);
5929 
5930   store_to_memory(control(), doing_unsafe_access_addr, intcon(0), doing_unsafe_access_bt, MemNode::unordered);
5931 
5932   return true;
5933 }
5934 
5935 #undef XTOP
5936 
5937 //------------------------clone_coping-----------------------------------
5938 // Helper function for inline_native_clone.
5939 void LibraryCallKit::copy_to_clone(Node* obj, Node* alloc_obj, Node* obj_size, bool is_array) {
5940   assert(obj_size != nullptr, "");
5941   Node* raw_obj = alloc_obj->in(1);
5942   assert(alloc_obj->is_CheckCastPP() && raw_obj->is_Proj() && raw_obj->in(0)->is_Allocate(), "");
5943 
5944   AllocateNode* alloc = nullptr;
5945   if (ReduceBulkZeroing &&
5946       // If we are implementing an array clone without knowing its source type
5947       // (can happen when compiling the array-guarded branch of a reflective
5948       // Object.clone() invocation), initialize the array within the allocation.
5949       // This is needed because some GCs (e.g. ZGC) might fall back in this case
5950       // to a runtime clone call that assumes fully initialized source arrays.
5951       (!is_array || obj->get_ptr_type()->isa_aryptr() != nullptr)) {
5952     // We will be completely responsible for initializing this object -
5953     // mark Initialize node as complete.
5954     alloc = AllocateNode::Ideal_allocation(alloc_obj);
5955     // The object was just allocated - there should be no any stores!
5956     guarantee(alloc != nullptr && alloc->maybe_set_complete(&_gvn), "");
5957     // Mark as complete_with_arraycopy so that on AllocateNode
5958     // expansion, we know this AllocateNode is initialized by an array
5959     // copy and a StoreStore barrier exists after the array copy.
5960     alloc->initialization()->set_complete_with_arraycopy();
5961   }
5962 
5963   Node* size = _gvn.transform(obj_size);
5964   access_clone(obj, alloc_obj, size, is_array);
5965 
5966   // Do not let reads from the cloned object float above the arraycopy.
5967   if (alloc != nullptr) {
5968     // Do not let stores that initialize this object be reordered with
5969     // a subsequent store that would make this object accessible by
5970     // other threads.
5971     // Record what AllocateNode this StoreStore protects so that
5972     // escape analysis can go from the MemBarStoreStoreNode to the
5973     // AllocateNode and eliminate the MemBarStoreStoreNode if possible
5974     // based on the escape status of the AllocateNode.
5975     insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
5976   } else {
5977     insert_mem_bar(Op_MemBarCPUOrder);
5978   }
5979 }
5980 
5981 //------------------------inline_native_clone----------------------------
5982 // protected native Object java.lang.Object.clone();
5983 //
5984 // Here are the simple edge cases:
5985 //  null receiver => normal trap
5986 //  virtual and clone was overridden => slow path to out-of-line clone
5987 //  not cloneable or finalizer => slow path to out-of-line Object.clone
5988 //
5989 // The general case has two steps, allocation and copying.
5990 // Allocation has two cases, and uses GraphKit::new_instance or new_array.
5991 //
5992 // Copying also has two cases, oop arrays and everything else.
5993 // Oop arrays use arrayof_oop_arraycopy (same as System.arraycopy).
5994 // Everything else uses the tight inline loop supplied by CopyArrayNode.
5995 //
5996 // These steps fold up nicely if and when the cloned object's klass
5997 // can be sharply typed as an object array, a type array, or an instance.
5998 //
5999 bool LibraryCallKit::inline_native_clone(bool is_virtual) {
6000   PhiNode* result_val;
6001 
6002   // Set the reexecute bit for the interpreter to reexecute
6003   // the bytecode that invokes Object.clone if deoptimization happens.
6004   { PreserveReexecuteState preexecs(this);
6005     jvms()->set_should_reexecute(true);
6006 
6007     Node* obj = argument(0);
6008     obj = null_check_receiver();
6009     if (stopped())  return true;
6010 
6011     const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
6012     if (obj_type->is_inlinetypeptr()) {
6013       // If the object to clone is an inline type, we can simply return it (i.e. a nop) since inline types have
6014       // no identity.
6015       set_result(obj);
6016       return true;
6017     }
6018 
6019     // If we are going to clone an instance, we need its exact type to
6020     // know the number and types of fields to convert the clone to
6021     // loads/stores. Maybe a speculative type can help us.
6022     if (!obj_type->klass_is_exact() &&
6023         obj_type->speculative_type() != nullptr &&
6024         obj_type->speculative_type()->is_instance_klass() &&
6025         !obj_type->speculative_type()->is_inlinetype()) {
6026       ciInstanceKlass* spec_ik = obj_type->speculative_type()->as_instance_klass();
6027       if (spec_ik->nof_nonstatic_fields() <= ArrayCopyLoadStoreMaxElem &&
6028           !spec_ik->has_injected_fields()) {
6029         if (!obj_type->isa_instptr() ||
6030             obj_type->is_instptr()->instance_klass()->has_subklass()) {
6031           obj = maybe_cast_profiled_obj(obj, obj_type->speculative_type(), false);
6032         }
6033       }
6034     }
6035 
6036     // Conservatively insert a memory barrier on all memory slices.
6037     // Do not let writes into the original float below the clone.
6038     insert_mem_bar(Op_MemBarCPUOrder);
6039 
6040     // paths into result_reg:
6041     enum {
6042       _slow_path = 1,     // out-of-line call to clone method (virtual or not)
6043       _objArray_path,     // plain array allocation, plus arrayof_oop_arraycopy
6044       _array_path,        // plain array allocation, plus arrayof_long_arraycopy
6045       _instance_path,     // plain instance allocation, plus arrayof_long_arraycopy
6046       PATH_LIMIT
6047     };
6048     RegionNode* result_reg = new RegionNode(PATH_LIMIT);
6049     result_val             = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
6050     PhiNode*    result_i_o = new PhiNode(result_reg, Type::ABIO);
6051     PhiNode*    result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
6052     record_for_igvn(result_reg);
6053 
6054     Node* obj_klass = load_object_klass(obj);
6055     // We only go to the fast case code if we pass a number of guards.
6056     // The paths which do not pass are accumulated in the slow_region.
6057     RegionNode* slow_region = new RegionNode(1);
6058     record_for_igvn(slow_region);
6059 
6060     Node* array_obj = obj;
6061     Node* array_ctl = generate_array_guard(obj_klass, (RegionNode*)nullptr, &array_obj);
6062     if (array_ctl != nullptr) {
6063       // It's an array.
6064       PreserveJVMState pjvms(this);
6065       set_control(array_ctl);
6066 
6067       BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
6068       const TypeAryPtr* ary_ptr = obj_type->isa_aryptr();
6069       if (UseArrayFlattening && bs->array_copy_requires_gc_barriers(true, T_OBJECT, true, false, BarrierSetC2::Expansion) &&
6070           obj_type->can_be_inline_array() &&
6071           (ary_ptr == nullptr || (!ary_ptr->is_not_flat() && (!ary_ptr->is_flat() || ary_ptr->elem()->inline_klass()->contains_oops())))) {
6072         // Flat inline type array may have object field that would require a
6073         // write barrier. Conservatively, go to slow path.
6074         generate_fair_guard(flat_array_test(obj_klass), slow_region);
6075       }
6076 
6077       if (!stopped()) {
6078         Node* obj_length = load_array_length(array_obj);
6079         Node* array_size = nullptr; // Size of the array without object alignment padding.
6080         Node* alloc_obj = new_array(obj_klass, obj_length, 0, &array_size, /*deoptimize_on_exception=*/true);
6081 
6082         BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
6083         if (bs->array_copy_requires_gc_barriers(true, T_OBJECT, true, false, BarrierSetC2::Parsing)) {
6084           // If it is an oop array, it requires very special treatment,
6085           // because gc barriers are required when accessing the array.
6086           Node* is_obja = generate_refArray_guard(obj_klass, (RegionNode*)nullptr);
6087           if (is_obja != nullptr) {
6088             PreserveJVMState pjvms2(this);
6089             set_control(is_obja);
6090             // Generate a direct call to the right arraycopy function(s).
6091             // Clones are always tightly coupled.
6092             ArrayCopyNode* ac = ArrayCopyNode::make(this, true, array_obj, intcon(0), alloc_obj, intcon(0), obj_length, true, false);
6093             ac->set_clone_oop_array();
6094             Node* n = _gvn.transform(ac);
6095             assert(n == ac, "cannot disappear");
6096             ac->connect_outputs(this, /*deoptimize_on_exception=*/true);
6097 
6098             result_reg->init_req(_objArray_path, control());
6099             result_val->init_req(_objArray_path, alloc_obj);
6100             result_i_o ->set_req(_objArray_path, i_o());
6101             result_mem ->set_req(_objArray_path, reset_memory());
6102           }
6103         }
6104         // Otherwise, there are no barriers to worry about.
6105         // (We can dispense with card marks if we know the allocation
6106         //  comes out of eden (TLAB)...  In fact, ReduceInitialCardMarks
6107         //  causes the non-eden paths to take compensating steps to
6108         //  simulate a fresh allocation, so that no further
6109         //  card marks are required in compiled code to initialize
6110         //  the object.)
6111 
6112         if (!stopped()) {
6113           copy_to_clone(obj, alloc_obj, array_size, true);
6114 
6115           // Present the results of the copy.
6116           result_reg->init_req(_array_path, control());
6117           result_val->init_req(_array_path, alloc_obj);
6118           result_i_o ->set_req(_array_path, i_o());
6119           result_mem ->set_req(_array_path, reset_memory());
6120         }
6121       }
6122     }
6123 
6124     if (!stopped()) {
6125       // It's an instance (we did array above).  Make the slow-path tests.
6126       // If this is a virtual call, we generate a funny guard.  We grab
6127       // the vtable entry corresponding to clone() from the target object.
6128       // If the target method which we are calling happens to be the
6129       // Object clone() method, we pass the guard.  We do not need this
6130       // guard for non-virtual calls; the caller is known to be the native
6131       // Object clone().
6132       if (is_virtual) {
6133         generate_virtual_guard(obj_klass, slow_region);
6134       }
6135 
6136       // The object must be easily cloneable and must not have a finalizer.
6137       // Both of these conditions may be checked in a single test.
6138       // We could optimize the test further, but we don't care.
6139       generate_misc_flags_guard(obj_klass,
6140                                 // Test both conditions:
6141                                 KlassFlags::_misc_is_cloneable_fast | KlassFlags::_misc_has_finalizer,
6142                                 // Must be cloneable but not finalizer:
6143                                 KlassFlags::_misc_is_cloneable_fast,
6144                                 slow_region);
6145     }
6146 
6147     if (!stopped()) {
6148       // It's an instance, and it passed the slow-path tests.
6149       PreserveJVMState pjvms(this);
6150       Node* obj_size = nullptr; // Total object size, including object alignment padding.
6151       // Need to deoptimize on exception from allocation since Object.clone intrinsic
6152       // is reexecuted if deoptimization occurs and there could be problems when merging
6153       // exception state between multiple Object.clone versions (reexecute=true vs reexecute=false).
6154       Node* alloc_obj = new_instance(obj_klass, nullptr, &obj_size, /*deoptimize_on_exception=*/true);
6155 
6156       copy_to_clone(obj, alloc_obj, obj_size, false);
6157 
6158       // Present the results of the slow call.
6159       result_reg->init_req(_instance_path, control());
6160       result_val->init_req(_instance_path, alloc_obj);
6161       result_i_o ->set_req(_instance_path, i_o());
6162       result_mem ->set_req(_instance_path, reset_memory());
6163     }
6164 
6165     // Generate code for the slow case.  We make a call to clone().
6166     set_control(_gvn.transform(slow_region));
6167     if (!stopped()) {
6168       PreserveJVMState pjvms(this);
6169       CallJavaNode* slow_call = generate_method_call(vmIntrinsics::_clone, is_virtual, false, true);
6170       // We need to deoptimize on exception (see comment above)
6171       Node* slow_result = set_results_for_java_call(slow_call, false, /* deoptimize */ true);
6172       // this->control() comes from set_results_for_java_call
6173       result_reg->init_req(_slow_path, control());
6174       result_val->init_req(_slow_path, slow_result);
6175       result_i_o ->set_req(_slow_path, i_o());
6176       result_mem ->set_req(_slow_path, reset_memory());
6177     }
6178 
6179     // Return the combined state.
6180     set_control(    _gvn.transform(result_reg));
6181     set_i_o(        _gvn.transform(result_i_o));
6182     set_all_memory( _gvn.transform(result_mem));
6183   } // original reexecute is set back here
6184 
6185   set_result(_gvn.transform(result_val));
6186   return true;
6187 }
6188 
6189 // If we have a tightly coupled allocation, the arraycopy may take care
6190 // of the array initialization. If one of the guards we insert between
6191 // the allocation and the arraycopy causes a deoptimization, an
6192 // uninitialized array will escape the compiled method. To prevent that
6193 // we set the JVM state for uncommon traps between the allocation and
6194 // the arraycopy to the state before the allocation so, in case of
6195 // deoptimization, we'll reexecute the allocation and the
6196 // initialization.
6197 JVMState* LibraryCallKit::arraycopy_restore_alloc_state(AllocateArrayNode* alloc, int& saved_reexecute_sp) {
6198   if (alloc != nullptr) {
6199     ciMethod* trap_method = alloc->jvms()->method();
6200     int trap_bci = alloc->jvms()->bci();
6201 
6202     if (!C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_intrinsic) &&
6203         !C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_null_check)) {
6204       // Make sure there's no store between the allocation and the
6205       // arraycopy otherwise visible side effects could be rexecuted
6206       // in case of deoptimization and cause incorrect execution.
6207       bool no_interfering_store = true;
6208       Node* mem = alloc->in(TypeFunc::Memory);
6209       if (mem->is_MergeMem()) {
6210         for (MergeMemStream mms(merged_memory(), mem->as_MergeMem()); mms.next_non_empty2(); ) {
6211           Node* n = mms.memory();
6212           if (n != mms.memory2() && !(n->is_Proj() && n->in(0) == alloc->initialization())) {
6213             assert(n->is_Store(), "what else?");
6214             no_interfering_store = false;
6215             break;
6216           }
6217         }
6218       } else {
6219         for (MergeMemStream mms(merged_memory()); mms.next_non_empty(); ) {
6220           Node* n = mms.memory();
6221           if (n != mem && !(n->is_Proj() && n->in(0) == alloc->initialization())) {
6222             assert(n->is_Store(), "what else?");
6223             no_interfering_store = false;
6224             break;
6225           }
6226         }
6227       }
6228 
6229       if (no_interfering_store) {
6230         SafePointNode* sfpt = create_safepoint_with_state_before_array_allocation(alloc);
6231 
6232         JVMState* saved_jvms = jvms();
6233         saved_reexecute_sp = _reexecute_sp;
6234 
6235         set_jvms(sfpt->jvms());
6236         _reexecute_sp = jvms()->sp();
6237 
6238         return saved_jvms;
6239       }
6240     }
6241   }
6242   return nullptr;
6243 }
6244 
6245 // Clone the JVMState of the array allocation and create a new safepoint with it. Re-push the array length to the stack
6246 // such that uncommon traps can be emitted to re-execute the array allocation in the interpreter.
6247 SafePointNode* LibraryCallKit::create_safepoint_with_state_before_array_allocation(const AllocateArrayNode* alloc) const {
6248   JVMState* old_jvms = alloc->jvms()->clone_shallow(C);
6249   uint size = alloc->req();
6250   SafePointNode* sfpt = new SafePointNode(size, old_jvms);
6251   old_jvms->set_map(sfpt);
6252   for (uint i = 0; i < size; i++) {
6253     sfpt->init_req(i, alloc->in(i));
6254   }
6255   int adjustment = 1;
6256   const TypeAryKlassPtr* ary_klass_ptr = alloc->in(AllocateNode::KlassNode)->bottom_type()->is_aryklassptr();
6257   if (ary_klass_ptr->is_null_free()) {
6258     // A null-free, tightly coupled array allocation can only come from LibraryCallKit::inline_newArray which
6259     // also requires the componentType and initVal on stack for re-execution.
6260     // Re-create and push the componentType.
6261     ciArrayKlass* klass = ary_klass_ptr->exact_klass()->as_array_klass();
6262     ciInstance* instance = klass->component_mirror_instance();
6263     const TypeInstPtr* t_instance = TypeInstPtr::make(instance);
6264     sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp(), makecon(t_instance));
6265     adjustment++;
6266   }
6267   // re-push array length for deoptimization
6268   sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp() + adjustment - 1, alloc->in(AllocateNode::ALength));
6269   if (ary_klass_ptr->is_null_free()) {
6270     // Re-create and push the initVal.
6271     Node* init_val = alloc->in(AllocateNode::InitValue);
6272     if (init_val == nullptr) {
6273       init_val = InlineTypeNode::make_all_zero(_gvn, ary_klass_ptr->elem()->is_instklassptr()->instance_klass()->as_inline_klass());
6274     } else if (UseCompressedOops) {
6275       init_val = _gvn.transform(new DecodeNNode(init_val, init_val->bottom_type()->make_ptr()));
6276     }
6277     sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp() + adjustment, init_val);
6278     adjustment++;
6279   }
6280   old_jvms->set_sp(old_jvms->sp() + adjustment);
6281   old_jvms->set_monoff(old_jvms->monoff() + adjustment);
6282   old_jvms->set_scloff(old_jvms->scloff() + adjustment);
6283   old_jvms->set_endoff(old_jvms->endoff() + adjustment);
6284   old_jvms->set_should_reexecute(true);
6285 
6286   sfpt->set_i_o(map()->i_o());
6287   sfpt->set_memory(map()->memory());
6288   sfpt->set_control(map()->control());
6289   return sfpt;
6290 }
6291 
6292 // In case of a deoptimization, we restart execution at the
6293 // allocation, allocating a new array. We would leave an uninitialized
6294 // array in the heap that GCs wouldn't expect. Move the allocation
6295 // after the traps so we don't allocate the array if we
6296 // deoptimize. This is possible because tightly_coupled_allocation()
6297 // guarantees there's no observer of the allocated array at this point
6298 // and the control flow is simple enough.
6299 void LibraryCallKit::arraycopy_move_allocation_here(AllocateArrayNode* alloc, Node* dest, JVMState* saved_jvms_before_guards,
6300                                                     int saved_reexecute_sp, uint new_idx) {
6301   if (saved_jvms_before_guards != nullptr && !stopped()) {
6302     replace_unrelated_uncommon_traps_with_alloc_state(alloc, saved_jvms_before_guards);
6303 
6304     assert(alloc != nullptr, "only with a tightly coupled allocation");
6305     // restore JVM state to the state at the arraycopy
6306     saved_jvms_before_guards->map()->set_control(map()->control());
6307     assert(saved_jvms_before_guards->map()->memory() == map()->memory(), "memory state changed?");
6308     assert(saved_jvms_before_guards->map()->i_o() == map()->i_o(), "IO state changed?");
6309     // If we've improved the types of some nodes (null check) while
6310     // emitting the guards, propagate them to the current state
6311     map()->replaced_nodes().apply(saved_jvms_before_guards->map(), new_idx);
6312     set_jvms(saved_jvms_before_guards);
6313     _reexecute_sp = saved_reexecute_sp;
6314 
6315     // Remove the allocation from above the guards
6316     CallProjections* callprojs = alloc->extract_projections(true);
6317     InitializeNode* init = alloc->initialization();
6318     Node* alloc_mem = alloc->in(TypeFunc::Memory);
6319     C->gvn_replace_by(callprojs->fallthrough_ioproj, alloc->in(TypeFunc::I_O));
6320     init->replace_mem_projs_by(alloc_mem, C);
6321 
6322     // The CastIINode created in GraphKit::new_array (in AllocateArrayNode::make_ideal_length) must stay below
6323     // the allocation (i.e. is only valid if the allocation succeeds):
6324     // 1) replace CastIINode with AllocateArrayNode's length here
6325     // 2) Create CastIINode again once allocation has moved (see below) at the end of this method
6326     //
6327     // Multiple identical CastIINodes might exist here. Each GraphKit::load_array_length() call will generate
6328     // new separate CastIINode (arraycopy guard checks or any array length use between array allocation and ararycopy)
6329     Node* init_control = init->proj_out(TypeFunc::Control);
6330     Node* alloc_length = alloc->Ideal_length();
6331 #ifdef ASSERT
6332     Node* prev_cast = nullptr;
6333 #endif
6334     for (uint i = 0; i < init_control->outcnt(); i++) {
6335       Node* init_out = init_control->raw_out(i);
6336       if (init_out->is_CastII() && init_out->in(TypeFunc::Control) == init_control && init_out->in(1) == alloc_length) {
6337 #ifdef ASSERT
6338         if (prev_cast == nullptr) {
6339           prev_cast = init_out;
6340         } else {
6341           if (prev_cast->cmp(*init_out) == false) {
6342             prev_cast->dump();
6343             init_out->dump();
6344             assert(false, "not equal CastIINode");
6345           }
6346         }
6347 #endif
6348         C->gvn_replace_by(init_out, alloc_length);
6349       }
6350     }
6351     C->gvn_replace_by(init->proj_out(TypeFunc::Control), alloc->in(0));
6352 
6353     // move the allocation here (after the guards)
6354     _gvn.hash_delete(alloc);
6355     alloc->set_req(TypeFunc::Control, control());
6356     alloc->set_req(TypeFunc::I_O, i_o());
6357     Node *mem = reset_memory();
6358     set_all_memory(mem);
6359     alloc->set_req(TypeFunc::Memory, mem);
6360     set_control(init->proj_out_or_null(TypeFunc::Control));
6361     set_i_o(callprojs->fallthrough_ioproj);
6362 
6363     // Update memory as done in GraphKit::set_output_for_allocation()
6364     const TypeInt* length_type = _gvn.find_int_type(alloc->in(AllocateNode::ALength));
6365     const TypeOopPtr* ary_type = _gvn.type(alloc->in(AllocateNode::KlassNode))->is_klassptr()->as_instance_type();
6366     if (ary_type->isa_aryptr() && length_type != nullptr) {
6367       ary_type = ary_type->is_aryptr()->cast_to_size(length_type);
6368     }
6369     const TypePtr* telemref = ary_type->add_offset(Type::OffsetBot);
6370     int            elemidx  = C->get_alias_index(telemref);
6371     // Need to properly move every memory projection for the Initialize
6372 #ifdef ASSERT
6373     int mark_idx = C->get_alias_index(ary_type->add_offset(oopDesc::mark_offset_in_bytes()));
6374     int klass_idx = C->get_alias_index(ary_type->add_offset(oopDesc::klass_offset_in_bytes()));
6375 #endif
6376     auto move_proj = [&](ProjNode* proj) {
6377       int alias_idx = C->get_alias_index(proj->adr_type());
6378       assert(alias_idx == Compile::AliasIdxRaw ||
6379              alias_idx == elemidx ||
6380              alias_idx == mark_idx ||
6381              alias_idx == klass_idx, "should be raw memory or array element type");
6382       set_memory(proj, alias_idx);
6383     };
6384     init->for_each_proj(move_proj, TypeFunc::Memory);
6385 
6386     Node* allocx = _gvn.transform(alloc);
6387     assert(allocx == alloc, "where has the allocation gone?");
6388     assert(dest->is_CheckCastPP(), "not an allocation result?");
6389 
6390     _gvn.hash_delete(dest);
6391     dest->set_req(0, control());
6392     Node* destx = _gvn.transform(dest);
6393     assert(destx == dest, "where has the allocation result gone?");
6394 
6395     array_ideal_length(alloc, ary_type, true);
6396   }
6397 }
6398 
6399 // Unrelated UCTs between the array allocation and the array copy, which are considered safe by tightly_coupled_allocation(),
6400 // need to be replaced by an UCT with a state before the array allocation (including the array length). This is necessary
6401 // because we could hit one of these UCTs (which are executed before the emitted array copy guards and the actual array
6402 // allocation which is moved down in arraycopy_move_allocation_here()). When later resuming execution in the interpreter,
6403 // we would have wrongly skipped the array allocation. To prevent this, we resume execution at the array allocation in
6404 // the interpreter similar to what we are doing for the newly emitted guards for the array copy.
6405 void LibraryCallKit::replace_unrelated_uncommon_traps_with_alloc_state(AllocateArrayNode* alloc,
6406                                                                        JVMState* saved_jvms_before_guards) {
6407   if (saved_jvms_before_guards->map()->control()->is_IfProj()) {
6408     // There is at least one unrelated uncommon trap which needs to be replaced.
6409     SafePointNode* sfpt = create_safepoint_with_state_before_array_allocation(alloc);
6410 
6411     JVMState* saved_jvms = jvms();
6412     const int saved_reexecute_sp = _reexecute_sp;
6413     set_jvms(sfpt->jvms());
6414     _reexecute_sp = jvms()->sp();
6415 
6416     replace_unrelated_uncommon_traps_with_alloc_state(saved_jvms_before_guards);
6417 
6418     // Restore state
6419     set_jvms(saved_jvms);
6420     _reexecute_sp = saved_reexecute_sp;
6421   }
6422 }
6423 
6424 // Replace the unrelated uncommon traps with new uncommon trap nodes by reusing the action and reason. The new uncommon
6425 // traps will have the state of the array allocation. Let the old uncommon trap nodes die.
6426 void LibraryCallKit::replace_unrelated_uncommon_traps_with_alloc_state(JVMState* saved_jvms_before_guards) {
6427   Node* if_proj = saved_jvms_before_guards->map()->control(); // Start the search right before the newly emitted guards
6428   while (if_proj->is_IfProj()) {
6429     CallStaticJavaNode* uncommon_trap = get_uncommon_trap_from_success_proj(if_proj);
6430     if (uncommon_trap != nullptr) {
6431       create_new_uncommon_trap(uncommon_trap);
6432     }
6433     assert(if_proj->in(0)->is_If(), "must be If");
6434     if_proj = if_proj->in(0)->in(0);
6435   }
6436   assert(if_proj->is_Proj() && if_proj->in(0)->is_Initialize(),
6437          "must have reached control projection of init node");
6438 }
6439 
6440 void LibraryCallKit::create_new_uncommon_trap(CallStaticJavaNode* uncommon_trap_call) {
6441   const int trap_request = uncommon_trap_call->uncommon_trap_request();
6442   assert(trap_request != 0, "no valid UCT trap request");
6443   PreserveJVMState pjvms(this);
6444   set_control(uncommon_trap_call->in(0));
6445   uncommon_trap(Deoptimization::trap_request_reason(trap_request),
6446                 Deoptimization::trap_request_action(trap_request));
6447   assert(stopped(), "Should be stopped");
6448   _gvn.hash_delete(uncommon_trap_call);
6449   uncommon_trap_call->set_req(0, top()); // not used anymore, kill it
6450 }
6451 
6452 // Common checks for array sorting intrinsics arguments.
6453 // Returns `true` if checks passed.
6454 bool LibraryCallKit::check_array_sort_arguments(Node* elementType, Node* obj, BasicType& bt) {
6455   // check address of the class
6456   if (elementType == nullptr || elementType->is_top()) {
6457     return false;  // dead path
6458   }
6459   const TypeInstPtr* elem_klass = gvn().type(elementType)->isa_instptr();
6460   if (elem_klass == nullptr) {
6461     return false;  // dead path
6462   }
6463   // java_mirror_type() returns non-null for compile-time Class constants only
6464   ciType* elem_type = elem_klass->java_mirror_type();
6465   if (elem_type == nullptr) {
6466     return false;
6467   }
6468   bt = elem_type->basic_type();
6469   // Disable the intrinsic if the CPU does not support SIMD sort
6470   if (!Matcher::supports_simd_sort(bt)) {
6471     return false;
6472   }
6473   // check address of the array
6474   if (obj == nullptr || obj->is_top()) {
6475     return false;  // dead path
6476   }
6477   const TypeAryPtr* obj_t = _gvn.type(obj)->isa_aryptr();
6478   if (obj_t == nullptr || obj_t->elem() == Type::BOTTOM) {
6479     return false; // failed input validation
6480   }
6481   return true;
6482 }
6483 
6484 //------------------------------inline_array_partition-----------------------
6485 bool LibraryCallKit::inline_array_partition() {
6486   address stubAddr = StubRoutines::select_array_partition_function();
6487   if (stubAddr == nullptr) {
6488     return false; // Intrinsic's stub is not implemented on this platform
6489   }
6490   assert(callee()->signature()->size() == 9, "arrayPartition has 8 parameters (one long)");
6491 
6492   // no receiver because it is a static method
6493   Node* elementType     = argument(0);
6494   Node* obj             = argument(1);
6495   Node* offset          = argument(2); // long
6496   Node* fromIndex       = argument(4);
6497   Node* toIndex         = argument(5);
6498   Node* indexPivot1     = argument(6);
6499   Node* indexPivot2     = argument(7);
6500   // PartitionOperation:  argument(8) is ignored
6501 
6502   Node* pivotIndices = nullptr;
6503   BasicType bt = T_ILLEGAL;
6504 
6505   if (!check_array_sort_arguments(elementType, obj, bt)) {
6506     return false;
6507   }
6508   null_check(obj);
6509   // If obj is dead, only null-path is taken.
6510   if (stopped()) {
6511     return true;
6512   }
6513   // Set the original stack and the reexecute bit for the interpreter to reexecute
6514   // the bytecode that invokes DualPivotQuicksort.partition() if deoptimization happens.
6515   { PreserveReexecuteState preexecs(this);
6516     jvms()->set_should_reexecute(true);
6517 
6518     Node* obj_adr = make_unsafe_address(obj, offset);
6519 
6520     // create the pivotIndices array of type int and size = 2
6521     Node* size = intcon(2);
6522     Node* klass_node = makecon(TypeKlassPtr::make(ciTypeArrayKlass::make(T_INT)));
6523     pivotIndices = new_array(klass_node, size, 0);  // no arguments to push
6524     AllocateArrayNode* alloc = tightly_coupled_allocation(pivotIndices);
6525     guarantee(alloc != nullptr, "created above");
6526     Node* pivotIndices_adr = basic_plus_adr(pivotIndices, arrayOopDesc::base_offset_in_bytes(T_INT));
6527 
6528     // pass the basic type enum to the stub
6529     Node* elemType = intcon(bt);
6530 
6531     // Call the stub
6532     const char *stubName = "array_partition_stub";
6533     make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::array_partition_Type(),
6534                       stubAddr, stubName, TypePtr::BOTTOM,
6535                       obj_adr, elemType, fromIndex, toIndex, pivotIndices_adr,
6536                       indexPivot1, indexPivot2);
6537 
6538   } // original reexecute is set back here
6539 
6540   if (!stopped()) {
6541     set_result(pivotIndices);
6542   }
6543 
6544   return true;
6545 }
6546 
6547 
6548 //------------------------------inline_array_sort-----------------------
6549 bool LibraryCallKit::inline_array_sort() {
6550   address stubAddr = StubRoutines::select_arraysort_function();
6551   if (stubAddr == nullptr) {
6552     return false; // Intrinsic's stub is not implemented on this platform
6553   }
6554   assert(callee()->signature()->size() == 7, "arraySort has 6 parameters (one long)");
6555 
6556   // no receiver because it is a static method
6557   Node* elementType     = argument(0);
6558   Node* obj             = argument(1);
6559   Node* offset          = argument(2); // long
6560   Node* fromIndex       = argument(4);
6561   Node* toIndex         = argument(5);
6562   // SortOperation:       argument(6) is ignored
6563 
6564   BasicType bt = T_ILLEGAL;
6565 
6566   if (!check_array_sort_arguments(elementType, obj, bt)) {
6567     return false;
6568   }
6569   null_check(obj);
6570   // If obj is dead, only null-path is taken.
6571   if (stopped()) {
6572     return true;
6573   }
6574   Node* obj_adr = make_unsafe_address(obj, offset);
6575 
6576   // pass the basic type enum to the stub
6577   Node* elemType = intcon(bt);
6578 
6579   // Call the stub.
6580   const char *stubName = "arraysort_stub";
6581   make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::array_sort_Type(),
6582                     stubAddr, stubName, TypePtr::BOTTOM,
6583                     obj_adr, elemType, fromIndex, toIndex);
6584 
6585   return true;
6586 }
6587 
6588 
6589 //------------------------------inline_arraycopy-----------------------
6590 // public static native void java.lang.System.arraycopy(Object src,  int  srcPos,
6591 //                                                      Object dest, int destPos,
6592 //                                                      int length);
6593 bool LibraryCallKit::inline_arraycopy() {
6594   // Get the arguments.
6595   Node* src         = argument(0);  // type: oop
6596   Node* src_offset  = argument(1);  // type: int
6597   Node* dest        = argument(2);  // type: oop
6598   Node* dest_offset = argument(3);  // type: int
6599   Node* length      = argument(4);  // type: int
6600 
6601   uint new_idx = C->unique();
6602 
6603   // Check for allocation before we add nodes that would confuse
6604   // tightly_coupled_allocation()
6605   AllocateArrayNode* alloc = tightly_coupled_allocation(dest);
6606 
6607   int saved_reexecute_sp = -1;
6608   JVMState* saved_jvms_before_guards = arraycopy_restore_alloc_state(alloc, saved_reexecute_sp);
6609   // See arraycopy_restore_alloc_state() comment
6610   // if alloc == null we don't have to worry about a tightly coupled allocation so we can emit all needed guards
6611   // if saved_jvms_before_guards is not null (then alloc is not null) then we can handle guards and a tightly coupled allocation
6612   // if saved_jvms_before_guards is null and alloc is not null, we can't emit any guards
6613   bool can_emit_guards = (alloc == nullptr || saved_jvms_before_guards != nullptr);
6614 
6615   // The following tests must be performed
6616   // (1) src and dest are arrays.
6617   // (2) src and dest arrays must have elements of the same BasicType
6618   // (3) src and dest must not be null.
6619   // (4) src_offset must not be negative.
6620   // (5) dest_offset must not be negative.
6621   // (6) length must not be negative.
6622   // (7) src_offset + length must not exceed length of src.
6623   // (8) dest_offset + length must not exceed length of dest.
6624   // (9) each element of an oop array must be assignable
6625 
6626   // (3) src and dest must not be null.
6627   // always do this here because we need the JVM state for uncommon traps
6628   Node* null_ctl = top();
6629   src  = saved_jvms_before_guards != nullptr ? null_check_oop(src, &null_ctl, true, true) : null_check(src, T_ARRAY);
6630   assert(null_ctl->is_top(), "no null control here");
6631   dest = null_check(dest, T_ARRAY);
6632 
6633   if (!can_emit_guards) {
6634     // if saved_jvms_before_guards is null and alloc is not null, we don't emit any
6635     // guards but the arraycopy node could still take advantage of a
6636     // tightly allocated allocation. tightly_coupled_allocation() is
6637     // called again to make sure it takes the null check above into
6638     // account: the null check is mandatory and if it caused an
6639     // uncommon trap to be emitted then the allocation can't be
6640     // considered tightly coupled in this context.
6641     alloc = tightly_coupled_allocation(dest);
6642   }
6643 
6644   bool validated = false;
6645 
6646   const Type* src_type  = _gvn.type(src);
6647   const Type* dest_type = _gvn.type(dest);
6648   const TypeAryPtr* top_src  = src_type->isa_aryptr();
6649   const TypeAryPtr* top_dest = dest_type->isa_aryptr();
6650 
6651   // Do we have the type of src?
6652   bool has_src = (top_src != nullptr && top_src->elem() != Type::BOTTOM);
6653   // Do we have the type of dest?
6654   bool has_dest = (top_dest != nullptr && top_dest->elem() != Type::BOTTOM);
6655   // Is the type for src from speculation?
6656   bool src_spec = false;
6657   // Is the type for dest from speculation?
6658   bool dest_spec = false;
6659 
6660   if ((!has_src || !has_dest) && can_emit_guards) {
6661     // We don't have sufficient type information, let's see if
6662     // speculative types can help. We need to have types for both src
6663     // and dest so that it pays off.
6664 
6665     // Do we already have or could we have type information for src
6666     bool could_have_src = has_src;
6667     // Do we already have or could we have type information for dest
6668     bool could_have_dest = has_dest;
6669 
6670     ciKlass* src_k = nullptr;
6671     if (!has_src) {
6672       src_k = src_type->speculative_type_not_null();
6673       if (src_k != nullptr && src_k->is_array_klass()) {
6674         could_have_src = true;
6675       }
6676     }
6677 
6678     ciKlass* dest_k = nullptr;
6679     if (!has_dest) {
6680       dest_k = dest_type->speculative_type_not_null();
6681       if (dest_k != nullptr && dest_k->is_array_klass()) {
6682         could_have_dest = true;
6683       }
6684     }
6685 
6686     if (could_have_src && could_have_dest) {
6687       // This is going to pay off so emit the required guards
6688       if (!has_src) {
6689         src = maybe_cast_profiled_obj(src, src_k, true);
6690         src_type  = _gvn.type(src);
6691         top_src  = src_type->isa_aryptr();
6692         has_src = (top_src != nullptr && top_src->elem() != Type::BOTTOM);
6693         src_spec = true;
6694       }
6695       if (!has_dest) {
6696         dest = maybe_cast_profiled_obj(dest, dest_k, true);
6697         dest_type  = _gvn.type(dest);
6698         top_dest  = dest_type->isa_aryptr();
6699         has_dest = (top_dest != nullptr && top_dest->elem() != Type::BOTTOM);
6700         dest_spec = true;
6701       }
6702     }
6703   }
6704 
6705   if (has_src && has_dest && can_emit_guards) {
6706     BasicType src_elem = top_src->isa_aryptr()->elem()->array_element_basic_type();
6707     BasicType dest_elem = top_dest->isa_aryptr()->elem()->array_element_basic_type();
6708     if (is_reference_type(src_elem, true)) src_elem = T_OBJECT;
6709     if (is_reference_type(dest_elem, true)) dest_elem = T_OBJECT;
6710 
6711     if (src_elem == dest_elem && top_src->is_flat() == top_dest->is_flat() && src_elem == T_OBJECT) {
6712       // If both arrays are object arrays then having the exact types
6713       // for both will remove the need for a subtype check at runtime
6714       // before the call and may make it possible to pick a faster copy
6715       // routine (without a subtype check on every element)
6716       // Do we have the exact type of src?
6717       bool could_have_src = src_spec;
6718       // Do we have the exact type of dest?
6719       bool could_have_dest = dest_spec;
6720       ciKlass* src_k = nullptr;
6721       ciKlass* dest_k = nullptr;
6722       if (!src_spec) {
6723         src_k = src_type->speculative_type_not_null();
6724         if (src_k != nullptr && src_k->is_array_klass()) {
6725           could_have_src = true;
6726         }
6727       }
6728       if (!dest_spec) {
6729         dest_k = dest_type->speculative_type_not_null();
6730         if (dest_k != nullptr && dest_k->is_array_klass()) {
6731           could_have_dest = true;
6732         }
6733       }
6734       if (could_have_src && could_have_dest) {
6735         // If we can have both exact types, emit the missing guards
6736         if (could_have_src && !src_spec) {
6737           src = maybe_cast_profiled_obj(src, src_k, true);
6738           src_type = _gvn.type(src);
6739           top_src = src_type->isa_aryptr();
6740         }
6741         if (could_have_dest && !dest_spec) {
6742           dest = maybe_cast_profiled_obj(dest, dest_k, true);
6743           dest_type = _gvn.type(dest);
6744           top_dest = dest_type->isa_aryptr();
6745         }
6746       }
6747     }
6748   }
6749 
6750   ciMethod* trap_method = method();
6751   int trap_bci = bci();
6752   if (saved_jvms_before_guards != nullptr) {
6753     trap_method = alloc->jvms()->method();
6754     trap_bci = alloc->jvms()->bci();
6755   }
6756 
6757   bool negative_length_guard_generated = false;
6758 
6759   if (!C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_intrinsic) &&
6760       can_emit_guards && !src->is_top() && !dest->is_top()) {
6761     // validate arguments: enables transformation the ArrayCopyNode
6762     validated = true;
6763 
6764     RegionNode* slow_region = new RegionNode(1);
6765     record_for_igvn(slow_region);
6766 
6767     // (1) src and dest are arrays.
6768     generate_non_array_guard(load_object_klass(src), slow_region, &src);
6769     generate_non_array_guard(load_object_klass(dest), slow_region, &dest);
6770 
6771     // (2) src and dest arrays must have elements of the same BasicType
6772     // done at macro expansion or at Ideal transformation time
6773 
6774     // (4) src_offset must not be negative.
6775     generate_negative_guard(src_offset, slow_region);
6776 
6777     // (5) dest_offset must not be negative.
6778     generate_negative_guard(dest_offset, slow_region);
6779 
6780     // (7) src_offset + length must not exceed length of src.
6781     generate_limit_guard(src_offset, length,
6782                          load_array_length(src),
6783                          slow_region);
6784 
6785     // (8) dest_offset + length must not exceed length of dest.
6786     generate_limit_guard(dest_offset, length,
6787                          load_array_length(dest),
6788                          slow_region);
6789 
6790     // (6) length must not be negative.
6791     // This is also checked in generate_arraycopy() during macro expansion, but
6792     // we also have to check it here for the case where the ArrayCopyNode will
6793     // be eliminated by Escape Analysis.
6794     if (EliminateAllocations) {
6795       generate_negative_guard(length, slow_region);
6796       negative_length_guard_generated = true;
6797     }
6798 
6799     // (9) each element of an oop array must be assignable
6800     Node* dest_klass = load_object_klass(dest);
6801     Node* refined_dest_klass = dest_klass;
6802     if (src != dest) {
6803       dest_klass = load_non_refined_array_klass(refined_dest_klass);
6804       Node* not_subtype_ctrl = gen_subtype_check(src, dest_klass);
6805       slow_region->add_req(not_subtype_ctrl);
6806     }
6807 
6808     // TODO 8350865 Improve this. What about atomicity? Make sure this is always folded for type arrays.
6809     // If destination is null-restricted, source must be null-restricted as well: src_null_restricted || !dst_null_restricted
6810     Node* src_klass = load_object_klass(src);
6811     Node* adr_prop_src = basic_plus_adr(src_klass, in_bytes(ArrayKlass::properties_offset()));
6812     Node* prop_src = _gvn.transform(LoadNode::make(_gvn, control(), immutable_memory(), adr_prop_src, TypeRawPtr::BOTTOM, TypeInt::INT, T_INT, MemNode::unordered));
6813     Node* adr_prop_dest = basic_plus_adr(refined_dest_klass, in_bytes(ArrayKlass::properties_offset()));
6814     Node* prop_dest = _gvn.transform(LoadNode::make(_gvn, control(), immutable_memory(), adr_prop_dest, TypeRawPtr::BOTTOM, TypeInt::INT, T_INT, MemNode::unordered));
6815 
6816     prop_dest = _gvn.transform(new XorINode(prop_dest, intcon(ArrayKlass::ArrayProperties::NULL_RESTRICTED)));
6817     prop_src = _gvn.transform(new OrINode(prop_dest, prop_src));
6818     prop_src = _gvn.transform(new AndINode(prop_src, intcon(ArrayKlass::ArrayProperties::NULL_RESTRICTED)));
6819 
6820     Node* chk = _gvn.transform(new CmpINode(prop_src, intcon(ArrayKlass::ArrayProperties::NULL_RESTRICTED)));
6821     Node* tst = _gvn.transform(new BoolNode(chk, BoolTest::ne));
6822     generate_fair_guard(tst, slow_region);
6823 
6824     // TODO 8350865 This is too strong
6825     generate_fair_guard(flat_array_test(src), slow_region);
6826     generate_fair_guard(flat_array_test(dest), slow_region);
6827 
6828     {
6829       PreserveJVMState pjvms(this);
6830       set_control(_gvn.transform(slow_region));
6831       uncommon_trap(Deoptimization::Reason_intrinsic,
6832                     Deoptimization::Action_make_not_entrant);
6833       assert(stopped(), "Should be stopped");
6834     }
6835 
6836     const TypeKlassPtr* dest_klass_t = _gvn.type(dest_klass)->isa_klassptr();
6837     if (dest_klass_t == nullptr) {
6838       // refined_dest_klass may not be an array, which leads to dest_klass being top. This means we
6839       // are in a dead path.
6840       uncommon_trap(Deoptimization::Reason_intrinsic,
6841                     Deoptimization::Action_make_not_entrant);
6842       return true;
6843     }
6844 
6845     const Type* toop = dest_klass_t->cast_to_exactness(false)->as_instance_type();
6846     src = _gvn.transform(new CheckCastPPNode(control(), src, toop));
6847     arraycopy_move_allocation_here(alloc, dest, saved_jvms_before_guards, saved_reexecute_sp, new_idx);
6848   }
6849 
6850   if (stopped()) {
6851     return true;
6852   }
6853 
6854   Node* dest_klass = load_object_klass(dest);
6855   dest_klass = load_non_refined_array_klass(dest_klass);
6856 
6857   ArrayCopyNode* ac = ArrayCopyNode::make(this, true, src, src_offset, dest, dest_offset, length, alloc != nullptr, negative_length_guard_generated,
6858                                           // Create LoadRange and LoadKlass nodes for use during macro expansion here
6859                                           // so the compiler has a chance to eliminate them: during macro expansion,
6860                                           // we have to set their control (CastPP nodes are eliminated).
6861                                           load_object_klass(src), dest_klass,
6862                                           load_array_length(src), load_array_length(dest));
6863 
6864   ac->set_arraycopy(validated);
6865 
6866   Node* n = _gvn.transform(ac);
6867   if (n == ac) {
6868     ac->connect_outputs(this);
6869   } else {
6870     assert(validated, "shouldn't transform if all arguments not validated");
6871     set_all_memory(n);
6872   }
6873   clear_upper_avx();
6874 
6875 
6876   return true;
6877 }
6878 
6879 
6880 // Helper function which determines if an arraycopy immediately follows
6881 // an allocation, with no intervening tests or other escapes for the object.
6882 AllocateArrayNode*
6883 LibraryCallKit::tightly_coupled_allocation(Node* ptr) {
6884   if (stopped())             return nullptr;  // no fast path
6885   if (!C->do_aliasing())     return nullptr;  // no MergeMems around
6886 
6887   AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(ptr);
6888   if (alloc == nullptr)  return nullptr;
6889 
6890   Node* rawmem = memory(Compile::AliasIdxRaw);
6891   // Is the allocation's memory state untouched?
6892   if (!(rawmem->is_Proj() && rawmem->in(0)->is_Initialize())) {
6893     // Bail out if there have been raw-memory effects since the allocation.
6894     // (Example:  There might have been a call or safepoint.)
6895     return nullptr;
6896   }
6897   rawmem = rawmem->in(0)->as_Initialize()->memory(Compile::AliasIdxRaw);
6898   if (!(rawmem->is_Proj() && rawmem->in(0) == alloc)) {
6899     return nullptr;
6900   }
6901 
6902   // There must be no unexpected observers of this allocation.
6903   for (DUIterator_Fast imax, i = ptr->fast_outs(imax); i < imax; i++) {
6904     Node* obs = ptr->fast_out(i);
6905     if (obs != this->map()) {
6906       return nullptr;
6907     }
6908   }
6909 
6910   // This arraycopy must unconditionally follow the allocation of the ptr.
6911   Node* alloc_ctl = ptr->in(0);
6912   Node* ctl = control();
6913   while (ctl != alloc_ctl) {
6914     // There may be guards which feed into the slow_region.
6915     // Any other control flow means that we might not get a chance
6916     // to finish initializing the allocated object.
6917     // Various low-level checks bottom out in uncommon traps. These
6918     // are considered safe since we've already checked above that
6919     // there is no unexpected observer of this allocation.
6920     if (get_uncommon_trap_from_success_proj(ctl) != nullptr) {
6921       assert(ctl->in(0)->is_If(), "must be If");
6922       ctl = ctl->in(0)->in(0);
6923     } else {
6924       return nullptr;
6925     }
6926   }
6927 
6928   // If we get this far, we have an allocation which immediately
6929   // precedes the arraycopy, and we can take over zeroing the new object.
6930   // The arraycopy will finish the initialization, and provide
6931   // a new control state to which we will anchor the destination pointer.
6932 
6933   return alloc;
6934 }
6935 
6936 CallStaticJavaNode* LibraryCallKit::get_uncommon_trap_from_success_proj(Node* node) {
6937   if (node->is_IfProj()) {
6938     IfProjNode* other_proj = node->as_IfProj()->other_if_proj();
6939     for (DUIterator_Fast jmax, j = other_proj->fast_outs(jmax); j < jmax; j++) {
6940       Node* obs = other_proj->fast_out(j);
6941       if (obs->in(0) == other_proj && obs->is_CallStaticJava() &&
6942           (obs->as_CallStaticJava()->entry_point() == OptoRuntime::uncommon_trap_blob()->entry_point())) {
6943         return obs->as_CallStaticJava();
6944       }
6945     }
6946   }
6947   return nullptr;
6948 }
6949 
6950 //-------------inline_encodeISOArray-----------------------------------
6951 // int sun.nio.cs.ISO_8859_1.Encoder#encodeISOArray0(byte[] sa, int sp, byte[] da, int dp, int len)
6952 // int java.lang.StringCoding#encodeISOArray0(byte[] sa, int sp, byte[] da, int dp, int len)
6953 // int java.lang.StringCoding#encodeAsciiArray0(char[] sa, int sp, byte[] da, int dp, int len)
6954 // encode char[] to byte[] in ISO_8859_1 or ASCII
6955 bool LibraryCallKit::inline_encodeISOArray(bool ascii) {
6956   assert(callee()->signature()->size() == 5, "encodeISOArray has 5 parameters");
6957   // no receiver since it is static method
6958   Node *src         = argument(0);
6959   Node *src_offset  = argument(1);
6960   Node *dst         = argument(2);
6961   Node *dst_offset  = argument(3);
6962   Node *length      = argument(4);
6963 
6964   // Cast source & target arrays to not-null
6965   if (VerifyIntrinsicChecks) {
6966     src = must_be_not_null(src, true);
6967     dst = must_be_not_null(dst, true);
6968     if (stopped()) {
6969       return true;
6970     }
6971   }
6972 
6973   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
6974   const TypeAryPtr* dst_type = dst->Value(&_gvn)->isa_aryptr();
6975   if (src_type == nullptr || src_type->elem() == Type::BOTTOM ||
6976       dst_type == nullptr || dst_type->elem() == Type::BOTTOM) {
6977     // failed array check
6978     return false;
6979   }
6980 
6981   // Figure out the size and type of the elements we will be copying.
6982   BasicType src_elem = src_type->elem()->array_element_basic_type();
6983   BasicType dst_elem = dst_type->elem()->array_element_basic_type();
6984   if (!((src_elem == T_CHAR) || (src_elem== T_BYTE)) || dst_elem != T_BYTE) {
6985     return false;
6986   }
6987 
6988   // Check source & target bounds
6989   if (VerifyIntrinsicChecks) {
6990     generate_string_range_check(src, src_offset, length, src_elem == T_BYTE, true);
6991     generate_string_range_check(dst, dst_offset, length, false, true);
6992     if (stopped()) {
6993       return true;
6994     }
6995   }
6996 
6997   Node* src_start = array_element_address(src, src_offset, T_CHAR);
6998   Node* dst_start = array_element_address(dst, dst_offset, dst_elem);
6999   // 'src_start' points to src array + scaled offset
7000   // 'dst_start' points to dst array + scaled offset
7001 
7002   const TypeAryPtr* mtype = TypeAryPtr::BYTES;
7003   Node* enc = new EncodeISOArrayNode(control(), memory(mtype), src_start, dst_start, length, ascii);
7004   enc = _gvn.transform(enc);
7005   Node* res_mem = _gvn.transform(new SCMemProjNode(enc));
7006   set_memory(res_mem, mtype);
7007   set_result(enc);
7008   clear_upper_avx();
7009 
7010   return true;
7011 }
7012 
7013 //-------------inline_multiplyToLen-----------------------------------
7014 bool LibraryCallKit::inline_multiplyToLen() {
7015   assert(UseMultiplyToLenIntrinsic, "not implemented on this platform");
7016 
7017   address stubAddr = StubRoutines::multiplyToLen();
7018   if (stubAddr == nullptr) {
7019     return false; // Intrinsic's stub is not implemented on this platform
7020   }
7021   const char* stubName = "multiplyToLen";
7022 
7023   assert(callee()->signature()->size() == 5, "multiplyToLen has 5 parameters");
7024 
7025   // no receiver because it is a static method
7026   Node* x    = argument(0);
7027   Node* xlen = argument(1);
7028   Node* y    = argument(2);
7029   Node* ylen = argument(3);
7030   Node* z    = argument(4);
7031 
7032   x = must_be_not_null(x, true);
7033   y = must_be_not_null(y, true);
7034 
7035   const TypeAryPtr* x_type = x->Value(&_gvn)->isa_aryptr();
7036   const TypeAryPtr* y_type = y->Value(&_gvn)->isa_aryptr();
7037   if (x_type == nullptr || x_type->elem() == Type::BOTTOM ||
7038       y_type == nullptr || y_type->elem() == Type::BOTTOM) {
7039     // failed array check
7040     return false;
7041   }
7042 
7043   BasicType x_elem = x_type->elem()->array_element_basic_type();
7044   BasicType y_elem = y_type->elem()->array_element_basic_type();
7045   if (x_elem != T_INT || y_elem != T_INT) {
7046     return false;
7047   }
7048 
7049   Node* x_start = array_element_address(x, intcon(0), x_elem);
7050   Node* y_start = array_element_address(y, intcon(0), y_elem);
7051   // 'x_start' points to x array + scaled xlen
7052   // 'y_start' points to y array + scaled ylen
7053 
7054   Node* z_start = array_element_address(z, intcon(0), T_INT);
7055 
7056   Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
7057                                  OptoRuntime::multiplyToLen_Type(),
7058                                  stubAddr, stubName, TypePtr::BOTTOM,
7059                                  x_start, xlen, y_start, ylen, z_start);
7060 
7061   C->set_has_split_ifs(true); // Has chance for split-if optimization
7062   set_result(z);
7063   return true;
7064 }
7065 
7066 //-------------inline_squareToLen------------------------------------
7067 bool LibraryCallKit::inline_squareToLen() {
7068   assert(UseSquareToLenIntrinsic, "not implemented on this platform");
7069 
7070   address stubAddr = StubRoutines::squareToLen();
7071   if (stubAddr == nullptr) {
7072     return false; // Intrinsic's stub is not implemented on this platform
7073   }
7074   const char* stubName = "squareToLen";
7075 
7076   assert(callee()->signature()->size() == 4, "implSquareToLen has 4 parameters");
7077 
7078   Node* x    = argument(0);
7079   Node* len  = argument(1);
7080   Node* z    = argument(2);
7081   Node* zlen = argument(3);
7082 
7083   x = must_be_not_null(x, true);
7084   z = must_be_not_null(z, true);
7085 
7086   const TypeAryPtr* x_type = x->Value(&_gvn)->isa_aryptr();
7087   const TypeAryPtr* z_type = z->Value(&_gvn)->isa_aryptr();
7088   if (x_type == nullptr || x_type->elem() == Type::BOTTOM ||
7089       z_type == nullptr || z_type->elem() == Type::BOTTOM) {
7090     // failed array check
7091     return false;
7092   }
7093 
7094   BasicType x_elem = x_type->elem()->array_element_basic_type();
7095   BasicType z_elem = z_type->elem()->array_element_basic_type();
7096   if (x_elem != T_INT || z_elem != T_INT) {
7097     return false;
7098   }
7099 
7100 
7101   Node* x_start = array_element_address(x, intcon(0), x_elem);
7102   Node* z_start = array_element_address(z, intcon(0), z_elem);
7103 
7104   Node*  call = make_runtime_call(RC_LEAF|RC_NO_FP,
7105                                   OptoRuntime::squareToLen_Type(),
7106                                   stubAddr, stubName, TypePtr::BOTTOM,
7107                                   x_start, len, z_start, zlen);
7108 
7109   set_result(z);
7110   return true;
7111 }
7112 
7113 //-------------inline_mulAdd------------------------------------------
7114 bool LibraryCallKit::inline_mulAdd() {
7115   assert(UseMulAddIntrinsic, "not implemented on this platform");
7116 
7117   address stubAddr = StubRoutines::mulAdd();
7118   if (stubAddr == nullptr) {
7119     return false; // Intrinsic's stub is not implemented on this platform
7120   }
7121   const char* stubName = "mulAdd";
7122 
7123   assert(callee()->signature()->size() == 5, "mulAdd has 5 parameters");
7124 
7125   Node* out      = argument(0);
7126   Node* in       = argument(1);
7127   Node* offset   = argument(2);
7128   Node* len      = argument(3);
7129   Node* k        = argument(4);
7130 
7131   in = must_be_not_null(in, true);
7132   out = must_be_not_null(out, true);
7133 
7134   const TypeAryPtr* out_type = out->Value(&_gvn)->isa_aryptr();
7135   const TypeAryPtr* in_type = in->Value(&_gvn)->isa_aryptr();
7136   if (out_type == nullptr || out_type->elem() == Type::BOTTOM ||
7137        in_type == nullptr ||  in_type->elem() == Type::BOTTOM) {
7138     // failed array check
7139     return false;
7140   }
7141 
7142   BasicType out_elem = out_type->elem()->array_element_basic_type();
7143   BasicType in_elem = in_type->elem()->array_element_basic_type();
7144   if (out_elem != T_INT || in_elem != T_INT) {
7145     return false;
7146   }
7147 
7148   Node* outlen = load_array_length(out);
7149   Node* new_offset = _gvn.transform(new SubINode(outlen, offset));
7150   Node* out_start = array_element_address(out, intcon(0), out_elem);
7151   Node* in_start = array_element_address(in, intcon(0), in_elem);
7152 
7153   Node*  call = make_runtime_call(RC_LEAF|RC_NO_FP,
7154                                   OptoRuntime::mulAdd_Type(),
7155                                   stubAddr, stubName, TypePtr::BOTTOM,
7156                                   out_start,in_start, new_offset, len, k);
7157   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7158   set_result(result);
7159   return true;
7160 }
7161 
7162 //-------------inline_montgomeryMultiply-----------------------------------
7163 bool LibraryCallKit::inline_montgomeryMultiply() {
7164   address stubAddr = StubRoutines::montgomeryMultiply();
7165   if (stubAddr == nullptr) {
7166     return false; // Intrinsic's stub is not implemented on this platform
7167   }
7168 
7169   assert(UseMontgomeryMultiplyIntrinsic, "not implemented on this platform");
7170   const char* stubName = "montgomery_multiply";
7171 
7172   assert(callee()->signature()->size() == 7, "montgomeryMultiply has 7 parameters");
7173 
7174   Node* a    = argument(0);
7175   Node* b    = argument(1);
7176   Node* n    = argument(2);
7177   Node* len  = argument(3);
7178   Node* inv  = argument(4);
7179   Node* m    = argument(6);
7180 
7181   const TypeAryPtr* a_type = a->Value(&_gvn)->isa_aryptr();
7182   const TypeAryPtr* b_type = b->Value(&_gvn)->isa_aryptr();
7183   const TypeAryPtr* n_type = n->Value(&_gvn)->isa_aryptr();
7184   const TypeAryPtr* m_type = m->Value(&_gvn)->isa_aryptr();
7185   if (a_type == nullptr || a_type->elem() == Type::BOTTOM ||
7186       b_type == nullptr || b_type->elem() == Type::BOTTOM ||
7187       n_type == nullptr || n_type->elem() == Type::BOTTOM ||
7188       m_type == nullptr || m_type->elem() == Type::BOTTOM) {
7189     // failed array check
7190     return false;
7191   }
7192 
7193   BasicType a_elem = a_type->elem()->array_element_basic_type();
7194   BasicType b_elem = b_type->elem()->array_element_basic_type();
7195   BasicType n_elem = n_type->elem()->array_element_basic_type();
7196   BasicType m_elem = m_type->elem()->array_element_basic_type();
7197   if (a_elem != T_INT || b_elem != T_INT || n_elem != T_INT || m_elem != T_INT) {
7198     return false;
7199   }
7200 
7201   // Make the call
7202   {
7203     Node* a_start = array_element_address(a, intcon(0), a_elem);
7204     Node* b_start = array_element_address(b, intcon(0), b_elem);
7205     Node* n_start = array_element_address(n, intcon(0), n_elem);
7206     Node* m_start = array_element_address(m, intcon(0), m_elem);
7207 
7208     Node* call = make_runtime_call(RC_LEAF,
7209                                    OptoRuntime::montgomeryMultiply_Type(),
7210                                    stubAddr, stubName, TypePtr::BOTTOM,
7211                                    a_start, b_start, n_start, len, inv, top(),
7212                                    m_start);
7213     set_result(m);
7214   }
7215 
7216   return true;
7217 }
7218 
7219 bool LibraryCallKit::inline_montgomerySquare() {
7220   address stubAddr = StubRoutines::montgomerySquare();
7221   if (stubAddr == nullptr) {
7222     return false; // Intrinsic's stub is not implemented on this platform
7223   }
7224 
7225   assert(UseMontgomerySquareIntrinsic, "not implemented on this platform");
7226   const char* stubName = "montgomery_square";
7227 
7228   assert(callee()->signature()->size() == 6, "montgomerySquare has 6 parameters");
7229 
7230   Node* a    = argument(0);
7231   Node* n    = argument(1);
7232   Node* len  = argument(2);
7233   Node* inv  = argument(3);
7234   Node* m    = argument(5);
7235 
7236   const TypeAryPtr* a_type = a->Value(&_gvn)->isa_aryptr();
7237   const TypeAryPtr* n_type = n->Value(&_gvn)->isa_aryptr();
7238   const TypeAryPtr* m_type = m->Value(&_gvn)->isa_aryptr();
7239   if (a_type == nullptr || a_type->elem() == Type::BOTTOM ||
7240       n_type == nullptr || n_type->elem() == Type::BOTTOM ||
7241       m_type == nullptr || m_type->elem() == Type::BOTTOM) {
7242     // failed array check
7243     return false;
7244   }
7245 
7246   BasicType a_elem = a_type->elem()->array_element_basic_type();
7247   BasicType n_elem = n_type->elem()->array_element_basic_type();
7248   BasicType m_elem = m_type->elem()->array_element_basic_type();
7249   if (a_elem != T_INT || n_elem != T_INT || m_elem != T_INT) {
7250     return false;
7251   }
7252 
7253   // Make the call
7254   {
7255     Node* a_start = array_element_address(a, intcon(0), a_elem);
7256     Node* n_start = array_element_address(n, intcon(0), n_elem);
7257     Node* m_start = array_element_address(m, intcon(0), m_elem);
7258 
7259     Node* call = make_runtime_call(RC_LEAF,
7260                                    OptoRuntime::montgomerySquare_Type(),
7261                                    stubAddr, stubName, TypePtr::BOTTOM,
7262                                    a_start, n_start, len, inv, top(),
7263                                    m_start);
7264     set_result(m);
7265   }
7266 
7267   return true;
7268 }
7269 
7270 bool LibraryCallKit::inline_bigIntegerShift(bool isRightShift) {
7271   address stubAddr = nullptr;
7272   const char* stubName = nullptr;
7273 
7274   stubAddr = isRightShift? StubRoutines::bigIntegerRightShift(): StubRoutines::bigIntegerLeftShift();
7275   if (stubAddr == nullptr) {
7276     return false; // Intrinsic's stub is not implemented on this platform
7277   }
7278 
7279   stubName = isRightShift? "bigIntegerRightShiftWorker" : "bigIntegerLeftShiftWorker";
7280 
7281   assert(callee()->signature()->size() == 5, "expected 5 arguments");
7282 
7283   Node* newArr = argument(0);
7284   Node* oldArr = argument(1);
7285   Node* newIdx = argument(2);
7286   Node* shiftCount = argument(3);
7287   Node* numIter = argument(4);
7288 
7289   const TypeAryPtr* newArr_type = newArr->Value(&_gvn)->isa_aryptr();
7290   const TypeAryPtr* oldArr_type = oldArr->Value(&_gvn)->isa_aryptr();
7291   if (newArr_type == nullptr || newArr_type->elem() == Type::BOTTOM ||
7292       oldArr_type == nullptr || oldArr_type->elem() == Type::BOTTOM) {
7293     return false;
7294   }
7295 
7296   BasicType newArr_elem = newArr_type->elem()->array_element_basic_type();
7297   BasicType oldArr_elem = oldArr_type->elem()->array_element_basic_type();
7298   if (newArr_elem != T_INT || oldArr_elem != T_INT) {
7299     return false;
7300   }
7301 
7302   // Make the call
7303   {
7304     Node* newArr_start = array_element_address(newArr, intcon(0), newArr_elem);
7305     Node* oldArr_start = array_element_address(oldArr, intcon(0), oldArr_elem);
7306 
7307     Node* call = make_runtime_call(RC_LEAF,
7308                                    OptoRuntime::bigIntegerShift_Type(),
7309                                    stubAddr,
7310                                    stubName,
7311                                    TypePtr::BOTTOM,
7312                                    newArr_start,
7313                                    oldArr_start,
7314                                    newIdx,
7315                                    shiftCount,
7316                                    numIter);
7317   }
7318 
7319   return true;
7320 }
7321 
7322 //-------------inline_vectorizedMismatch------------------------------
7323 bool LibraryCallKit::inline_vectorizedMismatch() {
7324   assert(UseVectorizedMismatchIntrinsic, "not implemented on this platform");
7325 
7326   assert(callee()->signature()->size() == 8, "vectorizedMismatch has 6 parameters");
7327   Node* obja    = argument(0); // Object
7328   Node* aoffset = argument(1); // long
7329   Node* objb    = argument(3); // Object
7330   Node* boffset = argument(4); // long
7331   Node* length  = argument(6); // int
7332   Node* scale   = argument(7); // int
7333 
7334   const TypeAryPtr* obja_t = _gvn.type(obja)->isa_aryptr();
7335   const TypeAryPtr* objb_t = _gvn.type(objb)->isa_aryptr();
7336   if (obja_t == nullptr || obja_t->elem() == Type::BOTTOM ||
7337       objb_t == nullptr || objb_t->elem() == Type::BOTTOM ||
7338       scale == top()) {
7339     return false; // failed input validation
7340   }
7341 
7342   Node* obja_adr = make_unsafe_address(obja, aoffset);
7343   Node* objb_adr = make_unsafe_address(objb, boffset);
7344 
7345   // Partial inlining handling for inputs smaller than ArrayOperationPartialInlineSize bytes in size.
7346   //
7347   //    inline_limit = ArrayOperationPartialInlineSize / element_size;
7348   //    if (length <= inline_limit) {
7349   //      inline_path:
7350   //        vmask   = VectorMaskGen length
7351   //        vload1  = LoadVectorMasked obja, vmask
7352   //        vload2  = LoadVectorMasked objb, vmask
7353   //        result1 = VectorCmpMasked vload1, vload2, vmask
7354   //    } else {
7355   //      call_stub_path:
7356   //        result2 = call vectorizedMismatch_stub(obja, objb, length, scale)
7357   //    }
7358   //    exit_block:
7359   //      return Phi(result1, result2);
7360   //
7361   enum { inline_path = 1,  // input is small enough to process it all at once
7362          stub_path   = 2,  // input is too large; call into the VM
7363          PATH_LIMIT  = 3
7364   };
7365 
7366   Node* exit_block = new RegionNode(PATH_LIMIT);
7367   Node* result_phi = new PhiNode(exit_block, TypeInt::INT);
7368   Node* memory_phi = new PhiNode(exit_block, Type::MEMORY, TypePtr::BOTTOM);
7369 
7370   Node* call_stub_path = control();
7371 
7372   BasicType elem_bt = T_ILLEGAL;
7373 
7374   const TypeInt* scale_t = _gvn.type(scale)->is_int();
7375   if (scale_t->is_con()) {
7376     switch (scale_t->get_con()) {
7377       case 0: elem_bt = T_BYTE;  break;
7378       case 1: elem_bt = T_SHORT; break;
7379       case 2: elem_bt = T_INT;   break;
7380       case 3: elem_bt = T_LONG;  break;
7381 
7382       default: elem_bt = T_ILLEGAL; break; // not supported
7383     }
7384   }
7385 
7386   int inline_limit = 0;
7387   bool do_partial_inline = false;
7388 
7389   if (elem_bt != T_ILLEGAL && ArrayOperationPartialInlineSize > 0) {
7390     inline_limit = ArrayOperationPartialInlineSize / type2aelembytes(elem_bt);
7391     do_partial_inline = inline_limit >= 16;
7392   }
7393 
7394   if (do_partial_inline) {
7395     assert(elem_bt != T_ILLEGAL, "sanity");
7396 
7397     if (Matcher::match_rule_supported_vector(Op_VectorMaskGen,    inline_limit, elem_bt) &&
7398         Matcher::match_rule_supported_vector(Op_LoadVectorMasked, inline_limit, elem_bt) &&
7399         Matcher::match_rule_supported_vector(Op_VectorCmpMasked,  inline_limit, elem_bt)) {
7400 
7401       const TypeVect* vt = TypeVect::make(elem_bt, inline_limit);
7402       Node* cmp_length = _gvn.transform(new CmpINode(length, intcon(inline_limit)));
7403       Node* bol_gt     = _gvn.transform(new BoolNode(cmp_length, BoolTest::gt));
7404 
7405       call_stub_path = generate_guard(bol_gt, nullptr, PROB_MIN);
7406 
7407       if (!stopped()) {
7408         Node* casted_length = _gvn.transform(new CastIINode(control(), length, TypeInt::make(0, inline_limit, Type::WidenMin)));
7409 
7410         const TypePtr* obja_adr_t = _gvn.type(obja_adr)->isa_ptr();
7411         const TypePtr* objb_adr_t = _gvn.type(objb_adr)->isa_ptr();
7412         Node* obja_adr_mem = memory(C->get_alias_index(obja_adr_t));
7413         Node* objb_adr_mem = memory(C->get_alias_index(objb_adr_t));
7414 
7415         Node* vmask      = _gvn.transform(VectorMaskGenNode::make(ConvI2X(casted_length), elem_bt));
7416         Node* vload_obja = _gvn.transform(new LoadVectorMaskedNode(control(), obja_adr_mem, obja_adr, obja_adr_t, vt, vmask));
7417         Node* vload_objb = _gvn.transform(new LoadVectorMaskedNode(control(), objb_adr_mem, objb_adr, objb_adr_t, vt, vmask));
7418         Node* result     = _gvn.transform(new VectorCmpMaskedNode(vload_obja, vload_objb, vmask, TypeInt::INT));
7419 
7420         exit_block->init_req(inline_path, control());
7421         memory_phi->init_req(inline_path, map()->memory());
7422         result_phi->init_req(inline_path, result);
7423 
7424         C->set_max_vector_size(MAX2((uint)ArrayOperationPartialInlineSize, C->max_vector_size()));
7425         clear_upper_avx();
7426       }
7427     }
7428   }
7429 
7430   if (call_stub_path != nullptr) {
7431     set_control(call_stub_path);
7432 
7433     Node* call = make_runtime_call(RC_LEAF,
7434                                    OptoRuntime::vectorizedMismatch_Type(),
7435                                    StubRoutines::vectorizedMismatch(), "vectorizedMismatch", TypePtr::BOTTOM,
7436                                    obja_adr, objb_adr, length, scale);
7437 
7438     exit_block->init_req(stub_path, control());
7439     memory_phi->init_req(stub_path, map()->memory());
7440     result_phi->init_req(stub_path, _gvn.transform(new ProjNode(call, TypeFunc::Parms)));
7441   }
7442 
7443   exit_block = _gvn.transform(exit_block);
7444   memory_phi = _gvn.transform(memory_phi);
7445   result_phi = _gvn.transform(result_phi);
7446 
7447   record_for_igvn(exit_block);
7448   record_for_igvn(memory_phi);
7449   record_for_igvn(result_phi);
7450 
7451   set_control(exit_block);
7452   set_all_memory(memory_phi);
7453   set_result(result_phi);
7454 
7455   return true;
7456 }
7457 
7458 //------------------------------inline_vectorizedHashcode----------------------------
7459 bool LibraryCallKit::inline_vectorizedHashCode() {
7460   assert(UseVectorizedHashCodeIntrinsic, "not implemented on this platform");
7461 
7462   assert(callee()->signature()->size() == 5, "vectorizedHashCode has 5 parameters");
7463   Node* array          = argument(0);
7464   Node* offset         = argument(1);
7465   Node* length         = argument(2);
7466   Node* initialValue   = argument(3);
7467   Node* basic_type     = argument(4);
7468 
7469   if (basic_type == top()) {
7470     return false; // failed input validation
7471   }
7472 
7473   const TypeInt* basic_type_t = _gvn.type(basic_type)->is_int();
7474   if (!basic_type_t->is_con()) {
7475     return false; // Only intrinsify if mode argument is constant
7476   }
7477 
7478   array = must_be_not_null(array, true);
7479 
7480   BasicType bt = (BasicType)basic_type_t->get_con();
7481 
7482   // Resolve address of first element
7483   Node* array_start = array_element_address(array, offset, bt);
7484 
7485   set_result(_gvn.transform(new VectorizedHashCodeNode(control(), memory(TypeAryPtr::get_array_body_type(bt)),
7486     array_start, length, initialValue, basic_type)));
7487   clear_upper_avx();
7488 
7489   return true;
7490 }
7491 
7492 /**
7493  * Calculate CRC32 for byte.
7494  * int java.util.zip.CRC32.update(int crc, int b)
7495  */
7496 bool LibraryCallKit::inline_updateCRC32() {
7497   assert(UseCRC32Intrinsics, "need AVX and CLMUL instructions support");
7498   assert(callee()->signature()->size() == 2, "update has 2 parameters");
7499   // no receiver since it is static method
7500   Node* crc  = argument(0); // type: int
7501   Node* b    = argument(1); // type: int
7502 
7503   /*
7504    *    int c = ~ crc;
7505    *    b = timesXtoThe32[(b ^ c) & 0xFF];
7506    *    b = b ^ (c >>> 8);
7507    *    crc = ~b;
7508    */
7509 
7510   Node* M1 = intcon(-1);
7511   crc = _gvn.transform(new XorINode(crc, M1));
7512   Node* result = _gvn.transform(new XorINode(crc, b));
7513   result = _gvn.transform(new AndINode(result, intcon(0xFF)));
7514 
7515   Node* base = makecon(TypeRawPtr::make(StubRoutines::crc_table_addr()));
7516   Node* offset = _gvn.transform(new LShiftINode(result, intcon(0x2)));
7517   Node* adr = basic_plus_adr(top(), base, ConvI2X(offset));
7518   result = make_load(control(), adr, TypeInt::INT, T_INT, MemNode::unordered);
7519 
7520   crc = _gvn.transform(new URShiftINode(crc, intcon(8)));
7521   result = _gvn.transform(new XorINode(crc, result));
7522   result = _gvn.transform(new XorINode(result, M1));
7523   set_result(result);
7524   return true;
7525 }
7526 
7527 /**
7528  * Calculate CRC32 for byte[] array.
7529  * int java.util.zip.CRC32.updateBytes(int crc, byte[] buf, int off, int len)
7530  */
7531 bool LibraryCallKit::inline_updateBytesCRC32() {
7532   assert(UseCRC32Intrinsics, "need AVX and CLMUL instructions support");
7533   assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
7534   // no receiver since it is static method
7535   Node* crc     = argument(0); // type: int
7536   Node* src     = argument(1); // type: oop
7537   Node* offset  = argument(2); // type: int
7538   Node* length  = argument(3); // type: int
7539 
7540   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7541   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
7542     // failed array check
7543     return false;
7544   }
7545 
7546   // Figure out the size and type of the elements we will be copying.
7547   BasicType src_elem = src_type->elem()->array_element_basic_type();
7548   if (src_elem != T_BYTE) {
7549     return false;
7550   }
7551 
7552   // 'src_start' points to src array + scaled offset
7553   src = must_be_not_null(src, true);
7554   Node* src_start = array_element_address(src, offset, src_elem);
7555 
7556   // We assume that range check is done by caller.
7557   // TODO: generate range check (offset+length < src.length) in debug VM.
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 /**
7572  * Calculate CRC32 for ByteBuffer.
7573  * int java.util.zip.CRC32.updateByteBuffer(int crc, long buf, int off, int len)
7574  */
7575 bool LibraryCallKit::inline_updateByteBufferCRC32() {
7576   assert(UseCRC32Intrinsics, "need AVX and CLMUL instructions support");
7577   assert(callee()->signature()->size() == 5, "updateByteBuffer has 4 parameters and one is long");
7578   // no receiver since it is static method
7579   Node* crc     = argument(0); // type: int
7580   Node* src     = argument(1); // type: long
7581   Node* offset  = argument(3); // type: int
7582   Node* length  = argument(4); // type: int
7583 
7584   src = ConvL2X(src);  // adjust Java long to machine word
7585   Node* base = _gvn.transform(new CastX2PNode(src));
7586   offset = ConvI2X(offset);
7587 
7588   // 'src_start' points to src array + scaled offset
7589   Node* src_start = basic_plus_adr(top(), base, offset);
7590 
7591   // Call the stub.
7592   address stubAddr = StubRoutines::updateBytesCRC32();
7593   const char *stubName = "updateBytesCRC32";
7594 
7595   Node* call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::updateBytesCRC32_Type(),
7596                                  stubAddr, stubName, TypePtr::BOTTOM,
7597                                  crc, src_start, length);
7598   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7599   set_result(result);
7600   return true;
7601 }
7602 
7603 //------------------------------get_table_from_crc32c_class-----------------------
7604 Node * LibraryCallKit::get_table_from_crc32c_class(ciInstanceKlass *crc32c_class) {
7605   Node* table = load_field_from_object(nullptr, "byteTable", "[I", /*decorators*/ IN_HEAP, /*is_static*/ true, crc32c_class);
7606   assert (table != nullptr, "wrong version of java.util.zip.CRC32C");
7607 
7608   return table;
7609 }
7610 
7611 //------------------------------inline_updateBytesCRC32C-----------------------
7612 //
7613 // Calculate CRC32C for byte[] array.
7614 // int java.util.zip.CRC32C.updateBytes(int crc, byte[] buf, int off, int end)
7615 //
7616 bool LibraryCallKit::inline_updateBytesCRC32C() {
7617   assert(UseCRC32CIntrinsics, "need CRC32C instruction support");
7618   assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
7619   assert(callee()->holder()->is_loaded(), "CRC32C class must be loaded");
7620   // no receiver since it is a static method
7621   Node* crc     = argument(0); // type: int
7622   Node* src     = argument(1); // type: oop
7623   Node* offset  = argument(2); // type: int
7624   Node* end     = argument(3); // type: int
7625 
7626   Node* length = _gvn.transform(new SubINode(end, offset));
7627 
7628   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7629   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
7630     // failed array check
7631     return false;
7632   }
7633 
7634   // Figure out the size and type of the elements we will be copying.
7635   BasicType src_elem = src_type->elem()->array_element_basic_type();
7636   if (src_elem != T_BYTE) {
7637     return false;
7638   }
7639 
7640   // 'src_start' points to src array + scaled offset
7641   src = must_be_not_null(src, true);
7642   Node* src_start = array_element_address(src, offset, src_elem);
7643 
7644   // static final int[] byteTable in class CRC32C
7645   Node* table = get_table_from_crc32c_class(callee()->holder());
7646   table = must_be_not_null(table, true);
7647   Node* table_start = array_element_address(table, intcon(0), T_INT);
7648 
7649   // We assume that range check is done by caller.
7650   // TODO: generate range check (offset+length < src.length) in debug VM.
7651 
7652   // Call the stub.
7653   address stubAddr = StubRoutines::updateBytesCRC32C();
7654   const char *stubName = "updateBytesCRC32C";
7655 
7656   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesCRC32C_Type(),
7657                                  stubAddr, stubName, TypePtr::BOTTOM,
7658                                  crc, src_start, length, table_start);
7659   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7660   set_result(result);
7661   return true;
7662 }
7663 
7664 //------------------------------inline_updateDirectByteBufferCRC32C-----------------------
7665 //
7666 // Calculate CRC32C for DirectByteBuffer.
7667 // int java.util.zip.CRC32C.updateDirectByteBuffer(int crc, long buf, int off, int end)
7668 //
7669 bool LibraryCallKit::inline_updateDirectByteBufferCRC32C() {
7670   assert(UseCRC32CIntrinsics, "need CRC32C instruction support");
7671   assert(callee()->signature()->size() == 5, "updateDirectByteBuffer has 4 parameters and one is long");
7672   assert(callee()->holder()->is_loaded(), "CRC32C class must be loaded");
7673   // no receiver since it is a static method
7674   Node* crc     = argument(0); // type: int
7675   Node* src     = argument(1); // type: long
7676   Node* offset  = argument(3); // type: int
7677   Node* end     = argument(4); // type: int
7678 
7679   Node* length = _gvn.transform(new SubINode(end, offset));
7680 
7681   src = ConvL2X(src);  // adjust Java long to machine word
7682   Node* base = _gvn.transform(new CastX2PNode(src));
7683   offset = ConvI2X(offset);
7684 
7685   // 'src_start' points to src array + scaled offset
7686   Node* src_start = basic_plus_adr(top(), base, offset);
7687 
7688   // static final int[] byteTable in class CRC32C
7689   Node* table = get_table_from_crc32c_class(callee()->holder());
7690   table = must_be_not_null(table, true);
7691   Node* table_start = array_element_address(table, intcon(0), T_INT);
7692 
7693   // Call the stub.
7694   address stubAddr = StubRoutines::updateBytesCRC32C();
7695   const char *stubName = "updateBytesCRC32C";
7696 
7697   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesCRC32C_Type(),
7698                                  stubAddr, stubName, TypePtr::BOTTOM,
7699                                  crc, src_start, length, table_start);
7700   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7701   set_result(result);
7702   return true;
7703 }
7704 
7705 //------------------------------inline_updateBytesAdler32----------------------
7706 //
7707 // Calculate Adler32 checksum for byte[] array.
7708 // int java.util.zip.Adler32.updateBytes(int crc, byte[] buf, int off, int len)
7709 //
7710 bool LibraryCallKit::inline_updateBytesAdler32() {
7711   assert(UseAdler32Intrinsics, "Adler32 Intrinsic support need"); // check if we actually need to check this flag or check a different one
7712   assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
7713   assert(callee()->holder()->is_loaded(), "Adler32 class must be loaded");
7714   // no receiver since it is static method
7715   Node* crc     = argument(0); // type: int
7716   Node* src     = argument(1); // type: oop
7717   Node* offset  = argument(2); // type: int
7718   Node* length  = argument(3); // type: int
7719 
7720   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7721   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
7722     // failed array check
7723     return false;
7724   }
7725 
7726   // Figure out the size and type of the elements we will be copying.
7727   BasicType src_elem = src_type->elem()->array_element_basic_type();
7728   if (src_elem != T_BYTE) {
7729     return false;
7730   }
7731 
7732   // 'src_start' points to src array + scaled offset
7733   Node* src_start = array_element_address(src, offset, src_elem);
7734 
7735   // We assume that range check is done by caller.
7736   // TODO: generate range check (offset+length < src.length) in debug VM.
7737 
7738   // Call the stub.
7739   address stubAddr = StubRoutines::updateBytesAdler32();
7740   const char *stubName = "updateBytesAdler32";
7741 
7742   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesAdler32_Type(),
7743                                  stubAddr, stubName, TypePtr::BOTTOM,
7744                                  crc, src_start, length);
7745   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7746   set_result(result);
7747   return true;
7748 }
7749 
7750 //------------------------------inline_updateByteBufferAdler32---------------
7751 //
7752 // Calculate Adler32 checksum for DirectByteBuffer.
7753 // int java.util.zip.Adler32.updateByteBuffer(int crc, long buf, int off, int len)
7754 //
7755 bool LibraryCallKit::inline_updateByteBufferAdler32() {
7756   assert(UseAdler32Intrinsics, "Adler32 Intrinsic support need"); // check if we actually need to check this flag or check a different one
7757   assert(callee()->signature()->size() == 5, "updateByteBuffer has 4 parameters and one is long");
7758   assert(callee()->holder()->is_loaded(), "Adler32 class must be loaded");
7759   // no receiver since it is static method
7760   Node* crc     = argument(0); // type: int
7761   Node* src     = argument(1); // type: long
7762   Node* offset  = argument(3); // type: int
7763   Node* length  = argument(4); // type: int
7764 
7765   src = ConvL2X(src);  // adjust Java long to machine word
7766   Node* base = _gvn.transform(new CastX2PNode(src));
7767   offset = ConvI2X(offset);
7768 
7769   // 'src_start' points to src array + scaled offset
7770   Node* src_start = basic_plus_adr(top(), base, offset);
7771 
7772   // Call the stub.
7773   address stubAddr = StubRoutines::updateBytesAdler32();
7774   const char *stubName = "updateBytesAdler32";
7775 
7776   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesAdler32_Type(),
7777                                  stubAddr, stubName, TypePtr::BOTTOM,
7778                                  crc, src_start, length);
7779 
7780   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7781   set_result(result);
7782   return true;
7783 }
7784 
7785 //----------------------------inline_reference_get0----------------------------
7786 // public T java.lang.ref.Reference.get();
7787 bool LibraryCallKit::inline_reference_get0() {
7788   const int referent_offset = java_lang_ref_Reference::referent_offset();
7789 
7790   // Get the argument:
7791   Node* reference_obj = null_check_receiver();
7792   if (stopped()) return true;
7793 
7794   DecoratorSet decorators = IN_HEAP | ON_WEAK_OOP_REF;
7795   Node* result = load_field_from_object(reference_obj, "referent", "Ljava/lang/Object;",
7796                                         decorators, /*is_static*/ false, nullptr);
7797   if (result == nullptr) return false;
7798 
7799   // Add memory barrier to prevent commoning reads from this field
7800   // across safepoint since GC can change its value.
7801   insert_mem_bar(Op_MemBarCPUOrder);
7802 
7803   set_result(result);
7804   return true;
7805 }
7806 
7807 //----------------------------inline_reference_refersTo0----------------------------
7808 // bool java.lang.ref.Reference.refersTo0();
7809 // bool java.lang.ref.PhantomReference.refersTo0();
7810 bool LibraryCallKit::inline_reference_refersTo0(bool is_phantom) {
7811   // Get arguments:
7812   Node* reference_obj = null_check_receiver();
7813   Node* other_obj = argument(1);
7814   if (stopped()) return true;
7815 
7816   DecoratorSet decorators = IN_HEAP | AS_NO_KEEPALIVE;
7817   decorators |= (is_phantom ? ON_PHANTOM_OOP_REF : ON_WEAK_OOP_REF);
7818   Node* referent = load_field_from_object(reference_obj, "referent", "Ljava/lang/Object;",
7819                                           decorators, /*is_static*/ false, nullptr);
7820   if (referent == nullptr) return false;
7821 
7822   // Add memory barrier to prevent commoning reads from this field
7823   // across safepoint since GC can change its value.
7824   insert_mem_bar(Op_MemBarCPUOrder);
7825 
7826   Node* cmp = _gvn.transform(new CmpPNode(referent, other_obj));
7827   Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
7828   IfNode* if_node = create_and_map_if(control(), bol, PROB_FAIR, COUNT_UNKNOWN);
7829 
7830   RegionNode* region = new RegionNode(3);
7831   PhiNode* phi = new PhiNode(region, TypeInt::BOOL);
7832 
7833   Node* if_true = _gvn.transform(new IfTrueNode(if_node));
7834   region->init_req(1, if_true);
7835   phi->init_req(1, intcon(1));
7836 
7837   Node* if_false = _gvn.transform(new IfFalseNode(if_node));
7838   region->init_req(2, if_false);
7839   phi->init_req(2, intcon(0));
7840 
7841   set_control(_gvn.transform(region));
7842   record_for_igvn(region);
7843   set_result(_gvn.transform(phi));
7844   return true;
7845 }
7846 
7847 //----------------------------inline_reference_clear0----------------------------
7848 // void java.lang.ref.Reference.clear0();
7849 // void java.lang.ref.PhantomReference.clear0();
7850 bool LibraryCallKit::inline_reference_clear0(bool is_phantom) {
7851   // This matches the implementation in JVM_ReferenceClear, see the comments there.
7852 
7853   // Get arguments
7854   Node* reference_obj = null_check_receiver();
7855   if (stopped()) return true;
7856 
7857   // Common access parameters
7858   DecoratorSet decorators = IN_HEAP | AS_NO_KEEPALIVE;
7859   decorators |= (is_phantom ? ON_PHANTOM_OOP_REF : ON_WEAK_OOP_REF);
7860   Node* referent_field_addr = basic_plus_adr(reference_obj, java_lang_ref_Reference::referent_offset());
7861   const TypePtr* referent_field_addr_type = _gvn.type(referent_field_addr)->isa_ptr();
7862   const Type* val_type = TypeOopPtr::make_from_klass(env()->Object_klass());
7863 
7864   Node* referent = access_load_at(reference_obj,
7865                                   referent_field_addr,
7866                                   referent_field_addr_type,
7867                                   val_type,
7868                                   T_OBJECT,
7869                                   decorators);
7870 
7871   IdealKit ideal(this);
7872 #define __ ideal.
7873   __ if_then(referent, BoolTest::ne, null());
7874     sync_kit(ideal);
7875     access_store_at(reference_obj,
7876                     referent_field_addr,
7877                     referent_field_addr_type,
7878                     null(),
7879                     val_type,
7880                     T_OBJECT,
7881                     decorators);
7882     __ sync_kit(this);
7883   __ end_if();
7884   final_sync(ideal);
7885 #undef __
7886 
7887   return true;
7888 }
7889 
7890 Node* LibraryCallKit::load_field_from_object(Node* fromObj, const char* fieldName, const char* fieldTypeString,
7891                                              DecoratorSet decorators, bool is_static,
7892                                              ciInstanceKlass* fromKls) {
7893   if (fromKls == nullptr) {
7894     const TypeInstPtr* tinst = _gvn.type(fromObj)->isa_instptr();
7895     assert(tinst != nullptr, "obj is null");
7896     assert(tinst->is_loaded(), "obj is not loaded");
7897     fromKls = tinst->instance_klass();
7898   } else {
7899     assert(is_static, "only for static field access");
7900   }
7901   ciField* field = fromKls->get_field_by_name(ciSymbol::make(fieldName),
7902                                               ciSymbol::make(fieldTypeString),
7903                                               is_static);
7904 
7905   assert(field != nullptr, "undefined field %s %s %s", fieldTypeString, fromKls->name()->as_utf8(), fieldName);
7906   if (field == nullptr) return (Node *) nullptr;
7907 
7908   if (is_static) {
7909     const TypeInstPtr* tip = TypeInstPtr::make(fromKls->java_mirror());
7910     fromObj = makecon(tip);
7911   }
7912 
7913   // Next code  copied from Parse::do_get_xxx():
7914 
7915   // Compute address and memory type.
7916   int offset  = field->offset_in_bytes();
7917   bool is_vol = field->is_volatile();
7918   ciType* field_klass = field->type();
7919   assert(field_klass->is_loaded(), "should be loaded");
7920   const TypePtr* adr_type = C->alias_type(field)->adr_type();
7921   Node *adr = basic_plus_adr(fromObj, fromObj, offset);
7922   assert(C->get_alias_index(adr_type) == C->get_alias_index(_gvn.type(adr)->isa_ptr()),
7923     "slice of address and input slice don't match");
7924   BasicType bt = field->layout_type();
7925 
7926   // Build the resultant type of the load
7927   const Type *type;
7928   if (bt == T_OBJECT) {
7929     type = TypeOopPtr::make_from_klass(field_klass->as_klass());
7930   } else {
7931     type = Type::get_const_basic_type(bt);
7932   }
7933 
7934   if (is_vol) {
7935     decorators |= MO_SEQ_CST;
7936   }
7937 
7938   return access_load_at(fromObj, adr, adr_type, type, bt, decorators);
7939 }
7940 
7941 Node * LibraryCallKit::field_address_from_object(Node * fromObj, const char * fieldName, const char * fieldTypeString,
7942                                                  bool is_exact /* true */, bool is_static /* false */,
7943                                                  ciInstanceKlass * fromKls /* nullptr */) {
7944   if (fromKls == nullptr) {
7945     const TypeInstPtr* tinst = _gvn.type(fromObj)->isa_instptr();
7946     assert(tinst != nullptr, "obj is null");
7947     assert(tinst->is_loaded(), "obj is not loaded");
7948     assert(!is_exact || tinst->klass_is_exact(), "klass not exact");
7949     fromKls = tinst->instance_klass();
7950   }
7951   else {
7952     assert(is_static, "only for static field access");
7953   }
7954   ciField* field = fromKls->get_field_by_name(ciSymbol::make(fieldName),
7955     ciSymbol::make(fieldTypeString),
7956     is_static);
7957 
7958   assert(field != nullptr, "undefined field");
7959   assert(!field->is_volatile(), "not defined for volatile fields");
7960 
7961   if (is_static) {
7962     const TypeInstPtr* tip = TypeInstPtr::make(fromKls->java_mirror());
7963     fromObj = makecon(tip);
7964   }
7965 
7966   // Next code  copied from Parse::do_get_xxx():
7967 
7968   // Compute address and memory type.
7969   int offset = field->offset_in_bytes();
7970   Node *adr = basic_plus_adr(fromObj, fromObj, offset);
7971 
7972   return adr;
7973 }
7974 
7975 //------------------------------inline_aescrypt_Block-----------------------
7976 bool LibraryCallKit::inline_aescrypt_Block(vmIntrinsics::ID id) {
7977   address stubAddr = nullptr;
7978   const char *stubName;
7979   bool is_decrypt = false;
7980   assert(UseAES, "need AES instruction support");
7981 
7982   switch(id) {
7983   case vmIntrinsics::_aescrypt_encryptBlock:
7984     stubAddr = StubRoutines::aescrypt_encryptBlock();
7985     stubName = "aescrypt_encryptBlock";
7986     break;
7987   case vmIntrinsics::_aescrypt_decryptBlock:
7988     stubAddr = StubRoutines::aescrypt_decryptBlock();
7989     stubName = "aescrypt_decryptBlock";
7990     is_decrypt = true;
7991     break;
7992   default:
7993     break;
7994   }
7995   if (stubAddr == nullptr) return false;
7996 
7997   Node* aescrypt_object = argument(0);
7998   Node* src             = argument(1);
7999   Node* src_offset      = argument(2);
8000   Node* dest            = argument(3);
8001   Node* dest_offset     = argument(4);
8002 
8003   src = must_be_not_null(src, true);
8004   dest = must_be_not_null(dest, true);
8005 
8006   // (1) src and dest are arrays.
8007   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
8008   const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
8009   assert( src_type != nullptr &&  src_type->elem() != Type::BOTTOM &&
8010          dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
8011 
8012   // for the quick and dirty code we will skip all the checks.
8013   // we are just trying to get the call to be generated.
8014   Node* src_start  = src;
8015   Node* dest_start = dest;
8016   if (src_offset != nullptr || dest_offset != nullptr) {
8017     assert(src_offset != nullptr && dest_offset != nullptr, "");
8018     src_start  = array_element_address(src,  src_offset,  T_BYTE);
8019     dest_start = array_element_address(dest, dest_offset, T_BYTE);
8020   }
8021 
8022   // now need to get the start of its expanded key array
8023   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
8024   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object, is_decrypt);
8025   if (k_start == nullptr) return false;
8026 
8027   // Call the stub.
8028   make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::aescrypt_block_Type(),
8029                     stubAddr, stubName, TypePtr::BOTTOM,
8030                     src_start, dest_start, k_start);
8031 
8032   return true;
8033 }
8034 
8035 //------------------------------inline_cipherBlockChaining_AESCrypt-----------------------
8036 bool LibraryCallKit::inline_cipherBlockChaining_AESCrypt(vmIntrinsics::ID id) {
8037   address stubAddr = nullptr;
8038   const char *stubName = nullptr;
8039   bool is_decrypt = false;
8040   assert(UseAES, "need AES instruction support");
8041 
8042   switch(id) {
8043   case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
8044     stubAddr = StubRoutines::cipherBlockChaining_encryptAESCrypt();
8045     stubName = "cipherBlockChaining_encryptAESCrypt";
8046     break;
8047   case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
8048     stubAddr = StubRoutines::cipherBlockChaining_decryptAESCrypt();
8049     stubName = "cipherBlockChaining_decryptAESCrypt";
8050     is_decrypt = true;
8051     break;
8052   default:
8053     break;
8054   }
8055   if (stubAddr == nullptr) return false;
8056 
8057   Node* cipherBlockChaining_object = argument(0);
8058   Node* src                        = argument(1);
8059   Node* src_offset                 = argument(2);
8060   Node* len                        = argument(3);
8061   Node* dest                       = argument(4);
8062   Node* dest_offset                = argument(5);
8063 
8064   src = must_be_not_null(src, false);
8065   dest = must_be_not_null(dest, false);
8066 
8067   // (1) src and dest are arrays.
8068   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
8069   const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
8070   assert( src_type != nullptr &&  src_type->elem() != Type::BOTTOM &&
8071          dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
8072 
8073   // checks are the responsibility of the caller
8074   Node* src_start  = src;
8075   Node* dest_start = dest;
8076   if (src_offset != nullptr || dest_offset != nullptr) {
8077     assert(src_offset != nullptr && dest_offset != nullptr, "");
8078     src_start  = array_element_address(src,  src_offset,  T_BYTE);
8079     dest_start = array_element_address(dest, dest_offset, T_BYTE);
8080   }
8081 
8082   // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
8083   // (because of the predicated logic executed earlier).
8084   // so we cast it here safely.
8085   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
8086 
8087   Node* embeddedCipherObj = load_field_from_object(cipherBlockChaining_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8088   if (embeddedCipherObj == nullptr) return false;
8089 
8090   // cast it to what we know it will be at runtime
8091   const TypeInstPtr* tinst = _gvn.type(cipherBlockChaining_object)->isa_instptr();
8092   assert(tinst != nullptr, "CBC obj is null");
8093   assert(tinst->is_loaded(), "CBC obj is not loaded");
8094   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8095   assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
8096 
8097   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8098   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
8099   const TypeOopPtr* xtype = aklass->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
8100   Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
8101   aescrypt_object = _gvn.transform(aescrypt_object);
8102 
8103   // we need to get the start of the aescrypt_object's expanded key array
8104   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object, is_decrypt);
8105   if (k_start == nullptr) return false;
8106 
8107   // similarly, get the start address of the r vector
8108   Node* objRvec = load_field_from_object(cipherBlockChaining_object, "r", "[B");
8109   if (objRvec == nullptr) return false;
8110   Node* r_start = array_element_address(objRvec, intcon(0), T_BYTE);
8111 
8112   // Call the stub, passing src_start, dest_start, k_start, r_start and src_len
8113   Node* cbcCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
8114                                      OptoRuntime::cipherBlockChaining_aescrypt_Type(),
8115                                      stubAddr, stubName, TypePtr::BOTTOM,
8116                                      src_start, dest_start, k_start, r_start, len);
8117 
8118   // return cipher length (int)
8119   Node* retvalue = _gvn.transform(new ProjNode(cbcCrypt, TypeFunc::Parms));
8120   set_result(retvalue);
8121   return true;
8122 }
8123 
8124 //------------------------------inline_electronicCodeBook_AESCrypt-----------------------
8125 bool LibraryCallKit::inline_electronicCodeBook_AESCrypt(vmIntrinsics::ID id) {
8126   address stubAddr = nullptr;
8127   const char *stubName = nullptr;
8128   bool is_decrypt = false;
8129   assert(UseAES, "need AES instruction support");
8130 
8131   switch (id) {
8132   case vmIntrinsics::_electronicCodeBook_encryptAESCrypt:
8133     stubAddr = StubRoutines::electronicCodeBook_encryptAESCrypt();
8134     stubName = "electronicCodeBook_encryptAESCrypt";
8135     break;
8136   case vmIntrinsics::_electronicCodeBook_decryptAESCrypt:
8137     stubAddr = StubRoutines::electronicCodeBook_decryptAESCrypt();
8138     stubName = "electronicCodeBook_decryptAESCrypt";
8139     is_decrypt = true;
8140     break;
8141   default:
8142     break;
8143   }
8144 
8145   if (stubAddr == nullptr) return false;
8146 
8147   Node* electronicCodeBook_object = argument(0);
8148   Node* src                       = argument(1);
8149   Node* src_offset                = argument(2);
8150   Node* len                       = argument(3);
8151   Node* dest                      = argument(4);
8152   Node* dest_offset               = argument(5);
8153 
8154   // (1) src and dest are arrays.
8155   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
8156   const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
8157   assert( src_type != nullptr &&  src_type->elem() != Type::BOTTOM &&
8158          dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
8159 
8160   // checks are the responsibility of the caller
8161   Node* src_start = src;
8162   Node* dest_start = dest;
8163   if (src_offset != nullptr || dest_offset != nullptr) {
8164     assert(src_offset != nullptr && dest_offset != nullptr, "");
8165     src_start = array_element_address(src, src_offset, T_BYTE);
8166     dest_start = array_element_address(dest, dest_offset, T_BYTE);
8167   }
8168 
8169   // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
8170   // (because of the predicated logic executed earlier).
8171   // so we cast it here safely.
8172   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
8173 
8174   Node* embeddedCipherObj = load_field_from_object(electronicCodeBook_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8175   if (embeddedCipherObj == nullptr) return false;
8176 
8177   // cast it to what we know it will be at runtime
8178   const TypeInstPtr* tinst = _gvn.type(electronicCodeBook_object)->isa_instptr();
8179   assert(tinst != nullptr, "ECB obj is null");
8180   assert(tinst->is_loaded(), "ECB obj is not loaded");
8181   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8182   assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
8183 
8184   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8185   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
8186   const TypeOopPtr* xtype = aklass->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
8187   Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
8188   aescrypt_object = _gvn.transform(aescrypt_object);
8189 
8190   // we need to get the start of the aescrypt_object's expanded key array
8191   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object, is_decrypt);
8192   if (k_start == nullptr) return false;
8193 
8194   // Call the stub, passing src_start, dest_start, k_start, r_start and src_len
8195   Node* ecbCrypt = make_runtime_call(RC_LEAF | RC_NO_FP,
8196                                      OptoRuntime::electronicCodeBook_aescrypt_Type(),
8197                                      stubAddr, stubName, TypePtr::BOTTOM,
8198                                      src_start, dest_start, k_start, len);
8199 
8200   // return cipher length (int)
8201   Node* retvalue = _gvn.transform(new ProjNode(ecbCrypt, TypeFunc::Parms));
8202   set_result(retvalue);
8203   return true;
8204 }
8205 
8206 //------------------------------inline_counterMode_AESCrypt-----------------------
8207 bool LibraryCallKit::inline_counterMode_AESCrypt(vmIntrinsics::ID id) {
8208   assert(UseAES, "need AES instruction support");
8209   if (!UseAESCTRIntrinsics) return false;
8210 
8211   address stubAddr = nullptr;
8212   const char *stubName = nullptr;
8213   if (id == vmIntrinsics::_counterMode_AESCrypt) {
8214     stubAddr = StubRoutines::counterMode_AESCrypt();
8215     stubName = "counterMode_AESCrypt";
8216   }
8217   if (stubAddr == nullptr) return false;
8218 
8219   Node* counterMode_object = argument(0);
8220   Node* src = argument(1);
8221   Node* src_offset = argument(2);
8222   Node* len = argument(3);
8223   Node* dest = argument(4);
8224   Node* dest_offset = argument(5);
8225 
8226   // (1) src and dest are arrays.
8227   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
8228   const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
8229   assert( src_type != nullptr &&  src_type->elem() != Type::BOTTOM &&
8230          dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
8231 
8232   // checks are the responsibility of the caller
8233   Node* src_start = src;
8234   Node* dest_start = dest;
8235   if (src_offset != nullptr || dest_offset != nullptr) {
8236     assert(src_offset != nullptr && dest_offset != nullptr, "");
8237     src_start = array_element_address(src, src_offset, T_BYTE);
8238     dest_start = array_element_address(dest, dest_offset, T_BYTE);
8239   }
8240 
8241   // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
8242   // (because of the predicated logic executed earlier).
8243   // so we cast it here safely.
8244   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
8245   Node* embeddedCipherObj = load_field_from_object(counterMode_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8246   if (embeddedCipherObj == nullptr) return false;
8247   // cast it to what we know it will be at runtime
8248   const TypeInstPtr* tinst = _gvn.type(counterMode_object)->isa_instptr();
8249   assert(tinst != nullptr, "CTR obj is null");
8250   assert(tinst->is_loaded(), "CTR obj is not loaded");
8251   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8252   assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
8253   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8254   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
8255   const TypeOopPtr* xtype = aklass->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
8256   Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
8257   aescrypt_object = _gvn.transform(aescrypt_object);
8258   // we need to get the start of the aescrypt_object's expanded key array
8259   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object, /* is_decrypt */ false);
8260   if (k_start == nullptr) return false;
8261   // similarly, get the start address of the r vector
8262   Node* obj_counter = load_field_from_object(counterMode_object, "counter", "[B");
8263   if (obj_counter == nullptr) return false;
8264   Node* cnt_start = array_element_address(obj_counter, intcon(0), T_BYTE);
8265 
8266   Node* saved_encCounter = load_field_from_object(counterMode_object, "encryptedCounter", "[B");
8267   if (saved_encCounter == nullptr) return false;
8268   Node* saved_encCounter_start = array_element_address(saved_encCounter, intcon(0), T_BYTE);
8269   Node* used = field_address_from_object(counterMode_object, "used", "I", /*is_exact*/ false);
8270 
8271   // Call the stub, passing src_start, dest_start, k_start, r_start and src_len
8272   Node* ctrCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
8273                                      OptoRuntime::counterMode_aescrypt_Type(),
8274                                      stubAddr, stubName, TypePtr::BOTTOM,
8275                                      src_start, dest_start, k_start, cnt_start, len, saved_encCounter_start, used);
8276 
8277   // return cipher length (int)
8278   Node* retvalue = _gvn.transform(new ProjNode(ctrCrypt, TypeFunc::Parms));
8279   set_result(retvalue);
8280   return true;
8281 }
8282 
8283 //------------------------------get_key_start_from_aescrypt_object-----------------------
8284 Node* LibraryCallKit::get_key_start_from_aescrypt_object(Node* aescrypt_object, bool is_decrypt) {
8285   // MixColumns for decryption can be reduced by preprocessing MixColumns with round keys.
8286   // Intel's extension is based on this optimization and AESCrypt generates round keys by preprocessing MixColumns.
8287   // However, ppc64 vncipher processes MixColumns and requires the same round keys with encryption.
8288   // The following platform specific stubs of encryption and decryption use the same round keys.
8289 #if defined(PPC64) || defined(S390) || defined(RISCV64)
8290   bool use_decryption_key = false;
8291 #else
8292   bool use_decryption_key = is_decrypt;
8293 #endif
8294   Node* objAESCryptKey = load_field_from_object(aescrypt_object, use_decryption_key ? "sessionKd" : "sessionKe", "[I");
8295   assert(objAESCryptKey != nullptr, "wrong version of com.sun.crypto.provider.AES_Crypt");
8296   if (objAESCryptKey == nullptr) return (Node *) nullptr;
8297 
8298   // now have the array, need to get the start address of the selected key array
8299   Node* k_start = array_element_address(objAESCryptKey, intcon(0), T_INT);
8300   return k_start;
8301 }
8302 
8303 //----------------------------inline_cipherBlockChaining_AESCrypt_predicate----------------------------
8304 // Return node representing slow path of predicate check.
8305 // the pseudo code we want to emulate with this predicate is:
8306 // for encryption:
8307 //    if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
8308 // for decryption:
8309 //    if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
8310 //    note cipher==plain is more conservative than the original java code but that's OK
8311 //
8312 Node* LibraryCallKit::inline_cipherBlockChaining_AESCrypt_predicate(bool decrypting) {
8313   // The receiver was checked for null already.
8314   Node* objCBC = argument(0);
8315 
8316   Node* src = argument(1);
8317   Node* dest = argument(4);
8318 
8319   // Load embeddedCipher field of CipherBlockChaining object.
8320   Node* embeddedCipherObj = load_field_from_object(objCBC, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8321 
8322   // get AESCrypt klass for instanceOf check
8323   // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
8324   // will have same classloader as CipherBlockChaining object
8325   const TypeInstPtr* tinst = _gvn.type(objCBC)->isa_instptr();
8326   assert(tinst != nullptr, "CBCobj is null");
8327   assert(tinst->is_loaded(), "CBCobj is not loaded");
8328 
8329   // we want to do an instanceof comparison against the AESCrypt class
8330   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8331   if (!klass_AESCrypt->is_loaded()) {
8332     // if AESCrypt is not even loaded, we never take the intrinsic fast path
8333     Node* ctrl = control();
8334     set_control(top()); // no regular fast path
8335     return ctrl;
8336   }
8337 
8338   src = must_be_not_null(src, true);
8339   dest = must_be_not_null(dest, true);
8340 
8341   // Resolve oops to stable for CmpP below.
8342   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8343 
8344   Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
8345   Node* cmp_instof  = _gvn.transform(new CmpINode(instof, intcon(1)));
8346   Node* bool_instof  = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
8347 
8348   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
8349 
8350   // for encryption, we are done
8351   if (!decrypting)
8352     return instof_false;  // even if it is null
8353 
8354   // for decryption, we need to add a further check to avoid
8355   // taking the intrinsic path when cipher and plain are the same
8356   // see the original java code for why.
8357   RegionNode* region = new RegionNode(3);
8358   region->init_req(1, instof_false);
8359 
8360   Node* cmp_src_dest = _gvn.transform(new CmpPNode(src, dest));
8361   Node* bool_src_dest = _gvn.transform(new BoolNode(cmp_src_dest, BoolTest::eq));
8362   Node* src_dest_conjoint = generate_guard(bool_src_dest, nullptr, PROB_MIN);
8363   region->init_req(2, src_dest_conjoint);
8364 
8365   record_for_igvn(region);
8366   return _gvn.transform(region);
8367 }
8368 
8369 //----------------------------inline_electronicCodeBook_AESCrypt_predicate----------------------------
8370 // Return node representing slow path of predicate check.
8371 // the pseudo code we want to emulate with this predicate is:
8372 // for encryption:
8373 //    if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
8374 // for decryption:
8375 //    if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
8376 //    note cipher==plain is more conservative than the original java code but that's OK
8377 //
8378 Node* LibraryCallKit::inline_electronicCodeBook_AESCrypt_predicate(bool decrypting) {
8379   // The receiver was checked for null already.
8380   Node* objECB = argument(0);
8381 
8382   // Load embeddedCipher field of ElectronicCodeBook object.
8383   Node* embeddedCipherObj = load_field_from_object(objECB, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8384 
8385   // get AESCrypt klass for instanceOf check
8386   // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
8387   // will have same classloader as ElectronicCodeBook object
8388   const TypeInstPtr* tinst = _gvn.type(objECB)->isa_instptr();
8389   assert(tinst != nullptr, "ECBobj is null");
8390   assert(tinst->is_loaded(), "ECBobj is not loaded");
8391 
8392   // we want to do an instanceof comparison against the AESCrypt class
8393   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8394   if (!klass_AESCrypt->is_loaded()) {
8395     // if AESCrypt is not even loaded, we never take the intrinsic fast path
8396     Node* ctrl = control();
8397     set_control(top()); // no regular fast path
8398     return ctrl;
8399   }
8400   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8401 
8402   Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
8403   Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
8404   Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
8405 
8406   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
8407 
8408   // for encryption, we are done
8409   if (!decrypting)
8410     return instof_false;  // even if it is null
8411 
8412   // for decryption, we need to add a further check to avoid
8413   // taking the intrinsic path when cipher and plain are the same
8414   // see the original java code for why.
8415   RegionNode* region = new RegionNode(3);
8416   region->init_req(1, instof_false);
8417   Node* src = argument(1);
8418   Node* dest = argument(4);
8419   Node* cmp_src_dest = _gvn.transform(new CmpPNode(src, dest));
8420   Node* bool_src_dest = _gvn.transform(new BoolNode(cmp_src_dest, BoolTest::eq));
8421   Node* src_dest_conjoint = generate_guard(bool_src_dest, nullptr, PROB_MIN);
8422   region->init_req(2, src_dest_conjoint);
8423 
8424   record_for_igvn(region);
8425   return _gvn.transform(region);
8426 }
8427 
8428 //----------------------------inline_counterMode_AESCrypt_predicate----------------------------
8429 // Return node representing slow path of predicate check.
8430 // the pseudo code we want to emulate with this predicate is:
8431 // for encryption:
8432 //    if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
8433 // for decryption:
8434 //    if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
8435 //    note cipher==plain is more conservative than the original java code but that's OK
8436 //
8437 
8438 Node* LibraryCallKit::inline_counterMode_AESCrypt_predicate() {
8439   // The receiver was checked for null already.
8440   Node* objCTR = argument(0);
8441 
8442   // Load embeddedCipher field of CipherBlockChaining object.
8443   Node* embeddedCipherObj = load_field_from_object(objCTR, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8444 
8445   // get AESCrypt klass for instanceOf check
8446   // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
8447   // will have same classloader as CipherBlockChaining object
8448   const TypeInstPtr* tinst = _gvn.type(objCTR)->isa_instptr();
8449   assert(tinst != nullptr, "CTRobj is null");
8450   assert(tinst->is_loaded(), "CTRobj is not loaded");
8451 
8452   // we want to do an instanceof comparison against the AESCrypt class
8453   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8454   if (!klass_AESCrypt->is_loaded()) {
8455     // if AESCrypt is not even loaded, we never take the intrinsic fast path
8456     Node* ctrl = control();
8457     set_control(top()); // no regular fast path
8458     return ctrl;
8459   }
8460 
8461   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8462   Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
8463   Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
8464   Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
8465   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
8466 
8467   return instof_false; // even if it is null
8468 }
8469 
8470 //------------------------------inline_ghash_processBlocks
8471 bool LibraryCallKit::inline_ghash_processBlocks() {
8472   address stubAddr;
8473   const char *stubName;
8474   assert(UseGHASHIntrinsics, "need GHASH intrinsics support");
8475 
8476   stubAddr = StubRoutines::ghash_processBlocks();
8477   stubName = "ghash_processBlocks";
8478 
8479   Node* data           = argument(0);
8480   Node* offset         = argument(1);
8481   Node* len            = argument(2);
8482   Node* state          = argument(3);
8483   Node* subkeyH        = argument(4);
8484 
8485   state = must_be_not_null(state, true);
8486   subkeyH = must_be_not_null(subkeyH, true);
8487   data = must_be_not_null(data, true);
8488 
8489   Node* state_start  = array_element_address(state, intcon(0), T_LONG);
8490   assert(state_start, "state is null");
8491   Node* subkeyH_start  = array_element_address(subkeyH, intcon(0), T_LONG);
8492   assert(subkeyH_start, "subkeyH is null");
8493   Node* data_start  = array_element_address(data, offset, T_BYTE);
8494   assert(data_start, "data is null");
8495 
8496   Node* ghash = make_runtime_call(RC_LEAF|RC_NO_FP,
8497                                   OptoRuntime::ghash_processBlocks_Type(),
8498                                   stubAddr, stubName, TypePtr::BOTTOM,
8499                                   state_start, subkeyH_start, data_start, len);
8500   return true;
8501 }
8502 
8503 //------------------------------inline_chacha20Block
8504 bool LibraryCallKit::inline_chacha20Block() {
8505   address stubAddr;
8506   const char *stubName;
8507   assert(UseChaCha20Intrinsics, "need ChaCha20 intrinsics support");
8508 
8509   stubAddr = StubRoutines::chacha20Block();
8510   stubName = "chacha20Block";
8511 
8512   Node* state          = argument(0);
8513   Node* result         = argument(1);
8514 
8515   state = must_be_not_null(state, true);
8516   result = must_be_not_null(result, true);
8517 
8518   Node* state_start  = array_element_address(state, intcon(0), T_INT);
8519   assert(state_start, "state is null");
8520   Node* result_start  = array_element_address(result, intcon(0), T_BYTE);
8521   assert(result_start, "result is null");
8522 
8523   Node* cc20Blk = make_runtime_call(RC_LEAF|RC_NO_FP,
8524                                   OptoRuntime::chacha20Block_Type(),
8525                                   stubAddr, stubName, TypePtr::BOTTOM,
8526                                   state_start, result_start);
8527   // return key stream length (int)
8528   Node* retvalue = _gvn.transform(new ProjNode(cc20Blk, TypeFunc::Parms));
8529   set_result(retvalue);
8530   return true;
8531 }
8532 
8533 //------------------------------inline_kyberNtt
8534 bool LibraryCallKit::inline_kyberNtt() {
8535   address stubAddr;
8536   const char *stubName;
8537   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8538   assert(callee()->signature()->size() == 2, "kyberNtt has 2 parameters");
8539 
8540   stubAddr = StubRoutines::kyberNtt();
8541   stubName = "kyberNtt";
8542   if (!stubAddr) return false;
8543 
8544   Node* coeffs          = argument(0);
8545   Node* ntt_zetas        = argument(1);
8546 
8547   coeffs = must_be_not_null(coeffs, true);
8548   ntt_zetas = must_be_not_null(ntt_zetas, true);
8549 
8550   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_SHORT);
8551   assert(coeffs_start, "coeffs is null");
8552   Node* ntt_zetas_start  = array_element_address(ntt_zetas, intcon(0), T_SHORT);
8553   assert(ntt_zetas_start, "ntt_zetas is null");
8554   Node* kyberNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
8555                                   OptoRuntime::kyberNtt_Type(),
8556                                   stubAddr, stubName, TypePtr::BOTTOM,
8557                                   coeffs_start, ntt_zetas_start);
8558   // return an int
8559   Node* retvalue = _gvn.transform(new ProjNode(kyberNtt, TypeFunc::Parms));
8560   set_result(retvalue);
8561   return true;
8562 }
8563 
8564 //------------------------------inline_kyberInverseNtt
8565 bool LibraryCallKit::inline_kyberInverseNtt() {
8566   address stubAddr;
8567   const char *stubName;
8568   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8569   assert(callee()->signature()->size() == 2, "kyberInverseNtt has 2 parameters");
8570 
8571   stubAddr = StubRoutines::kyberInverseNtt();
8572   stubName = "kyberInverseNtt";
8573   if (!stubAddr) return false;
8574 
8575   Node* coeffs          = argument(0);
8576   Node* zetas           = argument(1);
8577 
8578   coeffs = must_be_not_null(coeffs, true);
8579   zetas = must_be_not_null(zetas, true);
8580 
8581   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_SHORT);
8582   assert(coeffs_start, "coeffs is null");
8583   Node* zetas_start  = array_element_address(zetas, intcon(0), T_SHORT);
8584   assert(zetas_start, "inverseNtt_zetas is null");
8585   Node* kyberInverseNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
8586                                   OptoRuntime::kyberInverseNtt_Type(),
8587                                   stubAddr, stubName, TypePtr::BOTTOM,
8588                                   coeffs_start, zetas_start);
8589 
8590   // return an int
8591   Node* retvalue = _gvn.transform(new ProjNode(kyberInverseNtt, TypeFunc::Parms));
8592   set_result(retvalue);
8593   return true;
8594 }
8595 
8596 //------------------------------inline_kyberNttMult
8597 bool LibraryCallKit::inline_kyberNttMult() {
8598   address stubAddr;
8599   const char *stubName;
8600   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8601   assert(callee()->signature()->size() == 4, "kyberNttMult has 4 parameters");
8602 
8603   stubAddr = StubRoutines::kyberNttMult();
8604   stubName = "kyberNttMult";
8605   if (!stubAddr) return false;
8606 
8607   Node* result          = argument(0);
8608   Node* ntta            = argument(1);
8609   Node* nttb            = argument(2);
8610   Node* zetas           = argument(3);
8611 
8612   result = must_be_not_null(result, true);
8613   ntta = must_be_not_null(ntta, true);
8614   nttb = must_be_not_null(nttb, true);
8615   zetas = must_be_not_null(zetas, true);
8616 
8617   Node* result_start  = array_element_address(result, intcon(0), T_SHORT);
8618   assert(result_start, "result is null");
8619   Node* ntta_start  = array_element_address(ntta, intcon(0), T_SHORT);
8620   assert(ntta_start, "ntta is null");
8621   Node* nttb_start  = array_element_address(nttb, intcon(0), T_SHORT);
8622   assert(nttb_start, "nttb is null");
8623   Node* zetas_start  = array_element_address(zetas, intcon(0), T_SHORT);
8624   assert(zetas_start, "nttMult_zetas is null");
8625   Node* kyberNttMult = make_runtime_call(RC_LEAF|RC_NO_FP,
8626                                   OptoRuntime::kyberNttMult_Type(),
8627                                   stubAddr, stubName, TypePtr::BOTTOM,
8628                                   result_start, ntta_start, nttb_start,
8629                                   zetas_start);
8630 
8631   // return an int
8632   Node* retvalue = _gvn.transform(new ProjNode(kyberNttMult, TypeFunc::Parms));
8633   set_result(retvalue);
8634 
8635   return true;
8636 }
8637 
8638 //------------------------------inline_kyberAddPoly_2
8639 bool LibraryCallKit::inline_kyberAddPoly_2() {
8640   address stubAddr;
8641   const char *stubName;
8642   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8643   assert(callee()->signature()->size() == 3, "kyberAddPoly_2 has 3 parameters");
8644 
8645   stubAddr = StubRoutines::kyberAddPoly_2();
8646   stubName = "kyberAddPoly_2";
8647   if (!stubAddr) return false;
8648 
8649   Node* result          = argument(0);
8650   Node* a               = argument(1);
8651   Node* b               = argument(2);
8652 
8653   result = must_be_not_null(result, true);
8654   a = must_be_not_null(a, true);
8655   b = must_be_not_null(b, true);
8656 
8657   Node* result_start  = array_element_address(result, intcon(0), T_SHORT);
8658   assert(result_start, "result is null");
8659   Node* a_start  = array_element_address(a, intcon(0), T_SHORT);
8660   assert(a_start, "a is null");
8661   Node* b_start  = array_element_address(b, intcon(0), T_SHORT);
8662   assert(b_start, "b is null");
8663   Node* kyberAddPoly_2 = make_runtime_call(RC_LEAF|RC_NO_FP,
8664                                   OptoRuntime::kyberAddPoly_2_Type(),
8665                                   stubAddr, stubName, TypePtr::BOTTOM,
8666                                   result_start, a_start, b_start);
8667   // return an int
8668   Node* retvalue = _gvn.transform(new ProjNode(kyberAddPoly_2, TypeFunc::Parms));
8669   set_result(retvalue);
8670   return true;
8671 }
8672 
8673 //------------------------------inline_kyberAddPoly_3
8674 bool LibraryCallKit::inline_kyberAddPoly_3() {
8675   address stubAddr;
8676   const char *stubName;
8677   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8678   assert(callee()->signature()->size() == 4, "kyberAddPoly_3 has 4 parameters");
8679 
8680   stubAddr = StubRoutines::kyberAddPoly_3();
8681   stubName = "kyberAddPoly_3";
8682   if (!stubAddr) return false;
8683 
8684   Node* result          = argument(0);
8685   Node* a               = argument(1);
8686   Node* b               = argument(2);
8687   Node* c               = argument(3);
8688 
8689   result = must_be_not_null(result, true);
8690   a = must_be_not_null(a, true);
8691   b = must_be_not_null(b, true);
8692   c = must_be_not_null(c, true);
8693 
8694   Node* result_start  = array_element_address(result, intcon(0), T_SHORT);
8695   assert(result_start, "result is null");
8696   Node* a_start  = array_element_address(a, intcon(0), T_SHORT);
8697   assert(a_start, "a is null");
8698   Node* b_start  = array_element_address(b, intcon(0), T_SHORT);
8699   assert(b_start, "b is null");
8700   Node* c_start  = array_element_address(c, intcon(0), T_SHORT);
8701   assert(c_start, "c is null");
8702   Node* kyberAddPoly_3 = make_runtime_call(RC_LEAF|RC_NO_FP,
8703                                   OptoRuntime::kyberAddPoly_3_Type(),
8704                                   stubAddr, stubName, TypePtr::BOTTOM,
8705                                   result_start, a_start, b_start, c_start);
8706   // return an int
8707   Node* retvalue = _gvn.transform(new ProjNode(kyberAddPoly_3, TypeFunc::Parms));
8708   set_result(retvalue);
8709   return true;
8710 }
8711 
8712 //------------------------------inline_kyber12To16
8713 bool LibraryCallKit::inline_kyber12To16() {
8714   address stubAddr;
8715   const char *stubName;
8716   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8717   assert(callee()->signature()->size() == 4, "kyber12To16 has 4 parameters");
8718 
8719   stubAddr = StubRoutines::kyber12To16();
8720   stubName = "kyber12To16";
8721   if (!stubAddr) return false;
8722 
8723   Node* condensed       = argument(0);
8724   Node* condensedOffs   = argument(1);
8725   Node* parsed          = argument(2);
8726   Node* parsedLength    = argument(3);
8727 
8728   condensed = must_be_not_null(condensed, true);
8729   parsed = must_be_not_null(parsed, true);
8730 
8731   Node* condensed_start  = array_element_address(condensed, intcon(0), T_BYTE);
8732   assert(condensed_start, "condensed is null");
8733   Node* parsed_start  = array_element_address(parsed, intcon(0), T_SHORT);
8734   assert(parsed_start, "parsed is null");
8735   Node* kyber12To16 = make_runtime_call(RC_LEAF|RC_NO_FP,
8736                                   OptoRuntime::kyber12To16_Type(),
8737                                   stubAddr, stubName, TypePtr::BOTTOM,
8738                                   condensed_start, condensedOffs, parsed_start, parsedLength);
8739   // return an int
8740   Node* retvalue = _gvn.transform(new ProjNode(kyber12To16, TypeFunc::Parms));
8741   set_result(retvalue);
8742   return true;
8743 
8744 }
8745 
8746 //------------------------------inline_kyberBarrettReduce
8747 bool LibraryCallKit::inline_kyberBarrettReduce() {
8748   address stubAddr;
8749   const char *stubName;
8750   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8751   assert(callee()->signature()->size() == 1, "kyberBarrettReduce has 1 parameters");
8752 
8753   stubAddr = StubRoutines::kyberBarrettReduce();
8754   stubName = "kyberBarrettReduce";
8755   if (!stubAddr) return false;
8756 
8757   Node* coeffs          = argument(0);
8758 
8759   coeffs = must_be_not_null(coeffs, true);
8760 
8761   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_SHORT);
8762   assert(coeffs_start, "coeffs is null");
8763   Node* kyberBarrettReduce = make_runtime_call(RC_LEAF|RC_NO_FP,
8764                                   OptoRuntime::kyberBarrettReduce_Type(),
8765                                   stubAddr, stubName, TypePtr::BOTTOM,
8766                                   coeffs_start);
8767   // return an int
8768   Node* retvalue = _gvn.transform(new ProjNode(kyberBarrettReduce, TypeFunc::Parms));
8769   set_result(retvalue);
8770   return true;
8771 }
8772 
8773 //------------------------------inline_dilithiumAlmostNtt
8774 bool LibraryCallKit::inline_dilithiumAlmostNtt() {
8775   address stubAddr;
8776   const char *stubName;
8777   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8778   assert(callee()->signature()->size() == 2, "dilithiumAlmostNtt has 2 parameters");
8779 
8780   stubAddr = StubRoutines::dilithiumAlmostNtt();
8781   stubName = "dilithiumAlmostNtt";
8782   if (!stubAddr) return false;
8783 
8784   Node* coeffs          = argument(0);
8785   Node* ntt_zetas        = argument(1);
8786 
8787   coeffs = must_be_not_null(coeffs, true);
8788   ntt_zetas = must_be_not_null(ntt_zetas, true);
8789 
8790   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_INT);
8791   assert(coeffs_start, "coeffs is null");
8792   Node* ntt_zetas_start  = array_element_address(ntt_zetas, intcon(0), T_INT);
8793   assert(ntt_zetas_start, "ntt_zetas is null");
8794   Node* dilithiumAlmostNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
8795                                   OptoRuntime::dilithiumAlmostNtt_Type(),
8796                                   stubAddr, stubName, TypePtr::BOTTOM,
8797                                   coeffs_start, ntt_zetas_start);
8798   // return an int
8799   Node* retvalue = _gvn.transform(new ProjNode(dilithiumAlmostNtt, TypeFunc::Parms));
8800   set_result(retvalue);
8801   return true;
8802 }
8803 
8804 //------------------------------inline_dilithiumAlmostInverseNtt
8805 bool LibraryCallKit::inline_dilithiumAlmostInverseNtt() {
8806   address stubAddr;
8807   const char *stubName;
8808   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8809   assert(callee()->signature()->size() == 2, "dilithiumAlmostInverseNtt has 2 parameters");
8810 
8811   stubAddr = StubRoutines::dilithiumAlmostInverseNtt();
8812   stubName = "dilithiumAlmostInverseNtt";
8813   if (!stubAddr) return false;
8814 
8815   Node* coeffs          = argument(0);
8816   Node* zetas           = argument(1);
8817 
8818   coeffs = must_be_not_null(coeffs, true);
8819   zetas = must_be_not_null(zetas, true);
8820 
8821   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_INT);
8822   assert(coeffs_start, "coeffs is null");
8823   Node* zetas_start  = array_element_address(zetas, intcon(0), T_INT);
8824   assert(zetas_start, "inverseNtt_zetas is null");
8825   Node* dilithiumAlmostInverseNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
8826                                   OptoRuntime::dilithiumAlmostInverseNtt_Type(),
8827                                   stubAddr, stubName, TypePtr::BOTTOM,
8828                                   coeffs_start, zetas_start);
8829   // return an int
8830   Node* retvalue = _gvn.transform(new ProjNode(dilithiumAlmostInverseNtt, TypeFunc::Parms));
8831   set_result(retvalue);
8832   return true;
8833 }
8834 
8835 //------------------------------inline_dilithiumNttMult
8836 bool LibraryCallKit::inline_dilithiumNttMult() {
8837   address stubAddr;
8838   const char *stubName;
8839   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8840   assert(callee()->signature()->size() == 3, "dilithiumNttMult has 3 parameters");
8841 
8842   stubAddr = StubRoutines::dilithiumNttMult();
8843   stubName = "dilithiumNttMult";
8844   if (!stubAddr) return false;
8845 
8846   Node* result          = argument(0);
8847   Node* ntta            = argument(1);
8848   Node* nttb            = argument(2);
8849   Node* zetas           = argument(3);
8850 
8851   result = must_be_not_null(result, true);
8852   ntta = must_be_not_null(ntta, true);
8853   nttb = must_be_not_null(nttb, true);
8854   zetas = must_be_not_null(zetas, true);
8855 
8856   Node* result_start  = array_element_address(result, intcon(0), T_INT);
8857   assert(result_start, "result is null");
8858   Node* ntta_start  = array_element_address(ntta, intcon(0), T_INT);
8859   assert(ntta_start, "ntta is null");
8860   Node* nttb_start  = array_element_address(nttb, intcon(0), T_INT);
8861   assert(nttb_start, "nttb is null");
8862   Node* dilithiumNttMult = make_runtime_call(RC_LEAF|RC_NO_FP,
8863                                   OptoRuntime::dilithiumNttMult_Type(),
8864                                   stubAddr, stubName, TypePtr::BOTTOM,
8865                                   result_start, ntta_start, nttb_start);
8866 
8867   // return an int
8868   Node* retvalue = _gvn.transform(new ProjNode(dilithiumNttMult, TypeFunc::Parms));
8869   set_result(retvalue);
8870 
8871   return true;
8872 }
8873 
8874 //------------------------------inline_dilithiumMontMulByConstant
8875 bool LibraryCallKit::inline_dilithiumMontMulByConstant() {
8876   address stubAddr;
8877   const char *stubName;
8878   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8879   assert(callee()->signature()->size() == 2, "dilithiumMontMulByConstant has 2 parameters");
8880 
8881   stubAddr = StubRoutines::dilithiumMontMulByConstant();
8882   stubName = "dilithiumMontMulByConstant";
8883   if (!stubAddr) return false;
8884 
8885   Node* coeffs          = argument(0);
8886   Node* constant        = argument(1);
8887 
8888   coeffs = must_be_not_null(coeffs, true);
8889 
8890   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_INT);
8891   assert(coeffs_start, "coeffs is null");
8892   Node* dilithiumMontMulByConstant = make_runtime_call(RC_LEAF|RC_NO_FP,
8893                                   OptoRuntime::dilithiumMontMulByConstant_Type(),
8894                                   stubAddr, stubName, TypePtr::BOTTOM,
8895                                   coeffs_start, constant);
8896 
8897   // return an int
8898   Node* retvalue = _gvn.transform(new ProjNode(dilithiumMontMulByConstant, TypeFunc::Parms));
8899   set_result(retvalue);
8900   return true;
8901 }
8902 
8903 
8904 //------------------------------inline_dilithiumDecomposePoly
8905 bool LibraryCallKit::inline_dilithiumDecomposePoly() {
8906   address stubAddr;
8907   const char *stubName;
8908   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8909   assert(callee()->signature()->size() == 5, "dilithiumDecomposePoly has 5 parameters");
8910 
8911   stubAddr = StubRoutines::dilithiumDecomposePoly();
8912   stubName = "dilithiumDecomposePoly";
8913   if (!stubAddr) return false;
8914 
8915   Node* input          = argument(0);
8916   Node* lowPart        = argument(1);
8917   Node* highPart       = argument(2);
8918   Node* twoGamma2      = argument(3);
8919   Node* multiplier     = argument(4);
8920 
8921   input = must_be_not_null(input, true);
8922   lowPart = must_be_not_null(lowPart, true);
8923   highPart = must_be_not_null(highPart, true);
8924 
8925   Node* input_start  = array_element_address(input, intcon(0), T_INT);
8926   assert(input_start, "input is null");
8927   Node* lowPart_start  = array_element_address(lowPart, intcon(0), T_INT);
8928   assert(lowPart_start, "lowPart is null");
8929   Node* highPart_start  = array_element_address(highPart, intcon(0), T_INT);
8930   assert(highPart_start, "highPart is null");
8931 
8932   Node* dilithiumDecomposePoly = make_runtime_call(RC_LEAF|RC_NO_FP,
8933                                   OptoRuntime::dilithiumDecomposePoly_Type(),
8934                                   stubAddr, stubName, TypePtr::BOTTOM,
8935                                   input_start, lowPart_start, highPart_start,
8936                                   twoGamma2, multiplier);
8937 
8938   // return an int
8939   Node* retvalue = _gvn.transform(new ProjNode(dilithiumDecomposePoly, TypeFunc::Parms));
8940   set_result(retvalue);
8941   return true;
8942 }
8943 
8944 bool LibraryCallKit::inline_base64_encodeBlock() {
8945   address stubAddr;
8946   const char *stubName;
8947   assert(UseBASE64Intrinsics, "need Base64 intrinsics support");
8948   assert(callee()->signature()->size() == 6, "base64_encodeBlock has 6 parameters");
8949   stubAddr = StubRoutines::base64_encodeBlock();
8950   stubName = "encodeBlock";
8951 
8952   if (!stubAddr) return false;
8953   Node* base64obj = argument(0);
8954   Node* src = argument(1);
8955   Node* offset = argument(2);
8956   Node* len = argument(3);
8957   Node* dest = argument(4);
8958   Node* dp = argument(5);
8959   Node* isURL = argument(6);
8960 
8961   src = must_be_not_null(src, true);
8962   dest = must_be_not_null(dest, true);
8963 
8964   Node* src_start = array_element_address(src, intcon(0), T_BYTE);
8965   assert(src_start, "source array is null");
8966   Node* dest_start = array_element_address(dest, intcon(0), T_BYTE);
8967   assert(dest_start, "destination array is null");
8968 
8969   Node* base64 = make_runtime_call(RC_LEAF,
8970                                    OptoRuntime::base64_encodeBlock_Type(),
8971                                    stubAddr, stubName, TypePtr::BOTTOM,
8972                                    src_start, offset, len, dest_start, dp, isURL);
8973   return true;
8974 }
8975 
8976 bool LibraryCallKit::inline_base64_decodeBlock() {
8977   address stubAddr;
8978   const char *stubName;
8979   assert(UseBASE64Intrinsics, "need Base64 intrinsics support");
8980   assert(callee()->signature()->size() == 7, "base64_decodeBlock has 7 parameters");
8981   stubAddr = StubRoutines::base64_decodeBlock();
8982   stubName = "decodeBlock";
8983 
8984   if (!stubAddr) return false;
8985   Node* base64obj = argument(0);
8986   Node* src = argument(1);
8987   Node* src_offset = argument(2);
8988   Node* len = argument(3);
8989   Node* dest = argument(4);
8990   Node* dest_offset = argument(5);
8991   Node* isURL = argument(6);
8992   Node* isMIME = argument(7);
8993 
8994   src = must_be_not_null(src, true);
8995   dest = must_be_not_null(dest, true);
8996 
8997   Node* src_start = array_element_address(src, intcon(0), T_BYTE);
8998   assert(src_start, "source array is null");
8999   Node* dest_start = array_element_address(dest, intcon(0), T_BYTE);
9000   assert(dest_start, "destination array is null");
9001 
9002   Node* call = make_runtime_call(RC_LEAF,
9003                                  OptoRuntime::base64_decodeBlock_Type(),
9004                                  stubAddr, stubName, TypePtr::BOTTOM,
9005                                  src_start, src_offset, len, dest_start, dest_offset, isURL, isMIME);
9006   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
9007   set_result(result);
9008   return true;
9009 }
9010 
9011 bool LibraryCallKit::inline_poly1305_processBlocks() {
9012   address stubAddr;
9013   const char *stubName;
9014   assert(UsePoly1305Intrinsics, "need Poly intrinsics support");
9015   assert(callee()->signature()->size() == 5, "poly1305_processBlocks has %d parameters", callee()->signature()->size());
9016   stubAddr = StubRoutines::poly1305_processBlocks();
9017   stubName = "poly1305_processBlocks";
9018 
9019   if (!stubAddr) return false;
9020   null_check_receiver();  // null-check receiver
9021   if (stopped())  return true;
9022 
9023   Node* input = argument(1);
9024   Node* input_offset = argument(2);
9025   Node* len = argument(3);
9026   Node* alimbs = argument(4);
9027   Node* rlimbs = argument(5);
9028 
9029   input = must_be_not_null(input, true);
9030   alimbs = must_be_not_null(alimbs, true);
9031   rlimbs = must_be_not_null(rlimbs, true);
9032 
9033   Node* input_start = array_element_address(input, input_offset, T_BYTE);
9034   assert(input_start, "input array is null");
9035   Node* acc_start = array_element_address(alimbs, intcon(0), T_LONG);
9036   assert(acc_start, "acc array is null");
9037   Node* r_start = array_element_address(rlimbs, intcon(0), T_LONG);
9038   assert(r_start, "r array is null");
9039 
9040   Node* call = make_runtime_call(RC_LEAF | RC_NO_FP,
9041                                  OptoRuntime::poly1305_processBlocks_Type(),
9042                                  stubAddr, stubName, TypePtr::BOTTOM,
9043                                  input_start, len, acc_start, r_start);
9044   return true;
9045 }
9046 
9047 bool LibraryCallKit::inline_intpoly_montgomeryMult_P256() {
9048   address stubAddr;
9049   const char *stubName;
9050   assert(UseIntPolyIntrinsics, "need intpoly intrinsics support");
9051   assert(callee()->signature()->size() == 3, "intpoly_montgomeryMult_P256 has %d parameters", callee()->signature()->size());
9052   stubAddr = StubRoutines::intpoly_montgomeryMult_P256();
9053   stubName = "intpoly_montgomeryMult_P256";
9054 
9055   if (!stubAddr) return false;
9056   null_check_receiver();  // null-check receiver
9057   if (stopped())  return true;
9058 
9059   Node* a = argument(1);
9060   Node* b = argument(2);
9061   Node* r = argument(3);
9062 
9063   a = must_be_not_null(a, true);
9064   b = must_be_not_null(b, true);
9065   r = must_be_not_null(r, true);
9066 
9067   Node* a_start = array_element_address(a, intcon(0), T_LONG);
9068   assert(a_start, "a array is null");
9069   Node* b_start = array_element_address(b, intcon(0), T_LONG);
9070   assert(b_start, "b array is null");
9071   Node* r_start = array_element_address(r, intcon(0), T_LONG);
9072   assert(r_start, "r array is null");
9073 
9074   Node* call = make_runtime_call(RC_LEAF | RC_NO_FP,
9075                                  OptoRuntime::intpoly_montgomeryMult_P256_Type(),
9076                                  stubAddr, stubName, TypePtr::BOTTOM,
9077                                  a_start, b_start, r_start);
9078   return true;
9079 }
9080 
9081 bool LibraryCallKit::inline_intpoly_assign() {
9082   assert(UseIntPolyIntrinsics, "need intpoly intrinsics support");
9083   assert(callee()->signature()->size() == 3, "intpoly_assign has %d parameters", callee()->signature()->size());
9084   const char *stubName = "intpoly_assign";
9085   address stubAddr = StubRoutines::intpoly_assign();
9086   if (!stubAddr) return false;
9087 
9088   Node* set = argument(0);
9089   Node* a = argument(1);
9090   Node* b = argument(2);
9091   Node* arr_length = load_array_length(a);
9092 
9093   a = must_be_not_null(a, true);
9094   b = must_be_not_null(b, true);
9095 
9096   Node* a_start = array_element_address(a, intcon(0), T_LONG);
9097   assert(a_start, "a array is null");
9098   Node* b_start = array_element_address(b, intcon(0), T_LONG);
9099   assert(b_start, "b array is null");
9100 
9101   Node* call = make_runtime_call(RC_LEAF | RC_NO_FP,
9102                                  OptoRuntime::intpoly_assign_Type(),
9103                                  stubAddr, stubName, TypePtr::BOTTOM,
9104                                  set, a_start, b_start, arr_length);
9105   return true;
9106 }
9107 
9108 //------------------------------inline_digestBase_implCompress-----------------------
9109 //
9110 // Calculate MD5 for single-block byte[] array.
9111 // void com.sun.security.provider.MD5.implCompress(byte[] buf, int ofs)
9112 //
9113 // Calculate SHA (i.e., SHA-1) for single-block byte[] array.
9114 // void com.sun.security.provider.SHA.implCompress(byte[] buf, int ofs)
9115 //
9116 // Calculate SHA2 (i.e., SHA-244 or SHA-256) for single-block byte[] array.
9117 // void com.sun.security.provider.SHA2.implCompress(byte[] buf, int ofs)
9118 //
9119 // Calculate SHA5 (i.e., SHA-384 or SHA-512) for single-block byte[] array.
9120 // void com.sun.security.provider.SHA5.implCompress(byte[] buf, int ofs)
9121 //
9122 // Calculate SHA3 (i.e., SHA3-224 or SHA3-256 or SHA3-384 or SHA3-512) for single-block byte[] array.
9123 // void com.sun.security.provider.SHA3.implCompress(byte[] buf, int ofs)
9124 //
9125 bool LibraryCallKit::inline_digestBase_implCompress(vmIntrinsics::ID id) {
9126   assert(callee()->signature()->size() == 2, "sha_implCompress has 2 parameters");
9127 
9128   Node* digestBase_obj = argument(0);
9129   Node* src            = argument(1); // type oop
9130   Node* ofs            = argument(2); // type int
9131 
9132   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
9133   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
9134     // failed array check
9135     return false;
9136   }
9137   // Figure out the size and type of the elements we will be copying.
9138   BasicType src_elem = src_type->elem()->array_element_basic_type();
9139   if (src_elem != T_BYTE) {
9140     return false;
9141   }
9142   // 'src_start' points to src array + offset
9143   src = must_be_not_null(src, true);
9144   Node* src_start = array_element_address(src, ofs, src_elem);
9145   Node* state = nullptr;
9146   Node* block_size = nullptr;
9147   address stubAddr;
9148   const char *stubName;
9149 
9150   switch(id) {
9151   case vmIntrinsics::_md5_implCompress:
9152     assert(UseMD5Intrinsics, "need MD5 instruction support");
9153     state = get_state_from_digest_object(digestBase_obj, T_INT);
9154     stubAddr = StubRoutines::md5_implCompress();
9155     stubName = "md5_implCompress";
9156     break;
9157   case vmIntrinsics::_sha_implCompress:
9158     assert(UseSHA1Intrinsics, "need SHA1 instruction support");
9159     state = get_state_from_digest_object(digestBase_obj, T_INT);
9160     stubAddr = StubRoutines::sha1_implCompress();
9161     stubName = "sha1_implCompress";
9162     break;
9163   case vmIntrinsics::_sha2_implCompress:
9164     assert(UseSHA256Intrinsics, "need SHA256 instruction support");
9165     state = get_state_from_digest_object(digestBase_obj, T_INT);
9166     stubAddr = StubRoutines::sha256_implCompress();
9167     stubName = "sha256_implCompress";
9168     break;
9169   case vmIntrinsics::_sha5_implCompress:
9170     assert(UseSHA512Intrinsics, "need SHA512 instruction support");
9171     state = get_state_from_digest_object(digestBase_obj, T_LONG);
9172     stubAddr = StubRoutines::sha512_implCompress();
9173     stubName = "sha512_implCompress";
9174     break;
9175   case vmIntrinsics::_sha3_implCompress:
9176     assert(UseSHA3Intrinsics, "need SHA3 instruction support");
9177     state = get_state_from_digest_object(digestBase_obj, T_LONG);
9178     stubAddr = StubRoutines::sha3_implCompress();
9179     stubName = "sha3_implCompress";
9180     block_size = get_block_size_from_digest_object(digestBase_obj);
9181     if (block_size == nullptr) return false;
9182     break;
9183   default:
9184     fatal_unexpected_iid(id);
9185     return false;
9186   }
9187   if (state == nullptr) return false;
9188 
9189   assert(stubAddr != nullptr, "Stub %s is not generated", stubName);
9190   if (stubAddr == nullptr) return false;
9191 
9192   // Call the stub.
9193   Node* call;
9194   if (block_size == nullptr) {
9195     call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::digestBase_implCompress_Type(false),
9196                              stubAddr, stubName, TypePtr::BOTTOM,
9197                              src_start, state);
9198   } else {
9199     call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::digestBase_implCompress_Type(true),
9200                              stubAddr, stubName, TypePtr::BOTTOM,
9201                              src_start, state, block_size);
9202   }
9203 
9204   return true;
9205 }
9206 
9207 //------------------------------inline_double_keccak
9208 bool LibraryCallKit::inline_double_keccak() {
9209   address stubAddr;
9210   const char *stubName;
9211   assert(UseSHA3Intrinsics, "need SHA3 intrinsics support");
9212   assert(callee()->signature()->size() == 2, "double_keccak has 2 parameters");
9213 
9214   stubAddr = StubRoutines::double_keccak();
9215   stubName = "double_keccak";
9216   if (!stubAddr) return false;
9217 
9218   Node* status0        = argument(0);
9219   Node* status1        = argument(1);
9220 
9221   status0 = must_be_not_null(status0, true);
9222   status1 = must_be_not_null(status1, true);
9223 
9224   Node* status0_start  = array_element_address(status0, intcon(0), T_LONG);
9225   assert(status0_start, "status0 is null");
9226   Node* status1_start  = array_element_address(status1, intcon(0), T_LONG);
9227   assert(status1_start, "status1 is null");
9228   Node* double_keccak = make_runtime_call(RC_LEAF|RC_NO_FP,
9229                                   OptoRuntime::double_keccak_Type(),
9230                                   stubAddr, stubName, TypePtr::BOTTOM,
9231                                   status0_start, status1_start);
9232   // return an int
9233   Node* retvalue = _gvn.transform(new ProjNode(double_keccak, TypeFunc::Parms));
9234   set_result(retvalue);
9235   return true;
9236 }
9237 
9238 
9239 //------------------------------inline_digestBase_implCompressMB-----------------------
9240 //
9241 // Calculate MD5/SHA/SHA2/SHA5/SHA3 for multi-block byte[] array.
9242 // int com.sun.security.provider.DigestBase.implCompressMultiBlock(byte[] b, int ofs, int limit)
9243 //
9244 bool LibraryCallKit::inline_digestBase_implCompressMB(int predicate) {
9245   assert(UseMD5Intrinsics || UseSHA1Intrinsics || UseSHA256Intrinsics || UseSHA512Intrinsics || UseSHA3Intrinsics,
9246          "need MD5/SHA1/SHA256/SHA512/SHA3 instruction support");
9247   assert((uint)predicate < 5, "sanity");
9248   assert(callee()->signature()->size() == 3, "digestBase_implCompressMB has 3 parameters");
9249 
9250   Node* digestBase_obj = argument(0); // The receiver was checked for null already.
9251   Node* src            = argument(1); // byte[] array
9252   Node* ofs            = argument(2); // type int
9253   Node* limit          = argument(3); // type int
9254 
9255   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
9256   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
9257     // failed array check
9258     return false;
9259   }
9260   // Figure out the size and type of the elements we will be copying.
9261   BasicType src_elem = src_type->elem()->array_element_basic_type();
9262   if (src_elem != T_BYTE) {
9263     return false;
9264   }
9265   // 'src_start' points to src array + offset
9266   src = must_be_not_null(src, false);
9267   Node* src_start = array_element_address(src, ofs, src_elem);
9268 
9269   const char* klass_digestBase_name = nullptr;
9270   const char* stub_name = nullptr;
9271   address     stub_addr = nullptr;
9272   BasicType elem_type = T_INT;
9273 
9274   switch (predicate) {
9275   case 0:
9276     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_md5_implCompress)) {
9277       klass_digestBase_name = "sun/security/provider/MD5";
9278       stub_name = "md5_implCompressMB";
9279       stub_addr = StubRoutines::md5_implCompressMB();
9280     }
9281     break;
9282   case 1:
9283     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha_implCompress)) {
9284       klass_digestBase_name = "sun/security/provider/SHA";
9285       stub_name = "sha1_implCompressMB";
9286       stub_addr = StubRoutines::sha1_implCompressMB();
9287     }
9288     break;
9289   case 2:
9290     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha2_implCompress)) {
9291       klass_digestBase_name = "sun/security/provider/SHA2";
9292       stub_name = "sha256_implCompressMB";
9293       stub_addr = StubRoutines::sha256_implCompressMB();
9294     }
9295     break;
9296   case 3:
9297     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha5_implCompress)) {
9298       klass_digestBase_name = "sun/security/provider/SHA5";
9299       stub_name = "sha512_implCompressMB";
9300       stub_addr = StubRoutines::sha512_implCompressMB();
9301       elem_type = T_LONG;
9302     }
9303     break;
9304   case 4:
9305     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha3_implCompress)) {
9306       klass_digestBase_name = "sun/security/provider/SHA3";
9307       stub_name = "sha3_implCompressMB";
9308       stub_addr = StubRoutines::sha3_implCompressMB();
9309       elem_type = T_LONG;
9310     }
9311     break;
9312   default:
9313     fatal("unknown DigestBase intrinsic predicate: %d", predicate);
9314   }
9315   if (klass_digestBase_name != nullptr) {
9316     assert(stub_addr != nullptr, "Stub is generated");
9317     if (stub_addr == nullptr) return false;
9318 
9319     // get DigestBase klass to lookup for SHA klass
9320     const TypeInstPtr* tinst = _gvn.type(digestBase_obj)->isa_instptr();
9321     assert(tinst != nullptr, "digestBase_obj is not instance???");
9322     assert(tinst->is_loaded(), "DigestBase is not loaded");
9323 
9324     ciKlass* klass_digestBase = tinst->instance_klass()->find_klass(ciSymbol::make(klass_digestBase_name));
9325     assert(klass_digestBase->is_loaded(), "predicate checks that this class is loaded");
9326     ciInstanceKlass* instklass_digestBase = klass_digestBase->as_instance_klass();
9327     return inline_digestBase_implCompressMB(digestBase_obj, instklass_digestBase, elem_type, stub_addr, stub_name, src_start, ofs, limit);
9328   }
9329   return false;
9330 }
9331 
9332 //------------------------------inline_digestBase_implCompressMB-----------------------
9333 bool LibraryCallKit::inline_digestBase_implCompressMB(Node* digestBase_obj, ciInstanceKlass* instklass_digestBase,
9334                                                       BasicType elem_type, address stubAddr, const char *stubName,
9335                                                       Node* src_start, Node* ofs, Node* limit) {
9336   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_digestBase);
9337   const TypeOopPtr* xtype = aklass->cast_to_exactness(false)->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
9338   Node* digest_obj = new CheckCastPPNode(control(), digestBase_obj, xtype);
9339   digest_obj = _gvn.transform(digest_obj);
9340 
9341   Node* state = get_state_from_digest_object(digest_obj, elem_type);
9342   if (state == nullptr) return false;
9343 
9344   Node* block_size = nullptr;
9345   if (strcmp("sha3_implCompressMB", stubName) == 0) {
9346     block_size = get_block_size_from_digest_object(digest_obj);
9347     if (block_size == nullptr) return false;
9348   }
9349 
9350   // Call the stub.
9351   Node* call;
9352   if (block_size == nullptr) {
9353     call = make_runtime_call(RC_LEAF|RC_NO_FP,
9354                              OptoRuntime::digestBase_implCompressMB_Type(false),
9355                              stubAddr, stubName, TypePtr::BOTTOM,
9356                              src_start, state, ofs, limit);
9357   } else {
9358      call = make_runtime_call(RC_LEAF|RC_NO_FP,
9359                              OptoRuntime::digestBase_implCompressMB_Type(true),
9360                              stubAddr, stubName, TypePtr::BOTTOM,
9361                              src_start, state, block_size, ofs, limit);
9362   }
9363 
9364   // return ofs (int)
9365   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
9366   set_result(result);
9367 
9368   return true;
9369 }
9370 
9371 //------------------------------inline_galoisCounterMode_AESCrypt-----------------------
9372 bool LibraryCallKit::inline_galoisCounterMode_AESCrypt() {
9373   assert(UseAES, "need AES instruction support");
9374   address stubAddr = nullptr;
9375   const char *stubName = nullptr;
9376   stubAddr = StubRoutines::galoisCounterMode_AESCrypt();
9377   stubName = "galoisCounterMode_AESCrypt";
9378 
9379   if (stubAddr == nullptr) return false;
9380 
9381   Node* in      = argument(0);
9382   Node* inOfs   = argument(1);
9383   Node* len     = argument(2);
9384   Node* ct      = argument(3);
9385   Node* ctOfs   = argument(4);
9386   Node* out     = argument(5);
9387   Node* outOfs  = argument(6);
9388   Node* gctr_object = argument(7);
9389   Node* ghash_object = argument(8);
9390 
9391   // (1) in, ct and out are arrays.
9392   const TypeAryPtr* in_type = in->Value(&_gvn)->isa_aryptr();
9393   const TypeAryPtr* ct_type = ct->Value(&_gvn)->isa_aryptr();
9394   const TypeAryPtr* out_type = out->Value(&_gvn)->isa_aryptr();
9395   assert( in_type != nullptr &&  in_type->elem() != Type::BOTTOM &&
9396           ct_type != nullptr &&  ct_type->elem() != Type::BOTTOM &&
9397          out_type != nullptr && out_type->elem() != Type::BOTTOM, "args are strange");
9398 
9399   // checks are the responsibility of the caller
9400   Node* in_start = in;
9401   Node* ct_start = ct;
9402   Node* out_start = out;
9403   if (inOfs != nullptr || ctOfs != nullptr || outOfs != nullptr) {
9404     assert(inOfs != nullptr && ctOfs != nullptr && outOfs != nullptr, "");
9405     in_start = array_element_address(in, inOfs, T_BYTE);
9406     ct_start = array_element_address(ct, ctOfs, T_BYTE);
9407     out_start = array_element_address(out, outOfs, T_BYTE);
9408   }
9409 
9410   // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
9411   // (because of the predicated logic executed earlier).
9412   // so we cast it here safely.
9413   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
9414   Node* embeddedCipherObj = load_field_from_object(gctr_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
9415   Node* counter = load_field_from_object(gctr_object, "counter", "[B");
9416   Node* subkeyHtbl = load_field_from_object(ghash_object, "subkeyHtbl", "[J");
9417   Node* state = load_field_from_object(ghash_object, "state", "[J");
9418 
9419   if (embeddedCipherObj == nullptr || counter == nullptr || subkeyHtbl == nullptr || state == nullptr) {
9420     return false;
9421   }
9422   // cast it to what we know it will be at runtime
9423   const TypeInstPtr* tinst = _gvn.type(gctr_object)->isa_instptr();
9424   assert(tinst != nullptr, "GCTR obj is null");
9425   assert(tinst->is_loaded(), "GCTR obj is not loaded");
9426   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
9427   assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
9428   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
9429   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
9430   const TypeOopPtr* xtype = aklass->as_instance_type();
9431   Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
9432   aescrypt_object = _gvn.transform(aescrypt_object);
9433   // we need to get the start of the aescrypt_object's expanded key array
9434   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object, /* is_decrypt */ false);
9435   if (k_start == nullptr) return false;
9436   // similarly, get the start address of the r vector
9437   Node* cnt_start = array_element_address(counter, intcon(0), T_BYTE);
9438   Node* state_start = array_element_address(state, intcon(0), T_LONG);
9439   Node* subkeyHtbl_start = array_element_address(subkeyHtbl, intcon(0), T_LONG);
9440 
9441 
9442   // Call the stub, passing params
9443   Node* gcmCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
9444                                OptoRuntime::galoisCounterMode_aescrypt_Type(),
9445                                stubAddr, stubName, TypePtr::BOTTOM,
9446                                in_start, len, ct_start, out_start, k_start, state_start, subkeyHtbl_start, cnt_start);
9447 
9448   // return cipher length (int)
9449   Node* retvalue = _gvn.transform(new ProjNode(gcmCrypt, TypeFunc::Parms));
9450   set_result(retvalue);
9451 
9452   return true;
9453 }
9454 
9455 //----------------------------inline_galoisCounterMode_AESCrypt_predicate----------------------------
9456 // Return node representing slow path of predicate check.
9457 // the pseudo code we want to emulate with this predicate is:
9458 // for encryption:
9459 //    if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
9460 // for decryption:
9461 //    if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
9462 //    note cipher==plain is more conservative than the original java code but that's OK
9463 //
9464 
9465 Node* LibraryCallKit::inline_galoisCounterMode_AESCrypt_predicate() {
9466   // The receiver was checked for null already.
9467   Node* objGCTR = argument(7);
9468   // Load embeddedCipher field of GCTR object.
9469   Node* embeddedCipherObj = load_field_from_object(objGCTR, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
9470   assert(embeddedCipherObj != nullptr, "embeddedCipherObj is null");
9471 
9472   // get AESCrypt klass for instanceOf check
9473   // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
9474   // will have same classloader as CipherBlockChaining object
9475   const TypeInstPtr* tinst = _gvn.type(objGCTR)->isa_instptr();
9476   assert(tinst != nullptr, "GCTR obj is null");
9477   assert(tinst->is_loaded(), "GCTR obj is not loaded");
9478 
9479   // we want to do an instanceof comparison against the AESCrypt class
9480   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
9481   if (!klass_AESCrypt->is_loaded()) {
9482     // if AESCrypt is not even loaded, we never take the intrinsic fast path
9483     Node* ctrl = control();
9484     set_control(top()); // no regular fast path
9485     return ctrl;
9486   }
9487 
9488   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
9489   Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
9490   Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
9491   Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
9492   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
9493 
9494   return instof_false; // even if it is null
9495 }
9496 
9497 //------------------------------get_state_from_digest_object-----------------------
9498 Node * LibraryCallKit::get_state_from_digest_object(Node *digest_object, BasicType elem_type) {
9499   const char* state_type;
9500   switch (elem_type) {
9501     case T_BYTE: state_type = "[B"; break;
9502     case T_INT:  state_type = "[I"; break;
9503     case T_LONG: state_type = "[J"; break;
9504     default: ShouldNotReachHere();
9505   }
9506   Node* digest_state = load_field_from_object(digest_object, "state", state_type);
9507   assert (digest_state != nullptr, "wrong version of sun.security.provider.MD5/SHA/SHA2/SHA5/SHA3");
9508   if (digest_state == nullptr) return (Node *) nullptr;
9509 
9510   // now have the array, need to get the start address of the state array
9511   Node* state = array_element_address(digest_state, intcon(0), elem_type);
9512   return state;
9513 }
9514 
9515 //------------------------------get_block_size_from_sha3_object----------------------------------
9516 Node * LibraryCallKit::get_block_size_from_digest_object(Node *digest_object) {
9517   Node* block_size = load_field_from_object(digest_object, "blockSize", "I");
9518   assert (block_size != nullptr, "sanity");
9519   return block_size;
9520 }
9521 
9522 //----------------------------inline_digestBase_implCompressMB_predicate----------------------------
9523 // Return node representing slow path of predicate check.
9524 // the pseudo code we want to emulate with this predicate is:
9525 //    if (digestBaseObj instanceof MD5/SHA/SHA2/SHA5/SHA3) do_intrinsic, else do_javapath
9526 //
9527 Node* LibraryCallKit::inline_digestBase_implCompressMB_predicate(int predicate) {
9528   assert(UseMD5Intrinsics || UseSHA1Intrinsics || UseSHA256Intrinsics || UseSHA512Intrinsics || UseSHA3Intrinsics,
9529          "need MD5/SHA1/SHA256/SHA512/SHA3 instruction support");
9530   assert((uint)predicate < 5, "sanity");
9531 
9532   // The receiver was checked for null already.
9533   Node* digestBaseObj = argument(0);
9534 
9535   // get DigestBase klass for instanceOf check
9536   const TypeInstPtr* tinst = _gvn.type(digestBaseObj)->isa_instptr();
9537   assert(tinst != nullptr, "digestBaseObj is null");
9538   assert(tinst->is_loaded(), "DigestBase is not loaded");
9539 
9540   const char* klass_name = nullptr;
9541   switch (predicate) {
9542   case 0:
9543     if (UseMD5Intrinsics) {
9544       // we want to do an instanceof comparison against the MD5 class
9545       klass_name = "sun/security/provider/MD5";
9546     }
9547     break;
9548   case 1:
9549     if (UseSHA1Intrinsics) {
9550       // we want to do an instanceof comparison against the SHA class
9551       klass_name = "sun/security/provider/SHA";
9552     }
9553     break;
9554   case 2:
9555     if (UseSHA256Intrinsics) {
9556       // we want to do an instanceof comparison against the SHA2 class
9557       klass_name = "sun/security/provider/SHA2";
9558     }
9559     break;
9560   case 3:
9561     if (UseSHA512Intrinsics) {
9562       // we want to do an instanceof comparison against the SHA5 class
9563       klass_name = "sun/security/provider/SHA5";
9564     }
9565     break;
9566   case 4:
9567     if (UseSHA3Intrinsics) {
9568       // we want to do an instanceof comparison against the SHA3 class
9569       klass_name = "sun/security/provider/SHA3";
9570     }
9571     break;
9572   default:
9573     fatal("unknown SHA intrinsic predicate: %d", predicate);
9574   }
9575 
9576   ciKlass* klass = nullptr;
9577   if (klass_name != nullptr) {
9578     klass = tinst->instance_klass()->find_klass(ciSymbol::make(klass_name));
9579   }
9580   if ((klass == nullptr) || !klass->is_loaded()) {
9581     // if none of MD5/SHA/SHA2/SHA5 is loaded, we never take the intrinsic fast path
9582     Node* ctrl = control();
9583     set_control(top()); // no intrinsic path
9584     return ctrl;
9585   }
9586   ciInstanceKlass* instklass = klass->as_instance_klass();
9587 
9588   Node* instof = gen_instanceof(digestBaseObj, makecon(TypeKlassPtr::make(instklass)));
9589   Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
9590   Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
9591   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
9592 
9593   return instof_false;  // even if it is null
9594 }
9595 
9596 //-------------inline_fma-----------------------------------
9597 bool LibraryCallKit::inline_fma(vmIntrinsics::ID id) {
9598   Node *a = nullptr;
9599   Node *b = nullptr;
9600   Node *c = nullptr;
9601   Node* result = nullptr;
9602   switch (id) {
9603   case vmIntrinsics::_fmaD:
9604     assert(callee()->signature()->size() == 6, "fma has 3 parameters of size 2 each.");
9605     // no receiver since it is static method
9606     a = argument(0);
9607     b = argument(2);
9608     c = argument(4);
9609     result = _gvn.transform(new FmaDNode(a, b, c));
9610     break;
9611   case vmIntrinsics::_fmaF:
9612     assert(callee()->signature()->size() == 3, "fma has 3 parameters of size 1 each.");
9613     a = argument(0);
9614     b = argument(1);
9615     c = argument(2);
9616     result = _gvn.transform(new FmaFNode(a, b, c));
9617     break;
9618   default:
9619     fatal_unexpected_iid(id);  break;
9620   }
9621   set_result(result);
9622   return true;
9623 }
9624 
9625 bool LibraryCallKit::inline_character_compare(vmIntrinsics::ID id) {
9626   // argument(0) is receiver
9627   Node* codePoint = argument(1);
9628   Node* n = nullptr;
9629 
9630   switch (id) {
9631     case vmIntrinsics::_isDigit :
9632       n = new DigitNode(control(), codePoint);
9633       break;
9634     case vmIntrinsics::_isLowerCase :
9635       n = new LowerCaseNode(control(), codePoint);
9636       break;
9637     case vmIntrinsics::_isUpperCase :
9638       n = new UpperCaseNode(control(), codePoint);
9639       break;
9640     case vmIntrinsics::_isWhitespace :
9641       n = new WhitespaceNode(control(), codePoint);
9642       break;
9643     default:
9644       fatal_unexpected_iid(id);
9645   }
9646 
9647   set_result(_gvn.transform(n));
9648   return true;
9649 }
9650 
9651 bool LibraryCallKit::inline_profileBoolean() {
9652   Node* counts = argument(1);
9653   const TypeAryPtr* ary = nullptr;
9654   ciArray* aobj = nullptr;
9655   if (counts->is_Con()
9656       && (ary = counts->bottom_type()->isa_aryptr()) != nullptr
9657       && (aobj = ary->const_oop()->as_array()) != nullptr
9658       && (aobj->length() == 2)) {
9659     // Profile is int[2] where [0] and [1] correspond to false and true value occurrences respectively.
9660     jint false_cnt = aobj->element_value(0).as_int();
9661     jint  true_cnt = aobj->element_value(1).as_int();
9662 
9663     if (C->log() != nullptr) {
9664       C->log()->elem("observe source='profileBoolean' false='%d' true='%d'",
9665                      false_cnt, true_cnt);
9666     }
9667 
9668     if (false_cnt + true_cnt == 0) {
9669       // According to profile, never executed.
9670       uncommon_trap_exact(Deoptimization::Reason_intrinsic,
9671                           Deoptimization::Action_reinterpret);
9672       return true;
9673     }
9674 
9675     // result is a boolean (0 or 1) and its profile (false_cnt & true_cnt)
9676     // is a number of each value occurrences.
9677     Node* result = argument(0);
9678     if (false_cnt == 0 || true_cnt == 0) {
9679       // According to profile, one value has been never seen.
9680       int expected_val = (false_cnt == 0) ? 1 : 0;
9681 
9682       Node* cmp  = _gvn.transform(new CmpINode(result, intcon(expected_val)));
9683       Node* test = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
9684 
9685       IfNode* check = create_and_map_if(control(), test, PROB_ALWAYS, COUNT_UNKNOWN);
9686       Node* fast_path = _gvn.transform(new IfTrueNode(check));
9687       Node* slow_path = _gvn.transform(new IfFalseNode(check));
9688 
9689       { // Slow path: uncommon trap for never seen value and then reexecute
9690         // MethodHandleImpl::profileBoolean() to bump the count, so JIT knows
9691         // the value has been seen at least once.
9692         PreserveJVMState pjvms(this);
9693         PreserveReexecuteState preexecs(this);
9694         jvms()->set_should_reexecute(true);
9695 
9696         set_control(slow_path);
9697         set_i_o(i_o());
9698 
9699         uncommon_trap_exact(Deoptimization::Reason_intrinsic,
9700                             Deoptimization::Action_reinterpret);
9701       }
9702       // The guard for never seen value enables sharpening of the result and
9703       // returning a constant. It allows to eliminate branches on the same value
9704       // later on.
9705       set_control(fast_path);
9706       result = intcon(expected_val);
9707     }
9708     // Stop profiling.
9709     // MethodHandleImpl::profileBoolean() has profiling logic in its bytecode.
9710     // By replacing method body with profile data (represented as ProfileBooleanNode
9711     // on IR level) we effectively disable profiling.
9712     // It enables full speed execution once optimized code is generated.
9713     Node* profile = _gvn.transform(new ProfileBooleanNode(result, false_cnt, true_cnt));
9714     C->record_for_igvn(profile);
9715     set_result(profile);
9716     return true;
9717   } else {
9718     // Continue profiling.
9719     // Profile data isn't available at the moment. So, execute method's bytecode version.
9720     // Usually, when GWT LambdaForms are profiled it means that a stand-alone nmethod
9721     // is compiled and counters aren't available since corresponding MethodHandle
9722     // isn't a compile-time constant.
9723     return false;
9724   }
9725 }
9726 
9727 bool LibraryCallKit::inline_isCompileConstant() {
9728   Node* n = argument(0);
9729   set_result(n->is_Con() ? intcon(1) : intcon(0));
9730   return true;
9731 }
9732 
9733 //------------------------------- inline_getObjectSize --------------------------------------
9734 //
9735 // Calculate the runtime size of the object/array.
9736 //   native long sun.instrument.InstrumentationImpl.getObjectSize0(long nativeAgent, Object objectToSize);
9737 //
9738 bool LibraryCallKit::inline_getObjectSize() {
9739   Node* obj = argument(3);
9740   Node* klass_node = load_object_klass(obj);
9741 
9742   jint  layout_con = Klass::_lh_neutral_value;
9743   Node* layout_val = get_layout_helper(klass_node, layout_con);
9744   int   layout_is_con = (layout_val == nullptr);
9745 
9746   if (layout_is_con) {
9747     // Layout helper is constant, can figure out things at compile time.
9748 
9749     if (Klass::layout_helper_is_instance(layout_con)) {
9750       // Instance case:  layout_con contains the size itself.
9751       Node *size = longcon(Klass::layout_helper_size_in_bytes(layout_con));
9752       set_result(size);
9753     } else {
9754       // Array case: size is round(header + element_size*arraylength).
9755       // Since arraylength is different for every array instance, we have to
9756       // compute the whole thing at runtime.
9757 
9758       Node* arr_length = load_array_length(obj);
9759 
9760       int round_mask = MinObjAlignmentInBytes - 1;
9761       int hsize  = Klass::layout_helper_header_size(layout_con);
9762       int eshift = Klass::layout_helper_log2_element_size(layout_con);
9763 
9764       if ((round_mask & ~right_n_bits(eshift)) == 0) {
9765         round_mask = 0;  // strength-reduce it if it goes away completely
9766       }
9767       assert((hsize & right_n_bits(eshift)) == 0, "hsize is pre-rounded");
9768       Node* header_size = intcon(hsize + round_mask);
9769 
9770       Node* lengthx = ConvI2X(arr_length);
9771       Node* headerx = ConvI2X(header_size);
9772 
9773       Node* abody = lengthx;
9774       if (eshift != 0) {
9775         abody = _gvn.transform(new LShiftXNode(lengthx, intcon(eshift)));
9776       }
9777       Node* size = _gvn.transform( new AddXNode(headerx, abody) );
9778       if (round_mask != 0) {
9779         size = _gvn.transform( new AndXNode(size, MakeConX(~round_mask)) );
9780       }
9781       size = ConvX2L(size);
9782       set_result(size);
9783     }
9784   } else {
9785     // Layout helper is not constant, need to test for array-ness at runtime.
9786 
9787     enum { _instance_path = 1, _array_path, PATH_LIMIT };
9788     RegionNode* result_reg = new RegionNode(PATH_LIMIT);
9789     PhiNode* result_val = new PhiNode(result_reg, TypeLong::LONG);
9790     record_for_igvn(result_reg);
9791 
9792     Node* array_ctl = generate_array_guard(klass_node, nullptr, &obj);
9793     if (array_ctl != nullptr) {
9794       // Array case: size is round(header + element_size*arraylength).
9795       // Since arraylength is different for every array instance, we have to
9796       // compute the whole thing at runtime.
9797 
9798       PreserveJVMState pjvms(this);
9799       set_control(array_ctl);
9800       Node* arr_length = load_array_length(obj);
9801 
9802       int round_mask = MinObjAlignmentInBytes - 1;
9803       Node* mask = intcon(round_mask);
9804 
9805       Node* hss = intcon(Klass::_lh_header_size_shift);
9806       Node* hsm = intcon(Klass::_lh_header_size_mask);
9807       Node* header_size = _gvn.transform(new URShiftINode(layout_val, hss));
9808       header_size = _gvn.transform(new AndINode(header_size, hsm));
9809       header_size = _gvn.transform(new AddINode(header_size, mask));
9810 
9811       // There is no need to mask or shift this value.
9812       // The semantics of LShiftINode include an implicit mask to 0x1F.
9813       assert(Klass::_lh_log2_element_size_shift == 0, "use shift in place");
9814       Node* elem_shift = layout_val;
9815 
9816       Node* lengthx = ConvI2X(arr_length);
9817       Node* headerx = ConvI2X(header_size);
9818 
9819       Node* abody = _gvn.transform(new LShiftXNode(lengthx, elem_shift));
9820       Node* size = _gvn.transform(new AddXNode(headerx, abody));
9821       if (round_mask != 0) {
9822         size = _gvn.transform(new AndXNode(size, MakeConX(~round_mask)));
9823       }
9824       size = ConvX2L(size);
9825 
9826       result_reg->init_req(_array_path, control());
9827       result_val->init_req(_array_path, size);
9828     }
9829 
9830     if (!stopped()) {
9831       // Instance case: the layout helper gives us instance size almost directly,
9832       // but we need to mask out the _lh_instance_slow_path_bit.
9833       Node* size = ConvI2X(layout_val);
9834       assert((int) Klass::_lh_instance_slow_path_bit < BytesPerLong, "clear bit");
9835       Node* mask = MakeConX(~(intptr_t) right_n_bits(LogBytesPerLong));
9836       size = _gvn.transform(new AndXNode(size, mask));
9837       size = ConvX2L(size);
9838 
9839       result_reg->init_req(_instance_path, control());
9840       result_val->init_req(_instance_path, size);
9841     }
9842 
9843     set_result(result_reg, result_val);
9844   }
9845 
9846   return true;
9847 }
9848 
9849 //------------------------------- inline_blackhole --------------------------------------
9850 //
9851 // Make sure all arguments to this node are alive.
9852 // This matches methods that were requested to be blackholed through compile commands.
9853 //
9854 bool LibraryCallKit::inline_blackhole() {
9855   assert(callee()->is_static(), "Should have been checked before: only static methods here");
9856   assert(callee()->is_empty(), "Should have been checked before: only empty methods here");
9857   assert(callee()->holder()->is_loaded(), "Should have been checked before: only methods for loaded classes here");
9858 
9859   // Blackhole node pinches only the control, not memory. This allows
9860   // the blackhole to be pinned in the loop that computes blackholed
9861   // values, but have no other side effects, like breaking the optimizations
9862   // across the blackhole.
9863 
9864   Node* bh = _gvn.transform(new BlackholeNode(control()));
9865   set_control(_gvn.transform(new ProjNode(bh, TypeFunc::Control)));
9866 
9867   // Bind call arguments as blackhole arguments to keep them alive
9868   uint nargs = callee()->arg_size();
9869   for (uint i = 0; i < nargs; i++) {
9870     bh->add_req(argument(i));
9871   }
9872 
9873   return true;
9874 }
9875 
9876 Node* LibraryCallKit::unbox_fp16_value(const TypeInstPtr* float16_box_type, ciField* field, Node* box) {
9877   const TypeInstPtr* box_type = _gvn.type(box)->isa_instptr();
9878   if (box_type == nullptr || box_type->instance_klass() != float16_box_type->instance_klass()) {
9879     return nullptr; // box klass is not Float16
9880   }
9881 
9882   // Null check; get notnull casted pointer
9883   Node* null_ctl = top();
9884   Node* not_null_box = null_check_oop(box, &null_ctl, true);
9885   // If not_null_box is dead, only null-path is taken
9886   if (stopped()) {
9887     set_control(null_ctl);
9888     return nullptr;
9889   }
9890   assert(not_null_box->bottom_type()->is_instptr()->maybe_null() == false, "");
9891   const TypePtr* adr_type = C->alias_type(field)->adr_type();
9892   Node* adr = basic_plus_adr(not_null_box, field->offset_in_bytes());
9893   return access_load_at(not_null_box, adr, adr_type, TypeInt::SHORT, T_SHORT, IN_HEAP);
9894 }
9895 
9896 Node* LibraryCallKit::box_fp16_value(const TypeInstPtr* float16_box_type, ciField* field, Node* value) {
9897   PreserveReexecuteState preexecs(this);
9898   jvms()->set_should_reexecute(true);
9899 
9900   const TypeKlassPtr* klass_type = float16_box_type->as_klass_type();
9901   Node* klass_node = makecon(klass_type);
9902   Node* box = new_instance(klass_node);
9903 
9904   Node* value_field = basic_plus_adr(box, field->offset_in_bytes());
9905   const TypePtr* value_adr_type = value_field->bottom_type()->is_ptr();
9906 
9907   Node* field_store = _gvn.transform(access_store_at(box,
9908                                                      value_field,
9909                                                      value_adr_type,
9910                                                      value,
9911                                                      TypeInt::SHORT,
9912                                                      T_SHORT,
9913                                                      IN_HEAP));
9914   set_memory(field_store, value_adr_type);
9915   return box;
9916 }
9917 
9918 bool LibraryCallKit::inline_fp16_operations(vmIntrinsics::ID id, int num_args) {
9919   if (!Matcher::match_rule_supported(Op_ReinterpretS2HF) ||
9920       !Matcher::match_rule_supported(Op_ReinterpretHF2S)) {
9921     return false;
9922   }
9923 
9924   const TypeInstPtr* box_type = _gvn.type(argument(0))->isa_instptr();
9925   if (box_type == nullptr || box_type->const_oop() == nullptr) {
9926     return false;
9927   }
9928 
9929   ciInstanceKlass* float16_klass = box_type->const_oop()->as_instance()->java_lang_Class_klass()->as_instance_klass();
9930   const TypeInstPtr* float16_box_type = TypeInstPtr::make_exact(TypePtr::NotNull, float16_klass);
9931   ciField* field = float16_klass->get_field_by_name(ciSymbols::value_name(),
9932                                                     ciSymbols::short_signature(),
9933                                                     false);
9934   assert(field != nullptr, "");
9935 
9936   // Transformed nodes
9937   Node* fld1 = nullptr;
9938   Node* fld2 = nullptr;
9939   Node* fld3 = nullptr;
9940   switch(num_args) {
9941     case 3:
9942       fld3 = unbox_fp16_value(float16_box_type, field, argument(3));
9943       if (fld3 == nullptr) {
9944         return false;
9945       }
9946       fld3 = _gvn.transform(new ReinterpretS2HFNode(fld3));
9947     // fall-through
9948     case 2:
9949       fld2 = unbox_fp16_value(float16_box_type, field, argument(2));
9950       if (fld2 == nullptr) {
9951         return false;
9952       }
9953       fld2 = _gvn.transform(new ReinterpretS2HFNode(fld2));
9954     // fall-through
9955     case 1:
9956       fld1 = unbox_fp16_value(float16_box_type, field, argument(1));
9957       if (fld1 == nullptr) {
9958         return false;
9959       }
9960       fld1 = _gvn.transform(new ReinterpretS2HFNode(fld1));
9961       break;
9962     default: fatal("Unsupported number of arguments %d", num_args);
9963   }
9964 
9965   Node* result = nullptr;
9966   switch (id) {
9967     // Unary operations
9968     case vmIntrinsics::_sqrt_float16:
9969       result = _gvn.transform(new SqrtHFNode(C, control(), fld1));
9970       break;
9971     // Ternary operations
9972     case vmIntrinsics::_fma_float16:
9973       result = _gvn.transform(new FmaHFNode(fld1, fld2, fld3));
9974       break;
9975     default:
9976       fatal_unexpected_iid(id);
9977       break;
9978   }
9979   result = _gvn.transform(new ReinterpretHF2SNode(result));
9980   set_result(box_fp16_value(float16_box_type, field, result));
9981   return true;
9982 }
9983