1 /*
   2  * Copyright (c) 1999, 2026, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "asm/macroAssembler.hpp"
  26 #include "ci/ciArrayKlass.hpp"
  27 #include "ci/ciFlatArrayKlass.hpp"
  28 #include "ci/ciInstanceKlass.hpp"
  29 #include "ci/ciSymbols.hpp"
  30 #include "ci/ciUtilities.inline.hpp"
  31 #include "classfile/vmIntrinsics.hpp"
  32 #include "compiler/compileBroker.hpp"
  33 #include "compiler/compileLog.hpp"
  34 #include "gc/shared/barrierSet.hpp"
  35 #include "gc/shared/c2/barrierSetC2.hpp"
  36 #include "jfr/support/jfrIntrinsics.hpp"
  37 #include "memory/resourceArea.hpp"
  38 #include "oops/accessDecorators.hpp"
  39 #include "oops/klass.inline.hpp"
  40 #include "oops/layoutKind.hpp"
  41 #include "oops/objArrayKlass.hpp"
  42 #include "opto/addnode.hpp"
  43 #include "opto/arraycopynode.hpp"
  44 #include "opto/c2compiler.hpp"
  45 #include "opto/castnode.hpp"
  46 #include "opto/cfgnode.hpp"
  47 #include "opto/convertnode.hpp"
  48 #include "opto/countbitsnode.hpp"
  49 #include "opto/graphKit.hpp"
  50 #include "opto/idealKit.hpp"
  51 #include "opto/inlinetypenode.hpp"
  52 #include "opto/library_call.hpp"
  53 #include "opto/mathexactnode.hpp"
  54 #include "opto/mulnode.hpp"
  55 #include "opto/narrowptrnode.hpp"
  56 #include "opto/opaquenode.hpp"
  57 #include "opto/opcodes.hpp"
  58 #include "opto/parse.hpp"
  59 #include "opto/rootnode.hpp"
  60 #include "opto/runtime.hpp"
  61 #include "opto/subnode.hpp"
  62 #include "opto/type.hpp"
  63 #include "opto/vectornode.hpp"
  64 #include "prims/jvmtiExport.hpp"
  65 #include "prims/jvmtiThreadState.hpp"
  66 #include "prims/unsafe.hpp"
  67 #include "runtime/globals.hpp"
  68 #include "runtime/jniHandles.inline.hpp"
  69 #include "runtime/mountUnmountDisabler.hpp"
  70 #include "runtime/objectMonitor.hpp"
  71 #include "runtime/sharedRuntime.hpp"
  72 #include "runtime/stubRoutines.hpp"
  73 #include "utilities/globalDefinitions.hpp"
  74 #include "utilities/macros.hpp"
  75 #include "utilities/powerOfTwo.hpp"
  76 
  77 //---------------------------make_vm_intrinsic----------------------------
  78 CallGenerator* Compile::make_vm_intrinsic(ciMethod* m, bool is_virtual) {
  79   vmIntrinsicID id = m->intrinsic_id();
  80   assert(id != vmIntrinsics::_none, "must be a VM intrinsic");
  81 
  82   if (!m->is_loaded()) {
  83     // Do not attempt to inline unloaded methods.
  84     return nullptr;
  85   }
  86 
  87   C2Compiler* compiler = (C2Compiler*)CompileBroker::compiler(CompLevel_full_optimization);
  88   bool is_available = false;
  89 
  90   {
  91     // For calling is_intrinsic_supported and is_intrinsic_disabled_by_flag
  92     // the compiler must transition to '_thread_in_vm' state because both
  93     // methods access VM-internal data.
  94     VM_ENTRY_MARK;
  95     methodHandle mh(THREAD, m->get_Method());
  96     is_available = compiler != nullptr && compiler->is_intrinsic_available(mh, C->directive());
  97     if (is_available && is_virtual) {
  98       is_available = vmIntrinsics::does_virtual_dispatch(id);
  99     }
 100   }
 101 
 102   if (is_available) {
 103     assert(id <= vmIntrinsics::LAST_COMPILER_INLINE, "caller responsibility");
 104     assert(id != vmIntrinsics::_Object_init && id != vmIntrinsics::_invoke, "enum out of order?");
 105     return new LibraryIntrinsic(m, is_virtual,
 106                                 vmIntrinsics::predicates_needed(id),
 107                                 vmIntrinsics::does_virtual_dispatch(id),
 108                                 id);
 109   } else {
 110     return nullptr;
 111   }
 112 }
 113 
 114 JVMState* LibraryIntrinsic::generate(JVMState* jvms) {
 115   LibraryCallKit kit(jvms, this);
 116   Compile* C = kit.C;
 117   int nodes = C->unique();
 118 #ifndef PRODUCT
 119   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
 120     char buf[1000];
 121     const char* str = vmIntrinsics::short_name_as_C_string(intrinsic_id(), buf, sizeof(buf));
 122     tty->print_cr("Intrinsic %s", str);
 123   }
 124 #endif
 125   ciMethod* callee = kit.callee();
 126   const int bci    = kit.bci();
 127 #ifdef ASSERT
 128   Node* ctrl = kit.control();
 129 #endif
 130   // Try to inline the intrinsic.
 131   if (callee->check_intrinsic_candidate() &&
 132       kit.try_to_inline(_last_predicate)) {
 133     const char *inline_msg = is_virtual() ? "(intrinsic, virtual)"
 134                                           : "(intrinsic)";
 135     CompileTask::print_inlining_ul(callee, jvms->depth() - 1, bci, InliningResult::SUCCESS, inline_msg);
 136     C->inline_printer()->record(callee, jvms, InliningResult::SUCCESS, inline_msg);
 137     C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_worked);
 138     if (C->log()) {
 139       C->log()->elem("intrinsic id='%s'%s nodes='%d'",
 140                      vmIntrinsics::name_at(intrinsic_id()),
 141                      (is_virtual() ? " virtual='1'" : ""),
 142                      C->unique() - nodes);
 143     }
 144     // Push the result from the inlined method onto the stack.
 145     kit.push_result();
 146     return kit.transfer_exceptions_into_jvms();
 147   }
 148 
 149   // The intrinsic bailed out
 150   assert(ctrl == kit.control(), "Control flow was added although the intrinsic bailed out");
 151   assert(jvms->map() == kit.map(), "Out of sync JVM state");
 152   if (jvms->has_method()) {
 153     // Not a root compile.
 154     const char* msg;
 155     if (callee->intrinsic_candidate()) {
 156       msg = is_virtual() ? "failed to inline (intrinsic, virtual)" : "failed to inline (intrinsic)";
 157     } else {
 158       msg = is_virtual() ? "failed to inline (intrinsic, virtual), method not annotated"
 159                          : "failed to inline (intrinsic), method not annotated";
 160     }
 161     CompileTask::print_inlining_ul(callee, jvms->depth() - 1, bci, InliningResult::FAILURE, msg);
 162     C->inline_printer()->record(callee, jvms, InliningResult::FAILURE, msg);
 163   } else {
 164     // Root compile
 165     ResourceMark rm;
 166     stringStream msg_stream;
 167     msg_stream.print("Did not generate intrinsic %s%s at bci:%d in",
 168                      vmIntrinsics::name_at(intrinsic_id()),
 169                      is_virtual() ? " (virtual)" : "", bci);
 170     const char *msg = msg_stream.freeze();
 171     log_debug(jit, inlining)("%s", msg);
 172     if (C->print_intrinsics() || C->print_inlining()) {
 173       tty->print("%s", msg);
 174     }
 175   }
 176   C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_failed);
 177 
 178   return nullptr;
 179 }
 180 
 181 Node* LibraryIntrinsic::generate_predicate(JVMState* jvms, int predicate) {
 182   LibraryCallKit kit(jvms, this);
 183   Compile* C = kit.C;
 184   int nodes = C->unique();
 185   _last_predicate = predicate;
 186 #ifndef PRODUCT
 187   assert(is_predicated() && predicate < predicates_count(), "sanity");
 188   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
 189     char buf[1000];
 190     const char* str = vmIntrinsics::short_name_as_C_string(intrinsic_id(), buf, sizeof(buf));
 191     tty->print_cr("Predicate for intrinsic %s", str);
 192   }
 193 #endif
 194   ciMethod* callee = kit.callee();
 195   const int bci    = kit.bci();
 196 
 197   Node* slow_ctl = kit.try_to_predicate(predicate);
 198   if (!kit.failing()) {
 199     const char *inline_msg = is_virtual() ? "(intrinsic, virtual, predicate)"
 200                                           : "(intrinsic, predicate)";
 201     CompileTask::print_inlining_ul(callee, jvms->depth() - 1, bci, InliningResult::SUCCESS, inline_msg);
 202     C->inline_printer()->record(callee, jvms, InliningResult::SUCCESS, inline_msg);
 203 
 204     C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_worked);
 205     if (C->log()) {
 206       C->log()->elem("predicate_intrinsic id='%s'%s nodes='%d'",
 207                      vmIntrinsics::name_at(intrinsic_id()),
 208                      (is_virtual() ? " virtual='1'" : ""),
 209                      C->unique() - nodes);
 210     }
 211     return slow_ctl; // Could be null if the check folds.
 212   }
 213 
 214   // The intrinsic bailed out
 215   if (jvms->has_method()) {
 216     // Not a root compile.
 217     const char* msg = "failed to generate predicate for intrinsic";
 218     CompileTask::print_inlining_ul(kit.callee(), jvms->depth() - 1, bci, InliningResult::FAILURE, msg);
 219     C->inline_printer()->record(kit.callee(), jvms, InliningResult::FAILURE, msg);
 220   } else {
 221     // Root compile
 222     ResourceMark rm;
 223     stringStream msg_stream;
 224     msg_stream.print("Did not generate intrinsic %s%s at bci:%d in",
 225                      vmIntrinsics::name_at(intrinsic_id()),
 226                      is_virtual() ? " (virtual)" : "", bci);
 227     const char *msg = msg_stream.freeze();
 228     log_debug(jit, inlining)("%s", msg);
 229     C->inline_printer()->record(kit.callee(), jvms, InliningResult::FAILURE, msg);
 230   }
 231   C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_failed);
 232   return nullptr;
 233 }
 234 
 235 bool LibraryCallKit::try_to_inline(int predicate) {
 236   // Handle symbolic names for otherwise undistinguished boolean switches:
 237   const bool is_store       = true;
 238   const bool is_compress    = true;
 239   const bool is_static      = true;
 240   const bool is_volatile    = true;
 241 
 242   if (!jvms()->has_method()) {
 243     // Root JVMState has a null method.
 244     assert(map()->memory()->Opcode() == Op_Parm, "");
 245     // Insert the memory aliasing node
 246     set_all_memory(reset_memory());
 247   }
 248   assert(merged_memory(), "");
 249 
 250   switch (intrinsic_id()) {
 251   case vmIntrinsics::_hashCode:                 return inline_native_hashcode(intrinsic()->is_virtual(), !is_static);
 252   case vmIntrinsics::_identityHashCode:         return inline_native_hashcode(/*!virtual*/ false,         is_static);
 253   case vmIntrinsics::_getClass:                 return inline_native_getClass();
 254 
 255   case vmIntrinsics::_ceil:
 256   case vmIntrinsics::_floor:
 257   case vmIntrinsics::_rint:
 258   case vmIntrinsics::_dsin:
 259   case vmIntrinsics::_dcos:
 260   case vmIntrinsics::_dtan:
 261   case vmIntrinsics::_dsinh:
 262   case vmIntrinsics::_dtanh:
 263   case vmIntrinsics::_dcbrt:
 264   case vmIntrinsics::_dabs:
 265   case vmIntrinsics::_fabs:
 266   case vmIntrinsics::_iabs:
 267   case vmIntrinsics::_labs:
 268   case vmIntrinsics::_datan2:
 269   case vmIntrinsics::_dsqrt:
 270   case vmIntrinsics::_dsqrt_strict:
 271   case vmIntrinsics::_dexp:
 272   case vmIntrinsics::_dlog:
 273   case vmIntrinsics::_dlog10:
 274   case vmIntrinsics::_dpow:
 275   case vmIntrinsics::_dcopySign:
 276   case vmIntrinsics::_fcopySign:
 277   case vmIntrinsics::_dsignum:
 278   case vmIntrinsics::_roundF:
 279   case vmIntrinsics::_roundD:
 280   case vmIntrinsics::_fsignum:                  return inline_math_native(intrinsic_id());
 281 
 282   case vmIntrinsics::_notify:
 283   case vmIntrinsics::_notifyAll:
 284     return inline_notify(intrinsic_id());
 285 
 286   case vmIntrinsics::_addExactI:                return inline_math_addExactI(false /* add */);
 287   case vmIntrinsics::_addExactL:                return inline_math_addExactL(false /* add */);
 288   case vmIntrinsics::_decrementExactI:          return inline_math_subtractExactI(true /* decrement */);
 289   case vmIntrinsics::_decrementExactL:          return inline_math_subtractExactL(true /* decrement */);
 290   case vmIntrinsics::_incrementExactI:          return inline_math_addExactI(true /* increment */);
 291   case vmIntrinsics::_incrementExactL:          return inline_math_addExactL(true /* increment */);
 292   case vmIntrinsics::_multiplyExactI:           return inline_math_multiplyExactI();
 293   case vmIntrinsics::_multiplyExactL:           return inline_math_multiplyExactL();
 294   case vmIntrinsics::_multiplyHigh:             return inline_math_multiplyHigh();
 295   case vmIntrinsics::_unsignedMultiplyHigh:     return inline_math_unsignedMultiplyHigh();
 296   case vmIntrinsics::_negateExactI:             return inline_math_negateExactI();
 297   case vmIntrinsics::_negateExactL:             return inline_math_negateExactL();
 298   case vmIntrinsics::_subtractExactI:           return inline_math_subtractExactI(false /* subtract */);
 299   case vmIntrinsics::_subtractExactL:           return inline_math_subtractExactL(false /* subtract */);
 300 
 301   case vmIntrinsics::_arraycopy:                return inline_arraycopy();
 302 
 303   case vmIntrinsics::_arraySort:                return inline_array_sort();
 304   case vmIntrinsics::_arrayPartition:           return inline_array_partition();
 305 
 306   case vmIntrinsics::_compareToL:               return inline_string_compareTo(StrIntrinsicNode::LL);
 307   case vmIntrinsics::_compareToU:               return inline_string_compareTo(StrIntrinsicNode::UU);
 308   case vmIntrinsics::_compareToLU:              return inline_string_compareTo(StrIntrinsicNode::LU);
 309   case vmIntrinsics::_compareToUL:              return inline_string_compareTo(StrIntrinsicNode::UL);
 310 
 311   case vmIntrinsics::_indexOfL:                 return inline_string_indexOf(StrIntrinsicNode::LL);
 312   case vmIntrinsics::_indexOfU:                 return inline_string_indexOf(StrIntrinsicNode::UU);
 313   case vmIntrinsics::_indexOfUL:                return inline_string_indexOf(StrIntrinsicNode::UL);
 314   case vmIntrinsics::_indexOfIL:                return inline_string_indexOfI(StrIntrinsicNode::LL);
 315   case vmIntrinsics::_indexOfIU:                return inline_string_indexOfI(StrIntrinsicNode::UU);
 316   case vmIntrinsics::_indexOfIUL:               return inline_string_indexOfI(StrIntrinsicNode::UL);
 317   case vmIntrinsics::_indexOfU_char:            return inline_string_indexOfChar(StrIntrinsicNode::U);
 318   case vmIntrinsics::_indexOfL_char:            return inline_string_indexOfChar(StrIntrinsicNode::L);
 319 
 320   case vmIntrinsics::_equalsL:                  return inline_string_equals(StrIntrinsicNode::LL);
 321 
 322   case vmIntrinsics::_vectorizedHashCode:       return inline_vectorizedHashCode();
 323 
 324   case vmIntrinsics::_toBytesStringU:           return inline_string_toBytesU();
 325   case vmIntrinsics::_getCharsStringU:          return inline_string_getCharsU();
 326   case vmIntrinsics::_getCharStringU:           return inline_string_char_access(!is_store);
 327   case vmIntrinsics::_putCharStringU:           return inline_string_char_access( is_store);
 328 
 329   case vmIntrinsics::_compressStringC:
 330   case vmIntrinsics::_compressStringB:          return inline_string_copy( is_compress);
 331   case vmIntrinsics::_inflateStringC:
 332   case vmIntrinsics::_inflateStringB:           return inline_string_copy(!is_compress);
 333 
 334   case vmIntrinsics::_getReference:             return inline_unsafe_access(!is_store, T_OBJECT,   Relaxed, false);
 335   case vmIntrinsics::_getBoolean:               return inline_unsafe_access(!is_store, T_BOOLEAN,  Relaxed, false);
 336   case vmIntrinsics::_getByte:                  return inline_unsafe_access(!is_store, T_BYTE,     Relaxed, false);
 337   case vmIntrinsics::_getShort:                 return inline_unsafe_access(!is_store, T_SHORT,    Relaxed, false);
 338   case vmIntrinsics::_getChar:                  return inline_unsafe_access(!is_store, T_CHAR,     Relaxed, false);
 339   case vmIntrinsics::_getInt:                   return inline_unsafe_access(!is_store, T_INT,      Relaxed, false);
 340   case vmIntrinsics::_getLong:                  return inline_unsafe_access(!is_store, T_LONG,     Relaxed, false);
 341   case vmIntrinsics::_getFloat:                 return inline_unsafe_access(!is_store, T_FLOAT,    Relaxed, false);
 342   case vmIntrinsics::_getDouble:                return inline_unsafe_access(!is_store, T_DOUBLE,   Relaxed, false);
 343 
 344   case vmIntrinsics::_putReference:             return inline_unsafe_access( is_store, T_OBJECT,   Relaxed, false);
 345   case vmIntrinsics::_putBoolean:               return inline_unsafe_access( is_store, T_BOOLEAN,  Relaxed, false);
 346   case vmIntrinsics::_putByte:                  return inline_unsafe_access( is_store, T_BYTE,     Relaxed, false);
 347   case vmIntrinsics::_putShort:                 return inline_unsafe_access( is_store, T_SHORT,    Relaxed, false);
 348   case vmIntrinsics::_putChar:                  return inline_unsafe_access( is_store, T_CHAR,     Relaxed, false);
 349   case vmIntrinsics::_putInt:                   return inline_unsafe_access( is_store, T_INT,      Relaxed, false);
 350   case vmIntrinsics::_putLong:                  return inline_unsafe_access( is_store, T_LONG,     Relaxed, false);
 351   case vmIntrinsics::_putFloat:                 return inline_unsafe_access( is_store, T_FLOAT,    Relaxed, false);
 352   case vmIntrinsics::_putDouble:                return inline_unsafe_access( is_store, T_DOUBLE,   Relaxed, false);
 353 
 354   case vmIntrinsics::_getReferenceVolatile:     return inline_unsafe_access(!is_store, T_OBJECT,   Volatile, false);
 355   case vmIntrinsics::_getBooleanVolatile:       return inline_unsafe_access(!is_store, T_BOOLEAN,  Volatile, false);
 356   case vmIntrinsics::_getByteVolatile:          return inline_unsafe_access(!is_store, T_BYTE,     Volatile, false);
 357   case vmIntrinsics::_getShortVolatile:         return inline_unsafe_access(!is_store, T_SHORT,    Volatile, false);
 358   case vmIntrinsics::_getCharVolatile:          return inline_unsafe_access(!is_store, T_CHAR,     Volatile, false);
 359   case vmIntrinsics::_getIntVolatile:           return inline_unsafe_access(!is_store, T_INT,      Volatile, false);
 360   case vmIntrinsics::_getLongVolatile:          return inline_unsafe_access(!is_store, T_LONG,     Volatile, false);
 361   case vmIntrinsics::_getFloatVolatile:         return inline_unsafe_access(!is_store, T_FLOAT,    Volatile, false);
 362   case vmIntrinsics::_getDoubleVolatile:        return inline_unsafe_access(!is_store, T_DOUBLE,   Volatile, false);
 363 
 364   case vmIntrinsics::_putReferenceVolatile:     return inline_unsafe_access( is_store, T_OBJECT,   Volatile, false);
 365   case vmIntrinsics::_putBooleanVolatile:       return inline_unsafe_access( is_store, T_BOOLEAN,  Volatile, false);
 366   case vmIntrinsics::_putByteVolatile:          return inline_unsafe_access( is_store, T_BYTE,     Volatile, false);
 367   case vmIntrinsics::_putShortVolatile:         return inline_unsafe_access( is_store, T_SHORT,    Volatile, false);
 368   case vmIntrinsics::_putCharVolatile:          return inline_unsafe_access( is_store, T_CHAR,     Volatile, false);
 369   case vmIntrinsics::_putIntVolatile:           return inline_unsafe_access( is_store, T_INT,      Volatile, false);
 370   case vmIntrinsics::_putLongVolatile:          return inline_unsafe_access( is_store, T_LONG,     Volatile, false);
 371   case vmIntrinsics::_putFloatVolatile:         return inline_unsafe_access( is_store, T_FLOAT,    Volatile, false);
 372   case vmIntrinsics::_putDoubleVolatile:        return inline_unsafe_access( is_store, T_DOUBLE,   Volatile, false);
 373 
 374   case vmIntrinsics::_getShortUnaligned:        return inline_unsafe_access(!is_store, T_SHORT,    Relaxed, true);
 375   case vmIntrinsics::_getCharUnaligned:         return inline_unsafe_access(!is_store, T_CHAR,     Relaxed, true);
 376   case vmIntrinsics::_getIntUnaligned:          return inline_unsafe_access(!is_store, T_INT,      Relaxed, true);
 377   case vmIntrinsics::_getLongUnaligned:         return inline_unsafe_access(!is_store, T_LONG,     Relaxed, true);
 378 
 379   case vmIntrinsics::_putShortUnaligned:        return inline_unsafe_access( is_store, T_SHORT,    Relaxed, true);
 380   case vmIntrinsics::_putCharUnaligned:         return inline_unsafe_access( is_store, T_CHAR,     Relaxed, true);
 381   case vmIntrinsics::_putIntUnaligned:          return inline_unsafe_access( is_store, T_INT,      Relaxed, true);
 382   case vmIntrinsics::_putLongUnaligned:         return inline_unsafe_access( is_store, T_LONG,     Relaxed, true);
 383 
 384   case vmIntrinsics::_getReferenceAcquire:      return inline_unsafe_access(!is_store, T_OBJECT,   Acquire, false);
 385   case vmIntrinsics::_getBooleanAcquire:        return inline_unsafe_access(!is_store, T_BOOLEAN,  Acquire, false);
 386   case vmIntrinsics::_getByteAcquire:           return inline_unsafe_access(!is_store, T_BYTE,     Acquire, false);
 387   case vmIntrinsics::_getShortAcquire:          return inline_unsafe_access(!is_store, T_SHORT,    Acquire, false);
 388   case vmIntrinsics::_getCharAcquire:           return inline_unsafe_access(!is_store, T_CHAR,     Acquire, false);
 389   case vmIntrinsics::_getIntAcquire:            return inline_unsafe_access(!is_store, T_INT,      Acquire, false);
 390   case vmIntrinsics::_getLongAcquire:           return inline_unsafe_access(!is_store, T_LONG,     Acquire, false);
 391   case vmIntrinsics::_getFloatAcquire:          return inline_unsafe_access(!is_store, T_FLOAT,    Acquire, false);
 392   case vmIntrinsics::_getDoubleAcquire:         return inline_unsafe_access(!is_store, T_DOUBLE,   Acquire, false);
 393 
 394   case vmIntrinsics::_putReferenceRelease:      return inline_unsafe_access( is_store, T_OBJECT,   Release, false);
 395   case vmIntrinsics::_putBooleanRelease:        return inline_unsafe_access( is_store, T_BOOLEAN,  Release, false);
 396   case vmIntrinsics::_putByteRelease:           return inline_unsafe_access( is_store, T_BYTE,     Release, false);
 397   case vmIntrinsics::_putShortRelease:          return inline_unsafe_access( is_store, T_SHORT,    Release, false);
 398   case vmIntrinsics::_putCharRelease:           return inline_unsafe_access( is_store, T_CHAR,     Release, false);
 399   case vmIntrinsics::_putIntRelease:            return inline_unsafe_access( is_store, T_INT,      Release, false);
 400   case vmIntrinsics::_putLongRelease:           return inline_unsafe_access( is_store, T_LONG,     Release, false);
 401   case vmIntrinsics::_putFloatRelease:          return inline_unsafe_access( is_store, T_FLOAT,    Release, false);
 402   case vmIntrinsics::_putDoubleRelease:         return inline_unsafe_access( is_store, T_DOUBLE,   Release, false);
 403 
 404   case vmIntrinsics::_getReferenceOpaque:       return inline_unsafe_access(!is_store, T_OBJECT,   Opaque, false);
 405   case vmIntrinsics::_getBooleanOpaque:         return inline_unsafe_access(!is_store, T_BOOLEAN,  Opaque, false);
 406   case vmIntrinsics::_getByteOpaque:            return inline_unsafe_access(!is_store, T_BYTE,     Opaque, false);
 407   case vmIntrinsics::_getShortOpaque:           return inline_unsafe_access(!is_store, T_SHORT,    Opaque, false);
 408   case vmIntrinsics::_getCharOpaque:            return inline_unsafe_access(!is_store, T_CHAR,     Opaque, false);
 409   case vmIntrinsics::_getIntOpaque:             return inline_unsafe_access(!is_store, T_INT,      Opaque, false);
 410   case vmIntrinsics::_getLongOpaque:            return inline_unsafe_access(!is_store, T_LONG,     Opaque, false);
 411   case vmIntrinsics::_getFloatOpaque:           return inline_unsafe_access(!is_store, T_FLOAT,    Opaque, false);
 412   case vmIntrinsics::_getDoubleOpaque:          return inline_unsafe_access(!is_store, T_DOUBLE,   Opaque, false);
 413 
 414   case vmIntrinsics::_putReferenceOpaque:       return inline_unsafe_access( is_store, T_OBJECT,   Opaque, false);
 415   case vmIntrinsics::_putBooleanOpaque:         return inline_unsafe_access( is_store, T_BOOLEAN,  Opaque, false);
 416   case vmIntrinsics::_putByteOpaque:            return inline_unsafe_access( is_store, T_BYTE,     Opaque, false);
 417   case vmIntrinsics::_putShortOpaque:           return inline_unsafe_access( is_store, T_SHORT,    Opaque, false);
 418   case vmIntrinsics::_putCharOpaque:            return inline_unsafe_access( is_store, T_CHAR,     Opaque, false);
 419   case vmIntrinsics::_putIntOpaque:             return inline_unsafe_access( is_store, T_INT,      Opaque, false);
 420   case vmIntrinsics::_putLongOpaque:            return inline_unsafe_access( is_store, T_LONG,     Opaque, false);
 421   case vmIntrinsics::_putFloatOpaque:           return inline_unsafe_access( is_store, T_FLOAT,    Opaque, false);
 422   case vmIntrinsics::_putDoubleOpaque:          return inline_unsafe_access( is_store, T_DOUBLE,   Opaque, false);
 423 
 424   case vmIntrinsics::_getFlatValue:             return inline_unsafe_flat_access(!is_store, Relaxed);
 425   case vmIntrinsics::_putFlatValue:             return inline_unsafe_flat_access( is_store, Relaxed);
 426 
 427   case vmIntrinsics::_compareAndSetReference:   return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap,      Volatile);
 428   case vmIntrinsics::_compareAndSetByte:        return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap,      Volatile);
 429   case vmIntrinsics::_compareAndSetShort:       return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap,      Volatile);
 430   case vmIntrinsics::_compareAndSetInt:         return inline_unsafe_load_store(T_INT,    LS_cmp_swap,      Volatile);
 431   case vmIntrinsics::_compareAndSetLong:        return inline_unsafe_load_store(T_LONG,   LS_cmp_swap,      Volatile);
 432 
 433   case vmIntrinsics::_weakCompareAndSetReferencePlain:     return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Relaxed);
 434   case vmIntrinsics::_weakCompareAndSetReferenceAcquire:   return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Acquire);
 435   case vmIntrinsics::_weakCompareAndSetReferenceRelease:   return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Release);
 436   case vmIntrinsics::_weakCompareAndSetReference:          return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Volatile);
 437   case vmIntrinsics::_weakCompareAndSetBytePlain:          return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap_weak, Relaxed);
 438   case vmIntrinsics::_weakCompareAndSetByteAcquire:        return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap_weak, Acquire);
 439   case vmIntrinsics::_weakCompareAndSetByteRelease:        return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap_weak, Release);
 440   case vmIntrinsics::_weakCompareAndSetByte:               return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap_weak, Volatile);
 441   case vmIntrinsics::_weakCompareAndSetShortPlain:         return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap_weak, Relaxed);
 442   case vmIntrinsics::_weakCompareAndSetShortAcquire:       return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap_weak, Acquire);
 443   case vmIntrinsics::_weakCompareAndSetShortRelease:       return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap_weak, Release);
 444   case vmIntrinsics::_weakCompareAndSetShort:              return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap_weak, Volatile);
 445   case vmIntrinsics::_weakCompareAndSetIntPlain:           return inline_unsafe_load_store(T_INT,    LS_cmp_swap_weak, Relaxed);
 446   case vmIntrinsics::_weakCompareAndSetIntAcquire:         return inline_unsafe_load_store(T_INT,    LS_cmp_swap_weak, Acquire);
 447   case vmIntrinsics::_weakCompareAndSetIntRelease:         return inline_unsafe_load_store(T_INT,    LS_cmp_swap_weak, Release);
 448   case vmIntrinsics::_weakCompareAndSetInt:                return inline_unsafe_load_store(T_INT,    LS_cmp_swap_weak, Volatile);
 449   case vmIntrinsics::_weakCompareAndSetLongPlain:          return inline_unsafe_load_store(T_LONG,   LS_cmp_swap_weak, Relaxed);
 450   case vmIntrinsics::_weakCompareAndSetLongAcquire:        return inline_unsafe_load_store(T_LONG,   LS_cmp_swap_weak, Acquire);
 451   case vmIntrinsics::_weakCompareAndSetLongRelease:        return inline_unsafe_load_store(T_LONG,   LS_cmp_swap_weak, Release);
 452   case vmIntrinsics::_weakCompareAndSetLong:               return inline_unsafe_load_store(T_LONG,   LS_cmp_swap_weak, Volatile);
 453 
 454   case vmIntrinsics::_compareAndExchangeReference:         return inline_unsafe_load_store(T_OBJECT, LS_cmp_exchange,  Volatile);
 455   case vmIntrinsics::_compareAndExchangeReferenceAcquire:  return inline_unsafe_load_store(T_OBJECT, LS_cmp_exchange,  Acquire);
 456   case vmIntrinsics::_compareAndExchangeReferenceRelease:  return inline_unsafe_load_store(T_OBJECT, LS_cmp_exchange,  Release);
 457   case vmIntrinsics::_compareAndExchangeByte:              return inline_unsafe_load_store(T_BYTE,   LS_cmp_exchange,  Volatile);
 458   case vmIntrinsics::_compareAndExchangeByteAcquire:       return inline_unsafe_load_store(T_BYTE,   LS_cmp_exchange,  Acquire);
 459   case vmIntrinsics::_compareAndExchangeByteRelease:       return inline_unsafe_load_store(T_BYTE,   LS_cmp_exchange,  Release);
 460   case vmIntrinsics::_compareAndExchangeShort:             return inline_unsafe_load_store(T_SHORT,  LS_cmp_exchange,  Volatile);
 461   case vmIntrinsics::_compareAndExchangeShortAcquire:      return inline_unsafe_load_store(T_SHORT,  LS_cmp_exchange,  Acquire);
 462   case vmIntrinsics::_compareAndExchangeShortRelease:      return inline_unsafe_load_store(T_SHORT,  LS_cmp_exchange,  Release);
 463   case vmIntrinsics::_compareAndExchangeInt:               return inline_unsafe_load_store(T_INT,    LS_cmp_exchange,  Volatile);
 464   case vmIntrinsics::_compareAndExchangeIntAcquire:        return inline_unsafe_load_store(T_INT,    LS_cmp_exchange,  Acquire);
 465   case vmIntrinsics::_compareAndExchangeIntRelease:        return inline_unsafe_load_store(T_INT,    LS_cmp_exchange,  Release);
 466   case vmIntrinsics::_compareAndExchangeLong:              return inline_unsafe_load_store(T_LONG,   LS_cmp_exchange,  Volatile);
 467   case vmIntrinsics::_compareAndExchangeLongAcquire:       return inline_unsafe_load_store(T_LONG,   LS_cmp_exchange,  Acquire);
 468   case vmIntrinsics::_compareAndExchangeLongRelease:       return inline_unsafe_load_store(T_LONG,   LS_cmp_exchange,  Release);
 469 
 470   case vmIntrinsics::_getAndAddByte:                    return inline_unsafe_load_store(T_BYTE,   LS_get_add,       Volatile);
 471   case vmIntrinsics::_getAndAddShort:                   return inline_unsafe_load_store(T_SHORT,  LS_get_add,       Volatile);
 472   case vmIntrinsics::_getAndAddInt:                     return inline_unsafe_load_store(T_INT,    LS_get_add,       Volatile);
 473   case vmIntrinsics::_getAndAddLong:                    return inline_unsafe_load_store(T_LONG,   LS_get_add,       Volatile);
 474 
 475   case vmIntrinsics::_getAndSetByte:                    return inline_unsafe_load_store(T_BYTE,   LS_get_set,       Volatile);
 476   case vmIntrinsics::_getAndSetShort:                   return inline_unsafe_load_store(T_SHORT,  LS_get_set,       Volatile);
 477   case vmIntrinsics::_getAndSetInt:                     return inline_unsafe_load_store(T_INT,    LS_get_set,       Volatile);
 478   case vmIntrinsics::_getAndSetLong:                    return inline_unsafe_load_store(T_LONG,   LS_get_set,       Volatile);
 479   case vmIntrinsics::_getAndSetReference:               return inline_unsafe_load_store(T_OBJECT, LS_get_set,       Volatile);
 480 
 481   case vmIntrinsics::_loadFence:
 482   case vmIntrinsics::_storeFence:
 483   case vmIntrinsics::_storeStoreFence:
 484   case vmIntrinsics::_fullFence:                return inline_unsafe_fence(intrinsic_id());
 485 
 486   case vmIntrinsics::_arrayInstanceBaseOffset:  return inline_arrayInstanceBaseOffset();
 487   case vmIntrinsics::_arrayInstanceIndexScale:  return inline_arrayInstanceIndexScale();
 488   case vmIntrinsics::_arrayLayout:              return inline_arrayLayout();
 489   case vmIntrinsics::_getFieldMap:              return inline_getFieldMap();
 490 
 491   case vmIntrinsics::_onSpinWait:               return inline_onspinwait();
 492 
 493   case vmIntrinsics::_currentCarrierThread:     return inline_native_currentCarrierThread();
 494   case vmIntrinsics::_currentThread:            return inline_native_currentThread();
 495   case vmIntrinsics::_setCurrentThread:         return inline_native_setCurrentThread();
 496 
 497   case vmIntrinsics::_scopedValueCache:          return inline_native_scopedValueCache();
 498   case vmIntrinsics::_setScopedValueCache:       return inline_native_setScopedValueCache();
 499 
 500   case vmIntrinsics::_Continuation_pin:          return inline_native_Continuation_pinning(false);
 501   case vmIntrinsics::_Continuation_unpin:        return inline_native_Continuation_pinning(true);
 502 
 503   case vmIntrinsics::_vthreadEndFirstTransition:    return inline_native_vthread_end_transition(CAST_FROM_FN_PTR(address, OptoRuntime::vthread_end_first_transition_Java()),
 504                                                                                                 "endFirstTransition", true);
 505   case vmIntrinsics::_vthreadStartFinalTransition:  return inline_native_vthread_start_transition(CAST_FROM_FN_PTR(address, OptoRuntime::vthread_start_final_transition_Java()),
 506                                                                                                   "startFinalTransition", true);
 507   case vmIntrinsics::_vthreadStartTransition:       return inline_native_vthread_start_transition(CAST_FROM_FN_PTR(address, OptoRuntime::vthread_start_transition_Java()),
 508                                                                                                   "startTransition", false);
 509   case vmIntrinsics::_vthreadEndTransition:         return inline_native_vthread_end_transition(CAST_FROM_FN_PTR(address, OptoRuntime::vthread_end_transition_Java()),
 510                                                                                                 "endTransition", false);
 511 #if INCLUDE_JVMTI
 512   case vmIntrinsics::_notifyJvmtiVThreadDisableSuspend: return inline_native_notify_jvmti_sync();
 513 #endif
 514 
 515 #ifdef JFR_HAVE_INTRINSICS
 516   case vmIntrinsics::_counterTime:              return inline_native_time_funcs(CAST_FROM_FN_PTR(address, JfrTime::time_function()), "counterTime");
 517   case vmIntrinsics::_getEventWriter:           return inline_native_getEventWriter();
 518   case vmIntrinsics::_jvm_commit:               return inline_native_jvm_commit();
 519 #endif
 520   case vmIntrinsics::_currentTimeMillis:        return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeMillis), "currentTimeMillis");
 521   case vmIntrinsics::_nanoTime:                 return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeNanos), "nanoTime");
 522   case vmIntrinsics::_writeback0:               return inline_unsafe_writeback0();
 523   case vmIntrinsics::_writebackPreSync0:        return inline_unsafe_writebackSync0(true);
 524   case vmIntrinsics::_writebackPostSync0:       return inline_unsafe_writebackSync0(false);
 525   case vmIntrinsics::_allocateInstance:         return inline_unsafe_allocate();
 526   case vmIntrinsics::_copyMemory:               return inline_unsafe_copyMemory();
 527   case vmIntrinsics::_setMemory:                return inline_unsafe_setMemory();
 528   case vmIntrinsics::_getLength:                return inline_native_getLength();
 529   case vmIntrinsics::_copyOf:                   return inline_array_copyOf(false);
 530   case vmIntrinsics::_copyOfRange:              return inline_array_copyOf(true);
 531   case vmIntrinsics::_equalsB:                  return inline_array_equals(StrIntrinsicNode::LL);
 532   case vmIntrinsics::_equalsC:                  return inline_array_equals(StrIntrinsicNode::UU);
 533   case vmIntrinsics::_Preconditions_checkIndex: return inline_preconditions_checkIndex(T_INT);
 534   case vmIntrinsics::_Preconditions_checkLongIndex: return inline_preconditions_checkIndex(T_LONG);
 535   case vmIntrinsics::_clone:                    return inline_native_clone(intrinsic()->is_virtual());
 536 
 537   case vmIntrinsics::_allocateUninitializedArray: return inline_unsafe_newArray(true);
 538   case vmIntrinsics::_newArray:                   return inline_unsafe_newArray(false);
 539   case vmIntrinsics::_newNullRestrictedNonAtomicArray: return inline_newArray(/* null_free */ true, /* atomic */ false);
 540   case vmIntrinsics::_newNullRestrictedAtomicArray: return inline_newArray(/* null_free */ true, /* atomic */ true);
 541   case vmIntrinsics::_newNullableAtomicArray:     return inline_newArray(/* null_free */ false, /* atomic */ true);
 542   case vmIntrinsics::_isFlatArray:              return inline_getArrayProperties(IsFlat);
 543   case vmIntrinsics::_isNullRestrictedArray:    return inline_getArrayProperties(IsNullRestricted);
 544   case vmIntrinsics::_isAtomicArray:            return inline_getArrayProperties(IsAtomic);
 545 
 546   case vmIntrinsics::_isAssignableFrom:         return inline_native_subtype_check();
 547 
 548   case vmIntrinsics::_isInstance:
 549   case vmIntrinsics::_isHidden:
 550   case vmIntrinsics::_getSuperclass:            return inline_native_Class_query(intrinsic_id());
 551 
 552   case vmIntrinsics::_floatToRawIntBits:
 553   case vmIntrinsics::_floatToIntBits:
 554   case vmIntrinsics::_intBitsToFloat:
 555   case vmIntrinsics::_doubleToRawLongBits:
 556   case vmIntrinsics::_doubleToLongBits:
 557   case vmIntrinsics::_longBitsToDouble:
 558   case vmIntrinsics::_floatToFloat16:
 559   case vmIntrinsics::_float16ToFloat:           return inline_fp_conversions(intrinsic_id());
 560   case vmIntrinsics::_sqrt_float16:             return inline_fp16_operations(intrinsic_id(), 1);
 561   case vmIntrinsics::_fma_float16:              return inline_fp16_operations(intrinsic_id(), 3);
 562   case vmIntrinsics::_floatIsFinite:
 563   case vmIntrinsics::_floatIsInfinite:
 564   case vmIntrinsics::_doubleIsFinite:
 565   case vmIntrinsics::_doubleIsInfinite:         return inline_fp_range_check(intrinsic_id());
 566 
 567   case vmIntrinsics::_numberOfLeadingZeros_i:
 568   case vmIntrinsics::_numberOfLeadingZeros_l:
 569   case vmIntrinsics::_numberOfTrailingZeros_i:
 570   case vmIntrinsics::_numberOfTrailingZeros_l:
 571   case vmIntrinsics::_bitCount_i:
 572   case vmIntrinsics::_bitCount_l:
 573   case vmIntrinsics::_reverse_i:
 574   case vmIntrinsics::_reverse_l:
 575   case vmIntrinsics::_reverseBytes_i:
 576   case vmIntrinsics::_reverseBytes_l:
 577   case vmIntrinsics::_reverseBytes_s:
 578   case vmIntrinsics::_reverseBytes_c:           return inline_number_methods(intrinsic_id());
 579 
 580   case vmIntrinsics::_compress_i:
 581   case vmIntrinsics::_compress_l:
 582   case vmIntrinsics::_expand_i:
 583   case vmIntrinsics::_expand_l:                 return inline_bitshuffle_methods(intrinsic_id());
 584 
 585   case vmIntrinsics::_compareUnsigned_i:
 586   case vmIntrinsics::_compareUnsigned_l:        return inline_compare_unsigned(intrinsic_id());
 587 
 588   case vmIntrinsics::_divideUnsigned_i:
 589   case vmIntrinsics::_divideUnsigned_l:
 590   case vmIntrinsics::_remainderUnsigned_i:
 591   case vmIntrinsics::_remainderUnsigned_l:      return inline_divmod_methods(intrinsic_id());
 592 
 593   case vmIntrinsics::_getCallerClass:           return inline_native_Reflection_getCallerClass();
 594 
 595   case vmIntrinsics::_Reference_get0:           return inline_reference_get0();
 596   case vmIntrinsics::_Reference_refersTo0:      return inline_reference_refersTo0(false);
 597   case vmIntrinsics::_PhantomReference_refersTo0: return inline_reference_refersTo0(true);
 598   case vmIntrinsics::_Reference_clear0:         return inline_reference_clear0(false);
 599   case vmIntrinsics::_PhantomReference_clear0:  return inline_reference_clear0(true);
 600 
 601   case vmIntrinsics::_Class_cast:               return inline_Class_cast();
 602 
 603   case vmIntrinsics::_aescrypt_encryptBlock:
 604   case vmIntrinsics::_aescrypt_decryptBlock:    return inline_aescrypt_Block(intrinsic_id());
 605 
 606   case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
 607   case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
 608     return inline_cipherBlockChaining_AESCrypt(intrinsic_id());
 609 
 610   case vmIntrinsics::_electronicCodeBook_encryptAESCrypt:
 611   case vmIntrinsics::_electronicCodeBook_decryptAESCrypt:
 612     return inline_electronicCodeBook_AESCrypt(intrinsic_id());
 613 
 614   case vmIntrinsics::_counterMode_AESCrypt:
 615     return inline_counterMode_AESCrypt(intrinsic_id());
 616 
 617   case vmIntrinsics::_galoisCounterMode_AESCrypt:
 618     return inline_galoisCounterMode_AESCrypt();
 619 
 620   case vmIntrinsics::_md5_implCompress:
 621   case vmIntrinsics::_sha_implCompress:
 622   case vmIntrinsics::_sha2_implCompress:
 623   case vmIntrinsics::_sha5_implCompress:
 624   case vmIntrinsics::_sha3_implCompress:
 625     return inline_digestBase_implCompress(intrinsic_id());
 626   case vmIntrinsics::_double_keccak:
 627     return inline_double_keccak();
 628 
 629   case vmIntrinsics::_digestBase_implCompressMB:
 630     return inline_digestBase_implCompressMB(predicate);
 631 
 632   case vmIntrinsics::_multiplyToLen:
 633     return inline_multiplyToLen();
 634 
 635   case vmIntrinsics::_squareToLen:
 636     return inline_squareToLen();
 637 
 638   case vmIntrinsics::_mulAdd:
 639     return inline_mulAdd();
 640 
 641   case vmIntrinsics::_montgomeryMultiply:
 642     return inline_montgomeryMultiply();
 643   case vmIntrinsics::_montgomerySquare:
 644     return inline_montgomerySquare();
 645 
 646   case vmIntrinsics::_bigIntegerRightShiftWorker:
 647     return inline_bigIntegerShift(true);
 648   case vmIntrinsics::_bigIntegerLeftShiftWorker:
 649     return inline_bigIntegerShift(false);
 650 
 651   case vmIntrinsics::_vectorizedMismatch:
 652     return inline_vectorizedMismatch();
 653 
 654   case vmIntrinsics::_ghash_processBlocks:
 655     return inline_ghash_processBlocks();
 656   case vmIntrinsics::_chacha20Block:
 657     return inline_chacha20Block();
 658   case vmIntrinsics::_kyberNtt:
 659     return inline_kyberNtt();
 660   case vmIntrinsics::_kyberInverseNtt:
 661     return inline_kyberInverseNtt();
 662   case vmIntrinsics::_kyberNttMult:
 663     return inline_kyberNttMult();
 664   case vmIntrinsics::_kyberAddPoly_2:
 665     return inline_kyberAddPoly_2();
 666   case vmIntrinsics::_kyberAddPoly_3:
 667     return inline_kyberAddPoly_3();
 668   case vmIntrinsics::_kyber12To16:
 669     return inline_kyber12To16();
 670   case vmIntrinsics::_kyberBarrettReduce:
 671     return inline_kyberBarrettReduce();
 672   case vmIntrinsics::_dilithiumAlmostNtt:
 673     return inline_dilithiumAlmostNtt();
 674   case vmIntrinsics::_dilithiumAlmostInverseNtt:
 675     return inline_dilithiumAlmostInverseNtt();
 676   case vmIntrinsics::_dilithiumNttMult:
 677     return inline_dilithiumNttMult();
 678   case vmIntrinsics::_dilithiumMontMulByConstant:
 679     return inline_dilithiumMontMulByConstant();
 680   case vmIntrinsics::_dilithiumDecomposePoly:
 681     return inline_dilithiumDecomposePoly();
 682   case vmIntrinsics::_base64_encodeBlock:
 683     return inline_base64_encodeBlock();
 684   case vmIntrinsics::_base64_decodeBlock:
 685     return inline_base64_decodeBlock();
 686   case vmIntrinsics::_poly1305_processBlocks:
 687     return inline_poly1305_processBlocks();
 688   case vmIntrinsics::_intpoly_montgomeryMult_P256:
 689     return inline_intpoly_montgomeryMult_P256();
 690   case vmIntrinsics::_intpoly_assign:
 691     return inline_intpoly_assign();
 692   case vmIntrinsics::_encodeISOArray:
 693   case vmIntrinsics::_encodeByteISOArray:
 694     return inline_encodeISOArray(false);
 695   case vmIntrinsics::_encodeAsciiArray:
 696     return inline_encodeISOArray(true);
 697 
 698   case vmIntrinsics::_updateCRC32:
 699     return inline_updateCRC32();
 700   case vmIntrinsics::_updateBytesCRC32:
 701     return inline_updateBytesCRC32();
 702   case vmIntrinsics::_updateByteBufferCRC32:
 703     return inline_updateByteBufferCRC32();
 704 
 705   case vmIntrinsics::_updateBytesCRC32C:
 706     return inline_updateBytesCRC32C();
 707   case vmIntrinsics::_updateDirectByteBufferCRC32C:
 708     return inline_updateDirectByteBufferCRC32C();
 709 
 710   case vmIntrinsics::_updateBytesAdler32:
 711     return inline_updateBytesAdler32();
 712   case vmIntrinsics::_updateByteBufferAdler32:
 713     return inline_updateByteBufferAdler32();
 714 
 715   case vmIntrinsics::_profileBoolean:
 716     return inline_profileBoolean();
 717   case vmIntrinsics::_isCompileConstant:
 718     return inline_isCompileConstant();
 719 
 720   case vmIntrinsics::_countPositives:
 721     return inline_countPositives();
 722 
 723   case vmIntrinsics::_fmaD:
 724   case vmIntrinsics::_fmaF:
 725     return inline_fma(intrinsic_id());
 726 
 727   case vmIntrinsics::_isDigit:
 728   case vmIntrinsics::_isLowerCase:
 729   case vmIntrinsics::_isUpperCase:
 730   case vmIntrinsics::_isWhitespace:
 731     return inline_character_compare(intrinsic_id());
 732 
 733   case vmIntrinsics::_min:
 734   case vmIntrinsics::_max:
 735   case vmIntrinsics::_min_strict:
 736   case vmIntrinsics::_max_strict:
 737   case vmIntrinsics::_minL:
 738   case vmIntrinsics::_maxL:
 739   case vmIntrinsics::_minF:
 740   case vmIntrinsics::_maxF:
 741   case vmIntrinsics::_minD:
 742   case vmIntrinsics::_maxD:
 743   case vmIntrinsics::_minF_strict:
 744   case vmIntrinsics::_maxF_strict:
 745   case vmIntrinsics::_minD_strict:
 746   case vmIntrinsics::_maxD_strict:
 747     return inline_min_max(intrinsic_id());
 748 
 749   case vmIntrinsics::_VectorUnaryOp:
 750     return inline_vector_nary_operation(1);
 751   case vmIntrinsics::_VectorBinaryOp:
 752     return inline_vector_nary_operation(2);
 753   case vmIntrinsics::_VectorUnaryLibOp:
 754     return inline_vector_call(1);
 755   case vmIntrinsics::_VectorBinaryLibOp:
 756     return inline_vector_call(2);
 757   case vmIntrinsics::_VectorTernaryOp:
 758     return inline_vector_nary_operation(3);
 759   case vmIntrinsics::_VectorFromBitsCoerced:
 760     return inline_vector_frombits_coerced();
 761   case vmIntrinsics::_VectorMaskOp:
 762     return inline_vector_mask_operation();
 763   case vmIntrinsics::_VectorLoadOp:
 764     return inline_vector_mem_operation(/*is_store=*/false);
 765   case vmIntrinsics::_VectorLoadMaskedOp:
 766     return inline_vector_mem_masked_operation(/*is_store*/false);
 767   case vmIntrinsics::_VectorStoreOp:
 768     return inline_vector_mem_operation(/*is_store=*/true);
 769   case vmIntrinsics::_VectorStoreMaskedOp:
 770     return inline_vector_mem_masked_operation(/*is_store=*/true);
 771   case vmIntrinsics::_VectorGatherOp:
 772     return inline_vector_gather_scatter(/*is_scatter*/ false);
 773   case vmIntrinsics::_VectorScatterOp:
 774     return inline_vector_gather_scatter(/*is_scatter*/ true);
 775   case vmIntrinsics::_VectorReductionCoerced:
 776     return inline_vector_reduction();
 777   case vmIntrinsics::_VectorTest:
 778     return inline_vector_test();
 779   case vmIntrinsics::_VectorBlend:
 780     return inline_vector_blend();
 781   case vmIntrinsics::_VectorRearrange:
 782     return inline_vector_rearrange();
 783   case vmIntrinsics::_VectorSelectFrom:
 784     return inline_vector_select_from();
 785   case vmIntrinsics::_VectorCompare:
 786     return inline_vector_compare();
 787   case vmIntrinsics::_VectorBroadcastInt:
 788     return inline_vector_broadcast_int();
 789   case vmIntrinsics::_VectorConvert:
 790     return inline_vector_convert();
 791   case vmIntrinsics::_VectorInsert:
 792     return inline_vector_insert();
 793   case vmIntrinsics::_VectorExtract:
 794     return inline_vector_extract();
 795   case vmIntrinsics::_VectorCompressExpand:
 796     return inline_vector_compress_expand();
 797   case vmIntrinsics::_VectorSelectFromTwoVectorOp:
 798     return inline_vector_select_from_two_vectors();
 799   case vmIntrinsics::_IndexVector:
 800     return inline_index_vector();
 801   case vmIntrinsics::_IndexPartiallyInUpperRange:
 802     return inline_index_partially_in_upper_range();
 803 
 804   case vmIntrinsics::_getObjectSize:
 805     return inline_getObjectSize();
 806 
 807   case vmIntrinsics::_blackhole:
 808     return inline_blackhole();
 809 
 810   default:
 811     // If you get here, it may be that someone has added a new intrinsic
 812     // to the list in vmIntrinsics.hpp without implementing it here.
 813 #ifndef PRODUCT
 814     if ((PrintMiscellaneous && (Verbose || WizardMode)) || PrintOpto) {
 815       tty->print_cr("*** Warning: Unimplemented intrinsic %s(%d)",
 816                     vmIntrinsics::name_at(intrinsic_id()), vmIntrinsics::as_int(intrinsic_id()));
 817     }
 818 #endif
 819     return false;
 820   }
 821 }
 822 
 823 Node* LibraryCallKit::try_to_predicate(int predicate) {
 824   if (!jvms()->has_method()) {
 825     // Root JVMState has a null method.
 826     assert(map()->memory()->Opcode() == Op_Parm, "");
 827     // Insert the memory aliasing node
 828     set_all_memory(reset_memory());
 829   }
 830   assert(merged_memory(), "");
 831 
 832   switch (intrinsic_id()) {
 833   case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
 834     return inline_cipherBlockChaining_AESCrypt_predicate(false);
 835   case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
 836     return inline_cipherBlockChaining_AESCrypt_predicate(true);
 837   case vmIntrinsics::_electronicCodeBook_encryptAESCrypt:
 838     return inline_electronicCodeBook_AESCrypt_predicate(false);
 839   case vmIntrinsics::_electronicCodeBook_decryptAESCrypt:
 840     return inline_electronicCodeBook_AESCrypt_predicate(true);
 841   case vmIntrinsics::_counterMode_AESCrypt:
 842     return inline_counterMode_AESCrypt_predicate();
 843   case vmIntrinsics::_digestBase_implCompressMB:
 844     return inline_digestBase_implCompressMB_predicate(predicate);
 845   case vmIntrinsics::_galoisCounterMode_AESCrypt:
 846     return inline_galoisCounterMode_AESCrypt_predicate();
 847 
 848   default:
 849     // If you get here, it may be that someone has added a new intrinsic
 850     // to the list in vmIntrinsics.hpp without implementing it here.
 851 #ifndef PRODUCT
 852     if ((PrintMiscellaneous && (Verbose || WizardMode)) || PrintOpto) {
 853       tty->print_cr("*** Warning: Unimplemented predicate for intrinsic %s(%d)",
 854                     vmIntrinsics::name_at(intrinsic_id()), vmIntrinsics::as_int(intrinsic_id()));
 855     }
 856 #endif
 857     Node* slow_ctl = control();
 858     set_control(top()); // No fast path intrinsic
 859     return slow_ctl;
 860   }
 861 }
 862 
 863 //------------------------------set_result-------------------------------
 864 // Helper function for finishing intrinsics.
 865 void LibraryCallKit::set_result(RegionNode* region, PhiNode* value) {
 866   record_for_igvn(region);
 867   set_control(_gvn.transform(region));
 868   set_result( _gvn.transform(value));
 869   assert(value->type()->basic_type() == result()->bottom_type()->basic_type(), "sanity");
 870 }
 871 
 872 //------------------------------generate_guard---------------------------
 873 // Helper function for generating guarded fast-slow graph structures.
 874 // The given 'test', if true, guards a slow path.  If the test fails
 875 // then a fast path can be taken.  (We generally hope it fails.)
 876 // In all cases, GraphKit::control() is updated to the fast path.
 877 // The returned value represents the control for the slow path.
 878 // The return value is never 'top'; it is either a valid control
 879 // or null if it is obvious that the slow path can never be taken.
 880 // Also, if region and the slow control are not null, the slow edge
 881 // is appended to the region.
 882 Node* LibraryCallKit::generate_guard(Node* test, RegionNode* region, float true_prob) {
 883   if (stopped()) {
 884     // Already short circuited.
 885     return nullptr;
 886   }
 887 
 888   // Build an if node and its projections.
 889   // If test is true we take the slow path, which we assume is uncommon.
 890   if (_gvn.type(test) == TypeInt::ZERO) {
 891     // The slow branch is never taken.  No need to build this guard.
 892     return nullptr;
 893   }
 894 
 895   IfNode* iff = create_and_map_if(control(), test, true_prob, COUNT_UNKNOWN);
 896 
 897   Node* if_slow = _gvn.transform(new IfTrueNode(iff));
 898   if (if_slow == top()) {
 899     // The slow branch is never taken.  No need to build this guard.
 900     return nullptr;
 901   }
 902 
 903   if (region != nullptr)
 904     region->add_req(if_slow);
 905 
 906   Node* if_fast = _gvn.transform(new IfFalseNode(iff));
 907   set_control(if_fast);
 908 
 909   return if_slow;
 910 }
 911 
 912 inline Node* LibraryCallKit::generate_slow_guard(Node* test, RegionNode* region) {
 913   return generate_guard(test, region, PROB_UNLIKELY_MAG(3));
 914 }
 915 inline Node* LibraryCallKit::generate_fair_guard(Node* test, RegionNode* region) {
 916   return generate_guard(test, region, PROB_FAIR);
 917 }
 918 
 919 inline Node* LibraryCallKit::generate_negative_guard(Node* index, RegionNode* region,
 920                                                      Node** pos_index, bool with_opaque) {
 921   if (stopped())
 922     return nullptr;                // already stopped
 923   if (_gvn.type(index)->higher_equal(TypeInt::POS)) // [0,maxint]
 924     return nullptr;                // index is already adequately typed
 925   Node* cmp_lt = _gvn.transform(new CmpINode(index, intcon(0)));
 926   Node* bol_lt = _gvn.transform(new BoolNode(cmp_lt, BoolTest::lt));
 927   if (with_opaque) {
 928     bol_lt = _gvn.transform(new OpaqueConstantBoolNode(C, bol_lt, false));
 929   }
 930   Node* is_neg = generate_guard(bol_lt, region, PROB_MIN);
 931   if (is_neg != nullptr && pos_index != nullptr) {
 932     // Emulate effect of Parse::adjust_map_after_if.
 933     Node* ccast = new CastIINode(control(), index, TypeInt::POS);
 934     (*pos_index) = _gvn.transform(ccast);
 935   }
 936   return is_neg;
 937 }
 938 
 939 // Make sure that 'position' is a valid limit index, in [0..length].
 940 // There are two equivalent plans for checking this:
 941 //   A. (offset + copyLength)  unsigned<=  arrayLength
 942 //   B. offset  <=  (arrayLength - copyLength)
 943 // We require that all of the values above, except for the sum and
 944 // difference, are already known to be non-negative.
 945 // Plan A is robust in the face of overflow, if offset and copyLength
 946 // are both hugely positive.
 947 //
 948 // Plan B is less direct and intuitive, but it does not overflow at
 949 // all, since the difference of two non-negatives is always
 950 // representable.  Whenever Java methods must perform the equivalent
 951 // check they generally use Plan B instead of Plan A.
 952 // For the moment we use Plan A.
 953 inline Node* LibraryCallKit::generate_limit_guard(Node* offset,
 954                                                   Node* subseq_length,
 955                                                   Node* array_length,
 956                                                   RegionNode* region,
 957                                                   bool with_opaque) {
 958   if (stopped())
 959     return nullptr;                // already stopped
 960   bool zero_offset = _gvn.type(offset) == TypeInt::ZERO;
 961   if (zero_offset && subseq_length->eqv_uncast(array_length))
 962     return nullptr;                // common case of whole-array copy
 963   Node* last = subseq_length;
 964   if (!zero_offset)             // last += offset
 965     last = _gvn.transform(new AddINode(last, offset));
 966   Node* cmp_lt = _gvn.transform(new CmpUNode(array_length, last));
 967   Node* bol_lt = _gvn.transform(new BoolNode(cmp_lt, BoolTest::lt));
 968   if (with_opaque) {
 969     bol_lt = _gvn.transform(new OpaqueConstantBoolNode(C, bol_lt, false));
 970   }
 971   Node* is_over = generate_guard(bol_lt, region, PROB_MIN);
 972   return is_over;
 973 }
 974 
 975 // Emit range checks for the given String.value byte array
 976 void LibraryCallKit::generate_string_range_check(Node* array,
 977                                                  Node* offset,
 978                                                  Node* count,
 979                                                  bool char_count,
 980                                                  bool halt_on_oob) {
 981   if (stopped()) {
 982     return; // already stopped
 983   }
 984   RegionNode* bailout = new RegionNode(1);
 985   record_for_igvn(bailout);
 986   if (char_count) {
 987     // Convert char count to byte count
 988     count = _gvn.transform(new LShiftINode(count, intcon(1)));
 989   }
 990 
 991   // Offset and count must not be negative
 992   generate_negative_guard(offset, bailout, nullptr, halt_on_oob);
 993   generate_negative_guard(count, bailout, nullptr, halt_on_oob);
 994   // Offset + count must not exceed length of array
 995   generate_limit_guard(offset, count, load_array_length(array), bailout, halt_on_oob);
 996 
 997   if (bailout->req() > 1) {
 998     if (halt_on_oob) {
 999       bailout = _gvn.transform(bailout)->as_Region();
1000       Node* frame = _gvn.transform(new ParmNode(C->start(), TypeFunc::FramePtr));
1001       Node* halt = _gvn.transform(new HaltNode(bailout, frame, "unexpected guard failure in intrinsic"));
1002       C->root()->add_req(halt);
1003     } else {
1004       PreserveJVMState pjvms(this);
1005       set_control(_gvn.transform(bailout));
1006       uncommon_trap(Deoptimization::Reason_intrinsic,
1007                     Deoptimization::Action_maybe_recompile);
1008     }
1009   }
1010 }
1011 
1012 Node* LibraryCallKit::current_thread_helper(Node*& tls_output, ByteSize handle_offset,
1013                                             bool is_immutable) {
1014   ciKlass* thread_klass = env()->Thread_klass();
1015   const Type* thread_type
1016     = TypeOopPtr::make_from_klass(thread_klass)->cast_to_ptr_type(TypePtr::NotNull);
1017 
1018   Node* thread = _gvn.transform(new ThreadLocalNode());
1019   Node* p = basic_plus_adr(top()/*!oop*/, thread, in_bytes(handle_offset));
1020   tls_output = thread;
1021 
1022   Node* thread_obj_handle
1023     = (is_immutable
1024       ? LoadNode::make(_gvn, nullptr, immutable_memory(), p, p->bottom_type()->is_ptr(),
1025         TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered)
1026       : make_load(nullptr, p, p->bottom_type()->is_ptr(), T_ADDRESS, MemNode::unordered));
1027   thread_obj_handle = _gvn.transform(thread_obj_handle);
1028 
1029   DecoratorSet decorators = IN_NATIVE;
1030   if (is_immutable) {
1031     decorators |= C2_IMMUTABLE_MEMORY;
1032   }
1033   return access_load(thread_obj_handle, thread_type, T_OBJECT, decorators);
1034 }
1035 
1036 //--------------------------generate_current_thread--------------------
1037 Node* LibraryCallKit::generate_current_thread(Node* &tls_output) {
1038   return current_thread_helper(tls_output, JavaThread::threadObj_offset(),
1039                                /*is_immutable*/false);
1040 }
1041 
1042 //--------------------------generate_virtual_thread--------------------
1043 Node* LibraryCallKit::generate_virtual_thread(Node* tls_output) {
1044   return current_thread_helper(tls_output, JavaThread::vthread_offset(),
1045                                !C->method()->changes_current_thread());
1046 }
1047 
1048 //------------------------------make_string_method_node------------------------
1049 // Helper method for String intrinsic functions. This version is called with
1050 // str1 and str2 pointing to byte[] nodes containing Latin1 or UTF16 encoded
1051 // characters (depending on 'is_byte'). cnt1 and cnt2 are pointing to Int nodes
1052 // containing the lengths of str1 and str2.
1053 Node* LibraryCallKit::make_string_method_node(int opcode, Node* str1_start, Node* cnt1, Node* str2_start, Node* cnt2, StrIntrinsicNode::ArgEnc ae) {
1054   Node* result = nullptr;
1055   switch (opcode) {
1056   case Op_StrIndexOf:
1057     result = new StrIndexOfNode(control(), memory(TypeAryPtr::BYTES),
1058                                 str1_start, cnt1, str2_start, cnt2, ae);
1059     break;
1060   case Op_StrComp:
1061     result = new StrCompNode(control(), memory(TypeAryPtr::BYTES),
1062                              str1_start, cnt1, str2_start, cnt2, ae);
1063     break;
1064   case Op_StrEquals:
1065     // We already know that cnt1 == cnt2 here (checked in 'inline_string_equals').
1066     // Use the constant length if there is one because optimized match rule may exist.
1067     result = new StrEqualsNode(control(), memory(TypeAryPtr::BYTES),
1068                                str1_start, str2_start, cnt2->is_Con() ? cnt2 : cnt1, ae);
1069     break;
1070   default:
1071     ShouldNotReachHere();
1072     return nullptr;
1073   }
1074 
1075   // All these intrinsics have checks.
1076   C->set_has_split_ifs(true); // Has chance for split-if optimization
1077   clear_upper_avx();
1078 
1079   return _gvn.transform(result);
1080 }
1081 
1082 //------------------------------inline_string_compareTo------------------------
1083 bool LibraryCallKit::inline_string_compareTo(StrIntrinsicNode::ArgEnc ae) {
1084   Node* arg1 = argument(0);
1085   Node* arg2 = argument(1);
1086 
1087   arg1 = must_be_not_null(arg1, true);
1088   arg2 = must_be_not_null(arg2, true);
1089 
1090   // Get start addr and length of first argument
1091   Node* arg1_start  = array_element_address(arg1, intcon(0), T_BYTE);
1092   Node* arg1_cnt    = load_array_length(arg1);
1093 
1094   // Get start addr and length of second argument
1095   Node* arg2_start  = array_element_address(arg2, intcon(0), T_BYTE);
1096   Node* arg2_cnt    = load_array_length(arg2);
1097 
1098   Node* result = make_string_method_node(Op_StrComp, arg1_start, arg1_cnt, arg2_start, arg2_cnt, ae);
1099   set_result(result);
1100   return true;
1101 }
1102 
1103 //------------------------------inline_string_equals------------------------
1104 bool LibraryCallKit::inline_string_equals(StrIntrinsicNode::ArgEnc ae) {
1105   Node* arg1 = argument(0);
1106   Node* arg2 = argument(1);
1107 
1108   // paths (plus control) merge
1109   RegionNode* region = new RegionNode(3);
1110   Node* phi = new PhiNode(region, TypeInt::BOOL);
1111 
1112   if (!stopped()) {
1113 
1114     arg1 = must_be_not_null(arg1, true);
1115     arg2 = must_be_not_null(arg2, true);
1116 
1117     // Get start addr and length of first argument
1118     Node* arg1_start  = array_element_address(arg1, intcon(0), T_BYTE);
1119     Node* arg1_cnt    = load_array_length(arg1);
1120 
1121     // Get start addr and length of second argument
1122     Node* arg2_start  = array_element_address(arg2, intcon(0), T_BYTE);
1123     Node* arg2_cnt    = load_array_length(arg2);
1124 
1125     // Check for arg1_cnt != arg2_cnt
1126     Node* cmp = _gvn.transform(new CmpINode(arg1_cnt, arg2_cnt));
1127     Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::ne));
1128     Node* if_ne = generate_slow_guard(bol, nullptr);
1129     if (if_ne != nullptr) {
1130       phi->init_req(2, intcon(0));
1131       region->init_req(2, if_ne);
1132     }
1133 
1134     // Check for count == 0 is done by assembler code for StrEquals.
1135 
1136     if (!stopped()) {
1137       Node* equals = make_string_method_node(Op_StrEquals, arg1_start, arg1_cnt, arg2_start, arg2_cnt, ae);
1138       phi->init_req(1, equals);
1139       region->init_req(1, control());
1140     }
1141   }
1142 
1143   // post merge
1144   set_control(_gvn.transform(region));
1145   record_for_igvn(region);
1146 
1147   set_result(_gvn.transform(phi));
1148   return true;
1149 }
1150 
1151 //------------------------------inline_array_equals----------------------------
1152 bool LibraryCallKit::inline_array_equals(StrIntrinsicNode::ArgEnc ae) {
1153   assert(ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::LL, "unsupported array types");
1154   Node* arg1 = argument(0);
1155   Node* arg2 = argument(1);
1156 
1157   const TypeAryPtr* mtype = (ae == StrIntrinsicNode::UU) ? TypeAryPtr::CHARS : TypeAryPtr::BYTES;
1158   set_result(_gvn.transform(new AryEqNode(control(), memory(mtype), arg1, arg2, ae)));
1159   clear_upper_avx();
1160 
1161   return true;
1162 }
1163 
1164 
1165 //------------------------------inline_countPositives------------------------------
1166 // int java.lang.StringCoding#countPositives0(byte[] ba, int off, int len)
1167 bool LibraryCallKit::inline_countPositives() {
1168   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1169     return false;
1170   }
1171 
1172   assert(callee()->signature()->size() == 3, "countPositives has 3 parameters");
1173   // no receiver since it is static method
1174   Node* ba         = argument(0);
1175   Node* offset     = argument(1);
1176   Node* len        = argument(2);
1177 
1178   ba = must_be_not_null(ba, true);
1179   generate_string_range_check(ba, offset, len, false, true);
1180   if (stopped()) {
1181     return true;
1182   }
1183 
1184   Node* ba_start = array_element_address(ba, offset, T_BYTE);
1185   Node* result = new CountPositivesNode(control(), memory(TypeAryPtr::BYTES), ba_start, len);
1186   set_result(_gvn.transform(result));
1187   clear_upper_avx();
1188   return true;
1189 }
1190 
1191 bool LibraryCallKit::inline_preconditions_checkIndex(BasicType bt) {
1192   Node* index = argument(0);
1193   Node* length = bt == T_INT ? argument(1) : argument(2);
1194   if (too_many_traps(Deoptimization::Reason_intrinsic) || too_many_traps(Deoptimization::Reason_range_check)) {
1195     return false;
1196   }
1197 
1198   // check that length is positive
1199   Node* len_pos_cmp = _gvn.transform(CmpNode::make(length, integercon(0, bt), bt));
1200   Node* len_pos_bol = _gvn.transform(new BoolNode(len_pos_cmp, BoolTest::ge));
1201 
1202   {
1203     BuildCutout unless(this, len_pos_bol, PROB_MAX);
1204     uncommon_trap(Deoptimization::Reason_intrinsic,
1205                   Deoptimization::Action_make_not_entrant);
1206   }
1207 
1208   if (stopped()) {
1209     // Length is known to be always negative during compilation and the IR graph so far constructed is good so return success
1210     return true;
1211   }
1212 
1213   // length is now known positive, add a cast node to make this explicit
1214   jlong upper_bound = _gvn.type(length)->is_integer(bt)->hi_as_long();
1215   Node* casted_length = ConstraintCastNode::make_cast_for_basic_type(
1216       control(), length, TypeInteger::make(0, upper_bound, Type::WidenMax, bt),
1217       ConstraintCastNode::DependencyType::FloatingNarrowing, bt);
1218   casted_length = _gvn.transform(casted_length);
1219   replace_in_map(length, casted_length);
1220   length = casted_length;
1221 
1222   // Use an unsigned comparison for the range check itself
1223   Node* rc_cmp = _gvn.transform(CmpNode::make(index, length, bt, true));
1224   BoolTest::mask btest = BoolTest::lt;
1225   Node* rc_bool = _gvn.transform(new BoolNode(rc_cmp, btest));
1226   RangeCheckNode* rc = new RangeCheckNode(control(), rc_bool, PROB_MAX, COUNT_UNKNOWN);
1227   _gvn.set_type(rc, rc->Value(&_gvn));
1228   if (!rc_bool->is_Con()) {
1229     record_for_igvn(rc);
1230   }
1231   set_control(_gvn.transform(new IfTrueNode(rc)));
1232   {
1233     PreserveJVMState pjvms(this);
1234     set_control(_gvn.transform(new IfFalseNode(rc)));
1235     uncommon_trap(Deoptimization::Reason_range_check,
1236                   Deoptimization::Action_make_not_entrant);
1237   }
1238 
1239   if (stopped()) {
1240     // Range check is known to always fail during compilation and the IR graph so far constructed is good so return success
1241     return true;
1242   }
1243 
1244   // index is now known to be >= 0 and < length, cast it
1245   Node* result = ConstraintCastNode::make_cast_for_basic_type(
1246       control(), index, TypeInteger::make(0, upper_bound, Type::WidenMax, bt),
1247       ConstraintCastNode::DependencyType::FloatingNarrowing, bt);
1248   result = _gvn.transform(result);
1249   set_result(result);
1250   replace_in_map(index, result);
1251   return true;
1252 }
1253 
1254 //------------------------------inline_string_indexOf------------------------
1255 bool LibraryCallKit::inline_string_indexOf(StrIntrinsicNode::ArgEnc ae) {
1256   if (!Matcher::match_rule_supported(Op_StrIndexOf)) {
1257     return false;
1258   }
1259   Node* src = argument(0);
1260   Node* tgt = argument(1);
1261 
1262   // Make the merge point
1263   RegionNode* result_rgn = new RegionNode(4);
1264   Node*       result_phi = new PhiNode(result_rgn, TypeInt::INT);
1265 
1266   src = must_be_not_null(src, true);
1267   tgt = must_be_not_null(tgt, true);
1268 
1269   // Get start addr and length of source string
1270   Node* src_start = array_element_address(src, intcon(0), T_BYTE);
1271   Node* src_count = load_array_length(src);
1272 
1273   // Get start addr and length of substring
1274   Node* tgt_start = array_element_address(tgt, intcon(0), T_BYTE);
1275   Node* tgt_count = load_array_length(tgt);
1276 
1277   Node* result = nullptr;
1278   bool call_opt_stub = (StubRoutines::_string_indexof_array[ae] != nullptr);
1279 
1280   if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
1281     // Divide src size by 2 if String is UTF16 encoded
1282     src_count = _gvn.transform(new RShiftINode(src_count, intcon(1)));
1283   }
1284   if (ae == StrIntrinsicNode::UU) {
1285     // Divide substring size by 2 if String is UTF16 encoded
1286     tgt_count = _gvn.transform(new RShiftINode(tgt_count, intcon(1)));
1287   }
1288 
1289   if (call_opt_stub) {
1290     Node* call = make_runtime_call(RC_LEAF, OptoRuntime::string_IndexOf_Type(),
1291                                    StubRoutines::_string_indexof_array[ae],
1292                                    "stringIndexOf", TypePtr::BOTTOM, src_start,
1293                                    src_count, tgt_start, tgt_count);
1294     result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
1295   } else {
1296     result = make_indexOf_node(src_start, src_count, tgt_start, tgt_count,
1297                                result_rgn, result_phi, ae);
1298   }
1299   if (result != nullptr) {
1300     result_phi->init_req(3, result);
1301     result_rgn->init_req(3, control());
1302   }
1303   set_control(_gvn.transform(result_rgn));
1304   record_for_igvn(result_rgn);
1305   set_result(_gvn.transform(result_phi));
1306 
1307   return true;
1308 }
1309 
1310 //-----------------------------inline_string_indexOfI-----------------------
1311 bool LibraryCallKit::inline_string_indexOfI(StrIntrinsicNode::ArgEnc ae) {
1312   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1313     return false;
1314   }
1315   if (!Matcher::match_rule_supported(Op_StrIndexOf)) {
1316     return false;
1317   }
1318 
1319   assert(callee()->signature()->size() == 5, "String.indexOf() has 5 arguments");
1320   Node* src         = argument(0); // byte[]
1321   Node* src_count   = argument(1); // char count
1322   Node* tgt         = argument(2); // byte[]
1323   Node* tgt_count   = argument(3); // char count
1324   Node* from_index  = argument(4); // char index
1325 
1326   src = must_be_not_null(src, true);
1327   tgt = must_be_not_null(tgt, true);
1328 
1329   // Multiply byte array index by 2 if String is UTF16 encoded
1330   Node* src_offset = (ae == StrIntrinsicNode::LL) ? from_index : _gvn.transform(new LShiftINode(from_index, intcon(1)));
1331   src_count = _gvn.transform(new SubINode(src_count, from_index));
1332   Node* src_start = array_element_address(src, src_offset, T_BYTE);
1333   Node* tgt_start = array_element_address(tgt, intcon(0), T_BYTE);
1334 
1335   // Range checks
1336   generate_string_range_check(src, src_offset, src_count, ae != StrIntrinsicNode::LL, true);
1337   generate_string_range_check(tgt, intcon(0), tgt_count, ae == StrIntrinsicNode::UU, true);
1338   if (stopped()) {
1339     return true;
1340   }
1341 
1342   RegionNode* region = new RegionNode(5);
1343   Node* phi = new PhiNode(region, TypeInt::INT);
1344   Node* result = nullptr;
1345 
1346   bool call_opt_stub = (StubRoutines::_string_indexof_array[ae] != nullptr);
1347 
1348   if (call_opt_stub) {
1349     Node* call = make_runtime_call(RC_LEAF, OptoRuntime::string_IndexOf_Type(),
1350                                    StubRoutines::_string_indexof_array[ae],
1351                                    "stringIndexOf", TypePtr::BOTTOM, src_start,
1352                                    src_count, tgt_start, tgt_count);
1353     result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
1354   } else {
1355     result = make_indexOf_node(src_start, src_count, tgt_start, tgt_count,
1356                                region, phi, ae);
1357   }
1358   if (result != nullptr) {
1359     // The result is index relative to from_index if substring was found, -1 otherwise.
1360     // Generate code which will fold into cmove.
1361     Node* cmp = _gvn.transform(new CmpINode(result, intcon(0)));
1362     Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::lt));
1363 
1364     Node* if_lt = generate_slow_guard(bol, nullptr);
1365     if (if_lt != nullptr) {
1366       // result == -1
1367       phi->init_req(3, result);
1368       region->init_req(3, if_lt);
1369     }
1370     if (!stopped()) {
1371       result = _gvn.transform(new AddINode(result, from_index));
1372       phi->init_req(4, result);
1373       region->init_req(4, control());
1374     }
1375   }
1376 
1377   set_control(_gvn.transform(region));
1378   record_for_igvn(region);
1379   set_result(_gvn.transform(phi));
1380   clear_upper_avx();
1381 
1382   return true;
1383 }
1384 
1385 // Create StrIndexOfNode with fast path checks
1386 Node* LibraryCallKit::make_indexOf_node(Node* src_start, Node* src_count, Node* tgt_start, Node* tgt_count,
1387                                         RegionNode* region, Node* phi, StrIntrinsicNode::ArgEnc ae) {
1388   // Check for substr count > string count
1389   Node* cmp = _gvn.transform(new CmpINode(tgt_count, src_count));
1390   Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::gt));
1391   Node* if_gt = generate_slow_guard(bol, nullptr);
1392   if (if_gt != nullptr) {
1393     phi->init_req(1, intcon(-1));
1394     region->init_req(1, if_gt);
1395   }
1396   if (!stopped()) {
1397     // Check for substr count == 0
1398     cmp = _gvn.transform(new CmpINode(tgt_count, intcon(0)));
1399     bol = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
1400     Node* if_zero = generate_slow_guard(bol, nullptr);
1401     if (if_zero != nullptr) {
1402       phi->init_req(2, intcon(0));
1403       region->init_req(2, if_zero);
1404     }
1405   }
1406   if (!stopped()) {
1407     return make_string_method_node(Op_StrIndexOf, src_start, src_count, tgt_start, tgt_count, ae);
1408   }
1409   return nullptr;
1410 }
1411 
1412 //-----------------------------inline_string_indexOfChar-----------------------
1413 bool LibraryCallKit::inline_string_indexOfChar(StrIntrinsicNode::ArgEnc ae) {
1414   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1415     return false;
1416   }
1417   if (!Matcher::match_rule_supported(Op_StrIndexOfChar)) {
1418     return false;
1419   }
1420   assert(callee()->signature()->size() == 4, "String.indexOfChar() has 4 arguments");
1421   Node* src         = argument(0); // byte[]
1422   Node* int_ch      = argument(1);
1423   Node* from_index  = argument(2);
1424   Node* max         = argument(3);
1425 
1426   src = must_be_not_null(src, true);
1427 
1428   Node* src_offset = ae == StrIntrinsicNode::L ? from_index : _gvn.transform(new LShiftINode(from_index, intcon(1)));
1429   Node* src_start = array_element_address(src, src_offset, T_BYTE);
1430   Node* src_count = _gvn.transform(new SubINode(max, from_index));
1431 
1432   // Range checks
1433   generate_string_range_check(src, src_offset, src_count, ae == StrIntrinsicNode::U, true);
1434 
1435   // Check for int_ch >= 0
1436   Node* int_ch_cmp = _gvn.transform(new CmpINode(int_ch, intcon(0)));
1437   Node* int_ch_bol = _gvn.transform(new BoolNode(int_ch_cmp, BoolTest::ge));
1438   {
1439     BuildCutout unless(this, int_ch_bol, PROB_MAX);
1440     uncommon_trap(Deoptimization::Reason_intrinsic,
1441                   Deoptimization::Action_maybe_recompile);
1442   }
1443   if (stopped()) {
1444     return true;
1445   }
1446 
1447   RegionNode* region = new RegionNode(3);
1448   Node* phi = new PhiNode(region, TypeInt::INT);
1449 
1450   Node* result = new StrIndexOfCharNode(control(), memory(TypeAryPtr::BYTES), src_start, src_count, int_ch, ae);
1451   C->set_has_split_ifs(true); // Has chance for split-if optimization
1452   _gvn.transform(result);
1453 
1454   Node* cmp = _gvn.transform(new CmpINode(result, intcon(0)));
1455   Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::lt));
1456 
1457   Node* if_lt = generate_slow_guard(bol, nullptr);
1458   if (if_lt != nullptr) {
1459     // result == -1
1460     phi->init_req(2, result);
1461     region->init_req(2, if_lt);
1462   }
1463   if (!stopped()) {
1464     result = _gvn.transform(new AddINode(result, from_index));
1465     phi->init_req(1, result);
1466     region->init_req(1, control());
1467   }
1468   set_control(_gvn.transform(region));
1469   record_for_igvn(region);
1470   set_result(_gvn.transform(phi));
1471   clear_upper_avx();
1472 
1473   return true;
1474 }
1475 //---------------------------inline_string_copy---------------------
1476 // compressIt == true --> generate a compressed copy operation (compress char[]/byte[] to byte[])
1477 //   int StringUTF16.compress0(char[] src, int srcOff, byte[] dst, int dstOff, int len)
1478 //   int StringUTF16.compress0(byte[] src, int srcOff, byte[] dst, int dstOff, int len)
1479 // compressIt == false --> generate an inflated copy operation (inflate byte[] to char[]/byte[])
1480 //   void StringLatin1.inflate0(byte[] src, int srcOff, char[] dst, int dstOff, int len)
1481 //   void StringLatin1.inflate0(byte[] src, int srcOff, byte[] dst, int dstOff, int len)
1482 bool LibraryCallKit::inline_string_copy(bool compress) {
1483   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1484     return false;
1485   }
1486   int nargs = 5;  // 2 oops, 3 ints
1487   assert(callee()->signature()->size() == nargs, "string copy has 5 arguments");
1488 
1489   Node* src         = argument(0);
1490   Node* src_offset  = argument(1);
1491   Node* dst         = argument(2);
1492   Node* dst_offset  = argument(3);
1493   Node* length      = argument(4);
1494 
1495   // Check for allocation before we add nodes that would confuse
1496   // tightly_coupled_allocation()
1497   AllocateArrayNode* alloc = tightly_coupled_allocation(dst);
1498 
1499   // Figure out the size and type of the elements we will be copying.
1500   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
1501   const TypeAryPtr* dst_type = dst->Value(&_gvn)->isa_aryptr();
1502   if (src_type == nullptr || dst_type == nullptr) {
1503     return false;
1504   }
1505   BasicType src_elem = src_type->elem()->array_element_basic_type();
1506   BasicType dst_elem = dst_type->elem()->array_element_basic_type();
1507   assert((compress && dst_elem == T_BYTE && (src_elem == T_BYTE || src_elem == T_CHAR)) ||
1508          (!compress && src_elem == T_BYTE && (dst_elem == T_BYTE || dst_elem == T_CHAR)),
1509          "Unsupported array types for inline_string_copy");
1510 
1511   src = must_be_not_null(src, true);
1512   dst = must_be_not_null(dst, true);
1513 
1514   // Convert char[] offsets to byte[] offsets
1515   bool convert_src = (compress && src_elem == T_BYTE);
1516   bool convert_dst = (!compress && dst_elem == T_BYTE);
1517   if (convert_src) {
1518     src_offset = _gvn.transform(new LShiftINode(src_offset, intcon(1)));
1519   } else if (convert_dst) {
1520     dst_offset = _gvn.transform(new LShiftINode(dst_offset, intcon(1)));
1521   }
1522 
1523   // Range checks
1524   generate_string_range_check(src, src_offset, length, convert_src, true);
1525   generate_string_range_check(dst, dst_offset, length, convert_dst, true);
1526   if (stopped()) {
1527     return true;
1528   }
1529 
1530   Node* src_start = array_element_address(src, src_offset, src_elem);
1531   Node* dst_start = array_element_address(dst, dst_offset, dst_elem);
1532   // 'src_start' points to src array + scaled offset
1533   // 'dst_start' points to dst array + scaled offset
1534   Node* count = nullptr;
1535   if (compress) {
1536     count = compress_string(src_start, TypeAryPtr::get_array_body_type(src_elem), dst_start, length);
1537   } else {
1538     inflate_string(src_start, dst_start, TypeAryPtr::get_array_body_type(dst_elem), length);
1539   }
1540 
1541   if (alloc != nullptr) {
1542     if (alloc->maybe_set_complete(&_gvn)) {
1543       // "You break it, you buy it."
1544       InitializeNode* init = alloc->initialization();
1545       assert(init->is_complete(), "we just did this");
1546       init->set_complete_with_arraycopy();
1547       assert(dst->is_CheckCastPP(), "sanity");
1548       assert(dst->in(0)->in(0) == init, "dest pinned");
1549     }
1550     // Do not let stores that initialize this object be reordered with
1551     // a subsequent store that would make this object accessible by
1552     // other threads.
1553     // Record what AllocateNode this StoreStore protects so that
1554     // escape analysis can go from the MemBarStoreStoreNode to the
1555     // AllocateNode and eliminate the MemBarStoreStoreNode if possible
1556     // based on the escape status of the AllocateNode.
1557     insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
1558   }
1559   if (compress) {
1560     set_result(_gvn.transform(count));
1561   }
1562   clear_upper_avx();
1563 
1564   return true;
1565 }
1566 
1567 #ifdef _LP64
1568 #define XTOP ,top() /*additional argument*/
1569 #else  //_LP64
1570 #define XTOP        /*no additional argument*/
1571 #endif //_LP64
1572 
1573 //------------------------inline_string_toBytesU--------------------------
1574 // public static byte[] StringUTF16.toBytes(char[] value, int off, int len)
1575 bool LibraryCallKit::inline_string_toBytesU() {
1576   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1577     return false;
1578   }
1579   // Get the arguments.
1580   Node* value     = argument(0);
1581   Node* offset    = argument(1);
1582   Node* length    = argument(2);
1583 
1584   Node* newcopy = nullptr;
1585 
1586   // Set the original stack and the reexecute bit for the interpreter to reexecute
1587   // the bytecode that invokes StringUTF16.toBytes() if deoptimization happens.
1588   { PreserveReexecuteState preexecs(this);
1589     jvms()->set_should_reexecute(true);
1590 
1591     // Check if a null path was taken unconditionally.
1592     value = null_check(value);
1593 
1594     RegionNode* bailout = new RegionNode(1);
1595     record_for_igvn(bailout);
1596 
1597     // Range checks
1598     generate_negative_guard(offset, bailout);
1599     generate_negative_guard(length, bailout);
1600     generate_limit_guard(offset, length, load_array_length(value), bailout);
1601     // Make sure that resulting byte[] length does not overflow Integer.MAX_VALUE
1602     generate_limit_guard(length, intcon(0), intcon(max_jint/2), bailout);
1603 
1604     if (bailout->req() > 1) {
1605       PreserveJVMState pjvms(this);
1606       set_control(_gvn.transform(bailout));
1607       uncommon_trap(Deoptimization::Reason_intrinsic,
1608                     Deoptimization::Action_maybe_recompile);
1609     }
1610     if (stopped()) {
1611       return true;
1612     }
1613 
1614     Node* size = _gvn.transform(new LShiftINode(length, intcon(1)));
1615     Node* klass_node = makecon(TypeKlassPtr::make(ciTypeArrayKlass::make(T_BYTE)));
1616     newcopy = new_array(klass_node, size, 0);  // no arguments to push
1617     AllocateArrayNode* alloc = tightly_coupled_allocation(newcopy);
1618     guarantee(alloc != nullptr, "created above");
1619 
1620     // Calculate starting addresses.
1621     Node* src_start = array_element_address(value, offset, T_CHAR);
1622     Node* dst_start = basic_plus_adr(newcopy, arrayOopDesc::base_offset_in_bytes(T_BYTE));
1623 
1624     // Check if dst array address is aligned to HeapWordSize
1625     bool aligned = (arrayOopDesc::base_offset_in_bytes(T_BYTE) % HeapWordSize == 0);
1626     // If true, then check if src array address is aligned to HeapWordSize
1627     if (aligned) {
1628       const TypeInt* toffset = gvn().type(offset)->is_int();
1629       aligned = toffset->is_con() && ((arrayOopDesc::base_offset_in_bytes(T_CHAR) +
1630                                        toffset->get_con() * type2aelembytes(T_CHAR)) % HeapWordSize == 0);
1631     }
1632 
1633     // Figure out which arraycopy runtime method to call (disjoint, uninitialized).
1634     const char* copyfunc_name = "arraycopy";
1635     address     copyfunc_addr = StubRoutines::select_arraycopy_function(T_CHAR, aligned, true, copyfunc_name, true);
1636     Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
1637                       OptoRuntime::fast_arraycopy_Type(),
1638                       copyfunc_addr, copyfunc_name, TypeRawPtr::BOTTOM,
1639                       src_start, dst_start, ConvI2X(length) XTOP);
1640     // Do not let reads from the cloned object float above the arraycopy.
1641     if (alloc->maybe_set_complete(&_gvn)) {
1642       // "You break it, you buy it."
1643       InitializeNode* init = alloc->initialization();
1644       assert(init->is_complete(), "we just did this");
1645       init->set_complete_with_arraycopy();
1646       assert(newcopy->is_CheckCastPP(), "sanity");
1647       assert(newcopy->in(0)->in(0) == init, "dest pinned");
1648     }
1649     // Do not let stores that initialize this object be reordered with
1650     // a subsequent store that would make this object accessible by
1651     // other threads.
1652     // Record what AllocateNode this StoreStore protects so that
1653     // escape analysis can go from the MemBarStoreStoreNode to the
1654     // AllocateNode and eliminate the MemBarStoreStoreNode if possible
1655     // based on the escape status of the AllocateNode.
1656     insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
1657   } // original reexecute is set back here
1658 
1659   C->set_has_split_ifs(true); // Has chance for split-if optimization
1660   if (!stopped()) {
1661     set_result(newcopy);
1662   }
1663   clear_upper_avx();
1664 
1665   return true;
1666 }
1667 
1668 //------------------------inline_string_getCharsU--------------------------
1669 // public void StringUTF16.getChars(byte[] src, int srcBegin, int srcEnd, char dst[], int dstBegin)
1670 bool LibraryCallKit::inline_string_getCharsU() {
1671   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1672     return false;
1673   }
1674 
1675   // Get the arguments.
1676   Node* src       = argument(0);
1677   Node* src_begin = argument(1);
1678   Node* src_end   = argument(2); // exclusive offset (i < src_end)
1679   Node* dst       = argument(3);
1680   Node* dst_begin = argument(4);
1681 
1682   // Check for allocation before we add nodes that would confuse
1683   // tightly_coupled_allocation()
1684   AllocateArrayNode* alloc = tightly_coupled_allocation(dst);
1685 
1686   // Check if a null path was taken unconditionally.
1687   src = null_check(src);
1688   dst = null_check(dst);
1689   if (stopped()) {
1690     return true;
1691   }
1692 
1693   // Get length and convert char[] offset to byte[] offset
1694   Node* length = _gvn.transform(new SubINode(src_end, src_begin));
1695   src_begin = _gvn.transform(new LShiftINode(src_begin, intcon(1)));
1696 
1697   // Range checks
1698   generate_string_range_check(src, src_begin, length, true);
1699   generate_string_range_check(dst, dst_begin, length, false);
1700   if (stopped()) {
1701     return true;
1702   }
1703 
1704   if (!stopped()) {
1705     // Calculate starting addresses.
1706     Node* src_start = array_element_address(src, src_begin, T_BYTE);
1707     Node* dst_start = array_element_address(dst, dst_begin, T_CHAR);
1708 
1709     // Check if array addresses are aligned to HeapWordSize
1710     const TypeInt* tsrc = gvn().type(src_begin)->is_int();
1711     const TypeInt* tdst = gvn().type(dst_begin)->is_int();
1712     bool aligned = tsrc->is_con() && ((arrayOopDesc::base_offset_in_bytes(T_BYTE) + tsrc->get_con() * type2aelembytes(T_BYTE)) % HeapWordSize == 0) &&
1713                    tdst->is_con() && ((arrayOopDesc::base_offset_in_bytes(T_CHAR) + tdst->get_con() * type2aelembytes(T_CHAR)) % HeapWordSize == 0);
1714 
1715     // Figure out which arraycopy runtime method to call (disjoint, uninitialized).
1716     const char* copyfunc_name = "arraycopy";
1717     address     copyfunc_addr = StubRoutines::select_arraycopy_function(T_CHAR, aligned, true, copyfunc_name, true);
1718     Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
1719                       OptoRuntime::fast_arraycopy_Type(),
1720                       copyfunc_addr, copyfunc_name, TypeRawPtr::BOTTOM,
1721                       src_start, dst_start, ConvI2X(length) XTOP);
1722     // Do not let reads from the cloned object float above the arraycopy.
1723     if (alloc != nullptr) {
1724       if (alloc->maybe_set_complete(&_gvn)) {
1725         // "You break it, you buy it."
1726         InitializeNode* init = alloc->initialization();
1727         assert(init->is_complete(), "we just did this");
1728         init->set_complete_with_arraycopy();
1729         assert(dst->is_CheckCastPP(), "sanity");
1730         assert(dst->in(0)->in(0) == init, "dest pinned");
1731       }
1732       // Do not let stores that initialize this object be reordered with
1733       // a subsequent store that would make this object accessible by
1734       // other threads.
1735       // Record what AllocateNode this StoreStore protects so that
1736       // escape analysis can go from the MemBarStoreStoreNode to the
1737       // AllocateNode and eliminate the MemBarStoreStoreNode if possible
1738       // based on the escape status of the AllocateNode.
1739       insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
1740     } else {
1741       insert_mem_bar(Op_MemBarCPUOrder);
1742     }
1743   }
1744 
1745   C->set_has_split_ifs(true); // Has chance for split-if optimization
1746   return true;
1747 }
1748 
1749 //----------------------inline_string_char_access----------------------------
1750 // Store/Load char to/from byte[] array.
1751 // static void StringUTF16.putChar(byte[] val, int index, int c)
1752 // static char StringUTF16.getChar(byte[] val, int index)
1753 bool LibraryCallKit::inline_string_char_access(bool is_store) {
1754   Node* value  = argument(0);
1755   Node* index  = argument(1);
1756   Node* ch = is_store ? argument(2) : nullptr;
1757 
1758   // This intrinsic accesses byte[] array as char[] array. Computing the offsets
1759   // correctly requires matched array shapes.
1760   assert (arrayOopDesc::base_offset_in_bytes(T_CHAR) == arrayOopDesc::base_offset_in_bytes(T_BYTE),
1761           "sanity: byte[] and char[] bases agree");
1762   assert (type2aelembytes(T_CHAR) == type2aelembytes(T_BYTE)*2,
1763           "sanity: byte[] and char[] scales agree");
1764 
1765   // Bail when getChar over constants is requested: constant folding would
1766   // reject folding mismatched char access over byte[]. A normal inlining for getChar
1767   // Java method would constant fold nicely instead.
1768   if (!is_store && value->is_Con() && index->is_Con()) {
1769     return false;
1770   }
1771 
1772   // Save state and restore on bailout
1773   SavedState old_state(this);
1774 
1775   value = must_be_not_null(value, true);
1776 
1777   Node* adr = array_element_address(value, index, T_CHAR);
1778   if (adr->is_top()) {
1779     return false;
1780   }
1781   old_state.discard();
1782   if (is_store) {
1783     access_store_at(value, adr, TypeAryPtr::BYTES, ch, TypeInt::CHAR, T_CHAR, IN_HEAP | MO_UNORDERED | C2_MISMATCHED);
1784   } else {
1785     ch = access_load_at(value, adr, TypeAryPtr::BYTES, TypeInt::CHAR, T_CHAR, IN_HEAP | MO_UNORDERED | C2_MISMATCHED | C2_CONTROL_DEPENDENT_LOAD | C2_UNKNOWN_CONTROL_LOAD);
1786     set_result(ch);
1787   }
1788   return true;
1789 }
1790 
1791 
1792 //------------------------------inline_math-----------------------------------
1793 // public static double Math.abs(double)
1794 // public static double Math.sqrt(double)
1795 // public static double Math.log(double)
1796 // public static double Math.log10(double)
1797 // public static double Math.round(double)
1798 bool LibraryCallKit::inline_double_math(vmIntrinsics::ID id) {
1799   Node* arg = argument(0);
1800   Node* n = nullptr;
1801   switch (id) {
1802   case vmIntrinsics::_dabs:   n = new AbsDNode(                arg);  break;
1803   case vmIntrinsics::_dsqrt:
1804   case vmIntrinsics::_dsqrt_strict:
1805                               n = new SqrtDNode(C, control(),  arg);  break;
1806   case vmIntrinsics::_ceil:   n = RoundDoubleModeNode::make(_gvn, arg, RoundDoubleModeNode::rmode_ceil); break;
1807   case vmIntrinsics::_floor:  n = RoundDoubleModeNode::make(_gvn, arg, RoundDoubleModeNode::rmode_floor); break;
1808   case vmIntrinsics::_rint:   n = RoundDoubleModeNode::make(_gvn, arg, RoundDoubleModeNode::rmode_rint); break;
1809   case vmIntrinsics::_roundD: n = new RoundDNode(arg); break;
1810   case vmIntrinsics::_dcopySign: n = CopySignDNode::make(_gvn, arg, argument(2)); break;
1811   case vmIntrinsics::_dsignum: n = SignumDNode::make(_gvn, arg); break;
1812   default:  fatal_unexpected_iid(id);  break;
1813   }
1814   set_result(_gvn.transform(n));
1815   return true;
1816 }
1817 
1818 //------------------------------inline_math-----------------------------------
1819 // public static float Math.abs(float)
1820 // public static int Math.abs(int)
1821 // public static long Math.abs(long)
1822 bool LibraryCallKit::inline_math(vmIntrinsics::ID id) {
1823   Node* arg = argument(0);
1824   Node* n = nullptr;
1825   switch (id) {
1826   case vmIntrinsics::_fabs:   n = new AbsFNode(                arg);  break;
1827   case vmIntrinsics::_iabs:   n = new AbsINode(                arg);  break;
1828   case vmIntrinsics::_labs:   n = new AbsLNode(                arg);  break;
1829   case vmIntrinsics::_fcopySign: n = new CopySignFNode(arg, argument(1)); break;
1830   case vmIntrinsics::_fsignum: n = SignumFNode::make(_gvn, arg); break;
1831   case vmIntrinsics::_roundF: n = new RoundFNode(arg); break;
1832   default:  fatal_unexpected_iid(id);  break;
1833   }
1834   set_result(_gvn.transform(n));
1835   return true;
1836 }
1837 
1838 //------------------------------runtime_math-----------------------------
1839 bool LibraryCallKit::runtime_math(const TypeFunc* call_type, address funcAddr, const char* funcName) {
1840   assert(call_type == OptoRuntime::Math_DD_D_Type() || call_type == OptoRuntime::Math_D_D_Type(),
1841          "must be (DD)D or (D)D type");
1842 
1843   // Inputs
1844   Node* a = argument(0);
1845   Node* b = (call_type == OptoRuntime::Math_DD_D_Type()) ? argument(2) : nullptr;
1846 
1847   const TypePtr* no_memory_effects = nullptr;
1848   Node* trig = make_runtime_call(RC_LEAF | RC_PURE, call_type, funcAddr, funcName,
1849                                  no_memory_effects,
1850                                  a, top(), b, b ? top() : nullptr);
1851   Node* value = _gvn.transform(new ProjNode(trig, TypeFunc::Parms+0));
1852 #ifdef ASSERT
1853   Node* value_top = _gvn.transform(new ProjNode(trig, TypeFunc::Parms+1));
1854   assert(value_top == top(), "second value must be top");
1855 #endif
1856 
1857   set_result(value);
1858   return true;
1859 }
1860 
1861 //------------------------------inline_math_pow-----------------------------
1862 bool LibraryCallKit::inline_math_pow() {
1863   Node* exp = argument(2);
1864   const TypeD* d = _gvn.type(exp)->isa_double_constant();
1865   if (d != nullptr) {
1866     if (d->getd() == 2.0) {
1867       // Special case: pow(x, 2.0) => x * x
1868       Node* base = argument(0);
1869       set_result(_gvn.transform(new MulDNode(base, base)));
1870       return true;
1871     } else if (d->getd() == 0.5 && Matcher::match_rule_supported(Op_SqrtD)) {
1872       // Special case: pow(x, 0.5) => sqrt(x)
1873       Node* base = argument(0);
1874       Node* zero = _gvn.zerocon(T_DOUBLE);
1875 
1876       RegionNode* region = new RegionNode(3);
1877       Node* phi = new PhiNode(region, Type::DOUBLE);
1878 
1879       Node* cmp  = _gvn.transform(new CmpDNode(base, zero));
1880       // According to the API specs, pow(-0.0, 0.5) = 0.0 and sqrt(-0.0) = -0.0.
1881       // So pow(-0.0, 0.5) shouldn't be replaced with sqrt(-0.0).
1882       // -0.0/+0.0 are both excluded since floating-point comparison doesn't distinguish -0.0 from +0.0.
1883       Node* test = _gvn.transform(new BoolNode(cmp, BoolTest::le));
1884 
1885       Node* if_pow = generate_slow_guard(test, nullptr);
1886       Node* value_sqrt = _gvn.transform(new SqrtDNode(C, control(), base));
1887       phi->init_req(1, value_sqrt);
1888       region->init_req(1, control());
1889 
1890       if (if_pow != nullptr) {
1891         set_control(if_pow);
1892         address target = StubRoutines::dpow() != nullptr ? StubRoutines::dpow() :
1893                                                         CAST_FROM_FN_PTR(address, SharedRuntime::dpow);
1894         const TypePtr* no_memory_effects = nullptr;
1895         Node* trig = make_runtime_call(RC_LEAF, OptoRuntime::Math_DD_D_Type(), target, "POW",
1896                                        no_memory_effects, base, top(), exp, top());
1897         Node* value_pow = _gvn.transform(new ProjNode(trig, TypeFunc::Parms+0));
1898 #ifdef ASSERT
1899         Node* value_top = _gvn.transform(new ProjNode(trig, TypeFunc::Parms+1));
1900         assert(value_top == top(), "second value must be top");
1901 #endif
1902         phi->init_req(2, value_pow);
1903         region->init_req(2, _gvn.transform(new ProjNode(trig, TypeFunc::Control)));
1904       }
1905 
1906       C->set_has_split_ifs(true); // Has chance for split-if optimization
1907       set_control(_gvn.transform(region));
1908       record_for_igvn(region);
1909       set_result(_gvn.transform(phi));
1910 
1911       return true;
1912     }
1913   }
1914 
1915   return StubRoutines::dpow() != nullptr ?
1916     runtime_math(OptoRuntime::Math_DD_D_Type(), StubRoutines::dpow(),  "dpow") :
1917     runtime_math(OptoRuntime::Math_DD_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dpow),  "POW");
1918 }
1919 
1920 //------------------------------inline_math_native-----------------------------
1921 bool LibraryCallKit::inline_math_native(vmIntrinsics::ID id) {
1922   switch (id) {
1923   case vmIntrinsics::_dsin:
1924     return StubRoutines::dsin() != nullptr ?
1925       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dsin(), "dsin") :
1926       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dsin),   "SIN");
1927   case vmIntrinsics::_dcos:
1928     return StubRoutines::dcos() != nullptr ?
1929       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dcos(), "dcos") :
1930       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dcos),   "COS");
1931   case vmIntrinsics::_dtan:
1932     return StubRoutines::dtan() != nullptr ?
1933       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dtan(), "dtan") :
1934       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dtan), "TAN");
1935   case vmIntrinsics::_dsinh:
1936     return StubRoutines::dsinh() != nullptr ?
1937       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dsinh(), "dsinh") : false;
1938   case vmIntrinsics::_dtanh:
1939     return StubRoutines::dtanh() != nullptr ?
1940       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dtanh(), "dtanh") : false;
1941   case vmIntrinsics::_dcbrt:
1942     return StubRoutines::dcbrt() != nullptr ?
1943       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dcbrt(), "dcbrt") : false;
1944   case vmIntrinsics::_dexp:
1945     return StubRoutines::dexp() != nullptr ?
1946       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dexp(),  "dexp") :
1947       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dexp),  "EXP");
1948   case vmIntrinsics::_dlog:
1949     return StubRoutines::dlog() != nullptr ?
1950       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dlog(), "dlog") :
1951       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dlog),   "LOG");
1952   case vmIntrinsics::_dlog10:
1953     return StubRoutines::dlog10() != nullptr ?
1954       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dlog10(), "dlog10") :
1955       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dlog10), "LOG10");
1956 
1957   case vmIntrinsics::_roundD: return Matcher::match_rule_supported(Op_RoundD) ? inline_double_math(id) : false;
1958   case vmIntrinsics::_ceil:
1959   case vmIntrinsics::_floor:
1960   case vmIntrinsics::_rint:   return Matcher::match_rule_supported(Op_RoundDoubleMode) ? inline_double_math(id) : false;
1961 
1962   case vmIntrinsics::_dsqrt:
1963   case vmIntrinsics::_dsqrt_strict:
1964                               return Matcher::match_rule_supported(Op_SqrtD) ? inline_double_math(id) : false;
1965   case vmIntrinsics::_dabs:   return Matcher::has_match_rule(Op_AbsD)   ? inline_double_math(id) : false;
1966   case vmIntrinsics::_fabs:   return Matcher::match_rule_supported(Op_AbsF)   ? inline_math(id) : false;
1967   case vmIntrinsics::_iabs:   return Matcher::match_rule_supported(Op_AbsI)   ? inline_math(id) : false;
1968   case vmIntrinsics::_labs:   return Matcher::match_rule_supported(Op_AbsL)   ? inline_math(id) : false;
1969 
1970   case vmIntrinsics::_dpow:      return inline_math_pow();
1971   case vmIntrinsics::_dcopySign: return inline_double_math(id);
1972   case vmIntrinsics::_fcopySign: return inline_math(id);
1973   case vmIntrinsics::_dsignum: return Matcher::match_rule_supported(Op_SignumD) ? inline_double_math(id) : false;
1974   case vmIntrinsics::_fsignum: return Matcher::match_rule_supported(Op_SignumF) ? inline_math(id) : false;
1975   case vmIntrinsics::_roundF: return Matcher::match_rule_supported(Op_RoundF) ? inline_math(id) : false;
1976 
1977    // These intrinsics are not yet correctly implemented
1978   case vmIntrinsics::_datan2:
1979     return false;
1980 
1981   default:
1982     fatal_unexpected_iid(id);
1983     return false;
1984   }
1985 }
1986 
1987 //----------------------------inline_notify-----------------------------------*
1988 bool LibraryCallKit::inline_notify(vmIntrinsics::ID id) {
1989   const TypeFunc* ftype = OptoRuntime::monitor_notify_Type();
1990   address func;
1991   if (id == vmIntrinsics::_notify) {
1992     func = OptoRuntime::monitor_notify_Java();
1993   } else {
1994     func = OptoRuntime::monitor_notifyAll_Java();
1995   }
1996   Node* call = make_runtime_call(RC_NO_LEAF, ftype, func, nullptr, TypeRawPtr::BOTTOM, argument(0));
1997   make_slow_call_ex(call, env()->Throwable_klass(), false);
1998   return true;
1999 }
2000 
2001 
2002 //----------------------------inline_min_max-----------------------------------
2003 bool LibraryCallKit::inline_min_max(vmIntrinsics::ID id) {
2004   Node* a = nullptr;
2005   Node* b = nullptr;
2006   Node* n = nullptr;
2007   switch (id) {
2008     case vmIntrinsics::_min:
2009     case vmIntrinsics::_max:
2010     case vmIntrinsics::_minF:
2011     case vmIntrinsics::_maxF:
2012     case vmIntrinsics::_minF_strict:
2013     case vmIntrinsics::_maxF_strict:
2014     case vmIntrinsics::_min_strict:
2015     case vmIntrinsics::_max_strict:
2016       assert(callee()->signature()->size() == 2, "minF/maxF has 2 parameters of size 1 each.");
2017       a = argument(0);
2018       b = argument(1);
2019       break;
2020     case vmIntrinsics::_minD:
2021     case vmIntrinsics::_maxD:
2022     case vmIntrinsics::_minD_strict:
2023     case vmIntrinsics::_maxD_strict:
2024       assert(callee()->signature()->size() == 4, "minD/maxD has 2 parameters of size 2 each.");
2025       a = argument(0);
2026       b = argument(2);
2027       break;
2028     case vmIntrinsics::_minL:
2029     case vmIntrinsics::_maxL:
2030       assert(callee()->signature()->size() == 4, "minL/maxL has 2 parameters of size 2 each.");
2031       a = argument(0);
2032       b = argument(2);
2033       break;
2034     default:
2035       fatal_unexpected_iid(id);
2036       break;
2037   }
2038 
2039   switch (id) {
2040     case vmIntrinsics::_min:
2041     case vmIntrinsics::_min_strict:
2042       n = new MinINode(a, b);
2043       break;
2044     case vmIntrinsics::_max:
2045     case vmIntrinsics::_max_strict:
2046       n = new MaxINode(a, b);
2047       break;
2048     case vmIntrinsics::_minF:
2049     case vmIntrinsics::_minF_strict:
2050       n = new MinFNode(a, b);
2051       break;
2052     case vmIntrinsics::_maxF:
2053     case vmIntrinsics::_maxF_strict:
2054       n = new MaxFNode(a, b);
2055       break;
2056     case vmIntrinsics::_minD:
2057     case vmIntrinsics::_minD_strict:
2058       n = new MinDNode(a, b);
2059       break;
2060     case vmIntrinsics::_maxD:
2061     case vmIntrinsics::_maxD_strict:
2062       n = new MaxDNode(a, b);
2063       break;
2064     case vmIntrinsics::_minL:
2065       n = new MinLNode(_gvn.C, a, b);
2066       break;
2067     case vmIntrinsics::_maxL:
2068       n = new MaxLNode(_gvn.C, a, b);
2069       break;
2070     default:
2071       fatal_unexpected_iid(id);
2072       break;
2073   }
2074 
2075   set_result(_gvn.transform(n));
2076   return true;
2077 }
2078 
2079 bool LibraryCallKit::inline_math_mathExact(Node* math, Node* test) {
2080   if (builtin_throw_too_many_traps(Deoptimization::Reason_intrinsic,
2081                                    env()->ArithmeticException_instance())) {
2082     // It has been already too many times, but we cannot use builtin_throw (e.g. we care about backtraces),
2083     // so let's bail out intrinsic rather than risking deopting again.
2084     return false;
2085   }
2086 
2087   Node* bol = _gvn.transform( new BoolNode(test, BoolTest::overflow) );
2088   IfNode* check = create_and_map_if(control(), bol, PROB_UNLIKELY_MAG(3), COUNT_UNKNOWN);
2089   Node* fast_path = _gvn.transform( new IfFalseNode(check));
2090   Node* slow_path = _gvn.transform( new IfTrueNode(check) );
2091 
2092   {
2093     PreserveJVMState pjvms(this);
2094     PreserveReexecuteState preexecs(this);
2095     jvms()->set_should_reexecute(true);
2096 
2097     set_control(slow_path);
2098     set_i_o(i_o());
2099 
2100     builtin_throw(Deoptimization::Reason_intrinsic,
2101                   env()->ArithmeticException_instance(),
2102                   /*allow_too_many_traps*/ false);
2103   }
2104 
2105   set_control(fast_path);
2106   set_result(math);
2107   return true;
2108 }
2109 
2110 template <typename OverflowOp>
2111 bool LibraryCallKit::inline_math_overflow(Node* arg1, Node* arg2) {
2112   typedef typename OverflowOp::MathOp MathOp;
2113 
2114   MathOp* mathOp = new MathOp(arg1, arg2);
2115   Node* operation = _gvn.transform( mathOp );
2116   Node* ofcheck = _gvn.transform( new OverflowOp(arg1, arg2) );
2117   return inline_math_mathExact(operation, ofcheck);
2118 }
2119 
2120 bool LibraryCallKit::inline_math_addExactI(bool is_increment) {
2121   return inline_math_overflow<OverflowAddINode>(argument(0), is_increment ? intcon(1) : argument(1));
2122 }
2123 
2124 bool LibraryCallKit::inline_math_addExactL(bool is_increment) {
2125   return inline_math_overflow<OverflowAddLNode>(argument(0), is_increment ? longcon(1) : argument(2));
2126 }
2127 
2128 bool LibraryCallKit::inline_math_subtractExactI(bool is_decrement) {
2129   return inline_math_overflow<OverflowSubINode>(argument(0), is_decrement ? intcon(1) : argument(1));
2130 }
2131 
2132 bool LibraryCallKit::inline_math_subtractExactL(bool is_decrement) {
2133   return inline_math_overflow<OverflowSubLNode>(argument(0), is_decrement ? longcon(1) : argument(2));
2134 }
2135 
2136 bool LibraryCallKit::inline_math_negateExactI() {
2137   return inline_math_overflow<OverflowSubINode>(intcon(0), argument(0));
2138 }
2139 
2140 bool LibraryCallKit::inline_math_negateExactL() {
2141   return inline_math_overflow<OverflowSubLNode>(longcon(0), argument(0));
2142 }
2143 
2144 bool LibraryCallKit::inline_math_multiplyExactI() {
2145   return inline_math_overflow<OverflowMulINode>(argument(0), argument(1));
2146 }
2147 
2148 bool LibraryCallKit::inline_math_multiplyExactL() {
2149   return inline_math_overflow<OverflowMulLNode>(argument(0), argument(2));
2150 }
2151 
2152 bool LibraryCallKit::inline_math_multiplyHigh() {
2153   set_result(_gvn.transform(new MulHiLNode(argument(0), argument(2))));
2154   return true;
2155 }
2156 
2157 bool LibraryCallKit::inline_math_unsignedMultiplyHigh() {
2158   set_result(_gvn.transform(new UMulHiLNode(argument(0), argument(2))));
2159   return true;
2160 }
2161 
2162 inline int
2163 LibraryCallKit::classify_unsafe_addr(Node* &base, Node* &offset, BasicType type) {
2164   const TypePtr* base_type = TypePtr::NULL_PTR;
2165   if (base != nullptr)  base_type = _gvn.type(base)->isa_ptr();
2166   if (base_type == nullptr) {
2167     // Unknown type.
2168     return Type::AnyPtr;
2169   } else if (_gvn.type(base->uncast()) == TypePtr::NULL_PTR) {
2170     // Since this is a null+long form, we have to switch to a rawptr.
2171     base   = _gvn.transform(new CastX2PNode(offset));
2172     offset = MakeConX(0);
2173     return Type::RawPtr;
2174   } else if (base_type->base() == Type::RawPtr) {
2175     return Type::RawPtr;
2176   } else if (base_type->isa_oopptr()) {
2177     // Base is never null => always a heap address.
2178     if (!TypePtr::NULL_PTR->higher_equal(base_type)) {
2179       return Type::OopPtr;
2180     }
2181     // Offset is small => always a heap address.
2182     const TypeX* offset_type = _gvn.type(offset)->isa_intptr_t();
2183     if (offset_type != nullptr &&
2184         base_type->offset() == 0 &&     // (should always be?)
2185         offset_type->_lo >= 0 &&
2186         !MacroAssembler::needs_explicit_null_check(offset_type->_hi)) {
2187       return Type::OopPtr;
2188     } else if (type == T_OBJECT) {
2189       // off heap access to an oop doesn't make any sense. Has to be on
2190       // heap.
2191       return Type::OopPtr;
2192     }
2193     // Otherwise, it might either be oop+off or null+addr.
2194     return Type::AnyPtr;
2195   } else {
2196     // No information:
2197     return Type::AnyPtr;
2198   }
2199 }
2200 
2201 Node* LibraryCallKit::make_unsafe_address(Node*& base, Node* offset, BasicType type, bool can_cast) {
2202   Node* uncasted_base = base;
2203   int kind = classify_unsafe_addr(uncasted_base, offset, type);
2204   if (kind == Type::RawPtr) {
2205     return basic_plus_adr(top(), uncasted_base, offset);
2206   } else if (kind == Type::AnyPtr) {
2207     assert(base == uncasted_base, "unexpected base change");
2208     if (can_cast) {
2209       if (!_gvn.type(base)->speculative_maybe_null() &&
2210           !too_many_traps(Deoptimization::Reason_speculate_null_check)) {
2211         // According to profiling, this access is always on
2212         // heap. Casting the base to not null and thus avoiding membars
2213         // around the access should allow better optimizations
2214         Node* null_ctl = top();
2215         base = null_check_oop(base, &null_ctl, true, true, true);
2216         assert(null_ctl->is_top(), "no null control here");
2217         return basic_plus_adr(base, offset);
2218       } else if (_gvn.type(base)->speculative_always_null() &&
2219                  !too_many_traps(Deoptimization::Reason_speculate_null_assert)) {
2220         // According to profiling, this access is always off
2221         // heap.
2222         base = null_assert(base);
2223         Node* raw_base = _gvn.transform(new CastX2PNode(offset));
2224         offset = MakeConX(0);
2225         return basic_plus_adr(top(), raw_base, offset);
2226       }
2227     }
2228     // We don't know if it's an on heap or off heap access. Fall back
2229     // to raw memory access.
2230     Node* raw = _gvn.transform(new CheckCastPPNode(control(), base, TypeRawPtr::BOTTOM));
2231     return basic_plus_adr(top(), raw, offset);
2232   } else {
2233     assert(base == uncasted_base, "unexpected base change");
2234     // We know it's an on heap access so base can't be null
2235     if (TypePtr::NULL_PTR->higher_equal(_gvn.type(base))) {
2236       base = must_be_not_null(base, true);
2237     }
2238     return basic_plus_adr(base, offset);
2239   }
2240 }
2241 
2242 //--------------------------inline_number_methods-----------------------------
2243 // inline int     Integer.numberOfLeadingZeros(int)
2244 // inline int        Long.numberOfLeadingZeros(long)
2245 //
2246 // inline int     Integer.numberOfTrailingZeros(int)
2247 // inline int        Long.numberOfTrailingZeros(long)
2248 //
2249 // inline int     Integer.bitCount(int)
2250 // inline int        Long.bitCount(long)
2251 //
2252 // inline char  Character.reverseBytes(char)
2253 // inline short     Short.reverseBytes(short)
2254 // inline int     Integer.reverseBytes(int)
2255 // inline long       Long.reverseBytes(long)
2256 bool LibraryCallKit::inline_number_methods(vmIntrinsics::ID id) {
2257   Node* arg = argument(0);
2258   Node* n = nullptr;
2259   switch (id) {
2260   case vmIntrinsics::_numberOfLeadingZeros_i:   n = new CountLeadingZerosINode( arg); break;
2261   case vmIntrinsics::_numberOfLeadingZeros_l:   n = new CountLeadingZerosLNode( arg); break;
2262   case vmIntrinsics::_numberOfTrailingZeros_i:  n = new CountTrailingZerosINode(arg); break;
2263   case vmIntrinsics::_numberOfTrailingZeros_l:  n = new CountTrailingZerosLNode(arg); break;
2264   case vmIntrinsics::_bitCount_i:               n = new PopCountINode(          arg); break;
2265   case vmIntrinsics::_bitCount_l:               n = new PopCountLNode(          arg); break;
2266   case vmIntrinsics::_reverseBytes_c:           n = new ReverseBytesUSNode(     arg); break;
2267   case vmIntrinsics::_reverseBytes_s:           n = new ReverseBytesSNode(      arg); break;
2268   case vmIntrinsics::_reverseBytes_i:           n = new ReverseBytesINode(      arg); break;
2269   case vmIntrinsics::_reverseBytes_l:           n = new ReverseBytesLNode(      arg); break;
2270   case vmIntrinsics::_reverse_i:                n = new ReverseINode(           arg); break;
2271   case vmIntrinsics::_reverse_l:                n = new ReverseLNode(           arg); break;
2272   default:  fatal_unexpected_iid(id);  break;
2273   }
2274   set_result(_gvn.transform(n));
2275   return true;
2276 }
2277 
2278 //--------------------------inline_bitshuffle_methods-----------------------------
2279 // inline int Integer.compress(int, int)
2280 // inline int Integer.expand(int, int)
2281 // inline long Long.compress(long, long)
2282 // inline long Long.expand(long, long)
2283 bool LibraryCallKit::inline_bitshuffle_methods(vmIntrinsics::ID id) {
2284   Node* n = nullptr;
2285   switch (id) {
2286     case vmIntrinsics::_compress_i:  n = new CompressBitsNode(argument(0), argument(1), TypeInt::INT); break;
2287     case vmIntrinsics::_expand_i:    n = new ExpandBitsNode(argument(0),  argument(1), TypeInt::INT); break;
2288     case vmIntrinsics::_compress_l:  n = new CompressBitsNode(argument(0), argument(2), TypeLong::LONG); break;
2289     case vmIntrinsics::_expand_l:    n = new ExpandBitsNode(argument(0), argument(2), TypeLong::LONG); break;
2290     default:  fatal_unexpected_iid(id);  break;
2291   }
2292   set_result(_gvn.transform(n));
2293   return true;
2294 }
2295 
2296 //--------------------------inline_number_methods-----------------------------
2297 // inline int Integer.compareUnsigned(int, int)
2298 // inline int    Long.compareUnsigned(long, long)
2299 bool LibraryCallKit::inline_compare_unsigned(vmIntrinsics::ID id) {
2300   Node* arg1 = argument(0);
2301   Node* arg2 = (id == vmIntrinsics::_compareUnsigned_l) ? argument(2) : argument(1);
2302   Node* n = nullptr;
2303   switch (id) {
2304     case vmIntrinsics::_compareUnsigned_i:   n = new CmpU3Node(arg1, arg2);  break;
2305     case vmIntrinsics::_compareUnsigned_l:   n = new CmpUL3Node(arg1, arg2); break;
2306     default:  fatal_unexpected_iid(id);  break;
2307   }
2308   set_result(_gvn.transform(n));
2309   return true;
2310 }
2311 
2312 //--------------------------inline_unsigned_divmod_methods-----------------------------
2313 // inline int Integer.divideUnsigned(int, int)
2314 // inline int Integer.remainderUnsigned(int, int)
2315 // inline long Long.divideUnsigned(long, long)
2316 // inline long Long.remainderUnsigned(long, long)
2317 bool LibraryCallKit::inline_divmod_methods(vmIntrinsics::ID id) {
2318   Node* n = nullptr;
2319   switch (id) {
2320     case vmIntrinsics::_divideUnsigned_i: {
2321       zero_check_int(argument(1));
2322       // Compile-time detect of null-exception
2323       if (stopped()) {
2324         return true; // keep the graph constructed so far
2325       }
2326       n = new UDivINode(control(), argument(0), argument(1));
2327       break;
2328     }
2329     case vmIntrinsics::_divideUnsigned_l: {
2330       zero_check_long(argument(2));
2331       // Compile-time detect of null-exception
2332       if (stopped()) {
2333         return true; // keep the graph constructed so far
2334       }
2335       n = new UDivLNode(control(), argument(0), argument(2));
2336       break;
2337     }
2338     case vmIntrinsics::_remainderUnsigned_i: {
2339       zero_check_int(argument(1));
2340       // Compile-time detect of null-exception
2341       if (stopped()) {
2342         return true; // keep the graph constructed so far
2343       }
2344       n = new UModINode(control(), argument(0), argument(1));
2345       break;
2346     }
2347     case vmIntrinsics::_remainderUnsigned_l: {
2348       zero_check_long(argument(2));
2349       // Compile-time detect of null-exception
2350       if (stopped()) {
2351         return true; // keep the graph constructed so far
2352       }
2353       n = new UModLNode(control(), argument(0), argument(2));
2354       break;
2355     }
2356     default:  fatal_unexpected_iid(id);  break;
2357   }
2358   set_result(_gvn.transform(n));
2359   return true;
2360 }
2361 
2362 //----------------------------inline_unsafe_access----------------------------
2363 
2364 const TypeOopPtr* LibraryCallKit::sharpen_unsafe_type(Compile::AliasType* alias_type, const TypePtr *adr_type) {
2365   // Attempt to infer a sharper value type from the offset and base type.
2366   ciKlass* sharpened_klass = nullptr;
2367   bool null_free = false;
2368 
2369   // See if it is an instance field, with an object type.
2370   if (alias_type->field() != nullptr) {
2371     if (alias_type->field()->type()->is_klass()) {
2372       sharpened_klass = alias_type->field()->type()->as_klass();
2373       null_free = alias_type->field()->is_null_free();
2374     }
2375   }
2376 
2377   const TypeOopPtr* result = nullptr;
2378   // See if it is a narrow oop array.
2379   if (adr_type->isa_aryptr()) {
2380     if (adr_type->offset() >= refArrayOopDesc::base_offset_in_bytes()) {
2381       const TypeOopPtr* elem_type = adr_type->is_aryptr()->elem()->make_oopptr();
2382       null_free = adr_type->is_aryptr()->is_null_free();
2383       if (elem_type != nullptr && elem_type->is_loaded()) {
2384         // Sharpen the value type.
2385         result = elem_type;
2386       }
2387     }
2388   }
2389 
2390   // The sharpened class might be unloaded if there is no class loader
2391   // contraint in place.
2392   if (result == nullptr && sharpened_klass != nullptr && sharpened_klass->is_loaded()) {
2393     // Sharpen the value type.
2394     result = TypeOopPtr::make_from_klass(sharpened_klass);
2395     if (null_free) {
2396       result = result->join_speculative(TypePtr::NOTNULL)->is_oopptr();
2397     }
2398   }
2399   if (result != nullptr) {
2400 #ifndef PRODUCT
2401     if (C->print_intrinsics() || C->print_inlining()) {
2402       tty->print("  from base type:  ");  adr_type->dump(); tty->cr();
2403       tty->print("  sharpened value: ");  result->dump();    tty->cr();
2404     }
2405 #endif
2406   }
2407   return result;
2408 }
2409 
2410 DecoratorSet LibraryCallKit::mo_decorator_for_access_kind(AccessKind kind) {
2411   switch (kind) {
2412       case Relaxed:
2413         return MO_UNORDERED;
2414       case Opaque:
2415         return MO_RELAXED;
2416       case Acquire:
2417         return MO_ACQUIRE;
2418       case Release:
2419         return MO_RELEASE;
2420       case Volatile:
2421         return MO_SEQ_CST;
2422       default:
2423         ShouldNotReachHere();
2424         return 0;
2425   }
2426 }
2427 
2428 LibraryCallKit::SavedState::SavedState(LibraryCallKit* kit) :
2429   _kit(kit),
2430   _sp(kit->sp()),
2431   _jvms(kit->jvms()),
2432   _map(kit->clone_map()),
2433   _discarded(false)
2434 {
2435   for (DUIterator_Fast imax, i = kit->control()->fast_outs(imax); i < imax; i++) {
2436     Node* out = kit->control()->fast_out(i);
2437     if (out->is_CFG()) {
2438       _ctrl_succ.push(out);
2439     }
2440   }
2441 }
2442 
2443 LibraryCallKit::SavedState::~SavedState() {
2444   if (_discarded) {
2445     _kit->destruct_map_clone(_map);
2446     return;
2447   }
2448   _kit->jvms()->set_map(_map);
2449   _kit->jvms()->set_sp(_sp);
2450   _map->set_jvms(_kit->jvms());
2451   _kit->set_map(_map);
2452   _kit->set_sp(_sp);
2453   for (DUIterator_Fast imax, i = _kit->control()->fast_outs(imax); i < imax; i++) {
2454     Node* out = _kit->control()->fast_out(i);
2455     if (out->is_CFG() && out->in(0) == _kit->control() && out != _kit->map() && !_ctrl_succ.member(out)) {
2456       _kit->_gvn.hash_delete(out);
2457       out->set_req(0, _kit->C->top());
2458       _kit->C->record_for_igvn(out);
2459       --i; --imax;
2460       _kit->_gvn.hash_find_insert(out);
2461     }
2462   }
2463 }
2464 
2465 void LibraryCallKit::SavedState::discard() {
2466   _discarded = true;
2467 }
2468 
2469 bool LibraryCallKit::inline_unsafe_access(bool is_store, const BasicType type, const AccessKind kind, const bool unaligned) {
2470   if (callee()->is_static())  return false;  // caller must have the capability!
2471   DecoratorSet decorators = C2_UNSAFE_ACCESS;
2472   guarantee(!is_store || kind != Acquire, "Acquire accesses can be produced only for loads");
2473   guarantee( is_store || kind != Release, "Release accesses can be produced only for stores");
2474   assert(type != T_OBJECT || !unaligned, "unaligned access not supported with object type");
2475 
2476   if (is_reference_type(type)) {
2477     decorators |= ON_UNKNOWN_OOP_REF;
2478   }
2479 
2480   if (unaligned) {
2481     decorators |= C2_UNALIGNED;
2482   }
2483 
2484 #ifndef PRODUCT
2485   {
2486     ResourceMark rm;
2487     // Check the signatures.
2488     ciSignature* sig = callee()->signature();
2489 #ifdef ASSERT
2490     if (!is_store) {
2491       // Object getReference(Object base, int/long offset), etc.
2492       BasicType rtype = sig->return_type()->basic_type();
2493       assert(rtype == type, "getter must return the expected value");
2494       assert(sig->count() == 2, "oop getter has 2 arguments");
2495       assert(sig->type_at(0)->basic_type() == T_OBJECT, "getter base is object");
2496       assert(sig->type_at(1)->basic_type() == T_LONG, "getter offset is correct");
2497     } else {
2498       // void putReference(Object base, int/long offset, Object x), etc.
2499       assert(sig->return_type()->basic_type() == T_VOID, "putter must not return a value");
2500       assert(sig->count() == 3, "oop putter has 3 arguments");
2501       assert(sig->type_at(0)->basic_type() == T_OBJECT, "putter base is object");
2502       assert(sig->type_at(1)->basic_type() == T_LONG, "putter offset is correct");
2503       BasicType vtype = sig->type_at(sig->count()-1)->basic_type();
2504       assert(vtype == type, "putter must accept the expected value");
2505     }
2506 #endif // ASSERT
2507  }
2508 #endif //PRODUCT
2509 
2510   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
2511 
2512   Node* receiver = argument(0);  // type: oop
2513 
2514   // Build address expression.
2515   Node* heap_base_oop = top();
2516 
2517   // The base is either a Java object or a value produced by Unsafe.staticFieldBase
2518   Node* base = argument(1);  // type: oop
2519   // The offset is a value produced by Unsafe.staticFieldOffset or Unsafe.objectFieldOffset
2520   Node* offset = argument(2);  // type: long
2521   // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
2522   // to be plain byte offsets, which are also the same as those accepted
2523   // by oopDesc::field_addr.
2524   assert(Unsafe_field_offset_to_byte_offset(11) == 11,
2525          "fieldOffset must be byte-scaled");
2526 
2527   if (base->is_InlineType()) {
2528     assert(!is_store, "InlineTypeNodes are non-larval value objects");
2529     InlineTypeNode* vt = base->as_InlineType();
2530     if (offset->is_Con()) {
2531       long off = find_long_con(offset, 0);
2532       ciInlineKlass* vk = vt->type()->inline_klass();
2533       if ((long)(int)off != off || !vk->contains_field_offset(off)) {
2534         return false;
2535       }
2536 
2537       ciField* field = vk->get_non_flat_field_by_offset(off);
2538       if (field != nullptr) {
2539         BasicType bt = type2field[field->type()->basic_type()];
2540         if (bt == T_ARRAY || bt == T_NARROWOOP) {
2541           bt = T_OBJECT;
2542         }
2543         if (bt == type && !field->is_flat()) {
2544           Node* value = vt->field_value_by_offset(off, false);
2545           const Type* value_type = _gvn.type(value);
2546           if (value->is_InlineType()) {
2547             value = value->as_InlineType()->adjust_scalarization_depth(this);
2548           } else if (value_type->is_inlinetypeptr()) {
2549             value = InlineTypeNode::make_from_oop(this, value, value_type->inline_klass());
2550           }
2551           set_result(value);
2552           return true;
2553         }
2554       }
2555     }
2556     {
2557       // Re-execute the unsafe access if allocation triggers deoptimization.
2558       PreserveReexecuteState preexecs(this);
2559       jvms()->set_should_reexecute(true);
2560       vt = vt->buffer(this);
2561     }
2562     base = vt->get_oop();
2563   }
2564 
2565   // 32-bit machines ignore the high half!
2566   offset = ConvL2X(offset);
2567 
2568   // Save state and restore on bailout
2569   SavedState old_state(this);
2570 
2571   Node* adr = make_unsafe_address(base, offset, type, kind == Relaxed);
2572   assert(!stopped(), "Inlining of unsafe access failed: address construction stopped unexpectedly");
2573 
2574   if (_gvn.type(base->uncast())->isa_ptr() == TypePtr::NULL_PTR) {
2575     if (type != T_OBJECT) {
2576       decorators |= IN_NATIVE; // off-heap primitive access
2577     } else {
2578       return false; // off-heap oop accesses are not supported
2579     }
2580   } else {
2581     heap_base_oop = base; // on-heap or mixed access
2582   }
2583 
2584   // Can base be null? Otherwise, always on-heap access.
2585   bool can_access_non_heap = TypePtr::NULL_PTR->higher_equal(_gvn.type(base));
2586 
2587   if (!can_access_non_heap) {
2588     decorators |= IN_HEAP;
2589   }
2590 
2591   Node* val = is_store ? argument(4) : nullptr;
2592 
2593   const TypePtr* adr_type = _gvn.type(adr)->isa_ptr();
2594   if (adr_type == TypePtr::NULL_PTR) {
2595     return false; // off-heap access with zero address
2596   }
2597 
2598   // Try to categorize the address.
2599   Compile::AliasType* alias_type = C->alias_type(adr_type);
2600   assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
2601 
2602   if (alias_type->adr_type() == TypeInstPtr::KLASS ||
2603       alias_type->adr_type() == TypeAryPtr::RANGE) {
2604     return false; // not supported
2605   }
2606 
2607   bool mismatched = false;
2608   BasicType bt = T_ILLEGAL;
2609   ciField* field = nullptr;
2610   if (adr_type->isa_instptr()) {
2611     const TypeInstPtr* instptr = adr_type->is_instptr();
2612     ciInstanceKlass* k = instptr->instance_klass();
2613     int off = instptr->offset();
2614     if (instptr->const_oop() != nullptr &&
2615         k == ciEnv::current()->Class_klass() &&
2616         instptr->offset() >= (k->size_helper() * wordSize)) {
2617       k = instptr->const_oop()->as_instance()->java_lang_Class_klass()->as_instance_klass();
2618       field = k->get_field_by_offset(off, true);
2619     } else {
2620       field = k->get_non_flat_field_by_offset(off);
2621     }
2622     if (field != nullptr) {
2623       bt = type2field[field->type()->basic_type()];
2624     }
2625     if (bt != alias_type->basic_type()) {
2626       // Type mismatch. Is it an access to a nested flat field?
2627       field = k->get_field_by_offset(off, false);
2628       if (field != nullptr) {
2629         bt = type2field[field->type()->basic_type()];
2630       }
2631     }
2632     assert(bt == alias_type->basic_type(), "should match");
2633   } else {
2634     bt = alias_type->basic_type();
2635   }
2636 
2637   if (bt != T_ILLEGAL) {
2638     assert(alias_type->adr_type()->is_oopptr(), "should be on-heap access");
2639     if (bt == T_BYTE && adr_type->isa_aryptr()) {
2640       // Alias type doesn't differentiate between byte[] and boolean[]).
2641       // Use address type to get the element type.
2642       bt = adr_type->is_aryptr()->elem()->array_element_basic_type();
2643     }
2644     if (is_reference_type(bt, true)) {
2645       // accessing an array field with getReference is not a mismatch
2646       bt = T_OBJECT;
2647     }
2648     if ((bt == T_OBJECT) != (type == T_OBJECT)) {
2649       // Don't intrinsify mismatched object accesses
2650       return false;
2651     }
2652     mismatched = (bt != type);
2653   } else if (alias_type->adr_type()->isa_oopptr()) {
2654     mismatched = true; // conservatively mark all "wide" on-heap accesses as mismatched
2655   }
2656 
2657   old_state.discard();
2658   assert(!mismatched || alias_type->adr_type()->is_oopptr(), "off-heap access can't be mismatched");
2659 
2660   if (mismatched) {
2661     decorators |= C2_MISMATCHED;
2662   }
2663 
2664   // First guess at the value type.
2665   const Type *value_type = Type::get_const_basic_type(type);
2666 
2667   // Figure out the memory ordering.
2668   decorators |= mo_decorator_for_access_kind(kind);
2669 
2670   if (!is_store) {
2671     if (type == T_OBJECT) {
2672       const TypeOopPtr* tjp = sharpen_unsafe_type(alias_type, adr_type);
2673       if (tjp != nullptr) {
2674         value_type = tjp;
2675       }
2676     }
2677   }
2678 
2679   receiver = null_check(receiver);
2680   if (stopped()) {
2681     return true;
2682   }
2683   // Heap pointers get a null-check from the interpreter,
2684   // as a courtesy.  However, this is not guaranteed by Unsafe,
2685   // and it is not possible to fully distinguish unintended nulls
2686   // from intended ones in this API.
2687 
2688   if (!is_store) {
2689     Node* p = nullptr;
2690     // Try to constant fold a load from a constant field
2691 
2692     if (heap_base_oop != top() && field != nullptr && field->is_constant() && !field->is_flat() && !mismatched) {
2693       // final or stable field
2694       p = make_constant_from_field(field, heap_base_oop);
2695     }
2696 
2697     if (p == nullptr) { // Could not constant fold the load
2698       p = access_load_at(heap_base_oop, adr, adr_type, value_type, type, decorators);
2699       const TypeOopPtr* ptr = value_type->make_oopptr();
2700       if (ptr != nullptr && ptr->is_inlinetypeptr()) {
2701         // Load a non-flattened inline type from memory
2702         p = InlineTypeNode::make_from_oop(this, p, ptr->inline_klass());
2703       }
2704       // Normalize the value returned by getBoolean in the following cases
2705       if (type == T_BOOLEAN &&
2706           (mismatched ||
2707            heap_base_oop == top() ||                  // - heap_base_oop is null or
2708            (can_access_non_heap && field == nullptr)) // - heap_base_oop is potentially null
2709                                                       //   and the unsafe access is made to large offset
2710                                                       //   (i.e., larger than the maximum offset necessary for any
2711                                                       //   field access)
2712             ) {
2713           IdealKit ideal = IdealKit(this);
2714 #define __ ideal.
2715           IdealVariable normalized_result(ideal);
2716           __ declarations_done();
2717           __ set(normalized_result, p);
2718           __ if_then(p, BoolTest::ne, ideal.ConI(0));
2719           __ set(normalized_result, ideal.ConI(1));
2720           ideal.end_if();
2721           final_sync(ideal);
2722           p = __ value(normalized_result);
2723 #undef __
2724       }
2725     }
2726     if (type == T_ADDRESS) {
2727       p = gvn().transform(new CastP2XNode(nullptr, p));
2728       p = ConvX2UL(p);
2729     }
2730     // The load node has the control of the preceding MemBarCPUOrder.  All
2731     // following nodes will have the control of the MemBarCPUOrder inserted at
2732     // the end of this method.  So, pushing the load onto the stack at a later
2733     // point is fine.
2734     set_result(p);
2735   } else {
2736     if (bt == T_ADDRESS) {
2737       // Repackage the long as a pointer.
2738       val = ConvL2X(val);
2739       val = gvn().transform(new CastX2PNode(val));
2740     }
2741     access_store_at(heap_base_oop, adr, adr_type, val, value_type, type, decorators);
2742   }
2743 
2744   return true;
2745 }
2746 
2747 bool LibraryCallKit::inline_unsafe_flat_access(bool is_store, AccessKind kind) {
2748 #ifdef ASSERT
2749   {
2750     ResourceMark rm;
2751     // Check the signatures.
2752     ciSignature* sig = callee()->signature();
2753     assert(sig->type_at(0)->basic_type() == T_OBJECT, "base should be object, but is %s", type2name(sig->type_at(0)->basic_type()));
2754     assert(sig->type_at(1)->basic_type() == T_LONG, "offset should be long, but is %s", type2name(sig->type_at(1)->basic_type()));
2755     assert(sig->type_at(2)->basic_type() == T_INT, "layout kind should be int, but is %s", type2name(sig->type_at(3)->basic_type()));
2756     assert(sig->type_at(3)->basic_type() == T_OBJECT, "value klass should be object, but is %s", type2name(sig->type_at(4)->basic_type()));
2757     if (is_store) {
2758       assert(sig->return_type()->basic_type() == T_VOID, "putter must not return a value, but returns %s", type2name(sig->return_type()->basic_type()));
2759       assert(sig->count() == 5, "flat putter should have 5 arguments, but has %d", sig->count());
2760       assert(sig->type_at(4)->basic_type() == T_OBJECT, "put value should be object, but is %s", type2name(sig->type_at(5)->basic_type()));
2761     } else {
2762       assert(sig->return_type()->basic_type() == T_OBJECT, "getter must return an object, but returns %s", type2name(sig->return_type()->basic_type()));
2763       assert(sig->count() == 4, "flat getter should have 4 arguments, but has %d", sig->count());
2764     }
2765  }
2766 #endif // ASSERT
2767 
2768   assert(kind == Relaxed, "Only plain accesses for now");
2769   if (callee()->is_static()) {
2770     // caller must have the capability!
2771     return false;
2772   }
2773   C->set_has_unsafe_access(true);
2774 
2775   const TypeInstPtr* value_klass_node = _gvn.type(argument(5))->isa_instptr();
2776   if (value_klass_node == nullptr || value_klass_node->const_oop() == nullptr) {
2777     // parameter valueType is not a constant
2778     return false;
2779   }
2780   ciType* mirror_type = value_klass_node->const_oop()->as_instance()->java_mirror_type();
2781   if (!mirror_type->is_inlinetype()) {
2782     // Dead code
2783     return false;
2784   }
2785   ciInlineKlass* value_klass = mirror_type->as_inline_klass();
2786 
2787   const TypeInt* layout_type = _gvn.type(argument(4))->isa_int();
2788   if (layout_type == nullptr || !layout_type->is_con()) {
2789     // parameter layoutKind is not a constant
2790     return false;
2791   }
2792   assert(layout_type->get_con() >= static_cast<int>(LayoutKind::REFERENCE) &&
2793          layout_type->get_con() < static_cast<int>(LayoutKind::UNKNOWN),
2794          "invalid layoutKind %d", layout_type->get_con());
2795   LayoutKind layout = static_cast<LayoutKind>(layout_type->get_con());
2796   assert(layout == LayoutKind::REFERENCE || layout == LayoutKind::NULL_FREE_NON_ATOMIC_FLAT ||
2797          layout == LayoutKind::NULL_FREE_ATOMIC_FLAT || layout == LayoutKind::NULLABLE_ATOMIC_FLAT,
2798          "unexpected layoutKind %d", layout_type->get_con());
2799 
2800   null_check(argument(0));
2801   if (stopped()) {
2802     return true;
2803   }
2804 
2805   Node* base = must_be_not_null(argument(1), true);
2806   Node* offset = argument(2);
2807   const Type* base_type = _gvn.type(base);
2808 
2809   Node* ptr;
2810   bool immutable_memory = false;
2811   DecoratorSet decorators = C2_UNSAFE_ACCESS | IN_HEAP | MO_UNORDERED;
2812   if (base_type->isa_instptr()) {
2813     const TypeLong* offset_type = _gvn.type(offset)->isa_long();
2814     if (offset_type == nullptr || !offset_type->is_con()) {
2815       // Offset into a non-array should be a constant
2816       decorators |= C2_MISMATCHED;
2817     } else {
2818       int offset_con = checked_cast<int>(offset_type->get_con());
2819       ciInstanceKlass* base_klass = base_type->is_instptr()->instance_klass();
2820       ciField* field = base_klass->get_non_flat_field_by_offset(offset_con);
2821       if (field == nullptr) {
2822         assert(!base_klass->is_final(), "non-existence field at offset %d of class %s", offset_con, base_klass->name()->as_utf8());
2823         decorators |= C2_MISMATCHED;
2824       } else {
2825         assert(field->type() == value_klass, "field at offset %d of %s is of type %s, but valueType is %s",
2826                offset_con, base_klass->name()->as_utf8(), field->type()->name(), value_klass->name()->as_utf8());
2827         immutable_memory = field->is_strict() && field->is_final();
2828 
2829         if (base->is_InlineType()) {
2830           assert(!is_store, "Cannot store into a non-larval value object");
2831           set_result(base->as_InlineType()->field_value_by_offset(offset_con, false));
2832           return true;
2833         }
2834       }
2835     }
2836 
2837     if (base->is_InlineType()) {
2838       assert(!is_store, "Cannot store into a non-larval value object");
2839       base = base->as_InlineType()->buffer(this, true);
2840     }
2841     ptr = basic_plus_adr(base, ConvL2X(offset));
2842   } else if (base_type->isa_aryptr()) {
2843     decorators |= IS_ARRAY;
2844     if (layout == LayoutKind::REFERENCE) {
2845       if (!base_type->is_aryptr()->is_not_flat()) {
2846         const TypeAryPtr* array_type = base_type->is_aryptr()->cast_to_not_flat();
2847         Node* new_base = _gvn.transform(new CastPPNode(control(), base, array_type, ConstraintCastNode::DependencyType::NonFloatingNarrowing));
2848         replace_in_map(base, new_base);
2849         base = new_base;
2850       }
2851       ptr = basic_plus_adr(base, ConvL2X(offset));
2852     } else {
2853       if (UseArrayFlattening) {
2854         // Flat array must have an exact type
2855         bool is_null_free = !LayoutKindHelper::is_nullable_flat(layout);
2856         bool is_atomic = LayoutKindHelper::is_atomic_flat(layout);
2857         Node* new_base = cast_to_flat_array_exact(base, value_klass, is_null_free, is_atomic);
2858         replace_in_map(base, new_base);
2859         base = new_base;
2860         ptr = basic_plus_adr(base, ConvL2X(offset));
2861         const TypeAryPtr* ptr_type = _gvn.type(ptr)->is_aryptr();
2862         if (ptr_type->field_offset().get() != 0) {
2863           ptr = _gvn.transform(new CastPPNode(control(), ptr, ptr_type->with_field_offset(0), ConstraintCastNode::DependencyType::NonFloatingNarrowing));
2864         }
2865       } else {
2866         uncommon_trap(Deoptimization::Reason_intrinsic,
2867                       Deoptimization::Action_none);
2868         return true;
2869       }
2870     }
2871   } else {
2872     decorators |= C2_MISMATCHED;
2873     ptr = basic_plus_adr(base, ConvL2X(offset));
2874   }
2875 
2876   if (is_store) {
2877     Node* value = argument(6);
2878     const Type* value_type = _gvn.type(value);
2879     if (!value_type->is_inlinetypeptr()) {
2880       value_type = Type::get_const_type(value_klass)->filter_speculative(value_type);
2881       Node* new_value = _gvn.transform(new CastPPNode(control(), value, value_type, ConstraintCastNode::DependencyType::NonFloatingNarrowing));
2882       new_value = InlineTypeNode::make_from_oop(this, new_value, value_klass);
2883       replace_in_map(value, new_value);
2884       value = new_value;
2885     }
2886 
2887     assert(value_type->inline_klass() == value_klass, "value is of type %s while valueType is %s", value_type->inline_klass()->name()->as_utf8(), value_klass->name()->as_utf8());
2888     if (layout == LayoutKind::REFERENCE) {
2889       const TypePtr* ptr_type = (decorators & C2_MISMATCHED) != 0 ? TypeRawPtr::BOTTOM : _gvn.type(ptr)->is_ptr();
2890       access_store_at(base, ptr, ptr_type, value, value_type, T_OBJECT, decorators);
2891     } else {
2892       bool atomic = LayoutKindHelper::is_atomic_flat(layout);
2893       bool null_free = !LayoutKindHelper::is_nullable_flat(layout);
2894       value->as_InlineType()->store_flat(this, base, ptr, atomic, immutable_memory, null_free, decorators);
2895     }
2896 
2897     return true;
2898   } else {
2899     decorators |= (C2_CONTROL_DEPENDENT_LOAD | C2_UNKNOWN_CONTROL_LOAD);
2900     InlineTypeNode* result;
2901     if (layout == LayoutKind::REFERENCE) {
2902       const TypePtr* ptr_type = (decorators & C2_MISMATCHED) != 0 ? TypeRawPtr::BOTTOM : _gvn.type(ptr)->is_ptr();
2903       Node* oop = access_load_at(base, ptr, ptr_type, Type::get_const_type(value_klass), T_OBJECT, decorators);
2904       result = InlineTypeNode::make_from_oop(this, oop, value_klass);
2905     } else {
2906       bool atomic = LayoutKindHelper::is_atomic_flat(layout);
2907       bool null_free = !LayoutKindHelper::is_nullable_flat(layout);
2908       result = InlineTypeNode::make_from_flat(this, value_klass, base, ptr, atomic, immutable_memory, null_free, decorators);
2909     }
2910 
2911     set_result(result);
2912     return true;
2913   }
2914 }
2915 
2916 //----------------------------inline_unsafe_load_store----------------------------
2917 // This method serves a couple of different customers (depending on LoadStoreKind):
2918 //
2919 // LS_cmp_swap:
2920 //
2921 //   boolean compareAndSetReference(Object o, long offset, Object expected, Object x);
2922 //   boolean compareAndSetInt(   Object o, long offset, int    expected, int    x);
2923 //   boolean compareAndSetLong(  Object o, long offset, long   expected, long   x);
2924 //
2925 // LS_cmp_swap_weak:
2926 //
2927 //   boolean weakCompareAndSetReference(       Object o, long offset, Object expected, Object x);
2928 //   boolean weakCompareAndSetReferencePlain(  Object o, long offset, Object expected, Object x);
2929 //   boolean weakCompareAndSetReferenceAcquire(Object o, long offset, Object expected, Object x);
2930 //   boolean weakCompareAndSetReferenceRelease(Object o, long offset, Object expected, Object x);
2931 //
2932 //   boolean weakCompareAndSetInt(          Object o, long offset, int    expected, int    x);
2933 //   boolean weakCompareAndSetIntPlain(     Object o, long offset, int    expected, int    x);
2934 //   boolean weakCompareAndSetIntAcquire(   Object o, long offset, int    expected, int    x);
2935 //   boolean weakCompareAndSetIntRelease(   Object o, long offset, int    expected, int    x);
2936 //
2937 //   boolean weakCompareAndSetLong(         Object o, long offset, long   expected, long   x);
2938 //   boolean weakCompareAndSetLongPlain(    Object o, long offset, long   expected, long   x);
2939 //   boolean weakCompareAndSetLongAcquire(  Object o, long offset, long   expected, long   x);
2940 //   boolean weakCompareAndSetLongRelease(  Object o, long offset, long   expected, long   x);
2941 //
2942 // LS_cmp_exchange:
2943 //
2944 //   Object compareAndExchangeReferenceVolatile(Object o, long offset, Object expected, Object x);
2945 //   Object compareAndExchangeReferenceAcquire( Object o, long offset, Object expected, Object x);
2946 //   Object compareAndExchangeReferenceRelease( Object o, long offset, Object expected, Object x);
2947 //
2948 //   Object compareAndExchangeIntVolatile(   Object o, long offset, Object expected, Object x);
2949 //   Object compareAndExchangeIntAcquire(    Object o, long offset, Object expected, Object x);
2950 //   Object compareAndExchangeIntRelease(    Object o, long offset, Object expected, Object x);
2951 //
2952 //   Object compareAndExchangeLongVolatile(  Object o, long offset, Object expected, Object x);
2953 //   Object compareAndExchangeLongAcquire(   Object o, long offset, Object expected, Object x);
2954 //   Object compareAndExchangeLongRelease(   Object o, long offset, Object expected, Object x);
2955 //
2956 // LS_get_add:
2957 //
2958 //   int  getAndAddInt( Object o, long offset, int  delta)
2959 //   long getAndAddLong(Object o, long offset, long delta)
2960 //
2961 // LS_get_set:
2962 //
2963 //   int    getAndSet(Object o, long offset, int    newValue)
2964 //   long   getAndSet(Object o, long offset, long   newValue)
2965 //   Object getAndSet(Object o, long offset, Object newValue)
2966 //
2967 bool LibraryCallKit::inline_unsafe_load_store(const BasicType type, const LoadStoreKind kind, const AccessKind access_kind) {
2968   // This basic scheme here is the same as inline_unsafe_access, but
2969   // differs in enough details that combining them would make the code
2970   // overly confusing.  (This is a true fact! I originally combined
2971   // them, but even I was confused by it!) As much code/comments as
2972   // possible are retained from inline_unsafe_access though to make
2973   // the correspondences clearer. - dl
2974 
2975   if (callee()->is_static())  return false;  // caller must have the capability!
2976 
2977   DecoratorSet decorators = C2_UNSAFE_ACCESS;
2978   decorators |= mo_decorator_for_access_kind(access_kind);
2979 
2980 #ifndef PRODUCT
2981   BasicType rtype;
2982   {
2983     ResourceMark rm;
2984     // Check the signatures.
2985     ciSignature* sig = callee()->signature();
2986     rtype = sig->return_type()->basic_type();
2987     switch(kind) {
2988       case LS_get_add:
2989       case LS_get_set: {
2990       // Check the signatures.
2991 #ifdef ASSERT
2992       assert(rtype == type, "get and set must return the expected type");
2993       assert(sig->count() == 3, "get and set has 3 arguments");
2994       assert(sig->type_at(0)->basic_type() == T_OBJECT, "get and set base is object");
2995       assert(sig->type_at(1)->basic_type() == T_LONG, "get and set offset is long");
2996       assert(sig->type_at(2)->basic_type() == type, "get and set must take expected type as new value/delta");
2997       assert(access_kind == Volatile, "mo is not passed to intrinsic nodes in current implementation");
2998 #endif // ASSERT
2999         break;
3000       }
3001       case LS_cmp_swap:
3002       case LS_cmp_swap_weak: {
3003       // Check the signatures.
3004 #ifdef ASSERT
3005       assert(rtype == T_BOOLEAN, "CAS must return boolean");
3006       assert(sig->count() == 4, "CAS has 4 arguments");
3007       assert(sig->type_at(0)->basic_type() == T_OBJECT, "CAS base is object");
3008       assert(sig->type_at(1)->basic_type() == T_LONG, "CAS offset is long");
3009 #endif // ASSERT
3010         break;
3011       }
3012       case LS_cmp_exchange: {
3013       // Check the signatures.
3014 #ifdef ASSERT
3015       assert(rtype == type, "CAS must return the expected type");
3016       assert(sig->count() == 4, "CAS has 4 arguments");
3017       assert(sig->type_at(0)->basic_type() == T_OBJECT, "CAS base is object");
3018       assert(sig->type_at(1)->basic_type() == T_LONG, "CAS offset is long");
3019 #endif // ASSERT
3020         break;
3021       }
3022       default:
3023         ShouldNotReachHere();
3024     }
3025   }
3026 #endif //PRODUCT
3027 
3028   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
3029 
3030   // Get arguments:
3031   Node* receiver = nullptr;
3032   Node* base     = nullptr;
3033   Node* offset   = nullptr;
3034   Node* oldval   = nullptr;
3035   Node* newval   = nullptr;
3036   switch(kind) {
3037     case LS_cmp_swap:
3038     case LS_cmp_swap_weak:
3039     case LS_cmp_exchange: {
3040       const bool two_slot_type = type2size[type] == 2;
3041       receiver = argument(0);  // type: oop
3042       base     = argument(1);  // type: oop
3043       offset   = argument(2);  // type: long
3044       oldval   = argument(4);  // type: oop, int, or long
3045       newval   = argument(two_slot_type ? 6 : 5);  // type: oop, int, or long
3046       break;
3047     }
3048     case LS_get_add:
3049     case LS_get_set: {
3050       receiver = argument(0);  // type: oop
3051       base     = argument(1);  // type: oop
3052       offset   = argument(2);  // type: long
3053       oldval   = nullptr;
3054       newval   = argument(4);  // type: oop, int, or long
3055       break;
3056     }
3057     default:
3058       ShouldNotReachHere();
3059   }
3060 
3061   // Build field offset expression.
3062   // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
3063   // to be plain byte offsets, which are also the same as those accepted
3064   // by oopDesc::field_addr.
3065   assert(Unsafe_field_offset_to_byte_offset(11) == 11, "fieldOffset must be byte-scaled");
3066   // 32-bit machines ignore the high half of long offsets
3067   offset = ConvL2X(offset);
3068   // Save state and restore on bailout
3069   SavedState old_state(this);
3070   Node* adr = make_unsafe_address(base, offset,type, false);
3071   const TypePtr *adr_type = _gvn.type(adr)->isa_ptr();
3072 
3073   Compile::AliasType* alias_type = C->alias_type(adr_type);
3074   BasicType bt = alias_type->basic_type();
3075   if (bt != T_ILLEGAL &&
3076       (is_reference_type(bt) != (type == T_OBJECT))) {
3077     // Don't intrinsify mismatched object accesses.
3078     return false;
3079   }
3080 
3081   old_state.discard();
3082 
3083   // For CAS, unlike inline_unsafe_access, there seems no point in
3084   // trying to refine types. Just use the coarse types here.
3085   assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
3086   const Type *value_type = Type::get_const_basic_type(type);
3087 
3088   switch (kind) {
3089     case LS_get_set:
3090     case LS_cmp_exchange: {
3091       if (type == T_OBJECT) {
3092         const TypeOopPtr* tjp = sharpen_unsafe_type(alias_type, adr_type);
3093         if (tjp != nullptr) {
3094           value_type = tjp;
3095         }
3096       }
3097       break;
3098     }
3099     case LS_cmp_swap:
3100     case LS_cmp_swap_weak:
3101     case LS_get_add:
3102       break;
3103     default:
3104       ShouldNotReachHere();
3105   }
3106 
3107   // Null check receiver.
3108   receiver = null_check(receiver);
3109   if (stopped()) {
3110     return true;
3111   }
3112 
3113   int alias_idx = C->get_alias_index(adr_type);
3114 
3115   if (is_reference_type(type)) {
3116     decorators |= IN_HEAP | ON_UNKNOWN_OOP_REF;
3117 
3118     if (oldval != nullptr && oldval->is_InlineType()) {
3119       // Re-execute the unsafe access if allocation triggers deoptimization.
3120       PreserveReexecuteState preexecs(this);
3121       jvms()->set_should_reexecute(true);
3122       oldval = oldval->as_InlineType()->buffer(this)->get_oop();
3123     }
3124     if (newval != nullptr && newval->is_InlineType()) {
3125       // Re-execute the unsafe access if allocation triggers deoptimization.
3126       PreserveReexecuteState preexecs(this);
3127       jvms()->set_should_reexecute(true);
3128       newval = newval->as_InlineType()->buffer(this)->get_oop();
3129     }
3130 
3131     // Transformation of a value which could be null pointer (CastPP #null)
3132     // could be delayed during Parse (for example, in adjust_map_after_if()).
3133     // Execute transformation here to avoid barrier generation in such case.
3134     if (_gvn.type(newval) == TypePtr::NULL_PTR)
3135       newval = _gvn.makecon(TypePtr::NULL_PTR);
3136 
3137     if (oldval != nullptr && _gvn.type(oldval) == TypePtr::NULL_PTR) {
3138       // Refine the value to a null constant, when it is known to be null
3139       oldval = _gvn.makecon(TypePtr::NULL_PTR);
3140     }
3141   }
3142 
3143   Node* result = nullptr;
3144   switch (kind) {
3145     case LS_cmp_exchange: {
3146       result = access_atomic_cmpxchg_val_at(base, adr, adr_type, alias_idx,
3147                                             oldval, newval, value_type, type, decorators);
3148       break;
3149     }
3150     case LS_cmp_swap_weak:
3151       decorators |= C2_WEAK_CMPXCHG;
3152     case LS_cmp_swap: {
3153       result = access_atomic_cmpxchg_bool_at(base, adr, adr_type, alias_idx,
3154                                              oldval, newval, value_type, type, decorators);
3155       break;
3156     }
3157     case LS_get_set: {
3158       result = access_atomic_xchg_at(base, adr, adr_type, alias_idx,
3159                                      newval, value_type, type, decorators);
3160       break;
3161     }
3162     case LS_get_add: {
3163       result = access_atomic_add_at(base, adr, adr_type, alias_idx,
3164                                     newval, value_type, type, decorators);
3165       break;
3166     }
3167     default:
3168       ShouldNotReachHere();
3169   }
3170 
3171   assert(type2size[result->bottom_type()->basic_type()] == type2size[rtype], "result type should match");
3172   set_result(result);
3173   return true;
3174 }
3175 
3176 bool LibraryCallKit::inline_unsafe_fence(vmIntrinsics::ID id) {
3177   // Regardless of form, don't allow previous ld/st to move down,
3178   // then issue acquire, release, or volatile mem_bar.
3179   insert_mem_bar(Op_MemBarCPUOrder);
3180   switch(id) {
3181     case vmIntrinsics::_loadFence:
3182       insert_mem_bar(Op_LoadFence);
3183       return true;
3184     case vmIntrinsics::_storeFence:
3185       insert_mem_bar(Op_StoreFence);
3186       return true;
3187     case vmIntrinsics::_storeStoreFence:
3188       insert_mem_bar(Op_StoreStoreFence);
3189       return true;
3190     case vmIntrinsics::_fullFence:
3191       insert_mem_bar(Op_MemBarVolatile);
3192       return true;
3193     default:
3194       fatal_unexpected_iid(id);
3195       return false;
3196   }
3197 }
3198 
3199 // private native int arrayInstanceBaseOffset0(Object[] array);
3200 bool LibraryCallKit::inline_arrayInstanceBaseOffset() {
3201   Node* array = argument(1);
3202   Node* klass_node = load_object_klass(array);
3203 
3204   jint  layout_con = Klass::_lh_neutral_value;
3205   Node* layout_val = get_layout_helper(klass_node, layout_con);
3206   int   layout_is_con = (layout_val == nullptr);
3207 
3208   Node* header_size = nullptr;
3209   if (layout_is_con) {
3210     int hsize = Klass::layout_helper_header_size(layout_con);
3211     header_size = intcon(hsize);
3212   } else {
3213     Node* hss = intcon(Klass::_lh_header_size_shift);
3214     Node* hsm = intcon(Klass::_lh_header_size_mask);
3215     header_size = _gvn.transform(new URShiftINode(layout_val, hss));
3216     header_size = _gvn.transform(new AndINode(header_size, hsm));
3217   }
3218   set_result(header_size);
3219   return true;
3220 }
3221 
3222 // private native int arrayInstanceIndexScale0(Object[] array);
3223 bool LibraryCallKit::inline_arrayInstanceIndexScale() {
3224   Node* array = argument(1);
3225   Node* klass_node = load_object_klass(array);
3226 
3227   jint  layout_con = Klass::_lh_neutral_value;
3228   Node* layout_val = get_layout_helper(klass_node, layout_con);
3229   int   layout_is_con = (layout_val == nullptr);
3230 
3231   Node* element_size = nullptr;
3232   if (layout_is_con) {
3233     int log_element_size  = Klass::layout_helper_log2_element_size(layout_con);
3234     int elem_size = 1 << log_element_size;
3235     element_size = intcon(elem_size);
3236   } else {
3237     Node* ess = intcon(Klass::_lh_log2_element_size_shift);
3238     Node* esm = intcon(Klass::_lh_log2_element_size_mask);
3239     Node* log_element_size = _gvn.transform(new URShiftINode(layout_val, ess));
3240     log_element_size = _gvn.transform(new AndINode(log_element_size, esm));
3241     element_size = _gvn.transform(new LShiftINode(intcon(1), log_element_size));
3242   }
3243   set_result(element_size);
3244   return true;
3245 }
3246 
3247 // private native int arrayLayout0(Object[] array);
3248 bool LibraryCallKit::inline_arrayLayout() {
3249   RegionNode* region = new RegionNode(2);
3250   Node* phi = new PhiNode(region, TypeInt::POS);
3251 
3252   Node* array = argument(1);
3253   Node* klass_node = load_object_klass(array);
3254   generate_refArray_guard(klass_node, region);
3255   if (region->req() == 3) {
3256     phi->add_req(intcon((jint)LayoutKind::REFERENCE));
3257   }
3258 
3259   int layout_kind_offset = in_bytes(FlatArrayKlass::layout_kind_offset());
3260   Node* layout_kind_addr = basic_plus_adr(top(), klass_node, layout_kind_offset);
3261   Node* layout_kind = make_load(nullptr, layout_kind_addr, TypeInt::POS, T_INT, MemNode::unordered);
3262 
3263   region->init_req(1, control());
3264   phi->init_req(1, layout_kind);
3265 
3266   set_control(_gvn.transform(region));
3267   set_result(_gvn.transform(phi));
3268   return true;
3269 }
3270 
3271 // private native int[] getFieldMap0(Class <?> c);
3272 //   int offset = c._klass._acmp_maps_offset;
3273 //   return (int[])c.obj_field(offset);
3274 bool LibraryCallKit::inline_getFieldMap() {
3275   Node* mirror = argument(1);
3276   Node* klass = load_klass_from_mirror(mirror, false, nullptr, 0);
3277 
3278   int field_map_offset_offset = in_bytes(InstanceKlass::acmp_maps_offset_offset());
3279   Node* field_map_offset_addr = basic_plus_adr(top(), klass, field_map_offset_offset);
3280   Node* field_map_offset = make_load(nullptr, field_map_offset_addr, TypeInt::INT, T_INT, MemNode::unordered);
3281   field_map_offset = _gvn.transform(ConvI2L(field_map_offset));
3282 
3283   Node* map_addr = basic_plus_adr(mirror, field_map_offset);
3284   const TypeAryPtr* val_type = TypeAryPtr::INTS->cast_to_ptr_type(TypePtr::NotNull)->with_offset(0);
3285   // TODO 8350865 Remove this
3286   val_type = val_type->cast_to_not_flat(true)->cast_to_not_null_free(true);
3287   Node* map = access_load_at(mirror, map_addr, TypeAryPtr::INTS, val_type, T_ARRAY, IN_HEAP | MO_UNORDERED);
3288 
3289   set_result(map);
3290   return true;
3291 }
3292 
3293 bool LibraryCallKit::inline_onspinwait() {
3294   insert_mem_bar(Op_OnSpinWait);
3295   return true;
3296 }
3297 
3298 bool LibraryCallKit::klass_needs_init_guard(Node* kls) {
3299   if (!kls->is_Con()) {
3300     return true;
3301   }
3302   const TypeInstKlassPtr* klsptr = kls->bottom_type()->isa_instklassptr();
3303   if (klsptr == nullptr) {
3304     return true;
3305   }
3306   ciInstanceKlass* ik = klsptr->instance_klass();
3307   // don't need a guard for a klass that is already initialized
3308   return !ik->is_initialized();
3309 }
3310 
3311 //----------------------------inline_unsafe_writeback0-------------------------
3312 // public native void Unsafe.writeback0(long address)
3313 bool LibraryCallKit::inline_unsafe_writeback0() {
3314   if (!Matcher::has_match_rule(Op_CacheWB)) {
3315     return false;
3316   }
3317 #ifndef PRODUCT
3318   assert(Matcher::has_match_rule(Op_CacheWBPreSync), "found match rule for CacheWB but not CacheWBPreSync");
3319   assert(Matcher::has_match_rule(Op_CacheWBPostSync), "found match rule for CacheWB but not CacheWBPostSync");
3320   ciSignature* sig = callee()->signature();
3321   assert(sig->type_at(0)->basic_type() == T_LONG, "Unsafe_writeback0 address is long!");
3322 #endif
3323   null_check_receiver();  // null-check, then ignore
3324   Node *addr = argument(1);
3325   addr = new CastX2PNode(addr);
3326   addr = _gvn.transform(addr);
3327   Node *flush = new CacheWBNode(control(), memory(TypeRawPtr::BOTTOM), addr);
3328   flush = _gvn.transform(flush);
3329   set_memory(flush, TypeRawPtr::BOTTOM);
3330   return true;
3331 }
3332 
3333 //----------------------------inline_unsafe_writeback0-------------------------
3334 // public native void Unsafe.writeback0(long address)
3335 bool LibraryCallKit::inline_unsafe_writebackSync0(bool is_pre) {
3336   if (is_pre && !Matcher::has_match_rule(Op_CacheWBPreSync)) {
3337     return false;
3338   }
3339   if (!is_pre && !Matcher::has_match_rule(Op_CacheWBPostSync)) {
3340     return false;
3341   }
3342 #ifndef PRODUCT
3343   assert(Matcher::has_match_rule(Op_CacheWB),
3344          (is_pre ? "found match rule for CacheWBPreSync but not CacheWB"
3345                 : "found match rule for CacheWBPostSync but not CacheWB"));
3346 
3347 #endif
3348   null_check_receiver();  // null-check, then ignore
3349   Node *sync;
3350   if (is_pre) {
3351     sync = new CacheWBPreSyncNode(control(), memory(TypeRawPtr::BOTTOM));
3352   } else {
3353     sync = new CacheWBPostSyncNode(control(), memory(TypeRawPtr::BOTTOM));
3354   }
3355   sync = _gvn.transform(sync);
3356   set_memory(sync, TypeRawPtr::BOTTOM);
3357   return true;
3358 }
3359 
3360 //----------------------------inline_unsafe_allocate---------------------------
3361 // public native Object Unsafe.allocateInstance(Class<?> cls);
3362 bool LibraryCallKit::inline_unsafe_allocate() {
3363 
3364 #if INCLUDE_JVMTI
3365   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
3366     return false;
3367   }
3368 #endif //INCLUDE_JVMTI
3369 
3370   if (callee()->is_static())  return false;  // caller must have the capability!
3371 
3372   null_check_receiver();  // null-check, then ignore
3373   Node* cls = null_check(argument(1));
3374   if (stopped())  return true;
3375 
3376   Node* kls = load_klass_from_mirror(cls, false, nullptr, 0);
3377   kls = null_check(kls);
3378   if (stopped())  return true;  // argument was like int.class
3379 
3380 #if INCLUDE_JVMTI
3381     // Don't try to access new allocated obj in the intrinsic.
3382     // It causes perfomance issues even when jvmti event VmObjectAlloc is disabled.
3383     // Deoptimize and allocate in interpreter instead.
3384     Node* addr = makecon(TypeRawPtr::make((address) &JvmtiExport::_should_notify_object_alloc));
3385     Node* should_post_vm_object_alloc = make_load(this->control(), addr, TypeInt::INT, T_INT, MemNode::unordered);
3386     Node* chk = _gvn.transform(new CmpINode(should_post_vm_object_alloc, intcon(0)));
3387     Node* tst = _gvn.transform(new BoolNode(chk, BoolTest::eq));
3388     {
3389       BuildCutout unless(this, tst, PROB_MAX);
3390       uncommon_trap(Deoptimization::Reason_intrinsic,
3391                     Deoptimization::Action_make_not_entrant);
3392     }
3393     if (stopped()) {
3394       return true;
3395     }
3396 #endif //INCLUDE_JVMTI
3397 
3398   Node* test = nullptr;
3399   if (LibraryCallKit::klass_needs_init_guard(kls)) {
3400     // Note:  The argument might still be an illegal value like
3401     // Serializable.class or Object[].class.   The runtime will handle it.
3402     // But we must make an explicit check for initialization.
3403     Node* insp = basic_plus_adr(top(), kls, in_bytes(InstanceKlass::init_state_offset()));
3404     // Use T_BOOLEAN for InstanceKlass::_init_state so the compiler
3405     // can generate code to load it as unsigned byte.
3406     Node* inst = make_load(nullptr, insp, TypeInt::UBYTE, T_BOOLEAN, MemNode::acquire);
3407     Node* bits = intcon(InstanceKlass::fully_initialized);
3408     test = _gvn.transform(new SubINode(inst, bits));
3409     // The 'test' is non-zero if we need to take a slow path.
3410   }
3411   Node* obj = new_instance(kls, test);
3412   set_result(obj);
3413   return true;
3414 }
3415 
3416 //------------------------inline_native_time_funcs--------------
3417 // inline code for System.currentTimeMillis() and System.nanoTime()
3418 // these have the same type and signature
3419 bool LibraryCallKit::inline_native_time_funcs(address funcAddr, const char* funcName) {
3420   const TypeFunc* tf = OptoRuntime::void_long_Type();
3421   const TypePtr* no_memory_effects = nullptr;
3422   Node* time = make_runtime_call(RC_LEAF, tf, funcAddr, funcName, no_memory_effects);
3423   Node* value = _gvn.transform(new ProjNode(time, TypeFunc::Parms+0));
3424 #ifdef ASSERT
3425   Node* value_top = _gvn.transform(new ProjNode(time, TypeFunc::Parms+1));
3426   assert(value_top == top(), "second value must be top");
3427 #endif
3428   set_result(value);
3429   return true;
3430 }
3431 
3432 //--------------------inline_native_vthread_start_transition--------------------
3433 // inline void startTransition(boolean is_mount);
3434 // inline void startFinalTransition();
3435 // Pseudocode of implementation:
3436 //
3437 // java_lang_Thread::set_is_in_vthread_transition(vthread, true);
3438 // carrier->set_is_in_vthread_transition(true);
3439 // OrderAccess::storeload();
3440 // int disable_requests = java_lang_Thread::vthread_transition_disable_count(vthread)
3441 //                        + global_vthread_transition_disable_count();
3442 // if (disable_requests > 0) {
3443 //   slow path: runtime call
3444 // }
3445 bool LibraryCallKit::inline_native_vthread_start_transition(address funcAddr, const char* funcName, bool is_final_transition) {
3446   Node* vt_oop = _gvn.transform(must_be_not_null(argument(0), true)); // VirtualThread this argument
3447   IdealKit ideal(this);
3448 
3449   Node* thread = ideal.thread();
3450   Node* jt_addr = basic_plus_adr(top(), thread, in_bytes(JavaThread::is_in_vthread_transition_offset()));
3451   Node* vt_addr = basic_plus_adr(vt_oop, java_lang_Thread::is_in_vthread_transition_offset());
3452   access_store_at(nullptr, jt_addr, _gvn.type(jt_addr)->is_ptr(), ideal.ConI(1), TypeInt::BOOL, T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
3453   access_store_at(nullptr, vt_addr, _gvn.type(vt_addr)->is_ptr(), ideal.ConI(1), TypeInt::BOOL, T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
3454   insert_mem_bar(Op_MemBarVolatile);
3455   ideal.sync_kit(this);
3456 
3457   Node* global_disable_addr = makecon(TypeRawPtr::make((address)MountUnmountDisabler::global_vthread_transition_disable_count_address()));
3458   Node* global_disable = ideal.load(ideal.ctrl(), global_disable_addr, TypeInt::INT, T_INT, Compile::AliasIdxRaw, true /*require_atomic_access*/);
3459   Node* vt_disable_addr = basic_plus_adr(vt_oop, java_lang_Thread::vthread_transition_disable_count_offset());
3460   Node* vt_disable = ideal.load(ideal.ctrl(), vt_disable_addr, TypeInt::INT, T_INT, Compile::AliasIdxRaw, true /*require_atomic_access*/);
3461   Node* disabled = _gvn.transform(new AddINode(global_disable, vt_disable));
3462 
3463   ideal.if_then(disabled, BoolTest::ne, ideal.ConI(0)); {
3464     sync_kit(ideal);
3465     Node* is_mount = is_final_transition ? ideal.ConI(0) : _gvn.transform(argument(1));
3466     const TypeFunc* tf = OptoRuntime::vthread_transition_Type();
3467     make_runtime_call(RC_NO_LEAF, tf, funcAddr, funcName, TypePtr::BOTTOM, vt_oop, is_mount);
3468     ideal.sync_kit(this);
3469   }
3470   ideal.end_if();
3471 
3472   final_sync(ideal);
3473   return true;
3474 }
3475 
3476 bool LibraryCallKit::inline_native_vthread_end_transition(address funcAddr, const char* funcName, bool is_first_transition) {
3477   Node* vt_oop = _gvn.transform(must_be_not_null(argument(0), true)); // VirtualThread this argument
3478   IdealKit ideal(this);
3479 
3480   Node* _notify_jvmti_addr = makecon(TypeRawPtr::make((address)MountUnmountDisabler::notify_jvmti_events_address()));
3481   Node* _notify_jvmti = ideal.load(ideal.ctrl(), _notify_jvmti_addr, TypeInt::BOOL, T_BOOLEAN, Compile::AliasIdxRaw);
3482 
3483   ideal.if_then(_notify_jvmti, BoolTest::eq, ideal.ConI(1)); {
3484     sync_kit(ideal);
3485     Node* is_mount = is_first_transition ? ideal.ConI(1) : _gvn.transform(argument(1));
3486     const TypeFunc* tf = OptoRuntime::vthread_transition_Type();
3487     make_runtime_call(RC_NO_LEAF, tf, funcAddr, funcName, TypePtr::BOTTOM, vt_oop, is_mount);
3488     ideal.sync_kit(this);
3489   } ideal.else_(); {
3490     Node* thread = ideal.thread();
3491     Node* jt_addr = basic_plus_adr(top(), thread, in_bytes(JavaThread::is_in_vthread_transition_offset()));
3492     Node* vt_addr = basic_plus_adr(vt_oop, java_lang_Thread::is_in_vthread_transition_offset());
3493 
3494     sync_kit(ideal);
3495     access_store_at(nullptr, jt_addr, _gvn.type(jt_addr)->is_ptr(), ideal.ConI(0), TypeInt::BOOL, T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
3496     access_store_at(nullptr, vt_addr, _gvn.type(vt_addr)->is_ptr(), ideal.ConI(0), TypeInt::BOOL, T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
3497     ideal.sync_kit(this);
3498   } ideal.end_if();
3499 
3500   final_sync(ideal);
3501   return true;
3502 }
3503 
3504 #if INCLUDE_JVMTI
3505 
3506 // Always update the is_disable_suspend bit.
3507 bool LibraryCallKit::inline_native_notify_jvmti_sync() {
3508   if (!DoJVMTIVirtualThreadTransitions) {
3509     return true;
3510   }
3511   IdealKit ideal(this);
3512 
3513   {
3514     // unconditionally update the is_disable_suspend bit in current JavaThread
3515     Node* thread = ideal.thread();
3516     Node* arg = _gvn.transform(argument(0)); // argument for notification
3517     Node* addr = basic_plus_adr(top(), thread, in_bytes(JavaThread::is_disable_suspend_offset()));
3518     const TypePtr *addr_type = _gvn.type(addr)->isa_ptr();
3519 
3520     sync_kit(ideal);
3521     access_store_at(nullptr, addr, addr_type, arg, _gvn.type(arg), T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
3522     ideal.sync_kit(this);
3523   }
3524   final_sync(ideal);
3525 
3526   return true;
3527 }
3528 
3529 #endif // INCLUDE_JVMTI
3530 
3531 #ifdef JFR_HAVE_INTRINSICS
3532 
3533 /**
3534  * if oop->klass != null
3535  *   // normal class
3536  *   epoch = _epoch_state ? 2 : 1
3537  *   if oop->klass->trace_id & ((epoch << META_SHIFT) | epoch)) != epoch {
3538  *     ... // enter slow path when the klass is first recorded or the epoch of JFR shifts
3539  *   }
3540  *   id = oop->klass->trace_id >> TRACE_ID_SHIFT // normal class path
3541  * else
3542  *   // primitive class
3543  *   if oop->array_klass != null
3544  *     id = (oop->array_klass->trace_id >> TRACE_ID_SHIFT) + 1 // primitive class path
3545  *   else
3546  *     id = LAST_TYPE_ID + 1 // void class path
3547  *   if (!signaled)
3548  *     signaled = true
3549  */
3550 bool LibraryCallKit::inline_native_classID() {
3551   Node* cls = argument(0);
3552 
3553   IdealKit ideal(this);
3554 #define __ ideal.
3555   IdealVariable result(ideal); __ declarations_done();
3556   Node* kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(),
3557                                                  basic_plus_adr(cls, java_lang_Class::klass_offset()),
3558                                                  TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
3559 
3560 
3561   __ if_then(kls, BoolTest::ne, null()); {
3562     Node* kls_trace_id_addr = basic_plus_adr(kls, in_bytes(KLASS_TRACE_ID_OFFSET));
3563     Node* kls_trace_id_raw = ideal.load(ideal.ctrl(), kls_trace_id_addr,TypeLong::LONG, T_LONG, Compile::AliasIdxRaw);
3564 
3565     Node* epoch_address = makecon(TypeRawPtr::make(JfrIntrinsicSupport::epoch_address()));
3566     Node* epoch = ideal.load(ideal.ctrl(), epoch_address, TypeInt::BOOL, T_BOOLEAN, Compile::AliasIdxRaw);
3567     epoch = _gvn.transform(new LShiftLNode(longcon(1), epoch));
3568     Node* mask = _gvn.transform(new LShiftLNode(epoch, intcon(META_SHIFT)));
3569     mask = _gvn.transform(new OrLNode(mask, epoch));
3570     Node* kls_trace_id_raw_and_mask = _gvn.transform(new AndLNode(kls_trace_id_raw, mask));
3571 
3572     float unlikely  = PROB_UNLIKELY(0.999);
3573     __ if_then(kls_trace_id_raw_and_mask, BoolTest::ne, epoch, unlikely); {
3574       sync_kit(ideal);
3575       make_runtime_call(RC_LEAF,
3576                         OptoRuntime::class_id_load_barrier_Type(),
3577                         CAST_FROM_FN_PTR(address, JfrIntrinsicSupport::load_barrier),
3578                         "class id load barrier",
3579                         TypePtr::BOTTOM,
3580                         kls);
3581       ideal.sync_kit(this);
3582     } __ end_if();
3583 
3584     ideal.set(result,  _gvn.transform(new URShiftLNode(kls_trace_id_raw, ideal.ConI(TRACE_ID_SHIFT))));
3585   } __ else_(); {
3586     Node* array_kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(),
3587                                                    basic_plus_adr(cls, java_lang_Class::array_klass_offset()),
3588                                                    TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
3589     __ if_then(array_kls, BoolTest::ne, null()); {
3590       Node* array_kls_trace_id_addr = basic_plus_adr(array_kls, in_bytes(KLASS_TRACE_ID_OFFSET));
3591       Node* array_kls_trace_id_raw = ideal.load(ideal.ctrl(), array_kls_trace_id_addr, TypeLong::LONG, T_LONG, Compile::AliasIdxRaw);
3592       Node* array_kls_trace_id = _gvn.transform(new URShiftLNode(array_kls_trace_id_raw, ideal.ConI(TRACE_ID_SHIFT)));
3593       ideal.set(result, _gvn.transform(new AddLNode(array_kls_trace_id, longcon(1))));
3594     } __ else_(); {
3595       // void class case
3596       ideal.set(result, _gvn.transform(longcon(LAST_TYPE_ID + 1)));
3597     } __ end_if();
3598 
3599     Node* signaled_flag_address = makecon(TypeRawPtr::make(JfrIntrinsicSupport::signal_address()));
3600     Node* signaled = ideal.load(ideal.ctrl(), signaled_flag_address, TypeInt::BOOL, T_BOOLEAN, Compile::AliasIdxRaw, true, MemNode::acquire);
3601     __ if_then(signaled, BoolTest::ne, ideal.ConI(1)); {
3602       ideal.store(ideal.ctrl(), signaled_flag_address, ideal.ConI(1), T_BOOLEAN, Compile::AliasIdxRaw, MemNode::release, true);
3603     } __ end_if();
3604   } __ end_if();
3605 
3606   final_sync(ideal);
3607   set_result(ideal.value(result));
3608 #undef __
3609   return true;
3610 }
3611 
3612 //------------------------inline_native_jvm_commit------------------
3613 bool LibraryCallKit::inline_native_jvm_commit() {
3614   enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
3615 
3616   // Save input memory and i_o state.
3617   Node* input_memory_state = reset_memory();
3618   set_all_memory(input_memory_state);
3619   Node* input_io_state = i_o();
3620 
3621   // TLS.
3622   Node* tls_ptr = _gvn.transform(new ThreadLocalNode());
3623   // Jfr java buffer.
3624   Node* java_buffer_offset = _gvn.transform(new AddPNode(top(), tls_ptr, _gvn.transform(MakeConX(in_bytes(JAVA_BUFFER_OFFSET_JFR)))));
3625   Node* java_buffer = _gvn.transform(new LoadPNode(control(), input_memory_state, java_buffer_offset, TypePtr::BOTTOM, TypeRawPtr::NOTNULL, MemNode::unordered));
3626   Node* java_buffer_pos_offset = _gvn.transform(new AddPNode(top(), java_buffer, _gvn.transform(MakeConX(in_bytes(JFR_BUFFER_POS_OFFSET)))));
3627 
3628   // Load the current value of the notified field in the JfrThreadLocal.
3629   Node* notified_offset = basic_plus_adr(top(), tls_ptr, in_bytes(NOTIFY_OFFSET_JFR));
3630   Node* notified = make_load(control(), notified_offset, TypeInt::BOOL, T_BOOLEAN, MemNode::unordered);
3631 
3632   // Test for notification.
3633   Node* notified_cmp = _gvn.transform(new CmpINode(notified, _gvn.intcon(1)));
3634   Node* test_notified = _gvn.transform(new BoolNode(notified_cmp, BoolTest::eq));
3635   IfNode* iff_notified = create_and_map_if(control(), test_notified, PROB_MIN, COUNT_UNKNOWN);
3636 
3637   // True branch, is notified.
3638   Node* is_notified = _gvn.transform(new IfTrueNode(iff_notified));
3639   set_control(is_notified);
3640 
3641   // Reset notified state.
3642   store_to_memory(control(), notified_offset, _gvn.intcon(0), T_BOOLEAN, MemNode::unordered);
3643   Node* notified_reset_memory = reset_memory();
3644 
3645   // 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.
3646   Node* current_pos_X = _gvn.transform(new LoadXNode(control(), input_memory_state, java_buffer_pos_offset, TypeRawPtr::NOTNULL, TypeX_X, MemNode::unordered));
3647   // Convert the machine-word to a long.
3648   Node* current_pos = _gvn.transform(ConvX2L(current_pos_X));
3649 
3650   // False branch, not notified.
3651   Node* not_notified = _gvn.transform(new IfFalseNode(iff_notified));
3652   set_control(not_notified);
3653   set_all_memory(input_memory_state);
3654 
3655   // Arg is the next position as a long.
3656   Node* arg = argument(0);
3657   // Convert long to machine-word.
3658   Node* next_pos_X = _gvn.transform(ConvL2X(arg));
3659 
3660   // Store the next_position to the underlying jfr java buffer.
3661   store_to_memory(control(), java_buffer_pos_offset, next_pos_X, LP64_ONLY(T_LONG) NOT_LP64(T_INT), MemNode::release);
3662 
3663   Node* commit_memory = reset_memory();
3664   set_all_memory(commit_memory);
3665 
3666   // 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.
3667   Node* java_buffer_flags_offset = _gvn.transform(new AddPNode(top(), java_buffer, _gvn.transform(MakeConX(in_bytes(JFR_BUFFER_FLAGS_OFFSET)))));
3668   Node* flags = make_load(control(), java_buffer_flags_offset, TypeInt::UBYTE, T_BYTE, MemNode::unordered);
3669   Node* lease_constant = _gvn.transform(_gvn.intcon(4));
3670 
3671   // And flags with lease constant.
3672   Node* lease = _gvn.transform(new AndINode(flags, lease_constant));
3673 
3674   // Branch on lease to conditionalize returning the leased java buffer.
3675   Node* lease_cmp = _gvn.transform(new CmpINode(lease, lease_constant));
3676   Node* test_lease = _gvn.transform(new BoolNode(lease_cmp, BoolTest::eq));
3677   IfNode* iff_lease = create_and_map_if(control(), test_lease, PROB_MIN, COUNT_UNKNOWN);
3678 
3679   // False branch, not a lease.
3680   Node* not_lease = _gvn.transform(new IfFalseNode(iff_lease));
3681 
3682   // True branch, is lease.
3683   Node* is_lease = _gvn.transform(new IfTrueNode(iff_lease));
3684   set_control(is_lease);
3685 
3686   // Make a runtime call, which can safepoint, to return the leased buffer. This updates both the JfrThreadLocal and the Java event writer oop.
3687   Node* call_return_lease = make_runtime_call(RC_NO_LEAF,
3688                                               OptoRuntime::void_void_Type(),
3689                                               SharedRuntime::jfr_return_lease(),
3690                                               "return_lease", TypePtr::BOTTOM);
3691   Node* call_return_lease_control = _gvn.transform(new ProjNode(call_return_lease, TypeFunc::Control));
3692 
3693   RegionNode* lease_compare_rgn = new RegionNode(PATH_LIMIT);
3694   record_for_igvn(lease_compare_rgn);
3695   PhiNode* lease_compare_mem = new PhiNode(lease_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3696   record_for_igvn(lease_compare_mem);
3697   PhiNode* lease_compare_io = new PhiNode(lease_compare_rgn, Type::ABIO);
3698   record_for_igvn(lease_compare_io);
3699   PhiNode* lease_result_value = new PhiNode(lease_compare_rgn, TypeLong::LONG);
3700   record_for_igvn(lease_result_value);
3701 
3702   // Update control and phi nodes.
3703   lease_compare_rgn->init_req(_true_path, call_return_lease_control);
3704   lease_compare_rgn->init_req(_false_path, not_lease);
3705 
3706   lease_compare_mem->init_req(_true_path, _gvn.transform(reset_memory()));
3707   lease_compare_mem->init_req(_false_path, commit_memory);
3708 
3709   lease_compare_io->init_req(_true_path, i_o());
3710   lease_compare_io->init_req(_false_path, input_io_state);
3711 
3712   lease_result_value->init_req(_true_path, _gvn.longcon(0)); // if the lease was returned, return 0L.
3713   lease_result_value->init_req(_false_path, arg); // if not lease, return new updated position.
3714 
3715   RegionNode* result_rgn = new RegionNode(PATH_LIMIT);
3716   PhiNode* result_mem = new PhiNode(result_rgn, Type::MEMORY, TypePtr::BOTTOM);
3717   PhiNode* result_io = new PhiNode(result_rgn, Type::ABIO);
3718   PhiNode* result_value = new PhiNode(result_rgn, TypeLong::LONG);
3719 
3720   // Update control and phi nodes.
3721   result_rgn->init_req(_true_path, is_notified);
3722   result_rgn->init_req(_false_path, _gvn.transform(lease_compare_rgn));
3723 
3724   result_mem->init_req(_true_path, notified_reset_memory);
3725   result_mem->init_req(_false_path, _gvn.transform(lease_compare_mem));
3726 
3727   result_io->init_req(_true_path, input_io_state);
3728   result_io->init_req(_false_path, _gvn.transform(lease_compare_io));
3729 
3730   result_value->init_req(_true_path, current_pos);
3731   result_value->init_req(_false_path, _gvn.transform(lease_result_value));
3732 
3733   // Set output state.
3734   set_control(_gvn.transform(result_rgn));
3735   set_all_memory(_gvn.transform(result_mem));
3736   set_i_o(_gvn.transform(result_io));
3737   set_result(result_rgn, result_value);
3738   return true;
3739 }
3740 
3741 /*
3742  * The intrinsic is a model of this pseudo-code:
3743  *
3744  * JfrThreadLocal* const tl = Thread::jfr_thread_local()
3745  * jobject h_event_writer = tl->java_event_writer();
3746  * if (h_event_writer == nullptr) {
3747  *   return nullptr;
3748  * }
3749  * oop threadObj = Thread::threadObj();
3750  * oop vthread = java_lang_Thread::vthread(threadObj);
3751  * traceid tid;
3752  * bool pinVirtualThread;
3753  * bool excluded;
3754  * if (vthread != threadObj) {  // i.e. current thread is virtual
3755  *   tid = java_lang_Thread::tid(vthread);
3756  *   u2 vthread_epoch_raw = java_lang_Thread::jfr_epoch(vthread);
3757  *   pinVirtualThread = VMContinuations;
3758  *   excluded = vthread_epoch_raw & excluded_mask;
3759  *   if (!excluded) {
3760  *     traceid current_epoch = JfrTraceIdEpoch::current_generation();
3761  *     u2 vthread_epoch = vthread_epoch_raw & epoch_mask;
3762  *     if (vthread_epoch != current_epoch) {
3763  *       write_checkpoint();
3764  *     }
3765  *   }
3766  * } else {
3767  *   tid = java_lang_Thread::tid(threadObj);
3768  *   u2 thread_epoch_raw = java_lang_Thread::jfr_epoch(threadObj);
3769  *   pinVirtualThread = false;
3770  *   excluded = thread_epoch_raw & excluded_mask;
3771  * }
3772  * oop event_writer = JNIHandles::resolve_non_null(h_event_writer);
3773  * traceid tid_in_event_writer = getField(event_writer, "threadID");
3774  * if (tid_in_event_writer != tid) {
3775  *   setField(event_writer, "pinVirtualThread", pinVirtualThread);
3776  *   setField(event_writer, "excluded", excluded);
3777  *   setField(event_writer, "threadID", tid);
3778  * }
3779  * return event_writer
3780  */
3781 bool LibraryCallKit::inline_native_getEventWriter() {
3782   enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
3783 
3784   // Save input memory and i_o state.
3785   Node* input_memory_state = reset_memory();
3786   set_all_memory(input_memory_state);
3787   Node* input_io_state = i_o();
3788 
3789   // The most significant bit of the u2 is used to denote thread exclusion
3790   Node* excluded_shift = _gvn.intcon(15);
3791   Node* excluded_mask = _gvn.intcon(1 << 15);
3792   // The epoch generation is the range [1-32767]
3793   Node* epoch_mask = _gvn.intcon(32767);
3794 
3795   // TLS
3796   Node* tls_ptr = _gvn.transform(new ThreadLocalNode());
3797 
3798   // Load the address of java event writer jobject handle from the jfr_thread_local structure.
3799   Node* jobj_ptr = basic_plus_adr(top(), tls_ptr, in_bytes(THREAD_LOCAL_WRITER_OFFSET_JFR));
3800 
3801   // Load the eventwriter jobject handle.
3802   Node* jobj = make_load(control(), jobj_ptr, TypeRawPtr::BOTTOM, T_ADDRESS, MemNode::unordered);
3803 
3804   // Null check the jobject handle.
3805   Node* jobj_cmp_null = _gvn.transform(new CmpPNode(jobj, null()));
3806   Node* test_jobj_not_equal_null = _gvn.transform(new BoolNode(jobj_cmp_null, BoolTest::ne));
3807   IfNode* iff_jobj_not_equal_null = create_and_map_if(control(), test_jobj_not_equal_null, PROB_MAX, COUNT_UNKNOWN);
3808 
3809   // False path, jobj is null.
3810   Node* jobj_is_null = _gvn.transform(new IfFalseNode(iff_jobj_not_equal_null));
3811 
3812   // True path, jobj is not null.
3813   Node* jobj_is_not_null = _gvn.transform(new IfTrueNode(iff_jobj_not_equal_null));
3814 
3815   set_control(jobj_is_not_null);
3816 
3817   // Load the threadObj for the CarrierThread.
3818   Node* threadObj = generate_current_thread(tls_ptr);
3819 
3820   // Load the vthread.
3821   Node* vthread = generate_virtual_thread(tls_ptr);
3822 
3823   // If vthread != threadObj, this is a virtual thread.
3824   Node* vthread_cmp_threadObj = _gvn.transform(new CmpPNode(vthread, threadObj));
3825   Node* test_vthread_not_equal_threadObj = _gvn.transform(new BoolNode(vthread_cmp_threadObj, BoolTest::ne));
3826   IfNode* iff_vthread_not_equal_threadObj =
3827     create_and_map_if(jobj_is_not_null, test_vthread_not_equal_threadObj, PROB_FAIR, COUNT_UNKNOWN);
3828 
3829   // False branch, fallback to threadObj.
3830   Node* vthread_equal_threadObj = _gvn.transform(new IfFalseNode(iff_vthread_not_equal_threadObj));
3831   set_control(vthread_equal_threadObj);
3832 
3833   // Load the tid field from the vthread object.
3834   Node* thread_obj_tid = load_field_from_object(threadObj, "tid", "J");
3835 
3836   // Load the raw epoch value from the threadObj.
3837   Node* threadObj_epoch_offset = basic_plus_adr(threadObj, java_lang_Thread::jfr_epoch_offset());
3838   Node* threadObj_epoch_raw = access_load_at(threadObj, threadObj_epoch_offset,
3839                                              _gvn.type(threadObj_epoch_offset)->isa_ptr(),
3840                                              TypeInt::CHAR, T_CHAR,
3841                                              IN_HEAP | MO_UNORDERED | C2_MISMATCHED | C2_CONTROL_DEPENDENT_LOAD);
3842 
3843   // Mask off the excluded information from the epoch.
3844   Node * threadObj_is_excluded = _gvn.transform(new AndINode(threadObj_epoch_raw, excluded_mask));
3845 
3846   // True branch, this is a virtual thread.
3847   Node* vthread_not_equal_threadObj = _gvn.transform(new IfTrueNode(iff_vthread_not_equal_threadObj));
3848   set_control(vthread_not_equal_threadObj);
3849 
3850   // Load the tid field from the vthread object.
3851   Node* vthread_tid = load_field_from_object(vthread, "tid", "J");
3852 
3853   // Continuation support determines if a virtual thread should be pinned.
3854   Node* global_addr = makecon(TypeRawPtr::make((address)&VMContinuations));
3855   Node* continuation_support = make_load(control(), global_addr, TypeInt::BOOL, T_BOOLEAN, MemNode::unordered);
3856 
3857   // Load the raw epoch value from the vthread.
3858   Node* vthread_epoch_offset = basic_plus_adr(vthread, java_lang_Thread::jfr_epoch_offset());
3859   Node* vthread_epoch_raw = access_load_at(vthread, vthread_epoch_offset, _gvn.type(vthread_epoch_offset)->is_ptr(),
3860                                            TypeInt::CHAR, T_CHAR,
3861                                            IN_HEAP | MO_UNORDERED | C2_MISMATCHED | C2_CONTROL_DEPENDENT_LOAD);
3862 
3863   // Mask off the excluded information from the epoch.
3864   Node * vthread_is_excluded = _gvn.transform(new AndINode(vthread_epoch_raw, _gvn.transform(excluded_mask)));
3865 
3866   // Branch on excluded to conditionalize updating the epoch for the virtual thread.
3867   Node* is_excluded_cmp = _gvn.transform(new CmpINode(vthread_is_excluded, _gvn.transform(excluded_mask)));
3868   Node* test_not_excluded = _gvn.transform(new BoolNode(is_excluded_cmp, BoolTest::ne));
3869   IfNode* iff_not_excluded = create_and_map_if(control(), test_not_excluded, PROB_MAX, COUNT_UNKNOWN);
3870 
3871   // False branch, vthread is excluded, no need to write epoch info.
3872   Node* excluded = _gvn.transform(new IfFalseNode(iff_not_excluded));
3873 
3874   // True branch, vthread is included, update epoch info.
3875   Node* included = _gvn.transform(new IfTrueNode(iff_not_excluded));
3876   set_control(included);
3877 
3878   // Get epoch value.
3879   Node* epoch = _gvn.transform(new AndINode(vthread_epoch_raw, _gvn.transform(epoch_mask)));
3880 
3881   // Load the current epoch generation. The value is unsigned 16-bit, so we type it as T_CHAR.
3882   Node* epoch_generation_address = makecon(TypeRawPtr::make(JfrIntrinsicSupport::epoch_generation_address()));
3883   Node* current_epoch_generation = make_load(control(), epoch_generation_address, TypeInt::CHAR, T_CHAR, MemNode::unordered);
3884 
3885   // Compare the epoch in the vthread to the current epoch generation.
3886   Node* const epoch_cmp = _gvn.transform(new CmpUNode(current_epoch_generation, epoch));
3887   Node* test_epoch_not_equal = _gvn.transform(new BoolNode(epoch_cmp, BoolTest::ne));
3888   IfNode* iff_epoch_not_equal = create_and_map_if(control(), test_epoch_not_equal, PROB_FAIR, COUNT_UNKNOWN);
3889 
3890   // False path, epoch is equal, checkpoint information is valid.
3891   Node* epoch_is_equal = _gvn.transform(new IfFalseNode(iff_epoch_not_equal));
3892 
3893   // True path, epoch is not equal, write a checkpoint for the vthread.
3894   Node* epoch_is_not_equal = _gvn.transform(new IfTrueNode(iff_epoch_not_equal));
3895 
3896   set_control(epoch_is_not_equal);
3897 
3898   // Make a runtime call, which can safepoint, to write a checkpoint for the vthread for this epoch.
3899   // The call also updates the native thread local thread id and the vthread with the current epoch.
3900   Node* call_write_checkpoint = make_runtime_call(RC_NO_LEAF,
3901                                                   OptoRuntime::jfr_write_checkpoint_Type(),
3902                                                   SharedRuntime::jfr_write_checkpoint(),
3903                                                   "write_checkpoint", TypePtr::BOTTOM);
3904   Node* call_write_checkpoint_control = _gvn.transform(new ProjNode(call_write_checkpoint, TypeFunc::Control));
3905 
3906   // vthread epoch != current epoch
3907   RegionNode* epoch_compare_rgn = new RegionNode(PATH_LIMIT);
3908   record_for_igvn(epoch_compare_rgn);
3909   PhiNode* epoch_compare_mem = new PhiNode(epoch_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3910   record_for_igvn(epoch_compare_mem);
3911   PhiNode* epoch_compare_io = new PhiNode(epoch_compare_rgn, Type::ABIO);
3912   record_for_igvn(epoch_compare_io);
3913 
3914   // Update control and phi nodes.
3915   epoch_compare_rgn->init_req(_true_path, call_write_checkpoint_control);
3916   epoch_compare_rgn->init_req(_false_path, epoch_is_equal);
3917   epoch_compare_mem->init_req(_true_path, _gvn.transform(reset_memory()));
3918   epoch_compare_mem->init_req(_false_path, input_memory_state);
3919   epoch_compare_io->init_req(_true_path, i_o());
3920   epoch_compare_io->init_req(_false_path, input_io_state);
3921 
3922   // excluded != true
3923   RegionNode* exclude_compare_rgn = new RegionNode(PATH_LIMIT);
3924   record_for_igvn(exclude_compare_rgn);
3925   PhiNode* exclude_compare_mem = new PhiNode(exclude_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3926   record_for_igvn(exclude_compare_mem);
3927   PhiNode* exclude_compare_io = new PhiNode(exclude_compare_rgn, Type::ABIO);
3928   record_for_igvn(exclude_compare_io);
3929 
3930   // Update control and phi nodes.
3931   exclude_compare_rgn->init_req(_true_path, _gvn.transform(epoch_compare_rgn));
3932   exclude_compare_rgn->init_req(_false_path, excluded);
3933   exclude_compare_mem->init_req(_true_path, _gvn.transform(epoch_compare_mem));
3934   exclude_compare_mem->init_req(_false_path, input_memory_state);
3935   exclude_compare_io->init_req(_true_path, _gvn.transform(epoch_compare_io));
3936   exclude_compare_io->init_req(_false_path, input_io_state);
3937 
3938   // vthread != threadObj
3939   RegionNode* vthread_compare_rgn = new RegionNode(PATH_LIMIT);
3940   record_for_igvn(vthread_compare_rgn);
3941   PhiNode* vthread_compare_mem = new PhiNode(vthread_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3942   PhiNode* vthread_compare_io = new PhiNode(vthread_compare_rgn, Type::ABIO);
3943   record_for_igvn(vthread_compare_io);
3944   PhiNode* tid = new PhiNode(vthread_compare_rgn, TypeLong::LONG);
3945   record_for_igvn(tid);
3946   PhiNode* exclusion = new PhiNode(vthread_compare_rgn, TypeInt::CHAR);
3947   record_for_igvn(exclusion);
3948   PhiNode* pinVirtualThread = new PhiNode(vthread_compare_rgn, TypeInt::BOOL);
3949   record_for_igvn(pinVirtualThread);
3950 
3951   // Update control and phi nodes.
3952   vthread_compare_rgn->init_req(_true_path, _gvn.transform(exclude_compare_rgn));
3953   vthread_compare_rgn->init_req(_false_path, vthread_equal_threadObj);
3954   vthread_compare_mem->init_req(_true_path, _gvn.transform(exclude_compare_mem));
3955   vthread_compare_mem->init_req(_false_path, input_memory_state);
3956   vthread_compare_io->init_req(_true_path, _gvn.transform(exclude_compare_io));
3957   vthread_compare_io->init_req(_false_path, input_io_state);
3958   tid->init_req(_true_path, _gvn.transform(vthread_tid));
3959   tid->init_req(_false_path, _gvn.transform(thread_obj_tid));
3960   exclusion->init_req(_true_path, _gvn.transform(vthread_is_excluded));
3961   exclusion->init_req(_false_path, _gvn.transform(threadObj_is_excluded));
3962   pinVirtualThread->init_req(_true_path, _gvn.transform(continuation_support));
3963   pinVirtualThread->init_req(_false_path, _gvn.intcon(0));
3964 
3965   // Update branch state.
3966   set_control(_gvn.transform(vthread_compare_rgn));
3967   set_all_memory(_gvn.transform(vthread_compare_mem));
3968   set_i_o(_gvn.transform(vthread_compare_io));
3969 
3970   // Load the event writer oop by dereferencing the jobject handle.
3971   ciKlass* klass_EventWriter = env()->find_system_klass(ciSymbol::make("jdk/jfr/internal/event/EventWriter"));
3972   assert(klass_EventWriter->is_loaded(), "invariant");
3973   ciInstanceKlass* const instklass_EventWriter = klass_EventWriter->as_instance_klass();
3974   const TypeKlassPtr* const aklass = TypeKlassPtr::make(instklass_EventWriter);
3975   const TypeOopPtr* const xtype = aklass->as_instance_type();
3976   Node* jobj_untagged = _gvn.transform(new AddPNode(top(), jobj, _gvn.MakeConX(-JNIHandles::TypeTag::global)));
3977   Node* event_writer = access_load(jobj_untagged, xtype, T_OBJECT, IN_NATIVE | C2_CONTROL_DEPENDENT_LOAD);
3978 
3979   // Load the current thread id from the event writer object.
3980   Node* const event_writer_tid = load_field_from_object(event_writer, "threadID", "J");
3981   // Get the field offset to, conditionally, store an updated tid value later.
3982   Node* const event_writer_tid_field = field_address_from_object(event_writer, "threadID", "J", false);
3983   // Get the field offset to, conditionally, store an updated exclusion value later.
3984   Node* const event_writer_excluded_field = field_address_from_object(event_writer, "excluded", "Z", false);
3985   // Get the field offset to, conditionally, store an updated pinVirtualThread value later.
3986   Node* const event_writer_pin_field = field_address_from_object(event_writer, "pinVirtualThread", "Z", false);
3987 
3988   RegionNode* event_writer_tid_compare_rgn = new RegionNode(PATH_LIMIT);
3989   record_for_igvn(event_writer_tid_compare_rgn);
3990   PhiNode* event_writer_tid_compare_mem = new PhiNode(event_writer_tid_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3991   record_for_igvn(event_writer_tid_compare_mem);
3992   PhiNode* event_writer_tid_compare_io = new PhiNode(event_writer_tid_compare_rgn, Type::ABIO);
3993   record_for_igvn(event_writer_tid_compare_io);
3994 
3995   // Compare the current tid from the thread object to what is currently stored in the event writer object.
3996   Node* const tid_cmp = _gvn.transform(new CmpLNode(event_writer_tid, _gvn.transform(tid)));
3997   Node* test_tid_not_equal = _gvn.transform(new BoolNode(tid_cmp, BoolTest::ne));
3998   IfNode* iff_tid_not_equal = create_and_map_if(_gvn.transform(vthread_compare_rgn), test_tid_not_equal, PROB_FAIR, COUNT_UNKNOWN);
3999 
4000   // False path, tids are the same.
4001   Node* tid_is_equal = _gvn.transform(new IfFalseNode(iff_tid_not_equal));
4002 
4003   // True path, tid is not equal, need to update the tid in the event writer.
4004   Node* tid_is_not_equal = _gvn.transform(new IfTrueNode(iff_tid_not_equal));
4005   record_for_igvn(tid_is_not_equal);
4006 
4007   // Store the pin state to the event writer.
4008   store_to_memory(tid_is_not_equal, event_writer_pin_field, _gvn.transform(pinVirtualThread), T_BOOLEAN, MemNode::unordered);
4009 
4010   // Store the exclusion state to the event writer.
4011   Node* excluded_bool = _gvn.transform(new URShiftINode(_gvn.transform(exclusion), excluded_shift));
4012   store_to_memory(tid_is_not_equal, event_writer_excluded_field, excluded_bool, T_BOOLEAN, MemNode::unordered);
4013 
4014   // Store the tid to the event writer.
4015   store_to_memory(tid_is_not_equal, event_writer_tid_field, tid, T_LONG, MemNode::unordered);
4016 
4017   // Update control and phi nodes.
4018   event_writer_tid_compare_rgn->init_req(_true_path, tid_is_not_equal);
4019   event_writer_tid_compare_rgn->init_req(_false_path, tid_is_equal);
4020   event_writer_tid_compare_mem->init_req(_true_path, _gvn.transform(reset_memory()));
4021   event_writer_tid_compare_mem->init_req(_false_path, _gvn.transform(vthread_compare_mem));
4022   event_writer_tid_compare_io->init_req(_true_path, _gvn.transform(i_o()));
4023   event_writer_tid_compare_io->init_req(_false_path, _gvn.transform(vthread_compare_io));
4024 
4025   // Result of top level CFG, Memory, IO and Value.
4026   RegionNode* result_rgn = new RegionNode(PATH_LIMIT);
4027   PhiNode* result_mem = new PhiNode(result_rgn, Type::MEMORY, TypePtr::BOTTOM);
4028   PhiNode* result_io = new PhiNode(result_rgn, Type::ABIO);
4029   PhiNode* result_value = new PhiNode(result_rgn, TypeInstPtr::BOTTOM);
4030 
4031   // Result control.
4032   result_rgn->init_req(_true_path, _gvn.transform(event_writer_tid_compare_rgn));
4033   result_rgn->init_req(_false_path, jobj_is_null);
4034 
4035   // Result memory.
4036   result_mem->init_req(_true_path, _gvn.transform(event_writer_tid_compare_mem));
4037   result_mem->init_req(_false_path, _gvn.transform(input_memory_state));
4038 
4039   // Result IO.
4040   result_io->init_req(_true_path, _gvn.transform(event_writer_tid_compare_io));
4041   result_io->init_req(_false_path, _gvn.transform(input_io_state));
4042 
4043   // Result value.
4044   result_value->init_req(_true_path, _gvn.transform(event_writer)); // return event writer oop
4045   result_value->init_req(_false_path, null()); // return null
4046 
4047   // Set output state.
4048   set_control(_gvn.transform(result_rgn));
4049   set_all_memory(_gvn.transform(result_mem));
4050   set_i_o(_gvn.transform(result_io));
4051   set_result(result_rgn, result_value);
4052   return true;
4053 }
4054 
4055 /*
4056  * The intrinsic is a model of this pseudo-code:
4057  *
4058  * JfrThreadLocal* const tl = thread->jfr_thread_local();
4059  * if (carrierThread != thread) { // is virtual thread
4060  *   const u2 vthread_epoch_raw = java_lang_Thread::jfr_epoch(thread);
4061  *   bool excluded = vthread_epoch_raw & excluded_mask;
4062  *   AtomicAccess::store(&tl->_contextual_tid, java_lang_Thread::tid(thread));
4063  *   AtomicAccess::store(&tl->_contextual_thread_excluded, is_excluded);
4064  *   if (!excluded) {
4065  *     const u2 vthread_epoch = vthread_epoch_raw & epoch_mask;
4066  *     AtomicAccess::store(&tl->_vthread_epoch, vthread_epoch);
4067  *   }
4068  *   AtomicAccess::release_store(&tl->_vthread, true);
4069  *   return;
4070  * }
4071  * AtomicAccess::release_store(&tl->_vthread, false);
4072  */
4073 void LibraryCallKit::extend_setCurrentThread(Node* jt, Node* thread) {
4074   enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
4075 
4076   Node* input_memory_state = reset_memory();
4077   set_all_memory(input_memory_state);
4078 
4079   // The most significant bit of the u2 is used to denote thread exclusion
4080   Node* excluded_mask = _gvn.intcon(1 << 15);
4081   // The epoch generation is the range [1-32767]
4082   Node* epoch_mask = _gvn.intcon(32767);
4083 
4084   Node* const carrierThread = generate_current_thread(jt);
4085   // If thread != carrierThread, this is a virtual thread.
4086   Node* thread_cmp_carrierThread = _gvn.transform(new CmpPNode(thread, carrierThread));
4087   Node* test_thread_not_equal_carrierThread = _gvn.transform(new BoolNode(thread_cmp_carrierThread, BoolTest::ne));
4088   IfNode* iff_thread_not_equal_carrierThread =
4089     create_and_map_if(control(), test_thread_not_equal_carrierThread, PROB_FAIR, COUNT_UNKNOWN);
4090 
4091   Node* vthread_offset = basic_plus_adr(top(), jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_OFFSET_JFR));
4092 
4093   // False branch, is carrierThread.
4094   Node* thread_equal_carrierThread = _gvn.transform(new IfFalseNode(iff_thread_not_equal_carrierThread));
4095   // Store release
4096   Node* vthread_false_memory = store_to_memory(thread_equal_carrierThread, vthread_offset, _gvn.intcon(0), T_BOOLEAN, MemNode::release, true);
4097 
4098   set_all_memory(input_memory_state);
4099 
4100   // True branch, is virtual thread.
4101   Node* thread_not_equal_carrierThread = _gvn.transform(new IfTrueNode(iff_thread_not_equal_carrierThread));
4102   set_control(thread_not_equal_carrierThread);
4103 
4104   // Load the raw epoch value from the vthread.
4105   Node* epoch_offset = basic_plus_adr(thread, java_lang_Thread::jfr_epoch_offset());
4106   Node* epoch_raw = access_load_at(thread, epoch_offset, _gvn.type(epoch_offset)->is_ptr(), TypeInt::CHAR, T_CHAR,
4107                                    IN_HEAP | MO_UNORDERED | C2_MISMATCHED | C2_CONTROL_DEPENDENT_LOAD);
4108 
4109   // Mask off the excluded information from the epoch.
4110   Node * const is_excluded = _gvn.transform(new AndINode(epoch_raw, _gvn.transform(excluded_mask)));
4111 
4112   // Load the tid field from the thread.
4113   Node* tid = load_field_from_object(thread, "tid", "J");
4114 
4115   // Store the vthread tid to the jfr thread local.
4116   Node* thread_id_offset = basic_plus_adr(top(), jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_ID_OFFSET_JFR));
4117   Node* tid_memory = store_to_memory(control(), thread_id_offset, tid, T_LONG, MemNode::unordered, true);
4118 
4119   // Branch is_excluded to conditionalize updating the epoch .
4120   Node* excluded_cmp = _gvn.transform(new CmpINode(is_excluded, _gvn.transform(excluded_mask)));
4121   Node* test_excluded = _gvn.transform(new BoolNode(excluded_cmp, BoolTest::eq));
4122   IfNode* iff_excluded = create_and_map_if(control(), test_excluded, PROB_MIN, COUNT_UNKNOWN);
4123 
4124   // True branch, vthread is excluded, no need to write epoch info.
4125   Node* excluded = _gvn.transform(new IfTrueNode(iff_excluded));
4126   set_control(excluded);
4127   Node* vthread_is_excluded = _gvn.intcon(1);
4128 
4129   // False branch, vthread is included, update epoch info.
4130   Node* included = _gvn.transform(new IfFalseNode(iff_excluded));
4131   set_control(included);
4132   Node* vthread_is_included = _gvn.intcon(0);
4133 
4134   // Get epoch value.
4135   Node* epoch = _gvn.transform(new AndINode(epoch_raw, _gvn.transform(epoch_mask)));
4136 
4137   // Store the vthread epoch to the jfr thread local.
4138   Node* vthread_epoch_offset = basic_plus_adr(top(), jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_EPOCH_OFFSET_JFR));
4139   Node* included_memory = store_to_memory(control(), vthread_epoch_offset, epoch, T_CHAR, MemNode::unordered, true);
4140 
4141   RegionNode* excluded_rgn = new RegionNode(PATH_LIMIT);
4142   record_for_igvn(excluded_rgn);
4143   PhiNode* excluded_mem = new PhiNode(excluded_rgn, Type::MEMORY, TypePtr::BOTTOM);
4144   record_for_igvn(excluded_mem);
4145   PhiNode* exclusion = new PhiNode(excluded_rgn, TypeInt::BOOL);
4146   record_for_igvn(exclusion);
4147 
4148   // Merge the excluded control and memory.
4149   excluded_rgn->init_req(_true_path, excluded);
4150   excluded_rgn->init_req(_false_path, included);
4151   excluded_mem->init_req(_true_path, tid_memory);
4152   excluded_mem->init_req(_false_path, included_memory);
4153   exclusion->init_req(_true_path, _gvn.transform(vthread_is_excluded));
4154   exclusion->init_req(_false_path, _gvn.transform(vthread_is_included));
4155 
4156   // Set intermediate state.
4157   set_control(_gvn.transform(excluded_rgn));
4158   set_all_memory(excluded_mem);
4159 
4160   // Store the vthread exclusion state to the jfr thread local.
4161   Node* thread_local_excluded_offset = basic_plus_adr(top(), jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_EXCLUDED_OFFSET_JFR));
4162   store_to_memory(control(), thread_local_excluded_offset, _gvn.transform(exclusion), T_BOOLEAN, MemNode::unordered, true);
4163 
4164   // Store release
4165   Node * vthread_true_memory = store_to_memory(control(), vthread_offset, _gvn.intcon(1), T_BOOLEAN, MemNode::release, true);
4166 
4167   RegionNode* thread_compare_rgn = new RegionNode(PATH_LIMIT);
4168   record_for_igvn(thread_compare_rgn);
4169   PhiNode* thread_compare_mem = new PhiNode(thread_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
4170   record_for_igvn(thread_compare_mem);
4171   PhiNode* vthread = new PhiNode(thread_compare_rgn, TypeInt::BOOL);
4172   record_for_igvn(vthread);
4173 
4174   // Merge the thread_compare control and memory.
4175   thread_compare_rgn->init_req(_true_path, control());
4176   thread_compare_rgn->init_req(_false_path, thread_equal_carrierThread);
4177   thread_compare_mem->init_req(_true_path, vthread_true_memory);
4178   thread_compare_mem->init_req(_false_path, vthread_false_memory);
4179 
4180   // Set output state.
4181   set_control(_gvn.transform(thread_compare_rgn));
4182   set_all_memory(_gvn.transform(thread_compare_mem));
4183 }
4184 
4185 #endif // JFR_HAVE_INTRINSICS
4186 
4187 //------------------------inline_native_currentCarrierThread------------------
4188 bool LibraryCallKit::inline_native_currentCarrierThread() {
4189   Node* junk = nullptr;
4190   set_result(generate_current_thread(junk));
4191   return true;
4192 }
4193 
4194 //------------------------inline_native_currentThread------------------
4195 bool LibraryCallKit::inline_native_currentThread() {
4196   Node* junk = nullptr;
4197   set_result(generate_virtual_thread(junk));
4198   return true;
4199 }
4200 
4201 //------------------------inline_native_setVthread------------------
4202 bool LibraryCallKit::inline_native_setCurrentThread() {
4203   assert(C->method()->changes_current_thread(),
4204          "method changes current Thread but is not annotated ChangesCurrentThread");
4205   Node* arr = argument(1);
4206   Node* thread = _gvn.transform(new ThreadLocalNode());
4207   Node* p = basic_plus_adr(top()/*!oop*/, thread, in_bytes(JavaThread::vthread_offset()));
4208   Node* thread_obj_handle
4209     = make_load(nullptr, p, p->bottom_type()->is_ptr(), T_OBJECT, MemNode::unordered);
4210   thread_obj_handle = _gvn.transform(thread_obj_handle);
4211   const TypePtr *adr_type = _gvn.type(thread_obj_handle)->isa_ptr();
4212   access_store_at(nullptr, thread_obj_handle, adr_type, arr, _gvn.type(arr), T_OBJECT, IN_NATIVE | MO_UNORDERED);
4213 
4214   // Change the _monitor_owner_id of the JavaThread
4215   Node* tid = load_field_from_object(arr, "tid", "J");
4216   Node* monitor_owner_id_offset = basic_plus_adr(top(), thread, in_bytes(JavaThread::monitor_owner_id_offset()));
4217   store_to_memory(control(), monitor_owner_id_offset, tid, T_LONG, MemNode::unordered, true);
4218 
4219   JFR_ONLY(extend_setCurrentThread(thread, arr);)
4220   return true;
4221 }
4222 
4223 const Type* LibraryCallKit::scopedValueCache_type() {
4224   ciKlass* objects_klass = ciObjArrayKlass::make(env()->Object_klass());
4225   const TypeOopPtr* etype = TypeOopPtr::make_from_klass(env()->Object_klass());
4226   const TypeAry* arr0 = TypeAry::make(etype, TypeInt::POS, /* stable= */ false, /* flat= */ false, /* not_flat= */ true, /* not_null_free= */ true, true);
4227 
4228   // Because we create the scopedValue cache lazily we have to make the
4229   // type of the result BotPTR.
4230   bool xk = etype->klass_is_exact();
4231   const Type* objects_type = TypeAryPtr::make(TypePtr::BotPTR, arr0, objects_klass, xk, TypeAryPtr::Offset(0));
4232   return objects_type;
4233 }
4234 
4235 Node* LibraryCallKit::scopedValueCache_helper() {
4236   Node* thread = _gvn.transform(new ThreadLocalNode());
4237   Node* p = basic_plus_adr(top()/*!oop*/, thread, in_bytes(JavaThread::scopedValueCache_offset()));
4238   // We cannot use immutable_memory() because we might flip onto a
4239   // different carrier thread, at which point we'll need to use that
4240   // carrier thread's cache.
4241   // return _gvn.transform(LoadNode::make(_gvn, nullptr, immutable_memory(), p, p->bottom_type()->is_ptr(),
4242   //       TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered));
4243   return make_load(nullptr, p, p->bottom_type()->is_ptr(), T_ADDRESS, MemNode::unordered);
4244 }
4245 
4246 //------------------------inline_native_scopedValueCache------------------
4247 bool LibraryCallKit::inline_native_scopedValueCache() {
4248   Node* cache_obj_handle = scopedValueCache_helper();
4249   const Type* objects_type = scopedValueCache_type();
4250   set_result(access_load(cache_obj_handle, objects_type, T_OBJECT, IN_NATIVE));
4251 
4252   return true;
4253 }
4254 
4255 //------------------------inline_native_setScopedValueCache------------------
4256 bool LibraryCallKit::inline_native_setScopedValueCache() {
4257   Node* arr = argument(0);
4258   Node* cache_obj_handle = scopedValueCache_helper();
4259   const Type* objects_type = scopedValueCache_type();
4260 
4261   const TypePtr *adr_type = _gvn.type(cache_obj_handle)->isa_ptr();
4262   access_store_at(nullptr, cache_obj_handle, adr_type, arr, objects_type, T_OBJECT, IN_NATIVE | MO_UNORDERED);
4263 
4264   return true;
4265 }
4266 
4267 //------------------------inline_native_Continuation_pin and unpin-----------
4268 
4269 // Shared implementation routine for both pin and unpin.
4270 bool LibraryCallKit::inline_native_Continuation_pinning(bool unpin) {
4271   enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
4272 
4273   // Save input memory.
4274   Node* input_memory_state = reset_memory();
4275   set_all_memory(input_memory_state);
4276 
4277   // TLS
4278   Node* tls_ptr = _gvn.transform(new ThreadLocalNode());
4279   Node* last_continuation_offset = basic_plus_adr(top(), tls_ptr, in_bytes(JavaThread::cont_entry_offset()));
4280   Node* last_continuation = make_load(control(), last_continuation_offset, last_continuation_offset->get_ptr_type(), T_ADDRESS, MemNode::unordered);
4281 
4282   // Null check the last continuation object.
4283   Node* continuation_cmp_null = _gvn.transform(new CmpPNode(last_continuation, null()));
4284   Node* test_continuation_not_equal_null = _gvn.transform(new BoolNode(continuation_cmp_null, BoolTest::ne));
4285   IfNode* iff_continuation_not_equal_null = create_and_map_if(control(), test_continuation_not_equal_null, PROB_MAX, COUNT_UNKNOWN);
4286 
4287   // False path, last continuation is null.
4288   Node* continuation_is_null = _gvn.transform(new IfFalseNode(iff_continuation_not_equal_null));
4289 
4290   // True path, last continuation is not null.
4291   Node* continuation_is_not_null = _gvn.transform(new IfTrueNode(iff_continuation_not_equal_null));
4292 
4293   set_control(continuation_is_not_null);
4294 
4295   // Load the pin count from the last continuation.
4296   Node* pin_count_offset = basic_plus_adr(top(), last_continuation, in_bytes(ContinuationEntry::pin_count_offset()));
4297   Node* pin_count = make_load(control(), pin_count_offset, TypeInt::INT, T_INT, MemNode::unordered);
4298 
4299   // The loaded pin count is compared against a context specific rhs for over/underflow detection.
4300   Node* pin_count_rhs;
4301   if (unpin) {
4302     pin_count_rhs = _gvn.intcon(0);
4303   } else {
4304     pin_count_rhs = _gvn.intcon(UINT32_MAX);
4305   }
4306   Node* pin_count_cmp = _gvn.transform(new CmpUNode(_gvn.transform(pin_count), pin_count_rhs));
4307   Node* test_pin_count_over_underflow = _gvn.transform(new BoolNode(pin_count_cmp, BoolTest::eq));
4308   IfNode* iff_pin_count_over_underflow = create_and_map_if(control(), test_pin_count_over_underflow, PROB_MIN, COUNT_UNKNOWN);
4309 
4310   // True branch, pin count over/underflow.
4311   Node* pin_count_over_underflow = _gvn.transform(new IfTrueNode(iff_pin_count_over_underflow));
4312   {
4313     // Trap (but not deoptimize (Action_none)) and continue in the interpreter
4314     // which will throw IllegalStateException for pin count over/underflow.
4315     // No memory changed so far - we can use memory create by reset_memory()
4316     // at the beginning of this intrinsic. No need to call reset_memory() again.
4317     PreserveJVMState pjvms(this);
4318     set_control(pin_count_over_underflow);
4319     uncommon_trap(Deoptimization::Reason_intrinsic,
4320                   Deoptimization::Action_none);
4321     assert(stopped(), "invariant");
4322   }
4323 
4324   // False branch, no pin count over/underflow. Increment or decrement pin count and store back.
4325   Node* valid_pin_count = _gvn.transform(new IfFalseNode(iff_pin_count_over_underflow));
4326   set_control(valid_pin_count);
4327 
4328   Node* next_pin_count;
4329   if (unpin) {
4330     next_pin_count = _gvn.transform(new SubINode(pin_count, _gvn.intcon(1)));
4331   } else {
4332     next_pin_count = _gvn.transform(new AddINode(pin_count, _gvn.intcon(1)));
4333   }
4334 
4335   store_to_memory(control(), pin_count_offset, next_pin_count, T_INT, MemNode::unordered);
4336 
4337   // Result of top level CFG and Memory.
4338   RegionNode* result_rgn = new RegionNode(PATH_LIMIT);
4339   record_for_igvn(result_rgn);
4340   PhiNode* result_mem = new PhiNode(result_rgn, Type::MEMORY, TypePtr::BOTTOM);
4341   record_for_igvn(result_mem);
4342 
4343   result_rgn->init_req(_true_path, _gvn.transform(valid_pin_count));
4344   result_rgn->init_req(_false_path, _gvn.transform(continuation_is_null));
4345   result_mem->init_req(_true_path, _gvn.transform(reset_memory()));
4346   result_mem->init_req(_false_path, _gvn.transform(input_memory_state));
4347 
4348   // Set output state.
4349   set_control(_gvn.transform(result_rgn));
4350   set_all_memory(_gvn.transform(result_mem));
4351 
4352   return true;
4353 }
4354 
4355 //---------------------------load_mirror_from_klass----------------------------
4356 // Given a klass oop, load its java mirror (a java.lang.Class oop).
4357 Node* LibraryCallKit::load_mirror_from_klass(Node* klass) {
4358   Node* p = basic_plus_adr(top(), klass, in_bytes(Klass::java_mirror_offset()));
4359   Node* load = make_load(nullptr, p, TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered);
4360   // mirror = ((OopHandle)mirror)->resolve();
4361   return access_load(load, TypeInstPtr::MIRROR, T_OBJECT, IN_NATIVE);
4362 }
4363 
4364 //-----------------------load_klass_from_mirror_common-------------------------
4365 // Given a java mirror (a java.lang.Class oop), load its corresponding klass oop.
4366 // Test the klass oop for null (signifying a primitive Class like Integer.TYPE),
4367 // and branch to the given path on the region.
4368 // If never_see_null, take an uncommon trap on null, so we can optimistically
4369 // compile for the non-null case.
4370 // If the region is null, force never_see_null = true.
4371 Node* LibraryCallKit::load_klass_from_mirror_common(Node* mirror,
4372                                                     bool never_see_null,
4373                                                     RegionNode* region,
4374                                                     int null_path,
4375                                                     int offset) {
4376   if (region == nullptr)  never_see_null = true;
4377   Node* p = basic_plus_adr(mirror, offset);
4378   const TypeKlassPtr*  kls_type = TypeInstKlassPtr::OBJECT_OR_NULL;
4379   Node* kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), p, TypeRawPtr::BOTTOM, kls_type));
4380   Node* null_ctl = top();
4381   kls = null_check_oop(kls, &null_ctl, never_see_null);
4382   if (region != nullptr) {
4383     // Set region->in(null_path) if the mirror is a primitive (e.g, int.class).
4384     region->init_req(null_path, null_ctl);
4385   } else {
4386     assert(null_ctl == top(), "no loose ends");
4387   }
4388   return kls;
4389 }
4390 
4391 //--------------------(inline_native_Class_query helpers)---------------------
4392 // Use this for JVM_ACC_INTERFACE.
4393 // Fall through if (mods & mask) == bits, take the guard otherwise.
4394 Node* LibraryCallKit::generate_klass_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region,
4395                                                  ByteSize offset, const Type* type, BasicType bt) {
4396   // Branch around if the given klass has the given modifier bit set.
4397   // Like generate_guard, adds a new path onto the region.
4398   Node* modp = basic_plus_adr(top(), kls, in_bytes(offset));
4399   Node* mods = make_load(nullptr, modp, type, bt, MemNode::unordered);
4400   Node* mask = intcon(modifier_mask);
4401   Node* bits = intcon(modifier_bits);
4402   Node* mbit = _gvn.transform(new AndINode(mods, mask));
4403   Node* cmp  = _gvn.transform(new CmpINode(mbit, bits));
4404   Node* bol  = _gvn.transform(new BoolNode(cmp, BoolTest::ne));
4405   return generate_fair_guard(bol, region);
4406 }
4407 
4408 Node* LibraryCallKit::generate_interface_guard(Node* kls, RegionNode* region) {
4409   return generate_klass_flags_guard(kls, JVM_ACC_INTERFACE, 0, region,
4410                                     InstanceKlass::access_flags_offset(), TypeInt::CHAR, T_CHAR);
4411 }
4412 
4413 // Use this for testing if Klass is_hidden, has_finalizer, and is_cloneable_fast.
4414 Node* LibraryCallKit::generate_misc_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region) {
4415   return generate_klass_flags_guard(kls, modifier_mask, modifier_bits, region,
4416                                     Klass::misc_flags_offset(), TypeInt::UBYTE, T_BOOLEAN);
4417 }
4418 
4419 Node* LibraryCallKit::generate_hidden_class_guard(Node* kls, RegionNode* region) {
4420   return generate_misc_flags_guard(kls, KlassFlags::_misc_is_hidden_class, 0, region);
4421 }
4422 
4423 //-------------------------inline_native_Class_query-------------------
4424 bool LibraryCallKit::inline_native_Class_query(vmIntrinsics::ID id) {
4425   const Type* return_type = TypeInt::BOOL;
4426   Node* prim_return_value = top();  // what happens if it's a primitive class?
4427   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
4428   bool expect_prim = false;     // most of these guys expect to work on refs
4429 
4430   enum { _normal_path = 1, _prim_path = 2, PATH_LIMIT };
4431 
4432   Node* mirror = argument(0);
4433   Node* obj    = top();
4434 
4435   switch (id) {
4436   case vmIntrinsics::_isInstance:
4437     // nothing is an instance of a primitive type
4438     prim_return_value = intcon(0);
4439     obj = argument(1);
4440     break;
4441   case vmIntrinsics::_isHidden:
4442     prim_return_value = intcon(0);
4443     break;
4444   case vmIntrinsics::_getSuperclass:
4445     prim_return_value = null();
4446     return_type = TypeInstPtr::MIRROR->cast_to_ptr_type(TypePtr::BotPTR);
4447     break;
4448   default:
4449     fatal_unexpected_iid(id);
4450     break;
4451   }
4452 
4453   const TypeInstPtr* mirror_con = _gvn.type(mirror)->isa_instptr();
4454   if (mirror_con == nullptr)  return false;  // cannot happen?
4455 
4456 #ifndef PRODUCT
4457   if (C->print_intrinsics() || C->print_inlining()) {
4458     ciType* k = mirror_con->java_mirror_type();
4459     if (k) {
4460       tty->print("Inlining %s on constant Class ", vmIntrinsics::name_at(intrinsic_id()));
4461       k->print_name();
4462       tty->cr();
4463     }
4464   }
4465 #endif
4466 
4467   // Null-check the mirror, and the mirror's klass ptr (in case it is a primitive).
4468   RegionNode* region = new RegionNode(PATH_LIMIT);
4469   record_for_igvn(region);
4470   PhiNode* phi = new PhiNode(region, return_type);
4471 
4472   // The mirror will never be null of Reflection.getClassAccessFlags, however
4473   // it may be null for Class.isInstance or Class.getModifiers. Throw a NPE
4474   // if it is. See bug 4774291.
4475 
4476   // For Reflection.getClassAccessFlags(), the null check occurs in
4477   // the wrong place; see inline_unsafe_access(), above, for a similar
4478   // situation.
4479   mirror = null_check(mirror);
4480   // If mirror or obj is dead, only null-path is taken.
4481   if (stopped())  return true;
4482 
4483   if (expect_prim)  never_see_null = false;  // expect nulls (meaning prims)
4484 
4485   // Now load the mirror's klass metaobject, and null-check it.
4486   // Side-effects region with the control path if the klass is null.
4487   Node* kls = load_klass_from_mirror(mirror, never_see_null, region, _prim_path);
4488   // If kls is null, we have a primitive mirror.
4489   phi->init_req(_prim_path, prim_return_value);
4490   if (stopped()) { set_result(region, phi); return true; }
4491   bool safe_for_replace = (region->in(_prim_path) == top());
4492 
4493   Node* p;  // handy temp
4494   Node* null_ctl;
4495 
4496   // Now that we have the non-null klass, we can perform the real query.
4497   // For constant classes, the query will constant-fold in LoadNode::Value.
4498   Node* query_value = top();
4499   switch (id) {
4500   case vmIntrinsics::_isInstance:
4501     // nothing is an instance of a primitive type
4502     query_value = gen_instanceof(obj, kls, safe_for_replace);
4503     break;
4504 
4505   case vmIntrinsics::_isHidden:
4506     // (To verify this code sequence, check the asserts in JVM_IsHiddenClass.)
4507     if (generate_hidden_class_guard(kls, region) != nullptr)
4508       // A guard was added.  If the guard is taken, it was an hidden class.
4509       phi->add_req(intcon(1));
4510     // If we fall through, it's a plain class.
4511     query_value = intcon(0);
4512     break;
4513 
4514 
4515   case vmIntrinsics::_getSuperclass:
4516     // The rules here are somewhat unfortunate, but we can still do better
4517     // with random logic than with a JNI call.
4518     // Interfaces store null or Object as _super, but must report null.
4519     // Arrays store an intermediate super as _super, but must report Object.
4520     // Other types can report the actual _super.
4521     // (To verify this code sequence, check the asserts in JVM_IsInterface.)
4522     if (generate_array_guard(kls, region) != nullptr) {
4523       // A guard was added.  If the guard is taken, it was an array.
4524       phi->add_req(makecon(TypeInstPtr::make(env()->Object_klass()->java_mirror())));
4525     }
4526     // Check for interface after array since this checks AccessFlags offset into InstanceKlass.
4527     // In other words, we are accessing subtype-specific information, so we need to determine the subtype first.
4528     if (generate_interface_guard(kls, region) != nullptr) {
4529       // A guard was added.  If the guard is taken, it was an interface.
4530       phi->add_req(null());
4531     }
4532     // If we fall through, it's a plain class.  Get its _super.
4533     if (!stopped()) {
4534       p = basic_plus_adr(top(), kls, in_bytes(Klass::super_offset()));
4535       kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), p, TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
4536       null_ctl = top();
4537       kls = null_check_oop(kls, &null_ctl);
4538       if (null_ctl != top()) {
4539         // If the guard is taken, Object.superClass is null (both klass and mirror).
4540         region->add_req(null_ctl);
4541         phi   ->add_req(null());
4542       }
4543       if (!stopped()) {
4544         query_value = load_mirror_from_klass(kls);
4545       }
4546     }
4547     break;
4548 
4549   default:
4550     fatal_unexpected_iid(id);
4551     break;
4552   }
4553 
4554   // Fall-through is the normal case of a query to a real class.
4555   phi->init_req(1, query_value);
4556   region->init_req(1, control());
4557 
4558   C->set_has_split_ifs(true); // Has chance for split-if optimization
4559   set_result(region, phi);
4560   return true;
4561 }
4562 
4563 
4564 //-------------------------inline_Class_cast-------------------
4565 bool LibraryCallKit::inline_Class_cast() {
4566   Node* mirror = argument(0); // Class
4567   Node* obj    = argument(1);
4568   const TypeInstPtr* mirror_con = _gvn.type(mirror)->isa_instptr();
4569   if (mirror_con == nullptr) {
4570     return false;  // dead path (mirror->is_top()).
4571   }
4572   if (obj == nullptr || obj->is_top()) {
4573     return false;  // dead path
4574   }
4575   const TypeOopPtr* tp = _gvn.type(obj)->isa_oopptr();
4576 
4577   // First, see if Class.cast() can be folded statically.
4578   // java_mirror_type() returns non-null for compile-time Class constants.
4579   ciType* tm = mirror_con->java_mirror_type();
4580   if (tm != nullptr && tm->is_klass() &&
4581       tp != nullptr) {
4582     if (!tp->is_loaded()) {
4583       // Don't use intrinsic when class is not loaded.
4584       return false;
4585     } else {
4586       const TypeKlassPtr* tklass = TypeKlassPtr::make(tm->as_klass(), Type::trust_interfaces);
4587       int static_res = C->static_subtype_check(tklass, tp->as_klass_type());
4588       if (static_res == Compile::SSC_always_true) {
4589         // isInstance() is true - fold the code.
4590         set_result(obj);
4591         return true;
4592       } else if (static_res == Compile::SSC_always_false) {
4593         // Don't use intrinsic, have to throw ClassCastException.
4594         // If the reference is null, the non-intrinsic bytecode will
4595         // be optimized appropriately.
4596         return false;
4597       }
4598     }
4599   }
4600 
4601   // Bailout intrinsic and do normal inlining if exception path is frequent.
4602   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
4603     return false;
4604   }
4605 
4606   // Generate dynamic checks.
4607   // Class.cast() is java implementation of _checkcast bytecode.
4608   // Do checkcast (Parse::do_checkcast()) optimizations here.
4609 
4610   mirror = null_check(mirror);
4611   // If mirror is dead, only null-path is taken.
4612   if (stopped()) {
4613     return true;
4614   }
4615 
4616   // Not-subtype or the mirror's klass ptr is nullptr (in case it is a primitive).
4617   enum { _bad_type_path = 1, _prim_path = 2, _npe_path = 3, PATH_LIMIT };
4618   RegionNode* region = new RegionNode(PATH_LIMIT);
4619   record_for_igvn(region);
4620 
4621   // Now load the mirror's klass metaobject, and null-check it.
4622   // If kls is null, we have a primitive mirror and
4623   // nothing is an instance of a primitive type.
4624   Node* kls = load_klass_from_mirror(mirror, false, region, _prim_path);
4625 
4626   Node* res = top();
4627   Node* io = i_o();
4628   Node* mem = merged_memory();
4629   if (!stopped()) {
4630 
4631     Node* bad_type_ctrl = top();
4632     // Do checkcast optimizations.
4633     res = gen_checkcast(obj, kls, &bad_type_ctrl);
4634     region->init_req(_bad_type_path, bad_type_ctrl);
4635   }
4636   if (region->in(_prim_path) != top() ||
4637       region->in(_bad_type_path) != top() ||
4638       region->in(_npe_path) != top()) {
4639     // Let Interpreter throw ClassCastException.
4640     PreserveJVMState pjvms(this);
4641     set_control(_gvn.transform(region));
4642     // Set IO and memory because gen_checkcast may override them when buffering inline types
4643     set_i_o(io);
4644     set_all_memory(mem);
4645     uncommon_trap(Deoptimization::Reason_intrinsic,
4646                   Deoptimization::Action_maybe_recompile);
4647   }
4648   if (!stopped()) {
4649     set_result(res);
4650   }
4651   return true;
4652 }
4653 
4654 
4655 //--------------------------inline_native_subtype_check------------------------
4656 // This intrinsic takes the JNI calls out of the heart of
4657 // UnsafeFieldAccessorImpl.set, which improves Field.set, readObject, etc.
4658 bool LibraryCallKit::inline_native_subtype_check() {
4659   // Pull both arguments off the stack.
4660   Node* args[2];                // two java.lang.Class mirrors: superc, subc
4661   args[0] = argument(0);
4662   args[1] = argument(1);
4663   Node* klasses[2];             // corresponding Klasses: superk, subk
4664   klasses[0] = klasses[1] = top();
4665 
4666   enum {
4667     // A full decision tree on {superc is prim, subc is prim}:
4668     _prim_0_path = 1,           // {P,N} => false
4669                                 // {P,P} & superc!=subc => false
4670     _prim_same_path,            // {P,P} & superc==subc => true
4671     _prim_1_path,               // {N,P} => false
4672     _ref_subtype_path,          // {N,N} & subtype check wins => true
4673     _both_ref_path,             // {N,N} & subtype check loses => false
4674     PATH_LIMIT
4675   };
4676 
4677   RegionNode* region = new RegionNode(PATH_LIMIT);
4678   RegionNode* prim_region = new RegionNode(2);
4679   Node*       phi    = new PhiNode(region, TypeInt::BOOL);
4680   record_for_igvn(region);
4681   record_for_igvn(prim_region);
4682 
4683   const TypePtr* adr_type = TypeRawPtr::BOTTOM;   // memory type of loads
4684   const TypeKlassPtr* kls_type = TypeInstKlassPtr::OBJECT_OR_NULL;
4685   int class_klass_offset = java_lang_Class::klass_offset();
4686 
4687   // First null-check both mirrors and load each mirror's klass metaobject.
4688   int which_arg;
4689   for (which_arg = 0; which_arg <= 1; which_arg++) {
4690     Node* arg = args[which_arg];
4691     arg = null_check(arg);
4692     if (stopped())  break;
4693     args[which_arg] = arg;
4694 
4695     Node* p = basic_plus_adr(arg, class_klass_offset);
4696     Node* kls = LoadKlassNode::make(_gvn, immutable_memory(), p, adr_type, kls_type);
4697     klasses[which_arg] = _gvn.transform(kls);
4698   }
4699 
4700   // Having loaded both klasses, test each for null.
4701   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
4702   for (which_arg = 0; which_arg <= 1; which_arg++) {
4703     Node* kls = klasses[which_arg];
4704     Node* null_ctl = top();
4705     kls = null_check_oop(kls, &null_ctl, never_see_null);
4706     if (which_arg == 0) {
4707       prim_region->init_req(1, null_ctl);
4708     } else {
4709       region->init_req(_prim_1_path, null_ctl);
4710     }
4711     if (stopped())  break;
4712     klasses[which_arg] = kls;
4713   }
4714 
4715   if (!stopped()) {
4716     // now we have two reference types, in klasses[0..1]
4717     Node* subk   = klasses[1];  // the argument to isAssignableFrom
4718     Node* superk = klasses[0];  // the receiver
4719     region->set_req(_both_ref_path, gen_subtype_check(subk, superk));
4720     region->set_req(_ref_subtype_path, control());
4721   }
4722 
4723   // If both operands are primitive (both klasses null), then
4724   // we must return true when they are identical primitives.
4725   // It is convenient to test this after the first null klass check.
4726   // This path is also used if superc is a value mirror.
4727   set_control(_gvn.transform(prim_region));
4728   if (!stopped()) {
4729     // Since superc is primitive, make a guard for the superc==subc case.
4730     Node* cmp_eq = _gvn.transform(new CmpPNode(args[0], args[1]));
4731     Node* bol_eq = _gvn.transform(new BoolNode(cmp_eq, BoolTest::eq));
4732     generate_fair_guard(bol_eq, region);
4733     if (region->req() == PATH_LIMIT+1) {
4734       // A guard was added.  If the added guard is taken, superc==subc.
4735       region->swap_edges(PATH_LIMIT, _prim_same_path);
4736       region->del_req(PATH_LIMIT);
4737     }
4738     region->set_req(_prim_0_path, control()); // Not equal after all.
4739   }
4740 
4741   // these are the only paths that produce 'true':
4742   phi->set_req(_prim_same_path,   intcon(1));
4743   phi->set_req(_ref_subtype_path, intcon(1));
4744 
4745   // pull together the cases:
4746   assert(region->req() == PATH_LIMIT, "sane region");
4747   for (uint i = 1; i < region->req(); i++) {
4748     Node* ctl = region->in(i);
4749     if (ctl == nullptr || ctl == top()) {
4750       region->set_req(i, top());
4751       phi   ->set_req(i, top());
4752     } else if (phi->in(i) == nullptr) {
4753       phi->set_req(i, intcon(0)); // all other paths produce 'false'
4754     }
4755   }
4756 
4757   set_control(_gvn.transform(region));
4758   set_result(_gvn.transform(phi));
4759   return true;
4760 }
4761 
4762 //---------------------generate_array_guard_common------------------------
4763 Node* LibraryCallKit::generate_array_guard_common(Node* kls, RegionNode* region, ArrayKind kind, Node** obj) {
4764 
4765   if (stopped()) {
4766     return nullptr;
4767   }
4768 
4769   // Like generate_guard, adds a new path onto the region.
4770   jint  layout_con = 0;
4771   Node* layout_val = get_layout_helper(kls, layout_con);
4772   if (layout_val == nullptr) {
4773     bool query = 0;
4774     switch(kind) {
4775       case RefArray:       query = Klass::layout_helper_is_refArray(layout_con); break;
4776       case NonRefArray:    query = !Klass::layout_helper_is_refArray(layout_con); break;
4777       case TypeArray:      query = Klass::layout_helper_is_typeArray(layout_con); break;
4778       case AnyArray:       query = Klass::layout_helper_is_array(layout_con); break;
4779       case NonArray:       query = !Klass::layout_helper_is_array(layout_con); break;
4780       default:
4781         ShouldNotReachHere();
4782     }
4783     if (!query) {
4784       return nullptr;                       // never a branch
4785     } else {                             // always a branch
4786       Node* always_branch = control();
4787       if (region != nullptr)
4788         region->add_req(always_branch);
4789       set_control(top());
4790       return always_branch;
4791     }
4792   }
4793   unsigned int value = 0;
4794   BoolTest::mask btest = BoolTest::illegal;
4795   switch(kind) {
4796     case RefArray:
4797     case NonRefArray: {
4798       value = Klass::_lh_array_tag_ref_value;
4799       layout_val = _gvn.transform(new RShiftINode(layout_val, intcon(Klass::_lh_array_tag_shift)));
4800       btest = (kind == RefArray) ? BoolTest::eq : BoolTest::ne;
4801       break;
4802     }
4803     case TypeArray: {
4804       value = Klass::_lh_array_tag_type_value;
4805       layout_val = _gvn.transform(new RShiftINode(layout_val, intcon(Klass::_lh_array_tag_shift)));
4806       btest = BoolTest::eq;
4807       break;
4808     }
4809     case AnyArray:    value = Klass::_lh_neutral_value; btest = BoolTest::lt; break;
4810     case NonArray:    value = Klass::_lh_neutral_value; btest = BoolTest::gt; break;
4811     default:
4812       ShouldNotReachHere();
4813   }
4814   // Now test the correct condition.
4815   jint nval = (jint)value;
4816   Node* cmp = _gvn.transform(new CmpINode(layout_val, intcon(nval)));
4817   Node* bol = _gvn.transform(new BoolNode(cmp, btest));
4818   Node* ctrl = generate_fair_guard(bol, region);
4819   Node* is_array_ctrl = kind == NonArray ? control() : ctrl;
4820   if (obj != nullptr && is_array_ctrl != nullptr && is_array_ctrl != top()) {
4821     // Keep track of the fact that 'obj' is an array to prevent
4822     // array specific accesses from floating above the guard.
4823     *obj = _gvn.transform(new CastPPNode(is_array_ctrl, *obj, TypeAryPtr::BOTTOM));
4824   }
4825   return ctrl;
4826 }
4827 
4828 // public static native Object[] ValueClass::newNullRestrictedAtomicArray(Class<?> componentType, int length, Object initVal);
4829 // public static native Object[] ValueClass::newNullRestrictedNonAtomicArray(Class<?> componentType, int length, Object initVal);
4830 // public static native Object[] ValueClass::newNullableAtomicArray(Class<?> componentType, int length);
4831 bool LibraryCallKit::inline_newArray(bool null_free, bool atomic) {
4832   assert(null_free || atomic, "nullable implies atomic");
4833   Node* componentType = argument(0);
4834   Node* length = argument(1);
4835   Node* init_val = null_free ? argument(2) : nullptr;
4836 
4837   const TypeInstPtr* tp = _gvn.type(componentType)->isa_instptr();
4838   if (tp != nullptr) {
4839     ciInstanceKlass* ik = tp->instance_klass();
4840     if (ik == C->env()->Class_klass()) {
4841       ciType* t = tp->java_mirror_type();
4842       if (t != nullptr && t->is_inlinetype()) {
4843 
4844         ciArrayKlass* array_klass = ciArrayKlass::make(t, null_free, atomic, true);
4845         assert(array_klass->is_elem_null_free() == null_free, "inconsistency");
4846 
4847         // TOOD 8350865 ZGC needs card marks on initializing oop stores
4848         if (UseZGC && null_free && !array_klass->is_flat_array_klass()) {
4849           return false;
4850         }
4851 
4852         if (array_klass->is_loaded() && array_klass->element_klass()->as_inline_klass()->is_initialized()) {
4853           const TypeAryKlassPtr* array_klass_type = TypeAryKlassPtr::make(array_klass, Type::trust_interfaces);
4854           if (null_free) {
4855             if (init_val->is_InlineType()) {
4856               if (array_klass_type->is_flat() && init_val->as_InlineType()->is_all_zero(&gvn(), /* flat */ true)) {
4857                 // Zeroing is enough because the init value is the all-zero value
4858                 init_val = nullptr;
4859               } else {
4860                 init_val = init_val->as_InlineType()->buffer(this);
4861               }
4862             }
4863             // TODO 8350865 Should we add a check of the init_val type (maybe in debug only + halt)?
4864             // If we insert a checkcast here, we can be sure that init_val is an InlineTypeNode, so
4865             // when we folded a field load from an allocation (e.g. during escape analysis), we can
4866             // remove the check init_val->is_InlineType().
4867           }
4868           Node* obj = new_array(makecon(array_klass_type), length, 0, nullptr, false, init_val);
4869           const TypeAryPtr* arytype = gvn().type(obj)->is_aryptr();
4870           assert(arytype->is_null_free() == null_free, "inconsistency");
4871           assert(arytype->is_not_null_free() == !null_free, "inconsistency");
4872           set_result(obj);
4873           return true;
4874         }
4875       }
4876     }
4877   }
4878   return false;
4879 }
4880 
4881 // public static native boolean ValueClass::isFlatArray(Object array);
4882 // public static native boolean ValueClass::isNullRestrictedArray(Object array);
4883 // public static native boolean ValueClass::isAtomicArray(Object array);
4884 bool LibraryCallKit::inline_getArrayProperties(ArrayPropertiesCheck check) {
4885   Node* array = argument(0);
4886 
4887   Node* bol;
4888   switch(check) {
4889     case IsFlat:
4890       // TODO 8350865 Use the object version here instead of loading the klass
4891       // 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
4892       bol = flat_array_test(load_object_klass(array));
4893       break;
4894     case IsNullRestricted:
4895       bol = null_free_array_test(array);
4896       break;
4897     case IsAtomic:
4898       // TODO 8350865 Implement this. It's a bit more complicated, see conditions in JVM_IsAtomicArray
4899       // Enable TestIntrinsics::test87/88 once this is implemented
4900       // bol = null_free_atomic_array_test
4901       return false;
4902     default:
4903       ShouldNotReachHere();
4904   }
4905 
4906   Node* res = gvn().transform(new CMoveINode(bol, intcon(0), intcon(1), TypeInt::BOOL));
4907   set_result(res);
4908   return true;
4909 }
4910 
4911 // Load the default refined array klass from an ObjArrayKlass. This relies on the first entry in the
4912 // '_next_refined_array_klass' linked list being the default (see ObjArrayKlass::klass_with_properties).
4913 Node* LibraryCallKit::load_default_refined_array_klass(Node* klass_node, bool type_array_guard) {
4914   RegionNode* region = new RegionNode(2);
4915   Node* phi = new PhiNode(region, TypeInstKlassPtr::OBJECT_OR_NULL);
4916 
4917   if (type_array_guard) {
4918     generate_typeArray_guard(klass_node, region);
4919     if (region->req() == 3) {
4920       phi->add_req(klass_node);
4921     }
4922   }
4923   Node* adr_refined_klass = basic_plus_adr(top(), klass_node, in_bytes(ObjArrayKlass::next_refined_array_klass_offset()));
4924   Node* refined_klass = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), adr_refined_klass, TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
4925 
4926   // Can be null if not initialized yet, just deopt
4927   Node* null_ctl = top();
4928   refined_klass = null_check_oop(refined_klass, &null_ctl, /* never_see_null= */ true);
4929 
4930   region->init_req(1, control());
4931   phi->init_req(1, refined_klass);
4932 
4933   set_control(_gvn.transform(region));
4934   return _gvn.transform(phi);
4935 }
4936 
4937 // Load the non-refined array klass from an ObjArrayKlass.
4938 Node* LibraryCallKit::load_non_refined_array_klass(Node* klass_node) {
4939   const TypeAryKlassPtr* ary_klass_ptr = _gvn.type(klass_node)->isa_aryklassptr();
4940   if (ary_klass_ptr != nullptr && ary_klass_ptr->klass_is_exact()) {
4941     return _gvn.makecon(ary_klass_ptr->cast_to_refined_array_klass_ptr(false));
4942   }
4943 
4944   RegionNode* region = new RegionNode(2);
4945   Node* phi = new PhiNode(region, TypeInstKlassPtr::OBJECT);
4946 
4947   generate_typeArray_guard(klass_node, region);
4948   if (region->req() == 3) {
4949     phi->add_req(klass_node);
4950   }
4951   Node* super_adr = basic_plus_adr(top(), klass_node, in_bytes(Klass::super_offset()));
4952   Node* super_klass = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), super_adr, TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT));
4953 
4954   region->init_req(1, control());
4955   phi->init_req(1, super_klass);
4956 
4957   set_control(_gvn.transform(region));
4958   return _gvn.transform(phi);
4959 }
4960 
4961 //-----------------------inline_native_newArray--------------------------
4962 // private static native Object java.lang.reflect.Array.newArray(Class<?> componentType, int length);
4963 // private        native Object Unsafe.allocateUninitializedArray0(Class<?> cls, int size);
4964 bool LibraryCallKit::inline_unsafe_newArray(bool uninitialized) {
4965   Node* mirror;
4966   Node* count_val;
4967   if (uninitialized) {
4968     null_check_receiver();
4969     mirror    = argument(1);
4970     count_val = argument(2);
4971   } else {
4972     mirror    = argument(0);
4973     count_val = argument(1);
4974   }
4975 
4976   mirror = null_check(mirror);
4977   // If mirror or obj is dead, only null-path is taken.
4978   if (stopped())  return true;
4979 
4980   enum { _normal_path = 1, _slow_path = 2, PATH_LIMIT };
4981   RegionNode* result_reg = new RegionNode(PATH_LIMIT);
4982   PhiNode*    result_val = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
4983   PhiNode*    result_io  = new PhiNode(result_reg, Type::ABIO);
4984   PhiNode*    result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
4985 
4986   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
4987   Node* klass_node = load_array_klass_from_mirror(mirror, never_see_null,
4988                                                   result_reg, _slow_path);
4989   Node* normal_ctl   = control();
4990   Node* no_array_ctl = result_reg->in(_slow_path);
4991 
4992   // Generate code for the slow case.  We make a call to newArray().
4993   set_control(no_array_ctl);
4994   if (!stopped()) {
4995     // Either the input type is void.class, or else the
4996     // array klass has not yet been cached.  Either the
4997     // ensuing call will throw an exception, or else it
4998     // will cache the array klass for next time.
4999     PreserveJVMState pjvms(this);
5000     CallJavaNode* slow_call = nullptr;
5001     if (uninitialized) {
5002       // Generate optimized virtual call (holder class 'Unsafe' is final)
5003       slow_call = generate_method_call(vmIntrinsics::_allocateUninitializedArray, false, false, true);
5004     } else {
5005       slow_call = generate_method_call_static(vmIntrinsics::_newArray, true);
5006     }
5007     Node* slow_result = set_results_for_java_call(slow_call);
5008     // this->control() comes from set_results_for_java_call
5009     result_reg->set_req(_slow_path, control());
5010     result_val->set_req(_slow_path, slow_result);
5011     result_io ->set_req(_slow_path, i_o());
5012     result_mem->set_req(_slow_path, reset_memory());
5013   }
5014 
5015   set_control(normal_ctl);
5016   if (!stopped()) {
5017     // Normal case:  The array type has been cached in the java.lang.Class.
5018     // The following call works fine even if the array type is polymorphic.
5019     // It could be a dynamic mix of int[], boolean[], Object[], etc.
5020 
5021     klass_node = load_default_refined_array_klass(klass_node);
5022 
5023     Node* obj = new_array(klass_node, count_val, 0);  // no arguments to push
5024     result_reg->init_req(_normal_path, control());
5025     result_val->init_req(_normal_path, obj);
5026     result_io ->init_req(_normal_path, i_o());
5027     result_mem->init_req(_normal_path, reset_memory());
5028 
5029     if (uninitialized) {
5030       // Mark the allocation so that zeroing is skipped
5031       AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(obj);
5032       alloc->maybe_set_complete(&_gvn);
5033     }
5034   }
5035 
5036   // Return the combined state.
5037   set_i_o(        _gvn.transform(result_io)  );
5038   set_all_memory( _gvn.transform(result_mem));
5039 
5040   C->set_has_split_ifs(true); // Has chance for split-if optimization
5041   set_result(result_reg, result_val);
5042   return true;
5043 }
5044 
5045 //----------------------inline_native_getLength--------------------------
5046 // public static native int java.lang.reflect.Array.getLength(Object array);
5047 bool LibraryCallKit::inline_native_getLength() {
5048   if (too_many_traps(Deoptimization::Reason_intrinsic))  return false;
5049 
5050   Node* array = null_check(argument(0));
5051   // If array is dead, only null-path is taken.
5052   if (stopped())  return true;
5053 
5054   // Deoptimize if it is a non-array.
5055   Node* non_array = generate_non_array_guard(load_object_klass(array), nullptr, &array);
5056 
5057   if (non_array != nullptr) {
5058     PreserveJVMState pjvms(this);
5059     set_control(non_array);
5060     uncommon_trap(Deoptimization::Reason_intrinsic,
5061                   Deoptimization::Action_maybe_recompile);
5062   }
5063 
5064   // If control is dead, only non-array-path is taken.
5065   if (stopped())  return true;
5066 
5067   // The works fine even if the array type is polymorphic.
5068   // It could be a dynamic mix of int[], boolean[], Object[], etc.
5069   Node* result = load_array_length(array);
5070 
5071   C->set_has_split_ifs(true);  // Has chance for split-if optimization
5072   set_result(result);
5073   return true;
5074 }
5075 
5076 //------------------------inline_array_copyOf----------------------------
5077 // public static <T,U> T[] java.util.Arrays.copyOf(     U[] original, int newLength,         Class<? extends T[]> newType);
5078 // public static <T,U> T[] java.util.Arrays.copyOfRange(U[] original, int from,      int to, Class<? extends T[]> newType);
5079 bool LibraryCallKit::inline_array_copyOf(bool is_copyOfRange) {
5080   if (too_many_traps(Deoptimization::Reason_intrinsic))  return false;
5081 
5082   // Get the arguments.
5083   Node* original          = argument(0);
5084   Node* start             = is_copyOfRange? argument(1): intcon(0);
5085   Node* end               = is_copyOfRange? argument(2): argument(1);
5086   Node* array_type_mirror = is_copyOfRange? argument(3): argument(2);
5087 
5088   Node* newcopy = nullptr;
5089 
5090   // Set the original stack and the reexecute bit for the interpreter to reexecute
5091   // the bytecode that invokes Arrays.copyOf if deoptimization happens.
5092   { PreserveReexecuteState preexecs(this);
5093     jvms()->set_should_reexecute(true);
5094 
5095     array_type_mirror = null_check(array_type_mirror);
5096     original          = null_check(original);
5097 
5098     // Check if a null path was taken unconditionally.
5099     if (stopped())  return true;
5100 
5101     Node* orig_length = load_array_length(original);
5102 
5103     Node* klass_node = load_klass_from_mirror(array_type_mirror, false, nullptr, 0);
5104     klass_node = null_check(klass_node);
5105 
5106     RegionNode* bailout = new RegionNode(1);
5107     record_for_igvn(bailout);
5108 
5109     // Despite the generic type of Arrays.copyOf, the mirror might be int, int[], etc.
5110     // Bail out if that is so.
5111     // Inline type array may have object field that would require a
5112     // write barrier. Conservatively, go to slow path.
5113     // TODO 8251971: Optimize for the case when flat src/dst are later found
5114     // to not contain oops (i.e., move this check to the macro expansion phase).
5115     BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
5116     const TypeAryPtr* orig_t = _gvn.type(original)->isa_aryptr();
5117     const TypeKlassPtr* tklass = _gvn.type(klass_node)->is_klassptr();
5118     bool exclude_flat = UseArrayFlattening && bs->array_copy_requires_gc_barriers(true, T_OBJECT, false, false, BarrierSetC2::Parsing) &&
5119                         // Can src array be flat and contain oops?
5120                         (orig_t == nullptr || (!orig_t->is_not_flat() && (!orig_t->is_flat() || orig_t->elem()->inline_klass()->contains_oops()))) &&
5121                         // Can dest array be flat and contain oops?
5122                         tklass->can_be_inline_array() && (!tklass->is_flat() || tklass->is_aryklassptr()->elem()->is_instklassptr()->instance_klass()->as_inline_klass()->contains_oops());
5123     Node* not_objArray = exclude_flat ? generate_non_refArray_guard(klass_node, bailout) : generate_typeArray_guard(klass_node, bailout);
5124 
5125     Node* refined_klass_node = load_default_refined_array_klass(klass_node, /* type_array_guard= */ false);
5126 
5127     if (not_objArray != nullptr) {
5128       // Improve the klass node's type from the new optimistic assumption:
5129       ciKlass* ak = ciArrayKlass::make(env()->Object_klass());
5130       bool not_flat = !UseArrayFlattening;
5131       bool not_null_free = !Arguments::is_valhalla_enabled();
5132       const Type* akls = TypeAryKlassPtr::make(TypePtr::NotNull, ak, Type::Offset(0), Type::trust_interfaces, not_flat, not_null_free, false, false, not_flat, true);
5133       Node* cast = new CastPPNode(control(), refined_klass_node, akls);
5134       refined_klass_node = _gvn.transform(cast);
5135     }
5136 
5137     // Bail out if either start or end is negative.
5138     generate_negative_guard(start, bailout, &start);
5139     generate_negative_guard(end,   bailout, &end);
5140 
5141     Node* length = end;
5142     if (_gvn.type(start) != TypeInt::ZERO) {
5143       length = _gvn.transform(new SubINode(end, start));
5144     }
5145 
5146     // Bail out if length is negative (i.e., if start > end).
5147     // Without this the new_array would throw
5148     // NegativeArraySizeException but IllegalArgumentException is what
5149     // should be thrown
5150     generate_negative_guard(length, bailout, &length);
5151 
5152     // Handle inline type arrays
5153     bool can_validate = !too_many_traps(Deoptimization::Reason_class_check);
5154     if (!stopped()) {
5155       // TODO 8251971
5156       if (!orig_t->is_null_free()) {
5157         // Not statically known to be null free, add a check
5158         generate_fair_guard(null_free_array_test(original), bailout);
5159       }
5160       orig_t = _gvn.type(original)->isa_aryptr();
5161       if (orig_t != nullptr && orig_t->is_flat()) {
5162         // Src is flat, check that dest is flat as well
5163         if (exclude_flat) {
5164           // Dest can't be flat, bail out
5165           bailout->add_req(control());
5166           set_control(top());
5167         } else {
5168           generate_fair_guard(flat_array_test(refined_klass_node, /* flat = */ false), bailout);
5169         }
5170         // TODO 8350865 This is not correct anymore. Write tests and fix logic similar to arraycopy.
5171       } else if (UseArrayFlattening && (orig_t == nullptr || !orig_t->is_not_flat()) &&
5172                  // If dest is flat, src must be flat as well (guaranteed by src <: dest check if validated).
5173                  ((!tklass->is_flat() && tklass->can_be_inline_array()) || !can_validate)) {
5174         // Src might be flat and dest might not be flat. Go to the slow path if src is flat.
5175         // TODO 8251971: Optimize for the case when src/dest are later found to be both flat.
5176         generate_fair_guard(flat_array_test(load_object_klass(original)), bailout);
5177         if (orig_t != nullptr) {
5178           orig_t = orig_t->cast_to_not_flat();
5179           original = _gvn.transform(new CheckCastPPNode(control(), original, orig_t));
5180         }
5181       }
5182       if (!can_validate) {
5183         // No validation. The subtype check emitted at macro expansion time will not go to the slow
5184         // path but call checkcast_arraycopy which can not handle flat/null-free inline type arrays.
5185         // TODO 8251971: Optimize for the case when src/dest are later found to be both flat/null-free.
5186         generate_fair_guard(flat_array_test(refined_klass_node), bailout);
5187         generate_fair_guard(null_free_array_test(original), bailout);
5188       }
5189     }
5190 
5191     // Bail out if start is larger than the original length
5192     Node* orig_tail = _gvn.transform(new SubINode(orig_length, start));
5193     generate_negative_guard(orig_tail, bailout, &orig_tail);
5194 
5195     if (bailout->req() > 1) {
5196       PreserveJVMState pjvms(this);
5197       set_control(_gvn.transform(bailout));
5198       uncommon_trap(Deoptimization::Reason_intrinsic,
5199                     Deoptimization::Action_maybe_recompile);
5200     }
5201 
5202     if (!stopped()) {
5203       // How many elements will we copy from the original?
5204       // The answer is MinI(orig_tail, length).
5205       Node* moved = _gvn.transform(new MinINode(orig_tail, length));
5206 
5207       // Generate a direct call to the right arraycopy function(s).
5208       // We know the copy is disjoint but we might not know if the
5209       // oop stores need checking.
5210       // Extreme case:  Arrays.copyOf((Integer[])x, 10, String[].class).
5211       // This will fail a store-check if x contains any non-nulls.
5212 
5213       // ArrayCopyNode:Ideal may transform the ArrayCopyNode to
5214       // loads/stores but it is legal only if we're sure the
5215       // Arrays.copyOf would succeed. So we need all input arguments
5216       // to the copyOf to be validated, including that the copy to the
5217       // new array won't trigger an ArrayStoreException. That subtype
5218       // check can be optimized if we know something on the type of
5219       // the input array from type speculation.
5220       if (_gvn.type(klass_node)->singleton()) {
5221         const TypeKlassPtr* subk = _gvn.type(load_object_klass(original))->is_klassptr();
5222         const TypeKlassPtr* superk = _gvn.type(klass_node)->is_klassptr();
5223 
5224         int test = C->static_subtype_check(superk, subk);
5225         if (test != Compile::SSC_always_true && test != Compile::SSC_always_false) {
5226           const TypeOopPtr* t_original = _gvn.type(original)->is_oopptr();
5227           if (t_original->speculative_type() != nullptr) {
5228             original = maybe_cast_profiled_obj(original, t_original->speculative_type(), true);
5229           }
5230         }
5231       }
5232 
5233       bool validated = false;
5234       // Reason_class_check rather than Reason_intrinsic because we
5235       // want to intrinsify even if this traps.
5236       if (can_validate) {
5237         Node* not_subtype_ctrl = gen_subtype_check(original, klass_node);
5238 
5239         if (not_subtype_ctrl != top()) {
5240           PreserveJVMState pjvms(this);
5241           set_control(not_subtype_ctrl);
5242           uncommon_trap(Deoptimization::Reason_class_check,
5243                         Deoptimization::Action_make_not_entrant);
5244           assert(stopped(), "Should be stopped");
5245         }
5246         validated = true;
5247       }
5248 
5249       if (!stopped()) {
5250         newcopy = new_array(refined_klass_node, length, 0);  // no arguments to push
5251 
5252         ArrayCopyNode* ac = ArrayCopyNode::make(this, true, original, start, newcopy, intcon(0), moved, true, true,
5253                                                 load_object_klass(original), klass_node);
5254         if (!is_copyOfRange) {
5255           ac->set_copyof(validated);
5256         } else {
5257           ac->set_copyofrange(validated);
5258         }
5259         Node* n = _gvn.transform(ac);
5260         if (n == ac) {
5261           ac->connect_outputs(this);
5262         } else {
5263           assert(validated, "shouldn't transform if all arguments not validated");
5264           set_all_memory(n);
5265         }
5266       }
5267     }
5268   } // original reexecute is set back here
5269 
5270   C->set_has_split_ifs(true); // Has chance for split-if optimization
5271   if (!stopped()) {
5272     set_result(newcopy);
5273   }
5274   return true;
5275 }
5276 
5277 
5278 //----------------------generate_virtual_guard---------------------------
5279 // Helper for hashCode and clone.  Peeks inside the vtable to avoid a call.
5280 Node* LibraryCallKit::generate_virtual_guard(Node* obj_klass,
5281                                              RegionNode* slow_region) {
5282   ciMethod* method = callee();
5283   int vtable_index = method->vtable_index();
5284   assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index,
5285          "bad index %d", vtable_index);
5286   // Get the Method* out of the appropriate vtable entry.
5287   int entry_offset  = in_bytes(Klass::vtable_start_offset()) +
5288                      vtable_index*vtableEntry::size_in_bytes() +
5289                      in_bytes(vtableEntry::method_offset());
5290   Node* entry_addr  = basic_plus_adr(top(), obj_klass, entry_offset);
5291   Node* target_call = make_load(nullptr, entry_addr, TypePtr::NOTNULL, T_ADDRESS, MemNode::unordered);
5292 
5293   // Compare the target method with the expected method (e.g., Object.hashCode).
5294   const TypePtr* native_call_addr = TypeMetadataPtr::make(method);
5295 
5296   Node* native_call = makecon(native_call_addr);
5297   Node* chk_native  = _gvn.transform(new CmpPNode(target_call, native_call));
5298   Node* test_native = _gvn.transform(new BoolNode(chk_native, BoolTest::ne));
5299 
5300   return generate_slow_guard(test_native, slow_region);
5301 }
5302 
5303 //-----------------------generate_method_call----------------------------
5304 // Use generate_method_call to make a slow-call to the real
5305 // method if the fast path fails.  An alternative would be to
5306 // use a stub like OptoRuntime::slow_arraycopy_Java.
5307 // This only works for expanding the current library call,
5308 // not another intrinsic.  (E.g., don't use this for making an
5309 // arraycopy call inside of the copyOf intrinsic.)
5310 CallJavaNode*
5311 LibraryCallKit::generate_method_call(vmIntrinsicID method_id, bool is_virtual, bool is_static, bool res_not_null) {
5312   // When compiling the intrinsic method itself, do not use this technique.
5313   guarantee(callee() != C->method(), "cannot make slow-call to self");
5314 
5315   ciMethod* method = callee();
5316   // ensure the JVMS we have will be correct for this call
5317   guarantee(method_id == method->intrinsic_id(), "must match");
5318 
5319   const TypeFunc* tf = TypeFunc::make(method);
5320   if (res_not_null) {
5321     assert(tf->return_type() == T_OBJECT, "");
5322     const TypeTuple* range = tf->range_cc();
5323     const Type** fields = TypeTuple::fields(range->cnt());
5324     fields[TypeFunc::Parms] = range->field_at(TypeFunc::Parms)->filter_speculative(TypePtr::NOTNULL);
5325     const TypeTuple* new_range = TypeTuple::make(range->cnt(), fields);
5326     tf = TypeFunc::make(tf->domain_cc(), new_range);
5327   }
5328   CallJavaNode* slow_call;
5329   if (is_static) {
5330     assert(!is_virtual, "");
5331     slow_call = new CallStaticJavaNode(C, tf,
5332                            SharedRuntime::get_resolve_static_call_stub(), method);
5333   } else if (is_virtual) {
5334     assert(!gvn().type(argument(0))->maybe_null(), "should not be null");
5335     int vtable_index = Method::invalid_vtable_index;
5336     if (UseInlineCaches) {
5337       // Suppress the vtable call
5338     } else {
5339       // hashCode and clone are not a miranda methods,
5340       // so the vtable index is fixed.
5341       // No need to use the linkResolver to get it.
5342        vtable_index = method->vtable_index();
5343        assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index,
5344               "bad index %d", vtable_index);
5345     }
5346     slow_call = new CallDynamicJavaNode(tf,
5347                           SharedRuntime::get_resolve_virtual_call_stub(),
5348                           method, vtable_index);
5349   } else {  // neither virtual nor static:  opt_virtual
5350     assert(!gvn().type(argument(0))->maybe_null(), "should not be null");
5351     slow_call = new CallStaticJavaNode(C, tf,
5352                                 SharedRuntime::get_resolve_opt_virtual_call_stub(), method);
5353     slow_call->set_optimized_virtual(true);
5354   }
5355   if (CallGenerator::is_inlined_method_handle_intrinsic(this->method(), bci(), callee())) {
5356     // To be able to issue a direct call (optimized virtual or virtual)
5357     // and skip a call to MH.linkTo*/invokeBasic adapter, additional information
5358     // about the method being invoked should be attached to the call site to
5359     // make resolution logic work (see SharedRuntime::resolve_{virtual,opt_virtual}_call_C).
5360     slow_call->set_override_symbolic_info(true);
5361   }
5362   set_arguments_for_java_call(slow_call);
5363   set_edges_for_java_call(slow_call);
5364   return slow_call;
5365 }
5366 
5367 
5368 /**
5369  * Build special case code for calls to hashCode on an object. This call may
5370  * be virtual (invokevirtual) or bound (invokespecial). For each case we generate
5371  * slightly different code.
5372  */
5373 bool LibraryCallKit::inline_native_hashcode(bool is_virtual, bool is_static) {
5374   assert(is_static == callee()->is_static(), "correct intrinsic selection");
5375   assert(!(is_virtual && is_static), "either virtual, special, or static");
5376 
5377   enum { _slow_path = 1, _fast_path, _null_path, PATH_LIMIT };
5378 
5379   RegionNode* result_reg = new RegionNode(PATH_LIMIT);
5380   PhiNode*    result_val = new PhiNode(result_reg, TypeInt::INT);
5381   PhiNode*    result_io  = new PhiNode(result_reg, Type::ABIO);
5382   PhiNode*    result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
5383   Node* obj = argument(0);
5384 
5385   // Don't intrinsify hashcode on inline types for now.
5386   // The "is locked" runtime check also subsumes the inline type check (as inline types cannot be locked) and goes to the slow path.
5387   if (gvn().type(obj)->is_inlinetypeptr()) {
5388     return false;
5389   }
5390 
5391   if (!is_static) {
5392     // Check for hashing null object
5393     obj = null_check_receiver();
5394     if (stopped())  return true;        // unconditionally null
5395     result_reg->init_req(_null_path, top());
5396     result_val->init_req(_null_path, top());
5397   } else {
5398     // Do a null check, and return zero if null.
5399     // System.identityHashCode(null) == 0
5400     Node* null_ctl = top();
5401     obj = null_check_oop(obj, &null_ctl);
5402     result_reg->init_req(_null_path, null_ctl);
5403     result_val->init_req(_null_path, _gvn.intcon(0));
5404   }
5405 
5406   // Unconditionally null?  Then return right away.
5407   if (stopped()) {
5408     set_control( result_reg->in(_null_path));
5409     if (!stopped())
5410       set_result(result_val->in(_null_path));
5411     return true;
5412   }
5413 
5414   // We only go to the fast case code if we pass a number of guards.  The
5415   // paths which do not pass are accumulated in the slow_region.
5416   RegionNode* slow_region = new RegionNode(1);
5417   record_for_igvn(slow_region);
5418 
5419   // If this is a virtual call, we generate a funny guard.  We pull out
5420   // the vtable entry corresponding to hashCode() from the target object.
5421   // If the target method which we are calling happens to be the native
5422   // Object hashCode() method, we pass the guard.  We do not need this
5423   // guard for non-virtual calls -- the caller is known to be the native
5424   // Object hashCode().
5425   if (is_virtual) {
5426     // After null check, get the object's klass.
5427     Node* obj_klass = load_object_klass(obj);
5428     generate_virtual_guard(obj_klass, slow_region);
5429   }
5430 
5431   // Get the header out of the object, use LoadMarkNode when available
5432   Node* header_addr = basic_plus_adr(obj, oopDesc::mark_offset_in_bytes());
5433   // The control of the load must be null. Otherwise, the load can move before
5434   // the null check after castPP removal.
5435   Node* no_ctrl = nullptr;
5436   Node* header = make_load(no_ctrl, header_addr, TypeX_X, TypeX_X->basic_type(), MemNode::unordered);
5437 
5438   if (!UseObjectMonitorTable) {
5439     // Test the header to see if it is safe to read w.r.t. locking.
5440     // We cannot use the inline type mask as this may check bits that are overriden
5441     // by an object monitor's pointer when inflating locking.
5442     Node *lock_mask      = _gvn.MakeConX(markWord::lock_mask_in_place);
5443     Node *lmasked_header = _gvn.transform(new AndXNode(header, lock_mask));
5444     Node *monitor_val   = _gvn.MakeConX(markWord::monitor_value);
5445     Node *chk_monitor   = _gvn.transform(new CmpXNode(lmasked_header, monitor_val));
5446     Node *test_monitor  = _gvn.transform(new BoolNode(chk_monitor, BoolTest::eq));
5447 
5448     generate_slow_guard(test_monitor, slow_region);
5449   }
5450 
5451   // Get the hash value and check to see that it has been properly assigned.
5452   // We depend on hash_mask being at most 32 bits and avoid the use of
5453   // hash_mask_in_place because it could be larger than 32 bits in a 64-bit
5454   // vm: see markWord.hpp.
5455   Node *hash_mask      = _gvn.intcon(markWord::hash_mask);
5456   Node *hash_shift     = _gvn.intcon(markWord::hash_shift);
5457   Node *hshifted_header= _gvn.transform(new URShiftXNode(header, hash_shift));
5458   // This hack lets the hash bits live anywhere in the mark object now, as long
5459   // as the shift drops the relevant bits into the low 32 bits.  Note that
5460   // Java spec says that HashCode is an int so there's no point in capturing
5461   // an 'X'-sized hashcode (32 in 32-bit build or 64 in 64-bit build).
5462   hshifted_header      = ConvX2I(hshifted_header);
5463   Node *hash_val       = _gvn.transform(new AndINode(hshifted_header, hash_mask));
5464 
5465   Node *no_hash_val    = _gvn.intcon(markWord::no_hash);
5466   Node *chk_assigned   = _gvn.transform(new CmpINode( hash_val, no_hash_val));
5467   Node *test_assigned  = _gvn.transform(new BoolNode( chk_assigned, BoolTest::eq));
5468 
5469   generate_slow_guard(test_assigned, slow_region);
5470 
5471   Node* init_mem = reset_memory();
5472   // fill in the rest of the null path:
5473   result_io ->init_req(_null_path, i_o());
5474   result_mem->init_req(_null_path, init_mem);
5475 
5476   result_val->init_req(_fast_path, hash_val);
5477   result_reg->init_req(_fast_path, control());
5478   result_io ->init_req(_fast_path, i_o());
5479   result_mem->init_req(_fast_path, init_mem);
5480 
5481   // Generate code for the slow case.  We make a call to hashCode().
5482   set_control(_gvn.transform(slow_region));
5483   if (!stopped()) {
5484     // No need for PreserveJVMState, because we're using up the present state.
5485     set_all_memory(init_mem);
5486     vmIntrinsics::ID hashCode_id = is_static ? vmIntrinsics::_identityHashCode : vmIntrinsics::_hashCode;
5487     CallJavaNode* slow_call = generate_method_call(hashCode_id, is_virtual, is_static, false);
5488     Node* slow_result = set_results_for_java_call(slow_call);
5489     // this->control() comes from set_results_for_java_call
5490     result_reg->init_req(_slow_path, control());
5491     result_val->init_req(_slow_path, slow_result);
5492     result_io  ->set_req(_slow_path, i_o());
5493     result_mem ->set_req(_slow_path, reset_memory());
5494   }
5495 
5496   // Return the combined state.
5497   set_i_o(        _gvn.transform(result_io)  );
5498   set_all_memory( _gvn.transform(result_mem));
5499 
5500   set_result(result_reg, result_val);
5501   return true;
5502 }
5503 
5504 //---------------------------inline_native_getClass----------------------------
5505 // public final native Class<?> java.lang.Object.getClass();
5506 //
5507 // Build special case code for calls to getClass on an object.
5508 bool LibraryCallKit::inline_native_getClass() {
5509   Node* obj = argument(0);
5510   if (obj->is_InlineType()) {
5511     const Type* t = _gvn.type(obj);
5512     if (t->maybe_null()) {
5513       null_check(obj);
5514     }
5515     set_result(makecon(TypeInstPtr::make(t->inline_klass()->java_mirror())));
5516     return true;
5517   }
5518   obj = null_check_receiver();
5519   if (stopped())  return true;
5520   set_result(load_mirror_from_klass(load_object_klass(obj)));
5521   return true;
5522 }
5523 
5524 //-----------------inline_native_Reflection_getCallerClass---------------------
5525 // public static native Class<?> sun.reflect.Reflection.getCallerClass();
5526 //
5527 // In the presence of deep enough inlining, getCallerClass() becomes a no-op.
5528 //
5529 // NOTE: This code must perform the same logic as JVM_GetCallerClass
5530 // in that it must skip particular security frames and checks for
5531 // caller sensitive methods.
5532 bool LibraryCallKit::inline_native_Reflection_getCallerClass() {
5533 #ifndef PRODUCT
5534   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5535     tty->print_cr("Attempting to inline sun.reflect.Reflection.getCallerClass");
5536   }
5537 #endif
5538 
5539   if (!jvms()->has_method()) {
5540 #ifndef PRODUCT
5541     if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5542       tty->print_cr("  Bailing out because intrinsic was inlined at top level");
5543     }
5544 #endif
5545     return false;
5546   }
5547 
5548   // Walk back up the JVM state to find the caller at the required
5549   // depth.
5550   JVMState* caller_jvms = jvms();
5551 
5552   // Cf. JVM_GetCallerClass
5553   // NOTE: Start the loop at depth 1 because the current JVM state does
5554   // not include the Reflection.getCallerClass() frame.
5555   for (int n = 1; caller_jvms != nullptr; caller_jvms = caller_jvms->caller(), n++) {
5556     ciMethod* m = caller_jvms->method();
5557     switch (n) {
5558     case 0:
5559       fatal("current JVM state does not include the Reflection.getCallerClass frame");
5560       break;
5561     case 1:
5562       // Frame 0 and 1 must be caller sensitive (see JVM_GetCallerClass).
5563       if (!m->caller_sensitive()) {
5564 #ifndef PRODUCT
5565         if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5566           tty->print_cr("  Bailing out: CallerSensitive annotation expected at frame %d", n);
5567         }
5568 #endif
5569         return false;  // bail-out; let JVM_GetCallerClass do the work
5570       }
5571       break;
5572     default:
5573       if (!m->is_ignored_by_security_stack_walk()) {
5574         // We have reached the desired frame; return the holder class.
5575         // Acquire method holder as java.lang.Class and push as constant.
5576         ciInstanceKlass* caller_klass = caller_jvms->method()->holder();
5577         ciInstance* caller_mirror = caller_klass->java_mirror();
5578         set_result(makecon(TypeInstPtr::make(caller_mirror)));
5579 
5580 #ifndef PRODUCT
5581         if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5582           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());
5583           tty->print_cr("  JVM state at this point:");
5584           for (int i = jvms()->depth(), n = 1; i >= 1; i--, n++) {
5585             ciMethod* m = jvms()->of_depth(i)->method();
5586             tty->print_cr("   %d) %s.%s", n, m->holder()->name()->as_utf8(), m->name()->as_utf8());
5587           }
5588         }
5589 #endif
5590         return true;
5591       }
5592       break;
5593     }
5594   }
5595 
5596 #ifndef PRODUCT
5597   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5598     tty->print_cr("  Bailing out because caller depth exceeded inlining depth = %d", jvms()->depth());
5599     tty->print_cr("  JVM state at this point:");
5600     for (int i = jvms()->depth(), n = 1; i >= 1; i--, n++) {
5601       ciMethod* m = jvms()->of_depth(i)->method();
5602       tty->print_cr("   %d) %s.%s", n, m->holder()->name()->as_utf8(), m->name()->as_utf8());
5603     }
5604   }
5605 #endif
5606 
5607   return false;  // bail-out; let JVM_GetCallerClass do the work
5608 }
5609 
5610 bool LibraryCallKit::inline_fp_conversions(vmIntrinsics::ID id) {
5611   Node* arg = argument(0);
5612   Node* result = nullptr;
5613 
5614   switch (id) {
5615   case vmIntrinsics::_floatToRawIntBits:    result = new MoveF2INode(arg);  break;
5616   case vmIntrinsics::_intBitsToFloat:       result = new MoveI2FNode(arg);  break;
5617   case vmIntrinsics::_doubleToRawLongBits:  result = new MoveD2LNode(arg);  break;
5618   case vmIntrinsics::_longBitsToDouble:     result = new MoveL2DNode(arg);  break;
5619   case vmIntrinsics::_floatToFloat16:       result = new ConvF2HFNode(arg); break;
5620   case vmIntrinsics::_float16ToFloat:       result = new ConvHF2FNode(arg); break;
5621 
5622   case vmIntrinsics::_doubleToLongBits: {
5623     // two paths (plus control) merge in a wood
5624     RegionNode *r = new RegionNode(3);
5625     Node *phi = new PhiNode(r, TypeLong::LONG);
5626 
5627     Node *cmpisnan = _gvn.transform(new CmpDNode(arg, arg));
5628     // Build the boolean node
5629     Node *bolisnan = _gvn.transform(new BoolNode(cmpisnan, BoolTest::ne));
5630 
5631     // Branch either way.
5632     // NaN case is less traveled, which makes all the difference.
5633     IfNode *ifisnan = create_and_xform_if(control(), bolisnan, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
5634     Node *opt_isnan = _gvn.transform(ifisnan);
5635     assert( opt_isnan->is_If(), "Expect an IfNode");
5636     IfNode *opt_ifisnan = (IfNode*)opt_isnan;
5637     Node *iftrue = _gvn.transform(new IfTrueNode(opt_ifisnan));
5638 
5639     set_control(iftrue);
5640 
5641     static const jlong nan_bits = CONST64(0x7ff8000000000000);
5642     Node *slow_result = longcon(nan_bits); // return NaN
5643     phi->init_req(1, _gvn.transform( slow_result ));
5644     r->init_req(1, iftrue);
5645 
5646     // Else fall through
5647     Node *iffalse = _gvn.transform(new IfFalseNode(opt_ifisnan));
5648     set_control(iffalse);
5649 
5650     phi->init_req(2, _gvn.transform(new MoveD2LNode(arg)));
5651     r->init_req(2, iffalse);
5652 
5653     // Post merge
5654     set_control(_gvn.transform(r));
5655     record_for_igvn(r);
5656 
5657     C->set_has_split_ifs(true); // Has chance for split-if optimization
5658     result = phi;
5659     assert(result->bottom_type()->isa_long(), "must be");
5660     break;
5661   }
5662 
5663   case vmIntrinsics::_floatToIntBits: {
5664     // two paths (plus control) merge in a wood
5665     RegionNode *r = new RegionNode(3);
5666     Node *phi = new PhiNode(r, TypeInt::INT);
5667 
5668     Node *cmpisnan = _gvn.transform(new CmpFNode(arg, arg));
5669     // Build the boolean node
5670     Node *bolisnan = _gvn.transform(new BoolNode(cmpisnan, BoolTest::ne));
5671 
5672     // Branch either way.
5673     // NaN case is less traveled, which makes all the difference.
5674     IfNode *ifisnan = create_and_xform_if(control(), bolisnan, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
5675     Node *opt_isnan = _gvn.transform(ifisnan);
5676     assert( opt_isnan->is_If(), "Expect an IfNode");
5677     IfNode *opt_ifisnan = (IfNode*)opt_isnan;
5678     Node *iftrue = _gvn.transform(new IfTrueNode(opt_ifisnan));
5679 
5680     set_control(iftrue);
5681 
5682     static const jint nan_bits = 0x7fc00000;
5683     Node *slow_result = makecon(TypeInt::make(nan_bits)); // return NaN
5684     phi->init_req(1, _gvn.transform( slow_result ));
5685     r->init_req(1, iftrue);
5686 
5687     // Else fall through
5688     Node *iffalse = _gvn.transform(new IfFalseNode(opt_ifisnan));
5689     set_control(iffalse);
5690 
5691     phi->init_req(2, _gvn.transform(new MoveF2INode(arg)));
5692     r->init_req(2, iffalse);
5693 
5694     // Post merge
5695     set_control(_gvn.transform(r));
5696     record_for_igvn(r);
5697 
5698     C->set_has_split_ifs(true); // Has chance for split-if optimization
5699     result = phi;
5700     assert(result->bottom_type()->isa_int(), "must be");
5701     break;
5702   }
5703 
5704   default:
5705     fatal_unexpected_iid(id);
5706     break;
5707   }
5708   set_result(_gvn.transform(result));
5709   return true;
5710 }
5711 
5712 bool LibraryCallKit::inline_fp_range_check(vmIntrinsics::ID id) {
5713   Node* arg = argument(0);
5714   Node* result = nullptr;
5715 
5716   switch (id) {
5717   case vmIntrinsics::_floatIsInfinite:
5718     result = new IsInfiniteFNode(arg);
5719     break;
5720   case vmIntrinsics::_floatIsFinite:
5721     result = new IsFiniteFNode(arg);
5722     break;
5723   case vmIntrinsics::_doubleIsInfinite:
5724     result = new IsInfiniteDNode(arg);
5725     break;
5726   case vmIntrinsics::_doubleIsFinite:
5727     result = new IsFiniteDNode(arg);
5728     break;
5729   default:
5730     fatal_unexpected_iid(id);
5731     break;
5732   }
5733   set_result(_gvn.transform(result));
5734   return true;
5735 }
5736 
5737 //----------------------inline_unsafe_copyMemory-------------------------
5738 // public native void Unsafe.copyMemory0(Object srcBase, long srcOffset, Object destBase, long destOffset, long bytes);
5739 
5740 static bool has_wide_mem(PhaseGVN& gvn, Node* addr, Node* base) {
5741   const TypeAryPtr* addr_t = gvn.type(addr)->isa_aryptr();
5742   const Type*       base_t = gvn.type(base);
5743 
5744   bool in_native = (base_t == TypePtr::NULL_PTR);
5745   bool in_heap   = !TypePtr::NULL_PTR->higher_equal(base_t);
5746   bool is_mixed  = !in_heap && !in_native;
5747 
5748   if (is_mixed) {
5749     return true; // mixed accesses can touch both on-heap and off-heap memory
5750   }
5751   if (in_heap) {
5752     bool is_prim_array = (addr_t != nullptr) && (addr_t->elem() != Type::BOTTOM);
5753     if (!is_prim_array) {
5754       // Though Unsafe.copyMemory() ensures at runtime for on-heap accesses that base is a primitive array,
5755       // there's not enough type information available to determine proper memory slice for it.
5756       return true;
5757     }
5758   }
5759   return false;
5760 }
5761 
5762 bool LibraryCallKit::inline_unsafe_copyMemory() {
5763   if (callee()->is_static())  return false;  // caller must have the capability!
5764   null_check_receiver();  // null-check receiver
5765   if (stopped())  return true;
5766 
5767   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
5768 
5769   Node* src_base =         argument(1);  // type: oop
5770   Node* src_off  = ConvL2X(argument(2)); // type: long
5771   Node* dst_base =         argument(4);  // type: oop
5772   Node* dst_off  = ConvL2X(argument(5)); // type: long
5773   Node* size     = ConvL2X(argument(7)); // type: long
5774 
5775   assert(Unsafe_field_offset_to_byte_offset(11) == 11,
5776          "fieldOffset must be byte-scaled");
5777 
5778   Node* src_addr = make_unsafe_address(src_base, src_off);
5779   Node* dst_addr = make_unsafe_address(dst_base, dst_off);
5780 
5781   Node* thread = _gvn.transform(new ThreadLocalNode());
5782   Node* doing_unsafe_access_addr = basic_plus_adr(top(), thread, in_bytes(JavaThread::doing_unsafe_access_offset()));
5783   BasicType doing_unsafe_access_bt = T_BYTE;
5784   assert((sizeof(bool) * CHAR_BIT) == 8, "not implemented");
5785 
5786   // update volatile field
5787   store_to_memory(control(), doing_unsafe_access_addr, intcon(1), doing_unsafe_access_bt, MemNode::unordered);
5788 
5789   int flags = RC_LEAF | RC_NO_FP;
5790 
5791   const TypePtr* dst_type = TypePtr::BOTTOM;
5792 
5793   // Adjust memory effects of the runtime call based on input values.
5794   if (!has_wide_mem(_gvn, src_addr, src_base) &&
5795       !has_wide_mem(_gvn, dst_addr, dst_base)) {
5796     dst_type = _gvn.type(dst_addr)->is_ptr(); // narrow out memory
5797 
5798     const TypePtr* src_type = _gvn.type(src_addr)->is_ptr();
5799     if (C->get_alias_index(src_type) == C->get_alias_index(dst_type)) {
5800       flags |= RC_NARROW_MEM; // narrow in memory
5801     }
5802   }
5803 
5804   // Call it.  Note that the length argument is not scaled.
5805   make_runtime_call(flags,
5806                     OptoRuntime::fast_arraycopy_Type(),
5807                     StubRoutines::unsafe_arraycopy(),
5808                     "unsafe_arraycopy",
5809                     dst_type,
5810                     src_addr, dst_addr, size XTOP);
5811 
5812   store_to_memory(control(), doing_unsafe_access_addr, intcon(0), doing_unsafe_access_bt, MemNode::unordered);
5813 
5814   return true;
5815 }
5816 
5817 // unsafe_setmemory(void *base, ulong offset, size_t length, char fill_value);
5818 // Fill 'length' bytes starting from 'base[offset]' with 'fill_value'
5819 bool LibraryCallKit::inline_unsafe_setMemory() {
5820   if (callee()->is_static())  return false;  // caller must have the capability!
5821   null_check_receiver();  // null-check receiver
5822   if (stopped())  return true;
5823 
5824   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
5825 
5826   Node* dst_base =         argument(1);  // type: oop
5827   Node* dst_off  = ConvL2X(argument(2)); // type: long
5828   Node* size     = ConvL2X(argument(4)); // type: long
5829   Node* byte     =         argument(6);  // type: byte
5830 
5831   assert(Unsafe_field_offset_to_byte_offset(11) == 11,
5832          "fieldOffset must be byte-scaled");
5833 
5834   Node* dst_addr = make_unsafe_address(dst_base, dst_off);
5835 
5836   Node* thread = _gvn.transform(new ThreadLocalNode());
5837   Node* doing_unsafe_access_addr = basic_plus_adr(top(), thread, in_bytes(JavaThread::doing_unsafe_access_offset()));
5838   BasicType doing_unsafe_access_bt = T_BYTE;
5839   assert((sizeof(bool) * CHAR_BIT) == 8, "not implemented");
5840 
5841   // update volatile field
5842   store_to_memory(control(), doing_unsafe_access_addr, intcon(1), doing_unsafe_access_bt, MemNode::unordered);
5843 
5844   int flags = RC_LEAF | RC_NO_FP;
5845 
5846   const TypePtr* dst_type = TypePtr::BOTTOM;
5847 
5848   // Adjust memory effects of the runtime call based on input values.
5849   if (!has_wide_mem(_gvn, dst_addr, dst_base)) {
5850     dst_type = _gvn.type(dst_addr)->is_ptr(); // narrow out memory
5851 
5852     flags |= RC_NARROW_MEM; // narrow in memory
5853   }
5854 
5855   // Call it.  Note that the length argument is not scaled.
5856   make_runtime_call(flags,
5857                     OptoRuntime::unsafe_setmemory_Type(),
5858                     StubRoutines::unsafe_setmemory(),
5859                     "unsafe_setmemory",
5860                     dst_type,
5861                     dst_addr, size XTOP, byte);
5862 
5863   store_to_memory(control(), doing_unsafe_access_addr, intcon(0), doing_unsafe_access_bt, MemNode::unordered);
5864 
5865   return true;
5866 }
5867 
5868 #undef XTOP
5869 
5870 //------------------------clone_coping-----------------------------------
5871 // Helper function for inline_native_clone.
5872 void LibraryCallKit::copy_to_clone(Node* obj, Node* alloc_obj, Node* obj_size, bool is_array) {
5873   assert(obj_size != nullptr, "");
5874   Node* raw_obj = alloc_obj->in(1);
5875   assert(alloc_obj->is_CheckCastPP() && raw_obj->is_Proj() && raw_obj->in(0)->is_Allocate(), "");
5876 
5877   AllocateNode* alloc = nullptr;
5878   if (ReduceBulkZeroing &&
5879       // If we are implementing an array clone without knowing its source type
5880       // (can happen when compiling the array-guarded branch of a reflective
5881       // Object.clone() invocation), initialize the array within the allocation.
5882       // This is needed because some GCs (e.g. ZGC) might fall back in this case
5883       // to a runtime clone call that assumes fully initialized source arrays.
5884       (!is_array || obj->get_ptr_type()->isa_aryptr() != nullptr)) {
5885     // We will be completely responsible for initializing this object -
5886     // mark Initialize node as complete.
5887     alloc = AllocateNode::Ideal_allocation(alloc_obj);
5888     // The object was just allocated - there should be no any stores!
5889     guarantee(alloc != nullptr && alloc->maybe_set_complete(&_gvn), "");
5890     // Mark as complete_with_arraycopy so that on AllocateNode
5891     // expansion, we know this AllocateNode is initialized by an array
5892     // copy and a StoreStore barrier exists after the array copy.
5893     alloc->initialization()->set_complete_with_arraycopy();
5894   }
5895 
5896   Node* size = _gvn.transform(obj_size);
5897   access_clone(obj, alloc_obj, size, is_array);
5898 
5899   // Do not let reads from the cloned object float above the arraycopy.
5900   if (alloc != nullptr) {
5901     // Do not let stores that initialize this object be reordered with
5902     // a subsequent store that would make this object accessible by
5903     // other threads.
5904     // Record what AllocateNode this StoreStore protects so that
5905     // escape analysis can go from the MemBarStoreStoreNode to the
5906     // AllocateNode and eliminate the MemBarStoreStoreNode if possible
5907     // based on the escape status of the AllocateNode.
5908     insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
5909   } else {
5910     insert_mem_bar(Op_MemBarCPUOrder);
5911   }
5912 }
5913 
5914 //------------------------inline_native_clone----------------------------
5915 // protected native Object java.lang.Object.clone();
5916 //
5917 // Here are the simple edge cases:
5918 //  null receiver => normal trap
5919 //  virtual and clone was overridden => slow path to out-of-line clone
5920 //  not cloneable or finalizer => slow path to out-of-line Object.clone
5921 //
5922 // The general case has two steps, allocation and copying.
5923 // Allocation has two cases, and uses GraphKit::new_instance or new_array.
5924 //
5925 // Copying also has two cases, oop arrays and everything else.
5926 // Oop arrays use arrayof_oop_arraycopy (same as System.arraycopy).
5927 // Everything else uses the tight inline loop supplied by CopyArrayNode.
5928 //
5929 // These steps fold up nicely if and when the cloned object's klass
5930 // can be sharply typed as an object array, a type array, or an instance.
5931 //
5932 bool LibraryCallKit::inline_native_clone(bool is_virtual) {
5933   PhiNode* result_val;
5934 
5935   // Set the reexecute bit for the interpreter to reexecute
5936   // the bytecode that invokes Object.clone if deoptimization happens.
5937   { PreserveReexecuteState preexecs(this);
5938     jvms()->set_should_reexecute(true);
5939 
5940     Node* obj = argument(0);
5941     obj = null_check_receiver();
5942     if (stopped())  return true;
5943 
5944     const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
5945     if (obj_type->is_inlinetypeptr()) {
5946       // If the object to clone is an inline type, we can simply return it (i.e. a nop) since inline types have
5947       // no identity.
5948       set_result(obj);
5949       return true;
5950     }
5951 
5952     // If we are going to clone an instance, we need its exact type to
5953     // know the number and types of fields to convert the clone to
5954     // loads/stores. Maybe a speculative type can help us.
5955     if (!obj_type->klass_is_exact() &&
5956         obj_type->speculative_type() != nullptr &&
5957         obj_type->speculative_type()->is_instance_klass() &&
5958         !obj_type->speculative_type()->is_inlinetype()) {
5959       ciInstanceKlass* spec_ik = obj_type->speculative_type()->as_instance_klass();
5960       if (spec_ik->nof_nonstatic_fields() <= ArrayCopyLoadStoreMaxElem &&
5961           !spec_ik->has_injected_fields()) {
5962         if (!obj_type->isa_instptr() ||
5963             obj_type->is_instptr()->instance_klass()->has_subklass()) {
5964           obj = maybe_cast_profiled_obj(obj, obj_type->speculative_type(), false);
5965         }
5966       }
5967     }
5968 
5969     // Conservatively insert a memory barrier on all memory slices.
5970     // Do not let writes into the original float below the clone.
5971     insert_mem_bar(Op_MemBarCPUOrder);
5972 
5973     // paths into result_reg:
5974     enum {
5975       _slow_path = 1,     // out-of-line call to clone method (virtual or not)
5976       _objArray_path,     // plain array allocation, plus arrayof_oop_arraycopy
5977       _array_path,        // plain array allocation, plus arrayof_long_arraycopy
5978       _instance_path,     // plain instance allocation, plus arrayof_long_arraycopy
5979       PATH_LIMIT
5980     };
5981     RegionNode* result_reg = new RegionNode(PATH_LIMIT);
5982     result_val             = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
5983     PhiNode*    result_i_o = new PhiNode(result_reg, Type::ABIO);
5984     PhiNode*    result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
5985     record_for_igvn(result_reg);
5986 
5987     Node* obj_klass = load_object_klass(obj);
5988     // We only go to the fast case code if we pass a number of guards.
5989     // The paths which do not pass are accumulated in the slow_region.
5990     RegionNode* slow_region = new RegionNode(1);
5991     record_for_igvn(slow_region);
5992 
5993     Node* array_obj = obj;
5994     Node* array_ctl = generate_array_guard(obj_klass, (RegionNode*)nullptr, &array_obj);
5995     if (array_ctl != nullptr) {
5996       // It's an array.
5997       PreserveJVMState pjvms(this);
5998       set_control(array_ctl);
5999 
6000       BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
6001       const TypeAryPtr* ary_ptr = obj_type->isa_aryptr();
6002       if (UseArrayFlattening && bs->array_copy_requires_gc_barriers(true, T_OBJECT, true, false, BarrierSetC2::Expansion) &&
6003           obj_type->can_be_inline_array() &&
6004           (ary_ptr == nullptr || (!ary_ptr->is_not_flat() && (!ary_ptr->is_flat() || ary_ptr->elem()->inline_klass()->contains_oops())))) {
6005         // Flat inline type array may have object field that would require a
6006         // write barrier. Conservatively, go to slow path.
6007         generate_fair_guard(flat_array_test(obj_klass), slow_region);
6008       }
6009 
6010       if (!stopped()) {
6011         Node* obj_length = load_array_length(array_obj);
6012         Node* array_size = nullptr; // Size of the array without object alignment padding.
6013         Node* alloc_obj = new_array(obj_klass, obj_length, 0, &array_size, /*deoptimize_on_exception=*/true);
6014 
6015         BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
6016         if (bs->array_copy_requires_gc_barriers(true, T_OBJECT, true, false, BarrierSetC2::Parsing)) {
6017           // If it is an oop array, it requires very special treatment,
6018           // because gc barriers are required when accessing the array.
6019           Node* is_obja = generate_refArray_guard(obj_klass, (RegionNode*)nullptr);
6020           if (is_obja != nullptr) {
6021             PreserveJVMState pjvms2(this);
6022             set_control(is_obja);
6023             // Generate a direct call to the right arraycopy function(s).
6024             // Clones are always tightly coupled.
6025             ArrayCopyNode* ac = ArrayCopyNode::make(this, true, array_obj, intcon(0), alloc_obj, intcon(0), obj_length, true, false);
6026             ac->set_clone_oop_array();
6027             Node* n = _gvn.transform(ac);
6028             assert(n == ac, "cannot disappear");
6029             ac->connect_outputs(this, /*deoptimize_on_exception=*/true);
6030 
6031             result_reg->init_req(_objArray_path, control());
6032             result_val->init_req(_objArray_path, alloc_obj);
6033             result_i_o ->set_req(_objArray_path, i_o());
6034             result_mem ->set_req(_objArray_path, reset_memory());
6035           }
6036         }
6037         // Otherwise, there are no barriers to worry about.
6038         // (We can dispense with card marks if we know the allocation
6039         //  comes out of eden (TLAB)...  In fact, ReduceInitialCardMarks
6040         //  causes the non-eden paths to take compensating steps to
6041         //  simulate a fresh allocation, so that no further
6042         //  card marks are required in compiled code to initialize
6043         //  the object.)
6044 
6045         if (!stopped()) {
6046           copy_to_clone(obj, alloc_obj, array_size, true);
6047 
6048           // Present the results of the copy.
6049           result_reg->init_req(_array_path, control());
6050           result_val->init_req(_array_path, alloc_obj);
6051           result_i_o ->set_req(_array_path, i_o());
6052           result_mem ->set_req(_array_path, reset_memory());
6053         }
6054       }
6055     }
6056 
6057     if (!stopped()) {
6058       // It's an instance (we did array above).  Make the slow-path tests.
6059       // If this is a virtual call, we generate a funny guard.  We grab
6060       // the vtable entry corresponding to clone() from the target object.
6061       // If the target method which we are calling happens to be the
6062       // Object clone() method, we pass the guard.  We do not need this
6063       // guard for non-virtual calls; the caller is known to be the native
6064       // Object clone().
6065       if (is_virtual) {
6066         generate_virtual_guard(obj_klass, slow_region);
6067       }
6068 
6069       // The object must be easily cloneable and must not have a finalizer.
6070       // Both of these conditions may be checked in a single test.
6071       // We could optimize the test further, but we don't care.
6072       generate_misc_flags_guard(obj_klass,
6073                                 // Test both conditions:
6074                                 KlassFlags::_misc_is_cloneable_fast | KlassFlags::_misc_has_finalizer,
6075                                 // Must be cloneable but not finalizer:
6076                                 KlassFlags::_misc_is_cloneable_fast,
6077                                 slow_region);
6078     }
6079 
6080     if (!stopped()) {
6081       // It's an instance, and it passed the slow-path tests.
6082       PreserveJVMState pjvms(this);
6083       Node* obj_size = nullptr; // Total object size, including object alignment padding.
6084       // Need to deoptimize on exception from allocation since Object.clone intrinsic
6085       // is reexecuted if deoptimization occurs and there could be problems when merging
6086       // exception state between multiple Object.clone versions (reexecute=true vs reexecute=false).
6087       Node* alloc_obj = new_instance(obj_klass, nullptr, &obj_size, /*deoptimize_on_exception=*/true);
6088 
6089       copy_to_clone(obj, alloc_obj, obj_size, false);
6090 
6091       // Present the results of the slow call.
6092       result_reg->init_req(_instance_path, control());
6093       result_val->init_req(_instance_path, alloc_obj);
6094       result_i_o ->set_req(_instance_path, i_o());
6095       result_mem ->set_req(_instance_path, reset_memory());
6096     }
6097 
6098     // Generate code for the slow case.  We make a call to clone().
6099     set_control(_gvn.transform(slow_region));
6100     if (!stopped()) {
6101       PreserveJVMState pjvms(this);
6102       CallJavaNode* slow_call = generate_method_call(vmIntrinsics::_clone, is_virtual, false, true);
6103       // We need to deoptimize on exception (see comment above)
6104       Node* slow_result = set_results_for_java_call(slow_call, false, /* deoptimize */ true);
6105       // this->control() comes from set_results_for_java_call
6106       result_reg->init_req(_slow_path, control());
6107       result_val->init_req(_slow_path, slow_result);
6108       result_i_o ->set_req(_slow_path, i_o());
6109       result_mem ->set_req(_slow_path, reset_memory());
6110     }
6111 
6112     // Return the combined state.
6113     set_control(    _gvn.transform(result_reg));
6114     set_i_o(        _gvn.transform(result_i_o));
6115     set_all_memory( _gvn.transform(result_mem));
6116   } // original reexecute is set back here
6117 
6118   set_result(_gvn.transform(result_val));
6119   return true;
6120 }
6121 
6122 // If we have a tightly coupled allocation, the arraycopy may take care
6123 // of the array initialization. If one of the guards we insert between
6124 // the allocation and the arraycopy causes a deoptimization, an
6125 // uninitialized array will escape the compiled method. To prevent that
6126 // we set the JVM state for uncommon traps between the allocation and
6127 // the arraycopy to the state before the allocation so, in case of
6128 // deoptimization, we'll reexecute the allocation and the
6129 // initialization.
6130 JVMState* LibraryCallKit::arraycopy_restore_alloc_state(AllocateArrayNode* alloc, int& saved_reexecute_sp) {
6131   if (alloc != nullptr) {
6132     ciMethod* trap_method = alloc->jvms()->method();
6133     int trap_bci = alloc->jvms()->bci();
6134 
6135     if (!C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_intrinsic) &&
6136         !C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_null_check)) {
6137       // Make sure there's no store between the allocation and the
6138       // arraycopy otherwise visible side effects could be rexecuted
6139       // in case of deoptimization and cause incorrect execution.
6140       bool no_interfering_store = true;
6141       Node* mem = alloc->in(TypeFunc::Memory);
6142       if (mem->is_MergeMem()) {
6143         for (MergeMemStream mms(merged_memory(), mem->as_MergeMem()); mms.next_non_empty2(); ) {
6144           Node* n = mms.memory();
6145           if (n != mms.memory2() && !(n->is_Proj() && n->in(0) == alloc->initialization())) {
6146             assert(n->is_Store(), "what else?");
6147             no_interfering_store = false;
6148             break;
6149           }
6150         }
6151       } else {
6152         for (MergeMemStream mms(merged_memory()); mms.next_non_empty(); ) {
6153           Node* n = mms.memory();
6154           if (n != mem && !(n->is_Proj() && n->in(0) == alloc->initialization())) {
6155             assert(n->is_Store(), "what else?");
6156             no_interfering_store = false;
6157             break;
6158           }
6159         }
6160       }
6161 
6162       if (no_interfering_store) {
6163         SafePointNode* sfpt = create_safepoint_with_state_before_array_allocation(alloc);
6164 
6165         JVMState* saved_jvms = jvms();
6166         saved_reexecute_sp = _reexecute_sp;
6167 
6168         set_jvms(sfpt->jvms());
6169         _reexecute_sp = jvms()->sp();
6170 
6171         return saved_jvms;
6172       }
6173     }
6174   }
6175   return nullptr;
6176 }
6177 
6178 // Clone the JVMState of the array allocation and create a new safepoint with it. Re-push the array length to the stack
6179 // such that uncommon traps can be emitted to re-execute the array allocation in the interpreter.
6180 SafePointNode* LibraryCallKit::create_safepoint_with_state_before_array_allocation(const AllocateArrayNode* alloc) const {
6181   JVMState* old_jvms = alloc->jvms()->clone_shallow(C);
6182   uint size = alloc->req();
6183   SafePointNode* sfpt = new SafePointNode(size, old_jvms);
6184   old_jvms->set_map(sfpt);
6185   for (uint i = 0; i < size; i++) {
6186     sfpt->init_req(i, alloc->in(i));
6187   }
6188   int adjustment = 1;
6189   const TypeAryKlassPtr* ary_klass_ptr = alloc->in(AllocateNode::KlassNode)->bottom_type()->is_aryklassptr();
6190   if (ary_klass_ptr->is_null_free()) {
6191     // A null-free, tightly coupled array allocation can only come from LibraryCallKit::inline_newArray which
6192     // also requires the componentType and initVal on stack for re-execution.
6193     // Re-create and push the componentType.
6194     ciArrayKlass* klass = ary_klass_ptr->exact_klass()->as_array_klass();
6195     ciInstance* instance = klass->component_mirror_instance();
6196     const TypeInstPtr* t_instance = TypeInstPtr::make(instance);
6197     sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp(), makecon(t_instance));
6198     adjustment++;
6199   }
6200   // re-push array length for deoptimization
6201   sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp() + adjustment - 1, alloc->in(AllocateNode::ALength));
6202   if (ary_klass_ptr->is_null_free()) {
6203     // Re-create and push the initVal.
6204     Node* init_val = alloc->in(AllocateNode::InitValue);
6205     if (init_val == nullptr) {
6206       init_val = InlineTypeNode::make_all_zero(_gvn, ary_klass_ptr->elem()->is_instklassptr()->instance_klass()->as_inline_klass());
6207     } else if (UseCompressedOops) {
6208       init_val = _gvn.transform(new DecodeNNode(init_val, init_val->bottom_type()->make_ptr()));
6209     }
6210     sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp() + adjustment, init_val);
6211     adjustment++;
6212   }
6213   old_jvms->set_sp(old_jvms->sp() + adjustment);
6214   old_jvms->set_monoff(old_jvms->monoff() + adjustment);
6215   old_jvms->set_scloff(old_jvms->scloff() + adjustment);
6216   old_jvms->set_endoff(old_jvms->endoff() + adjustment);
6217   old_jvms->set_should_reexecute(true);
6218 
6219   sfpt->set_i_o(map()->i_o());
6220   sfpt->set_memory(map()->memory());
6221   sfpt->set_control(map()->control());
6222   return sfpt;
6223 }
6224 
6225 // In case of a deoptimization, we restart execution at the
6226 // allocation, allocating a new array. We would leave an uninitialized
6227 // array in the heap that GCs wouldn't expect. Move the allocation
6228 // after the traps so we don't allocate the array if we
6229 // deoptimize. This is possible because tightly_coupled_allocation()
6230 // guarantees there's no observer of the allocated array at this point
6231 // and the control flow is simple enough.
6232 void LibraryCallKit::arraycopy_move_allocation_here(AllocateArrayNode* alloc, Node* dest, JVMState* saved_jvms_before_guards,
6233                                                     int saved_reexecute_sp, uint new_idx) {
6234   if (saved_jvms_before_guards != nullptr && !stopped()) {
6235     replace_unrelated_uncommon_traps_with_alloc_state(alloc, saved_jvms_before_guards);
6236 
6237     assert(alloc != nullptr, "only with a tightly coupled allocation");
6238     // restore JVM state to the state at the arraycopy
6239     saved_jvms_before_guards->map()->set_control(map()->control());
6240     assert(saved_jvms_before_guards->map()->memory() == map()->memory(), "memory state changed?");
6241     assert(saved_jvms_before_guards->map()->i_o() == map()->i_o(), "IO state changed?");
6242     // If we've improved the types of some nodes (null check) while
6243     // emitting the guards, propagate them to the current state
6244     map()->replaced_nodes().apply(saved_jvms_before_guards->map(), new_idx);
6245     set_jvms(saved_jvms_before_guards);
6246     _reexecute_sp = saved_reexecute_sp;
6247 
6248     // Remove the allocation from above the guards
6249     CallProjections* callprojs = alloc->extract_projections(true);
6250     InitializeNode* init = alloc->initialization();
6251     Node* alloc_mem = alloc->in(TypeFunc::Memory);
6252     C->gvn_replace_by(callprojs->fallthrough_ioproj, alloc->in(TypeFunc::I_O));
6253     init->replace_mem_projs_by(alloc_mem, C);
6254 
6255     // The CastIINode created in GraphKit::new_array (in AllocateArrayNode::make_ideal_length) must stay below
6256     // the allocation (i.e. is only valid if the allocation succeeds):
6257     // 1) replace CastIINode with AllocateArrayNode's length here
6258     // 2) Create CastIINode again once allocation has moved (see below) at the end of this method
6259     //
6260     // Multiple identical CastIINodes might exist here. Each GraphKit::load_array_length() call will generate
6261     // new separate CastIINode (arraycopy guard checks or any array length use between array allocation and ararycopy)
6262     Node* init_control = init->proj_out(TypeFunc::Control);
6263     Node* alloc_length = alloc->Ideal_length();
6264 #ifdef ASSERT
6265     Node* prev_cast = nullptr;
6266 #endif
6267     for (uint i = 0; i < init_control->outcnt(); i++) {
6268       Node* init_out = init_control->raw_out(i);
6269       if (init_out->is_CastII() && init_out->in(TypeFunc::Control) == init_control && init_out->in(1) == alloc_length) {
6270 #ifdef ASSERT
6271         if (prev_cast == nullptr) {
6272           prev_cast = init_out;
6273         } else {
6274           if (prev_cast->cmp(*init_out) == false) {
6275             prev_cast->dump();
6276             init_out->dump();
6277             assert(false, "not equal CastIINode");
6278           }
6279         }
6280 #endif
6281         C->gvn_replace_by(init_out, alloc_length);
6282       }
6283     }
6284     C->gvn_replace_by(init->proj_out(TypeFunc::Control), alloc->in(0));
6285 
6286     // move the allocation here (after the guards)
6287     _gvn.hash_delete(alloc);
6288     alloc->set_req(TypeFunc::Control, control());
6289     alloc->set_req(TypeFunc::I_O, i_o());
6290     Node *mem = reset_memory();
6291     set_all_memory(mem);
6292     alloc->set_req(TypeFunc::Memory, mem);
6293     set_control(init->proj_out_or_null(TypeFunc::Control));
6294     set_i_o(callprojs->fallthrough_ioproj);
6295 
6296     // Update memory as done in GraphKit::set_output_for_allocation()
6297     const TypeInt* length_type = _gvn.find_int_type(alloc->in(AllocateNode::ALength));
6298     const TypeOopPtr* ary_type = _gvn.type(alloc->in(AllocateNode::KlassNode))->is_klassptr()->as_instance_type();
6299     if (ary_type->isa_aryptr() && length_type != nullptr) {
6300       ary_type = ary_type->is_aryptr()->cast_to_size(length_type);
6301     }
6302     const TypePtr* telemref = ary_type->add_offset(Type::OffsetBot);
6303     int            elemidx  = C->get_alias_index(telemref);
6304     // Need to properly move every memory projection for the Initialize
6305 #ifdef ASSERT
6306     int mark_idx = C->get_alias_index(ary_type->add_offset(oopDesc::mark_offset_in_bytes()));
6307     int klass_idx = C->get_alias_index(ary_type->add_offset(oopDesc::klass_offset_in_bytes()));
6308 #endif
6309     auto move_proj = [&](ProjNode* proj) {
6310       int alias_idx = C->get_alias_index(proj->adr_type());
6311       assert(alias_idx == Compile::AliasIdxRaw ||
6312              alias_idx == elemidx ||
6313              alias_idx == mark_idx ||
6314              alias_idx == klass_idx, "should be raw memory or array element type");
6315       set_memory(proj, alias_idx);
6316     };
6317     init->for_each_proj(move_proj, TypeFunc::Memory);
6318 
6319     Node* allocx = _gvn.transform(alloc);
6320     assert(allocx == alloc, "where has the allocation gone?");
6321     assert(dest->is_CheckCastPP(), "not an allocation result?");
6322 
6323     _gvn.hash_delete(dest);
6324     dest->set_req(0, control());
6325     Node* destx = _gvn.transform(dest);
6326     assert(destx == dest, "where has the allocation result gone?");
6327 
6328     array_ideal_length(alloc, ary_type, true);
6329   }
6330 }
6331 
6332 // Unrelated UCTs between the array allocation and the array copy, which are considered safe by tightly_coupled_allocation(),
6333 // need to be replaced by an UCT with a state before the array allocation (including the array length). This is necessary
6334 // because we could hit one of these UCTs (which are executed before the emitted array copy guards and the actual array
6335 // allocation which is moved down in arraycopy_move_allocation_here()). When later resuming execution in the interpreter,
6336 // we would have wrongly skipped the array allocation. To prevent this, we resume execution at the array allocation in
6337 // the interpreter similar to what we are doing for the newly emitted guards for the array copy.
6338 void LibraryCallKit::replace_unrelated_uncommon_traps_with_alloc_state(AllocateArrayNode* alloc,
6339                                                                        JVMState* saved_jvms_before_guards) {
6340   if (saved_jvms_before_guards->map()->control()->is_IfProj()) {
6341     // There is at least one unrelated uncommon trap which needs to be replaced.
6342     SafePointNode* sfpt = create_safepoint_with_state_before_array_allocation(alloc);
6343 
6344     JVMState* saved_jvms = jvms();
6345     const int saved_reexecute_sp = _reexecute_sp;
6346     set_jvms(sfpt->jvms());
6347     _reexecute_sp = jvms()->sp();
6348 
6349     replace_unrelated_uncommon_traps_with_alloc_state(saved_jvms_before_guards);
6350 
6351     // Restore state
6352     set_jvms(saved_jvms);
6353     _reexecute_sp = saved_reexecute_sp;
6354   }
6355 }
6356 
6357 // Replace the unrelated uncommon traps with new uncommon trap nodes by reusing the action and reason. The new uncommon
6358 // traps will have the state of the array allocation. Let the old uncommon trap nodes die.
6359 void LibraryCallKit::replace_unrelated_uncommon_traps_with_alloc_state(JVMState* saved_jvms_before_guards) {
6360   Node* if_proj = saved_jvms_before_guards->map()->control(); // Start the search right before the newly emitted guards
6361   while (if_proj->is_IfProj()) {
6362     CallStaticJavaNode* uncommon_trap = get_uncommon_trap_from_success_proj(if_proj);
6363     if (uncommon_trap != nullptr) {
6364       create_new_uncommon_trap(uncommon_trap);
6365     }
6366     assert(if_proj->in(0)->is_If(), "must be If");
6367     if_proj = if_proj->in(0)->in(0);
6368   }
6369   assert(if_proj->is_Proj() && if_proj->in(0)->is_Initialize(),
6370          "must have reached control projection of init node");
6371 }
6372 
6373 void LibraryCallKit::create_new_uncommon_trap(CallStaticJavaNode* uncommon_trap_call) {
6374   const int trap_request = uncommon_trap_call->uncommon_trap_request();
6375   assert(trap_request != 0, "no valid UCT trap request");
6376   PreserveJVMState pjvms(this);
6377   set_control(uncommon_trap_call->in(0));
6378   uncommon_trap(Deoptimization::trap_request_reason(trap_request),
6379                 Deoptimization::trap_request_action(trap_request));
6380   assert(stopped(), "Should be stopped");
6381   _gvn.hash_delete(uncommon_trap_call);
6382   uncommon_trap_call->set_req(0, top()); // not used anymore, kill it
6383 }
6384 
6385 // Common checks for array sorting intrinsics arguments.
6386 // Returns `true` if checks passed.
6387 bool LibraryCallKit::check_array_sort_arguments(Node* elementType, Node* obj, BasicType& bt) {
6388   // check address of the class
6389   if (elementType == nullptr || elementType->is_top()) {
6390     return false;  // dead path
6391   }
6392   const TypeInstPtr* elem_klass = gvn().type(elementType)->isa_instptr();
6393   if (elem_klass == nullptr) {
6394     return false;  // dead path
6395   }
6396   // java_mirror_type() returns non-null for compile-time Class constants only
6397   ciType* elem_type = elem_klass->java_mirror_type();
6398   if (elem_type == nullptr) {
6399     return false;
6400   }
6401   bt = elem_type->basic_type();
6402   // Disable the intrinsic if the CPU does not support SIMD sort
6403   if (!Matcher::supports_simd_sort(bt)) {
6404     return false;
6405   }
6406   // check address of the array
6407   if (obj == nullptr || obj->is_top()) {
6408     return false;  // dead path
6409   }
6410   const TypeAryPtr* obj_t = _gvn.type(obj)->isa_aryptr();
6411   if (obj_t == nullptr || obj_t->elem() == Type::BOTTOM) {
6412     return false; // failed input validation
6413   }
6414   return true;
6415 }
6416 
6417 //------------------------------inline_array_partition-----------------------
6418 bool LibraryCallKit::inline_array_partition() {
6419   address stubAddr = StubRoutines::select_array_partition_function();
6420   if (stubAddr == nullptr) {
6421     return false; // Intrinsic's stub is not implemented on this platform
6422   }
6423   assert(callee()->signature()->size() == 9, "arrayPartition has 8 parameters (one long)");
6424 
6425   // no receiver because it is a static method
6426   Node* elementType     = argument(0);
6427   Node* obj             = argument(1);
6428   Node* offset          = argument(2); // long
6429   Node* fromIndex       = argument(4);
6430   Node* toIndex         = argument(5);
6431   Node* indexPivot1     = argument(6);
6432   Node* indexPivot2     = argument(7);
6433   // PartitionOperation:  argument(8) is ignored
6434 
6435   Node* pivotIndices = nullptr;
6436   BasicType bt = T_ILLEGAL;
6437 
6438   if (!check_array_sort_arguments(elementType, obj, bt)) {
6439     return false;
6440   }
6441   null_check(obj);
6442   // If obj is dead, only null-path is taken.
6443   if (stopped()) {
6444     return true;
6445   }
6446   // Set the original stack and the reexecute bit for the interpreter to reexecute
6447   // the bytecode that invokes DualPivotQuicksort.partition() if deoptimization happens.
6448   { PreserveReexecuteState preexecs(this);
6449     jvms()->set_should_reexecute(true);
6450 
6451     Node* obj_adr = make_unsafe_address(obj, offset);
6452 
6453     // create the pivotIndices array of type int and size = 2
6454     Node* size = intcon(2);
6455     Node* klass_node = makecon(TypeKlassPtr::make(ciTypeArrayKlass::make(T_INT)));
6456     pivotIndices = new_array(klass_node, size, 0);  // no arguments to push
6457     AllocateArrayNode* alloc = tightly_coupled_allocation(pivotIndices);
6458     guarantee(alloc != nullptr, "created above");
6459     Node* pivotIndices_adr = basic_plus_adr(pivotIndices, arrayOopDesc::base_offset_in_bytes(T_INT));
6460 
6461     // pass the basic type enum to the stub
6462     Node* elemType = intcon(bt);
6463 
6464     // Call the stub
6465     const char *stubName = "array_partition_stub";
6466     make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::array_partition_Type(),
6467                       stubAddr, stubName, TypePtr::BOTTOM,
6468                       obj_adr, elemType, fromIndex, toIndex, pivotIndices_adr,
6469                       indexPivot1, indexPivot2);
6470 
6471   } // original reexecute is set back here
6472 
6473   if (!stopped()) {
6474     set_result(pivotIndices);
6475   }
6476 
6477   return true;
6478 }
6479 
6480 
6481 //------------------------------inline_array_sort-----------------------
6482 bool LibraryCallKit::inline_array_sort() {
6483   address stubAddr = StubRoutines::select_arraysort_function();
6484   if (stubAddr == nullptr) {
6485     return false; // Intrinsic's stub is not implemented on this platform
6486   }
6487   assert(callee()->signature()->size() == 7, "arraySort has 6 parameters (one long)");
6488 
6489   // no receiver because it is a static method
6490   Node* elementType     = argument(0);
6491   Node* obj             = argument(1);
6492   Node* offset          = argument(2); // long
6493   Node* fromIndex       = argument(4);
6494   Node* toIndex         = argument(5);
6495   // SortOperation:       argument(6) is ignored
6496 
6497   BasicType bt = T_ILLEGAL;
6498 
6499   if (!check_array_sort_arguments(elementType, obj, bt)) {
6500     return false;
6501   }
6502   null_check(obj);
6503   // If obj is dead, only null-path is taken.
6504   if (stopped()) {
6505     return true;
6506   }
6507   Node* obj_adr = make_unsafe_address(obj, offset);
6508 
6509   // pass the basic type enum to the stub
6510   Node* elemType = intcon(bt);
6511 
6512   // Call the stub.
6513   const char *stubName = "arraysort_stub";
6514   make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::array_sort_Type(),
6515                     stubAddr, stubName, TypePtr::BOTTOM,
6516                     obj_adr, elemType, fromIndex, toIndex);
6517 
6518   return true;
6519 }
6520 
6521 
6522 //------------------------------inline_arraycopy-----------------------
6523 // public static native void java.lang.System.arraycopy(Object src,  int  srcPos,
6524 //                                                      Object dest, int destPos,
6525 //                                                      int length);
6526 bool LibraryCallKit::inline_arraycopy() {
6527   // Get the arguments.
6528   Node* src         = argument(0);  // type: oop
6529   Node* src_offset  = argument(1);  // type: int
6530   Node* dest        = argument(2);  // type: oop
6531   Node* dest_offset = argument(3);  // type: int
6532   Node* length      = argument(4);  // type: int
6533 
6534   uint new_idx = C->unique();
6535 
6536   // Check for allocation before we add nodes that would confuse
6537   // tightly_coupled_allocation()
6538   AllocateArrayNode* alloc = tightly_coupled_allocation(dest);
6539 
6540   int saved_reexecute_sp = -1;
6541   JVMState* saved_jvms_before_guards = arraycopy_restore_alloc_state(alloc, saved_reexecute_sp);
6542   // See arraycopy_restore_alloc_state() comment
6543   // if alloc == null we don't have to worry about a tightly coupled allocation so we can emit all needed guards
6544   // if saved_jvms_before_guards is not null (then alloc is not null) then we can handle guards and a tightly coupled allocation
6545   // if saved_jvms_before_guards is null and alloc is not null, we can't emit any guards
6546   bool can_emit_guards = (alloc == nullptr || saved_jvms_before_guards != nullptr);
6547 
6548   // The following tests must be performed
6549   // (1) src and dest are arrays.
6550   // (2) src and dest arrays must have elements of the same BasicType
6551   // (3) src and dest must not be null.
6552   // (4) src_offset must not be negative.
6553   // (5) dest_offset must not be negative.
6554   // (6) length must not be negative.
6555   // (7) src_offset + length must not exceed length of src.
6556   // (8) dest_offset + length must not exceed length of dest.
6557   // (9) each element of an oop array must be assignable
6558 
6559   // (3) src and dest must not be null.
6560   // always do this here because we need the JVM state for uncommon traps
6561   Node* null_ctl = top();
6562   src  = saved_jvms_before_guards != nullptr ? null_check_oop(src, &null_ctl, true, true) : null_check(src, T_ARRAY);
6563   assert(null_ctl->is_top(), "no null control here");
6564   dest = null_check(dest, T_ARRAY);
6565 
6566   if (!can_emit_guards) {
6567     // if saved_jvms_before_guards is null and alloc is not null, we don't emit any
6568     // guards but the arraycopy node could still take advantage of a
6569     // tightly allocated allocation. tightly_coupled_allocation() is
6570     // called again to make sure it takes the null check above into
6571     // account: the null check is mandatory and if it caused an
6572     // uncommon trap to be emitted then the allocation can't be
6573     // considered tightly coupled in this context.
6574     alloc = tightly_coupled_allocation(dest);
6575   }
6576 
6577   bool validated = false;
6578 
6579   const Type* src_type  = _gvn.type(src);
6580   const Type* dest_type = _gvn.type(dest);
6581   const TypeAryPtr* top_src  = src_type->isa_aryptr();
6582   const TypeAryPtr* top_dest = dest_type->isa_aryptr();
6583 
6584   // Do we have the type of src?
6585   bool has_src = (top_src != nullptr && top_src->elem() != Type::BOTTOM);
6586   // Do we have the type of dest?
6587   bool has_dest = (top_dest != nullptr && top_dest->elem() != Type::BOTTOM);
6588   // Is the type for src from speculation?
6589   bool src_spec = false;
6590   // Is the type for dest from speculation?
6591   bool dest_spec = false;
6592 
6593   if ((!has_src || !has_dest) && can_emit_guards) {
6594     // We don't have sufficient type information, let's see if
6595     // speculative types can help. We need to have types for both src
6596     // and dest so that it pays off.
6597 
6598     // Do we already have or could we have type information for src
6599     bool could_have_src = has_src;
6600     // Do we already have or could we have type information for dest
6601     bool could_have_dest = has_dest;
6602 
6603     ciKlass* src_k = nullptr;
6604     if (!has_src) {
6605       src_k = src_type->speculative_type_not_null();
6606       if (src_k != nullptr && src_k->is_array_klass()) {
6607         could_have_src = true;
6608       }
6609     }
6610 
6611     ciKlass* dest_k = nullptr;
6612     if (!has_dest) {
6613       dest_k = dest_type->speculative_type_not_null();
6614       if (dest_k != nullptr && dest_k->is_array_klass()) {
6615         could_have_dest = true;
6616       }
6617     }
6618 
6619     if (could_have_src && could_have_dest) {
6620       // This is going to pay off so emit the required guards
6621       if (!has_src) {
6622         src = maybe_cast_profiled_obj(src, src_k, true);
6623         src_type  = _gvn.type(src);
6624         top_src  = src_type->isa_aryptr();
6625         has_src = (top_src != nullptr && top_src->elem() != Type::BOTTOM);
6626         src_spec = true;
6627       }
6628       if (!has_dest) {
6629         dest = maybe_cast_profiled_obj(dest, dest_k, true);
6630         dest_type  = _gvn.type(dest);
6631         top_dest  = dest_type->isa_aryptr();
6632         has_dest = (top_dest != nullptr && top_dest->elem() != Type::BOTTOM);
6633         dest_spec = true;
6634       }
6635     }
6636   }
6637 
6638   if (has_src && has_dest && can_emit_guards) {
6639     BasicType src_elem = top_src->isa_aryptr()->elem()->array_element_basic_type();
6640     BasicType dest_elem = top_dest->isa_aryptr()->elem()->array_element_basic_type();
6641     if (is_reference_type(src_elem, true)) src_elem = T_OBJECT;
6642     if (is_reference_type(dest_elem, true)) dest_elem = T_OBJECT;
6643 
6644     if (src_elem == dest_elem && top_src->is_flat() == top_dest->is_flat() && src_elem == T_OBJECT) {
6645       // If both arrays are object arrays then having the exact types
6646       // for both will remove the need for a subtype check at runtime
6647       // before the call and may make it possible to pick a faster copy
6648       // routine (without a subtype check on every element)
6649       // Do we have the exact type of src?
6650       bool could_have_src = src_spec;
6651       // Do we have the exact type of dest?
6652       bool could_have_dest = dest_spec;
6653       ciKlass* src_k = nullptr;
6654       ciKlass* dest_k = nullptr;
6655       if (!src_spec) {
6656         src_k = src_type->speculative_type_not_null();
6657         if (src_k != nullptr && src_k->is_array_klass()) {
6658           could_have_src = true;
6659         }
6660       }
6661       if (!dest_spec) {
6662         dest_k = dest_type->speculative_type_not_null();
6663         if (dest_k != nullptr && dest_k->is_array_klass()) {
6664           could_have_dest = true;
6665         }
6666       }
6667       if (could_have_src && could_have_dest) {
6668         // If we can have both exact types, emit the missing guards
6669         if (could_have_src && !src_spec) {
6670           src = maybe_cast_profiled_obj(src, src_k, true);
6671           src_type = _gvn.type(src);
6672           top_src = src_type->isa_aryptr();
6673         }
6674         if (could_have_dest && !dest_spec) {
6675           dest = maybe_cast_profiled_obj(dest, dest_k, true);
6676           dest_type = _gvn.type(dest);
6677           top_dest = dest_type->isa_aryptr();
6678         }
6679       }
6680     }
6681   }
6682 
6683   ciMethod* trap_method = method();
6684   int trap_bci = bci();
6685   if (saved_jvms_before_guards != nullptr) {
6686     trap_method = alloc->jvms()->method();
6687     trap_bci = alloc->jvms()->bci();
6688   }
6689 
6690   bool negative_length_guard_generated = false;
6691 
6692   if (!C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_intrinsic) &&
6693       can_emit_guards && !src->is_top() && !dest->is_top()) {
6694     // validate arguments: enables transformation the ArrayCopyNode
6695     validated = true;
6696 
6697     RegionNode* slow_region = new RegionNode(1);
6698     record_for_igvn(slow_region);
6699 
6700     // (1) src and dest are arrays.
6701     generate_non_array_guard(load_object_klass(src), slow_region, &src);
6702     generate_non_array_guard(load_object_klass(dest), slow_region, &dest);
6703 
6704     // (2) src and dest arrays must have elements of the same BasicType
6705     // done at macro expansion or at Ideal transformation time
6706 
6707     // (4) src_offset must not be negative.
6708     generate_negative_guard(src_offset, slow_region);
6709 
6710     // (5) dest_offset must not be negative.
6711     generate_negative_guard(dest_offset, slow_region);
6712 
6713     // (7) src_offset + length must not exceed length of src.
6714     generate_limit_guard(src_offset, length,
6715                          load_array_length(src),
6716                          slow_region);
6717 
6718     // (8) dest_offset + length must not exceed length of dest.
6719     generate_limit_guard(dest_offset, length,
6720                          load_array_length(dest),
6721                          slow_region);
6722 
6723     // (6) length must not be negative.
6724     // This is also checked in generate_arraycopy() during macro expansion, but
6725     // we also have to check it here for the case where the ArrayCopyNode will
6726     // be eliminated by Escape Analysis.
6727     if (EliminateAllocations) {
6728       generate_negative_guard(length, slow_region);
6729       negative_length_guard_generated = true;
6730     }
6731 
6732     // (9) each element of an oop array must be assignable
6733     Node* dest_klass = load_object_klass(dest);
6734     Node* refined_dest_klass = dest_klass;
6735     if (src != dest) {
6736       dest_klass = load_non_refined_array_klass(refined_dest_klass);
6737       Node* not_subtype_ctrl = gen_subtype_check(src, dest_klass);
6738       slow_region->add_req(not_subtype_ctrl);
6739     }
6740 
6741     // TODO 8350865 Improve this. What about atomicity? Make sure this is always folded for type arrays.
6742     // If destination is null-restricted, source must be null-restricted as well: src_null_restricted || !dst_null_restricted
6743     Node* src_klass = load_object_klass(src);
6744     Node* adr_prop_src = basic_plus_adr(top(), src_klass, in_bytes(ArrayKlass::properties_offset()));
6745     Node* prop_src = _gvn.transform(LoadNode::make(_gvn, control(), immutable_memory(), adr_prop_src, TypeRawPtr::BOTTOM, TypeInt::INT, T_INT, MemNode::unordered));
6746     Node* adr_prop_dest = basic_plus_adr(top(), refined_dest_klass, in_bytes(ArrayKlass::properties_offset()));
6747     Node* prop_dest = _gvn.transform(LoadNode::make(_gvn, control(), immutable_memory(), adr_prop_dest, TypeRawPtr::BOTTOM, TypeInt::INT, T_INT, MemNode::unordered));
6748 
6749     const ArrayProperties props_null_restricted = ArrayProperties::Default().with_null_restricted();
6750     jint props_value = (jint)props_null_restricted.value();
6751 
6752     prop_dest = _gvn.transform(new XorINode(prop_dest, intcon(props_value)));
6753     prop_src = _gvn.transform(new OrINode(prop_dest, prop_src));
6754     prop_src = _gvn.transform(new AndINode(prop_src, intcon(props_value)));
6755 
6756     Node* chk = _gvn.transform(new CmpINode(prop_src, intcon(props_value)));
6757     Node* tst = _gvn.transform(new BoolNode(chk, BoolTest::ne));
6758     generate_fair_guard(tst, slow_region);
6759 
6760     // TODO 8350865 This is too strong
6761     generate_fair_guard(flat_array_test(src), slow_region);
6762     generate_fair_guard(flat_array_test(dest), slow_region);
6763 
6764     {
6765       PreserveJVMState pjvms(this);
6766       set_control(_gvn.transform(slow_region));
6767       uncommon_trap(Deoptimization::Reason_intrinsic,
6768                     Deoptimization::Action_make_not_entrant);
6769       assert(stopped(), "Should be stopped");
6770     }
6771 
6772     const TypeKlassPtr* dest_klass_t = _gvn.type(dest_klass)->isa_klassptr();
6773     if (dest_klass_t == nullptr) {
6774       // refined_dest_klass may not be an array, which leads to dest_klass being top. This means we
6775       // are in a dead path.
6776       uncommon_trap(Deoptimization::Reason_intrinsic,
6777                     Deoptimization::Action_make_not_entrant);
6778       return true;
6779     }
6780 
6781     const Type* toop = dest_klass_t->cast_to_exactness(false)->as_instance_type();
6782     src = _gvn.transform(new CheckCastPPNode(control(), src, toop));
6783     arraycopy_move_allocation_here(alloc, dest, saved_jvms_before_guards, saved_reexecute_sp, new_idx);
6784   }
6785 
6786   if (stopped()) {
6787     return true;
6788   }
6789 
6790   Node* dest_klass = load_object_klass(dest);
6791   dest_klass = load_non_refined_array_klass(dest_klass);
6792 
6793   ArrayCopyNode* ac = ArrayCopyNode::make(this, true, src, src_offset, dest, dest_offset, length, alloc != nullptr, negative_length_guard_generated,
6794                                           // Create LoadRange and LoadKlass nodes for use during macro expansion here
6795                                           // so the compiler has a chance to eliminate them: during macro expansion,
6796                                           // we have to set their control (CastPP nodes are eliminated).
6797                                           load_object_klass(src), dest_klass,
6798                                           load_array_length(src), load_array_length(dest));
6799 
6800   ac->set_arraycopy(validated);
6801 
6802   Node* n = _gvn.transform(ac);
6803   if (n == ac) {
6804     ac->connect_outputs(this);
6805   } else {
6806     assert(validated, "shouldn't transform if all arguments not validated");
6807     set_all_memory(n);
6808   }
6809   clear_upper_avx();
6810 
6811 
6812   return true;
6813 }
6814 
6815 
6816 // Helper function which determines if an arraycopy immediately follows
6817 // an allocation, with no intervening tests or other escapes for the object.
6818 AllocateArrayNode*
6819 LibraryCallKit::tightly_coupled_allocation(Node* ptr) {
6820   if (stopped())             return nullptr;  // no fast path
6821   if (!C->do_aliasing())     return nullptr;  // no MergeMems around
6822 
6823   AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(ptr);
6824   if (alloc == nullptr)  return nullptr;
6825 
6826   Node* rawmem = memory(Compile::AliasIdxRaw);
6827   // Is the allocation's memory state untouched?
6828   if (!(rawmem->is_Proj() && rawmem->in(0)->is_Initialize())) {
6829     // Bail out if there have been raw-memory effects since the allocation.
6830     // (Example:  There might have been a call or safepoint.)
6831     return nullptr;
6832   }
6833   rawmem = rawmem->in(0)->as_Initialize()->memory(Compile::AliasIdxRaw);
6834   if (!(rawmem->is_Proj() && rawmem->in(0) == alloc)) {
6835     return nullptr;
6836   }
6837 
6838   // There must be no unexpected observers of this allocation.
6839   for (DUIterator_Fast imax, i = ptr->fast_outs(imax); i < imax; i++) {
6840     Node* obs = ptr->fast_out(i);
6841     if (obs != this->map()) {
6842       return nullptr;
6843     }
6844   }
6845 
6846   // This arraycopy must unconditionally follow the allocation of the ptr.
6847   Node* alloc_ctl = ptr->in(0);
6848   Node* ctl = control();
6849   while (ctl != alloc_ctl) {
6850     // There may be guards which feed into the slow_region.
6851     // Any other control flow means that we might not get a chance
6852     // to finish initializing the allocated object.
6853     // Various low-level checks bottom out in uncommon traps. These
6854     // are considered safe since we've already checked above that
6855     // there is no unexpected observer of this allocation.
6856     if (get_uncommon_trap_from_success_proj(ctl) != nullptr) {
6857       assert(ctl->in(0)->is_If(), "must be If");
6858       ctl = ctl->in(0)->in(0);
6859     } else {
6860       return nullptr;
6861     }
6862   }
6863 
6864   // If we get this far, we have an allocation which immediately
6865   // precedes the arraycopy, and we can take over zeroing the new object.
6866   // The arraycopy will finish the initialization, and provide
6867   // a new control state to which we will anchor the destination pointer.
6868 
6869   return alloc;
6870 }
6871 
6872 CallStaticJavaNode* LibraryCallKit::get_uncommon_trap_from_success_proj(Node* node) {
6873   if (node->is_IfProj()) {
6874     IfProjNode* other_proj = node->as_IfProj()->other_if_proj();
6875     for (DUIterator_Fast jmax, j = other_proj->fast_outs(jmax); j < jmax; j++) {
6876       Node* obs = other_proj->fast_out(j);
6877       if (obs->in(0) == other_proj && obs->is_CallStaticJava() &&
6878           (obs->as_CallStaticJava()->entry_point() == OptoRuntime::uncommon_trap_blob()->entry_point())) {
6879         return obs->as_CallStaticJava();
6880       }
6881     }
6882   }
6883   return nullptr;
6884 }
6885 
6886 //-------------inline_encodeISOArray-----------------------------------
6887 // int sun.nio.cs.ISO_8859_1.Encoder#encodeISOArray0(byte[] sa, int sp, byte[] da, int dp, int len)
6888 // int java.lang.StringCoding#encodeISOArray0(byte[] sa, int sp, byte[] da, int dp, int len)
6889 // int java.lang.StringCoding#encodeAsciiArray0(char[] sa, int sp, byte[] da, int dp, int len)
6890 // encode char[] to byte[] in ISO_8859_1 or ASCII
6891 bool LibraryCallKit::inline_encodeISOArray(bool ascii) {
6892   assert(callee()->signature()->size() == 5, "encodeISOArray has 5 parameters");
6893   // no receiver since it is static method
6894   Node *src         = argument(0);
6895   Node *src_offset  = argument(1);
6896   Node *dst         = argument(2);
6897   Node *dst_offset  = argument(3);
6898   Node *length      = argument(4);
6899 
6900   // Cast source & target arrays to not-null
6901   src = must_be_not_null(src, true);
6902   dst = must_be_not_null(dst, true);
6903   if (stopped()) {
6904     return true;
6905   }
6906 
6907   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
6908   const TypeAryPtr* dst_type = dst->Value(&_gvn)->isa_aryptr();
6909   if (src_type == nullptr || src_type->elem() == Type::BOTTOM ||
6910       dst_type == nullptr || dst_type->elem() == Type::BOTTOM) {
6911     // failed array check
6912     return false;
6913   }
6914 
6915   // Figure out the size and type of the elements we will be copying.
6916   BasicType src_elem = src_type->elem()->array_element_basic_type();
6917   BasicType dst_elem = dst_type->elem()->array_element_basic_type();
6918   if (!((src_elem == T_CHAR) || (src_elem== T_BYTE)) || dst_elem != T_BYTE) {
6919     return false;
6920   }
6921 
6922   // Check source & target bounds
6923   generate_string_range_check(src, src_offset, length, src_elem == T_BYTE, true);
6924   generate_string_range_check(dst, dst_offset, length, false, true);
6925   if (stopped()) {
6926     return true;
6927   }
6928 
6929   Node* src_start = array_element_address(src, src_offset, T_CHAR);
6930   Node* dst_start = array_element_address(dst, dst_offset, dst_elem);
6931   // 'src_start' points to src array + scaled offset
6932   // 'dst_start' points to dst array + scaled offset
6933 
6934   const TypeAryPtr* mtype = TypeAryPtr::BYTES;
6935   Node* enc = new EncodeISOArrayNode(control(), memory(mtype), src_start, dst_start, length, ascii);
6936   enc = _gvn.transform(enc);
6937   Node* res_mem = _gvn.transform(new SCMemProjNode(enc));
6938   set_memory(res_mem, mtype);
6939   set_result(enc);
6940   clear_upper_avx();
6941 
6942   return true;
6943 }
6944 
6945 //-------------inline_multiplyToLen-----------------------------------
6946 bool LibraryCallKit::inline_multiplyToLen() {
6947   assert(UseMultiplyToLenIntrinsic, "not implemented on this platform");
6948 
6949   address stubAddr = StubRoutines::multiplyToLen();
6950   if (stubAddr == nullptr) {
6951     return false; // Intrinsic's stub is not implemented on this platform
6952   }
6953   const char* stubName = "multiplyToLen";
6954 
6955   assert(callee()->signature()->size() == 5, "multiplyToLen has 5 parameters");
6956 
6957   // no receiver because it is a static method
6958   Node* x    = argument(0);
6959   Node* xlen = argument(1);
6960   Node* y    = argument(2);
6961   Node* ylen = argument(3);
6962   Node* z    = argument(4);
6963 
6964   x = must_be_not_null(x, true);
6965   y = must_be_not_null(y, true);
6966 
6967   const TypeAryPtr* x_type = x->Value(&_gvn)->isa_aryptr();
6968   const TypeAryPtr* y_type = y->Value(&_gvn)->isa_aryptr();
6969   if (x_type == nullptr || x_type->elem() == Type::BOTTOM ||
6970       y_type == nullptr || y_type->elem() == Type::BOTTOM) {
6971     // failed array check
6972     return false;
6973   }
6974 
6975   BasicType x_elem = x_type->elem()->array_element_basic_type();
6976   BasicType y_elem = y_type->elem()->array_element_basic_type();
6977   if (x_elem != T_INT || y_elem != T_INT) {
6978     return false;
6979   }
6980 
6981   Node* x_start = array_element_address(x, intcon(0), x_elem);
6982   Node* y_start = array_element_address(y, intcon(0), y_elem);
6983   // 'x_start' points to x array + scaled xlen
6984   // 'y_start' points to y array + scaled ylen
6985 
6986   Node* z_start = array_element_address(z, intcon(0), T_INT);
6987 
6988   Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
6989                                  OptoRuntime::multiplyToLen_Type(),
6990                                  stubAddr, stubName, TypePtr::BOTTOM,
6991                                  x_start, xlen, y_start, ylen, z_start);
6992 
6993   C->set_has_split_ifs(true); // Has chance for split-if optimization
6994   set_result(z);
6995   return true;
6996 }
6997 
6998 //-------------inline_squareToLen------------------------------------
6999 bool LibraryCallKit::inline_squareToLen() {
7000   assert(UseSquareToLenIntrinsic, "not implemented on this platform");
7001 
7002   address stubAddr = StubRoutines::squareToLen();
7003   if (stubAddr == nullptr) {
7004     return false; // Intrinsic's stub is not implemented on this platform
7005   }
7006   const char* stubName = "squareToLen";
7007 
7008   assert(callee()->signature()->size() == 4, "implSquareToLen has 4 parameters");
7009 
7010   Node* x    = argument(0);
7011   Node* len  = argument(1);
7012   Node* z    = argument(2);
7013   Node* zlen = argument(3);
7014 
7015   x = must_be_not_null(x, true);
7016   z = must_be_not_null(z, true);
7017 
7018   const TypeAryPtr* x_type = x->Value(&_gvn)->isa_aryptr();
7019   const TypeAryPtr* z_type = z->Value(&_gvn)->isa_aryptr();
7020   if (x_type == nullptr || x_type->elem() == Type::BOTTOM ||
7021       z_type == nullptr || z_type->elem() == Type::BOTTOM) {
7022     // failed array check
7023     return false;
7024   }
7025 
7026   BasicType x_elem = x_type->elem()->array_element_basic_type();
7027   BasicType z_elem = z_type->elem()->array_element_basic_type();
7028   if (x_elem != T_INT || z_elem != T_INT) {
7029     return false;
7030   }
7031 
7032 
7033   Node* x_start = array_element_address(x, intcon(0), x_elem);
7034   Node* z_start = array_element_address(z, intcon(0), z_elem);
7035 
7036   Node*  call = make_runtime_call(RC_LEAF|RC_NO_FP,
7037                                   OptoRuntime::squareToLen_Type(),
7038                                   stubAddr, stubName, TypePtr::BOTTOM,
7039                                   x_start, len, z_start, zlen);
7040 
7041   set_result(z);
7042   return true;
7043 }
7044 
7045 //-------------inline_mulAdd------------------------------------------
7046 bool LibraryCallKit::inline_mulAdd() {
7047   assert(UseMulAddIntrinsic, "not implemented on this platform");
7048 
7049   address stubAddr = StubRoutines::mulAdd();
7050   if (stubAddr == nullptr) {
7051     return false; // Intrinsic's stub is not implemented on this platform
7052   }
7053   const char* stubName = "mulAdd";
7054 
7055   assert(callee()->signature()->size() == 5, "mulAdd has 5 parameters");
7056 
7057   Node* out      = argument(0);
7058   Node* in       = argument(1);
7059   Node* offset   = argument(2);
7060   Node* len      = argument(3);
7061   Node* k        = argument(4);
7062 
7063   in = must_be_not_null(in, true);
7064   out = must_be_not_null(out, true);
7065 
7066   const TypeAryPtr* out_type = out->Value(&_gvn)->isa_aryptr();
7067   const TypeAryPtr* in_type = in->Value(&_gvn)->isa_aryptr();
7068   if (out_type == nullptr || out_type->elem() == Type::BOTTOM ||
7069        in_type == nullptr ||  in_type->elem() == Type::BOTTOM) {
7070     // failed array check
7071     return false;
7072   }
7073 
7074   BasicType out_elem = out_type->elem()->array_element_basic_type();
7075   BasicType in_elem = in_type->elem()->array_element_basic_type();
7076   if (out_elem != T_INT || in_elem != T_INT) {
7077     return false;
7078   }
7079 
7080   Node* outlen = load_array_length(out);
7081   Node* new_offset = _gvn.transform(new SubINode(outlen, offset));
7082   Node* out_start = array_element_address(out, intcon(0), out_elem);
7083   Node* in_start = array_element_address(in, intcon(0), in_elem);
7084 
7085   Node*  call = make_runtime_call(RC_LEAF|RC_NO_FP,
7086                                   OptoRuntime::mulAdd_Type(),
7087                                   stubAddr, stubName, TypePtr::BOTTOM,
7088                                   out_start,in_start, new_offset, len, k);
7089   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7090   set_result(result);
7091   return true;
7092 }
7093 
7094 //-------------inline_montgomeryMultiply-----------------------------------
7095 bool LibraryCallKit::inline_montgomeryMultiply() {
7096   address stubAddr = StubRoutines::montgomeryMultiply();
7097   if (stubAddr == nullptr) {
7098     return false; // Intrinsic's stub is not implemented on this platform
7099   }
7100 
7101   assert(UseMontgomeryMultiplyIntrinsic, "not implemented on this platform");
7102   const char* stubName = "montgomery_multiply";
7103 
7104   assert(callee()->signature()->size() == 7, "montgomeryMultiply has 7 parameters");
7105 
7106   Node* a    = argument(0);
7107   Node* b    = argument(1);
7108   Node* n    = argument(2);
7109   Node* len  = argument(3);
7110   Node* inv  = argument(4);
7111   Node* m    = argument(6);
7112 
7113   const TypeAryPtr* a_type = a->Value(&_gvn)->isa_aryptr();
7114   const TypeAryPtr* b_type = b->Value(&_gvn)->isa_aryptr();
7115   const TypeAryPtr* n_type = n->Value(&_gvn)->isa_aryptr();
7116   const TypeAryPtr* m_type = m->Value(&_gvn)->isa_aryptr();
7117   if (a_type == nullptr || a_type->elem() == Type::BOTTOM ||
7118       b_type == nullptr || b_type->elem() == Type::BOTTOM ||
7119       n_type == nullptr || n_type->elem() == Type::BOTTOM ||
7120       m_type == nullptr || m_type->elem() == Type::BOTTOM) {
7121     // failed array check
7122     return false;
7123   }
7124 
7125   BasicType a_elem = a_type->elem()->array_element_basic_type();
7126   BasicType b_elem = b_type->elem()->array_element_basic_type();
7127   BasicType n_elem = n_type->elem()->array_element_basic_type();
7128   BasicType m_elem = m_type->elem()->array_element_basic_type();
7129   if (a_elem != T_INT || b_elem != T_INT || n_elem != T_INT || m_elem != T_INT) {
7130     return false;
7131   }
7132 
7133   // Make the call
7134   {
7135     Node* a_start = array_element_address(a, intcon(0), a_elem);
7136     Node* b_start = array_element_address(b, intcon(0), b_elem);
7137     Node* n_start = array_element_address(n, intcon(0), n_elem);
7138     Node* m_start = array_element_address(m, intcon(0), m_elem);
7139 
7140     Node* call = make_runtime_call(RC_LEAF,
7141                                    OptoRuntime::montgomeryMultiply_Type(),
7142                                    stubAddr, stubName, TypePtr::BOTTOM,
7143                                    a_start, b_start, n_start, len, inv, top(),
7144                                    m_start);
7145     set_result(m);
7146   }
7147 
7148   return true;
7149 }
7150 
7151 bool LibraryCallKit::inline_montgomerySquare() {
7152   address stubAddr = StubRoutines::montgomerySquare();
7153   if (stubAddr == nullptr) {
7154     return false; // Intrinsic's stub is not implemented on this platform
7155   }
7156 
7157   assert(UseMontgomerySquareIntrinsic, "not implemented on this platform");
7158   const char* stubName = "montgomery_square";
7159 
7160   assert(callee()->signature()->size() == 6, "montgomerySquare has 6 parameters");
7161 
7162   Node* a    = argument(0);
7163   Node* n    = argument(1);
7164   Node* len  = argument(2);
7165   Node* inv  = argument(3);
7166   Node* m    = argument(5);
7167 
7168   const TypeAryPtr* a_type = a->Value(&_gvn)->isa_aryptr();
7169   const TypeAryPtr* n_type = n->Value(&_gvn)->isa_aryptr();
7170   const TypeAryPtr* m_type = m->Value(&_gvn)->isa_aryptr();
7171   if (a_type == nullptr || a_type->elem() == Type::BOTTOM ||
7172       n_type == nullptr || n_type->elem() == Type::BOTTOM ||
7173       m_type == nullptr || m_type->elem() == Type::BOTTOM) {
7174     // failed array check
7175     return false;
7176   }
7177 
7178   BasicType a_elem = a_type->elem()->array_element_basic_type();
7179   BasicType n_elem = n_type->elem()->array_element_basic_type();
7180   BasicType m_elem = m_type->elem()->array_element_basic_type();
7181   if (a_elem != T_INT || n_elem != T_INT || m_elem != T_INT) {
7182     return false;
7183   }
7184 
7185   // Make the call
7186   {
7187     Node* a_start = array_element_address(a, intcon(0), a_elem);
7188     Node* n_start = array_element_address(n, intcon(0), n_elem);
7189     Node* m_start = array_element_address(m, intcon(0), m_elem);
7190 
7191     Node* call = make_runtime_call(RC_LEAF,
7192                                    OptoRuntime::montgomerySquare_Type(),
7193                                    stubAddr, stubName, TypePtr::BOTTOM,
7194                                    a_start, n_start, len, inv, top(),
7195                                    m_start);
7196     set_result(m);
7197   }
7198 
7199   return true;
7200 }
7201 
7202 bool LibraryCallKit::inline_bigIntegerShift(bool isRightShift) {
7203   address stubAddr = nullptr;
7204   const char* stubName = nullptr;
7205 
7206   stubAddr = isRightShift? StubRoutines::bigIntegerRightShift(): StubRoutines::bigIntegerLeftShift();
7207   if (stubAddr == nullptr) {
7208     return false; // Intrinsic's stub is not implemented on this platform
7209   }
7210 
7211   stubName = isRightShift? "bigIntegerRightShiftWorker" : "bigIntegerLeftShiftWorker";
7212 
7213   assert(callee()->signature()->size() == 5, "expected 5 arguments");
7214 
7215   Node* newArr = argument(0);
7216   Node* oldArr = argument(1);
7217   Node* newIdx = argument(2);
7218   Node* shiftCount = argument(3);
7219   Node* numIter = argument(4);
7220 
7221   const TypeAryPtr* newArr_type = newArr->Value(&_gvn)->isa_aryptr();
7222   const TypeAryPtr* oldArr_type = oldArr->Value(&_gvn)->isa_aryptr();
7223   if (newArr_type == nullptr || newArr_type->elem() == Type::BOTTOM ||
7224       oldArr_type == nullptr || oldArr_type->elem() == Type::BOTTOM) {
7225     return false;
7226   }
7227 
7228   BasicType newArr_elem = newArr_type->elem()->array_element_basic_type();
7229   BasicType oldArr_elem = oldArr_type->elem()->array_element_basic_type();
7230   if (newArr_elem != T_INT || oldArr_elem != T_INT) {
7231     return false;
7232   }
7233 
7234   // Make the call
7235   {
7236     Node* newArr_start = array_element_address(newArr, intcon(0), newArr_elem);
7237     Node* oldArr_start = array_element_address(oldArr, intcon(0), oldArr_elem);
7238 
7239     Node* call = make_runtime_call(RC_LEAF,
7240                                    OptoRuntime::bigIntegerShift_Type(),
7241                                    stubAddr,
7242                                    stubName,
7243                                    TypePtr::BOTTOM,
7244                                    newArr_start,
7245                                    oldArr_start,
7246                                    newIdx,
7247                                    shiftCount,
7248                                    numIter);
7249   }
7250 
7251   return true;
7252 }
7253 
7254 //-------------inline_vectorizedMismatch------------------------------
7255 bool LibraryCallKit::inline_vectorizedMismatch() {
7256   assert(UseVectorizedMismatchIntrinsic, "not implemented on this platform");
7257 
7258   assert(callee()->signature()->size() == 8, "vectorizedMismatch has 6 parameters");
7259   Node* obja    = argument(0); // Object
7260   Node* aoffset = argument(1); // long
7261   Node* objb    = argument(3); // Object
7262   Node* boffset = argument(4); // long
7263   Node* length  = argument(6); // int
7264   Node* scale   = argument(7); // int
7265 
7266   const TypeAryPtr* obja_t = _gvn.type(obja)->isa_aryptr();
7267   const TypeAryPtr* objb_t = _gvn.type(objb)->isa_aryptr();
7268   if (obja_t == nullptr || obja_t->elem() == Type::BOTTOM ||
7269       objb_t == nullptr || objb_t->elem() == Type::BOTTOM ||
7270       scale == top()) {
7271     return false; // failed input validation
7272   }
7273 
7274   Node* obja_adr = make_unsafe_address(obja, aoffset);
7275   Node* objb_adr = make_unsafe_address(objb, boffset);
7276 
7277   // Partial inlining handling for inputs smaller than ArrayOperationPartialInlineSize bytes in size.
7278   //
7279   //    inline_limit = ArrayOperationPartialInlineSize / element_size;
7280   //    if (length <= inline_limit) {
7281   //      inline_path:
7282   //        vmask   = VectorMaskGen length
7283   //        vload1  = LoadVectorMasked obja, vmask
7284   //        vload2  = LoadVectorMasked objb, vmask
7285   //        result1 = VectorCmpMasked vload1, vload2, vmask
7286   //    } else {
7287   //      call_stub_path:
7288   //        result2 = call vectorizedMismatch_stub(obja, objb, length, scale)
7289   //    }
7290   //    exit_block:
7291   //      return Phi(result1, result2);
7292   //
7293   enum { inline_path = 1,  // input is small enough to process it all at once
7294          stub_path   = 2,  // input is too large; call into the VM
7295          PATH_LIMIT  = 3
7296   };
7297 
7298   Node* exit_block = new RegionNode(PATH_LIMIT);
7299   Node* result_phi = new PhiNode(exit_block, TypeInt::INT);
7300   Node* memory_phi = new PhiNode(exit_block, Type::MEMORY, TypePtr::BOTTOM);
7301 
7302   Node* call_stub_path = control();
7303 
7304   BasicType elem_bt = T_ILLEGAL;
7305 
7306   const TypeInt* scale_t = _gvn.type(scale)->is_int();
7307   if (scale_t->is_con()) {
7308     switch (scale_t->get_con()) {
7309       case 0: elem_bt = T_BYTE;  break;
7310       case 1: elem_bt = T_SHORT; break;
7311       case 2: elem_bt = T_INT;   break;
7312       case 3: elem_bt = T_LONG;  break;
7313 
7314       default: elem_bt = T_ILLEGAL; break; // not supported
7315     }
7316   }
7317 
7318   int inline_limit = 0;
7319   bool do_partial_inline = false;
7320 
7321   if (elem_bt != T_ILLEGAL && ArrayOperationPartialInlineSize > 0) {
7322     inline_limit = ArrayOperationPartialInlineSize / type2aelembytes(elem_bt);
7323     do_partial_inline = inline_limit >= 16;
7324   }
7325 
7326   if (do_partial_inline) {
7327     assert(elem_bt != T_ILLEGAL, "sanity");
7328 
7329     if (Matcher::match_rule_supported_vector(Op_VectorMaskGen,    inline_limit, elem_bt) &&
7330         Matcher::match_rule_supported_vector(Op_LoadVectorMasked, inline_limit, elem_bt) &&
7331         Matcher::match_rule_supported_vector(Op_VectorCmpMasked,  inline_limit, elem_bt)) {
7332 
7333       const TypeVect* vt = TypeVect::make(elem_bt, inline_limit);
7334       Node* cmp_length = _gvn.transform(new CmpINode(length, intcon(inline_limit)));
7335       Node* bol_gt     = _gvn.transform(new BoolNode(cmp_length, BoolTest::gt));
7336 
7337       call_stub_path = generate_guard(bol_gt, nullptr, PROB_MIN);
7338 
7339       if (!stopped()) {
7340         Node* casted_length = _gvn.transform(new CastIINode(control(), length, TypeInt::make(0, inline_limit, Type::WidenMin)));
7341 
7342         const TypePtr* obja_adr_t = _gvn.type(obja_adr)->isa_ptr();
7343         const TypePtr* objb_adr_t = _gvn.type(objb_adr)->isa_ptr();
7344         Node* obja_adr_mem = memory(C->get_alias_index(obja_adr_t));
7345         Node* objb_adr_mem = memory(C->get_alias_index(objb_adr_t));
7346 
7347         Node* vmask      = _gvn.transform(VectorMaskGenNode::make(ConvI2X(casted_length), elem_bt));
7348         Node* vload_obja = _gvn.transform(new LoadVectorMaskedNode(control(), obja_adr_mem, obja_adr, obja_adr_t, vt, vmask));
7349         Node* vload_objb = _gvn.transform(new LoadVectorMaskedNode(control(), objb_adr_mem, objb_adr, objb_adr_t, vt, vmask));
7350         Node* result     = _gvn.transform(new VectorCmpMaskedNode(vload_obja, vload_objb, vmask, TypeInt::INT));
7351 
7352         exit_block->init_req(inline_path, control());
7353         memory_phi->init_req(inline_path, map()->memory());
7354         result_phi->init_req(inline_path, result);
7355 
7356         C->set_max_vector_size(MAX2((uint)ArrayOperationPartialInlineSize, C->max_vector_size()));
7357         clear_upper_avx();
7358       }
7359     }
7360   }
7361 
7362   if (call_stub_path != nullptr) {
7363     set_control(call_stub_path);
7364 
7365     Node* call = make_runtime_call(RC_LEAF,
7366                                    OptoRuntime::vectorizedMismatch_Type(),
7367                                    StubRoutines::vectorizedMismatch(), "vectorizedMismatch", TypePtr::BOTTOM,
7368                                    obja_adr, objb_adr, length, scale);
7369 
7370     exit_block->init_req(stub_path, control());
7371     memory_phi->init_req(stub_path, map()->memory());
7372     result_phi->init_req(stub_path, _gvn.transform(new ProjNode(call, TypeFunc::Parms)));
7373   }
7374 
7375   exit_block = _gvn.transform(exit_block);
7376   memory_phi = _gvn.transform(memory_phi);
7377   result_phi = _gvn.transform(result_phi);
7378 
7379   record_for_igvn(exit_block);
7380   record_for_igvn(memory_phi);
7381   record_for_igvn(result_phi);
7382 
7383   set_control(exit_block);
7384   set_all_memory(memory_phi);
7385   set_result(result_phi);
7386 
7387   return true;
7388 }
7389 
7390 //------------------------------inline_vectorizedHashcode----------------------------
7391 bool LibraryCallKit::inline_vectorizedHashCode() {
7392   assert(UseVectorizedHashCodeIntrinsic, "not implemented on this platform");
7393 
7394   assert(callee()->signature()->size() == 5, "vectorizedHashCode has 5 parameters");
7395   Node* array          = argument(0);
7396   Node* offset         = argument(1);
7397   Node* length         = argument(2);
7398   Node* initialValue   = argument(3);
7399   Node* basic_type     = argument(4);
7400 
7401   if (basic_type == top()) {
7402     return false; // failed input validation
7403   }
7404 
7405   const TypeInt* basic_type_t = _gvn.type(basic_type)->is_int();
7406   if (!basic_type_t->is_con()) {
7407     return false; // Only intrinsify if mode argument is constant
7408   }
7409 
7410   array = must_be_not_null(array, true);
7411 
7412   BasicType bt = (BasicType)basic_type_t->get_con();
7413 
7414   // Resolve address of first element
7415   Node* array_start = array_element_address(array, offset, bt);
7416 
7417   set_result(_gvn.transform(new VectorizedHashCodeNode(control(), memory(TypeAryPtr::get_array_body_type(bt)),
7418     array_start, length, initialValue, basic_type)));
7419   clear_upper_avx();
7420 
7421   return true;
7422 }
7423 
7424 /**
7425  * Calculate CRC32 for byte.
7426  * int java.util.zip.CRC32.update(int crc, int b)
7427  */
7428 bool LibraryCallKit::inline_updateCRC32() {
7429   assert(UseCRC32Intrinsics, "need AVX and CLMUL instructions support");
7430   assert(callee()->signature()->size() == 2, "update has 2 parameters");
7431   // no receiver since it is static method
7432   Node* crc  = argument(0); // type: int
7433   Node* b    = argument(1); // type: int
7434 
7435   /*
7436    *    int c = ~ crc;
7437    *    b = timesXtoThe32[(b ^ c) & 0xFF];
7438    *    b = b ^ (c >>> 8);
7439    *    crc = ~b;
7440    */
7441 
7442   Node* M1 = intcon(-1);
7443   crc = _gvn.transform(new XorINode(crc, M1));
7444   Node* result = _gvn.transform(new XorINode(crc, b));
7445   result = _gvn.transform(new AndINode(result, intcon(0xFF)));
7446 
7447   Node* base = makecon(TypeRawPtr::make(StubRoutines::crc_table_addr()));
7448   Node* offset = _gvn.transform(new LShiftINode(result, intcon(0x2)));
7449   Node* adr = basic_plus_adr(top(), base, ConvI2X(offset));
7450   result = make_load(control(), adr, TypeInt::INT, T_INT, MemNode::unordered);
7451 
7452   crc = _gvn.transform(new URShiftINode(crc, intcon(8)));
7453   result = _gvn.transform(new XorINode(crc, result));
7454   result = _gvn.transform(new XorINode(result, M1));
7455   set_result(result);
7456   return true;
7457 }
7458 
7459 /**
7460  * Calculate CRC32 for byte[] array.
7461  * int java.util.zip.CRC32.updateBytes(int crc, byte[] buf, int off, int len)
7462  */
7463 bool LibraryCallKit::inline_updateBytesCRC32() {
7464   assert(UseCRC32Intrinsics, "need AVX and CLMUL instructions support");
7465   assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
7466   // no receiver since it is static method
7467   Node* crc     = argument(0); // type: int
7468   Node* src     = argument(1); // type: oop
7469   Node* offset  = argument(2); // type: int
7470   Node* length  = argument(3); // type: int
7471 
7472   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7473   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
7474     // failed array check
7475     return false;
7476   }
7477 
7478   // Figure out the size and type of the elements we will be copying.
7479   BasicType src_elem = src_type->elem()->array_element_basic_type();
7480   if (src_elem != T_BYTE) {
7481     return false;
7482   }
7483 
7484   // 'src_start' points to src array + scaled offset
7485   src = must_be_not_null(src, true);
7486   Node* src_start = array_element_address(src, offset, src_elem);
7487 
7488   // We assume that range check is done by caller.
7489   // TODO: generate range check (offset+length < src.length) in debug VM.
7490 
7491   // Call the stub.
7492   address stubAddr = StubRoutines::updateBytesCRC32();
7493   const char *stubName = "updateBytesCRC32";
7494 
7495   Node* call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::updateBytesCRC32_Type(),
7496                                  stubAddr, stubName, TypePtr::BOTTOM,
7497                                  crc, src_start, length);
7498   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7499   set_result(result);
7500   return true;
7501 }
7502 
7503 /**
7504  * Calculate CRC32 for ByteBuffer.
7505  * int java.util.zip.CRC32.updateByteBuffer(int crc, long buf, int off, int len)
7506  */
7507 bool LibraryCallKit::inline_updateByteBufferCRC32() {
7508   assert(UseCRC32Intrinsics, "need AVX and CLMUL instructions support");
7509   assert(callee()->signature()->size() == 5, "updateByteBuffer has 4 parameters and one is long");
7510   // no receiver since it is static method
7511   Node* crc     = argument(0); // type: int
7512   Node* src     = argument(1); // type: long
7513   Node* offset  = argument(3); // type: int
7514   Node* length  = argument(4); // type: int
7515 
7516   src = ConvL2X(src);  // adjust Java long to machine word
7517   Node* base = _gvn.transform(new CastX2PNode(src));
7518   offset = ConvI2X(offset);
7519 
7520   // 'src_start' points to src array + scaled offset
7521   Node* src_start = basic_plus_adr(top(), base, offset);
7522 
7523   // Call the stub.
7524   address stubAddr = StubRoutines::updateBytesCRC32();
7525   const char *stubName = "updateBytesCRC32";
7526 
7527   Node* call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::updateBytesCRC32_Type(),
7528                                  stubAddr, stubName, TypePtr::BOTTOM,
7529                                  crc, src_start, length);
7530   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7531   set_result(result);
7532   return true;
7533 }
7534 
7535 //------------------------------get_table_from_crc32c_class-----------------------
7536 Node * LibraryCallKit::get_table_from_crc32c_class(ciInstanceKlass *crc32c_class) {
7537   Node* table = load_field_from_object(nullptr, "byteTable", "[I", /*decorators*/ IN_HEAP, /*is_static*/ true, crc32c_class);
7538   assert (table != nullptr, "wrong version of java.util.zip.CRC32C");
7539 
7540   return table;
7541 }
7542 
7543 //------------------------------inline_updateBytesCRC32C-----------------------
7544 //
7545 // Calculate CRC32C for byte[] array.
7546 // int java.util.zip.CRC32C.updateBytes(int crc, byte[] buf, int off, int end)
7547 //
7548 bool LibraryCallKit::inline_updateBytesCRC32C() {
7549   assert(UseCRC32CIntrinsics, "need CRC32C instruction support");
7550   assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
7551   assert(callee()->holder()->is_loaded(), "CRC32C class must be loaded");
7552   // no receiver since it is a static method
7553   Node* crc     = argument(0); // type: int
7554   Node* src     = argument(1); // type: oop
7555   Node* offset  = argument(2); // type: int
7556   Node* end     = argument(3); // type: int
7557 
7558   Node* length = _gvn.transform(new SubINode(end, offset));
7559 
7560   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7561   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
7562     // failed array check
7563     return false;
7564   }
7565 
7566   // Figure out the size and type of the elements we will be copying.
7567   BasicType src_elem = src_type->elem()->array_element_basic_type();
7568   if (src_elem != T_BYTE) {
7569     return false;
7570   }
7571 
7572   // 'src_start' points to src array + scaled offset
7573   src = must_be_not_null(src, true);
7574   Node* src_start = array_element_address(src, offset, src_elem);
7575 
7576   // static final int[] byteTable in class CRC32C
7577   Node* table = get_table_from_crc32c_class(callee()->holder());
7578   table = must_be_not_null(table, true);
7579   Node* table_start = array_element_address(table, intcon(0), T_INT);
7580 
7581   // We assume that range check is done by caller.
7582   // TODO: generate range check (offset+length < src.length) in debug VM.
7583 
7584   // Call the stub.
7585   address stubAddr = StubRoutines::updateBytesCRC32C();
7586   const char *stubName = "updateBytesCRC32C";
7587 
7588   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesCRC32C_Type(),
7589                                  stubAddr, stubName, TypePtr::BOTTOM,
7590                                  crc, src_start, length, table_start);
7591   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7592   set_result(result);
7593   return true;
7594 }
7595 
7596 //------------------------------inline_updateDirectByteBufferCRC32C-----------------------
7597 //
7598 // Calculate CRC32C for DirectByteBuffer.
7599 // int java.util.zip.CRC32C.updateDirectByteBuffer(int crc, long buf, int off, int end)
7600 //
7601 bool LibraryCallKit::inline_updateDirectByteBufferCRC32C() {
7602   assert(UseCRC32CIntrinsics, "need CRC32C instruction support");
7603   assert(callee()->signature()->size() == 5, "updateDirectByteBuffer has 4 parameters and one is long");
7604   assert(callee()->holder()->is_loaded(), "CRC32C class must be loaded");
7605   // no receiver since it is a static method
7606   Node* crc     = argument(0); // type: int
7607   Node* src     = argument(1); // type: long
7608   Node* offset  = argument(3); // type: int
7609   Node* end     = argument(4); // type: int
7610 
7611   Node* length = _gvn.transform(new SubINode(end, offset));
7612 
7613   src = ConvL2X(src);  // adjust Java long to machine word
7614   Node* base = _gvn.transform(new CastX2PNode(src));
7615   offset = ConvI2X(offset);
7616 
7617   // 'src_start' points to src array + scaled offset
7618   Node* src_start = basic_plus_adr(top(), base, offset);
7619 
7620   // static final int[] byteTable in class CRC32C
7621   Node* table = get_table_from_crc32c_class(callee()->holder());
7622   table = must_be_not_null(table, true);
7623   Node* table_start = array_element_address(table, intcon(0), T_INT);
7624 
7625   // Call the stub.
7626   address stubAddr = StubRoutines::updateBytesCRC32C();
7627   const char *stubName = "updateBytesCRC32C";
7628 
7629   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesCRC32C_Type(),
7630                                  stubAddr, stubName, TypePtr::BOTTOM,
7631                                  crc, src_start, length, table_start);
7632   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7633   set_result(result);
7634   return true;
7635 }
7636 
7637 //------------------------------inline_updateBytesAdler32----------------------
7638 //
7639 // Calculate Adler32 checksum for byte[] array.
7640 // int java.util.zip.Adler32.updateBytes(int crc, byte[] buf, int off, int len)
7641 //
7642 bool LibraryCallKit::inline_updateBytesAdler32() {
7643   assert(UseAdler32Intrinsics, "Adler32 Intrinsic support need"); // check if we actually need to check this flag or check a different one
7644   assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
7645   assert(callee()->holder()->is_loaded(), "Adler32 class must be loaded");
7646   // no receiver since it is static method
7647   Node* crc     = argument(0); // type: int
7648   Node* src     = argument(1); // type: oop
7649   Node* offset  = argument(2); // type: int
7650   Node* length  = argument(3); // type: int
7651 
7652   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7653   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
7654     // failed array check
7655     return false;
7656   }
7657 
7658   // Figure out the size and type of the elements we will be copying.
7659   BasicType src_elem = src_type->elem()->array_element_basic_type();
7660   if (src_elem != T_BYTE) {
7661     return false;
7662   }
7663 
7664   // 'src_start' points to src array + scaled offset
7665   Node* src_start = array_element_address(src, offset, src_elem);
7666 
7667   // We assume that range check is done by caller.
7668   // TODO: generate range check (offset+length < src.length) in debug VM.
7669 
7670   // Call the stub.
7671   address stubAddr = StubRoutines::updateBytesAdler32();
7672   const char *stubName = "updateBytesAdler32";
7673 
7674   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesAdler32_Type(),
7675                                  stubAddr, stubName, TypePtr::BOTTOM,
7676                                  crc, src_start, length);
7677   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7678   set_result(result);
7679   return true;
7680 }
7681 
7682 //------------------------------inline_updateByteBufferAdler32---------------
7683 //
7684 // Calculate Adler32 checksum for DirectByteBuffer.
7685 // int java.util.zip.Adler32.updateByteBuffer(int crc, long buf, int off, int len)
7686 //
7687 bool LibraryCallKit::inline_updateByteBufferAdler32() {
7688   assert(UseAdler32Intrinsics, "Adler32 Intrinsic support need"); // check if we actually need to check this flag or check a different one
7689   assert(callee()->signature()->size() == 5, "updateByteBuffer has 4 parameters and one is long");
7690   assert(callee()->holder()->is_loaded(), "Adler32 class must be loaded");
7691   // no receiver since it is static method
7692   Node* crc     = argument(0); // type: int
7693   Node* src     = argument(1); // type: long
7694   Node* offset  = argument(3); // type: int
7695   Node* length  = argument(4); // type: int
7696 
7697   src = ConvL2X(src);  // adjust Java long to machine word
7698   Node* base = _gvn.transform(new CastX2PNode(src));
7699   offset = ConvI2X(offset);
7700 
7701   // 'src_start' points to src array + scaled offset
7702   Node* src_start = basic_plus_adr(top(), base, offset);
7703 
7704   // Call the stub.
7705   address stubAddr = StubRoutines::updateBytesAdler32();
7706   const char *stubName = "updateBytesAdler32";
7707 
7708   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesAdler32_Type(),
7709                                  stubAddr, stubName, TypePtr::BOTTOM,
7710                                  crc, src_start, length);
7711 
7712   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7713   set_result(result);
7714   return true;
7715 }
7716 
7717 //----------------------------inline_reference_get0----------------------------
7718 // public T java.lang.ref.Reference.get();
7719 bool LibraryCallKit::inline_reference_get0() {
7720   const int referent_offset = java_lang_ref_Reference::referent_offset();
7721 
7722   // Get the argument:
7723   Node* reference_obj = null_check_receiver();
7724   if (stopped()) return true;
7725 
7726   DecoratorSet decorators = IN_HEAP | ON_WEAK_OOP_REF;
7727   Node* result = load_field_from_object(reference_obj, "referent", "Ljava/lang/Object;",
7728                                         decorators, /*is_static*/ false, nullptr);
7729   if (result == nullptr) return false;
7730 
7731   // Add memory barrier to prevent commoning reads from this field
7732   // across safepoint since GC can change its value.
7733   insert_mem_bar(Op_MemBarCPUOrder);
7734 
7735   set_result(result);
7736   return true;
7737 }
7738 
7739 //----------------------------inline_reference_refersTo0----------------------------
7740 // bool java.lang.ref.Reference.refersTo0();
7741 // bool java.lang.ref.PhantomReference.refersTo0();
7742 bool LibraryCallKit::inline_reference_refersTo0(bool is_phantom) {
7743   // Get arguments:
7744   Node* reference_obj = null_check_receiver();
7745   Node* other_obj = argument(1);
7746   if (stopped()) return true;
7747 
7748   DecoratorSet decorators = IN_HEAP | AS_NO_KEEPALIVE;
7749   decorators |= (is_phantom ? ON_PHANTOM_OOP_REF : ON_WEAK_OOP_REF);
7750   Node* referent = load_field_from_object(reference_obj, "referent", "Ljava/lang/Object;",
7751                                           decorators, /*is_static*/ false, nullptr);
7752   if (referent == nullptr) return false;
7753 
7754   // Add memory barrier to prevent commoning reads from this field
7755   // across safepoint since GC can change its value.
7756   insert_mem_bar(Op_MemBarCPUOrder);
7757 
7758   Node* cmp = _gvn.transform(new CmpPNode(referent, other_obj));
7759   Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
7760   IfNode* if_node = create_and_map_if(control(), bol, PROB_FAIR, COUNT_UNKNOWN);
7761 
7762   RegionNode* region = new RegionNode(3);
7763   PhiNode* phi = new PhiNode(region, TypeInt::BOOL);
7764 
7765   Node* if_true = _gvn.transform(new IfTrueNode(if_node));
7766   region->init_req(1, if_true);
7767   phi->init_req(1, intcon(1));
7768 
7769   Node* if_false = _gvn.transform(new IfFalseNode(if_node));
7770   region->init_req(2, if_false);
7771   phi->init_req(2, intcon(0));
7772 
7773   set_control(_gvn.transform(region));
7774   record_for_igvn(region);
7775   set_result(_gvn.transform(phi));
7776   return true;
7777 }
7778 
7779 //----------------------------inline_reference_clear0----------------------------
7780 // void java.lang.ref.Reference.clear0();
7781 // void java.lang.ref.PhantomReference.clear0();
7782 bool LibraryCallKit::inline_reference_clear0(bool is_phantom) {
7783   // This matches the implementation in JVM_ReferenceClear, see the comments there.
7784 
7785   // Get arguments
7786   Node* reference_obj = null_check_receiver();
7787   if (stopped()) return true;
7788 
7789   // Common access parameters
7790   DecoratorSet decorators = IN_HEAP | AS_NO_KEEPALIVE;
7791   decorators |= (is_phantom ? ON_PHANTOM_OOP_REF : ON_WEAK_OOP_REF);
7792   Node* referent_field_addr = basic_plus_adr(reference_obj, java_lang_ref_Reference::referent_offset());
7793   const TypePtr* referent_field_addr_type = _gvn.type(referent_field_addr)->isa_ptr();
7794   const Type* val_type = TypeOopPtr::make_from_klass(env()->Object_klass());
7795 
7796   Node* referent = access_load_at(reference_obj,
7797                                   referent_field_addr,
7798                                   referent_field_addr_type,
7799                                   val_type,
7800                                   T_OBJECT,
7801                                   decorators);
7802 
7803   IdealKit ideal(this);
7804 #define __ ideal.
7805   __ if_then(referent, BoolTest::ne, null());
7806     sync_kit(ideal);
7807     access_store_at(reference_obj,
7808                     referent_field_addr,
7809                     referent_field_addr_type,
7810                     null(),
7811                     val_type,
7812                     T_OBJECT,
7813                     decorators);
7814     __ sync_kit(this);
7815   __ end_if();
7816   final_sync(ideal);
7817 #undef __
7818 
7819   return true;
7820 }
7821 
7822 Node* LibraryCallKit::load_field_from_object(Node* fromObj, const char* fieldName, const char* fieldTypeString,
7823                                              DecoratorSet decorators, bool is_static,
7824                                              ciInstanceKlass* fromKls) {
7825   if (fromKls == nullptr) {
7826     const TypeInstPtr* tinst = _gvn.type(fromObj)->isa_instptr();
7827     assert(tinst != nullptr, "obj is null");
7828     assert(tinst->is_loaded(), "obj is not loaded");
7829     fromKls = tinst->instance_klass();
7830   } else {
7831     assert(is_static, "only for static field access");
7832   }
7833   ciField* field = fromKls->get_field_by_name(ciSymbol::make(fieldName),
7834                                               ciSymbol::make(fieldTypeString),
7835                                               is_static);
7836 
7837   assert(field != nullptr, "undefined field %s %s %s", fieldTypeString, fromKls->name()->as_utf8(), fieldName);
7838   if (field == nullptr) return (Node *) nullptr;
7839 
7840   if (is_static) {
7841     const TypeInstPtr* tip = TypeInstPtr::make(fromKls->java_mirror());
7842     fromObj = makecon(tip);
7843   }
7844 
7845   // Next code  copied from Parse::do_get_xxx():
7846 
7847   // Compute address and memory type.
7848   int offset  = field->offset_in_bytes();
7849   bool is_vol = field->is_volatile();
7850   ciType* field_klass = field->type();
7851   assert(field_klass->is_loaded(), "should be loaded");
7852   const TypePtr* adr_type = C->alias_type(field)->adr_type();
7853   Node *adr = basic_plus_adr(fromObj, fromObj, offset);
7854   assert(C->get_alias_index(adr_type) == C->get_alias_index(_gvn.type(adr)->isa_ptr()),
7855     "slice of address and input slice don't match");
7856   BasicType bt = field->layout_type();
7857 
7858   // Build the resultant type of the load
7859   const Type *type;
7860   if (bt == T_OBJECT) {
7861     type = TypeOopPtr::make_from_klass(field_klass->as_klass());
7862   } else {
7863     type = Type::get_const_basic_type(bt);
7864   }
7865 
7866   if (is_vol) {
7867     decorators |= MO_SEQ_CST;
7868   }
7869 
7870   return access_load_at(fromObj, adr, adr_type, type, bt, decorators);
7871 }
7872 
7873 Node * LibraryCallKit::field_address_from_object(Node * fromObj, const char * fieldName, const char * fieldTypeString,
7874                                                  bool is_exact /* true */, bool is_static /* false */,
7875                                                  ciInstanceKlass * fromKls /* nullptr */) {
7876   if (fromKls == nullptr) {
7877     const TypeInstPtr* tinst = _gvn.type(fromObj)->isa_instptr();
7878     assert(tinst != nullptr, "obj is null");
7879     assert(tinst->is_loaded(), "obj is not loaded");
7880     assert(!is_exact || tinst->klass_is_exact(), "klass not exact");
7881     fromKls = tinst->instance_klass();
7882   }
7883   else {
7884     assert(is_static, "only for static field access");
7885   }
7886   ciField* field = fromKls->get_field_by_name(ciSymbol::make(fieldName),
7887     ciSymbol::make(fieldTypeString),
7888     is_static);
7889 
7890   assert(field != nullptr, "undefined field");
7891   assert(!field->is_volatile(), "not defined for volatile fields");
7892 
7893   if (is_static) {
7894     const TypeInstPtr* tip = TypeInstPtr::make(fromKls->java_mirror());
7895     fromObj = makecon(tip);
7896   }
7897 
7898   // Next code  copied from Parse::do_get_xxx():
7899 
7900   // Compute address and memory type.
7901   int offset = field->offset_in_bytes();
7902   Node *adr = basic_plus_adr(fromObj, fromObj, offset);
7903 
7904   return adr;
7905 }
7906 
7907 //------------------------------inline_aescrypt_Block-----------------------
7908 bool LibraryCallKit::inline_aescrypt_Block(vmIntrinsics::ID id) {
7909   address stubAddr = nullptr;
7910   const char *stubName;
7911   bool is_decrypt = false;
7912   assert(UseAES, "need AES instruction support");
7913 
7914   switch(id) {
7915   case vmIntrinsics::_aescrypt_encryptBlock:
7916     stubAddr = StubRoutines::aescrypt_encryptBlock();
7917     stubName = "aescrypt_encryptBlock";
7918     break;
7919   case vmIntrinsics::_aescrypt_decryptBlock:
7920     stubAddr = StubRoutines::aescrypt_decryptBlock();
7921     stubName = "aescrypt_decryptBlock";
7922     is_decrypt = true;
7923     break;
7924   default:
7925     break;
7926   }
7927   if (stubAddr == nullptr) return false;
7928 
7929   Node* aescrypt_object = argument(0);
7930   Node* src             = argument(1);
7931   Node* src_offset      = argument(2);
7932   Node* dest            = argument(3);
7933   Node* dest_offset     = argument(4);
7934 
7935   src = must_be_not_null(src, true);
7936   dest = must_be_not_null(dest, true);
7937 
7938   // (1) src and dest are arrays.
7939   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7940   const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
7941   assert( src_type != nullptr &&  src_type->elem() != Type::BOTTOM &&
7942          dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
7943 
7944   // for the quick and dirty code we will skip all the checks.
7945   // we are just trying to get the call to be generated.
7946   Node* src_start  = src;
7947   Node* dest_start = dest;
7948   if (src_offset != nullptr || dest_offset != nullptr) {
7949     assert(src_offset != nullptr && dest_offset != nullptr, "");
7950     src_start  = array_element_address(src,  src_offset,  T_BYTE);
7951     dest_start = array_element_address(dest, dest_offset, T_BYTE);
7952   }
7953 
7954   // now need to get the start of its expanded key array
7955   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
7956   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object, is_decrypt);
7957   if (k_start == nullptr) return false;
7958 
7959   // Call the stub.
7960   make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::aescrypt_block_Type(),
7961                     stubAddr, stubName, TypePtr::BOTTOM,
7962                     src_start, dest_start, k_start);
7963 
7964   return true;
7965 }
7966 
7967 //------------------------------inline_cipherBlockChaining_AESCrypt-----------------------
7968 bool LibraryCallKit::inline_cipherBlockChaining_AESCrypt(vmIntrinsics::ID id) {
7969   address stubAddr = nullptr;
7970   const char *stubName = nullptr;
7971   bool is_decrypt = false;
7972   assert(UseAES, "need AES instruction support");
7973 
7974   switch(id) {
7975   case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
7976     stubAddr = StubRoutines::cipherBlockChaining_encryptAESCrypt();
7977     stubName = "cipherBlockChaining_encryptAESCrypt";
7978     break;
7979   case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
7980     stubAddr = StubRoutines::cipherBlockChaining_decryptAESCrypt();
7981     stubName = "cipherBlockChaining_decryptAESCrypt";
7982     is_decrypt = true;
7983     break;
7984   default:
7985     break;
7986   }
7987   if (stubAddr == nullptr) return false;
7988 
7989   Node* cipherBlockChaining_object = argument(0);
7990   Node* src                        = argument(1);
7991   Node* src_offset                 = argument(2);
7992   Node* len                        = argument(3);
7993   Node* dest                       = argument(4);
7994   Node* dest_offset                = argument(5);
7995 
7996   src = must_be_not_null(src, false);
7997   dest = must_be_not_null(dest, false);
7998 
7999   // (1) src and dest are arrays.
8000   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
8001   const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
8002   assert( src_type != nullptr &&  src_type->elem() != Type::BOTTOM &&
8003          dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
8004 
8005   // checks are the responsibility of the caller
8006   Node* src_start  = src;
8007   Node* dest_start = dest;
8008   if (src_offset != nullptr || dest_offset != nullptr) {
8009     assert(src_offset != nullptr && dest_offset != nullptr, "");
8010     src_start  = array_element_address(src,  src_offset,  T_BYTE);
8011     dest_start = array_element_address(dest, dest_offset, T_BYTE);
8012   }
8013 
8014   // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
8015   // (because of the predicated logic executed earlier).
8016   // so we cast it here safely.
8017   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
8018 
8019   Node* embeddedCipherObj = load_field_from_object(cipherBlockChaining_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8020   if (embeddedCipherObj == nullptr) return false;
8021 
8022   // cast it to what we know it will be at runtime
8023   const TypeInstPtr* tinst = _gvn.type(cipherBlockChaining_object)->isa_instptr();
8024   assert(tinst != nullptr, "CBC obj is null");
8025   assert(tinst->is_loaded(), "CBC obj is not loaded");
8026   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8027   assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
8028 
8029   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8030   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
8031   const TypeOopPtr* xtype = aklass->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
8032   Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
8033   aescrypt_object = _gvn.transform(aescrypt_object);
8034 
8035   // we need to get the start of the aescrypt_object's expanded key array
8036   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object, is_decrypt);
8037   if (k_start == nullptr) return false;
8038 
8039   // similarly, get the start address of the r vector
8040   Node* objRvec = load_field_from_object(cipherBlockChaining_object, "r", "[B");
8041   if (objRvec == nullptr) return false;
8042   Node* r_start = array_element_address(objRvec, intcon(0), T_BYTE);
8043 
8044   // Call the stub, passing src_start, dest_start, k_start, r_start and src_len
8045   Node* cbcCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
8046                                      OptoRuntime::cipherBlockChaining_aescrypt_Type(),
8047                                      stubAddr, stubName, TypePtr::BOTTOM,
8048                                      src_start, dest_start, k_start, r_start, len);
8049 
8050   // return cipher length (int)
8051   Node* retvalue = _gvn.transform(new ProjNode(cbcCrypt, TypeFunc::Parms));
8052   set_result(retvalue);
8053   return true;
8054 }
8055 
8056 //------------------------------inline_electronicCodeBook_AESCrypt-----------------------
8057 bool LibraryCallKit::inline_electronicCodeBook_AESCrypt(vmIntrinsics::ID id) {
8058   address stubAddr = nullptr;
8059   const char *stubName = nullptr;
8060   bool is_decrypt = false;
8061   assert(UseAES, "need AES instruction support");
8062 
8063   switch (id) {
8064   case vmIntrinsics::_electronicCodeBook_encryptAESCrypt:
8065     stubAddr = StubRoutines::electronicCodeBook_encryptAESCrypt();
8066     stubName = "electronicCodeBook_encryptAESCrypt";
8067     break;
8068   case vmIntrinsics::_electronicCodeBook_decryptAESCrypt:
8069     stubAddr = StubRoutines::electronicCodeBook_decryptAESCrypt();
8070     stubName = "electronicCodeBook_decryptAESCrypt";
8071     is_decrypt = true;
8072     break;
8073   default:
8074     break;
8075   }
8076 
8077   if (stubAddr == nullptr) return false;
8078 
8079   Node* electronicCodeBook_object = argument(0);
8080   Node* src                       = argument(1);
8081   Node* src_offset                = argument(2);
8082   Node* len                       = argument(3);
8083   Node* dest                      = argument(4);
8084   Node* dest_offset               = argument(5);
8085 
8086   // (1) src and dest are arrays.
8087   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
8088   const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
8089   assert( src_type != nullptr &&  src_type->elem() != Type::BOTTOM &&
8090          dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
8091 
8092   // checks are the responsibility of the caller
8093   Node* src_start = src;
8094   Node* dest_start = dest;
8095   if (src_offset != nullptr || dest_offset != nullptr) {
8096     assert(src_offset != nullptr && dest_offset != nullptr, "");
8097     src_start = array_element_address(src, src_offset, T_BYTE);
8098     dest_start = array_element_address(dest, dest_offset, T_BYTE);
8099   }
8100 
8101   // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
8102   // (because of the predicated logic executed earlier).
8103   // so we cast it here safely.
8104   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
8105 
8106   Node* embeddedCipherObj = load_field_from_object(electronicCodeBook_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8107   if (embeddedCipherObj == nullptr) return false;
8108 
8109   // cast it to what we know it will be at runtime
8110   const TypeInstPtr* tinst = _gvn.type(electronicCodeBook_object)->isa_instptr();
8111   assert(tinst != nullptr, "ECB obj is null");
8112   assert(tinst->is_loaded(), "ECB obj is not loaded");
8113   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8114   assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
8115 
8116   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8117   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
8118   const TypeOopPtr* xtype = aklass->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
8119   Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
8120   aescrypt_object = _gvn.transform(aescrypt_object);
8121 
8122   // we need to get the start of the aescrypt_object's expanded key array
8123   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object, is_decrypt);
8124   if (k_start == nullptr) return false;
8125 
8126   // Call the stub, passing src_start, dest_start, k_start, r_start and src_len
8127   Node* ecbCrypt = make_runtime_call(RC_LEAF | RC_NO_FP,
8128                                      OptoRuntime::electronicCodeBook_aescrypt_Type(),
8129                                      stubAddr, stubName, TypePtr::BOTTOM,
8130                                      src_start, dest_start, k_start, len);
8131 
8132   // return cipher length (int)
8133   Node* retvalue = _gvn.transform(new ProjNode(ecbCrypt, TypeFunc::Parms));
8134   set_result(retvalue);
8135   return true;
8136 }
8137 
8138 //------------------------------inline_counterMode_AESCrypt-----------------------
8139 bool LibraryCallKit::inline_counterMode_AESCrypt(vmIntrinsics::ID id) {
8140   assert(UseAES, "need AES instruction support");
8141   if (!UseAESCTRIntrinsics) return false;
8142 
8143   address stubAddr = nullptr;
8144   const char *stubName = nullptr;
8145   if (id == vmIntrinsics::_counterMode_AESCrypt) {
8146     stubAddr = StubRoutines::counterMode_AESCrypt();
8147     stubName = "counterMode_AESCrypt";
8148   }
8149   if (stubAddr == nullptr) return false;
8150 
8151   Node* counterMode_object = argument(0);
8152   Node* src = argument(1);
8153   Node* src_offset = argument(2);
8154   Node* len = argument(3);
8155   Node* dest = argument(4);
8156   Node* dest_offset = argument(5);
8157 
8158   // (1) src and dest are arrays.
8159   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
8160   const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
8161   assert( src_type != nullptr &&  src_type->elem() != Type::BOTTOM &&
8162          dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
8163 
8164   // checks are the responsibility of the caller
8165   Node* src_start = src;
8166   Node* dest_start = dest;
8167   if (src_offset != nullptr || dest_offset != nullptr) {
8168     assert(src_offset != nullptr && dest_offset != nullptr, "");
8169     src_start = array_element_address(src, src_offset, T_BYTE);
8170     dest_start = array_element_address(dest, dest_offset, T_BYTE);
8171   }
8172 
8173   // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
8174   // (because of the predicated logic executed earlier).
8175   // so we cast it here safely.
8176   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
8177   Node* embeddedCipherObj = load_field_from_object(counterMode_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8178   if (embeddedCipherObj == nullptr) return false;
8179   // cast it to what we know it will be at runtime
8180   const TypeInstPtr* tinst = _gvn.type(counterMode_object)->isa_instptr();
8181   assert(tinst != nullptr, "CTR obj is null");
8182   assert(tinst->is_loaded(), "CTR obj is not loaded");
8183   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8184   assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
8185   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8186   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
8187   const TypeOopPtr* xtype = aklass->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
8188   Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
8189   aescrypt_object = _gvn.transform(aescrypt_object);
8190   // we need to get the start of the aescrypt_object's expanded key array
8191   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object, /* is_decrypt */ false);
8192   if (k_start == nullptr) return false;
8193   // similarly, get the start address of the r vector
8194   Node* obj_counter = load_field_from_object(counterMode_object, "counter", "[B");
8195   if (obj_counter == nullptr) return false;
8196   Node* cnt_start = array_element_address(obj_counter, intcon(0), T_BYTE);
8197 
8198   Node* saved_encCounter = load_field_from_object(counterMode_object, "encryptedCounter", "[B");
8199   if (saved_encCounter == nullptr) return false;
8200   Node* saved_encCounter_start = array_element_address(saved_encCounter, intcon(0), T_BYTE);
8201   Node* used = field_address_from_object(counterMode_object, "used", "I", /*is_exact*/ false);
8202 
8203   // Call the stub, passing src_start, dest_start, k_start, r_start and src_len
8204   Node* ctrCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
8205                                      OptoRuntime::counterMode_aescrypt_Type(),
8206                                      stubAddr, stubName, TypePtr::BOTTOM,
8207                                      src_start, dest_start, k_start, cnt_start, len, saved_encCounter_start, used);
8208 
8209   // return cipher length (int)
8210   Node* retvalue = _gvn.transform(new ProjNode(ctrCrypt, TypeFunc::Parms));
8211   set_result(retvalue);
8212   return true;
8213 }
8214 
8215 //------------------------------get_key_start_from_aescrypt_object-----------------------
8216 Node* LibraryCallKit::get_key_start_from_aescrypt_object(Node* aescrypt_object, bool is_decrypt) {
8217   // MixColumns for decryption can be reduced by preprocessing MixColumns with round keys.
8218   // Intel's extension is based on this optimization and AESCrypt generates round keys by preprocessing MixColumns.
8219   // However, ppc64 vncipher processes MixColumns and requires the same round keys with encryption.
8220   // The following platform specific stubs of encryption and decryption use the same round keys.
8221 #if defined(PPC64) || defined(S390) || defined(RISCV64)
8222   bool use_decryption_key = false;
8223 #else
8224   bool use_decryption_key = is_decrypt;
8225 #endif
8226   Node* objAESCryptKey = load_field_from_object(aescrypt_object, use_decryption_key ? "sessionKd" : "sessionKe", "[I");
8227   assert(objAESCryptKey != nullptr, "wrong version of com.sun.crypto.provider.AES_Crypt");
8228   if (objAESCryptKey == nullptr) return (Node *) nullptr;
8229 
8230   // now have the array, need to get the start address of the selected key array
8231   Node* k_start = array_element_address(objAESCryptKey, intcon(0), T_INT);
8232   return k_start;
8233 }
8234 
8235 //----------------------------inline_cipherBlockChaining_AESCrypt_predicate----------------------------
8236 // Return node representing slow path of predicate check.
8237 // the pseudo code we want to emulate with this predicate is:
8238 // for encryption:
8239 //    if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
8240 // for decryption:
8241 //    if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
8242 //    note cipher==plain is more conservative than the original java code but that's OK
8243 //
8244 Node* LibraryCallKit::inline_cipherBlockChaining_AESCrypt_predicate(bool decrypting) {
8245   // The receiver was checked for null already.
8246   Node* objCBC = argument(0);
8247 
8248   Node* src = argument(1);
8249   Node* dest = argument(4);
8250 
8251   // Load embeddedCipher field of CipherBlockChaining object.
8252   Node* embeddedCipherObj = load_field_from_object(objCBC, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8253 
8254   // get AESCrypt klass for instanceOf check
8255   // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
8256   // will have same classloader as CipherBlockChaining object
8257   const TypeInstPtr* tinst = _gvn.type(objCBC)->isa_instptr();
8258   assert(tinst != nullptr, "CBCobj is null");
8259   assert(tinst->is_loaded(), "CBCobj is not loaded");
8260 
8261   // we want to do an instanceof comparison against the AESCrypt class
8262   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8263   if (!klass_AESCrypt->is_loaded()) {
8264     // if AESCrypt is not even loaded, we never take the intrinsic fast path
8265     Node* ctrl = control();
8266     set_control(top()); // no regular fast path
8267     return ctrl;
8268   }
8269 
8270   src = must_be_not_null(src, true);
8271   dest = must_be_not_null(dest, true);
8272 
8273   // Resolve oops to stable for CmpP below.
8274   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8275 
8276   Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
8277   Node* cmp_instof  = _gvn.transform(new CmpINode(instof, intcon(1)));
8278   Node* bool_instof  = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
8279 
8280   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
8281 
8282   // for encryption, we are done
8283   if (!decrypting)
8284     return instof_false;  // even if it is null
8285 
8286   // for decryption, we need to add a further check to avoid
8287   // taking the intrinsic path when cipher and plain are the same
8288   // see the original java code for why.
8289   RegionNode* region = new RegionNode(3);
8290   region->init_req(1, instof_false);
8291 
8292   Node* cmp_src_dest = _gvn.transform(new CmpPNode(src, dest));
8293   Node* bool_src_dest = _gvn.transform(new BoolNode(cmp_src_dest, BoolTest::eq));
8294   Node* src_dest_conjoint = generate_guard(bool_src_dest, nullptr, PROB_MIN);
8295   region->init_req(2, src_dest_conjoint);
8296 
8297   record_for_igvn(region);
8298   return _gvn.transform(region);
8299 }
8300 
8301 //----------------------------inline_electronicCodeBook_AESCrypt_predicate----------------------------
8302 // Return node representing slow path of predicate check.
8303 // the pseudo code we want to emulate with this predicate is:
8304 // for encryption:
8305 //    if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
8306 // for decryption:
8307 //    if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
8308 //    note cipher==plain is more conservative than the original java code but that's OK
8309 //
8310 Node* LibraryCallKit::inline_electronicCodeBook_AESCrypt_predicate(bool decrypting) {
8311   // The receiver was checked for null already.
8312   Node* objECB = argument(0);
8313 
8314   // Load embeddedCipher field of ElectronicCodeBook object.
8315   Node* embeddedCipherObj = load_field_from_object(objECB, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8316 
8317   // get AESCrypt klass for instanceOf check
8318   // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
8319   // will have same classloader as ElectronicCodeBook object
8320   const TypeInstPtr* tinst = _gvn.type(objECB)->isa_instptr();
8321   assert(tinst != nullptr, "ECBobj is null");
8322   assert(tinst->is_loaded(), "ECBobj is not loaded");
8323 
8324   // we want to do an instanceof comparison against the AESCrypt class
8325   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8326   if (!klass_AESCrypt->is_loaded()) {
8327     // if AESCrypt is not even loaded, we never take the intrinsic fast path
8328     Node* ctrl = control();
8329     set_control(top()); // no regular fast path
8330     return ctrl;
8331   }
8332   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8333 
8334   Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
8335   Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
8336   Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
8337 
8338   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
8339 
8340   // for encryption, we are done
8341   if (!decrypting)
8342     return instof_false;  // even if it is null
8343 
8344   // for decryption, we need to add a further check to avoid
8345   // taking the intrinsic path when cipher and plain are the same
8346   // see the original java code for why.
8347   RegionNode* region = new RegionNode(3);
8348   region->init_req(1, instof_false);
8349   Node* src = argument(1);
8350   Node* dest = argument(4);
8351   Node* cmp_src_dest = _gvn.transform(new CmpPNode(src, dest));
8352   Node* bool_src_dest = _gvn.transform(new BoolNode(cmp_src_dest, BoolTest::eq));
8353   Node* src_dest_conjoint = generate_guard(bool_src_dest, nullptr, PROB_MIN);
8354   region->init_req(2, src_dest_conjoint);
8355 
8356   record_for_igvn(region);
8357   return _gvn.transform(region);
8358 }
8359 
8360 //----------------------------inline_counterMode_AESCrypt_predicate----------------------------
8361 // Return node representing slow path of predicate check.
8362 // the pseudo code we want to emulate with this predicate is:
8363 // for encryption:
8364 //    if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
8365 // for decryption:
8366 //    if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
8367 //    note cipher==plain is more conservative than the original java code but that's OK
8368 //
8369 
8370 Node* LibraryCallKit::inline_counterMode_AESCrypt_predicate() {
8371   // The receiver was checked for null already.
8372   Node* objCTR = argument(0);
8373 
8374   // Load embeddedCipher field of CipherBlockChaining object.
8375   Node* embeddedCipherObj = load_field_from_object(objCTR, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8376 
8377   // get AESCrypt klass for instanceOf check
8378   // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
8379   // will have same classloader as CipherBlockChaining object
8380   const TypeInstPtr* tinst = _gvn.type(objCTR)->isa_instptr();
8381   assert(tinst != nullptr, "CTRobj is null");
8382   assert(tinst->is_loaded(), "CTRobj is not loaded");
8383 
8384   // we want to do an instanceof comparison against the AESCrypt class
8385   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8386   if (!klass_AESCrypt->is_loaded()) {
8387     // if AESCrypt is not even loaded, we never take the intrinsic fast path
8388     Node* ctrl = control();
8389     set_control(top()); // no regular fast path
8390     return ctrl;
8391   }
8392 
8393   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8394   Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
8395   Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
8396   Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
8397   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
8398 
8399   return instof_false; // even if it is null
8400 }
8401 
8402 //------------------------------inline_ghash_processBlocks
8403 bool LibraryCallKit::inline_ghash_processBlocks() {
8404   address stubAddr;
8405   const char *stubName;
8406   assert(UseGHASHIntrinsics, "need GHASH intrinsics support");
8407 
8408   stubAddr = StubRoutines::ghash_processBlocks();
8409   stubName = "ghash_processBlocks";
8410 
8411   Node* data           = argument(0);
8412   Node* offset         = argument(1);
8413   Node* len            = argument(2);
8414   Node* state          = argument(3);
8415   Node* subkeyH        = argument(4);
8416 
8417   state = must_be_not_null(state, true);
8418   subkeyH = must_be_not_null(subkeyH, true);
8419   data = must_be_not_null(data, true);
8420 
8421   Node* state_start  = array_element_address(state, intcon(0), T_LONG);
8422   assert(state_start, "state is null");
8423   Node* subkeyH_start  = array_element_address(subkeyH, intcon(0), T_LONG);
8424   assert(subkeyH_start, "subkeyH is null");
8425   Node* data_start  = array_element_address(data, offset, T_BYTE);
8426   assert(data_start, "data is null");
8427 
8428   Node* ghash = make_runtime_call(RC_LEAF|RC_NO_FP,
8429                                   OptoRuntime::ghash_processBlocks_Type(),
8430                                   stubAddr, stubName, TypePtr::BOTTOM,
8431                                   state_start, subkeyH_start, data_start, len);
8432   return true;
8433 }
8434 
8435 //------------------------------inline_chacha20Block
8436 bool LibraryCallKit::inline_chacha20Block() {
8437   address stubAddr;
8438   const char *stubName;
8439   assert(UseChaCha20Intrinsics, "need ChaCha20 intrinsics support");
8440 
8441   stubAddr = StubRoutines::chacha20Block();
8442   stubName = "chacha20Block";
8443 
8444   Node* state          = argument(0);
8445   Node* result         = argument(1);
8446 
8447   state = must_be_not_null(state, true);
8448   result = must_be_not_null(result, true);
8449 
8450   Node* state_start  = array_element_address(state, intcon(0), T_INT);
8451   assert(state_start, "state is null");
8452   Node* result_start  = array_element_address(result, intcon(0), T_BYTE);
8453   assert(result_start, "result is null");
8454 
8455   Node* cc20Blk = make_runtime_call(RC_LEAF|RC_NO_FP,
8456                                   OptoRuntime::chacha20Block_Type(),
8457                                   stubAddr, stubName, TypePtr::BOTTOM,
8458                                   state_start, result_start);
8459   // return key stream length (int)
8460   Node* retvalue = _gvn.transform(new ProjNode(cc20Blk, TypeFunc::Parms));
8461   set_result(retvalue);
8462   return true;
8463 }
8464 
8465 //------------------------------inline_kyberNtt
8466 bool LibraryCallKit::inline_kyberNtt() {
8467   address stubAddr;
8468   const char *stubName;
8469   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8470   assert(callee()->signature()->size() == 2, "kyberNtt has 2 parameters");
8471 
8472   stubAddr = StubRoutines::kyberNtt();
8473   stubName = "kyberNtt";
8474   if (!stubAddr) return false;
8475 
8476   Node* coeffs          = argument(0);
8477   Node* ntt_zetas        = argument(1);
8478 
8479   coeffs = must_be_not_null(coeffs, true);
8480   ntt_zetas = must_be_not_null(ntt_zetas, true);
8481 
8482   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_SHORT);
8483   assert(coeffs_start, "coeffs is null");
8484   Node* ntt_zetas_start  = array_element_address(ntt_zetas, intcon(0), T_SHORT);
8485   assert(ntt_zetas_start, "ntt_zetas is null");
8486   Node* kyberNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
8487                                   OptoRuntime::kyberNtt_Type(),
8488                                   stubAddr, stubName, TypePtr::BOTTOM,
8489                                   coeffs_start, ntt_zetas_start);
8490   // return an int
8491   Node* retvalue = _gvn.transform(new ProjNode(kyberNtt, TypeFunc::Parms));
8492   set_result(retvalue);
8493   return true;
8494 }
8495 
8496 //------------------------------inline_kyberInverseNtt
8497 bool LibraryCallKit::inline_kyberInverseNtt() {
8498   address stubAddr;
8499   const char *stubName;
8500   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8501   assert(callee()->signature()->size() == 2, "kyberInverseNtt has 2 parameters");
8502 
8503   stubAddr = StubRoutines::kyberInverseNtt();
8504   stubName = "kyberInverseNtt";
8505   if (!stubAddr) return false;
8506 
8507   Node* coeffs          = argument(0);
8508   Node* zetas           = argument(1);
8509 
8510   coeffs = must_be_not_null(coeffs, true);
8511   zetas = must_be_not_null(zetas, true);
8512 
8513   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_SHORT);
8514   assert(coeffs_start, "coeffs is null");
8515   Node* zetas_start  = array_element_address(zetas, intcon(0), T_SHORT);
8516   assert(zetas_start, "inverseNtt_zetas is null");
8517   Node* kyberInverseNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
8518                                   OptoRuntime::kyberInverseNtt_Type(),
8519                                   stubAddr, stubName, TypePtr::BOTTOM,
8520                                   coeffs_start, zetas_start);
8521 
8522   // return an int
8523   Node* retvalue = _gvn.transform(new ProjNode(kyberInverseNtt, TypeFunc::Parms));
8524   set_result(retvalue);
8525   return true;
8526 }
8527 
8528 //------------------------------inline_kyberNttMult
8529 bool LibraryCallKit::inline_kyberNttMult() {
8530   address stubAddr;
8531   const char *stubName;
8532   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8533   assert(callee()->signature()->size() == 4, "kyberNttMult has 4 parameters");
8534 
8535   stubAddr = StubRoutines::kyberNttMult();
8536   stubName = "kyberNttMult";
8537   if (!stubAddr) return false;
8538 
8539   Node* result          = argument(0);
8540   Node* ntta            = argument(1);
8541   Node* nttb            = argument(2);
8542   Node* zetas           = argument(3);
8543 
8544   result = must_be_not_null(result, true);
8545   ntta = must_be_not_null(ntta, true);
8546   nttb = must_be_not_null(nttb, true);
8547   zetas = must_be_not_null(zetas, true);
8548 
8549   Node* result_start  = array_element_address(result, intcon(0), T_SHORT);
8550   assert(result_start, "result is null");
8551   Node* ntta_start  = array_element_address(ntta, intcon(0), T_SHORT);
8552   assert(ntta_start, "ntta is null");
8553   Node* nttb_start  = array_element_address(nttb, intcon(0), T_SHORT);
8554   assert(nttb_start, "nttb is null");
8555   Node* zetas_start  = array_element_address(zetas, intcon(0), T_SHORT);
8556   assert(zetas_start, "nttMult_zetas is null");
8557   Node* kyberNttMult = make_runtime_call(RC_LEAF|RC_NO_FP,
8558                                   OptoRuntime::kyberNttMult_Type(),
8559                                   stubAddr, stubName, TypePtr::BOTTOM,
8560                                   result_start, ntta_start, nttb_start,
8561                                   zetas_start);
8562 
8563   // return an int
8564   Node* retvalue = _gvn.transform(new ProjNode(kyberNttMult, TypeFunc::Parms));
8565   set_result(retvalue);
8566 
8567   return true;
8568 }
8569 
8570 //------------------------------inline_kyberAddPoly_2
8571 bool LibraryCallKit::inline_kyberAddPoly_2() {
8572   address stubAddr;
8573   const char *stubName;
8574   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8575   assert(callee()->signature()->size() == 3, "kyberAddPoly_2 has 3 parameters");
8576 
8577   stubAddr = StubRoutines::kyberAddPoly_2();
8578   stubName = "kyberAddPoly_2";
8579   if (!stubAddr) return false;
8580 
8581   Node* result          = argument(0);
8582   Node* a               = argument(1);
8583   Node* b               = argument(2);
8584 
8585   result = must_be_not_null(result, true);
8586   a = must_be_not_null(a, true);
8587   b = must_be_not_null(b, true);
8588 
8589   Node* result_start  = array_element_address(result, intcon(0), T_SHORT);
8590   assert(result_start, "result is null");
8591   Node* a_start  = array_element_address(a, intcon(0), T_SHORT);
8592   assert(a_start, "a is null");
8593   Node* b_start  = array_element_address(b, intcon(0), T_SHORT);
8594   assert(b_start, "b is null");
8595   Node* kyberAddPoly_2 = make_runtime_call(RC_LEAF|RC_NO_FP,
8596                                   OptoRuntime::kyberAddPoly_2_Type(),
8597                                   stubAddr, stubName, TypePtr::BOTTOM,
8598                                   result_start, a_start, b_start);
8599   // return an int
8600   Node* retvalue = _gvn.transform(new ProjNode(kyberAddPoly_2, TypeFunc::Parms));
8601   set_result(retvalue);
8602   return true;
8603 }
8604 
8605 //------------------------------inline_kyberAddPoly_3
8606 bool LibraryCallKit::inline_kyberAddPoly_3() {
8607   address stubAddr;
8608   const char *stubName;
8609   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8610   assert(callee()->signature()->size() == 4, "kyberAddPoly_3 has 4 parameters");
8611 
8612   stubAddr = StubRoutines::kyberAddPoly_3();
8613   stubName = "kyberAddPoly_3";
8614   if (!stubAddr) return false;
8615 
8616   Node* result          = argument(0);
8617   Node* a               = argument(1);
8618   Node* b               = argument(2);
8619   Node* c               = argument(3);
8620 
8621   result = must_be_not_null(result, true);
8622   a = must_be_not_null(a, true);
8623   b = must_be_not_null(b, true);
8624   c = must_be_not_null(c, true);
8625 
8626   Node* result_start  = array_element_address(result, intcon(0), T_SHORT);
8627   assert(result_start, "result is null");
8628   Node* a_start  = array_element_address(a, intcon(0), T_SHORT);
8629   assert(a_start, "a is null");
8630   Node* b_start  = array_element_address(b, intcon(0), T_SHORT);
8631   assert(b_start, "b is null");
8632   Node* c_start  = array_element_address(c, intcon(0), T_SHORT);
8633   assert(c_start, "c is null");
8634   Node* kyberAddPoly_3 = make_runtime_call(RC_LEAF|RC_NO_FP,
8635                                   OptoRuntime::kyberAddPoly_3_Type(),
8636                                   stubAddr, stubName, TypePtr::BOTTOM,
8637                                   result_start, a_start, b_start, c_start);
8638   // return an int
8639   Node* retvalue = _gvn.transform(new ProjNode(kyberAddPoly_3, TypeFunc::Parms));
8640   set_result(retvalue);
8641   return true;
8642 }
8643 
8644 //------------------------------inline_kyber12To16
8645 bool LibraryCallKit::inline_kyber12To16() {
8646   address stubAddr;
8647   const char *stubName;
8648   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8649   assert(callee()->signature()->size() == 4, "kyber12To16 has 4 parameters");
8650 
8651   stubAddr = StubRoutines::kyber12To16();
8652   stubName = "kyber12To16";
8653   if (!stubAddr) return false;
8654 
8655   Node* condensed       = argument(0);
8656   Node* condensedOffs   = argument(1);
8657   Node* parsed          = argument(2);
8658   Node* parsedLength    = argument(3);
8659 
8660   condensed = must_be_not_null(condensed, true);
8661   parsed = must_be_not_null(parsed, true);
8662 
8663   Node* condensed_start  = array_element_address(condensed, intcon(0), T_BYTE);
8664   assert(condensed_start, "condensed is null");
8665   Node* parsed_start  = array_element_address(parsed, intcon(0), T_SHORT);
8666   assert(parsed_start, "parsed is null");
8667   Node* kyber12To16 = make_runtime_call(RC_LEAF|RC_NO_FP,
8668                                   OptoRuntime::kyber12To16_Type(),
8669                                   stubAddr, stubName, TypePtr::BOTTOM,
8670                                   condensed_start, condensedOffs, parsed_start, parsedLength);
8671   // return an int
8672   Node* retvalue = _gvn.transform(new ProjNode(kyber12To16, TypeFunc::Parms));
8673   set_result(retvalue);
8674   return true;
8675 
8676 }
8677 
8678 //------------------------------inline_kyberBarrettReduce
8679 bool LibraryCallKit::inline_kyberBarrettReduce() {
8680   address stubAddr;
8681   const char *stubName;
8682   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8683   assert(callee()->signature()->size() == 1, "kyberBarrettReduce has 1 parameters");
8684 
8685   stubAddr = StubRoutines::kyberBarrettReduce();
8686   stubName = "kyberBarrettReduce";
8687   if (!stubAddr) return false;
8688 
8689   Node* coeffs          = argument(0);
8690 
8691   coeffs = must_be_not_null(coeffs, true);
8692 
8693   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_SHORT);
8694   assert(coeffs_start, "coeffs is null");
8695   Node* kyberBarrettReduce = make_runtime_call(RC_LEAF|RC_NO_FP,
8696                                   OptoRuntime::kyberBarrettReduce_Type(),
8697                                   stubAddr, stubName, TypePtr::BOTTOM,
8698                                   coeffs_start);
8699   // return an int
8700   Node* retvalue = _gvn.transform(new ProjNode(kyberBarrettReduce, TypeFunc::Parms));
8701   set_result(retvalue);
8702   return true;
8703 }
8704 
8705 //------------------------------inline_dilithiumAlmostNtt
8706 bool LibraryCallKit::inline_dilithiumAlmostNtt() {
8707   address stubAddr;
8708   const char *stubName;
8709   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8710   assert(callee()->signature()->size() == 2, "dilithiumAlmostNtt has 2 parameters");
8711 
8712   stubAddr = StubRoutines::dilithiumAlmostNtt();
8713   stubName = "dilithiumAlmostNtt";
8714   if (!stubAddr) return false;
8715 
8716   Node* coeffs          = argument(0);
8717   Node* ntt_zetas        = argument(1);
8718 
8719   coeffs = must_be_not_null(coeffs, true);
8720   ntt_zetas = must_be_not_null(ntt_zetas, true);
8721 
8722   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_INT);
8723   assert(coeffs_start, "coeffs is null");
8724   Node* ntt_zetas_start  = array_element_address(ntt_zetas, intcon(0), T_INT);
8725   assert(ntt_zetas_start, "ntt_zetas is null");
8726   Node* dilithiumAlmostNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
8727                                   OptoRuntime::dilithiumAlmostNtt_Type(),
8728                                   stubAddr, stubName, TypePtr::BOTTOM,
8729                                   coeffs_start, ntt_zetas_start);
8730   // return an int
8731   Node* retvalue = _gvn.transform(new ProjNode(dilithiumAlmostNtt, TypeFunc::Parms));
8732   set_result(retvalue);
8733   return true;
8734 }
8735 
8736 //------------------------------inline_dilithiumAlmostInverseNtt
8737 bool LibraryCallKit::inline_dilithiumAlmostInverseNtt() {
8738   address stubAddr;
8739   const char *stubName;
8740   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8741   assert(callee()->signature()->size() == 2, "dilithiumAlmostInverseNtt has 2 parameters");
8742 
8743   stubAddr = StubRoutines::dilithiumAlmostInverseNtt();
8744   stubName = "dilithiumAlmostInverseNtt";
8745   if (!stubAddr) return false;
8746 
8747   Node* coeffs          = argument(0);
8748   Node* zetas           = argument(1);
8749 
8750   coeffs = must_be_not_null(coeffs, true);
8751   zetas = must_be_not_null(zetas, true);
8752 
8753   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_INT);
8754   assert(coeffs_start, "coeffs is null");
8755   Node* zetas_start  = array_element_address(zetas, intcon(0), T_INT);
8756   assert(zetas_start, "inverseNtt_zetas is null");
8757   Node* dilithiumAlmostInverseNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
8758                                   OptoRuntime::dilithiumAlmostInverseNtt_Type(),
8759                                   stubAddr, stubName, TypePtr::BOTTOM,
8760                                   coeffs_start, zetas_start);
8761   // return an int
8762   Node* retvalue = _gvn.transform(new ProjNode(dilithiumAlmostInverseNtt, TypeFunc::Parms));
8763   set_result(retvalue);
8764   return true;
8765 }
8766 
8767 //------------------------------inline_dilithiumNttMult
8768 bool LibraryCallKit::inline_dilithiumNttMult() {
8769   address stubAddr;
8770   const char *stubName;
8771   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8772   assert(callee()->signature()->size() == 3, "dilithiumNttMult has 3 parameters");
8773 
8774   stubAddr = StubRoutines::dilithiumNttMult();
8775   stubName = "dilithiumNttMult";
8776   if (!stubAddr) return false;
8777 
8778   Node* result          = argument(0);
8779   Node* ntta            = argument(1);
8780   Node* nttb            = argument(2);
8781   Node* zetas           = argument(3);
8782 
8783   result = must_be_not_null(result, true);
8784   ntta = must_be_not_null(ntta, true);
8785   nttb = must_be_not_null(nttb, true);
8786   zetas = must_be_not_null(zetas, true);
8787 
8788   Node* result_start  = array_element_address(result, intcon(0), T_INT);
8789   assert(result_start, "result is null");
8790   Node* ntta_start  = array_element_address(ntta, intcon(0), T_INT);
8791   assert(ntta_start, "ntta is null");
8792   Node* nttb_start  = array_element_address(nttb, intcon(0), T_INT);
8793   assert(nttb_start, "nttb is null");
8794   Node* dilithiumNttMult = make_runtime_call(RC_LEAF|RC_NO_FP,
8795                                   OptoRuntime::dilithiumNttMult_Type(),
8796                                   stubAddr, stubName, TypePtr::BOTTOM,
8797                                   result_start, ntta_start, nttb_start);
8798 
8799   // return an int
8800   Node* retvalue = _gvn.transform(new ProjNode(dilithiumNttMult, TypeFunc::Parms));
8801   set_result(retvalue);
8802 
8803   return true;
8804 }
8805 
8806 //------------------------------inline_dilithiumMontMulByConstant
8807 bool LibraryCallKit::inline_dilithiumMontMulByConstant() {
8808   address stubAddr;
8809   const char *stubName;
8810   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8811   assert(callee()->signature()->size() == 2, "dilithiumMontMulByConstant has 2 parameters");
8812 
8813   stubAddr = StubRoutines::dilithiumMontMulByConstant();
8814   stubName = "dilithiumMontMulByConstant";
8815   if (!stubAddr) return false;
8816 
8817   Node* coeffs          = argument(0);
8818   Node* constant        = argument(1);
8819 
8820   coeffs = must_be_not_null(coeffs, true);
8821 
8822   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_INT);
8823   assert(coeffs_start, "coeffs is null");
8824   Node* dilithiumMontMulByConstant = make_runtime_call(RC_LEAF|RC_NO_FP,
8825                                   OptoRuntime::dilithiumMontMulByConstant_Type(),
8826                                   stubAddr, stubName, TypePtr::BOTTOM,
8827                                   coeffs_start, constant);
8828 
8829   // return an int
8830   Node* retvalue = _gvn.transform(new ProjNode(dilithiumMontMulByConstant, TypeFunc::Parms));
8831   set_result(retvalue);
8832   return true;
8833 }
8834 
8835 
8836 //------------------------------inline_dilithiumDecomposePoly
8837 bool LibraryCallKit::inline_dilithiumDecomposePoly() {
8838   address stubAddr;
8839   const char *stubName;
8840   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8841   assert(callee()->signature()->size() == 5, "dilithiumDecomposePoly has 5 parameters");
8842 
8843   stubAddr = StubRoutines::dilithiumDecomposePoly();
8844   stubName = "dilithiumDecomposePoly";
8845   if (!stubAddr) return false;
8846 
8847   Node* input          = argument(0);
8848   Node* lowPart        = argument(1);
8849   Node* highPart       = argument(2);
8850   Node* twoGamma2      = argument(3);
8851   Node* multiplier     = argument(4);
8852 
8853   input = must_be_not_null(input, true);
8854   lowPart = must_be_not_null(lowPart, true);
8855   highPart = must_be_not_null(highPart, true);
8856 
8857   Node* input_start  = array_element_address(input, intcon(0), T_INT);
8858   assert(input_start, "input is null");
8859   Node* lowPart_start  = array_element_address(lowPart, intcon(0), T_INT);
8860   assert(lowPart_start, "lowPart is null");
8861   Node* highPart_start  = array_element_address(highPart, intcon(0), T_INT);
8862   assert(highPart_start, "highPart is null");
8863 
8864   Node* dilithiumDecomposePoly = make_runtime_call(RC_LEAF|RC_NO_FP,
8865                                   OptoRuntime::dilithiumDecomposePoly_Type(),
8866                                   stubAddr, stubName, TypePtr::BOTTOM,
8867                                   input_start, lowPart_start, highPart_start,
8868                                   twoGamma2, multiplier);
8869 
8870   // return an int
8871   Node* retvalue = _gvn.transform(new ProjNode(dilithiumDecomposePoly, TypeFunc::Parms));
8872   set_result(retvalue);
8873   return true;
8874 }
8875 
8876 bool LibraryCallKit::inline_base64_encodeBlock() {
8877   address stubAddr;
8878   const char *stubName;
8879   assert(UseBASE64Intrinsics, "need Base64 intrinsics support");
8880   assert(callee()->signature()->size() == 6, "base64_encodeBlock has 6 parameters");
8881   stubAddr = StubRoutines::base64_encodeBlock();
8882   stubName = "encodeBlock";
8883 
8884   if (!stubAddr) return false;
8885   Node* base64obj = argument(0);
8886   Node* src = argument(1);
8887   Node* offset = argument(2);
8888   Node* len = argument(3);
8889   Node* dest = argument(4);
8890   Node* dp = argument(5);
8891   Node* isURL = argument(6);
8892 
8893   src = must_be_not_null(src, true);
8894   dest = must_be_not_null(dest, true);
8895 
8896   Node* src_start = array_element_address(src, intcon(0), T_BYTE);
8897   assert(src_start, "source array is null");
8898   Node* dest_start = array_element_address(dest, intcon(0), T_BYTE);
8899   assert(dest_start, "destination array is null");
8900 
8901   Node* base64 = make_runtime_call(RC_LEAF,
8902                                    OptoRuntime::base64_encodeBlock_Type(),
8903                                    stubAddr, stubName, TypePtr::BOTTOM,
8904                                    src_start, offset, len, dest_start, dp, isURL);
8905   return true;
8906 }
8907 
8908 bool LibraryCallKit::inline_base64_decodeBlock() {
8909   address stubAddr;
8910   const char *stubName;
8911   assert(UseBASE64Intrinsics, "need Base64 intrinsics support");
8912   assert(callee()->signature()->size() == 7, "base64_decodeBlock has 7 parameters");
8913   stubAddr = StubRoutines::base64_decodeBlock();
8914   stubName = "decodeBlock";
8915 
8916   if (!stubAddr) return false;
8917   Node* base64obj = argument(0);
8918   Node* src = argument(1);
8919   Node* src_offset = argument(2);
8920   Node* len = argument(3);
8921   Node* dest = argument(4);
8922   Node* dest_offset = argument(5);
8923   Node* isURL = argument(6);
8924   Node* isMIME = argument(7);
8925 
8926   src = must_be_not_null(src, true);
8927   dest = must_be_not_null(dest, true);
8928 
8929   Node* src_start = array_element_address(src, intcon(0), T_BYTE);
8930   assert(src_start, "source array is null");
8931   Node* dest_start = array_element_address(dest, intcon(0), T_BYTE);
8932   assert(dest_start, "destination array is null");
8933 
8934   Node* call = make_runtime_call(RC_LEAF,
8935                                  OptoRuntime::base64_decodeBlock_Type(),
8936                                  stubAddr, stubName, TypePtr::BOTTOM,
8937                                  src_start, src_offset, len, dest_start, dest_offset, isURL, isMIME);
8938   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
8939   set_result(result);
8940   return true;
8941 }
8942 
8943 bool LibraryCallKit::inline_poly1305_processBlocks() {
8944   address stubAddr;
8945   const char *stubName;
8946   assert(UsePoly1305Intrinsics, "need Poly intrinsics support");
8947   assert(callee()->signature()->size() == 5, "poly1305_processBlocks has %d parameters", callee()->signature()->size());
8948   stubAddr = StubRoutines::poly1305_processBlocks();
8949   stubName = "poly1305_processBlocks";
8950 
8951   if (!stubAddr) return false;
8952   null_check_receiver();  // null-check receiver
8953   if (stopped())  return true;
8954 
8955   Node* input = argument(1);
8956   Node* input_offset = argument(2);
8957   Node* len = argument(3);
8958   Node* alimbs = argument(4);
8959   Node* rlimbs = argument(5);
8960 
8961   input = must_be_not_null(input, true);
8962   alimbs = must_be_not_null(alimbs, true);
8963   rlimbs = must_be_not_null(rlimbs, true);
8964 
8965   Node* input_start = array_element_address(input, input_offset, T_BYTE);
8966   assert(input_start, "input array is null");
8967   Node* acc_start = array_element_address(alimbs, intcon(0), T_LONG);
8968   assert(acc_start, "acc array is null");
8969   Node* r_start = array_element_address(rlimbs, intcon(0), T_LONG);
8970   assert(r_start, "r array is null");
8971 
8972   Node* call = make_runtime_call(RC_LEAF | RC_NO_FP,
8973                                  OptoRuntime::poly1305_processBlocks_Type(),
8974                                  stubAddr, stubName, TypePtr::BOTTOM,
8975                                  input_start, len, acc_start, r_start);
8976   return true;
8977 }
8978 
8979 bool LibraryCallKit::inline_intpoly_montgomeryMult_P256() {
8980   address stubAddr;
8981   const char *stubName;
8982   assert(UseIntPolyIntrinsics, "need intpoly intrinsics support");
8983   assert(callee()->signature()->size() == 3, "intpoly_montgomeryMult_P256 has %d parameters", callee()->signature()->size());
8984   stubAddr = StubRoutines::intpoly_montgomeryMult_P256();
8985   stubName = "intpoly_montgomeryMult_P256";
8986 
8987   if (!stubAddr) return false;
8988   null_check_receiver();  // null-check receiver
8989   if (stopped())  return true;
8990 
8991   Node* a = argument(1);
8992   Node* b = argument(2);
8993   Node* r = argument(3);
8994 
8995   a = must_be_not_null(a, true);
8996   b = must_be_not_null(b, true);
8997   r = must_be_not_null(r, true);
8998 
8999   Node* a_start = array_element_address(a, intcon(0), T_LONG);
9000   assert(a_start, "a array is null");
9001   Node* b_start = array_element_address(b, intcon(0), T_LONG);
9002   assert(b_start, "b array is null");
9003   Node* r_start = array_element_address(r, intcon(0), T_LONG);
9004   assert(r_start, "r array is null");
9005 
9006   Node* call = make_runtime_call(RC_LEAF | RC_NO_FP,
9007                                  OptoRuntime::intpoly_montgomeryMult_P256_Type(),
9008                                  stubAddr, stubName, TypePtr::BOTTOM,
9009                                  a_start, b_start, r_start);
9010   return true;
9011 }
9012 
9013 bool LibraryCallKit::inline_intpoly_assign() {
9014   assert(UseIntPolyIntrinsics, "need intpoly intrinsics support");
9015   assert(callee()->signature()->size() == 3, "intpoly_assign has %d parameters", callee()->signature()->size());
9016   const char *stubName = "intpoly_assign";
9017   address stubAddr = StubRoutines::intpoly_assign();
9018   if (!stubAddr) return false;
9019 
9020   Node* set = argument(0);
9021   Node* a = argument(1);
9022   Node* b = argument(2);
9023   Node* arr_length = load_array_length(a);
9024 
9025   a = must_be_not_null(a, true);
9026   b = must_be_not_null(b, true);
9027 
9028   Node* a_start = array_element_address(a, intcon(0), T_LONG);
9029   assert(a_start, "a array is null");
9030   Node* b_start = array_element_address(b, intcon(0), T_LONG);
9031   assert(b_start, "b array is null");
9032 
9033   Node* call = make_runtime_call(RC_LEAF | RC_NO_FP,
9034                                  OptoRuntime::intpoly_assign_Type(),
9035                                  stubAddr, stubName, TypePtr::BOTTOM,
9036                                  set, a_start, b_start, arr_length);
9037   return true;
9038 }
9039 
9040 //------------------------------inline_digestBase_implCompress-----------------------
9041 //
9042 // Calculate MD5 for single-block byte[] array.
9043 // void com.sun.security.provider.MD5.implCompress(byte[] buf, int ofs)
9044 //
9045 // Calculate SHA (i.e., SHA-1) for single-block byte[] array.
9046 // void com.sun.security.provider.SHA.implCompress(byte[] buf, int ofs)
9047 //
9048 // Calculate SHA2 (i.e., SHA-244 or SHA-256) for single-block byte[] array.
9049 // void com.sun.security.provider.SHA2.implCompress(byte[] buf, int ofs)
9050 //
9051 // Calculate SHA5 (i.e., SHA-384 or SHA-512) for single-block byte[] array.
9052 // void com.sun.security.provider.SHA5.implCompress(byte[] buf, int ofs)
9053 //
9054 // Calculate SHA3 (i.e., SHA3-224 or SHA3-256 or SHA3-384 or SHA3-512) for single-block byte[] array.
9055 // void com.sun.security.provider.SHA3.implCompress(byte[] buf, int ofs)
9056 //
9057 bool LibraryCallKit::inline_digestBase_implCompress(vmIntrinsics::ID id) {
9058   assert(callee()->signature()->size() == 2, "sha_implCompress has 2 parameters");
9059 
9060   Node* digestBase_obj = argument(0);
9061   Node* src            = argument(1); // type oop
9062   Node* ofs            = argument(2); // type int
9063 
9064   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
9065   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
9066     // failed array check
9067     return false;
9068   }
9069   // Figure out the size and type of the elements we will be copying.
9070   BasicType src_elem = src_type->elem()->array_element_basic_type();
9071   if (src_elem != T_BYTE) {
9072     return false;
9073   }
9074   // 'src_start' points to src array + offset
9075   src = must_be_not_null(src, true);
9076   Node* src_start = array_element_address(src, ofs, src_elem);
9077   Node* state = nullptr;
9078   Node* block_size = nullptr;
9079   address stubAddr;
9080   const char *stubName;
9081 
9082   switch(id) {
9083   case vmIntrinsics::_md5_implCompress:
9084     assert(UseMD5Intrinsics, "need MD5 instruction support");
9085     state = get_state_from_digest_object(digestBase_obj, T_INT);
9086     stubAddr = StubRoutines::md5_implCompress();
9087     stubName = "md5_implCompress";
9088     break;
9089   case vmIntrinsics::_sha_implCompress:
9090     assert(UseSHA1Intrinsics, "need SHA1 instruction support");
9091     state = get_state_from_digest_object(digestBase_obj, T_INT);
9092     stubAddr = StubRoutines::sha1_implCompress();
9093     stubName = "sha1_implCompress";
9094     break;
9095   case vmIntrinsics::_sha2_implCompress:
9096     assert(UseSHA256Intrinsics, "need SHA256 instruction support");
9097     state = get_state_from_digest_object(digestBase_obj, T_INT);
9098     stubAddr = StubRoutines::sha256_implCompress();
9099     stubName = "sha256_implCompress";
9100     break;
9101   case vmIntrinsics::_sha5_implCompress:
9102     assert(UseSHA512Intrinsics, "need SHA512 instruction support");
9103     state = get_state_from_digest_object(digestBase_obj, T_LONG);
9104     stubAddr = StubRoutines::sha512_implCompress();
9105     stubName = "sha512_implCompress";
9106     break;
9107   case vmIntrinsics::_sha3_implCompress:
9108     assert(UseSHA3Intrinsics, "need SHA3 instruction support");
9109     state = get_state_from_digest_object(digestBase_obj, T_LONG);
9110     stubAddr = StubRoutines::sha3_implCompress();
9111     stubName = "sha3_implCompress";
9112     block_size = get_block_size_from_digest_object(digestBase_obj);
9113     if (block_size == nullptr) return false;
9114     break;
9115   default:
9116     fatal_unexpected_iid(id);
9117     return false;
9118   }
9119   if (state == nullptr) return false;
9120 
9121   assert(stubAddr != nullptr, "Stub %s is not generated", stubName);
9122   if (stubAddr == nullptr) return false;
9123 
9124   // Call the stub.
9125   Node* call;
9126   if (block_size == nullptr) {
9127     call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::digestBase_implCompress_Type(false),
9128                              stubAddr, stubName, TypePtr::BOTTOM,
9129                              src_start, state);
9130   } else {
9131     call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::digestBase_implCompress_Type(true),
9132                              stubAddr, stubName, TypePtr::BOTTOM,
9133                              src_start, state, block_size);
9134   }
9135 
9136   return true;
9137 }
9138 
9139 //------------------------------inline_double_keccak
9140 bool LibraryCallKit::inline_double_keccak() {
9141   address stubAddr;
9142   const char *stubName;
9143   assert(UseSHA3Intrinsics, "need SHA3 intrinsics support");
9144   assert(callee()->signature()->size() == 2, "double_keccak has 2 parameters");
9145 
9146   stubAddr = StubRoutines::double_keccak();
9147   stubName = "double_keccak";
9148   if (!stubAddr) return false;
9149 
9150   Node* status0        = argument(0);
9151   Node* status1        = argument(1);
9152 
9153   status0 = must_be_not_null(status0, true);
9154   status1 = must_be_not_null(status1, true);
9155 
9156   Node* status0_start  = array_element_address(status0, intcon(0), T_LONG);
9157   assert(status0_start, "status0 is null");
9158   Node* status1_start  = array_element_address(status1, intcon(0), T_LONG);
9159   assert(status1_start, "status1 is null");
9160   Node* double_keccak = make_runtime_call(RC_LEAF|RC_NO_FP,
9161                                   OptoRuntime::double_keccak_Type(),
9162                                   stubAddr, stubName, TypePtr::BOTTOM,
9163                                   status0_start, status1_start);
9164   // return an int
9165   Node* retvalue = _gvn.transform(new ProjNode(double_keccak, TypeFunc::Parms));
9166   set_result(retvalue);
9167   return true;
9168 }
9169 
9170 
9171 //------------------------------inline_digestBase_implCompressMB-----------------------
9172 //
9173 // Calculate MD5/SHA/SHA2/SHA5/SHA3 for multi-block byte[] array.
9174 // int com.sun.security.provider.DigestBase.implCompressMultiBlock(byte[] b, int ofs, int limit)
9175 //
9176 bool LibraryCallKit::inline_digestBase_implCompressMB(int predicate) {
9177   assert(UseMD5Intrinsics || UseSHA1Intrinsics || UseSHA256Intrinsics || UseSHA512Intrinsics || UseSHA3Intrinsics,
9178          "need MD5/SHA1/SHA256/SHA512/SHA3 instruction support");
9179   assert((uint)predicate < 5, "sanity");
9180   assert(callee()->signature()->size() == 3, "digestBase_implCompressMB has 3 parameters");
9181 
9182   Node* digestBase_obj = argument(0); // The receiver was checked for null already.
9183   Node* src            = argument(1); // byte[] array
9184   Node* ofs            = argument(2); // type int
9185   Node* limit          = argument(3); // type int
9186 
9187   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
9188   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
9189     // failed array check
9190     return false;
9191   }
9192   // Figure out the size and type of the elements we will be copying.
9193   BasicType src_elem = src_type->elem()->array_element_basic_type();
9194   if (src_elem != T_BYTE) {
9195     return false;
9196   }
9197   // 'src_start' points to src array + offset
9198   src = must_be_not_null(src, false);
9199   Node* src_start = array_element_address(src, ofs, src_elem);
9200 
9201   const char* klass_digestBase_name = nullptr;
9202   const char* stub_name = nullptr;
9203   address     stub_addr = nullptr;
9204   BasicType elem_type = T_INT;
9205 
9206   switch (predicate) {
9207   case 0:
9208     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_md5_implCompress)) {
9209       klass_digestBase_name = "sun/security/provider/MD5";
9210       stub_name = "md5_implCompressMB";
9211       stub_addr = StubRoutines::md5_implCompressMB();
9212     }
9213     break;
9214   case 1:
9215     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha_implCompress)) {
9216       klass_digestBase_name = "sun/security/provider/SHA";
9217       stub_name = "sha1_implCompressMB";
9218       stub_addr = StubRoutines::sha1_implCompressMB();
9219     }
9220     break;
9221   case 2:
9222     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha2_implCompress)) {
9223       klass_digestBase_name = "sun/security/provider/SHA2";
9224       stub_name = "sha256_implCompressMB";
9225       stub_addr = StubRoutines::sha256_implCompressMB();
9226     }
9227     break;
9228   case 3:
9229     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha5_implCompress)) {
9230       klass_digestBase_name = "sun/security/provider/SHA5";
9231       stub_name = "sha512_implCompressMB";
9232       stub_addr = StubRoutines::sha512_implCompressMB();
9233       elem_type = T_LONG;
9234     }
9235     break;
9236   case 4:
9237     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha3_implCompress)) {
9238       klass_digestBase_name = "sun/security/provider/SHA3";
9239       stub_name = "sha3_implCompressMB";
9240       stub_addr = StubRoutines::sha3_implCompressMB();
9241       elem_type = T_LONG;
9242     }
9243     break;
9244   default:
9245     fatal("unknown DigestBase intrinsic predicate: %d", predicate);
9246   }
9247   if (klass_digestBase_name != nullptr) {
9248     assert(stub_addr != nullptr, "Stub is generated");
9249     if (stub_addr == nullptr) return false;
9250 
9251     // get DigestBase klass to lookup for SHA klass
9252     const TypeInstPtr* tinst = _gvn.type(digestBase_obj)->isa_instptr();
9253     assert(tinst != nullptr, "digestBase_obj is not instance???");
9254     assert(tinst->is_loaded(), "DigestBase is not loaded");
9255 
9256     ciKlass* klass_digestBase = tinst->instance_klass()->find_klass(ciSymbol::make(klass_digestBase_name));
9257     assert(klass_digestBase->is_loaded(), "predicate checks that this class is loaded");
9258     ciInstanceKlass* instklass_digestBase = klass_digestBase->as_instance_klass();
9259     return inline_digestBase_implCompressMB(digestBase_obj, instklass_digestBase, elem_type, stub_addr, stub_name, src_start, ofs, limit);
9260   }
9261   return false;
9262 }
9263 
9264 //------------------------------inline_digestBase_implCompressMB-----------------------
9265 bool LibraryCallKit::inline_digestBase_implCompressMB(Node* digestBase_obj, ciInstanceKlass* instklass_digestBase,
9266                                                       BasicType elem_type, address stubAddr, const char *stubName,
9267                                                       Node* src_start, Node* ofs, Node* limit) {
9268   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_digestBase);
9269   const TypeOopPtr* xtype = aklass->cast_to_exactness(false)->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
9270   Node* digest_obj = new CheckCastPPNode(control(), digestBase_obj, xtype);
9271   digest_obj = _gvn.transform(digest_obj);
9272 
9273   Node* state = get_state_from_digest_object(digest_obj, elem_type);
9274   if (state == nullptr) return false;
9275 
9276   Node* block_size = nullptr;
9277   if (strcmp("sha3_implCompressMB", stubName) == 0) {
9278     block_size = get_block_size_from_digest_object(digest_obj);
9279     if (block_size == nullptr) return false;
9280   }
9281 
9282   // Call the stub.
9283   Node* call;
9284   if (block_size == nullptr) {
9285     call = make_runtime_call(RC_LEAF|RC_NO_FP,
9286                              OptoRuntime::digestBase_implCompressMB_Type(false),
9287                              stubAddr, stubName, TypePtr::BOTTOM,
9288                              src_start, state, ofs, limit);
9289   } else {
9290      call = make_runtime_call(RC_LEAF|RC_NO_FP,
9291                              OptoRuntime::digestBase_implCompressMB_Type(true),
9292                              stubAddr, stubName, TypePtr::BOTTOM,
9293                              src_start, state, block_size, ofs, limit);
9294   }
9295 
9296   // return ofs (int)
9297   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
9298   set_result(result);
9299 
9300   return true;
9301 }
9302 
9303 //------------------------------inline_galoisCounterMode_AESCrypt-----------------------
9304 bool LibraryCallKit::inline_galoisCounterMode_AESCrypt() {
9305   assert(UseAES, "need AES instruction support");
9306   address stubAddr = nullptr;
9307   const char *stubName = nullptr;
9308   stubAddr = StubRoutines::galoisCounterMode_AESCrypt();
9309   stubName = "galoisCounterMode_AESCrypt";
9310 
9311   if (stubAddr == nullptr) return false;
9312 
9313   Node* in      = argument(0);
9314   Node* inOfs   = argument(1);
9315   Node* len     = argument(2);
9316   Node* ct      = argument(3);
9317   Node* ctOfs   = argument(4);
9318   Node* out     = argument(5);
9319   Node* outOfs  = argument(6);
9320   Node* gctr_object = argument(7);
9321   Node* ghash_object = argument(8);
9322 
9323   // (1) in, ct and out are arrays.
9324   const TypeAryPtr* in_type = in->Value(&_gvn)->isa_aryptr();
9325   const TypeAryPtr* ct_type = ct->Value(&_gvn)->isa_aryptr();
9326   const TypeAryPtr* out_type = out->Value(&_gvn)->isa_aryptr();
9327   assert( in_type != nullptr &&  in_type->elem() != Type::BOTTOM &&
9328           ct_type != nullptr &&  ct_type->elem() != Type::BOTTOM &&
9329          out_type != nullptr && out_type->elem() != Type::BOTTOM, "args are strange");
9330 
9331   // checks are the responsibility of the caller
9332   Node* in_start = in;
9333   Node* ct_start = ct;
9334   Node* out_start = out;
9335   if (inOfs != nullptr || ctOfs != nullptr || outOfs != nullptr) {
9336     assert(inOfs != nullptr && ctOfs != nullptr && outOfs != nullptr, "");
9337     in_start = array_element_address(in, inOfs, T_BYTE);
9338     ct_start = array_element_address(ct, ctOfs, T_BYTE);
9339     out_start = array_element_address(out, outOfs, T_BYTE);
9340   }
9341 
9342   // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
9343   // (because of the predicated logic executed earlier).
9344   // so we cast it here safely.
9345   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
9346   Node* embeddedCipherObj = load_field_from_object(gctr_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
9347   Node* counter = load_field_from_object(gctr_object, "counter", "[B");
9348   Node* subkeyHtbl = load_field_from_object(ghash_object, "subkeyHtbl", "[J");
9349   Node* state = load_field_from_object(ghash_object, "state", "[J");
9350 
9351   if (embeddedCipherObj == nullptr || counter == nullptr || subkeyHtbl == nullptr || state == nullptr) {
9352     return false;
9353   }
9354   // cast it to what we know it will be at runtime
9355   const TypeInstPtr* tinst = _gvn.type(gctr_object)->isa_instptr();
9356   assert(tinst != nullptr, "GCTR obj is null");
9357   assert(tinst->is_loaded(), "GCTR obj is not loaded");
9358   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
9359   assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
9360   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
9361   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
9362   const TypeOopPtr* xtype = aklass->as_instance_type();
9363   Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
9364   aescrypt_object = _gvn.transform(aescrypt_object);
9365   // we need to get the start of the aescrypt_object's expanded key array
9366   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object, /* is_decrypt */ false);
9367   if (k_start == nullptr) return false;
9368   // similarly, get the start address of the r vector
9369   Node* cnt_start = array_element_address(counter, intcon(0), T_BYTE);
9370   Node* state_start = array_element_address(state, intcon(0), T_LONG);
9371   Node* subkeyHtbl_start = array_element_address(subkeyHtbl, intcon(0), T_LONG);
9372 
9373 
9374   // Call the stub, passing params
9375   Node* gcmCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
9376                                OptoRuntime::galoisCounterMode_aescrypt_Type(),
9377                                stubAddr, stubName, TypePtr::BOTTOM,
9378                                in_start, len, ct_start, out_start, k_start, state_start, subkeyHtbl_start, cnt_start);
9379 
9380   // return cipher length (int)
9381   Node* retvalue = _gvn.transform(new ProjNode(gcmCrypt, TypeFunc::Parms));
9382   set_result(retvalue);
9383 
9384   return true;
9385 }
9386 
9387 //----------------------------inline_galoisCounterMode_AESCrypt_predicate----------------------------
9388 // Return node representing slow path of predicate check.
9389 // the pseudo code we want to emulate with this predicate is:
9390 // for encryption:
9391 //    if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
9392 // for decryption:
9393 //    if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
9394 //    note cipher==plain is more conservative than the original java code but that's OK
9395 //
9396 
9397 Node* LibraryCallKit::inline_galoisCounterMode_AESCrypt_predicate() {
9398   // The receiver was checked for null already.
9399   Node* objGCTR = argument(7);
9400   // Load embeddedCipher field of GCTR object.
9401   Node* embeddedCipherObj = load_field_from_object(objGCTR, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
9402   assert(embeddedCipherObj != nullptr, "embeddedCipherObj is null");
9403 
9404   // get AESCrypt klass for instanceOf check
9405   // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
9406   // will have same classloader as CipherBlockChaining object
9407   const TypeInstPtr* tinst = _gvn.type(objGCTR)->isa_instptr();
9408   assert(tinst != nullptr, "GCTR obj is null");
9409   assert(tinst->is_loaded(), "GCTR obj is not loaded");
9410 
9411   // we want to do an instanceof comparison against the AESCrypt class
9412   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
9413   if (!klass_AESCrypt->is_loaded()) {
9414     // if AESCrypt is not even loaded, we never take the intrinsic fast path
9415     Node* ctrl = control();
9416     set_control(top()); // no regular fast path
9417     return ctrl;
9418   }
9419 
9420   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
9421   Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
9422   Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
9423   Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
9424   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
9425 
9426   return instof_false; // even if it is null
9427 }
9428 
9429 //------------------------------get_state_from_digest_object-----------------------
9430 Node * LibraryCallKit::get_state_from_digest_object(Node *digest_object, BasicType elem_type) {
9431   const char* state_type;
9432   switch (elem_type) {
9433     case T_BYTE: state_type = "[B"; break;
9434     case T_INT:  state_type = "[I"; break;
9435     case T_LONG: state_type = "[J"; break;
9436     default: ShouldNotReachHere();
9437   }
9438   Node* digest_state = load_field_from_object(digest_object, "state", state_type);
9439   assert (digest_state != nullptr, "wrong version of sun.security.provider.MD5/SHA/SHA2/SHA5/SHA3");
9440   if (digest_state == nullptr) return (Node *) nullptr;
9441 
9442   // now have the array, need to get the start address of the state array
9443   Node* state = array_element_address(digest_state, intcon(0), elem_type);
9444   return state;
9445 }
9446 
9447 //------------------------------get_block_size_from_sha3_object----------------------------------
9448 Node * LibraryCallKit::get_block_size_from_digest_object(Node *digest_object) {
9449   Node* block_size = load_field_from_object(digest_object, "blockSize", "I");
9450   assert (block_size != nullptr, "sanity");
9451   return block_size;
9452 }
9453 
9454 //----------------------------inline_digestBase_implCompressMB_predicate----------------------------
9455 // Return node representing slow path of predicate check.
9456 // the pseudo code we want to emulate with this predicate is:
9457 //    if (digestBaseObj instanceof MD5/SHA/SHA2/SHA5/SHA3) do_intrinsic, else do_javapath
9458 //
9459 Node* LibraryCallKit::inline_digestBase_implCompressMB_predicate(int predicate) {
9460   assert(UseMD5Intrinsics || UseSHA1Intrinsics || UseSHA256Intrinsics || UseSHA512Intrinsics || UseSHA3Intrinsics,
9461          "need MD5/SHA1/SHA256/SHA512/SHA3 instruction support");
9462   assert((uint)predicate < 5, "sanity");
9463 
9464   // The receiver was checked for null already.
9465   Node* digestBaseObj = argument(0);
9466 
9467   // get DigestBase klass for instanceOf check
9468   const TypeInstPtr* tinst = _gvn.type(digestBaseObj)->isa_instptr();
9469   assert(tinst != nullptr, "digestBaseObj is null");
9470   assert(tinst->is_loaded(), "DigestBase is not loaded");
9471 
9472   const char* klass_name = nullptr;
9473   switch (predicate) {
9474   case 0:
9475     if (UseMD5Intrinsics) {
9476       // we want to do an instanceof comparison against the MD5 class
9477       klass_name = "sun/security/provider/MD5";
9478     }
9479     break;
9480   case 1:
9481     if (UseSHA1Intrinsics) {
9482       // we want to do an instanceof comparison against the SHA class
9483       klass_name = "sun/security/provider/SHA";
9484     }
9485     break;
9486   case 2:
9487     if (UseSHA256Intrinsics) {
9488       // we want to do an instanceof comparison against the SHA2 class
9489       klass_name = "sun/security/provider/SHA2";
9490     }
9491     break;
9492   case 3:
9493     if (UseSHA512Intrinsics) {
9494       // we want to do an instanceof comparison against the SHA5 class
9495       klass_name = "sun/security/provider/SHA5";
9496     }
9497     break;
9498   case 4:
9499     if (UseSHA3Intrinsics) {
9500       // we want to do an instanceof comparison against the SHA3 class
9501       klass_name = "sun/security/provider/SHA3";
9502     }
9503     break;
9504   default:
9505     fatal("unknown SHA intrinsic predicate: %d", predicate);
9506   }
9507 
9508   ciKlass* klass = nullptr;
9509   if (klass_name != nullptr) {
9510     klass = tinst->instance_klass()->find_klass(ciSymbol::make(klass_name));
9511   }
9512   if ((klass == nullptr) || !klass->is_loaded()) {
9513     // if none of MD5/SHA/SHA2/SHA5 is loaded, we never take the intrinsic fast path
9514     Node* ctrl = control();
9515     set_control(top()); // no intrinsic path
9516     return ctrl;
9517   }
9518   ciInstanceKlass* instklass = klass->as_instance_klass();
9519 
9520   Node* instof = gen_instanceof(digestBaseObj, makecon(TypeKlassPtr::make(instklass)));
9521   Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
9522   Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
9523   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
9524 
9525   return instof_false;  // even if it is null
9526 }
9527 
9528 //-------------inline_fma-----------------------------------
9529 bool LibraryCallKit::inline_fma(vmIntrinsics::ID id) {
9530   Node *a = nullptr;
9531   Node *b = nullptr;
9532   Node *c = nullptr;
9533   Node* result = nullptr;
9534   switch (id) {
9535   case vmIntrinsics::_fmaD:
9536     assert(callee()->signature()->size() == 6, "fma has 3 parameters of size 2 each.");
9537     // no receiver since it is static method
9538     a = argument(0);
9539     b = argument(2);
9540     c = argument(4);
9541     result = _gvn.transform(new FmaDNode(a, b, c));
9542     break;
9543   case vmIntrinsics::_fmaF:
9544     assert(callee()->signature()->size() == 3, "fma has 3 parameters of size 1 each.");
9545     a = argument(0);
9546     b = argument(1);
9547     c = argument(2);
9548     result = _gvn.transform(new FmaFNode(a, b, c));
9549     break;
9550   default:
9551     fatal_unexpected_iid(id);  break;
9552   }
9553   set_result(result);
9554   return true;
9555 }
9556 
9557 bool LibraryCallKit::inline_character_compare(vmIntrinsics::ID id) {
9558   // argument(0) is receiver
9559   Node* codePoint = argument(1);
9560   Node* n = nullptr;
9561 
9562   switch (id) {
9563     case vmIntrinsics::_isDigit :
9564       n = new DigitNode(control(), codePoint);
9565       break;
9566     case vmIntrinsics::_isLowerCase :
9567       n = new LowerCaseNode(control(), codePoint);
9568       break;
9569     case vmIntrinsics::_isUpperCase :
9570       n = new UpperCaseNode(control(), codePoint);
9571       break;
9572     case vmIntrinsics::_isWhitespace :
9573       n = new WhitespaceNode(control(), codePoint);
9574       break;
9575     default:
9576       fatal_unexpected_iid(id);
9577   }
9578 
9579   set_result(_gvn.transform(n));
9580   return true;
9581 }
9582 
9583 bool LibraryCallKit::inline_profileBoolean() {
9584   Node* counts = argument(1);
9585   const TypeAryPtr* ary = nullptr;
9586   ciArray* aobj = nullptr;
9587   if (counts->is_Con()
9588       && (ary = counts->bottom_type()->isa_aryptr()) != nullptr
9589       && (aobj = ary->const_oop()->as_array()) != nullptr
9590       && (aobj->length() == 2)) {
9591     // Profile is int[2] where [0] and [1] correspond to false and true value occurrences respectively.
9592     jint false_cnt = aobj->element_value(0).as_int();
9593     jint  true_cnt = aobj->element_value(1).as_int();
9594 
9595     if (C->log() != nullptr) {
9596       C->log()->elem("observe source='profileBoolean' false='%d' true='%d'",
9597                      false_cnt, true_cnt);
9598     }
9599 
9600     if (false_cnt + true_cnt == 0) {
9601       // According to profile, never executed.
9602       uncommon_trap_exact(Deoptimization::Reason_intrinsic,
9603                           Deoptimization::Action_reinterpret);
9604       return true;
9605     }
9606 
9607     // result is a boolean (0 or 1) and its profile (false_cnt & true_cnt)
9608     // is a number of each value occurrences.
9609     Node* result = argument(0);
9610     if (false_cnt == 0 || true_cnt == 0) {
9611       // According to profile, one value has been never seen.
9612       int expected_val = (false_cnt == 0) ? 1 : 0;
9613 
9614       Node* cmp  = _gvn.transform(new CmpINode(result, intcon(expected_val)));
9615       Node* test = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
9616 
9617       IfNode* check = create_and_map_if(control(), test, PROB_ALWAYS, COUNT_UNKNOWN);
9618       Node* fast_path = _gvn.transform(new IfTrueNode(check));
9619       Node* slow_path = _gvn.transform(new IfFalseNode(check));
9620 
9621       { // Slow path: uncommon trap for never seen value and then reexecute
9622         // MethodHandleImpl::profileBoolean() to bump the count, so JIT knows
9623         // the value has been seen at least once.
9624         PreserveJVMState pjvms(this);
9625         PreserveReexecuteState preexecs(this);
9626         jvms()->set_should_reexecute(true);
9627 
9628         set_control(slow_path);
9629         set_i_o(i_o());
9630 
9631         uncommon_trap_exact(Deoptimization::Reason_intrinsic,
9632                             Deoptimization::Action_reinterpret);
9633       }
9634       // The guard for never seen value enables sharpening of the result and
9635       // returning a constant. It allows to eliminate branches on the same value
9636       // later on.
9637       set_control(fast_path);
9638       result = intcon(expected_val);
9639     }
9640     // Stop profiling.
9641     // MethodHandleImpl::profileBoolean() has profiling logic in its bytecode.
9642     // By replacing method body with profile data (represented as ProfileBooleanNode
9643     // on IR level) we effectively disable profiling.
9644     // It enables full speed execution once optimized code is generated.
9645     Node* profile = _gvn.transform(new ProfileBooleanNode(result, false_cnt, true_cnt));
9646     C->record_for_igvn(profile);
9647     set_result(profile);
9648     return true;
9649   } else {
9650     // Continue profiling.
9651     // Profile data isn't available at the moment. So, execute method's bytecode version.
9652     // Usually, when GWT LambdaForms are profiled it means that a stand-alone nmethod
9653     // is compiled and counters aren't available since corresponding MethodHandle
9654     // isn't a compile-time constant.
9655     return false;
9656   }
9657 }
9658 
9659 bool LibraryCallKit::inline_isCompileConstant() {
9660   Node* n = argument(0);
9661   set_result(n->is_Con() ? intcon(1) : intcon(0));
9662   return true;
9663 }
9664 
9665 //------------------------------- inline_getObjectSize --------------------------------------
9666 //
9667 // Calculate the runtime size of the object/array.
9668 //   native long sun.instrument.InstrumentationImpl.getObjectSize0(long nativeAgent, Object objectToSize);
9669 //
9670 bool LibraryCallKit::inline_getObjectSize() {
9671   Node* obj = argument(3);
9672   Node* klass_node = load_object_klass(obj);
9673 
9674   jint  layout_con = Klass::_lh_neutral_value;
9675   Node* layout_val = get_layout_helper(klass_node, layout_con);
9676   int   layout_is_con = (layout_val == nullptr);
9677 
9678   if (layout_is_con) {
9679     // Layout helper is constant, can figure out things at compile time.
9680 
9681     if (Klass::layout_helper_is_instance(layout_con)) {
9682       // Instance case:  layout_con contains the size itself.
9683       Node *size = longcon(Klass::layout_helper_size_in_bytes(layout_con));
9684       set_result(size);
9685     } else {
9686       // Array case: size is round(header + element_size*arraylength).
9687       // Since arraylength is different for every array instance, we have to
9688       // compute the whole thing at runtime.
9689 
9690       Node* arr_length = load_array_length(obj);
9691 
9692       int round_mask = MinObjAlignmentInBytes - 1;
9693       int hsize  = Klass::layout_helper_header_size(layout_con);
9694       int eshift = Klass::layout_helper_log2_element_size(layout_con);
9695 
9696       if ((round_mask & ~right_n_bits(eshift)) == 0) {
9697         round_mask = 0;  // strength-reduce it if it goes away completely
9698       }
9699       assert((hsize & right_n_bits(eshift)) == 0, "hsize is pre-rounded");
9700       Node* header_size = intcon(hsize + round_mask);
9701 
9702       Node* lengthx = ConvI2X(arr_length);
9703       Node* headerx = ConvI2X(header_size);
9704 
9705       Node* abody = lengthx;
9706       if (eshift != 0) {
9707         abody = _gvn.transform(new LShiftXNode(lengthx, intcon(eshift)));
9708       }
9709       Node* size = _gvn.transform( new AddXNode(headerx, abody) );
9710       if (round_mask != 0) {
9711         size = _gvn.transform( new AndXNode(size, MakeConX(~round_mask)) );
9712       }
9713       size = ConvX2L(size);
9714       set_result(size);
9715     }
9716   } else {
9717     // Layout helper is not constant, need to test for array-ness at runtime.
9718 
9719     enum { _instance_path = 1, _array_path, PATH_LIMIT };
9720     RegionNode* result_reg = new RegionNode(PATH_LIMIT);
9721     PhiNode* result_val = new PhiNode(result_reg, TypeLong::LONG);
9722     record_for_igvn(result_reg);
9723 
9724     Node* array_ctl = generate_array_guard(klass_node, nullptr, &obj);
9725     if (array_ctl != nullptr) {
9726       // Array case: size is round(header + element_size*arraylength).
9727       // Since arraylength is different for every array instance, we have to
9728       // compute the whole thing at runtime.
9729 
9730       PreserveJVMState pjvms(this);
9731       set_control(array_ctl);
9732       Node* arr_length = load_array_length(obj);
9733 
9734       int round_mask = MinObjAlignmentInBytes - 1;
9735       Node* mask = intcon(round_mask);
9736 
9737       Node* hss = intcon(Klass::_lh_header_size_shift);
9738       Node* hsm = intcon(Klass::_lh_header_size_mask);
9739       Node* header_size = _gvn.transform(new URShiftINode(layout_val, hss));
9740       header_size = _gvn.transform(new AndINode(header_size, hsm));
9741       header_size = _gvn.transform(new AddINode(header_size, mask));
9742 
9743       // There is no need to mask or shift this value.
9744       // The semantics of LShiftINode include an implicit mask to 0x1F.
9745       assert(Klass::_lh_log2_element_size_shift == 0, "use shift in place");
9746       Node* elem_shift = layout_val;
9747 
9748       Node* lengthx = ConvI2X(arr_length);
9749       Node* headerx = ConvI2X(header_size);
9750 
9751       Node* abody = _gvn.transform(new LShiftXNode(lengthx, elem_shift));
9752       Node* size = _gvn.transform(new AddXNode(headerx, abody));
9753       if (round_mask != 0) {
9754         size = _gvn.transform(new AndXNode(size, MakeConX(~round_mask)));
9755       }
9756       size = ConvX2L(size);
9757 
9758       result_reg->init_req(_array_path, control());
9759       result_val->init_req(_array_path, size);
9760     }
9761 
9762     if (!stopped()) {
9763       // Instance case: the layout helper gives us instance size almost directly,
9764       // but we need to mask out the _lh_instance_slow_path_bit.
9765       Node* size = ConvI2X(layout_val);
9766       assert((int) Klass::_lh_instance_slow_path_bit < BytesPerLong, "clear bit");
9767       Node* mask = MakeConX(~(intptr_t) right_n_bits(LogBytesPerLong));
9768       size = _gvn.transform(new AndXNode(size, mask));
9769       size = ConvX2L(size);
9770 
9771       result_reg->init_req(_instance_path, control());
9772       result_val->init_req(_instance_path, size);
9773     }
9774 
9775     set_result(result_reg, result_val);
9776   }
9777 
9778   return true;
9779 }
9780 
9781 //------------------------------- inline_blackhole --------------------------------------
9782 //
9783 // Make sure all arguments to this node are alive.
9784 // This matches methods that were requested to be blackholed through compile commands.
9785 //
9786 bool LibraryCallKit::inline_blackhole() {
9787   assert(callee()->is_static(), "Should have been checked before: only static methods here");
9788   assert(callee()->is_empty(), "Should have been checked before: only empty methods here");
9789   assert(callee()->holder()->is_loaded(), "Should have been checked before: only methods for loaded classes here");
9790 
9791   // Blackhole node pinches only the control, not memory. This allows
9792   // the blackhole to be pinned in the loop that computes blackholed
9793   // values, but have no other side effects, like breaking the optimizations
9794   // across the blackhole.
9795 
9796   Node* bh = _gvn.transform(new BlackholeNode(control()));
9797   set_control(_gvn.transform(new ProjNode(bh, TypeFunc::Control)));
9798 
9799   // Bind call arguments as blackhole arguments to keep them alive
9800   uint nargs = callee()->arg_size();
9801   for (uint i = 0; i < nargs; i++) {
9802     bh->add_req(argument(i));
9803   }
9804 
9805   return true;
9806 }
9807 
9808 Node* LibraryCallKit::unbox_fp16_value(const TypeInstPtr* float16_box_type, ciField* field, Node* box) {
9809   const TypeInstPtr* box_type = _gvn.type(box)->isa_instptr();
9810   if (box_type == nullptr || box_type->instance_klass() != float16_box_type->instance_klass()) {
9811     return nullptr; // box klass is not Float16
9812   }
9813 
9814   // Null check; get notnull casted pointer
9815   Node* null_ctl = top();
9816   Node* not_null_box = null_check_oop(box, &null_ctl, true);
9817   // If not_null_box is dead, only null-path is taken
9818   if (stopped()) {
9819     set_control(null_ctl);
9820     return nullptr;
9821   }
9822   assert(not_null_box->bottom_type()->is_instptr()->maybe_null() == false, "");
9823   const TypePtr* adr_type = C->alias_type(field)->adr_type();
9824   Node* adr = basic_plus_adr(not_null_box, field->offset_in_bytes());
9825   return access_load_at(not_null_box, adr, adr_type, TypeInt::SHORT, T_SHORT, IN_HEAP);
9826 }
9827 
9828 Node* LibraryCallKit::box_fp16_value(const TypeInstPtr* float16_box_type, ciField* field, Node* value) {
9829   PreserveReexecuteState preexecs(this);
9830   jvms()->set_should_reexecute(true);
9831 
9832   const TypeKlassPtr* klass_type = float16_box_type->as_klass_type();
9833   Node* klass_node = makecon(klass_type);
9834   Node* box = new_instance(klass_node);
9835 
9836   Node* value_field = basic_plus_adr(box, field->offset_in_bytes());
9837   const TypePtr* value_adr_type = value_field->bottom_type()->is_ptr();
9838 
9839   Node* field_store = _gvn.transform(access_store_at(box,
9840                                                      value_field,
9841                                                      value_adr_type,
9842                                                      value,
9843                                                      TypeInt::SHORT,
9844                                                      T_SHORT,
9845                                                      IN_HEAP));
9846   set_memory(field_store, value_adr_type);
9847   return box;
9848 }
9849 
9850 bool LibraryCallKit::inline_fp16_operations(vmIntrinsics::ID id, int num_args) {
9851   if (!Matcher::match_rule_supported(Op_ReinterpretS2HF) ||
9852       !Matcher::match_rule_supported(Op_ReinterpretHF2S)) {
9853     return false;
9854   }
9855 
9856   const TypeInstPtr* box_type = _gvn.type(argument(0))->isa_instptr();
9857   if (box_type == nullptr || box_type->const_oop() == nullptr) {
9858     return false;
9859   }
9860 
9861   ciInstanceKlass* float16_klass = box_type->const_oop()->as_instance()->java_lang_Class_klass()->as_instance_klass();
9862   const TypeInstPtr* float16_box_type = TypeInstPtr::make_exact(TypePtr::NotNull, float16_klass);
9863   ciField* field = float16_klass->get_field_by_name(ciSymbols::value_name(),
9864                                                     ciSymbols::short_signature(),
9865                                                     false);
9866   assert(field != nullptr, "");
9867 
9868   // Transformed nodes
9869   Node* fld1 = nullptr;
9870   Node* fld2 = nullptr;
9871   Node* fld3 = nullptr;
9872   switch(num_args) {
9873     case 3:
9874       fld3 = unbox_fp16_value(float16_box_type, field, argument(3));
9875       if (fld3 == nullptr) {
9876         return false;
9877       }
9878       fld3 = _gvn.transform(new ReinterpretS2HFNode(fld3));
9879     // fall-through
9880     case 2:
9881       fld2 = unbox_fp16_value(float16_box_type, field, argument(2));
9882       if (fld2 == nullptr) {
9883         return false;
9884       }
9885       fld2 = _gvn.transform(new ReinterpretS2HFNode(fld2));
9886     // fall-through
9887     case 1:
9888       fld1 = unbox_fp16_value(float16_box_type, field, argument(1));
9889       if (fld1 == nullptr) {
9890         return false;
9891       }
9892       fld1 = _gvn.transform(new ReinterpretS2HFNode(fld1));
9893       break;
9894     default: fatal("Unsupported number of arguments %d", num_args);
9895   }
9896 
9897   Node* result = nullptr;
9898   switch (id) {
9899     // Unary operations
9900     case vmIntrinsics::_sqrt_float16:
9901       result = _gvn.transform(new SqrtHFNode(C, control(), fld1));
9902       break;
9903     // Ternary operations
9904     case vmIntrinsics::_fma_float16:
9905       result = _gvn.transform(new FmaHFNode(fld1, fld2, fld3));
9906       break;
9907     default:
9908       fatal_unexpected_iid(id);
9909       break;
9910   }
9911   result = _gvn.transform(new ReinterpretHF2SNode(result));
9912   set_result(box_fp16_value(float16_box_type, field, result));
9913   return true;
9914 }
9915