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             // If we insert a checkcast here, we can be sure that init_val is an InlineTypeNode, so
4935             // when we folded a field load from an allocation (e.g. during escape analysis), we can
4936             // remove the check init_val->is_InlineType().
4937           }
4938           Node* obj = new_array(makecon(array_klass_type), length, 0, nullptr, false, init_val);
4939           const TypeAryPtr* arytype = gvn().type(obj)->is_aryptr();
4940           assert(arytype->is_null_free() == null_free, "inconsistency");
4941           assert(arytype->is_not_null_free() == !null_free, "inconsistency");
4942           set_result(obj);
4943           return true;
4944         }
4945       }
4946     }
4947   }
4948   return false;
4949 }
4950 
4951 // public static native boolean ValueClass::isFlatArray(Object array);
4952 // public static native boolean ValueClass::isNullRestrictedArray(Object array);
4953 // public static native boolean ValueClass::isAtomicArray(Object array);
4954 bool LibraryCallKit::inline_getArrayProperties(ArrayPropertiesCheck check) {
4955   Node* array = argument(0);
4956 
4957   Node* bol;
4958   switch(check) {
4959     case IsFlat:
4960       // TODO 8350865 Use the object version here instead of loading the klass
4961       // 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
4962       bol = flat_array_test(load_object_klass(array));
4963       break;
4964     case IsNullRestricted:
4965       bol = null_free_array_test(array);
4966       break;
4967     case IsAtomic:
4968       // TODO 8350865 Implement this. It's a bit more complicated, see conditions in JVM_IsAtomicArray
4969       // Enable TestIntrinsics::test87/88 once this is implemented
4970       // bol = null_free_atomic_array_test
4971       return false;
4972     default:
4973       ShouldNotReachHere();
4974   }
4975 
4976   Node* res = gvn().transform(new CMoveINode(bol, intcon(0), intcon(1), TypeInt::BOOL));
4977   set_result(res);
4978   return true;
4979 }
4980 
4981 // Load the default refined array klass from an ObjArrayKlass. This relies on the first entry in the
4982 // '_next_refined_array_klass' linked list being the default (see ObjArrayKlass::klass_with_properties).
4983 Node* LibraryCallKit::load_default_refined_array_klass(Node* klass_node, bool type_array_guard) {
4984   RegionNode* region = new RegionNode(2);
4985   Node* phi = new PhiNode(region, TypeInstKlassPtr::OBJECT_OR_NULL);
4986 
4987   if (type_array_guard) {
4988     generate_typeArray_guard(klass_node, region);
4989     if (region->req() == 3) {
4990       phi->add_req(klass_node);
4991     }
4992   }
4993   Node* adr_refined_klass = basic_plus_adr(klass_node, in_bytes(ObjArrayKlass::next_refined_array_klass_offset()));
4994   Node* refined_klass = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), adr_refined_klass, TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
4995 
4996   // Can be null if not initialized yet, just deopt
4997   Node* null_ctl = top();
4998   refined_klass = null_check_oop(refined_klass, &null_ctl, /* never_see_null= */ true);
4999 
5000   region->init_req(1, control());
5001   phi->init_req(1, refined_klass);
5002 
5003   set_control(_gvn.transform(region));
5004   return _gvn.transform(phi);
5005 }
5006 
5007 // Load the non-refined array klass from an ObjArrayKlass.
5008 Node* LibraryCallKit::load_non_refined_array_klass(Node* klass_node) {
5009   const TypeAryKlassPtr* ary_klass_ptr = _gvn.type(klass_node)->isa_aryklassptr();
5010   if (ary_klass_ptr != nullptr && ary_klass_ptr->klass_is_exact()) {
5011     return _gvn.makecon(ary_klass_ptr->cast_to_refined_array_klass_ptr(false));
5012   }
5013 
5014   RegionNode* region = new RegionNode(2);
5015   Node* phi = new PhiNode(region, TypeInstKlassPtr::OBJECT);
5016 
5017   generate_typeArray_guard(klass_node, region);
5018   if (region->req() == 3) {
5019     phi->add_req(klass_node);
5020   }
5021   Node* super_adr = basic_plus_adr(klass_node, in_bytes(Klass::super_offset()));
5022   Node* super_klass = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), super_adr, TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT));
5023 
5024   region->init_req(1, control());
5025   phi->init_req(1, super_klass);
5026 
5027   set_control(_gvn.transform(region));
5028   return _gvn.transform(phi);
5029 }
5030 
5031 //-----------------------inline_native_newArray--------------------------
5032 // private static native Object java.lang.reflect.Array.newArray(Class<?> componentType, int length);
5033 // private        native Object Unsafe.allocateUninitializedArray0(Class<?> cls, int size);
5034 bool LibraryCallKit::inline_unsafe_newArray(bool uninitialized) {
5035   Node* mirror;
5036   Node* count_val;
5037   if (uninitialized) {
5038     null_check_receiver();
5039     mirror    = argument(1);
5040     count_val = argument(2);
5041   } else {
5042     mirror    = argument(0);
5043     count_val = argument(1);
5044   }
5045 
5046   mirror = null_check(mirror);
5047   // If mirror or obj is dead, only null-path is taken.
5048   if (stopped())  return true;
5049 
5050   enum { _normal_path = 1, _slow_path = 2, PATH_LIMIT };
5051   RegionNode* result_reg = new RegionNode(PATH_LIMIT);
5052   PhiNode*    result_val = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
5053   PhiNode*    result_io  = new PhiNode(result_reg, Type::ABIO);
5054   PhiNode*    result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
5055 
5056   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
5057   Node* klass_node = load_array_klass_from_mirror(mirror, never_see_null,
5058                                                   result_reg, _slow_path);
5059   Node* normal_ctl   = control();
5060   Node* no_array_ctl = result_reg->in(_slow_path);
5061 
5062   // Generate code for the slow case.  We make a call to newArray().
5063   set_control(no_array_ctl);
5064   if (!stopped()) {
5065     // Either the input type is void.class, or else the
5066     // array klass has not yet been cached.  Either the
5067     // ensuing call will throw an exception, or else it
5068     // will cache the array klass for next time.
5069     PreserveJVMState pjvms(this);
5070     CallJavaNode* slow_call = nullptr;
5071     if (uninitialized) {
5072       // Generate optimized virtual call (holder class 'Unsafe' is final)
5073       slow_call = generate_method_call(vmIntrinsics::_allocateUninitializedArray, false, false, true);
5074     } else {
5075       slow_call = generate_method_call_static(vmIntrinsics::_newArray, true);
5076     }
5077     Node* slow_result = set_results_for_java_call(slow_call);
5078     // this->control() comes from set_results_for_java_call
5079     result_reg->set_req(_slow_path, control());
5080     result_val->set_req(_slow_path, slow_result);
5081     result_io ->set_req(_slow_path, i_o());
5082     result_mem->set_req(_slow_path, reset_memory());
5083   }
5084 
5085   set_control(normal_ctl);
5086   if (!stopped()) {
5087     // Normal case:  The array type has been cached in the java.lang.Class.
5088     // The following call works fine even if the array type is polymorphic.
5089     // It could be a dynamic mix of int[], boolean[], Object[], etc.
5090 
5091     klass_node = load_default_refined_array_klass(klass_node);
5092 
5093     Node* obj = new_array(klass_node, count_val, 0);  // no arguments to push
5094     result_reg->init_req(_normal_path, control());
5095     result_val->init_req(_normal_path, obj);
5096     result_io ->init_req(_normal_path, i_o());
5097     result_mem->init_req(_normal_path, reset_memory());
5098 
5099     if (uninitialized) {
5100       // Mark the allocation so that zeroing is skipped
5101       AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(obj);
5102       alloc->maybe_set_complete(&_gvn);
5103     }
5104   }
5105 
5106   // Return the combined state.
5107   set_i_o(        _gvn.transform(result_io)  );
5108   set_all_memory( _gvn.transform(result_mem));
5109 
5110   C->set_has_split_ifs(true); // Has chance for split-if optimization
5111   set_result(result_reg, result_val);
5112   return true;
5113 }
5114 
5115 //----------------------inline_native_getLength--------------------------
5116 // public static native int java.lang.reflect.Array.getLength(Object array);
5117 bool LibraryCallKit::inline_native_getLength() {
5118   if (too_many_traps(Deoptimization::Reason_intrinsic))  return false;
5119 
5120   Node* array = null_check(argument(0));
5121   // If array is dead, only null-path is taken.
5122   if (stopped())  return true;
5123 
5124   // Deoptimize if it is a non-array.
5125   Node* non_array = generate_non_array_guard(load_object_klass(array), nullptr, &array);
5126 
5127   if (non_array != nullptr) {
5128     PreserveJVMState pjvms(this);
5129     set_control(non_array);
5130     uncommon_trap(Deoptimization::Reason_intrinsic,
5131                   Deoptimization::Action_maybe_recompile);
5132   }
5133 
5134   // If control is dead, only non-array-path is taken.
5135   if (stopped())  return true;
5136 
5137   // The works fine even if the array type is polymorphic.
5138   // It could be a dynamic mix of int[], boolean[], Object[], etc.
5139   Node* result = load_array_length(array);
5140 
5141   C->set_has_split_ifs(true);  // Has chance for split-if optimization
5142   set_result(result);
5143   return true;
5144 }
5145 
5146 //------------------------inline_array_copyOf----------------------------
5147 // public static <T,U> T[] java.util.Arrays.copyOf(     U[] original, int newLength,         Class<? extends T[]> newType);
5148 // public static <T,U> T[] java.util.Arrays.copyOfRange(U[] original, int from,      int to, Class<? extends T[]> newType);
5149 bool LibraryCallKit::inline_array_copyOf(bool is_copyOfRange) {
5150   if (too_many_traps(Deoptimization::Reason_intrinsic))  return false;
5151 
5152   // Get the arguments.
5153   Node* original          = argument(0);
5154   Node* start             = is_copyOfRange? argument(1): intcon(0);
5155   Node* end               = is_copyOfRange? argument(2): argument(1);
5156   Node* array_type_mirror = is_copyOfRange? argument(3): argument(2);
5157 
5158   Node* newcopy = nullptr;
5159 
5160   // Set the original stack and the reexecute bit for the interpreter to reexecute
5161   // the bytecode that invokes Arrays.copyOf if deoptimization happens.
5162   { PreserveReexecuteState preexecs(this);
5163     jvms()->set_should_reexecute(true);
5164 
5165     array_type_mirror = null_check(array_type_mirror);
5166     original          = null_check(original);
5167 
5168     // Check if a null path was taken unconditionally.
5169     if (stopped())  return true;
5170 
5171     Node* orig_length = load_array_length(original);
5172 
5173     Node* klass_node = load_klass_from_mirror(array_type_mirror, false, nullptr, 0);
5174     klass_node = null_check(klass_node);
5175 
5176     RegionNode* bailout = new RegionNode(1);
5177     record_for_igvn(bailout);
5178 
5179     // Despite the generic type of Arrays.copyOf, the mirror might be int, int[], etc.
5180     // Bail out if that is so.
5181     // Inline type array may have object field that would require a
5182     // write barrier. Conservatively, go to slow path.
5183     // TODO 8251971: Optimize for the case when flat src/dst are later found
5184     // to not contain oops (i.e., move this check to the macro expansion phase).
5185     BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
5186     const TypeAryPtr* orig_t = _gvn.type(original)->isa_aryptr();
5187     const TypeKlassPtr* tklass = _gvn.type(klass_node)->is_klassptr();
5188     bool exclude_flat = UseArrayFlattening && bs->array_copy_requires_gc_barriers(true, T_OBJECT, false, false, BarrierSetC2::Parsing) &&
5189                         // Can src array be flat and contain oops?
5190                         (orig_t == nullptr || (!orig_t->is_not_flat() && (!orig_t->is_flat() || orig_t->elem()->inline_klass()->contains_oops()))) &&
5191                         // Can dest array be flat and contain oops?
5192                         tklass->can_be_inline_array() && (!tklass->is_flat() || tklass->is_aryklassptr()->elem()->is_instklassptr()->instance_klass()->as_inline_klass()->contains_oops());
5193     Node* not_objArray = exclude_flat ? generate_non_refArray_guard(klass_node, bailout) : generate_typeArray_guard(klass_node, bailout);
5194 
5195     Node* refined_klass_node = load_default_refined_array_klass(klass_node, /* type_array_guard= */ false);
5196 
5197     if (not_objArray != nullptr) {
5198       // Improve the klass node's type from the new optimistic assumption:
5199       ciKlass* ak = ciArrayKlass::make(env()->Object_klass());
5200       bool not_flat = !UseArrayFlattening;
5201       bool not_null_free = !Arguments::is_valhalla_enabled();
5202       const Type* akls = TypeAryKlassPtr::make(TypePtr::NotNull, ak, Type::Offset(0), Type::trust_interfaces, not_flat, not_null_free, false, false, not_flat, true);
5203       Node* cast = new CastPPNode(control(), refined_klass_node, akls);
5204       refined_klass_node = _gvn.transform(cast);
5205     }
5206 
5207     // Bail out if either start or end is negative.
5208     generate_negative_guard(start, bailout, &start);
5209     generate_negative_guard(end,   bailout, &end);
5210 
5211     Node* length = end;
5212     if (_gvn.type(start) != TypeInt::ZERO) {
5213       length = _gvn.transform(new SubINode(end, start));
5214     }
5215 
5216     // Bail out if length is negative (i.e., if start > end).
5217     // Without this the new_array would throw
5218     // NegativeArraySizeException but IllegalArgumentException is what
5219     // should be thrown
5220     generate_negative_guard(length, bailout, &length);
5221 
5222     // Handle inline type arrays
5223     bool can_validate = !too_many_traps(Deoptimization::Reason_class_check);
5224     if (!stopped()) {
5225       // TODO 8251971
5226       if (!orig_t->is_null_free()) {
5227         // Not statically known to be null free, add a check
5228         generate_fair_guard(null_free_array_test(original), bailout);
5229       }
5230       orig_t = _gvn.type(original)->isa_aryptr();
5231       if (orig_t != nullptr && orig_t->is_flat()) {
5232         // Src is flat, check that dest is flat as well
5233         if (exclude_flat) {
5234           // Dest can't be flat, bail out
5235           bailout->add_req(control());
5236           set_control(top());
5237         } else {
5238           generate_fair_guard(flat_array_test(refined_klass_node, /* flat = */ false), bailout);
5239         }
5240         // TODO 8350865 This is not correct anymore. Write tests and fix logic similar to arraycopy.
5241       } else if (UseArrayFlattening && (orig_t == nullptr || !orig_t->is_not_flat()) &&
5242                  // If dest is flat, src must be flat as well (guaranteed by src <: dest check if validated).
5243                  ((!tklass->is_flat() && tklass->can_be_inline_array()) || !can_validate)) {
5244         // Src might be flat and dest might not be flat. Go to the slow path if src is flat.
5245         // TODO 8251971: Optimize for the case when src/dest are later found to be both flat.
5246         generate_fair_guard(flat_array_test(load_object_klass(original)), bailout);
5247         if (orig_t != nullptr) {
5248           orig_t = orig_t->cast_to_not_flat();
5249           original = _gvn.transform(new CheckCastPPNode(control(), original, orig_t));
5250         }
5251       }
5252       if (!can_validate) {
5253         // No validation. The subtype check emitted at macro expansion time will not go to the slow
5254         // path but call checkcast_arraycopy which can not handle flat/null-free inline type arrays.
5255         // TODO 8251971: Optimize for the case when src/dest are later found to be both flat/null-free.
5256         generate_fair_guard(flat_array_test(refined_klass_node), bailout);
5257         generate_fair_guard(null_free_array_test(original), bailout);
5258       }
5259     }
5260 
5261     // Bail out if start is larger than the original length
5262     Node* orig_tail = _gvn.transform(new SubINode(orig_length, start));
5263     generate_negative_guard(orig_tail, bailout, &orig_tail);
5264 
5265     if (bailout->req() > 1) {
5266       PreserveJVMState pjvms(this);
5267       set_control(_gvn.transform(bailout));
5268       uncommon_trap(Deoptimization::Reason_intrinsic,
5269                     Deoptimization::Action_maybe_recompile);
5270     }
5271 
5272     if (!stopped()) {
5273       // How many elements will we copy from the original?
5274       // The answer is MinI(orig_tail, length).
5275       Node* moved = _gvn.transform(new MinINode(orig_tail, length));
5276 
5277       // Generate a direct call to the right arraycopy function(s).
5278       // We know the copy is disjoint but we might not know if the
5279       // oop stores need checking.
5280       // Extreme case:  Arrays.copyOf((Integer[])x, 10, String[].class).
5281       // This will fail a store-check if x contains any non-nulls.
5282 
5283       // ArrayCopyNode:Ideal may transform the ArrayCopyNode to
5284       // loads/stores but it is legal only if we're sure the
5285       // Arrays.copyOf would succeed. So we need all input arguments
5286       // to the copyOf to be validated, including that the copy to the
5287       // new array won't trigger an ArrayStoreException. That subtype
5288       // check can be optimized if we know something on the type of
5289       // the input array from type speculation.
5290       if (_gvn.type(klass_node)->singleton()) {
5291         const TypeKlassPtr* subk = _gvn.type(load_object_klass(original))->is_klassptr();
5292         const TypeKlassPtr* superk = _gvn.type(klass_node)->is_klassptr();
5293 
5294         int test = C->static_subtype_check(superk, subk);
5295         if (test != Compile::SSC_always_true && test != Compile::SSC_always_false) {
5296           const TypeOopPtr* t_original = _gvn.type(original)->is_oopptr();
5297           if (t_original->speculative_type() != nullptr) {
5298             original = maybe_cast_profiled_obj(original, t_original->speculative_type(), true);
5299           }
5300         }
5301       }
5302 
5303       bool validated = false;
5304       // Reason_class_check rather than Reason_intrinsic because we
5305       // want to intrinsify even if this traps.
5306       if (can_validate) {
5307         Node* not_subtype_ctrl = gen_subtype_check(original, klass_node);
5308 
5309         if (not_subtype_ctrl != top()) {
5310           PreserveJVMState pjvms(this);
5311           set_control(not_subtype_ctrl);
5312           uncommon_trap(Deoptimization::Reason_class_check,
5313                         Deoptimization::Action_make_not_entrant);
5314           assert(stopped(), "Should be stopped");
5315         }
5316         validated = true;
5317       }
5318 
5319       if (!stopped()) {
5320         newcopy = new_array(refined_klass_node, length, 0);  // no arguments to push
5321 
5322         ArrayCopyNode* ac = ArrayCopyNode::make(this, true, original, start, newcopy, intcon(0), moved, true, true,
5323                                                 load_object_klass(original), klass_node);
5324         if (!is_copyOfRange) {
5325           ac->set_copyof(validated);
5326         } else {
5327           ac->set_copyofrange(validated);
5328         }
5329         Node* n = _gvn.transform(ac);
5330         if (n == ac) {
5331           ac->connect_outputs(this);
5332         } else {
5333           assert(validated, "shouldn't transform if all arguments not validated");
5334           set_all_memory(n);
5335         }
5336       }
5337     }
5338   } // original reexecute is set back here
5339 
5340   C->set_has_split_ifs(true); // Has chance for split-if optimization
5341   if (!stopped()) {
5342     set_result(newcopy);
5343   }
5344   return true;
5345 }
5346 
5347 
5348 //----------------------generate_virtual_guard---------------------------
5349 // Helper for hashCode and clone.  Peeks inside the vtable to avoid a call.
5350 Node* LibraryCallKit::generate_virtual_guard(Node* obj_klass,
5351                                              RegionNode* slow_region) {
5352   ciMethod* method = callee();
5353   int vtable_index = method->vtable_index();
5354   assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index,
5355          "bad index %d", vtable_index);
5356   // Get the Method* out of the appropriate vtable entry.
5357   int entry_offset  = in_bytes(Klass::vtable_start_offset()) +
5358                      vtable_index*vtableEntry::size_in_bytes() +
5359                      in_bytes(vtableEntry::method_offset());
5360   Node* entry_addr  = basic_plus_adr(obj_klass, entry_offset);
5361   Node* target_call = make_load(nullptr, entry_addr, TypePtr::NOTNULL, T_ADDRESS, MemNode::unordered);
5362 
5363   // Compare the target method with the expected method (e.g., Object.hashCode).
5364   const TypePtr* native_call_addr = TypeMetadataPtr::make(method);
5365 
5366   Node* native_call = makecon(native_call_addr);
5367   Node* chk_native  = _gvn.transform(new CmpPNode(target_call, native_call));
5368   Node* test_native = _gvn.transform(new BoolNode(chk_native, BoolTest::ne));
5369 
5370   return generate_slow_guard(test_native, slow_region);
5371 }
5372 
5373 //-----------------------generate_method_call----------------------------
5374 // Use generate_method_call to make a slow-call to the real
5375 // method if the fast path fails.  An alternative would be to
5376 // use a stub like OptoRuntime::slow_arraycopy_Java.
5377 // This only works for expanding the current library call,
5378 // not another intrinsic.  (E.g., don't use this for making an
5379 // arraycopy call inside of the copyOf intrinsic.)
5380 CallJavaNode*
5381 LibraryCallKit::generate_method_call(vmIntrinsicID method_id, bool is_virtual, bool is_static, bool res_not_null) {
5382   // When compiling the intrinsic method itself, do not use this technique.
5383   guarantee(callee() != C->method(), "cannot make slow-call to self");
5384 
5385   ciMethod* method = callee();
5386   // ensure the JVMS we have will be correct for this call
5387   guarantee(method_id == method->intrinsic_id(), "must match");
5388 
5389   const TypeFunc* tf = TypeFunc::make(method);
5390   if (res_not_null) {
5391     assert(tf->return_type() == T_OBJECT, "");
5392     const TypeTuple* range = tf->range_cc();
5393     const Type** fields = TypeTuple::fields(range->cnt());
5394     fields[TypeFunc::Parms] = range->field_at(TypeFunc::Parms)->filter_speculative(TypePtr::NOTNULL);
5395     const TypeTuple* new_range = TypeTuple::make(range->cnt(), fields);
5396     tf = TypeFunc::make(tf->domain_cc(), new_range);
5397   }
5398   CallJavaNode* slow_call;
5399   if (is_static) {
5400     assert(!is_virtual, "");
5401     slow_call = new CallStaticJavaNode(C, tf,
5402                            SharedRuntime::get_resolve_static_call_stub(), method);
5403   } else if (is_virtual) {
5404     assert(!gvn().type(argument(0))->maybe_null(), "should not be null");
5405     int vtable_index = Method::invalid_vtable_index;
5406     if (UseInlineCaches) {
5407       // Suppress the vtable call
5408     } else {
5409       // hashCode and clone are not a miranda methods,
5410       // so the vtable index is fixed.
5411       // No need to use the linkResolver to get it.
5412        vtable_index = method->vtable_index();
5413        assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index,
5414               "bad index %d", vtable_index);
5415     }
5416     slow_call = new CallDynamicJavaNode(tf,
5417                           SharedRuntime::get_resolve_virtual_call_stub(),
5418                           method, vtable_index);
5419   } else {  // neither virtual nor static:  opt_virtual
5420     assert(!gvn().type(argument(0))->maybe_null(), "should not be null");
5421     slow_call = new CallStaticJavaNode(C, tf,
5422                                 SharedRuntime::get_resolve_opt_virtual_call_stub(), method);
5423     slow_call->set_optimized_virtual(true);
5424   }
5425   if (CallGenerator::is_inlined_method_handle_intrinsic(this->method(), bci(), callee())) {
5426     // To be able to issue a direct call (optimized virtual or virtual)
5427     // and skip a call to MH.linkTo*/invokeBasic adapter, additional information
5428     // about the method being invoked should be attached to the call site to
5429     // make resolution logic work (see SharedRuntime::resolve_{virtual,opt_virtual}_call_C).
5430     slow_call->set_override_symbolic_info(true);
5431   }
5432   set_arguments_for_java_call(slow_call);
5433   set_edges_for_java_call(slow_call);
5434   return slow_call;
5435 }
5436 
5437 
5438 /**
5439  * Build special case code for calls to hashCode on an object. This call may
5440  * be virtual (invokevirtual) or bound (invokespecial). For each case we generate
5441  * slightly different code.
5442  */
5443 bool LibraryCallKit::inline_native_hashcode(bool is_virtual, bool is_static) {
5444   assert(is_static == callee()->is_static(), "correct intrinsic selection");
5445   assert(!(is_virtual && is_static), "either virtual, special, or static");
5446 
5447   enum { _slow_path = 1, _fast_path, _null_path, PATH_LIMIT };
5448 
5449   RegionNode* result_reg = new RegionNode(PATH_LIMIT);
5450   PhiNode*    result_val = new PhiNode(result_reg, TypeInt::INT);
5451   PhiNode*    result_io  = new PhiNode(result_reg, Type::ABIO);
5452   PhiNode*    result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
5453   Node* obj = argument(0);
5454 
5455   // Don't intrinsify hashcode on inline types for now.
5456   // The "is locked" runtime check also subsumes the inline type check (as inline types cannot be locked) and goes to the slow path.
5457   if (gvn().type(obj)->is_inlinetypeptr()) {
5458     return false;
5459   }
5460 
5461   if (!is_static) {
5462     // Check for hashing null object
5463     obj = null_check_receiver();
5464     if (stopped())  return true;        // unconditionally null
5465     result_reg->init_req(_null_path, top());
5466     result_val->init_req(_null_path, top());
5467   } else {
5468     // Do a null check, and return zero if null.
5469     // System.identityHashCode(null) == 0
5470     Node* null_ctl = top();
5471     obj = null_check_oop(obj, &null_ctl);
5472     result_reg->init_req(_null_path, null_ctl);
5473     result_val->init_req(_null_path, _gvn.intcon(0));
5474   }
5475 
5476   // Unconditionally null?  Then return right away.
5477   if (stopped()) {
5478     set_control( result_reg->in(_null_path));
5479     if (!stopped())
5480       set_result(result_val->in(_null_path));
5481     return true;
5482   }
5483 
5484   // We only go to the fast case code if we pass a number of guards.  The
5485   // paths which do not pass are accumulated in the slow_region.
5486   RegionNode* slow_region = new RegionNode(1);
5487   record_for_igvn(slow_region);
5488 
5489   // If this is a virtual call, we generate a funny guard.  We pull out
5490   // the vtable entry corresponding to hashCode() from the target object.
5491   // If the target method which we are calling happens to be the native
5492   // Object hashCode() method, we pass the guard.  We do not need this
5493   // guard for non-virtual calls -- the caller is known to be the native
5494   // Object hashCode().
5495   if (is_virtual) {
5496     // After null check, get the object's klass.
5497     Node* obj_klass = load_object_klass(obj);
5498     generate_virtual_guard(obj_klass, slow_region);
5499   }
5500 
5501   // Get the header out of the object, use LoadMarkNode when available
5502   Node* header_addr = basic_plus_adr(obj, oopDesc::mark_offset_in_bytes());
5503   // The control of the load must be null. Otherwise, the load can move before
5504   // the null check after castPP removal.
5505   Node* no_ctrl = nullptr;
5506   Node* header = make_load(no_ctrl, header_addr, TypeX_X, TypeX_X->basic_type(), MemNode::unordered);
5507 
5508   if (!UseObjectMonitorTable) {
5509     // Test the header to see if it is safe to read w.r.t. locking.
5510     // We cannot use the inline type mask as this may check bits that are overriden
5511     // by an object monitor's pointer when inflating locking.
5512     Node *lock_mask      = _gvn.MakeConX(markWord::lock_mask_in_place);
5513     Node *lmasked_header = _gvn.transform(new AndXNode(header, lock_mask));
5514     Node *monitor_val   = _gvn.MakeConX(markWord::monitor_value);
5515     Node *chk_monitor   = _gvn.transform(new CmpXNode(lmasked_header, monitor_val));
5516     Node *test_monitor  = _gvn.transform(new BoolNode(chk_monitor, BoolTest::eq));
5517 
5518     generate_slow_guard(test_monitor, slow_region);
5519   }
5520 
5521   // Get the hash value and check to see that it has been properly assigned.
5522   // We depend on hash_mask being at most 32 bits and avoid the use of
5523   // hash_mask_in_place because it could be larger than 32 bits in a 64-bit
5524   // vm: see markWord.hpp.
5525   Node *hash_mask      = _gvn.intcon(markWord::hash_mask);
5526   Node *hash_shift     = _gvn.intcon(markWord::hash_shift);
5527   Node *hshifted_header= _gvn.transform(new URShiftXNode(header, hash_shift));
5528   // This hack lets the hash bits live anywhere in the mark object now, as long
5529   // as the shift drops the relevant bits into the low 32 bits.  Note that
5530   // Java spec says that HashCode is an int so there's no point in capturing
5531   // an 'X'-sized hashcode (32 in 32-bit build or 64 in 64-bit build).
5532   hshifted_header      = ConvX2I(hshifted_header);
5533   Node *hash_val       = _gvn.transform(new AndINode(hshifted_header, hash_mask));
5534 
5535   Node *no_hash_val    = _gvn.intcon(markWord::no_hash);
5536   Node *chk_assigned   = _gvn.transform(new CmpINode( hash_val, no_hash_val));
5537   Node *test_assigned  = _gvn.transform(new BoolNode( chk_assigned, BoolTest::eq));
5538 
5539   generate_slow_guard(test_assigned, slow_region);
5540 
5541   Node* init_mem = reset_memory();
5542   // fill in the rest of the null path:
5543   result_io ->init_req(_null_path, i_o());
5544   result_mem->init_req(_null_path, init_mem);
5545 
5546   result_val->init_req(_fast_path, hash_val);
5547   result_reg->init_req(_fast_path, control());
5548   result_io ->init_req(_fast_path, i_o());
5549   result_mem->init_req(_fast_path, init_mem);
5550 
5551   // Generate code for the slow case.  We make a call to hashCode().
5552   set_control(_gvn.transform(slow_region));
5553   if (!stopped()) {
5554     // No need for PreserveJVMState, because we're using up the present state.
5555     set_all_memory(init_mem);
5556     vmIntrinsics::ID hashCode_id = is_static ? vmIntrinsics::_identityHashCode : vmIntrinsics::_hashCode;
5557     CallJavaNode* slow_call = generate_method_call(hashCode_id, is_virtual, is_static, false);
5558     Node* slow_result = set_results_for_java_call(slow_call);
5559     // this->control() comes from set_results_for_java_call
5560     result_reg->init_req(_slow_path, control());
5561     result_val->init_req(_slow_path, slow_result);
5562     result_io  ->set_req(_slow_path, i_o());
5563     result_mem ->set_req(_slow_path, reset_memory());
5564   }
5565 
5566   // Return the combined state.
5567   set_i_o(        _gvn.transform(result_io)  );
5568   set_all_memory( _gvn.transform(result_mem));
5569 
5570   set_result(result_reg, result_val);
5571   return true;
5572 }
5573 
5574 //---------------------------inline_native_getClass----------------------------
5575 // public final native Class<?> java.lang.Object.getClass();
5576 //
5577 // Build special case code for calls to getClass on an object.
5578 bool LibraryCallKit::inline_native_getClass() {
5579   Node* obj = argument(0);
5580   if (obj->is_InlineType()) {
5581     const Type* t = _gvn.type(obj);
5582     if (t->maybe_null()) {
5583       null_check(obj);
5584     }
5585     set_result(makecon(TypeInstPtr::make(t->inline_klass()->java_mirror())));
5586     return true;
5587   }
5588   obj = null_check_receiver();
5589   if (stopped())  return true;
5590   set_result(load_mirror_from_klass(load_object_klass(obj)));
5591   return true;
5592 }
5593 
5594 //-----------------inline_native_Reflection_getCallerClass---------------------
5595 // public static native Class<?> sun.reflect.Reflection.getCallerClass();
5596 //
5597 // In the presence of deep enough inlining, getCallerClass() becomes a no-op.
5598 //
5599 // NOTE: This code must perform the same logic as JVM_GetCallerClass
5600 // in that it must skip particular security frames and checks for
5601 // caller sensitive methods.
5602 bool LibraryCallKit::inline_native_Reflection_getCallerClass() {
5603 #ifndef PRODUCT
5604   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5605     tty->print_cr("Attempting to inline sun.reflect.Reflection.getCallerClass");
5606   }
5607 #endif
5608 
5609   if (!jvms()->has_method()) {
5610 #ifndef PRODUCT
5611     if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5612       tty->print_cr("  Bailing out because intrinsic was inlined at top level");
5613     }
5614 #endif
5615     return false;
5616   }
5617 
5618   // Walk back up the JVM state to find the caller at the required
5619   // depth.
5620   JVMState* caller_jvms = jvms();
5621 
5622   // Cf. JVM_GetCallerClass
5623   // NOTE: Start the loop at depth 1 because the current JVM state does
5624   // not include the Reflection.getCallerClass() frame.
5625   for (int n = 1; caller_jvms != nullptr; caller_jvms = caller_jvms->caller(), n++) {
5626     ciMethod* m = caller_jvms->method();
5627     switch (n) {
5628     case 0:
5629       fatal("current JVM state does not include the Reflection.getCallerClass frame");
5630       break;
5631     case 1:
5632       // Frame 0 and 1 must be caller sensitive (see JVM_GetCallerClass).
5633       if (!m->caller_sensitive()) {
5634 #ifndef PRODUCT
5635         if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5636           tty->print_cr("  Bailing out: CallerSensitive annotation expected at frame %d", n);
5637         }
5638 #endif
5639         return false;  // bail-out; let JVM_GetCallerClass do the work
5640       }
5641       break;
5642     default:
5643       if (!m->is_ignored_by_security_stack_walk()) {
5644         // We have reached the desired frame; return the holder class.
5645         // Acquire method holder as java.lang.Class and push as constant.
5646         ciInstanceKlass* caller_klass = caller_jvms->method()->holder();
5647         ciInstance* caller_mirror = caller_klass->java_mirror();
5648         set_result(makecon(TypeInstPtr::make(caller_mirror)));
5649 
5650 #ifndef PRODUCT
5651         if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5652           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());
5653           tty->print_cr("  JVM state at this point:");
5654           for (int i = jvms()->depth(), n = 1; i >= 1; i--, n++) {
5655             ciMethod* m = jvms()->of_depth(i)->method();
5656             tty->print_cr("   %d) %s.%s", n, m->holder()->name()->as_utf8(), m->name()->as_utf8());
5657           }
5658         }
5659 #endif
5660         return true;
5661       }
5662       break;
5663     }
5664   }
5665 
5666 #ifndef PRODUCT
5667   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5668     tty->print_cr("  Bailing out because caller depth exceeded inlining depth = %d", jvms()->depth());
5669     tty->print_cr("  JVM state at this point:");
5670     for (int i = jvms()->depth(), n = 1; i >= 1; i--, n++) {
5671       ciMethod* m = jvms()->of_depth(i)->method();
5672       tty->print_cr("   %d) %s.%s", n, m->holder()->name()->as_utf8(), m->name()->as_utf8());
5673     }
5674   }
5675 #endif
5676 
5677   return false;  // bail-out; let JVM_GetCallerClass do the work
5678 }
5679 
5680 bool LibraryCallKit::inline_fp_conversions(vmIntrinsics::ID id) {
5681   Node* arg = argument(0);
5682   Node* result = nullptr;
5683 
5684   switch (id) {
5685   case vmIntrinsics::_floatToRawIntBits:    result = new MoveF2INode(arg);  break;
5686   case vmIntrinsics::_intBitsToFloat:       result = new MoveI2FNode(arg);  break;
5687   case vmIntrinsics::_doubleToRawLongBits:  result = new MoveD2LNode(arg);  break;
5688   case vmIntrinsics::_longBitsToDouble:     result = new MoveL2DNode(arg);  break;
5689   case vmIntrinsics::_floatToFloat16:       result = new ConvF2HFNode(arg); break;
5690   case vmIntrinsics::_float16ToFloat:       result = new ConvHF2FNode(arg); break;
5691 
5692   case vmIntrinsics::_doubleToLongBits: {
5693     // two paths (plus control) merge in a wood
5694     RegionNode *r = new RegionNode(3);
5695     Node *phi = new PhiNode(r, TypeLong::LONG);
5696 
5697     Node *cmpisnan = _gvn.transform(new CmpDNode(arg, arg));
5698     // Build the boolean node
5699     Node *bolisnan = _gvn.transform(new BoolNode(cmpisnan, BoolTest::ne));
5700 
5701     // Branch either way.
5702     // NaN case is less traveled, which makes all the difference.
5703     IfNode *ifisnan = create_and_xform_if(control(), bolisnan, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
5704     Node *opt_isnan = _gvn.transform(ifisnan);
5705     assert( opt_isnan->is_If(), "Expect an IfNode");
5706     IfNode *opt_ifisnan = (IfNode*)opt_isnan;
5707     Node *iftrue = _gvn.transform(new IfTrueNode(opt_ifisnan));
5708 
5709     set_control(iftrue);
5710 
5711     static const jlong nan_bits = CONST64(0x7ff8000000000000);
5712     Node *slow_result = longcon(nan_bits); // return NaN
5713     phi->init_req(1, _gvn.transform( slow_result ));
5714     r->init_req(1, iftrue);
5715 
5716     // Else fall through
5717     Node *iffalse = _gvn.transform(new IfFalseNode(opt_ifisnan));
5718     set_control(iffalse);
5719 
5720     phi->init_req(2, _gvn.transform(new MoveD2LNode(arg)));
5721     r->init_req(2, iffalse);
5722 
5723     // Post merge
5724     set_control(_gvn.transform(r));
5725     record_for_igvn(r);
5726 
5727     C->set_has_split_ifs(true); // Has chance for split-if optimization
5728     result = phi;
5729     assert(result->bottom_type()->isa_long(), "must be");
5730     break;
5731   }
5732 
5733   case vmIntrinsics::_floatToIntBits: {
5734     // two paths (plus control) merge in a wood
5735     RegionNode *r = new RegionNode(3);
5736     Node *phi = new PhiNode(r, TypeInt::INT);
5737 
5738     Node *cmpisnan = _gvn.transform(new CmpFNode(arg, arg));
5739     // Build the boolean node
5740     Node *bolisnan = _gvn.transform(new BoolNode(cmpisnan, BoolTest::ne));
5741 
5742     // Branch either way.
5743     // NaN case is less traveled, which makes all the difference.
5744     IfNode *ifisnan = create_and_xform_if(control(), bolisnan, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
5745     Node *opt_isnan = _gvn.transform(ifisnan);
5746     assert( opt_isnan->is_If(), "Expect an IfNode");
5747     IfNode *opt_ifisnan = (IfNode*)opt_isnan;
5748     Node *iftrue = _gvn.transform(new IfTrueNode(opt_ifisnan));
5749 
5750     set_control(iftrue);
5751 
5752     static const jint nan_bits = 0x7fc00000;
5753     Node *slow_result = makecon(TypeInt::make(nan_bits)); // return NaN
5754     phi->init_req(1, _gvn.transform( slow_result ));
5755     r->init_req(1, iftrue);
5756 
5757     // Else fall through
5758     Node *iffalse = _gvn.transform(new IfFalseNode(opt_ifisnan));
5759     set_control(iffalse);
5760 
5761     phi->init_req(2, _gvn.transform(new MoveF2INode(arg)));
5762     r->init_req(2, iffalse);
5763 
5764     // Post merge
5765     set_control(_gvn.transform(r));
5766     record_for_igvn(r);
5767 
5768     C->set_has_split_ifs(true); // Has chance for split-if optimization
5769     result = phi;
5770     assert(result->bottom_type()->isa_int(), "must be");
5771     break;
5772   }
5773 
5774   default:
5775     fatal_unexpected_iid(id);
5776     break;
5777   }
5778   set_result(_gvn.transform(result));
5779   return true;
5780 }
5781 
5782 bool LibraryCallKit::inline_fp_range_check(vmIntrinsics::ID id) {
5783   Node* arg = argument(0);
5784   Node* result = nullptr;
5785 
5786   switch (id) {
5787   case vmIntrinsics::_floatIsInfinite:
5788     result = new IsInfiniteFNode(arg);
5789     break;
5790   case vmIntrinsics::_floatIsFinite:
5791     result = new IsFiniteFNode(arg);
5792     break;
5793   case vmIntrinsics::_doubleIsInfinite:
5794     result = new IsInfiniteDNode(arg);
5795     break;
5796   case vmIntrinsics::_doubleIsFinite:
5797     result = new IsFiniteDNode(arg);
5798     break;
5799   default:
5800     fatal_unexpected_iid(id);
5801     break;
5802   }
5803   set_result(_gvn.transform(result));
5804   return true;
5805 }
5806 
5807 //----------------------inline_unsafe_copyMemory-------------------------
5808 // public native void Unsafe.copyMemory0(Object srcBase, long srcOffset, Object destBase, long destOffset, long bytes);
5809 
5810 static bool has_wide_mem(PhaseGVN& gvn, Node* addr, Node* base) {
5811   const TypeAryPtr* addr_t = gvn.type(addr)->isa_aryptr();
5812   const Type*       base_t = gvn.type(base);
5813 
5814   bool in_native = (base_t == TypePtr::NULL_PTR);
5815   bool in_heap   = !TypePtr::NULL_PTR->higher_equal(base_t);
5816   bool is_mixed  = !in_heap && !in_native;
5817 
5818   if (is_mixed) {
5819     return true; // mixed accesses can touch both on-heap and off-heap memory
5820   }
5821   if (in_heap) {
5822     bool is_prim_array = (addr_t != nullptr) && (addr_t->elem() != Type::BOTTOM);
5823     if (!is_prim_array) {
5824       // Though Unsafe.copyMemory() ensures at runtime for on-heap accesses that base is a primitive array,
5825       // there's not enough type information available to determine proper memory slice for it.
5826       return true;
5827     }
5828   }
5829   return false;
5830 }
5831 
5832 bool LibraryCallKit::inline_unsafe_copyMemory() {
5833   if (callee()->is_static())  return false;  // caller must have the capability!
5834   null_check_receiver();  // null-check receiver
5835   if (stopped())  return true;
5836 
5837   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
5838 
5839   Node* src_base =         argument(1);  // type: oop
5840   Node* src_off  = ConvL2X(argument(2)); // type: long
5841   Node* dst_base =         argument(4);  // type: oop
5842   Node* dst_off  = ConvL2X(argument(5)); // type: long
5843   Node* size     = ConvL2X(argument(7)); // type: long
5844 
5845   assert(Unsafe_field_offset_to_byte_offset(11) == 11,
5846          "fieldOffset must be byte-scaled");
5847 
5848   Node* src_addr = make_unsafe_address(src_base, src_off);
5849   Node* dst_addr = make_unsafe_address(dst_base, dst_off);
5850 
5851   Node* thread = _gvn.transform(new ThreadLocalNode());
5852   Node* doing_unsafe_access_addr = basic_plus_adr(top(), thread, in_bytes(JavaThread::doing_unsafe_access_offset()));
5853   BasicType doing_unsafe_access_bt = T_BYTE;
5854   assert((sizeof(bool) * CHAR_BIT) == 8, "not implemented");
5855 
5856   // update volatile field
5857   store_to_memory(control(), doing_unsafe_access_addr, intcon(1), doing_unsafe_access_bt, MemNode::unordered);
5858 
5859   int flags = RC_LEAF | RC_NO_FP;
5860 
5861   const TypePtr* dst_type = TypePtr::BOTTOM;
5862 
5863   // Adjust memory effects of the runtime call based on input values.
5864   if (!has_wide_mem(_gvn, src_addr, src_base) &&
5865       !has_wide_mem(_gvn, dst_addr, dst_base)) {
5866     dst_type = _gvn.type(dst_addr)->is_ptr(); // narrow out memory
5867 
5868     const TypePtr* src_type = _gvn.type(src_addr)->is_ptr();
5869     if (C->get_alias_index(src_type) == C->get_alias_index(dst_type)) {
5870       flags |= RC_NARROW_MEM; // narrow in memory
5871     }
5872   }
5873 
5874   // Call it.  Note that the length argument is not scaled.
5875   make_runtime_call(flags,
5876                     OptoRuntime::fast_arraycopy_Type(),
5877                     StubRoutines::unsafe_arraycopy(),
5878                     "unsafe_arraycopy",
5879                     dst_type,
5880                     src_addr, dst_addr, size XTOP);
5881 
5882   store_to_memory(control(), doing_unsafe_access_addr, intcon(0), doing_unsafe_access_bt, MemNode::unordered);
5883 
5884   return true;
5885 }
5886 
5887 // unsafe_setmemory(void *base, ulong offset, size_t length, char fill_value);
5888 // Fill 'length' bytes starting from 'base[offset]' with 'fill_value'
5889 bool LibraryCallKit::inline_unsafe_setMemory() {
5890   if (callee()->is_static())  return false;  // caller must have the capability!
5891   null_check_receiver();  // null-check receiver
5892   if (stopped())  return true;
5893 
5894   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
5895 
5896   Node* dst_base =         argument(1);  // type: oop
5897   Node* dst_off  = ConvL2X(argument(2)); // type: long
5898   Node* size     = ConvL2X(argument(4)); // type: long
5899   Node* byte     =         argument(6);  // type: byte
5900 
5901   assert(Unsafe_field_offset_to_byte_offset(11) == 11,
5902          "fieldOffset must be byte-scaled");
5903 
5904   Node* dst_addr = make_unsafe_address(dst_base, dst_off);
5905 
5906   Node* thread = _gvn.transform(new ThreadLocalNode());
5907   Node* doing_unsafe_access_addr = basic_plus_adr(top(), thread, in_bytes(JavaThread::doing_unsafe_access_offset()));
5908   BasicType doing_unsafe_access_bt = T_BYTE;
5909   assert((sizeof(bool) * CHAR_BIT) == 8, "not implemented");
5910 
5911   // update volatile field
5912   store_to_memory(control(), doing_unsafe_access_addr, intcon(1), doing_unsafe_access_bt, MemNode::unordered);
5913 
5914   int flags = RC_LEAF | RC_NO_FP;
5915 
5916   const TypePtr* dst_type = TypePtr::BOTTOM;
5917 
5918   // Adjust memory effects of the runtime call based on input values.
5919   if (!has_wide_mem(_gvn, dst_addr, dst_base)) {
5920     dst_type = _gvn.type(dst_addr)->is_ptr(); // narrow out memory
5921 
5922     flags |= RC_NARROW_MEM; // narrow in memory
5923   }
5924 
5925   // Call it.  Note that the length argument is not scaled.
5926   make_runtime_call(flags,
5927                     OptoRuntime::unsafe_setmemory_Type(),
5928                     StubRoutines::unsafe_setmemory(),
5929                     "unsafe_setmemory",
5930                     dst_type,
5931                     dst_addr, size XTOP, byte);
5932 
5933   store_to_memory(control(), doing_unsafe_access_addr, intcon(0), doing_unsafe_access_bt, MemNode::unordered);
5934 
5935   return true;
5936 }
5937 
5938 #undef XTOP
5939 
5940 //------------------------clone_coping-----------------------------------
5941 // Helper function for inline_native_clone.
5942 void LibraryCallKit::copy_to_clone(Node* obj, Node* alloc_obj, Node* obj_size, bool is_array) {
5943   assert(obj_size != nullptr, "");
5944   Node* raw_obj = alloc_obj->in(1);
5945   assert(alloc_obj->is_CheckCastPP() && raw_obj->is_Proj() && raw_obj->in(0)->is_Allocate(), "");
5946 
5947   AllocateNode* alloc = nullptr;
5948   if (ReduceBulkZeroing &&
5949       // If we are implementing an array clone without knowing its source type
5950       // (can happen when compiling the array-guarded branch of a reflective
5951       // Object.clone() invocation), initialize the array within the allocation.
5952       // This is needed because some GCs (e.g. ZGC) might fall back in this case
5953       // to a runtime clone call that assumes fully initialized source arrays.
5954       (!is_array || obj->get_ptr_type()->isa_aryptr() != nullptr)) {
5955     // We will be completely responsible for initializing this object -
5956     // mark Initialize node as complete.
5957     alloc = AllocateNode::Ideal_allocation(alloc_obj);
5958     // The object was just allocated - there should be no any stores!
5959     guarantee(alloc != nullptr && alloc->maybe_set_complete(&_gvn), "");
5960     // Mark as complete_with_arraycopy so that on AllocateNode
5961     // expansion, we know this AllocateNode is initialized by an array
5962     // copy and a StoreStore barrier exists after the array copy.
5963     alloc->initialization()->set_complete_with_arraycopy();
5964   }
5965 
5966   Node* size = _gvn.transform(obj_size);
5967   access_clone(obj, alloc_obj, size, is_array);
5968 
5969   // Do not let reads from the cloned object float above the arraycopy.
5970   if (alloc != nullptr) {
5971     // Do not let stores that initialize this object be reordered with
5972     // a subsequent store that would make this object accessible by
5973     // other threads.
5974     // Record what AllocateNode this StoreStore protects so that
5975     // escape analysis can go from the MemBarStoreStoreNode to the
5976     // AllocateNode and eliminate the MemBarStoreStoreNode if possible
5977     // based on the escape status of the AllocateNode.
5978     insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
5979   } else {
5980     insert_mem_bar(Op_MemBarCPUOrder);
5981   }
5982 }
5983 
5984 //------------------------inline_native_clone----------------------------
5985 // protected native Object java.lang.Object.clone();
5986 //
5987 // Here are the simple edge cases:
5988 //  null receiver => normal trap
5989 //  virtual and clone was overridden => slow path to out-of-line clone
5990 //  not cloneable or finalizer => slow path to out-of-line Object.clone
5991 //
5992 // The general case has two steps, allocation and copying.
5993 // Allocation has two cases, and uses GraphKit::new_instance or new_array.
5994 //
5995 // Copying also has two cases, oop arrays and everything else.
5996 // Oop arrays use arrayof_oop_arraycopy (same as System.arraycopy).
5997 // Everything else uses the tight inline loop supplied by CopyArrayNode.
5998 //
5999 // These steps fold up nicely if and when the cloned object's klass
6000 // can be sharply typed as an object array, a type array, or an instance.
6001 //
6002 bool LibraryCallKit::inline_native_clone(bool is_virtual) {
6003   PhiNode* result_val;
6004 
6005   // Set the reexecute bit for the interpreter to reexecute
6006   // the bytecode that invokes Object.clone if deoptimization happens.
6007   { PreserveReexecuteState preexecs(this);
6008     jvms()->set_should_reexecute(true);
6009 
6010     Node* obj = argument(0);
6011     obj = null_check_receiver();
6012     if (stopped())  return true;
6013 
6014     const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
6015     if (obj_type->is_inlinetypeptr()) {
6016       // If the object to clone is an inline type, we can simply return it (i.e. a nop) since inline types have
6017       // no identity.
6018       set_result(obj);
6019       return true;
6020     }
6021 
6022     // If we are going to clone an instance, we need its exact type to
6023     // know the number and types of fields to convert the clone to
6024     // loads/stores. Maybe a speculative type can help us.
6025     if (!obj_type->klass_is_exact() &&
6026         obj_type->speculative_type() != nullptr &&
6027         obj_type->speculative_type()->is_instance_klass() &&
6028         !obj_type->speculative_type()->is_inlinetype()) {
6029       ciInstanceKlass* spec_ik = obj_type->speculative_type()->as_instance_klass();
6030       if (spec_ik->nof_nonstatic_fields() <= ArrayCopyLoadStoreMaxElem &&
6031           !spec_ik->has_injected_fields()) {
6032         if (!obj_type->isa_instptr() ||
6033             obj_type->is_instptr()->instance_klass()->has_subklass()) {
6034           obj = maybe_cast_profiled_obj(obj, obj_type->speculative_type(), false);
6035         }
6036       }
6037     }
6038 
6039     // Conservatively insert a memory barrier on all memory slices.
6040     // Do not let writes into the original float below the clone.
6041     insert_mem_bar(Op_MemBarCPUOrder);
6042 
6043     // paths into result_reg:
6044     enum {
6045       _slow_path = 1,     // out-of-line call to clone method (virtual or not)
6046       _objArray_path,     // plain array allocation, plus arrayof_oop_arraycopy
6047       _array_path,        // plain array allocation, plus arrayof_long_arraycopy
6048       _instance_path,     // plain instance allocation, plus arrayof_long_arraycopy
6049       PATH_LIMIT
6050     };
6051     RegionNode* result_reg = new RegionNode(PATH_LIMIT);
6052     result_val             = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
6053     PhiNode*    result_i_o = new PhiNode(result_reg, Type::ABIO);
6054     PhiNode*    result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
6055     record_for_igvn(result_reg);
6056 
6057     Node* obj_klass = load_object_klass(obj);
6058     // We only go to the fast case code if we pass a number of guards.
6059     // The paths which do not pass are accumulated in the slow_region.
6060     RegionNode* slow_region = new RegionNode(1);
6061     record_for_igvn(slow_region);
6062 
6063     Node* array_obj = obj;
6064     Node* array_ctl = generate_array_guard(obj_klass, (RegionNode*)nullptr, &array_obj);
6065     if (array_ctl != nullptr) {
6066       // It's an array.
6067       PreserveJVMState pjvms(this);
6068       set_control(array_ctl);
6069 
6070       BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
6071       const TypeAryPtr* ary_ptr = obj_type->isa_aryptr();
6072       if (UseArrayFlattening && bs->array_copy_requires_gc_barriers(true, T_OBJECT, true, false, BarrierSetC2::Expansion) &&
6073           obj_type->can_be_inline_array() &&
6074           (ary_ptr == nullptr || (!ary_ptr->is_not_flat() && (!ary_ptr->is_flat() || ary_ptr->elem()->inline_klass()->contains_oops())))) {
6075         // Flat inline type array may have object field that would require a
6076         // write barrier. Conservatively, go to slow path.
6077         generate_fair_guard(flat_array_test(obj_klass), slow_region);
6078       }
6079 
6080       if (!stopped()) {
6081         Node* obj_length = load_array_length(array_obj);
6082         Node* array_size = nullptr; // Size of the array without object alignment padding.
6083         Node* alloc_obj = new_array(obj_klass, obj_length, 0, &array_size, /*deoptimize_on_exception=*/true);
6084 
6085         BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
6086         if (bs->array_copy_requires_gc_barriers(true, T_OBJECT, true, false, BarrierSetC2::Parsing)) {
6087           // If it is an oop array, it requires very special treatment,
6088           // because gc barriers are required when accessing the array.
6089           Node* is_obja = generate_refArray_guard(obj_klass, (RegionNode*)nullptr);
6090           if (is_obja != nullptr) {
6091             PreserveJVMState pjvms2(this);
6092             set_control(is_obja);
6093             // Generate a direct call to the right arraycopy function(s).
6094             // Clones are always tightly coupled.
6095             ArrayCopyNode* ac = ArrayCopyNode::make(this, true, array_obj, intcon(0), alloc_obj, intcon(0), obj_length, true, false);
6096             ac->set_clone_oop_array();
6097             Node* n = _gvn.transform(ac);
6098             assert(n == ac, "cannot disappear");
6099             ac->connect_outputs(this, /*deoptimize_on_exception=*/true);
6100 
6101             result_reg->init_req(_objArray_path, control());
6102             result_val->init_req(_objArray_path, alloc_obj);
6103             result_i_o ->set_req(_objArray_path, i_o());
6104             result_mem ->set_req(_objArray_path, reset_memory());
6105           }
6106         }
6107         // Otherwise, there are no barriers to worry about.
6108         // (We can dispense with card marks if we know the allocation
6109         //  comes out of eden (TLAB)...  In fact, ReduceInitialCardMarks
6110         //  causes the non-eden paths to take compensating steps to
6111         //  simulate a fresh allocation, so that no further
6112         //  card marks are required in compiled code to initialize
6113         //  the object.)
6114 
6115         if (!stopped()) {
6116           copy_to_clone(obj, alloc_obj, array_size, true);
6117 
6118           // Present the results of the copy.
6119           result_reg->init_req(_array_path, control());
6120           result_val->init_req(_array_path, alloc_obj);
6121           result_i_o ->set_req(_array_path, i_o());
6122           result_mem ->set_req(_array_path, reset_memory());
6123         }
6124       }
6125     }
6126 
6127     if (!stopped()) {
6128       // It's an instance (we did array above).  Make the slow-path tests.
6129       // If this is a virtual call, we generate a funny guard.  We grab
6130       // the vtable entry corresponding to clone() from the target object.
6131       // If the target method which we are calling happens to be the
6132       // Object clone() method, we pass the guard.  We do not need this
6133       // guard for non-virtual calls; the caller is known to be the native
6134       // Object clone().
6135       if (is_virtual) {
6136         generate_virtual_guard(obj_klass, slow_region);
6137       }
6138 
6139       // The object must be easily cloneable and must not have a finalizer.
6140       // Both of these conditions may be checked in a single test.
6141       // We could optimize the test further, but we don't care.
6142       generate_misc_flags_guard(obj_klass,
6143                                 // Test both conditions:
6144                                 KlassFlags::_misc_is_cloneable_fast | KlassFlags::_misc_has_finalizer,
6145                                 // Must be cloneable but not finalizer:
6146                                 KlassFlags::_misc_is_cloneable_fast,
6147                                 slow_region);
6148     }
6149 
6150     if (!stopped()) {
6151       // It's an instance, and it passed the slow-path tests.
6152       PreserveJVMState pjvms(this);
6153       Node* obj_size = nullptr; // Total object size, including object alignment padding.
6154       // Need to deoptimize on exception from allocation since Object.clone intrinsic
6155       // is reexecuted if deoptimization occurs and there could be problems when merging
6156       // exception state between multiple Object.clone versions (reexecute=true vs reexecute=false).
6157       Node* alloc_obj = new_instance(obj_klass, nullptr, &obj_size, /*deoptimize_on_exception=*/true);
6158 
6159       copy_to_clone(obj, alloc_obj, obj_size, false);
6160 
6161       // Present the results of the slow call.
6162       result_reg->init_req(_instance_path, control());
6163       result_val->init_req(_instance_path, alloc_obj);
6164       result_i_o ->set_req(_instance_path, i_o());
6165       result_mem ->set_req(_instance_path, reset_memory());
6166     }
6167 
6168     // Generate code for the slow case.  We make a call to clone().
6169     set_control(_gvn.transform(slow_region));
6170     if (!stopped()) {
6171       PreserveJVMState pjvms(this);
6172       CallJavaNode* slow_call = generate_method_call(vmIntrinsics::_clone, is_virtual, false, true);
6173       // We need to deoptimize on exception (see comment above)
6174       Node* slow_result = set_results_for_java_call(slow_call, false, /* deoptimize */ true);
6175       // this->control() comes from set_results_for_java_call
6176       result_reg->init_req(_slow_path, control());
6177       result_val->init_req(_slow_path, slow_result);
6178       result_i_o ->set_req(_slow_path, i_o());
6179       result_mem ->set_req(_slow_path, reset_memory());
6180     }
6181 
6182     // Return the combined state.
6183     set_control(    _gvn.transform(result_reg));
6184     set_i_o(        _gvn.transform(result_i_o));
6185     set_all_memory( _gvn.transform(result_mem));
6186   } // original reexecute is set back here
6187 
6188   set_result(_gvn.transform(result_val));
6189   return true;
6190 }
6191 
6192 // If we have a tightly coupled allocation, the arraycopy may take care
6193 // of the array initialization. If one of the guards we insert between
6194 // the allocation and the arraycopy causes a deoptimization, an
6195 // uninitialized array will escape the compiled method. To prevent that
6196 // we set the JVM state for uncommon traps between the allocation and
6197 // the arraycopy to the state before the allocation so, in case of
6198 // deoptimization, we'll reexecute the allocation and the
6199 // initialization.
6200 JVMState* LibraryCallKit::arraycopy_restore_alloc_state(AllocateArrayNode* alloc, int& saved_reexecute_sp) {
6201   if (alloc != nullptr) {
6202     ciMethod* trap_method = alloc->jvms()->method();
6203     int trap_bci = alloc->jvms()->bci();
6204 
6205     if (!C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_intrinsic) &&
6206         !C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_null_check)) {
6207       // Make sure there's no store between the allocation and the
6208       // arraycopy otherwise visible side effects could be rexecuted
6209       // in case of deoptimization and cause incorrect execution.
6210       bool no_interfering_store = true;
6211       Node* mem = alloc->in(TypeFunc::Memory);
6212       if (mem->is_MergeMem()) {
6213         for (MergeMemStream mms(merged_memory(), mem->as_MergeMem()); mms.next_non_empty2(); ) {
6214           Node* n = mms.memory();
6215           if (n != mms.memory2() && !(n->is_Proj() && n->in(0) == alloc->initialization())) {
6216             assert(n->is_Store(), "what else?");
6217             no_interfering_store = false;
6218             break;
6219           }
6220         }
6221       } else {
6222         for (MergeMemStream mms(merged_memory()); mms.next_non_empty(); ) {
6223           Node* n = mms.memory();
6224           if (n != mem && !(n->is_Proj() && n->in(0) == alloc->initialization())) {
6225             assert(n->is_Store(), "what else?");
6226             no_interfering_store = false;
6227             break;
6228           }
6229         }
6230       }
6231 
6232       if (no_interfering_store) {
6233         SafePointNode* sfpt = create_safepoint_with_state_before_array_allocation(alloc);
6234 
6235         JVMState* saved_jvms = jvms();
6236         saved_reexecute_sp = _reexecute_sp;
6237 
6238         set_jvms(sfpt->jvms());
6239         _reexecute_sp = jvms()->sp();
6240 
6241         return saved_jvms;
6242       }
6243     }
6244   }
6245   return nullptr;
6246 }
6247 
6248 // Clone the JVMState of the array allocation and create a new safepoint with it. Re-push the array length to the stack
6249 // such that uncommon traps can be emitted to re-execute the array allocation in the interpreter.
6250 SafePointNode* LibraryCallKit::create_safepoint_with_state_before_array_allocation(const AllocateArrayNode* alloc) const {
6251   JVMState* old_jvms = alloc->jvms()->clone_shallow(C);
6252   uint size = alloc->req();
6253   SafePointNode* sfpt = new SafePointNode(size, old_jvms);
6254   old_jvms->set_map(sfpt);
6255   for (uint i = 0; i < size; i++) {
6256     sfpt->init_req(i, alloc->in(i));
6257   }
6258   int adjustment = 1;
6259   const TypeAryKlassPtr* ary_klass_ptr = alloc->in(AllocateNode::KlassNode)->bottom_type()->is_aryklassptr();
6260   if (ary_klass_ptr->is_null_free()) {
6261     // A null-free, tightly coupled array allocation can only come from LibraryCallKit::inline_newArray which
6262     // also requires the componentType and initVal on stack for re-execution.
6263     // Re-create and push the componentType.
6264     ciArrayKlass* klass = ary_klass_ptr->exact_klass()->as_array_klass();
6265     ciInstance* instance = klass->component_mirror_instance();
6266     const TypeInstPtr* t_instance = TypeInstPtr::make(instance);
6267     sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp(), makecon(t_instance));
6268     adjustment++;
6269   }
6270   // re-push array length for deoptimization
6271   sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp() + adjustment - 1, alloc->in(AllocateNode::ALength));
6272   if (ary_klass_ptr->is_null_free()) {
6273     // Re-create and push the initVal.
6274     Node* init_val = alloc->in(AllocateNode::InitValue);
6275     if (init_val == nullptr) {
6276       init_val = InlineTypeNode::make_all_zero(_gvn, ary_klass_ptr->elem()->is_instklassptr()->instance_klass()->as_inline_klass());
6277     } else if (UseCompressedOops) {
6278       init_val = _gvn.transform(new DecodeNNode(init_val, init_val->bottom_type()->make_ptr()));
6279     }
6280     sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp() + adjustment, init_val);
6281     adjustment++;
6282   }
6283   old_jvms->set_sp(old_jvms->sp() + adjustment);
6284   old_jvms->set_monoff(old_jvms->monoff() + adjustment);
6285   old_jvms->set_scloff(old_jvms->scloff() + adjustment);
6286   old_jvms->set_endoff(old_jvms->endoff() + adjustment);
6287   old_jvms->set_should_reexecute(true);
6288 
6289   sfpt->set_i_o(map()->i_o());
6290   sfpt->set_memory(map()->memory());
6291   sfpt->set_control(map()->control());
6292   return sfpt;
6293 }
6294 
6295 // In case of a deoptimization, we restart execution at the
6296 // allocation, allocating a new array. We would leave an uninitialized
6297 // array in the heap that GCs wouldn't expect. Move the allocation
6298 // after the traps so we don't allocate the array if we
6299 // deoptimize. This is possible because tightly_coupled_allocation()
6300 // guarantees there's no observer of the allocated array at this point
6301 // and the control flow is simple enough.
6302 void LibraryCallKit::arraycopy_move_allocation_here(AllocateArrayNode* alloc, Node* dest, JVMState* saved_jvms_before_guards,
6303                                                     int saved_reexecute_sp, uint new_idx) {
6304   if (saved_jvms_before_guards != nullptr && !stopped()) {
6305     replace_unrelated_uncommon_traps_with_alloc_state(alloc, saved_jvms_before_guards);
6306 
6307     assert(alloc != nullptr, "only with a tightly coupled allocation");
6308     // restore JVM state to the state at the arraycopy
6309     saved_jvms_before_guards->map()->set_control(map()->control());
6310     assert(saved_jvms_before_guards->map()->memory() == map()->memory(), "memory state changed?");
6311     assert(saved_jvms_before_guards->map()->i_o() == map()->i_o(), "IO state changed?");
6312     // If we've improved the types of some nodes (null check) while
6313     // emitting the guards, propagate them to the current state
6314     map()->replaced_nodes().apply(saved_jvms_before_guards->map(), new_idx);
6315     set_jvms(saved_jvms_before_guards);
6316     _reexecute_sp = saved_reexecute_sp;
6317 
6318     // Remove the allocation from above the guards
6319     CallProjections* callprojs = alloc->extract_projections(true);
6320     InitializeNode* init = alloc->initialization();
6321     Node* alloc_mem = alloc->in(TypeFunc::Memory);
6322     C->gvn_replace_by(callprojs->fallthrough_ioproj, alloc->in(TypeFunc::I_O));
6323     init->replace_mem_projs_by(alloc_mem, C);
6324 
6325     // The CastIINode created in GraphKit::new_array (in AllocateArrayNode::make_ideal_length) must stay below
6326     // the allocation (i.e. is only valid if the allocation succeeds):
6327     // 1) replace CastIINode with AllocateArrayNode's length here
6328     // 2) Create CastIINode again once allocation has moved (see below) at the end of this method
6329     //
6330     // Multiple identical CastIINodes might exist here. Each GraphKit::load_array_length() call will generate
6331     // new separate CastIINode (arraycopy guard checks or any array length use between array allocation and ararycopy)
6332     Node* init_control = init->proj_out(TypeFunc::Control);
6333     Node* alloc_length = alloc->Ideal_length();
6334 #ifdef ASSERT
6335     Node* prev_cast = nullptr;
6336 #endif
6337     for (uint i = 0; i < init_control->outcnt(); i++) {
6338       Node* init_out = init_control->raw_out(i);
6339       if (init_out->is_CastII() && init_out->in(TypeFunc::Control) == init_control && init_out->in(1) == alloc_length) {
6340 #ifdef ASSERT
6341         if (prev_cast == nullptr) {
6342           prev_cast = init_out;
6343         } else {
6344           if (prev_cast->cmp(*init_out) == false) {
6345             prev_cast->dump();
6346             init_out->dump();
6347             assert(false, "not equal CastIINode");
6348           }
6349         }
6350 #endif
6351         C->gvn_replace_by(init_out, alloc_length);
6352       }
6353     }
6354     C->gvn_replace_by(init->proj_out(TypeFunc::Control), alloc->in(0));
6355 
6356     // move the allocation here (after the guards)
6357     _gvn.hash_delete(alloc);
6358     alloc->set_req(TypeFunc::Control, control());
6359     alloc->set_req(TypeFunc::I_O, i_o());
6360     Node *mem = reset_memory();
6361     set_all_memory(mem);
6362     alloc->set_req(TypeFunc::Memory, mem);
6363     set_control(init->proj_out_or_null(TypeFunc::Control));
6364     set_i_o(callprojs->fallthrough_ioproj);
6365 
6366     // Update memory as done in GraphKit::set_output_for_allocation()
6367     const TypeInt* length_type = _gvn.find_int_type(alloc->in(AllocateNode::ALength));
6368     const TypeOopPtr* ary_type = _gvn.type(alloc->in(AllocateNode::KlassNode))->is_klassptr()->as_instance_type();
6369     if (ary_type->isa_aryptr() && length_type != nullptr) {
6370       ary_type = ary_type->is_aryptr()->cast_to_size(length_type);
6371     }
6372     const TypePtr* telemref = ary_type->add_offset(Type::OffsetBot);
6373     int            elemidx  = C->get_alias_index(telemref);
6374     // Need to properly move every memory projection for the Initialize
6375 #ifdef ASSERT
6376     int mark_idx = C->get_alias_index(ary_type->add_offset(oopDesc::mark_offset_in_bytes()));
6377     int klass_idx = C->get_alias_index(ary_type->add_offset(oopDesc::klass_offset_in_bytes()));
6378 #endif
6379     auto move_proj = [&](ProjNode* proj) {
6380       int alias_idx = C->get_alias_index(proj->adr_type());
6381       assert(alias_idx == Compile::AliasIdxRaw ||
6382              alias_idx == elemidx ||
6383              alias_idx == mark_idx ||
6384              alias_idx == klass_idx, "should be raw memory or array element type");
6385       set_memory(proj, alias_idx);
6386     };
6387     init->for_each_proj(move_proj, TypeFunc::Memory);
6388 
6389     Node* allocx = _gvn.transform(alloc);
6390     assert(allocx == alloc, "where has the allocation gone?");
6391     assert(dest->is_CheckCastPP(), "not an allocation result?");
6392 
6393     _gvn.hash_delete(dest);
6394     dest->set_req(0, control());
6395     Node* destx = _gvn.transform(dest);
6396     assert(destx == dest, "where has the allocation result gone?");
6397 
6398     array_ideal_length(alloc, ary_type, true);
6399   }
6400 }
6401 
6402 // Unrelated UCTs between the array allocation and the array copy, which are considered safe by tightly_coupled_allocation(),
6403 // need to be replaced by an UCT with a state before the array allocation (including the array length). This is necessary
6404 // because we could hit one of these UCTs (which are executed before the emitted array copy guards and the actual array
6405 // allocation which is moved down in arraycopy_move_allocation_here()). When later resuming execution in the interpreter,
6406 // we would have wrongly skipped the array allocation. To prevent this, we resume execution at the array allocation in
6407 // the interpreter similar to what we are doing for the newly emitted guards for the array copy.
6408 void LibraryCallKit::replace_unrelated_uncommon_traps_with_alloc_state(AllocateArrayNode* alloc,
6409                                                                        JVMState* saved_jvms_before_guards) {
6410   if (saved_jvms_before_guards->map()->control()->is_IfProj()) {
6411     // There is at least one unrelated uncommon trap which needs to be replaced.
6412     SafePointNode* sfpt = create_safepoint_with_state_before_array_allocation(alloc);
6413 
6414     JVMState* saved_jvms = jvms();
6415     const int saved_reexecute_sp = _reexecute_sp;
6416     set_jvms(sfpt->jvms());
6417     _reexecute_sp = jvms()->sp();
6418 
6419     replace_unrelated_uncommon_traps_with_alloc_state(saved_jvms_before_guards);
6420 
6421     // Restore state
6422     set_jvms(saved_jvms);
6423     _reexecute_sp = saved_reexecute_sp;
6424   }
6425 }
6426 
6427 // Replace the unrelated uncommon traps with new uncommon trap nodes by reusing the action and reason. The new uncommon
6428 // traps will have the state of the array allocation. Let the old uncommon trap nodes die.
6429 void LibraryCallKit::replace_unrelated_uncommon_traps_with_alloc_state(JVMState* saved_jvms_before_guards) {
6430   Node* if_proj = saved_jvms_before_guards->map()->control(); // Start the search right before the newly emitted guards
6431   while (if_proj->is_IfProj()) {
6432     CallStaticJavaNode* uncommon_trap = get_uncommon_trap_from_success_proj(if_proj);
6433     if (uncommon_trap != nullptr) {
6434       create_new_uncommon_trap(uncommon_trap);
6435     }
6436     assert(if_proj->in(0)->is_If(), "must be If");
6437     if_proj = if_proj->in(0)->in(0);
6438   }
6439   assert(if_proj->is_Proj() && if_proj->in(0)->is_Initialize(),
6440          "must have reached control projection of init node");
6441 }
6442 
6443 void LibraryCallKit::create_new_uncommon_trap(CallStaticJavaNode* uncommon_trap_call) {
6444   const int trap_request = uncommon_trap_call->uncommon_trap_request();
6445   assert(trap_request != 0, "no valid UCT trap request");
6446   PreserveJVMState pjvms(this);
6447   set_control(uncommon_trap_call->in(0));
6448   uncommon_trap(Deoptimization::trap_request_reason(trap_request),
6449                 Deoptimization::trap_request_action(trap_request));
6450   assert(stopped(), "Should be stopped");
6451   _gvn.hash_delete(uncommon_trap_call);
6452   uncommon_trap_call->set_req(0, top()); // not used anymore, kill it
6453 }
6454 
6455 // Common checks for array sorting intrinsics arguments.
6456 // Returns `true` if checks passed.
6457 bool LibraryCallKit::check_array_sort_arguments(Node* elementType, Node* obj, BasicType& bt) {
6458   // check address of the class
6459   if (elementType == nullptr || elementType->is_top()) {
6460     return false;  // dead path
6461   }
6462   const TypeInstPtr* elem_klass = gvn().type(elementType)->isa_instptr();
6463   if (elem_klass == nullptr) {
6464     return false;  // dead path
6465   }
6466   // java_mirror_type() returns non-null for compile-time Class constants only
6467   ciType* elem_type = elem_klass->java_mirror_type();
6468   if (elem_type == nullptr) {
6469     return false;
6470   }
6471   bt = elem_type->basic_type();
6472   // Disable the intrinsic if the CPU does not support SIMD sort
6473   if (!Matcher::supports_simd_sort(bt)) {
6474     return false;
6475   }
6476   // check address of the array
6477   if (obj == nullptr || obj->is_top()) {
6478     return false;  // dead path
6479   }
6480   const TypeAryPtr* obj_t = _gvn.type(obj)->isa_aryptr();
6481   if (obj_t == nullptr || obj_t->elem() == Type::BOTTOM) {
6482     return false; // failed input validation
6483   }
6484   return true;
6485 }
6486 
6487 //------------------------------inline_array_partition-----------------------
6488 bool LibraryCallKit::inline_array_partition() {
6489   address stubAddr = StubRoutines::select_array_partition_function();
6490   if (stubAddr == nullptr) {
6491     return false; // Intrinsic's stub is not implemented on this platform
6492   }
6493   assert(callee()->signature()->size() == 9, "arrayPartition has 8 parameters (one long)");
6494 
6495   // no receiver because it is a static method
6496   Node* elementType     = argument(0);
6497   Node* obj             = argument(1);
6498   Node* offset          = argument(2); // long
6499   Node* fromIndex       = argument(4);
6500   Node* toIndex         = argument(5);
6501   Node* indexPivot1     = argument(6);
6502   Node* indexPivot2     = argument(7);
6503   // PartitionOperation:  argument(8) is ignored
6504 
6505   Node* pivotIndices = nullptr;
6506   BasicType bt = T_ILLEGAL;
6507 
6508   if (!check_array_sort_arguments(elementType, obj, bt)) {
6509     return false;
6510   }
6511   null_check(obj);
6512   // If obj is dead, only null-path is taken.
6513   if (stopped()) {
6514     return true;
6515   }
6516   // Set the original stack and the reexecute bit for the interpreter to reexecute
6517   // the bytecode that invokes DualPivotQuicksort.partition() if deoptimization happens.
6518   { PreserveReexecuteState preexecs(this);
6519     jvms()->set_should_reexecute(true);
6520 
6521     Node* obj_adr = make_unsafe_address(obj, offset);
6522 
6523     // create the pivotIndices array of type int and size = 2
6524     Node* size = intcon(2);
6525     Node* klass_node = makecon(TypeKlassPtr::make(ciTypeArrayKlass::make(T_INT)));
6526     pivotIndices = new_array(klass_node, size, 0);  // no arguments to push
6527     AllocateArrayNode* alloc = tightly_coupled_allocation(pivotIndices);
6528     guarantee(alloc != nullptr, "created above");
6529     Node* pivotIndices_adr = basic_plus_adr(pivotIndices, arrayOopDesc::base_offset_in_bytes(T_INT));
6530 
6531     // pass the basic type enum to the stub
6532     Node* elemType = intcon(bt);
6533 
6534     // Call the stub
6535     const char *stubName = "array_partition_stub";
6536     make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::array_partition_Type(),
6537                       stubAddr, stubName, TypePtr::BOTTOM,
6538                       obj_adr, elemType, fromIndex, toIndex, pivotIndices_adr,
6539                       indexPivot1, indexPivot2);
6540 
6541   } // original reexecute is set back here
6542 
6543   if (!stopped()) {
6544     set_result(pivotIndices);
6545   }
6546 
6547   return true;
6548 }
6549 
6550 
6551 //------------------------------inline_array_sort-----------------------
6552 bool LibraryCallKit::inline_array_sort() {
6553   address stubAddr = StubRoutines::select_arraysort_function();
6554   if (stubAddr == nullptr) {
6555     return false; // Intrinsic's stub is not implemented on this platform
6556   }
6557   assert(callee()->signature()->size() == 7, "arraySort has 6 parameters (one long)");
6558 
6559   // no receiver because it is a static method
6560   Node* elementType     = argument(0);
6561   Node* obj             = argument(1);
6562   Node* offset          = argument(2); // long
6563   Node* fromIndex       = argument(4);
6564   Node* toIndex         = argument(5);
6565   // SortOperation:       argument(6) is ignored
6566 
6567   BasicType bt = T_ILLEGAL;
6568 
6569   if (!check_array_sort_arguments(elementType, obj, bt)) {
6570     return false;
6571   }
6572   null_check(obj);
6573   // If obj is dead, only null-path is taken.
6574   if (stopped()) {
6575     return true;
6576   }
6577   Node* obj_adr = make_unsafe_address(obj, offset);
6578 
6579   // pass the basic type enum to the stub
6580   Node* elemType = intcon(bt);
6581 
6582   // Call the stub.
6583   const char *stubName = "arraysort_stub";
6584   make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::array_sort_Type(),
6585                     stubAddr, stubName, TypePtr::BOTTOM,
6586                     obj_adr, elemType, fromIndex, toIndex);
6587 
6588   return true;
6589 }
6590 
6591 
6592 //------------------------------inline_arraycopy-----------------------
6593 // public static native void java.lang.System.arraycopy(Object src,  int  srcPos,
6594 //                                                      Object dest, int destPos,
6595 //                                                      int length);
6596 bool LibraryCallKit::inline_arraycopy() {
6597   // Get the arguments.
6598   Node* src         = argument(0);  // type: oop
6599   Node* src_offset  = argument(1);  // type: int
6600   Node* dest        = argument(2);  // type: oop
6601   Node* dest_offset = argument(3);  // type: int
6602   Node* length      = argument(4);  // type: int
6603 
6604   uint new_idx = C->unique();
6605 
6606   // Check for allocation before we add nodes that would confuse
6607   // tightly_coupled_allocation()
6608   AllocateArrayNode* alloc = tightly_coupled_allocation(dest);
6609 
6610   int saved_reexecute_sp = -1;
6611   JVMState* saved_jvms_before_guards = arraycopy_restore_alloc_state(alloc, saved_reexecute_sp);
6612   // See arraycopy_restore_alloc_state() comment
6613   // if alloc == null we don't have to worry about a tightly coupled allocation so we can emit all needed guards
6614   // if saved_jvms_before_guards is not null (then alloc is not null) then we can handle guards and a tightly coupled allocation
6615   // if saved_jvms_before_guards is null and alloc is not null, we can't emit any guards
6616   bool can_emit_guards = (alloc == nullptr || saved_jvms_before_guards != nullptr);
6617 
6618   // The following tests must be performed
6619   // (1) src and dest are arrays.
6620   // (2) src and dest arrays must have elements of the same BasicType
6621   // (3) src and dest must not be null.
6622   // (4) src_offset must not be negative.
6623   // (5) dest_offset must not be negative.
6624   // (6) length must not be negative.
6625   // (7) src_offset + length must not exceed length of src.
6626   // (8) dest_offset + length must not exceed length of dest.
6627   // (9) each element of an oop array must be assignable
6628 
6629   // (3) src and dest must not be null.
6630   // always do this here because we need the JVM state for uncommon traps
6631   Node* null_ctl = top();
6632   src  = saved_jvms_before_guards != nullptr ? null_check_oop(src, &null_ctl, true, true) : null_check(src, T_ARRAY);
6633   assert(null_ctl->is_top(), "no null control here");
6634   dest = null_check(dest, T_ARRAY);
6635 
6636   if (!can_emit_guards) {
6637     // if saved_jvms_before_guards is null and alloc is not null, we don't emit any
6638     // guards but the arraycopy node could still take advantage of a
6639     // tightly allocated allocation. tightly_coupled_allocation() is
6640     // called again to make sure it takes the null check above into
6641     // account: the null check is mandatory and if it caused an
6642     // uncommon trap to be emitted then the allocation can't be
6643     // considered tightly coupled in this context.
6644     alloc = tightly_coupled_allocation(dest);
6645   }
6646 
6647   bool validated = false;
6648 
6649   const Type* src_type  = _gvn.type(src);
6650   const Type* dest_type = _gvn.type(dest);
6651   const TypeAryPtr* top_src  = src_type->isa_aryptr();
6652   const TypeAryPtr* top_dest = dest_type->isa_aryptr();
6653 
6654   // Do we have the type of src?
6655   bool has_src = (top_src != nullptr && top_src->elem() != Type::BOTTOM);
6656   // Do we have the type of dest?
6657   bool has_dest = (top_dest != nullptr && top_dest->elem() != Type::BOTTOM);
6658   // Is the type for src from speculation?
6659   bool src_spec = false;
6660   // Is the type for dest from speculation?
6661   bool dest_spec = false;
6662 
6663   if ((!has_src || !has_dest) && can_emit_guards) {
6664     // We don't have sufficient type information, let's see if
6665     // speculative types can help. We need to have types for both src
6666     // and dest so that it pays off.
6667 
6668     // Do we already have or could we have type information for src
6669     bool could_have_src = has_src;
6670     // Do we already have or could we have type information for dest
6671     bool could_have_dest = has_dest;
6672 
6673     ciKlass* src_k = nullptr;
6674     if (!has_src) {
6675       src_k = src_type->speculative_type_not_null();
6676       if (src_k != nullptr && src_k->is_array_klass()) {
6677         could_have_src = true;
6678       }
6679     }
6680 
6681     ciKlass* dest_k = nullptr;
6682     if (!has_dest) {
6683       dest_k = dest_type->speculative_type_not_null();
6684       if (dest_k != nullptr && dest_k->is_array_klass()) {
6685         could_have_dest = true;
6686       }
6687     }
6688 
6689     if (could_have_src && could_have_dest) {
6690       // This is going to pay off so emit the required guards
6691       if (!has_src) {
6692         src = maybe_cast_profiled_obj(src, src_k, true);
6693         src_type  = _gvn.type(src);
6694         top_src  = src_type->isa_aryptr();
6695         has_src = (top_src != nullptr && top_src->elem() != Type::BOTTOM);
6696         src_spec = true;
6697       }
6698       if (!has_dest) {
6699         dest = maybe_cast_profiled_obj(dest, dest_k, true);
6700         dest_type  = _gvn.type(dest);
6701         top_dest  = dest_type->isa_aryptr();
6702         has_dest = (top_dest != nullptr && top_dest->elem() != Type::BOTTOM);
6703         dest_spec = true;
6704       }
6705     }
6706   }
6707 
6708   if (has_src && has_dest && can_emit_guards) {
6709     BasicType src_elem = top_src->isa_aryptr()->elem()->array_element_basic_type();
6710     BasicType dest_elem = top_dest->isa_aryptr()->elem()->array_element_basic_type();
6711     if (is_reference_type(src_elem, true)) src_elem = T_OBJECT;
6712     if (is_reference_type(dest_elem, true)) dest_elem = T_OBJECT;
6713 
6714     if (src_elem == dest_elem && top_src->is_flat() == top_dest->is_flat() && src_elem == T_OBJECT) {
6715       // If both arrays are object arrays then having the exact types
6716       // for both will remove the need for a subtype check at runtime
6717       // before the call and may make it possible to pick a faster copy
6718       // routine (without a subtype check on every element)
6719       // Do we have the exact type of src?
6720       bool could_have_src = src_spec;
6721       // Do we have the exact type of dest?
6722       bool could_have_dest = dest_spec;
6723       ciKlass* src_k = nullptr;
6724       ciKlass* dest_k = nullptr;
6725       if (!src_spec) {
6726         src_k = src_type->speculative_type_not_null();
6727         if (src_k != nullptr && src_k->is_array_klass()) {
6728           could_have_src = true;
6729         }
6730       }
6731       if (!dest_spec) {
6732         dest_k = dest_type->speculative_type_not_null();
6733         if (dest_k != nullptr && dest_k->is_array_klass()) {
6734           could_have_dest = true;
6735         }
6736       }
6737       if (could_have_src && could_have_dest) {
6738         // If we can have both exact types, emit the missing guards
6739         if (could_have_src && !src_spec) {
6740           src = maybe_cast_profiled_obj(src, src_k, true);
6741           src_type = _gvn.type(src);
6742           top_src = src_type->isa_aryptr();
6743         }
6744         if (could_have_dest && !dest_spec) {
6745           dest = maybe_cast_profiled_obj(dest, dest_k, true);
6746           dest_type = _gvn.type(dest);
6747           top_dest = dest_type->isa_aryptr();
6748         }
6749       }
6750     }
6751   }
6752 
6753   ciMethod* trap_method = method();
6754   int trap_bci = bci();
6755   if (saved_jvms_before_guards != nullptr) {
6756     trap_method = alloc->jvms()->method();
6757     trap_bci = alloc->jvms()->bci();
6758   }
6759 
6760   bool negative_length_guard_generated = false;
6761 
6762   if (!C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_intrinsic) &&
6763       can_emit_guards && !src->is_top() && !dest->is_top()) {
6764     // validate arguments: enables transformation the ArrayCopyNode
6765     validated = true;
6766 
6767     RegionNode* slow_region = new RegionNode(1);
6768     record_for_igvn(slow_region);
6769 
6770     // (1) src and dest are arrays.
6771     generate_non_array_guard(load_object_klass(src), slow_region, &src);
6772     generate_non_array_guard(load_object_klass(dest), slow_region, &dest);
6773 
6774     // (2) src and dest arrays must have elements of the same BasicType
6775     // done at macro expansion or at Ideal transformation time
6776 
6777     // (4) src_offset must not be negative.
6778     generate_negative_guard(src_offset, slow_region);
6779 
6780     // (5) dest_offset must not be negative.
6781     generate_negative_guard(dest_offset, slow_region);
6782 
6783     // (7) src_offset + length must not exceed length of src.
6784     generate_limit_guard(src_offset, length,
6785                          load_array_length(src),
6786                          slow_region);
6787 
6788     // (8) dest_offset + length must not exceed length of dest.
6789     generate_limit_guard(dest_offset, length,
6790                          load_array_length(dest),
6791                          slow_region);
6792 
6793     // (6) length must not be negative.
6794     // This is also checked in generate_arraycopy() during macro expansion, but
6795     // we also have to check it here for the case where the ArrayCopyNode will
6796     // be eliminated by Escape Analysis.
6797     if (EliminateAllocations) {
6798       generate_negative_guard(length, slow_region);
6799       negative_length_guard_generated = true;
6800     }
6801 
6802     // (9) each element of an oop array must be assignable
6803     Node* dest_klass = load_object_klass(dest);
6804     Node* refined_dest_klass = dest_klass;
6805     if (src != dest) {
6806       dest_klass = load_non_refined_array_klass(refined_dest_klass);
6807       Node* not_subtype_ctrl = gen_subtype_check(src, dest_klass);
6808       slow_region->add_req(not_subtype_ctrl);
6809     }
6810 
6811     // TODO 8350865 Improve this. What about atomicity? Make sure this is always folded for type arrays.
6812     // If destination is null-restricted, source must be null-restricted as well: src_null_restricted || !dst_null_restricted
6813     Node* src_klass = load_object_klass(src);
6814     Node* adr_prop_src = basic_plus_adr(src_klass, in_bytes(ArrayKlass::properties_offset()));
6815     Node* prop_src = _gvn.transform(LoadNode::make(_gvn, control(), immutable_memory(), adr_prop_src, TypeRawPtr::BOTTOM, TypeInt::INT, T_INT, MemNode::unordered));
6816     Node* adr_prop_dest = basic_plus_adr(refined_dest_klass, in_bytes(ArrayKlass::properties_offset()));
6817     Node* prop_dest = _gvn.transform(LoadNode::make(_gvn, control(), immutable_memory(), adr_prop_dest, TypeRawPtr::BOTTOM, TypeInt::INT, T_INT, MemNode::unordered));
6818 
6819     prop_dest = _gvn.transform(new XorINode(prop_dest, intcon(ArrayKlass::ArrayProperties::NULL_RESTRICTED)));
6820     prop_src = _gvn.transform(new OrINode(prop_dest, prop_src));
6821     prop_src = _gvn.transform(new AndINode(prop_src, intcon(ArrayKlass::ArrayProperties::NULL_RESTRICTED)));
6822 
6823     Node* chk = _gvn.transform(new CmpINode(prop_src, intcon(ArrayKlass::ArrayProperties::NULL_RESTRICTED)));
6824     Node* tst = _gvn.transform(new BoolNode(chk, BoolTest::ne));
6825     generate_fair_guard(tst, slow_region);
6826 
6827     // TODO 8350865 This is too strong
6828     generate_fair_guard(flat_array_test(src), slow_region);
6829     generate_fair_guard(flat_array_test(dest), slow_region);
6830 
6831     {
6832       PreserveJVMState pjvms(this);
6833       set_control(_gvn.transform(slow_region));
6834       uncommon_trap(Deoptimization::Reason_intrinsic,
6835                     Deoptimization::Action_make_not_entrant);
6836       assert(stopped(), "Should be stopped");
6837     }
6838 
6839     const TypeKlassPtr* dest_klass_t = _gvn.type(dest_klass)->isa_klassptr();
6840     if (dest_klass_t == nullptr) {
6841       // refined_dest_klass may not be an array, which leads to dest_klass being top. This means we
6842       // are in a dead path.
6843       uncommon_trap(Deoptimization::Reason_intrinsic,
6844                     Deoptimization::Action_make_not_entrant);
6845       return true;
6846     }
6847 
6848     const Type* toop = dest_klass_t->cast_to_exactness(false)->as_instance_type();
6849     src = _gvn.transform(new CheckCastPPNode(control(), src, toop));
6850     arraycopy_move_allocation_here(alloc, dest, saved_jvms_before_guards, saved_reexecute_sp, new_idx);
6851   }
6852 
6853   if (stopped()) {
6854     return true;
6855   }
6856 
6857   Node* dest_klass = load_object_klass(dest);
6858   dest_klass = load_non_refined_array_klass(dest_klass);
6859 
6860   ArrayCopyNode* ac = ArrayCopyNode::make(this, true, src, src_offset, dest, dest_offset, length, alloc != nullptr, negative_length_guard_generated,
6861                                           // Create LoadRange and LoadKlass nodes for use during macro expansion here
6862                                           // so the compiler has a chance to eliminate them: during macro expansion,
6863                                           // we have to set their control (CastPP nodes are eliminated).
6864                                           load_object_klass(src), dest_klass,
6865                                           load_array_length(src), load_array_length(dest));
6866 
6867   ac->set_arraycopy(validated);
6868 
6869   Node* n = _gvn.transform(ac);
6870   if (n == ac) {
6871     ac->connect_outputs(this);
6872   } else {
6873     assert(validated, "shouldn't transform if all arguments not validated");
6874     set_all_memory(n);
6875   }
6876   clear_upper_avx();
6877 
6878 
6879   return true;
6880 }
6881 
6882 
6883 // Helper function which determines if an arraycopy immediately follows
6884 // an allocation, with no intervening tests or other escapes for the object.
6885 AllocateArrayNode*
6886 LibraryCallKit::tightly_coupled_allocation(Node* ptr) {
6887   if (stopped())             return nullptr;  // no fast path
6888   if (!C->do_aliasing())     return nullptr;  // no MergeMems around
6889 
6890   AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(ptr);
6891   if (alloc == nullptr)  return nullptr;
6892 
6893   Node* rawmem = memory(Compile::AliasIdxRaw);
6894   // Is the allocation's memory state untouched?
6895   if (!(rawmem->is_Proj() && rawmem->in(0)->is_Initialize())) {
6896     // Bail out if there have been raw-memory effects since the allocation.
6897     // (Example:  There might have been a call or safepoint.)
6898     return nullptr;
6899   }
6900   rawmem = rawmem->in(0)->as_Initialize()->memory(Compile::AliasIdxRaw);
6901   if (!(rawmem->is_Proj() && rawmem->in(0) == alloc)) {
6902     return nullptr;
6903   }
6904 
6905   // There must be no unexpected observers of this allocation.
6906   for (DUIterator_Fast imax, i = ptr->fast_outs(imax); i < imax; i++) {
6907     Node* obs = ptr->fast_out(i);
6908     if (obs != this->map()) {
6909       return nullptr;
6910     }
6911   }
6912 
6913   // This arraycopy must unconditionally follow the allocation of the ptr.
6914   Node* alloc_ctl = ptr->in(0);
6915   Node* ctl = control();
6916   while (ctl != alloc_ctl) {
6917     // There may be guards which feed into the slow_region.
6918     // Any other control flow means that we might not get a chance
6919     // to finish initializing the allocated object.
6920     // Various low-level checks bottom out in uncommon traps. These
6921     // are considered safe since we've already checked above that
6922     // there is no unexpected observer of this allocation.
6923     if (get_uncommon_trap_from_success_proj(ctl) != nullptr) {
6924       assert(ctl->in(0)->is_If(), "must be If");
6925       ctl = ctl->in(0)->in(0);
6926     } else {
6927       return nullptr;
6928     }
6929   }
6930 
6931   // If we get this far, we have an allocation which immediately
6932   // precedes the arraycopy, and we can take over zeroing the new object.
6933   // The arraycopy will finish the initialization, and provide
6934   // a new control state to which we will anchor the destination pointer.
6935 
6936   return alloc;
6937 }
6938 
6939 CallStaticJavaNode* LibraryCallKit::get_uncommon_trap_from_success_proj(Node* node) {
6940   if (node->is_IfProj()) {
6941     IfProjNode* other_proj = node->as_IfProj()->other_if_proj();
6942     for (DUIterator_Fast jmax, j = other_proj->fast_outs(jmax); j < jmax; j++) {
6943       Node* obs = other_proj->fast_out(j);
6944       if (obs->in(0) == other_proj && obs->is_CallStaticJava() &&
6945           (obs->as_CallStaticJava()->entry_point() == OptoRuntime::uncommon_trap_blob()->entry_point())) {
6946         return obs->as_CallStaticJava();
6947       }
6948     }
6949   }
6950   return nullptr;
6951 }
6952 
6953 //-------------inline_encodeISOArray-----------------------------------
6954 // int sun.nio.cs.ISO_8859_1.Encoder#encodeISOArray0(byte[] sa, int sp, byte[] da, int dp, int len)
6955 // int java.lang.StringCoding#encodeISOArray0(byte[] sa, int sp, byte[] da, int dp, int len)
6956 // int java.lang.StringCoding#encodeAsciiArray0(char[] sa, int sp, byte[] da, int dp, int len)
6957 // encode char[] to byte[] in ISO_8859_1 or ASCII
6958 bool LibraryCallKit::inline_encodeISOArray(bool ascii) {
6959   assert(callee()->signature()->size() == 5, "encodeISOArray has 5 parameters");
6960   // no receiver since it is static method
6961   Node *src         = argument(0);
6962   Node *src_offset  = argument(1);
6963   Node *dst         = argument(2);
6964   Node *dst_offset  = argument(3);
6965   Node *length      = argument(4);
6966 
6967   // Cast source & target arrays to not-null
6968   if (VerifyIntrinsicChecks) {
6969     src = must_be_not_null(src, true);
6970     dst = must_be_not_null(dst, true);
6971     if (stopped()) {
6972       return true;
6973     }
6974   }
6975 
6976   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
6977   const TypeAryPtr* dst_type = dst->Value(&_gvn)->isa_aryptr();
6978   if (src_type == nullptr || src_type->elem() == Type::BOTTOM ||
6979       dst_type == nullptr || dst_type->elem() == Type::BOTTOM) {
6980     // failed array check
6981     return false;
6982   }
6983 
6984   // Figure out the size and type of the elements we will be copying.
6985   BasicType src_elem = src_type->elem()->array_element_basic_type();
6986   BasicType dst_elem = dst_type->elem()->array_element_basic_type();
6987   if (!((src_elem == T_CHAR) || (src_elem== T_BYTE)) || dst_elem != T_BYTE) {
6988     return false;
6989   }
6990 
6991   // Check source & target bounds
6992   if (VerifyIntrinsicChecks) {
6993     generate_string_range_check(src, src_offset, length, src_elem == T_BYTE, true);
6994     generate_string_range_check(dst, dst_offset, length, false, true);
6995     if (stopped()) {
6996       return true;
6997     }
6998   }
6999 
7000   Node* src_start = array_element_address(src, src_offset, T_CHAR);
7001   Node* dst_start = array_element_address(dst, dst_offset, dst_elem);
7002   // 'src_start' points to src array + scaled offset
7003   // 'dst_start' points to dst array + scaled offset
7004 
7005   const TypeAryPtr* mtype = TypeAryPtr::BYTES;
7006   Node* enc = new EncodeISOArrayNode(control(), memory(mtype), src_start, dst_start, length, ascii);
7007   enc = _gvn.transform(enc);
7008   Node* res_mem = _gvn.transform(new SCMemProjNode(enc));
7009   set_memory(res_mem, mtype);
7010   set_result(enc);
7011   clear_upper_avx();
7012 
7013   return true;
7014 }
7015 
7016 //-------------inline_multiplyToLen-----------------------------------
7017 bool LibraryCallKit::inline_multiplyToLen() {
7018   assert(UseMultiplyToLenIntrinsic, "not implemented on this platform");
7019 
7020   address stubAddr = StubRoutines::multiplyToLen();
7021   if (stubAddr == nullptr) {
7022     return false; // Intrinsic's stub is not implemented on this platform
7023   }
7024   const char* stubName = "multiplyToLen";
7025 
7026   assert(callee()->signature()->size() == 5, "multiplyToLen has 5 parameters");
7027 
7028   // no receiver because it is a static method
7029   Node* x    = argument(0);
7030   Node* xlen = argument(1);
7031   Node* y    = argument(2);
7032   Node* ylen = argument(3);
7033   Node* z    = argument(4);
7034 
7035   x = must_be_not_null(x, true);
7036   y = must_be_not_null(y, true);
7037 
7038   const TypeAryPtr* x_type = x->Value(&_gvn)->isa_aryptr();
7039   const TypeAryPtr* y_type = y->Value(&_gvn)->isa_aryptr();
7040   if (x_type == nullptr || x_type->elem() == Type::BOTTOM ||
7041       y_type == nullptr || y_type->elem() == Type::BOTTOM) {
7042     // failed array check
7043     return false;
7044   }
7045 
7046   BasicType x_elem = x_type->elem()->array_element_basic_type();
7047   BasicType y_elem = y_type->elem()->array_element_basic_type();
7048   if (x_elem != T_INT || y_elem != T_INT) {
7049     return false;
7050   }
7051 
7052   Node* x_start = array_element_address(x, intcon(0), x_elem);
7053   Node* y_start = array_element_address(y, intcon(0), y_elem);
7054   // 'x_start' points to x array + scaled xlen
7055   // 'y_start' points to y array + scaled ylen
7056 
7057   Node* z_start = array_element_address(z, intcon(0), T_INT);
7058 
7059   Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
7060                                  OptoRuntime::multiplyToLen_Type(),
7061                                  stubAddr, stubName, TypePtr::BOTTOM,
7062                                  x_start, xlen, y_start, ylen, z_start);
7063 
7064   C->set_has_split_ifs(true); // Has chance for split-if optimization
7065   set_result(z);
7066   return true;
7067 }
7068 
7069 //-------------inline_squareToLen------------------------------------
7070 bool LibraryCallKit::inline_squareToLen() {
7071   assert(UseSquareToLenIntrinsic, "not implemented on this platform");
7072 
7073   address stubAddr = StubRoutines::squareToLen();
7074   if (stubAddr == nullptr) {
7075     return false; // Intrinsic's stub is not implemented on this platform
7076   }
7077   const char* stubName = "squareToLen";
7078 
7079   assert(callee()->signature()->size() == 4, "implSquareToLen has 4 parameters");
7080 
7081   Node* x    = argument(0);
7082   Node* len  = argument(1);
7083   Node* z    = argument(2);
7084   Node* zlen = argument(3);
7085 
7086   x = must_be_not_null(x, true);
7087   z = must_be_not_null(z, true);
7088 
7089   const TypeAryPtr* x_type = x->Value(&_gvn)->isa_aryptr();
7090   const TypeAryPtr* z_type = z->Value(&_gvn)->isa_aryptr();
7091   if (x_type == nullptr || x_type->elem() == Type::BOTTOM ||
7092       z_type == nullptr || z_type->elem() == Type::BOTTOM) {
7093     // failed array check
7094     return false;
7095   }
7096 
7097   BasicType x_elem = x_type->elem()->array_element_basic_type();
7098   BasicType z_elem = z_type->elem()->array_element_basic_type();
7099   if (x_elem != T_INT || z_elem != T_INT) {
7100     return false;
7101   }
7102 
7103 
7104   Node* x_start = array_element_address(x, intcon(0), x_elem);
7105   Node* z_start = array_element_address(z, intcon(0), z_elem);
7106 
7107   Node*  call = make_runtime_call(RC_LEAF|RC_NO_FP,
7108                                   OptoRuntime::squareToLen_Type(),
7109                                   stubAddr, stubName, TypePtr::BOTTOM,
7110                                   x_start, len, z_start, zlen);
7111 
7112   set_result(z);
7113   return true;
7114 }
7115 
7116 //-------------inline_mulAdd------------------------------------------
7117 bool LibraryCallKit::inline_mulAdd() {
7118   assert(UseMulAddIntrinsic, "not implemented on this platform");
7119 
7120   address stubAddr = StubRoutines::mulAdd();
7121   if (stubAddr == nullptr) {
7122     return false; // Intrinsic's stub is not implemented on this platform
7123   }
7124   const char* stubName = "mulAdd";
7125 
7126   assert(callee()->signature()->size() == 5, "mulAdd has 5 parameters");
7127 
7128   Node* out      = argument(0);
7129   Node* in       = argument(1);
7130   Node* offset   = argument(2);
7131   Node* len      = argument(3);
7132   Node* k        = argument(4);
7133 
7134   in = must_be_not_null(in, true);
7135   out = must_be_not_null(out, true);
7136 
7137   const TypeAryPtr* out_type = out->Value(&_gvn)->isa_aryptr();
7138   const TypeAryPtr* in_type = in->Value(&_gvn)->isa_aryptr();
7139   if (out_type == nullptr || out_type->elem() == Type::BOTTOM ||
7140        in_type == nullptr ||  in_type->elem() == Type::BOTTOM) {
7141     // failed array check
7142     return false;
7143   }
7144 
7145   BasicType out_elem = out_type->elem()->array_element_basic_type();
7146   BasicType in_elem = in_type->elem()->array_element_basic_type();
7147   if (out_elem != T_INT || in_elem != T_INT) {
7148     return false;
7149   }
7150 
7151   Node* outlen = load_array_length(out);
7152   Node* new_offset = _gvn.transform(new SubINode(outlen, offset));
7153   Node* out_start = array_element_address(out, intcon(0), out_elem);
7154   Node* in_start = array_element_address(in, intcon(0), in_elem);
7155 
7156   Node*  call = make_runtime_call(RC_LEAF|RC_NO_FP,
7157                                   OptoRuntime::mulAdd_Type(),
7158                                   stubAddr, stubName, TypePtr::BOTTOM,
7159                                   out_start,in_start, new_offset, len, k);
7160   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7161   set_result(result);
7162   return true;
7163 }
7164 
7165 //-------------inline_montgomeryMultiply-----------------------------------
7166 bool LibraryCallKit::inline_montgomeryMultiply() {
7167   address stubAddr = StubRoutines::montgomeryMultiply();
7168   if (stubAddr == nullptr) {
7169     return false; // Intrinsic's stub is not implemented on this platform
7170   }
7171 
7172   assert(UseMontgomeryMultiplyIntrinsic, "not implemented on this platform");
7173   const char* stubName = "montgomery_multiply";
7174 
7175   assert(callee()->signature()->size() == 7, "montgomeryMultiply has 7 parameters");
7176 
7177   Node* a    = argument(0);
7178   Node* b    = argument(1);
7179   Node* n    = argument(2);
7180   Node* len  = argument(3);
7181   Node* inv  = argument(4);
7182   Node* m    = argument(6);
7183 
7184   const TypeAryPtr* a_type = a->Value(&_gvn)->isa_aryptr();
7185   const TypeAryPtr* b_type = b->Value(&_gvn)->isa_aryptr();
7186   const TypeAryPtr* n_type = n->Value(&_gvn)->isa_aryptr();
7187   const TypeAryPtr* m_type = m->Value(&_gvn)->isa_aryptr();
7188   if (a_type == nullptr || a_type->elem() == Type::BOTTOM ||
7189       b_type == nullptr || b_type->elem() == Type::BOTTOM ||
7190       n_type == nullptr || n_type->elem() == Type::BOTTOM ||
7191       m_type == nullptr || m_type->elem() == Type::BOTTOM) {
7192     // failed array check
7193     return false;
7194   }
7195 
7196   BasicType a_elem = a_type->elem()->array_element_basic_type();
7197   BasicType b_elem = b_type->elem()->array_element_basic_type();
7198   BasicType n_elem = n_type->elem()->array_element_basic_type();
7199   BasicType m_elem = m_type->elem()->array_element_basic_type();
7200   if (a_elem != T_INT || b_elem != T_INT || n_elem != T_INT || m_elem != T_INT) {
7201     return false;
7202   }
7203 
7204   // Make the call
7205   {
7206     Node* a_start = array_element_address(a, intcon(0), a_elem);
7207     Node* b_start = array_element_address(b, intcon(0), b_elem);
7208     Node* n_start = array_element_address(n, intcon(0), n_elem);
7209     Node* m_start = array_element_address(m, intcon(0), m_elem);
7210 
7211     Node* call = make_runtime_call(RC_LEAF,
7212                                    OptoRuntime::montgomeryMultiply_Type(),
7213                                    stubAddr, stubName, TypePtr::BOTTOM,
7214                                    a_start, b_start, n_start, len, inv, top(),
7215                                    m_start);
7216     set_result(m);
7217   }
7218 
7219   return true;
7220 }
7221 
7222 bool LibraryCallKit::inline_montgomerySquare() {
7223   address stubAddr = StubRoutines::montgomerySquare();
7224   if (stubAddr == nullptr) {
7225     return false; // Intrinsic's stub is not implemented on this platform
7226   }
7227 
7228   assert(UseMontgomerySquareIntrinsic, "not implemented on this platform");
7229   const char* stubName = "montgomery_square";
7230 
7231   assert(callee()->signature()->size() == 6, "montgomerySquare has 6 parameters");
7232 
7233   Node* a    = argument(0);
7234   Node* n    = argument(1);
7235   Node* len  = argument(2);
7236   Node* inv  = argument(3);
7237   Node* m    = argument(5);
7238 
7239   const TypeAryPtr* a_type = a->Value(&_gvn)->isa_aryptr();
7240   const TypeAryPtr* n_type = n->Value(&_gvn)->isa_aryptr();
7241   const TypeAryPtr* m_type = m->Value(&_gvn)->isa_aryptr();
7242   if (a_type == nullptr || a_type->elem() == Type::BOTTOM ||
7243       n_type == nullptr || n_type->elem() == Type::BOTTOM ||
7244       m_type == nullptr || m_type->elem() == Type::BOTTOM) {
7245     // failed array check
7246     return false;
7247   }
7248 
7249   BasicType a_elem = a_type->elem()->array_element_basic_type();
7250   BasicType n_elem = n_type->elem()->array_element_basic_type();
7251   BasicType m_elem = m_type->elem()->array_element_basic_type();
7252   if (a_elem != T_INT || n_elem != T_INT || m_elem != T_INT) {
7253     return false;
7254   }
7255 
7256   // Make the call
7257   {
7258     Node* a_start = array_element_address(a, intcon(0), a_elem);
7259     Node* n_start = array_element_address(n, intcon(0), n_elem);
7260     Node* m_start = array_element_address(m, intcon(0), m_elem);
7261 
7262     Node* call = make_runtime_call(RC_LEAF,
7263                                    OptoRuntime::montgomerySquare_Type(),
7264                                    stubAddr, stubName, TypePtr::BOTTOM,
7265                                    a_start, n_start, len, inv, top(),
7266                                    m_start);
7267     set_result(m);
7268   }
7269 
7270   return true;
7271 }
7272 
7273 bool LibraryCallKit::inline_bigIntegerShift(bool isRightShift) {
7274   address stubAddr = nullptr;
7275   const char* stubName = nullptr;
7276 
7277   stubAddr = isRightShift? StubRoutines::bigIntegerRightShift(): StubRoutines::bigIntegerLeftShift();
7278   if (stubAddr == nullptr) {
7279     return false; // Intrinsic's stub is not implemented on this platform
7280   }
7281 
7282   stubName = isRightShift? "bigIntegerRightShiftWorker" : "bigIntegerLeftShiftWorker";
7283 
7284   assert(callee()->signature()->size() == 5, "expected 5 arguments");
7285 
7286   Node* newArr = argument(0);
7287   Node* oldArr = argument(1);
7288   Node* newIdx = argument(2);
7289   Node* shiftCount = argument(3);
7290   Node* numIter = argument(4);
7291 
7292   const TypeAryPtr* newArr_type = newArr->Value(&_gvn)->isa_aryptr();
7293   const TypeAryPtr* oldArr_type = oldArr->Value(&_gvn)->isa_aryptr();
7294   if (newArr_type == nullptr || newArr_type->elem() == Type::BOTTOM ||
7295       oldArr_type == nullptr || oldArr_type->elem() == Type::BOTTOM) {
7296     return false;
7297   }
7298 
7299   BasicType newArr_elem = newArr_type->elem()->array_element_basic_type();
7300   BasicType oldArr_elem = oldArr_type->elem()->array_element_basic_type();
7301   if (newArr_elem != T_INT || oldArr_elem != T_INT) {
7302     return false;
7303   }
7304 
7305   // Make the call
7306   {
7307     Node* newArr_start = array_element_address(newArr, intcon(0), newArr_elem);
7308     Node* oldArr_start = array_element_address(oldArr, intcon(0), oldArr_elem);
7309 
7310     Node* call = make_runtime_call(RC_LEAF,
7311                                    OptoRuntime::bigIntegerShift_Type(),
7312                                    stubAddr,
7313                                    stubName,
7314                                    TypePtr::BOTTOM,
7315                                    newArr_start,
7316                                    oldArr_start,
7317                                    newIdx,
7318                                    shiftCount,
7319                                    numIter);
7320   }
7321 
7322   return true;
7323 }
7324 
7325 //-------------inline_vectorizedMismatch------------------------------
7326 bool LibraryCallKit::inline_vectorizedMismatch() {
7327   assert(UseVectorizedMismatchIntrinsic, "not implemented on this platform");
7328 
7329   assert(callee()->signature()->size() == 8, "vectorizedMismatch has 6 parameters");
7330   Node* obja    = argument(0); // Object
7331   Node* aoffset = argument(1); // long
7332   Node* objb    = argument(3); // Object
7333   Node* boffset = argument(4); // long
7334   Node* length  = argument(6); // int
7335   Node* scale   = argument(7); // int
7336 
7337   const TypeAryPtr* obja_t = _gvn.type(obja)->isa_aryptr();
7338   const TypeAryPtr* objb_t = _gvn.type(objb)->isa_aryptr();
7339   if (obja_t == nullptr || obja_t->elem() == Type::BOTTOM ||
7340       objb_t == nullptr || objb_t->elem() == Type::BOTTOM ||
7341       scale == top()) {
7342     return false; // failed input validation
7343   }
7344 
7345   Node* obja_adr = make_unsafe_address(obja, aoffset);
7346   Node* objb_adr = make_unsafe_address(objb, boffset);
7347 
7348   // Partial inlining handling for inputs smaller than ArrayOperationPartialInlineSize bytes in size.
7349   //
7350   //    inline_limit = ArrayOperationPartialInlineSize / element_size;
7351   //    if (length <= inline_limit) {
7352   //      inline_path:
7353   //        vmask   = VectorMaskGen length
7354   //        vload1  = LoadVectorMasked obja, vmask
7355   //        vload2  = LoadVectorMasked objb, vmask
7356   //        result1 = VectorCmpMasked vload1, vload2, vmask
7357   //    } else {
7358   //      call_stub_path:
7359   //        result2 = call vectorizedMismatch_stub(obja, objb, length, scale)
7360   //    }
7361   //    exit_block:
7362   //      return Phi(result1, result2);
7363   //
7364   enum { inline_path = 1,  // input is small enough to process it all at once
7365          stub_path   = 2,  // input is too large; call into the VM
7366          PATH_LIMIT  = 3
7367   };
7368 
7369   Node* exit_block = new RegionNode(PATH_LIMIT);
7370   Node* result_phi = new PhiNode(exit_block, TypeInt::INT);
7371   Node* memory_phi = new PhiNode(exit_block, Type::MEMORY, TypePtr::BOTTOM);
7372 
7373   Node* call_stub_path = control();
7374 
7375   BasicType elem_bt = T_ILLEGAL;
7376 
7377   const TypeInt* scale_t = _gvn.type(scale)->is_int();
7378   if (scale_t->is_con()) {
7379     switch (scale_t->get_con()) {
7380       case 0: elem_bt = T_BYTE;  break;
7381       case 1: elem_bt = T_SHORT; break;
7382       case 2: elem_bt = T_INT;   break;
7383       case 3: elem_bt = T_LONG;  break;
7384 
7385       default: elem_bt = T_ILLEGAL; break; // not supported
7386     }
7387   }
7388 
7389   int inline_limit = 0;
7390   bool do_partial_inline = false;
7391 
7392   if (elem_bt != T_ILLEGAL && ArrayOperationPartialInlineSize > 0) {
7393     inline_limit = ArrayOperationPartialInlineSize / type2aelembytes(elem_bt);
7394     do_partial_inline = inline_limit >= 16;
7395   }
7396 
7397   if (do_partial_inline) {
7398     assert(elem_bt != T_ILLEGAL, "sanity");
7399 
7400     if (Matcher::match_rule_supported_vector(Op_VectorMaskGen,    inline_limit, elem_bt) &&
7401         Matcher::match_rule_supported_vector(Op_LoadVectorMasked, inline_limit, elem_bt) &&
7402         Matcher::match_rule_supported_vector(Op_VectorCmpMasked,  inline_limit, elem_bt)) {
7403 
7404       const TypeVect* vt = TypeVect::make(elem_bt, inline_limit);
7405       Node* cmp_length = _gvn.transform(new CmpINode(length, intcon(inline_limit)));
7406       Node* bol_gt     = _gvn.transform(new BoolNode(cmp_length, BoolTest::gt));
7407 
7408       call_stub_path = generate_guard(bol_gt, nullptr, PROB_MIN);
7409 
7410       if (!stopped()) {
7411         Node* casted_length = _gvn.transform(new CastIINode(control(), length, TypeInt::make(0, inline_limit, Type::WidenMin)));
7412 
7413         const TypePtr* obja_adr_t = _gvn.type(obja_adr)->isa_ptr();
7414         const TypePtr* objb_adr_t = _gvn.type(objb_adr)->isa_ptr();
7415         Node* obja_adr_mem = memory(C->get_alias_index(obja_adr_t));
7416         Node* objb_adr_mem = memory(C->get_alias_index(objb_adr_t));
7417 
7418         Node* vmask      = _gvn.transform(VectorMaskGenNode::make(ConvI2X(casted_length), elem_bt));
7419         Node* vload_obja = _gvn.transform(new LoadVectorMaskedNode(control(), obja_adr_mem, obja_adr, obja_adr_t, vt, vmask));
7420         Node* vload_objb = _gvn.transform(new LoadVectorMaskedNode(control(), objb_adr_mem, objb_adr, objb_adr_t, vt, vmask));
7421         Node* result     = _gvn.transform(new VectorCmpMaskedNode(vload_obja, vload_objb, vmask, TypeInt::INT));
7422 
7423         exit_block->init_req(inline_path, control());
7424         memory_phi->init_req(inline_path, map()->memory());
7425         result_phi->init_req(inline_path, result);
7426 
7427         C->set_max_vector_size(MAX2((uint)ArrayOperationPartialInlineSize, C->max_vector_size()));
7428         clear_upper_avx();
7429       }
7430     }
7431   }
7432 
7433   if (call_stub_path != nullptr) {
7434     set_control(call_stub_path);
7435 
7436     Node* call = make_runtime_call(RC_LEAF,
7437                                    OptoRuntime::vectorizedMismatch_Type(),
7438                                    StubRoutines::vectorizedMismatch(), "vectorizedMismatch", TypePtr::BOTTOM,
7439                                    obja_adr, objb_adr, length, scale);
7440 
7441     exit_block->init_req(stub_path, control());
7442     memory_phi->init_req(stub_path, map()->memory());
7443     result_phi->init_req(stub_path, _gvn.transform(new ProjNode(call, TypeFunc::Parms)));
7444   }
7445 
7446   exit_block = _gvn.transform(exit_block);
7447   memory_phi = _gvn.transform(memory_phi);
7448   result_phi = _gvn.transform(result_phi);
7449 
7450   record_for_igvn(exit_block);
7451   record_for_igvn(memory_phi);
7452   record_for_igvn(result_phi);
7453 
7454   set_control(exit_block);
7455   set_all_memory(memory_phi);
7456   set_result(result_phi);
7457 
7458   return true;
7459 }
7460 
7461 //------------------------------inline_vectorizedHashcode----------------------------
7462 bool LibraryCallKit::inline_vectorizedHashCode() {
7463   assert(UseVectorizedHashCodeIntrinsic, "not implemented on this platform");
7464 
7465   assert(callee()->signature()->size() == 5, "vectorizedHashCode has 5 parameters");
7466   Node* array          = argument(0);
7467   Node* offset         = argument(1);
7468   Node* length         = argument(2);
7469   Node* initialValue   = argument(3);
7470   Node* basic_type     = argument(4);
7471 
7472   if (basic_type == top()) {
7473     return false; // failed input validation
7474   }
7475 
7476   const TypeInt* basic_type_t = _gvn.type(basic_type)->is_int();
7477   if (!basic_type_t->is_con()) {
7478     return false; // Only intrinsify if mode argument is constant
7479   }
7480 
7481   array = must_be_not_null(array, true);
7482 
7483   BasicType bt = (BasicType)basic_type_t->get_con();
7484 
7485   // Resolve address of first element
7486   Node* array_start = array_element_address(array, offset, bt);
7487 
7488   set_result(_gvn.transform(new VectorizedHashCodeNode(control(), memory(TypeAryPtr::get_array_body_type(bt)),
7489     array_start, length, initialValue, basic_type)));
7490   clear_upper_avx();
7491 
7492   return true;
7493 }
7494 
7495 /**
7496  * Calculate CRC32 for byte.
7497  * int java.util.zip.CRC32.update(int crc, int b)
7498  */
7499 bool LibraryCallKit::inline_updateCRC32() {
7500   assert(UseCRC32Intrinsics, "need AVX and CLMUL instructions support");
7501   assert(callee()->signature()->size() == 2, "update has 2 parameters");
7502   // no receiver since it is static method
7503   Node* crc  = argument(0); // type: int
7504   Node* b    = argument(1); // type: int
7505 
7506   /*
7507    *    int c = ~ crc;
7508    *    b = timesXtoThe32[(b ^ c) & 0xFF];
7509    *    b = b ^ (c >>> 8);
7510    *    crc = ~b;
7511    */
7512 
7513   Node* M1 = intcon(-1);
7514   crc = _gvn.transform(new XorINode(crc, M1));
7515   Node* result = _gvn.transform(new XorINode(crc, b));
7516   result = _gvn.transform(new AndINode(result, intcon(0xFF)));
7517 
7518   Node* base = makecon(TypeRawPtr::make(StubRoutines::crc_table_addr()));
7519   Node* offset = _gvn.transform(new LShiftINode(result, intcon(0x2)));
7520   Node* adr = basic_plus_adr(top(), base, ConvI2X(offset));
7521   result = make_load(control(), adr, TypeInt::INT, T_INT, MemNode::unordered);
7522 
7523   crc = _gvn.transform(new URShiftINode(crc, intcon(8)));
7524   result = _gvn.transform(new XorINode(crc, result));
7525   result = _gvn.transform(new XorINode(result, M1));
7526   set_result(result);
7527   return true;
7528 }
7529 
7530 /**
7531  * Calculate CRC32 for byte[] array.
7532  * int java.util.zip.CRC32.updateBytes(int crc, byte[] buf, int off, int len)
7533  */
7534 bool LibraryCallKit::inline_updateBytesCRC32() {
7535   assert(UseCRC32Intrinsics, "need AVX and CLMUL instructions support");
7536   assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
7537   // no receiver since it is static method
7538   Node* crc     = argument(0); // type: int
7539   Node* src     = argument(1); // type: oop
7540   Node* offset  = argument(2); // type: int
7541   Node* length  = argument(3); // type: int
7542 
7543   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7544   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
7545     // failed array check
7546     return false;
7547   }
7548 
7549   // Figure out the size and type of the elements we will be copying.
7550   BasicType src_elem = src_type->elem()->array_element_basic_type();
7551   if (src_elem != T_BYTE) {
7552     return false;
7553   }
7554 
7555   // 'src_start' points to src array + scaled offset
7556   src = must_be_not_null(src, true);
7557   Node* src_start = array_element_address(src, offset, src_elem);
7558 
7559   // We assume that range check is done by caller.
7560   // TODO: generate range check (offset+length < src.length) in debug VM.
7561 
7562   // Call the stub.
7563   address stubAddr = StubRoutines::updateBytesCRC32();
7564   const char *stubName = "updateBytesCRC32";
7565 
7566   Node* call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::updateBytesCRC32_Type(),
7567                                  stubAddr, stubName, TypePtr::BOTTOM,
7568                                  crc, src_start, length);
7569   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7570   set_result(result);
7571   return true;
7572 }
7573 
7574 /**
7575  * Calculate CRC32 for ByteBuffer.
7576  * int java.util.zip.CRC32.updateByteBuffer(int crc, long buf, int off, int len)
7577  */
7578 bool LibraryCallKit::inline_updateByteBufferCRC32() {
7579   assert(UseCRC32Intrinsics, "need AVX and CLMUL instructions support");
7580   assert(callee()->signature()->size() == 5, "updateByteBuffer has 4 parameters and one is long");
7581   // no receiver since it is static method
7582   Node* crc     = argument(0); // type: int
7583   Node* src     = argument(1); // type: long
7584   Node* offset  = argument(3); // type: int
7585   Node* length  = argument(4); // type: int
7586 
7587   src = ConvL2X(src);  // adjust Java long to machine word
7588   Node* base = _gvn.transform(new CastX2PNode(src));
7589   offset = ConvI2X(offset);
7590 
7591   // 'src_start' points to src array + scaled offset
7592   Node* src_start = basic_plus_adr(top(), base, offset);
7593 
7594   // Call the stub.
7595   address stubAddr = StubRoutines::updateBytesCRC32();
7596   const char *stubName = "updateBytesCRC32";
7597 
7598   Node* call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::updateBytesCRC32_Type(),
7599                                  stubAddr, stubName, TypePtr::BOTTOM,
7600                                  crc, src_start, length);
7601   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7602   set_result(result);
7603   return true;
7604 }
7605 
7606 //------------------------------get_table_from_crc32c_class-----------------------
7607 Node * LibraryCallKit::get_table_from_crc32c_class(ciInstanceKlass *crc32c_class) {
7608   Node* table = load_field_from_object(nullptr, "byteTable", "[I", /*decorators*/ IN_HEAP, /*is_static*/ true, crc32c_class);
7609   assert (table != nullptr, "wrong version of java.util.zip.CRC32C");
7610 
7611   return table;
7612 }
7613 
7614 //------------------------------inline_updateBytesCRC32C-----------------------
7615 //
7616 // Calculate CRC32C for byte[] array.
7617 // int java.util.zip.CRC32C.updateBytes(int crc, byte[] buf, int off, int end)
7618 //
7619 bool LibraryCallKit::inline_updateBytesCRC32C() {
7620   assert(UseCRC32CIntrinsics, "need CRC32C instruction support");
7621   assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
7622   assert(callee()->holder()->is_loaded(), "CRC32C class must be loaded");
7623   // no receiver since it is a static method
7624   Node* crc     = argument(0); // type: int
7625   Node* src     = argument(1); // type: oop
7626   Node* offset  = argument(2); // type: int
7627   Node* end     = argument(3); // type: int
7628 
7629   Node* length = _gvn.transform(new SubINode(end, offset));
7630 
7631   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7632   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
7633     // failed array check
7634     return false;
7635   }
7636 
7637   // Figure out the size and type of the elements we will be copying.
7638   BasicType src_elem = src_type->elem()->array_element_basic_type();
7639   if (src_elem != T_BYTE) {
7640     return false;
7641   }
7642 
7643   // 'src_start' points to src array + scaled offset
7644   src = must_be_not_null(src, true);
7645   Node* src_start = array_element_address(src, offset, src_elem);
7646 
7647   // static final int[] byteTable in class CRC32C
7648   Node* table = get_table_from_crc32c_class(callee()->holder());
7649   table = must_be_not_null(table, true);
7650   Node* table_start = array_element_address(table, intcon(0), T_INT);
7651 
7652   // We assume that range check is done by caller.
7653   // TODO: generate range check (offset+length < src.length) in debug VM.
7654 
7655   // Call the stub.
7656   address stubAddr = StubRoutines::updateBytesCRC32C();
7657   const char *stubName = "updateBytesCRC32C";
7658 
7659   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesCRC32C_Type(),
7660                                  stubAddr, stubName, TypePtr::BOTTOM,
7661                                  crc, src_start, length, table_start);
7662   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7663   set_result(result);
7664   return true;
7665 }
7666 
7667 //------------------------------inline_updateDirectByteBufferCRC32C-----------------------
7668 //
7669 // Calculate CRC32C for DirectByteBuffer.
7670 // int java.util.zip.CRC32C.updateDirectByteBuffer(int crc, long buf, int off, int end)
7671 //
7672 bool LibraryCallKit::inline_updateDirectByteBufferCRC32C() {
7673   assert(UseCRC32CIntrinsics, "need CRC32C instruction support");
7674   assert(callee()->signature()->size() == 5, "updateDirectByteBuffer has 4 parameters and one is long");
7675   assert(callee()->holder()->is_loaded(), "CRC32C class must be loaded");
7676   // no receiver since it is a static method
7677   Node* crc     = argument(0); // type: int
7678   Node* src     = argument(1); // type: long
7679   Node* offset  = argument(3); // type: int
7680   Node* end     = argument(4); // type: int
7681 
7682   Node* length = _gvn.transform(new SubINode(end, offset));
7683 
7684   src = ConvL2X(src);  // adjust Java long to machine word
7685   Node* base = _gvn.transform(new CastX2PNode(src));
7686   offset = ConvI2X(offset);
7687 
7688   // 'src_start' points to src array + scaled offset
7689   Node* src_start = basic_plus_adr(top(), base, offset);
7690 
7691   // static final int[] byteTable in class CRC32C
7692   Node* table = get_table_from_crc32c_class(callee()->holder());
7693   table = must_be_not_null(table, true);
7694   Node* table_start = array_element_address(table, intcon(0), T_INT);
7695 
7696   // Call the stub.
7697   address stubAddr = StubRoutines::updateBytesCRC32C();
7698   const char *stubName = "updateBytesCRC32C";
7699 
7700   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesCRC32C_Type(),
7701                                  stubAddr, stubName, TypePtr::BOTTOM,
7702                                  crc, src_start, length, table_start);
7703   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7704   set_result(result);
7705   return true;
7706 }
7707 
7708 //------------------------------inline_updateBytesAdler32----------------------
7709 //
7710 // Calculate Adler32 checksum for byte[] array.
7711 // int java.util.zip.Adler32.updateBytes(int crc, byte[] buf, int off, int len)
7712 //
7713 bool LibraryCallKit::inline_updateBytesAdler32() {
7714   assert(UseAdler32Intrinsics, "Adler32 Intrinsic support need"); // check if we actually need to check this flag or check a different one
7715   assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
7716   assert(callee()->holder()->is_loaded(), "Adler32 class must be loaded");
7717   // no receiver since it is static method
7718   Node* crc     = argument(0); // type: int
7719   Node* src     = argument(1); // type: oop
7720   Node* offset  = argument(2); // type: int
7721   Node* length  = argument(3); // type: int
7722 
7723   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7724   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
7725     // failed array check
7726     return false;
7727   }
7728 
7729   // Figure out the size and type of the elements we will be copying.
7730   BasicType src_elem = src_type->elem()->array_element_basic_type();
7731   if (src_elem != T_BYTE) {
7732     return false;
7733   }
7734 
7735   // 'src_start' points to src array + scaled offset
7736   Node* src_start = array_element_address(src, offset, src_elem);
7737 
7738   // We assume that range check is done by caller.
7739   // TODO: generate range check (offset+length < src.length) in debug VM.
7740 
7741   // Call the stub.
7742   address stubAddr = StubRoutines::updateBytesAdler32();
7743   const char *stubName = "updateBytesAdler32";
7744 
7745   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesAdler32_Type(),
7746                                  stubAddr, stubName, TypePtr::BOTTOM,
7747                                  crc, src_start, length);
7748   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7749   set_result(result);
7750   return true;
7751 }
7752 
7753 //------------------------------inline_updateByteBufferAdler32---------------
7754 //
7755 // Calculate Adler32 checksum for DirectByteBuffer.
7756 // int java.util.zip.Adler32.updateByteBuffer(int crc, long buf, int off, int len)
7757 //
7758 bool LibraryCallKit::inline_updateByteBufferAdler32() {
7759   assert(UseAdler32Intrinsics, "Adler32 Intrinsic support need"); // check if we actually need to check this flag or check a different one
7760   assert(callee()->signature()->size() == 5, "updateByteBuffer has 4 parameters and one is long");
7761   assert(callee()->holder()->is_loaded(), "Adler32 class must be loaded");
7762   // no receiver since it is static method
7763   Node* crc     = argument(0); // type: int
7764   Node* src     = argument(1); // type: long
7765   Node* offset  = argument(3); // type: int
7766   Node* length  = argument(4); // type: int
7767 
7768   src = ConvL2X(src);  // adjust Java long to machine word
7769   Node* base = _gvn.transform(new CastX2PNode(src));
7770   offset = ConvI2X(offset);
7771 
7772   // 'src_start' points to src array + scaled offset
7773   Node* src_start = basic_plus_adr(top(), base, offset);
7774 
7775   // Call the stub.
7776   address stubAddr = StubRoutines::updateBytesAdler32();
7777   const char *stubName = "updateBytesAdler32";
7778 
7779   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesAdler32_Type(),
7780                                  stubAddr, stubName, TypePtr::BOTTOM,
7781                                  crc, src_start, length);
7782 
7783   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7784   set_result(result);
7785   return true;
7786 }
7787 
7788 //----------------------------inline_reference_get0----------------------------
7789 // public T java.lang.ref.Reference.get();
7790 bool LibraryCallKit::inline_reference_get0() {
7791   const int referent_offset = java_lang_ref_Reference::referent_offset();
7792 
7793   // Get the argument:
7794   Node* reference_obj = null_check_receiver();
7795   if (stopped()) return true;
7796 
7797   DecoratorSet decorators = IN_HEAP | ON_WEAK_OOP_REF;
7798   Node* result = load_field_from_object(reference_obj, "referent", "Ljava/lang/Object;",
7799                                         decorators, /*is_static*/ false, nullptr);
7800   if (result == nullptr) return false;
7801 
7802   // Add memory barrier to prevent commoning reads from this field
7803   // across safepoint since GC can change its value.
7804   insert_mem_bar(Op_MemBarCPUOrder);
7805 
7806   set_result(result);
7807   return true;
7808 }
7809 
7810 //----------------------------inline_reference_refersTo0----------------------------
7811 // bool java.lang.ref.Reference.refersTo0();
7812 // bool java.lang.ref.PhantomReference.refersTo0();
7813 bool LibraryCallKit::inline_reference_refersTo0(bool is_phantom) {
7814   // Get arguments:
7815   Node* reference_obj = null_check_receiver();
7816   Node* other_obj = argument(1);
7817   if (stopped()) return true;
7818 
7819   DecoratorSet decorators = IN_HEAP | AS_NO_KEEPALIVE;
7820   decorators |= (is_phantom ? ON_PHANTOM_OOP_REF : ON_WEAK_OOP_REF);
7821   Node* referent = load_field_from_object(reference_obj, "referent", "Ljava/lang/Object;",
7822                                           decorators, /*is_static*/ false, nullptr);
7823   if (referent == nullptr) return false;
7824 
7825   // Add memory barrier to prevent commoning reads from this field
7826   // across safepoint since GC can change its value.
7827   insert_mem_bar(Op_MemBarCPUOrder);
7828 
7829   Node* cmp = _gvn.transform(new CmpPNode(referent, other_obj));
7830   Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
7831   IfNode* if_node = create_and_map_if(control(), bol, PROB_FAIR, COUNT_UNKNOWN);
7832 
7833   RegionNode* region = new RegionNode(3);
7834   PhiNode* phi = new PhiNode(region, TypeInt::BOOL);
7835 
7836   Node* if_true = _gvn.transform(new IfTrueNode(if_node));
7837   region->init_req(1, if_true);
7838   phi->init_req(1, intcon(1));
7839 
7840   Node* if_false = _gvn.transform(new IfFalseNode(if_node));
7841   region->init_req(2, if_false);
7842   phi->init_req(2, intcon(0));
7843 
7844   set_control(_gvn.transform(region));
7845   record_for_igvn(region);
7846   set_result(_gvn.transform(phi));
7847   return true;
7848 }
7849 
7850 //----------------------------inline_reference_clear0----------------------------
7851 // void java.lang.ref.Reference.clear0();
7852 // void java.lang.ref.PhantomReference.clear0();
7853 bool LibraryCallKit::inline_reference_clear0(bool is_phantom) {
7854   // This matches the implementation in JVM_ReferenceClear, see the comments there.
7855 
7856   // Get arguments
7857   Node* reference_obj = null_check_receiver();
7858   if (stopped()) return true;
7859 
7860   // Common access parameters
7861   DecoratorSet decorators = IN_HEAP | AS_NO_KEEPALIVE;
7862   decorators |= (is_phantom ? ON_PHANTOM_OOP_REF : ON_WEAK_OOP_REF);
7863   Node* referent_field_addr = basic_plus_adr(reference_obj, java_lang_ref_Reference::referent_offset());
7864   const TypePtr* referent_field_addr_type = _gvn.type(referent_field_addr)->isa_ptr();
7865   const Type* val_type = TypeOopPtr::make_from_klass(env()->Object_klass());
7866 
7867   Node* referent = access_load_at(reference_obj,
7868                                   referent_field_addr,
7869                                   referent_field_addr_type,
7870                                   val_type,
7871                                   T_OBJECT,
7872                                   decorators);
7873 
7874   IdealKit ideal(this);
7875 #define __ ideal.
7876   __ if_then(referent, BoolTest::ne, null());
7877     sync_kit(ideal);
7878     access_store_at(reference_obj,
7879                     referent_field_addr,
7880                     referent_field_addr_type,
7881                     null(),
7882                     val_type,
7883                     T_OBJECT,
7884                     decorators);
7885     __ sync_kit(this);
7886   __ end_if();
7887   final_sync(ideal);
7888 #undef __
7889 
7890   return true;
7891 }
7892 
7893 Node* LibraryCallKit::load_field_from_object(Node* fromObj, const char* fieldName, const char* fieldTypeString,
7894                                              DecoratorSet decorators, bool is_static,
7895                                              ciInstanceKlass* fromKls) {
7896   if (fromKls == nullptr) {
7897     const TypeInstPtr* tinst = _gvn.type(fromObj)->isa_instptr();
7898     assert(tinst != nullptr, "obj is null");
7899     assert(tinst->is_loaded(), "obj is not loaded");
7900     fromKls = tinst->instance_klass();
7901   } else {
7902     assert(is_static, "only for static field access");
7903   }
7904   ciField* field = fromKls->get_field_by_name(ciSymbol::make(fieldName),
7905                                               ciSymbol::make(fieldTypeString),
7906                                               is_static);
7907 
7908   assert(field != nullptr, "undefined field %s %s %s", fieldTypeString, fromKls->name()->as_utf8(), fieldName);
7909   if (field == nullptr) return (Node *) nullptr;
7910 
7911   if (is_static) {
7912     const TypeInstPtr* tip = TypeInstPtr::make(fromKls->java_mirror());
7913     fromObj = makecon(tip);
7914   }
7915 
7916   // Next code  copied from Parse::do_get_xxx():
7917 
7918   // Compute address and memory type.
7919   int offset  = field->offset_in_bytes();
7920   bool is_vol = field->is_volatile();
7921   ciType* field_klass = field->type();
7922   assert(field_klass->is_loaded(), "should be loaded");
7923   const TypePtr* adr_type = C->alias_type(field)->adr_type();
7924   Node *adr = basic_plus_adr(fromObj, fromObj, offset);
7925   assert(C->get_alias_index(adr_type) == C->get_alias_index(_gvn.type(adr)->isa_ptr()),
7926     "slice of address and input slice don't match");
7927   BasicType bt = field->layout_type();
7928 
7929   // Build the resultant type of the load
7930   const Type *type;
7931   if (bt == T_OBJECT) {
7932     type = TypeOopPtr::make_from_klass(field_klass->as_klass());
7933   } else {
7934     type = Type::get_const_basic_type(bt);
7935   }
7936 
7937   if (is_vol) {
7938     decorators |= MO_SEQ_CST;
7939   }
7940 
7941   return access_load_at(fromObj, adr, adr_type, type, bt, decorators);
7942 }
7943 
7944 Node * LibraryCallKit::field_address_from_object(Node * fromObj, const char * fieldName, const char * fieldTypeString,
7945                                                  bool is_exact /* true */, bool is_static /* false */,
7946                                                  ciInstanceKlass * fromKls /* nullptr */) {
7947   if (fromKls == nullptr) {
7948     const TypeInstPtr* tinst = _gvn.type(fromObj)->isa_instptr();
7949     assert(tinst != nullptr, "obj is null");
7950     assert(tinst->is_loaded(), "obj is not loaded");
7951     assert(!is_exact || tinst->klass_is_exact(), "klass not exact");
7952     fromKls = tinst->instance_klass();
7953   }
7954   else {
7955     assert(is_static, "only for static field access");
7956   }
7957   ciField* field = fromKls->get_field_by_name(ciSymbol::make(fieldName),
7958     ciSymbol::make(fieldTypeString),
7959     is_static);
7960 
7961   assert(field != nullptr, "undefined field");
7962   assert(!field->is_volatile(), "not defined for volatile fields");
7963 
7964   if (is_static) {
7965     const TypeInstPtr* tip = TypeInstPtr::make(fromKls->java_mirror());
7966     fromObj = makecon(tip);
7967   }
7968 
7969   // Next code  copied from Parse::do_get_xxx():
7970 
7971   // Compute address and memory type.
7972   int offset = field->offset_in_bytes();
7973   Node *adr = basic_plus_adr(fromObj, fromObj, offset);
7974 
7975   return adr;
7976 }
7977 
7978 //------------------------------inline_aescrypt_Block-----------------------
7979 bool LibraryCallKit::inline_aescrypt_Block(vmIntrinsics::ID id) {
7980   address stubAddr = nullptr;
7981   const char *stubName;
7982   bool is_decrypt = false;
7983   assert(UseAES, "need AES instruction support");
7984 
7985   switch(id) {
7986   case vmIntrinsics::_aescrypt_encryptBlock:
7987     stubAddr = StubRoutines::aescrypt_encryptBlock();
7988     stubName = "aescrypt_encryptBlock";
7989     break;
7990   case vmIntrinsics::_aescrypt_decryptBlock:
7991     stubAddr = StubRoutines::aescrypt_decryptBlock();
7992     stubName = "aescrypt_decryptBlock";
7993     is_decrypt = true;
7994     break;
7995   default:
7996     break;
7997   }
7998   if (stubAddr == nullptr) return false;
7999 
8000   Node* aescrypt_object = argument(0);
8001   Node* src             = argument(1);
8002   Node* src_offset      = argument(2);
8003   Node* dest            = argument(3);
8004   Node* dest_offset     = argument(4);
8005 
8006   src = must_be_not_null(src, true);
8007   dest = must_be_not_null(dest, true);
8008 
8009   // (1) src and dest are arrays.
8010   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
8011   const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
8012   assert( src_type != nullptr &&  src_type->elem() != Type::BOTTOM &&
8013          dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
8014 
8015   // for the quick and dirty code we will skip all the checks.
8016   // we are just trying to get the call to be generated.
8017   Node* src_start  = src;
8018   Node* dest_start = dest;
8019   if (src_offset != nullptr || dest_offset != nullptr) {
8020     assert(src_offset != nullptr && dest_offset != nullptr, "");
8021     src_start  = array_element_address(src,  src_offset,  T_BYTE);
8022     dest_start = array_element_address(dest, dest_offset, T_BYTE);
8023   }
8024 
8025   // now need to get the start of its expanded key array
8026   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
8027   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object, is_decrypt);
8028   if (k_start == nullptr) return false;
8029 
8030   // Call the stub.
8031   make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::aescrypt_block_Type(),
8032                     stubAddr, stubName, TypePtr::BOTTOM,
8033                     src_start, dest_start, k_start);
8034 
8035   return true;
8036 }
8037 
8038 //------------------------------inline_cipherBlockChaining_AESCrypt-----------------------
8039 bool LibraryCallKit::inline_cipherBlockChaining_AESCrypt(vmIntrinsics::ID id) {
8040   address stubAddr = nullptr;
8041   const char *stubName = nullptr;
8042   bool is_decrypt = false;
8043   assert(UseAES, "need AES instruction support");
8044 
8045   switch(id) {
8046   case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
8047     stubAddr = StubRoutines::cipherBlockChaining_encryptAESCrypt();
8048     stubName = "cipherBlockChaining_encryptAESCrypt";
8049     break;
8050   case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
8051     stubAddr = StubRoutines::cipherBlockChaining_decryptAESCrypt();
8052     stubName = "cipherBlockChaining_decryptAESCrypt";
8053     is_decrypt = true;
8054     break;
8055   default:
8056     break;
8057   }
8058   if (stubAddr == nullptr) return false;
8059 
8060   Node* cipherBlockChaining_object = argument(0);
8061   Node* src                        = argument(1);
8062   Node* src_offset                 = argument(2);
8063   Node* len                        = argument(3);
8064   Node* dest                       = argument(4);
8065   Node* dest_offset                = argument(5);
8066 
8067   src = must_be_not_null(src, false);
8068   dest = must_be_not_null(dest, false);
8069 
8070   // (1) src and dest are arrays.
8071   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
8072   const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
8073   assert( src_type != nullptr &&  src_type->elem() != Type::BOTTOM &&
8074          dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
8075 
8076   // checks are the responsibility of the caller
8077   Node* src_start  = src;
8078   Node* dest_start = dest;
8079   if (src_offset != nullptr || dest_offset != nullptr) {
8080     assert(src_offset != nullptr && dest_offset != nullptr, "");
8081     src_start  = array_element_address(src,  src_offset,  T_BYTE);
8082     dest_start = array_element_address(dest, dest_offset, T_BYTE);
8083   }
8084 
8085   // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
8086   // (because of the predicated logic executed earlier).
8087   // so we cast it here safely.
8088   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
8089 
8090   Node* embeddedCipherObj = load_field_from_object(cipherBlockChaining_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8091   if (embeddedCipherObj == nullptr) return false;
8092 
8093   // cast it to what we know it will be at runtime
8094   const TypeInstPtr* tinst = _gvn.type(cipherBlockChaining_object)->isa_instptr();
8095   assert(tinst != nullptr, "CBC obj is null");
8096   assert(tinst->is_loaded(), "CBC obj is not loaded");
8097   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8098   assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
8099 
8100   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8101   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
8102   const TypeOopPtr* xtype = aklass->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
8103   Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
8104   aescrypt_object = _gvn.transform(aescrypt_object);
8105 
8106   // we need to get the start of the aescrypt_object's expanded key array
8107   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object, is_decrypt);
8108   if (k_start == nullptr) return false;
8109 
8110   // similarly, get the start address of the r vector
8111   Node* objRvec = load_field_from_object(cipherBlockChaining_object, "r", "[B");
8112   if (objRvec == nullptr) return false;
8113   Node* r_start = array_element_address(objRvec, intcon(0), T_BYTE);
8114 
8115   // Call the stub, passing src_start, dest_start, k_start, r_start and src_len
8116   Node* cbcCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
8117                                      OptoRuntime::cipherBlockChaining_aescrypt_Type(),
8118                                      stubAddr, stubName, TypePtr::BOTTOM,
8119                                      src_start, dest_start, k_start, r_start, len);
8120 
8121   // return cipher length (int)
8122   Node* retvalue = _gvn.transform(new ProjNode(cbcCrypt, TypeFunc::Parms));
8123   set_result(retvalue);
8124   return true;
8125 }
8126 
8127 //------------------------------inline_electronicCodeBook_AESCrypt-----------------------
8128 bool LibraryCallKit::inline_electronicCodeBook_AESCrypt(vmIntrinsics::ID id) {
8129   address stubAddr = nullptr;
8130   const char *stubName = nullptr;
8131   bool is_decrypt = false;
8132   assert(UseAES, "need AES instruction support");
8133 
8134   switch (id) {
8135   case vmIntrinsics::_electronicCodeBook_encryptAESCrypt:
8136     stubAddr = StubRoutines::electronicCodeBook_encryptAESCrypt();
8137     stubName = "electronicCodeBook_encryptAESCrypt";
8138     break;
8139   case vmIntrinsics::_electronicCodeBook_decryptAESCrypt:
8140     stubAddr = StubRoutines::electronicCodeBook_decryptAESCrypt();
8141     stubName = "electronicCodeBook_decryptAESCrypt";
8142     is_decrypt = true;
8143     break;
8144   default:
8145     break;
8146   }
8147 
8148   if (stubAddr == nullptr) return false;
8149 
8150   Node* electronicCodeBook_object = argument(0);
8151   Node* src                       = argument(1);
8152   Node* src_offset                = argument(2);
8153   Node* len                       = argument(3);
8154   Node* dest                      = argument(4);
8155   Node* dest_offset               = argument(5);
8156 
8157   // (1) src and dest are arrays.
8158   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
8159   const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
8160   assert( src_type != nullptr &&  src_type->elem() != Type::BOTTOM &&
8161          dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
8162 
8163   // checks are the responsibility of the caller
8164   Node* src_start = src;
8165   Node* dest_start = dest;
8166   if (src_offset != nullptr || dest_offset != nullptr) {
8167     assert(src_offset != nullptr && dest_offset != nullptr, "");
8168     src_start = array_element_address(src, src_offset, T_BYTE);
8169     dest_start = array_element_address(dest, dest_offset, T_BYTE);
8170   }
8171 
8172   // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
8173   // (because of the predicated logic executed earlier).
8174   // so we cast it here safely.
8175   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
8176 
8177   Node* embeddedCipherObj = load_field_from_object(electronicCodeBook_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8178   if (embeddedCipherObj == nullptr) return false;
8179 
8180   // cast it to what we know it will be at runtime
8181   const TypeInstPtr* tinst = _gvn.type(electronicCodeBook_object)->isa_instptr();
8182   assert(tinst != nullptr, "ECB obj is null");
8183   assert(tinst->is_loaded(), "ECB obj is not loaded");
8184   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8185   assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
8186 
8187   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8188   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
8189   const TypeOopPtr* xtype = aklass->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
8190   Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
8191   aescrypt_object = _gvn.transform(aescrypt_object);
8192 
8193   // we need to get the start of the aescrypt_object's expanded key array
8194   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object, is_decrypt);
8195   if (k_start == nullptr) return false;
8196 
8197   // Call the stub, passing src_start, dest_start, k_start, r_start and src_len
8198   Node* ecbCrypt = make_runtime_call(RC_LEAF | RC_NO_FP,
8199                                      OptoRuntime::electronicCodeBook_aescrypt_Type(),
8200                                      stubAddr, stubName, TypePtr::BOTTOM,
8201                                      src_start, dest_start, k_start, len);
8202 
8203   // return cipher length (int)
8204   Node* retvalue = _gvn.transform(new ProjNode(ecbCrypt, TypeFunc::Parms));
8205   set_result(retvalue);
8206   return true;
8207 }
8208 
8209 //------------------------------inline_counterMode_AESCrypt-----------------------
8210 bool LibraryCallKit::inline_counterMode_AESCrypt(vmIntrinsics::ID id) {
8211   assert(UseAES, "need AES instruction support");
8212   if (!UseAESCTRIntrinsics) return false;
8213 
8214   address stubAddr = nullptr;
8215   const char *stubName = nullptr;
8216   if (id == vmIntrinsics::_counterMode_AESCrypt) {
8217     stubAddr = StubRoutines::counterMode_AESCrypt();
8218     stubName = "counterMode_AESCrypt";
8219   }
8220   if (stubAddr == nullptr) return false;
8221 
8222   Node* counterMode_object = argument(0);
8223   Node* src = argument(1);
8224   Node* src_offset = argument(2);
8225   Node* len = argument(3);
8226   Node* dest = argument(4);
8227   Node* dest_offset = argument(5);
8228 
8229   // (1) src and dest are arrays.
8230   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
8231   const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
8232   assert( src_type != nullptr &&  src_type->elem() != Type::BOTTOM &&
8233          dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
8234 
8235   // checks are the responsibility of the caller
8236   Node* src_start = src;
8237   Node* dest_start = dest;
8238   if (src_offset != nullptr || dest_offset != nullptr) {
8239     assert(src_offset != nullptr && dest_offset != nullptr, "");
8240     src_start = array_element_address(src, src_offset, T_BYTE);
8241     dest_start = array_element_address(dest, dest_offset, T_BYTE);
8242   }
8243 
8244   // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
8245   // (because of the predicated logic executed earlier).
8246   // so we cast it here safely.
8247   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
8248   Node* embeddedCipherObj = load_field_from_object(counterMode_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8249   if (embeddedCipherObj == nullptr) return false;
8250   // cast it to what we know it will be at runtime
8251   const TypeInstPtr* tinst = _gvn.type(counterMode_object)->isa_instptr();
8252   assert(tinst != nullptr, "CTR obj is null");
8253   assert(tinst->is_loaded(), "CTR obj is not loaded");
8254   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8255   assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
8256   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8257   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
8258   const TypeOopPtr* xtype = aklass->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
8259   Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
8260   aescrypt_object = _gvn.transform(aescrypt_object);
8261   // we need to get the start of the aescrypt_object's expanded key array
8262   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object, /* is_decrypt */ false);
8263   if (k_start == nullptr) return false;
8264   // similarly, get the start address of the r vector
8265   Node* obj_counter = load_field_from_object(counterMode_object, "counter", "[B");
8266   if (obj_counter == nullptr) return false;
8267   Node* cnt_start = array_element_address(obj_counter, intcon(0), T_BYTE);
8268 
8269   Node* saved_encCounter = load_field_from_object(counterMode_object, "encryptedCounter", "[B");
8270   if (saved_encCounter == nullptr) return false;
8271   Node* saved_encCounter_start = array_element_address(saved_encCounter, intcon(0), T_BYTE);
8272   Node* used = field_address_from_object(counterMode_object, "used", "I", /*is_exact*/ false);
8273 
8274   // Call the stub, passing src_start, dest_start, k_start, r_start and src_len
8275   Node* ctrCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
8276                                      OptoRuntime::counterMode_aescrypt_Type(),
8277                                      stubAddr, stubName, TypePtr::BOTTOM,
8278                                      src_start, dest_start, k_start, cnt_start, len, saved_encCounter_start, used);
8279 
8280   // return cipher length (int)
8281   Node* retvalue = _gvn.transform(new ProjNode(ctrCrypt, TypeFunc::Parms));
8282   set_result(retvalue);
8283   return true;
8284 }
8285 
8286 //------------------------------get_key_start_from_aescrypt_object-----------------------
8287 Node* LibraryCallKit::get_key_start_from_aescrypt_object(Node* aescrypt_object, bool is_decrypt) {
8288   // MixColumns for decryption can be reduced by preprocessing MixColumns with round keys.
8289   // Intel's extension is based on this optimization and AESCrypt generates round keys by preprocessing MixColumns.
8290   // However, ppc64 vncipher processes MixColumns and requires the same round keys with encryption.
8291   // The following platform specific stubs of encryption and decryption use the same round keys.
8292 #if defined(PPC64) || defined(S390) || defined(RISCV64)
8293   bool use_decryption_key = false;
8294 #else
8295   bool use_decryption_key = is_decrypt;
8296 #endif
8297   Node* objAESCryptKey = load_field_from_object(aescrypt_object, use_decryption_key ? "sessionKd" : "sessionKe", "[I");
8298   assert(objAESCryptKey != nullptr, "wrong version of com.sun.crypto.provider.AES_Crypt");
8299   if (objAESCryptKey == nullptr) return (Node *) nullptr;
8300 
8301   // now have the array, need to get the start address of the selected key array
8302   Node* k_start = array_element_address(objAESCryptKey, intcon(0), T_INT);
8303   return k_start;
8304 }
8305 
8306 //----------------------------inline_cipherBlockChaining_AESCrypt_predicate----------------------------
8307 // Return node representing slow path of predicate check.
8308 // the pseudo code we want to emulate with this predicate is:
8309 // for encryption:
8310 //    if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
8311 // for decryption:
8312 //    if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
8313 //    note cipher==plain is more conservative than the original java code but that's OK
8314 //
8315 Node* LibraryCallKit::inline_cipherBlockChaining_AESCrypt_predicate(bool decrypting) {
8316   // The receiver was checked for null already.
8317   Node* objCBC = argument(0);
8318 
8319   Node* src = argument(1);
8320   Node* dest = argument(4);
8321 
8322   // Load embeddedCipher field of CipherBlockChaining object.
8323   Node* embeddedCipherObj = load_field_from_object(objCBC, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8324 
8325   // get AESCrypt klass for instanceOf check
8326   // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
8327   // will have same classloader as CipherBlockChaining object
8328   const TypeInstPtr* tinst = _gvn.type(objCBC)->isa_instptr();
8329   assert(tinst != nullptr, "CBCobj is null");
8330   assert(tinst->is_loaded(), "CBCobj is not loaded");
8331 
8332   // we want to do an instanceof comparison against the AESCrypt class
8333   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8334   if (!klass_AESCrypt->is_loaded()) {
8335     // if AESCrypt is not even loaded, we never take the intrinsic fast path
8336     Node* ctrl = control();
8337     set_control(top()); // no regular fast path
8338     return ctrl;
8339   }
8340 
8341   src = must_be_not_null(src, true);
8342   dest = must_be_not_null(dest, true);
8343 
8344   // Resolve oops to stable for CmpP below.
8345   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8346 
8347   Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
8348   Node* cmp_instof  = _gvn.transform(new CmpINode(instof, intcon(1)));
8349   Node* bool_instof  = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
8350 
8351   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
8352 
8353   // for encryption, we are done
8354   if (!decrypting)
8355     return instof_false;  // even if it is null
8356 
8357   // for decryption, we need to add a further check to avoid
8358   // taking the intrinsic path when cipher and plain are the same
8359   // see the original java code for why.
8360   RegionNode* region = new RegionNode(3);
8361   region->init_req(1, instof_false);
8362 
8363   Node* cmp_src_dest = _gvn.transform(new CmpPNode(src, dest));
8364   Node* bool_src_dest = _gvn.transform(new BoolNode(cmp_src_dest, BoolTest::eq));
8365   Node* src_dest_conjoint = generate_guard(bool_src_dest, nullptr, PROB_MIN);
8366   region->init_req(2, src_dest_conjoint);
8367 
8368   record_for_igvn(region);
8369   return _gvn.transform(region);
8370 }
8371 
8372 //----------------------------inline_electronicCodeBook_AESCrypt_predicate----------------------------
8373 // Return node representing slow path of predicate check.
8374 // the pseudo code we want to emulate with this predicate is:
8375 // for encryption:
8376 //    if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
8377 // for decryption:
8378 //    if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
8379 //    note cipher==plain is more conservative than the original java code but that's OK
8380 //
8381 Node* LibraryCallKit::inline_electronicCodeBook_AESCrypt_predicate(bool decrypting) {
8382   // The receiver was checked for null already.
8383   Node* objECB = argument(0);
8384 
8385   // Load embeddedCipher field of ElectronicCodeBook object.
8386   Node* embeddedCipherObj = load_field_from_object(objECB, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8387 
8388   // get AESCrypt klass for instanceOf check
8389   // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
8390   // will have same classloader as ElectronicCodeBook object
8391   const TypeInstPtr* tinst = _gvn.type(objECB)->isa_instptr();
8392   assert(tinst != nullptr, "ECBobj is null");
8393   assert(tinst->is_loaded(), "ECBobj is not loaded");
8394 
8395   // we want to do an instanceof comparison against the AESCrypt class
8396   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8397   if (!klass_AESCrypt->is_loaded()) {
8398     // if AESCrypt is not even loaded, we never take the intrinsic fast path
8399     Node* ctrl = control();
8400     set_control(top()); // no regular fast path
8401     return ctrl;
8402   }
8403   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8404 
8405   Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
8406   Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
8407   Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
8408 
8409   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
8410 
8411   // for encryption, we are done
8412   if (!decrypting)
8413     return instof_false;  // even if it is null
8414 
8415   // for decryption, we need to add a further check to avoid
8416   // taking the intrinsic path when cipher and plain are the same
8417   // see the original java code for why.
8418   RegionNode* region = new RegionNode(3);
8419   region->init_req(1, instof_false);
8420   Node* src = argument(1);
8421   Node* dest = argument(4);
8422   Node* cmp_src_dest = _gvn.transform(new CmpPNode(src, dest));
8423   Node* bool_src_dest = _gvn.transform(new BoolNode(cmp_src_dest, BoolTest::eq));
8424   Node* src_dest_conjoint = generate_guard(bool_src_dest, nullptr, PROB_MIN);
8425   region->init_req(2, src_dest_conjoint);
8426 
8427   record_for_igvn(region);
8428   return _gvn.transform(region);
8429 }
8430 
8431 //----------------------------inline_counterMode_AESCrypt_predicate----------------------------
8432 // Return node representing slow path of predicate check.
8433 // the pseudo code we want to emulate with this predicate is:
8434 // for encryption:
8435 //    if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
8436 // for decryption:
8437 //    if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
8438 //    note cipher==plain is more conservative than the original java code but that's OK
8439 //
8440 
8441 Node* LibraryCallKit::inline_counterMode_AESCrypt_predicate() {
8442   // The receiver was checked for null already.
8443   Node* objCTR = argument(0);
8444 
8445   // Load embeddedCipher field of CipherBlockChaining object.
8446   Node* embeddedCipherObj = load_field_from_object(objCTR, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8447 
8448   // get AESCrypt klass for instanceOf check
8449   // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
8450   // will have same classloader as CipherBlockChaining object
8451   const TypeInstPtr* tinst = _gvn.type(objCTR)->isa_instptr();
8452   assert(tinst != nullptr, "CTRobj is null");
8453   assert(tinst->is_loaded(), "CTRobj is not loaded");
8454 
8455   // we want to do an instanceof comparison against the AESCrypt class
8456   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8457   if (!klass_AESCrypt->is_loaded()) {
8458     // if AESCrypt is not even loaded, we never take the intrinsic fast path
8459     Node* ctrl = control();
8460     set_control(top()); // no regular fast path
8461     return ctrl;
8462   }
8463 
8464   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8465   Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
8466   Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
8467   Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
8468   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
8469 
8470   return instof_false; // even if it is null
8471 }
8472 
8473 //------------------------------inline_ghash_processBlocks
8474 bool LibraryCallKit::inline_ghash_processBlocks() {
8475   address stubAddr;
8476   const char *stubName;
8477   assert(UseGHASHIntrinsics, "need GHASH intrinsics support");
8478 
8479   stubAddr = StubRoutines::ghash_processBlocks();
8480   stubName = "ghash_processBlocks";
8481 
8482   Node* data           = argument(0);
8483   Node* offset         = argument(1);
8484   Node* len            = argument(2);
8485   Node* state          = argument(3);
8486   Node* subkeyH        = argument(4);
8487 
8488   state = must_be_not_null(state, true);
8489   subkeyH = must_be_not_null(subkeyH, true);
8490   data = must_be_not_null(data, true);
8491 
8492   Node* state_start  = array_element_address(state, intcon(0), T_LONG);
8493   assert(state_start, "state is null");
8494   Node* subkeyH_start  = array_element_address(subkeyH, intcon(0), T_LONG);
8495   assert(subkeyH_start, "subkeyH is null");
8496   Node* data_start  = array_element_address(data, offset, T_BYTE);
8497   assert(data_start, "data is null");
8498 
8499   Node* ghash = make_runtime_call(RC_LEAF|RC_NO_FP,
8500                                   OptoRuntime::ghash_processBlocks_Type(),
8501                                   stubAddr, stubName, TypePtr::BOTTOM,
8502                                   state_start, subkeyH_start, data_start, len);
8503   return true;
8504 }
8505 
8506 //------------------------------inline_chacha20Block
8507 bool LibraryCallKit::inline_chacha20Block() {
8508   address stubAddr;
8509   const char *stubName;
8510   assert(UseChaCha20Intrinsics, "need ChaCha20 intrinsics support");
8511 
8512   stubAddr = StubRoutines::chacha20Block();
8513   stubName = "chacha20Block";
8514 
8515   Node* state          = argument(0);
8516   Node* result         = argument(1);
8517 
8518   state = must_be_not_null(state, true);
8519   result = must_be_not_null(result, true);
8520 
8521   Node* state_start  = array_element_address(state, intcon(0), T_INT);
8522   assert(state_start, "state is null");
8523   Node* result_start  = array_element_address(result, intcon(0), T_BYTE);
8524   assert(result_start, "result is null");
8525 
8526   Node* cc20Blk = make_runtime_call(RC_LEAF|RC_NO_FP,
8527                                   OptoRuntime::chacha20Block_Type(),
8528                                   stubAddr, stubName, TypePtr::BOTTOM,
8529                                   state_start, result_start);
8530   // return key stream length (int)
8531   Node* retvalue = _gvn.transform(new ProjNode(cc20Blk, TypeFunc::Parms));
8532   set_result(retvalue);
8533   return true;
8534 }
8535 
8536 //------------------------------inline_kyberNtt
8537 bool LibraryCallKit::inline_kyberNtt() {
8538   address stubAddr;
8539   const char *stubName;
8540   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8541   assert(callee()->signature()->size() == 2, "kyberNtt has 2 parameters");
8542 
8543   stubAddr = StubRoutines::kyberNtt();
8544   stubName = "kyberNtt";
8545   if (!stubAddr) return false;
8546 
8547   Node* coeffs          = argument(0);
8548   Node* ntt_zetas        = argument(1);
8549 
8550   coeffs = must_be_not_null(coeffs, true);
8551   ntt_zetas = must_be_not_null(ntt_zetas, true);
8552 
8553   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_SHORT);
8554   assert(coeffs_start, "coeffs is null");
8555   Node* ntt_zetas_start  = array_element_address(ntt_zetas, intcon(0), T_SHORT);
8556   assert(ntt_zetas_start, "ntt_zetas is null");
8557   Node* kyberNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
8558                                   OptoRuntime::kyberNtt_Type(),
8559                                   stubAddr, stubName, TypePtr::BOTTOM,
8560                                   coeffs_start, ntt_zetas_start);
8561   // return an int
8562   Node* retvalue = _gvn.transform(new ProjNode(kyberNtt, TypeFunc::Parms));
8563   set_result(retvalue);
8564   return true;
8565 }
8566 
8567 //------------------------------inline_kyberInverseNtt
8568 bool LibraryCallKit::inline_kyberInverseNtt() {
8569   address stubAddr;
8570   const char *stubName;
8571   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8572   assert(callee()->signature()->size() == 2, "kyberInverseNtt has 2 parameters");
8573 
8574   stubAddr = StubRoutines::kyberInverseNtt();
8575   stubName = "kyberInverseNtt";
8576   if (!stubAddr) return false;
8577 
8578   Node* coeffs          = argument(0);
8579   Node* zetas           = argument(1);
8580 
8581   coeffs = must_be_not_null(coeffs, true);
8582   zetas = must_be_not_null(zetas, true);
8583 
8584   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_SHORT);
8585   assert(coeffs_start, "coeffs is null");
8586   Node* zetas_start  = array_element_address(zetas, intcon(0), T_SHORT);
8587   assert(zetas_start, "inverseNtt_zetas is null");
8588   Node* kyberInverseNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
8589                                   OptoRuntime::kyberInverseNtt_Type(),
8590                                   stubAddr, stubName, TypePtr::BOTTOM,
8591                                   coeffs_start, zetas_start);
8592 
8593   // return an int
8594   Node* retvalue = _gvn.transform(new ProjNode(kyberInverseNtt, TypeFunc::Parms));
8595   set_result(retvalue);
8596   return true;
8597 }
8598 
8599 //------------------------------inline_kyberNttMult
8600 bool LibraryCallKit::inline_kyberNttMult() {
8601   address stubAddr;
8602   const char *stubName;
8603   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8604   assert(callee()->signature()->size() == 4, "kyberNttMult has 4 parameters");
8605 
8606   stubAddr = StubRoutines::kyberNttMult();
8607   stubName = "kyberNttMult";
8608   if (!stubAddr) return false;
8609 
8610   Node* result          = argument(0);
8611   Node* ntta            = argument(1);
8612   Node* nttb            = argument(2);
8613   Node* zetas           = argument(3);
8614 
8615   result = must_be_not_null(result, true);
8616   ntta = must_be_not_null(ntta, true);
8617   nttb = must_be_not_null(nttb, true);
8618   zetas = must_be_not_null(zetas, true);
8619 
8620   Node* result_start  = array_element_address(result, intcon(0), T_SHORT);
8621   assert(result_start, "result is null");
8622   Node* ntta_start  = array_element_address(ntta, intcon(0), T_SHORT);
8623   assert(ntta_start, "ntta is null");
8624   Node* nttb_start  = array_element_address(nttb, intcon(0), T_SHORT);
8625   assert(nttb_start, "nttb is null");
8626   Node* zetas_start  = array_element_address(zetas, intcon(0), T_SHORT);
8627   assert(zetas_start, "nttMult_zetas is null");
8628   Node* kyberNttMult = make_runtime_call(RC_LEAF|RC_NO_FP,
8629                                   OptoRuntime::kyberNttMult_Type(),
8630                                   stubAddr, stubName, TypePtr::BOTTOM,
8631                                   result_start, ntta_start, nttb_start,
8632                                   zetas_start);
8633 
8634   // return an int
8635   Node* retvalue = _gvn.transform(new ProjNode(kyberNttMult, TypeFunc::Parms));
8636   set_result(retvalue);
8637 
8638   return true;
8639 }
8640 
8641 //------------------------------inline_kyberAddPoly_2
8642 bool LibraryCallKit::inline_kyberAddPoly_2() {
8643   address stubAddr;
8644   const char *stubName;
8645   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8646   assert(callee()->signature()->size() == 3, "kyberAddPoly_2 has 3 parameters");
8647 
8648   stubAddr = StubRoutines::kyberAddPoly_2();
8649   stubName = "kyberAddPoly_2";
8650   if (!stubAddr) return false;
8651 
8652   Node* result          = argument(0);
8653   Node* a               = argument(1);
8654   Node* b               = argument(2);
8655 
8656   result = must_be_not_null(result, true);
8657   a = must_be_not_null(a, true);
8658   b = must_be_not_null(b, true);
8659 
8660   Node* result_start  = array_element_address(result, intcon(0), T_SHORT);
8661   assert(result_start, "result is null");
8662   Node* a_start  = array_element_address(a, intcon(0), T_SHORT);
8663   assert(a_start, "a is null");
8664   Node* b_start  = array_element_address(b, intcon(0), T_SHORT);
8665   assert(b_start, "b is null");
8666   Node* kyberAddPoly_2 = make_runtime_call(RC_LEAF|RC_NO_FP,
8667                                   OptoRuntime::kyberAddPoly_2_Type(),
8668                                   stubAddr, stubName, TypePtr::BOTTOM,
8669                                   result_start, a_start, b_start);
8670   // return an int
8671   Node* retvalue = _gvn.transform(new ProjNode(kyberAddPoly_2, TypeFunc::Parms));
8672   set_result(retvalue);
8673   return true;
8674 }
8675 
8676 //------------------------------inline_kyberAddPoly_3
8677 bool LibraryCallKit::inline_kyberAddPoly_3() {
8678   address stubAddr;
8679   const char *stubName;
8680   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8681   assert(callee()->signature()->size() == 4, "kyberAddPoly_3 has 4 parameters");
8682 
8683   stubAddr = StubRoutines::kyberAddPoly_3();
8684   stubName = "kyberAddPoly_3";
8685   if (!stubAddr) return false;
8686 
8687   Node* result          = argument(0);
8688   Node* a               = argument(1);
8689   Node* b               = argument(2);
8690   Node* c               = argument(3);
8691 
8692   result = must_be_not_null(result, true);
8693   a = must_be_not_null(a, true);
8694   b = must_be_not_null(b, true);
8695   c = must_be_not_null(c, true);
8696 
8697   Node* result_start  = array_element_address(result, intcon(0), T_SHORT);
8698   assert(result_start, "result is null");
8699   Node* a_start  = array_element_address(a, intcon(0), T_SHORT);
8700   assert(a_start, "a is null");
8701   Node* b_start  = array_element_address(b, intcon(0), T_SHORT);
8702   assert(b_start, "b is null");
8703   Node* c_start  = array_element_address(c, intcon(0), T_SHORT);
8704   assert(c_start, "c is null");
8705   Node* kyberAddPoly_3 = make_runtime_call(RC_LEAF|RC_NO_FP,
8706                                   OptoRuntime::kyberAddPoly_3_Type(),
8707                                   stubAddr, stubName, TypePtr::BOTTOM,
8708                                   result_start, a_start, b_start, c_start);
8709   // return an int
8710   Node* retvalue = _gvn.transform(new ProjNode(kyberAddPoly_3, TypeFunc::Parms));
8711   set_result(retvalue);
8712   return true;
8713 }
8714 
8715 //------------------------------inline_kyber12To16
8716 bool LibraryCallKit::inline_kyber12To16() {
8717   address stubAddr;
8718   const char *stubName;
8719   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8720   assert(callee()->signature()->size() == 4, "kyber12To16 has 4 parameters");
8721 
8722   stubAddr = StubRoutines::kyber12To16();
8723   stubName = "kyber12To16";
8724   if (!stubAddr) return false;
8725 
8726   Node* condensed       = argument(0);
8727   Node* condensedOffs   = argument(1);
8728   Node* parsed          = argument(2);
8729   Node* parsedLength    = argument(3);
8730 
8731   condensed = must_be_not_null(condensed, true);
8732   parsed = must_be_not_null(parsed, true);
8733 
8734   Node* condensed_start  = array_element_address(condensed, intcon(0), T_BYTE);
8735   assert(condensed_start, "condensed is null");
8736   Node* parsed_start  = array_element_address(parsed, intcon(0), T_SHORT);
8737   assert(parsed_start, "parsed is null");
8738   Node* kyber12To16 = make_runtime_call(RC_LEAF|RC_NO_FP,
8739                                   OptoRuntime::kyber12To16_Type(),
8740                                   stubAddr, stubName, TypePtr::BOTTOM,
8741                                   condensed_start, condensedOffs, parsed_start, parsedLength);
8742   // return an int
8743   Node* retvalue = _gvn.transform(new ProjNode(kyber12To16, TypeFunc::Parms));
8744   set_result(retvalue);
8745   return true;
8746 
8747 }
8748 
8749 //------------------------------inline_kyberBarrettReduce
8750 bool LibraryCallKit::inline_kyberBarrettReduce() {
8751   address stubAddr;
8752   const char *stubName;
8753   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8754   assert(callee()->signature()->size() == 1, "kyberBarrettReduce has 1 parameters");
8755 
8756   stubAddr = StubRoutines::kyberBarrettReduce();
8757   stubName = "kyberBarrettReduce";
8758   if (!stubAddr) return false;
8759 
8760   Node* coeffs          = argument(0);
8761 
8762   coeffs = must_be_not_null(coeffs, true);
8763 
8764   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_SHORT);
8765   assert(coeffs_start, "coeffs is null");
8766   Node* kyberBarrettReduce = make_runtime_call(RC_LEAF|RC_NO_FP,
8767                                   OptoRuntime::kyberBarrettReduce_Type(),
8768                                   stubAddr, stubName, TypePtr::BOTTOM,
8769                                   coeffs_start);
8770   // return an int
8771   Node* retvalue = _gvn.transform(new ProjNode(kyberBarrettReduce, TypeFunc::Parms));
8772   set_result(retvalue);
8773   return true;
8774 }
8775 
8776 //------------------------------inline_dilithiumAlmostNtt
8777 bool LibraryCallKit::inline_dilithiumAlmostNtt() {
8778   address stubAddr;
8779   const char *stubName;
8780   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8781   assert(callee()->signature()->size() == 2, "dilithiumAlmostNtt has 2 parameters");
8782 
8783   stubAddr = StubRoutines::dilithiumAlmostNtt();
8784   stubName = "dilithiumAlmostNtt";
8785   if (!stubAddr) return false;
8786 
8787   Node* coeffs          = argument(0);
8788   Node* ntt_zetas        = argument(1);
8789 
8790   coeffs = must_be_not_null(coeffs, true);
8791   ntt_zetas = must_be_not_null(ntt_zetas, true);
8792 
8793   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_INT);
8794   assert(coeffs_start, "coeffs is null");
8795   Node* ntt_zetas_start  = array_element_address(ntt_zetas, intcon(0), T_INT);
8796   assert(ntt_zetas_start, "ntt_zetas is null");
8797   Node* dilithiumAlmostNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
8798                                   OptoRuntime::dilithiumAlmostNtt_Type(),
8799                                   stubAddr, stubName, TypePtr::BOTTOM,
8800                                   coeffs_start, ntt_zetas_start);
8801   // return an int
8802   Node* retvalue = _gvn.transform(new ProjNode(dilithiumAlmostNtt, TypeFunc::Parms));
8803   set_result(retvalue);
8804   return true;
8805 }
8806 
8807 //------------------------------inline_dilithiumAlmostInverseNtt
8808 bool LibraryCallKit::inline_dilithiumAlmostInverseNtt() {
8809   address stubAddr;
8810   const char *stubName;
8811   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8812   assert(callee()->signature()->size() == 2, "dilithiumAlmostInverseNtt has 2 parameters");
8813 
8814   stubAddr = StubRoutines::dilithiumAlmostInverseNtt();
8815   stubName = "dilithiumAlmostInverseNtt";
8816   if (!stubAddr) return false;
8817 
8818   Node* coeffs          = argument(0);
8819   Node* zetas           = argument(1);
8820 
8821   coeffs = must_be_not_null(coeffs, true);
8822   zetas = must_be_not_null(zetas, true);
8823 
8824   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_INT);
8825   assert(coeffs_start, "coeffs is null");
8826   Node* zetas_start  = array_element_address(zetas, intcon(0), T_INT);
8827   assert(zetas_start, "inverseNtt_zetas is null");
8828   Node* dilithiumAlmostInverseNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
8829                                   OptoRuntime::dilithiumAlmostInverseNtt_Type(),
8830                                   stubAddr, stubName, TypePtr::BOTTOM,
8831                                   coeffs_start, zetas_start);
8832   // return an int
8833   Node* retvalue = _gvn.transform(new ProjNode(dilithiumAlmostInverseNtt, TypeFunc::Parms));
8834   set_result(retvalue);
8835   return true;
8836 }
8837 
8838 //------------------------------inline_dilithiumNttMult
8839 bool LibraryCallKit::inline_dilithiumNttMult() {
8840   address stubAddr;
8841   const char *stubName;
8842   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8843   assert(callee()->signature()->size() == 3, "dilithiumNttMult has 3 parameters");
8844 
8845   stubAddr = StubRoutines::dilithiumNttMult();
8846   stubName = "dilithiumNttMult";
8847   if (!stubAddr) return false;
8848 
8849   Node* result          = argument(0);
8850   Node* ntta            = argument(1);
8851   Node* nttb            = argument(2);
8852   Node* zetas           = argument(3);
8853 
8854   result = must_be_not_null(result, true);
8855   ntta = must_be_not_null(ntta, true);
8856   nttb = must_be_not_null(nttb, true);
8857   zetas = must_be_not_null(zetas, true);
8858 
8859   Node* result_start  = array_element_address(result, intcon(0), T_INT);
8860   assert(result_start, "result is null");
8861   Node* ntta_start  = array_element_address(ntta, intcon(0), T_INT);
8862   assert(ntta_start, "ntta is null");
8863   Node* nttb_start  = array_element_address(nttb, intcon(0), T_INT);
8864   assert(nttb_start, "nttb is null");
8865   Node* dilithiumNttMult = make_runtime_call(RC_LEAF|RC_NO_FP,
8866                                   OptoRuntime::dilithiumNttMult_Type(),
8867                                   stubAddr, stubName, TypePtr::BOTTOM,
8868                                   result_start, ntta_start, nttb_start);
8869 
8870   // return an int
8871   Node* retvalue = _gvn.transform(new ProjNode(dilithiumNttMult, TypeFunc::Parms));
8872   set_result(retvalue);
8873 
8874   return true;
8875 }
8876 
8877 //------------------------------inline_dilithiumMontMulByConstant
8878 bool LibraryCallKit::inline_dilithiumMontMulByConstant() {
8879   address stubAddr;
8880   const char *stubName;
8881   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8882   assert(callee()->signature()->size() == 2, "dilithiumMontMulByConstant has 2 parameters");
8883 
8884   stubAddr = StubRoutines::dilithiumMontMulByConstant();
8885   stubName = "dilithiumMontMulByConstant";
8886   if (!stubAddr) return false;
8887 
8888   Node* coeffs          = argument(0);
8889   Node* constant        = argument(1);
8890 
8891   coeffs = must_be_not_null(coeffs, true);
8892 
8893   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_INT);
8894   assert(coeffs_start, "coeffs is null");
8895   Node* dilithiumMontMulByConstant = make_runtime_call(RC_LEAF|RC_NO_FP,
8896                                   OptoRuntime::dilithiumMontMulByConstant_Type(),
8897                                   stubAddr, stubName, TypePtr::BOTTOM,
8898                                   coeffs_start, constant);
8899 
8900   // return an int
8901   Node* retvalue = _gvn.transform(new ProjNode(dilithiumMontMulByConstant, TypeFunc::Parms));
8902   set_result(retvalue);
8903   return true;
8904 }
8905 
8906 
8907 //------------------------------inline_dilithiumDecomposePoly
8908 bool LibraryCallKit::inline_dilithiumDecomposePoly() {
8909   address stubAddr;
8910   const char *stubName;
8911   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8912   assert(callee()->signature()->size() == 5, "dilithiumDecomposePoly has 5 parameters");
8913 
8914   stubAddr = StubRoutines::dilithiumDecomposePoly();
8915   stubName = "dilithiumDecomposePoly";
8916   if (!stubAddr) return false;
8917 
8918   Node* input          = argument(0);
8919   Node* lowPart        = argument(1);
8920   Node* highPart       = argument(2);
8921   Node* twoGamma2      = argument(3);
8922   Node* multiplier     = argument(4);
8923 
8924   input = must_be_not_null(input, true);
8925   lowPart = must_be_not_null(lowPart, true);
8926   highPart = must_be_not_null(highPart, true);
8927 
8928   Node* input_start  = array_element_address(input, intcon(0), T_INT);
8929   assert(input_start, "input is null");
8930   Node* lowPart_start  = array_element_address(lowPart, intcon(0), T_INT);
8931   assert(lowPart_start, "lowPart is null");
8932   Node* highPart_start  = array_element_address(highPart, intcon(0), T_INT);
8933   assert(highPart_start, "highPart is null");
8934 
8935   Node* dilithiumDecomposePoly = make_runtime_call(RC_LEAF|RC_NO_FP,
8936                                   OptoRuntime::dilithiumDecomposePoly_Type(),
8937                                   stubAddr, stubName, TypePtr::BOTTOM,
8938                                   input_start, lowPart_start, highPart_start,
8939                                   twoGamma2, multiplier);
8940 
8941   // return an int
8942   Node* retvalue = _gvn.transform(new ProjNode(dilithiumDecomposePoly, TypeFunc::Parms));
8943   set_result(retvalue);
8944   return true;
8945 }
8946 
8947 bool LibraryCallKit::inline_base64_encodeBlock() {
8948   address stubAddr;
8949   const char *stubName;
8950   assert(UseBASE64Intrinsics, "need Base64 intrinsics support");
8951   assert(callee()->signature()->size() == 6, "base64_encodeBlock has 6 parameters");
8952   stubAddr = StubRoutines::base64_encodeBlock();
8953   stubName = "encodeBlock";
8954 
8955   if (!stubAddr) return false;
8956   Node* base64obj = argument(0);
8957   Node* src = argument(1);
8958   Node* offset = argument(2);
8959   Node* len = argument(3);
8960   Node* dest = argument(4);
8961   Node* dp = argument(5);
8962   Node* isURL = argument(6);
8963 
8964   src = must_be_not_null(src, true);
8965   dest = must_be_not_null(dest, true);
8966 
8967   Node* src_start = array_element_address(src, intcon(0), T_BYTE);
8968   assert(src_start, "source array is null");
8969   Node* dest_start = array_element_address(dest, intcon(0), T_BYTE);
8970   assert(dest_start, "destination array is null");
8971 
8972   Node* base64 = make_runtime_call(RC_LEAF,
8973                                    OptoRuntime::base64_encodeBlock_Type(),
8974                                    stubAddr, stubName, TypePtr::BOTTOM,
8975                                    src_start, offset, len, dest_start, dp, isURL);
8976   return true;
8977 }
8978 
8979 bool LibraryCallKit::inline_base64_decodeBlock() {
8980   address stubAddr;
8981   const char *stubName;
8982   assert(UseBASE64Intrinsics, "need Base64 intrinsics support");
8983   assert(callee()->signature()->size() == 7, "base64_decodeBlock has 7 parameters");
8984   stubAddr = StubRoutines::base64_decodeBlock();
8985   stubName = "decodeBlock";
8986 
8987   if (!stubAddr) return false;
8988   Node* base64obj = argument(0);
8989   Node* src = argument(1);
8990   Node* src_offset = argument(2);
8991   Node* len = argument(3);
8992   Node* dest = argument(4);
8993   Node* dest_offset = argument(5);
8994   Node* isURL = argument(6);
8995   Node* isMIME = argument(7);
8996 
8997   src = must_be_not_null(src, true);
8998   dest = must_be_not_null(dest, true);
8999 
9000   Node* src_start = array_element_address(src, intcon(0), T_BYTE);
9001   assert(src_start, "source array is null");
9002   Node* dest_start = array_element_address(dest, intcon(0), T_BYTE);
9003   assert(dest_start, "destination array is null");
9004 
9005   Node* call = make_runtime_call(RC_LEAF,
9006                                  OptoRuntime::base64_decodeBlock_Type(),
9007                                  stubAddr, stubName, TypePtr::BOTTOM,
9008                                  src_start, src_offset, len, dest_start, dest_offset, isURL, isMIME);
9009   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
9010   set_result(result);
9011   return true;
9012 }
9013 
9014 bool LibraryCallKit::inline_poly1305_processBlocks() {
9015   address stubAddr;
9016   const char *stubName;
9017   assert(UsePoly1305Intrinsics, "need Poly intrinsics support");
9018   assert(callee()->signature()->size() == 5, "poly1305_processBlocks has %d parameters", callee()->signature()->size());
9019   stubAddr = StubRoutines::poly1305_processBlocks();
9020   stubName = "poly1305_processBlocks";
9021 
9022   if (!stubAddr) return false;
9023   null_check_receiver();  // null-check receiver
9024   if (stopped())  return true;
9025 
9026   Node* input = argument(1);
9027   Node* input_offset = argument(2);
9028   Node* len = argument(3);
9029   Node* alimbs = argument(4);
9030   Node* rlimbs = argument(5);
9031 
9032   input = must_be_not_null(input, true);
9033   alimbs = must_be_not_null(alimbs, true);
9034   rlimbs = must_be_not_null(rlimbs, true);
9035 
9036   Node* input_start = array_element_address(input, input_offset, T_BYTE);
9037   assert(input_start, "input array is null");
9038   Node* acc_start = array_element_address(alimbs, intcon(0), T_LONG);
9039   assert(acc_start, "acc array is null");
9040   Node* r_start = array_element_address(rlimbs, intcon(0), T_LONG);
9041   assert(r_start, "r array is null");
9042 
9043   Node* call = make_runtime_call(RC_LEAF | RC_NO_FP,
9044                                  OptoRuntime::poly1305_processBlocks_Type(),
9045                                  stubAddr, stubName, TypePtr::BOTTOM,
9046                                  input_start, len, acc_start, r_start);
9047   return true;
9048 }
9049 
9050 bool LibraryCallKit::inline_intpoly_montgomeryMult_P256() {
9051   address stubAddr;
9052   const char *stubName;
9053   assert(UseIntPolyIntrinsics, "need intpoly intrinsics support");
9054   assert(callee()->signature()->size() == 3, "intpoly_montgomeryMult_P256 has %d parameters", callee()->signature()->size());
9055   stubAddr = StubRoutines::intpoly_montgomeryMult_P256();
9056   stubName = "intpoly_montgomeryMult_P256";
9057 
9058   if (!stubAddr) return false;
9059   null_check_receiver();  // null-check receiver
9060   if (stopped())  return true;
9061 
9062   Node* a = argument(1);
9063   Node* b = argument(2);
9064   Node* r = argument(3);
9065 
9066   a = must_be_not_null(a, true);
9067   b = must_be_not_null(b, true);
9068   r = must_be_not_null(r, true);
9069 
9070   Node* a_start = array_element_address(a, intcon(0), T_LONG);
9071   assert(a_start, "a array is null");
9072   Node* b_start = array_element_address(b, intcon(0), T_LONG);
9073   assert(b_start, "b array is null");
9074   Node* r_start = array_element_address(r, intcon(0), T_LONG);
9075   assert(r_start, "r array is null");
9076 
9077   Node* call = make_runtime_call(RC_LEAF | RC_NO_FP,
9078                                  OptoRuntime::intpoly_montgomeryMult_P256_Type(),
9079                                  stubAddr, stubName, TypePtr::BOTTOM,
9080                                  a_start, b_start, r_start);
9081   return true;
9082 }
9083 
9084 bool LibraryCallKit::inline_intpoly_assign() {
9085   assert(UseIntPolyIntrinsics, "need intpoly intrinsics support");
9086   assert(callee()->signature()->size() == 3, "intpoly_assign has %d parameters", callee()->signature()->size());
9087   const char *stubName = "intpoly_assign";
9088   address stubAddr = StubRoutines::intpoly_assign();
9089   if (!stubAddr) return false;
9090 
9091   Node* set = argument(0);
9092   Node* a = argument(1);
9093   Node* b = argument(2);
9094   Node* arr_length = load_array_length(a);
9095 
9096   a = must_be_not_null(a, true);
9097   b = must_be_not_null(b, true);
9098 
9099   Node* a_start = array_element_address(a, intcon(0), T_LONG);
9100   assert(a_start, "a array is null");
9101   Node* b_start = array_element_address(b, intcon(0), T_LONG);
9102   assert(b_start, "b array is null");
9103 
9104   Node* call = make_runtime_call(RC_LEAF | RC_NO_FP,
9105                                  OptoRuntime::intpoly_assign_Type(),
9106                                  stubAddr, stubName, TypePtr::BOTTOM,
9107                                  set, a_start, b_start, arr_length);
9108   return true;
9109 }
9110 
9111 //------------------------------inline_digestBase_implCompress-----------------------
9112 //
9113 // Calculate MD5 for single-block byte[] array.
9114 // void com.sun.security.provider.MD5.implCompress(byte[] buf, int ofs)
9115 //
9116 // Calculate SHA (i.e., SHA-1) for single-block byte[] array.
9117 // void com.sun.security.provider.SHA.implCompress(byte[] buf, int ofs)
9118 //
9119 // Calculate SHA2 (i.e., SHA-244 or SHA-256) for single-block byte[] array.
9120 // void com.sun.security.provider.SHA2.implCompress(byte[] buf, int ofs)
9121 //
9122 // Calculate SHA5 (i.e., SHA-384 or SHA-512) for single-block byte[] array.
9123 // void com.sun.security.provider.SHA5.implCompress(byte[] buf, int ofs)
9124 //
9125 // Calculate SHA3 (i.e., SHA3-224 or SHA3-256 or SHA3-384 or SHA3-512) for single-block byte[] array.
9126 // void com.sun.security.provider.SHA3.implCompress(byte[] buf, int ofs)
9127 //
9128 bool LibraryCallKit::inline_digestBase_implCompress(vmIntrinsics::ID id) {
9129   assert(callee()->signature()->size() == 2, "sha_implCompress has 2 parameters");
9130 
9131   Node* digestBase_obj = argument(0);
9132   Node* src            = argument(1); // type oop
9133   Node* ofs            = argument(2); // type int
9134 
9135   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
9136   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
9137     // failed array check
9138     return false;
9139   }
9140   // Figure out the size and type of the elements we will be copying.
9141   BasicType src_elem = src_type->elem()->array_element_basic_type();
9142   if (src_elem != T_BYTE) {
9143     return false;
9144   }
9145   // 'src_start' points to src array + offset
9146   src = must_be_not_null(src, true);
9147   Node* src_start = array_element_address(src, ofs, src_elem);
9148   Node* state = nullptr;
9149   Node* block_size = nullptr;
9150   address stubAddr;
9151   const char *stubName;
9152 
9153   switch(id) {
9154   case vmIntrinsics::_md5_implCompress:
9155     assert(UseMD5Intrinsics, "need MD5 instruction support");
9156     state = get_state_from_digest_object(digestBase_obj, T_INT);
9157     stubAddr = StubRoutines::md5_implCompress();
9158     stubName = "md5_implCompress";
9159     break;
9160   case vmIntrinsics::_sha_implCompress:
9161     assert(UseSHA1Intrinsics, "need SHA1 instruction support");
9162     state = get_state_from_digest_object(digestBase_obj, T_INT);
9163     stubAddr = StubRoutines::sha1_implCompress();
9164     stubName = "sha1_implCompress";
9165     break;
9166   case vmIntrinsics::_sha2_implCompress:
9167     assert(UseSHA256Intrinsics, "need SHA256 instruction support");
9168     state = get_state_from_digest_object(digestBase_obj, T_INT);
9169     stubAddr = StubRoutines::sha256_implCompress();
9170     stubName = "sha256_implCompress";
9171     break;
9172   case vmIntrinsics::_sha5_implCompress:
9173     assert(UseSHA512Intrinsics, "need SHA512 instruction support");
9174     state = get_state_from_digest_object(digestBase_obj, T_LONG);
9175     stubAddr = StubRoutines::sha512_implCompress();
9176     stubName = "sha512_implCompress";
9177     break;
9178   case vmIntrinsics::_sha3_implCompress:
9179     assert(UseSHA3Intrinsics, "need SHA3 instruction support");
9180     state = get_state_from_digest_object(digestBase_obj, T_LONG);
9181     stubAddr = StubRoutines::sha3_implCompress();
9182     stubName = "sha3_implCompress";
9183     block_size = get_block_size_from_digest_object(digestBase_obj);
9184     if (block_size == nullptr) return false;
9185     break;
9186   default:
9187     fatal_unexpected_iid(id);
9188     return false;
9189   }
9190   if (state == nullptr) return false;
9191 
9192   assert(stubAddr != nullptr, "Stub %s is not generated", stubName);
9193   if (stubAddr == nullptr) return false;
9194 
9195   // Call the stub.
9196   Node* call;
9197   if (block_size == nullptr) {
9198     call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::digestBase_implCompress_Type(false),
9199                              stubAddr, stubName, TypePtr::BOTTOM,
9200                              src_start, state);
9201   } else {
9202     call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::digestBase_implCompress_Type(true),
9203                              stubAddr, stubName, TypePtr::BOTTOM,
9204                              src_start, state, block_size);
9205   }
9206 
9207   return true;
9208 }
9209 
9210 //------------------------------inline_double_keccak
9211 bool LibraryCallKit::inline_double_keccak() {
9212   address stubAddr;
9213   const char *stubName;
9214   assert(UseSHA3Intrinsics, "need SHA3 intrinsics support");
9215   assert(callee()->signature()->size() == 2, "double_keccak has 2 parameters");
9216 
9217   stubAddr = StubRoutines::double_keccak();
9218   stubName = "double_keccak";
9219   if (!stubAddr) return false;
9220 
9221   Node* status0        = argument(0);
9222   Node* status1        = argument(1);
9223 
9224   status0 = must_be_not_null(status0, true);
9225   status1 = must_be_not_null(status1, true);
9226 
9227   Node* status0_start  = array_element_address(status0, intcon(0), T_LONG);
9228   assert(status0_start, "status0 is null");
9229   Node* status1_start  = array_element_address(status1, intcon(0), T_LONG);
9230   assert(status1_start, "status1 is null");
9231   Node* double_keccak = make_runtime_call(RC_LEAF|RC_NO_FP,
9232                                   OptoRuntime::double_keccak_Type(),
9233                                   stubAddr, stubName, TypePtr::BOTTOM,
9234                                   status0_start, status1_start);
9235   // return an int
9236   Node* retvalue = _gvn.transform(new ProjNode(double_keccak, TypeFunc::Parms));
9237   set_result(retvalue);
9238   return true;
9239 }
9240 
9241 
9242 //------------------------------inline_digestBase_implCompressMB-----------------------
9243 //
9244 // Calculate MD5/SHA/SHA2/SHA5/SHA3 for multi-block byte[] array.
9245 // int com.sun.security.provider.DigestBase.implCompressMultiBlock(byte[] b, int ofs, int limit)
9246 //
9247 bool LibraryCallKit::inline_digestBase_implCompressMB(int predicate) {
9248   assert(UseMD5Intrinsics || UseSHA1Intrinsics || UseSHA256Intrinsics || UseSHA512Intrinsics || UseSHA3Intrinsics,
9249          "need MD5/SHA1/SHA256/SHA512/SHA3 instruction support");
9250   assert((uint)predicate < 5, "sanity");
9251   assert(callee()->signature()->size() == 3, "digestBase_implCompressMB has 3 parameters");
9252 
9253   Node* digestBase_obj = argument(0); // The receiver was checked for null already.
9254   Node* src            = argument(1); // byte[] array
9255   Node* ofs            = argument(2); // type int
9256   Node* limit          = argument(3); // type int
9257 
9258   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
9259   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
9260     // failed array check
9261     return false;
9262   }
9263   // Figure out the size and type of the elements we will be copying.
9264   BasicType src_elem = src_type->elem()->array_element_basic_type();
9265   if (src_elem != T_BYTE) {
9266     return false;
9267   }
9268   // 'src_start' points to src array + offset
9269   src = must_be_not_null(src, false);
9270   Node* src_start = array_element_address(src, ofs, src_elem);
9271 
9272   const char* klass_digestBase_name = nullptr;
9273   const char* stub_name = nullptr;
9274   address     stub_addr = nullptr;
9275   BasicType elem_type = T_INT;
9276 
9277   switch (predicate) {
9278   case 0:
9279     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_md5_implCompress)) {
9280       klass_digestBase_name = "sun/security/provider/MD5";
9281       stub_name = "md5_implCompressMB";
9282       stub_addr = StubRoutines::md5_implCompressMB();
9283     }
9284     break;
9285   case 1:
9286     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha_implCompress)) {
9287       klass_digestBase_name = "sun/security/provider/SHA";
9288       stub_name = "sha1_implCompressMB";
9289       stub_addr = StubRoutines::sha1_implCompressMB();
9290     }
9291     break;
9292   case 2:
9293     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha2_implCompress)) {
9294       klass_digestBase_name = "sun/security/provider/SHA2";
9295       stub_name = "sha256_implCompressMB";
9296       stub_addr = StubRoutines::sha256_implCompressMB();
9297     }
9298     break;
9299   case 3:
9300     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha5_implCompress)) {
9301       klass_digestBase_name = "sun/security/provider/SHA5";
9302       stub_name = "sha512_implCompressMB";
9303       stub_addr = StubRoutines::sha512_implCompressMB();
9304       elem_type = T_LONG;
9305     }
9306     break;
9307   case 4:
9308     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha3_implCompress)) {
9309       klass_digestBase_name = "sun/security/provider/SHA3";
9310       stub_name = "sha3_implCompressMB";
9311       stub_addr = StubRoutines::sha3_implCompressMB();
9312       elem_type = T_LONG;
9313     }
9314     break;
9315   default:
9316     fatal("unknown DigestBase intrinsic predicate: %d", predicate);
9317   }
9318   if (klass_digestBase_name != nullptr) {
9319     assert(stub_addr != nullptr, "Stub is generated");
9320     if (stub_addr == nullptr) return false;
9321 
9322     // get DigestBase klass to lookup for SHA klass
9323     const TypeInstPtr* tinst = _gvn.type(digestBase_obj)->isa_instptr();
9324     assert(tinst != nullptr, "digestBase_obj is not instance???");
9325     assert(tinst->is_loaded(), "DigestBase is not loaded");
9326 
9327     ciKlass* klass_digestBase = tinst->instance_klass()->find_klass(ciSymbol::make(klass_digestBase_name));
9328     assert(klass_digestBase->is_loaded(), "predicate checks that this class is loaded");
9329     ciInstanceKlass* instklass_digestBase = klass_digestBase->as_instance_klass();
9330     return inline_digestBase_implCompressMB(digestBase_obj, instklass_digestBase, elem_type, stub_addr, stub_name, src_start, ofs, limit);
9331   }
9332   return false;
9333 }
9334 
9335 //------------------------------inline_digestBase_implCompressMB-----------------------
9336 bool LibraryCallKit::inline_digestBase_implCompressMB(Node* digestBase_obj, ciInstanceKlass* instklass_digestBase,
9337                                                       BasicType elem_type, address stubAddr, const char *stubName,
9338                                                       Node* src_start, Node* ofs, Node* limit) {
9339   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_digestBase);
9340   const TypeOopPtr* xtype = aklass->cast_to_exactness(false)->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
9341   Node* digest_obj = new CheckCastPPNode(control(), digestBase_obj, xtype);
9342   digest_obj = _gvn.transform(digest_obj);
9343 
9344   Node* state = get_state_from_digest_object(digest_obj, elem_type);
9345   if (state == nullptr) return false;
9346 
9347   Node* block_size = nullptr;
9348   if (strcmp("sha3_implCompressMB", stubName) == 0) {
9349     block_size = get_block_size_from_digest_object(digest_obj);
9350     if (block_size == nullptr) return false;
9351   }
9352 
9353   // Call the stub.
9354   Node* call;
9355   if (block_size == nullptr) {
9356     call = make_runtime_call(RC_LEAF|RC_NO_FP,
9357                              OptoRuntime::digestBase_implCompressMB_Type(false),
9358                              stubAddr, stubName, TypePtr::BOTTOM,
9359                              src_start, state, ofs, limit);
9360   } else {
9361      call = make_runtime_call(RC_LEAF|RC_NO_FP,
9362                              OptoRuntime::digestBase_implCompressMB_Type(true),
9363                              stubAddr, stubName, TypePtr::BOTTOM,
9364                              src_start, state, block_size, ofs, limit);
9365   }
9366 
9367   // return ofs (int)
9368   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
9369   set_result(result);
9370 
9371   return true;
9372 }
9373 
9374 //------------------------------inline_galoisCounterMode_AESCrypt-----------------------
9375 bool LibraryCallKit::inline_galoisCounterMode_AESCrypt() {
9376   assert(UseAES, "need AES instruction support");
9377   address stubAddr = nullptr;
9378   const char *stubName = nullptr;
9379   stubAddr = StubRoutines::galoisCounterMode_AESCrypt();
9380   stubName = "galoisCounterMode_AESCrypt";
9381 
9382   if (stubAddr == nullptr) return false;
9383 
9384   Node* in      = argument(0);
9385   Node* inOfs   = argument(1);
9386   Node* len     = argument(2);
9387   Node* ct      = argument(3);
9388   Node* ctOfs   = argument(4);
9389   Node* out     = argument(5);
9390   Node* outOfs  = argument(6);
9391   Node* gctr_object = argument(7);
9392   Node* ghash_object = argument(8);
9393 
9394   // (1) in, ct and out are arrays.
9395   const TypeAryPtr* in_type = in->Value(&_gvn)->isa_aryptr();
9396   const TypeAryPtr* ct_type = ct->Value(&_gvn)->isa_aryptr();
9397   const TypeAryPtr* out_type = out->Value(&_gvn)->isa_aryptr();
9398   assert( in_type != nullptr &&  in_type->elem() != Type::BOTTOM &&
9399           ct_type != nullptr &&  ct_type->elem() != Type::BOTTOM &&
9400          out_type != nullptr && out_type->elem() != Type::BOTTOM, "args are strange");
9401 
9402   // checks are the responsibility of the caller
9403   Node* in_start = in;
9404   Node* ct_start = ct;
9405   Node* out_start = out;
9406   if (inOfs != nullptr || ctOfs != nullptr || outOfs != nullptr) {
9407     assert(inOfs != nullptr && ctOfs != nullptr && outOfs != nullptr, "");
9408     in_start = array_element_address(in, inOfs, T_BYTE);
9409     ct_start = array_element_address(ct, ctOfs, T_BYTE);
9410     out_start = array_element_address(out, outOfs, T_BYTE);
9411   }
9412 
9413   // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
9414   // (because of the predicated logic executed earlier).
9415   // so we cast it here safely.
9416   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
9417   Node* embeddedCipherObj = load_field_from_object(gctr_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
9418   Node* counter = load_field_from_object(gctr_object, "counter", "[B");
9419   Node* subkeyHtbl = load_field_from_object(ghash_object, "subkeyHtbl", "[J");
9420   Node* state = load_field_from_object(ghash_object, "state", "[J");
9421 
9422   if (embeddedCipherObj == nullptr || counter == nullptr || subkeyHtbl == nullptr || state == nullptr) {
9423     return false;
9424   }
9425   // cast it to what we know it will be at runtime
9426   const TypeInstPtr* tinst = _gvn.type(gctr_object)->isa_instptr();
9427   assert(tinst != nullptr, "GCTR obj is null");
9428   assert(tinst->is_loaded(), "GCTR obj is not loaded");
9429   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
9430   assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
9431   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
9432   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
9433   const TypeOopPtr* xtype = aklass->as_instance_type();
9434   Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
9435   aescrypt_object = _gvn.transform(aescrypt_object);
9436   // we need to get the start of the aescrypt_object's expanded key array
9437   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object, /* is_decrypt */ false);
9438   if (k_start == nullptr) return false;
9439   // similarly, get the start address of the r vector
9440   Node* cnt_start = array_element_address(counter, intcon(0), T_BYTE);
9441   Node* state_start = array_element_address(state, intcon(0), T_LONG);
9442   Node* subkeyHtbl_start = array_element_address(subkeyHtbl, intcon(0), T_LONG);
9443 
9444 
9445   // Call the stub, passing params
9446   Node* gcmCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
9447                                OptoRuntime::galoisCounterMode_aescrypt_Type(),
9448                                stubAddr, stubName, TypePtr::BOTTOM,
9449                                in_start, len, ct_start, out_start, k_start, state_start, subkeyHtbl_start, cnt_start);
9450 
9451   // return cipher length (int)
9452   Node* retvalue = _gvn.transform(new ProjNode(gcmCrypt, TypeFunc::Parms));
9453   set_result(retvalue);
9454 
9455   return true;
9456 }
9457 
9458 //----------------------------inline_galoisCounterMode_AESCrypt_predicate----------------------------
9459 // Return node representing slow path of predicate check.
9460 // the pseudo code we want to emulate with this predicate is:
9461 // for encryption:
9462 //    if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
9463 // for decryption:
9464 //    if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
9465 //    note cipher==plain is more conservative than the original java code but that's OK
9466 //
9467 
9468 Node* LibraryCallKit::inline_galoisCounterMode_AESCrypt_predicate() {
9469   // The receiver was checked for null already.
9470   Node* objGCTR = argument(7);
9471   // Load embeddedCipher field of GCTR object.
9472   Node* embeddedCipherObj = load_field_from_object(objGCTR, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
9473   assert(embeddedCipherObj != nullptr, "embeddedCipherObj is null");
9474 
9475   // get AESCrypt klass for instanceOf check
9476   // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
9477   // will have same classloader as CipherBlockChaining object
9478   const TypeInstPtr* tinst = _gvn.type(objGCTR)->isa_instptr();
9479   assert(tinst != nullptr, "GCTR obj is null");
9480   assert(tinst->is_loaded(), "GCTR obj is not loaded");
9481 
9482   // we want to do an instanceof comparison against the AESCrypt class
9483   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
9484   if (!klass_AESCrypt->is_loaded()) {
9485     // if AESCrypt is not even loaded, we never take the intrinsic fast path
9486     Node* ctrl = control();
9487     set_control(top()); // no regular fast path
9488     return ctrl;
9489   }
9490 
9491   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
9492   Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
9493   Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
9494   Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
9495   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
9496 
9497   return instof_false; // even if it is null
9498 }
9499 
9500 //------------------------------get_state_from_digest_object-----------------------
9501 Node * LibraryCallKit::get_state_from_digest_object(Node *digest_object, BasicType elem_type) {
9502   const char* state_type;
9503   switch (elem_type) {
9504     case T_BYTE: state_type = "[B"; break;
9505     case T_INT:  state_type = "[I"; break;
9506     case T_LONG: state_type = "[J"; break;
9507     default: ShouldNotReachHere();
9508   }
9509   Node* digest_state = load_field_from_object(digest_object, "state", state_type);
9510   assert (digest_state != nullptr, "wrong version of sun.security.provider.MD5/SHA/SHA2/SHA5/SHA3");
9511   if (digest_state == nullptr) return (Node *) nullptr;
9512 
9513   // now have the array, need to get the start address of the state array
9514   Node* state = array_element_address(digest_state, intcon(0), elem_type);
9515   return state;
9516 }
9517 
9518 //------------------------------get_block_size_from_sha3_object----------------------------------
9519 Node * LibraryCallKit::get_block_size_from_digest_object(Node *digest_object) {
9520   Node* block_size = load_field_from_object(digest_object, "blockSize", "I");
9521   assert (block_size != nullptr, "sanity");
9522   return block_size;
9523 }
9524 
9525 //----------------------------inline_digestBase_implCompressMB_predicate----------------------------
9526 // Return node representing slow path of predicate check.
9527 // the pseudo code we want to emulate with this predicate is:
9528 //    if (digestBaseObj instanceof MD5/SHA/SHA2/SHA5/SHA3) do_intrinsic, else do_javapath
9529 //
9530 Node* LibraryCallKit::inline_digestBase_implCompressMB_predicate(int predicate) {
9531   assert(UseMD5Intrinsics || UseSHA1Intrinsics || UseSHA256Intrinsics || UseSHA512Intrinsics || UseSHA3Intrinsics,
9532          "need MD5/SHA1/SHA256/SHA512/SHA3 instruction support");
9533   assert((uint)predicate < 5, "sanity");
9534 
9535   // The receiver was checked for null already.
9536   Node* digestBaseObj = argument(0);
9537 
9538   // get DigestBase klass for instanceOf check
9539   const TypeInstPtr* tinst = _gvn.type(digestBaseObj)->isa_instptr();
9540   assert(tinst != nullptr, "digestBaseObj is null");
9541   assert(tinst->is_loaded(), "DigestBase is not loaded");
9542 
9543   const char* klass_name = nullptr;
9544   switch (predicate) {
9545   case 0:
9546     if (UseMD5Intrinsics) {
9547       // we want to do an instanceof comparison against the MD5 class
9548       klass_name = "sun/security/provider/MD5";
9549     }
9550     break;
9551   case 1:
9552     if (UseSHA1Intrinsics) {
9553       // we want to do an instanceof comparison against the SHA class
9554       klass_name = "sun/security/provider/SHA";
9555     }
9556     break;
9557   case 2:
9558     if (UseSHA256Intrinsics) {
9559       // we want to do an instanceof comparison against the SHA2 class
9560       klass_name = "sun/security/provider/SHA2";
9561     }
9562     break;
9563   case 3:
9564     if (UseSHA512Intrinsics) {
9565       // we want to do an instanceof comparison against the SHA5 class
9566       klass_name = "sun/security/provider/SHA5";
9567     }
9568     break;
9569   case 4:
9570     if (UseSHA3Intrinsics) {
9571       // we want to do an instanceof comparison against the SHA3 class
9572       klass_name = "sun/security/provider/SHA3";
9573     }
9574     break;
9575   default:
9576     fatal("unknown SHA intrinsic predicate: %d", predicate);
9577   }
9578 
9579   ciKlass* klass = nullptr;
9580   if (klass_name != nullptr) {
9581     klass = tinst->instance_klass()->find_klass(ciSymbol::make(klass_name));
9582   }
9583   if ((klass == nullptr) || !klass->is_loaded()) {
9584     // if none of MD5/SHA/SHA2/SHA5 is loaded, we never take the intrinsic fast path
9585     Node* ctrl = control();
9586     set_control(top()); // no intrinsic path
9587     return ctrl;
9588   }
9589   ciInstanceKlass* instklass = klass->as_instance_klass();
9590 
9591   Node* instof = gen_instanceof(digestBaseObj, makecon(TypeKlassPtr::make(instklass)));
9592   Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
9593   Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
9594   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
9595 
9596   return instof_false;  // even if it is null
9597 }
9598 
9599 //-------------inline_fma-----------------------------------
9600 bool LibraryCallKit::inline_fma(vmIntrinsics::ID id) {
9601   Node *a = nullptr;
9602   Node *b = nullptr;
9603   Node *c = nullptr;
9604   Node* result = nullptr;
9605   switch (id) {
9606   case vmIntrinsics::_fmaD:
9607     assert(callee()->signature()->size() == 6, "fma has 3 parameters of size 2 each.");
9608     // no receiver since it is static method
9609     a = argument(0);
9610     b = argument(2);
9611     c = argument(4);
9612     result = _gvn.transform(new FmaDNode(a, b, c));
9613     break;
9614   case vmIntrinsics::_fmaF:
9615     assert(callee()->signature()->size() == 3, "fma has 3 parameters of size 1 each.");
9616     a = argument(0);
9617     b = argument(1);
9618     c = argument(2);
9619     result = _gvn.transform(new FmaFNode(a, b, c));
9620     break;
9621   default:
9622     fatal_unexpected_iid(id);  break;
9623   }
9624   set_result(result);
9625   return true;
9626 }
9627 
9628 bool LibraryCallKit::inline_character_compare(vmIntrinsics::ID id) {
9629   // argument(0) is receiver
9630   Node* codePoint = argument(1);
9631   Node* n = nullptr;
9632 
9633   switch (id) {
9634     case vmIntrinsics::_isDigit :
9635       n = new DigitNode(control(), codePoint);
9636       break;
9637     case vmIntrinsics::_isLowerCase :
9638       n = new LowerCaseNode(control(), codePoint);
9639       break;
9640     case vmIntrinsics::_isUpperCase :
9641       n = new UpperCaseNode(control(), codePoint);
9642       break;
9643     case vmIntrinsics::_isWhitespace :
9644       n = new WhitespaceNode(control(), codePoint);
9645       break;
9646     default:
9647       fatal_unexpected_iid(id);
9648   }
9649 
9650   set_result(_gvn.transform(n));
9651   return true;
9652 }
9653 
9654 bool LibraryCallKit::inline_profileBoolean() {
9655   Node* counts = argument(1);
9656   const TypeAryPtr* ary = nullptr;
9657   ciArray* aobj = nullptr;
9658   if (counts->is_Con()
9659       && (ary = counts->bottom_type()->isa_aryptr()) != nullptr
9660       && (aobj = ary->const_oop()->as_array()) != nullptr
9661       && (aobj->length() == 2)) {
9662     // Profile is int[2] where [0] and [1] correspond to false and true value occurrences respectively.
9663     jint false_cnt = aobj->element_value(0).as_int();
9664     jint  true_cnt = aobj->element_value(1).as_int();
9665 
9666     if (C->log() != nullptr) {
9667       C->log()->elem("observe source='profileBoolean' false='%d' true='%d'",
9668                      false_cnt, true_cnt);
9669     }
9670 
9671     if (false_cnt + true_cnt == 0) {
9672       // According to profile, never executed.
9673       uncommon_trap_exact(Deoptimization::Reason_intrinsic,
9674                           Deoptimization::Action_reinterpret);
9675       return true;
9676     }
9677 
9678     // result is a boolean (0 or 1) and its profile (false_cnt & true_cnt)
9679     // is a number of each value occurrences.
9680     Node* result = argument(0);
9681     if (false_cnt == 0 || true_cnt == 0) {
9682       // According to profile, one value has been never seen.
9683       int expected_val = (false_cnt == 0) ? 1 : 0;
9684 
9685       Node* cmp  = _gvn.transform(new CmpINode(result, intcon(expected_val)));
9686       Node* test = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
9687 
9688       IfNode* check = create_and_map_if(control(), test, PROB_ALWAYS, COUNT_UNKNOWN);
9689       Node* fast_path = _gvn.transform(new IfTrueNode(check));
9690       Node* slow_path = _gvn.transform(new IfFalseNode(check));
9691 
9692       { // Slow path: uncommon trap for never seen value and then reexecute
9693         // MethodHandleImpl::profileBoolean() to bump the count, so JIT knows
9694         // the value has been seen at least once.
9695         PreserveJVMState pjvms(this);
9696         PreserveReexecuteState preexecs(this);
9697         jvms()->set_should_reexecute(true);
9698 
9699         set_control(slow_path);
9700         set_i_o(i_o());
9701 
9702         uncommon_trap_exact(Deoptimization::Reason_intrinsic,
9703                             Deoptimization::Action_reinterpret);
9704       }
9705       // The guard for never seen value enables sharpening of the result and
9706       // returning a constant. It allows to eliminate branches on the same value
9707       // later on.
9708       set_control(fast_path);
9709       result = intcon(expected_val);
9710     }
9711     // Stop profiling.
9712     // MethodHandleImpl::profileBoolean() has profiling logic in its bytecode.
9713     // By replacing method body with profile data (represented as ProfileBooleanNode
9714     // on IR level) we effectively disable profiling.
9715     // It enables full speed execution once optimized code is generated.
9716     Node* profile = _gvn.transform(new ProfileBooleanNode(result, false_cnt, true_cnt));
9717     C->record_for_igvn(profile);
9718     set_result(profile);
9719     return true;
9720   } else {
9721     // Continue profiling.
9722     // Profile data isn't available at the moment. So, execute method's bytecode version.
9723     // Usually, when GWT LambdaForms are profiled it means that a stand-alone nmethod
9724     // is compiled and counters aren't available since corresponding MethodHandle
9725     // isn't a compile-time constant.
9726     return false;
9727   }
9728 }
9729 
9730 bool LibraryCallKit::inline_isCompileConstant() {
9731   Node* n = argument(0);
9732   set_result(n->is_Con() ? intcon(1) : intcon(0));
9733   return true;
9734 }
9735 
9736 //------------------------------- inline_getObjectSize --------------------------------------
9737 //
9738 // Calculate the runtime size of the object/array.
9739 //   native long sun.instrument.InstrumentationImpl.getObjectSize0(long nativeAgent, Object objectToSize);
9740 //
9741 bool LibraryCallKit::inline_getObjectSize() {
9742   Node* obj = argument(3);
9743   Node* klass_node = load_object_klass(obj);
9744 
9745   jint  layout_con = Klass::_lh_neutral_value;
9746   Node* layout_val = get_layout_helper(klass_node, layout_con);
9747   int   layout_is_con = (layout_val == nullptr);
9748 
9749   if (layout_is_con) {
9750     // Layout helper is constant, can figure out things at compile time.
9751 
9752     if (Klass::layout_helper_is_instance(layout_con)) {
9753       // Instance case:  layout_con contains the size itself.
9754       Node *size = longcon(Klass::layout_helper_size_in_bytes(layout_con));
9755       set_result(size);
9756     } else {
9757       // Array case: size is round(header + element_size*arraylength).
9758       // Since arraylength is different for every array instance, we have to
9759       // compute the whole thing at runtime.
9760 
9761       Node* arr_length = load_array_length(obj);
9762 
9763       int round_mask = MinObjAlignmentInBytes - 1;
9764       int hsize  = Klass::layout_helper_header_size(layout_con);
9765       int eshift = Klass::layout_helper_log2_element_size(layout_con);
9766 
9767       if ((round_mask & ~right_n_bits(eshift)) == 0) {
9768         round_mask = 0;  // strength-reduce it if it goes away completely
9769       }
9770       assert((hsize & right_n_bits(eshift)) == 0, "hsize is pre-rounded");
9771       Node* header_size = intcon(hsize + round_mask);
9772 
9773       Node* lengthx = ConvI2X(arr_length);
9774       Node* headerx = ConvI2X(header_size);
9775 
9776       Node* abody = lengthx;
9777       if (eshift != 0) {
9778         abody = _gvn.transform(new LShiftXNode(lengthx, intcon(eshift)));
9779       }
9780       Node* size = _gvn.transform( new AddXNode(headerx, abody) );
9781       if (round_mask != 0) {
9782         size = _gvn.transform( new AndXNode(size, MakeConX(~round_mask)) );
9783       }
9784       size = ConvX2L(size);
9785       set_result(size);
9786     }
9787   } else {
9788     // Layout helper is not constant, need to test for array-ness at runtime.
9789 
9790     enum { _instance_path = 1, _array_path, PATH_LIMIT };
9791     RegionNode* result_reg = new RegionNode(PATH_LIMIT);
9792     PhiNode* result_val = new PhiNode(result_reg, TypeLong::LONG);
9793     record_for_igvn(result_reg);
9794 
9795     Node* array_ctl = generate_array_guard(klass_node, nullptr, &obj);
9796     if (array_ctl != nullptr) {
9797       // Array case: size is round(header + element_size*arraylength).
9798       // Since arraylength is different for every array instance, we have to
9799       // compute the whole thing at runtime.
9800 
9801       PreserveJVMState pjvms(this);
9802       set_control(array_ctl);
9803       Node* arr_length = load_array_length(obj);
9804 
9805       int round_mask = MinObjAlignmentInBytes - 1;
9806       Node* mask = intcon(round_mask);
9807 
9808       Node* hss = intcon(Klass::_lh_header_size_shift);
9809       Node* hsm = intcon(Klass::_lh_header_size_mask);
9810       Node* header_size = _gvn.transform(new URShiftINode(layout_val, hss));
9811       header_size = _gvn.transform(new AndINode(header_size, hsm));
9812       header_size = _gvn.transform(new AddINode(header_size, mask));
9813 
9814       // There is no need to mask or shift this value.
9815       // The semantics of LShiftINode include an implicit mask to 0x1F.
9816       assert(Klass::_lh_log2_element_size_shift == 0, "use shift in place");
9817       Node* elem_shift = layout_val;
9818 
9819       Node* lengthx = ConvI2X(arr_length);
9820       Node* headerx = ConvI2X(header_size);
9821 
9822       Node* abody = _gvn.transform(new LShiftXNode(lengthx, elem_shift));
9823       Node* size = _gvn.transform(new AddXNode(headerx, abody));
9824       if (round_mask != 0) {
9825         size = _gvn.transform(new AndXNode(size, MakeConX(~round_mask)));
9826       }
9827       size = ConvX2L(size);
9828 
9829       result_reg->init_req(_array_path, control());
9830       result_val->init_req(_array_path, size);
9831     }
9832 
9833     if (!stopped()) {
9834       // Instance case: the layout helper gives us instance size almost directly,
9835       // but we need to mask out the _lh_instance_slow_path_bit.
9836       Node* size = ConvI2X(layout_val);
9837       assert((int) Klass::_lh_instance_slow_path_bit < BytesPerLong, "clear bit");
9838       Node* mask = MakeConX(~(intptr_t) right_n_bits(LogBytesPerLong));
9839       size = _gvn.transform(new AndXNode(size, mask));
9840       size = ConvX2L(size);
9841 
9842       result_reg->init_req(_instance_path, control());
9843       result_val->init_req(_instance_path, size);
9844     }
9845 
9846     set_result(result_reg, result_val);
9847   }
9848 
9849   return true;
9850 }
9851 
9852 //------------------------------- inline_blackhole --------------------------------------
9853 //
9854 // Make sure all arguments to this node are alive.
9855 // This matches methods that were requested to be blackholed through compile commands.
9856 //
9857 bool LibraryCallKit::inline_blackhole() {
9858   assert(callee()->is_static(), "Should have been checked before: only static methods here");
9859   assert(callee()->is_empty(), "Should have been checked before: only empty methods here");
9860   assert(callee()->holder()->is_loaded(), "Should have been checked before: only methods for loaded classes here");
9861 
9862   // Blackhole node pinches only the control, not memory. This allows
9863   // the blackhole to be pinned in the loop that computes blackholed
9864   // values, but have no other side effects, like breaking the optimizations
9865   // across the blackhole.
9866 
9867   Node* bh = _gvn.transform(new BlackholeNode(control()));
9868   set_control(_gvn.transform(new ProjNode(bh, TypeFunc::Control)));
9869 
9870   // Bind call arguments as blackhole arguments to keep them alive
9871   uint nargs = callee()->arg_size();
9872   for (uint i = 0; i < nargs; i++) {
9873     bh->add_req(argument(i));
9874   }
9875 
9876   return true;
9877 }
9878 
9879 Node* LibraryCallKit::unbox_fp16_value(const TypeInstPtr* float16_box_type, ciField* field, Node* box) {
9880   const TypeInstPtr* box_type = _gvn.type(box)->isa_instptr();
9881   if (box_type == nullptr || box_type->instance_klass() != float16_box_type->instance_klass()) {
9882     return nullptr; // box klass is not Float16
9883   }
9884 
9885   // Null check; get notnull casted pointer
9886   Node* null_ctl = top();
9887   Node* not_null_box = null_check_oop(box, &null_ctl, true);
9888   // If not_null_box is dead, only null-path is taken
9889   if (stopped()) {
9890     set_control(null_ctl);
9891     return nullptr;
9892   }
9893   assert(not_null_box->bottom_type()->is_instptr()->maybe_null() == false, "");
9894   const TypePtr* adr_type = C->alias_type(field)->adr_type();
9895   Node* adr = basic_plus_adr(not_null_box, field->offset_in_bytes());
9896   return access_load_at(not_null_box, adr, adr_type, TypeInt::SHORT, T_SHORT, IN_HEAP);
9897 }
9898 
9899 Node* LibraryCallKit::box_fp16_value(const TypeInstPtr* float16_box_type, ciField* field, Node* value) {
9900   PreserveReexecuteState preexecs(this);
9901   jvms()->set_should_reexecute(true);
9902 
9903   const TypeKlassPtr* klass_type = float16_box_type->as_klass_type();
9904   Node* klass_node = makecon(klass_type);
9905   Node* box = new_instance(klass_node);
9906 
9907   Node* value_field = basic_plus_adr(box, field->offset_in_bytes());
9908   const TypePtr* value_adr_type = value_field->bottom_type()->is_ptr();
9909 
9910   Node* field_store = _gvn.transform(access_store_at(box,
9911                                                      value_field,
9912                                                      value_adr_type,
9913                                                      value,
9914                                                      TypeInt::SHORT,
9915                                                      T_SHORT,
9916                                                      IN_HEAP));
9917   set_memory(field_store, value_adr_type);
9918   return box;
9919 }
9920 
9921 bool LibraryCallKit::inline_fp16_operations(vmIntrinsics::ID id, int num_args) {
9922   if (!Matcher::match_rule_supported(Op_ReinterpretS2HF) ||
9923       !Matcher::match_rule_supported(Op_ReinterpretHF2S)) {
9924     return false;
9925   }
9926 
9927   const TypeInstPtr* box_type = _gvn.type(argument(0))->isa_instptr();
9928   if (box_type == nullptr || box_type->const_oop() == nullptr) {
9929     return false;
9930   }
9931 
9932   ciInstanceKlass* float16_klass = box_type->const_oop()->as_instance()->java_lang_Class_klass()->as_instance_klass();
9933   const TypeInstPtr* float16_box_type = TypeInstPtr::make_exact(TypePtr::NotNull, float16_klass);
9934   ciField* field = float16_klass->get_field_by_name(ciSymbols::value_name(),
9935                                                     ciSymbols::short_signature(),
9936                                                     false);
9937   assert(field != nullptr, "");
9938 
9939   // Transformed nodes
9940   Node* fld1 = nullptr;
9941   Node* fld2 = nullptr;
9942   Node* fld3 = nullptr;
9943   switch(num_args) {
9944     case 3:
9945       fld3 = unbox_fp16_value(float16_box_type, field, argument(3));
9946       if (fld3 == nullptr) {
9947         return false;
9948       }
9949       fld3 = _gvn.transform(new ReinterpretS2HFNode(fld3));
9950     // fall-through
9951     case 2:
9952       fld2 = unbox_fp16_value(float16_box_type, field, argument(2));
9953       if (fld2 == nullptr) {
9954         return false;
9955       }
9956       fld2 = _gvn.transform(new ReinterpretS2HFNode(fld2));
9957     // fall-through
9958     case 1:
9959       fld1 = unbox_fp16_value(float16_box_type, field, argument(1));
9960       if (fld1 == nullptr) {
9961         return false;
9962       }
9963       fld1 = _gvn.transform(new ReinterpretS2HFNode(fld1));
9964       break;
9965     default: fatal("Unsupported number of arguments %d", num_args);
9966   }
9967 
9968   Node* result = nullptr;
9969   switch (id) {
9970     // Unary operations
9971     case vmIntrinsics::_sqrt_float16:
9972       result = _gvn.transform(new SqrtHFNode(C, control(), fld1));
9973       break;
9974     // Ternary operations
9975     case vmIntrinsics::_fma_float16:
9976       result = _gvn.transform(new FmaHFNode(fld1, fld2, fld3));
9977       break;
9978     default:
9979       fatal_unexpected_iid(id);
9980       break;
9981   }
9982   result = _gvn.transform(new ReinterpretHF2SNode(result));
9983   set_result(box_fp16_value(float16_box_type, field, result));
9984   return true;
9985 }
9986