1 /*
   2  * Copyright (c) 1999, 2026, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "asm/macroAssembler.hpp"
  26 #include "ci/ciArrayKlass.hpp"
  27 #include "ci/ciFlatArrayKlass.hpp"
  28 #include "ci/ciInstanceKlass.hpp"
  29 #include "ci/ciSymbols.hpp"
  30 #include "ci/ciUtilities.inline.hpp"
  31 #include "classfile/vmIntrinsics.hpp"
  32 #include "compiler/compileBroker.hpp"
  33 #include "compiler/compileLog.hpp"
  34 #include "gc/shared/barrierSet.hpp"
  35 #include "gc/shared/c2/barrierSetC2.hpp"
  36 #include "jfr/support/jfrIntrinsics.hpp"
  37 #include "memory/resourceArea.hpp"
  38 #include "oops/accessDecorators.hpp"
  39 #include "oops/klass.inline.hpp"
  40 #include "oops/layoutKind.hpp"
  41 #include "oops/objArrayKlass.hpp"
  42 #include "opto/addnode.hpp"
  43 #include "opto/arraycopynode.hpp"
  44 #include "opto/c2compiler.hpp"
  45 #include "opto/castnode.hpp"
  46 #include "opto/cfgnode.hpp"
  47 #include "opto/convertnode.hpp"
  48 #include "opto/countbitsnode.hpp"
  49 #include "opto/graphKit.hpp"
  50 #include "opto/idealKit.hpp"
  51 #include "opto/inlinetypenode.hpp"
  52 #include "opto/library_call.hpp"
  53 #include "opto/mathexactnode.hpp"
  54 #include "opto/mulnode.hpp"
  55 #include "opto/narrowptrnode.hpp"
  56 #include "opto/opaquenode.hpp"
  57 #include "opto/opcodes.hpp"
  58 #include "opto/parse.hpp"
  59 #include "opto/rootnode.hpp"
  60 #include "opto/runtime.hpp"
  61 #include "opto/subnode.hpp"
  62 #include "opto/type.hpp"
  63 #include "opto/vectornode.hpp"
  64 #include "prims/jvmtiExport.hpp"
  65 #include "prims/jvmtiThreadState.hpp"
  66 #include "prims/unsafe.hpp"
  67 #include "runtime/globals.hpp"
  68 #include "runtime/jniHandles.inline.hpp"
  69 #include "runtime/mountUnmountDisabler.hpp"
  70 #include "runtime/objectMonitor.hpp"
  71 #include "runtime/sharedRuntime.hpp"
  72 #include "runtime/stubRoutines.hpp"
  73 #include "utilities/globalDefinitions.hpp"
  74 #include "utilities/macros.hpp"
  75 #include "utilities/powerOfTwo.hpp"
  76 
  77 //---------------------------make_vm_intrinsic----------------------------
  78 CallGenerator* Compile::make_vm_intrinsic(ciMethod* m, bool is_virtual) {
  79   vmIntrinsicID id = m->intrinsic_id();
  80   assert(id != vmIntrinsics::_none, "must be a VM intrinsic");
  81 
  82   if (!m->is_loaded()) {
  83     // Do not attempt to inline unloaded methods.
  84     return nullptr;
  85   }
  86 
  87   C2Compiler* compiler = (C2Compiler*)CompileBroker::compiler(CompLevel_full_optimization);
  88   bool is_available = false;
  89 
  90   {
  91     // For calling is_intrinsic_supported and is_intrinsic_disabled_by_flag
  92     // the compiler must transition to '_thread_in_vm' state because both
  93     // methods access VM-internal data.
  94     VM_ENTRY_MARK;
  95     methodHandle mh(THREAD, m->get_Method());
  96     is_available = compiler != nullptr && compiler->is_intrinsic_available(mh, C->directive());
  97     if (is_available && is_virtual) {
  98       is_available = vmIntrinsics::does_virtual_dispatch(id);
  99     }
 100   }
 101 
 102   if (is_available) {
 103     assert(id <= vmIntrinsics::LAST_COMPILER_INLINE, "caller responsibility");
 104     assert(id != vmIntrinsics::_Object_init && id != vmIntrinsics::_invoke, "enum out of order?");
 105     return new LibraryIntrinsic(m, is_virtual,
 106                                 vmIntrinsics::predicates_needed(id),
 107                                 vmIntrinsics::does_virtual_dispatch(id),
 108                                 id);
 109   } else {
 110     return nullptr;
 111   }
 112 }
 113 
 114 JVMState* LibraryIntrinsic::generate(JVMState* jvms) {
 115   LibraryCallKit kit(jvms, this);
 116   Compile* C = kit.C;
 117   int nodes = C->unique();
 118 #ifndef PRODUCT
 119   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
 120     char buf[1000];
 121     const char* str = vmIntrinsics::short_name_as_C_string(intrinsic_id(), buf, sizeof(buf));
 122     tty->print_cr("Intrinsic %s", str);
 123   }
 124 #endif
 125   ciMethod* callee = kit.callee();
 126   const int bci    = kit.bci();
 127 #ifdef ASSERT
 128   Node* ctrl = kit.control();
 129 #endif
 130   // Try to inline the intrinsic.
 131   if (callee->check_intrinsic_candidate() &&
 132       kit.try_to_inline(_last_predicate)) {
 133     const char *inline_msg = is_virtual() ? "(intrinsic, virtual)"
 134                                           : "(intrinsic)";
 135     CompileTask::print_inlining_ul(callee, jvms->depth() - 1, bci, InliningResult::SUCCESS, inline_msg);
 136     C->inline_printer()->record(callee, jvms, InliningResult::SUCCESS, inline_msg);
 137     C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_worked);
 138     if (C->log()) {
 139       C->log()->elem("intrinsic id='%s'%s nodes='%d'",
 140                      vmIntrinsics::name_at(intrinsic_id()),
 141                      (is_virtual() ? " virtual='1'" : ""),
 142                      C->unique() - nodes);
 143     }
 144     // Push the result from the inlined method onto the stack.
 145     kit.push_result();
 146     return kit.transfer_exceptions_into_jvms();
 147   }
 148 
 149   // The intrinsic bailed out
 150   assert(ctrl == kit.control(), "Control flow was added although the intrinsic bailed out");
 151   assert(jvms->map() == kit.map(), "Out of sync JVM state");
 152   if (jvms->has_method()) {
 153     // Not a root compile.
 154     const char* msg;
 155     if (callee->intrinsic_candidate()) {
 156       msg = is_virtual() ? "failed to inline (intrinsic, virtual)" : "failed to inline (intrinsic)";
 157     } else {
 158       msg = is_virtual() ? "failed to inline (intrinsic, virtual), method not annotated"
 159                          : "failed to inline (intrinsic), method not annotated";
 160     }
 161     CompileTask::print_inlining_ul(callee, jvms->depth() - 1, bci, InliningResult::FAILURE, msg);
 162     C->inline_printer()->record(callee, jvms, InliningResult::FAILURE, msg);
 163   } else {
 164     // Root compile
 165     ResourceMark rm;
 166     stringStream msg_stream;
 167     msg_stream.print("Did not generate intrinsic %s%s at bci:%d in",
 168                      vmIntrinsics::name_at(intrinsic_id()),
 169                      is_virtual() ? " (virtual)" : "", bci);
 170     const char *msg = msg_stream.freeze();
 171     log_debug(jit, inlining)("%s", msg);
 172     if (C->print_intrinsics() || C->print_inlining()) {
 173       tty->print("%s", msg);
 174     }
 175   }
 176   C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_failed);
 177 
 178   return nullptr;
 179 }
 180 
 181 Node* LibraryIntrinsic::generate_predicate(JVMState* jvms, int predicate) {
 182   LibraryCallKit kit(jvms, this);
 183   Compile* C = kit.C;
 184   int nodes = C->unique();
 185   _last_predicate = predicate;
 186 #ifndef PRODUCT
 187   assert(is_predicated() && predicate < predicates_count(), "sanity");
 188   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
 189     char buf[1000];
 190     const char* str = vmIntrinsics::short_name_as_C_string(intrinsic_id(), buf, sizeof(buf));
 191     tty->print_cr("Predicate for intrinsic %s", str);
 192   }
 193 #endif
 194   ciMethod* callee = kit.callee();
 195   const int bci    = kit.bci();
 196 
 197   Node* slow_ctl = kit.try_to_predicate(predicate);
 198   if (!kit.failing()) {
 199     const char *inline_msg = is_virtual() ? "(intrinsic, virtual, predicate)"
 200                                           : "(intrinsic, predicate)";
 201     CompileTask::print_inlining_ul(callee, jvms->depth() - 1, bci, InliningResult::SUCCESS, inline_msg);
 202     C->inline_printer()->record(callee, jvms, InliningResult::SUCCESS, inline_msg);
 203 
 204     C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_worked);
 205     if (C->log()) {
 206       C->log()->elem("predicate_intrinsic id='%s'%s nodes='%d'",
 207                      vmIntrinsics::name_at(intrinsic_id()),
 208                      (is_virtual() ? " virtual='1'" : ""),
 209                      C->unique() - nodes);
 210     }
 211     return slow_ctl; // Could be null if the check folds.
 212   }
 213 
 214   // The intrinsic bailed out
 215   if (jvms->has_method()) {
 216     // Not a root compile.
 217     const char* msg = "failed to generate predicate for intrinsic";
 218     CompileTask::print_inlining_ul(kit.callee(), jvms->depth() - 1, bci, InliningResult::FAILURE, msg);
 219     C->inline_printer()->record(kit.callee(), jvms, InliningResult::FAILURE, msg);
 220   } else {
 221     // Root compile
 222     ResourceMark rm;
 223     stringStream msg_stream;
 224     msg_stream.print("Did not generate intrinsic %s%s at bci:%d in",
 225                      vmIntrinsics::name_at(intrinsic_id()),
 226                      is_virtual() ? " (virtual)" : "", bci);
 227     const char *msg = msg_stream.freeze();
 228     log_debug(jit, inlining)("%s", msg);
 229     C->inline_printer()->record(kit.callee(), jvms, InliningResult::FAILURE, msg);
 230   }
 231   C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_failed);
 232   return nullptr;
 233 }
 234 
 235 bool LibraryCallKit::try_to_inline(int predicate) {
 236   // Handle symbolic names for otherwise undistinguished boolean switches:
 237   const bool is_store       = true;
 238   const bool is_compress    = true;
 239   const bool is_static      = true;
 240   const bool is_volatile    = true;
 241 
 242   if (!jvms()->has_method()) {
 243     // Root JVMState has a null method.
 244     assert(map()->memory()->Opcode() == Op_Parm, "");
 245     // Insert the memory aliasing node
 246     set_all_memory(reset_memory());
 247   }
 248   assert(merged_memory(), "");
 249 
 250   switch (intrinsic_id()) {
 251   case vmIntrinsics::_hashCode:                 return inline_native_hashcode(intrinsic()->is_virtual(), !is_static);
 252   case vmIntrinsics::_identityHashCode:         return inline_native_hashcode(/*!virtual*/ false,         is_static);
 253   case vmIntrinsics::_getClass:                 return inline_native_getClass();
 254 
 255   case vmIntrinsics::_ceil:
 256   case vmIntrinsics::_floor:
 257   case vmIntrinsics::_rint:
 258   case vmIntrinsics::_dsin:
 259   case vmIntrinsics::_dcos:
 260   case vmIntrinsics::_dtan:
 261   case vmIntrinsics::_dsinh:
 262   case vmIntrinsics::_dtanh:
 263   case vmIntrinsics::_dcbrt:
 264   case vmIntrinsics::_dabs:
 265   case vmIntrinsics::_fabs:
 266   case vmIntrinsics::_iabs:
 267   case vmIntrinsics::_labs:
 268   case vmIntrinsics::_datan2:
 269   case vmIntrinsics::_dsqrt:
 270   case vmIntrinsics::_dsqrt_strict:
 271   case vmIntrinsics::_dexp:
 272   case vmIntrinsics::_dlog:
 273   case vmIntrinsics::_dlog10:
 274   case vmIntrinsics::_dpow:
 275   case vmIntrinsics::_dcopySign:
 276   case vmIntrinsics::_fcopySign:
 277   case vmIntrinsics::_dsignum:
 278   case vmIntrinsics::_roundF:
 279   case vmIntrinsics::_roundD:
 280   case vmIntrinsics::_fsignum:                  return inline_math_native(intrinsic_id());
 281 
 282   case vmIntrinsics::_notify:
 283   case vmIntrinsics::_notifyAll:
 284     return inline_notify(intrinsic_id());
 285 
 286   case vmIntrinsics::_addExactI:                return inline_math_addExactI(false /* add */);
 287   case vmIntrinsics::_addExactL:                return inline_math_addExactL(false /* add */);
 288   case vmIntrinsics::_decrementExactI:          return inline_math_subtractExactI(true /* decrement */);
 289   case vmIntrinsics::_decrementExactL:          return inline_math_subtractExactL(true /* decrement */);
 290   case vmIntrinsics::_incrementExactI:          return inline_math_addExactI(true /* increment */);
 291   case vmIntrinsics::_incrementExactL:          return inline_math_addExactL(true /* increment */);
 292   case vmIntrinsics::_multiplyExactI:           return inline_math_multiplyExactI();
 293   case vmIntrinsics::_multiplyExactL:           return inline_math_multiplyExactL();
 294   case vmIntrinsics::_multiplyHigh:             return inline_math_multiplyHigh();
 295   case vmIntrinsics::_unsignedMultiplyHigh:     return inline_math_unsignedMultiplyHigh();
 296   case vmIntrinsics::_negateExactI:             return inline_math_negateExactI();
 297   case vmIntrinsics::_negateExactL:             return inline_math_negateExactL();
 298   case vmIntrinsics::_subtractExactI:           return inline_math_subtractExactI(false /* subtract */);
 299   case vmIntrinsics::_subtractExactL:           return inline_math_subtractExactL(false /* subtract */);
 300 
 301   case vmIntrinsics::_arraycopy:                return inline_arraycopy();
 302 
 303   case vmIntrinsics::_arraySort:                return inline_array_sort();
 304   case vmIntrinsics::_arrayPartition:           return inline_array_partition();
 305 
 306   case vmIntrinsics::_compareToL:               return inline_string_compareTo(StrIntrinsicNode::LL);
 307   case vmIntrinsics::_compareToU:               return inline_string_compareTo(StrIntrinsicNode::UU);
 308   case vmIntrinsics::_compareToLU:              return inline_string_compareTo(StrIntrinsicNode::LU);
 309   case vmIntrinsics::_compareToUL:              return inline_string_compareTo(StrIntrinsicNode::UL);
 310 
 311   case vmIntrinsics::_indexOfL:                 return inline_string_indexOf(StrIntrinsicNode::LL);
 312   case vmIntrinsics::_indexOfU:                 return inline_string_indexOf(StrIntrinsicNode::UU);
 313   case vmIntrinsics::_indexOfUL:                return inline_string_indexOf(StrIntrinsicNode::UL);
 314   case vmIntrinsics::_indexOfIL:                return inline_string_indexOfI(StrIntrinsicNode::LL);
 315   case vmIntrinsics::_indexOfIU:                return inline_string_indexOfI(StrIntrinsicNode::UU);
 316   case vmIntrinsics::_indexOfIUL:               return inline_string_indexOfI(StrIntrinsicNode::UL);
 317   case vmIntrinsics::_indexOfU_char:            return inline_string_indexOfChar(StrIntrinsicNode::U);
 318   case vmIntrinsics::_indexOfL_char:            return inline_string_indexOfChar(StrIntrinsicNode::L);
 319 
 320   case vmIntrinsics::_equalsL:                  return inline_string_equals(StrIntrinsicNode::LL);
 321 
 322   case vmIntrinsics::_vectorizedHashCode:       return inline_vectorizedHashCode();
 323 
 324   case vmIntrinsics::_toBytesStringU:           return inline_string_toBytesU();
 325   case vmIntrinsics::_getCharsStringU:          return inline_string_getCharsU();
 326   case vmIntrinsics::_getCharStringU:           return inline_string_char_access(!is_store);
 327   case vmIntrinsics::_putCharStringU:           return inline_string_char_access( is_store);
 328 
 329   case vmIntrinsics::_compressStringC:
 330   case vmIntrinsics::_compressStringB:          return inline_string_copy( is_compress);
 331   case vmIntrinsics::_inflateStringC:
 332   case vmIntrinsics::_inflateStringB:           return inline_string_copy(!is_compress);
 333 
 334   case vmIntrinsics::_getReference:             return inline_unsafe_access(!is_store, T_OBJECT,   Relaxed, false);
 335   case vmIntrinsics::_getBoolean:               return inline_unsafe_access(!is_store, T_BOOLEAN,  Relaxed, false);
 336   case vmIntrinsics::_getByte:                  return inline_unsafe_access(!is_store, T_BYTE,     Relaxed, false);
 337   case vmIntrinsics::_getShort:                 return inline_unsafe_access(!is_store, T_SHORT,    Relaxed, false);
 338   case vmIntrinsics::_getChar:                  return inline_unsafe_access(!is_store, T_CHAR,     Relaxed, false);
 339   case vmIntrinsics::_getInt:                   return inline_unsafe_access(!is_store, T_INT,      Relaxed, false);
 340   case vmIntrinsics::_getLong:                  return inline_unsafe_access(!is_store, T_LONG,     Relaxed, false);
 341   case vmIntrinsics::_getFloat:                 return inline_unsafe_access(!is_store, T_FLOAT,    Relaxed, false);
 342   case vmIntrinsics::_getDouble:                return inline_unsafe_access(!is_store, T_DOUBLE,   Relaxed, false);
 343 
 344   case vmIntrinsics::_putReference:             return inline_unsafe_access( is_store, T_OBJECT,   Relaxed, false);
 345   case vmIntrinsics::_putBoolean:               return inline_unsafe_access( is_store, T_BOOLEAN,  Relaxed, false);
 346   case vmIntrinsics::_putByte:                  return inline_unsafe_access( is_store, T_BYTE,     Relaxed, false);
 347   case vmIntrinsics::_putShort:                 return inline_unsafe_access( is_store, T_SHORT,    Relaxed, false);
 348   case vmIntrinsics::_putChar:                  return inline_unsafe_access( is_store, T_CHAR,     Relaxed, false);
 349   case vmIntrinsics::_putInt:                   return inline_unsafe_access( is_store, T_INT,      Relaxed, false);
 350   case vmIntrinsics::_putLong:                  return inline_unsafe_access( is_store, T_LONG,     Relaxed, false);
 351   case vmIntrinsics::_putFloat:                 return inline_unsafe_access( is_store, T_FLOAT,    Relaxed, false);
 352   case vmIntrinsics::_putDouble:                return inline_unsafe_access( is_store, T_DOUBLE,   Relaxed, false);
 353 
 354   case vmIntrinsics::_getReferenceVolatile:     return inline_unsafe_access(!is_store, T_OBJECT,   Volatile, false);
 355   case vmIntrinsics::_getBooleanVolatile:       return inline_unsafe_access(!is_store, T_BOOLEAN,  Volatile, false);
 356   case vmIntrinsics::_getByteVolatile:          return inline_unsafe_access(!is_store, T_BYTE,     Volatile, false);
 357   case vmIntrinsics::_getShortVolatile:         return inline_unsafe_access(!is_store, T_SHORT,    Volatile, false);
 358   case vmIntrinsics::_getCharVolatile:          return inline_unsafe_access(!is_store, T_CHAR,     Volatile, false);
 359   case vmIntrinsics::_getIntVolatile:           return inline_unsafe_access(!is_store, T_INT,      Volatile, false);
 360   case vmIntrinsics::_getLongVolatile:          return inline_unsafe_access(!is_store, T_LONG,     Volatile, false);
 361   case vmIntrinsics::_getFloatVolatile:         return inline_unsafe_access(!is_store, T_FLOAT,    Volatile, false);
 362   case vmIntrinsics::_getDoubleVolatile:        return inline_unsafe_access(!is_store, T_DOUBLE,   Volatile, false);
 363 
 364   case vmIntrinsics::_putReferenceVolatile:     return inline_unsafe_access( is_store, T_OBJECT,   Volatile, false);
 365   case vmIntrinsics::_putBooleanVolatile:       return inline_unsafe_access( is_store, T_BOOLEAN,  Volatile, false);
 366   case vmIntrinsics::_putByteVolatile:          return inline_unsafe_access( is_store, T_BYTE,     Volatile, false);
 367   case vmIntrinsics::_putShortVolatile:         return inline_unsafe_access( is_store, T_SHORT,    Volatile, false);
 368   case vmIntrinsics::_putCharVolatile:          return inline_unsafe_access( is_store, T_CHAR,     Volatile, false);
 369   case vmIntrinsics::_putIntVolatile:           return inline_unsafe_access( is_store, T_INT,      Volatile, false);
 370   case vmIntrinsics::_putLongVolatile:          return inline_unsafe_access( is_store, T_LONG,     Volatile, false);
 371   case vmIntrinsics::_putFloatVolatile:         return inline_unsafe_access( is_store, T_FLOAT,    Volatile, false);
 372   case vmIntrinsics::_putDoubleVolatile:        return inline_unsafe_access( is_store, T_DOUBLE,   Volatile, false);
 373 
 374   case vmIntrinsics::_getShortUnaligned:        return inline_unsafe_access(!is_store, T_SHORT,    Relaxed, true);
 375   case vmIntrinsics::_getCharUnaligned:         return inline_unsafe_access(!is_store, T_CHAR,     Relaxed, true);
 376   case vmIntrinsics::_getIntUnaligned:          return inline_unsafe_access(!is_store, T_INT,      Relaxed, true);
 377   case vmIntrinsics::_getLongUnaligned:         return inline_unsafe_access(!is_store, T_LONG,     Relaxed, true);
 378 
 379   case vmIntrinsics::_putShortUnaligned:        return inline_unsafe_access( is_store, T_SHORT,    Relaxed, true);
 380   case vmIntrinsics::_putCharUnaligned:         return inline_unsafe_access( is_store, T_CHAR,     Relaxed, true);
 381   case vmIntrinsics::_putIntUnaligned:          return inline_unsafe_access( is_store, T_INT,      Relaxed, true);
 382   case vmIntrinsics::_putLongUnaligned:         return inline_unsafe_access( is_store, T_LONG,     Relaxed, true);
 383 
 384   case vmIntrinsics::_getReferenceAcquire:      return inline_unsafe_access(!is_store, T_OBJECT,   Acquire, false);
 385   case vmIntrinsics::_getBooleanAcquire:        return inline_unsafe_access(!is_store, T_BOOLEAN,  Acquire, false);
 386   case vmIntrinsics::_getByteAcquire:           return inline_unsafe_access(!is_store, T_BYTE,     Acquire, false);
 387   case vmIntrinsics::_getShortAcquire:          return inline_unsafe_access(!is_store, T_SHORT,    Acquire, false);
 388   case vmIntrinsics::_getCharAcquire:           return inline_unsafe_access(!is_store, T_CHAR,     Acquire, false);
 389   case vmIntrinsics::_getIntAcquire:            return inline_unsafe_access(!is_store, T_INT,      Acquire, false);
 390   case vmIntrinsics::_getLongAcquire:           return inline_unsafe_access(!is_store, T_LONG,     Acquire, false);
 391   case vmIntrinsics::_getFloatAcquire:          return inline_unsafe_access(!is_store, T_FLOAT,    Acquire, false);
 392   case vmIntrinsics::_getDoubleAcquire:         return inline_unsafe_access(!is_store, T_DOUBLE,   Acquire, false);
 393 
 394   case vmIntrinsics::_putReferenceRelease:      return inline_unsafe_access( is_store, T_OBJECT,   Release, false);
 395   case vmIntrinsics::_putBooleanRelease:        return inline_unsafe_access( is_store, T_BOOLEAN,  Release, false);
 396   case vmIntrinsics::_putByteRelease:           return inline_unsafe_access( is_store, T_BYTE,     Release, false);
 397   case vmIntrinsics::_putShortRelease:          return inline_unsafe_access( is_store, T_SHORT,    Release, false);
 398   case vmIntrinsics::_putCharRelease:           return inline_unsafe_access( is_store, T_CHAR,     Release, false);
 399   case vmIntrinsics::_putIntRelease:            return inline_unsafe_access( is_store, T_INT,      Release, false);
 400   case vmIntrinsics::_putLongRelease:           return inline_unsafe_access( is_store, T_LONG,     Release, false);
 401   case vmIntrinsics::_putFloatRelease:          return inline_unsafe_access( is_store, T_FLOAT,    Release, false);
 402   case vmIntrinsics::_putDoubleRelease:         return inline_unsafe_access( is_store, T_DOUBLE,   Release, false);
 403 
 404   case vmIntrinsics::_getReferenceOpaque:       return inline_unsafe_access(!is_store, T_OBJECT,   Opaque, false);
 405   case vmIntrinsics::_getBooleanOpaque:         return inline_unsafe_access(!is_store, T_BOOLEAN,  Opaque, false);
 406   case vmIntrinsics::_getByteOpaque:            return inline_unsafe_access(!is_store, T_BYTE,     Opaque, false);
 407   case vmIntrinsics::_getShortOpaque:           return inline_unsafe_access(!is_store, T_SHORT,    Opaque, false);
 408   case vmIntrinsics::_getCharOpaque:            return inline_unsafe_access(!is_store, T_CHAR,     Opaque, false);
 409   case vmIntrinsics::_getIntOpaque:             return inline_unsafe_access(!is_store, T_INT,      Opaque, false);
 410   case vmIntrinsics::_getLongOpaque:            return inline_unsafe_access(!is_store, T_LONG,     Opaque, false);
 411   case vmIntrinsics::_getFloatOpaque:           return inline_unsafe_access(!is_store, T_FLOAT,    Opaque, false);
 412   case vmIntrinsics::_getDoubleOpaque:          return inline_unsafe_access(!is_store, T_DOUBLE,   Opaque, false);
 413 
 414   case vmIntrinsics::_putReferenceOpaque:       return inline_unsafe_access( is_store, T_OBJECT,   Opaque, false);
 415   case vmIntrinsics::_putBooleanOpaque:         return inline_unsafe_access( is_store, T_BOOLEAN,  Opaque, false);
 416   case vmIntrinsics::_putByteOpaque:            return inline_unsafe_access( is_store, T_BYTE,     Opaque, false);
 417   case vmIntrinsics::_putShortOpaque:           return inline_unsafe_access( is_store, T_SHORT,    Opaque, false);
 418   case vmIntrinsics::_putCharOpaque:            return inline_unsafe_access( is_store, T_CHAR,     Opaque, false);
 419   case vmIntrinsics::_putIntOpaque:             return inline_unsafe_access( is_store, T_INT,      Opaque, false);
 420   case vmIntrinsics::_putLongOpaque:            return inline_unsafe_access( is_store, T_LONG,     Opaque, false);
 421   case vmIntrinsics::_putFloatOpaque:           return inline_unsafe_access( is_store, T_FLOAT,    Opaque, false);
 422   case vmIntrinsics::_putDoubleOpaque:          return inline_unsafe_access( is_store, T_DOUBLE,   Opaque, false);
 423 
 424   case vmIntrinsics::_getFlatValue:             return inline_unsafe_flat_access(!is_store, Relaxed);
 425   case vmIntrinsics::_putFlatValue:             return inline_unsafe_flat_access( is_store, Relaxed);
 426 
 427   case vmIntrinsics::_compareAndSetReference:   return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap,      Volatile);
 428   case vmIntrinsics::_compareAndSetByte:        return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap,      Volatile);
 429   case vmIntrinsics::_compareAndSetShort:       return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap,      Volatile);
 430   case vmIntrinsics::_compareAndSetInt:         return inline_unsafe_load_store(T_INT,    LS_cmp_swap,      Volatile);
 431   case vmIntrinsics::_compareAndSetLong:        return inline_unsafe_load_store(T_LONG,   LS_cmp_swap,      Volatile);
 432 
 433   case vmIntrinsics::_weakCompareAndSetReferencePlain:     return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Relaxed);
 434   case vmIntrinsics::_weakCompareAndSetReferenceAcquire:   return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Acquire);
 435   case vmIntrinsics::_weakCompareAndSetReferenceRelease:   return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Release);
 436   case vmIntrinsics::_weakCompareAndSetReference:          return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Volatile);
 437   case vmIntrinsics::_weakCompareAndSetBytePlain:          return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap_weak, Relaxed);
 438   case vmIntrinsics::_weakCompareAndSetByteAcquire:        return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap_weak, Acquire);
 439   case vmIntrinsics::_weakCompareAndSetByteRelease:        return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap_weak, Release);
 440   case vmIntrinsics::_weakCompareAndSetByte:               return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap_weak, Volatile);
 441   case vmIntrinsics::_weakCompareAndSetShortPlain:         return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap_weak, Relaxed);
 442   case vmIntrinsics::_weakCompareAndSetShortAcquire:       return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap_weak, Acquire);
 443   case vmIntrinsics::_weakCompareAndSetShortRelease:       return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap_weak, Release);
 444   case vmIntrinsics::_weakCompareAndSetShort:              return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap_weak, Volatile);
 445   case vmIntrinsics::_weakCompareAndSetIntPlain:           return inline_unsafe_load_store(T_INT,    LS_cmp_swap_weak, Relaxed);
 446   case vmIntrinsics::_weakCompareAndSetIntAcquire:         return inline_unsafe_load_store(T_INT,    LS_cmp_swap_weak, Acquire);
 447   case vmIntrinsics::_weakCompareAndSetIntRelease:         return inline_unsafe_load_store(T_INT,    LS_cmp_swap_weak, Release);
 448   case vmIntrinsics::_weakCompareAndSetInt:                return inline_unsafe_load_store(T_INT,    LS_cmp_swap_weak, Volatile);
 449   case vmIntrinsics::_weakCompareAndSetLongPlain:          return inline_unsafe_load_store(T_LONG,   LS_cmp_swap_weak, Relaxed);
 450   case vmIntrinsics::_weakCompareAndSetLongAcquire:        return inline_unsafe_load_store(T_LONG,   LS_cmp_swap_weak, Acquire);
 451   case vmIntrinsics::_weakCompareAndSetLongRelease:        return inline_unsafe_load_store(T_LONG,   LS_cmp_swap_weak, Release);
 452   case vmIntrinsics::_weakCompareAndSetLong:               return inline_unsafe_load_store(T_LONG,   LS_cmp_swap_weak, Volatile);
 453 
 454   case vmIntrinsics::_compareAndExchangeReference:         return inline_unsafe_load_store(T_OBJECT, LS_cmp_exchange,  Volatile);
 455   case vmIntrinsics::_compareAndExchangeReferenceAcquire:  return inline_unsafe_load_store(T_OBJECT, LS_cmp_exchange,  Acquire);
 456   case vmIntrinsics::_compareAndExchangeReferenceRelease:  return inline_unsafe_load_store(T_OBJECT, LS_cmp_exchange,  Release);
 457   case vmIntrinsics::_compareAndExchangeByte:              return inline_unsafe_load_store(T_BYTE,   LS_cmp_exchange,  Volatile);
 458   case vmIntrinsics::_compareAndExchangeByteAcquire:       return inline_unsafe_load_store(T_BYTE,   LS_cmp_exchange,  Acquire);
 459   case vmIntrinsics::_compareAndExchangeByteRelease:       return inline_unsafe_load_store(T_BYTE,   LS_cmp_exchange,  Release);
 460   case vmIntrinsics::_compareAndExchangeShort:             return inline_unsafe_load_store(T_SHORT,  LS_cmp_exchange,  Volatile);
 461   case vmIntrinsics::_compareAndExchangeShortAcquire:      return inline_unsafe_load_store(T_SHORT,  LS_cmp_exchange,  Acquire);
 462   case vmIntrinsics::_compareAndExchangeShortRelease:      return inline_unsafe_load_store(T_SHORT,  LS_cmp_exchange,  Release);
 463   case vmIntrinsics::_compareAndExchangeInt:               return inline_unsafe_load_store(T_INT,    LS_cmp_exchange,  Volatile);
 464   case vmIntrinsics::_compareAndExchangeIntAcquire:        return inline_unsafe_load_store(T_INT,    LS_cmp_exchange,  Acquire);
 465   case vmIntrinsics::_compareAndExchangeIntRelease:        return inline_unsafe_load_store(T_INT,    LS_cmp_exchange,  Release);
 466   case vmIntrinsics::_compareAndExchangeLong:              return inline_unsafe_load_store(T_LONG,   LS_cmp_exchange,  Volatile);
 467   case vmIntrinsics::_compareAndExchangeLongAcquire:       return inline_unsafe_load_store(T_LONG,   LS_cmp_exchange,  Acquire);
 468   case vmIntrinsics::_compareAndExchangeLongRelease:       return inline_unsafe_load_store(T_LONG,   LS_cmp_exchange,  Release);
 469 
 470   case vmIntrinsics::_getAndAddByte:                    return inline_unsafe_load_store(T_BYTE,   LS_get_add,       Volatile);
 471   case vmIntrinsics::_getAndAddShort:                   return inline_unsafe_load_store(T_SHORT,  LS_get_add,       Volatile);
 472   case vmIntrinsics::_getAndAddInt:                     return inline_unsafe_load_store(T_INT,    LS_get_add,       Volatile);
 473   case vmIntrinsics::_getAndAddLong:                    return inline_unsafe_load_store(T_LONG,   LS_get_add,       Volatile);
 474 
 475   case vmIntrinsics::_getAndSetByte:                    return inline_unsafe_load_store(T_BYTE,   LS_get_set,       Volatile);
 476   case vmIntrinsics::_getAndSetShort:                   return inline_unsafe_load_store(T_SHORT,  LS_get_set,       Volatile);
 477   case vmIntrinsics::_getAndSetInt:                     return inline_unsafe_load_store(T_INT,    LS_get_set,       Volatile);
 478   case vmIntrinsics::_getAndSetLong:                    return inline_unsafe_load_store(T_LONG,   LS_get_set,       Volatile);
 479   case vmIntrinsics::_getAndSetReference:               return inline_unsafe_load_store(T_OBJECT, LS_get_set,       Volatile);
 480 
 481   case vmIntrinsics::_loadFence:
 482   case vmIntrinsics::_storeFence:
 483   case vmIntrinsics::_storeStoreFence:
 484   case vmIntrinsics::_fullFence:                return inline_unsafe_fence(intrinsic_id());
 485 
 486   case vmIntrinsics::_arrayInstanceBaseOffset:  return inline_arrayInstanceBaseOffset();
 487   case vmIntrinsics::_arrayInstanceIndexScale:  return inline_arrayInstanceIndexScale();
 488   case vmIntrinsics::_arrayLayout:              return inline_arrayLayout();
 489   case vmIntrinsics::_getFieldMap:              return inline_getFieldMap();
 490 
 491   case vmIntrinsics::_onSpinWait:               return inline_onspinwait();
 492 
 493   case vmIntrinsics::_currentCarrierThread:     return inline_native_currentCarrierThread();
 494   case vmIntrinsics::_currentThread:            return inline_native_currentThread();
 495   case vmIntrinsics::_setCurrentThread:         return inline_native_setCurrentThread();
 496 
 497   case vmIntrinsics::_scopedValueCache:          return inline_native_scopedValueCache();
 498   case vmIntrinsics::_setScopedValueCache:       return inline_native_setScopedValueCache();
 499 
 500   case vmIntrinsics::_Continuation_pin:          return inline_native_Continuation_pinning(false);
 501   case vmIntrinsics::_Continuation_unpin:        return inline_native_Continuation_pinning(true);
 502 
 503   case vmIntrinsics::_vthreadEndFirstTransition:    return inline_native_vthread_end_transition(CAST_FROM_FN_PTR(address, OptoRuntime::vthread_end_first_transition_Java()),
 504                                                                                                 "endFirstTransition", true);
 505   case vmIntrinsics::_vthreadStartFinalTransition:  return inline_native_vthread_start_transition(CAST_FROM_FN_PTR(address, OptoRuntime::vthread_start_final_transition_Java()),
 506                                                                                                   "startFinalTransition", true);
 507   case vmIntrinsics::_vthreadStartTransition:       return inline_native_vthread_start_transition(CAST_FROM_FN_PTR(address, OptoRuntime::vthread_start_transition_Java()),
 508                                                                                                   "startTransition", false);
 509   case vmIntrinsics::_vthreadEndTransition:         return inline_native_vthread_end_transition(CAST_FROM_FN_PTR(address, OptoRuntime::vthread_end_transition_Java()),
 510                                                                                                 "endTransition", false);
 511 #if INCLUDE_JVMTI
 512   case vmIntrinsics::_notifyJvmtiVThreadDisableSuspend: return inline_native_notify_jvmti_sync();
 513 #endif
 514 
 515 #ifdef JFR_HAVE_INTRINSICS
 516   case vmIntrinsics::_counterTime:              return inline_native_time_funcs(CAST_FROM_FN_PTR(address, JfrTime::time_function()), "counterTime");
 517   case vmIntrinsics::_getEventWriter:           return inline_native_getEventWriter();
 518   case vmIntrinsics::_jvm_commit:               return inline_native_jvm_commit();
 519 #endif
 520   case vmIntrinsics::_currentTimeMillis:        return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeMillis), "currentTimeMillis");
 521   case vmIntrinsics::_nanoTime:                 return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeNanos), "nanoTime");
 522   case vmIntrinsics::_writeback0:               return inline_unsafe_writeback0();
 523   case vmIntrinsics::_writebackPreSync0:        return inline_unsafe_writebackSync0(true);
 524   case vmIntrinsics::_writebackPostSync0:       return inline_unsafe_writebackSync0(false);
 525   case vmIntrinsics::_allocateInstance:         return inline_unsafe_allocate();
 526   case vmIntrinsics::_copyMemory:               return inline_unsafe_copyMemory();
 527   case vmIntrinsics::_setMemory:                return inline_unsafe_setMemory();
 528   case vmIntrinsics::_getLength:                return inline_native_getLength();
 529   case vmIntrinsics::_copyOf:                   return inline_array_copyOf(false);
 530   case vmIntrinsics::_copyOfRange:              return inline_array_copyOf(true);
 531   case vmIntrinsics::_equalsB:                  return inline_array_equals(StrIntrinsicNode::LL);
 532   case vmIntrinsics::_equalsC:                  return inline_array_equals(StrIntrinsicNode::UU);
 533   case vmIntrinsics::_Preconditions_checkIndex: return inline_preconditions_checkIndex(T_INT);
 534   case vmIntrinsics::_Preconditions_checkLongIndex: return inline_preconditions_checkIndex(T_LONG);
 535   case vmIntrinsics::_clone:                    return inline_native_clone(intrinsic()->is_virtual());
 536 
 537   case vmIntrinsics::_allocateUninitializedArray: return inline_unsafe_newArray(true);
 538   case vmIntrinsics::_newArray:                   return inline_unsafe_newArray(false);
 539   case vmIntrinsics::_newNullRestrictedNonAtomicArray: return inline_newArray(/* null_free */ true, /* atomic */ false);
 540   case vmIntrinsics::_newNullRestrictedAtomicArray: return inline_newArray(/* null_free */ true, /* atomic */ true);
 541   case vmIntrinsics::_newNullableAtomicArray:     return inline_newArray(/* null_free */ false, /* atomic */ true);
 542   case vmIntrinsics::_isFlatArray:              return inline_getArrayProperties(IsFlat);
 543   case vmIntrinsics::_isNullRestrictedArray:    return inline_getArrayProperties(IsNullRestricted);
 544   case vmIntrinsics::_isAtomicArray:            return inline_getArrayProperties(IsAtomic);
 545 
 546   case vmIntrinsics::_isAssignableFrom:         return inline_native_subtype_check();
 547 
 548   case vmIntrinsics::_isInstance:
 549   case vmIntrinsics::_isHidden:
 550   case vmIntrinsics::_getSuperclass:            return inline_native_Class_query(intrinsic_id());
 551 
 552   case vmIntrinsics::_floatToRawIntBits:
 553   case vmIntrinsics::_floatToIntBits:
 554   case vmIntrinsics::_intBitsToFloat:
 555   case vmIntrinsics::_doubleToRawLongBits:
 556   case vmIntrinsics::_doubleToLongBits:
 557   case vmIntrinsics::_longBitsToDouble:
 558   case vmIntrinsics::_floatToFloat16:
 559   case vmIntrinsics::_float16ToFloat:           return inline_fp_conversions(intrinsic_id());
 560   case vmIntrinsics::_sqrt_float16:             return inline_fp16_operations(intrinsic_id(), 1);
 561   case vmIntrinsics::_fma_float16:              return inline_fp16_operations(intrinsic_id(), 3);
 562   case vmIntrinsics::_floatIsFinite:
 563   case vmIntrinsics::_floatIsInfinite:
 564   case vmIntrinsics::_doubleIsFinite:
 565   case vmIntrinsics::_doubleIsInfinite:         return inline_fp_range_check(intrinsic_id());
 566 
 567   case vmIntrinsics::_numberOfLeadingZeros_i:
 568   case vmIntrinsics::_numberOfLeadingZeros_l:
 569   case vmIntrinsics::_numberOfTrailingZeros_i:
 570   case vmIntrinsics::_numberOfTrailingZeros_l:
 571   case vmIntrinsics::_bitCount_i:
 572   case vmIntrinsics::_bitCount_l:
 573   case vmIntrinsics::_reverse_i:
 574   case vmIntrinsics::_reverse_l:
 575   case vmIntrinsics::_reverseBytes_i:
 576   case vmIntrinsics::_reverseBytes_l:
 577   case vmIntrinsics::_reverseBytes_s:
 578   case vmIntrinsics::_reverseBytes_c:           return inline_number_methods(intrinsic_id());
 579 
 580   case vmIntrinsics::_compress_i:
 581   case vmIntrinsics::_compress_l:
 582   case vmIntrinsics::_expand_i:
 583   case vmIntrinsics::_expand_l:                 return inline_bitshuffle_methods(intrinsic_id());
 584 
 585   case vmIntrinsics::_compareUnsigned_i:
 586   case vmIntrinsics::_compareUnsigned_l:        return inline_compare_unsigned(intrinsic_id());
 587 
 588   case vmIntrinsics::_divideUnsigned_i:
 589   case vmIntrinsics::_divideUnsigned_l:
 590   case vmIntrinsics::_remainderUnsigned_i:
 591   case vmIntrinsics::_remainderUnsigned_l:      return inline_divmod_methods(intrinsic_id());
 592 
 593   case vmIntrinsics::_getCallerClass:           return inline_native_Reflection_getCallerClass();
 594 
 595   case vmIntrinsics::_Reference_get0:           return inline_reference_get0();
 596   case vmIntrinsics::_Reference_refersTo0:      return inline_reference_refersTo0(false);
 597   case vmIntrinsics::_Reference_reachabilityFence: return inline_reference_reachabilityFence();
 598   case vmIntrinsics::_PhantomReference_refersTo0: return inline_reference_refersTo0(true);
 599   case vmIntrinsics::_Reference_clear0:         return inline_reference_clear0(false);
 600   case vmIntrinsics::_PhantomReference_clear0:  return inline_reference_clear0(true);
 601 
 602   case vmIntrinsics::_Class_cast:               return inline_Class_cast();
 603 
 604   case vmIntrinsics::_aescrypt_encryptBlock:
 605   case vmIntrinsics::_aescrypt_decryptBlock:    return inline_aescrypt_Block(intrinsic_id());
 606 
 607   case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
 608   case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
 609     return inline_cipherBlockChaining_AESCrypt(intrinsic_id());
 610 
 611   case vmIntrinsics::_electronicCodeBook_encryptAESCrypt:
 612   case vmIntrinsics::_electronicCodeBook_decryptAESCrypt:
 613     return inline_electronicCodeBook_AESCrypt(intrinsic_id());
 614 
 615   case vmIntrinsics::_counterMode_AESCrypt:
 616     return inline_counterMode_AESCrypt(intrinsic_id());
 617 
 618   case vmIntrinsics::_galoisCounterMode_AESCrypt:
 619     return inline_galoisCounterMode_AESCrypt();
 620 
 621   case vmIntrinsics::_md5_implCompress:
 622   case vmIntrinsics::_sha_implCompress:
 623   case vmIntrinsics::_sha2_implCompress:
 624   case vmIntrinsics::_sha5_implCompress:
 625   case vmIntrinsics::_sha3_implCompress:
 626     return inline_digestBase_implCompress(intrinsic_id());
 627   case vmIntrinsics::_double_keccak:
 628     return inline_double_keccak();
 629 
 630   case vmIntrinsics::_digestBase_implCompressMB:
 631     return inline_digestBase_implCompressMB(predicate);
 632 
 633   case vmIntrinsics::_multiplyToLen:
 634     return inline_multiplyToLen();
 635 
 636   case vmIntrinsics::_squareToLen:
 637     return inline_squareToLen();
 638 
 639   case vmIntrinsics::_mulAdd:
 640     return inline_mulAdd();
 641 
 642   case vmIntrinsics::_montgomeryMultiply:
 643     return inline_montgomeryMultiply();
 644   case vmIntrinsics::_montgomerySquare:
 645     return inline_montgomerySquare();
 646 
 647   case vmIntrinsics::_bigIntegerRightShiftWorker:
 648     return inline_bigIntegerShift(true);
 649   case vmIntrinsics::_bigIntegerLeftShiftWorker:
 650     return inline_bigIntegerShift(false);
 651 
 652   case vmIntrinsics::_vectorizedMismatch:
 653     return inline_vectorizedMismatch();
 654 
 655   case vmIntrinsics::_ghash_processBlocks:
 656     return inline_ghash_processBlocks();
 657   case vmIntrinsics::_chacha20Block:
 658     return inline_chacha20Block();
 659   case vmIntrinsics::_kyberNtt:
 660     return inline_kyberNtt();
 661   case vmIntrinsics::_kyberInverseNtt:
 662     return inline_kyberInverseNtt();
 663   case vmIntrinsics::_kyberNttMult:
 664     return inline_kyberNttMult();
 665   case vmIntrinsics::_kyberAddPoly_2:
 666     return inline_kyberAddPoly_2();
 667   case vmIntrinsics::_kyberAddPoly_3:
 668     return inline_kyberAddPoly_3();
 669   case vmIntrinsics::_kyber12To16:
 670     return inline_kyber12To16();
 671   case vmIntrinsics::_kyberBarrettReduce:
 672     return inline_kyberBarrettReduce();
 673   case vmIntrinsics::_dilithiumAlmostNtt:
 674     return inline_dilithiumAlmostNtt();
 675   case vmIntrinsics::_dilithiumAlmostInverseNtt:
 676     return inline_dilithiumAlmostInverseNtt();
 677   case vmIntrinsics::_dilithiumNttMult:
 678     return inline_dilithiumNttMult();
 679   case vmIntrinsics::_dilithiumMontMulByConstant:
 680     return inline_dilithiumMontMulByConstant();
 681   case vmIntrinsics::_dilithiumDecomposePoly:
 682     return inline_dilithiumDecomposePoly();
 683   case vmIntrinsics::_base64_encodeBlock:
 684     return inline_base64_encodeBlock();
 685   case vmIntrinsics::_base64_decodeBlock:
 686     return inline_base64_decodeBlock();
 687   case vmIntrinsics::_poly1305_processBlocks:
 688     return inline_poly1305_processBlocks();
 689   case vmIntrinsics::_intpoly_montgomeryMult_P256:
 690     return inline_intpoly_montgomeryMult_P256();
 691   case vmIntrinsics::_intpoly_assign:
 692     return inline_intpoly_assign();
 693   case vmIntrinsics::_encodeISOArray:
 694   case vmIntrinsics::_encodeByteISOArray:
 695     return inline_encodeISOArray(false);
 696   case vmIntrinsics::_encodeAsciiArray:
 697     return inline_encodeISOArray(true);
 698 
 699   case vmIntrinsics::_updateCRC32:
 700     return inline_updateCRC32();
 701   case vmIntrinsics::_updateBytesCRC32:
 702     return inline_updateBytesCRC32();
 703   case vmIntrinsics::_updateByteBufferCRC32:
 704     return inline_updateByteBufferCRC32();
 705 
 706   case vmIntrinsics::_updateBytesCRC32C:
 707     return inline_updateBytesCRC32C();
 708   case vmIntrinsics::_updateDirectByteBufferCRC32C:
 709     return inline_updateDirectByteBufferCRC32C();
 710 
 711   case vmIntrinsics::_updateBytesAdler32:
 712     return inline_updateBytesAdler32();
 713   case vmIntrinsics::_updateByteBufferAdler32:
 714     return inline_updateByteBufferAdler32();
 715 
 716   case vmIntrinsics::_profileBoolean:
 717     return inline_profileBoolean();
 718   case vmIntrinsics::_isCompileConstant:
 719     return inline_isCompileConstant();
 720 
 721   case vmIntrinsics::_countPositives:
 722     return inline_countPositives();
 723 
 724   case vmIntrinsics::_fmaD:
 725   case vmIntrinsics::_fmaF:
 726     return inline_fma(intrinsic_id());
 727 
 728   case vmIntrinsics::_isDigit:
 729   case vmIntrinsics::_isLowerCase:
 730   case vmIntrinsics::_isUpperCase:
 731   case vmIntrinsics::_isWhitespace:
 732     return inline_character_compare(intrinsic_id());
 733 
 734   case vmIntrinsics::_min:
 735   case vmIntrinsics::_max:
 736   case vmIntrinsics::_min_strict:
 737   case vmIntrinsics::_max_strict:
 738   case vmIntrinsics::_minL:
 739   case vmIntrinsics::_maxL:
 740   case vmIntrinsics::_minF:
 741   case vmIntrinsics::_maxF:
 742   case vmIntrinsics::_minD:
 743   case vmIntrinsics::_maxD:
 744   case vmIntrinsics::_minF_strict:
 745   case vmIntrinsics::_maxF_strict:
 746   case vmIntrinsics::_minD_strict:
 747   case vmIntrinsics::_maxD_strict:
 748     return inline_min_max(intrinsic_id());
 749 
 750   case vmIntrinsics::_VectorUnaryOp:
 751     return inline_vector_nary_operation(1);
 752   case vmIntrinsics::_VectorBinaryOp:
 753     return inline_vector_nary_operation(2);
 754   case vmIntrinsics::_VectorUnaryLibOp:
 755     return inline_vector_call(1);
 756   case vmIntrinsics::_VectorBinaryLibOp:
 757     return inline_vector_call(2);
 758   case vmIntrinsics::_VectorTernaryOp:
 759     return inline_vector_nary_operation(3);
 760   case vmIntrinsics::_VectorFromBitsCoerced:
 761     return inline_vector_frombits_coerced();
 762   case vmIntrinsics::_VectorMaskOp:
 763     return inline_vector_mask_operation();
 764   case vmIntrinsics::_VectorLoadOp:
 765     return inline_vector_mem_operation(/*is_store=*/false);
 766   case vmIntrinsics::_VectorLoadMaskedOp:
 767     return inline_vector_mem_masked_operation(/*is_store*/false);
 768   case vmIntrinsics::_VectorStoreOp:
 769     return inline_vector_mem_operation(/*is_store=*/true);
 770   case vmIntrinsics::_VectorStoreMaskedOp:
 771     return inline_vector_mem_masked_operation(/*is_store=*/true);
 772   case vmIntrinsics::_VectorGatherOp:
 773     return inline_vector_gather_scatter(/*is_scatter*/ false);
 774   case vmIntrinsics::_VectorScatterOp:
 775     return inline_vector_gather_scatter(/*is_scatter*/ true);
 776   case vmIntrinsics::_VectorReductionCoerced:
 777     return inline_vector_reduction();
 778   case vmIntrinsics::_VectorTest:
 779     return inline_vector_test();
 780   case vmIntrinsics::_VectorBlend:
 781     return inline_vector_blend();
 782   case vmIntrinsics::_VectorRearrange:
 783     return inline_vector_rearrange();
 784   case vmIntrinsics::_VectorSelectFrom:
 785     return inline_vector_select_from();
 786   case vmIntrinsics::_VectorCompare:
 787     return inline_vector_compare();
 788   case vmIntrinsics::_VectorBroadcastInt:
 789     return inline_vector_broadcast_int();
 790   case vmIntrinsics::_VectorConvert:
 791     return inline_vector_convert();
 792   case vmIntrinsics::_VectorInsert:
 793     return inline_vector_insert();
 794   case vmIntrinsics::_VectorExtract:
 795     return inline_vector_extract();
 796   case vmIntrinsics::_VectorCompressExpand:
 797     return inline_vector_compress_expand();
 798   case vmIntrinsics::_VectorSelectFromTwoVectorOp:
 799     return inline_vector_select_from_two_vectors();
 800   case vmIntrinsics::_IndexVector:
 801     return inline_index_vector();
 802   case vmIntrinsics::_IndexPartiallyInUpperRange:
 803     return inline_index_partially_in_upper_range();
 804 
 805   case vmIntrinsics::_getObjectSize:
 806     return inline_getObjectSize();
 807 
 808   case vmIntrinsics::_blackhole:
 809     return inline_blackhole();
 810 
 811   default:
 812     // If you get here, it may be that someone has added a new intrinsic
 813     // to the list in vmIntrinsics.hpp without implementing it here.
 814 #ifndef PRODUCT
 815     if ((PrintMiscellaneous && (Verbose || WizardMode)) || PrintOpto) {
 816       tty->print_cr("*** Warning: Unimplemented intrinsic %s(%d)",
 817                     vmIntrinsics::name_at(intrinsic_id()), vmIntrinsics::as_int(intrinsic_id()));
 818     }
 819 #endif
 820     return false;
 821   }
 822 }
 823 
 824 Node* LibraryCallKit::try_to_predicate(int predicate) {
 825   if (!jvms()->has_method()) {
 826     // Root JVMState has a null method.
 827     assert(map()->memory()->Opcode() == Op_Parm, "");
 828     // Insert the memory aliasing node
 829     set_all_memory(reset_memory());
 830   }
 831   assert(merged_memory(), "");
 832 
 833   switch (intrinsic_id()) {
 834   case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
 835     return inline_cipherBlockChaining_AESCrypt_predicate(false);
 836   case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
 837     return inline_cipherBlockChaining_AESCrypt_predicate(true);
 838   case vmIntrinsics::_electronicCodeBook_encryptAESCrypt:
 839     return inline_electronicCodeBook_AESCrypt_predicate(false);
 840   case vmIntrinsics::_electronicCodeBook_decryptAESCrypt:
 841     return inline_electronicCodeBook_AESCrypt_predicate(true);
 842   case vmIntrinsics::_counterMode_AESCrypt:
 843     return inline_counterMode_AESCrypt_predicate();
 844   case vmIntrinsics::_digestBase_implCompressMB:
 845     return inline_digestBase_implCompressMB_predicate(predicate);
 846   case vmIntrinsics::_galoisCounterMode_AESCrypt:
 847     return inline_galoisCounterMode_AESCrypt_predicate();
 848 
 849   default:
 850     // If you get here, it may be that someone has added a new intrinsic
 851     // to the list in vmIntrinsics.hpp without implementing it here.
 852 #ifndef PRODUCT
 853     if ((PrintMiscellaneous && (Verbose || WizardMode)) || PrintOpto) {
 854       tty->print_cr("*** Warning: Unimplemented predicate for intrinsic %s(%d)",
 855                     vmIntrinsics::name_at(intrinsic_id()), vmIntrinsics::as_int(intrinsic_id()));
 856     }
 857 #endif
 858     Node* slow_ctl = control();
 859     set_control(top()); // No fast path intrinsic
 860     return slow_ctl;
 861   }
 862 }
 863 
 864 //------------------------------set_result-------------------------------
 865 // Helper function for finishing intrinsics.
 866 void LibraryCallKit::set_result(RegionNode* region, PhiNode* value) {
 867   record_for_igvn(region);
 868   set_control(_gvn.transform(region));
 869   set_result( _gvn.transform(value));
 870   assert(value->type()->basic_type() == result()->bottom_type()->basic_type(), "sanity");
 871 }
 872 
 873 RegionNode* LibraryCallKit::create_bailout() {
 874   RegionNode* bailout = new RegionNode(1);
 875   record_for_igvn(bailout);
 876   return bailout;
 877 }
 878 
 879 bool LibraryCallKit::check_bailout(RegionNode* bailout) {
 880   if (bailout->req() > 1) {
 881     bailout = _gvn.transform(bailout)->as_Region();
 882     Node* frame = _gvn.transform(new ParmNode(C->start(), TypeFunc::FramePtr));
 883     Node* halt = _gvn.transform(new HaltNode(bailout, frame, "unexpected guard failure in intrinsic"));
 884     C->root()->add_req(halt);
 885   }
 886   return stopped();
 887 }
 888 
 889 //------------------------------generate_guard---------------------------
 890 // Helper function for generating guarded fast-slow graph structures.
 891 // The given 'test', if true, guards a slow path.  If the test fails
 892 // then a fast path can be taken.  (We generally hope it fails.)
 893 // In all cases, GraphKit::control() is updated to the fast path.
 894 // The returned value represents the control for the slow path.
 895 // The return value is never 'top'; it is either a valid control
 896 // or null if it is obvious that the slow path can never be taken.
 897 // Also, if region and the slow control are not null, the slow edge
 898 // is appended to the region.
 899 Node* LibraryCallKit::generate_guard(Node* test, RegionNode* region, float true_prob) {
 900   if (stopped()) {
 901     // Already short circuited.
 902     return nullptr;
 903   }
 904 
 905   // Build an if node and its projections.
 906   // If test is true we take the slow path, which we assume is uncommon.
 907   if (_gvn.type(test) == TypeInt::ZERO) {
 908     // The slow branch is never taken.  No need to build this guard.
 909     return nullptr;
 910   }
 911 
 912   IfNode* iff = create_and_map_if(control(), test, true_prob, COUNT_UNKNOWN);
 913 
 914   Node* if_slow = _gvn.transform(new IfTrueNode(iff));
 915   if (if_slow == top()) {
 916     // The slow branch is never taken.  No need to build this guard.
 917     return nullptr;
 918   }
 919 
 920   if (region != nullptr)
 921     region->add_req(if_slow);
 922 
 923   Node* if_fast = _gvn.transform(new IfFalseNode(iff));
 924   set_control(if_fast);
 925 
 926   return if_slow;
 927 }
 928 
 929 inline Node* LibraryCallKit::generate_slow_guard(Node* test, RegionNode* region) {
 930   return generate_guard(test, region, PROB_UNLIKELY_MAG(3));
 931 }
 932 inline Node* LibraryCallKit::generate_fair_guard(Node* test, RegionNode* region) {
 933   return generate_guard(test, region, PROB_FAIR);
 934 }
 935 
 936 inline Node* LibraryCallKit::generate_negative_guard(Node* index, RegionNode* region,
 937                                                      Node** pos_index, bool with_opaque) {
 938   if (stopped())
 939     return nullptr;                // already stopped
 940   if (_gvn.type(index)->higher_equal(TypeInt::POS)) // [0,maxint]
 941     return nullptr;                // index is already adequately typed
 942   Node* cmp_lt = _gvn.transform(new CmpINode(index, intcon(0)));
 943   Node* bol_lt = _gvn.transform(new BoolNode(cmp_lt, BoolTest::lt));
 944   if (with_opaque) {
 945     bol_lt = _gvn.transform(new OpaqueConstantBoolNode(C, bol_lt, false));
 946   }
 947   Node* is_neg = generate_guard(bol_lt, region, PROB_MIN);
 948   if (is_neg != nullptr && pos_index != nullptr) {
 949     // Emulate effect of Parse::adjust_map_after_if.
 950     Node* ccast = new CastIINode(control(), index, TypeInt::POS);
 951     (*pos_index) = _gvn.transform(ccast);
 952   }
 953   return is_neg;
 954 }
 955 
 956 // Make sure that 'position' is a valid limit index, in [0..length].
 957 // There are two equivalent plans for checking this:
 958 //   A. (offset + copyLength)  unsigned<=  arrayLength
 959 //   B. offset  <=  (arrayLength - copyLength)
 960 // We require that all of the values above, except for the sum and
 961 // difference, are already known to be non-negative.
 962 // Plan A is robust in the face of overflow, if offset and copyLength
 963 // are both hugely positive.
 964 //
 965 // Plan B is less direct and intuitive, but it does not overflow at
 966 // all, since the difference of two non-negatives is always
 967 // representable.  Whenever Java methods must perform the equivalent
 968 // check they generally use Plan B instead of Plan A.
 969 // For the moment we use Plan A.
 970 inline Node* LibraryCallKit::generate_limit_guard(Node* offset,
 971                                                   Node* subseq_length,
 972                                                   Node* array_length,
 973                                                   RegionNode* region,
 974                                                   bool with_opaque) {
 975   if (stopped())
 976     return nullptr;                // already stopped
 977   bool zero_offset = _gvn.type(offset) == TypeInt::ZERO;
 978   if (zero_offset && subseq_length->eqv_uncast(array_length))
 979     return nullptr;                // common case of whole-array copy
 980   Node* last = subseq_length;
 981   if (!zero_offset)             // last += offset
 982     last = _gvn.transform(new AddINode(last, offset));
 983   Node* cmp_lt = _gvn.transform(new CmpUNode(array_length, last));
 984   Node* bol_lt = _gvn.transform(new BoolNode(cmp_lt, BoolTest::lt));
 985   if (with_opaque) {
 986     bol_lt = _gvn.transform(new OpaqueConstantBoolNode(C, bol_lt, false));
 987   }
 988   Node* is_over = generate_guard(bol_lt, region, PROB_MIN);
 989   return is_over;
 990 }
 991 
 992 // Emit range checks for the given String.value byte array
 993 void LibraryCallKit::generate_string_range_check(Node* array,
 994                                                  Node* offset,
 995                                                  Node* count,
 996                                                  bool char_count,
 997                                                  RegionNode* region) {
 998   if (stopped()) {
 999     return; // already stopped
1000   }
1001   if (char_count) {
1002     // Convert char count to byte count
1003     count = _gvn.transform(new LShiftINode(count, intcon(1)));
1004   }
1005   // Offset and count must not be negative
1006   generate_negative_guard(offset, region, nullptr, true);
1007   generate_negative_guard(count, region, nullptr, true);
1008   // Offset + count must not exceed length of array
1009   generate_limit_guard(offset, count, load_array_length(array), region, true);
1010 }
1011 
1012 Node* LibraryCallKit::current_thread_helper(Node*& tls_output, ByteSize handle_offset,
1013                                             bool is_immutable) {
1014   ciKlass* thread_klass = env()->Thread_klass();
1015   const Type* thread_type
1016     = TypeOopPtr::make_from_klass(thread_klass)->cast_to_ptr_type(TypePtr::NotNull);
1017 
1018   Node* thread = _gvn.transform(new ThreadLocalNode());
1019   Node* p = off_heap_plus_addr(thread, in_bytes(handle_offset));
1020   tls_output = thread;
1021 
1022   Node* thread_obj_handle
1023     = (is_immutable
1024       ? LoadNode::make(_gvn, nullptr, immutable_memory(), p, p->bottom_type()->is_ptr(),
1025         TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered)
1026       : make_load(nullptr, p, p->bottom_type()->is_ptr(), T_ADDRESS, MemNode::unordered));
1027   thread_obj_handle = _gvn.transform(thread_obj_handle);
1028 
1029   DecoratorSet decorators = IN_NATIVE;
1030   if (is_immutable) {
1031     decorators |= C2_IMMUTABLE_MEMORY;
1032   }
1033   return access_load(thread_obj_handle, thread_type, T_OBJECT, decorators);
1034 }
1035 
1036 //--------------------------generate_current_thread--------------------
1037 Node* LibraryCallKit::generate_current_thread(Node* &tls_output) {
1038   return current_thread_helper(tls_output, JavaThread::threadObj_offset(),
1039                                /*is_immutable*/false);
1040 }
1041 
1042 //--------------------------generate_virtual_thread--------------------
1043 Node* LibraryCallKit::generate_virtual_thread(Node* tls_output) {
1044   return current_thread_helper(tls_output, JavaThread::vthread_offset(),
1045                                !C->method()->changes_current_thread());
1046 }
1047 
1048 //------------------------------make_string_method_node------------------------
1049 // Helper method for String intrinsic functions. This version is called with
1050 // str1 and str2 pointing to byte[] nodes containing Latin1 or UTF16 encoded
1051 // characters (depending on 'is_byte'). cnt1 and cnt2 are pointing to Int nodes
1052 // containing the lengths of str1 and str2.
1053 Node* LibraryCallKit::make_string_method_node(int opcode, Node* str1_start, Node* cnt1, Node* str2_start, Node* cnt2, StrIntrinsicNode::ArgEnc ae) {
1054   Node* result = nullptr;
1055   switch (opcode) {
1056   case Op_StrIndexOf:
1057     result = new StrIndexOfNode(control(), memory(TypeAryPtr::BYTES),
1058                                 str1_start, cnt1, str2_start, cnt2, ae);
1059     break;
1060   case Op_StrComp:
1061     result = new StrCompNode(control(), memory(TypeAryPtr::BYTES),
1062                              str1_start, cnt1, str2_start, cnt2, ae);
1063     break;
1064   case Op_StrEquals:
1065     // We already know that cnt1 == cnt2 here (checked in 'inline_string_equals').
1066     // Use the constant length if there is one because optimized match rule may exist.
1067     result = new StrEqualsNode(control(), memory(TypeAryPtr::BYTES),
1068                                str1_start, str2_start, cnt2->is_Con() ? cnt2 : cnt1, ae);
1069     break;
1070   default:
1071     ShouldNotReachHere();
1072     return nullptr;
1073   }
1074 
1075   // All these intrinsics have checks.
1076   C->set_has_split_ifs(true); // Has chance for split-if optimization
1077   clear_upper_avx();
1078 
1079   return _gvn.transform(result);
1080 }
1081 
1082 //------------------------------inline_string_compareTo------------------------
1083 bool LibraryCallKit::inline_string_compareTo(StrIntrinsicNode::ArgEnc ae) {
1084   Node* arg1 = argument(0);
1085   Node* arg2 = argument(1);
1086 
1087   arg1 = must_be_not_null(arg1, true);
1088   arg2 = must_be_not_null(arg2, true);
1089 
1090   // Get start addr and length of first argument
1091   Node* arg1_start  = array_element_address(arg1, intcon(0), T_BYTE);
1092   Node* arg1_cnt    = load_array_length(arg1);
1093 
1094   // Get start addr and length of second argument
1095   Node* arg2_start  = array_element_address(arg2, intcon(0), T_BYTE);
1096   Node* arg2_cnt    = load_array_length(arg2);
1097 
1098   Node* result = make_string_method_node(Op_StrComp, arg1_start, arg1_cnt, arg2_start, arg2_cnt, ae);
1099   set_result(result);
1100   return true;
1101 }
1102 
1103 //------------------------------inline_string_equals------------------------
1104 bool LibraryCallKit::inline_string_equals(StrIntrinsicNode::ArgEnc ae) {
1105   Node* arg1 = argument(0);
1106   Node* arg2 = argument(1);
1107 
1108   // paths (plus control) merge
1109   RegionNode* region = new RegionNode(3);
1110   Node* phi = new PhiNode(region, TypeInt::BOOL);
1111 
1112   if (!stopped()) {
1113 
1114     arg1 = must_be_not_null(arg1, true);
1115     arg2 = must_be_not_null(arg2, true);
1116 
1117     // Get start addr and length of first argument
1118     Node* arg1_start  = array_element_address(arg1, intcon(0), T_BYTE);
1119     Node* arg1_cnt    = load_array_length(arg1);
1120 
1121     // Get start addr and length of second argument
1122     Node* arg2_start  = array_element_address(arg2, intcon(0), T_BYTE);
1123     Node* arg2_cnt    = load_array_length(arg2);
1124 
1125     // Check for arg1_cnt != arg2_cnt
1126     Node* cmp = _gvn.transform(new CmpINode(arg1_cnt, arg2_cnt));
1127     Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::ne));
1128     Node* if_ne = generate_slow_guard(bol, nullptr);
1129     if (if_ne != nullptr) {
1130       phi->init_req(2, intcon(0));
1131       region->init_req(2, if_ne);
1132     }
1133 
1134     // Check for count == 0 is done by assembler code for StrEquals.
1135 
1136     if (!stopped()) {
1137       Node* equals = make_string_method_node(Op_StrEquals, arg1_start, arg1_cnt, arg2_start, arg2_cnt, ae);
1138       phi->init_req(1, equals);
1139       region->init_req(1, control());
1140     }
1141   }
1142 
1143   // post merge
1144   set_control(_gvn.transform(region));
1145   record_for_igvn(region);
1146 
1147   set_result(_gvn.transform(phi));
1148   return true;
1149 }
1150 
1151 //------------------------------inline_array_equals----------------------------
1152 bool LibraryCallKit::inline_array_equals(StrIntrinsicNode::ArgEnc ae) {
1153   assert(ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::LL, "unsupported array types");
1154   Node* arg1 = argument(0);
1155   Node* arg2 = argument(1);
1156 
1157   const TypeAryPtr* mtype = (ae == StrIntrinsicNode::UU) ? TypeAryPtr::CHARS : TypeAryPtr::BYTES;
1158   set_result(_gvn.transform(new AryEqNode(control(), memory(mtype), arg1, arg2, ae)));
1159   clear_upper_avx();
1160 
1161   return true;
1162 }
1163 
1164 
1165 //------------------------------inline_countPositives------------------------------
1166 // int java.lang.StringCoding#countPositives0(byte[] ba, int off, int len)
1167 bool LibraryCallKit::inline_countPositives() {
1168   assert(callee()->signature()->size() == 3, "countPositives has 3 parameters");
1169   // no receiver since it is static method
1170   Node* ba         = argument(0);
1171   Node* offset     = argument(1);
1172   Node* len        = argument(2);
1173 
1174   ba = must_be_not_null(ba, true);
1175   RegionNode* bailout = create_bailout();
1176   generate_string_range_check(ba, offset, len, false, bailout);
1177   if (check_bailout(bailout)) {
1178     return true;
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 (!Matcher::match_rule_supported(Op_StrIndexOf)) {
1310     return false;
1311   }
1312 
1313   assert(callee()->signature()->size() == 5, "String.indexOf() has 5 arguments");
1314   Node* src         = argument(0); // byte[]
1315   Node* src_count   = argument(1); // char count
1316   Node* tgt         = argument(2); // byte[]
1317   Node* tgt_count   = argument(3); // char count
1318   Node* from_index  = argument(4); // char index
1319 
1320   src = must_be_not_null(src, true);
1321   tgt = must_be_not_null(tgt, true);
1322 
1323   // Multiply byte array index by 2 if String is UTF16 encoded
1324   Node* src_offset = (ae == StrIntrinsicNode::LL) ? from_index : _gvn.transform(new LShiftINode(from_index, intcon(1)));
1325   src_count = _gvn.transform(new SubINode(src_count, from_index));
1326   Node* src_start = array_element_address(src, src_offset, T_BYTE);
1327   Node* tgt_start = array_element_address(tgt, intcon(0), T_BYTE);
1328 
1329   // Range checks
1330   RegionNode* bailout = create_bailout();
1331   generate_string_range_check(src, src_offset, src_count, ae != StrIntrinsicNode::LL, bailout);
1332   generate_string_range_check(tgt, intcon(0), tgt_count, ae == StrIntrinsicNode::UU, bailout);
1333   if (check_bailout(bailout)) {
1334     return true;
1335   }
1336 
1337   RegionNode* region = new RegionNode(5);
1338   Node* phi = new PhiNode(region, TypeInt::INT);
1339   Node* result = nullptr;
1340 
1341   bool call_opt_stub = (StubRoutines::_string_indexof_array[ae] != nullptr);
1342 
1343   if (call_opt_stub) {
1344     Node* call = make_runtime_call(RC_LEAF, OptoRuntime::string_IndexOf_Type(),
1345                                    StubRoutines::_string_indexof_array[ae],
1346                                    "stringIndexOf", TypePtr::BOTTOM, src_start,
1347                                    src_count, tgt_start, tgt_count);
1348     result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
1349   } else {
1350     result = make_indexOf_node(src_start, src_count, tgt_start, tgt_count,
1351                                region, phi, ae);
1352   }
1353   if (result != nullptr) {
1354     // The result is index relative to from_index if substring was found, -1 otherwise.
1355     // Generate code which will fold into cmove.
1356     Node* cmp = _gvn.transform(new CmpINode(result, intcon(0)));
1357     Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::lt));
1358 
1359     Node* if_lt = generate_slow_guard(bol, nullptr);
1360     if (if_lt != nullptr) {
1361       // result == -1
1362       phi->init_req(3, result);
1363       region->init_req(3, if_lt);
1364     }
1365     if (!stopped()) {
1366       result = _gvn.transform(new AddINode(result, from_index));
1367       phi->init_req(4, result);
1368       region->init_req(4, control());
1369     }
1370   }
1371 
1372   set_control(_gvn.transform(region));
1373   record_for_igvn(region);
1374   set_result(_gvn.transform(phi));
1375   clear_upper_avx();
1376 
1377   return true;
1378 }
1379 
1380 // Create StrIndexOfNode with fast path checks
1381 Node* LibraryCallKit::make_indexOf_node(Node* src_start, Node* src_count, Node* tgt_start, Node* tgt_count,
1382                                         RegionNode* region, Node* phi, StrIntrinsicNode::ArgEnc ae) {
1383   // Check for substr count > string count
1384   Node* cmp = _gvn.transform(new CmpINode(tgt_count, src_count));
1385   Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::gt));
1386   Node* if_gt = generate_slow_guard(bol, nullptr);
1387   if (if_gt != nullptr) {
1388     phi->init_req(1, intcon(-1));
1389     region->init_req(1, if_gt);
1390   }
1391   if (!stopped()) {
1392     // Check for substr count == 0
1393     cmp = _gvn.transform(new CmpINode(tgt_count, intcon(0)));
1394     bol = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
1395     Node* if_zero = generate_slow_guard(bol, nullptr);
1396     if (if_zero != nullptr) {
1397       phi->init_req(2, intcon(0));
1398       region->init_req(2, if_zero);
1399     }
1400   }
1401   if (!stopped()) {
1402     return make_string_method_node(Op_StrIndexOf, src_start, src_count, tgt_start, tgt_count, ae);
1403   }
1404   return nullptr;
1405 }
1406 
1407 //-----------------------------inline_string_indexOfChar-----------------------
1408 bool LibraryCallKit::inline_string_indexOfChar(StrIntrinsicNode::ArgEnc ae) {
1409   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1410     return false;
1411   }
1412   if (!Matcher::match_rule_supported(Op_StrIndexOfChar)) {
1413     return false;
1414   }
1415   assert(callee()->signature()->size() == 4, "String.indexOfChar() has 4 arguments");
1416   Node* src         = argument(0); // byte[]
1417   Node* int_ch      = argument(1);
1418   Node* from_index  = argument(2);
1419   Node* max         = argument(3);
1420 
1421   src = must_be_not_null(src, true);
1422 
1423   Node* src_offset = ae == StrIntrinsicNode::L ? from_index : _gvn.transform(new LShiftINode(from_index, intcon(1)));
1424   Node* src_start = array_element_address(src, src_offset, T_BYTE);
1425   Node* src_count = _gvn.transform(new SubINode(max, from_index));
1426 
1427   // Range checks
1428   RegionNode* bailout = create_bailout();
1429   generate_string_range_check(src, src_offset, src_count, ae == StrIntrinsicNode::U, bailout);
1430   if (check_bailout(bailout)) {
1431     return true;
1432   }
1433 
1434   // Check for int_ch >= 0
1435   Node* int_ch_cmp = _gvn.transform(new CmpINode(int_ch, intcon(0)));
1436   Node* int_ch_bol = _gvn.transform(new BoolNode(int_ch_cmp, BoolTest::ge));
1437   {
1438     BuildCutout unless(this, int_ch_bol, PROB_MAX);
1439     uncommon_trap(Deoptimization::Reason_intrinsic,
1440                   Deoptimization::Action_maybe_recompile);
1441   }
1442   if (stopped()) {
1443     return true;
1444   }
1445 
1446   RegionNode* region = new RegionNode(3);
1447   Node* phi = new PhiNode(region, TypeInt::INT);
1448 
1449   Node* result = new StrIndexOfCharNode(control(), memory(TypeAryPtr::BYTES), src_start, src_count, int_ch, ae);
1450   C->set_has_split_ifs(true); // Has chance for split-if optimization
1451   _gvn.transform(result);
1452 
1453   Node* cmp = _gvn.transform(new CmpINode(result, intcon(0)));
1454   Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::lt));
1455 
1456   Node* if_lt = generate_slow_guard(bol, nullptr);
1457   if (if_lt != nullptr) {
1458     // result == -1
1459     phi->init_req(2, result);
1460     region->init_req(2, if_lt);
1461   }
1462   if (!stopped()) {
1463     result = _gvn.transform(new AddINode(result, from_index));
1464     phi->init_req(1, result);
1465     region->init_req(1, control());
1466   }
1467   set_control(_gvn.transform(region));
1468   record_for_igvn(region);
1469   set_result(_gvn.transform(phi));
1470   clear_upper_avx();
1471 
1472   return true;
1473 }
1474 //---------------------------inline_string_copy---------------------
1475 // compressIt == true --> generate a compressed copy operation (compress char[]/byte[] to byte[])
1476 //   int StringUTF16.compress0(char[] src, int srcOff, byte[] dst, int dstOff, int len)
1477 //   int StringUTF16.compress0(byte[] src, int srcOff, byte[] dst, int dstOff, int len)
1478 // compressIt == false --> generate an inflated copy operation (inflate byte[] to char[]/byte[])
1479 //   void StringLatin1.inflate0(byte[] src, int srcOff, char[] dst, int dstOff, int len)
1480 //   void StringLatin1.inflate0(byte[] src, int srcOff, byte[] dst, int dstOff, int len)
1481 bool LibraryCallKit::inline_string_copy(bool compress) {
1482   int nargs = 5;  // 2 oops, 3 ints
1483   assert(callee()->signature()->size() == nargs, "string copy has 5 arguments");
1484 
1485   Node* src         = argument(0);
1486   Node* src_offset  = argument(1);
1487   Node* dst         = argument(2);
1488   Node* dst_offset  = argument(3);
1489   Node* length      = argument(4);
1490 
1491   // Check for allocation before we add nodes that would confuse
1492   // tightly_coupled_allocation()
1493   AllocateArrayNode* alloc = tightly_coupled_allocation(dst);
1494 
1495   // Figure out the size and type of the elements we will be copying.
1496   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
1497   const TypeAryPtr* dst_type = dst->Value(&_gvn)->isa_aryptr();
1498   if (src_type == nullptr || dst_type == nullptr) {
1499     return false;
1500   }
1501   BasicType src_elem = src_type->elem()->array_element_basic_type();
1502   BasicType dst_elem = dst_type->elem()->array_element_basic_type();
1503   assert((compress && dst_elem == T_BYTE && (src_elem == T_BYTE || src_elem == T_CHAR)) ||
1504          (!compress && src_elem == T_BYTE && (dst_elem == T_BYTE || dst_elem == T_CHAR)),
1505          "Unsupported array types for inline_string_copy");
1506 
1507   src = must_be_not_null(src, true);
1508   dst = must_be_not_null(dst, true);
1509 
1510   // Convert char[] offsets to byte[] offsets
1511   bool convert_src = (compress && src_elem == T_BYTE);
1512   bool convert_dst = (!compress && dst_elem == T_BYTE);
1513   if (convert_src) {
1514     src_offset = _gvn.transform(new LShiftINode(src_offset, intcon(1)));
1515   } else if (convert_dst) {
1516     dst_offset = _gvn.transform(new LShiftINode(dst_offset, intcon(1)));
1517   }
1518 
1519   // Range checks
1520   RegionNode* bailout = create_bailout();
1521   generate_string_range_check(src, src_offset, length, convert_src, bailout);
1522   generate_string_range_check(dst, dst_offset, length, convert_dst, bailout);
1523   if (check_bailout(bailout)) {
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.toBytes0(char[] value, int off, int len)
1572 bool LibraryCallKit::inline_string_toBytesU() {
1573   // Get the arguments.
1574   assert(callee()->signature()->size() == 3, "character array encoder requires 3 arguments");
1575   Node* value     = argument(0);
1576   Node* offset    = argument(1);
1577   Node* length    = argument(2);
1578 
1579   Node* newcopy = nullptr;
1580 
1581   // Set the original stack and the reexecute bit for the interpreter to reexecute
1582   // the bytecode that invokes StringUTF16.toBytes0() if deoptimization happens.
1583   { PreserveReexecuteState preexecs(this);
1584     jvms()->set_should_reexecute(true);
1585 
1586     value = must_be_not_null(value, true);
1587     RegionNode* bailout = create_bailout();
1588     generate_negative_guard(offset, bailout, nullptr, true);
1589     generate_negative_guard(length, bailout, nullptr, true);
1590     generate_limit_guard(offset, length, load_array_length(value), bailout, true);
1591     // Make sure that resulting byte[] length does not overflow Integer.MAX_VALUE
1592     generate_limit_guard(length, intcon(0), intcon(max_jint/2), bailout, true);
1593     if (check_bailout(bailout)) {
1594       return true;
1595     }
1596 
1597     Node* size = _gvn.transform(new LShiftINode(length, intcon(1)));
1598     Node* klass_node = makecon(TypeKlassPtr::make(ciTypeArrayKlass::make(T_BYTE)));
1599     newcopy = new_array(klass_node, size, 0);  // no arguments to push
1600     AllocateArrayNode* alloc = tightly_coupled_allocation(newcopy);
1601     guarantee(alloc != nullptr, "created above");
1602 
1603     // Calculate starting addresses.
1604     Node* src_start = array_element_address(value, offset, T_CHAR);
1605     Node* dst_start = basic_plus_adr(newcopy, arrayOopDesc::base_offset_in_bytes(T_BYTE));
1606 
1607     // Check if dst array address is aligned to HeapWordSize
1608     bool aligned = (arrayOopDesc::base_offset_in_bytes(T_BYTE) % HeapWordSize == 0);
1609     // If true, then check if src array address is aligned to HeapWordSize
1610     if (aligned) {
1611       const TypeInt* toffset = gvn().type(offset)->is_int();
1612       aligned = toffset->is_con() && ((arrayOopDesc::base_offset_in_bytes(T_CHAR) +
1613                                        toffset->get_con() * type2aelembytes(T_CHAR)) % HeapWordSize == 0);
1614     }
1615 
1616     // Figure out which arraycopy runtime method to call (disjoint, uninitialized).
1617     const char* copyfunc_name = "arraycopy";
1618     address     copyfunc_addr = StubRoutines::select_arraycopy_function(T_CHAR, aligned, true, copyfunc_name, true);
1619     Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
1620                       OptoRuntime::fast_arraycopy_Type(),
1621                       copyfunc_addr, copyfunc_name, TypeRawPtr::BOTTOM,
1622                       src_start, dst_start, ConvI2X(length) XTOP);
1623     // Do not let reads from the cloned object float above the arraycopy.
1624     if (alloc->maybe_set_complete(&_gvn)) {
1625       // "You break it, you buy it."
1626       InitializeNode* init = alloc->initialization();
1627       assert(init->is_complete(), "we just did this");
1628       init->set_complete_with_arraycopy();
1629       assert(newcopy->is_CheckCastPP(), "sanity");
1630       assert(newcopy->in(0)->in(0) == init, "dest pinned");
1631     }
1632     // Do not let stores that initialize this object be reordered with
1633     // a subsequent store that would make this object accessible by
1634     // other threads.
1635     // Record what AllocateNode this StoreStore protects so that
1636     // escape analysis can go from the MemBarStoreStoreNode to the
1637     // AllocateNode and eliminate the MemBarStoreStoreNode if possible
1638     // based on the escape status of the AllocateNode.
1639     insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
1640   } // original reexecute is set back here
1641 
1642   C->set_has_split_ifs(true); // Has chance for split-if optimization
1643   if (!stopped()) {
1644     set_result(newcopy);
1645   }
1646   clear_upper_avx();
1647 
1648   return true;
1649 }
1650 
1651 //------------------------inline_string_getCharsU--------------------------
1652 // public void StringUTF16.getChars0(byte[] src, int srcBegin, int srcEnd, char dst[], int dstBegin)
1653 bool LibraryCallKit::inline_string_getCharsU() {
1654   assert(callee()->signature()->size() == 5, "StringUTF16.getChars0() has 5 arguments");
1655   // Get the arguments.
1656   Node* src       = argument(0);
1657   Node* src_begin = argument(1);
1658   Node* src_end   = argument(2); // exclusive offset (i < src_end)
1659   Node* dst       = argument(3);
1660   Node* dst_begin = argument(4);
1661 
1662   // Check for allocation before we add nodes that would confuse
1663   // tightly_coupled_allocation()
1664   AllocateArrayNode* alloc = tightly_coupled_allocation(dst);
1665 
1666   // Check if a null path was taken unconditionally.
1667   src = must_be_not_null(src, true);
1668   dst = must_be_not_null(dst, true);
1669   if (stopped()) {
1670     return true;
1671   }
1672 
1673   // Get length and convert char[] offset to byte[] offset
1674   Node* length = _gvn.transform(new SubINode(src_end, src_begin));
1675   src_begin = _gvn.transform(new LShiftINode(src_begin, intcon(1)));
1676 
1677   // Range checks
1678   RegionNode* bailout = create_bailout();
1679   generate_string_range_check(src, src_begin, length, true, bailout);
1680   generate_string_range_check(dst, dst_begin, length, false, bailout);
1681   if (check_bailout(bailout)) {
1682     return true;
1683   }
1684 
1685   // Calculate starting addresses.
1686   Node* src_start = array_element_address(src, src_begin, T_BYTE);
1687   Node* dst_start = array_element_address(dst, dst_begin, T_CHAR);
1688 
1689   // Check if array addresses are aligned to HeapWordSize
1690   const TypeInt* tsrc = gvn().type(src_begin)->is_int();
1691   const TypeInt* tdst = gvn().type(dst_begin)->is_int();
1692   bool aligned = tsrc->is_con() && ((arrayOopDesc::base_offset_in_bytes(T_BYTE) + tsrc->get_con() * type2aelembytes(T_BYTE)) % HeapWordSize == 0) &&
1693                  tdst->is_con() && ((arrayOopDesc::base_offset_in_bytes(T_CHAR) + tdst->get_con() * type2aelembytes(T_CHAR)) % HeapWordSize == 0);
1694 
1695   // Figure out which arraycopy runtime method to call (disjoint, uninitialized).
1696   const char* copyfunc_name = "arraycopy";
1697   address     copyfunc_addr = StubRoutines::select_arraycopy_function(T_CHAR, aligned, true, copyfunc_name, true);
1698   Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
1699                     OptoRuntime::fast_arraycopy_Type(),
1700                     copyfunc_addr, copyfunc_name, TypeRawPtr::BOTTOM,
1701                     src_start, dst_start, ConvI2X(length) XTOP);
1702   // Do not let reads from the cloned object float above the arraycopy.
1703   if (alloc != nullptr) {
1704     if (alloc->maybe_set_complete(&_gvn)) {
1705       // "You break it, you buy it."
1706       InitializeNode* init = alloc->initialization();
1707       assert(init->is_complete(), "we just did this");
1708       init->set_complete_with_arraycopy();
1709       assert(dst->is_CheckCastPP(), "sanity");
1710       assert(dst->in(0)->in(0) == init, "dest pinned");
1711     }
1712     // Do not let stores that initialize this object be reordered with
1713     // a subsequent store that would make this object accessible by
1714     // other threads.
1715     // Record what AllocateNode this StoreStore protects so that
1716     // escape analysis can go from the MemBarStoreStoreNode to the
1717     // AllocateNode and eliminate the MemBarStoreStoreNode if possible
1718     // based on the escape status of the AllocateNode.
1719     insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
1720   } else {
1721     insert_mem_bar(Op_MemBarCPUOrder);
1722   }
1723 
1724   C->set_has_split_ifs(true); // Has chance for split-if optimization
1725   return true;
1726 }
1727 
1728 //----------------------inline_string_char_access----------------------------
1729 // Store/Load char to/from byte[] array.
1730 // static void StringUTF16.putChar(byte[] val, int index, int c)
1731 // static char StringUTF16.getChar(byte[] val, int index)
1732 bool LibraryCallKit::inline_string_char_access(bool is_store) {
1733   Node* ch;
1734   if (is_store) {
1735     assert(callee()->signature()->size() == 3, "StringUTF16.putChar() has 3 arguments");
1736     ch = argument(2);
1737   } else {
1738     assert(callee()->signature()->size() == 2, "StringUTF16.getChar() has 2 arguments");
1739     ch = nullptr;
1740   }
1741   Node* value  = argument(0);
1742   Node* index  = argument(1);
1743 
1744   // This intrinsic accesses byte[] array as char[] array. Computing the offsets
1745   // correctly requires matched array shapes.
1746   assert (arrayOopDesc::base_offset_in_bytes(T_CHAR) == arrayOopDesc::base_offset_in_bytes(T_BYTE),
1747           "sanity: byte[] and char[] bases agree");
1748   assert (type2aelembytes(T_CHAR) == type2aelembytes(T_BYTE)*2,
1749           "sanity: byte[] and char[] scales agree");
1750 
1751   // Bail when getChar over constants is requested: constant folding would
1752   // reject folding mismatched char access over byte[]. A normal inlining for getChar
1753   // Java method would constant fold nicely instead.
1754   if (!is_store && value->is_Con() && index->is_Con()) {
1755     return false;
1756   }
1757 
1758   // Save state and restore on bailout
1759   SavedState old_state(this);
1760 
1761   value = must_be_not_null(value, true);
1762 
1763   Node* adr = array_element_address(value, index, T_CHAR);
1764   if (adr->is_top()) {
1765     return false;
1766   }
1767   old_state.discard();
1768   if (is_store) {
1769     access_store_at(value, adr, TypeAryPtr::BYTES, ch, TypeInt::CHAR, T_CHAR, IN_HEAP | MO_UNORDERED | C2_MISMATCHED);
1770   } else {
1771     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);
1772     set_result(ch);
1773   }
1774   return true;
1775 }
1776 
1777 
1778 //------------------------------inline_math-----------------------------------
1779 // public static double Math.abs(double)
1780 // public static double Math.sqrt(double)
1781 // public static double Math.log(double)
1782 // public static double Math.log10(double)
1783 // public static double Math.round(double)
1784 bool LibraryCallKit::inline_double_math(vmIntrinsics::ID id) {
1785   Node* arg = argument(0);
1786   Node* n = nullptr;
1787   switch (id) {
1788   case vmIntrinsics::_dabs:   n = new AbsDNode(                arg);  break;
1789   case vmIntrinsics::_dsqrt:
1790   case vmIntrinsics::_dsqrt_strict:
1791                               n = new SqrtDNode(C, control(),  arg);  break;
1792   case vmIntrinsics::_ceil:   n = RoundDoubleModeNode::make(_gvn, arg, RoundDoubleModeNode::rmode_ceil); break;
1793   case vmIntrinsics::_floor:  n = RoundDoubleModeNode::make(_gvn, arg, RoundDoubleModeNode::rmode_floor); break;
1794   case vmIntrinsics::_rint:   n = RoundDoubleModeNode::make(_gvn, arg, RoundDoubleModeNode::rmode_rint); break;
1795   case vmIntrinsics::_roundD: n = new RoundDNode(arg); break;
1796   case vmIntrinsics::_dcopySign: n = CopySignDNode::make(_gvn, arg, argument(2)); break;
1797   case vmIntrinsics::_dsignum: n = SignumDNode::make(_gvn, arg); break;
1798   default:  fatal_unexpected_iid(id);  break;
1799   }
1800   set_result(_gvn.transform(n));
1801   return true;
1802 }
1803 
1804 //------------------------------inline_math-----------------------------------
1805 // public static float Math.abs(float)
1806 // public static int Math.abs(int)
1807 // public static long Math.abs(long)
1808 bool LibraryCallKit::inline_math(vmIntrinsics::ID id) {
1809   Node* arg = argument(0);
1810   Node* n = nullptr;
1811   switch (id) {
1812   case vmIntrinsics::_fabs:   n = new AbsFNode(                arg);  break;
1813   case vmIntrinsics::_iabs:   n = new AbsINode(                arg);  break;
1814   case vmIntrinsics::_labs:   n = new AbsLNode(                arg);  break;
1815   case vmIntrinsics::_fcopySign: n = new CopySignFNode(arg, argument(1)); break;
1816   case vmIntrinsics::_fsignum: n = SignumFNode::make(_gvn, arg); break;
1817   case vmIntrinsics::_roundF: n = new RoundFNode(arg); break;
1818   default:  fatal_unexpected_iid(id);  break;
1819   }
1820   set_result(_gvn.transform(n));
1821   return true;
1822 }
1823 
1824 //------------------------------runtime_math-----------------------------
1825 bool LibraryCallKit::runtime_math(const TypeFunc* call_type, address funcAddr, const char* funcName) {
1826   assert(call_type == OptoRuntime::Math_DD_D_Type() || call_type == OptoRuntime::Math_D_D_Type(),
1827          "must be (DD)D or (D)D type");
1828 
1829   // Inputs
1830   Node* a = argument(0);
1831   Node* b = (call_type == OptoRuntime::Math_DD_D_Type()) ? argument(2) : nullptr;
1832 
1833   const TypePtr* no_memory_effects = nullptr;
1834   Node* trig = make_runtime_call(RC_LEAF | RC_PURE, call_type, funcAddr, funcName,
1835                                  no_memory_effects,
1836                                  a, top(), b, b ? top() : nullptr);
1837   Node* value = _gvn.transform(new ProjNode(trig, TypeFunc::Parms+0));
1838 #ifdef ASSERT
1839   Node* value_top = _gvn.transform(new ProjNode(trig, TypeFunc::Parms+1));
1840   assert(value_top == top(), "second value must be top");
1841 #endif
1842 
1843   set_result(value);
1844   return true;
1845 }
1846 
1847 //------------------------------inline_math_pow-----------------------------
1848 bool LibraryCallKit::inline_math_pow() {
1849   Node* base = argument(0);
1850   Node* exp = argument(2);
1851 
1852   CallNode* pow = new PowDNode(C, base, exp);
1853   set_predefined_input_for_runtime_call(pow);
1854   pow = _gvn.transform(pow)->as_CallLeafPure();
1855   set_predefined_output_for_runtime_call(pow);
1856   Node* result = _gvn.transform(new ProjNode(pow, TypeFunc::Parms + 0));
1857   record_for_igvn(pow);
1858   set_result(result);
1859   return true;
1860 }
1861 
1862 //------------------------------inline_math_native-----------------------------
1863 bool LibraryCallKit::inline_math_native(vmIntrinsics::ID id) {
1864   switch (id) {
1865   case vmIntrinsics::_dsin:
1866     return StubRoutines::dsin() != nullptr ?
1867       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dsin(), "dsin") :
1868       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dsin),   "SIN");
1869   case vmIntrinsics::_dcos:
1870     return StubRoutines::dcos() != nullptr ?
1871       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dcos(), "dcos") :
1872       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dcos),   "COS");
1873   case vmIntrinsics::_dtan:
1874     return StubRoutines::dtan() != nullptr ?
1875       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dtan(), "dtan") :
1876       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dtan), "TAN");
1877   case vmIntrinsics::_dsinh:
1878     return StubRoutines::dsinh() != nullptr ?
1879       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dsinh(), "dsinh") : false;
1880   case vmIntrinsics::_dtanh:
1881     return StubRoutines::dtanh() != nullptr ?
1882       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dtanh(), "dtanh") : false;
1883   case vmIntrinsics::_dcbrt:
1884     return StubRoutines::dcbrt() != nullptr ?
1885       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dcbrt(), "dcbrt") : false;
1886   case vmIntrinsics::_dexp:
1887     return StubRoutines::dexp() != nullptr ?
1888       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dexp(),  "dexp") :
1889       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dexp),  "EXP");
1890   case vmIntrinsics::_dlog:
1891     return StubRoutines::dlog() != nullptr ?
1892       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dlog(), "dlog") :
1893       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dlog),   "LOG");
1894   case vmIntrinsics::_dlog10:
1895     return StubRoutines::dlog10() != nullptr ?
1896       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dlog10(), "dlog10") :
1897       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dlog10), "LOG10");
1898 
1899   case vmIntrinsics::_roundD: return Matcher::match_rule_supported(Op_RoundD) ? inline_double_math(id) : false;
1900   case vmIntrinsics::_ceil:
1901   case vmIntrinsics::_floor:
1902   case vmIntrinsics::_rint:   return Matcher::match_rule_supported(Op_RoundDoubleMode) ? inline_double_math(id) : false;
1903 
1904   case vmIntrinsics::_dsqrt:
1905   case vmIntrinsics::_dsqrt_strict:
1906                               return Matcher::match_rule_supported(Op_SqrtD) ? inline_double_math(id) : false;
1907   case vmIntrinsics::_dabs:   return Matcher::has_match_rule(Op_AbsD)   ? inline_double_math(id) : false;
1908   case vmIntrinsics::_fabs:   return Matcher::match_rule_supported(Op_AbsF)   ? inline_math(id) : false;
1909   case vmIntrinsics::_iabs:   return Matcher::match_rule_supported(Op_AbsI)   ? inline_math(id) : false;
1910   case vmIntrinsics::_labs:   return Matcher::match_rule_supported(Op_AbsL)   ? inline_math(id) : false;
1911 
1912   case vmIntrinsics::_dpow:      return inline_math_pow();
1913   case vmIntrinsics::_dcopySign: return inline_double_math(id);
1914   case vmIntrinsics::_fcopySign: return inline_math(id);
1915   case vmIntrinsics::_dsignum: return Matcher::match_rule_supported(Op_SignumD) ? inline_double_math(id) : false;
1916   case vmIntrinsics::_fsignum: return Matcher::match_rule_supported(Op_SignumF) ? inline_math(id) : false;
1917   case vmIntrinsics::_roundF: return Matcher::match_rule_supported(Op_RoundF) ? inline_math(id) : false;
1918 
1919    // These intrinsics are not yet correctly implemented
1920   case vmIntrinsics::_datan2:
1921     return false;
1922 
1923   default:
1924     fatal_unexpected_iid(id);
1925     return false;
1926   }
1927 }
1928 
1929 //----------------------------inline_notify-----------------------------------*
1930 bool LibraryCallKit::inline_notify(vmIntrinsics::ID id) {
1931   const TypeFunc* ftype = OptoRuntime::monitor_notify_Type();
1932   address func;
1933   if (id == vmIntrinsics::_notify) {
1934     func = OptoRuntime::monitor_notify_Java();
1935   } else {
1936     func = OptoRuntime::monitor_notifyAll_Java();
1937   }
1938   Node* call = make_runtime_call(RC_NO_LEAF, ftype, func, nullptr, TypeRawPtr::BOTTOM, argument(0));
1939   make_slow_call_ex(call, env()->Throwable_klass(), false);
1940   return true;
1941 }
1942 
1943 
1944 //----------------------------inline_min_max-----------------------------------
1945 bool LibraryCallKit::inline_min_max(vmIntrinsics::ID id) {
1946   Node* a = nullptr;
1947   Node* b = nullptr;
1948   Node* n = nullptr;
1949   switch (id) {
1950     case vmIntrinsics::_min:
1951     case vmIntrinsics::_max:
1952     case vmIntrinsics::_minF:
1953     case vmIntrinsics::_maxF:
1954     case vmIntrinsics::_minF_strict:
1955     case vmIntrinsics::_maxF_strict:
1956     case vmIntrinsics::_min_strict:
1957     case vmIntrinsics::_max_strict:
1958       assert(callee()->signature()->size() == 2, "minF/maxF has 2 parameters of size 1 each.");
1959       a = argument(0);
1960       b = argument(1);
1961       break;
1962     case vmIntrinsics::_minD:
1963     case vmIntrinsics::_maxD:
1964     case vmIntrinsics::_minD_strict:
1965     case vmIntrinsics::_maxD_strict:
1966       assert(callee()->signature()->size() == 4, "minD/maxD has 2 parameters of size 2 each.");
1967       a = argument(0);
1968       b = argument(2);
1969       break;
1970     case vmIntrinsics::_minL:
1971     case vmIntrinsics::_maxL:
1972       assert(callee()->signature()->size() == 4, "minL/maxL has 2 parameters of size 2 each.");
1973       a = argument(0);
1974       b = argument(2);
1975       break;
1976     default:
1977       fatal_unexpected_iid(id);
1978       break;
1979   }
1980 
1981   switch (id) {
1982     case vmIntrinsics::_min:
1983     case vmIntrinsics::_min_strict:
1984       n = new MinINode(a, b);
1985       break;
1986     case vmIntrinsics::_max:
1987     case vmIntrinsics::_max_strict:
1988       n = new MaxINode(a, b);
1989       break;
1990     case vmIntrinsics::_minF:
1991     case vmIntrinsics::_minF_strict:
1992       n = new MinFNode(a, b);
1993       break;
1994     case vmIntrinsics::_maxF:
1995     case vmIntrinsics::_maxF_strict:
1996       n = new MaxFNode(a, b);
1997       break;
1998     case vmIntrinsics::_minD:
1999     case vmIntrinsics::_minD_strict:
2000       n = new MinDNode(a, b);
2001       break;
2002     case vmIntrinsics::_maxD:
2003     case vmIntrinsics::_maxD_strict:
2004       n = new MaxDNode(a, b);
2005       break;
2006     case vmIntrinsics::_minL:
2007       n = new MinLNode(_gvn.C, a, b);
2008       break;
2009     case vmIntrinsics::_maxL:
2010       n = new MaxLNode(_gvn.C, a, b);
2011       break;
2012     default:
2013       fatal_unexpected_iid(id);
2014       break;
2015   }
2016 
2017   set_result(_gvn.transform(n));
2018   return true;
2019 }
2020 
2021 bool LibraryCallKit::inline_math_mathExact(Node* math, Node* test) {
2022   if (builtin_throw_too_many_traps(Deoptimization::Reason_intrinsic,
2023                                    env()->ArithmeticException_instance())) {
2024     // It has been already too many times, but we cannot use builtin_throw (e.g. we care about backtraces),
2025     // so let's bail out intrinsic rather than risking deopting again.
2026     return false;
2027   }
2028 
2029   Node* bol = _gvn.transform( new BoolNode(test, BoolTest::overflow) );
2030   IfNode* check = create_and_map_if(control(), bol, PROB_UNLIKELY_MAG(3), COUNT_UNKNOWN);
2031   Node* fast_path = _gvn.transform( new IfFalseNode(check));
2032   Node* slow_path = _gvn.transform( new IfTrueNode(check) );
2033 
2034   {
2035     PreserveJVMState pjvms(this);
2036     PreserveReexecuteState preexecs(this);
2037     jvms()->set_should_reexecute(true);
2038 
2039     set_control(slow_path);
2040     set_i_o(i_o());
2041 
2042     builtin_throw(Deoptimization::Reason_intrinsic,
2043                   env()->ArithmeticException_instance(),
2044                   /*allow_too_many_traps*/ false);
2045   }
2046 
2047   set_control(fast_path);
2048   set_result(math);
2049   return true;
2050 }
2051 
2052 template <typename OverflowOp>
2053 bool LibraryCallKit::inline_math_overflow(Node* arg1, Node* arg2) {
2054   typedef typename OverflowOp::MathOp MathOp;
2055 
2056   MathOp* mathOp = new MathOp(arg1, arg2);
2057   Node* operation = _gvn.transform( mathOp );
2058   Node* ofcheck = _gvn.transform( new OverflowOp(arg1, arg2) );
2059   return inline_math_mathExact(operation, ofcheck);
2060 }
2061 
2062 bool LibraryCallKit::inline_math_addExactI(bool is_increment) {
2063   return inline_math_overflow<OverflowAddINode>(argument(0), is_increment ? intcon(1) : argument(1));
2064 }
2065 
2066 bool LibraryCallKit::inline_math_addExactL(bool is_increment) {
2067   return inline_math_overflow<OverflowAddLNode>(argument(0), is_increment ? longcon(1) : argument(2));
2068 }
2069 
2070 bool LibraryCallKit::inline_math_subtractExactI(bool is_decrement) {
2071   return inline_math_overflow<OverflowSubINode>(argument(0), is_decrement ? intcon(1) : argument(1));
2072 }
2073 
2074 bool LibraryCallKit::inline_math_subtractExactL(bool is_decrement) {
2075   return inline_math_overflow<OverflowSubLNode>(argument(0), is_decrement ? longcon(1) : argument(2));
2076 }
2077 
2078 bool LibraryCallKit::inline_math_negateExactI() {
2079   return inline_math_overflow<OverflowSubINode>(intcon(0), argument(0));
2080 }
2081 
2082 bool LibraryCallKit::inline_math_negateExactL() {
2083   return inline_math_overflow<OverflowSubLNode>(longcon(0), argument(0));
2084 }
2085 
2086 bool LibraryCallKit::inline_math_multiplyExactI() {
2087   return inline_math_overflow<OverflowMulINode>(argument(0), argument(1));
2088 }
2089 
2090 bool LibraryCallKit::inline_math_multiplyExactL() {
2091   return inline_math_overflow<OverflowMulLNode>(argument(0), argument(2));
2092 }
2093 
2094 bool LibraryCallKit::inline_math_multiplyHigh() {
2095   set_result(_gvn.transform(new MulHiLNode(argument(0), argument(2))));
2096   return true;
2097 }
2098 
2099 bool LibraryCallKit::inline_math_unsignedMultiplyHigh() {
2100   set_result(_gvn.transform(new UMulHiLNode(argument(0), argument(2))));
2101   return true;
2102 }
2103 
2104 inline int
2105 LibraryCallKit::classify_unsafe_addr(Node* &base, Node* &offset, BasicType type) {
2106   const TypePtr* base_type = TypePtr::NULL_PTR;
2107   if (base != nullptr)  base_type = _gvn.type(base)->isa_ptr();
2108   if (base_type == nullptr) {
2109     // Unknown type.
2110     return Type::AnyPtr;
2111   } else if (_gvn.type(base->uncast()) == TypePtr::NULL_PTR) {
2112     // Since this is a null+long form, we have to switch to a rawptr.
2113     base   = _gvn.transform(new CastX2PNode(offset));
2114     offset = MakeConX(0);
2115     return Type::RawPtr;
2116   } else if (base_type->base() == Type::RawPtr) {
2117     return Type::RawPtr;
2118   } else if (base_type->isa_oopptr()) {
2119     // Base is never null => always a heap address.
2120     if (!TypePtr::NULL_PTR->higher_equal(base_type)) {
2121       return Type::OopPtr;
2122     }
2123     // Offset is small => always a heap address.
2124     const TypeX* offset_type = _gvn.type(offset)->isa_intptr_t();
2125     if (offset_type != nullptr &&
2126         base_type->offset() == 0 &&     // (should always be?)
2127         offset_type->_lo >= 0 &&
2128         !MacroAssembler::needs_explicit_null_check(offset_type->_hi)) {
2129       return Type::OopPtr;
2130     } else if (type == T_OBJECT) {
2131       // off heap access to an oop doesn't make any sense. Has to be on
2132       // heap.
2133       return Type::OopPtr;
2134     }
2135     // Otherwise, it might either be oop+off or null+addr.
2136     return Type::AnyPtr;
2137   } else {
2138     // No information:
2139     return Type::AnyPtr;
2140   }
2141 }
2142 
2143 Node* LibraryCallKit::make_unsafe_address(Node*& base, Node* offset, BasicType type, bool can_cast) {
2144   Node* uncasted_base = base;
2145   int kind = classify_unsafe_addr(uncasted_base, offset, type);
2146   if (kind == Type::RawPtr) {
2147     return off_heap_plus_addr(uncasted_base, offset);
2148   } else if (kind == Type::AnyPtr) {
2149     assert(base == uncasted_base, "unexpected base change");
2150     if (can_cast) {
2151       if (!_gvn.type(base)->speculative_maybe_null() &&
2152           !too_many_traps(Deoptimization::Reason_speculate_null_check)) {
2153         // According to profiling, this access is always on
2154         // heap. Casting the base to not null and thus avoiding membars
2155         // around the access should allow better optimizations
2156         Node* null_ctl = top();
2157         base = null_check_oop(base, &null_ctl, true, true, true);
2158         assert(null_ctl->is_top(), "no null control here");
2159         return basic_plus_adr(base, offset);
2160       } else if (_gvn.type(base)->speculative_always_null() &&
2161                  !too_many_traps(Deoptimization::Reason_speculate_null_assert)) {
2162         // According to profiling, this access is always off
2163         // heap.
2164         base = null_assert(base);
2165         Node* raw_base = _gvn.transform(new CastX2PNode(offset));
2166         offset = MakeConX(0);
2167         return off_heap_plus_addr(raw_base, offset);
2168       }
2169     }
2170     // We don't know if it's an on heap or off heap access. Fall back
2171     // to raw memory access.
2172     Node* raw = _gvn.transform(new CheckCastPPNode(control(), base, TypeRawPtr::BOTTOM));
2173     return off_heap_plus_addr(raw, offset);
2174   } else {
2175     assert(base == uncasted_base, "unexpected base change");
2176     // We know it's an on heap access so base can't be null
2177     if (TypePtr::NULL_PTR->higher_equal(_gvn.type(base))) {
2178       base = must_be_not_null(base, true);
2179     }
2180     return basic_plus_adr(base, offset);
2181   }
2182 }
2183 
2184 //--------------------------inline_number_methods-----------------------------
2185 // inline int     Integer.numberOfLeadingZeros(int)
2186 // inline int        Long.numberOfLeadingZeros(long)
2187 //
2188 // inline int     Integer.numberOfTrailingZeros(int)
2189 // inline int        Long.numberOfTrailingZeros(long)
2190 //
2191 // inline int     Integer.bitCount(int)
2192 // inline int        Long.bitCount(long)
2193 //
2194 // inline char  Character.reverseBytes(char)
2195 // inline short     Short.reverseBytes(short)
2196 // inline int     Integer.reverseBytes(int)
2197 // inline long       Long.reverseBytes(long)
2198 bool LibraryCallKit::inline_number_methods(vmIntrinsics::ID id) {
2199   Node* arg = argument(0);
2200   Node* n = nullptr;
2201   switch (id) {
2202   case vmIntrinsics::_numberOfLeadingZeros_i:   n = new CountLeadingZerosINode( arg); break;
2203   case vmIntrinsics::_numberOfLeadingZeros_l:   n = new CountLeadingZerosLNode( arg); break;
2204   case vmIntrinsics::_numberOfTrailingZeros_i:  n = new CountTrailingZerosINode(arg); break;
2205   case vmIntrinsics::_numberOfTrailingZeros_l:  n = new CountTrailingZerosLNode(arg); break;
2206   case vmIntrinsics::_bitCount_i:               n = new PopCountINode(          arg); break;
2207   case vmIntrinsics::_bitCount_l:               n = new PopCountLNode(          arg); break;
2208   case vmIntrinsics::_reverseBytes_c:           n = new ReverseBytesUSNode(     arg); break;
2209   case vmIntrinsics::_reverseBytes_s:           n = new ReverseBytesSNode(      arg); break;
2210   case vmIntrinsics::_reverseBytes_i:           n = new ReverseBytesINode(      arg); break;
2211   case vmIntrinsics::_reverseBytes_l:           n = new ReverseBytesLNode(      arg); break;
2212   case vmIntrinsics::_reverse_i:                n = new ReverseINode(           arg); break;
2213   case vmIntrinsics::_reverse_l:                n = new ReverseLNode(           arg); break;
2214   default:  fatal_unexpected_iid(id);  break;
2215   }
2216   set_result(_gvn.transform(n));
2217   return true;
2218 }
2219 
2220 //--------------------------inline_bitshuffle_methods-----------------------------
2221 // inline int Integer.compress(int, int)
2222 // inline int Integer.expand(int, int)
2223 // inline long Long.compress(long, long)
2224 // inline long Long.expand(long, long)
2225 bool LibraryCallKit::inline_bitshuffle_methods(vmIntrinsics::ID id) {
2226   Node* n = nullptr;
2227   switch (id) {
2228     case vmIntrinsics::_compress_i:  n = new CompressBitsNode(argument(0), argument(1), TypeInt::INT); break;
2229     case vmIntrinsics::_expand_i:    n = new ExpandBitsNode(argument(0),  argument(1), TypeInt::INT); break;
2230     case vmIntrinsics::_compress_l:  n = new CompressBitsNode(argument(0), argument(2), TypeLong::LONG); break;
2231     case vmIntrinsics::_expand_l:    n = new ExpandBitsNode(argument(0), argument(2), TypeLong::LONG); break;
2232     default:  fatal_unexpected_iid(id);  break;
2233   }
2234   set_result(_gvn.transform(n));
2235   return true;
2236 }
2237 
2238 //--------------------------inline_number_methods-----------------------------
2239 // inline int Integer.compareUnsigned(int, int)
2240 // inline int    Long.compareUnsigned(long, long)
2241 bool LibraryCallKit::inline_compare_unsigned(vmIntrinsics::ID id) {
2242   Node* arg1 = argument(0);
2243   Node* arg2 = (id == vmIntrinsics::_compareUnsigned_l) ? argument(2) : argument(1);
2244   Node* n = nullptr;
2245   switch (id) {
2246     case vmIntrinsics::_compareUnsigned_i:   n = new CmpU3Node(arg1, arg2);  break;
2247     case vmIntrinsics::_compareUnsigned_l:   n = new CmpUL3Node(arg1, arg2); break;
2248     default:  fatal_unexpected_iid(id);  break;
2249   }
2250   set_result(_gvn.transform(n));
2251   return true;
2252 }
2253 
2254 //--------------------------inline_unsigned_divmod_methods-----------------------------
2255 // inline int Integer.divideUnsigned(int, int)
2256 // inline int Integer.remainderUnsigned(int, int)
2257 // inline long Long.divideUnsigned(long, long)
2258 // inline long Long.remainderUnsigned(long, long)
2259 bool LibraryCallKit::inline_divmod_methods(vmIntrinsics::ID id) {
2260   Node* n = nullptr;
2261   switch (id) {
2262     case vmIntrinsics::_divideUnsigned_i: {
2263       zero_check_int(argument(1));
2264       // Compile-time detect of null-exception
2265       if (stopped()) {
2266         return true; // keep the graph constructed so far
2267       }
2268       n = new UDivINode(control(), argument(0), argument(1));
2269       break;
2270     }
2271     case vmIntrinsics::_divideUnsigned_l: {
2272       zero_check_long(argument(2));
2273       // Compile-time detect of null-exception
2274       if (stopped()) {
2275         return true; // keep the graph constructed so far
2276       }
2277       n = new UDivLNode(control(), argument(0), argument(2));
2278       break;
2279     }
2280     case vmIntrinsics::_remainderUnsigned_i: {
2281       zero_check_int(argument(1));
2282       // Compile-time detect of null-exception
2283       if (stopped()) {
2284         return true; // keep the graph constructed so far
2285       }
2286       n = new UModINode(control(), argument(0), argument(1));
2287       break;
2288     }
2289     case vmIntrinsics::_remainderUnsigned_l: {
2290       zero_check_long(argument(2));
2291       // Compile-time detect of null-exception
2292       if (stopped()) {
2293         return true; // keep the graph constructed so far
2294       }
2295       n = new UModLNode(control(), argument(0), argument(2));
2296       break;
2297     }
2298     default:  fatal_unexpected_iid(id);  break;
2299   }
2300   set_result(_gvn.transform(n));
2301   return true;
2302 }
2303 
2304 //----------------------------inline_unsafe_access----------------------------
2305 
2306 const TypeOopPtr* LibraryCallKit::sharpen_unsafe_type(Compile::AliasType* alias_type, const TypePtr *adr_type) {
2307   // Attempt to infer a sharper value type from the offset and base type.
2308   ciKlass* sharpened_klass = nullptr;
2309   bool null_free = false;
2310 
2311   // See if it is an instance field, with an object type.
2312   if (alias_type->field() != nullptr) {
2313     if (alias_type->field()->type()->is_klass()) {
2314       sharpened_klass = alias_type->field()->type()->as_klass();
2315       null_free = alias_type->field()->is_null_free();
2316     }
2317   }
2318 
2319   const TypeOopPtr* result = nullptr;
2320   // See if it is a narrow oop array.
2321   if (adr_type->isa_aryptr()) {
2322     if (adr_type->offset() >= refArrayOopDesc::base_offset_in_bytes()) {
2323       const TypeOopPtr* elem_type = adr_type->is_aryptr()->elem()->make_oopptr();
2324       null_free = adr_type->is_aryptr()->is_null_free();
2325       if (elem_type != nullptr && elem_type->is_loaded()) {
2326         // Sharpen the value type.
2327         result = elem_type;
2328       }
2329     }
2330   }
2331 
2332   // The sharpened class might be unloaded if there is no class loader
2333   // contraint in place.
2334   if (result == nullptr && sharpened_klass != nullptr && sharpened_klass->is_loaded()) {
2335     // Sharpen the value type.
2336     result = TypeOopPtr::make_from_klass(sharpened_klass);
2337     if (null_free) {
2338       result = result->join_speculative(TypePtr::NOTNULL)->is_oopptr();
2339     }
2340   }
2341   if (result != nullptr) {
2342 #ifndef PRODUCT
2343     if (C->print_intrinsics() || C->print_inlining()) {
2344       tty->print("  from base type:  ");  adr_type->dump(); tty->cr();
2345       tty->print("  sharpened value: ");  result->dump();    tty->cr();
2346     }
2347 #endif
2348   }
2349   return result;
2350 }
2351 
2352 DecoratorSet LibraryCallKit::mo_decorator_for_access_kind(AccessKind kind) {
2353   switch (kind) {
2354       case Relaxed:
2355         return MO_UNORDERED;
2356       case Opaque:
2357         return MO_RELAXED;
2358       case Acquire:
2359         return MO_ACQUIRE;
2360       case Release:
2361         return MO_RELEASE;
2362       case Volatile:
2363         return MO_SEQ_CST;
2364       default:
2365         ShouldNotReachHere();
2366         return 0;
2367   }
2368 }
2369 
2370 bool LibraryCallKit::inline_unsafe_access(bool is_store, const BasicType type, const AccessKind kind, const bool unaligned) {
2371   if (callee()->is_static())  return false;  // caller must have the capability!
2372   DecoratorSet decorators = C2_UNSAFE_ACCESS;
2373   guarantee(!is_store || kind != Acquire, "Acquire accesses can be produced only for loads");
2374   guarantee( is_store || kind != Release, "Release accesses can be produced only for stores");
2375   assert(type != T_OBJECT || !unaligned, "unaligned access not supported with object type");
2376 
2377   if (is_reference_type(type)) {
2378     decorators |= ON_UNKNOWN_OOP_REF;
2379   }
2380 
2381   if (unaligned) {
2382     decorators |= C2_UNALIGNED;
2383   }
2384 
2385 #ifndef PRODUCT
2386   {
2387     ResourceMark rm;
2388     // Check the signatures.
2389     ciSignature* sig = callee()->signature();
2390 #ifdef ASSERT
2391     if (!is_store) {
2392       // Object getReference(Object base, int/long offset), etc.
2393       BasicType rtype = sig->return_type()->basic_type();
2394       assert(rtype == type, "getter must return the expected value");
2395       assert(sig->count() == 2, "oop getter has 2 arguments");
2396       assert(sig->type_at(0)->basic_type() == T_OBJECT, "getter base is object");
2397       assert(sig->type_at(1)->basic_type() == T_LONG, "getter offset is correct");
2398     } else {
2399       // void putReference(Object base, int/long offset, Object x), etc.
2400       assert(sig->return_type()->basic_type() == T_VOID, "putter must not return a value");
2401       assert(sig->count() == 3, "oop putter has 3 arguments");
2402       assert(sig->type_at(0)->basic_type() == T_OBJECT, "putter base is object");
2403       assert(sig->type_at(1)->basic_type() == T_LONG, "putter offset is correct");
2404       BasicType vtype = sig->type_at(sig->count()-1)->basic_type();
2405       assert(vtype == type, "putter must accept the expected value");
2406     }
2407 #endif // ASSERT
2408  }
2409 #endif //PRODUCT
2410 
2411   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
2412 
2413   Node* receiver = argument(0);  // type: oop
2414 
2415   // Build address expression.
2416   Node* heap_base_oop = top();
2417 
2418   // The base is either a Java object or a value produced by Unsafe.staticFieldBase
2419   Node* base = argument(1);  // type: oop
2420   // The offset is a value produced by Unsafe.staticFieldOffset or Unsafe.objectFieldOffset
2421   Node* offset = argument(2);  // type: long
2422   // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
2423   // to be plain byte offsets, which are also the same as those accepted
2424   // by oopDesc::field_addr.
2425   assert(Unsafe_field_offset_to_byte_offset(11) == 11,
2426          "fieldOffset must be byte-scaled");
2427 
2428   if (base->is_InlineType()) {
2429     assert(!is_store, "InlineTypeNodes are non-larval value objects");
2430     InlineTypeNode* vt = base->as_InlineType();
2431     if (offset->is_Con()) {
2432       long off = find_long_con(offset, 0);
2433       ciInlineKlass* vk = vt->type()->inline_klass();
2434       if ((long)(int)off != off || !vk->contains_field_offset(off)) {
2435         return false;
2436       }
2437 
2438       ciField* field = vk->get_non_flat_field_by_offset(off);
2439       if (field != nullptr) {
2440         BasicType bt = type2field[field->type()->basic_type()];
2441         if (bt == T_ARRAY || bt == T_NARROWOOP) {
2442           bt = T_OBJECT;
2443         }
2444         if (bt == type && !field->is_flat()) {
2445           Node* value = vt->field_value_by_offset(off, false);
2446           const Type* value_type = _gvn.type(value);
2447           if (value->is_InlineType()) {
2448             value = value->as_InlineType()->adjust_scalarization_depth(this);
2449           } else if (value_type->is_inlinetypeptr()) {
2450             value = InlineTypeNode::make_from_oop(this, value, value_type->inline_klass());
2451           }
2452           set_result(value);
2453           return true;
2454         }
2455       }
2456     }
2457     {
2458       // Re-execute the unsafe access if allocation triggers deoptimization.
2459       PreserveReexecuteState preexecs(this);
2460       jvms()->set_should_reexecute(true);
2461       vt = vt->buffer(this);
2462     }
2463     base = vt->get_oop();
2464   }
2465 
2466   // 32-bit machines ignore the high half!
2467   offset = ConvL2X(offset);
2468 
2469   // Save state and restore on bailout
2470   SavedState old_state(this);
2471 
2472   Node* adr = make_unsafe_address(base, offset, type, kind == Relaxed);
2473   assert(!stopped(), "Inlining of unsafe access failed: address construction stopped unexpectedly");
2474 
2475   if (_gvn.type(base->uncast())->isa_ptr() == TypePtr::NULL_PTR) {
2476     if (type != T_OBJECT) {
2477       decorators |= IN_NATIVE; // off-heap primitive access
2478     } else {
2479       return false; // off-heap oop accesses are not supported
2480     }
2481   } else {
2482     heap_base_oop = base; // on-heap or mixed access
2483   }
2484 
2485   // Can base be null? Otherwise, always on-heap access.
2486   bool can_access_non_heap = TypePtr::NULL_PTR->higher_equal(_gvn.type(base));
2487 
2488   if (!can_access_non_heap) {
2489     decorators |= IN_HEAP;
2490   }
2491 
2492   Node* val = is_store ? argument(4) : nullptr;
2493 
2494   const TypePtr* adr_type = _gvn.type(adr)->isa_ptr();
2495   if (adr_type == TypePtr::NULL_PTR) {
2496     return false; // off-heap access with zero address
2497   }
2498 
2499   // Try to categorize the address.
2500   Compile::AliasType* alias_type = C->alias_type(adr_type);
2501   assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
2502 
2503   if (alias_type->adr_type() == TypeInstPtr::KLASS ||
2504       alias_type->adr_type() == TypeAryPtr::RANGE) {
2505     return false; // not supported
2506   }
2507 
2508   bool mismatched = false;
2509   BasicType bt = T_ILLEGAL;
2510   ciField* field = nullptr;
2511   if (adr_type->isa_instptr()) {
2512     const TypeInstPtr* instptr = adr_type->is_instptr();
2513     ciInstanceKlass* k = instptr->instance_klass();
2514     int off = instptr->offset();
2515     if (instptr->const_oop() != nullptr &&
2516         k == ciEnv::current()->Class_klass() &&
2517         instptr->offset() >= (k->size_helper() * wordSize)) {
2518       k = instptr->const_oop()->as_instance()->java_lang_Class_klass()->as_instance_klass();
2519       field = k->get_field_by_offset(off, true);
2520     } else {
2521       field = k->get_non_flat_field_by_offset(off);
2522     }
2523     if (field != nullptr) {
2524       bt = type2field[field->type()->basic_type()];
2525     }
2526     if (bt != alias_type->basic_type()) {
2527       // Type mismatch. Is it an access to a nested flat field?
2528       field = k->get_field_by_offset(off, false);
2529       if (field != nullptr) {
2530         bt = type2field[field->type()->basic_type()];
2531       }
2532     }
2533     assert(bt == alias_type->basic_type(), "should match");
2534   } else {
2535     bt = alias_type->basic_type();
2536   }
2537 
2538   if (bt != T_ILLEGAL) {
2539     assert(alias_type->adr_type()->is_oopptr(), "should be on-heap access");
2540     if (bt == T_BYTE && adr_type->isa_aryptr()) {
2541       // Alias type doesn't differentiate between byte[] and boolean[]).
2542       // Use address type to get the element type.
2543       bt = adr_type->is_aryptr()->elem()->array_element_basic_type();
2544     }
2545     if (is_reference_type(bt, true)) {
2546       // accessing an array field with getReference is not a mismatch
2547       bt = T_OBJECT;
2548     }
2549     if ((bt == T_OBJECT) != (type == T_OBJECT)) {
2550       // Don't intrinsify mismatched object accesses
2551       return false;
2552     }
2553     mismatched = (bt != type);
2554   } else if (alias_type->adr_type()->isa_oopptr()) {
2555     mismatched = true; // conservatively mark all "wide" on-heap accesses as mismatched
2556   }
2557 
2558   old_state.discard();
2559   assert(!mismatched || alias_type->adr_type()->is_oopptr(), "off-heap access can't be mismatched");
2560 
2561   if (mismatched) {
2562     decorators |= C2_MISMATCHED;
2563   }
2564 
2565   // First guess at the value type.
2566   const Type *value_type = Type::get_const_basic_type(type);
2567 
2568   // Figure out the memory ordering.
2569   decorators |= mo_decorator_for_access_kind(kind);
2570 
2571   if (!is_store) {
2572     if (type == T_OBJECT) {
2573       const TypeOopPtr* tjp = sharpen_unsafe_type(alias_type, adr_type);
2574       if (tjp != nullptr) {
2575         value_type = tjp;
2576       }
2577     }
2578   }
2579 
2580   receiver = null_check(receiver);
2581   if (stopped()) {
2582     return true;
2583   }
2584   // Heap pointers get a null-check from the interpreter,
2585   // as a courtesy.  However, this is not guaranteed by Unsafe,
2586   // and it is not possible to fully distinguish unintended nulls
2587   // from intended ones in this API.
2588 
2589   if (!is_store) {
2590     Node* p = nullptr;
2591     // Try to constant fold a load from a constant field
2592 
2593     if (heap_base_oop != top() && field != nullptr && field->is_constant() && !field->is_flat() && !mismatched) {
2594       // final or stable field
2595       p = make_constant_from_field(field, heap_base_oop);
2596     }
2597 
2598     if (p == nullptr) { // Could not constant fold the load
2599       p = access_load_at(heap_base_oop, adr, adr_type, value_type, type, decorators);
2600       const TypeOopPtr* ptr = value_type->make_oopptr();
2601       if (ptr != nullptr && ptr->is_inlinetypeptr()) {
2602         // Load a non-flattened inline type from memory
2603         p = InlineTypeNode::make_from_oop(this, p, ptr->inline_klass());
2604       }
2605       // Normalize the value returned by getBoolean in the following cases
2606       if (type == T_BOOLEAN &&
2607           (mismatched ||
2608            heap_base_oop == top() ||                  // - heap_base_oop is null or
2609            (can_access_non_heap && field == nullptr)) // - heap_base_oop is potentially null
2610                                                       //   and the unsafe access is made to large offset
2611                                                       //   (i.e., larger than the maximum offset necessary for any
2612                                                       //   field access)
2613             ) {
2614           IdealKit ideal = IdealKit(this);
2615 #define __ ideal.
2616           IdealVariable normalized_result(ideal);
2617           __ declarations_done();
2618           __ set(normalized_result, p);
2619           __ if_then(p, BoolTest::ne, ideal.ConI(0));
2620           __ set(normalized_result, ideal.ConI(1));
2621           ideal.end_if();
2622           final_sync(ideal);
2623           p = __ value(normalized_result);
2624 #undef __
2625       }
2626     }
2627     if (type == T_ADDRESS) {
2628       p = gvn().transform(new CastP2XNode(nullptr, p));
2629       p = ConvX2UL(p);
2630     }
2631     // The load node has the control of the preceding MemBarCPUOrder.  All
2632     // following nodes will have the control of the MemBarCPUOrder inserted at
2633     // the end of this method.  So, pushing the load onto the stack at a later
2634     // point is fine.
2635     set_result(p);
2636   } else {
2637     if (bt == T_ADDRESS) {
2638       // Repackage the long as a pointer.
2639       val = ConvL2X(val);
2640       val = gvn().transform(new CastX2PNode(val));
2641     }
2642     access_store_at(heap_base_oop, adr, adr_type, val, value_type, type, decorators);
2643   }
2644 
2645   return true;
2646 }
2647 
2648 bool LibraryCallKit::inline_unsafe_flat_access(bool is_store, AccessKind kind) {
2649 #ifdef ASSERT
2650   {
2651     ResourceMark rm;
2652     // Check the signatures.
2653     ciSignature* sig = callee()->signature();
2654     assert(sig->type_at(0)->basic_type() == T_OBJECT, "base should be object, but is %s", type2name(sig->type_at(0)->basic_type()));
2655     assert(sig->type_at(1)->basic_type() == T_LONG, "offset should be long, but is %s", type2name(sig->type_at(1)->basic_type()));
2656     assert(sig->type_at(2)->basic_type() == T_INT, "layout kind should be int, but is %s", type2name(sig->type_at(3)->basic_type()));
2657     assert(sig->type_at(3)->basic_type() == T_OBJECT, "value klass should be object, but is %s", type2name(sig->type_at(4)->basic_type()));
2658     if (is_store) {
2659       assert(sig->return_type()->basic_type() == T_VOID, "putter must not return a value, but returns %s", type2name(sig->return_type()->basic_type()));
2660       assert(sig->count() == 5, "flat putter should have 5 arguments, but has %d", sig->count());
2661       assert(sig->type_at(4)->basic_type() == T_OBJECT, "put value should be object, but is %s", type2name(sig->type_at(5)->basic_type()));
2662     } else {
2663       assert(sig->return_type()->basic_type() == T_OBJECT, "getter must return an object, but returns %s", type2name(sig->return_type()->basic_type()));
2664       assert(sig->count() == 4, "flat getter should have 4 arguments, but has %d", sig->count());
2665     }
2666  }
2667 #endif // ASSERT
2668 
2669   assert(kind == Relaxed, "Only plain accesses for now");
2670   if (callee()->is_static()) {
2671     // caller must have the capability!
2672     return false;
2673   }
2674   C->set_has_unsafe_access(true);
2675 
2676   const TypeInstPtr* value_klass_node = _gvn.type(argument(5))->isa_instptr();
2677   if (value_klass_node == nullptr || value_klass_node->const_oop() == nullptr) {
2678     // parameter valueType is not a constant
2679     return false;
2680   }
2681   ciType* mirror_type = value_klass_node->const_oop()->as_instance()->java_mirror_type();
2682   if (!mirror_type->is_inlinetype()) {
2683     // Dead code
2684     return false;
2685   }
2686   ciInlineKlass* value_klass = mirror_type->as_inline_klass();
2687 
2688   const TypeInt* layout_type = _gvn.type(argument(4))->isa_int();
2689   if (layout_type == nullptr || !layout_type->is_con()) {
2690     // parameter layoutKind is not a constant
2691     return false;
2692   }
2693   assert(layout_type->get_con() >= static_cast<int>(LayoutKind::REFERENCE) &&
2694          layout_type->get_con() < static_cast<int>(LayoutKind::UNKNOWN),
2695          "invalid layoutKind %d", layout_type->get_con());
2696   LayoutKind layout = static_cast<LayoutKind>(layout_type->get_con());
2697   assert(layout == LayoutKind::REFERENCE || layout == LayoutKind::NULL_FREE_NON_ATOMIC_FLAT ||
2698          layout == LayoutKind::NULL_FREE_ATOMIC_FLAT || layout == LayoutKind::NULLABLE_ATOMIC_FLAT,
2699          "unexpected layoutKind %d", layout_type->get_con());
2700 
2701   null_check(argument(0));
2702   if (stopped()) {
2703     return true;
2704   }
2705 
2706   Node* base = must_be_not_null(argument(1), true);
2707   Node* offset = argument(2);
2708   const Type* base_type = _gvn.type(base);
2709 
2710   Node* ptr;
2711   bool immutable_memory = false;
2712   DecoratorSet decorators = C2_UNSAFE_ACCESS | IN_HEAP | MO_UNORDERED;
2713   if (base_type->isa_instptr()) {
2714     const TypeLong* offset_type = _gvn.type(offset)->isa_long();
2715     if (offset_type == nullptr || !offset_type->is_con()) {
2716       // Offset into a non-array should be a constant
2717       decorators |= C2_MISMATCHED;
2718     } else {
2719       int offset_con = checked_cast<int>(offset_type->get_con());
2720       ciInstanceKlass* base_klass = base_type->is_instptr()->instance_klass();
2721       ciField* field = base_klass->get_non_flat_field_by_offset(offset_con);
2722       if (field == nullptr) {
2723         assert(!base_klass->is_final(), "non-existence field at offset %d of class %s", offset_con, base_klass->name()->as_utf8());
2724         decorators |= C2_MISMATCHED;
2725       } else {
2726         assert(field->type() == value_klass, "field at offset %d of %s is of type %s, but valueType is %s",
2727                offset_con, base_klass->name()->as_utf8(), field->type()->name(), value_klass->name()->as_utf8());
2728         immutable_memory = field->is_strict() && field->is_final();
2729 
2730         if (base->is_InlineType()) {
2731           assert(!is_store, "Cannot store into a non-larval value object");
2732           set_result(base->as_InlineType()->field_value_by_offset(offset_con, false));
2733           return true;
2734         }
2735       }
2736     }
2737 
2738     if (base->is_InlineType()) {
2739       assert(!is_store, "Cannot store into a non-larval value object");
2740       base = base->as_InlineType()->buffer(this, true);
2741     }
2742     ptr = basic_plus_adr(base, ConvL2X(offset));
2743   } else if (base_type->isa_aryptr()) {
2744     decorators |= IS_ARRAY;
2745     if (layout == LayoutKind::REFERENCE) {
2746       if (!base_type->is_aryptr()->is_not_flat()) {
2747         const TypeAryPtr* array_type = base_type->is_aryptr()->cast_to_not_flat();
2748         Node* new_base = _gvn.transform(new CastPPNode(control(), base, array_type, ConstraintCastNode::DependencyType::NonFloatingNarrowing));
2749         replace_in_map(base, new_base);
2750         base = new_base;
2751       }
2752       ptr = basic_plus_adr(base, ConvL2X(offset));
2753     } else {
2754       if (UseArrayFlattening) {
2755         // Flat array must have an exact type
2756         bool is_null_free = !LayoutKindHelper::is_nullable_flat(layout);
2757         bool is_atomic = LayoutKindHelper::is_atomic_flat(layout);
2758         Node* new_base = cast_to_flat_array_exact(base, value_klass, is_null_free, is_atomic);
2759         replace_in_map(base, new_base);
2760         base = new_base;
2761         ptr = basic_plus_adr(base, ConvL2X(offset));
2762         const TypeAryPtr* ptr_type = _gvn.type(ptr)->is_aryptr();
2763         if (ptr_type->field_offset().get() != 0) {
2764           ptr = _gvn.transform(new CastPPNode(control(), ptr, ptr_type->with_field_offset(0), ConstraintCastNode::DependencyType::NonFloatingNarrowing));
2765         }
2766       } else {
2767         uncommon_trap(Deoptimization::Reason_intrinsic,
2768                       Deoptimization::Action_none);
2769         return true;
2770       }
2771     }
2772   } else {
2773     decorators |= C2_MISMATCHED;
2774     ptr = basic_plus_adr(base, ConvL2X(offset));
2775   }
2776 
2777   if (is_store) {
2778     Node* value = argument(6);
2779     const Type* value_type = _gvn.type(value);
2780     if (!value_type->is_inlinetypeptr()) {
2781       value_type = Type::get_const_type(value_klass)->filter_speculative(value_type);
2782       Node* new_value = _gvn.transform(new CastPPNode(control(), value, value_type, ConstraintCastNode::DependencyType::NonFloatingNarrowing));
2783       new_value = InlineTypeNode::make_from_oop(this, new_value, value_klass);
2784       replace_in_map(value, new_value);
2785       value = new_value;
2786     }
2787 
2788     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());
2789     if (layout == LayoutKind::REFERENCE) {
2790       const TypePtr* ptr_type = (decorators & C2_MISMATCHED) != 0 ? TypeRawPtr::BOTTOM : _gvn.type(ptr)->is_ptr();
2791       access_store_at(base, ptr, ptr_type, value, value_type, T_OBJECT, decorators);
2792     } else {
2793       bool atomic = LayoutKindHelper::is_atomic_flat(layout);
2794       bool null_free = !LayoutKindHelper::is_nullable_flat(layout);
2795       value->as_InlineType()->store_flat(this, base, ptr, atomic, immutable_memory, null_free, decorators);
2796     }
2797 
2798     return true;
2799   } else {
2800     decorators |= (C2_CONTROL_DEPENDENT_LOAD | C2_UNKNOWN_CONTROL_LOAD);
2801     InlineTypeNode* result;
2802     if (layout == LayoutKind::REFERENCE) {
2803       const TypePtr* ptr_type = (decorators & C2_MISMATCHED) != 0 ? TypeRawPtr::BOTTOM : _gvn.type(ptr)->is_ptr();
2804       Node* oop = access_load_at(base, ptr, ptr_type, Type::get_const_type(value_klass), T_OBJECT, decorators);
2805       result = InlineTypeNode::make_from_oop(this, oop, value_klass);
2806     } else {
2807       bool atomic = LayoutKindHelper::is_atomic_flat(layout);
2808       bool null_free = !LayoutKindHelper::is_nullable_flat(layout);
2809       result = InlineTypeNode::make_from_flat(this, value_klass, base, ptr, atomic, immutable_memory, null_free, decorators);
2810     }
2811 
2812     set_result(result);
2813     return true;
2814   }
2815 }
2816 
2817 //----------------------------inline_unsafe_load_store----------------------------
2818 // This method serves a couple of different customers (depending on LoadStoreKind):
2819 //
2820 // LS_cmp_swap:
2821 //
2822 //   boolean compareAndSetReference(Object o, long offset, Object expected, Object x);
2823 //   boolean compareAndSetInt(   Object o, long offset, int    expected, int    x);
2824 //   boolean compareAndSetLong(  Object o, long offset, long   expected, long   x);
2825 //
2826 // LS_cmp_swap_weak:
2827 //
2828 //   boolean weakCompareAndSetReference(       Object o, long offset, Object expected, Object x);
2829 //   boolean weakCompareAndSetReferencePlain(  Object o, long offset, Object expected, Object x);
2830 //   boolean weakCompareAndSetReferenceAcquire(Object o, long offset, Object expected, Object x);
2831 //   boolean weakCompareAndSetReferenceRelease(Object o, long offset, Object expected, Object x);
2832 //
2833 //   boolean weakCompareAndSetInt(          Object o, long offset, int    expected, int    x);
2834 //   boolean weakCompareAndSetIntPlain(     Object o, long offset, int    expected, int    x);
2835 //   boolean weakCompareAndSetIntAcquire(   Object o, long offset, int    expected, int    x);
2836 //   boolean weakCompareAndSetIntRelease(   Object o, long offset, int    expected, int    x);
2837 //
2838 //   boolean weakCompareAndSetLong(         Object o, long offset, long   expected, long   x);
2839 //   boolean weakCompareAndSetLongPlain(    Object o, long offset, long   expected, long   x);
2840 //   boolean weakCompareAndSetLongAcquire(  Object o, long offset, long   expected, long   x);
2841 //   boolean weakCompareAndSetLongRelease(  Object o, long offset, long   expected, long   x);
2842 //
2843 // LS_cmp_exchange:
2844 //
2845 //   Object compareAndExchangeReferenceVolatile(Object o, long offset, Object expected, Object x);
2846 //   Object compareAndExchangeReferenceAcquire( Object o, long offset, Object expected, Object x);
2847 //   Object compareAndExchangeReferenceRelease( Object o, long offset, Object expected, Object x);
2848 //
2849 //   Object compareAndExchangeIntVolatile(   Object o, long offset, Object expected, Object x);
2850 //   Object compareAndExchangeIntAcquire(    Object o, long offset, Object expected, Object x);
2851 //   Object compareAndExchangeIntRelease(    Object o, long offset, Object expected, Object x);
2852 //
2853 //   Object compareAndExchangeLongVolatile(  Object o, long offset, Object expected, Object x);
2854 //   Object compareAndExchangeLongAcquire(   Object o, long offset, Object expected, Object x);
2855 //   Object compareAndExchangeLongRelease(   Object o, long offset, Object expected, Object x);
2856 //
2857 // LS_get_add:
2858 //
2859 //   int  getAndAddInt( Object o, long offset, int  delta)
2860 //   long getAndAddLong(Object o, long offset, long delta)
2861 //
2862 // LS_get_set:
2863 //
2864 //   int    getAndSet(Object o, long offset, int    newValue)
2865 //   long   getAndSet(Object o, long offset, long   newValue)
2866 //   Object getAndSet(Object o, long offset, Object newValue)
2867 //
2868 bool LibraryCallKit::inline_unsafe_load_store(const BasicType type, const LoadStoreKind kind, const AccessKind access_kind) {
2869   // This basic scheme here is the same as inline_unsafe_access, but
2870   // differs in enough details that combining them would make the code
2871   // overly confusing.  (This is a true fact! I originally combined
2872   // them, but even I was confused by it!) As much code/comments as
2873   // possible are retained from inline_unsafe_access though to make
2874   // the correspondences clearer. - dl
2875 
2876   if (callee()->is_static())  return false;  // caller must have the capability!
2877 
2878   DecoratorSet decorators = C2_UNSAFE_ACCESS;
2879   decorators |= mo_decorator_for_access_kind(access_kind);
2880 
2881 #ifndef PRODUCT
2882   BasicType rtype;
2883   {
2884     ResourceMark rm;
2885     // Check the signatures.
2886     ciSignature* sig = callee()->signature();
2887     rtype = sig->return_type()->basic_type();
2888     switch(kind) {
2889       case LS_get_add:
2890       case LS_get_set: {
2891       // Check the signatures.
2892 #ifdef ASSERT
2893       assert(rtype == type, "get and set must return the expected type");
2894       assert(sig->count() == 3, "get and set has 3 arguments");
2895       assert(sig->type_at(0)->basic_type() == T_OBJECT, "get and set base is object");
2896       assert(sig->type_at(1)->basic_type() == T_LONG, "get and set offset is long");
2897       assert(sig->type_at(2)->basic_type() == type, "get and set must take expected type as new value/delta");
2898       assert(access_kind == Volatile, "mo is not passed to intrinsic nodes in current implementation");
2899 #endif // ASSERT
2900         break;
2901       }
2902       case LS_cmp_swap:
2903       case LS_cmp_swap_weak: {
2904       // Check the signatures.
2905 #ifdef ASSERT
2906       assert(rtype == T_BOOLEAN, "CAS must return boolean");
2907       assert(sig->count() == 4, "CAS has 4 arguments");
2908       assert(sig->type_at(0)->basic_type() == T_OBJECT, "CAS base is object");
2909       assert(sig->type_at(1)->basic_type() == T_LONG, "CAS offset is long");
2910 #endif // ASSERT
2911         break;
2912       }
2913       case LS_cmp_exchange: {
2914       // Check the signatures.
2915 #ifdef ASSERT
2916       assert(rtype == type, "CAS must return the expected type");
2917       assert(sig->count() == 4, "CAS has 4 arguments");
2918       assert(sig->type_at(0)->basic_type() == T_OBJECT, "CAS base is object");
2919       assert(sig->type_at(1)->basic_type() == T_LONG, "CAS offset is long");
2920 #endif // ASSERT
2921         break;
2922       }
2923       default:
2924         ShouldNotReachHere();
2925     }
2926   }
2927 #endif //PRODUCT
2928 
2929   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
2930 
2931   // Get arguments:
2932   Node* receiver = nullptr;
2933   Node* base     = nullptr;
2934   Node* offset   = nullptr;
2935   Node* oldval   = nullptr;
2936   Node* newval   = nullptr;
2937   switch(kind) {
2938     case LS_cmp_swap:
2939     case LS_cmp_swap_weak:
2940     case LS_cmp_exchange: {
2941       const bool two_slot_type = type2size[type] == 2;
2942       receiver = argument(0);  // type: oop
2943       base     = argument(1);  // type: oop
2944       offset   = argument(2);  // type: long
2945       oldval   = argument(4);  // type: oop, int, or long
2946       newval   = argument(two_slot_type ? 6 : 5);  // type: oop, int, or long
2947       break;
2948     }
2949     case LS_get_add:
2950     case LS_get_set: {
2951       receiver = argument(0);  // type: oop
2952       base     = argument(1);  // type: oop
2953       offset   = argument(2);  // type: long
2954       oldval   = nullptr;
2955       newval   = argument(4);  // type: oop, int, or long
2956       break;
2957     }
2958     default:
2959       ShouldNotReachHere();
2960   }
2961 
2962   // Build field offset expression.
2963   // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
2964   // to be plain byte offsets, which are also the same as those accepted
2965   // by oopDesc::field_addr.
2966   assert(Unsafe_field_offset_to_byte_offset(11) == 11, "fieldOffset must be byte-scaled");
2967   // 32-bit machines ignore the high half of long offsets
2968   offset = ConvL2X(offset);
2969   // Save state and restore on bailout
2970   SavedState old_state(this);
2971   Node* adr = make_unsafe_address(base, offset,type, false);
2972   const TypePtr *adr_type = _gvn.type(adr)->isa_ptr();
2973 
2974   Compile::AliasType* alias_type = C->alias_type(adr_type);
2975   BasicType bt = alias_type->basic_type();
2976   if (bt != T_ILLEGAL &&
2977       (is_reference_type(bt) != (type == T_OBJECT))) {
2978     // Don't intrinsify mismatched object accesses.
2979     return false;
2980   }
2981 
2982   old_state.discard();
2983 
2984   // For CAS, unlike inline_unsafe_access, there seems no point in
2985   // trying to refine types. Just use the coarse types here.
2986   assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
2987   const Type *value_type = Type::get_const_basic_type(type);
2988 
2989   switch (kind) {
2990     case LS_get_set:
2991     case LS_cmp_exchange: {
2992       if (type == T_OBJECT) {
2993         const TypeOopPtr* tjp = sharpen_unsafe_type(alias_type, adr_type);
2994         if (tjp != nullptr) {
2995           value_type = tjp;
2996         }
2997       }
2998       break;
2999     }
3000     case LS_cmp_swap:
3001     case LS_cmp_swap_weak:
3002     case LS_get_add:
3003       break;
3004     default:
3005       ShouldNotReachHere();
3006   }
3007 
3008   // Null check receiver.
3009   receiver = null_check(receiver);
3010   if (stopped()) {
3011     return true;
3012   }
3013 
3014   int alias_idx = C->get_alias_index(adr_type);
3015 
3016   if (is_reference_type(type)) {
3017     decorators |= IN_HEAP | ON_UNKNOWN_OOP_REF;
3018 
3019     if (oldval != nullptr && oldval->is_InlineType()) {
3020       // Re-execute the unsafe access if allocation triggers deoptimization.
3021       PreserveReexecuteState preexecs(this);
3022       jvms()->set_should_reexecute(true);
3023       oldval = oldval->as_InlineType()->buffer(this)->get_oop();
3024     }
3025     if (newval != nullptr && newval->is_InlineType()) {
3026       // Re-execute the unsafe access if allocation triggers deoptimization.
3027       PreserveReexecuteState preexecs(this);
3028       jvms()->set_should_reexecute(true);
3029       newval = newval->as_InlineType()->buffer(this)->get_oop();
3030     }
3031 
3032     // Transformation of a value which could be null pointer (CastPP #null)
3033     // could be delayed during Parse (for example, in adjust_map_after_if()).
3034     // Execute transformation here to avoid barrier generation in such case.
3035     if (_gvn.type(newval) == TypePtr::NULL_PTR)
3036       newval = _gvn.makecon(TypePtr::NULL_PTR);
3037 
3038     if (oldval != nullptr && _gvn.type(oldval) == TypePtr::NULL_PTR) {
3039       // Refine the value to a null constant, when it is known to be null
3040       oldval = _gvn.makecon(TypePtr::NULL_PTR);
3041     }
3042   }
3043 
3044   Node* result = nullptr;
3045   switch (kind) {
3046     case LS_cmp_exchange: {
3047       result = access_atomic_cmpxchg_val_at(base, adr, adr_type, alias_idx,
3048                                             oldval, newval, value_type, type, decorators);
3049       break;
3050     }
3051     case LS_cmp_swap_weak:
3052       decorators |= C2_WEAK_CMPXCHG;
3053     case LS_cmp_swap: {
3054       result = access_atomic_cmpxchg_bool_at(base, adr, adr_type, alias_idx,
3055                                              oldval, newval, value_type, type, decorators);
3056       break;
3057     }
3058     case LS_get_set: {
3059       result = access_atomic_xchg_at(base, adr, adr_type, alias_idx,
3060                                      newval, value_type, type, decorators);
3061       break;
3062     }
3063     case LS_get_add: {
3064       result = access_atomic_add_at(base, adr, adr_type, alias_idx,
3065                                     newval, value_type, type, decorators);
3066       break;
3067     }
3068     default:
3069       ShouldNotReachHere();
3070   }
3071 
3072   assert(type2size[result->bottom_type()->basic_type()] == type2size[rtype], "result type should match");
3073   set_result(result);
3074   return true;
3075 }
3076 
3077 bool LibraryCallKit::inline_unsafe_fence(vmIntrinsics::ID id) {
3078   // Regardless of form, don't allow previous ld/st to move down,
3079   // then issue acquire, release, or volatile mem_bar.
3080   insert_mem_bar(Op_MemBarCPUOrder);
3081   switch(id) {
3082     case vmIntrinsics::_loadFence:
3083       insert_mem_bar(Op_LoadFence);
3084       return true;
3085     case vmIntrinsics::_storeFence:
3086       insert_mem_bar(Op_StoreFence);
3087       return true;
3088     case vmIntrinsics::_storeStoreFence:
3089       insert_mem_bar(Op_StoreStoreFence);
3090       return true;
3091     case vmIntrinsics::_fullFence:
3092       insert_mem_bar(Op_MemBarFull);
3093       return true;
3094     default:
3095       fatal_unexpected_iid(id);
3096       return false;
3097   }
3098 }
3099 
3100 // private native int arrayInstanceBaseOffset0(Object[] array);
3101 bool LibraryCallKit::inline_arrayInstanceBaseOffset() {
3102   Node* array = argument(1);
3103   Node* klass_node = load_object_klass(array);
3104 
3105   jint  layout_con = Klass::_lh_neutral_value;
3106   Node* layout_val = get_layout_helper(klass_node, layout_con);
3107   int   layout_is_con = (layout_val == nullptr);
3108 
3109   Node* header_size = nullptr;
3110   if (layout_is_con) {
3111     int hsize = Klass::layout_helper_header_size(layout_con);
3112     header_size = intcon(hsize);
3113   } else {
3114     Node* hss = intcon(Klass::_lh_header_size_shift);
3115     Node* hsm = intcon(Klass::_lh_header_size_mask);
3116     header_size = _gvn.transform(new URShiftINode(layout_val, hss));
3117     header_size = _gvn.transform(new AndINode(header_size, hsm));
3118   }
3119   set_result(header_size);
3120   return true;
3121 }
3122 
3123 // private native int arrayInstanceIndexScale0(Object[] array);
3124 bool LibraryCallKit::inline_arrayInstanceIndexScale() {
3125   Node* array = argument(1);
3126   Node* klass_node = load_object_klass(array);
3127 
3128   jint  layout_con = Klass::_lh_neutral_value;
3129   Node* layout_val = get_layout_helper(klass_node, layout_con);
3130   int   layout_is_con = (layout_val == nullptr);
3131 
3132   Node* element_size = nullptr;
3133   if (layout_is_con) {
3134     int log_element_size  = Klass::layout_helper_log2_element_size(layout_con);
3135     int elem_size = 1 << log_element_size;
3136     element_size = intcon(elem_size);
3137   } else {
3138     Node* ess = intcon(Klass::_lh_log2_element_size_shift);
3139     Node* esm = intcon(Klass::_lh_log2_element_size_mask);
3140     Node* log_element_size = _gvn.transform(new URShiftINode(layout_val, ess));
3141     log_element_size = _gvn.transform(new AndINode(log_element_size, esm));
3142     element_size = _gvn.transform(new LShiftINode(intcon(1), log_element_size));
3143   }
3144   set_result(element_size);
3145   return true;
3146 }
3147 
3148 // private native int arrayLayout0(Object[] array);
3149 bool LibraryCallKit::inline_arrayLayout() {
3150   RegionNode* region = new RegionNode(2);
3151   Node* phi = new PhiNode(region, TypeInt::POS);
3152 
3153   Node* array = argument(1);
3154   Node* klass_node = load_object_klass(array);
3155   generate_refArray_guard(klass_node, region);
3156   if (region->req() == 3) {
3157     phi->add_req(intcon((jint)LayoutKind::REFERENCE));
3158   }
3159 
3160   int layout_kind_offset = in_bytes(FlatArrayKlass::layout_kind_offset());
3161   Node* layout_kind_addr = basic_plus_adr(top(), klass_node, layout_kind_offset);
3162   Node* layout_kind = make_load(nullptr, layout_kind_addr, TypeInt::POS, T_INT, MemNode::unordered);
3163 
3164   region->init_req(1, control());
3165   phi->init_req(1, layout_kind);
3166 
3167   set_control(_gvn.transform(region));
3168   set_result(_gvn.transform(phi));
3169   return true;
3170 }
3171 
3172 // private native int[] getFieldMap0(Class <?> c);
3173 //   int offset = c._klass._acmp_maps_offset;
3174 //   return (int[])c.obj_field(offset);
3175 bool LibraryCallKit::inline_getFieldMap() {
3176   Node* mirror = argument(1);
3177   Node* klass = load_klass_from_mirror(mirror, false, nullptr, 0);
3178 
3179   int field_map_offset_offset = in_bytes(InstanceKlass::acmp_maps_offset_offset());
3180   Node* field_map_offset_addr = basic_plus_adr(top(), klass, field_map_offset_offset);
3181   Node* field_map_offset = make_load(nullptr, field_map_offset_addr, TypeInt::INT, T_INT, MemNode::unordered);
3182   field_map_offset = _gvn.transform(ConvI2L(field_map_offset));
3183 
3184   Node* map_addr = basic_plus_adr(mirror, field_map_offset);
3185   const TypeAryPtr* val_type = TypeAryPtr::INTS->cast_to_ptr_type(TypePtr::NotNull)->with_offset(0);
3186   // TODO 8350865 Remove this
3187   val_type = val_type->cast_to_not_flat(true)->cast_to_not_null_free(true);
3188   Node* map = access_load_at(mirror, map_addr, TypeAryPtr::INTS, val_type, T_ARRAY, IN_HEAP | MO_UNORDERED);
3189 
3190   set_result(map);
3191   return true;
3192 }
3193 
3194 bool LibraryCallKit::inline_onspinwait() {
3195   insert_mem_bar(Op_OnSpinWait);
3196   return true;
3197 }
3198 
3199 bool LibraryCallKit::klass_needs_init_guard(Node* kls) {
3200   if (!kls->is_Con()) {
3201     return true;
3202   }
3203   const TypeInstKlassPtr* klsptr = kls->bottom_type()->isa_instklassptr();
3204   if (klsptr == nullptr) {
3205     return true;
3206   }
3207   ciInstanceKlass* ik = klsptr->instance_klass();
3208   // don't need a guard for a klass that is already initialized
3209   return !ik->is_initialized();
3210 }
3211 
3212 //----------------------------inline_unsafe_writeback0-------------------------
3213 // public native void Unsafe.writeback0(long address)
3214 bool LibraryCallKit::inline_unsafe_writeback0() {
3215   if (!Matcher::has_match_rule(Op_CacheWB)) {
3216     return false;
3217   }
3218 #ifndef PRODUCT
3219   assert(Matcher::has_match_rule(Op_CacheWBPreSync), "found match rule for CacheWB but not CacheWBPreSync");
3220   assert(Matcher::has_match_rule(Op_CacheWBPostSync), "found match rule for CacheWB but not CacheWBPostSync");
3221   ciSignature* sig = callee()->signature();
3222   assert(sig->type_at(0)->basic_type() == T_LONG, "Unsafe_writeback0 address is long!");
3223 #endif
3224   null_check_receiver();  // null-check, then ignore
3225   Node *addr = argument(1);
3226   addr = new CastX2PNode(addr);
3227   addr = _gvn.transform(addr);
3228   Node *flush = new CacheWBNode(control(), memory(TypeRawPtr::BOTTOM), addr);
3229   flush = _gvn.transform(flush);
3230   set_memory(flush, TypeRawPtr::BOTTOM);
3231   return true;
3232 }
3233 
3234 //----------------------------inline_unsafe_writeback0-------------------------
3235 // public native void Unsafe.writeback0(long address)
3236 bool LibraryCallKit::inline_unsafe_writebackSync0(bool is_pre) {
3237   if (is_pre && !Matcher::has_match_rule(Op_CacheWBPreSync)) {
3238     return false;
3239   }
3240   if (!is_pre && !Matcher::has_match_rule(Op_CacheWBPostSync)) {
3241     return false;
3242   }
3243 #ifndef PRODUCT
3244   assert(Matcher::has_match_rule(Op_CacheWB),
3245          (is_pre ? "found match rule for CacheWBPreSync but not CacheWB"
3246                 : "found match rule for CacheWBPostSync but not CacheWB"));
3247 
3248 #endif
3249   null_check_receiver();  // null-check, then ignore
3250   Node *sync;
3251   if (is_pre) {
3252     sync = new CacheWBPreSyncNode(control(), memory(TypeRawPtr::BOTTOM));
3253   } else {
3254     sync = new CacheWBPostSyncNode(control(), memory(TypeRawPtr::BOTTOM));
3255   }
3256   sync = _gvn.transform(sync);
3257   set_memory(sync, TypeRawPtr::BOTTOM);
3258   return true;
3259 }
3260 
3261 //----------------------------inline_unsafe_allocate---------------------------
3262 // public native Object Unsafe.allocateInstance(Class<?> cls);
3263 bool LibraryCallKit::inline_unsafe_allocate() {
3264 
3265 #if INCLUDE_JVMTI
3266   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
3267     return false;
3268   }
3269 #endif //INCLUDE_JVMTI
3270 
3271   if (callee()->is_static())  return false;  // caller must have the capability!
3272 
3273   null_check_receiver();  // null-check, then ignore
3274   Node* cls = null_check(argument(1));
3275   if (stopped())  return true;
3276 
3277   Node* kls = load_klass_from_mirror(cls, false, nullptr, 0);
3278   kls = null_check(kls);
3279   if (stopped())  return true;  // argument was like int.class
3280 
3281 #if INCLUDE_JVMTI
3282     // Don't try to access new allocated obj in the intrinsic.
3283     // It causes perfomance issues even when jvmti event VmObjectAlloc is disabled.
3284     // Deoptimize and allocate in interpreter instead.
3285     Node* addr = makecon(TypeRawPtr::make((address) &JvmtiExport::_should_notify_object_alloc));
3286     Node* should_post_vm_object_alloc = make_load(this->control(), addr, TypeInt::INT, T_INT, MemNode::unordered);
3287     Node* chk = _gvn.transform(new CmpINode(should_post_vm_object_alloc, intcon(0)));
3288     Node* tst = _gvn.transform(new BoolNode(chk, BoolTest::eq));
3289     {
3290       BuildCutout unless(this, tst, PROB_MAX);
3291       uncommon_trap(Deoptimization::Reason_intrinsic,
3292                     Deoptimization::Action_make_not_entrant);
3293     }
3294     if (stopped()) {
3295       return true;
3296     }
3297 #endif //INCLUDE_JVMTI
3298 
3299   Node* test = nullptr;
3300   if (LibraryCallKit::klass_needs_init_guard(kls)) {
3301     // Note:  The argument might still be an illegal value like
3302     // Serializable.class or Object[].class.   The runtime will handle it.
3303     // But we must make an explicit check for initialization.
3304     Node* insp = off_heap_plus_addr(kls, in_bytes(InstanceKlass::init_state_offset()));
3305     // Use T_BOOLEAN for InstanceKlass::_init_state so the compiler
3306     // can generate code to load it as unsigned byte.
3307     Node* inst = make_load(nullptr, insp, TypeInt::UBYTE, T_BOOLEAN, MemNode::acquire);
3308     Node* bits = intcon(InstanceKlass::fully_initialized);
3309     test = _gvn.transform(new SubINode(inst, bits));
3310     // The 'test' is non-zero if we need to take a slow path.
3311   }
3312   Node* obj = new_instance(kls, test);
3313   set_result(obj);
3314   return true;
3315 }
3316 
3317 //------------------------inline_native_time_funcs--------------
3318 // inline code for System.currentTimeMillis() and System.nanoTime()
3319 // these have the same type and signature
3320 bool LibraryCallKit::inline_native_time_funcs(address funcAddr, const char* funcName) {
3321   const TypeFunc* tf = OptoRuntime::void_long_Type();
3322   const TypePtr* no_memory_effects = nullptr;
3323   Node* time = make_runtime_call(RC_LEAF, tf, funcAddr, funcName, no_memory_effects);
3324   Node* value = _gvn.transform(new ProjNode(time, TypeFunc::Parms+0));
3325 #ifdef ASSERT
3326   Node* value_top = _gvn.transform(new ProjNode(time, TypeFunc::Parms+1));
3327   assert(value_top == top(), "second value must be top");
3328 #endif
3329   set_result(value);
3330   return true;
3331 }
3332 
3333 //--------------------inline_native_vthread_start_transition--------------------
3334 // inline void startTransition(boolean is_mount);
3335 // inline void startFinalTransition();
3336 // Pseudocode of implementation:
3337 //
3338 // java_lang_Thread::set_is_in_vthread_transition(vthread, true);
3339 // carrier->set_is_in_vthread_transition(true);
3340 // OrderAccess::storeload();
3341 // int disable_requests = java_lang_Thread::vthread_transition_disable_count(vthread)
3342 //                        + global_vthread_transition_disable_count();
3343 // if (disable_requests > 0) {
3344 //   slow path: runtime call
3345 // }
3346 bool LibraryCallKit::inline_native_vthread_start_transition(address funcAddr, const char* funcName, bool is_final_transition) {
3347   Node* vt_oop = must_be_not_null(argument(0), true); // VirtualThread this argument
3348   IdealKit ideal(this);
3349 
3350   Node* thread = ideal.thread();
3351   Node* jt_addr = off_heap_plus_addr(thread, in_bytes(JavaThread::is_in_vthread_transition_offset()));
3352   Node* vt_addr = basic_plus_adr(vt_oop, java_lang_Thread::is_in_vthread_transition_offset());
3353   access_store_at(nullptr, jt_addr, _gvn.type(jt_addr)->is_ptr(), ideal.ConI(1), TypeInt::BOOL, T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
3354   access_store_at(nullptr, vt_addr, _gvn.type(vt_addr)->is_ptr(), ideal.ConI(1), TypeInt::BOOL, T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
3355   insert_mem_bar(Op_MemBarStoreLoad);
3356   ideal.sync_kit(this);
3357 
3358   Node* global_disable_addr = makecon(TypeRawPtr::make((address)MountUnmountDisabler::global_vthread_transition_disable_count_address()));
3359   Node* global_disable = ideal.load(ideal.ctrl(), global_disable_addr, TypeInt::INT, T_INT, Compile::AliasIdxRaw, true /*require_atomic_access*/);
3360   Node* vt_disable_addr = basic_plus_adr(vt_oop, java_lang_Thread::vthread_transition_disable_count_offset());
3361   const TypePtr* vt_disable_addr_t = _gvn.type(vt_disable_addr)->is_ptr();
3362   Node* vt_disable = ideal.load(ideal.ctrl(), vt_disable_addr, TypeInt::INT, T_INT, C->get_alias_index(vt_disable_addr_t), true /*require_atomic_access*/);
3363   Node* disabled = _gvn.transform(new AddINode(global_disable, vt_disable));
3364 
3365   ideal.if_then(disabled, BoolTest::ne, ideal.ConI(0)); {
3366     sync_kit(ideal);
3367     Node* is_mount = is_final_transition ? ideal.ConI(0) : argument(1);
3368     const TypeFunc* tf = OptoRuntime::vthread_transition_Type();
3369     make_runtime_call(RC_NO_LEAF, tf, funcAddr, funcName, TypePtr::BOTTOM, vt_oop, is_mount);
3370     ideal.sync_kit(this);
3371   }
3372   ideal.end_if();
3373 
3374   final_sync(ideal);
3375   return true;
3376 }
3377 
3378 bool LibraryCallKit::inline_native_vthread_end_transition(address funcAddr, const char* funcName, bool is_first_transition) {
3379   Node* vt_oop = must_be_not_null(argument(0), true); // VirtualThread this argument
3380   IdealKit ideal(this);
3381 
3382   Node* _notify_jvmti_addr = makecon(TypeRawPtr::make((address)MountUnmountDisabler::notify_jvmti_events_address()));
3383   Node* _notify_jvmti = ideal.load(ideal.ctrl(), _notify_jvmti_addr, TypeInt::BOOL, T_BOOLEAN, Compile::AliasIdxRaw);
3384 
3385   ideal.if_then(_notify_jvmti, BoolTest::eq, ideal.ConI(1)); {
3386     sync_kit(ideal);
3387     Node* is_mount = is_first_transition ? ideal.ConI(1) : argument(1);
3388     const TypeFunc* tf = OptoRuntime::vthread_transition_Type();
3389     make_runtime_call(RC_NO_LEAF, tf, funcAddr, funcName, TypePtr::BOTTOM, vt_oop, is_mount);
3390     ideal.sync_kit(this);
3391   } ideal.else_(); {
3392     Node* thread = ideal.thread();
3393     Node* jt_addr = off_heap_plus_addr(thread, in_bytes(JavaThread::is_in_vthread_transition_offset()));
3394     Node* vt_addr = basic_plus_adr(vt_oop, java_lang_Thread::is_in_vthread_transition_offset());
3395 
3396     sync_kit(ideal);
3397     access_store_at(nullptr, jt_addr, _gvn.type(jt_addr)->is_ptr(), ideal.ConI(0), TypeInt::BOOL, T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
3398     access_store_at(nullptr, vt_addr, _gvn.type(vt_addr)->is_ptr(), ideal.ConI(0), TypeInt::BOOL, T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
3399     ideal.sync_kit(this);
3400   } ideal.end_if();
3401 
3402   final_sync(ideal);
3403   return true;
3404 }
3405 
3406 #if INCLUDE_JVMTI
3407 
3408 // Always update the is_disable_suspend bit.
3409 bool LibraryCallKit::inline_native_notify_jvmti_sync() {
3410   if (!DoJVMTIVirtualThreadTransitions) {
3411     return true;
3412   }
3413   IdealKit ideal(this);
3414 
3415   {
3416     // unconditionally update the is_disable_suspend bit in current JavaThread
3417     Node* thread = ideal.thread();
3418     Node* arg = argument(0); // argument for notification
3419     Node* addr = off_heap_plus_addr(thread, in_bytes(JavaThread::is_disable_suspend_offset()));
3420     const TypePtr *addr_type = _gvn.type(addr)->isa_ptr();
3421 
3422     sync_kit(ideal);
3423     access_store_at(nullptr, addr, addr_type, arg, _gvn.type(arg), T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
3424     ideal.sync_kit(this);
3425   }
3426   final_sync(ideal);
3427 
3428   return true;
3429 }
3430 
3431 #endif // INCLUDE_JVMTI
3432 
3433 #ifdef JFR_HAVE_INTRINSICS
3434 
3435 /**
3436  * if oop->klass != null
3437  *   // normal class
3438  *   epoch = _epoch_state ? 2 : 1
3439  *   if oop->klass->trace_id & ((epoch << META_SHIFT) | epoch)) != epoch {
3440  *     ... // enter slow path when the klass is first recorded or the epoch of JFR shifts
3441  *   }
3442  *   id = oop->klass->trace_id >> TRACE_ID_SHIFT // normal class path
3443  * else
3444  *   // primitive class
3445  *   if oop->array_klass != null
3446  *     id = (oop->array_klass->trace_id >> TRACE_ID_SHIFT) + 1 // primitive class path
3447  *   else
3448  *     id = LAST_TYPE_ID + 1 // void class path
3449  *   if (!signaled)
3450  *     signaled = true
3451  */
3452 bool LibraryCallKit::inline_native_classID() {
3453   Node* cls = argument(0);
3454 
3455   IdealKit ideal(this);
3456 #define __ ideal.
3457   IdealVariable result(ideal); __ declarations_done();
3458   Node* kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(),
3459                                                  basic_plus_adr(cls, java_lang_Class::klass_offset()),
3460                                                  TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
3461 
3462 
3463   __ if_then(kls, BoolTest::ne, null()); {
3464     Node* kls_trace_id_addr = basic_plus_adr(kls, in_bytes(KLASS_TRACE_ID_OFFSET));
3465     Node* kls_trace_id_raw = ideal.load(ideal.ctrl(), kls_trace_id_addr,TypeLong::LONG, T_LONG, Compile::AliasIdxRaw);
3466 
3467     Node* epoch_address = makecon(TypeRawPtr::make(JfrIntrinsicSupport::epoch_address()));
3468     Node* epoch = ideal.load(ideal.ctrl(), epoch_address, TypeInt::BOOL, T_BOOLEAN, Compile::AliasIdxRaw);
3469     epoch = _gvn.transform(new LShiftLNode(longcon(1), epoch));
3470     Node* mask = _gvn.transform(new LShiftLNode(epoch, intcon(META_SHIFT)));
3471     mask = _gvn.transform(new OrLNode(mask, epoch));
3472     Node* kls_trace_id_raw_and_mask = _gvn.transform(new AndLNode(kls_trace_id_raw, mask));
3473 
3474     float unlikely  = PROB_UNLIKELY(0.999);
3475     __ if_then(kls_trace_id_raw_and_mask, BoolTest::ne, epoch, unlikely); {
3476       sync_kit(ideal);
3477       make_runtime_call(RC_LEAF,
3478                         OptoRuntime::class_id_load_barrier_Type(),
3479                         CAST_FROM_FN_PTR(address, JfrIntrinsicSupport::load_barrier),
3480                         "class id load barrier",
3481                         TypePtr::BOTTOM,
3482                         kls);
3483       ideal.sync_kit(this);
3484     } __ end_if();
3485 
3486     ideal.set(result,  _gvn.transform(new URShiftLNode(kls_trace_id_raw, ideal.ConI(TRACE_ID_SHIFT))));
3487   } __ else_(); {
3488     Node* array_kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(),
3489                                                    basic_plus_adr(cls, java_lang_Class::array_klass_offset()),
3490                                                    TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
3491     __ if_then(array_kls, BoolTest::ne, null()); {
3492       Node* array_kls_trace_id_addr = basic_plus_adr(array_kls, in_bytes(KLASS_TRACE_ID_OFFSET));
3493       Node* array_kls_trace_id_raw = ideal.load(ideal.ctrl(), array_kls_trace_id_addr, TypeLong::LONG, T_LONG, Compile::AliasIdxRaw);
3494       Node* array_kls_trace_id = _gvn.transform(new URShiftLNode(array_kls_trace_id_raw, ideal.ConI(TRACE_ID_SHIFT)));
3495       ideal.set(result, _gvn.transform(new AddLNode(array_kls_trace_id, longcon(1))));
3496     } __ else_(); {
3497       // void class case
3498       ideal.set(result, longcon(LAST_TYPE_ID + 1));
3499     } __ end_if();
3500 
3501     Node* signaled_flag_address = makecon(TypeRawPtr::make(JfrIntrinsicSupport::signal_address()));
3502     Node* signaled = ideal.load(ideal.ctrl(), signaled_flag_address, TypeInt::BOOL, T_BOOLEAN, Compile::AliasIdxRaw, true, MemNode::acquire);
3503     __ if_then(signaled, BoolTest::ne, ideal.ConI(1)); {
3504       ideal.store(ideal.ctrl(), signaled_flag_address, ideal.ConI(1), T_BOOLEAN, Compile::AliasIdxRaw, MemNode::release, true);
3505     } __ end_if();
3506   } __ end_if();
3507 
3508   final_sync(ideal);
3509   set_result(ideal.value(result));
3510 #undef __
3511   return true;
3512 }
3513 
3514 //------------------------inline_native_jvm_commit------------------
3515 bool LibraryCallKit::inline_native_jvm_commit() {
3516   enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
3517 
3518   // Save input memory and i_o state.
3519   Node* input_memory_state = reset_memory();
3520   set_all_memory(input_memory_state);
3521   Node* input_io_state = i_o();
3522 
3523   // TLS.
3524   Node* tls_ptr = _gvn.transform(new ThreadLocalNode());
3525   // Jfr java buffer.
3526   Node* java_buffer_offset = _gvn.transform(AddPNode::make_off_heap(tls_ptr, MakeConX(in_bytes(JAVA_BUFFER_OFFSET_JFR))));
3527   Node* java_buffer = _gvn.transform(new LoadPNode(control(), input_memory_state, java_buffer_offset, TypePtr::BOTTOM, TypeRawPtr::NOTNULL, MemNode::unordered));
3528   Node* java_buffer_pos_offset = _gvn.transform(AddPNode::make_off_heap(java_buffer, MakeConX(in_bytes(JFR_BUFFER_POS_OFFSET))));
3529 
3530   // Load the current value of the notified field in the JfrThreadLocal.
3531   Node* notified_offset = off_heap_plus_addr(tls_ptr, in_bytes(NOTIFY_OFFSET_JFR));
3532   Node* notified = make_load(control(), notified_offset, TypeInt::BOOL, T_BOOLEAN, MemNode::unordered);
3533 
3534   // Test for notification.
3535   Node* notified_cmp = _gvn.transform(new CmpINode(notified, _gvn.intcon(1)));
3536   Node* test_notified = _gvn.transform(new BoolNode(notified_cmp, BoolTest::eq));
3537   IfNode* iff_notified = create_and_map_if(control(), test_notified, PROB_MIN, COUNT_UNKNOWN);
3538 
3539   // True branch, is notified.
3540   Node* is_notified = _gvn.transform(new IfTrueNode(iff_notified));
3541   set_control(is_notified);
3542 
3543   // Reset notified state.
3544   store_to_memory(control(), notified_offset, _gvn.intcon(0), T_BOOLEAN, MemNode::unordered);
3545   Node* notified_reset_memory = reset_memory();
3546 
3547   // 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.
3548   Node* current_pos_X = _gvn.transform(new LoadXNode(control(), input_memory_state, java_buffer_pos_offset, TypeRawPtr::NOTNULL, TypeX_X, MemNode::unordered));
3549   // Convert the machine-word to a long.
3550   Node* current_pos = ConvX2L(current_pos_X);
3551 
3552   // False branch, not notified.
3553   Node* not_notified = _gvn.transform(new IfFalseNode(iff_notified));
3554   set_control(not_notified);
3555   set_all_memory(input_memory_state);
3556 
3557   // Arg is the next position as a long.
3558   Node* arg = argument(0);
3559   // Convert long to machine-word.
3560   Node* next_pos_X = ConvL2X(arg);
3561 
3562   // Store the next_position to the underlying jfr java buffer.
3563   store_to_memory(control(), java_buffer_pos_offset, next_pos_X, LP64_ONLY(T_LONG) NOT_LP64(T_INT), MemNode::release);
3564 
3565   Node* commit_memory = reset_memory();
3566   set_all_memory(commit_memory);
3567 
3568   // 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.
3569   Node* java_buffer_flags_offset = _gvn.transform(AddPNode::make_off_heap(java_buffer, MakeConX(in_bytes(JFR_BUFFER_FLAGS_OFFSET))));
3570   Node* flags = make_load(control(), java_buffer_flags_offset, TypeInt::UBYTE, T_BYTE, MemNode::unordered);
3571   Node* lease_constant = _gvn.intcon(4);
3572 
3573   // And flags with lease constant.
3574   Node* lease = _gvn.transform(new AndINode(flags, lease_constant));
3575 
3576   // Branch on lease to conditionalize returning the leased java buffer.
3577   Node* lease_cmp = _gvn.transform(new CmpINode(lease, lease_constant));
3578   Node* test_lease = _gvn.transform(new BoolNode(lease_cmp, BoolTest::eq));
3579   IfNode* iff_lease = create_and_map_if(control(), test_lease, PROB_MIN, COUNT_UNKNOWN);
3580 
3581   // False branch, not a lease.
3582   Node* not_lease = _gvn.transform(new IfFalseNode(iff_lease));
3583 
3584   // True branch, is lease.
3585   Node* is_lease = _gvn.transform(new IfTrueNode(iff_lease));
3586   set_control(is_lease);
3587 
3588   // Make a runtime call, which can safepoint, to return the leased buffer. This updates both the JfrThreadLocal and the Java event writer oop.
3589   Node* call_return_lease = make_runtime_call(RC_NO_LEAF,
3590                                               OptoRuntime::void_void_Type(),
3591                                               SharedRuntime::jfr_return_lease(),
3592                                               "return_lease", TypePtr::BOTTOM);
3593   Node* call_return_lease_control = _gvn.transform(new ProjNode(call_return_lease, TypeFunc::Control));
3594 
3595   RegionNode* lease_compare_rgn = new RegionNode(PATH_LIMIT);
3596   record_for_igvn(lease_compare_rgn);
3597   PhiNode* lease_compare_mem = new PhiNode(lease_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3598   record_for_igvn(lease_compare_mem);
3599   PhiNode* lease_compare_io = new PhiNode(lease_compare_rgn, Type::ABIO);
3600   record_for_igvn(lease_compare_io);
3601   PhiNode* lease_result_value = new PhiNode(lease_compare_rgn, TypeLong::LONG);
3602   record_for_igvn(lease_result_value);
3603 
3604   // Update control and phi nodes.
3605   lease_compare_rgn->init_req(_true_path, call_return_lease_control);
3606   lease_compare_rgn->init_req(_false_path, not_lease);
3607 
3608   lease_compare_mem->init_req(_true_path, reset_memory());
3609   lease_compare_mem->init_req(_false_path, commit_memory);
3610 
3611   lease_compare_io->init_req(_true_path, i_o());
3612   lease_compare_io->init_req(_false_path, input_io_state);
3613 
3614   lease_result_value->init_req(_true_path, _gvn.longcon(0)); // if the lease was returned, return 0L.
3615   lease_result_value->init_req(_false_path, arg); // if not lease, return new updated position.
3616 
3617   RegionNode* result_rgn = new RegionNode(PATH_LIMIT);
3618   PhiNode* result_mem = new PhiNode(result_rgn, Type::MEMORY, TypePtr::BOTTOM);
3619   PhiNode* result_io = new PhiNode(result_rgn, Type::ABIO);
3620   PhiNode* result_value = new PhiNode(result_rgn, TypeLong::LONG);
3621 
3622   // Update control and phi nodes.
3623   result_rgn->init_req(_true_path, is_notified);
3624   result_rgn->init_req(_false_path, _gvn.transform(lease_compare_rgn));
3625 
3626   result_mem->init_req(_true_path, notified_reset_memory);
3627   result_mem->init_req(_false_path, _gvn.transform(lease_compare_mem));
3628 
3629   result_io->init_req(_true_path, input_io_state);
3630   result_io->init_req(_false_path, _gvn.transform(lease_compare_io));
3631 
3632   result_value->init_req(_true_path, current_pos);
3633   result_value->init_req(_false_path, _gvn.transform(lease_result_value));
3634 
3635   // Set output state.
3636   set_control(_gvn.transform(result_rgn));
3637   set_all_memory(_gvn.transform(result_mem));
3638   set_i_o(_gvn.transform(result_io));
3639   set_result(result_rgn, result_value);
3640   return true;
3641 }
3642 
3643 /*
3644  * The intrinsic is a model of this pseudo-code:
3645  *
3646  * JfrThreadLocal* const tl = Thread::jfr_thread_local()
3647  * jobject h_event_writer = tl->java_event_writer();
3648  * if (h_event_writer == nullptr) {
3649  *   return nullptr;
3650  * }
3651  * oop threadObj = Thread::threadObj();
3652  * oop vthread = java_lang_Thread::vthread(threadObj);
3653  * traceid tid;
3654  * bool pinVirtualThread;
3655  * bool excluded;
3656  * if (vthread != threadObj) {  // i.e. current thread is virtual
3657  *   tid = java_lang_Thread::tid(vthread);
3658  *   u2 vthread_epoch_raw = java_lang_Thread::jfr_epoch(vthread);
3659  *   pinVirtualThread = VMContinuations;
3660  *   excluded = vthread_epoch_raw & excluded_mask;
3661  *   if (!excluded) {
3662  *     traceid current_epoch = JfrTraceIdEpoch::current_generation();
3663  *     u2 vthread_epoch = vthread_epoch_raw & epoch_mask;
3664  *     if (vthread_epoch != current_epoch) {
3665  *       write_checkpoint();
3666  *     }
3667  *   }
3668  * } else {
3669  *   tid = java_lang_Thread::tid(threadObj);
3670  *   u2 thread_epoch_raw = java_lang_Thread::jfr_epoch(threadObj);
3671  *   pinVirtualThread = false;
3672  *   excluded = thread_epoch_raw & excluded_mask;
3673  * }
3674  * oop event_writer = JNIHandles::resolve_non_null(h_event_writer);
3675  * traceid tid_in_event_writer = getField(event_writer, "threadID");
3676  * if (tid_in_event_writer != tid) {
3677  *   setField(event_writer, "pinVirtualThread", pinVirtualThread);
3678  *   setField(event_writer, "excluded", excluded);
3679  *   setField(event_writer, "threadID", tid);
3680  * }
3681  * return event_writer
3682  */
3683 bool LibraryCallKit::inline_native_getEventWriter() {
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   // The most significant bit of the u2 is used to denote thread exclusion
3692   Node* excluded_shift = _gvn.intcon(15);
3693   Node* excluded_mask = _gvn.intcon(1 << 15);
3694   // The epoch generation is the range [1-32767]
3695   Node* epoch_mask = _gvn.intcon(32767);
3696 
3697   // TLS
3698   Node* tls_ptr = _gvn.transform(new ThreadLocalNode());
3699 
3700   // Load the address of java event writer jobject handle from the jfr_thread_local structure.
3701   Node* jobj_ptr = off_heap_plus_addr(tls_ptr, in_bytes(THREAD_LOCAL_WRITER_OFFSET_JFR));
3702 
3703   // Load the eventwriter jobject handle.
3704   Node* jobj = make_load(control(), jobj_ptr, TypeRawPtr::BOTTOM, T_ADDRESS, MemNode::unordered);
3705 
3706   // Null check the jobject handle.
3707   Node* jobj_cmp_null = _gvn.transform(new CmpPNode(jobj, null()));
3708   Node* test_jobj_not_equal_null = _gvn.transform(new BoolNode(jobj_cmp_null, BoolTest::ne));
3709   IfNode* iff_jobj_not_equal_null = create_and_map_if(control(), test_jobj_not_equal_null, PROB_MAX, COUNT_UNKNOWN);
3710 
3711   // False path, jobj is null.
3712   Node* jobj_is_null = _gvn.transform(new IfFalseNode(iff_jobj_not_equal_null));
3713 
3714   // True path, jobj is not null.
3715   Node* jobj_is_not_null = _gvn.transform(new IfTrueNode(iff_jobj_not_equal_null));
3716 
3717   set_control(jobj_is_not_null);
3718 
3719   // Load the threadObj for the CarrierThread.
3720   Node* threadObj = generate_current_thread(tls_ptr);
3721 
3722   // Load the vthread.
3723   Node* vthread = generate_virtual_thread(tls_ptr);
3724 
3725   // If vthread != threadObj, this is a virtual thread.
3726   Node* vthread_cmp_threadObj = _gvn.transform(new CmpPNode(vthread, threadObj));
3727   Node* test_vthread_not_equal_threadObj = _gvn.transform(new BoolNode(vthread_cmp_threadObj, BoolTest::ne));
3728   IfNode* iff_vthread_not_equal_threadObj =
3729     create_and_map_if(jobj_is_not_null, test_vthread_not_equal_threadObj, PROB_FAIR, COUNT_UNKNOWN);
3730 
3731   // False branch, fallback to threadObj.
3732   Node* vthread_equal_threadObj = _gvn.transform(new IfFalseNode(iff_vthread_not_equal_threadObj));
3733   set_control(vthread_equal_threadObj);
3734 
3735   // Load the tid field from the vthread object.
3736   Node* thread_obj_tid = load_field_from_object(threadObj, "tid", "J");
3737 
3738   // Load the raw epoch value from the threadObj.
3739   Node* threadObj_epoch_offset = basic_plus_adr(threadObj, java_lang_Thread::jfr_epoch_offset());
3740   Node* threadObj_epoch_raw = access_load_at(threadObj, threadObj_epoch_offset,
3741                                              _gvn.type(threadObj_epoch_offset)->isa_ptr(),
3742                                              TypeInt::CHAR, T_CHAR,
3743                                              IN_HEAP | MO_UNORDERED | C2_MISMATCHED | C2_CONTROL_DEPENDENT_LOAD);
3744 
3745   // Mask off the excluded information from the epoch.
3746   Node * threadObj_is_excluded = _gvn.transform(new AndINode(threadObj_epoch_raw, excluded_mask));
3747 
3748   // True branch, this is a virtual thread.
3749   Node* vthread_not_equal_threadObj = _gvn.transform(new IfTrueNode(iff_vthread_not_equal_threadObj));
3750   set_control(vthread_not_equal_threadObj);
3751 
3752   // Load the tid field from the vthread object.
3753   Node* vthread_tid = load_field_from_object(vthread, "tid", "J");
3754 
3755   // Continuation support determines if a virtual thread should be pinned.
3756   Node* global_addr = makecon(TypeRawPtr::make((address)&VMContinuations));
3757   Node* continuation_support = make_load(control(), global_addr, TypeInt::BOOL, T_BOOLEAN, MemNode::unordered);
3758 
3759   // Load the raw epoch value from the vthread.
3760   Node* vthread_epoch_offset = basic_plus_adr(vthread, java_lang_Thread::jfr_epoch_offset());
3761   Node* vthread_epoch_raw = access_load_at(vthread, vthread_epoch_offset, _gvn.type(vthread_epoch_offset)->is_ptr(),
3762                                            TypeInt::CHAR, T_CHAR,
3763                                            IN_HEAP | MO_UNORDERED | C2_MISMATCHED | C2_CONTROL_DEPENDENT_LOAD);
3764 
3765   // Mask off the excluded information from the epoch.
3766   Node * vthread_is_excluded = _gvn.transform(new AndINode(vthread_epoch_raw, excluded_mask));
3767 
3768   // Branch on excluded to conditionalize updating the epoch for the virtual thread.
3769   Node* is_excluded_cmp = _gvn.transform(new CmpINode(vthread_is_excluded, excluded_mask));
3770   Node* test_not_excluded = _gvn.transform(new BoolNode(is_excluded_cmp, BoolTest::ne));
3771   IfNode* iff_not_excluded = create_and_map_if(control(), test_not_excluded, PROB_MAX, COUNT_UNKNOWN);
3772 
3773   // False branch, vthread is excluded, no need to write epoch info.
3774   Node* excluded = _gvn.transform(new IfFalseNode(iff_not_excluded));
3775 
3776   // True branch, vthread is included, update epoch info.
3777   Node* included = _gvn.transform(new IfTrueNode(iff_not_excluded));
3778   set_control(included);
3779 
3780   // Get epoch value.
3781   Node* epoch = _gvn.transform(new AndINode(vthread_epoch_raw, epoch_mask));
3782 
3783   // Load the current epoch generation. The value is unsigned 16-bit, so we type it as T_CHAR.
3784   Node* epoch_generation_address = makecon(TypeRawPtr::make(JfrIntrinsicSupport::epoch_generation_address()));
3785   Node* current_epoch_generation = make_load(control(), epoch_generation_address, TypeInt::CHAR, T_CHAR, MemNode::unordered);
3786 
3787   // Compare the epoch in the vthread to the current epoch generation.
3788   Node* const epoch_cmp = _gvn.transform(new CmpUNode(current_epoch_generation, epoch));
3789   Node* test_epoch_not_equal = _gvn.transform(new BoolNode(epoch_cmp, BoolTest::ne));
3790   IfNode* iff_epoch_not_equal = create_and_map_if(control(), test_epoch_not_equal, PROB_FAIR, COUNT_UNKNOWN);
3791 
3792   // False path, epoch is equal, checkpoint information is valid.
3793   Node* epoch_is_equal = _gvn.transform(new IfFalseNode(iff_epoch_not_equal));
3794 
3795   // True path, epoch is not equal, write a checkpoint for the vthread.
3796   Node* epoch_is_not_equal = _gvn.transform(new IfTrueNode(iff_epoch_not_equal));
3797 
3798   set_control(epoch_is_not_equal);
3799 
3800   // Make a runtime call, which can safepoint, to write a checkpoint for the vthread for this epoch.
3801   // The call also updates the native thread local thread id and the vthread with the current epoch.
3802   Node* call_write_checkpoint = make_runtime_call(RC_NO_LEAF,
3803                                                   OptoRuntime::jfr_write_checkpoint_Type(),
3804                                                   SharedRuntime::jfr_write_checkpoint(),
3805                                                   "write_checkpoint", TypePtr::BOTTOM);
3806   Node* call_write_checkpoint_control = _gvn.transform(new ProjNode(call_write_checkpoint, TypeFunc::Control));
3807 
3808   // vthread epoch != current epoch
3809   RegionNode* epoch_compare_rgn = new RegionNode(PATH_LIMIT);
3810   record_for_igvn(epoch_compare_rgn);
3811   PhiNode* epoch_compare_mem = new PhiNode(epoch_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3812   record_for_igvn(epoch_compare_mem);
3813   PhiNode* epoch_compare_io = new PhiNode(epoch_compare_rgn, Type::ABIO);
3814   record_for_igvn(epoch_compare_io);
3815 
3816   // Update control and phi nodes.
3817   epoch_compare_rgn->init_req(_true_path, call_write_checkpoint_control);
3818   epoch_compare_rgn->init_req(_false_path, epoch_is_equal);
3819   epoch_compare_mem->init_req(_true_path, reset_memory());
3820   epoch_compare_mem->init_req(_false_path, input_memory_state);
3821   epoch_compare_io->init_req(_true_path, i_o());
3822   epoch_compare_io->init_req(_false_path, input_io_state);
3823 
3824   // excluded != true
3825   RegionNode* exclude_compare_rgn = new RegionNode(PATH_LIMIT);
3826   record_for_igvn(exclude_compare_rgn);
3827   PhiNode* exclude_compare_mem = new PhiNode(exclude_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3828   record_for_igvn(exclude_compare_mem);
3829   PhiNode* exclude_compare_io = new PhiNode(exclude_compare_rgn, Type::ABIO);
3830   record_for_igvn(exclude_compare_io);
3831 
3832   // Update control and phi nodes.
3833   exclude_compare_rgn->init_req(_true_path, _gvn.transform(epoch_compare_rgn));
3834   exclude_compare_rgn->init_req(_false_path, excluded);
3835   exclude_compare_mem->init_req(_true_path, _gvn.transform(epoch_compare_mem));
3836   exclude_compare_mem->init_req(_false_path, input_memory_state);
3837   exclude_compare_io->init_req(_true_path, _gvn.transform(epoch_compare_io));
3838   exclude_compare_io->init_req(_false_path, input_io_state);
3839 
3840   // vthread != threadObj
3841   RegionNode* vthread_compare_rgn = new RegionNode(PATH_LIMIT);
3842   record_for_igvn(vthread_compare_rgn);
3843   PhiNode* vthread_compare_mem = new PhiNode(vthread_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3844   PhiNode* vthread_compare_io = new PhiNode(vthread_compare_rgn, Type::ABIO);
3845   record_for_igvn(vthread_compare_io);
3846   PhiNode* tid = new PhiNode(vthread_compare_rgn, TypeLong::LONG);
3847   record_for_igvn(tid);
3848   PhiNode* exclusion = new PhiNode(vthread_compare_rgn, TypeInt::CHAR);
3849   record_for_igvn(exclusion);
3850   PhiNode* pinVirtualThread = new PhiNode(vthread_compare_rgn, TypeInt::BOOL);
3851   record_for_igvn(pinVirtualThread);
3852 
3853   // Update control and phi nodes.
3854   vthread_compare_rgn->init_req(_true_path, _gvn.transform(exclude_compare_rgn));
3855   vthread_compare_rgn->init_req(_false_path, vthread_equal_threadObj);
3856   vthread_compare_mem->init_req(_true_path, _gvn.transform(exclude_compare_mem));
3857   vthread_compare_mem->init_req(_false_path, input_memory_state);
3858   vthread_compare_io->init_req(_true_path, _gvn.transform(exclude_compare_io));
3859   vthread_compare_io->init_req(_false_path, input_io_state);
3860   tid->init_req(_true_path, vthread_tid);
3861   tid->init_req(_false_path, thread_obj_tid);
3862   exclusion->init_req(_true_path, vthread_is_excluded);
3863   exclusion->init_req(_false_path, threadObj_is_excluded);
3864   pinVirtualThread->init_req(_true_path, continuation_support);
3865   pinVirtualThread->init_req(_false_path, _gvn.intcon(0));
3866 
3867   // Update branch state.
3868   set_control(_gvn.transform(vthread_compare_rgn));
3869   set_all_memory(_gvn.transform(vthread_compare_mem));
3870   set_i_o(_gvn.transform(vthread_compare_io));
3871 
3872   // Load the event writer oop by dereferencing the jobject handle.
3873   ciKlass* klass_EventWriter = env()->find_system_klass(ciSymbol::make("jdk/jfr/internal/event/EventWriter"));
3874   assert(klass_EventWriter->is_loaded(), "invariant");
3875   ciInstanceKlass* const instklass_EventWriter = klass_EventWriter->as_instance_klass();
3876   const TypeKlassPtr* const aklass = TypeKlassPtr::make(instklass_EventWriter);
3877   const TypeOopPtr* const xtype = aklass->as_instance_type();
3878   Node* jobj_untagged = _gvn.transform(AddPNode::make_off_heap(jobj, _gvn.MakeConX(-JNIHandles::TypeTag::global)));
3879   Node* event_writer = access_load(jobj_untagged, xtype, T_OBJECT, IN_NATIVE | C2_CONTROL_DEPENDENT_LOAD);
3880 
3881   // Load the current thread id from the event writer object.
3882   Node* const event_writer_tid = load_field_from_object(event_writer, "threadID", "J");
3883   // Get the field offset to, conditionally, store an updated tid value later.
3884   Node* const event_writer_tid_field = field_address_from_object(event_writer, "threadID", "J", false);
3885   // Get the field offset to, conditionally, store an updated exclusion value later.
3886   Node* const event_writer_excluded_field = field_address_from_object(event_writer, "excluded", "Z", false);
3887   // Get the field offset to, conditionally, store an updated pinVirtualThread value later.
3888   Node* const event_writer_pin_field = field_address_from_object(event_writer, "pinVirtualThread", "Z", false);
3889 
3890   RegionNode* event_writer_tid_compare_rgn = new RegionNode(PATH_LIMIT);
3891   record_for_igvn(event_writer_tid_compare_rgn);
3892   PhiNode* event_writer_tid_compare_mem = new PhiNode(event_writer_tid_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3893   record_for_igvn(event_writer_tid_compare_mem);
3894   PhiNode* event_writer_tid_compare_io = new PhiNode(event_writer_tid_compare_rgn, Type::ABIO);
3895   record_for_igvn(event_writer_tid_compare_io);
3896 
3897   // Compare the current tid from the thread object to what is currently stored in the event writer object.
3898   Node* const tid_cmp = _gvn.transform(new CmpLNode(event_writer_tid, _gvn.transform(tid)));
3899   Node* test_tid_not_equal = _gvn.transform(new BoolNode(tid_cmp, BoolTest::ne));
3900   IfNode* iff_tid_not_equal = create_and_map_if(_gvn.transform(vthread_compare_rgn), test_tid_not_equal, PROB_FAIR, COUNT_UNKNOWN);
3901 
3902   // False path, tids are the same.
3903   Node* tid_is_equal = _gvn.transform(new IfFalseNode(iff_tid_not_equal));
3904 
3905   // True path, tid is not equal, need to update the tid in the event writer.
3906   Node* tid_is_not_equal = _gvn.transform(new IfTrueNode(iff_tid_not_equal));
3907   record_for_igvn(tid_is_not_equal);
3908 
3909   // Store the pin state to the event writer.
3910   store_to_memory(tid_is_not_equal, event_writer_pin_field, _gvn.transform(pinVirtualThread), T_BOOLEAN, MemNode::unordered);
3911 
3912   // Store the exclusion state to the event writer.
3913   Node* excluded_bool = _gvn.transform(new URShiftINode(_gvn.transform(exclusion), excluded_shift));
3914   store_to_memory(tid_is_not_equal, event_writer_excluded_field, excluded_bool, T_BOOLEAN, MemNode::unordered);
3915 
3916   // Store the tid to the event writer.
3917   store_to_memory(tid_is_not_equal, event_writer_tid_field, tid, T_LONG, MemNode::unordered);
3918 
3919   // Update control and phi nodes.
3920   event_writer_tid_compare_rgn->init_req(_true_path, tid_is_not_equal);
3921   event_writer_tid_compare_rgn->init_req(_false_path, tid_is_equal);
3922   event_writer_tid_compare_mem->init_req(_true_path, reset_memory());
3923   event_writer_tid_compare_mem->init_req(_false_path, _gvn.transform(vthread_compare_mem));
3924   event_writer_tid_compare_io->init_req(_true_path, i_o());
3925   event_writer_tid_compare_io->init_req(_false_path, _gvn.transform(vthread_compare_io));
3926 
3927   // Result of top level CFG, Memory, IO and Value.
3928   RegionNode* result_rgn = new RegionNode(PATH_LIMIT);
3929   PhiNode* result_mem = new PhiNode(result_rgn, Type::MEMORY, TypePtr::BOTTOM);
3930   PhiNode* result_io = new PhiNode(result_rgn, Type::ABIO);
3931   PhiNode* result_value = new PhiNode(result_rgn, TypeInstPtr::BOTTOM);
3932 
3933   // Result control.
3934   result_rgn->init_req(_true_path, _gvn.transform(event_writer_tid_compare_rgn));
3935   result_rgn->init_req(_false_path, jobj_is_null);
3936 
3937   // Result memory.
3938   result_mem->init_req(_true_path, _gvn.transform(event_writer_tid_compare_mem));
3939   result_mem->init_req(_false_path, input_memory_state);
3940 
3941   // Result IO.
3942   result_io->init_req(_true_path, _gvn.transform(event_writer_tid_compare_io));
3943   result_io->init_req(_false_path, input_io_state);
3944 
3945   // Result value.
3946   result_value->init_req(_true_path, event_writer); // return event writer oop
3947   result_value->init_req(_false_path, null()); // return null
3948 
3949   // Set output state.
3950   set_control(_gvn.transform(result_rgn));
3951   set_all_memory(_gvn.transform(result_mem));
3952   set_i_o(_gvn.transform(result_io));
3953   set_result(result_rgn, result_value);
3954   return true;
3955 }
3956 
3957 /*
3958  * The intrinsic is a model of this pseudo-code:
3959  *
3960  * JfrThreadLocal* const tl = thread->jfr_thread_local();
3961  * if (carrierThread != thread) { // is virtual thread
3962  *   const u2 vthread_epoch_raw = java_lang_Thread::jfr_epoch(thread);
3963  *   bool excluded = vthread_epoch_raw & excluded_mask;
3964  *   AtomicAccess::store(&tl->_contextual_tid, java_lang_Thread::tid(thread));
3965  *   AtomicAccess::store(&tl->_contextual_thread_excluded, is_excluded);
3966  *   if (!excluded) {
3967  *     const u2 vthread_epoch = vthread_epoch_raw & epoch_mask;
3968  *     AtomicAccess::store(&tl->_vthread_epoch, vthread_epoch);
3969  *   }
3970  *   AtomicAccess::release_store(&tl->_vthread, true);
3971  *   return;
3972  * }
3973  * AtomicAccess::release_store(&tl->_vthread, false);
3974  */
3975 void LibraryCallKit::extend_setCurrentThread(Node* jt, Node* thread) {
3976   enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
3977 
3978   Node* input_memory_state = reset_memory();
3979   set_all_memory(input_memory_state);
3980 
3981   // The most significant bit of the u2 is used to denote thread exclusion
3982   Node* excluded_mask = _gvn.intcon(1 << 15);
3983   // The epoch generation is the range [1-32767]
3984   Node* epoch_mask = _gvn.intcon(32767);
3985 
3986   Node* const carrierThread = generate_current_thread(jt);
3987   // If thread != carrierThread, this is a virtual thread.
3988   Node* thread_cmp_carrierThread = _gvn.transform(new CmpPNode(thread, carrierThread));
3989   Node* test_thread_not_equal_carrierThread = _gvn.transform(new BoolNode(thread_cmp_carrierThread, BoolTest::ne));
3990   IfNode* iff_thread_not_equal_carrierThread =
3991     create_and_map_if(control(), test_thread_not_equal_carrierThread, PROB_FAIR, COUNT_UNKNOWN);
3992 
3993   Node* vthread_offset = off_heap_plus_addr(jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_OFFSET_JFR));
3994 
3995   // False branch, is carrierThread.
3996   Node* thread_equal_carrierThread = _gvn.transform(new IfFalseNode(iff_thread_not_equal_carrierThread));
3997   // Store release
3998   Node* vthread_false_memory = store_to_memory(thread_equal_carrierThread, vthread_offset, _gvn.intcon(0), T_BOOLEAN, MemNode::release, true);
3999 
4000   set_all_memory(input_memory_state);
4001 
4002   // True branch, is virtual thread.
4003   Node* thread_not_equal_carrierThread = _gvn.transform(new IfTrueNode(iff_thread_not_equal_carrierThread));
4004   set_control(thread_not_equal_carrierThread);
4005 
4006   // Load the raw epoch value from the vthread.
4007   Node* epoch_offset = basic_plus_adr(thread, java_lang_Thread::jfr_epoch_offset());
4008   Node* epoch_raw = access_load_at(thread, epoch_offset, _gvn.type(epoch_offset)->is_ptr(), TypeInt::CHAR, T_CHAR,
4009                                    IN_HEAP | MO_UNORDERED | C2_MISMATCHED | C2_CONTROL_DEPENDENT_LOAD);
4010 
4011   // Mask off the excluded information from the epoch.
4012   Node * const is_excluded = _gvn.transform(new AndINode(epoch_raw, excluded_mask));
4013 
4014   // Load the tid field from the thread.
4015   Node* tid = load_field_from_object(thread, "tid", "J");
4016 
4017   // Store the vthread tid to the jfr thread local.
4018   Node* thread_id_offset = off_heap_plus_addr(jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_ID_OFFSET_JFR));
4019   Node* tid_memory = store_to_memory(control(), thread_id_offset, tid, T_LONG, MemNode::unordered, true);
4020 
4021   // Branch is_excluded to conditionalize updating the epoch .
4022   Node* excluded_cmp = _gvn.transform(new CmpINode(is_excluded, excluded_mask));
4023   Node* test_excluded = _gvn.transform(new BoolNode(excluded_cmp, BoolTest::eq));
4024   IfNode* iff_excluded = create_and_map_if(control(), test_excluded, PROB_MIN, COUNT_UNKNOWN);
4025 
4026   // True branch, vthread is excluded, no need to write epoch info.
4027   Node* excluded = _gvn.transform(new IfTrueNode(iff_excluded));
4028   set_control(excluded);
4029   Node* vthread_is_excluded = _gvn.intcon(1);
4030 
4031   // False branch, vthread is included, update epoch info.
4032   Node* included = _gvn.transform(new IfFalseNode(iff_excluded));
4033   set_control(included);
4034   Node* vthread_is_included = _gvn.intcon(0);
4035 
4036   // Get epoch value.
4037   Node* epoch = _gvn.transform(new AndINode(epoch_raw, epoch_mask));
4038 
4039   // Store the vthread epoch to the jfr thread local.
4040   Node* vthread_epoch_offset = off_heap_plus_addr(jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_EPOCH_OFFSET_JFR));
4041   Node* included_memory = store_to_memory(control(), vthread_epoch_offset, epoch, T_CHAR, MemNode::unordered, true);
4042 
4043   RegionNode* excluded_rgn = new RegionNode(PATH_LIMIT);
4044   record_for_igvn(excluded_rgn);
4045   PhiNode* excluded_mem = new PhiNode(excluded_rgn, Type::MEMORY, TypePtr::BOTTOM);
4046   record_for_igvn(excluded_mem);
4047   PhiNode* exclusion = new PhiNode(excluded_rgn, TypeInt::BOOL);
4048   record_for_igvn(exclusion);
4049 
4050   // Merge the excluded control and memory.
4051   excluded_rgn->init_req(_true_path, excluded);
4052   excluded_rgn->init_req(_false_path, included);
4053   excluded_mem->init_req(_true_path, tid_memory);
4054   excluded_mem->init_req(_false_path, included_memory);
4055   exclusion->init_req(_true_path, vthread_is_excluded);
4056   exclusion->init_req(_false_path, vthread_is_included);
4057 
4058   // Set intermediate state.
4059   set_control(_gvn.transform(excluded_rgn));
4060   set_all_memory(excluded_mem);
4061 
4062   // Store the vthread exclusion state to the jfr thread local.
4063   Node* thread_local_excluded_offset = off_heap_plus_addr(jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_EXCLUDED_OFFSET_JFR));
4064   store_to_memory(control(), thread_local_excluded_offset, _gvn.transform(exclusion), T_BOOLEAN, MemNode::unordered, true);
4065 
4066   // Store release
4067   Node * vthread_true_memory = store_to_memory(control(), vthread_offset, _gvn.intcon(1), T_BOOLEAN, MemNode::release, true);
4068 
4069   RegionNode* thread_compare_rgn = new RegionNode(PATH_LIMIT);
4070   record_for_igvn(thread_compare_rgn);
4071   PhiNode* thread_compare_mem = new PhiNode(thread_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
4072   record_for_igvn(thread_compare_mem);
4073   PhiNode* vthread = new PhiNode(thread_compare_rgn, TypeInt::BOOL);
4074   record_for_igvn(vthread);
4075 
4076   // Merge the thread_compare control and memory.
4077   thread_compare_rgn->init_req(_true_path, control());
4078   thread_compare_rgn->init_req(_false_path, thread_equal_carrierThread);
4079   thread_compare_mem->init_req(_true_path, vthread_true_memory);
4080   thread_compare_mem->init_req(_false_path, vthread_false_memory);
4081 
4082   // Set output state.
4083   set_control(_gvn.transform(thread_compare_rgn));
4084   set_all_memory(_gvn.transform(thread_compare_mem));
4085 }
4086 
4087 #endif // JFR_HAVE_INTRINSICS
4088 
4089 //------------------------inline_native_currentCarrierThread------------------
4090 bool LibraryCallKit::inline_native_currentCarrierThread() {
4091   Node* junk = nullptr;
4092   set_result(generate_current_thread(junk));
4093   return true;
4094 }
4095 
4096 //------------------------inline_native_currentThread------------------
4097 bool LibraryCallKit::inline_native_currentThread() {
4098   Node* junk = nullptr;
4099   set_result(generate_virtual_thread(junk));
4100   return true;
4101 }
4102 
4103 //------------------------inline_native_setVthread------------------
4104 bool LibraryCallKit::inline_native_setCurrentThread() {
4105   assert(C->method()->changes_current_thread(),
4106          "method changes current Thread but is not annotated ChangesCurrentThread");
4107   Node* arr = argument(1);
4108   Node* thread = _gvn.transform(new ThreadLocalNode());
4109   Node* p = off_heap_plus_addr(thread, in_bytes(JavaThread::vthread_offset()));
4110   Node* thread_obj_handle
4111     = make_load(nullptr, p, p->bottom_type()->is_ptr(), T_OBJECT, MemNode::unordered);
4112   const TypePtr *adr_type = _gvn.type(thread_obj_handle)->isa_ptr();
4113   access_store_at(nullptr, thread_obj_handle, adr_type, arr, _gvn.type(arr), T_OBJECT, IN_NATIVE | MO_UNORDERED);
4114 
4115   // Change the _monitor_owner_id of the JavaThread
4116   Node* tid = load_field_from_object(arr, "tid", "J");
4117   Node* monitor_owner_id_offset = off_heap_plus_addr(thread, in_bytes(JavaThread::monitor_owner_id_offset()));
4118   store_to_memory(control(), monitor_owner_id_offset, tid, T_LONG, MemNode::unordered, true);
4119 
4120   JFR_ONLY(extend_setCurrentThread(thread, arr);)
4121   return true;
4122 }
4123 
4124 const Type* LibraryCallKit::scopedValueCache_type() {
4125   ciKlass* objects_klass = ciObjArrayKlass::make(env()->Object_klass());
4126   const TypeOopPtr* etype = TypeOopPtr::make_from_klass(env()->Object_klass());
4127   const TypeAry* arr0 = TypeAry::make(etype, TypeInt::POS, /* stable= */ false, /* flat= */ false, /* not_flat= */ true, /* not_null_free= */ true, true);
4128 
4129   // Because we create the scopedValue cache lazily we have to make the
4130   // type of the result BotPTR.
4131   bool xk = etype->klass_is_exact();
4132   const Type* objects_type = TypeAryPtr::make(TypePtr::BotPTR, arr0, objects_klass, xk, TypeAryPtr::Offset(0));
4133   return objects_type;
4134 }
4135 
4136 Node* LibraryCallKit::scopedValueCache_helper() {
4137   Node* thread = _gvn.transform(new ThreadLocalNode());
4138   Node* p = off_heap_plus_addr(thread, in_bytes(JavaThread::scopedValueCache_offset()));
4139   // We cannot use immutable_memory() because we might flip onto a
4140   // different carrier thread, at which point we'll need to use that
4141   // carrier thread's cache.
4142   // return _gvn.transform(LoadNode::make(_gvn, nullptr, immutable_memory(), p, p->bottom_type()->is_ptr(),
4143   //       TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered));
4144   return make_load(nullptr, p, p->bottom_type()->is_ptr(), T_ADDRESS, MemNode::unordered);
4145 }
4146 
4147 //------------------------inline_native_scopedValueCache------------------
4148 bool LibraryCallKit::inline_native_scopedValueCache() {
4149   Node* cache_obj_handle = scopedValueCache_helper();
4150   const Type* objects_type = scopedValueCache_type();
4151   set_result(access_load(cache_obj_handle, objects_type, T_OBJECT, IN_NATIVE));
4152 
4153   return true;
4154 }
4155 
4156 //------------------------inline_native_setScopedValueCache------------------
4157 bool LibraryCallKit::inline_native_setScopedValueCache() {
4158   Node* arr = argument(0);
4159   Node* cache_obj_handle = scopedValueCache_helper();
4160   const Type* objects_type = scopedValueCache_type();
4161 
4162   const TypePtr *adr_type = _gvn.type(cache_obj_handle)->isa_ptr();
4163   access_store_at(nullptr, cache_obj_handle, adr_type, arr, objects_type, T_OBJECT, IN_NATIVE | MO_UNORDERED);
4164 
4165   return true;
4166 }
4167 
4168 //------------------------inline_native_Continuation_pin and unpin-----------
4169 
4170 // Shared implementation routine for both pin and unpin.
4171 bool LibraryCallKit::inline_native_Continuation_pinning(bool unpin) {
4172   enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
4173 
4174   // Save input memory.
4175   Node* input_memory_state = reset_memory();
4176   set_all_memory(input_memory_state);
4177 
4178   // TLS
4179   Node* tls_ptr = _gvn.transform(new ThreadLocalNode());
4180   Node* last_continuation_offset = off_heap_plus_addr(tls_ptr, in_bytes(JavaThread::cont_entry_offset()));
4181   Node* last_continuation = make_load(control(), last_continuation_offset, last_continuation_offset->get_ptr_type(), T_ADDRESS, MemNode::unordered);
4182 
4183   // Null check the last continuation object.
4184   Node* continuation_cmp_null = _gvn.transform(new CmpPNode(last_continuation, null()));
4185   Node* test_continuation_not_equal_null = _gvn.transform(new BoolNode(continuation_cmp_null, BoolTest::ne));
4186   IfNode* iff_continuation_not_equal_null = create_and_map_if(control(), test_continuation_not_equal_null, PROB_MAX, COUNT_UNKNOWN);
4187 
4188   // False path, last continuation is null.
4189   Node* continuation_is_null = _gvn.transform(new IfFalseNode(iff_continuation_not_equal_null));
4190 
4191   // True path, last continuation is not null.
4192   Node* continuation_is_not_null = _gvn.transform(new IfTrueNode(iff_continuation_not_equal_null));
4193 
4194   set_control(continuation_is_not_null);
4195 
4196   // Load the pin count from the last continuation.
4197   Node* pin_count_offset = off_heap_plus_addr(last_continuation, in_bytes(ContinuationEntry::pin_count_offset()));
4198   Node* pin_count = make_load(control(), pin_count_offset, TypeInt::INT, T_INT, MemNode::unordered);
4199 
4200   // The loaded pin count is compared against a context specific rhs for over/underflow detection.
4201   Node* pin_count_rhs;
4202   if (unpin) {
4203     pin_count_rhs = _gvn.intcon(0);
4204   } else {
4205     pin_count_rhs = _gvn.intcon(UINT32_MAX);
4206   }
4207   Node* pin_count_cmp = _gvn.transform(new CmpUNode(pin_count, pin_count_rhs));
4208   Node* test_pin_count_over_underflow = _gvn.transform(new BoolNode(pin_count_cmp, BoolTest::eq));
4209   IfNode* iff_pin_count_over_underflow = create_and_map_if(control(), test_pin_count_over_underflow, PROB_MIN, COUNT_UNKNOWN);
4210 
4211   // True branch, pin count over/underflow.
4212   Node* pin_count_over_underflow = _gvn.transform(new IfTrueNode(iff_pin_count_over_underflow));
4213   {
4214     // Trap (but not deoptimize (Action_none)) and continue in the interpreter
4215     // which will throw IllegalStateException for pin count over/underflow.
4216     // No memory changed so far - we can use memory create by reset_memory()
4217     // at the beginning of this intrinsic. No need to call reset_memory() again.
4218     PreserveJVMState pjvms(this);
4219     set_control(pin_count_over_underflow);
4220     uncommon_trap(Deoptimization::Reason_intrinsic,
4221                   Deoptimization::Action_none);
4222     assert(stopped(), "invariant");
4223   }
4224 
4225   // False branch, no pin count over/underflow. Increment or decrement pin count and store back.
4226   Node* valid_pin_count = _gvn.transform(new IfFalseNode(iff_pin_count_over_underflow));
4227   set_control(valid_pin_count);
4228 
4229   Node* next_pin_count;
4230   if (unpin) {
4231     next_pin_count = _gvn.transform(new SubINode(pin_count, _gvn.intcon(1)));
4232   } else {
4233     next_pin_count = _gvn.transform(new AddINode(pin_count, _gvn.intcon(1)));
4234   }
4235 
4236   store_to_memory(control(), pin_count_offset, next_pin_count, T_INT, MemNode::unordered);
4237 
4238   // Result of top level CFG and Memory.
4239   RegionNode* result_rgn = new RegionNode(PATH_LIMIT);
4240   record_for_igvn(result_rgn);
4241   PhiNode* result_mem = new PhiNode(result_rgn, Type::MEMORY, TypePtr::BOTTOM);
4242   record_for_igvn(result_mem);
4243 
4244   result_rgn->init_req(_true_path, valid_pin_count);
4245   result_rgn->init_req(_false_path, continuation_is_null);
4246   result_mem->init_req(_true_path, reset_memory());
4247   result_mem->init_req(_false_path, input_memory_state);
4248 
4249   // Set output state.
4250   set_control(_gvn.transform(result_rgn));
4251   set_all_memory(_gvn.transform(result_mem));
4252 
4253   return true;
4254 }
4255 
4256 //---------------------------load_mirror_from_klass----------------------------
4257 // Given a klass oop, load its java mirror (a java.lang.Class oop).
4258 Node* LibraryCallKit::load_mirror_from_klass(Node* klass) {
4259   Node* p = off_heap_plus_addr(klass, in_bytes(Klass::java_mirror_offset()));
4260   Node* load = make_load(nullptr, p, TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered);
4261   // mirror = ((OopHandle)mirror)->resolve();
4262   return access_load(load, TypeInstPtr::MIRROR, T_OBJECT, IN_NATIVE);
4263 }
4264 
4265 //-----------------------load_klass_from_mirror_common-------------------------
4266 // Given a java mirror (a java.lang.Class oop), load its corresponding klass oop.
4267 // Test the klass oop for null (signifying a primitive Class like Integer.TYPE),
4268 // and branch to the given path on the region.
4269 // If never_see_null, take an uncommon trap on null, so we can optimistically
4270 // compile for the non-null case.
4271 // If the region is null, force never_see_null = true.
4272 Node* LibraryCallKit::load_klass_from_mirror_common(Node* mirror,
4273                                                     bool never_see_null,
4274                                                     RegionNode* region,
4275                                                     int null_path,
4276                                                     int offset) {
4277   if (region == nullptr)  never_see_null = true;
4278   Node* p = basic_plus_adr(mirror, offset);
4279   const TypeKlassPtr*  kls_type = TypeInstKlassPtr::OBJECT_OR_NULL;
4280   Node* kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), p, TypeRawPtr::BOTTOM, kls_type));
4281   Node* null_ctl = top();
4282   kls = null_check_oop(kls, &null_ctl, never_see_null);
4283   if (region != nullptr) {
4284     // Set region->in(null_path) if the mirror is a primitive (e.g, int.class).
4285     region->init_req(null_path, null_ctl);
4286   } else {
4287     assert(null_ctl == top(), "no loose ends");
4288   }
4289   return kls;
4290 }
4291 
4292 //--------------------(inline_native_Class_query helpers)---------------------
4293 // Use this for JVM_ACC_INTERFACE.
4294 // Fall through if (mods & mask) == bits, take the guard otherwise.
4295 Node* LibraryCallKit::generate_klass_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region,
4296                                                  ByteSize offset, const Type* type, BasicType bt) {
4297   // Branch around if the given klass has the given modifier bit set.
4298   // Like generate_guard, adds a new path onto the region.
4299   Node* modp = off_heap_plus_addr(kls, in_bytes(offset));
4300   Node* mods = make_load(nullptr, modp, type, bt, MemNode::unordered);
4301   Node* mask = intcon(modifier_mask);
4302   Node* bits = intcon(modifier_bits);
4303   Node* mbit = _gvn.transform(new AndINode(mods, mask));
4304   Node* cmp  = _gvn.transform(new CmpINode(mbit, bits));
4305   Node* bol  = _gvn.transform(new BoolNode(cmp, BoolTest::ne));
4306   return generate_fair_guard(bol, region);
4307 }
4308 
4309 Node* LibraryCallKit::generate_interface_guard(Node* kls, RegionNode* region) {
4310   return generate_klass_flags_guard(kls, JVM_ACC_INTERFACE, 0, region,
4311                                     InstanceKlass::access_flags_offset(), TypeInt::CHAR, T_CHAR);
4312 }
4313 
4314 // Use this for testing if Klass is_hidden, has_finalizer, and is_cloneable_fast.
4315 Node* LibraryCallKit::generate_misc_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region) {
4316   return generate_klass_flags_guard(kls, modifier_mask, modifier_bits, region,
4317                                     Klass::misc_flags_offset(), TypeInt::UBYTE, T_BOOLEAN);
4318 }
4319 
4320 Node* LibraryCallKit::generate_hidden_class_guard(Node* kls, RegionNode* region) {
4321   return generate_misc_flags_guard(kls, KlassFlags::_misc_is_hidden_class, 0, region);
4322 }
4323 
4324 //-------------------------inline_native_Class_query-------------------
4325 bool LibraryCallKit::inline_native_Class_query(vmIntrinsics::ID id) {
4326   const Type* return_type = TypeInt::BOOL;
4327   Node* prim_return_value = top();  // what happens if it's a primitive class?
4328   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
4329   bool expect_prim = false;     // most of these guys expect to work on refs
4330 
4331   enum { _normal_path = 1, _prim_path = 2, PATH_LIMIT };
4332 
4333   Node* mirror = argument(0);
4334   Node* obj    = top();
4335 
4336   switch (id) {
4337   case vmIntrinsics::_isInstance:
4338     // nothing is an instance of a primitive type
4339     prim_return_value = intcon(0);
4340     obj = argument(1);
4341     break;
4342   case vmIntrinsics::_isHidden:
4343     prim_return_value = intcon(0);
4344     break;
4345   case vmIntrinsics::_getSuperclass:
4346     prim_return_value = null();
4347     return_type = TypeInstPtr::MIRROR->cast_to_ptr_type(TypePtr::BotPTR);
4348     break;
4349   default:
4350     fatal_unexpected_iid(id);
4351     break;
4352   }
4353 
4354   const TypeInstPtr* mirror_con = _gvn.type(mirror)->isa_instptr();
4355   if (mirror_con == nullptr)  return false;  // cannot happen?
4356 
4357 #ifndef PRODUCT
4358   if (C->print_intrinsics() || C->print_inlining()) {
4359     ciType* k = mirror_con->java_mirror_type();
4360     if (k) {
4361       tty->print("Inlining %s on constant Class ", vmIntrinsics::name_at(intrinsic_id()));
4362       k->print_name();
4363       tty->cr();
4364     }
4365   }
4366 #endif
4367 
4368   // Null-check the mirror, and the mirror's klass ptr (in case it is a primitive).
4369   RegionNode* region = new RegionNode(PATH_LIMIT);
4370   record_for_igvn(region);
4371   PhiNode* phi = new PhiNode(region, return_type);
4372 
4373   // The mirror will never be null of Reflection.getClassAccessFlags, however
4374   // it may be null for Class.isInstance or Class.getModifiers. Throw a NPE
4375   // if it is. See bug 4774291.
4376 
4377   // For Reflection.getClassAccessFlags(), the null check occurs in
4378   // the wrong place; see inline_unsafe_access(), above, for a similar
4379   // situation.
4380   mirror = null_check(mirror);
4381   // If mirror or obj is dead, only null-path is taken.
4382   if (stopped())  return true;
4383 
4384   if (expect_prim)  never_see_null = false;  // expect nulls (meaning prims)
4385 
4386   // Now load the mirror's klass metaobject, and null-check it.
4387   // Side-effects region with the control path if the klass is null.
4388   Node* kls = load_klass_from_mirror(mirror, never_see_null, region, _prim_path);
4389   // If kls is null, we have a primitive mirror.
4390   phi->init_req(_prim_path, prim_return_value);
4391   if (stopped()) { set_result(region, phi); return true; }
4392   bool safe_for_replace = (region->in(_prim_path) == top());
4393 
4394   Node* p;  // handy temp
4395   Node* null_ctl;
4396 
4397   // Now that we have the non-null klass, we can perform the real query.
4398   // For constant classes, the query will constant-fold in LoadNode::Value.
4399   Node* query_value = top();
4400   switch (id) {
4401   case vmIntrinsics::_isInstance:
4402     // nothing is an instance of a primitive type
4403     query_value = gen_instanceof(obj, kls, safe_for_replace);
4404     break;
4405 
4406   case vmIntrinsics::_isHidden:
4407     // (To verify this code sequence, check the asserts in JVM_IsHiddenClass.)
4408     if (generate_hidden_class_guard(kls, region) != nullptr)
4409       // A guard was added.  If the guard is taken, it was an hidden class.
4410       phi->add_req(intcon(1));
4411     // If we fall through, it's a plain class.
4412     query_value = intcon(0);
4413     break;
4414 
4415 
4416   case vmIntrinsics::_getSuperclass:
4417     // The rules here are somewhat unfortunate, but we can still do better
4418     // with random logic than with a JNI call.
4419     // Interfaces store null or Object as _super, but must report null.
4420     // Arrays store an intermediate super as _super, but must report Object.
4421     // Other types can report the actual _super.
4422     // (To verify this code sequence, check the asserts in JVM_IsInterface.)
4423     if (generate_array_guard(kls, region) != nullptr) {
4424       // A guard was added.  If the guard is taken, it was an array.
4425       phi->add_req(makecon(TypeInstPtr::make(env()->Object_klass()->java_mirror())));
4426     }
4427     // Check for interface after array since this checks AccessFlags offset into InstanceKlass.
4428     // In other words, we are accessing subtype-specific information, so we need to determine the subtype first.
4429     if (generate_interface_guard(kls, region) != nullptr) {
4430       // A guard was added.  If the guard is taken, it was an interface.
4431       phi->add_req(null());
4432     }
4433     // If we fall through, it's a plain class.  Get its _super.
4434     if (!stopped()) {
4435       p = basic_plus_adr(top(), kls, in_bytes(Klass::super_offset()));
4436       kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), p, TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
4437       null_ctl = top();
4438       kls = null_check_oop(kls, &null_ctl);
4439       if (null_ctl != top()) {
4440         // If the guard is taken, Object.superClass is null (both klass and mirror).
4441         region->add_req(null_ctl);
4442         phi   ->add_req(null());
4443       }
4444       if (!stopped()) {
4445         query_value = load_mirror_from_klass(kls);
4446       }
4447     }
4448     break;
4449 
4450   default:
4451     fatal_unexpected_iid(id);
4452     break;
4453   }
4454 
4455   // Fall-through is the normal case of a query to a real class.
4456   phi->init_req(1, query_value);
4457   region->init_req(1, control());
4458 
4459   C->set_has_split_ifs(true); // Has chance for split-if optimization
4460   set_result(region, phi);
4461   return true;
4462 }
4463 
4464 
4465 //-------------------------inline_Class_cast-------------------
4466 bool LibraryCallKit::inline_Class_cast() {
4467   Node* mirror = argument(0); // Class
4468   Node* obj    = argument(1);
4469   const TypeInstPtr* mirror_con = _gvn.type(mirror)->isa_instptr();
4470   if (mirror_con == nullptr) {
4471     return false;  // dead path (mirror->is_top()).
4472   }
4473   if (obj == nullptr || obj->is_top()) {
4474     return false;  // dead path
4475   }
4476   const TypeOopPtr* tp = _gvn.type(obj)->isa_oopptr();
4477 
4478   // First, see if Class.cast() can be folded statically.
4479   // java_mirror_type() returns non-null for compile-time Class constants.
4480   ciType* tm = mirror_con->java_mirror_type();
4481   if (tm != nullptr && tm->is_klass() &&
4482       tp != nullptr) {
4483     if (!tp->is_loaded()) {
4484       // Don't use intrinsic when class is not loaded.
4485       return false;
4486     } else {
4487       const TypeKlassPtr* tklass = TypeKlassPtr::make(tm->as_klass(), Type::trust_interfaces);
4488       int static_res = C->static_subtype_check(tklass, tp->as_klass_type());
4489       if (static_res == Compile::SSC_always_true) {
4490         // isInstance() is true - fold the code.
4491         set_result(obj);
4492         return true;
4493       } else if (static_res == Compile::SSC_always_false) {
4494         // Don't use intrinsic, have to throw ClassCastException.
4495         // If the reference is null, the non-intrinsic bytecode will
4496         // be optimized appropriately.
4497         return false;
4498       }
4499     }
4500   }
4501 
4502   // Bailout intrinsic and do normal inlining if exception path is frequent.
4503   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
4504     return false;
4505   }
4506 
4507   // Generate dynamic checks.
4508   // Class.cast() is java implementation of _checkcast bytecode.
4509   // Do checkcast (Parse::do_checkcast()) optimizations here.
4510 
4511   mirror = null_check(mirror);
4512   // If mirror is dead, only null-path is taken.
4513   if (stopped()) {
4514     return true;
4515   }
4516 
4517   // Not-subtype or the mirror's klass ptr is nullptr (in case it is a primitive).
4518   enum { _bad_type_path = 1, _prim_path = 2, _npe_path = 3, PATH_LIMIT };
4519   RegionNode* region = new RegionNode(PATH_LIMIT);
4520   record_for_igvn(region);
4521 
4522   // Now load the mirror's klass metaobject, and null-check it.
4523   // If kls is null, we have a primitive mirror and
4524   // nothing is an instance of a primitive type.
4525   Node* kls = load_klass_from_mirror(mirror, false, region, _prim_path);
4526 
4527   Node* res = top();
4528   Node* io = i_o();
4529   Node* mem = merged_memory();
4530   SafePointNode* new_cast_failure_map = nullptr;
4531 
4532   if (!stopped()) {
4533 
4534     Node* bad_type_ctrl = top();
4535     // Do checkcast optimizations.
4536     res = gen_checkcast(obj, kls, &bad_type_ctrl, &new_cast_failure_map);
4537     region->init_req(_bad_type_path, bad_type_ctrl);
4538   }
4539   if (region->in(_prim_path) != top() ||
4540       region->in(_bad_type_path) != top() ||
4541       region->in(_npe_path) != top()) {
4542     // Let Interpreter throw ClassCastException.
4543     PreserveJVMState pjvms(this);
4544     if (new_cast_failure_map != nullptr) {
4545       // The current map on the success path could have been modified. Use the dedicated failure path map.
4546       set_map(new_cast_failure_map);
4547     }
4548     set_control(_gvn.transform(region));
4549     // Set IO and memory because gen_checkcast may override them when buffering inline types
4550     set_i_o(io);
4551     set_all_memory(mem);
4552     uncommon_trap(Deoptimization::Reason_intrinsic,
4553                   Deoptimization::Action_maybe_recompile);
4554   }
4555   if (!stopped()) {
4556     set_result(res);
4557   }
4558   return true;
4559 }
4560 
4561 
4562 //--------------------------inline_native_subtype_check------------------------
4563 // This intrinsic takes the JNI calls out of the heart of
4564 // UnsafeFieldAccessorImpl.set, which improves Field.set, readObject, etc.
4565 bool LibraryCallKit::inline_native_subtype_check() {
4566   // Pull both arguments off the stack.
4567   Node* args[2];                // two java.lang.Class mirrors: superc, subc
4568   args[0] = argument(0);
4569   args[1] = argument(1);
4570   Node* klasses[2];             // corresponding Klasses: superk, subk
4571   klasses[0] = klasses[1] = top();
4572 
4573   enum {
4574     // A full decision tree on {superc is prim, subc is prim}:
4575     _prim_0_path = 1,           // {P,N} => false
4576                                 // {P,P} & superc!=subc => false
4577     _prim_same_path,            // {P,P} & superc==subc => true
4578     _prim_1_path,               // {N,P} => false
4579     _ref_subtype_path,          // {N,N} & subtype check wins => true
4580     _both_ref_path,             // {N,N} & subtype check loses => false
4581     PATH_LIMIT
4582   };
4583 
4584   RegionNode* region = new RegionNode(PATH_LIMIT);
4585   RegionNode* prim_region = new RegionNode(2);
4586   Node*       phi    = new PhiNode(region, TypeInt::BOOL);
4587   record_for_igvn(region);
4588   record_for_igvn(prim_region);
4589 
4590   const TypePtr* adr_type = TypeRawPtr::BOTTOM;   // memory type of loads
4591   const TypeKlassPtr* kls_type = TypeInstKlassPtr::OBJECT_OR_NULL;
4592   int class_klass_offset = java_lang_Class::klass_offset();
4593 
4594   // First null-check both mirrors and load each mirror's klass metaobject.
4595   int which_arg;
4596   for (which_arg = 0; which_arg <= 1; which_arg++) {
4597     Node* arg = args[which_arg];
4598     arg = null_check(arg);
4599     if (stopped())  break;
4600     args[which_arg] = arg;
4601 
4602     Node* p = basic_plus_adr(arg, class_klass_offset);
4603     Node* kls = LoadKlassNode::make(_gvn, immutable_memory(), p, adr_type, kls_type);
4604     klasses[which_arg] = _gvn.transform(kls);
4605   }
4606 
4607   // Having loaded both klasses, test each for null.
4608   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
4609   for (which_arg = 0; which_arg <= 1; which_arg++) {
4610     Node* kls = klasses[which_arg];
4611     Node* null_ctl = top();
4612     kls = null_check_oop(kls, &null_ctl, never_see_null);
4613     if (which_arg == 0) {
4614       prim_region->init_req(1, null_ctl);
4615     } else {
4616       region->init_req(_prim_1_path, null_ctl);
4617     }
4618     if (stopped())  break;
4619     klasses[which_arg] = kls;
4620   }
4621 
4622   if (!stopped()) {
4623     // now we have two reference types, in klasses[0..1]
4624     Node* subk   = klasses[1];  // the argument to isAssignableFrom
4625     Node* superk = klasses[0];  // the receiver
4626     region->set_req(_both_ref_path, gen_subtype_check(subk, superk));
4627     region->set_req(_ref_subtype_path, control());
4628   }
4629 
4630   // If both operands are primitive (both klasses null), then
4631   // we must return true when they are identical primitives.
4632   // It is convenient to test this after the first null klass check.
4633   // This path is also used if superc is a value mirror.
4634   set_control(_gvn.transform(prim_region));
4635   if (!stopped()) {
4636     // Since superc is primitive, make a guard for the superc==subc case.
4637     Node* cmp_eq = _gvn.transform(new CmpPNode(args[0], args[1]));
4638     Node* bol_eq = _gvn.transform(new BoolNode(cmp_eq, BoolTest::eq));
4639     generate_fair_guard(bol_eq, region);
4640     if (region->req() == PATH_LIMIT+1) {
4641       // A guard was added.  If the added guard is taken, superc==subc.
4642       region->swap_edges(PATH_LIMIT, _prim_same_path);
4643       region->del_req(PATH_LIMIT);
4644     }
4645     region->set_req(_prim_0_path, control()); // Not equal after all.
4646   }
4647 
4648   // these are the only paths that produce 'true':
4649   phi->set_req(_prim_same_path,   intcon(1));
4650   phi->set_req(_ref_subtype_path, intcon(1));
4651 
4652   // pull together the cases:
4653   assert(region->req() == PATH_LIMIT, "sane region");
4654   for (uint i = 1; i < region->req(); i++) {
4655     Node* ctl = region->in(i);
4656     if (ctl == nullptr || ctl == top()) {
4657       region->set_req(i, top());
4658       phi   ->set_req(i, top());
4659     } else if (phi->in(i) == nullptr) {
4660       phi->set_req(i, intcon(0)); // all other paths produce 'false'
4661     }
4662   }
4663 
4664   set_control(_gvn.transform(region));
4665   set_result(_gvn.transform(phi));
4666   return true;
4667 }
4668 
4669 //---------------------generate_array_guard_common------------------------
4670 Node* LibraryCallKit::generate_array_guard_common(Node* kls, RegionNode* region, ArrayKind kind, Node** obj) {
4671 
4672   if (stopped()) {
4673     return nullptr;
4674   }
4675 
4676   // Like generate_guard, adds a new path onto the region.
4677   jint  layout_con = 0;
4678   Node* layout_val = get_layout_helper(kls, layout_con);
4679   if (layout_val == nullptr) {
4680     bool query = 0;
4681     switch(kind) {
4682       case RefArray:       query = Klass::layout_helper_is_refArray(layout_con); break;
4683       case NonRefArray:    query = !Klass::layout_helper_is_refArray(layout_con); break;
4684       case TypeArray:      query = Klass::layout_helper_is_typeArray(layout_con); break;
4685       case AnyArray:       query = Klass::layout_helper_is_array(layout_con); break;
4686       case NonArray:       query = !Klass::layout_helper_is_array(layout_con); break;
4687       default:
4688         ShouldNotReachHere();
4689     }
4690     if (!query) {
4691       return nullptr;                       // never a branch
4692     } else {                             // always a branch
4693       Node* always_branch = control();
4694       if (region != nullptr)
4695         region->add_req(always_branch);
4696       set_control(top());
4697       return always_branch;
4698     }
4699   }
4700   unsigned int value = 0;
4701   BoolTest::mask btest = BoolTest::illegal;
4702   switch(kind) {
4703     case RefArray:
4704     case NonRefArray: {
4705       value = Klass::_lh_array_tag_ref_value;
4706       layout_val = _gvn.transform(new RShiftINode(layout_val, intcon(Klass::_lh_array_tag_shift)));
4707       btest = (kind == RefArray) ? BoolTest::eq : BoolTest::ne;
4708       break;
4709     }
4710     case TypeArray: {
4711       value = Klass::_lh_array_tag_type_value;
4712       layout_val = _gvn.transform(new RShiftINode(layout_val, intcon(Klass::_lh_array_tag_shift)));
4713       btest = BoolTest::eq;
4714       break;
4715     }
4716     case AnyArray:    value = Klass::_lh_neutral_value; btest = BoolTest::lt; break;
4717     case NonArray:    value = Klass::_lh_neutral_value; btest = BoolTest::gt; break;
4718     default:
4719       ShouldNotReachHere();
4720   }
4721   // Now test the correct condition.
4722   jint nval = (jint)value;
4723   Node* cmp = _gvn.transform(new CmpINode(layout_val, intcon(nval)));
4724   Node* bol = _gvn.transform(new BoolNode(cmp, btest));
4725   Node* ctrl = generate_fair_guard(bol, region);
4726   Node* is_array_ctrl = kind == NonArray ? control() : ctrl;
4727   if (obj != nullptr && is_array_ctrl != nullptr && is_array_ctrl != top()) {
4728     // Keep track of the fact that 'obj' is an array to prevent
4729     // array specific accesses from floating above the guard.
4730     *obj = _gvn.transform(new CheckCastPPNode(is_array_ctrl, *obj, TypeAryPtr::BOTTOM));
4731   }
4732   return ctrl;
4733 }
4734 
4735 // public static native Object[] ValueClass::newNullRestrictedAtomicArray(Class<?> componentType, int length, Object initVal);
4736 // public static native Object[] ValueClass::newNullRestrictedNonAtomicArray(Class<?> componentType, int length, Object initVal);
4737 // public static native Object[] ValueClass::newNullableAtomicArray(Class<?> componentType, int length);
4738 bool LibraryCallKit::inline_newArray(bool null_free, bool atomic) {
4739   assert(null_free || atomic, "nullable implies atomic");
4740   Node* componentType = argument(0);
4741   Node* length = argument(1);
4742   Node* init_val = null_free ? argument(2) : nullptr;
4743 
4744   const TypeInstPtr* tp = _gvn.type(componentType)->isa_instptr();
4745   if (tp != nullptr) {
4746     ciInstanceKlass* ik = tp->instance_klass();
4747     if (ik == C->env()->Class_klass()) {
4748       ciType* t = tp->java_mirror_type();
4749       if (t != nullptr && t->is_inlinetype()) {
4750 
4751         ciArrayKlass* array_klass = ciArrayKlass::make(t, null_free, atomic, true);
4752         assert(array_klass->is_elem_null_free() == null_free, "inconsistency");
4753 
4754         // TOOD 8350865 ZGC needs card marks on initializing oop stores
4755         if (UseZGC && null_free && !array_klass->is_flat_array_klass()) {
4756           return false;
4757         }
4758 
4759         if (array_klass->is_loaded() && array_klass->element_klass()->as_inline_klass()->is_initialized()) {
4760           const TypeAryKlassPtr* array_klass_type = TypeAryKlassPtr::make(array_klass, Type::trust_interfaces);
4761           if (null_free) {
4762             if (init_val->is_InlineType()) {
4763               if (array_klass_type->is_flat() && init_val->as_InlineType()->is_all_zero(&gvn(), /* flat */ true)) {
4764                 // Zeroing is enough because the init value is the all-zero value
4765                 init_val = nullptr;
4766               } else {
4767                 init_val = init_val->as_InlineType()->buffer(this);
4768               }
4769             }
4770             // TODO 8350865 Should we add a check of the init_val type (maybe in debug only + halt)?
4771             // If we insert a checkcast here, we can be sure that init_val is an InlineTypeNode, so
4772             // when we folded a field load from an allocation (e.g. during escape analysis), we can
4773             // remove the check init_val->is_InlineType().
4774           }
4775           Node* obj = new_array(makecon(array_klass_type), length, 0, nullptr, false, init_val);
4776           const TypeAryPtr* arytype = gvn().type(obj)->is_aryptr();
4777           assert(arytype->is_null_free() == null_free, "inconsistency");
4778           assert(arytype->is_not_null_free() == !null_free, "inconsistency");
4779           set_result(obj);
4780           return true;
4781         }
4782       }
4783     }
4784   }
4785   return false;
4786 }
4787 
4788 // public static native boolean ValueClass::isFlatArray(Object array);
4789 // public static native boolean ValueClass::isNullRestrictedArray(Object array);
4790 // public static native boolean ValueClass::isAtomicArray(Object array);
4791 bool LibraryCallKit::inline_getArrayProperties(ArrayPropertiesCheck check) {
4792   Node* array = argument(0);
4793 
4794   Node* bol;
4795   switch(check) {
4796     case IsFlat:
4797       // TODO 8350865 Use the object version here instead of loading the klass
4798       // 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
4799       bol = flat_array_test(load_object_klass(array));
4800       break;
4801     case IsNullRestricted:
4802       bol = null_free_array_test(array);
4803       break;
4804     case IsAtomic:
4805       // TODO 8350865 Implement this. It's a bit more complicated, see conditions in JVM_IsAtomicArray
4806       // Enable TestIntrinsics::test87/88 once this is implemented
4807       // bol = null_free_atomic_array_test
4808       return false;
4809     default:
4810       ShouldNotReachHere();
4811   }
4812 
4813   Node* res = gvn().transform(new CMoveINode(bol, intcon(0), intcon(1), TypeInt::BOOL));
4814   set_result(res);
4815   return true;
4816 }
4817 
4818 // Load the default refined array klass from an ObjArrayKlass. This relies on the first entry in the
4819 // '_next_refined_array_klass' linked list being the default (see ObjArrayKlass::klass_with_properties).
4820 Node* LibraryCallKit::load_default_refined_array_klass(Node* klass_node, bool type_array_guard) {
4821   RegionNode* region = new RegionNode(2);
4822   Node* phi = new PhiNode(region, TypeInstKlassPtr::OBJECT_OR_NULL);
4823 
4824   if (type_array_guard) {
4825     generate_typeArray_guard(klass_node, region);
4826     if (region->req() == 3) {
4827       phi->add_req(klass_node);
4828     }
4829   }
4830   Node* adr_refined_klass = basic_plus_adr(top(), klass_node, in_bytes(ObjArrayKlass::next_refined_array_klass_offset()));
4831   Node* refined_klass = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), adr_refined_klass, TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
4832 
4833   // Can be null if not initialized yet, just deopt
4834   Node* null_ctl = top();
4835   refined_klass = null_check_oop(refined_klass, &null_ctl, /* never_see_null= */ true);
4836 
4837   region->init_req(1, control());
4838   phi->init_req(1, refined_klass);
4839 
4840   set_control(_gvn.transform(region));
4841   return _gvn.transform(phi);
4842 }
4843 
4844 // Load the non-refined array klass from an ObjArrayKlass.
4845 Node* LibraryCallKit::load_non_refined_array_klass(Node* klass_node) {
4846   const TypeAryKlassPtr* ary_klass_ptr = _gvn.type(klass_node)->isa_aryklassptr();
4847   if (ary_klass_ptr != nullptr && ary_klass_ptr->klass_is_exact()) {
4848     return _gvn.makecon(ary_klass_ptr->cast_to_refined_array_klass_ptr(false));
4849   }
4850 
4851   RegionNode* region = new RegionNode(2);
4852   Node* phi = new PhiNode(region, TypeInstKlassPtr::OBJECT);
4853 
4854   generate_typeArray_guard(klass_node, region);
4855   if (region->req() == 3) {
4856     phi->add_req(klass_node);
4857   }
4858   Node* super_adr = basic_plus_adr(top(), klass_node, in_bytes(Klass::super_offset()));
4859   Node* super_klass = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), super_adr, TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT));
4860 
4861   region->init_req(1, control());
4862   phi->init_req(1, super_klass);
4863 
4864   set_control(_gvn.transform(region));
4865   return _gvn.transform(phi);
4866 }
4867 
4868 //-----------------------inline_native_newArray--------------------------
4869 // private static native Object java.lang.reflect.Array.newArray(Class<?> componentType, int length);
4870 // private        native Object Unsafe.allocateUninitializedArray0(Class<?> cls, int size);
4871 bool LibraryCallKit::inline_unsafe_newArray(bool uninitialized) {
4872   Node* mirror;
4873   Node* count_val;
4874   if (uninitialized) {
4875     null_check_receiver();
4876     mirror    = argument(1);
4877     count_val = argument(2);
4878   } else {
4879     mirror    = argument(0);
4880     count_val = argument(1);
4881   }
4882 
4883   mirror = null_check(mirror);
4884   // If mirror or obj is dead, only null-path is taken.
4885   if (stopped())  return true;
4886 
4887   enum { _normal_path = 1, _slow_path = 2, PATH_LIMIT };
4888   RegionNode* result_reg = new RegionNode(PATH_LIMIT);
4889   PhiNode*    result_val = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
4890   PhiNode*    result_io  = new PhiNode(result_reg, Type::ABIO);
4891   PhiNode*    result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
4892 
4893   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
4894   Node* klass_node = load_array_klass_from_mirror(mirror, never_see_null,
4895                                                   result_reg, _slow_path);
4896   Node* normal_ctl   = control();
4897   Node* no_array_ctl = result_reg->in(_slow_path);
4898 
4899   // Generate code for the slow case.  We make a call to newArray().
4900   set_control(no_array_ctl);
4901   if (!stopped()) {
4902     // Either the input type is void.class, or else the
4903     // array klass has not yet been cached.  Either the
4904     // ensuing call will throw an exception, or else it
4905     // will cache the array klass for next time.
4906     PreserveJVMState pjvms(this);
4907     CallJavaNode* slow_call = nullptr;
4908     if (uninitialized) {
4909       // Generate optimized virtual call (holder class 'Unsafe' is final)
4910       slow_call = generate_method_call(vmIntrinsics::_allocateUninitializedArray, false, false, true);
4911     } else {
4912       slow_call = generate_method_call_static(vmIntrinsics::_newArray, true);
4913     }
4914     Node* slow_result = set_results_for_java_call(slow_call);
4915     // this->control() comes from set_results_for_java_call
4916     result_reg->set_req(_slow_path, control());
4917     result_val->set_req(_slow_path, slow_result);
4918     result_io ->set_req(_slow_path, i_o());
4919     result_mem->set_req(_slow_path, reset_memory());
4920   }
4921 
4922   set_control(normal_ctl);
4923   if (!stopped()) {
4924     // Normal case:  The array type has been cached in the java.lang.Class.
4925     // The following call works fine even if the array type is polymorphic.
4926     // It could be a dynamic mix of int[], boolean[], Object[], etc.
4927 
4928     klass_node = load_default_refined_array_klass(klass_node);
4929 
4930     Node* obj = new_array(klass_node, count_val, 0);  // no arguments to push
4931     result_reg->init_req(_normal_path, control());
4932     result_val->init_req(_normal_path, obj);
4933     result_io ->init_req(_normal_path, i_o());
4934     result_mem->init_req(_normal_path, reset_memory());
4935 
4936     if (uninitialized) {
4937       // Mark the allocation so that zeroing is skipped
4938       AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(obj);
4939       alloc->maybe_set_complete(&_gvn);
4940     }
4941   }
4942 
4943   // Return the combined state.
4944   set_i_o(        _gvn.transform(result_io)  );
4945   set_all_memory( _gvn.transform(result_mem));
4946 
4947   C->set_has_split_ifs(true); // Has chance for split-if optimization
4948   set_result(result_reg, result_val);
4949   return true;
4950 }
4951 
4952 //----------------------inline_native_getLength--------------------------
4953 // public static native int java.lang.reflect.Array.getLength(Object array);
4954 bool LibraryCallKit::inline_native_getLength() {
4955   if (too_many_traps(Deoptimization::Reason_intrinsic))  return false;
4956 
4957   Node* array = null_check(argument(0));
4958   // If array is dead, only null-path is taken.
4959   if (stopped())  return true;
4960 
4961   // Deoptimize if it is a non-array.
4962   Node* non_array = generate_non_array_guard(load_object_klass(array), nullptr, &array);
4963 
4964   if (non_array != nullptr) {
4965     PreserveJVMState pjvms(this);
4966     set_control(non_array);
4967     uncommon_trap(Deoptimization::Reason_intrinsic,
4968                   Deoptimization::Action_maybe_recompile);
4969   }
4970 
4971   // If control is dead, only non-array-path is taken.
4972   if (stopped())  return true;
4973 
4974   // The works fine even if the array type is polymorphic.
4975   // It could be a dynamic mix of int[], boolean[], Object[], etc.
4976   Node* result = load_array_length(array);
4977 
4978   C->set_has_split_ifs(true);  // Has chance for split-if optimization
4979   set_result(result);
4980   return true;
4981 }
4982 
4983 //------------------------inline_array_copyOf----------------------------
4984 // public static <T,U> T[] java.util.Arrays.copyOf(     U[] original, int newLength,         Class<? extends T[]> newType);
4985 // public static <T,U> T[] java.util.Arrays.copyOfRange(U[] original, int from,      int to, Class<? extends T[]> newType);
4986 bool LibraryCallKit::inline_array_copyOf(bool is_copyOfRange) {
4987   if (too_many_traps(Deoptimization::Reason_intrinsic))  return false;
4988 
4989   // Get the arguments.
4990   Node* original          = argument(0);
4991   Node* start             = is_copyOfRange? argument(1): intcon(0);
4992   Node* end               = is_copyOfRange? argument(2): argument(1);
4993   Node* array_type_mirror = is_copyOfRange? argument(3): argument(2);
4994 
4995   Node* newcopy = nullptr;
4996 
4997   // Set the original stack and the reexecute bit for the interpreter to reexecute
4998   // the bytecode that invokes Arrays.copyOf if deoptimization happens.
4999   { PreserveReexecuteState preexecs(this);
5000     jvms()->set_should_reexecute(true);
5001 
5002     array_type_mirror = null_check(array_type_mirror);
5003     original          = null_check(original);
5004 
5005     // Check if a null path was taken unconditionally.
5006     if (stopped())  return true;
5007 
5008     Node* orig_length = load_array_length(original);
5009 
5010     Node* klass_node = load_klass_from_mirror(array_type_mirror, false, nullptr, 0);
5011     klass_node = null_check(klass_node);
5012 
5013     RegionNode* bailout = new RegionNode(1);
5014     record_for_igvn(bailout);
5015 
5016     // Despite the generic type of Arrays.copyOf, the mirror might be int, int[], etc.
5017     // Bail out if that is so.
5018     // Inline type array may have object field that would require a
5019     // write barrier. Conservatively, go to slow path.
5020     // TODO 8251971: Optimize for the case when flat src/dst are later found
5021     // to not contain oops (i.e., move this check to the macro expansion phase).
5022     // TODO 8382226: Revisit for flat abstract value class arrays
5023     BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
5024     const TypeAryPtr* orig_t = _gvn.type(original)->isa_aryptr();
5025     const TypeKlassPtr* tklass = _gvn.type(klass_node)->is_klassptr();
5026     bool exclude_flat = UseArrayFlattening && bs->array_copy_requires_gc_barriers(true, T_OBJECT, false, false, BarrierSetC2::Parsing) &&
5027                         // Can src array be flat and contain oops?
5028                         (orig_t == nullptr || (!orig_t->is_not_flat() && (!orig_t->is_flat() || orig_t->elem()->inline_klass()->contains_oops()))) &&
5029                         // Can dest array be flat and contain oops?
5030                         tklass->can_be_inline_array() && (!tklass->is_flat() || tklass->is_aryklassptr()->elem()->is_instklassptr()->instance_klass()->as_inline_klass()->contains_oops());
5031     Node* not_objArray = exclude_flat ? generate_non_refArray_guard(klass_node, bailout) : generate_typeArray_guard(klass_node, bailout);
5032 
5033     Node* refined_klass_node = load_default_refined_array_klass(klass_node, /* type_array_guard= */ false);
5034 
5035     if (not_objArray != nullptr) {
5036       // Improve the klass node's type from the new optimistic assumption:
5037       ciKlass* ak = ciArrayKlass::make(env()->Object_klass());
5038       bool not_flat = !UseArrayFlattening;
5039       bool not_null_free = !Arguments::is_valhalla_enabled();
5040       const Type* akls = TypeAryKlassPtr::make(TypePtr::NotNull, ak, Type::Offset(0), Type::trust_interfaces, not_flat, not_null_free, false, false, not_flat, true);
5041       Node* cast = new CastPPNode(control(), refined_klass_node, akls);
5042       refined_klass_node = _gvn.transform(cast);
5043     }
5044 
5045     // Bail out if either start or end is negative.
5046     generate_negative_guard(start, bailout, &start);
5047     generate_negative_guard(end,   bailout, &end);
5048 
5049     Node* length = end;
5050     if (_gvn.type(start) != TypeInt::ZERO) {
5051       length = _gvn.transform(new SubINode(end, start));
5052     }
5053 
5054     // Bail out if length is negative (i.e., if start > end).
5055     // Without this the new_array would throw
5056     // NegativeArraySizeException but IllegalArgumentException is what
5057     // should be thrown
5058     generate_negative_guard(length, bailout, &length);
5059 
5060     // Handle inline type arrays
5061     bool can_validate = !too_many_traps(Deoptimization::Reason_class_check);
5062     if (!stopped()) {
5063       // TODO 8251971
5064       if (!orig_t->is_null_free()) {
5065         // Not statically known to be null free, add a check
5066         generate_fair_guard(null_free_array_test(original), bailout);
5067       }
5068       orig_t = _gvn.type(original)->isa_aryptr();
5069       if (orig_t != nullptr && orig_t->is_flat()) {
5070         // Src is flat, check that dest is flat as well
5071         if (exclude_flat) {
5072           // Dest can't be flat, bail out
5073           bailout->add_req(control());
5074           set_control(top());
5075         } else {
5076           generate_fair_guard(flat_array_test(refined_klass_node, /* flat = */ false), bailout);
5077         }
5078         // TODO 8350865 This is not correct anymore. Write tests and fix logic similar to arraycopy.
5079       } else if (UseArrayFlattening && (orig_t == nullptr || !orig_t->is_not_flat()) &&
5080                  // If dest is flat, src must be flat as well (guaranteed by src <: dest check if validated).
5081                  ((!tklass->is_flat() && tklass->can_be_inline_array()) || !can_validate)) {
5082         // Src might be flat and dest might not be flat. Go to the slow path if src is flat.
5083         // TODO 8251971: Optimize for the case when src/dest are later found to be both flat.
5084         generate_fair_guard(flat_array_test(load_object_klass(original)), bailout);
5085         if (orig_t != nullptr) {
5086           orig_t = orig_t->cast_to_not_flat();
5087           original = _gvn.transform(new CheckCastPPNode(control(), original, orig_t));
5088         }
5089       }
5090       if (!can_validate) {
5091         // No validation. The subtype check emitted at macro expansion time will not go to the slow
5092         // path but call checkcast_arraycopy which can not handle flat/null-free inline type arrays.
5093         // TODO 8251971: Optimize for the case when src/dest are later found to be both flat/null-free.
5094         generate_fair_guard(flat_array_test(refined_klass_node), bailout);
5095         generate_fair_guard(null_free_array_test(original), bailout);
5096       }
5097     }
5098 
5099     // Bail out if start is larger than the original length
5100     Node* orig_tail = _gvn.transform(new SubINode(orig_length, start));
5101     generate_negative_guard(orig_tail, bailout, &orig_tail);
5102 
5103     if (bailout->req() > 1) {
5104       PreserveJVMState pjvms(this);
5105       set_control(_gvn.transform(bailout));
5106       uncommon_trap(Deoptimization::Reason_intrinsic,
5107                     Deoptimization::Action_maybe_recompile);
5108     }
5109 
5110     if (!stopped()) {
5111       // How many elements will we copy from the original?
5112       // The answer is MinI(orig_tail, length).
5113       Node* moved = _gvn.transform(new MinINode(orig_tail, length));
5114 
5115       // Generate a direct call to the right arraycopy function(s).
5116       // We know the copy is disjoint but we might not know if the
5117       // oop stores need checking.
5118       // Extreme case:  Arrays.copyOf((Integer[])x, 10, String[].class).
5119       // This will fail a store-check if x contains any non-nulls.
5120 
5121       // ArrayCopyNode:Ideal may transform the ArrayCopyNode to
5122       // loads/stores but it is legal only if we're sure the
5123       // Arrays.copyOf would succeed. So we need all input arguments
5124       // to the copyOf to be validated, including that the copy to the
5125       // new array won't trigger an ArrayStoreException. That subtype
5126       // check can be optimized if we know something on the type of
5127       // the input array from type speculation.
5128       if (_gvn.type(klass_node)->singleton()) {
5129         const TypeKlassPtr* subk = _gvn.type(load_object_klass(original))->is_klassptr();
5130         const TypeKlassPtr* superk = _gvn.type(klass_node)->is_klassptr();
5131 
5132         int test = C->static_subtype_check(superk, subk);
5133         if (test != Compile::SSC_always_true && test != Compile::SSC_always_false) {
5134           const TypeOopPtr* t_original = _gvn.type(original)->is_oopptr();
5135           if (t_original->speculative_type() != nullptr) {
5136             original = maybe_cast_profiled_obj(original, t_original->speculative_type(), true);
5137           }
5138         }
5139       }
5140 
5141       bool validated = false;
5142       // Reason_class_check rather than Reason_intrinsic because we
5143       // want to intrinsify even if this traps.
5144       if (can_validate) {
5145         Node* not_subtype_ctrl = gen_subtype_check(original, klass_node);
5146 
5147         if (not_subtype_ctrl != top()) {
5148           PreserveJVMState pjvms(this);
5149           set_control(not_subtype_ctrl);
5150           uncommon_trap(Deoptimization::Reason_class_check,
5151                         Deoptimization::Action_make_not_entrant);
5152           assert(stopped(), "Should be stopped");
5153         }
5154         validated = true;
5155       }
5156 
5157       if (!stopped()) {
5158         newcopy = new_array(refined_klass_node, length, 0);  // no arguments to push
5159 
5160         ArrayCopyNode* ac = ArrayCopyNode::make(this, true, original, start, newcopy, intcon(0), moved, true, true,
5161                                                 load_object_klass(original), klass_node);
5162         if (!is_copyOfRange) {
5163           ac->set_copyof(validated);
5164         } else {
5165           ac->set_copyofrange(validated);
5166         }
5167         Node* n = _gvn.transform(ac);
5168         if (n == ac) {
5169           ac->connect_outputs(this);
5170         } else {
5171           assert(validated, "shouldn't transform if all arguments not validated");
5172           set_all_memory(n);
5173         }
5174       }
5175     }
5176   } // original reexecute is set back here
5177 
5178   C->set_has_split_ifs(true); // Has chance for split-if optimization
5179   if (!stopped()) {
5180     set_result(newcopy);
5181   }
5182   return true;
5183 }
5184 
5185 
5186 //----------------------generate_virtual_guard---------------------------
5187 // Helper for hashCode and clone.  Peeks inside the vtable to avoid a call.
5188 Node* LibraryCallKit::generate_virtual_guard(Node* obj_klass,
5189                                              RegionNode* slow_region) {
5190   ciMethod* method = callee();
5191   int vtable_index = method->vtable_index();
5192   assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index,
5193          "bad index %d", vtable_index);
5194   // Get the Method* out of the appropriate vtable entry.
5195   int entry_offset = in_bytes(Klass::vtable_start_offset()) +
5196                      vtable_index*vtableEntry::size_in_bytes() +
5197                      in_bytes(vtableEntry::method_offset());
5198   Node* entry_addr = off_heap_plus_addr(obj_klass, entry_offset);
5199   Node* target_call = make_load(nullptr, entry_addr, TypePtr::NOTNULL, T_ADDRESS, MemNode::unordered);
5200 
5201   // Compare the target method with the expected method (e.g., Object.hashCode).
5202   const TypePtr* native_call_addr = TypeMetadataPtr::make(method);
5203 
5204   Node* native_call = makecon(native_call_addr);
5205   Node* chk_native  = _gvn.transform(new CmpPNode(target_call, native_call));
5206   Node* test_native = _gvn.transform(new BoolNode(chk_native, BoolTest::ne));
5207 
5208   return generate_slow_guard(test_native, slow_region);
5209 }
5210 
5211 //-----------------------generate_method_call----------------------------
5212 // Use generate_method_call to make a slow-call to the real
5213 // method if the fast path fails.  An alternative would be to
5214 // use a stub like OptoRuntime::slow_arraycopy_Java.
5215 // This only works for expanding the current library call,
5216 // not another intrinsic.  (E.g., don't use this for making an
5217 // arraycopy call inside of the copyOf intrinsic.)
5218 CallJavaNode*
5219 LibraryCallKit::generate_method_call(vmIntrinsicID method_id, bool is_virtual, bool is_static, bool res_not_null) {
5220   // When compiling the intrinsic method itself, do not use this technique.
5221   guarantee(callee() != C->method(), "cannot make slow-call to self");
5222 
5223   ciMethod* method = callee();
5224   // ensure the JVMS we have will be correct for this call
5225   guarantee(method_id == method->intrinsic_id(), "must match");
5226 
5227   const TypeFunc* tf = TypeFunc::make(method);
5228   if (res_not_null) {
5229     assert(tf->return_type() == T_OBJECT, "");
5230     const TypeTuple* range = tf->range_cc();
5231     const Type** fields = TypeTuple::fields(range->cnt());
5232     fields[TypeFunc::Parms] = range->field_at(TypeFunc::Parms)->filter_speculative(TypePtr::NOTNULL);
5233     const TypeTuple* new_range = TypeTuple::make(range->cnt(), fields);
5234     tf = TypeFunc::make(tf->domain_cc(), new_range);
5235   }
5236   CallJavaNode* slow_call;
5237   if (is_static) {
5238     assert(!is_virtual, "");
5239     slow_call = new CallStaticJavaNode(C, tf,
5240                            SharedRuntime::get_resolve_static_call_stub(), method);
5241   } else if (is_virtual) {
5242     assert(!gvn().type(argument(0))->maybe_null(), "should not be null");
5243     int vtable_index = Method::invalid_vtable_index;
5244     if (UseInlineCaches) {
5245       // Suppress the vtable call
5246     } else {
5247       // hashCode and clone are not a miranda methods,
5248       // so the vtable index is fixed.
5249       // No need to use the linkResolver to get it.
5250        vtable_index = method->vtable_index();
5251        assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index,
5252               "bad index %d", vtable_index);
5253     }
5254     slow_call = new CallDynamicJavaNode(tf,
5255                           SharedRuntime::get_resolve_virtual_call_stub(),
5256                           method, vtable_index);
5257   } else {  // neither virtual nor static:  opt_virtual
5258     assert(!gvn().type(argument(0))->maybe_null(), "should not be null");
5259     slow_call = new CallStaticJavaNode(C, tf,
5260                                 SharedRuntime::get_resolve_opt_virtual_call_stub(), method);
5261     slow_call->set_optimized_virtual(true);
5262   }
5263   if (CallGenerator::is_inlined_method_handle_intrinsic(this->method(), bci(), callee())) {
5264     // To be able to issue a direct call (optimized virtual or virtual)
5265     // and skip a call to MH.linkTo*/invokeBasic adapter, additional information
5266     // about the method being invoked should be attached to the call site to
5267     // make resolution logic work (see SharedRuntime::resolve_{virtual,opt_virtual}_call_C).
5268     slow_call->set_override_symbolic_info(true);
5269   }
5270   set_arguments_for_java_call(slow_call);
5271   set_edges_for_java_call(slow_call);
5272   return slow_call;
5273 }
5274 
5275 
5276 /**
5277  * Build special case code for calls to hashCode on an object. This call may
5278  * be virtual (invokevirtual) or bound (invokespecial). For each case we generate
5279  * slightly different code.
5280  */
5281 bool LibraryCallKit::inline_native_hashcode(bool is_virtual, bool is_static) {
5282   assert(is_static == callee()->is_static(), "correct intrinsic selection");
5283   assert(!(is_virtual && is_static), "either virtual, special, or static");
5284 
5285   enum { _slow_path = 1, _fast_path, _null_path, PATH_LIMIT };
5286 
5287   RegionNode* result_reg = new RegionNode(PATH_LIMIT);
5288   PhiNode*    result_val = new PhiNode(result_reg, TypeInt::INT);
5289   PhiNode*    result_io  = new PhiNode(result_reg, Type::ABIO);
5290   PhiNode*    result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
5291   Node* obj = argument(0);
5292 
5293   // Don't intrinsify hashcode on inline types for now.
5294   // The "is locked" runtime check also subsumes the inline type check (as inline types cannot be locked) and goes to the slow path.
5295   if (gvn().type(obj)->is_inlinetypeptr()) {
5296     return false;
5297   }
5298 
5299   if (!is_static) {
5300     // Check for hashing null object
5301     obj = null_check_receiver();
5302     if (stopped())  return true;        // unconditionally null
5303     result_reg->init_req(_null_path, top());
5304     result_val->init_req(_null_path, top());
5305   } else {
5306     // Do a null check, and return zero if null.
5307     // System.identityHashCode(null) == 0
5308     Node* null_ctl = top();
5309     obj = null_check_oop(obj, &null_ctl);
5310     result_reg->init_req(_null_path, null_ctl);
5311     result_val->init_req(_null_path, _gvn.intcon(0));
5312   }
5313 
5314   // Unconditionally null?  Then return right away.
5315   if (stopped()) {
5316     set_control( result_reg->in(_null_path));
5317     if (!stopped())
5318       set_result(result_val->in(_null_path));
5319     return true;
5320   }
5321 
5322   // We only go to the fast case code if we pass a number of guards.  The
5323   // paths which do not pass are accumulated in the slow_region.
5324   RegionNode* slow_region = new RegionNode(1);
5325   record_for_igvn(slow_region);
5326 
5327   // If this is a virtual call, we generate a funny guard.  We pull out
5328   // the vtable entry corresponding to hashCode() from the target object.
5329   // If the target method which we are calling happens to be the native
5330   // Object hashCode() method, we pass the guard.  We do not need this
5331   // guard for non-virtual calls -- the caller is known to be the native
5332   // Object hashCode().
5333   if (is_virtual) {
5334     // After null check, get the object's klass.
5335     Node* obj_klass = load_object_klass(obj);
5336     generate_virtual_guard(obj_klass, slow_region);
5337   }
5338 
5339   // Get the header out of the object, use LoadMarkNode when available
5340   Node* header_addr = basic_plus_adr(obj, oopDesc::mark_offset_in_bytes());
5341   // The control of the load must be null. Otherwise, the load can move before
5342   // the null check after castPP removal.
5343   Node* no_ctrl = nullptr;
5344   Node* header = make_load(no_ctrl, header_addr, TypeX_X, TypeX_X->basic_type(), MemNode::unordered);
5345 
5346   if (!UseObjectMonitorTable) {
5347     // Test the header to see if it is safe to read w.r.t. locking.
5348     // We cannot use the inline type mask as this may check bits that are overriden
5349     // by an object monitor's pointer when inflating locking.
5350     Node *lock_mask      = _gvn.MakeConX(markWord::lock_mask_in_place);
5351     Node *lmasked_header = _gvn.transform(new AndXNode(header, lock_mask));
5352     Node *monitor_val   = _gvn.MakeConX(markWord::monitor_value);
5353     Node *chk_monitor   = _gvn.transform(new CmpXNode(lmasked_header, monitor_val));
5354     Node *test_monitor  = _gvn.transform(new BoolNode(chk_monitor, BoolTest::eq));
5355 
5356     generate_slow_guard(test_monitor, slow_region);
5357   }
5358 
5359   // Get the hash value and check to see that it has been properly assigned.
5360   // We depend on hash_mask being at most 32 bits and avoid the use of
5361   // hash_mask_in_place because it could be larger than 32 bits in a 64-bit
5362   // vm: see markWord.hpp.
5363   Node *hash_mask      = _gvn.intcon(markWord::hash_mask);
5364   Node *hash_shift     = _gvn.intcon(markWord::hash_shift);
5365   Node *hshifted_header= _gvn.transform(new URShiftXNode(header, hash_shift));
5366   // This hack lets the hash bits live anywhere in the mark object now, as long
5367   // as the shift drops the relevant bits into the low 32 bits.  Note that
5368   // Java spec says that HashCode is an int so there's no point in capturing
5369   // an 'X'-sized hashcode (32 in 32-bit build or 64 in 64-bit build).
5370   hshifted_header      = ConvX2I(hshifted_header);
5371   Node *hash_val       = _gvn.transform(new AndINode(hshifted_header, hash_mask));
5372 
5373   Node *no_hash_val    = _gvn.intcon(markWord::no_hash);
5374   Node *chk_assigned   = _gvn.transform(new CmpINode( hash_val, no_hash_val));
5375   Node *test_assigned  = _gvn.transform(new BoolNode( chk_assigned, BoolTest::eq));
5376 
5377   generate_slow_guard(test_assigned, slow_region);
5378 
5379   Node* init_mem = reset_memory();
5380   // fill in the rest of the null path:
5381   result_io ->init_req(_null_path, i_o());
5382   result_mem->init_req(_null_path, init_mem);
5383 
5384   result_val->init_req(_fast_path, hash_val);
5385   result_reg->init_req(_fast_path, control());
5386   result_io ->init_req(_fast_path, i_o());
5387   result_mem->init_req(_fast_path, init_mem);
5388 
5389   // Generate code for the slow case.  We make a call to hashCode().
5390   set_control(_gvn.transform(slow_region));
5391   if (!stopped()) {
5392     // No need for PreserveJVMState, because we're using up the present state.
5393     set_all_memory(init_mem);
5394     vmIntrinsics::ID hashCode_id = is_static ? vmIntrinsics::_identityHashCode : vmIntrinsics::_hashCode;
5395     CallJavaNode* slow_call = generate_method_call(hashCode_id, is_virtual, is_static, false);
5396     Node* slow_result = set_results_for_java_call(slow_call);
5397     // this->control() comes from set_results_for_java_call
5398     result_reg->init_req(_slow_path, control());
5399     result_val->init_req(_slow_path, slow_result);
5400     result_io  ->set_req(_slow_path, i_o());
5401     result_mem ->set_req(_slow_path, reset_memory());
5402   }
5403 
5404   // Return the combined state.
5405   set_i_o(        _gvn.transform(result_io)  );
5406   set_all_memory( _gvn.transform(result_mem));
5407 
5408   set_result(result_reg, result_val);
5409   return true;
5410 }
5411 
5412 //---------------------------inline_native_getClass----------------------------
5413 // public final native Class<?> java.lang.Object.getClass();
5414 //
5415 // Build special case code for calls to getClass on an object.
5416 bool LibraryCallKit::inline_native_getClass() {
5417   Node* obj = argument(0);
5418   if (obj->is_InlineType()) {
5419     const Type* t = _gvn.type(obj);
5420     if (t->maybe_null()) {
5421       null_check(obj);
5422     }
5423     set_result(makecon(TypeInstPtr::make(t->inline_klass()->java_mirror())));
5424     return true;
5425   }
5426   obj = null_check_receiver();
5427   if (stopped())  return true;
5428   set_result(load_mirror_from_klass(load_object_klass(obj)));
5429   return true;
5430 }
5431 
5432 //-----------------inline_native_Reflection_getCallerClass---------------------
5433 // public static native Class<?> sun.reflect.Reflection.getCallerClass();
5434 //
5435 // In the presence of deep enough inlining, getCallerClass() becomes a no-op.
5436 //
5437 // NOTE: This code must perform the same logic as JVM_GetCallerClass
5438 // in that it must skip particular security frames and checks for
5439 // caller sensitive methods.
5440 bool LibraryCallKit::inline_native_Reflection_getCallerClass() {
5441 #ifndef PRODUCT
5442   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5443     tty->print_cr("Attempting to inline sun.reflect.Reflection.getCallerClass");
5444   }
5445 #endif
5446 
5447   if (!jvms()->has_method()) {
5448 #ifndef PRODUCT
5449     if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5450       tty->print_cr("  Bailing out because intrinsic was inlined at top level");
5451     }
5452 #endif
5453     return false;
5454   }
5455 
5456   // Walk back up the JVM state to find the caller at the required
5457   // depth.
5458   JVMState* caller_jvms = jvms();
5459 
5460   // Cf. JVM_GetCallerClass
5461   // NOTE: Start the loop at depth 1 because the current JVM state does
5462   // not include the Reflection.getCallerClass() frame.
5463   for (int n = 1; caller_jvms != nullptr; caller_jvms = caller_jvms->caller(), n++) {
5464     ciMethod* m = caller_jvms->method();
5465     switch (n) {
5466     case 0:
5467       fatal("current JVM state does not include the Reflection.getCallerClass frame");
5468       break;
5469     case 1:
5470       // Frame 0 and 1 must be caller sensitive (see JVM_GetCallerClass).
5471       if (!m->caller_sensitive()) {
5472 #ifndef PRODUCT
5473         if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5474           tty->print_cr("  Bailing out: CallerSensitive annotation expected at frame %d", n);
5475         }
5476 #endif
5477         return false;  // bail-out; let JVM_GetCallerClass do the work
5478       }
5479       break;
5480     default:
5481       if (!m->is_ignored_by_security_stack_walk()) {
5482         // We have reached the desired frame; return the holder class.
5483         // Acquire method holder as java.lang.Class and push as constant.
5484         ciInstanceKlass* caller_klass = caller_jvms->method()->holder();
5485         ciInstance* caller_mirror = caller_klass->java_mirror();
5486         set_result(makecon(TypeInstPtr::make(caller_mirror)));
5487 
5488 #ifndef PRODUCT
5489         if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5490           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());
5491           tty->print_cr("  JVM state at this point:");
5492           for (int i = jvms()->depth(), n = 1; i >= 1; i--, n++) {
5493             ciMethod* m = jvms()->of_depth(i)->method();
5494             tty->print_cr("   %d) %s.%s", n, m->holder()->name()->as_utf8(), m->name()->as_utf8());
5495           }
5496         }
5497 #endif
5498         return true;
5499       }
5500       break;
5501     }
5502   }
5503 
5504 #ifndef PRODUCT
5505   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5506     tty->print_cr("  Bailing out because caller depth exceeded inlining depth = %d", jvms()->depth());
5507     tty->print_cr("  JVM state at this point:");
5508     for (int i = jvms()->depth(), n = 1; i >= 1; i--, n++) {
5509       ciMethod* m = jvms()->of_depth(i)->method();
5510       tty->print_cr("   %d) %s.%s", n, m->holder()->name()->as_utf8(), m->name()->as_utf8());
5511     }
5512   }
5513 #endif
5514 
5515   return false;  // bail-out; let JVM_GetCallerClass do the work
5516 }
5517 
5518 bool LibraryCallKit::inline_fp_conversions(vmIntrinsics::ID id) {
5519   Node* arg = argument(0);
5520   Node* result = nullptr;
5521 
5522   switch (id) {
5523   case vmIntrinsics::_floatToRawIntBits:    result = new MoveF2INode(arg);  break;
5524   case vmIntrinsics::_intBitsToFloat:       result = new MoveI2FNode(arg);  break;
5525   case vmIntrinsics::_doubleToRawLongBits:  result = new MoveD2LNode(arg);  break;
5526   case vmIntrinsics::_longBitsToDouble:     result = new MoveL2DNode(arg);  break;
5527   case vmIntrinsics::_floatToFloat16:       result = new ConvF2HFNode(arg); break;
5528   case vmIntrinsics::_float16ToFloat:       result = new ConvHF2FNode(arg); break;
5529 
5530   case vmIntrinsics::_doubleToLongBits: {
5531     // two paths (plus control) merge in a wood
5532     RegionNode *r = new RegionNode(3);
5533     Node *phi = new PhiNode(r, TypeLong::LONG);
5534 
5535     Node *cmpisnan = _gvn.transform(new CmpDNode(arg, arg));
5536     // Build the boolean node
5537     Node *bolisnan = _gvn.transform(new BoolNode(cmpisnan, BoolTest::ne));
5538 
5539     // Branch either way.
5540     // NaN case is less traveled, which makes all the difference.
5541     IfNode *ifisnan = create_and_xform_if(control(), bolisnan, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
5542     Node *opt_isnan = _gvn.transform(ifisnan);
5543     assert( opt_isnan->is_If(), "Expect an IfNode");
5544     IfNode *opt_ifisnan = (IfNode*)opt_isnan;
5545     Node *iftrue = _gvn.transform(new IfTrueNode(opt_ifisnan));
5546 
5547     set_control(iftrue);
5548 
5549     static const jlong nan_bits = CONST64(0x7ff8000000000000);
5550     Node *slow_result = longcon(nan_bits); // return NaN
5551     phi->init_req(1, _gvn.transform( slow_result ));
5552     r->init_req(1, iftrue);
5553 
5554     // Else fall through
5555     Node *iffalse = _gvn.transform(new IfFalseNode(opt_ifisnan));
5556     set_control(iffalse);
5557 
5558     phi->init_req(2, _gvn.transform(new MoveD2LNode(arg)));
5559     r->init_req(2, iffalse);
5560 
5561     // Post merge
5562     set_control(_gvn.transform(r));
5563     record_for_igvn(r);
5564 
5565     C->set_has_split_ifs(true); // Has chance for split-if optimization
5566     result = phi;
5567     assert(result->bottom_type()->isa_long(), "must be");
5568     break;
5569   }
5570 
5571   case vmIntrinsics::_floatToIntBits: {
5572     // two paths (plus control) merge in a wood
5573     RegionNode *r = new RegionNode(3);
5574     Node *phi = new PhiNode(r, TypeInt::INT);
5575 
5576     Node *cmpisnan = _gvn.transform(new CmpFNode(arg, arg));
5577     // Build the boolean node
5578     Node *bolisnan = _gvn.transform(new BoolNode(cmpisnan, BoolTest::ne));
5579 
5580     // Branch either way.
5581     // NaN case is less traveled, which makes all the difference.
5582     IfNode *ifisnan = create_and_xform_if(control(), bolisnan, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
5583     Node *opt_isnan = _gvn.transform(ifisnan);
5584     assert( opt_isnan->is_If(), "Expect an IfNode");
5585     IfNode *opt_ifisnan = (IfNode*)opt_isnan;
5586     Node *iftrue = _gvn.transform(new IfTrueNode(opt_ifisnan));
5587 
5588     set_control(iftrue);
5589 
5590     static const jint nan_bits = 0x7fc00000;
5591     Node *slow_result = makecon(TypeInt::make(nan_bits)); // return NaN
5592     phi->init_req(1, _gvn.transform( slow_result ));
5593     r->init_req(1, iftrue);
5594 
5595     // Else fall through
5596     Node *iffalse = _gvn.transform(new IfFalseNode(opt_ifisnan));
5597     set_control(iffalse);
5598 
5599     phi->init_req(2, _gvn.transform(new MoveF2INode(arg)));
5600     r->init_req(2, iffalse);
5601 
5602     // Post merge
5603     set_control(_gvn.transform(r));
5604     record_for_igvn(r);
5605 
5606     C->set_has_split_ifs(true); // Has chance for split-if optimization
5607     result = phi;
5608     assert(result->bottom_type()->isa_int(), "must be");
5609     break;
5610   }
5611 
5612   default:
5613     fatal_unexpected_iid(id);
5614     break;
5615   }
5616   set_result(_gvn.transform(result));
5617   return true;
5618 }
5619 
5620 bool LibraryCallKit::inline_fp_range_check(vmIntrinsics::ID id) {
5621   Node* arg = argument(0);
5622   Node* result = nullptr;
5623 
5624   switch (id) {
5625   case vmIntrinsics::_floatIsInfinite:
5626     result = new IsInfiniteFNode(arg);
5627     break;
5628   case vmIntrinsics::_floatIsFinite:
5629     result = new IsFiniteFNode(arg);
5630     break;
5631   case vmIntrinsics::_doubleIsInfinite:
5632     result = new IsInfiniteDNode(arg);
5633     break;
5634   case vmIntrinsics::_doubleIsFinite:
5635     result = new IsFiniteDNode(arg);
5636     break;
5637   default:
5638     fatal_unexpected_iid(id);
5639     break;
5640   }
5641   set_result(_gvn.transform(result));
5642   return true;
5643 }
5644 
5645 //----------------------inline_unsafe_copyMemory-------------------------
5646 // public native void Unsafe.copyMemory0(Object srcBase, long srcOffset, Object destBase, long destOffset, long bytes);
5647 
5648 static bool has_wide_mem(PhaseGVN& gvn, Node* addr, Node* base) {
5649   const TypeAryPtr* addr_t = gvn.type(addr)->isa_aryptr();
5650   const Type*       base_t = gvn.type(base);
5651 
5652   bool in_native = (base_t == TypePtr::NULL_PTR);
5653   bool in_heap   = !TypePtr::NULL_PTR->higher_equal(base_t);
5654   bool is_mixed  = !in_heap && !in_native;
5655 
5656   if (is_mixed) {
5657     return true; // mixed accesses can touch both on-heap and off-heap memory
5658   }
5659   if (in_heap) {
5660     bool is_prim_array = (addr_t != nullptr) && (addr_t->elem() != Type::BOTTOM);
5661     if (!is_prim_array) {
5662       // Though Unsafe.copyMemory() ensures at runtime for on-heap accesses that base is a primitive array,
5663       // there's not enough type information available to determine proper memory slice for it.
5664       return true;
5665     }
5666   }
5667   return false;
5668 }
5669 
5670 bool LibraryCallKit::inline_unsafe_copyMemory() {
5671   if (callee()->is_static())  return false;  // caller must have the capability!
5672   null_check_receiver();  // null-check receiver
5673   if (stopped())  return true;
5674 
5675   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
5676 
5677   Node* src_base =         argument(1);  // type: oop
5678   Node* src_off  = ConvL2X(argument(2)); // type: long
5679   Node* dst_base =         argument(4);  // type: oop
5680   Node* dst_off  = ConvL2X(argument(5)); // type: long
5681   Node* size     = ConvL2X(argument(7)); // type: long
5682 
5683   assert(Unsafe_field_offset_to_byte_offset(11) == 11,
5684          "fieldOffset must be byte-scaled");
5685 
5686   Node* src_addr = make_unsafe_address(src_base, src_off);
5687   Node* dst_addr = make_unsafe_address(dst_base, dst_off);
5688 
5689   Node* thread = _gvn.transform(new ThreadLocalNode());
5690   Node* doing_unsafe_access_addr = off_heap_plus_addr(thread, in_bytes(JavaThread::doing_unsafe_access_offset()));
5691   BasicType doing_unsafe_access_bt = T_BYTE;
5692   assert((sizeof(bool) * CHAR_BIT) == 8, "not implemented");
5693 
5694   // update volatile field
5695   store_to_memory(control(), doing_unsafe_access_addr, intcon(1), doing_unsafe_access_bt, MemNode::unordered);
5696 
5697   int flags = RC_LEAF | RC_NO_FP;
5698 
5699   const TypePtr* dst_type = TypePtr::BOTTOM;
5700 
5701   // Adjust memory effects of the runtime call based on input values.
5702   if (!has_wide_mem(_gvn, src_addr, src_base) &&
5703       !has_wide_mem(_gvn, dst_addr, dst_base)) {
5704     dst_type = _gvn.type(dst_addr)->is_ptr(); // narrow out memory
5705 
5706     const TypePtr* src_type = _gvn.type(src_addr)->is_ptr();
5707     if (C->get_alias_index(src_type) == C->get_alias_index(dst_type)) {
5708       flags |= RC_NARROW_MEM; // narrow in memory
5709     }
5710   }
5711 
5712   // Call it.  Note that the length argument is not scaled.
5713   make_runtime_call(flags,
5714                     OptoRuntime::fast_arraycopy_Type(),
5715                     StubRoutines::unsafe_arraycopy(),
5716                     "unsafe_arraycopy",
5717                     dst_type,
5718                     src_addr, dst_addr, size XTOP);
5719 
5720   store_to_memory(control(), doing_unsafe_access_addr, intcon(0), doing_unsafe_access_bt, MemNode::unordered);
5721 
5722   return true;
5723 }
5724 
5725 // unsafe_setmemory(void *base, ulong offset, size_t length, char fill_value);
5726 // Fill 'length' bytes starting from 'base[offset]' with 'fill_value'
5727 bool LibraryCallKit::inline_unsafe_setMemory() {
5728   if (callee()->is_static())  return false;  // caller must have the capability!
5729   null_check_receiver();  // null-check receiver
5730   if (stopped())  return true;
5731 
5732   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
5733 
5734   Node* dst_base =         argument(1);  // type: oop
5735   Node* dst_off  = ConvL2X(argument(2)); // type: long
5736   Node* size     = ConvL2X(argument(4)); // type: long
5737   Node* byte     =         argument(6);  // type: byte
5738 
5739   assert(Unsafe_field_offset_to_byte_offset(11) == 11,
5740          "fieldOffset must be byte-scaled");
5741 
5742   Node* dst_addr = make_unsafe_address(dst_base, dst_off);
5743 
5744   Node* thread = _gvn.transform(new ThreadLocalNode());
5745   Node* doing_unsafe_access_addr = off_heap_plus_addr(thread, in_bytes(JavaThread::doing_unsafe_access_offset()));
5746   BasicType doing_unsafe_access_bt = T_BYTE;
5747   assert((sizeof(bool) * CHAR_BIT) == 8, "not implemented");
5748 
5749   // update volatile field
5750   store_to_memory(control(), doing_unsafe_access_addr, intcon(1), doing_unsafe_access_bt, MemNode::unordered);
5751 
5752   int flags = RC_LEAF | RC_NO_FP;
5753 
5754   const TypePtr* dst_type = TypePtr::BOTTOM;
5755 
5756   // Adjust memory effects of the runtime call based on input values.
5757   if (!has_wide_mem(_gvn, dst_addr, dst_base)) {
5758     dst_type = _gvn.type(dst_addr)->is_ptr(); // narrow out memory
5759 
5760     flags |= RC_NARROW_MEM; // narrow in memory
5761   }
5762 
5763   // Call it.  Note that the length argument is not scaled.
5764   make_runtime_call(flags,
5765                     OptoRuntime::unsafe_setmemory_Type(),
5766                     StubRoutines::unsafe_setmemory(),
5767                     "unsafe_setmemory",
5768                     dst_type,
5769                     dst_addr, size XTOP, byte);
5770 
5771   store_to_memory(control(), doing_unsafe_access_addr, intcon(0), doing_unsafe_access_bt, MemNode::unordered);
5772 
5773   return true;
5774 }
5775 
5776 #undef XTOP
5777 
5778 //------------------------clone_coping-----------------------------------
5779 // Helper function for inline_native_clone.
5780 void LibraryCallKit::copy_to_clone(Node* obj, Node* alloc_obj, Node* obj_size, bool is_array) {
5781   assert(obj_size != nullptr, "");
5782   Node* raw_obj = alloc_obj->in(1);
5783   assert(alloc_obj->is_CheckCastPP() && raw_obj->is_Proj() && raw_obj->in(0)->is_Allocate(), "");
5784 
5785   AllocateNode* alloc = nullptr;
5786   if (ReduceBulkZeroing &&
5787       // If we are implementing an array clone without knowing its source type
5788       // (can happen when compiling the array-guarded branch of a reflective
5789       // Object.clone() invocation), initialize the array within the allocation.
5790       // This is needed because some GCs (e.g. ZGC) might fall back in this case
5791       // to a runtime clone call that assumes fully initialized source arrays.
5792       (!is_array || obj->get_ptr_type()->isa_aryptr() != nullptr)) {
5793     // We will be completely responsible for initializing this object -
5794     // mark Initialize node as complete.
5795     alloc = AllocateNode::Ideal_allocation(alloc_obj);
5796     // The object was just allocated - there should be no any stores!
5797     guarantee(alloc != nullptr && alloc->maybe_set_complete(&_gvn), "");
5798     // Mark as complete_with_arraycopy so that on AllocateNode
5799     // expansion, we know this AllocateNode is initialized by an array
5800     // copy and a StoreStore barrier exists after the array copy.
5801     alloc->initialization()->set_complete_with_arraycopy();
5802   }
5803 
5804   Node* size = _gvn.transform(obj_size);
5805   access_clone(obj, alloc_obj, size, is_array);
5806 
5807   // Do not let reads from the cloned object float above the arraycopy.
5808   if (alloc != nullptr) {
5809     // Do not let stores that initialize this object be reordered with
5810     // a subsequent store that would make this object accessible by
5811     // other threads.
5812     // Record what AllocateNode this StoreStore protects so that
5813     // escape analysis can go from the MemBarStoreStoreNode to the
5814     // AllocateNode and eliminate the MemBarStoreStoreNode if possible
5815     // based on the escape status of the AllocateNode.
5816     insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
5817   } else {
5818     insert_mem_bar(Op_MemBarCPUOrder);
5819   }
5820 }
5821 
5822 //------------------------inline_native_clone----------------------------
5823 // protected native Object java.lang.Object.clone();
5824 //
5825 // Here are the simple edge cases:
5826 //  null receiver => normal trap
5827 //  virtual and clone was overridden => slow path to out-of-line clone
5828 //  not cloneable or finalizer => slow path to out-of-line Object.clone
5829 //
5830 // The general case has two steps, allocation and copying.
5831 // Allocation has two cases, and uses GraphKit::new_instance or new_array.
5832 //
5833 // Copying also has two cases, oop arrays and everything else.
5834 // Oop arrays use arrayof_oop_arraycopy (same as System.arraycopy).
5835 // Everything else uses the tight inline loop supplied by CopyArrayNode.
5836 //
5837 // These steps fold up nicely if and when the cloned object's klass
5838 // can be sharply typed as an object array, a type array, or an instance.
5839 //
5840 bool LibraryCallKit::inline_native_clone(bool is_virtual) {
5841   PhiNode* result_val;
5842 
5843   // Set the reexecute bit for the interpreter to reexecute
5844   // the bytecode that invokes Object.clone if deoptimization happens.
5845   { PreserveReexecuteState preexecs(this);
5846     jvms()->set_should_reexecute(true);
5847 
5848     Node* obj = argument(0);
5849     obj = null_check_receiver();
5850     if (stopped())  return true;
5851 
5852     const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
5853     if (obj_type->is_inlinetypeptr()) {
5854       // If the object to clone is an inline type, we can simply return it (i.e. a nop) since inline types have
5855       // no identity.
5856       set_result(obj);
5857       return true;
5858     }
5859 
5860     // If we are going to clone an instance, we need its exact type to
5861     // know the number and types of fields to convert the clone to
5862     // loads/stores. Maybe a speculative type can help us.
5863     if (!obj_type->klass_is_exact() &&
5864         obj_type->speculative_type() != nullptr &&
5865         obj_type->speculative_type()->is_instance_klass() &&
5866         !obj_type->speculative_type()->is_inlinetype()) {
5867       ciInstanceKlass* spec_ik = obj_type->speculative_type()->as_instance_klass();
5868       if (spec_ik->nof_nonstatic_fields() <= ArrayCopyLoadStoreMaxElem &&
5869           !spec_ik->has_injected_fields()) {
5870         if (!obj_type->isa_instptr() ||
5871             obj_type->is_instptr()->instance_klass()->has_subklass()) {
5872           obj = maybe_cast_profiled_obj(obj, obj_type->speculative_type(), false);
5873         }
5874       }
5875     }
5876 
5877     // Conservatively insert a memory barrier on all memory slices.
5878     // Do not let writes into the original float below the clone.
5879     insert_mem_bar(Op_MemBarCPUOrder);
5880 
5881     // paths into result_reg:
5882     enum {
5883       _slow_path = 1,     // out-of-line call to clone method (virtual or not)
5884       _objArray_path,     // plain array allocation, plus arrayof_oop_arraycopy
5885       _array_path,        // plain array allocation, plus arrayof_long_arraycopy
5886       _instance_path,     // plain instance allocation, plus arrayof_long_arraycopy
5887       PATH_LIMIT
5888     };
5889     RegionNode* result_reg = new RegionNode(PATH_LIMIT);
5890     result_val             = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
5891     PhiNode*    result_i_o = new PhiNode(result_reg, Type::ABIO);
5892     PhiNode*    result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
5893     record_for_igvn(result_reg);
5894 
5895     Node* obj_klass = load_object_klass(obj);
5896     // We only go to the fast case code if we pass a number of guards.
5897     // The paths which do not pass are accumulated in the slow_region.
5898     RegionNode* slow_region = new RegionNode(1);
5899     record_for_igvn(slow_region);
5900 
5901     Node* array_obj = obj;
5902     Node* array_ctl = generate_array_guard(obj_klass, (RegionNode*)nullptr, &array_obj);
5903     if (array_ctl != nullptr) {
5904       // It's an array.
5905       PreserveJVMState pjvms(this);
5906       set_control(array_ctl);
5907 
5908       BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
5909       const TypeAryPtr* ary_ptr = obj_type->isa_aryptr();
5910       if (UseArrayFlattening && bs->array_copy_requires_gc_barriers(true, T_OBJECT, true, false, BarrierSetC2::Expansion) &&
5911           obj_type->can_be_inline_array() &&
5912           (ary_ptr == nullptr || (!ary_ptr->is_not_flat() && (!ary_ptr->is_flat() || ary_ptr->elem()->inline_klass()->contains_oops())))) {
5913         // Flat inline type array may have object field that would require a
5914         // write barrier. Conservatively, go to slow path.
5915         generate_fair_guard(flat_array_test(obj_klass), slow_region);
5916       }
5917 
5918       if (!stopped()) {
5919         Node* obj_length = load_array_length(array_obj);
5920         Node* array_size = nullptr; // Size of the array without object alignment padding.
5921         Node* alloc_obj = new_array(obj_klass, obj_length, 0, &array_size, /*deoptimize_on_exception=*/true);
5922 
5923         BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
5924         if (bs->array_copy_requires_gc_barriers(true, T_OBJECT, true, false, BarrierSetC2::Parsing)) {
5925           // If it is an oop array, it requires very special treatment,
5926           // because gc barriers are required when accessing the array.
5927           Node* is_obja = generate_refArray_guard(obj_klass, (RegionNode*)nullptr);
5928           if (is_obja != nullptr) {
5929             PreserveJVMState pjvms2(this);
5930             set_control(is_obja);
5931             // Generate a direct call to the right arraycopy function(s).
5932             // Clones are always tightly coupled.
5933             ArrayCopyNode* ac = ArrayCopyNode::make(this, true, array_obj, intcon(0), alloc_obj, intcon(0), obj_length, true, false);
5934             ac->set_clone_oop_array();
5935             Node* n = _gvn.transform(ac);
5936             assert(n == ac, "cannot disappear");
5937             ac->connect_outputs(this, /*deoptimize_on_exception=*/true);
5938 
5939             result_reg->init_req(_objArray_path, control());
5940             result_val->init_req(_objArray_path, alloc_obj);
5941             result_i_o ->set_req(_objArray_path, i_o());
5942             result_mem ->set_req(_objArray_path, reset_memory());
5943           }
5944         }
5945         // Otherwise, there are no barriers to worry about.
5946         // (We can dispense with card marks if we know the allocation
5947         //  comes out of eden (TLAB)...  In fact, ReduceInitialCardMarks
5948         //  causes the non-eden paths to take compensating steps to
5949         //  simulate a fresh allocation, so that no further
5950         //  card marks are required in compiled code to initialize
5951         //  the object.)
5952 
5953         if (!stopped()) {
5954           copy_to_clone(obj, alloc_obj, array_size, true);
5955 
5956           // Present the results of the copy.
5957           result_reg->init_req(_array_path, control());
5958           result_val->init_req(_array_path, alloc_obj);
5959           result_i_o ->set_req(_array_path, i_o());
5960           result_mem ->set_req(_array_path, reset_memory());
5961         }
5962       }
5963     }
5964 
5965     if (!stopped()) {
5966       // It's an instance (we did array above).  Make the slow-path tests.
5967       // If this is a virtual call, we generate a funny guard.  We grab
5968       // the vtable entry corresponding to clone() from the target object.
5969       // If the target method which we are calling happens to be the
5970       // Object clone() method, we pass the guard.  We do not need this
5971       // guard for non-virtual calls; the caller is known to be the native
5972       // Object clone().
5973       if (is_virtual) {
5974         generate_virtual_guard(obj_klass, slow_region);
5975       }
5976 
5977       // The object must be easily cloneable and must not have a finalizer.
5978       // Both of these conditions may be checked in a single test.
5979       // We could optimize the test further, but we don't care.
5980       generate_misc_flags_guard(obj_klass,
5981                                 // Test both conditions:
5982                                 KlassFlags::_misc_is_cloneable_fast | KlassFlags::_misc_has_finalizer,
5983                                 // Must be cloneable but not finalizer:
5984                                 KlassFlags::_misc_is_cloneable_fast,
5985                                 slow_region);
5986     }
5987 
5988     if (!stopped()) {
5989       // It's an instance, and it passed the slow-path tests.
5990       PreserveJVMState pjvms(this);
5991       Node* obj_size = nullptr; // Total object size, including object alignment padding.
5992       // Need to deoptimize on exception from allocation since Object.clone intrinsic
5993       // is reexecuted if deoptimization occurs and there could be problems when merging
5994       // exception state between multiple Object.clone versions (reexecute=true vs reexecute=false).
5995       Node* alloc_obj = new_instance(obj_klass, nullptr, &obj_size, /*deoptimize_on_exception=*/true);
5996 
5997       copy_to_clone(obj, alloc_obj, obj_size, false);
5998 
5999       // Present the results of the slow call.
6000       result_reg->init_req(_instance_path, control());
6001       result_val->init_req(_instance_path, alloc_obj);
6002       result_i_o ->set_req(_instance_path, i_o());
6003       result_mem ->set_req(_instance_path, reset_memory());
6004     }
6005 
6006     // Generate code for the slow case.  We make a call to clone().
6007     set_control(_gvn.transform(slow_region));
6008     if (!stopped()) {
6009       PreserveJVMState pjvms(this);
6010       CallJavaNode* slow_call = generate_method_call(vmIntrinsics::_clone, is_virtual, false, true);
6011       // We need to deoptimize on exception (see comment above)
6012       Node* slow_result = set_results_for_java_call(slow_call, false, /* deoptimize */ true);
6013       // this->control() comes from set_results_for_java_call
6014       result_reg->init_req(_slow_path, control());
6015       result_val->init_req(_slow_path, slow_result);
6016       result_i_o ->set_req(_slow_path, i_o());
6017       result_mem ->set_req(_slow_path, reset_memory());
6018     }
6019 
6020     // Return the combined state.
6021     set_control(    _gvn.transform(result_reg));
6022     set_i_o(        _gvn.transform(result_i_o));
6023     set_all_memory( _gvn.transform(result_mem));
6024   } // original reexecute is set back here
6025 
6026   set_result(_gvn.transform(result_val));
6027   return true;
6028 }
6029 
6030 // If we have a tightly coupled allocation, the arraycopy may take care
6031 // of the array initialization. If one of the guards we insert between
6032 // the allocation and the arraycopy causes a deoptimization, an
6033 // uninitialized array will escape the compiled method. To prevent that
6034 // we set the JVM state for uncommon traps between the allocation and
6035 // the arraycopy to the state before the allocation so, in case of
6036 // deoptimization, we'll reexecute the allocation and the
6037 // initialization.
6038 JVMState* LibraryCallKit::arraycopy_restore_alloc_state(AllocateArrayNode* alloc, int& saved_reexecute_sp) {
6039   if (alloc != nullptr) {
6040     ciMethod* trap_method = alloc->jvms()->method();
6041     int trap_bci = alloc->jvms()->bci();
6042 
6043     if (!C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_intrinsic) &&
6044         !C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_null_check)) {
6045       // Make sure there's no store between the allocation and the
6046       // arraycopy otherwise visible side effects could be rexecuted
6047       // in case of deoptimization and cause incorrect execution.
6048       bool no_interfering_store = true;
6049       Node* mem = alloc->in(TypeFunc::Memory);
6050       if (mem->is_MergeMem()) {
6051         for (MergeMemStream mms(merged_memory(), mem->as_MergeMem()); mms.next_non_empty2(); ) {
6052           Node* n = mms.memory();
6053           if (n != mms.memory2() && !(n->is_Proj() && n->in(0) == alloc->initialization())) {
6054             assert(n->is_Store(), "what else?");
6055             no_interfering_store = false;
6056             break;
6057           }
6058         }
6059       } else {
6060         for (MergeMemStream mms(merged_memory()); mms.next_non_empty(); ) {
6061           Node* n = mms.memory();
6062           if (n != mem && !(n->is_Proj() && n->in(0) == alloc->initialization())) {
6063             assert(n->is_Store(), "what else?");
6064             no_interfering_store = false;
6065             break;
6066           }
6067         }
6068       }
6069 
6070       if (no_interfering_store) {
6071         SafePointNode* sfpt = create_safepoint_with_state_before_array_allocation(alloc);
6072 
6073         JVMState* saved_jvms = jvms();
6074         saved_reexecute_sp = _reexecute_sp;
6075 
6076         set_jvms(sfpt->jvms());
6077         _reexecute_sp = jvms()->sp();
6078 
6079         return saved_jvms;
6080       }
6081     }
6082   }
6083   return nullptr;
6084 }
6085 
6086 // Clone the JVMState of the array allocation and create a new safepoint with it. Re-push the array length to the stack
6087 // such that uncommon traps can be emitted to re-execute the array allocation in the interpreter.
6088 SafePointNode* LibraryCallKit::create_safepoint_with_state_before_array_allocation(const AllocateArrayNode* alloc) const {
6089   JVMState* old_jvms = alloc->jvms()->clone_shallow(C);
6090   uint size = alloc->req();
6091   SafePointNode* sfpt = new SafePointNode(size, old_jvms);
6092   old_jvms->set_map(sfpt);
6093   for (uint i = 0; i < size; i++) {
6094     sfpt->init_req(i, alloc->in(i));
6095   }
6096   int adjustment = 1;
6097   const TypeAryKlassPtr* ary_klass_ptr = alloc->in(AllocateNode::KlassNode)->bottom_type()->is_aryklassptr();
6098   if (ary_klass_ptr->is_null_free()) {
6099     // A null-free, tightly coupled array allocation can only come from LibraryCallKit::inline_newArray which
6100     // also requires the componentType and initVal on stack for re-execution.
6101     // Re-create and push the componentType.
6102     ciArrayKlass* klass = ary_klass_ptr->exact_klass()->as_array_klass();
6103     ciInstance* instance = klass->component_mirror_instance();
6104     const TypeInstPtr* t_instance = TypeInstPtr::make(instance);
6105     sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp(), makecon(t_instance));
6106     adjustment++;
6107   }
6108   // re-push array length for deoptimization
6109   sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp() + adjustment - 1, alloc->in(AllocateNode::ALength));
6110   if (ary_klass_ptr->is_null_free()) {
6111     // Re-create and push the initVal.
6112     Node* init_val = alloc->in(AllocateNode::InitValue);
6113     if (init_val == nullptr) {
6114       init_val = InlineTypeNode::make_all_zero(_gvn, ary_klass_ptr->elem()->is_instklassptr()->instance_klass()->as_inline_klass());
6115     } else if (UseCompressedOops) {
6116       init_val = _gvn.transform(new DecodeNNode(init_val, init_val->bottom_type()->make_ptr()));
6117     }
6118     sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp() + adjustment, init_val);
6119     adjustment++;
6120   }
6121   old_jvms->set_sp(old_jvms->sp() + adjustment);
6122   old_jvms->set_monoff(old_jvms->monoff() + adjustment);
6123   old_jvms->set_scloff(old_jvms->scloff() + adjustment);
6124   old_jvms->set_endoff(old_jvms->endoff() + adjustment);
6125   old_jvms->set_should_reexecute(true);
6126 
6127   sfpt->set_i_o(map()->i_o());
6128   sfpt->set_memory(map()->memory());
6129   sfpt->set_control(map()->control());
6130   return sfpt;
6131 }
6132 
6133 // In case of a deoptimization, we restart execution at the
6134 // allocation, allocating a new array. We would leave an uninitialized
6135 // array in the heap that GCs wouldn't expect. Move the allocation
6136 // after the traps so we don't allocate the array if we
6137 // deoptimize. This is possible because tightly_coupled_allocation()
6138 // guarantees there's no observer of the allocated array at this point
6139 // and the control flow is simple enough.
6140 void LibraryCallKit::arraycopy_move_allocation_here(AllocateArrayNode* alloc, Node* dest, JVMState* saved_jvms_before_guards,
6141                                                     int saved_reexecute_sp, uint new_idx) {
6142   if (saved_jvms_before_guards != nullptr && !stopped()) {
6143     replace_unrelated_uncommon_traps_with_alloc_state(alloc, saved_jvms_before_guards);
6144 
6145     assert(alloc != nullptr, "only with a tightly coupled allocation");
6146     // restore JVM state to the state at the arraycopy
6147     saved_jvms_before_guards->map()->set_control(map()->control());
6148     assert(saved_jvms_before_guards->map()->memory() == map()->memory(), "memory state changed?");
6149     assert(saved_jvms_before_guards->map()->i_o() == map()->i_o(), "IO state changed?");
6150     // If we've improved the types of some nodes (null check) while
6151     // emitting the guards, propagate them to the current state
6152     map()->replaced_nodes().apply(saved_jvms_before_guards->map(), new_idx);
6153     set_jvms(saved_jvms_before_guards);
6154     _reexecute_sp = saved_reexecute_sp;
6155 
6156     // Remove the allocation from above the guards
6157     CallProjections* callprojs = alloc->extract_projections(true);
6158     InitializeNode* init = alloc->initialization();
6159     Node* alloc_mem = alloc->in(TypeFunc::Memory);
6160     C->gvn_replace_by(callprojs->fallthrough_ioproj, alloc->in(TypeFunc::I_O));
6161     init->replace_mem_projs_by(alloc_mem, C);
6162 
6163     // The CastIINode created in GraphKit::new_array (in AllocateArrayNode::make_ideal_length) must stay below
6164     // the allocation (i.e. is only valid if the allocation succeeds):
6165     // 1) replace CastIINode with AllocateArrayNode's length here
6166     // 2) Create CastIINode again once allocation has moved (see below) at the end of this method
6167     //
6168     // Multiple identical CastIINodes might exist here. Each GraphKit::load_array_length() call will generate
6169     // new separate CastIINode (arraycopy guard checks or any array length use between array allocation and ararycopy)
6170     Node* init_control = init->proj_out(TypeFunc::Control);
6171     Node* alloc_length = alloc->Ideal_length();
6172 #ifdef ASSERT
6173     Node* prev_cast = nullptr;
6174 #endif
6175     for (uint i = 0; i < init_control->outcnt(); i++) {
6176       Node* init_out = init_control->raw_out(i);
6177       if (init_out->is_CastII() && init_out->in(TypeFunc::Control) == init_control && init_out->in(1) == alloc_length) {
6178 #ifdef ASSERT
6179         if (prev_cast == nullptr) {
6180           prev_cast = init_out;
6181         } else {
6182           if (prev_cast->cmp(*init_out) == false) {
6183             prev_cast->dump();
6184             init_out->dump();
6185             assert(false, "not equal CastIINode");
6186           }
6187         }
6188 #endif
6189         C->gvn_replace_by(init_out, alloc_length);
6190       }
6191     }
6192     C->gvn_replace_by(init->proj_out(TypeFunc::Control), alloc->in(0));
6193 
6194     // move the allocation here (after the guards)
6195     _gvn.hash_delete(alloc);
6196     alloc->set_req(TypeFunc::Control, control());
6197     alloc->set_req(TypeFunc::I_O, i_o());
6198     Node *mem = reset_memory();
6199     set_all_memory(mem);
6200     alloc->set_req(TypeFunc::Memory, mem);
6201     set_control(init->proj_out_or_null(TypeFunc::Control));
6202     set_i_o(callprojs->fallthrough_ioproj);
6203 
6204     // Update memory as done in GraphKit::set_output_for_allocation()
6205     const TypeInt* length_type = _gvn.find_int_type(alloc->in(AllocateNode::ALength));
6206     const TypeOopPtr* ary_type = _gvn.type(alloc->in(AllocateNode::KlassNode))->is_klassptr()->as_instance_type();
6207     if (ary_type->isa_aryptr() && length_type != nullptr) {
6208       ary_type = ary_type->is_aryptr()->cast_to_size(length_type);
6209     }
6210     const TypePtr* telemref = ary_type->add_offset(Type::OffsetBot);
6211     int            elemidx  = C->get_alias_index(telemref);
6212     // Need to properly move every memory projection for the Initialize
6213 #ifdef ASSERT
6214     int mark_idx = C->get_alias_index(ary_type->add_offset(oopDesc::mark_offset_in_bytes()));
6215     int klass_idx = C->get_alias_index(ary_type->add_offset(oopDesc::klass_offset_in_bytes()));
6216 #endif
6217     auto move_proj = [&](ProjNode* proj) {
6218       int alias_idx = C->get_alias_index(proj->adr_type());
6219       assert(alias_idx == Compile::AliasIdxRaw ||
6220              alias_idx == elemidx ||
6221              alias_idx == mark_idx ||
6222              alias_idx == klass_idx, "should be raw memory or array element type");
6223       set_memory(proj, alias_idx);
6224     };
6225     init->for_each_proj(move_proj, TypeFunc::Memory);
6226 
6227     Node* allocx = _gvn.transform(alloc);
6228     assert(allocx == alloc, "where has the allocation gone?");
6229     assert(dest->is_CheckCastPP(), "not an allocation result?");
6230 
6231     _gvn.hash_delete(dest);
6232     dest->set_req(0, control());
6233     Node* destx = _gvn.transform(dest);
6234     assert(destx == dest, "where has the allocation result gone?");
6235 
6236     array_ideal_length(alloc, ary_type, true);
6237   }
6238 }
6239 
6240 // Unrelated UCTs between the array allocation and the array copy, which are considered safe by tightly_coupled_allocation(),
6241 // need to be replaced by an UCT with a state before the array allocation (including the array length). This is necessary
6242 // because we could hit one of these UCTs (which are executed before the emitted array copy guards and the actual array
6243 // allocation which is moved down in arraycopy_move_allocation_here()). When later resuming execution in the interpreter,
6244 // we would have wrongly skipped the array allocation. To prevent this, we resume execution at the array allocation in
6245 // the interpreter similar to what we are doing for the newly emitted guards for the array copy.
6246 void LibraryCallKit::replace_unrelated_uncommon_traps_with_alloc_state(AllocateArrayNode* alloc,
6247                                                                        JVMState* saved_jvms_before_guards) {
6248   if (saved_jvms_before_guards->map()->control()->is_IfProj()) {
6249     // There is at least one unrelated uncommon trap which needs to be replaced.
6250     SafePointNode* sfpt = create_safepoint_with_state_before_array_allocation(alloc);
6251 
6252     JVMState* saved_jvms = jvms();
6253     const int saved_reexecute_sp = _reexecute_sp;
6254     set_jvms(sfpt->jvms());
6255     _reexecute_sp = jvms()->sp();
6256 
6257     replace_unrelated_uncommon_traps_with_alloc_state(saved_jvms_before_guards);
6258 
6259     // Restore state
6260     set_jvms(saved_jvms);
6261     _reexecute_sp = saved_reexecute_sp;
6262   }
6263 }
6264 
6265 // Replace the unrelated uncommon traps with new uncommon trap nodes by reusing the action and reason. The new uncommon
6266 // traps will have the state of the array allocation. Let the old uncommon trap nodes die.
6267 void LibraryCallKit::replace_unrelated_uncommon_traps_with_alloc_state(JVMState* saved_jvms_before_guards) {
6268   Node* if_proj = saved_jvms_before_guards->map()->control(); // Start the search right before the newly emitted guards
6269   while (if_proj->is_IfProj()) {
6270     CallStaticJavaNode* uncommon_trap = get_uncommon_trap_from_success_proj(if_proj);
6271     if (uncommon_trap != nullptr) {
6272       create_new_uncommon_trap(uncommon_trap);
6273     }
6274     assert(if_proj->in(0)->is_If(), "must be If");
6275     if_proj = if_proj->in(0)->in(0);
6276   }
6277   assert(if_proj->is_Proj() && if_proj->in(0)->is_Initialize(),
6278          "must have reached control projection of init node");
6279 }
6280 
6281 void LibraryCallKit::create_new_uncommon_trap(CallStaticJavaNode* uncommon_trap_call) {
6282   const int trap_request = uncommon_trap_call->uncommon_trap_request();
6283   assert(trap_request != 0, "no valid UCT trap request");
6284   PreserveJVMState pjvms(this);
6285   set_control(uncommon_trap_call->in(0));
6286   uncommon_trap(Deoptimization::trap_request_reason(trap_request),
6287                 Deoptimization::trap_request_action(trap_request));
6288   assert(stopped(), "Should be stopped");
6289   _gvn.hash_delete(uncommon_trap_call);
6290   uncommon_trap_call->set_req(0, top()); // not used anymore, kill it
6291 }
6292 
6293 // Common checks for array sorting intrinsics arguments.
6294 // Returns `true` if checks passed.
6295 bool LibraryCallKit::check_array_sort_arguments(Node* elementType, Node* obj, BasicType& bt) {
6296   // check address of the class
6297   if (elementType == nullptr || elementType->is_top()) {
6298     return false;  // dead path
6299   }
6300   const TypeInstPtr* elem_klass = gvn().type(elementType)->isa_instptr();
6301   if (elem_klass == nullptr) {
6302     return false;  // dead path
6303   }
6304   // java_mirror_type() returns non-null for compile-time Class constants only
6305   ciType* elem_type = elem_klass->java_mirror_type();
6306   if (elem_type == nullptr) {
6307     return false;
6308   }
6309   bt = elem_type->basic_type();
6310   // Disable the intrinsic if the CPU does not support SIMD sort
6311   if (!Matcher::supports_simd_sort(bt)) {
6312     return false;
6313   }
6314   // check address of the array
6315   if (obj == nullptr || obj->is_top()) {
6316     return false;  // dead path
6317   }
6318   const TypeAryPtr* obj_t = _gvn.type(obj)->isa_aryptr();
6319   if (obj_t == nullptr || obj_t->elem() == Type::BOTTOM) {
6320     return false; // failed input validation
6321   }
6322   return true;
6323 }
6324 
6325 //------------------------------inline_array_partition-----------------------
6326 bool LibraryCallKit::inline_array_partition() {
6327   address stubAddr = StubRoutines::select_array_partition_function();
6328   if (stubAddr == nullptr) {
6329     return false; // Intrinsic's stub is not implemented on this platform
6330   }
6331   assert(callee()->signature()->size() == 9, "arrayPartition has 8 parameters (one long)");
6332 
6333   // no receiver because it is a static method
6334   Node* elementType     = argument(0);
6335   Node* obj             = argument(1);
6336   Node* offset          = argument(2); // long
6337   Node* fromIndex       = argument(4);
6338   Node* toIndex         = argument(5);
6339   Node* indexPivot1     = argument(6);
6340   Node* indexPivot2     = argument(7);
6341   // PartitionOperation:  argument(8) is ignored
6342 
6343   Node* pivotIndices = nullptr;
6344   BasicType bt = T_ILLEGAL;
6345 
6346   if (!check_array_sort_arguments(elementType, obj, bt)) {
6347     return false;
6348   }
6349   null_check(obj);
6350   // If obj is dead, only null-path is taken.
6351   if (stopped()) {
6352     return true;
6353   }
6354   // Set the original stack and the reexecute bit for the interpreter to reexecute
6355   // the bytecode that invokes DualPivotQuicksort.partition() if deoptimization happens.
6356   { PreserveReexecuteState preexecs(this);
6357     jvms()->set_should_reexecute(true);
6358 
6359     Node* obj_adr = make_unsafe_address(obj, offset);
6360 
6361     // create the pivotIndices array of type int and size = 2
6362     Node* size = intcon(2);
6363     Node* klass_node = makecon(TypeKlassPtr::make(ciTypeArrayKlass::make(T_INT)));
6364     pivotIndices = new_array(klass_node, size, 0);  // no arguments to push
6365     AllocateArrayNode* alloc = tightly_coupled_allocation(pivotIndices);
6366     guarantee(alloc != nullptr, "created above");
6367     Node* pivotIndices_adr = basic_plus_adr(pivotIndices, arrayOopDesc::base_offset_in_bytes(T_INT));
6368 
6369     // pass the basic type enum to the stub
6370     Node* elemType = intcon(bt);
6371 
6372     // Call the stub
6373     const char *stubName = "array_partition_stub";
6374     make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::array_partition_Type(),
6375                       stubAddr, stubName, TypePtr::BOTTOM,
6376                       obj_adr, elemType, fromIndex, toIndex, pivotIndices_adr,
6377                       indexPivot1, indexPivot2);
6378 
6379   } // original reexecute is set back here
6380 
6381   if (!stopped()) {
6382     set_result(pivotIndices);
6383   }
6384 
6385   return true;
6386 }
6387 
6388 
6389 //------------------------------inline_array_sort-----------------------
6390 bool LibraryCallKit::inline_array_sort() {
6391   address stubAddr = StubRoutines::select_arraysort_function();
6392   if (stubAddr == nullptr) {
6393     return false; // Intrinsic's stub is not implemented on this platform
6394   }
6395   assert(callee()->signature()->size() == 7, "arraySort has 6 parameters (one long)");
6396 
6397   // no receiver because it is a static method
6398   Node* elementType     = argument(0);
6399   Node* obj             = argument(1);
6400   Node* offset          = argument(2); // long
6401   Node* fromIndex       = argument(4);
6402   Node* toIndex         = argument(5);
6403   // SortOperation:       argument(6) is ignored
6404 
6405   BasicType bt = T_ILLEGAL;
6406 
6407   if (!check_array_sort_arguments(elementType, obj, bt)) {
6408     return false;
6409   }
6410   null_check(obj);
6411   // If obj is dead, only null-path is taken.
6412   if (stopped()) {
6413     return true;
6414   }
6415   Node* obj_adr = make_unsafe_address(obj, offset);
6416 
6417   // pass the basic type enum to the stub
6418   Node* elemType = intcon(bt);
6419 
6420   // Call the stub.
6421   const char *stubName = "arraysort_stub";
6422   make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::array_sort_Type(),
6423                     stubAddr, stubName, TypePtr::BOTTOM,
6424                     obj_adr, elemType, fromIndex, toIndex);
6425 
6426   return true;
6427 }
6428 
6429 
6430 //------------------------------inline_arraycopy-----------------------
6431 // public static native void java.lang.System.arraycopy(Object src,  int  srcPos,
6432 //                                                      Object dest, int destPos,
6433 //                                                      int length);
6434 bool LibraryCallKit::inline_arraycopy() {
6435   // Get the arguments.
6436   Node* src         = argument(0);  // type: oop
6437   Node* src_offset  = argument(1);  // type: int
6438   Node* dest        = argument(2);  // type: oop
6439   Node* dest_offset = argument(3);  // type: int
6440   Node* length      = argument(4);  // type: int
6441 
6442   uint new_idx = C->unique();
6443 
6444   // Check for allocation before we add nodes that would confuse
6445   // tightly_coupled_allocation()
6446   AllocateArrayNode* alloc = tightly_coupled_allocation(dest);
6447 
6448   int saved_reexecute_sp = -1;
6449   JVMState* saved_jvms_before_guards = arraycopy_restore_alloc_state(alloc, saved_reexecute_sp);
6450   // See arraycopy_restore_alloc_state() comment
6451   // if alloc == null we don't have to worry about a tightly coupled allocation so we can emit all needed guards
6452   // if saved_jvms_before_guards is not null (then alloc is not null) then we can handle guards and a tightly coupled allocation
6453   // if saved_jvms_before_guards is null and alloc is not null, we can't emit any guards
6454   bool can_emit_guards = (alloc == nullptr || saved_jvms_before_guards != nullptr);
6455 
6456   // The following tests must be performed
6457   // (1) src and dest are arrays.
6458   // (2) src and dest arrays must have elements of the same BasicType
6459   // (3) src and dest must not be null.
6460   // (4) src_offset must not be negative.
6461   // (5) dest_offset must not be negative.
6462   // (6) length must not be negative.
6463   // (7) src_offset + length must not exceed length of src.
6464   // (8) dest_offset + length must not exceed length of dest.
6465   // (9) each element of an oop array must be assignable
6466 
6467   // (3) src and dest must not be null.
6468   // always do this here because we need the JVM state for uncommon traps
6469   Node* null_ctl = top();
6470   src  = saved_jvms_before_guards != nullptr ? null_check_oop(src, &null_ctl, true, true) : null_check(src, T_ARRAY);
6471   assert(null_ctl->is_top(), "no null control here");
6472   dest = null_check(dest, T_ARRAY);
6473 
6474   if (!can_emit_guards) {
6475     // if saved_jvms_before_guards is null and alloc is not null, we don't emit any
6476     // guards but the arraycopy node could still take advantage of a
6477     // tightly allocated allocation. tightly_coupled_allocation() is
6478     // called again to make sure it takes the null check above into
6479     // account: the null check is mandatory and if it caused an
6480     // uncommon trap to be emitted then the allocation can't be
6481     // considered tightly coupled in this context.
6482     alloc = tightly_coupled_allocation(dest);
6483   }
6484 
6485   bool validated = false;
6486 
6487   const Type* src_type  = _gvn.type(src);
6488   const Type* dest_type = _gvn.type(dest);
6489   const TypeAryPtr* top_src  = src_type->isa_aryptr();
6490   const TypeAryPtr* top_dest = dest_type->isa_aryptr();
6491 
6492   // Do we have the type of src?
6493   bool has_src = (top_src != nullptr && top_src->elem() != Type::BOTTOM);
6494   // Do we have the type of dest?
6495   bool has_dest = (top_dest != nullptr && top_dest->elem() != Type::BOTTOM);
6496   // Is the type for src from speculation?
6497   bool src_spec = false;
6498   // Is the type for dest from speculation?
6499   bool dest_spec = false;
6500 
6501   if ((!has_src || !has_dest) && can_emit_guards) {
6502     // We don't have sufficient type information, let's see if
6503     // speculative types can help. We need to have types for both src
6504     // and dest so that it pays off.
6505 
6506     // Do we already have or could we have type information for src
6507     bool could_have_src = has_src;
6508     // Do we already have or could we have type information for dest
6509     bool could_have_dest = has_dest;
6510 
6511     ciKlass* src_k = nullptr;
6512     if (!has_src) {
6513       src_k = src_type->speculative_type_not_null();
6514       if (src_k != nullptr && src_k->is_array_klass()) {
6515         could_have_src = true;
6516       }
6517     }
6518 
6519     ciKlass* dest_k = nullptr;
6520     if (!has_dest) {
6521       dest_k = dest_type->speculative_type_not_null();
6522       if (dest_k != nullptr && dest_k->is_array_klass()) {
6523         could_have_dest = true;
6524       }
6525     }
6526 
6527     if (could_have_src && could_have_dest) {
6528       // This is going to pay off so emit the required guards
6529       if (!has_src) {
6530         src = maybe_cast_profiled_obj(src, src_k, true);
6531         src_type  = _gvn.type(src);
6532         top_src  = src_type->isa_aryptr();
6533         has_src = (top_src != nullptr && top_src->elem() != Type::BOTTOM);
6534         src_spec = true;
6535       }
6536       if (!has_dest) {
6537         dest = maybe_cast_profiled_obj(dest, dest_k, true);
6538         dest_type  = _gvn.type(dest);
6539         top_dest  = dest_type->isa_aryptr();
6540         has_dest = (top_dest != nullptr && top_dest->elem() != Type::BOTTOM);
6541         dest_spec = true;
6542       }
6543     }
6544   }
6545 
6546   if (has_src && has_dest && can_emit_guards) {
6547     BasicType src_elem = top_src->isa_aryptr()->elem()->array_element_basic_type();
6548     BasicType dest_elem = top_dest->isa_aryptr()->elem()->array_element_basic_type();
6549     if (is_reference_type(src_elem, true)) src_elem = T_OBJECT;
6550     if (is_reference_type(dest_elem, true)) dest_elem = T_OBJECT;
6551 
6552     if (src_elem == dest_elem && top_src->is_flat() == top_dest->is_flat() && src_elem == T_OBJECT) {
6553       // If both arrays are object arrays then having the exact types
6554       // for both will remove the need for a subtype check at runtime
6555       // before the call and may make it possible to pick a faster copy
6556       // routine (without a subtype check on every element)
6557       // Do we have the exact type of src?
6558       bool could_have_src = src_spec;
6559       // Do we have the exact type of dest?
6560       bool could_have_dest = dest_spec;
6561       ciKlass* src_k = nullptr;
6562       ciKlass* dest_k = nullptr;
6563       if (!src_spec) {
6564         src_k = src_type->speculative_type_not_null();
6565         if (src_k != nullptr && src_k->is_array_klass()) {
6566           could_have_src = true;
6567         }
6568       }
6569       if (!dest_spec) {
6570         dest_k = dest_type->speculative_type_not_null();
6571         if (dest_k != nullptr && dest_k->is_array_klass()) {
6572           could_have_dest = true;
6573         }
6574       }
6575       if (could_have_src && could_have_dest) {
6576         // If we can have both exact types, emit the missing guards
6577         if (could_have_src && !src_spec) {
6578           src = maybe_cast_profiled_obj(src, src_k, true);
6579           src_type = _gvn.type(src);
6580           top_src = src_type->isa_aryptr();
6581         }
6582         if (could_have_dest && !dest_spec) {
6583           dest = maybe_cast_profiled_obj(dest, dest_k, true);
6584           dest_type = _gvn.type(dest);
6585           top_dest = dest_type->isa_aryptr();
6586         }
6587       }
6588     }
6589   }
6590 
6591   ciMethod* trap_method = method();
6592   int trap_bci = bci();
6593   if (saved_jvms_before_guards != nullptr) {
6594     trap_method = alloc->jvms()->method();
6595     trap_bci = alloc->jvms()->bci();
6596   }
6597 
6598   bool negative_length_guard_generated = false;
6599 
6600   if (!C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_intrinsic) &&
6601       can_emit_guards && !src->is_top() && !dest->is_top()) {
6602     // validate arguments: enables transformation the ArrayCopyNode
6603     validated = true;
6604 
6605     RegionNode* slow_region = new RegionNode(1);
6606     record_for_igvn(slow_region);
6607 
6608     // (1) src and dest are arrays.
6609     generate_non_array_guard(load_object_klass(src), slow_region, &src);
6610     generate_non_array_guard(load_object_klass(dest), slow_region, &dest);
6611 
6612     // (2) src and dest arrays must have elements of the same BasicType
6613     // done at macro expansion or at Ideal transformation time
6614 
6615     // (4) src_offset must not be negative.
6616     generate_negative_guard(src_offset, slow_region);
6617 
6618     // (5) dest_offset must not be negative.
6619     generate_negative_guard(dest_offset, slow_region);
6620 
6621     // (7) src_offset + length must not exceed length of src.
6622     generate_limit_guard(src_offset, length,
6623                          load_array_length(src),
6624                          slow_region);
6625 
6626     // (8) dest_offset + length must not exceed length of dest.
6627     generate_limit_guard(dest_offset, length,
6628                          load_array_length(dest),
6629                          slow_region);
6630 
6631     // (6) length must not be negative.
6632     // This is also checked in generate_arraycopy() during macro expansion, but
6633     // we also have to check it here for the case where the ArrayCopyNode will
6634     // be eliminated by Escape Analysis.
6635     if (EliminateAllocations) {
6636       generate_negative_guard(length, slow_region);
6637       negative_length_guard_generated = true;
6638     }
6639 
6640     // (9) each element of an oop array must be assignable
6641     Node* dest_klass = load_object_klass(dest);
6642     Node* refined_dest_klass = dest_klass;
6643     if (src != dest) {
6644       dest_klass = load_non_refined_array_klass(refined_dest_klass);
6645       Node* not_subtype_ctrl = gen_subtype_check(src, dest_klass);
6646       slow_region->add_req(not_subtype_ctrl);
6647     }
6648 
6649     // TODO 8350865 Improve this. What about atomicity? Make sure this is always folded for type arrays.
6650     // If destination is null-restricted, source must be null-restricted as well: src_null_restricted || !dst_null_restricted
6651     Node* src_klass = load_object_klass(src);
6652     Node* adr_prop_src = basic_plus_adr(top(), src_klass, in_bytes(ArrayKlass::properties_offset()));
6653     Node* prop_src = _gvn.transform(LoadNode::make(_gvn, control(), immutable_memory(), adr_prop_src,
6654                                                    _gvn.type(adr_prop_src)->is_ptr(), TypeInt::INT, T_INT,
6655                                                    MemNode::unordered));
6656     Node* adr_prop_dest = basic_plus_adr(top(), refined_dest_klass, in_bytes(ArrayKlass::properties_offset()));
6657     Node* prop_dest = _gvn.transform(LoadNode::make(_gvn, control(), immutable_memory(), adr_prop_dest,
6658                                                     _gvn.type(adr_prop_dest)->is_ptr(), TypeInt::INT, T_INT,
6659                                                     MemNode::unordered));
6660 
6661     const ArrayProperties props_null_restricted = ArrayProperties::Default().with_null_restricted();
6662     jint props_value = (jint)props_null_restricted.value();
6663 
6664     prop_dest = _gvn.transform(new XorINode(prop_dest, intcon(props_value)));
6665     prop_src = _gvn.transform(new OrINode(prop_dest, prop_src));
6666     prop_src = _gvn.transform(new AndINode(prop_src, intcon(props_value)));
6667 
6668     Node* chk = _gvn.transform(new CmpINode(prop_src, intcon(props_value)));
6669     Node* tst = _gvn.transform(new BoolNode(chk, BoolTest::ne));
6670     generate_fair_guard(tst, slow_region);
6671 
6672     // TODO 8350865 This is too strong
6673     generate_fair_guard(flat_array_test(src), slow_region);
6674     generate_fair_guard(flat_array_test(dest), slow_region);
6675 
6676     {
6677       PreserveJVMState pjvms(this);
6678       set_control(_gvn.transform(slow_region));
6679       uncommon_trap(Deoptimization::Reason_intrinsic,
6680                     Deoptimization::Action_make_not_entrant);
6681       assert(stopped(), "Should be stopped");
6682     }
6683 
6684     const TypeKlassPtr* dest_klass_t = _gvn.type(dest_klass)->isa_klassptr();
6685     if (dest_klass_t == nullptr) {
6686       // refined_dest_klass may not be an array, which leads to dest_klass being top. This means we
6687       // are in a dead path.
6688       uncommon_trap(Deoptimization::Reason_intrinsic,
6689                     Deoptimization::Action_make_not_entrant);
6690       return true;
6691     }
6692 
6693     const Type* toop = dest_klass_t->cast_to_exactness(false)->as_instance_type();
6694     src = _gvn.transform(new CheckCastPPNode(control(), src, toop));
6695     arraycopy_move_allocation_here(alloc, dest, saved_jvms_before_guards, saved_reexecute_sp, new_idx);
6696   }
6697 
6698   if (stopped()) {
6699     return true;
6700   }
6701 
6702   Node* dest_klass = load_object_klass(dest);
6703   dest_klass = load_non_refined_array_klass(dest_klass);
6704 
6705   ArrayCopyNode* ac = ArrayCopyNode::make(this, true, src, src_offset, dest, dest_offset, length, alloc != nullptr, negative_length_guard_generated,
6706                                           // Create LoadRange and LoadKlass nodes for use during macro expansion here
6707                                           // so the compiler has a chance to eliminate them: during macro expansion,
6708                                           // we have to set their control (CastPP nodes are eliminated).
6709                                           load_object_klass(src), dest_klass,
6710                                           load_array_length(src), load_array_length(dest));
6711 
6712   ac->set_arraycopy(validated);
6713 
6714   Node* n = _gvn.transform(ac);
6715   if (n == ac) {
6716     ac->connect_outputs(this);
6717   } else {
6718     assert(validated, "shouldn't transform if all arguments not validated");
6719     set_all_memory(n);
6720   }
6721   clear_upper_avx();
6722 
6723 
6724   return true;
6725 }
6726 
6727 
6728 // Helper function which determines if an arraycopy immediately follows
6729 // an allocation, with no intervening tests or other escapes for the object.
6730 AllocateArrayNode*
6731 LibraryCallKit::tightly_coupled_allocation(Node* ptr) {
6732   if (stopped())             return nullptr;  // no fast path
6733   if (!C->do_aliasing())     return nullptr;  // no MergeMems around
6734 
6735   AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(ptr);
6736   if (alloc == nullptr)  return nullptr;
6737 
6738   Node* rawmem = memory(Compile::AliasIdxRaw);
6739   // Is the allocation's memory state untouched?
6740   if (!(rawmem->is_Proj() && rawmem->in(0)->is_Initialize())) {
6741     // Bail out if there have been raw-memory effects since the allocation.
6742     // (Example:  There might have been a call or safepoint.)
6743     return nullptr;
6744   }
6745   rawmem = rawmem->in(0)->as_Initialize()->memory(Compile::AliasIdxRaw);
6746   if (!(rawmem->is_Proj() && rawmem->in(0) == alloc)) {
6747     return nullptr;
6748   }
6749 
6750   // There must be no unexpected observers of this allocation.
6751   for (DUIterator_Fast imax, i = ptr->fast_outs(imax); i < imax; i++) {
6752     Node* obs = ptr->fast_out(i);
6753     if (obs != this->map()) {
6754       return nullptr;
6755     }
6756   }
6757 
6758   // This arraycopy must unconditionally follow the allocation of the ptr.
6759   Node* alloc_ctl = ptr->in(0);
6760   Node* ctl = control();
6761   while (ctl != alloc_ctl) {
6762     // There may be guards which feed into the slow_region.
6763     // Any other control flow means that we might not get a chance
6764     // to finish initializing the allocated object.
6765     // Various low-level checks bottom out in uncommon traps. These
6766     // are considered safe since we've already checked above that
6767     // there is no unexpected observer of this allocation.
6768     if (get_uncommon_trap_from_success_proj(ctl) != nullptr) {
6769       assert(ctl->in(0)->is_If(), "must be If");
6770       ctl = ctl->in(0)->in(0);
6771     } else {
6772       return nullptr;
6773     }
6774   }
6775 
6776   // If we get this far, we have an allocation which immediately
6777   // precedes the arraycopy, and we can take over zeroing the new object.
6778   // The arraycopy will finish the initialization, and provide
6779   // a new control state to which we will anchor the destination pointer.
6780 
6781   return alloc;
6782 }
6783 
6784 CallStaticJavaNode* LibraryCallKit::get_uncommon_trap_from_success_proj(Node* node) {
6785   if (node->is_IfProj()) {
6786     IfProjNode* other_proj = node->as_IfProj()->other_if_proj();
6787     for (DUIterator_Fast jmax, j = other_proj->fast_outs(jmax); j < jmax; j++) {
6788       Node* obs = other_proj->fast_out(j);
6789       if (obs->in(0) == other_proj && obs->is_CallStaticJava() &&
6790           (obs->as_CallStaticJava()->entry_point() == OptoRuntime::uncommon_trap_blob()->entry_point())) {
6791         return obs->as_CallStaticJava();
6792       }
6793     }
6794   }
6795   return nullptr;
6796 }
6797 
6798 //-------------inline_encodeISOArray-----------------------------------
6799 // int sun.nio.cs.ISO_8859_1.Encoder#encodeISOArray0(byte[] sa, int sp, byte[] da, int dp, int len)
6800 // int java.lang.StringCoding#encodeISOArray0(byte[] sa, int sp, byte[] da, int dp, int len)
6801 // int java.lang.StringCoding#encodeAsciiArray0(char[] sa, int sp, byte[] da, int dp, int len)
6802 // encode char[] to byte[] in ISO_8859_1 or ASCII
6803 bool LibraryCallKit::inline_encodeISOArray(bool ascii) {
6804   assert(callee()->signature()->size() == 5, "encodeISOArray has 5 parameters");
6805   // no receiver since it is static method
6806   Node *src         = argument(0);
6807   Node *src_offset  = argument(1);
6808   Node *dst         = argument(2);
6809   Node *dst_offset  = argument(3);
6810   Node *length      = argument(4);
6811 
6812   // Cast source & target arrays to not-null
6813   src = must_be_not_null(src, true);
6814   dst = must_be_not_null(dst, true);
6815   if (stopped()) {
6816     return true;
6817   }
6818 
6819   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
6820   const TypeAryPtr* dst_type = dst->Value(&_gvn)->isa_aryptr();
6821   if (src_type == nullptr || src_type->elem() == Type::BOTTOM ||
6822       dst_type == nullptr || dst_type->elem() == Type::BOTTOM) {
6823     // failed array check
6824     return false;
6825   }
6826 
6827   // Figure out the size and type of the elements we will be copying.
6828   BasicType src_elem = src_type->elem()->array_element_basic_type();
6829   BasicType dst_elem = dst_type->elem()->array_element_basic_type();
6830   if (!((src_elem == T_CHAR) || (src_elem== T_BYTE)) || dst_elem != T_BYTE) {
6831     return false;
6832   }
6833 
6834   // Check source & target bounds
6835   RegionNode* bailout = create_bailout();
6836   generate_string_range_check(src, src_offset, length, src_elem == T_BYTE, bailout);
6837   generate_string_range_check(dst, dst_offset, length, false, bailout);
6838   if (check_bailout(bailout)) {
6839     return true;
6840   }
6841 
6842   Node* src_start = array_element_address(src, src_offset, T_CHAR);
6843   Node* dst_start = array_element_address(dst, dst_offset, dst_elem);
6844   // 'src_start' points to src array + scaled offset
6845   // 'dst_start' points to dst array + scaled offset
6846 
6847   const TypeAryPtr* mtype = TypeAryPtr::BYTES;
6848   Node* enc = new EncodeISOArrayNode(control(), memory(mtype), src_start, dst_start, length, ascii);
6849   enc = _gvn.transform(enc);
6850   Node* res_mem = _gvn.transform(new SCMemProjNode(enc));
6851   set_memory(res_mem, mtype);
6852   set_result(enc);
6853   clear_upper_avx();
6854 
6855   return true;
6856 }
6857 
6858 //-------------inline_multiplyToLen-----------------------------------
6859 bool LibraryCallKit::inline_multiplyToLen() {
6860   assert(UseMultiplyToLenIntrinsic, "not implemented on this platform");
6861 
6862   address stubAddr = StubRoutines::multiplyToLen();
6863   if (stubAddr == nullptr) {
6864     return false; // Intrinsic's stub is not implemented on this platform
6865   }
6866   const char* stubName = "multiplyToLen";
6867 
6868   assert(callee()->signature()->size() == 5, "multiplyToLen has 5 parameters");
6869 
6870   // no receiver because it is a static method
6871   Node* x    = argument(0);
6872   Node* xlen = argument(1);
6873   Node* y    = argument(2);
6874   Node* ylen = argument(3);
6875   Node* z    = argument(4);
6876 
6877   x = must_be_not_null(x, true);
6878   y = must_be_not_null(y, true);
6879 
6880   const TypeAryPtr* x_type = x->Value(&_gvn)->isa_aryptr();
6881   const TypeAryPtr* y_type = y->Value(&_gvn)->isa_aryptr();
6882   if (x_type == nullptr || x_type->elem() == Type::BOTTOM ||
6883       y_type == nullptr || y_type->elem() == Type::BOTTOM) {
6884     // failed array check
6885     return false;
6886   }
6887 
6888   BasicType x_elem = x_type->elem()->array_element_basic_type();
6889   BasicType y_elem = y_type->elem()->array_element_basic_type();
6890   if (x_elem != T_INT || y_elem != T_INT) {
6891     return false;
6892   }
6893 
6894   Node* x_start = array_element_address(x, intcon(0), x_elem);
6895   Node* y_start = array_element_address(y, intcon(0), y_elem);
6896   // 'x_start' points to x array + scaled xlen
6897   // 'y_start' points to y array + scaled ylen
6898 
6899   Node* z_start = array_element_address(z, intcon(0), T_INT);
6900 
6901   Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
6902                                  OptoRuntime::multiplyToLen_Type(),
6903                                  stubAddr, stubName, TypePtr::BOTTOM,
6904                                  x_start, xlen, y_start, ylen, z_start);
6905 
6906   C->set_has_split_ifs(true); // Has chance for split-if optimization
6907   set_result(z);
6908   return true;
6909 }
6910 
6911 //-------------inline_squareToLen------------------------------------
6912 bool LibraryCallKit::inline_squareToLen() {
6913   assert(UseSquareToLenIntrinsic, "not implemented on this platform");
6914 
6915   address stubAddr = StubRoutines::squareToLen();
6916   if (stubAddr == nullptr) {
6917     return false; // Intrinsic's stub is not implemented on this platform
6918   }
6919   const char* stubName = "squareToLen";
6920 
6921   assert(callee()->signature()->size() == 4, "implSquareToLen has 4 parameters");
6922 
6923   Node* x    = argument(0);
6924   Node* len  = argument(1);
6925   Node* z    = argument(2);
6926   Node* zlen = argument(3);
6927 
6928   x = must_be_not_null(x, true);
6929   z = must_be_not_null(z, true);
6930 
6931   const TypeAryPtr* x_type = x->Value(&_gvn)->isa_aryptr();
6932   const TypeAryPtr* z_type = z->Value(&_gvn)->isa_aryptr();
6933   if (x_type == nullptr || x_type->elem() == Type::BOTTOM ||
6934       z_type == nullptr || z_type->elem() == Type::BOTTOM) {
6935     // failed array check
6936     return false;
6937   }
6938 
6939   BasicType x_elem = x_type->elem()->array_element_basic_type();
6940   BasicType z_elem = z_type->elem()->array_element_basic_type();
6941   if (x_elem != T_INT || z_elem != T_INT) {
6942     return false;
6943   }
6944 
6945 
6946   Node* x_start = array_element_address(x, intcon(0), x_elem);
6947   Node* z_start = array_element_address(z, intcon(0), z_elem);
6948 
6949   Node*  call = make_runtime_call(RC_LEAF|RC_NO_FP,
6950                                   OptoRuntime::squareToLen_Type(),
6951                                   stubAddr, stubName, TypePtr::BOTTOM,
6952                                   x_start, len, z_start, zlen);
6953 
6954   set_result(z);
6955   return true;
6956 }
6957 
6958 //-------------inline_mulAdd------------------------------------------
6959 bool LibraryCallKit::inline_mulAdd() {
6960   assert(UseMulAddIntrinsic, "not implemented on this platform");
6961 
6962   address stubAddr = StubRoutines::mulAdd();
6963   if (stubAddr == nullptr) {
6964     return false; // Intrinsic's stub is not implemented on this platform
6965   }
6966   const char* stubName = "mulAdd";
6967 
6968   assert(callee()->signature()->size() == 5, "mulAdd has 5 parameters");
6969 
6970   Node* out      = argument(0);
6971   Node* in       = argument(1);
6972   Node* offset   = argument(2);
6973   Node* len      = argument(3);
6974   Node* k        = argument(4);
6975 
6976   in = must_be_not_null(in, true);
6977   out = must_be_not_null(out, true);
6978 
6979   const TypeAryPtr* out_type = out->Value(&_gvn)->isa_aryptr();
6980   const TypeAryPtr* in_type = in->Value(&_gvn)->isa_aryptr();
6981   if (out_type == nullptr || out_type->elem() == Type::BOTTOM ||
6982        in_type == nullptr ||  in_type->elem() == Type::BOTTOM) {
6983     // failed array check
6984     return false;
6985   }
6986 
6987   BasicType out_elem = out_type->elem()->array_element_basic_type();
6988   BasicType in_elem = in_type->elem()->array_element_basic_type();
6989   if (out_elem != T_INT || in_elem != T_INT) {
6990     return false;
6991   }
6992 
6993   Node* outlen = load_array_length(out);
6994   Node* new_offset = _gvn.transform(new SubINode(outlen, offset));
6995   Node* out_start = array_element_address(out, intcon(0), out_elem);
6996   Node* in_start = array_element_address(in, intcon(0), in_elem);
6997 
6998   Node*  call = make_runtime_call(RC_LEAF|RC_NO_FP,
6999                                   OptoRuntime::mulAdd_Type(),
7000                                   stubAddr, stubName, TypePtr::BOTTOM,
7001                                   out_start,in_start, new_offset, len, k);
7002   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7003   set_result(result);
7004   return true;
7005 }
7006 
7007 //-------------inline_montgomeryMultiply-----------------------------------
7008 bool LibraryCallKit::inline_montgomeryMultiply() {
7009   address stubAddr = StubRoutines::montgomeryMultiply();
7010   if (stubAddr == nullptr) {
7011     return false; // Intrinsic's stub is not implemented on this platform
7012   }
7013 
7014   assert(UseMontgomeryMultiplyIntrinsic, "not implemented on this platform");
7015   const char* stubName = "montgomery_multiply";
7016 
7017   assert(callee()->signature()->size() == 7, "montgomeryMultiply has 7 parameters");
7018 
7019   Node* a    = argument(0);
7020   Node* b    = argument(1);
7021   Node* n    = argument(2);
7022   Node* len  = argument(3);
7023   Node* inv  = argument(4);
7024   Node* m    = argument(6);
7025 
7026   const TypeAryPtr* a_type = a->Value(&_gvn)->isa_aryptr();
7027   const TypeAryPtr* b_type = b->Value(&_gvn)->isa_aryptr();
7028   const TypeAryPtr* n_type = n->Value(&_gvn)->isa_aryptr();
7029   const TypeAryPtr* m_type = m->Value(&_gvn)->isa_aryptr();
7030   if (a_type == nullptr || a_type->elem() == Type::BOTTOM ||
7031       b_type == nullptr || b_type->elem() == Type::BOTTOM ||
7032       n_type == nullptr || n_type->elem() == Type::BOTTOM ||
7033       m_type == nullptr || m_type->elem() == Type::BOTTOM) {
7034     // failed array check
7035     return false;
7036   }
7037 
7038   BasicType a_elem = a_type->elem()->array_element_basic_type();
7039   BasicType b_elem = b_type->elem()->array_element_basic_type();
7040   BasicType n_elem = n_type->elem()->array_element_basic_type();
7041   BasicType m_elem = m_type->elem()->array_element_basic_type();
7042   if (a_elem != T_INT || b_elem != T_INT || n_elem != T_INT || m_elem != T_INT) {
7043     return false;
7044   }
7045 
7046   // Make the call
7047   {
7048     Node* a_start = array_element_address(a, intcon(0), a_elem);
7049     Node* b_start = array_element_address(b, intcon(0), b_elem);
7050     Node* n_start = array_element_address(n, intcon(0), n_elem);
7051     Node* m_start = array_element_address(m, intcon(0), m_elem);
7052 
7053     Node* call = make_runtime_call(RC_LEAF,
7054                                    OptoRuntime::montgomeryMultiply_Type(),
7055                                    stubAddr, stubName, TypePtr::BOTTOM,
7056                                    a_start, b_start, n_start, len, inv, top(),
7057                                    m_start);
7058     set_result(m);
7059   }
7060 
7061   return true;
7062 }
7063 
7064 bool LibraryCallKit::inline_montgomerySquare() {
7065   address stubAddr = StubRoutines::montgomerySquare();
7066   if (stubAddr == nullptr) {
7067     return false; // Intrinsic's stub is not implemented on this platform
7068   }
7069 
7070   assert(UseMontgomerySquareIntrinsic, "not implemented on this platform");
7071   const char* stubName = "montgomery_square";
7072 
7073   assert(callee()->signature()->size() == 6, "montgomerySquare has 6 parameters");
7074 
7075   Node* a    = argument(0);
7076   Node* n    = argument(1);
7077   Node* len  = argument(2);
7078   Node* inv  = argument(3);
7079   Node* m    = argument(5);
7080 
7081   const TypeAryPtr* a_type = a->Value(&_gvn)->isa_aryptr();
7082   const TypeAryPtr* n_type = n->Value(&_gvn)->isa_aryptr();
7083   const TypeAryPtr* m_type = m->Value(&_gvn)->isa_aryptr();
7084   if (a_type == nullptr || a_type->elem() == Type::BOTTOM ||
7085       n_type == nullptr || n_type->elem() == Type::BOTTOM ||
7086       m_type == nullptr || m_type->elem() == Type::BOTTOM) {
7087     // failed array check
7088     return false;
7089   }
7090 
7091   BasicType a_elem = a_type->elem()->array_element_basic_type();
7092   BasicType n_elem = n_type->elem()->array_element_basic_type();
7093   BasicType m_elem = m_type->elem()->array_element_basic_type();
7094   if (a_elem != T_INT || n_elem != T_INT || m_elem != T_INT) {
7095     return false;
7096   }
7097 
7098   // Make the call
7099   {
7100     Node* a_start = array_element_address(a, intcon(0), a_elem);
7101     Node* n_start = array_element_address(n, intcon(0), n_elem);
7102     Node* m_start = array_element_address(m, intcon(0), m_elem);
7103 
7104     Node* call = make_runtime_call(RC_LEAF,
7105                                    OptoRuntime::montgomerySquare_Type(),
7106                                    stubAddr, stubName, TypePtr::BOTTOM,
7107                                    a_start, n_start, len, inv, top(),
7108                                    m_start);
7109     set_result(m);
7110   }
7111 
7112   return true;
7113 }
7114 
7115 bool LibraryCallKit::inline_bigIntegerShift(bool isRightShift) {
7116   address stubAddr = nullptr;
7117   const char* stubName = nullptr;
7118 
7119   stubAddr = isRightShift? StubRoutines::bigIntegerRightShift(): StubRoutines::bigIntegerLeftShift();
7120   if (stubAddr == nullptr) {
7121     return false; // Intrinsic's stub is not implemented on this platform
7122   }
7123 
7124   stubName = isRightShift? "bigIntegerRightShiftWorker" : "bigIntegerLeftShiftWorker";
7125 
7126   assert(callee()->signature()->size() == 5, "expected 5 arguments");
7127 
7128   Node* newArr = argument(0);
7129   Node* oldArr = argument(1);
7130   Node* newIdx = argument(2);
7131   Node* shiftCount = argument(3);
7132   Node* numIter = argument(4);
7133 
7134   const TypeAryPtr* newArr_type = newArr->Value(&_gvn)->isa_aryptr();
7135   const TypeAryPtr* oldArr_type = oldArr->Value(&_gvn)->isa_aryptr();
7136   if (newArr_type == nullptr || newArr_type->elem() == Type::BOTTOM ||
7137       oldArr_type == nullptr || oldArr_type->elem() == Type::BOTTOM) {
7138     return false;
7139   }
7140 
7141   BasicType newArr_elem = newArr_type->elem()->array_element_basic_type();
7142   BasicType oldArr_elem = oldArr_type->elem()->array_element_basic_type();
7143   if (newArr_elem != T_INT || oldArr_elem != T_INT) {
7144     return false;
7145   }
7146 
7147   // Make the call
7148   {
7149     Node* newArr_start = array_element_address(newArr, intcon(0), newArr_elem);
7150     Node* oldArr_start = array_element_address(oldArr, intcon(0), oldArr_elem);
7151 
7152     Node* call = make_runtime_call(RC_LEAF,
7153                                    OptoRuntime::bigIntegerShift_Type(),
7154                                    stubAddr,
7155                                    stubName,
7156                                    TypePtr::BOTTOM,
7157                                    newArr_start,
7158                                    oldArr_start,
7159                                    newIdx,
7160                                    shiftCount,
7161                                    numIter);
7162   }
7163 
7164   return true;
7165 }
7166 
7167 //-------------inline_vectorizedMismatch------------------------------
7168 bool LibraryCallKit::inline_vectorizedMismatch() {
7169   assert(UseVectorizedMismatchIntrinsic, "not implemented on this platform");
7170 
7171   assert(callee()->signature()->size() == 8, "vectorizedMismatch has 6 parameters");
7172   Node* obja    = argument(0); // Object
7173   Node* aoffset = argument(1); // long
7174   Node* objb    = argument(3); // Object
7175   Node* boffset = argument(4); // long
7176   Node* length  = argument(6); // int
7177   Node* scale   = argument(7); // int
7178 
7179   const TypeAryPtr* obja_t = _gvn.type(obja)->isa_aryptr();
7180   const TypeAryPtr* objb_t = _gvn.type(objb)->isa_aryptr();
7181   if (obja_t == nullptr || obja_t->elem() == Type::BOTTOM ||
7182       objb_t == nullptr || objb_t->elem() == Type::BOTTOM ||
7183       scale == top()) {
7184     return false; // failed input validation
7185   }
7186 
7187   Node* obja_adr = make_unsafe_address(obja, aoffset);
7188   Node* objb_adr = make_unsafe_address(objb, boffset);
7189 
7190   // Partial inlining handling for inputs smaller than ArrayOperationPartialInlineSize bytes in size.
7191   //
7192   //    inline_limit = ArrayOperationPartialInlineSize / element_size;
7193   //    if (length <= inline_limit) {
7194   //      inline_path:
7195   //        vmask   = VectorMaskGen length
7196   //        vload1  = LoadVectorMasked obja, vmask
7197   //        vload2  = LoadVectorMasked objb, vmask
7198   //        result1 = VectorCmpMasked vload1, vload2, vmask
7199   //    } else {
7200   //      call_stub_path:
7201   //        result2 = call vectorizedMismatch_stub(obja, objb, length, scale)
7202   //    }
7203   //    exit_block:
7204   //      return Phi(result1, result2);
7205   //
7206   enum { inline_path = 1,  // input is small enough to process it all at once
7207          stub_path   = 2,  // input is too large; call into the VM
7208          PATH_LIMIT  = 3
7209   };
7210 
7211   Node* exit_block = new RegionNode(PATH_LIMIT);
7212   Node* result_phi = new PhiNode(exit_block, TypeInt::INT);
7213   Node* memory_phi = new PhiNode(exit_block, Type::MEMORY, TypePtr::BOTTOM);
7214 
7215   Node* call_stub_path = control();
7216 
7217   BasicType elem_bt = T_ILLEGAL;
7218 
7219   const TypeInt* scale_t = _gvn.type(scale)->is_int();
7220   if (scale_t->is_con()) {
7221     switch (scale_t->get_con()) {
7222       case 0: elem_bt = T_BYTE;  break;
7223       case 1: elem_bt = T_SHORT; break;
7224       case 2: elem_bt = T_INT;   break;
7225       case 3: elem_bt = T_LONG;  break;
7226 
7227       default: elem_bt = T_ILLEGAL; break; // not supported
7228     }
7229   }
7230 
7231   int inline_limit = 0;
7232   bool do_partial_inline = false;
7233 
7234   if (elem_bt != T_ILLEGAL && ArrayOperationPartialInlineSize > 0) {
7235     inline_limit = ArrayOperationPartialInlineSize / type2aelembytes(elem_bt);
7236     do_partial_inline = inline_limit >= 16;
7237   }
7238 
7239   if (do_partial_inline) {
7240     assert(elem_bt != T_ILLEGAL, "sanity");
7241 
7242     if (Matcher::match_rule_supported_vector(Op_VectorMaskGen,    inline_limit, elem_bt) &&
7243         Matcher::match_rule_supported_vector(Op_LoadVectorMasked, inline_limit, elem_bt) &&
7244         Matcher::match_rule_supported_vector(Op_VectorCmpMasked,  inline_limit, elem_bt)) {
7245 
7246       const TypeVect* vt = TypeVect::make(elem_bt, inline_limit);
7247       Node* cmp_length = _gvn.transform(new CmpINode(length, intcon(inline_limit)));
7248       Node* bol_gt     = _gvn.transform(new BoolNode(cmp_length, BoolTest::gt));
7249 
7250       call_stub_path = generate_guard(bol_gt, nullptr, PROB_MIN);
7251 
7252       if (!stopped()) {
7253         Node* casted_length = _gvn.transform(new CastIINode(control(), length, TypeInt::make(0, inline_limit, Type::WidenMin)));
7254 
7255         const TypePtr* obja_adr_t = _gvn.type(obja_adr)->isa_ptr();
7256         const TypePtr* objb_adr_t = _gvn.type(objb_adr)->isa_ptr();
7257         Node* obja_adr_mem = memory(C->get_alias_index(obja_adr_t));
7258         Node* objb_adr_mem = memory(C->get_alias_index(objb_adr_t));
7259 
7260         Node* vmask      = _gvn.transform(VectorMaskGenNode::make(ConvI2X(casted_length), elem_bt));
7261         Node* vload_obja = _gvn.transform(new LoadVectorMaskedNode(control(), obja_adr_mem, obja_adr, obja_adr_t, vt, vmask));
7262         Node* vload_objb = _gvn.transform(new LoadVectorMaskedNode(control(), objb_adr_mem, objb_adr, objb_adr_t, vt, vmask));
7263         Node* result     = _gvn.transform(new VectorCmpMaskedNode(vload_obja, vload_objb, vmask, TypeInt::INT));
7264 
7265         exit_block->init_req(inline_path, control());
7266         memory_phi->init_req(inline_path, map()->memory());
7267         result_phi->init_req(inline_path, result);
7268 
7269         C->set_max_vector_size(MAX2((uint)ArrayOperationPartialInlineSize, C->max_vector_size()));
7270         clear_upper_avx();
7271       }
7272     }
7273   }
7274 
7275   if (call_stub_path != nullptr) {
7276     set_control(call_stub_path);
7277 
7278     Node* call = make_runtime_call(RC_LEAF,
7279                                    OptoRuntime::vectorizedMismatch_Type(),
7280                                    StubRoutines::vectorizedMismatch(), "vectorizedMismatch", TypePtr::BOTTOM,
7281                                    obja_adr, objb_adr, length, scale);
7282 
7283     exit_block->init_req(stub_path, control());
7284     memory_phi->init_req(stub_path, map()->memory());
7285     result_phi->init_req(stub_path, _gvn.transform(new ProjNode(call, TypeFunc::Parms)));
7286   }
7287 
7288   exit_block = _gvn.transform(exit_block);
7289   memory_phi = _gvn.transform(memory_phi);
7290   result_phi = _gvn.transform(result_phi);
7291 
7292   record_for_igvn(exit_block);
7293   record_for_igvn(memory_phi);
7294   record_for_igvn(result_phi);
7295 
7296   set_control(exit_block);
7297   set_all_memory(memory_phi);
7298   set_result(result_phi);
7299 
7300   return true;
7301 }
7302 
7303 //------------------------------inline_vectorizedHashcode----------------------------
7304 bool LibraryCallKit::inline_vectorizedHashCode() {
7305   assert(UseVectorizedHashCodeIntrinsic, "not implemented on this platform");
7306 
7307   assert(callee()->signature()->size() == 5, "vectorizedHashCode has 5 parameters");
7308   Node* array          = argument(0);
7309   Node* offset         = argument(1);
7310   Node* length         = argument(2);
7311   Node* initialValue   = argument(3);
7312   Node* basic_type     = argument(4);
7313 
7314   if (basic_type == top()) {
7315     return false; // failed input validation
7316   }
7317 
7318   const TypeInt* basic_type_t = _gvn.type(basic_type)->is_int();
7319   if (!basic_type_t->is_con()) {
7320     return false; // Only intrinsify if mode argument is constant
7321   }
7322 
7323   array = must_be_not_null(array, true);
7324 
7325   BasicType bt = (BasicType)basic_type_t->get_con();
7326 
7327   // Resolve address of first element
7328   Node* array_start = array_element_address(array, offset, bt);
7329 
7330   set_result(_gvn.transform(new VectorizedHashCodeNode(control(), memory(TypeAryPtr::get_array_body_type(bt)),
7331     array_start, length, initialValue, basic_type)));
7332   clear_upper_avx();
7333 
7334   return true;
7335 }
7336 
7337 /**
7338  * Calculate CRC32 for byte.
7339  * int java.util.zip.CRC32.update(int crc, int b)
7340  */
7341 bool LibraryCallKit::inline_updateCRC32() {
7342   assert(UseCRC32Intrinsics, "need AVX and CLMUL instructions support");
7343   assert(callee()->signature()->size() == 2, "update has 2 parameters");
7344   // no receiver since it is static method
7345   Node* crc  = argument(0); // type: int
7346   Node* b    = argument(1); // type: int
7347 
7348   /*
7349    *    int c = ~ crc;
7350    *    b = timesXtoThe32[(b ^ c) & 0xFF];
7351    *    b = b ^ (c >>> 8);
7352    *    crc = ~b;
7353    */
7354 
7355   Node* M1 = intcon(-1);
7356   crc = _gvn.transform(new XorINode(crc, M1));
7357   Node* result = _gvn.transform(new XorINode(crc, b));
7358   result = _gvn.transform(new AndINode(result, intcon(0xFF)));
7359 
7360   Node* base = makecon(TypeRawPtr::make(StubRoutines::crc_table_addr()));
7361   Node* offset = _gvn.transform(new LShiftINode(result, intcon(0x2)));
7362   Node* adr = off_heap_plus_addr(base, ConvI2X(offset));
7363   result = make_load(control(), adr, TypeInt::INT, T_INT, MemNode::unordered);
7364 
7365   crc = _gvn.transform(new URShiftINode(crc, intcon(8)));
7366   result = _gvn.transform(new XorINode(crc, result));
7367   result = _gvn.transform(new XorINode(result, M1));
7368   set_result(result);
7369   return true;
7370 }
7371 
7372 /**
7373  * Calculate CRC32 for byte[] array.
7374  * int java.util.zip.CRC32.updateBytes(int crc, byte[] buf, int off, int len)
7375  */
7376 bool LibraryCallKit::inline_updateBytesCRC32() {
7377   assert(UseCRC32Intrinsics, "need AVX and CLMUL instructions support");
7378   assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
7379   // no receiver since it is static method
7380   Node* crc     = argument(0); // type: int
7381   Node* src     = argument(1); // type: oop
7382   Node* offset  = argument(2); // type: int
7383   Node* length  = argument(3); // type: int
7384 
7385   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7386   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
7387     // failed array check
7388     return false;
7389   }
7390 
7391   // Figure out the size and type of the elements we will be copying.
7392   BasicType src_elem = src_type->elem()->array_element_basic_type();
7393   if (src_elem != T_BYTE) {
7394     return false;
7395   }
7396 
7397   // 'src_start' points to src array + scaled offset
7398   src = must_be_not_null(src, true);
7399   Node* src_start = array_element_address(src, offset, src_elem);
7400 
7401   // We assume that range check is done by caller.
7402   // TODO: generate range check (offset+length < src.length) in debug VM.
7403 
7404   // Call the stub.
7405   address stubAddr = StubRoutines::updateBytesCRC32();
7406   const char *stubName = "updateBytesCRC32";
7407 
7408   Node* call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::updateBytesCRC32_Type(),
7409                                  stubAddr, stubName, TypePtr::BOTTOM,
7410                                  crc, src_start, length);
7411   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7412   set_result(result);
7413   return true;
7414 }
7415 
7416 /**
7417  * Calculate CRC32 for ByteBuffer.
7418  * int java.util.zip.CRC32.updateByteBuffer(int crc, long buf, int off, int len)
7419  */
7420 bool LibraryCallKit::inline_updateByteBufferCRC32() {
7421   assert(UseCRC32Intrinsics, "need AVX and CLMUL instructions support");
7422   assert(callee()->signature()->size() == 5, "updateByteBuffer has 4 parameters and one is long");
7423   // no receiver since it is static method
7424   Node* crc     = argument(0); // type: int
7425   Node* src     = argument(1); // type: long
7426   Node* offset  = argument(3); // type: int
7427   Node* length  = argument(4); // type: int
7428 
7429   src = ConvL2X(src);  // adjust Java long to machine word
7430   Node* base = _gvn.transform(new CastX2PNode(src));
7431   offset = ConvI2X(offset);
7432 
7433   // 'src_start' points to src array + scaled offset
7434   Node* src_start = off_heap_plus_addr(base, offset);
7435 
7436   // Call the stub.
7437   address stubAddr = StubRoutines::updateBytesCRC32();
7438   const char *stubName = "updateBytesCRC32";
7439 
7440   Node* call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::updateBytesCRC32_Type(),
7441                                  stubAddr, stubName, TypePtr::BOTTOM,
7442                                  crc, src_start, length);
7443   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7444   set_result(result);
7445   return true;
7446 }
7447 
7448 //------------------------------get_table_from_crc32c_class-----------------------
7449 Node * LibraryCallKit::get_table_from_crc32c_class(ciInstanceKlass *crc32c_class) {
7450   Node* table = load_field_from_object(nullptr, "byteTable", "[I", /*decorators*/ IN_HEAP, /*is_static*/ true, crc32c_class);
7451   assert (table != nullptr, "wrong version of java.util.zip.CRC32C");
7452 
7453   return table;
7454 }
7455 
7456 //------------------------------inline_updateBytesCRC32C-----------------------
7457 //
7458 // Calculate CRC32C for byte[] array.
7459 // int java.util.zip.CRC32C.updateBytes(int crc, byte[] buf, int off, int end)
7460 //
7461 bool LibraryCallKit::inline_updateBytesCRC32C() {
7462   assert(UseCRC32CIntrinsics, "need CRC32C instruction support");
7463   assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
7464   assert(callee()->holder()->is_loaded(), "CRC32C class must be loaded");
7465   // no receiver since it is a static method
7466   Node* crc     = argument(0); // type: int
7467   Node* src     = argument(1); // type: oop
7468   Node* offset  = argument(2); // type: int
7469   Node* end     = argument(3); // type: int
7470 
7471   Node* length = _gvn.transform(new SubINode(end, offset));
7472 
7473   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7474   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
7475     // failed array check
7476     return false;
7477   }
7478 
7479   // Figure out the size and type of the elements we will be copying.
7480   BasicType src_elem = src_type->elem()->array_element_basic_type();
7481   if (src_elem != T_BYTE) {
7482     return false;
7483   }
7484 
7485   // 'src_start' points to src array + scaled offset
7486   src = must_be_not_null(src, true);
7487   Node* src_start = array_element_address(src, offset, src_elem);
7488 
7489   // static final int[] byteTable in class CRC32C
7490   Node* table = get_table_from_crc32c_class(callee()->holder());
7491   table = must_be_not_null(table, true);
7492   Node* table_start = array_element_address(table, intcon(0), T_INT);
7493 
7494   // We assume that range check is done by caller.
7495   // TODO: generate range check (offset+length < src.length) in debug VM.
7496 
7497   // Call the stub.
7498   address stubAddr = StubRoutines::updateBytesCRC32C();
7499   const char *stubName = "updateBytesCRC32C";
7500 
7501   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesCRC32C_Type(),
7502                                  stubAddr, stubName, TypePtr::BOTTOM,
7503                                  crc, src_start, length, table_start);
7504   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7505   set_result(result);
7506   return true;
7507 }
7508 
7509 //------------------------------inline_updateDirectByteBufferCRC32C-----------------------
7510 //
7511 // Calculate CRC32C for DirectByteBuffer.
7512 // int java.util.zip.CRC32C.updateDirectByteBuffer(int crc, long buf, int off, int end)
7513 //
7514 bool LibraryCallKit::inline_updateDirectByteBufferCRC32C() {
7515   assert(UseCRC32CIntrinsics, "need CRC32C instruction support");
7516   assert(callee()->signature()->size() == 5, "updateDirectByteBuffer has 4 parameters and one is long");
7517   assert(callee()->holder()->is_loaded(), "CRC32C class must be loaded");
7518   // no receiver since it is a static method
7519   Node* crc     = argument(0); // type: int
7520   Node* src     = argument(1); // type: long
7521   Node* offset  = argument(3); // type: int
7522   Node* end     = argument(4); // type: int
7523 
7524   Node* length = _gvn.transform(new SubINode(end, offset));
7525 
7526   src = ConvL2X(src);  // adjust Java long to machine word
7527   Node* base = _gvn.transform(new CastX2PNode(src));
7528   offset = ConvI2X(offset);
7529 
7530   // 'src_start' points to src array + scaled offset
7531   Node* src_start = off_heap_plus_addr(base, offset);
7532 
7533   // static final int[] byteTable in class CRC32C
7534   Node* table = get_table_from_crc32c_class(callee()->holder());
7535   table = must_be_not_null(table, true);
7536   Node* table_start = array_element_address(table, intcon(0), T_INT);
7537 
7538   // Call the stub.
7539   address stubAddr = StubRoutines::updateBytesCRC32C();
7540   const char *stubName = "updateBytesCRC32C";
7541 
7542   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesCRC32C_Type(),
7543                                  stubAddr, stubName, TypePtr::BOTTOM,
7544                                  crc, src_start, length, table_start);
7545   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7546   set_result(result);
7547   return true;
7548 }
7549 
7550 //------------------------------inline_updateBytesAdler32----------------------
7551 //
7552 // Calculate Adler32 checksum for byte[] array.
7553 // int java.util.zip.Adler32.updateBytes(int crc, byte[] buf, int off, int len)
7554 //
7555 bool LibraryCallKit::inline_updateBytesAdler32() {
7556   assert(UseAdler32Intrinsics, "Adler32 Intrinsic support need"); // check if we actually need to check this flag or check a different one
7557   assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
7558   assert(callee()->holder()->is_loaded(), "Adler32 class must be loaded");
7559   // no receiver since it is static method
7560   Node* crc     = argument(0); // type: int
7561   Node* src     = argument(1); // type: oop
7562   Node* offset  = argument(2); // type: int
7563   Node* length  = argument(3); // type: int
7564 
7565   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7566   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
7567     // failed array check
7568     return false;
7569   }
7570 
7571   // Figure out the size and type of the elements we will be copying.
7572   BasicType src_elem = src_type->elem()->array_element_basic_type();
7573   if (src_elem != T_BYTE) {
7574     return false;
7575   }
7576 
7577   // 'src_start' points to src array + scaled offset
7578   Node* src_start = array_element_address(src, offset, src_elem);
7579 
7580   // We assume that range check is done by caller.
7581   // TODO: generate range check (offset+length < src.length) in debug VM.
7582 
7583   // Call the stub.
7584   address stubAddr = StubRoutines::updateBytesAdler32();
7585   const char *stubName = "updateBytesAdler32";
7586 
7587   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesAdler32_Type(),
7588                                  stubAddr, stubName, TypePtr::BOTTOM,
7589                                  crc, src_start, length);
7590   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7591   set_result(result);
7592   return true;
7593 }
7594 
7595 //------------------------------inline_updateByteBufferAdler32---------------
7596 //
7597 // Calculate Adler32 checksum for DirectByteBuffer.
7598 // int java.util.zip.Adler32.updateByteBuffer(int crc, long buf, int off, int len)
7599 //
7600 bool LibraryCallKit::inline_updateByteBufferAdler32() {
7601   assert(UseAdler32Intrinsics, "Adler32 Intrinsic support need"); // check if we actually need to check this flag or check a different one
7602   assert(callee()->signature()->size() == 5, "updateByteBuffer has 4 parameters and one is long");
7603   assert(callee()->holder()->is_loaded(), "Adler32 class must be loaded");
7604   // no receiver since it is static method
7605   Node* crc     = argument(0); // type: int
7606   Node* src     = argument(1); // type: long
7607   Node* offset  = argument(3); // type: int
7608   Node* length  = argument(4); // type: int
7609 
7610   src = ConvL2X(src);  // adjust Java long to machine word
7611   Node* base = _gvn.transform(new CastX2PNode(src));
7612   offset = ConvI2X(offset);
7613 
7614   // 'src_start' points to src array + scaled offset
7615   Node* src_start = off_heap_plus_addr(base, offset);
7616 
7617   // Call the stub.
7618   address stubAddr = StubRoutines::updateBytesAdler32();
7619   const char *stubName = "updateBytesAdler32";
7620 
7621   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesAdler32_Type(),
7622                                  stubAddr, stubName, TypePtr::BOTTOM,
7623                                  crc, src_start, length);
7624 
7625   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7626   set_result(result);
7627   return true;
7628 }
7629 
7630 //----------------------------inline_reference_get0----------------------------
7631 // public T java.lang.ref.Reference.get();
7632 bool LibraryCallKit::inline_reference_get0() {
7633   const int referent_offset = java_lang_ref_Reference::referent_offset();
7634 
7635   // Get the argument:
7636   Node* reference_obj = null_check_receiver();
7637   if (stopped()) return true;
7638 
7639   DecoratorSet decorators = IN_HEAP | ON_WEAK_OOP_REF;
7640   Node* result = load_field_from_object(reference_obj, "referent", "Ljava/lang/Object;",
7641                                         decorators, /*is_static*/ false, nullptr);
7642   if (result == nullptr) return false;
7643 
7644   // Add memory barrier to prevent commoning reads from this field
7645   // across safepoint since GC can change its value.
7646   insert_mem_bar(Op_MemBarCPUOrder);
7647 
7648   set_result(result);
7649   return true;
7650 }
7651 
7652 //----------------------------inline_reference_refersTo0----------------------------
7653 // bool java.lang.ref.Reference.refersTo0();
7654 // bool java.lang.ref.PhantomReference.refersTo0();
7655 bool LibraryCallKit::inline_reference_refersTo0(bool is_phantom) {
7656   // Get arguments:
7657   Node* reference_obj = null_check_receiver();
7658   Node* other_obj = argument(1);
7659   if (stopped()) return true;
7660 
7661   DecoratorSet decorators = IN_HEAP | AS_NO_KEEPALIVE;
7662   decorators |= (is_phantom ? ON_PHANTOM_OOP_REF : ON_WEAK_OOP_REF);
7663   Node* referent = load_field_from_object(reference_obj, "referent", "Ljava/lang/Object;",
7664                                           decorators, /*is_static*/ false, nullptr);
7665   if (referent == nullptr) return false;
7666 
7667   // Add memory barrier to prevent commoning reads from this field
7668   // across safepoint since GC can change its value.
7669   insert_mem_bar(Op_MemBarCPUOrder);
7670 
7671   Node* cmp = _gvn.transform(new CmpPNode(referent, other_obj));
7672   Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
7673   IfNode* if_node = create_and_map_if(control(), bol, PROB_FAIR, COUNT_UNKNOWN);
7674 
7675   RegionNode* region = new RegionNode(3);
7676   PhiNode* phi = new PhiNode(region, TypeInt::BOOL);
7677 
7678   Node* if_true = _gvn.transform(new IfTrueNode(if_node));
7679   region->init_req(1, if_true);
7680   phi->init_req(1, intcon(1));
7681 
7682   Node* if_false = _gvn.transform(new IfFalseNode(if_node));
7683   region->init_req(2, if_false);
7684   phi->init_req(2, intcon(0));
7685 
7686   set_control(_gvn.transform(region));
7687   record_for_igvn(region);
7688   set_result(_gvn.transform(phi));
7689   return true;
7690 }
7691 
7692 //----------------------------inline_reference_clear0----------------------------
7693 // void java.lang.ref.Reference.clear0();
7694 // void java.lang.ref.PhantomReference.clear0();
7695 bool LibraryCallKit::inline_reference_clear0(bool is_phantom) {
7696   // This matches the implementation in JVM_ReferenceClear, see the comments there.
7697 
7698   // Get arguments
7699   Node* reference_obj = null_check_receiver();
7700   if (stopped()) return true;
7701 
7702   // Common access parameters
7703   DecoratorSet decorators = IN_HEAP | AS_NO_KEEPALIVE;
7704   decorators |= (is_phantom ? ON_PHANTOM_OOP_REF : ON_WEAK_OOP_REF);
7705   Node* referent_field_addr = basic_plus_adr(reference_obj, java_lang_ref_Reference::referent_offset());
7706   const TypePtr* referent_field_addr_type = _gvn.type(referent_field_addr)->isa_ptr();
7707   const Type* val_type = TypeOopPtr::make_from_klass(env()->Object_klass());
7708 
7709   Node* referent = access_load_at(reference_obj,
7710                                   referent_field_addr,
7711                                   referent_field_addr_type,
7712                                   val_type,
7713                                   T_OBJECT,
7714                                   decorators);
7715 
7716   IdealKit ideal(this);
7717 #define __ ideal.
7718   __ if_then(referent, BoolTest::ne, null());
7719     sync_kit(ideal);
7720     access_store_at(reference_obj,
7721                     referent_field_addr,
7722                     referent_field_addr_type,
7723                     null(),
7724                     val_type,
7725                     T_OBJECT,
7726                     decorators);
7727     __ sync_kit(this);
7728   __ end_if();
7729   final_sync(ideal);
7730 #undef __
7731 
7732   return true;
7733 }
7734 
7735 //-----------------------inline_reference_reachabilityFence-----------------
7736 // bool java.lang.ref.Reference.reachabilityFence();
7737 bool LibraryCallKit::inline_reference_reachabilityFence() {
7738   Node* referent = argument(0);
7739   insert_reachability_fence(referent);
7740   return true;
7741 }
7742 
7743 Node* LibraryCallKit::load_field_from_object(Node* fromObj, const char* fieldName, const char* fieldTypeString,
7744                                              DecoratorSet decorators, bool is_static,
7745                                              ciInstanceKlass* fromKls) {
7746   if (fromKls == nullptr) {
7747     const TypeInstPtr* tinst = _gvn.type(fromObj)->isa_instptr();
7748     assert(tinst != nullptr, "obj is null");
7749     assert(tinst->is_loaded(), "obj is not loaded");
7750     fromKls = tinst->instance_klass();
7751   } else {
7752     assert(is_static, "only for static field access");
7753   }
7754   ciField* field = fromKls->get_field_by_name(ciSymbol::make(fieldName),
7755                                               ciSymbol::make(fieldTypeString),
7756                                               is_static);
7757 
7758   assert(field != nullptr, "undefined field %s %s %s", fieldTypeString, fromKls->name()->as_utf8(), fieldName);
7759   if (field == nullptr) return (Node *) nullptr;
7760 
7761   if (is_static) {
7762     const TypeInstPtr* tip = TypeInstPtr::make(fromKls->java_mirror());
7763     fromObj = makecon(tip);
7764   }
7765 
7766   // Next code  copied from Parse::do_get_xxx():
7767 
7768   // Compute address and memory type.
7769   int offset  = field->offset_in_bytes();
7770   bool is_vol = field->is_volatile();
7771   ciType* field_klass = field->type();
7772   assert(field_klass->is_loaded(), "should be loaded");
7773   const TypePtr* adr_type = C->alias_type(field)->adr_type();
7774   Node *adr = basic_plus_adr(fromObj, fromObj, offset);
7775   assert(C->get_alias_index(adr_type) == C->get_alias_index(_gvn.type(adr)->isa_ptr()),
7776     "slice of address and input slice don't match");
7777   BasicType bt = field->layout_type();
7778 
7779   // Build the resultant type of the load
7780   const Type *type;
7781   if (bt == T_OBJECT) {
7782     type = TypeOopPtr::make_from_klass(field_klass->as_klass());
7783   } else {
7784     type = Type::get_const_basic_type(bt);
7785   }
7786 
7787   if (is_vol) {
7788     decorators |= MO_SEQ_CST;
7789   }
7790 
7791   return access_load_at(fromObj, adr, adr_type, type, bt, decorators);
7792 }
7793 
7794 Node * LibraryCallKit::field_address_from_object(Node * fromObj, const char * fieldName, const char * fieldTypeString,
7795                                                  bool is_exact /* true */, bool is_static /* false */,
7796                                                  ciInstanceKlass * fromKls /* nullptr */) {
7797   if (fromKls == nullptr) {
7798     const TypeInstPtr* tinst = _gvn.type(fromObj)->isa_instptr();
7799     assert(tinst != nullptr, "obj is null");
7800     assert(tinst->is_loaded(), "obj is not loaded");
7801     assert(!is_exact || tinst->klass_is_exact(), "klass not exact");
7802     fromKls = tinst->instance_klass();
7803   }
7804   else {
7805     assert(is_static, "only for static field access");
7806   }
7807   ciField* field = fromKls->get_field_by_name(ciSymbol::make(fieldName),
7808     ciSymbol::make(fieldTypeString),
7809     is_static);
7810 
7811   assert(field != nullptr, "undefined field");
7812   assert(!field->is_volatile(), "not defined for volatile fields");
7813 
7814   if (is_static) {
7815     const TypeInstPtr* tip = TypeInstPtr::make(fromKls->java_mirror());
7816     fromObj = makecon(tip);
7817   }
7818 
7819   // Next code  copied from Parse::do_get_xxx():
7820 
7821   // Compute address and memory type.
7822   int offset = field->offset_in_bytes();
7823   Node *adr = basic_plus_adr(fromObj, fromObj, offset);
7824 
7825   return adr;
7826 }
7827 
7828 //------------------------------inline_aescrypt_Block-----------------------
7829 bool LibraryCallKit::inline_aescrypt_Block(vmIntrinsics::ID id) {
7830   address stubAddr = nullptr;
7831   const char *stubName;
7832   bool is_decrypt = false;
7833   assert(UseAES, "need AES instruction support");
7834 
7835   switch(id) {
7836   case vmIntrinsics::_aescrypt_encryptBlock:
7837     stubAddr = StubRoutines::aescrypt_encryptBlock();
7838     stubName = "aescrypt_encryptBlock";
7839     break;
7840   case vmIntrinsics::_aescrypt_decryptBlock:
7841     stubAddr = StubRoutines::aescrypt_decryptBlock();
7842     stubName = "aescrypt_decryptBlock";
7843     is_decrypt = true;
7844     break;
7845   default:
7846     break;
7847   }
7848   if (stubAddr == nullptr) return false;
7849 
7850   Node* aescrypt_object = argument(0);
7851   Node* src             = argument(1);
7852   Node* src_offset      = argument(2);
7853   Node* dest            = argument(3);
7854   Node* dest_offset     = argument(4);
7855 
7856   src = must_be_not_null(src, true);
7857   dest = must_be_not_null(dest, true);
7858 
7859   // (1) src and dest are arrays.
7860   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7861   const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
7862   assert( src_type != nullptr &&  src_type->elem() != Type::BOTTOM &&
7863          dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
7864 
7865   // for the quick and dirty code we will skip all the checks.
7866   // we are just trying to get the call to be generated.
7867   Node* src_start  = src;
7868   Node* dest_start = dest;
7869   if (src_offset != nullptr || dest_offset != nullptr) {
7870     assert(src_offset != nullptr && dest_offset != nullptr, "");
7871     src_start  = array_element_address(src,  src_offset,  T_BYTE);
7872     dest_start = array_element_address(dest, dest_offset, T_BYTE);
7873   }
7874 
7875   // now need to get the start of its expanded key array
7876   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
7877   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object, is_decrypt);
7878   if (k_start == nullptr) return false;
7879 
7880   // Call the stub.
7881   make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::aescrypt_block_Type(),
7882                     stubAddr, stubName, TypePtr::BOTTOM,
7883                     src_start, dest_start, k_start);
7884 
7885   return true;
7886 }
7887 
7888 //------------------------------inline_cipherBlockChaining_AESCrypt-----------------------
7889 bool LibraryCallKit::inline_cipherBlockChaining_AESCrypt(vmIntrinsics::ID id) {
7890   address stubAddr = nullptr;
7891   const char *stubName = nullptr;
7892   bool is_decrypt = false;
7893   assert(UseAES, "need AES instruction support");
7894 
7895   switch(id) {
7896   case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
7897     stubAddr = StubRoutines::cipherBlockChaining_encryptAESCrypt();
7898     stubName = "cipherBlockChaining_encryptAESCrypt";
7899     break;
7900   case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
7901     stubAddr = StubRoutines::cipherBlockChaining_decryptAESCrypt();
7902     stubName = "cipherBlockChaining_decryptAESCrypt";
7903     is_decrypt = true;
7904     break;
7905   default:
7906     break;
7907   }
7908   if (stubAddr == nullptr) return false;
7909 
7910   Node* cipherBlockChaining_object = argument(0);
7911   Node* src                        = argument(1);
7912   Node* src_offset                 = argument(2);
7913   Node* len                        = argument(3);
7914   Node* dest                       = argument(4);
7915   Node* dest_offset                = argument(5);
7916 
7917   src = must_be_not_null(src, false);
7918   dest = must_be_not_null(dest, false);
7919 
7920   // (1) src and dest are arrays.
7921   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7922   const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
7923   assert( src_type != nullptr &&  src_type->elem() != Type::BOTTOM &&
7924          dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
7925 
7926   // checks are the responsibility of the caller
7927   Node* src_start  = src;
7928   Node* dest_start = dest;
7929   if (src_offset != nullptr || dest_offset != nullptr) {
7930     assert(src_offset != nullptr && dest_offset != nullptr, "");
7931     src_start  = array_element_address(src,  src_offset,  T_BYTE);
7932     dest_start = array_element_address(dest, dest_offset, T_BYTE);
7933   }
7934 
7935   // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
7936   // (because of the predicated logic executed earlier).
7937   // so we cast it here safely.
7938   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
7939 
7940   Node* embeddedCipherObj = load_field_from_object(cipherBlockChaining_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
7941   if (embeddedCipherObj == nullptr) return false;
7942 
7943   // cast it to what we know it will be at runtime
7944   const TypeInstPtr* tinst = _gvn.type(cipherBlockChaining_object)->isa_instptr();
7945   assert(tinst != nullptr, "CBC obj is null");
7946   assert(tinst->is_loaded(), "CBC obj is not loaded");
7947   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
7948   assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
7949 
7950   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
7951   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
7952   const TypeOopPtr* xtype = aklass->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
7953   Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
7954   aescrypt_object = _gvn.transform(aescrypt_object);
7955 
7956   // we need to get the start of the aescrypt_object's expanded key array
7957   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object, is_decrypt);
7958   if (k_start == nullptr) return false;
7959 
7960   // similarly, get the start address of the r vector
7961   Node* objRvec = load_field_from_object(cipherBlockChaining_object, "r", "[B");
7962   if (objRvec == nullptr) return false;
7963   Node* r_start = array_element_address(objRvec, intcon(0), T_BYTE);
7964 
7965   // Call the stub, passing src_start, dest_start, k_start, r_start and src_len
7966   Node* cbcCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
7967                                      OptoRuntime::cipherBlockChaining_aescrypt_Type(),
7968                                      stubAddr, stubName, TypePtr::BOTTOM,
7969                                      src_start, dest_start, k_start, r_start, len);
7970 
7971   // return cipher length (int)
7972   Node* retvalue = _gvn.transform(new ProjNode(cbcCrypt, TypeFunc::Parms));
7973   set_result(retvalue);
7974   return true;
7975 }
7976 
7977 //------------------------------inline_electronicCodeBook_AESCrypt-----------------------
7978 bool LibraryCallKit::inline_electronicCodeBook_AESCrypt(vmIntrinsics::ID id) {
7979   address stubAddr = nullptr;
7980   const char *stubName = nullptr;
7981   bool is_decrypt = false;
7982   assert(UseAES, "need AES instruction support");
7983 
7984   switch (id) {
7985   case vmIntrinsics::_electronicCodeBook_encryptAESCrypt:
7986     stubAddr = StubRoutines::electronicCodeBook_encryptAESCrypt();
7987     stubName = "electronicCodeBook_encryptAESCrypt";
7988     break;
7989   case vmIntrinsics::_electronicCodeBook_decryptAESCrypt:
7990     stubAddr = StubRoutines::electronicCodeBook_decryptAESCrypt();
7991     stubName = "electronicCodeBook_decryptAESCrypt";
7992     is_decrypt = true;
7993     break;
7994   default:
7995     break;
7996   }
7997 
7998   if (stubAddr == nullptr) return false;
7999 
8000   Node* electronicCodeBook_object = argument(0);
8001   Node* src                       = argument(1);
8002   Node* src_offset                = argument(2);
8003   Node* len                       = argument(3);
8004   Node* dest                      = argument(4);
8005   Node* dest_offset               = argument(5);
8006 
8007   // (1) src and dest are arrays.
8008   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
8009   const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
8010   assert( src_type != nullptr &&  src_type->elem() != Type::BOTTOM &&
8011          dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
8012 
8013   // checks are the responsibility of the caller
8014   Node* src_start = src;
8015   Node* dest_start = dest;
8016   if (src_offset != nullptr || dest_offset != nullptr) {
8017     assert(src_offset != nullptr && dest_offset != nullptr, "");
8018     src_start = array_element_address(src, src_offset, T_BYTE);
8019     dest_start = array_element_address(dest, dest_offset, T_BYTE);
8020   }
8021 
8022   // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
8023   // (because of the predicated logic executed earlier).
8024   // so we cast it here safely.
8025   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
8026 
8027   Node* embeddedCipherObj = load_field_from_object(electronicCodeBook_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8028   if (embeddedCipherObj == nullptr) return false;
8029 
8030   // cast it to what we know it will be at runtime
8031   const TypeInstPtr* tinst = _gvn.type(electronicCodeBook_object)->isa_instptr();
8032   assert(tinst != nullptr, "ECB obj is null");
8033   assert(tinst->is_loaded(), "ECB obj is not loaded");
8034   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8035   assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
8036 
8037   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8038   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
8039   const TypeOopPtr* xtype = aklass->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
8040   Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
8041   aescrypt_object = _gvn.transform(aescrypt_object);
8042 
8043   // we need to get the start of the aescrypt_object's expanded key array
8044   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object, is_decrypt);
8045   if (k_start == nullptr) return false;
8046 
8047   // Call the stub, passing src_start, dest_start, k_start, r_start and src_len
8048   Node* ecbCrypt = make_runtime_call(RC_LEAF | RC_NO_FP,
8049                                      OptoRuntime::electronicCodeBook_aescrypt_Type(),
8050                                      stubAddr, stubName, TypePtr::BOTTOM,
8051                                      src_start, dest_start, k_start, len);
8052 
8053   // return cipher length (int)
8054   Node* retvalue = _gvn.transform(new ProjNode(ecbCrypt, TypeFunc::Parms));
8055   set_result(retvalue);
8056   return true;
8057 }
8058 
8059 //------------------------------inline_counterMode_AESCrypt-----------------------
8060 bool LibraryCallKit::inline_counterMode_AESCrypt(vmIntrinsics::ID id) {
8061   assert(UseAES, "need AES instruction support");
8062   if (!UseAESCTRIntrinsics) return false;
8063 
8064   address stubAddr = nullptr;
8065   const char *stubName = nullptr;
8066   if (id == vmIntrinsics::_counterMode_AESCrypt) {
8067     stubAddr = StubRoutines::counterMode_AESCrypt();
8068     stubName = "counterMode_AESCrypt";
8069   }
8070   if (stubAddr == nullptr) return false;
8071 
8072   Node* counterMode_object = argument(0);
8073   Node* src = argument(1);
8074   Node* src_offset = argument(2);
8075   Node* len = argument(3);
8076   Node* dest = argument(4);
8077   Node* dest_offset = argument(5);
8078 
8079   // (1) src and dest are arrays.
8080   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
8081   const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
8082   assert( src_type != nullptr &&  src_type->elem() != Type::BOTTOM &&
8083          dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
8084 
8085   // checks are the responsibility of the caller
8086   Node* src_start = src;
8087   Node* dest_start = dest;
8088   if (src_offset != nullptr || dest_offset != nullptr) {
8089     assert(src_offset != nullptr && dest_offset != nullptr, "");
8090     src_start = array_element_address(src, src_offset, T_BYTE);
8091     dest_start = array_element_address(dest, dest_offset, T_BYTE);
8092   }
8093 
8094   // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
8095   // (because of the predicated logic executed earlier).
8096   // so we cast it here safely.
8097   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
8098   Node* embeddedCipherObj = load_field_from_object(counterMode_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8099   if (embeddedCipherObj == nullptr) return false;
8100   // cast it to what we know it will be at runtime
8101   const TypeInstPtr* tinst = _gvn.type(counterMode_object)->isa_instptr();
8102   assert(tinst != nullptr, "CTR obj is null");
8103   assert(tinst->is_loaded(), "CTR obj is not loaded");
8104   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8105   assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
8106   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8107   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
8108   const TypeOopPtr* xtype = aklass->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
8109   Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
8110   aescrypt_object = _gvn.transform(aescrypt_object);
8111   // we need to get the start of the aescrypt_object's expanded key array
8112   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object, /* is_decrypt */ false);
8113   if (k_start == nullptr) return false;
8114   // similarly, get the start address of the r vector
8115   Node* obj_counter = load_field_from_object(counterMode_object, "counter", "[B");
8116   if (obj_counter == nullptr) return false;
8117   Node* cnt_start = array_element_address(obj_counter, intcon(0), T_BYTE);
8118 
8119   Node* saved_encCounter = load_field_from_object(counterMode_object, "encryptedCounter", "[B");
8120   if (saved_encCounter == nullptr) return false;
8121   Node* saved_encCounter_start = array_element_address(saved_encCounter, intcon(0), T_BYTE);
8122   Node* used = field_address_from_object(counterMode_object, "used", "I", /*is_exact*/ false);
8123 
8124   // Call the stub, passing src_start, dest_start, k_start, r_start and src_len
8125   Node* ctrCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
8126                                      OptoRuntime::counterMode_aescrypt_Type(),
8127                                      stubAddr, stubName, TypePtr::BOTTOM,
8128                                      src_start, dest_start, k_start, cnt_start, len, saved_encCounter_start, used);
8129 
8130   // return cipher length (int)
8131   Node* retvalue = _gvn.transform(new ProjNode(ctrCrypt, TypeFunc::Parms));
8132   set_result(retvalue);
8133   return true;
8134 }
8135 
8136 //------------------------------get_key_start_from_aescrypt_object-----------------------
8137 Node* LibraryCallKit::get_key_start_from_aescrypt_object(Node* aescrypt_object, bool is_decrypt) {
8138   // MixColumns for decryption can be reduced by preprocessing MixColumns with round keys.
8139   // Intel's extension is based on this optimization and AESCrypt generates round keys by preprocessing MixColumns.
8140   // However, ppc64 vncipher processes MixColumns and requires the same round keys with encryption.
8141   // The following platform specific stubs of encryption and decryption use the same round keys.
8142 #if defined(PPC64) || defined(S390) || defined(RISCV64)
8143   bool use_decryption_key = false;
8144 #else
8145   bool use_decryption_key = is_decrypt;
8146 #endif
8147   Node* objAESCryptKey = load_field_from_object(aescrypt_object, use_decryption_key ? "sessionKd" : "sessionKe", "[I");
8148   assert(objAESCryptKey != nullptr, "wrong version of com.sun.crypto.provider.AES_Crypt");
8149   if (objAESCryptKey == nullptr) return (Node *) nullptr;
8150 
8151   // now have the array, need to get the start address of the selected key array
8152   Node* k_start = array_element_address(objAESCryptKey, intcon(0), T_INT);
8153   return k_start;
8154 }
8155 
8156 //----------------------------inline_cipherBlockChaining_AESCrypt_predicate----------------------------
8157 // Return node representing slow path of predicate check.
8158 // the pseudo code we want to emulate with this predicate is:
8159 // for encryption:
8160 //    if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
8161 // for decryption:
8162 //    if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
8163 //    note cipher==plain is more conservative than the original java code but that's OK
8164 //
8165 Node* LibraryCallKit::inline_cipherBlockChaining_AESCrypt_predicate(bool decrypting) {
8166   // The receiver was checked for null already.
8167   Node* objCBC = argument(0);
8168 
8169   Node* src = argument(1);
8170   Node* dest = argument(4);
8171 
8172   // Load embeddedCipher field of CipherBlockChaining object.
8173   Node* embeddedCipherObj = load_field_from_object(objCBC, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8174 
8175   // get AESCrypt klass for instanceOf check
8176   // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
8177   // will have same classloader as CipherBlockChaining object
8178   const TypeInstPtr* tinst = _gvn.type(objCBC)->isa_instptr();
8179   assert(tinst != nullptr, "CBCobj is null");
8180   assert(tinst->is_loaded(), "CBCobj is not loaded");
8181 
8182   // we want to do an instanceof comparison against the AESCrypt class
8183   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8184   if (!klass_AESCrypt->is_loaded()) {
8185     // if AESCrypt is not even loaded, we never take the intrinsic fast path
8186     Node* ctrl = control();
8187     set_control(top()); // no regular fast path
8188     return ctrl;
8189   }
8190 
8191   src = must_be_not_null(src, true);
8192   dest = must_be_not_null(dest, true);
8193 
8194   // Resolve oops to stable for CmpP below.
8195   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8196 
8197   Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
8198   Node* cmp_instof  = _gvn.transform(new CmpINode(instof, intcon(1)));
8199   Node* bool_instof  = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
8200 
8201   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
8202 
8203   // for encryption, we are done
8204   if (!decrypting)
8205     return instof_false;  // even if it is null
8206 
8207   // for decryption, we need to add a further check to avoid
8208   // taking the intrinsic path when cipher and plain are the same
8209   // see the original java code for why.
8210   RegionNode* region = new RegionNode(3);
8211   region->init_req(1, instof_false);
8212 
8213   Node* cmp_src_dest = _gvn.transform(new CmpPNode(src, dest));
8214   Node* bool_src_dest = _gvn.transform(new BoolNode(cmp_src_dest, BoolTest::eq));
8215   Node* src_dest_conjoint = generate_guard(bool_src_dest, nullptr, PROB_MIN);
8216   region->init_req(2, src_dest_conjoint);
8217 
8218   record_for_igvn(region);
8219   return _gvn.transform(region);
8220 }
8221 
8222 //----------------------------inline_electronicCodeBook_AESCrypt_predicate----------------------------
8223 // Return node representing slow path of predicate check.
8224 // the pseudo code we want to emulate with this predicate is:
8225 // for encryption:
8226 //    if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
8227 // for decryption:
8228 //    if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
8229 //    note cipher==plain is more conservative than the original java code but that's OK
8230 //
8231 Node* LibraryCallKit::inline_electronicCodeBook_AESCrypt_predicate(bool decrypting) {
8232   // The receiver was checked for null already.
8233   Node* objECB = argument(0);
8234 
8235   // Load embeddedCipher field of ElectronicCodeBook object.
8236   Node* embeddedCipherObj = load_field_from_object(objECB, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8237 
8238   // get AESCrypt klass for instanceOf check
8239   // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
8240   // will have same classloader as ElectronicCodeBook object
8241   const TypeInstPtr* tinst = _gvn.type(objECB)->isa_instptr();
8242   assert(tinst != nullptr, "ECBobj is null");
8243   assert(tinst->is_loaded(), "ECBobj is not loaded");
8244 
8245   // we want to do an instanceof comparison against the AESCrypt class
8246   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8247   if (!klass_AESCrypt->is_loaded()) {
8248     // if AESCrypt is not even loaded, we never take the intrinsic fast path
8249     Node* ctrl = control();
8250     set_control(top()); // no regular fast path
8251     return ctrl;
8252   }
8253   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8254 
8255   Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
8256   Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
8257   Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
8258 
8259   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
8260 
8261   // for encryption, we are done
8262   if (!decrypting)
8263     return instof_false;  // even if it is null
8264 
8265   // for decryption, we need to add a further check to avoid
8266   // taking the intrinsic path when cipher and plain are the same
8267   // see the original java code for why.
8268   RegionNode* region = new RegionNode(3);
8269   region->init_req(1, instof_false);
8270   Node* src = argument(1);
8271   Node* dest = argument(4);
8272   Node* cmp_src_dest = _gvn.transform(new CmpPNode(src, dest));
8273   Node* bool_src_dest = _gvn.transform(new BoolNode(cmp_src_dest, BoolTest::eq));
8274   Node* src_dest_conjoint = generate_guard(bool_src_dest, nullptr, PROB_MIN);
8275   region->init_req(2, src_dest_conjoint);
8276 
8277   record_for_igvn(region);
8278   return _gvn.transform(region);
8279 }
8280 
8281 //----------------------------inline_counterMode_AESCrypt_predicate----------------------------
8282 // Return node representing slow path of predicate check.
8283 // the pseudo code we want to emulate with this predicate is:
8284 // for encryption:
8285 //    if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
8286 // for decryption:
8287 //    if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
8288 //    note cipher==plain is more conservative than the original java code but that's OK
8289 //
8290 
8291 Node* LibraryCallKit::inline_counterMode_AESCrypt_predicate() {
8292   // The receiver was checked for null already.
8293   Node* objCTR = argument(0);
8294 
8295   // Load embeddedCipher field of CipherBlockChaining object.
8296   Node* embeddedCipherObj = load_field_from_object(objCTR, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8297 
8298   // get AESCrypt klass for instanceOf check
8299   // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
8300   // will have same classloader as CipherBlockChaining object
8301   const TypeInstPtr* tinst = _gvn.type(objCTR)->isa_instptr();
8302   assert(tinst != nullptr, "CTRobj is null");
8303   assert(tinst->is_loaded(), "CTRobj is not loaded");
8304 
8305   // we want to do an instanceof comparison against the AESCrypt class
8306   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8307   if (!klass_AESCrypt->is_loaded()) {
8308     // if AESCrypt is not even loaded, we never take the intrinsic fast path
8309     Node* ctrl = control();
8310     set_control(top()); // no regular fast path
8311     return ctrl;
8312   }
8313 
8314   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8315   Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
8316   Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
8317   Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
8318   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
8319 
8320   return instof_false; // even if it is null
8321 }
8322 
8323 //------------------------------inline_ghash_processBlocks
8324 bool LibraryCallKit::inline_ghash_processBlocks() {
8325   address stubAddr;
8326   const char *stubName;
8327   assert(UseGHASHIntrinsics, "need GHASH intrinsics support");
8328 
8329   stubAddr = StubRoutines::ghash_processBlocks();
8330   stubName = "ghash_processBlocks";
8331 
8332   Node* data           = argument(0);
8333   Node* offset         = argument(1);
8334   Node* len            = argument(2);
8335   Node* state          = argument(3);
8336   Node* subkeyH        = argument(4);
8337 
8338   state = must_be_not_null(state, true);
8339   subkeyH = must_be_not_null(subkeyH, true);
8340   data = must_be_not_null(data, true);
8341 
8342   Node* state_start  = array_element_address(state, intcon(0), T_LONG);
8343   assert(state_start, "state is null");
8344   Node* subkeyH_start  = array_element_address(subkeyH, intcon(0), T_LONG);
8345   assert(subkeyH_start, "subkeyH is null");
8346   Node* data_start  = array_element_address(data, offset, T_BYTE);
8347   assert(data_start, "data is null");
8348 
8349   Node* ghash = make_runtime_call(RC_LEAF|RC_NO_FP,
8350                                   OptoRuntime::ghash_processBlocks_Type(),
8351                                   stubAddr, stubName, TypePtr::BOTTOM,
8352                                   state_start, subkeyH_start, data_start, len);
8353   return true;
8354 }
8355 
8356 //------------------------------inline_chacha20Block
8357 bool LibraryCallKit::inline_chacha20Block() {
8358   address stubAddr;
8359   const char *stubName;
8360   assert(UseChaCha20Intrinsics, "need ChaCha20 intrinsics support");
8361 
8362   stubAddr = StubRoutines::chacha20Block();
8363   stubName = "chacha20Block";
8364 
8365   Node* state          = argument(0);
8366   Node* result         = argument(1);
8367 
8368   state = must_be_not_null(state, true);
8369   result = must_be_not_null(result, true);
8370 
8371   Node* state_start  = array_element_address(state, intcon(0), T_INT);
8372   assert(state_start, "state is null");
8373   Node* result_start  = array_element_address(result, intcon(0), T_BYTE);
8374   assert(result_start, "result is null");
8375 
8376   Node* cc20Blk = make_runtime_call(RC_LEAF|RC_NO_FP,
8377                                   OptoRuntime::chacha20Block_Type(),
8378                                   stubAddr, stubName, TypePtr::BOTTOM,
8379                                   state_start, result_start);
8380   // return key stream length (int)
8381   Node* retvalue = _gvn.transform(new ProjNode(cc20Blk, TypeFunc::Parms));
8382   set_result(retvalue);
8383   return true;
8384 }
8385 
8386 //------------------------------inline_kyberNtt
8387 bool LibraryCallKit::inline_kyberNtt() {
8388   address stubAddr;
8389   const char *stubName;
8390   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8391   assert(callee()->signature()->size() == 2, "kyberNtt has 2 parameters");
8392 
8393   stubAddr = StubRoutines::kyberNtt();
8394   stubName = "kyberNtt";
8395   if (!stubAddr) return false;
8396 
8397   Node* coeffs          = argument(0);
8398   Node* ntt_zetas        = argument(1);
8399 
8400   coeffs = must_be_not_null(coeffs, true);
8401   ntt_zetas = must_be_not_null(ntt_zetas, true);
8402 
8403   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_SHORT);
8404   assert(coeffs_start, "coeffs is null");
8405   Node* ntt_zetas_start  = array_element_address(ntt_zetas, intcon(0), T_SHORT);
8406   assert(ntt_zetas_start, "ntt_zetas is null");
8407   Node* kyberNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
8408                                   OptoRuntime::kyberNtt_Type(),
8409                                   stubAddr, stubName, TypePtr::BOTTOM,
8410                                   coeffs_start, ntt_zetas_start);
8411   // return an int
8412   Node* retvalue = _gvn.transform(new ProjNode(kyberNtt, TypeFunc::Parms));
8413   set_result(retvalue);
8414   return true;
8415 }
8416 
8417 //------------------------------inline_kyberInverseNtt
8418 bool LibraryCallKit::inline_kyberInverseNtt() {
8419   address stubAddr;
8420   const char *stubName;
8421   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8422   assert(callee()->signature()->size() == 2, "kyberInverseNtt has 2 parameters");
8423 
8424   stubAddr = StubRoutines::kyberInverseNtt();
8425   stubName = "kyberInverseNtt";
8426   if (!stubAddr) return false;
8427 
8428   Node* coeffs          = argument(0);
8429   Node* zetas           = argument(1);
8430 
8431   coeffs = must_be_not_null(coeffs, true);
8432   zetas = must_be_not_null(zetas, true);
8433 
8434   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_SHORT);
8435   assert(coeffs_start, "coeffs is null");
8436   Node* zetas_start  = array_element_address(zetas, intcon(0), T_SHORT);
8437   assert(zetas_start, "inverseNtt_zetas is null");
8438   Node* kyberInverseNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
8439                                   OptoRuntime::kyberInverseNtt_Type(),
8440                                   stubAddr, stubName, TypePtr::BOTTOM,
8441                                   coeffs_start, zetas_start);
8442 
8443   // return an int
8444   Node* retvalue = _gvn.transform(new ProjNode(kyberInverseNtt, TypeFunc::Parms));
8445   set_result(retvalue);
8446   return true;
8447 }
8448 
8449 //------------------------------inline_kyberNttMult
8450 bool LibraryCallKit::inline_kyberNttMult() {
8451   address stubAddr;
8452   const char *stubName;
8453   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8454   assert(callee()->signature()->size() == 4, "kyberNttMult has 4 parameters");
8455 
8456   stubAddr = StubRoutines::kyberNttMult();
8457   stubName = "kyberNttMult";
8458   if (!stubAddr) return false;
8459 
8460   Node* result          = argument(0);
8461   Node* ntta            = argument(1);
8462   Node* nttb            = argument(2);
8463   Node* zetas           = argument(3);
8464 
8465   result = must_be_not_null(result, true);
8466   ntta = must_be_not_null(ntta, true);
8467   nttb = must_be_not_null(nttb, true);
8468   zetas = must_be_not_null(zetas, true);
8469 
8470   Node* result_start  = array_element_address(result, intcon(0), T_SHORT);
8471   assert(result_start, "result is null");
8472   Node* ntta_start  = array_element_address(ntta, intcon(0), T_SHORT);
8473   assert(ntta_start, "ntta is null");
8474   Node* nttb_start  = array_element_address(nttb, intcon(0), T_SHORT);
8475   assert(nttb_start, "nttb is null");
8476   Node* zetas_start  = array_element_address(zetas, intcon(0), T_SHORT);
8477   assert(zetas_start, "nttMult_zetas is null");
8478   Node* kyberNttMult = make_runtime_call(RC_LEAF|RC_NO_FP,
8479                                   OptoRuntime::kyberNttMult_Type(),
8480                                   stubAddr, stubName, TypePtr::BOTTOM,
8481                                   result_start, ntta_start, nttb_start,
8482                                   zetas_start);
8483 
8484   // return an int
8485   Node* retvalue = _gvn.transform(new ProjNode(kyberNttMult, TypeFunc::Parms));
8486   set_result(retvalue);
8487 
8488   return true;
8489 }
8490 
8491 //------------------------------inline_kyberAddPoly_2
8492 bool LibraryCallKit::inline_kyberAddPoly_2() {
8493   address stubAddr;
8494   const char *stubName;
8495   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8496   assert(callee()->signature()->size() == 3, "kyberAddPoly_2 has 3 parameters");
8497 
8498   stubAddr = StubRoutines::kyberAddPoly_2();
8499   stubName = "kyberAddPoly_2";
8500   if (!stubAddr) return false;
8501 
8502   Node* result          = argument(0);
8503   Node* a               = argument(1);
8504   Node* b               = argument(2);
8505 
8506   result = must_be_not_null(result, true);
8507   a = must_be_not_null(a, true);
8508   b = must_be_not_null(b, true);
8509 
8510   Node* result_start  = array_element_address(result, intcon(0), T_SHORT);
8511   assert(result_start, "result is null");
8512   Node* a_start  = array_element_address(a, intcon(0), T_SHORT);
8513   assert(a_start, "a is null");
8514   Node* b_start  = array_element_address(b, intcon(0), T_SHORT);
8515   assert(b_start, "b is null");
8516   Node* kyberAddPoly_2 = make_runtime_call(RC_LEAF|RC_NO_FP,
8517                                   OptoRuntime::kyberAddPoly_2_Type(),
8518                                   stubAddr, stubName, TypePtr::BOTTOM,
8519                                   result_start, a_start, b_start);
8520   // return an int
8521   Node* retvalue = _gvn.transform(new ProjNode(kyberAddPoly_2, TypeFunc::Parms));
8522   set_result(retvalue);
8523   return true;
8524 }
8525 
8526 //------------------------------inline_kyberAddPoly_3
8527 bool LibraryCallKit::inline_kyberAddPoly_3() {
8528   address stubAddr;
8529   const char *stubName;
8530   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8531   assert(callee()->signature()->size() == 4, "kyberAddPoly_3 has 4 parameters");
8532 
8533   stubAddr = StubRoutines::kyberAddPoly_3();
8534   stubName = "kyberAddPoly_3";
8535   if (!stubAddr) return false;
8536 
8537   Node* result          = argument(0);
8538   Node* a               = argument(1);
8539   Node* b               = argument(2);
8540   Node* c               = argument(3);
8541 
8542   result = must_be_not_null(result, true);
8543   a = must_be_not_null(a, true);
8544   b = must_be_not_null(b, true);
8545   c = must_be_not_null(c, true);
8546 
8547   Node* result_start  = array_element_address(result, intcon(0), T_SHORT);
8548   assert(result_start, "result is null");
8549   Node* a_start  = array_element_address(a, intcon(0), T_SHORT);
8550   assert(a_start, "a is null");
8551   Node* b_start  = array_element_address(b, intcon(0), T_SHORT);
8552   assert(b_start, "b is null");
8553   Node* c_start  = array_element_address(c, intcon(0), T_SHORT);
8554   assert(c_start, "c is null");
8555   Node* kyberAddPoly_3 = make_runtime_call(RC_LEAF|RC_NO_FP,
8556                                   OptoRuntime::kyberAddPoly_3_Type(),
8557                                   stubAddr, stubName, TypePtr::BOTTOM,
8558                                   result_start, a_start, b_start, c_start);
8559   // return an int
8560   Node* retvalue = _gvn.transform(new ProjNode(kyberAddPoly_3, TypeFunc::Parms));
8561   set_result(retvalue);
8562   return true;
8563 }
8564 
8565 //------------------------------inline_kyber12To16
8566 bool LibraryCallKit::inline_kyber12To16() {
8567   address stubAddr;
8568   const char *stubName;
8569   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8570   assert(callee()->signature()->size() == 4, "kyber12To16 has 4 parameters");
8571 
8572   stubAddr = StubRoutines::kyber12To16();
8573   stubName = "kyber12To16";
8574   if (!stubAddr) return false;
8575 
8576   Node* condensed       = argument(0);
8577   Node* condensedOffs   = argument(1);
8578   Node* parsed          = argument(2);
8579   Node* parsedLength    = argument(3);
8580 
8581   condensed = must_be_not_null(condensed, true);
8582   parsed = must_be_not_null(parsed, true);
8583 
8584   Node* condensed_start  = array_element_address(condensed, intcon(0), T_BYTE);
8585   assert(condensed_start, "condensed is null");
8586   Node* parsed_start  = array_element_address(parsed, intcon(0), T_SHORT);
8587   assert(parsed_start, "parsed is null");
8588   Node* kyber12To16 = make_runtime_call(RC_LEAF|RC_NO_FP,
8589                                   OptoRuntime::kyber12To16_Type(),
8590                                   stubAddr, stubName, TypePtr::BOTTOM,
8591                                   condensed_start, condensedOffs, parsed_start, parsedLength);
8592   // return an int
8593   Node* retvalue = _gvn.transform(new ProjNode(kyber12To16, TypeFunc::Parms));
8594   set_result(retvalue);
8595   return true;
8596 
8597 }
8598 
8599 //------------------------------inline_kyberBarrettReduce
8600 bool LibraryCallKit::inline_kyberBarrettReduce() {
8601   address stubAddr;
8602   const char *stubName;
8603   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8604   assert(callee()->signature()->size() == 1, "kyberBarrettReduce has 1 parameters");
8605 
8606   stubAddr = StubRoutines::kyberBarrettReduce();
8607   stubName = "kyberBarrettReduce";
8608   if (!stubAddr) return false;
8609 
8610   Node* coeffs          = argument(0);
8611 
8612   coeffs = must_be_not_null(coeffs, true);
8613 
8614   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_SHORT);
8615   assert(coeffs_start, "coeffs is null");
8616   Node* kyberBarrettReduce = make_runtime_call(RC_LEAF|RC_NO_FP,
8617                                   OptoRuntime::kyberBarrettReduce_Type(),
8618                                   stubAddr, stubName, TypePtr::BOTTOM,
8619                                   coeffs_start);
8620   // return an int
8621   Node* retvalue = _gvn.transform(new ProjNode(kyberBarrettReduce, TypeFunc::Parms));
8622   set_result(retvalue);
8623   return true;
8624 }
8625 
8626 //------------------------------inline_dilithiumAlmostNtt
8627 bool LibraryCallKit::inline_dilithiumAlmostNtt() {
8628   address stubAddr;
8629   const char *stubName;
8630   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8631   assert(callee()->signature()->size() == 2, "dilithiumAlmostNtt has 2 parameters");
8632 
8633   stubAddr = StubRoutines::dilithiumAlmostNtt();
8634   stubName = "dilithiumAlmostNtt";
8635   if (!stubAddr) return false;
8636 
8637   Node* coeffs          = argument(0);
8638   Node* ntt_zetas        = argument(1);
8639 
8640   coeffs = must_be_not_null(coeffs, true);
8641   ntt_zetas = must_be_not_null(ntt_zetas, true);
8642 
8643   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_INT);
8644   assert(coeffs_start, "coeffs is null");
8645   Node* ntt_zetas_start  = array_element_address(ntt_zetas, intcon(0), T_INT);
8646   assert(ntt_zetas_start, "ntt_zetas is null");
8647   Node* dilithiumAlmostNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
8648                                   OptoRuntime::dilithiumAlmostNtt_Type(),
8649                                   stubAddr, stubName, TypePtr::BOTTOM,
8650                                   coeffs_start, ntt_zetas_start);
8651   // return an int
8652   Node* retvalue = _gvn.transform(new ProjNode(dilithiumAlmostNtt, TypeFunc::Parms));
8653   set_result(retvalue);
8654   return true;
8655 }
8656 
8657 //------------------------------inline_dilithiumAlmostInverseNtt
8658 bool LibraryCallKit::inline_dilithiumAlmostInverseNtt() {
8659   address stubAddr;
8660   const char *stubName;
8661   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8662   assert(callee()->signature()->size() == 2, "dilithiumAlmostInverseNtt has 2 parameters");
8663 
8664   stubAddr = StubRoutines::dilithiumAlmostInverseNtt();
8665   stubName = "dilithiumAlmostInverseNtt";
8666   if (!stubAddr) return false;
8667 
8668   Node* coeffs          = argument(0);
8669   Node* zetas           = argument(1);
8670 
8671   coeffs = must_be_not_null(coeffs, true);
8672   zetas = must_be_not_null(zetas, true);
8673 
8674   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_INT);
8675   assert(coeffs_start, "coeffs is null");
8676   Node* zetas_start  = array_element_address(zetas, intcon(0), T_INT);
8677   assert(zetas_start, "inverseNtt_zetas is null");
8678   Node* dilithiumAlmostInverseNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
8679                                   OptoRuntime::dilithiumAlmostInverseNtt_Type(),
8680                                   stubAddr, stubName, TypePtr::BOTTOM,
8681                                   coeffs_start, zetas_start);
8682   // return an int
8683   Node* retvalue = _gvn.transform(new ProjNode(dilithiumAlmostInverseNtt, TypeFunc::Parms));
8684   set_result(retvalue);
8685   return true;
8686 }
8687 
8688 //------------------------------inline_dilithiumNttMult
8689 bool LibraryCallKit::inline_dilithiumNttMult() {
8690   address stubAddr;
8691   const char *stubName;
8692   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8693   assert(callee()->signature()->size() == 3, "dilithiumNttMult has 3 parameters");
8694 
8695   stubAddr = StubRoutines::dilithiumNttMult();
8696   stubName = "dilithiumNttMult";
8697   if (!stubAddr) return false;
8698 
8699   Node* result          = argument(0);
8700   Node* ntta            = argument(1);
8701   Node* nttb            = argument(2);
8702   Node* zetas           = argument(3);
8703 
8704   result = must_be_not_null(result, true);
8705   ntta = must_be_not_null(ntta, true);
8706   nttb = must_be_not_null(nttb, true);
8707   zetas = must_be_not_null(zetas, true);
8708 
8709   Node* result_start  = array_element_address(result, intcon(0), T_INT);
8710   assert(result_start, "result is null");
8711   Node* ntta_start  = array_element_address(ntta, intcon(0), T_INT);
8712   assert(ntta_start, "ntta is null");
8713   Node* nttb_start  = array_element_address(nttb, intcon(0), T_INT);
8714   assert(nttb_start, "nttb is null");
8715   Node* dilithiumNttMult = make_runtime_call(RC_LEAF|RC_NO_FP,
8716                                   OptoRuntime::dilithiumNttMult_Type(),
8717                                   stubAddr, stubName, TypePtr::BOTTOM,
8718                                   result_start, ntta_start, nttb_start);
8719 
8720   // return an int
8721   Node* retvalue = _gvn.transform(new ProjNode(dilithiumNttMult, TypeFunc::Parms));
8722   set_result(retvalue);
8723 
8724   return true;
8725 }
8726 
8727 //------------------------------inline_dilithiumMontMulByConstant
8728 bool LibraryCallKit::inline_dilithiumMontMulByConstant() {
8729   address stubAddr;
8730   const char *stubName;
8731   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8732   assert(callee()->signature()->size() == 2, "dilithiumMontMulByConstant has 2 parameters");
8733 
8734   stubAddr = StubRoutines::dilithiumMontMulByConstant();
8735   stubName = "dilithiumMontMulByConstant";
8736   if (!stubAddr) return false;
8737 
8738   Node* coeffs          = argument(0);
8739   Node* constant        = argument(1);
8740 
8741   coeffs = must_be_not_null(coeffs, true);
8742 
8743   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_INT);
8744   assert(coeffs_start, "coeffs is null");
8745   Node* dilithiumMontMulByConstant = make_runtime_call(RC_LEAF|RC_NO_FP,
8746                                   OptoRuntime::dilithiumMontMulByConstant_Type(),
8747                                   stubAddr, stubName, TypePtr::BOTTOM,
8748                                   coeffs_start, constant);
8749 
8750   // return an int
8751   Node* retvalue = _gvn.transform(new ProjNode(dilithiumMontMulByConstant, TypeFunc::Parms));
8752   set_result(retvalue);
8753   return true;
8754 }
8755 
8756 
8757 //------------------------------inline_dilithiumDecomposePoly
8758 bool LibraryCallKit::inline_dilithiumDecomposePoly() {
8759   address stubAddr;
8760   const char *stubName;
8761   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8762   assert(callee()->signature()->size() == 5, "dilithiumDecomposePoly has 5 parameters");
8763 
8764   stubAddr = StubRoutines::dilithiumDecomposePoly();
8765   stubName = "dilithiumDecomposePoly";
8766   if (!stubAddr) return false;
8767 
8768   Node* input          = argument(0);
8769   Node* lowPart        = argument(1);
8770   Node* highPart       = argument(2);
8771   Node* twoGamma2      = argument(3);
8772   Node* multiplier     = argument(4);
8773 
8774   input = must_be_not_null(input, true);
8775   lowPart = must_be_not_null(lowPart, true);
8776   highPart = must_be_not_null(highPart, true);
8777 
8778   Node* input_start  = array_element_address(input, intcon(0), T_INT);
8779   assert(input_start, "input is null");
8780   Node* lowPart_start  = array_element_address(lowPart, intcon(0), T_INT);
8781   assert(lowPart_start, "lowPart is null");
8782   Node* highPart_start  = array_element_address(highPart, intcon(0), T_INT);
8783   assert(highPart_start, "highPart is null");
8784 
8785   Node* dilithiumDecomposePoly = make_runtime_call(RC_LEAF|RC_NO_FP,
8786                                   OptoRuntime::dilithiumDecomposePoly_Type(),
8787                                   stubAddr, stubName, TypePtr::BOTTOM,
8788                                   input_start, lowPart_start, highPart_start,
8789                                   twoGamma2, multiplier);
8790 
8791   // return an int
8792   Node* retvalue = _gvn.transform(new ProjNode(dilithiumDecomposePoly, TypeFunc::Parms));
8793   set_result(retvalue);
8794   return true;
8795 }
8796 
8797 bool LibraryCallKit::inline_base64_encodeBlock() {
8798   address stubAddr;
8799   const char *stubName;
8800   assert(UseBASE64Intrinsics, "need Base64 intrinsics support");
8801   assert(callee()->signature()->size() == 6, "base64_encodeBlock has 6 parameters");
8802   stubAddr = StubRoutines::base64_encodeBlock();
8803   stubName = "encodeBlock";
8804 
8805   if (!stubAddr) return false;
8806   Node* base64obj = argument(0);
8807   Node* src = argument(1);
8808   Node* offset = argument(2);
8809   Node* len = argument(3);
8810   Node* dest = argument(4);
8811   Node* dp = argument(5);
8812   Node* isURL = argument(6);
8813 
8814   src = must_be_not_null(src, true);
8815   dest = must_be_not_null(dest, true);
8816 
8817   Node* src_start = array_element_address(src, intcon(0), T_BYTE);
8818   assert(src_start, "source array is null");
8819   Node* dest_start = array_element_address(dest, intcon(0), T_BYTE);
8820   assert(dest_start, "destination array is null");
8821 
8822   Node* base64 = make_runtime_call(RC_LEAF,
8823                                    OptoRuntime::base64_encodeBlock_Type(),
8824                                    stubAddr, stubName, TypePtr::BOTTOM,
8825                                    src_start, offset, len, dest_start, dp, isURL);
8826   return true;
8827 }
8828 
8829 bool LibraryCallKit::inline_base64_decodeBlock() {
8830   address stubAddr;
8831   const char *stubName;
8832   assert(UseBASE64Intrinsics, "need Base64 intrinsics support");
8833   assert(callee()->signature()->size() == 7, "base64_decodeBlock has 7 parameters");
8834   stubAddr = StubRoutines::base64_decodeBlock();
8835   stubName = "decodeBlock";
8836 
8837   if (!stubAddr) return false;
8838   Node* base64obj = argument(0);
8839   Node* src = argument(1);
8840   Node* src_offset = argument(2);
8841   Node* len = argument(3);
8842   Node* dest = argument(4);
8843   Node* dest_offset = argument(5);
8844   Node* isURL = argument(6);
8845   Node* isMIME = argument(7);
8846 
8847   src = must_be_not_null(src, true);
8848   dest = must_be_not_null(dest, true);
8849 
8850   Node* src_start = array_element_address(src, intcon(0), T_BYTE);
8851   assert(src_start, "source array is null");
8852   Node* dest_start = array_element_address(dest, intcon(0), T_BYTE);
8853   assert(dest_start, "destination array is null");
8854 
8855   Node* call = make_runtime_call(RC_LEAF,
8856                                  OptoRuntime::base64_decodeBlock_Type(),
8857                                  stubAddr, stubName, TypePtr::BOTTOM,
8858                                  src_start, src_offset, len, dest_start, dest_offset, isURL, isMIME);
8859   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
8860   set_result(result);
8861   return true;
8862 }
8863 
8864 bool LibraryCallKit::inline_poly1305_processBlocks() {
8865   address stubAddr;
8866   const char *stubName;
8867   assert(UsePoly1305Intrinsics, "need Poly intrinsics support");
8868   assert(callee()->signature()->size() == 5, "poly1305_processBlocks has %d parameters", callee()->signature()->size());
8869   stubAddr = StubRoutines::poly1305_processBlocks();
8870   stubName = "poly1305_processBlocks";
8871 
8872   if (!stubAddr) return false;
8873   null_check_receiver();  // null-check receiver
8874   if (stopped())  return true;
8875 
8876   Node* input = argument(1);
8877   Node* input_offset = argument(2);
8878   Node* len = argument(3);
8879   Node* alimbs = argument(4);
8880   Node* rlimbs = argument(5);
8881 
8882   input = must_be_not_null(input, true);
8883   alimbs = must_be_not_null(alimbs, true);
8884   rlimbs = must_be_not_null(rlimbs, true);
8885 
8886   Node* input_start = array_element_address(input, input_offset, T_BYTE);
8887   assert(input_start, "input array is null");
8888   Node* acc_start = array_element_address(alimbs, intcon(0), T_LONG);
8889   assert(acc_start, "acc array is null");
8890   Node* r_start = array_element_address(rlimbs, intcon(0), T_LONG);
8891   assert(r_start, "r array is null");
8892 
8893   Node* call = make_runtime_call(RC_LEAF | RC_NO_FP,
8894                                  OptoRuntime::poly1305_processBlocks_Type(),
8895                                  stubAddr, stubName, TypePtr::BOTTOM,
8896                                  input_start, len, acc_start, r_start);
8897   return true;
8898 }
8899 
8900 bool LibraryCallKit::inline_intpoly_montgomeryMult_P256() {
8901   address stubAddr;
8902   const char *stubName;
8903   assert(UseIntPolyIntrinsics, "need intpoly intrinsics support");
8904   assert(callee()->signature()->size() == 3, "intpoly_montgomeryMult_P256 has %d parameters", callee()->signature()->size());
8905   stubAddr = StubRoutines::intpoly_montgomeryMult_P256();
8906   stubName = "intpoly_montgomeryMult_P256";
8907 
8908   if (!stubAddr) return false;
8909   null_check_receiver();  // null-check receiver
8910   if (stopped())  return true;
8911 
8912   Node* a = argument(1);
8913   Node* b = argument(2);
8914   Node* r = argument(3);
8915 
8916   a = must_be_not_null(a, true);
8917   b = must_be_not_null(b, true);
8918   r = must_be_not_null(r, true);
8919 
8920   Node* a_start = array_element_address(a, intcon(0), T_LONG);
8921   assert(a_start, "a array is null");
8922   Node* b_start = array_element_address(b, intcon(0), T_LONG);
8923   assert(b_start, "b array is null");
8924   Node* r_start = array_element_address(r, intcon(0), T_LONG);
8925   assert(r_start, "r array is null");
8926 
8927   Node* call = make_runtime_call(RC_LEAF | RC_NO_FP,
8928                                  OptoRuntime::intpoly_montgomeryMult_P256_Type(),
8929                                  stubAddr, stubName, TypePtr::BOTTOM,
8930                                  a_start, b_start, r_start);
8931   return true;
8932 }
8933 
8934 bool LibraryCallKit::inline_intpoly_assign() {
8935   assert(UseIntPolyIntrinsics, "need intpoly intrinsics support");
8936   assert(callee()->signature()->size() == 3, "intpoly_assign has %d parameters", callee()->signature()->size());
8937   const char *stubName = "intpoly_assign";
8938   address stubAddr = StubRoutines::intpoly_assign();
8939   if (!stubAddr) return false;
8940 
8941   Node* set = argument(0);
8942   Node* a = argument(1);
8943   Node* b = argument(2);
8944   Node* arr_length = load_array_length(a);
8945 
8946   a = must_be_not_null(a, true);
8947   b = must_be_not_null(b, true);
8948 
8949   Node* a_start = array_element_address(a, intcon(0), T_LONG);
8950   assert(a_start, "a array is null");
8951   Node* b_start = array_element_address(b, intcon(0), T_LONG);
8952   assert(b_start, "b array is null");
8953 
8954   Node* call = make_runtime_call(RC_LEAF | RC_NO_FP,
8955                                  OptoRuntime::intpoly_assign_Type(),
8956                                  stubAddr, stubName, TypePtr::BOTTOM,
8957                                  set, a_start, b_start, arr_length);
8958   return true;
8959 }
8960 
8961 //------------------------------inline_digestBase_implCompress-----------------------
8962 //
8963 // Calculate MD5 for single-block byte[] array.
8964 // void com.sun.security.provider.MD5.implCompress(byte[] buf, int ofs)
8965 //
8966 // Calculate SHA (i.e., SHA-1) for single-block byte[] array.
8967 // void com.sun.security.provider.SHA.implCompress(byte[] buf, int ofs)
8968 //
8969 // Calculate SHA2 (i.e., SHA-244 or SHA-256) for single-block byte[] array.
8970 // void com.sun.security.provider.SHA2.implCompress(byte[] buf, int ofs)
8971 //
8972 // Calculate SHA5 (i.e., SHA-384 or SHA-512) for single-block byte[] array.
8973 // void com.sun.security.provider.SHA5.implCompress(byte[] buf, int ofs)
8974 //
8975 // Calculate SHA3 (i.e., SHA3-224 or SHA3-256 or SHA3-384 or SHA3-512) for single-block byte[] array.
8976 // void com.sun.security.provider.SHA3.implCompress(byte[] buf, int ofs)
8977 //
8978 bool LibraryCallKit::inline_digestBase_implCompress(vmIntrinsics::ID id) {
8979   assert(callee()->signature()->size() == 2, "sha_implCompress has 2 parameters");
8980 
8981   Node* digestBase_obj = argument(0);
8982   Node* src            = argument(1); // type oop
8983   Node* ofs            = argument(2); // type int
8984 
8985   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
8986   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
8987     // failed array check
8988     return false;
8989   }
8990   // Figure out the size and type of the elements we will be copying.
8991   BasicType src_elem = src_type->elem()->array_element_basic_type();
8992   if (src_elem != T_BYTE) {
8993     return false;
8994   }
8995   // 'src_start' points to src array + offset
8996   src = must_be_not_null(src, true);
8997   Node* src_start = array_element_address(src, ofs, src_elem);
8998   Node* state = nullptr;
8999   Node* block_size = nullptr;
9000   address stubAddr;
9001   const char *stubName;
9002 
9003   switch(id) {
9004   case vmIntrinsics::_md5_implCompress:
9005     assert(UseMD5Intrinsics, "need MD5 instruction support");
9006     state = get_state_from_digest_object(digestBase_obj, T_INT);
9007     stubAddr = StubRoutines::md5_implCompress();
9008     stubName = "md5_implCompress";
9009     break;
9010   case vmIntrinsics::_sha_implCompress:
9011     assert(UseSHA1Intrinsics, "need SHA1 instruction support");
9012     state = get_state_from_digest_object(digestBase_obj, T_INT);
9013     stubAddr = StubRoutines::sha1_implCompress();
9014     stubName = "sha1_implCompress";
9015     break;
9016   case vmIntrinsics::_sha2_implCompress:
9017     assert(UseSHA256Intrinsics, "need SHA256 instruction support");
9018     state = get_state_from_digest_object(digestBase_obj, T_INT);
9019     stubAddr = StubRoutines::sha256_implCompress();
9020     stubName = "sha256_implCompress";
9021     break;
9022   case vmIntrinsics::_sha5_implCompress:
9023     assert(UseSHA512Intrinsics, "need SHA512 instruction support");
9024     state = get_state_from_digest_object(digestBase_obj, T_LONG);
9025     stubAddr = StubRoutines::sha512_implCompress();
9026     stubName = "sha512_implCompress";
9027     break;
9028   case vmIntrinsics::_sha3_implCompress:
9029     assert(UseSHA3Intrinsics, "need SHA3 instruction support");
9030     state = get_state_from_digest_object(digestBase_obj, T_LONG);
9031     stubAddr = StubRoutines::sha3_implCompress();
9032     stubName = "sha3_implCompress";
9033     block_size = get_block_size_from_digest_object(digestBase_obj);
9034     if (block_size == nullptr) return false;
9035     break;
9036   default:
9037     fatal_unexpected_iid(id);
9038     return false;
9039   }
9040   if (state == nullptr) return false;
9041 
9042   assert(stubAddr != nullptr, "Stub %s is not generated", stubName);
9043   if (stubAddr == nullptr) return false;
9044 
9045   // Call the stub.
9046   Node* call;
9047   if (block_size == nullptr) {
9048     call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::digestBase_implCompress_Type(false),
9049                              stubAddr, stubName, TypePtr::BOTTOM,
9050                              src_start, state);
9051   } else {
9052     call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::digestBase_implCompress_Type(true),
9053                              stubAddr, stubName, TypePtr::BOTTOM,
9054                              src_start, state, block_size);
9055   }
9056 
9057   return true;
9058 }
9059 
9060 //------------------------------inline_double_keccak
9061 bool LibraryCallKit::inline_double_keccak() {
9062   address stubAddr;
9063   const char *stubName;
9064   assert(UseSHA3Intrinsics, "need SHA3 intrinsics support");
9065   assert(callee()->signature()->size() == 2, "double_keccak has 2 parameters");
9066 
9067   stubAddr = StubRoutines::double_keccak();
9068   stubName = "double_keccak";
9069   if (!stubAddr) return false;
9070 
9071   Node* status0        = argument(0);
9072   Node* status1        = argument(1);
9073 
9074   status0 = must_be_not_null(status0, true);
9075   status1 = must_be_not_null(status1, true);
9076 
9077   Node* status0_start  = array_element_address(status0, intcon(0), T_LONG);
9078   assert(status0_start, "status0 is null");
9079   Node* status1_start  = array_element_address(status1, intcon(0), T_LONG);
9080   assert(status1_start, "status1 is null");
9081   Node* double_keccak = make_runtime_call(RC_LEAF|RC_NO_FP,
9082                                   OptoRuntime::double_keccak_Type(),
9083                                   stubAddr, stubName, TypePtr::BOTTOM,
9084                                   status0_start, status1_start);
9085   // return an int
9086   Node* retvalue = _gvn.transform(new ProjNode(double_keccak, TypeFunc::Parms));
9087   set_result(retvalue);
9088   return true;
9089 }
9090 
9091 
9092 //------------------------------inline_digestBase_implCompressMB-----------------------
9093 //
9094 // Calculate MD5/SHA/SHA2/SHA5/SHA3 for multi-block byte[] array.
9095 // int com.sun.security.provider.DigestBase.implCompressMultiBlock(byte[] b, int ofs, int limit)
9096 //
9097 bool LibraryCallKit::inline_digestBase_implCompressMB(int predicate) {
9098   assert(UseMD5Intrinsics || UseSHA1Intrinsics || UseSHA256Intrinsics || UseSHA512Intrinsics || UseSHA3Intrinsics,
9099          "need MD5/SHA1/SHA256/SHA512/SHA3 instruction support");
9100   assert((uint)predicate < 5, "sanity");
9101   assert(callee()->signature()->size() == 3, "digestBase_implCompressMB has 3 parameters");
9102 
9103   Node* digestBase_obj = argument(0); // The receiver was checked for null already.
9104   Node* src            = argument(1); // byte[] array
9105   Node* ofs            = argument(2); // type int
9106   Node* limit          = argument(3); // type int
9107 
9108   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
9109   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
9110     // failed array check
9111     return false;
9112   }
9113   // Figure out the size and type of the elements we will be copying.
9114   BasicType src_elem = src_type->elem()->array_element_basic_type();
9115   if (src_elem != T_BYTE) {
9116     return false;
9117   }
9118   // 'src_start' points to src array + offset
9119   src = must_be_not_null(src, false);
9120   Node* src_start = array_element_address(src, ofs, src_elem);
9121 
9122   const char* klass_digestBase_name = nullptr;
9123   const char* stub_name = nullptr;
9124   address     stub_addr = nullptr;
9125   BasicType elem_type = T_INT;
9126 
9127   switch (predicate) {
9128   case 0:
9129     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_md5_implCompress)) {
9130       klass_digestBase_name = "sun/security/provider/MD5";
9131       stub_name = "md5_implCompressMB";
9132       stub_addr = StubRoutines::md5_implCompressMB();
9133     }
9134     break;
9135   case 1:
9136     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha_implCompress)) {
9137       klass_digestBase_name = "sun/security/provider/SHA";
9138       stub_name = "sha1_implCompressMB";
9139       stub_addr = StubRoutines::sha1_implCompressMB();
9140     }
9141     break;
9142   case 2:
9143     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha2_implCompress)) {
9144       klass_digestBase_name = "sun/security/provider/SHA2";
9145       stub_name = "sha256_implCompressMB";
9146       stub_addr = StubRoutines::sha256_implCompressMB();
9147     }
9148     break;
9149   case 3:
9150     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha5_implCompress)) {
9151       klass_digestBase_name = "sun/security/provider/SHA5";
9152       stub_name = "sha512_implCompressMB";
9153       stub_addr = StubRoutines::sha512_implCompressMB();
9154       elem_type = T_LONG;
9155     }
9156     break;
9157   case 4:
9158     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha3_implCompress)) {
9159       klass_digestBase_name = "sun/security/provider/SHA3";
9160       stub_name = "sha3_implCompressMB";
9161       stub_addr = StubRoutines::sha3_implCompressMB();
9162       elem_type = T_LONG;
9163     }
9164     break;
9165   default:
9166     fatal("unknown DigestBase intrinsic predicate: %d", predicate);
9167   }
9168   if (klass_digestBase_name != nullptr) {
9169     assert(stub_addr != nullptr, "Stub is generated");
9170     if (stub_addr == nullptr) return false;
9171 
9172     // get DigestBase klass to lookup for SHA klass
9173     const TypeInstPtr* tinst = _gvn.type(digestBase_obj)->isa_instptr();
9174     assert(tinst != nullptr, "digestBase_obj is not instance???");
9175     assert(tinst->is_loaded(), "DigestBase is not loaded");
9176 
9177     ciKlass* klass_digestBase = tinst->instance_klass()->find_klass(ciSymbol::make(klass_digestBase_name));
9178     assert(klass_digestBase->is_loaded(), "predicate checks that this class is loaded");
9179     ciInstanceKlass* instklass_digestBase = klass_digestBase->as_instance_klass();
9180     return inline_digestBase_implCompressMB(digestBase_obj, instklass_digestBase, elem_type, stub_addr, stub_name, src_start, ofs, limit);
9181   }
9182   return false;
9183 }
9184 
9185 //------------------------------inline_digestBase_implCompressMB-----------------------
9186 bool LibraryCallKit::inline_digestBase_implCompressMB(Node* digestBase_obj, ciInstanceKlass* instklass_digestBase,
9187                                                       BasicType elem_type, address stubAddr, const char *stubName,
9188                                                       Node* src_start, Node* ofs, Node* limit) {
9189   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_digestBase);
9190   const TypeOopPtr* xtype = aklass->cast_to_exactness(false)->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
9191   Node* digest_obj = new CheckCastPPNode(control(), digestBase_obj, xtype);
9192   digest_obj = _gvn.transform(digest_obj);
9193 
9194   Node* state = get_state_from_digest_object(digest_obj, elem_type);
9195   if (state == nullptr) return false;
9196 
9197   Node* block_size = nullptr;
9198   if (strcmp("sha3_implCompressMB", stubName) == 0) {
9199     block_size = get_block_size_from_digest_object(digest_obj);
9200     if (block_size == nullptr) return false;
9201   }
9202 
9203   // Call the stub.
9204   Node* call;
9205   if (block_size == nullptr) {
9206     call = make_runtime_call(RC_LEAF|RC_NO_FP,
9207                              OptoRuntime::digestBase_implCompressMB_Type(false),
9208                              stubAddr, stubName, TypePtr::BOTTOM,
9209                              src_start, state, ofs, limit);
9210   } else {
9211      call = make_runtime_call(RC_LEAF|RC_NO_FP,
9212                              OptoRuntime::digestBase_implCompressMB_Type(true),
9213                              stubAddr, stubName, TypePtr::BOTTOM,
9214                              src_start, state, block_size, ofs, limit);
9215   }
9216 
9217   // return ofs (int)
9218   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
9219   set_result(result);
9220 
9221   return true;
9222 }
9223 
9224 //------------------------------inline_galoisCounterMode_AESCrypt-----------------------
9225 bool LibraryCallKit::inline_galoisCounterMode_AESCrypt() {
9226   assert(UseAES, "need AES instruction support");
9227   address stubAddr = nullptr;
9228   const char *stubName = nullptr;
9229   stubAddr = StubRoutines::galoisCounterMode_AESCrypt();
9230   stubName = "galoisCounterMode_AESCrypt";
9231 
9232   if (stubAddr == nullptr) return false;
9233 
9234   Node* in      = argument(0);
9235   Node* inOfs   = argument(1);
9236   Node* len     = argument(2);
9237   Node* ct      = argument(3);
9238   Node* ctOfs   = argument(4);
9239   Node* out     = argument(5);
9240   Node* outOfs  = argument(6);
9241   Node* gctr_object = argument(7);
9242   Node* ghash_object = argument(8);
9243 
9244   // (1) in, ct and out are arrays.
9245   const TypeAryPtr* in_type = in->Value(&_gvn)->isa_aryptr();
9246   const TypeAryPtr* ct_type = ct->Value(&_gvn)->isa_aryptr();
9247   const TypeAryPtr* out_type = out->Value(&_gvn)->isa_aryptr();
9248   assert( in_type != nullptr &&  in_type->elem() != Type::BOTTOM &&
9249           ct_type != nullptr &&  ct_type->elem() != Type::BOTTOM &&
9250          out_type != nullptr && out_type->elem() != Type::BOTTOM, "args are strange");
9251 
9252   // checks are the responsibility of the caller
9253   Node* in_start = in;
9254   Node* ct_start = ct;
9255   Node* out_start = out;
9256   if (inOfs != nullptr || ctOfs != nullptr || outOfs != nullptr) {
9257     assert(inOfs != nullptr && ctOfs != nullptr && outOfs != nullptr, "");
9258     in_start = array_element_address(in, inOfs, T_BYTE);
9259     ct_start = array_element_address(ct, ctOfs, T_BYTE);
9260     out_start = array_element_address(out, outOfs, T_BYTE);
9261   }
9262 
9263   // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
9264   // (because of the predicated logic executed earlier).
9265   // so we cast it here safely.
9266   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
9267   Node* embeddedCipherObj = load_field_from_object(gctr_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
9268   Node* counter = load_field_from_object(gctr_object, "counter", "[B");
9269   Node* subkeyHtbl = load_field_from_object(ghash_object, "subkeyHtbl", "[J");
9270   Node* state = load_field_from_object(ghash_object, "state", "[J");
9271 
9272   if (embeddedCipherObj == nullptr || counter == nullptr || subkeyHtbl == nullptr || state == nullptr) {
9273     return false;
9274   }
9275   // cast it to what we know it will be at runtime
9276   const TypeInstPtr* tinst = _gvn.type(gctr_object)->isa_instptr();
9277   assert(tinst != nullptr, "GCTR obj is null");
9278   assert(tinst->is_loaded(), "GCTR obj is not loaded");
9279   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
9280   assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
9281   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
9282   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
9283   const TypeOopPtr* xtype = aklass->as_instance_type();
9284   Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
9285   aescrypt_object = _gvn.transform(aescrypt_object);
9286   // we need to get the start of the aescrypt_object's expanded key array
9287   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object, /* is_decrypt */ false);
9288   if (k_start == nullptr) return false;
9289   // similarly, get the start address of the r vector
9290   Node* cnt_start = array_element_address(counter, intcon(0), T_BYTE);
9291   Node* state_start = array_element_address(state, intcon(0), T_LONG);
9292   Node* subkeyHtbl_start = array_element_address(subkeyHtbl, intcon(0), T_LONG);
9293 
9294 
9295   // Call the stub, passing params
9296   Node* gcmCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
9297                                OptoRuntime::galoisCounterMode_aescrypt_Type(),
9298                                stubAddr, stubName, TypePtr::BOTTOM,
9299                                in_start, len, ct_start, out_start, k_start, state_start, subkeyHtbl_start, cnt_start);
9300 
9301   // return cipher length (int)
9302   Node* retvalue = _gvn.transform(new ProjNode(gcmCrypt, TypeFunc::Parms));
9303   set_result(retvalue);
9304 
9305   return true;
9306 }
9307 
9308 //----------------------------inline_galoisCounterMode_AESCrypt_predicate----------------------------
9309 // Return node representing slow path of predicate check.
9310 // the pseudo code we want to emulate with this predicate is:
9311 // for encryption:
9312 //    if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
9313 // for decryption:
9314 //    if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
9315 //    note cipher==plain is more conservative than the original java code but that's OK
9316 //
9317 
9318 Node* LibraryCallKit::inline_galoisCounterMode_AESCrypt_predicate() {
9319   // The receiver was checked for null already.
9320   Node* objGCTR = argument(7);
9321   // Load embeddedCipher field of GCTR object.
9322   Node* embeddedCipherObj = load_field_from_object(objGCTR, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
9323   assert(embeddedCipherObj != nullptr, "embeddedCipherObj is null");
9324 
9325   // get AESCrypt klass for instanceOf check
9326   // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
9327   // will have same classloader as CipherBlockChaining object
9328   const TypeInstPtr* tinst = _gvn.type(objGCTR)->isa_instptr();
9329   assert(tinst != nullptr, "GCTR obj is null");
9330   assert(tinst->is_loaded(), "GCTR obj is not loaded");
9331 
9332   // we want to do an instanceof comparison against the AESCrypt class
9333   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
9334   if (!klass_AESCrypt->is_loaded()) {
9335     // if AESCrypt is not even loaded, we never take the intrinsic fast path
9336     Node* ctrl = control();
9337     set_control(top()); // no regular fast path
9338     return ctrl;
9339   }
9340 
9341   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
9342   Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
9343   Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
9344   Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
9345   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
9346 
9347   return instof_false; // even if it is null
9348 }
9349 
9350 //------------------------------get_state_from_digest_object-----------------------
9351 Node * LibraryCallKit::get_state_from_digest_object(Node *digest_object, BasicType elem_type) {
9352   const char* state_type;
9353   switch (elem_type) {
9354     case T_BYTE: state_type = "[B"; break;
9355     case T_INT:  state_type = "[I"; break;
9356     case T_LONG: state_type = "[J"; break;
9357     default: ShouldNotReachHere();
9358   }
9359   Node* digest_state = load_field_from_object(digest_object, "state", state_type);
9360   assert (digest_state != nullptr, "wrong version of sun.security.provider.MD5/SHA/SHA2/SHA5/SHA3");
9361   if (digest_state == nullptr) return (Node *) nullptr;
9362 
9363   // now have the array, need to get the start address of the state array
9364   Node* state = array_element_address(digest_state, intcon(0), elem_type);
9365   return state;
9366 }
9367 
9368 //------------------------------get_block_size_from_sha3_object----------------------------------
9369 Node * LibraryCallKit::get_block_size_from_digest_object(Node *digest_object) {
9370   Node* block_size = load_field_from_object(digest_object, "blockSize", "I");
9371   assert (block_size != nullptr, "sanity");
9372   return block_size;
9373 }
9374 
9375 //----------------------------inline_digestBase_implCompressMB_predicate----------------------------
9376 // Return node representing slow path of predicate check.
9377 // the pseudo code we want to emulate with this predicate is:
9378 //    if (digestBaseObj instanceof MD5/SHA/SHA2/SHA5/SHA3) do_intrinsic, else do_javapath
9379 //
9380 Node* LibraryCallKit::inline_digestBase_implCompressMB_predicate(int predicate) {
9381   assert(UseMD5Intrinsics || UseSHA1Intrinsics || UseSHA256Intrinsics || UseSHA512Intrinsics || UseSHA3Intrinsics,
9382          "need MD5/SHA1/SHA256/SHA512/SHA3 instruction support");
9383   assert((uint)predicate < 5, "sanity");
9384 
9385   // The receiver was checked for null already.
9386   Node* digestBaseObj = argument(0);
9387 
9388   // get DigestBase klass for instanceOf check
9389   const TypeInstPtr* tinst = _gvn.type(digestBaseObj)->isa_instptr();
9390   assert(tinst != nullptr, "digestBaseObj is null");
9391   assert(tinst->is_loaded(), "DigestBase is not loaded");
9392 
9393   const char* klass_name = nullptr;
9394   switch (predicate) {
9395   case 0:
9396     if (UseMD5Intrinsics) {
9397       // we want to do an instanceof comparison against the MD5 class
9398       klass_name = "sun/security/provider/MD5";
9399     }
9400     break;
9401   case 1:
9402     if (UseSHA1Intrinsics) {
9403       // we want to do an instanceof comparison against the SHA class
9404       klass_name = "sun/security/provider/SHA";
9405     }
9406     break;
9407   case 2:
9408     if (UseSHA256Intrinsics) {
9409       // we want to do an instanceof comparison against the SHA2 class
9410       klass_name = "sun/security/provider/SHA2";
9411     }
9412     break;
9413   case 3:
9414     if (UseSHA512Intrinsics) {
9415       // we want to do an instanceof comparison against the SHA5 class
9416       klass_name = "sun/security/provider/SHA5";
9417     }
9418     break;
9419   case 4:
9420     if (UseSHA3Intrinsics) {
9421       // we want to do an instanceof comparison against the SHA3 class
9422       klass_name = "sun/security/provider/SHA3";
9423     }
9424     break;
9425   default:
9426     fatal("unknown SHA intrinsic predicate: %d", predicate);
9427   }
9428 
9429   ciKlass* klass = nullptr;
9430   if (klass_name != nullptr) {
9431     klass = tinst->instance_klass()->find_klass(ciSymbol::make(klass_name));
9432   }
9433   if ((klass == nullptr) || !klass->is_loaded()) {
9434     // if none of MD5/SHA/SHA2/SHA5 is loaded, we never take the intrinsic fast path
9435     Node* ctrl = control();
9436     set_control(top()); // no intrinsic path
9437     return ctrl;
9438   }
9439   ciInstanceKlass* instklass = klass->as_instance_klass();
9440 
9441   Node* instof = gen_instanceof(digestBaseObj, makecon(TypeKlassPtr::make(instklass)));
9442   Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
9443   Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
9444   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
9445 
9446   return instof_false;  // even if it is null
9447 }
9448 
9449 //-------------inline_fma-----------------------------------
9450 bool LibraryCallKit::inline_fma(vmIntrinsics::ID id) {
9451   Node *a = nullptr;
9452   Node *b = nullptr;
9453   Node *c = nullptr;
9454   Node* result = nullptr;
9455   switch (id) {
9456   case vmIntrinsics::_fmaD:
9457     assert(callee()->signature()->size() == 6, "fma has 3 parameters of size 2 each.");
9458     // no receiver since it is static method
9459     a = argument(0);
9460     b = argument(2);
9461     c = argument(4);
9462     result = _gvn.transform(new FmaDNode(a, b, c));
9463     break;
9464   case vmIntrinsics::_fmaF:
9465     assert(callee()->signature()->size() == 3, "fma has 3 parameters of size 1 each.");
9466     a = argument(0);
9467     b = argument(1);
9468     c = argument(2);
9469     result = _gvn.transform(new FmaFNode(a, b, c));
9470     break;
9471   default:
9472     fatal_unexpected_iid(id);  break;
9473   }
9474   set_result(result);
9475   return true;
9476 }
9477 
9478 bool LibraryCallKit::inline_character_compare(vmIntrinsics::ID id) {
9479   // argument(0) is receiver
9480   Node* codePoint = argument(1);
9481   Node* n = nullptr;
9482 
9483   switch (id) {
9484     case vmIntrinsics::_isDigit :
9485       n = new DigitNode(control(), codePoint);
9486       break;
9487     case vmIntrinsics::_isLowerCase :
9488       n = new LowerCaseNode(control(), codePoint);
9489       break;
9490     case vmIntrinsics::_isUpperCase :
9491       n = new UpperCaseNode(control(), codePoint);
9492       break;
9493     case vmIntrinsics::_isWhitespace :
9494       n = new WhitespaceNode(control(), codePoint);
9495       break;
9496     default:
9497       fatal_unexpected_iid(id);
9498   }
9499 
9500   set_result(_gvn.transform(n));
9501   return true;
9502 }
9503 
9504 bool LibraryCallKit::inline_profileBoolean() {
9505   Node* counts = argument(1);
9506   const TypeAryPtr* ary = nullptr;
9507   ciArray* aobj = nullptr;
9508   if (counts->is_Con()
9509       && (ary = counts->bottom_type()->isa_aryptr()) != nullptr
9510       && (aobj = ary->const_oop()->as_array()) != nullptr
9511       && (aobj->length() == 2)) {
9512     // Profile is int[2] where [0] and [1] correspond to false and true value occurrences respectively.
9513     jint false_cnt = aobj->element_value(0).as_int();
9514     jint  true_cnt = aobj->element_value(1).as_int();
9515 
9516     if (C->log() != nullptr) {
9517       C->log()->elem("observe source='profileBoolean' false='%d' true='%d'",
9518                      false_cnt, true_cnt);
9519     }
9520 
9521     if (false_cnt + true_cnt == 0) {
9522       // According to profile, never executed.
9523       uncommon_trap_exact(Deoptimization::Reason_intrinsic,
9524                           Deoptimization::Action_reinterpret);
9525       return true;
9526     }
9527 
9528     // result is a boolean (0 or 1) and its profile (false_cnt & true_cnt)
9529     // is a number of each value occurrences.
9530     Node* result = argument(0);
9531     if (false_cnt == 0 || true_cnt == 0) {
9532       // According to profile, one value has been never seen.
9533       int expected_val = (false_cnt == 0) ? 1 : 0;
9534 
9535       Node* cmp  = _gvn.transform(new CmpINode(result, intcon(expected_val)));
9536       Node* test = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
9537 
9538       IfNode* check = create_and_map_if(control(), test, PROB_ALWAYS, COUNT_UNKNOWN);
9539       Node* fast_path = _gvn.transform(new IfTrueNode(check));
9540       Node* slow_path = _gvn.transform(new IfFalseNode(check));
9541 
9542       { // Slow path: uncommon trap for never seen value and then reexecute
9543         // MethodHandleImpl::profileBoolean() to bump the count, so JIT knows
9544         // the value has been seen at least once.
9545         PreserveJVMState pjvms(this);
9546         PreserveReexecuteState preexecs(this);
9547         jvms()->set_should_reexecute(true);
9548 
9549         set_control(slow_path);
9550         set_i_o(i_o());
9551 
9552         uncommon_trap_exact(Deoptimization::Reason_intrinsic,
9553                             Deoptimization::Action_reinterpret);
9554       }
9555       // The guard for never seen value enables sharpening of the result and
9556       // returning a constant. It allows to eliminate branches on the same value
9557       // later on.
9558       set_control(fast_path);
9559       result = intcon(expected_val);
9560     }
9561     // Stop profiling.
9562     // MethodHandleImpl::profileBoolean() has profiling logic in its bytecode.
9563     // By replacing method body with profile data (represented as ProfileBooleanNode
9564     // on IR level) we effectively disable profiling.
9565     // It enables full speed execution once optimized code is generated.
9566     Node* profile = _gvn.transform(new ProfileBooleanNode(result, false_cnt, true_cnt));
9567     C->record_for_igvn(profile);
9568     set_result(profile);
9569     return true;
9570   } else {
9571     // Continue profiling.
9572     // Profile data isn't available at the moment. So, execute method's bytecode version.
9573     // Usually, when GWT LambdaForms are profiled it means that a stand-alone nmethod
9574     // is compiled and counters aren't available since corresponding MethodHandle
9575     // isn't a compile-time constant.
9576     return false;
9577   }
9578 }
9579 
9580 bool LibraryCallKit::inline_isCompileConstant() {
9581   Node* n = argument(0);
9582   set_result(n->is_Con() ? intcon(1) : intcon(0));
9583   return true;
9584 }
9585 
9586 //------------------------------- inline_getObjectSize --------------------------------------
9587 //
9588 // Calculate the runtime size of the object/array.
9589 //   native long sun.instrument.InstrumentationImpl.getObjectSize0(long nativeAgent, Object objectToSize);
9590 //
9591 bool LibraryCallKit::inline_getObjectSize() {
9592   Node* obj = argument(3);
9593   Node* klass_node = load_object_klass(obj);
9594 
9595   jint  layout_con = Klass::_lh_neutral_value;
9596   Node* layout_val = get_layout_helper(klass_node, layout_con);
9597   int   layout_is_con = (layout_val == nullptr);
9598 
9599   if (layout_is_con) {
9600     // Layout helper is constant, can figure out things at compile time.
9601 
9602     if (Klass::layout_helper_is_instance(layout_con)) {
9603       // Instance case:  layout_con contains the size itself.
9604       Node *size = longcon(Klass::layout_helper_size_in_bytes(layout_con));
9605       set_result(size);
9606     } else {
9607       // Array case: size is round(header + element_size*arraylength).
9608       // Since arraylength is different for every array instance, we have to
9609       // compute the whole thing at runtime.
9610 
9611       Node* arr_length = load_array_length(obj);
9612 
9613       int round_mask = MinObjAlignmentInBytes - 1;
9614       int hsize  = Klass::layout_helper_header_size(layout_con);
9615       int eshift = Klass::layout_helper_log2_element_size(layout_con);
9616 
9617       if ((round_mask & ~right_n_bits(eshift)) == 0) {
9618         round_mask = 0;  // strength-reduce it if it goes away completely
9619       }
9620       assert((hsize & right_n_bits(eshift)) == 0, "hsize is pre-rounded");
9621       Node* header_size = intcon(hsize + round_mask);
9622 
9623       Node* lengthx = ConvI2X(arr_length);
9624       Node* headerx = ConvI2X(header_size);
9625 
9626       Node* abody = lengthx;
9627       if (eshift != 0) {
9628         abody = _gvn.transform(new LShiftXNode(lengthx, intcon(eshift)));
9629       }
9630       Node* size = _gvn.transform( new AddXNode(headerx, abody) );
9631       if (round_mask != 0) {
9632         size = _gvn.transform( new AndXNode(size, MakeConX(~round_mask)) );
9633       }
9634       size = ConvX2L(size);
9635       set_result(size);
9636     }
9637   } else {
9638     // Layout helper is not constant, need to test for array-ness at runtime.
9639 
9640     enum { _instance_path = 1, _array_path, PATH_LIMIT };
9641     RegionNode* result_reg = new RegionNode(PATH_LIMIT);
9642     PhiNode* result_val = new PhiNode(result_reg, TypeLong::LONG);
9643     record_for_igvn(result_reg);
9644 
9645     Node* array_ctl = generate_array_guard(klass_node, nullptr, &obj);
9646     if (array_ctl != nullptr) {
9647       // Array case: size is round(header + element_size*arraylength).
9648       // Since arraylength is different for every array instance, we have to
9649       // compute the whole thing at runtime.
9650 
9651       PreserveJVMState pjvms(this);
9652       set_control(array_ctl);
9653       Node* arr_length = load_array_length(obj);
9654 
9655       int round_mask = MinObjAlignmentInBytes - 1;
9656       Node* mask = intcon(round_mask);
9657 
9658       Node* hss = intcon(Klass::_lh_header_size_shift);
9659       Node* hsm = intcon(Klass::_lh_header_size_mask);
9660       Node* header_size = _gvn.transform(new URShiftINode(layout_val, hss));
9661       header_size = _gvn.transform(new AndINode(header_size, hsm));
9662       header_size = _gvn.transform(new AddINode(header_size, mask));
9663 
9664       // There is no need to mask or shift this value.
9665       // The semantics of LShiftINode include an implicit mask to 0x1F.
9666       assert(Klass::_lh_log2_element_size_shift == 0, "use shift in place");
9667       Node* elem_shift = layout_val;
9668 
9669       Node* lengthx = ConvI2X(arr_length);
9670       Node* headerx = ConvI2X(header_size);
9671 
9672       Node* abody = _gvn.transform(new LShiftXNode(lengthx, elem_shift));
9673       Node* size = _gvn.transform(new AddXNode(headerx, abody));
9674       if (round_mask != 0) {
9675         size = _gvn.transform(new AndXNode(size, MakeConX(~round_mask)));
9676       }
9677       size = ConvX2L(size);
9678 
9679       result_reg->init_req(_array_path, control());
9680       result_val->init_req(_array_path, size);
9681     }
9682 
9683     if (!stopped()) {
9684       // Instance case: the layout helper gives us instance size almost directly,
9685       // but we need to mask out the _lh_instance_slow_path_bit.
9686       Node* size = ConvI2X(layout_val);
9687       assert((int) Klass::_lh_instance_slow_path_bit < BytesPerLong, "clear bit");
9688       Node* mask = MakeConX(~(intptr_t) right_n_bits(LogBytesPerLong));
9689       size = _gvn.transform(new AndXNode(size, mask));
9690       size = ConvX2L(size);
9691 
9692       result_reg->init_req(_instance_path, control());
9693       result_val->init_req(_instance_path, size);
9694     }
9695 
9696     set_result(result_reg, result_val);
9697   }
9698 
9699   return true;
9700 }
9701 
9702 //------------------------------- inline_blackhole --------------------------------------
9703 //
9704 // Make sure all arguments to this node are alive.
9705 // This matches methods that were requested to be blackholed through compile commands.
9706 //
9707 bool LibraryCallKit::inline_blackhole() {
9708   assert(callee()->is_static(), "Should have been checked before: only static methods here");
9709   assert(callee()->is_empty(), "Should have been checked before: only empty methods here");
9710   assert(callee()->holder()->is_loaded(), "Should have been checked before: only methods for loaded classes here");
9711 
9712   // Blackhole node pinches only the control, not memory. This allows
9713   // the blackhole to be pinned in the loop that computes blackholed
9714   // values, but have no other side effects, like breaking the optimizations
9715   // across the blackhole.
9716 
9717   Node* bh = _gvn.transform(new BlackholeNode(control()));
9718   set_control(_gvn.transform(new ProjNode(bh, TypeFunc::Control)));
9719 
9720   // Bind call arguments as blackhole arguments to keep them alive
9721   uint nargs = callee()->arg_size();
9722   for (uint i = 0; i < nargs; i++) {
9723     bh->add_req(argument(i));
9724   }
9725 
9726   return true;
9727 }
9728 
9729 Node* LibraryCallKit::unbox_fp16_value(const TypeInstPtr* float16_box_type, ciField* field, Node* box) {
9730   const TypeInstPtr* box_type = _gvn.type(box)->isa_instptr();
9731   if (box_type == nullptr || box_type->instance_klass() != float16_box_type->instance_klass()) {
9732     return nullptr; // box klass is not Float16
9733   }
9734 
9735   // Null check; get notnull casted pointer
9736   Node* null_ctl = top();
9737   Node* not_null_box = null_check_oop(box, &null_ctl, true);
9738   // If not_null_box is dead, only null-path is taken
9739   if (stopped()) {
9740     set_control(null_ctl);
9741     return nullptr;
9742   }
9743   assert(not_null_box->bottom_type()->is_instptr()->maybe_null() == false, "");
9744   const TypePtr* adr_type = C->alias_type(field)->adr_type();
9745   Node* adr = basic_plus_adr(not_null_box, field->offset_in_bytes());
9746   return access_load_at(not_null_box, adr, adr_type, TypeInt::SHORT, T_SHORT, IN_HEAP);
9747 }
9748 
9749 Node* LibraryCallKit::box_fp16_value(const TypeInstPtr* float16_box_type, ciField* field, Node* value) {
9750   PreserveReexecuteState preexecs(this);
9751   jvms()->set_should_reexecute(true);
9752 
9753   const TypeKlassPtr* klass_type = float16_box_type->as_klass_type();
9754   Node* klass_node = makecon(klass_type);
9755   Node* box = new_instance(klass_node);
9756 
9757   Node* value_field = basic_plus_adr(box, field->offset_in_bytes());
9758   const TypePtr* value_adr_type = value_field->bottom_type()->is_ptr();
9759 
9760   Node* field_store = _gvn.transform(access_store_at(box,
9761                                                      value_field,
9762                                                      value_adr_type,
9763                                                      value,
9764                                                      TypeInt::SHORT,
9765                                                      T_SHORT,
9766                                                      IN_HEAP));
9767   set_memory(field_store, value_adr_type);
9768   return box;
9769 }
9770 
9771 bool LibraryCallKit::inline_fp16_operations(vmIntrinsics::ID id, int num_args) {
9772   if (!Matcher::match_rule_supported(Op_ReinterpretS2HF) ||
9773       !Matcher::match_rule_supported(Op_ReinterpretHF2S)) {
9774     return false;
9775   }
9776 
9777   const TypeInstPtr* box_type = _gvn.type(argument(0))->isa_instptr();
9778   if (box_type == nullptr || box_type->const_oop() == nullptr) {
9779     return false;
9780   }
9781 
9782   ciInstanceKlass* float16_klass = box_type->const_oop()->as_instance()->java_lang_Class_klass()->as_instance_klass();
9783   const TypeInstPtr* float16_box_type = TypeInstPtr::make_exact(TypePtr::NotNull, float16_klass);
9784   ciField* field = float16_klass->get_field_by_name(ciSymbols::value_name(),
9785                                                     ciSymbols::short_signature(),
9786                                                     false);
9787   assert(field != nullptr, "");
9788 
9789   // Transformed nodes
9790   Node* fld1 = nullptr;
9791   Node* fld2 = nullptr;
9792   Node* fld3 = nullptr;
9793   switch(num_args) {
9794     case 3:
9795       fld3 = unbox_fp16_value(float16_box_type, field, argument(3));
9796       if (fld3 == nullptr) {
9797         return false;
9798       }
9799       fld3 = _gvn.transform(new ReinterpretS2HFNode(fld3));
9800     // fall-through
9801     case 2:
9802       fld2 = unbox_fp16_value(float16_box_type, field, argument(2));
9803       if (fld2 == nullptr) {
9804         return false;
9805       }
9806       fld2 = _gvn.transform(new ReinterpretS2HFNode(fld2));
9807     // fall-through
9808     case 1:
9809       fld1 = unbox_fp16_value(float16_box_type, field, argument(1));
9810       if (fld1 == nullptr) {
9811         return false;
9812       }
9813       fld1 = _gvn.transform(new ReinterpretS2HFNode(fld1));
9814       break;
9815     default: fatal("Unsupported number of arguments %d", num_args);
9816   }
9817 
9818   Node* result = nullptr;
9819   switch (id) {
9820     // Unary operations
9821     case vmIntrinsics::_sqrt_float16:
9822       result = _gvn.transform(new SqrtHFNode(C, control(), fld1));
9823       break;
9824     // Ternary operations
9825     case vmIntrinsics::_fma_float16:
9826       result = _gvn.transform(new FmaHFNode(fld1, fld2, fld3));
9827       break;
9828     default:
9829       fatal_unexpected_iid(id);
9830       break;
9831   }
9832   result = _gvn.transform(new ReinterpretHF2SNode(result));
9833   set_result(box_fp16_value(float16_box_type, field, result));
9834   return true;
9835 }
9836