1 /*
   2  * Copyright (c) 1999, 2025, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "asm/macroAssembler.hpp"
  26 #include "ci/ciArrayKlass.hpp"
  27 #include "ci/ciFlatArrayKlass.hpp"
  28 #include "ci/ciInstanceKlass.hpp"
  29 #include "ci/ciSymbols.hpp"
  30 #include "ci/ciUtilities.inline.hpp"
  31 #include "classfile/vmIntrinsics.hpp"
  32 #include "compiler/compileBroker.hpp"
  33 #include "compiler/compileLog.hpp"
  34 #include "gc/shared/barrierSet.hpp"
  35 #include "gc/shared/c2/barrierSetC2.hpp"
  36 #include "jfr/support/jfrIntrinsics.hpp"
  37 #include "memory/resourceArea.hpp"
  38 #include "oops/accessDecorators.hpp"
  39 #include "oops/klass.inline.hpp"
  40 #include "oops/layoutKind.hpp"
  41 #include "oops/objArrayKlass.hpp"
  42 #include "opto/addnode.hpp"
  43 #include "opto/arraycopynode.hpp"
  44 #include "opto/c2compiler.hpp"
  45 #include "opto/castnode.hpp"
  46 #include "opto/cfgnode.hpp"
  47 #include "opto/convertnode.hpp"
  48 #include "opto/countbitsnode.hpp"
  49 #include "opto/graphKit.hpp"
  50 #include "opto/idealKit.hpp"
  51 #include "opto/inlinetypenode.hpp"
  52 #include "opto/library_call.hpp"
  53 #include "opto/mathexactnode.hpp"
  54 #include "opto/mulnode.hpp"
  55 #include "opto/narrowptrnode.hpp"
  56 #include "opto/opaquenode.hpp"
  57 #include "opto/opcodes.hpp"
  58 #include "opto/parse.hpp"
  59 #include "opto/rootnode.hpp"
  60 #include "opto/runtime.hpp"
  61 #include "opto/subnode.hpp"
  62 #include "opto/type.hpp"
  63 #include "opto/vectornode.hpp"
  64 #include "prims/jvmtiExport.hpp"
  65 #include "prims/jvmtiThreadState.hpp"
  66 #include "prims/unsafe.hpp"
  67 #include "runtime/jniHandles.inline.hpp"
  68 #include "runtime/objectMonitor.hpp"
  69 #include "runtime/sharedRuntime.hpp"
  70 #include "runtime/stubRoutines.hpp"
  71 #include "utilities/globalDefinitions.hpp"
  72 #include "utilities/macros.hpp"
  73 #include "utilities/powerOfTwo.hpp"
  74 
  75 //---------------------------make_vm_intrinsic----------------------------
  76 CallGenerator* Compile::make_vm_intrinsic(ciMethod* m, bool is_virtual) {
  77   vmIntrinsicID id = m->intrinsic_id();
  78   assert(id != vmIntrinsics::_none, "must be a VM intrinsic");
  79 
  80   if (!m->is_loaded()) {
  81     // Do not attempt to inline unloaded methods.
  82     return nullptr;
  83   }
  84 
  85   C2Compiler* compiler = (C2Compiler*)CompileBroker::compiler(CompLevel_full_optimization);
  86   bool is_available = false;
  87 
  88   {
  89     // For calling is_intrinsic_supported and is_intrinsic_disabled_by_flag
  90     // the compiler must transition to '_thread_in_vm' state because both
  91     // methods access VM-internal data.
  92     VM_ENTRY_MARK;
  93     methodHandle mh(THREAD, m->get_Method());
  94     is_available = compiler != nullptr && compiler->is_intrinsic_available(mh, C->directive());
  95     if (is_available && is_virtual) {
  96       is_available = vmIntrinsics::does_virtual_dispatch(id);
  97     }
  98   }
  99 
 100   if (is_available) {
 101     assert(id <= vmIntrinsics::LAST_COMPILER_INLINE, "caller responsibility");
 102     assert(id != vmIntrinsics::_Object_init && id != vmIntrinsics::_invoke, "enum out of order?");
 103     return new LibraryIntrinsic(m, is_virtual,
 104                                 vmIntrinsics::predicates_needed(id),
 105                                 vmIntrinsics::does_virtual_dispatch(id),
 106                                 id);
 107   } else {
 108     return nullptr;
 109   }
 110 }
 111 
 112 JVMState* LibraryIntrinsic::generate(JVMState* jvms) {
 113   LibraryCallKit kit(jvms, this);
 114   Compile* C = kit.C;
 115   int nodes = C->unique();
 116 #ifndef PRODUCT
 117   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
 118     char buf[1000];
 119     const char* str = vmIntrinsics::short_name_as_C_string(intrinsic_id(), buf, sizeof(buf));
 120     tty->print_cr("Intrinsic %s", str);
 121   }
 122 #endif
 123   ciMethod* callee = kit.callee();
 124   const int bci    = kit.bci();
 125 #ifdef ASSERT
 126   Node* ctrl = kit.control();
 127 #endif
 128   // Try to inline the intrinsic.
 129   if (callee->check_intrinsic_candidate() &&
 130       kit.try_to_inline(_last_predicate)) {
 131     const char *inline_msg = is_virtual() ? "(intrinsic, virtual)"
 132                                           : "(intrinsic)";
 133     CompileTask::print_inlining_ul(callee, jvms->depth() - 1, bci, InliningResult::SUCCESS, inline_msg);
 134     C->inline_printer()->record(callee, jvms, InliningResult::SUCCESS, inline_msg);
 135     C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_worked);
 136     if (C->log()) {
 137       C->log()->elem("intrinsic id='%s'%s nodes='%d'",
 138                      vmIntrinsics::name_at(intrinsic_id()),
 139                      (is_virtual() ? " virtual='1'" : ""),
 140                      C->unique() - nodes);
 141     }
 142     // Push the result from the inlined method onto the stack.
 143     kit.push_result();
 144     return kit.transfer_exceptions_into_jvms();
 145   }
 146 
 147   // The intrinsic bailed out
 148   assert(ctrl == kit.control(), "Control flow was added although the intrinsic bailed out");
 149   assert(jvms->map() == kit.map(), "Out of sync JVM state");
 150   if (jvms->has_method()) {
 151     // Not a root compile.
 152     const char* msg;
 153     if (callee->intrinsic_candidate()) {
 154       msg = is_virtual() ? "failed to inline (intrinsic, virtual)" : "failed to inline (intrinsic)";
 155     } else {
 156       msg = is_virtual() ? "failed to inline (intrinsic, virtual), method not annotated"
 157                          : "failed to inline (intrinsic), method not annotated";
 158     }
 159     CompileTask::print_inlining_ul(callee, jvms->depth() - 1, bci, InliningResult::FAILURE, msg);
 160     C->inline_printer()->record(callee, jvms, InliningResult::FAILURE, msg);
 161   } else {
 162     // Root compile
 163     ResourceMark rm;
 164     stringStream msg_stream;
 165     msg_stream.print("Did not generate intrinsic %s%s at bci:%d in",
 166                      vmIntrinsics::name_at(intrinsic_id()),
 167                      is_virtual() ? " (virtual)" : "", bci);
 168     const char *msg = msg_stream.freeze();
 169     log_debug(jit, inlining)("%s", msg);
 170     if (C->print_intrinsics() || C->print_inlining()) {
 171       tty->print("%s", msg);
 172     }
 173   }
 174   C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_failed);
 175 
 176   return nullptr;
 177 }
 178 
 179 Node* LibraryIntrinsic::generate_predicate(JVMState* jvms, int predicate) {
 180   LibraryCallKit kit(jvms, this);
 181   Compile* C = kit.C;
 182   int nodes = C->unique();
 183   _last_predicate = predicate;
 184 #ifndef PRODUCT
 185   assert(is_predicated() && predicate < predicates_count(), "sanity");
 186   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
 187     char buf[1000];
 188     const char* str = vmIntrinsics::short_name_as_C_string(intrinsic_id(), buf, sizeof(buf));
 189     tty->print_cr("Predicate for intrinsic %s", str);
 190   }
 191 #endif
 192   ciMethod* callee = kit.callee();
 193   const int bci    = kit.bci();
 194 
 195   Node* slow_ctl = kit.try_to_predicate(predicate);
 196   if (!kit.failing()) {
 197     const char *inline_msg = is_virtual() ? "(intrinsic, virtual, predicate)"
 198                                           : "(intrinsic, predicate)";
 199     CompileTask::print_inlining_ul(callee, jvms->depth() - 1, bci, InliningResult::SUCCESS, inline_msg);
 200     C->inline_printer()->record(callee, jvms, InliningResult::SUCCESS, inline_msg);
 201 
 202     C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_worked);
 203     if (C->log()) {
 204       C->log()->elem("predicate_intrinsic id='%s'%s nodes='%d'",
 205                      vmIntrinsics::name_at(intrinsic_id()),
 206                      (is_virtual() ? " virtual='1'" : ""),
 207                      C->unique() - nodes);
 208     }
 209     return slow_ctl; // Could be null if the check folds.
 210   }
 211 
 212   // The intrinsic bailed out
 213   if (jvms->has_method()) {
 214     // Not a root compile.
 215     const char* msg = "failed to generate predicate for intrinsic";
 216     CompileTask::print_inlining_ul(kit.callee(), jvms->depth() - 1, bci, InliningResult::FAILURE, msg);
 217     C->inline_printer()->record(kit.callee(), jvms, InliningResult::FAILURE, msg);
 218   } else {
 219     // Root compile
 220     ResourceMark rm;
 221     stringStream msg_stream;
 222     msg_stream.print("Did not generate intrinsic %s%s at bci:%d in",
 223                      vmIntrinsics::name_at(intrinsic_id()),
 224                      is_virtual() ? " (virtual)" : "", bci);
 225     const char *msg = msg_stream.freeze();
 226     log_debug(jit, inlining)("%s", msg);
 227     C->inline_printer()->record(kit.callee(), jvms, InliningResult::FAILURE, msg);
 228   }
 229   C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_failed);
 230   return nullptr;
 231 }
 232 
 233 bool LibraryCallKit::try_to_inline(int predicate) {
 234   // Handle symbolic names for otherwise undistinguished boolean switches:
 235   const bool is_store       = true;
 236   const bool is_compress    = true;
 237   const bool is_static      = true;
 238   const bool is_volatile    = true;
 239 
 240   if (!jvms()->has_method()) {
 241     // Root JVMState has a null method.
 242     assert(map()->memory()->Opcode() == Op_Parm, "");
 243     // Insert the memory aliasing node
 244     set_all_memory(reset_memory());
 245   }
 246   assert(merged_memory(), "");
 247 
 248   switch (intrinsic_id()) {
 249   case vmIntrinsics::_hashCode:                 return inline_native_hashcode(intrinsic()->is_virtual(), !is_static);
 250   case vmIntrinsics::_identityHashCode:         return inline_native_hashcode(/*!virtual*/ false,         is_static);
 251   case vmIntrinsics::_getClass:                 return inline_native_getClass();
 252 
 253   case vmIntrinsics::_ceil:
 254   case vmIntrinsics::_floor:
 255   case vmIntrinsics::_rint:
 256   case vmIntrinsics::_dsin:
 257   case vmIntrinsics::_dcos:
 258   case vmIntrinsics::_dtan:
 259   case vmIntrinsics::_dsinh:
 260   case vmIntrinsics::_dtanh:
 261   case vmIntrinsics::_dcbrt:
 262   case vmIntrinsics::_dabs:
 263   case vmIntrinsics::_fabs:
 264   case vmIntrinsics::_iabs:
 265   case vmIntrinsics::_labs:
 266   case vmIntrinsics::_datan2:
 267   case vmIntrinsics::_dsqrt:
 268   case vmIntrinsics::_dsqrt_strict:
 269   case vmIntrinsics::_dexp:
 270   case vmIntrinsics::_dlog:
 271   case vmIntrinsics::_dlog10:
 272   case vmIntrinsics::_dpow:
 273   case vmIntrinsics::_dcopySign:
 274   case vmIntrinsics::_fcopySign:
 275   case vmIntrinsics::_dsignum:
 276   case vmIntrinsics::_roundF:
 277   case vmIntrinsics::_roundD:
 278   case vmIntrinsics::_fsignum:                  return inline_math_native(intrinsic_id());
 279 
 280   case vmIntrinsics::_notify:
 281   case vmIntrinsics::_notifyAll:
 282     return inline_notify(intrinsic_id());
 283 
 284   case vmIntrinsics::_addExactI:                return inline_math_addExactI(false /* add */);
 285   case vmIntrinsics::_addExactL:                return inline_math_addExactL(false /* add */);
 286   case vmIntrinsics::_decrementExactI:          return inline_math_subtractExactI(true /* decrement */);
 287   case vmIntrinsics::_decrementExactL:          return inline_math_subtractExactL(true /* decrement */);
 288   case vmIntrinsics::_incrementExactI:          return inline_math_addExactI(true /* increment */);
 289   case vmIntrinsics::_incrementExactL:          return inline_math_addExactL(true /* increment */);
 290   case vmIntrinsics::_multiplyExactI:           return inline_math_multiplyExactI();
 291   case vmIntrinsics::_multiplyExactL:           return inline_math_multiplyExactL();
 292   case vmIntrinsics::_multiplyHigh:             return inline_math_multiplyHigh();
 293   case vmIntrinsics::_unsignedMultiplyHigh:     return inline_math_unsignedMultiplyHigh();
 294   case vmIntrinsics::_negateExactI:             return inline_math_negateExactI();
 295   case vmIntrinsics::_negateExactL:             return inline_math_negateExactL();
 296   case vmIntrinsics::_subtractExactI:           return inline_math_subtractExactI(false /* subtract */);
 297   case vmIntrinsics::_subtractExactL:           return inline_math_subtractExactL(false /* subtract */);
 298 
 299   case vmIntrinsics::_arraycopy:                return inline_arraycopy();
 300 
 301   case vmIntrinsics::_arraySort:                return inline_array_sort();
 302   case vmIntrinsics::_arrayPartition:           return inline_array_partition();
 303 
 304   case vmIntrinsics::_compareToL:               return inline_string_compareTo(StrIntrinsicNode::LL);
 305   case vmIntrinsics::_compareToU:               return inline_string_compareTo(StrIntrinsicNode::UU);
 306   case vmIntrinsics::_compareToLU:              return inline_string_compareTo(StrIntrinsicNode::LU);
 307   case vmIntrinsics::_compareToUL:              return inline_string_compareTo(StrIntrinsicNode::UL);
 308 
 309   case vmIntrinsics::_indexOfL:                 return inline_string_indexOf(StrIntrinsicNode::LL);
 310   case vmIntrinsics::_indexOfU:                 return inline_string_indexOf(StrIntrinsicNode::UU);
 311   case vmIntrinsics::_indexOfUL:                return inline_string_indexOf(StrIntrinsicNode::UL);
 312   case vmIntrinsics::_indexOfIL:                return inline_string_indexOfI(StrIntrinsicNode::LL);
 313   case vmIntrinsics::_indexOfIU:                return inline_string_indexOfI(StrIntrinsicNode::UU);
 314   case vmIntrinsics::_indexOfIUL:               return inline_string_indexOfI(StrIntrinsicNode::UL);
 315   case vmIntrinsics::_indexOfU_char:            return inline_string_indexOfChar(StrIntrinsicNode::U);
 316   case vmIntrinsics::_indexOfL_char:            return inline_string_indexOfChar(StrIntrinsicNode::L);
 317 
 318   case vmIntrinsics::_equalsL:                  return inline_string_equals(StrIntrinsicNode::LL);
 319 
 320   case vmIntrinsics::_vectorizedHashCode:       return inline_vectorizedHashCode();
 321 
 322   case vmIntrinsics::_toBytesStringU:           return inline_string_toBytesU();
 323   case vmIntrinsics::_getCharsStringU:          return inline_string_getCharsU();
 324   case vmIntrinsics::_getCharStringU:           return inline_string_char_access(!is_store);
 325   case vmIntrinsics::_putCharStringU:           return inline_string_char_access( is_store);
 326 
 327   case vmIntrinsics::_compressStringC:
 328   case vmIntrinsics::_compressStringB:          return inline_string_copy( is_compress);
 329   case vmIntrinsics::_inflateStringC:
 330   case vmIntrinsics::_inflateStringB:           return inline_string_copy(!is_compress);
 331 
 332   case vmIntrinsics::_makePrivateBuffer:        return inline_unsafe_make_private_buffer();
 333   case vmIntrinsics::_finishPrivateBuffer:      return inline_unsafe_finish_private_buffer();
 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   case vmIntrinsics::_getValue:                 return inline_unsafe_access(!is_store, T_OBJECT,   Relaxed, false, true);
 344 
 345   case vmIntrinsics::_putReference:             return inline_unsafe_access( is_store, T_OBJECT,   Relaxed, false);
 346   case vmIntrinsics::_putBoolean:               return inline_unsafe_access( is_store, T_BOOLEAN,  Relaxed, false);
 347   case vmIntrinsics::_putByte:                  return inline_unsafe_access( is_store, T_BYTE,     Relaxed, false);
 348   case vmIntrinsics::_putShort:                 return inline_unsafe_access( is_store, T_SHORT,    Relaxed, false);
 349   case vmIntrinsics::_putChar:                  return inline_unsafe_access( is_store, T_CHAR,     Relaxed, false);
 350   case vmIntrinsics::_putInt:                   return inline_unsafe_access( is_store, T_INT,      Relaxed, false);
 351   case vmIntrinsics::_putLong:                  return inline_unsafe_access( is_store, T_LONG,     Relaxed, false);
 352   case vmIntrinsics::_putFloat:                 return inline_unsafe_access( is_store, T_FLOAT,    Relaxed, false);
 353   case vmIntrinsics::_putDouble:                return inline_unsafe_access( is_store, T_DOUBLE,   Relaxed, false);
 354   case vmIntrinsics::_putValue:                 return inline_unsafe_access( is_store, T_OBJECT,   Relaxed, false, true);
 355 
 356   case vmIntrinsics::_getReferenceVolatile:     return inline_unsafe_access(!is_store, T_OBJECT,   Volatile, false);
 357   case vmIntrinsics::_getBooleanVolatile:       return inline_unsafe_access(!is_store, T_BOOLEAN,  Volatile, false);
 358   case vmIntrinsics::_getByteVolatile:          return inline_unsafe_access(!is_store, T_BYTE,     Volatile, false);
 359   case vmIntrinsics::_getShortVolatile:         return inline_unsafe_access(!is_store, T_SHORT,    Volatile, false);
 360   case vmIntrinsics::_getCharVolatile:          return inline_unsafe_access(!is_store, T_CHAR,     Volatile, false);
 361   case vmIntrinsics::_getIntVolatile:           return inline_unsafe_access(!is_store, T_INT,      Volatile, false);
 362   case vmIntrinsics::_getLongVolatile:          return inline_unsafe_access(!is_store, T_LONG,     Volatile, false);
 363   case vmIntrinsics::_getFloatVolatile:         return inline_unsafe_access(!is_store, T_FLOAT,    Volatile, false);
 364   case vmIntrinsics::_getDoubleVolatile:        return inline_unsafe_access(!is_store, T_DOUBLE,   Volatile, false);
 365 
 366   case vmIntrinsics::_putReferenceVolatile:     return inline_unsafe_access( is_store, T_OBJECT,   Volatile, false);
 367   case vmIntrinsics::_putBooleanVolatile:       return inline_unsafe_access( is_store, T_BOOLEAN,  Volatile, false);
 368   case vmIntrinsics::_putByteVolatile:          return inline_unsafe_access( is_store, T_BYTE,     Volatile, false);
 369   case vmIntrinsics::_putShortVolatile:         return inline_unsafe_access( is_store, T_SHORT,    Volatile, false);
 370   case vmIntrinsics::_putCharVolatile:          return inline_unsafe_access( is_store, T_CHAR,     Volatile, false);
 371   case vmIntrinsics::_putIntVolatile:           return inline_unsafe_access( is_store, T_INT,      Volatile, false);
 372   case vmIntrinsics::_putLongVolatile:          return inline_unsafe_access( is_store, T_LONG,     Volatile, false);
 373   case vmIntrinsics::_putFloatVolatile:         return inline_unsafe_access( is_store, T_FLOAT,    Volatile, false);
 374   case vmIntrinsics::_putDoubleVolatile:        return inline_unsafe_access( is_store, T_DOUBLE,   Volatile, false);
 375 
 376   case vmIntrinsics::_getShortUnaligned:        return inline_unsafe_access(!is_store, T_SHORT,    Relaxed, true);
 377   case vmIntrinsics::_getCharUnaligned:         return inline_unsafe_access(!is_store, T_CHAR,     Relaxed, true);
 378   case vmIntrinsics::_getIntUnaligned:          return inline_unsafe_access(!is_store, T_INT,      Relaxed, true);
 379   case vmIntrinsics::_getLongUnaligned:         return inline_unsafe_access(!is_store, T_LONG,     Relaxed, true);
 380 
 381   case vmIntrinsics::_putShortUnaligned:        return inline_unsafe_access( is_store, T_SHORT,    Relaxed, true);
 382   case vmIntrinsics::_putCharUnaligned:         return inline_unsafe_access( is_store, T_CHAR,     Relaxed, true);
 383   case vmIntrinsics::_putIntUnaligned:          return inline_unsafe_access( is_store, T_INT,      Relaxed, true);
 384   case vmIntrinsics::_putLongUnaligned:         return inline_unsafe_access( is_store, T_LONG,     Relaxed, true);
 385 
 386   case vmIntrinsics::_getReferenceAcquire:      return inline_unsafe_access(!is_store, T_OBJECT,   Acquire, false);
 387   case vmIntrinsics::_getBooleanAcquire:        return inline_unsafe_access(!is_store, T_BOOLEAN,  Acquire, false);
 388   case vmIntrinsics::_getByteAcquire:           return inline_unsafe_access(!is_store, T_BYTE,     Acquire, false);
 389   case vmIntrinsics::_getShortAcquire:          return inline_unsafe_access(!is_store, T_SHORT,    Acquire, false);
 390   case vmIntrinsics::_getCharAcquire:           return inline_unsafe_access(!is_store, T_CHAR,     Acquire, false);
 391   case vmIntrinsics::_getIntAcquire:            return inline_unsafe_access(!is_store, T_INT,      Acquire, false);
 392   case vmIntrinsics::_getLongAcquire:           return inline_unsafe_access(!is_store, T_LONG,     Acquire, false);
 393   case vmIntrinsics::_getFloatAcquire:          return inline_unsafe_access(!is_store, T_FLOAT,    Acquire, false);
 394   case vmIntrinsics::_getDoubleAcquire:         return inline_unsafe_access(!is_store, T_DOUBLE,   Acquire, false);
 395 
 396   case vmIntrinsics::_putReferenceRelease:      return inline_unsafe_access( is_store, T_OBJECT,   Release, false);
 397   case vmIntrinsics::_putBooleanRelease:        return inline_unsafe_access( is_store, T_BOOLEAN,  Release, false);
 398   case vmIntrinsics::_putByteRelease:           return inline_unsafe_access( is_store, T_BYTE,     Release, false);
 399   case vmIntrinsics::_putShortRelease:          return inline_unsafe_access( is_store, T_SHORT,    Release, false);
 400   case vmIntrinsics::_putCharRelease:           return inline_unsafe_access( is_store, T_CHAR,     Release, false);
 401   case vmIntrinsics::_putIntRelease:            return inline_unsafe_access( is_store, T_INT,      Release, false);
 402   case vmIntrinsics::_putLongRelease:           return inline_unsafe_access( is_store, T_LONG,     Release, false);
 403   case vmIntrinsics::_putFloatRelease:          return inline_unsafe_access( is_store, T_FLOAT,    Release, false);
 404   case vmIntrinsics::_putDoubleRelease:         return inline_unsafe_access( is_store, T_DOUBLE,   Release, false);
 405 
 406   case vmIntrinsics::_getReferenceOpaque:       return inline_unsafe_access(!is_store, T_OBJECT,   Opaque, false);
 407   case vmIntrinsics::_getBooleanOpaque:         return inline_unsafe_access(!is_store, T_BOOLEAN,  Opaque, false);
 408   case vmIntrinsics::_getByteOpaque:            return inline_unsafe_access(!is_store, T_BYTE,     Opaque, false);
 409   case vmIntrinsics::_getShortOpaque:           return inline_unsafe_access(!is_store, T_SHORT,    Opaque, false);
 410   case vmIntrinsics::_getCharOpaque:            return inline_unsafe_access(!is_store, T_CHAR,     Opaque, false);
 411   case vmIntrinsics::_getIntOpaque:             return inline_unsafe_access(!is_store, T_INT,      Opaque, false);
 412   case vmIntrinsics::_getLongOpaque:            return inline_unsafe_access(!is_store, T_LONG,     Opaque, false);
 413   case vmIntrinsics::_getFloatOpaque:           return inline_unsafe_access(!is_store, T_FLOAT,    Opaque, false);
 414   case vmIntrinsics::_getDoubleOpaque:          return inline_unsafe_access(!is_store, T_DOUBLE,   Opaque, false);
 415 
 416   case vmIntrinsics::_putReferenceOpaque:       return inline_unsafe_access( is_store, T_OBJECT,   Opaque, false);
 417   case vmIntrinsics::_putBooleanOpaque:         return inline_unsafe_access( is_store, T_BOOLEAN,  Opaque, false);
 418   case vmIntrinsics::_putByteOpaque:            return inline_unsafe_access( is_store, T_BYTE,     Opaque, false);
 419   case vmIntrinsics::_putShortOpaque:           return inline_unsafe_access( is_store, T_SHORT,    Opaque, false);
 420   case vmIntrinsics::_putCharOpaque:            return inline_unsafe_access( is_store, T_CHAR,     Opaque, false);
 421   case vmIntrinsics::_putIntOpaque:             return inline_unsafe_access( is_store, T_INT,      Opaque, false);
 422   case vmIntrinsics::_putLongOpaque:            return inline_unsafe_access( is_store, T_LONG,     Opaque, false);
 423   case vmIntrinsics::_putFloatOpaque:           return inline_unsafe_access( is_store, T_FLOAT,    Opaque, false);
 424   case vmIntrinsics::_putDoubleOpaque:          return inline_unsafe_access( is_store, T_DOUBLE,   Opaque, false);
 425 
 426   case vmIntrinsics::_getFlatValue:             return inline_unsafe_flat_access(!is_store, Relaxed);
 427   case vmIntrinsics::_putFlatValue:             return inline_unsafe_flat_access( is_store, Relaxed);
 428 
 429   case vmIntrinsics::_compareAndSetReference:   return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap,      Volatile);
 430   case vmIntrinsics::_compareAndSetByte:        return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap,      Volatile);
 431   case vmIntrinsics::_compareAndSetShort:       return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap,      Volatile);
 432   case vmIntrinsics::_compareAndSetInt:         return inline_unsafe_load_store(T_INT,    LS_cmp_swap,      Volatile);
 433   case vmIntrinsics::_compareAndSetLong:        return inline_unsafe_load_store(T_LONG,   LS_cmp_swap,      Volatile);
 434 
 435   case vmIntrinsics::_weakCompareAndSetReferencePlain:     return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Relaxed);
 436   case vmIntrinsics::_weakCompareAndSetReferenceAcquire:   return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Acquire);
 437   case vmIntrinsics::_weakCompareAndSetReferenceRelease:   return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Release);
 438   case vmIntrinsics::_weakCompareAndSetReference:          return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Volatile);
 439   case vmIntrinsics::_weakCompareAndSetBytePlain:          return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap_weak, Relaxed);
 440   case vmIntrinsics::_weakCompareAndSetByteAcquire:        return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap_weak, Acquire);
 441   case vmIntrinsics::_weakCompareAndSetByteRelease:        return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap_weak, Release);
 442   case vmIntrinsics::_weakCompareAndSetByte:               return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap_weak, Volatile);
 443   case vmIntrinsics::_weakCompareAndSetShortPlain:         return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap_weak, Relaxed);
 444   case vmIntrinsics::_weakCompareAndSetShortAcquire:       return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap_weak, Acquire);
 445   case vmIntrinsics::_weakCompareAndSetShortRelease:       return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap_weak, Release);
 446   case vmIntrinsics::_weakCompareAndSetShort:              return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap_weak, Volatile);
 447   case vmIntrinsics::_weakCompareAndSetIntPlain:           return inline_unsafe_load_store(T_INT,    LS_cmp_swap_weak, Relaxed);
 448   case vmIntrinsics::_weakCompareAndSetIntAcquire:         return inline_unsafe_load_store(T_INT,    LS_cmp_swap_weak, Acquire);
 449   case vmIntrinsics::_weakCompareAndSetIntRelease:         return inline_unsafe_load_store(T_INT,    LS_cmp_swap_weak, Release);
 450   case vmIntrinsics::_weakCompareAndSetInt:                return inline_unsafe_load_store(T_INT,    LS_cmp_swap_weak, Volatile);
 451   case vmIntrinsics::_weakCompareAndSetLongPlain:          return inline_unsafe_load_store(T_LONG,   LS_cmp_swap_weak, Relaxed);
 452   case vmIntrinsics::_weakCompareAndSetLongAcquire:        return inline_unsafe_load_store(T_LONG,   LS_cmp_swap_weak, Acquire);
 453   case vmIntrinsics::_weakCompareAndSetLongRelease:        return inline_unsafe_load_store(T_LONG,   LS_cmp_swap_weak, Release);
 454   case vmIntrinsics::_weakCompareAndSetLong:               return inline_unsafe_load_store(T_LONG,   LS_cmp_swap_weak, Volatile);
 455 
 456   case vmIntrinsics::_compareAndExchangeReference:         return inline_unsafe_load_store(T_OBJECT, LS_cmp_exchange,  Volatile);
 457   case vmIntrinsics::_compareAndExchangeReferenceAcquire:  return inline_unsafe_load_store(T_OBJECT, LS_cmp_exchange,  Acquire);
 458   case vmIntrinsics::_compareAndExchangeReferenceRelease:  return inline_unsafe_load_store(T_OBJECT, LS_cmp_exchange,  Release);
 459   case vmIntrinsics::_compareAndExchangeByte:              return inline_unsafe_load_store(T_BYTE,   LS_cmp_exchange,  Volatile);
 460   case vmIntrinsics::_compareAndExchangeByteAcquire:       return inline_unsafe_load_store(T_BYTE,   LS_cmp_exchange,  Acquire);
 461   case vmIntrinsics::_compareAndExchangeByteRelease:       return inline_unsafe_load_store(T_BYTE,   LS_cmp_exchange,  Release);
 462   case vmIntrinsics::_compareAndExchangeShort:             return inline_unsafe_load_store(T_SHORT,  LS_cmp_exchange,  Volatile);
 463   case vmIntrinsics::_compareAndExchangeShortAcquire:      return inline_unsafe_load_store(T_SHORT,  LS_cmp_exchange,  Acquire);
 464   case vmIntrinsics::_compareAndExchangeShortRelease:      return inline_unsafe_load_store(T_SHORT,  LS_cmp_exchange,  Release);
 465   case vmIntrinsics::_compareAndExchangeInt:               return inline_unsafe_load_store(T_INT,    LS_cmp_exchange,  Volatile);
 466   case vmIntrinsics::_compareAndExchangeIntAcquire:        return inline_unsafe_load_store(T_INT,    LS_cmp_exchange,  Acquire);
 467   case vmIntrinsics::_compareAndExchangeIntRelease:        return inline_unsafe_load_store(T_INT,    LS_cmp_exchange,  Release);
 468   case vmIntrinsics::_compareAndExchangeLong:              return inline_unsafe_load_store(T_LONG,   LS_cmp_exchange,  Volatile);
 469   case vmIntrinsics::_compareAndExchangeLongAcquire:       return inline_unsafe_load_store(T_LONG,   LS_cmp_exchange,  Acquire);
 470   case vmIntrinsics::_compareAndExchangeLongRelease:       return inline_unsafe_load_store(T_LONG,   LS_cmp_exchange,  Release);
 471 
 472   case vmIntrinsics::_getAndAddByte:                    return inline_unsafe_load_store(T_BYTE,   LS_get_add,       Volatile);
 473   case vmIntrinsics::_getAndAddShort:                   return inline_unsafe_load_store(T_SHORT,  LS_get_add,       Volatile);
 474   case vmIntrinsics::_getAndAddInt:                     return inline_unsafe_load_store(T_INT,    LS_get_add,       Volatile);
 475   case vmIntrinsics::_getAndAddLong:                    return inline_unsafe_load_store(T_LONG,   LS_get_add,       Volatile);
 476 
 477   case vmIntrinsics::_getAndSetByte:                    return inline_unsafe_load_store(T_BYTE,   LS_get_set,       Volatile);
 478   case vmIntrinsics::_getAndSetShort:                   return inline_unsafe_load_store(T_SHORT,  LS_get_set,       Volatile);
 479   case vmIntrinsics::_getAndSetInt:                     return inline_unsafe_load_store(T_INT,    LS_get_set,       Volatile);
 480   case vmIntrinsics::_getAndSetLong:                    return inline_unsafe_load_store(T_LONG,   LS_get_set,       Volatile);
 481   case vmIntrinsics::_getAndSetReference:               return inline_unsafe_load_store(T_OBJECT, LS_get_set,       Volatile);
 482 
 483   case vmIntrinsics::_loadFence:
 484   case vmIntrinsics::_storeFence:
 485   case vmIntrinsics::_storeStoreFence:
 486   case vmIntrinsics::_fullFence:                return inline_unsafe_fence(intrinsic_id());
 487 
 488   case vmIntrinsics::_onSpinWait:               return inline_onspinwait();
 489 
 490   case vmIntrinsics::_currentCarrierThread:     return inline_native_currentCarrierThread();
 491   case vmIntrinsics::_currentThread:            return inline_native_currentThread();
 492   case vmIntrinsics::_setCurrentThread:         return inline_native_setCurrentThread();
 493 
 494   case vmIntrinsics::_scopedValueCache:          return inline_native_scopedValueCache();
 495   case vmIntrinsics::_setScopedValueCache:       return inline_native_setScopedValueCache();
 496 
 497   case vmIntrinsics::_Continuation_pin:          return inline_native_Continuation_pinning(false);
 498   case vmIntrinsics::_Continuation_unpin:        return inline_native_Continuation_pinning(true);
 499 
 500 #if INCLUDE_JVMTI
 501   case vmIntrinsics::_notifyJvmtiVThreadStart:   return inline_native_notify_jvmti_funcs(CAST_FROM_FN_PTR(address, OptoRuntime::notify_jvmti_vthread_start()),
 502                                                                                          "notifyJvmtiStart", true, false);
 503   case vmIntrinsics::_notifyJvmtiVThreadEnd:     return inline_native_notify_jvmti_funcs(CAST_FROM_FN_PTR(address, OptoRuntime::notify_jvmti_vthread_end()),
 504                                                                                          "notifyJvmtiEnd", false, true);
 505   case vmIntrinsics::_notifyJvmtiVThreadMount:   return inline_native_notify_jvmti_funcs(CAST_FROM_FN_PTR(address, OptoRuntime::notify_jvmti_vthread_mount()),
 506                                                                                          "notifyJvmtiMount", false, false);
 507   case vmIntrinsics::_notifyJvmtiVThreadUnmount: return inline_native_notify_jvmti_funcs(CAST_FROM_FN_PTR(address, OptoRuntime::notify_jvmti_vthread_unmount()),
 508                                                                                          "notifyJvmtiUnmount", false, false);
 509   case vmIntrinsics::_notifyJvmtiVThreadDisableSuspend: return inline_native_notify_jvmti_sync();
 510 #endif
 511 
 512 #ifdef JFR_HAVE_INTRINSICS
 513   case vmIntrinsics::_counterTime:              return inline_native_time_funcs(CAST_FROM_FN_PTR(address, JfrTime::time_function()), "counterTime");
 514   case vmIntrinsics::_getEventWriter:           return inline_native_getEventWriter();
 515   case vmIntrinsics::_jvm_commit:               return inline_native_jvm_commit();
 516 #endif
 517   case vmIntrinsics::_currentTimeMillis:        return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeMillis), "currentTimeMillis");
 518   case vmIntrinsics::_nanoTime:                 return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeNanos), "nanoTime");
 519   case vmIntrinsics::_writeback0:               return inline_unsafe_writeback0();
 520   case vmIntrinsics::_writebackPreSync0:        return inline_unsafe_writebackSync0(true);
 521   case vmIntrinsics::_writebackPostSync0:       return inline_unsafe_writebackSync0(false);
 522   case vmIntrinsics::_allocateInstance:         return inline_unsafe_allocate();
 523   case vmIntrinsics::_copyMemory:               return inline_unsafe_copyMemory();
 524   case vmIntrinsics::_setMemory:                return inline_unsafe_setMemory();
 525   case vmIntrinsics::_getLength:                return inline_native_getLength();
 526   case vmIntrinsics::_copyOf:                   return inline_array_copyOf(false);
 527   case vmIntrinsics::_copyOfRange:              return inline_array_copyOf(true);
 528   case vmIntrinsics::_equalsB:                  return inline_array_equals(StrIntrinsicNode::LL);
 529   case vmIntrinsics::_equalsC:                  return inline_array_equals(StrIntrinsicNode::UU);
 530   case vmIntrinsics::_Preconditions_checkIndex: return inline_preconditions_checkIndex(T_INT);
 531   case vmIntrinsics::_Preconditions_checkLongIndex: return inline_preconditions_checkIndex(T_LONG);
 532   case vmIntrinsics::_clone:                    return inline_native_clone(intrinsic()->is_virtual());
 533 
 534   case vmIntrinsics::_allocateUninitializedArray: return inline_unsafe_newArray(true);
 535   case vmIntrinsics::_newArray:                   return inline_unsafe_newArray(false);
 536   case vmIntrinsics::_newNullRestrictedNonAtomicArray: return inline_newArray(/* null_free */ true, /* atomic */ false);
 537   case vmIntrinsics::_newNullRestrictedAtomicArray: return inline_newArray(/* null_free */ true, /* atomic */ true);
 538   case vmIntrinsics::_newNullableAtomicArray:     return inline_newArray(/* null_free */ false, /* atomic */ true);
 539   case vmIntrinsics::_isFlatArray:              return inline_getArrayProperties(IsFlat);
 540   case vmIntrinsics::_isNullRestrictedArray:    return inline_getArrayProperties(IsNullRestricted);
 541   case vmIntrinsics::_isAtomicArray:            return inline_getArrayProperties(IsAtomic);
 542 
 543   case vmIntrinsics::_isAssignableFrom:         return inline_native_subtype_check();
 544 
 545   case vmIntrinsics::_isInstance:
 546   case vmIntrinsics::_isHidden:
 547   case vmIntrinsics::_getSuperclass:            return inline_native_Class_query(intrinsic_id());
 548 
 549   case vmIntrinsics::_floatToRawIntBits:
 550   case vmIntrinsics::_floatToIntBits:
 551   case vmIntrinsics::_intBitsToFloat:
 552   case vmIntrinsics::_doubleToRawLongBits:
 553   case vmIntrinsics::_doubleToLongBits:
 554   case vmIntrinsics::_longBitsToDouble:
 555   case vmIntrinsics::_floatToFloat16:
 556   case vmIntrinsics::_float16ToFloat:           return inline_fp_conversions(intrinsic_id());
 557   case vmIntrinsics::_sqrt_float16:             return inline_fp16_operations(intrinsic_id(), 1);
 558   case vmIntrinsics::_fma_float16:              return inline_fp16_operations(intrinsic_id(), 3);
 559   case vmIntrinsics::_floatIsFinite:
 560   case vmIntrinsics::_floatIsInfinite:
 561   case vmIntrinsics::_doubleIsFinite:
 562   case vmIntrinsics::_doubleIsInfinite:         return inline_fp_range_check(intrinsic_id());
 563 
 564   case vmIntrinsics::_numberOfLeadingZeros_i:
 565   case vmIntrinsics::_numberOfLeadingZeros_l:
 566   case vmIntrinsics::_numberOfTrailingZeros_i:
 567   case vmIntrinsics::_numberOfTrailingZeros_l:
 568   case vmIntrinsics::_bitCount_i:
 569   case vmIntrinsics::_bitCount_l:
 570   case vmIntrinsics::_reverse_i:
 571   case vmIntrinsics::_reverse_l:
 572   case vmIntrinsics::_reverseBytes_i:
 573   case vmIntrinsics::_reverseBytes_l:
 574   case vmIntrinsics::_reverseBytes_s:
 575   case vmIntrinsics::_reverseBytes_c:           return inline_number_methods(intrinsic_id());
 576 
 577   case vmIntrinsics::_compress_i:
 578   case vmIntrinsics::_compress_l:
 579   case vmIntrinsics::_expand_i:
 580   case vmIntrinsics::_expand_l:                 return inline_bitshuffle_methods(intrinsic_id());
 581 
 582   case vmIntrinsics::_compareUnsigned_i:
 583   case vmIntrinsics::_compareUnsigned_l:        return inline_compare_unsigned(intrinsic_id());
 584 
 585   case vmIntrinsics::_divideUnsigned_i:
 586   case vmIntrinsics::_divideUnsigned_l:
 587   case vmIntrinsics::_remainderUnsigned_i:
 588   case vmIntrinsics::_remainderUnsigned_l:      return inline_divmod_methods(intrinsic_id());
 589 
 590   case vmIntrinsics::_getCallerClass:           return inline_native_Reflection_getCallerClass();
 591 
 592   case vmIntrinsics::_Reference_get0:           return inline_reference_get0();
 593   case vmIntrinsics::_Reference_refersTo0:      return inline_reference_refersTo0(false);
 594   case vmIntrinsics::_PhantomReference_refersTo0: return inline_reference_refersTo0(true);
 595   case vmIntrinsics::_Reference_clear0:         return inline_reference_clear0(false);
 596   case vmIntrinsics::_PhantomReference_clear0:  return inline_reference_clear0(true);
 597 
 598   case vmIntrinsics::_Class_cast:               return inline_Class_cast();
 599 
 600   case vmIntrinsics::_aescrypt_encryptBlock:
 601   case vmIntrinsics::_aescrypt_decryptBlock:    return inline_aescrypt_Block(intrinsic_id());
 602 
 603   case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
 604   case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
 605     return inline_cipherBlockChaining_AESCrypt(intrinsic_id());
 606 
 607   case vmIntrinsics::_electronicCodeBook_encryptAESCrypt:
 608   case vmIntrinsics::_electronicCodeBook_decryptAESCrypt:
 609     return inline_electronicCodeBook_AESCrypt(intrinsic_id());
 610 
 611   case vmIntrinsics::_counterMode_AESCrypt:
 612     return inline_counterMode_AESCrypt(intrinsic_id());
 613 
 614   case vmIntrinsics::_galoisCounterMode_AESCrypt:
 615     return inline_galoisCounterMode_AESCrypt();
 616 
 617   case vmIntrinsics::_md5_implCompress:
 618   case vmIntrinsics::_sha_implCompress:
 619   case vmIntrinsics::_sha2_implCompress:
 620   case vmIntrinsics::_sha5_implCompress:
 621   case vmIntrinsics::_sha3_implCompress:
 622     return inline_digestBase_implCompress(intrinsic_id());
 623   case vmIntrinsics::_double_keccak:
 624     return inline_double_keccak();
 625 
 626   case vmIntrinsics::_digestBase_implCompressMB:
 627     return inline_digestBase_implCompressMB(predicate);
 628 
 629   case vmIntrinsics::_multiplyToLen:
 630     return inline_multiplyToLen();
 631 
 632   case vmIntrinsics::_squareToLen:
 633     return inline_squareToLen();
 634 
 635   case vmIntrinsics::_mulAdd:
 636     return inline_mulAdd();
 637 
 638   case vmIntrinsics::_montgomeryMultiply:
 639     return inline_montgomeryMultiply();
 640   case vmIntrinsics::_montgomerySquare:
 641     return inline_montgomerySquare();
 642 
 643   case vmIntrinsics::_bigIntegerRightShiftWorker:
 644     return inline_bigIntegerShift(true);
 645   case vmIntrinsics::_bigIntegerLeftShiftWorker:
 646     return inline_bigIntegerShift(false);
 647 
 648   case vmIntrinsics::_vectorizedMismatch:
 649     return inline_vectorizedMismatch();
 650 
 651   case vmIntrinsics::_ghash_processBlocks:
 652     return inline_ghash_processBlocks();
 653   case vmIntrinsics::_chacha20Block:
 654     return inline_chacha20Block();
 655   case vmIntrinsics::_kyberNtt:
 656     return inline_kyberNtt();
 657   case vmIntrinsics::_kyberInverseNtt:
 658     return inline_kyberInverseNtt();
 659   case vmIntrinsics::_kyberNttMult:
 660     return inline_kyberNttMult();
 661   case vmIntrinsics::_kyberAddPoly_2:
 662     return inline_kyberAddPoly_2();
 663   case vmIntrinsics::_kyberAddPoly_3:
 664     return inline_kyberAddPoly_3();
 665   case vmIntrinsics::_kyber12To16:
 666     return inline_kyber12To16();
 667   case vmIntrinsics::_kyberBarrettReduce:
 668     return inline_kyberBarrettReduce();
 669   case vmIntrinsics::_dilithiumAlmostNtt:
 670     return inline_dilithiumAlmostNtt();
 671   case vmIntrinsics::_dilithiumAlmostInverseNtt:
 672     return inline_dilithiumAlmostInverseNtt();
 673   case vmIntrinsics::_dilithiumNttMult:
 674     return inline_dilithiumNttMult();
 675   case vmIntrinsics::_dilithiumMontMulByConstant:
 676     return inline_dilithiumMontMulByConstant();
 677   case vmIntrinsics::_dilithiumDecomposePoly:
 678     return inline_dilithiumDecomposePoly();
 679   case vmIntrinsics::_base64_encodeBlock:
 680     return inline_base64_encodeBlock();
 681   case vmIntrinsics::_base64_decodeBlock:
 682     return inline_base64_decodeBlock();
 683   case vmIntrinsics::_poly1305_processBlocks:
 684     return inline_poly1305_processBlocks();
 685   case vmIntrinsics::_intpoly_montgomeryMult_P256:
 686     return inline_intpoly_montgomeryMult_P256();
 687   case vmIntrinsics::_intpoly_assign:
 688     return inline_intpoly_assign();
 689   case vmIntrinsics::_encodeISOArray:
 690   case vmIntrinsics::_encodeByteISOArray:
 691     return inline_encodeISOArray(false);
 692   case vmIntrinsics::_encodeAsciiArray:
 693     return inline_encodeISOArray(true);
 694 
 695   case vmIntrinsics::_updateCRC32:
 696     return inline_updateCRC32();
 697   case vmIntrinsics::_updateBytesCRC32:
 698     return inline_updateBytesCRC32();
 699   case vmIntrinsics::_updateByteBufferCRC32:
 700     return inline_updateByteBufferCRC32();
 701 
 702   case vmIntrinsics::_updateBytesCRC32C:
 703     return inline_updateBytesCRC32C();
 704   case vmIntrinsics::_updateDirectByteBufferCRC32C:
 705     return inline_updateDirectByteBufferCRC32C();
 706 
 707   case vmIntrinsics::_updateBytesAdler32:
 708     return inline_updateBytesAdler32();
 709   case vmIntrinsics::_updateByteBufferAdler32:
 710     return inline_updateByteBufferAdler32();
 711 
 712   case vmIntrinsics::_profileBoolean:
 713     return inline_profileBoolean();
 714   case vmIntrinsics::_isCompileConstant:
 715     return inline_isCompileConstant();
 716 
 717   case vmIntrinsics::_countPositives:
 718     return inline_countPositives();
 719 
 720   case vmIntrinsics::_fmaD:
 721   case vmIntrinsics::_fmaF:
 722     return inline_fma(intrinsic_id());
 723 
 724   case vmIntrinsics::_isDigit:
 725   case vmIntrinsics::_isLowerCase:
 726   case vmIntrinsics::_isUpperCase:
 727   case vmIntrinsics::_isWhitespace:
 728     return inline_character_compare(intrinsic_id());
 729 
 730   case vmIntrinsics::_min:
 731   case vmIntrinsics::_max:
 732   case vmIntrinsics::_min_strict:
 733   case vmIntrinsics::_max_strict:
 734   case vmIntrinsics::_minL:
 735   case vmIntrinsics::_maxL:
 736   case vmIntrinsics::_minF:
 737   case vmIntrinsics::_maxF:
 738   case vmIntrinsics::_minD:
 739   case vmIntrinsics::_maxD:
 740   case vmIntrinsics::_minF_strict:
 741   case vmIntrinsics::_maxF_strict:
 742   case vmIntrinsics::_minD_strict:
 743   case vmIntrinsics::_maxD_strict:
 744     return inline_min_max(intrinsic_id());
 745 
 746   case vmIntrinsics::_VectorUnaryOp:
 747     return inline_vector_nary_operation(1);
 748   case vmIntrinsics::_VectorBinaryOp:
 749     return inline_vector_nary_operation(2);
 750   case vmIntrinsics::_VectorUnaryLibOp:
 751     return inline_vector_call(1);
 752   case vmIntrinsics::_VectorBinaryLibOp:
 753     return inline_vector_call(2);
 754   case vmIntrinsics::_VectorTernaryOp:
 755     return inline_vector_nary_operation(3);
 756   case vmIntrinsics::_VectorFromBitsCoerced:
 757     return inline_vector_frombits_coerced();
 758   case vmIntrinsics::_VectorMaskOp:
 759     return inline_vector_mask_operation();
 760   case vmIntrinsics::_VectorLoadOp:
 761     return inline_vector_mem_operation(/*is_store=*/false);
 762   case vmIntrinsics::_VectorLoadMaskedOp:
 763     return inline_vector_mem_masked_operation(/*is_store*/false);
 764   case vmIntrinsics::_VectorStoreOp:
 765     return inline_vector_mem_operation(/*is_store=*/true);
 766   case vmIntrinsics::_VectorStoreMaskedOp:
 767     return inline_vector_mem_masked_operation(/*is_store=*/true);
 768   case vmIntrinsics::_VectorGatherOp:
 769     return inline_vector_gather_scatter(/*is_scatter*/ false);
 770   case vmIntrinsics::_VectorScatterOp:
 771     return inline_vector_gather_scatter(/*is_scatter*/ true);
 772   case vmIntrinsics::_VectorReductionCoerced:
 773     return inline_vector_reduction();
 774   case vmIntrinsics::_VectorTest:
 775     return inline_vector_test();
 776   case vmIntrinsics::_VectorBlend:
 777     return inline_vector_blend();
 778   case vmIntrinsics::_VectorRearrange:
 779     return inline_vector_rearrange();
 780   case vmIntrinsics::_VectorSelectFrom:
 781     return inline_vector_select_from();
 782   case vmIntrinsics::_VectorCompare:
 783     return inline_vector_compare();
 784   case vmIntrinsics::_VectorBroadcastInt:
 785     return inline_vector_broadcast_int();
 786   case vmIntrinsics::_VectorConvert:
 787     return inline_vector_convert();
 788   case vmIntrinsics::_VectorInsert:
 789     return inline_vector_insert();
 790   case vmIntrinsics::_VectorExtract:
 791     return inline_vector_extract();
 792   case vmIntrinsics::_VectorCompressExpand:
 793     return inline_vector_compress_expand();
 794   case vmIntrinsics::_VectorSelectFromTwoVectorOp:
 795     return inline_vector_select_from_two_vectors();
 796   case vmIntrinsics::_IndexVector:
 797     return inline_index_vector();
 798   case vmIntrinsics::_IndexPartiallyInUpperRange:
 799     return inline_index_partially_in_upper_range();
 800 
 801   case vmIntrinsics::_getObjectSize:
 802     return inline_getObjectSize();
 803 
 804   case vmIntrinsics::_blackhole:
 805     return inline_blackhole();
 806 
 807   default:
 808     // If you get here, it may be that someone has added a new intrinsic
 809     // to the list in vmIntrinsics.hpp without implementing it here.
 810 #ifndef PRODUCT
 811     if ((PrintMiscellaneous && (Verbose || WizardMode)) || PrintOpto) {
 812       tty->print_cr("*** Warning: Unimplemented intrinsic %s(%d)",
 813                     vmIntrinsics::name_at(intrinsic_id()), vmIntrinsics::as_int(intrinsic_id()));
 814     }
 815 #endif
 816     return false;
 817   }
 818 }
 819 
 820 Node* LibraryCallKit::try_to_predicate(int predicate) {
 821   if (!jvms()->has_method()) {
 822     // Root JVMState has a null method.
 823     assert(map()->memory()->Opcode() == Op_Parm, "");
 824     // Insert the memory aliasing node
 825     set_all_memory(reset_memory());
 826   }
 827   assert(merged_memory(), "");
 828 
 829   switch (intrinsic_id()) {
 830   case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
 831     return inline_cipherBlockChaining_AESCrypt_predicate(false);
 832   case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
 833     return inline_cipherBlockChaining_AESCrypt_predicate(true);
 834   case vmIntrinsics::_electronicCodeBook_encryptAESCrypt:
 835     return inline_electronicCodeBook_AESCrypt_predicate(false);
 836   case vmIntrinsics::_electronicCodeBook_decryptAESCrypt:
 837     return inline_electronicCodeBook_AESCrypt_predicate(true);
 838   case vmIntrinsics::_counterMode_AESCrypt:
 839     return inline_counterMode_AESCrypt_predicate();
 840   case vmIntrinsics::_digestBase_implCompressMB:
 841     return inline_digestBase_implCompressMB_predicate(predicate);
 842   case vmIntrinsics::_galoisCounterMode_AESCrypt:
 843     return inline_galoisCounterMode_AESCrypt_predicate();
 844 
 845   default:
 846     // If you get here, it may be that someone has added a new intrinsic
 847     // to the list in vmIntrinsics.hpp without implementing it here.
 848 #ifndef PRODUCT
 849     if ((PrintMiscellaneous && (Verbose || WizardMode)) || PrintOpto) {
 850       tty->print_cr("*** Warning: Unimplemented predicate for intrinsic %s(%d)",
 851                     vmIntrinsics::name_at(intrinsic_id()), vmIntrinsics::as_int(intrinsic_id()));
 852     }
 853 #endif
 854     Node* slow_ctl = control();
 855     set_control(top()); // No fast path intrinsic
 856     return slow_ctl;
 857   }
 858 }
 859 
 860 //------------------------------set_result-------------------------------
 861 // Helper function for finishing intrinsics.
 862 void LibraryCallKit::set_result(RegionNode* region, PhiNode* value) {
 863   record_for_igvn(region);
 864   set_control(_gvn.transform(region));
 865   set_result( _gvn.transform(value));
 866   assert(value->type()->basic_type() == result()->bottom_type()->basic_type(), "sanity");
 867 }
 868 
 869 //------------------------------generate_guard---------------------------
 870 // Helper function for generating guarded fast-slow graph structures.
 871 // The given 'test', if true, guards a slow path.  If the test fails
 872 // then a fast path can be taken.  (We generally hope it fails.)
 873 // In all cases, GraphKit::control() is updated to the fast path.
 874 // The returned value represents the control for the slow path.
 875 // The return value is never 'top'; it is either a valid control
 876 // or null if it is obvious that the slow path can never be taken.
 877 // Also, if region and the slow control are not null, the slow edge
 878 // is appended to the region.
 879 Node* LibraryCallKit::generate_guard(Node* test, RegionNode* region, float true_prob) {
 880   if (stopped()) {
 881     // Already short circuited.
 882     return nullptr;
 883   }
 884 
 885   // Build an if node and its projections.
 886   // If test is true we take the slow path, which we assume is uncommon.
 887   if (_gvn.type(test) == TypeInt::ZERO) {
 888     // The slow branch is never taken.  No need to build this guard.
 889     return nullptr;
 890   }
 891 
 892   IfNode* iff = create_and_map_if(control(), test, true_prob, COUNT_UNKNOWN);
 893 
 894   Node* if_slow = _gvn.transform(new IfTrueNode(iff));
 895   if (if_slow == top()) {
 896     // The slow branch is never taken.  No need to build this guard.
 897     return nullptr;
 898   }
 899 
 900   if (region != nullptr)
 901     region->add_req(if_slow);
 902 
 903   Node* if_fast = _gvn.transform(new IfFalseNode(iff));
 904   set_control(if_fast);
 905 
 906   return if_slow;
 907 }
 908 
 909 inline Node* LibraryCallKit::generate_slow_guard(Node* test, RegionNode* region) {
 910   return generate_guard(test, region, PROB_UNLIKELY_MAG(3));
 911 }
 912 inline Node* LibraryCallKit::generate_fair_guard(Node* test, RegionNode* region) {
 913   return generate_guard(test, region, PROB_FAIR);
 914 }
 915 
 916 inline Node* LibraryCallKit::generate_negative_guard(Node* index, RegionNode* region,
 917                                                      Node* *pos_index) {
 918   if (stopped())
 919     return nullptr;                // already stopped
 920   if (_gvn.type(index)->higher_equal(TypeInt::POS)) // [0,maxint]
 921     return nullptr;                // index is already adequately typed
 922   Node* cmp_lt = _gvn.transform(new CmpINode(index, intcon(0)));
 923   Node* bol_lt = _gvn.transform(new BoolNode(cmp_lt, BoolTest::lt));
 924   Node* is_neg = generate_guard(bol_lt, region, PROB_MIN);
 925   if (is_neg != nullptr && pos_index != nullptr) {
 926     // Emulate effect of Parse::adjust_map_after_if.
 927     Node* ccast = new CastIINode(control(), index, TypeInt::POS);
 928     (*pos_index) = _gvn.transform(ccast);
 929   }
 930   return is_neg;
 931 }
 932 
 933 // Make sure that 'position' is a valid limit index, in [0..length].
 934 // There are two equivalent plans for checking this:
 935 //   A. (offset + copyLength)  unsigned<=  arrayLength
 936 //   B. offset  <=  (arrayLength - copyLength)
 937 // We require that all of the values above, except for the sum and
 938 // difference, are already known to be non-negative.
 939 // Plan A is robust in the face of overflow, if offset and copyLength
 940 // are both hugely positive.
 941 //
 942 // Plan B is less direct and intuitive, but it does not overflow at
 943 // all, since the difference of two non-negatives is always
 944 // representable.  Whenever Java methods must perform the equivalent
 945 // check they generally use Plan B instead of Plan A.
 946 // For the moment we use Plan A.
 947 inline Node* LibraryCallKit::generate_limit_guard(Node* offset,
 948                                                   Node* subseq_length,
 949                                                   Node* array_length,
 950                                                   RegionNode* region) {
 951   if (stopped())
 952     return nullptr;                // already stopped
 953   bool zero_offset = _gvn.type(offset) == TypeInt::ZERO;
 954   if (zero_offset && subseq_length->eqv_uncast(array_length))
 955     return nullptr;                // common case of whole-array copy
 956   Node* last = subseq_length;
 957   if (!zero_offset)             // last += offset
 958     last = _gvn.transform(new AddINode(last, offset));
 959   Node* cmp_lt = _gvn.transform(new CmpUNode(array_length, last));
 960   Node* bol_lt = _gvn.transform(new BoolNode(cmp_lt, BoolTest::lt));
 961   Node* is_over = generate_guard(bol_lt, region, PROB_MIN);
 962   return is_over;
 963 }
 964 
 965 // Emit range checks for the given String.value byte array
 966 void LibraryCallKit::generate_string_range_check(Node* array,
 967                                                  Node* offset,
 968                                                  Node* count,
 969                                                  bool char_count,
 970                                                  bool halt_on_oob) {
 971   if (stopped()) {
 972     return; // already stopped
 973   }
 974   RegionNode* bailout = new RegionNode(1);
 975   record_for_igvn(bailout);
 976   if (char_count) {
 977     // Convert char count to byte count
 978     count = _gvn.transform(new LShiftINode(count, intcon(1)));
 979   }
 980 
 981   // Offset and count must not be negative
 982   generate_negative_guard(offset, bailout);
 983   generate_negative_guard(count, bailout);
 984   // Offset + count must not exceed length of array
 985   generate_limit_guard(offset, count, load_array_length(array), bailout);
 986 
 987   if (bailout->req() > 1) {
 988     if (halt_on_oob) {
 989       bailout = _gvn.transform(bailout)->as_Region();
 990       Node* frame = _gvn.transform(new ParmNode(C->start(), TypeFunc::FramePtr));
 991       Node* halt = _gvn.transform(new HaltNode(bailout, frame, "unexpected guard failure in intrinsic"));
 992       C->root()->add_req(halt);
 993     } else {
 994       PreserveJVMState pjvms(this);
 995       set_control(_gvn.transform(bailout));
 996       uncommon_trap(Deoptimization::Reason_intrinsic,
 997                     Deoptimization::Action_maybe_recompile);
 998     }
 999   }
1000 }
1001 
1002 Node* LibraryCallKit::current_thread_helper(Node*& tls_output, ByteSize handle_offset,
1003                                             bool is_immutable) {
1004   ciKlass* thread_klass = env()->Thread_klass();
1005   const Type* thread_type
1006     = TypeOopPtr::make_from_klass(thread_klass)->cast_to_ptr_type(TypePtr::NotNull);
1007 
1008   Node* thread = _gvn.transform(new ThreadLocalNode());
1009   Node* p = basic_plus_adr(top()/*!oop*/, thread, in_bytes(handle_offset));
1010   tls_output = thread;
1011 
1012   Node* thread_obj_handle
1013     = (is_immutable
1014       ? LoadNode::make(_gvn, nullptr, immutable_memory(), p, p->bottom_type()->is_ptr(),
1015         TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered)
1016       : make_load(nullptr, p, p->bottom_type()->is_ptr(), T_ADDRESS, MemNode::unordered));
1017   thread_obj_handle = _gvn.transform(thread_obj_handle);
1018 
1019   DecoratorSet decorators = IN_NATIVE;
1020   if (is_immutable) {
1021     decorators |= C2_IMMUTABLE_MEMORY;
1022   }
1023   return access_load(thread_obj_handle, thread_type, T_OBJECT, decorators);
1024 }
1025 
1026 //--------------------------generate_current_thread--------------------
1027 Node* LibraryCallKit::generate_current_thread(Node* &tls_output) {
1028   return current_thread_helper(tls_output, JavaThread::threadObj_offset(),
1029                                /*is_immutable*/false);
1030 }
1031 
1032 //--------------------------generate_virtual_thread--------------------
1033 Node* LibraryCallKit::generate_virtual_thread(Node* tls_output) {
1034   return current_thread_helper(tls_output, JavaThread::vthread_offset(),
1035                                !C->method()->changes_current_thread());
1036 }
1037 
1038 //------------------------------make_string_method_node------------------------
1039 // Helper method for String intrinsic functions. This version is called with
1040 // str1 and str2 pointing to byte[] nodes containing Latin1 or UTF16 encoded
1041 // characters (depending on 'is_byte'). cnt1 and cnt2 are pointing to Int nodes
1042 // containing the lengths of str1 and str2.
1043 Node* LibraryCallKit::make_string_method_node(int opcode, Node* str1_start, Node* cnt1, Node* str2_start, Node* cnt2, StrIntrinsicNode::ArgEnc ae) {
1044   Node* result = nullptr;
1045   switch (opcode) {
1046   case Op_StrIndexOf:
1047     result = new StrIndexOfNode(control(), memory(TypeAryPtr::BYTES),
1048                                 str1_start, cnt1, str2_start, cnt2, ae);
1049     break;
1050   case Op_StrComp:
1051     result = new StrCompNode(control(), memory(TypeAryPtr::BYTES),
1052                              str1_start, cnt1, str2_start, cnt2, ae);
1053     break;
1054   case Op_StrEquals:
1055     // We already know that cnt1 == cnt2 here (checked in 'inline_string_equals').
1056     // Use the constant length if there is one because optimized match rule may exist.
1057     result = new StrEqualsNode(control(), memory(TypeAryPtr::BYTES),
1058                                str1_start, str2_start, cnt2->is_Con() ? cnt2 : cnt1, ae);
1059     break;
1060   default:
1061     ShouldNotReachHere();
1062     return nullptr;
1063   }
1064 
1065   // All these intrinsics have checks.
1066   C->set_has_split_ifs(true); // Has chance for split-if optimization
1067   clear_upper_avx();
1068 
1069   return _gvn.transform(result);
1070 }
1071 
1072 //------------------------------inline_string_compareTo------------------------
1073 bool LibraryCallKit::inline_string_compareTo(StrIntrinsicNode::ArgEnc ae) {
1074   Node* arg1 = argument(0);
1075   Node* arg2 = argument(1);
1076 
1077   arg1 = must_be_not_null(arg1, true);
1078   arg2 = must_be_not_null(arg2, true);
1079 
1080   // Get start addr and length of first argument
1081   Node* arg1_start  = array_element_address(arg1, intcon(0), T_BYTE);
1082   Node* arg1_cnt    = load_array_length(arg1);
1083 
1084   // Get start addr and length of second argument
1085   Node* arg2_start  = array_element_address(arg2, intcon(0), T_BYTE);
1086   Node* arg2_cnt    = load_array_length(arg2);
1087 
1088   Node* result = make_string_method_node(Op_StrComp, arg1_start, arg1_cnt, arg2_start, arg2_cnt, ae);
1089   set_result(result);
1090   return true;
1091 }
1092 
1093 //------------------------------inline_string_equals------------------------
1094 bool LibraryCallKit::inline_string_equals(StrIntrinsicNode::ArgEnc ae) {
1095   Node* arg1 = argument(0);
1096   Node* arg2 = argument(1);
1097 
1098   // paths (plus control) merge
1099   RegionNode* region = new RegionNode(3);
1100   Node* phi = new PhiNode(region, TypeInt::BOOL);
1101 
1102   if (!stopped()) {
1103 
1104     arg1 = must_be_not_null(arg1, true);
1105     arg2 = must_be_not_null(arg2, true);
1106 
1107     // Get start addr and length of first argument
1108     Node* arg1_start  = array_element_address(arg1, intcon(0), T_BYTE);
1109     Node* arg1_cnt    = load_array_length(arg1);
1110 
1111     // Get start addr and length of second argument
1112     Node* arg2_start  = array_element_address(arg2, intcon(0), T_BYTE);
1113     Node* arg2_cnt    = load_array_length(arg2);
1114 
1115     // Check for arg1_cnt != arg2_cnt
1116     Node* cmp = _gvn.transform(new CmpINode(arg1_cnt, arg2_cnt));
1117     Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::ne));
1118     Node* if_ne = generate_slow_guard(bol, nullptr);
1119     if (if_ne != nullptr) {
1120       phi->init_req(2, intcon(0));
1121       region->init_req(2, if_ne);
1122     }
1123 
1124     // Check for count == 0 is done by assembler code for StrEquals.
1125 
1126     if (!stopped()) {
1127       Node* equals = make_string_method_node(Op_StrEquals, arg1_start, arg1_cnt, arg2_start, arg2_cnt, ae);
1128       phi->init_req(1, equals);
1129       region->init_req(1, control());
1130     }
1131   }
1132 
1133   // post merge
1134   set_control(_gvn.transform(region));
1135   record_for_igvn(region);
1136 
1137   set_result(_gvn.transform(phi));
1138   return true;
1139 }
1140 
1141 //------------------------------inline_array_equals----------------------------
1142 bool LibraryCallKit::inline_array_equals(StrIntrinsicNode::ArgEnc ae) {
1143   assert(ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::LL, "unsupported array types");
1144   Node* arg1 = argument(0);
1145   Node* arg2 = argument(1);
1146 
1147   const TypeAryPtr* mtype = (ae == StrIntrinsicNode::UU) ? TypeAryPtr::CHARS : TypeAryPtr::BYTES;
1148   set_result(_gvn.transform(new AryEqNode(control(), memory(mtype), arg1, arg2, ae)));
1149   clear_upper_avx();
1150 
1151   return true;
1152 }
1153 
1154 
1155 //------------------------------inline_countPositives------------------------------
1156 // int java.lang.StringCoding#countPositives0(byte[] ba, int off, int len)
1157 bool LibraryCallKit::inline_countPositives() {
1158   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1159     return false;
1160   }
1161 
1162   assert(callee()->signature()->size() == 3, "countPositives has 3 parameters");
1163   // no receiver since it is static method
1164   Node* ba         = argument(0);
1165   Node* offset     = argument(1);
1166   Node* len        = argument(2);
1167 
1168   if (VerifyIntrinsicChecks) {
1169     ba = must_be_not_null(ba, true);
1170     generate_string_range_check(ba, offset, len, false, true);
1171     if (stopped()) {
1172       return true;
1173     }
1174   }
1175 
1176   Node* ba_start = array_element_address(ba, offset, T_BYTE);
1177   Node* result = new CountPositivesNode(control(), memory(TypeAryPtr::BYTES), ba_start, len);
1178   set_result(_gvn.transform(result));
1179   clear_upper_avx();
1180   return true;
1181 }
1182 
1183 bool LibraryCallKit::inline_preconditions_checkIndex(BasicType bt) {
1184   Node* index = argument(0);
1185   Node* length = bt == T_INT ? argument(1) : argument(2);
1186   if (too_many_traps(Deoptimization::Reason_intrinsic) || too_many_traps(Deoptimization::Reason_range_check)) {
1187     return false;
1188   }
1189 
1190   // check that length is positive
1191   Node* len_pos_cmp = _gvn.transform(CmpNode::make(length, integercon(0, bt), bt));
1192   Node* len_pos_bol = _gvn.transform(new BoolNode(len_pos_cmp, BoolTest::ge));
1193 
1194   {
1195     BuildCutout unless(this, len_pos_bol, PROB_MAX);
1196     uncommon_trap(Deoptimization::Reason_intrinsic,
1197                   Deoptimization::Action_make_not_entrant);
1198   }
1199 
1200   if (stopped()) {
1201     // Length is known to be always negative during compilation and the IR graph so far constructed is good so return success
1202     return true;
1203   }
1204 
1205   // length is now known positive, add a cast node to make this explicit
1206   jlong upper_bound = _gvn.type(length)->is_integer(bt)->hi_as_long();
1207   Node* casted_length = ConstraintCastNode::make_cast_for_basic_type(
1208       control(), length, TypeInteger::make(0, upper_bound, Type::WidenMax, bt),
1209       ConstraintCastNode::RegularDependency, bt);
1210   casted_length = _gvn.transform(casted_length);
1211   replace_in_map(length, casted_length);
1212   length = casted_length;
1213 
1214   // Use an unsigned comparison for the range check itself
1215   Node* rc_cmp = _gvn.transform(CmpNode::make(index, length, bt, true));
1216   BoolTest::mask btest = BoolTest::lt;
1217   Node* rc_bool = _gvn.transform(new BoolNode(rc_cmp, btest));
1218   RangeCheckNode* rc = new RangeCheckNode(control(), rc_bool, PROB_MAX, COUNT_UNKNOWN);
1219   _gvn.set_type(rc, rc->Value(&_gvn));
1220   if (!rc_bool->is_Con()) {
1221     record_for_igvn(rc);
1222   }
1223   set_control(_gvn.transform(new IfTrueNode(rc)));
1224   {
1225     PreserveJVMState pjvms(this);
1226     set_control(_gvn.transform(new IfFalseNode(rc)));
1227     uncommon_trap(Deoptimization::Reason_range_check,
1228                   Deoptimization::Action_make_not_entrant);
1229   }
1230 
1231   if (stopped()) {
1232     // Range check is known to always fail during compilation and the IR graph so far constructed is good so return success
1233     return true;
1234   }
1235 
1236   // index is now known to be >= 0 and < length, cast it
1237   Node* result = ConstraintCastNode::make_cast_for_basic_type(
1238       control(), index, TypeInteger::make(0, upper_bound, Type::WidenMax, bt),
1239       ConstraintCastNode::RegularDependency, bt);
1240   result = _gvn.transform(result);
1241   set_result(result);
1242   replace_in_map(index, result);
1243   return true;
1244 }
1245 
1246 //------------------------------inline_string_indexOf------------------------
1247 bool LibraryCallKit::inline_string_indexOf(StrIntrinsicNode::ArgEnc ae) {
1248   if (!Matcher::match_rule_supported(Op_StrIndexOf)) {
1249     return false;
1250   }
1251   Node* src = argument(0);
1252   Node* tgt = argument(1);
1253 
1254   // Make the merge point
1255   RegionNode* result_rgn = new RegionNode(4);
1256   Node*       result_phi = new PhiNode(result_rgn, TypeInt::INT);
1257 
1258   src = must_be_not_null(src, true);
1259   tgt = must_be_not_null(tgt, true);
1260 
1261   // Get start addr and length of source string
1262   Node* src_start = array_element_address(src, intcon(0), T_BYTE);
1263   Node* src_count = load_array_length(src);
1264 
1265   // Get start addr and length of substring
1266   Node* tgt_start = array_element_address(tgt, intcon(0), T_BYTE);
1267   Node* tgt_count = load_array_length(tgt);
1268 
1269   Node* result = nullptr;
1270   bool call_opt_stub = (StubRoutines::_string_indexof_array[ae] != nullptr);
1271 
1272   if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
1273     // Divide src size by 2 if String is UTF16 encoded
1274     src_count = _gvn.transform(new RShiftINode(src_count, intcon(1)));
1275   }
1276   if (ae == StrIntrinsicNode::UU) {
1277     // Divide substring size by 2 if String is UTF16 encoded
1278     tgt_count = _gvn.transform(new RShiftINode(tgt_count, intcon(1)));
1279   }
1280 
1281   if (call_opt_stub) {
1282     Node* call = make_runtime_call(RC_LEAF, OptoRuntime::string_IndexOf_Type(),
1283                                    StubRoutines::_string_indexof_array[ae],
1284                                    "stringIndexOf", TypePtr::BOTTOM, src_start,
1285                                    src_count, tgt_start, tgt_count);
1286     result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
1287   } else {
1288     result = make_indexOf_node(src_start, src_count, tgt_start, tgt_count,
1289                                result_rgn, result_phi, ae);
1290   }
1291   if (result != nullptr) {
1292     result_phi->init_req(3, result);
1293     result_rgn->init_req(3, control());
1294   }
1295   set_control(_gvn.transform(result_rgn));
1296   record_for_igvn(result_rgn);
1297   set_result(_gvn.transform(result_phi));
1298 
1299   return true;
1300 }
1301 
1302 //-----------------------------inline_string_indexOfI-----------------------
1303 bool LibraryCallKit::inline_string_indexOfI(StrIntrinsicNode::ArgEnc ae) {
1304   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1305     return false;
1306   }
1307   if (!Matcher::match_rule_supported(Op_StrIndexOf)) {
1308     return false;
1309   }
1310 
1311   assert(callee()->signature()->size() == 5, "String.indexOf() has 5 arguments");
1312   Node* src         = argument(0); // byte[]
1313   Node* src_count   = argument(1); // char count
1314   Node* tgt         = argument(2); // byte[]
1315   Node* tgt_count   = argument(3); // char count
1316   Node* from_index  = argument(4); // char index
1317 
1318   src = must_be_not_null(src, true);
1319   tgt = must_be_not_null(tgt, true);
1320 
1321   // Multiply byte array index by 2 if String is UTF16 encoded
1322   Node* src_offset = (ae == StrIntrinsicNode::LL) ? from_index : _gvn.transform(new LShiftINode(from_index, intcon(1)));
1323   src_count = _gvn.transform(new SubINode(src_count, from_index));
1324   Node* src_start = array_element_address(src, src_offset, T_BYTE);
1325   Node* tgt_start = array_element_address(tgt, intcon(0), T_BYTE);
1326 
1327   // Range checks
1328   generate_string_range_check(src, src_offset, src_count, ae != StrIntrinsicNode::LL);
1329   generate_string_range_check(tgt, intcon(0), tgt_count, ae == StrIntrinsicNode::UU);
1330   if (stopped()) {
1331     return true;
1332   }
1333 
1334   RegionNode* region = new RegionNode(5);
1335   Node* phi = new PhiNode(region, TypeInt::INT);
1336   Node* result = nullptr;
1337 
1338   bool call_opt_stub = (StubRoutines::_string_indexof_array[ae] != nullptr);
1339 
1340   if (call_opt_stub) {
1341     Node* call = make_runtime_call(RC_LEAF, OptoRuntime::string_IndexOf_Type(),
1342                                    StubRoutines::_string_indexof_array[ae],
1343                                    "stringIndexOf", TypePtr::BOTTOM, src_start,
1344                                    src_count, tgt_start, tgt_count);
1345     result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
1346   } else {
1347     result = make_indexOf_node(src_start, src_count, tgt_start, tgt_count,
1348                                region, phi, ae);
1349   }
1350   if (result != nullptr) {
1351     // The result is index relative to from_index if substring was found, -1 otherwise.
1352     // Generate code which will fold into cmove.
1353     Node* cmp = _gvn.transform(new CmpINode(result, intcon(0)));
1354     Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::lt));
1355 
1356     Node* if_lt = generate_slow_guard(bol, nullptr);
1357     if (if_lt != nullptr) {
1358       // result == -1
1359       phi->init_req(3, result);
1360       region->init_req(3, if_lt);
1361     }
1362     if (!stopped()) {
1363       result = _gvn.transform(new AddINode(result, from_index));
1364       phi->init_req(4, result);
1365       region->init_req(4, control());
1366     }
1367   }
1368 
1369   set_control(_gvn.transform(region));
1370   record_for_igvn(region);
1371   set_result(_gvn.transform(phi));
1372   clear_upper_avx();
1373 
1374   return true;
1375 }
1376 
1377 // Create StrIndexOfNode with fast path checks
1378 Node* LibraryCallKit::make_indexOf_node(Node* src_start, Node* src_count, Node* tgt_start, Node* tgt_count,
1379                                         RegionNode* region, Node* phi, StrIntrinsicNode::ArgEnc ae) {
1380   // Check for substr count > string count
1381   Node* cmp = _gvn.transform(new CmpINode(tgt_count, src_count));
1382   Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::gt));
1383   Node* if_gt = generate_slow_guard(bol, nullptr);
1384   if (if_gt != nullptr) {
1385     phi->init_req(1, intcon(-1));
1386     region->init_req(1, if_gt);
1387   }
1388   if (!stopped()) {
1389     // Check for substr count == 0
1390     cmp = _gvn.transform(new CmpINode(tgt_count, intcon(0)));
1391     bol = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
1392     Node* if_zero = generate_slow_guard(bol, nullptr);
1393     if (if_zero != nullptr) {
1394       phi->init_req(2, intcon(0));
1395       region->init_req(2, if_zero);
1396     }
1397   }
1398   if (!stopped()) {
1399     return make_string_method_node(Op_StrIndexOf, src_start, src_count, tgt_start, tgt_count, ae);
1400   }
1401   return nullptr;
1402 }
1403 
1404 //-----------------------------inline_string_indexOfChar-----------------------
1405 bool LibraryCallKit::inline_string_indexOfChar(StrIntrinsicNode::ArgEnc ae) {
1406   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1407     return false;
1408   }
1409   if (!Matcher::match_rule_supported(Op_StrIndexOfChar)) {
1410     return false;
1411   }
1412   assert(callee()->signature()->size() == 4, "String.indexOfChar() has 4 arguments");
1413   Node* src         = argument(0); // byte[]
1414   Node* int_ch      = argument(1);
1415   Node* from_index  = argument(2);
1416   Node* max         = argument(3);
1417 
1418   src = must_be_not_null(src, true);
1419 
1420   Node* src_offset = ae == StrIntrinsicNode::L ? from_index : _gvn.transform(new LShiftINode(from_index, intcon(1)));
1421   Node* src_start = array_element_address(src, src_offset, T_BYTE);
1422   Node* src_count = _gvn.transform(new SubINode(max, from_index));
1423 
1424   // Range checks
1425   generate_string_range_check(src, src_offset, src_count, ae == StrIntrinsicNode::U);
1426 
1427   // Check for int_ch >= 0
1428   Node* int_ch_cmp = _gvn.transform(new CmpINode(int_ch, intcon(0)));
1429   Node* int_ch_bol = _gvn.transform(new BoolNode(int_ch_cmp, BoolTest::ge));
1430   {
1431     BuildCutout unless(this, int_ch_bol, PROB_MAX);
1432     uncommon_trap(Deoptimization::Reason_intrinsic,
1433                   Deoptimization::Action_maybe_recompile);
1434   }
1435   if (stopped()) {
1436     return true;
1437   }
1438 
1439   RegionNode* region = new RegionNode(3);
1440   Node* phi = new PhiNode(region, TypeInt::INT);
1441 
1442   Node* result = new StrIndexOfCharNode(control(), memory(TypeAryPtr::BYTES), src_start, src_count, int_ch, ae);
1443   C->set_has_split_ifs(true); // Has chance for split-if optimization
1444   _gvn.transform(result);
1445 
1446   Node* cmp = _gvn.transform(new CmpINode(result, intcon(0)));
1447   Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::lt));
1448 
1449   Node* if_lt = generate_slow_guard(bol, nullptr);
1450   if (if_lt != nullptr) {
1451     // result == -1
1452     phi->init_req(2, result);
1453     region->init_req(2, if_lt);
1454   }
1455   if (!stopped()) {
1456     result = _gvn.transform(new AddINode(result, from_index));
1457     phi->init_req(1, result);
1458     region->init_req(1, control());
1459   }
1460   set_control(_gvn.transform(region));
1461   record_for_igvn(region);
1462   set_result(_gvn.transform(phi));
1463   clear_upper_avx();
1464 
1465   return true;
1466 }
1467 //---------------------------inline_string_copy---------------------
1468 // compressIt == true --> generate a compressed copy operation (compress char[]/byte[] to byte[])
1469 //   int StringUTF16.compress(char[] src, int srcOff, byte[] dst, int dstOff, int len)
1470 //   int StringUTF16.compress(byte[] src, int srcOff, byte[] dst, int dstOff, int len)
1471 // compressIt == false --> generate an inflated copy operation (inflate byte[] to char[]/byte[])
1472 //   void StringLatin1.inflate(byte[] src, int srcOff, char[] dst, int dstOff, int len)
1473 //   void StringLatin1.inflate(byte[] src, int srcOff, byte[] dst, int dstOff, int len)
1474 bool LibraryCallKit::inline_string_copy(bool compress) {
1475   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1476     return false;
1477   }
1478   int nargs = 5;  // 2 oops, 3 ints
1479   assert(callee()->signature()->size() == nargs, "string copy has 5 arguments");
1480 
1481   Node* src         = argument(0);
1482   Node* src_offset  = argument(1);
1483   Node* dst         = argument(2);
1484   Node* dst_offset  = argument(3);
1485   Node* length      = argument(4);
1486 
1487   // Check for allocation before we add nodes that would confuse
1488   // tightly_coupled_allocation()
1489   AllocateArrayNode* alloc = tightly_coupled_allocation(dst);
1490 
1491   // Figure out the size and type of the elements we will be copying.
1492   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
1493   const TypeAryPtr* dst_type = dst->Value(&_gvn)->isa_aryptr();
1494   if (src_type == nullptr || dst_type == nullptr) {
1495     return false;
1496   }
1497   BasicType src_elem = src_type->elem()->array_element_basic_type();
1498   BasicType dst_elem = dst_type->elem()->array_element_basic_type();
1499   assert((compress && dst_elem == T_BYTE && (src_elem == T_BYTE || src_elem == T_CHAR)) ||
1500          (!compress && src_elem == T_BYTE && (dst_elem == T_BYTE || dst_elem == T_CHAR)),
1501          "Unsupported array types for inline_string_copy");
1502 
1503   src = must_be_not_null(src, true);
1504   dst = must_be_not_null(dst, true);
1505 
1506   // Convert char[] offsets to byte[] offsets
1507   bool convert_src = (compress && src_elem == T_BYTE);
1508   bool convert_dst = (!compress && dst_elem == T_BYTE);
1509   if (convert_src) {
1510     src_offset = _gvn.transform(new LShiftINode(src_offset, intcon(1)));
1511   } else if (convert_dst) {
1512     dst_offset = _gvn.transform(new LShiftINode(dst_offset, intcon(1)));
1513   }
1514 
1515   // Range checks
1516   generate_string_range_check(src, src_offset, length, convert_src);
1517   generate_string_range_check(dst, dst_offset, length, convert_dst);
1518   if (stopped()) {
1519     return true;
1520   }
1521 
1522   Node* src_start = array_element_address(src, src_offset, src_elem);
1523   Node* dst_start = array_element_address(dst, dst_offset, dst_elem);
1524   // 'src_start' points to src array + scaled offset
1525   // 'dst_start' points to dst array + scaled offset
1526   Node* count = nullptr;
1527   if (compress) {
1528     count = compress_string(src_start, TypeAryPtr::get_array_body_type(src_elem), dst_start, length);
1529   } else {
1530     inflate_string(src_start, dst_start, TypeAryPtr::get_array_body_type(dst_elem), length);
1531   }
1532 
1533   if (alloc != nullptr) {
1534     if (alloc->maybe_set_complete(&_gvn)) {
1535       // "You break it, you buy it."
1536       InitializeNode* init = alloc->initialization();
1537       assert(init->is_complete(), "we just did this");
1538       init->set_complete_with_arraycopy();
1539       assert(dst->is_CheckCastPP(), "sanity");
1540       assert(dst->in(0)->in(0) == init, "dest pinned");
1541     }
1542     // Do not let stores that initialize this object be reordered with
1543     // a subsequent store that would make this object accessible by
1544     // other threads.
1545     // Record what AllocateNode this StoreStore protects so that
1546     // escape analysis can go from the MemBarStoreStoreNode to the
1547     // AllocateNode and eliminate the MemBarStoreStoreNode if possible
1548     // based on the escape status of the AllocateNode.
1549     insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
1550   }
1551   if (compress) {
1552     set_result(_gvn.transform(count));
1553   }
1554   clear_upper_avx();
1555 
1556   return true;
1557 }
1558 
1559 #ifdef _LP64
1560 #define XTOP ,top() /*additional argument*/
1561 #else  //_LP64
1562 #define XTOP        /*no additional argument*/
1563 #endif //_LP64
1564 
1565 //------------------------inline_string_toBytesU--------------------------
1566 // public static byte[] StringUTF16.toBytes(char[] value, int off, int len)
1567 bool LibraryCallKit::inline_string_toBytesU() {
1568   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1569     return false;
1570   }
1571   // Get the arguments.
1572   Node* value     = argument(0);
1573   Node* offset    = argument(1);
1574   Node* length    = argument(2);
1575 
1576   Node* newcopy = nullptr;
1577 
1578   // Set the original stack and the reexecute bit for the interpreter to reexecute
1579   // the bytecode that invokes StringUTF16.toBytes() if deoptimization happens.
1580   { PreserveReexecuteState preexecs(this);
1581     jvms()->set_should_reexecute(true);
1582 
1583     // Check if a null path was taken unconditionally.
1584     value = null_check(value);
1585 
1586     RegionNode* bailout = new RegionNode(1);
1587     record_for_igvn(bailout);
1588 
1589     // Range checks
1590     generate_negative_guard(offset, bailout);
1591     generate_negative_guard(length, bailout);
1592     generate_limit_guard(offset, length, load_array_length(value), bailout);
1593     // Make sure that resulting byte[] length does not overflow Integer.MAX_VALUE
1594     generate_limit_guard(length, intcon(0), intcon(max_jint/2), bailout);
1595 
1596     if (bailout->req() > 1) {
1597       PreserveJVMState pjvms(this);
1598       set_control(_gvn.transform(bailout));
1599       uncommon_trap(Deoptimization::Reason_intrinsic,
1600                     Deoptimization::Action_maybe_recompile);
1601     }
1602     if (stopped()) {
1603       return true;
1604     }
1605 
1606     Node* size = _gvn.transform(new LShiftINode(length, intcon(1)));
1607     Node* klass_node = makecon(TypeKlassPtr::make(ciTypeArrayKlass::make(T_BYTE)));
1608     newcopy = new_array(klass_node, size, 0);  // no arguments to push
1609     AllocateArrayNode* alloc = tightly_coupled_allocation(newcopy);
1610     guarantee(alloc != nullptr, "created above");
1611 
1612     // Calculate starting addresses.
1613     Node* src_start = array_element_address(value, offset, T_CHAR);
1614     Node* dst_start = basic_plus_adr(newcopy, arrayOopDesc::base_offset_in_bytes(T_BYTE));
1615 
1616     // Check if dst array address is aligned to HeapWordSize
1617     bool aligned = (arrayOopDesc::base_offset_in_bytes(T_BYTE) % HeapWordSize == 0);
1618     // If true, then check if src array address is aligned to HeapWordSize
1619     if (aligned) {
1620       const TypeInt* toffset = gvn().type(offset)->is_int();
1621       aligned = toffset->is_con() && ((arrayOopDesc::base_offset_in_bytes(T_CHAR) +
1622                                        toffset->get_con() * type2aelembytes(T_CHAR)) % HeapWordSize == 0);
1623     }
1624 
1625     // Figure out which arraycopy runtime method to call (disjoint, uninitialized).
1626     const char* copyfunc_name = "arraycopy";
1627     address     copyfunc_addr = StubRoutines::select_arraycopy_function(T_CHAR, aligned, true, copyfunc_name, true);
1628     Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
1629                       OptoRuntime::fast_arraycopy_Type(),
1630                       copyfunc_addr, copyfunc_name, TypeRawPtr::BOTTOM,
1631                       src_start, dst_start, ConvI2X(length) XTOP);
1632     // Do not let reads from the cloned object float above the arraycopy.
1633     if (alloc->maybe_set_complete(&_gvn)) {
1634       // "You break it, you buy it."
1635       InitializeNode* init = alloc->initialization();
1636       assert(init->is_complete(), "we just did this");
1637       init->set_complete_with_arraycopy();
1638       assert(newcopy->is_CheckCastPP(), "sanity");
1639       assert(newcopy->in(0)->in(0) == init, "dest pinned");
1640     }
1641     // Do not let stores that initialize this object be reordered with
1642     // a subsequent store that would make this object accessible by
1643     // other threads.
1644     // Record what AllocateNode this StoreStore protects so that
1645     // escape analysis can go from the MemBarStoreStoreNode to the
1646     // AllocateNode and eliminate the MemBarStoreStoreNode if possible
1647     // based on the escape status of the AllocateNode.
1648     insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
1649   } // original reexecute is set back here
1650 
1651   C->set_has_split_ifs(true); // Has chance for split-if optimization
1652   if (!stopped()) {
1653     set_result(newcopy);
1654   }
1655   clear_upper_avx();
1656 
1657   return true;
1658 }
1659 
1660 //------------------------inline_string_getCharsU--------------------------
1661 // public void StringUTF16.getChars(byte[] src, int srcBegin, int srcEnd, char dst[], int dstBegin)
1662 bool LibraryCallKit::inline_string_getCharsU() {
1663   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1664     return false;
1665   }
1666 
1667   // Get the arguments.
1668   Node* src       = argument(0);
1669   Node* src_begin = argument(1);
1670   Node* src_end   = argument(2); // exclusive offset (i < src_end)
1671   Node* dst       = argument(3);
1672   Node* dst_begin = argument(4);
1673 
1674   // Check for allocation before we add nodes that would confuse
1675   // tightly_coupled_allocation()
1676   AllocateArrayNode* alloc = tightly_coupled_allocation(dst);
1677 
1678   // Check if a null path was taken unconditionally.
1679   src = null_check(src);
1680   dst = null_check(dst);
1681   if (stopped()) {
1682     return true;
1683   }
1684 
1685   // Get length and convert char[] offset to byte[] offset
1686   Node* length = _gvn.transform(new SubINode(src_end, src_begin));
1687   src_begin = _gvn.transform(new LShiftINode(src_begin, intcon(1)));
1688 
1689   // Range checks
1690   generate_string_range_check(src, src_begin, length, true);
1691   generate_string_range_check(dst, dst_begin, length, false);
1692   if (stopped()) {
1693     return true;
1694   }
1695 
1696   if (!stopped()) {
1697     // Calculate starting addresses.
1698     Node* src_start = array_element_address(src, src_begin, T_BYTE);
1699     Node* dst_start = array_element_address(dst, dst_begin, T_CHAR);
1700 
1701     // Check if array addresses are aligned to HeapWordSize
1702     const TypeInt* tsrc = gvn().type(src_begin)->is_int();
1703     const TypeInt* tdst = gvn().type(dst_begin)->is_int();
1704     bool aligned = tsrc->is_con() && ((arrayOopDesc::base_offset_in_bytes(T_BYTE) + tsrc->get_con() * type2aelembytes(T_BYTE)) % HeapWordSize == 0) &&
1705                    tdst->is_con() && ((arrayOopDesc::base_offset_in_bytes(T_CHAR) + tdst->get_con() * type2aelembytes(T_CHAR)) % HeapWordSize == 0);
1706 
1707     // Figure out which arraycopy runtime method to call (disjoint, uninitialized).
1708     const char* copyfunc_name = "arraycopy";
1709     address     copyfunc_addr = StubRoutines::select_arraycopy_function(T_CHAR, aligned, true, copyfunc_name, true);
1710     Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
1711                       OptoRuntime::fast_arraycopy_Type(),
1712                       copyfunc_addr, copyfunc_name, TypeRawPtr::BOTTOM,
1713                       src_start, dst_start, ConvI2X(length) XTOP);
1714     // Do not let reads from the cloned object float above the arraycopy.
1715     if (alloc != nullptr) {
1716       if (alloc->maybe_set_complete(&_gvn)) {
1717         // "You break it, you buy it."
1718         InitializeNode* init = alloc->initialization();
1719         assert(init->is_complete(), "we just did this");
1720         init->set_complete_with_arraycopy();
1721         assert(dst->is_CheckCastPP(), "sanity");
1722         assert(dst->in(0)->in(0) == init, "dest pinned");
1723       }
1724       // Do not let stores that initialize this object be reordered with
1725       // a subsequent store that would make this object accessible by
1726       // other threads.
1727       // Record what AllocateNode this StoreStore protects so that
1728       // escape analysis can go from the MemBarStoreStoreNode to the
1729       // AllocateNode and eliminate the MemBarStoreStoreNode if possible
1730       // based on the escape status of the AllocateNode.
1731       insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
1732     } else {
1733       insert_mem_bar(Op_MemBarCPUOrder);
1734     }
1735   }
1736 
1737   C->set_has_split_ifs(true); // Has chance for split-if optimization
1738   return true;
1739 }
1740 
1741 //----------------------inline_string_char_access----------------------------
1742 // Store/Load char to/from byte[] array.
1743 // static void StringUTF16.putChar(byte[] val, int index, int c)
1744 // static char StringUTF16.getChar(byte[] val, int index)
1745 bool LibraryCallKit::inline_string_char_access(bool is_store) {
1746   Node* value  = argument(0);
1747   Node* index  = argument(1);
1748   Node* ch = is_store ? argument(2) : nullptr;
1749 
1750   // This intrinsic accesses byte[] array as char[] array. Computing the offsets
1751   // correctly requires matched array shapes.
1752   assert (arrayOopDesc::base_offset_in_bytes(T_CHAR) == arrayOopDesc::base_offset_in_bytes(T_BYTE),
1753           "sanity: byte[] and char[] bases agree");
1754   assert (type2aelembytes(T_CHAR) == type2aelembytes(T_BYTE)*2,
1755           "sanity: byte[] and char[] scales agree");
1756 
1757   // Bail when getChar over constants is requested: constant folding would
1758   // reject folding mismatched char access over byte[]. A normal inlining for getChar
1759   // Java method would constant fold nicely instead.
1760   if (!is_store && value->is_Con() && index->is_Con()) {
1761     return false;
1762   }
1763 
1764   // Save state and restore on bailout
1765   SavedState old_state(this);
1766 
1767   value = must_be_not_null(value, true);
1768 
1769   Node* adr = array_element_address(value, index, T_CHAR);
1770   if (adr->is_top()) {
1771     return false;
1772   }
1773   old_state.discard();
1774   if (is_store) {
1775     access_store_at(value, adr, TypeAryPtr::BYTES, ch, TypeInt::CHAR, T_CHAR, IN_HEAP | MO_UNORDERED | C2_MISMATCHED);
1776   } else {
1777     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);
1778     set_result(ch);
1779   }
1780   return true;
1781 }
1782 
1783 
1784 //------------------------------inline_math-----------------------------------
1785 // public static double Math.abs(double)
1786 // public static double Math.sqrt(double)
1787 // public static double Math.log(double)
1788 // public static double Math.log10(double)
1789 // public static double Math.round(double)
1790 bool LibraryCallKit::inline_double_math(vmIntrinsics::ID id) {
1791   Node* arg = argument(0);
1792   Node* n = nullptr;
1793   switch (id) {
1794   case vmIntrinsics::_dabs:   n = new AbsDNode(                arg);  break;
1795   case vmIntrinsics::_dsqrt:
1796   case vmIntrinsics::_dsqrt_strict:
1797                               n = new SqrtDNode(C, control(),  arg);  break;
1798   case vmIntrinsics::_ceil:   n = RoundDoubleModeNode::make(_gvn, arg, RoundDoubleModeNode::rmode_ceil); break;
1799   case vmIntrinsics::_floor:  n = RoundDoubleModeNode::make(_gvn, arg, RoundDoubleModeNode::rmode_floor); break;
1800   case vmIntrinsics::_rint:   n = RoundDoubleModeNode::make(_gvn, arg, RoundDoubleModeNode::rmode_rint); break;
1801   case vmIntrinsics::_roundD: n = new RoundDNode(arg); break;
1802   case vmIntrinsics::_dcopySign: n = CopySignDNode::make(_gvn, arg, argument(2)); break;
1803   case vmIntrinsics::_dsignum: n = SignumDNode::make(_gvn, arg); break;
1804   default:  fatal_unexpected_iid(id);  break;
1805   }
1806   set_result(_gvn.transform(n));
1807   return true;
1808 }
1809 
1810 //------------------------------inline_math-----------------------------------
1811 // public static float Math.abs(float)
1812 // public static int Math.abs(int)
1813 // public static long Math.abs(long)
1814 bool LibraryCallKit::inline_math(vmIntrinsics::ID id) {
1815   Node* arg = argument(0);
1816   Node* n = nullptr;
1817   switch (id) {
1818   case vmIntrinsics::_fabs:   n = new AbsFNode(                arg);  break;
1819   case vmIntrinsics::_iabs:   n = new AbsINode(                arg);  break;
1820   case vmIntrinsics::_labs:   n = new AbsLNode(                arg);  break;
1821   case vmIntrinsics::_fcopySign: n = new CopySignFNode(arg, argument(1)); break;
1822   case vmIntrinsics::_fsignum: n = SignumFNode::make(_gvn, arg); break;
1823   case vmIntrinsics::_roundF: n = new RoundFNode(arg); break;
1824   default:  fatal_unexpected_iid(id);  break;
1825   }
1826   set_result(_gvn.transform(n));
1827   return true;
1828 }
1829 
1830 //------------------------------runtime_math-----------------------------
1831 bool LibraryCallKit::runtime_math(const TypeFunc* call_type, address funcAddr, const char* funcName) {
1832   assert(call_type == OptoRuntime::Math_DD_D_Type() || call_type == OptoRuntime::Math_D_D_Type(),
1833          "must be (DD)D or (D)D type");
1834 
1835   // Inputs
1836   Node* a = argument(0);
1837   Node* b = (call_type == OptoRuntime::Math_DD_D_Type()) ? argument(2) : nullptr;
1838 
1839   const TypePtr* no_memory_effects = nullptr;
1840   Node* trig = make_runtime_call(RC_LEAF | RC_PURE, call_type, funcAddr, funcName,
1841                                  no_memory_effects,
1842                                  a, top(), b, b ? top() : nullptr);
1843   Node* value = _gvn.transform(new ProjNode(trig, TypeFunc::Parms+0));
1844 #ifdef ASSERT
1845   Node* value_top = _gvn.transform(new ProjNode(trig, TypeFunc::Parms+1));
1846   assert(value_top == top(), "second value must be top");
1847 #endif
1848 
1849   set_result(value);
1850   return true;
1851 }
1852 
1853 //------------------------------inline_math_pow-----------------------------
1854 bool LibraryCallKit::inline_math_pow() {
1855   Node* exp = argument(2);
1856   const TypeD* d = _gvn.type(exp)->isa_double_constant();
1857   if (d != nullptr) {
1858     if (d->getd() == 2.0) {
1859       // Special case: pow(x, 2.0) => x * x
1860       Node* base = argument(0);
1861       set_result(_gvn.transform(new MulDNode(base, base)));
1862       return true;
1863     } else if (d->getd() == 0.5 && Matcher::match_rule_supported(Op_SqrtD)) {
1864       // Special case: pow(x, 0.5) => sqrt(x)
1865       Node* base = argument(0);
1866       Node* zero = _gvn.zerocon(T_DOUBLE);
1867 
1868       RegionNode* region = new RegionNode(3);
1869       Node* phi = new PhiNode(region, Type::DOUBLE);
1870 
1871       Node* cmp  = _gvn.transform(new CmpDNode(base, zero));
1872       // According to the API specs, pow(-0.0, 0.5) = 0.0 and sqrt(-0.0) = -0.0.
1873       // So pow(-0.0, 0.5) shouldn't be replaced with sqrt(-0.0).
1874       // -0.0/+0.0 are both excluded since floating-point comparison doesn't distinguish -0.0 from +0.0.
1875       Node* test = _gvn.transform(new BoolNode(cmp, BoolTest::le));
1876 
1877       Node* if_pow = generate_slow_guard(test, nullptr);
1878       Node* value_sqrt = _gvn.transform(new SqrtDNode(C, control(), base));
1879       phi->init_req(1, value_sqrt);
1880       region->init_req(1, control());
1881 
1882       if (if_pow != nullptr) {
1883         set_control(if_pow);
1884         address target = StubRoutines::dpow() != nullptr ? StubRoutines::dpow() :
1885                                                         CAST_FROM_FN_PTR(address, SharedRuntime::dpow);
1886         const TypePtr* no_memory_effects = nullptr;
1887         Node* trig = make_runtime_call(RC_LEAF, OptoRuntime::Math_DD_D_Type(), target, "POW",
1888                                        no_memory_effects, base, top(), exp, top());
1889         Node* value_pow = _gvn.transform(new ProjNode(trig, TypeFunc::Parms+0));
1890 #ifdef ASSERT
1891         Node* value_top = _gvn.transform(new ProjNode(trig, TypeFunc::Parms+1));
1892         assert(value_top == top(), "second value must be top");
1893 #endif
1894         phi->init_req(2, value_pow);
1895         region->init_req(2, _gvn.transform(new ProjNode(trig, TypeFunc::Control)));
1896       }
1897 
1898       C->set_has_split_ifs(true); // Has chance for split-if optimization
1899       set_control(_gvn.transform(region));
1900       record_for_igvn(region);
1901       set_result(_gvn.transform(phi));
1902 
1903       return true;
1904     }
1905   }
1906 
1907   return StubRoutines::dpow() != nullptr ?
1908     runtime_math(OptoRuntime::Math_DD_D_Type(), StubRoutines::dpow(),  "dpow") :
1909     runtime_math(OptoRuntime::Math_DD_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dpow),  "POW");
1910 }
1911 
1912 //------------------------------inline_math_native-----------------------------
1913 bool LibraryCallKit::inline_math_native(vmIntrinsics::ID id) {
1914   switch (id) {
1915   case vmIntrinsics::_dsin:
1916     return StubRoutines::dsin() != nullptr ?
1917       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dsin(), "dsin") :
1918       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dsin),   "SIN");
1919   case vmIntrinsics::_dcos:
1920     return StubRoutines::dcos() != nullptr ?
1921       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dcos(), "dcos") :
1922       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dcos),   "COS");
1923   case vmIntrinsics::_dtan:
1924     return StubRoutines::dtan() != nullptr ?
1925       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dtan(), "dtan") :
1926       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dtan), "TAN");
1927   case vmIntrinsics::_dsinh:
1928     return StubRoutines::dsinh() != nullptr ?
1929       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dsinh(), "dsinh") : false;
1930   case vmIntrinsics::_dtanh:
1931     return StubRoutines::dtanh() != nullptr ?
1932       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dtanh(), "dtanh") : false;
1933   case vmIntrinsics::_dcbrt:
1934     return StubRoutines::dcbrt() != nullptr ?
1935       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dcbrt(), "dcbrt") : false;
1936   case vmIntrinsics::_dexp:
1937     return StubRoutines::dexp() != nullptr ?
1938       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dexp(),  "dexp") :
1939       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dexp),  "EXP");
1940   case vmIntrinsics::_dlog:
1941     return StubRoutines::dlog() != nullptr ?
1942       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dlog(), "dlog") :
1943       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dlog),   "LOG");
1944   case vmIntrinsics::_dlog10:
1945     return StubRoutines::dlog10() != nullptr ?
1946       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dlog10(), "dlog10") :
1947       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dlog10), "LOG10");
1948 
1949   case vmIntrinsics::_roundD: return Matcher::match_rule_supported(Op_RoundD) ? inline_double_math(id) : false;
1950   case vmIntrinsics::_ceil:
1951   case vmIntrinsics::_floor:
1952   case vmIntrinsics::_rint:   return Matcher::match_rule_supported(Op_RoundDoubleMode) ? inline_double_math(id) : false;
1953 
1954   case vmIntrinsics::_dsqrt:
1955   case vmIntrinsics::_dsqrt_strict:
1956                               return Matcher::match_rule_supported(Op_SqrtD) ? inline_double_math(id) : false;
1957   case vmIntrinsics::_dabs:   return Matcher::has_match_rule(Op_AbsD)   ? inline_double_math(id) : false;
1958   case vmIntrinsics::_fabs:   return Matcher::match_rule_supported(Op_AbsF)   ? inline_math(id) : false;
1959   case vmIntrinsics::_iabs:   return Matcher::match_rule_supported(Op_AbsI)   ? inline_math(id) : false;
1960   case vmIntrinsics::_labs:   return Matcher::match_rule_supported(Op_AbsL)   ? inline_math(id) : false;
1961 
1962   case vmIntrinsics::_dpow:      return inline_math_pow();
1963   case vmIntrinsics::_dcopySign: return inline_double_math(id);
1964   case vmIntrinsics::_fcopySign: return inline_math(id);
1965   case vmIntrinsics::_dsignum: return Matcher::match_rule_supported(Op_SignumD) ? inline_double_math(id) : false;
1966   case vmIntrinsics::_fsignum: return Matcher::match_rule_supported(Op_SignumF) ? inline_math(id) : false;
1967   case vmIntrinsics::_roundF: return Matcher::match_rule_supported(Op_RoundF) ? inline_math(id) : false;
1968 
1969    // These intrinsics are not yet correctly implemented
1970   case vmIntrinsics::_datan2:
1971     return false;
1972 
1973   default:
1974     fatal_unexpected_iid(id);
1975     return false;
1976   }
1977 }
1978 
1979 //----------------------------inline_notify-----------------------------------*
1980 bool LibraryCallKit::inline_notify(vmIntrinsics::ID id) {
1981   const TypeFunc* ftype = OptoRuntime::monitor_notify_Type();
1982   address func;
1983   if (id == vmIntrinsics::_notify) {
1984     func = OptoRuntime::monitor_notify_Java();
1985   } else {
1986     func = OptoRuntime::monitor_notifyAll_Java();
1987   }
1988   Node* call = make_runtime_call(RC_NO_LEAF, ftype, func, nullptr, TypeRawPtr::BOTTOM, argument(0));
1989   make_slow_call_ex(call, env()->Throwable_klass(), false);
1990   return true;
1991 }
1992 
1993 
1994 //----------------------------inline_min_max-----------------------------------
1995 bool LibraryCallKit::inline_min_max(vmIntrinsics::ID id) {
1996   Node* a = nullptr;
1997   Node* b = nullptr;
1998   Node* n = nullptr;
1999   switch (id) {
2000     case vmIntrinsics::_min:
2001     case vmIntrinsics::_max:
2002     case vmIntrinsics::_minF:
2003     case vmIntrinsics::_maxF:
2004     case vmIntrinsics::_minF_strict:
2005     case vmIntrinsics::_maxF_strict:
2006     case vmIntrinsics::_min_strict:
2007     case vmIntrinsics::_max_strict:
2008       assert(callee()->signature()->size() == 2, "minF/maxF has 2 parameters of size 1 each.");
2009       a = argument(0);
2010       b = argument(1);
2011       break;
2012     case vmIntrinsics::_minD:
2013     case vmIntrinsics::_maxD:
2014     case vmIntrinsics::_minD_strict:
2015     case vmIntrinsics::_maxD_strict:
2016       assert(callee()->signature()->size() == 4, "minD/maxD has 2 parameters of size 2 each.");
2017       a = argument(0);
2018       b = argument(2);
2019       break;
2020     case vmIntrinsics::_minL:
2021     case vmIntrinsics::_maxL:
2022       assert(callee()->signature()->size() == 4, "minL/maxL has 2 parameters of size 2 each.");
2023       a = argument(0);
2024       b = argument(2);
2025       break;
2026     default:
2027       fatal_unexpected_iid(id);
2028       break;
2029   }
2030 
2031   switch (id) {
2032     case vmIntrinsics::_min:
2033     case vmIntrinsics::_min_strict:
2034       n = new MinINode(a, b);
2035       break;
2036     case vmIntrinsics::_max:
2037     case vmIntrinsics::_max_strict:
2038       n = new MaxINode(a, b);
2039       break;
2040     case vmIntrinsics::_minF:
2041     case vmIntrinsics::_minF_strict:
2042       n = new MinFNode(a, b);
2043       break;
2044     case vmIntrinsics::_maxF:
2045     case vmIntrinsics::_maxF_strict:
2046       n = new MaxFNode(a, b);
2047       break;
2048     case vmIntrinsics::_minD:
2049     case vmIntrinsics::_minD_strict:
2050       n = new MinDNode(a, b);
2051       break;
2052     case vmIntrinsics::_maxD:
2053     case vmIntrinsics::_maxD_strict:
2054       n = new MaxDNode(a, b);
2055       break;
2056     case vmIntrinsics::_minL:
2057       n = new MinLNode(_gvn.C, a, b);
2058       break;
2059     case vmIntrinsics::_maxL:
2060       n = new MaxLNode(_gvn.C, a, b);
2061       break;
2062     default:
2063       fatal_unexpected_iid(id);
2064       break;
2065   }
2066 
2067   set_result(_gvn.transform(n));
2068   return true;
2069 }
2070 
2071 bool LibraryCallKit::inline_math_mathExact(Node* math, Node* test) {
2072   if (builtin_throw_too_many_traps(Deoptimization::Reason_intrinsic,
2073                                    env()->ArithmeticException_instance())) {
2074     // It has been already too many times, but we cannot use builtin_throw (e.g. we care about backtraces),
2075     // so let's bail out intrinsic rather than risking deopting again.
2076     return false;
2077   }
2078 
2079   Node* bol = _gvn.transform( new BoolNode(test, BoolTest::overflow) );
2080   IfNode* check = create_and_map_if(control(), bol, PROB_UNLIKELY_MAG(3), COUNT_UNKNOWN);
2081   Node* fast_path = _gvn.transform( new IfFalseNode(check));
2082   Node* slow_path = _gvn.transform( new IfTrueNode(check) );
2083 
2084   {
2085     PreserveJVMState pjvms(this);
2086     PreserveReexecuteState preexecs(this);
2087     jvms()->set_should_reexecute(true);
2088 
2089     set_control(slow_path);
2090     set_i_o(i_o());
2091 
2092     builtin_throw(Deoptimization::Reason_intrinsic,
2093                   env()->ArithmeticException_instance(),
2094                   /*allow_too_many_traps*/ false);
2095   }
2096 
2097   set_control(fast_path);
2098   set_result(math);
2099   return true;
2100 }
2101 
2102 template <typename OverflowOp>
2103 bool LibraryCallKit::inline_math_overflow(Node* arg1, Node* arg2) {
2104   typedef typename OverflowOp::MathOp MathOp;
2105 
2106   MathOp* mathOp = new MathOp(arg1, arg2);
2107   Node* operation = _gvn.transform( mathOp );
2108   Node* ofcheck = _gvn.transform( new OverflowOp(arg1, arg2) );
2109   return inline_math_mathExact(operation, ofcheck);
2110 }
2111 
2112 bool LibraryCallKit::inline_math_addExactI(bool is_increment) {
2113   return inline_math_overflow<OverflowAddINode>(argument(0), is_increment ? intcon(1) : argument(1));
2114 }
2115 
2116 bool LibraryCallKit::inline_math_addExactL(bool is_increment) {
2117   return inline_math_overflow<OverflowAddLNode>(argument(0), is_increment ? longcon(1) : argument(2));
2118 }
2119 
2120 bool LibraryCallKit::inline_math_subtractExactI(bool is_decrement) {
2121   return inline_math_overflow<OverflowSubINode>(argument(0), is_decrement ? intcon(1) : argument(1));
2122 }
2123 
2124 bool LibraryCallKit::inline_math_subtractExactL(bool is_decrement) {
2125   return inline_math_overflow<OverflowSubLNode>(argument(0), is_decrement ? longcon(1) : argument(2));
2126 }
2127 
2128 bool LibraryCallKit::inline_math_negateExactI() {
2129   return inline_math_overflow<OverflowSubINode>(intcon(0), argument(0));
2130 }
2131 
2132 bool LibraryCallKit::inline_math_negateExactL() {
2133   return inline_math_overflow<OverflowSubLNode>(longcon(0), argument(0));
2134 }
2135 
2136 bool LibraryCallKit::inline_math_multiplyExactI() {
2137   return inline_math_overflow<OverflowMulINode>(argument(0), argument(1));
2138 }
2139 
2140 bool LibraryCallKit::inline_math_multiplyExactL() {
2141   return inline_math_overflow<OverflowMulLNode>(argument(0), argument(2));
2142 }
2143 
2144 bool LibraryCallKit::inline_math_multiplyHigh() {
2145   set_result(_gvn.transform(new MulHiLNode(argument(0), argument(2))));
2146   return true;
2147 }
2148 
2149 bool LibraryCallKit::inline_math_unsignedMultiplyHigh() {
2150   set_result(_gvn.transform(new UMulHiLNode(argument(0), argument(2))));
2151   return true;
2152 }
2153 
2154 inline int
2155 LibraryCallKit::classify_unsafe_addr(Node* &base, Node* &offset, BasicType type) {
2156   const TypePtr* base_type = TypePtr::NULL_PTR;
2157   if (base != nullptr)  base_type = _gvn.type(base)->isa_ptr();
2158   if (base_type == nullptr) {
2159     // Unknown type.
2160     return Type::AnyPtr;
2161   } else if (_gvn.type(base->uncast()) == TypePtr::NULL_PTR) {
2162     // Since this is a null+long form, we have to switch to a rawptr.
2163     base   = _gvn.transform(new CastX2PNode(offset));
2164     offset = MakeConX(0);
2165     return Type::RawPtr;
2166   } else if (base_type->base() == Type::RawPtr) {
2167     return Type::RawPtr;
2168   } else if (base_type->isa_oopptr()) {
2169     // Base is never null => always a heap address.
2170     if (!TypePtr::NULL_PTR->higher_equal(base_type)) {
2171       return Type::OopPtr;
2172     }
2173     // Offset is small => always a heap address.
2174     const TypeX* offset_type = _gvn.type(offset)->isa_intptr_t();
2175     if (offset_type != nullptr &&
2176         base_type->offset() == 0 &&     // (should always be?)
2177         offset_type->_lo >= 0 &&
2178         !MacroAssembler::needs_explicit_null_check(offset_type->_hi)) {
2179       return Type::OopPtr;
2180     } else if (type == T_OBJECT) {
2181       // off heap access to an oop doesn't make any sense. Has to be on
2182       // heap.
2183       return Type::OopPtr;
2184     }
2185     // Otherwise, it might either be oop+off or null+addr.
2186     return Type::AnyPtr;
2187   } else {
2188     // No information:
2189     return Type::AnyPtr;
2190   }
2191 }
2192 
2193 Node* LibraryCallKit::make_unsafe_address(Node*& base, Node* offset, BasicType type, bool can_cast) {
2194   Node* uncasted_base = base;
2195   int kind = classify_unsafe_addr(uncasted_base, offset, type);
2196   if (kind == Type::RawPtr) {
2197     return basic_plus_adr(top(), uncasted_base, offset);
2198   } else if (kind == Type::AnyPtr) {
2199     assert(base == uncasted_base, "unexpected base change");
2200     if (can_cast) {
2201       if (!_gvn.type(base)->speculative_maybe_null() &&
2202           !too_many_traps(Deoptimization::Reason_speculate_null_check)) {
2203         // According to profiling, this access is always on
2204         // heap. Casting the base to not null and thus avoiding membars
2205         // around the access should allow better optimizations
2206         Node* null_ctl = top();
2207         base = null_check_oop(base, &null_ctl, true, true, true);
2208         assert(null_ctl->is_top(), "no null control here");
2209         return basic_plus_adr(base, offset);
2210       } else if (_gvn.type(base)->speculative_always_null() &&
2211                  !too_many_traps(Deoptimization::Reason_speculate_null_assert)) {
2212         // According to profiling, this access is always off
2213         // heap.
2214         base = null_assert(base);
2215         Node* raw_base = _gvn.transform(new CastX2PNode(offset));
2216         offset = MakeConX(0);
2217         return basic_plus_adr(top(), raw_base, offset);
2218       }
2219     }
2220     // We don't know if it's an on heap or off heap access. Fall back
2221     // to raw memory access.
2222     Node* raw = _gvn.transform(new CheckCastPPNode(control(), base, TypeRawPtr::BOTTOM));
2223     return basic_plus_adr(top(), raw, offset);
2224   } else {
2225     assert(base == uncasted_base, "unexpected base change");
2226     // We know it's an on heap access so base can't be null
2227     if (TypePtr::NULL_PTR->higher_equal(_gvn.type(base))) {
2228       base = must_be_not_null(base, true);
2229     }
2230     return basic_plus_adr(base, offset);
2231   }
2232 }
2233 
2234 //--------------------------inline_number_methods-----------------------------
2235 // inline int     Integer.numberOfLeadingZeros(int)
2236 // inline int        Long.numberOfLeadingZeros(long)
2237 //
2238 // inline int     Integer.numberOfTrailingZeros(int)
2239 // inline int        Long.numberOfTrailingZeros(long)
2240 //
2241 // inline int     Integer.bitCount(int)
2242 // inline int        Long.bitCount(long)
2243 //
2244 // inline char  Character.reverseBytes(char)
2245 // inline short     Short.reverseBytes(short)
2246 // inline int     Integer.reverseBytes(int)
2247 // inline long       Long.reverseBytes(long)
2248 bool LibraryCallKit::inline_number_methods(vmIntrinsics::ID id) {
2249   Node* arg = argument(0);
2250   Node* n = nullptr;
2251   switch (id) {
2252   case vmIntrinsics::_numberOfLeadingZeros_i:   n = new CountLeadingZerosINode( arg); break;
2253   case vmIntrinsics::_numberOfLeadingZeros_l:   n = new CountLeadingZerosLNode( arg); break;
2254   case vmIntrinsics::_numberOfTrailingZeros_i:  n = new CountTrailingZerosINode(arg); break;
2255   case vmIntrinsics::_numberOfTrailingZeros_l:  n = new CountTrailingZerosLNode(arg); break;
2256   case vmIntrinsics::_bitCount_i:               n = new PopCountINode(          arg); break;
2257   case vmIntrinsics::_bitCount_l:               n = new PopCountLNode(          arg); break;
2258   case vmIntrinsics::_reverseBytes_c:           n = new ReverseBytesUSNode(     arg); break;
2259   case vmIntrinsics::_reverseBytes_s:           n = new ReverseBytesSNode(      arg); break;
2260   case vmIntrinsics::_reverseBytes_i:           n = new ReverseBytesINode(      arg); break;
2261   case vmIntrinsics::_reverseBytes_l:           n = new ReverseBytesLNode(      arg); break;
2262   case vmIntrinsics::_reverse_i:                n = new ReverseINode(           arg); break;
2263   case vmIntrinsics::_reverse_l:                n = new ReverseLNode(           arg); break;
2264   default:  fatal_unexpected_iid(id);  break;
2265   }
2266   set_result(_gvn.transform(n));
2267   return true;
2268 }
2269 
2270 //--------------------------inline_bitshuffle_methods-----------------------------
2271 // inline int Integer.compress(int, int)
2272 // inline int Integer.expand(int, int)
2273 // inline long Long.compress(long, long)
2274 // inline long Long.expand(long, long)
2275 bool LibraryCallKit::inline_bitshuffle_methods(vmIntrinsics::ID id) {
2276   Node* n = nullptr;
2277   switch (id) {
2278     case vmIntrinsics::_compress_i:  n = new CompressBitsNode(argument(0), argument(1), TypeInt::INT); break;
2279     case vmIntrinsics::_expand_i:    n = new ExpandBitsNode(argument(0),  argument(1), TypeInt::INT); break;
2280     case vmIntrinsics::_compress_l:  n = new CompressBitsNode(argument(0), argument(2), TypeLong::LONG); break;
2281     case vmIntrinsics::_expand_l:    n = new ExpandBitsNode(argument(0), argument(2), TypeLong::LONG); break;
2282     default:  fatal_unexpected_iid(id);  break;
2283   }
2284   set_result(_gvn.transform(n));
2285   return true;
2286 }
2287 
2288 //--------------------------inline_number_methods-----------------------------
2289 // inline int Integer.compareUnsigned(int, int)
2290 // inline int    Long.compareUnsigned(long, long)
2291 bool LibraryCallKit::inline_compare_unsigned(vmIntrinsics::ID id) {
2292   Node* arg1 = argument(0);
2293   Node* arg2 = (id == vmIntrinsics::_compareUnsigned_l) ? argument(2) : argument(1);
2294   Node* n = nullptr;
2295   switch (id) {
2296     case vmIntrinsics::_compareUnsigned_i:   n = new CmpU3Node(arg1, arg2);  break;
2297     case vmIntrinsics::_compareUnsigned_l:   n = new CmpUL3Node(arg1, arg2); break;
2298     default:  fatal_unexpected_iid(id);  break;
2299   }
2300   set_result(_gvn.transform(n));
2301   return true;
2302 }
2303 
2304 //--------------------------inline_unsigned_divmod_methods-----------------------------
2305 // inline int Integer.divideUnsigned(int, int)
2306 // inline int Integer.remainderUnsigned(int, int)
2307 // inline long Long.divideUnsigned(long, long)
2308 // inline long Long.remainderUnsigned(long, long)
2309 bool LibraryCallKit::inline_divmod_methods(vmIntrinsics::ID id) {
2310   Node* n = nullptr;
2311   switch (id) {
2312     case vmIntrinsics::_divideUnsigned_i: {
2313       zero_check_int(argument(1));
2314       // Compile-time detect of null-exception
2315       if (stopped()) {
2316         return true; // keep the graph constructed so far
2317       }
2318       n = new UDivINode(control(), argument(0), argument(1));
2319       break;
2320     }
2321     case vmIntrinsics::_divideUnsigned_l: {
2322       zero_check_long(argument(2));
2323       // Compile-time detect of null-exception
2324       if (stopped()) {
2325         return true; // keep the graph constructed so far
2326       }
2327       n = new UDivLNode(control(), argument(0), argument(2));
2328       break;
2329     }
2330     case vmIntrinsics::_remainderUnsigned_i: {
2331       zero_check_int(argument(1));
2332       // Compile-time detect of null-exception
2333       if (stopped()) {
2334         return true; // keep the graph constructed so far
2335       }
2336       n = new UModINode(control(), argument(0), argument(1));
2337       break;
2338     }
2339     case vmIntrinsics::_remainderUnsigned_l: {
2340       zero_check_long(argument(2));
2341       // Compile-time detect of null-exception
2342       if (stopped()) {
2343         return true; // keep the graph constructed so far
2344       }
2345       n = new UModLNode(control(), argument(0), argument(2));
2346       break;
2347     }
2348     default:  fatal_unexpected_iid(id);  break;
2349   }
2350   set_result(_gvn.transform(n));
2351   return true;
2352 }
2353 
2354 //----------------------------inline_unsafe_access----------------------------
2355 
2356 const TypeOopPtr* LibraryCallKit::sharpen_unsafe_type(Compile::AliasType* alias_type, const TypePtr *adr_type) {
2357   // Attempt to infer a sharper value type from the offset and base type.
2358   ciKlass* sharpened_klass = nullptr;
2359   bool null_free = false;
2360 
2361   // See if it is an instance field, with an object type.
2362   if (alias_type->field() != nullptr) {
2363     if (alias_type->field()->type()->is_klass()) {
2364       sharpened_klass = alias_type->field()->type()->as_klass();
2365       null_free = alias_type->field()->is_null_free();
2366     }
2367   }
2368 
2369   const TypeOopPtr* result = nullptr;
2370   // See if it is a narrow oop array.
2371   if (adr_type->isa_aryptr()) {
2372     if (adr_type->offset() >= refArrayOopDesc::base_offset_in_bytes()) {
2373       const TypeOopPtr* elem_type = adr_type->is_aryptr()->elem()->make_oopptr();
2374       null_free = adr_type->is_aryptr()->is_null_free();
2375       if (elem_type != nullptr && elem_type->is_loaded()) {
2376         // Sharpen the value type.
2377         result = elem_type;
2378       }
2379     }
2380   }
2381 
2382   // The sharpened class might be unloaded if there is no class loader
2383   // contraint in place.
2384   if (result == nullptr && sharpened_klass != nullptr && sharpened_klass->is_loaded()) {
2385     // Sharpen the value type.
2386     result = TypeOopPtr::make_from_klass(sharpened_klass);
2387     if (null_free) {
2388       result = result->join_speculative(TypePtr::NOTNULL)->is_oopptr();
2389     }
2390   }
2391   if (result != nullptr) {
2392 #ifndef PRODUCT
2393     if (C->print_intrinsics() || C->print_inlining()) {
2394       tty->print("  from base type:  ");  adr_type->dump(); tty->cr();
2395       tty->print("  sharpened value: ");  result->dump();    tty->cr();
2396     }
2397 #endif
2398   }
2399   return result;
2400 }
2401 
2402 DecoratorSet LibraryCallKit::mo_decorator_for_access_kind(AccessKind kind) {
2403   switch (kind) {
2404       case Relaxed:
2405         return MO_UNORDERED;
2406       case Opaque:
2407         return MO_RELAXED;
2408       case Acquire:
2409         return MO_ACQUIRE;
2410       case Release:
2411         return MO_RELEASE;
2412       case Volatile:
2413         return MO_SEQ_CST;
2414       default:
2415         ShouldNotReachHere();
2416         return 0;
2417   }
2418 }
2419 
2420 LibraryCallKit::SavedState::SavedState(LibraryCallKit* kit) :
2421   _kit(kit),
2422   _sp(kit->sp()),
2423   _jvms(kit->jvms()),
2424   _map(kit->clone_map()),
2425   _discarded(false)
2426 {
2427   for (DUIterator_Fast imax, i = kit->control()->fast_outs(imax); i < imax; i++) {
2428     Node* out = kit->control()->fast_out(i);
2429     if (out->is_CFG()) {
2430       _ctrl_succ.push(out);
2431     }
2432   }
2433 }
2434 
2435 LibraryCallKit::SavedState::~SavedState() {
2436   if (_discarded) {
2437     _kit->destruct_map_clone(_map);
2438     return;
2439   }
2440   _kit->jvms()->set_map(_map);
2441   _kit->jvms()->set_sp(_sp);
2442   _map->set_jvms(_kit->jvms());
2443   _kit->set_map(_map);
2444   _kit->set_sp(_sp);
2445   for (DUIterator_Fast imax, i = _kit->control()->fast_outs(imax); i < imax; i++) {
2446     Node* out = _kit->control()->fast_out(i);
2447     if (out->is_CFG() && out->in(0) == _kit->control() && out != _kit->map() && !_ctrl_succ.member(out)) {
2448       _kit->_gvn.hash_delete(out);
2449       out->set_req(0, _kit->C->top());
2450       _kit->C->record_for_igvn(out);
2451       --i; --imax;
2452       _kit->_gvn.hash_find_insert(out);
2453     }
2454   }
2455 }
2456 
2457 void LibraryCallKit::SavedState::discard() {
2458   _discarded = true;
2459 }
2460 
2461 bool LibraryCallKit::inline_unsafe_access(bool is_store, const BasicType type, const AccessKind kind, const bool unaligned, const bool is_flat) {
2462   if (callee()->is_static())  return false;  // caller must have the capability!
2463   DecoratorSet decorators = C2_UNSAFE_ACCESS;
2464   guarantee(!is_store || kind != Acquire, "Acquire accesses can be produced only for loads");
2465   guarantee( is_store || kind != Release, "Release accesses can be produced only for stores");
2466   assert(type != T_OBJECT || !unaligned, "unaligned access not supported with object type");
2467 
2468   if (is_reference_type(type)) {
2469     decorators |= ON_UNKNOWN_OOP_REF;
2470   }
2471 
2472   if (unaligned) {
2473     decorators |= C2_UNALIGNED;
2474   }
2475 
2476 #ifndef PRODUCT
2477   {
2478     ResourceMark rm;
2479     // Check the signatures.
2480     ciSignature* sig = callee()->signature();
2481 #ifdef ASSERT
2482     if (!is_store) {
2483       // Object getReference(Object base, int/long offset), etc.
2484       BasicType rtype = sig->return_type()->basic_type();
2485       assert(rtype == type, "getter must return the expected value");
2486       assert(sig->count() == 2 || (is_flat && sig->count() == 3), "oop getter has 2 or 3 arguments");
2487       assert(sig->type_at(0)->basic_type() == T_OBJECT, "getter base is object");
2488       assert(sig->type_at(1)->basic_type() == T_LONG, "getter offset is correct");
2489     } else {
2490       // void putReference(Object base, int/long offset, Object x), etc.
2491       assert(sig->return_type()->basic_type() == T_VOID, "putter must not return a value");
2492       assert(sig->count() == 3 || (is_flat && sig->count() == 4), "oop putter has 3 arguments");
2493       assert(sig->type_at(0)->basic_type() == T_OBJECT, "putter base is object");
2494       assert(sig->type_at(1)->basic_type() == T_LONG, "putter offset is correct");
2495       BasicType vtype = sig->type_at(sig->count()-1)->basic_type();
2496       assert(vtype == type, "putter must accept the expected value");
2497     }
2498 #endif // ASSERT
2499  }
2500 #endif //PRODUCT
2501 
2502   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
2503 
2504   Node* receiver = argument(0);  // type: oop
2505 
2506   // Build address expression.
2507   Node* heap_base_oop = top();
2508 
2509   // The base is either a Java object or a value produced by Unsafe.staticFieldBase
2510   Node* base = argument(1);  // type: oop
2511   // The offset is a value produced by Unsafe.staticFieldOffset or Unsafe.objectFieldOffset
2512   Node* offset = argument(2);  // type: long
2513   // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
2514   // to be plain byte offsets, which are also the same as those accepted
2515   // by oopDesc::field_addr.
2516   assert(Unsafe_field_offset_to_byte_offset(11) == 11,
2517          "fieldOffset must be byte-scaled");
2518 
2519   ciInlineKlass* inline_klass = nullptr;
2520   if (is_flat) {
2521     const TypeInstPtr* cls = _gvn.type(argument(4))->isa_instptr();
2522     if (cls == nullptr || cls->const_oop() == nullptr) {
2523       return false;
2524     }
2525     ciType* mirror_type = cls->const_oop()->as_instance()->java_mirror_type();
2526     if (!mirror_type->is_inlinetype()) {
2527       return false;
2528     }
2529     inline_klass = mirror_type->as_inline_klass();
2530   }
2531 
2532   if (base->is_InlineType()) {
2533     assert(!is_store, "InlineTypeNodes are non-larval value objects");
2534     InlineTypeNode* vt = base->as_InlineType();
2535     if (offset->is_Con()) {
2536       long off = find_long_con(offset, 0);
2537       ciInlineKlass* vk = vt->type()->inline_klass();
2538       if ((long)(int)off != off || !vk->contains_field_offset(off)) {
2539         return false;
2540       }
2541 
2542       ciField* field = vk->get_non_flat_field_by_offset(off);
2543       if (field != nullptr) {
2544         BasicType bt = type2field[field->type()->basic_type()];
2545         if (bt == T_ARRAY || bt == T_NARROWOOP) {
2546           bt = T_OBJECT;
2547         }
2548         if (bt == type && (!field->is_flat() || field->type() == inline_klass)) {
2549           Node* value = vt->field_value_by_offset(off, false);
2550           if (value->is_InlineType()) {
2551             value = value->as_InlineType()->adjust_scalarization_depth(this);
2552           }
2553           set_result(value);
2554           return true;
2555         }
2556       }
2557     }
2558     {
2559       // Re-execute the unsafe access if allocation triggers deoptimization.
2560       PreserveReexecuteState preexecs(this);
2561       jvms()->set_should_reexecute(true);
2562       vt = vt->buffer(this);
2563     }
2564     base = vt->get_oop();
2565   }
2566 
2567   // 32-bit machines ignore the high half!
2568   offset = ConvL2X(offset);
2569 
2570   // Save state and restore on bailout
2571   SavedState old_state(this);
2572 
2573   Node* adr = make_unsafe_address(base, offset, type, kind == Relaxed);
2574   assert(!stopped(), "Inlining of unsafe access failed: address construction stopped unexpectedly");
2575 
2576   if (_gvn.type(base->uncast())->isa_ptr() == TypePtr::NULL_PTR) {
2577     if (type != T_OBJECT && (inline_klass == nullptr || !inline_klass->has_object_fields())) {
2578       decorators |= IN_NATIVE; // off-heap primitive access
2579     } else {
2580       return false; // off-heap oop accesses are not supported
2581     }
2582   } else {
2583     heap_base_oop = base; // on-heap or mixed access
2584   }
2585 
2586   // Can base be null? Otherwise, always on-heap access.
2587   bool can_access_non_heap = TypePtr::NULL_PTR->higher_equal(_gvn.type(base));
2588 
2589   if (!can_access_non_heap) {
2590     decorators |= IN_HEAP;
2591   }
2592 
2593   Node* val = is_store ? argument(4 + (is_flat ? 1 : 0)) : nullptr;
2594 
2595   const TypePtr* adr_type = _gvn.type(adr)->isa_ptr();
2596   if (adr_type == TypePtr::NULL_PTR) {
2597     return false; // off-heap access with zero address
2598   }
2599 
2600   // Try to categorize the address.
2601   Compile::AliasType* alias_type = C->alias_type(adr_type);
2602   assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
2603 
2604   if (alias_type->adr_type() == TypeInstPtr::KLASS ||
2605       alias_type->adr_type() == TypeAryPtr::RANGE) {
2606     return false; // not supported
2607   }
2608 
2609   bool mismatched = false;
2610   BasicType bt = T_ILLEGAL;
2611   ciField* field = nullptr;
2612   if (adr_type->isa_instptr()) {
2613     const TypeInstPtr* instptr = adr_type->is_instptr();
2614     ciInstanceKlass* k = instptr->instance_klass();
2615     int off = instptr->offset();
2616     if (instptr->const_oop() != nullptr &&
2617         k == ciEnv::current()->Class_klass() &&
2618         instptr->offset() >= (k->size_helper() * wordSize)) {
2619       k = instptr->const_oop()->as_instance()->java_lang_Class_klass()->as_instance_klass();
2620       field = k->get_field_by_offset(off, true);
2621     } else {
2622       field = k->get_non_flat_field_by_offset(off);
2623     }
2624     if (field != nullptr) {
2625       bt = type2field[field->type()->basic_type()];
2626     }
2627     if (bt != alias_type->basic_type()) {
2628       // Type mismatch. Is it an access to a nested flat field?
2629       field = k->get_field_by_offset(off, false);
2630       if (field != nullptr) {
2631         bt = type2field[field->type()->basic_type()];
2632       }
2633     }
2634     assert(bt == alias_type->basic_type() || is_flat, "should match");
2635   } else {
2636     bt = alias_type->basic_type();
2637   }
2638 
2639   if (bt != T_ILLEGAL) {
2640     assert(alias_type->adr_type()->is_oopptr(), "should be on-heap access");
2641     if (bt == T_BYTE && adr_type->isa_aryptr()) {
2642       // Alias type doesn't differentiate between byte[] and boolean[]).
2643       // Use address type to get the element type.
2644       bt = adr_type->is_aryptr()->elem()->array_element_basic_type();
2645     }
2646     if (is_reference_type(bt, true)) {
2647       // accessing an array field with getReference is not a mismatch
2648       bt = T_OBJECT;
2649     }
2650     if ((bt == T_OBJECT) != (type == T_OBJECT)) {
2651       // Don't intrinsify mismatched object accesses
2652       return false;
2653     }
2654     mismatched = (bt != type);
2655   } else if (alias_type->adr_type()->isa_oopptr()) {
2656     mismatched = true; // conservatively mark all "wide" on-heap accesses as mismatched
2657   }
2658 
2659   if (is_flat) {
2660     if (adr_type->isa_instptr()) {
2661       if (field == nullptr || field->type() != inline_klass) {
2662         mismatched = true;
2663       }
2664     } else if (adr_type->isa_aryptr()) {
2665       const Type* elem = adr_type->is_aryptr()->elem();
2666       if (!adr_type->is_flat() || elem->inline_klass() != inline_klass) {
2667         mismatched = true;
2668       }
2669     } else {
2670       mismatched = true;
2671     }
2672     if (is_store) {
2673       const Type* val_t = _gvn.type(val);
2674       if (!val_t->is_inlinetypeptr() || val_t->inline_klass() != inline_klass) {
2675         return false;
2676       }
2677     }
2678   }
2679 
2680   old_state.discard();
2681   assert(!mismatched || alias_type->adr_type()->is_oopptr(), "off-heap access can't be mismatched");
2682 
2683   if (mismatched) {
2684     decorators |= C2_MISMATCHED;
2685   }
2686 
2687   // First guess at the value type.
2688   const Type *value_type = Type::get_const_basic_type(type);
2689 
2690   // Figure out the memory ordering.
2691   decorators |= mo_decorator_for_access_kind(kind);
2692 
2693   if (!is_store) {
2694     if (type == T_OBJECT && !is_flat) {
2695       const TypeOopPtr* tjp = sharpen_unsafe_type(alias_type, adr_type);
2696       if (tjp != nullptr) {
2697         value_type = tjp;
2698       }
2699     }
2700   }
2701 
2702   receiver = null_check(receiver);
2703   if (stopped()) {
2704     return true;
2705   }
2706   // Heap pointers get a null-check from the interpreter,
2707   // as a courtesy.  However, this is not guaranteed by Unsafe,
2708   // and it is not possible to fully distinguish unintended nulls
2709   // from intended ones in this API.
2710 
2711   if (!is_store) {
2712     Node* p = nullptr;
2713     // Try to constant fold a load from a constant field
2714 
2715     if (heap_base_oop != top() && field != nullptr && field->is_constant() && !field->is_flat() && !mismatched) {
2716       // final or stable field
2717       p = make_constant_from_field(field, heap_base_oop);
2718     }
2719 
2720     if (p == nullptr) { // Could not constant fold the load
2721       if (is_flat) {
2722         p = InlineTypeNode::make_from_flat(this, inline_klass, base, adr, adr_type, false, false, true);
2723       } else {
2724         p = access_load_at(heap_base_oop, adr, adr_type, value_type, type, decorators);
2725         const TypeOopPtr* ptr = value_type->make_oopptr();
2726         if (ptr != nullptr && ptr->is_inlinetypeptr()) {
2727           // Load a non-flattened inline type from memory
2728           p = InlineTypeNode::make_from_oop(this, p, ptr->inline_klass());
2729         }
2730       }
2731       // Normalize the value returned by getBoolean in the following cases
2732       if (type == T_BOOLEAN &&
2733           (mismatched ||
2734            heap_base_oop == top() ||                  // - heap_base_oop is null or
2735            (can_access_non_heap && field == nullptr)) // - heap_base_oop is potentially null
2736                                                       //   and the unsafe access is made to large offset
2737                                                       //   (i.e., larger than the maximum offset necessary for any
2738                                                       //   field access)
2739             ) {
2740           IdealKit ideal = IdealKit(this);
2741 #define __ ideal.
2742           IdealVariable normalized_result(ideal);
2743           __ declarations_done();
2744           __ set(normalized_result, p);
2745           __ if_then(p, BoolTest::ne, ideal.ConI(0));
2746           __ set(normalized_result, ideal.ConI(1));
2747           ideal.end_if();
2748           final_sync(ideal);
2749           p = __ value(normalized_result);
2750 #undef __
2751       }
2752     }
2753     if (type == T_ADDRESS) {
2754       p = gvn().transform(new CastP2XNode(nullptr, p));
2755       p = ConvX2UL(p);
2756     }
2757     // The load node has the control of the preceding MemBarCPUOrder.  All
2758     // following nodes will have the control of the MemBarCPUOrder inserted at
2759     // the end of this method.  So, pushing the load onto the stack at a later
2760     // point is fine.
2761     set_result(p);
2762   } else {
2763     if (bt == T_ADDRESS) {
2764       // Repackage the long as a pointer.
2765       val = ConvL2X(val);
2766       val = gvn().transform(new CastX2PNode(val));
2767     }
2768     if (is_flat) {
2769       val->as_InlineType()->store_flat(this, base, adr, false, false, true, decorators);
2770     } else {
2771       access_store_at(heap_base_oop, adr, adr_type, val, value_type, type, decorators);
2772     }
2773   }
2774 
2775   return true;
2776 }
2777 
2778 bool LibraryCallKit::inline_unsafe_flat_access(bool is_store, AccessKind kind) {
2779 #ifdef ASSERT
2780   {
2781     ResourceMark rm;
2782     // Check the signatures.
2783     ciSignature* sig = callee()->signature();
2784     assert(sig->type_at(0)->basic_type() == T_OBJECT, "base should be object, but is %s", type2name(sig->type_at(0)->basic_type()));
2785     assert(sig->type_at(1)->basic_type() == T_LONG, "offset should be long, but is %s", type2name(sig->type_at(1)->basic_type()));
2786     assert(sig->type_at(2)->basic_type() == T_INT, "layout kind should be int, but is %s", type2name(sig->type_at(3)->basic_type()));
2787     assert(sig->type_at(3)->basic_type() == T_OBJECT, "value klass should be object, but is %s", type2name(sig->type_at(4)->basic_type()));
2788     if (is_store) {
2789       assert(sig->return_type()->basic_type() == T_VOID, "putter must not return a value, but returns %s", type2name(sig->return_type()->basic_type()));
2790       assert(sig->count() == 5, "flat putter should have 5 arguments, but has %d", sig->count());
2791       assert(sig->type_at(4)->basic_type() == T_OBJECT, "put value should be object, but is %s", type2name(sig->type_at(5)->basic_type()));
2792     } else {
2793       assert(sig->return_type()->basic_type() == T_OBJECT, "getter must return an object, but returns %s", type2name(sig->return_type()->basic_type()));
2794       assert(sig->count() == 4, "flat getter should have 4 arguments, but has %d", sig->count());
2795     }
2796  }
2797 #endif // ASSERT
2798 
2799   assert(kind == Relaxed, "Only plain accesses for now");
2800   if (callee()->is_static()) {
2801     // caller must have the capability!
2802     return false;
2803   }
2804   C->set_has_unsafe_access(true);
2805 
2806   const TypeInstPtr* value_klass_node = _gvn.type(argument(5))->isa_instptr();
2807   if (value_klass_node == nullptr || value_klass_node->const_oop() == nullptr) {
2808     // parameter valueType is not a constant
2809     return false;
2810   }
2811   ciType* mirror_type = value_klass_node->const_oop()->as_instance()->java_mirror_type();
2812   if (!mirror_type->is_inlinetype()) {
2813     // Dead code
2814     return false;
2815   }
2816   ciInlineKlass* value_klass = mirror_type->as_inline_klass();
2817 
2818   const TypeInt* layout_type = _gvn.type(argument(4))->isa_int();
2819   if (layout_type == nullptr || !layout_type->is_con()) {
2820     // parameter layoutKind is not a constant
2821     return false;
2822   }
2823   assert(layout_type->get_con() >= static_cast<int>(LayoutKind::REFERENCE) &&
2824          layout_type->get_con() <= static_cast<int>(LayoutKind::UNKNOWN),
2825          "invalid layoutKind %d", layout_type->get_con());
2826   LayoutKind layout = static_cast<LayoutKind>(layout_type->get_con());
2827   assert(layout == LayoutKind::REFERENCE || layout == LayoutKind::NON_ATOMIC_FLAT ||
2828          layout == LayoutKind::ATOMIC_FLAT || layout == LayoutKind::NULLABLE_ATOMIC_FLAT,
2829          "unexpected layoutKind %d", layout_type->get_con());
2830 
2831   null_check(argument(0));
2832   if (stopped()) {
2833     return true;
2834   }
2835 
2836   Node* base = must_be_not_null(argument(1), true);
2837   Node* offset = argument(2);
2838   const Type* base_type = _gvn.type(base);
2839 
2840   Node* ptr;
2841   bool immutable_memory = false;
2842   DecoratorSet decorators = C2_UNSAFE_ACCESS | IN_HEAP | MO_UNORDERED;
2843   if (base_type->isa_instptr()) {
2844     const TypeLong* offset_type = _gvn.type(offset)->isa_long();
2845     if (offset_type == nullptr || !offset_type->is_con()) {
2846       // Offset into a non-array should be a constant
2847       decorators |= C2_MISMATCHED;
2848     } else {
2849       int offset_con = checked_cast<int>(offset_type->get_con());
2850       ciInstanceKlass* base_klass = base_type->is_instptr()->instance_klass();
2851       ciField* field = base_klass->get_non_flat_field_by_offset(offset_con);
2852       if (field == nullptr) {
2853         assert(!base_klass->is_final(), "non-existence field at offset %d of class %s", offset_con, base_klass->name()->as_utf8());
2854         decorators |= C2_MISMATCHED;
2855       } else {
2856         assert(field->type() == value_klass, "field at offset %d of %s is of type %s, but valueType is %s",
2857                offset_con, base_klass->name()->as_utf8(), field->type()->name(), value_klass->name()->as_utf8());
2858         immutable_memory = field->is_strict() && field->is_final();
2859 
2860         if (base->is_InlineType()) {
2861           assert(!is_store, "Cannot store into a non-larval value object");
2862           set_result(base->as_InlineType()->field_value_by_offset(offset_con, false));
2863           return true;
2864         }
2865       }
2866     }
2867 
2868     if (base->is_InlineType()) {
2869       assert(!is_store, "Cannot store into a non-larval value object");
2870       base = base->as_InlineType()->buffer(this, true);
2871     }
2872     ptr = basic_plus_adr(base, ConvL2X(offset));
2873   } else if (base_type->isa_aryptr()) {
2874     decorators |= IS_ARRAY;
2875     if (layout == LayoutKind::REFERENCE) {
2876       if (!base_type->is_aryptr()->is_not_flat()) {
2877         const TypeAryPtr* array_type = base_type->is_aryptr()->cast_to_not_flat();
2878         Node* new_base = _gvn.transform(new CastPPNode(control(), base, array_type, ConstraintCastNode::StrongDependency));
2879         replace_in_map(base, new_base);
2880         base = new_base;
2881       }
2882       ptr = basic_plus_adr(base, ConvL2X(offset));
2883     } else {
2884       if (UseArrayFlattening) {
2885         // Flat array must have an exact type
2886         bool is_null_free = layout != LayoutKind::NULLABLE_ATOMIC_FLAT;
2887         bool is_atomic = layout != LayoutKind::NON_ATOMIC_FLAT;
2888         Node* new_base = cast_to_flat_array(base, value_klass, is_null_free, !is_null_free, is_atomic);
2889         replace_in_map(base, new_base);
2890         base = new_base;
2891         ptr = basic_plus_adr(base, ConvL2X(offset));
2892         const TypeAryPtr* ptr_type = _gvn.type(ptr)->is_aryptr();
2893         if (ptr_type->field_offset().get() != 0) {
2894           ptr = _gvn.transform(new CastPPNode(control(), ptr, ptr_type->with_field_offset(0), ConstraintCastNode::StrongDependency));
2895         }
2896       } else {
2897         uncommon_trap(Deoptimization::Reason_intrinsic,
2898                       Deoptimization::Action_none);
2899         return true;
2900       }
2901     }
2902   } else {
2903     decorators |= C2_MISMATCHED;
2904     ptr = basic_plus_adr(base, ConvL2X(offset));
2905   }
2906 
2907   if (is_store) {
2908     Node* value = argument(6);
2909     const Type* value_type = _gvn.type(value);
2910     if (!value_type->is_inlinetypeptr()) {
2911       value_type = Type::get_const_type(value_klass)->filter_speculative(value_type);
2912       Node* new_value = _gvn.transform(new CastPPNode(control(), value, value_type, ConstraintCastNode::StrongDependency));
2913       new_value = InlineTypeNode::make_from_oop(this, new_value, value_klass);
2914       replace_in_map(value, new_value);
2915       value = new_value;
2916     }
2917 
2918     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());
2919     if (layout == LayoutKind::REFERENCE) {
2920       const TypePtr* ptr_type = (decorators & C2_MISMATCHED) != 0 ? TypeRawPtr::BOTTOM : _gvn.type(ptr)->is_ptr();
2921       access_store_at(base, ptr, ptr_type, value, value_type, T_OBJECT, decorators);
2922     } else {
2923       bool atomic = layout != LayoutKind::NON_ATOMIC_FLAT;
2924       bool null_free = layout != LayoutKind::NULLABLE_ATOMIC_FLAT;
2925       value->as_InlineType()->store_flat(this, base, ptr, atomic, immutable_memory, null_free, decorators);
2926     }
2927 
2928     return true;
2929   } else {
2930     decorators |= (C2_CONTROL_DEPENDENT_LOAD | C2_UNKNOWN_CONTROL_LOAD);
2931     InlineTypeNode* result;
2932     if (layout == LayoutKind::REFERENCE) {
2933       const TypePtr* ptr_type = (decorators & C2_MISMATCHED) != 0 ? TypeRawPtr::BOTTOM : _gvn.type(ptr)->is_ptr();
2934       Node* oop = access_load_at(base, ptr, ptr_type, Type::get_const_type(value_klass), T_OBJECT, decorators);
2935       result = InlineTypeNode::make_from_oop(this, oop, value_klass);
2936     } else {
2937       bool atomic = layout != LayoutKind::NON_ATOMIC_FLAT;
2938       bool null_free = layout != LayoutKind::NULLABLE_ATOMIC_FLAT;
2939       result = InlineTypeNode::make_from_flat(this, value_klass, base, ptr, atomic, immutable_memory, null_free, decorators);
2940     }
2941 
2942     set_result(result);
2943     return true;
2944   }
2945 }
2946 
2947 bool LibraryCallKit::inline_unsafe_make_private_buffer() {
2948   Node* receiver = argument(0);
2949   Node* value = argument(1);
2950 
2951   const Type* type = gvn().type(value);
2952   if (!type->is_inlinetypeptr()) {
2953     C->record_method_not_compilable("value passed to Unsafe::makePrivateBuffer is not of a constant value type");
2954     return false;
2955   }
2956 
2957   null_check(receiver);
2958   if (stopped()) {
2959     return true;
2960   }
2961 
2962   value = null_check(value);
2963   if (stopped()) {
2964     return true;
2965   }
2966 
2967   ciInlineKlass* vk = type->inline_klass();
2968   Node* klass = makecon(TypeKlassPtr::make(vk));
2969   Node* obj = new_instance(klass);
2970   AllocateNode::Ideal_allocation(obj)->_larval = true;
2971 
2972   assert(value->is_InlineType(), "must be an InlineTypeNode");
2973   Node* payload_ptr = basic_plus_adr(obj, vk->payload_offset());
2974   value->as_InlineType()->store_flat(this, obj, payload_ptr, false, true, true, IN_HEAP | MO_UNORDERED);
2975 
2976   set_result(obj);
2977   return true;
2978 }
2979 
2980 bool LibraryCallKit::inline_unsafe_finish_private_buffer() {
2981   Node* receiver = argument(0);
2982   Node* buffer = argument(1);
2983 
2984   const Type* type = gvn().type(buffer);
2985   if (!type->is_inlinetypeptr()) {
2986     C->record_method_not_compilable("value passed to Unsafe::finishPrivateBuffer is not of a constant value type");
2987     return false;
2988   }
2989 
2990   AllocateNode* alloc = AllocateNode::Ideal_allocation(buffer);
2991   if (alloc == nullptr) {
2992     C->record_method_not_compilable("value passed to Unsafe::finishPrivateBuffer must be allocated by Unsafe::makePrivateBuffer");
2993     return false;
2994   }
2995 
2996   null_check(receiver);
2997   if (stopped()) {
2998     return true;
2999   }
3000 
3001   // Unset the larval bit in the object header
3002   Node* old_header = make_load(control(), buffer, TypeX_X, TypeX_X->basic_type(), MemNode::unordered, LoadNode::Pinned);
3003   Node* new_header = gvn().transform(new AndXNode(old_header, MakeConX(~markWord::larval_bit_in_place)));
3004   access_store_at(buffer, buffer, type->is_ptr(), new_header, TypeX_X, TypeX_X->basic_type(), MO_UNORDERED | IN_HEAP);
3005 
3006   // We must ensure that the buffer is properly published
3007   insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out(AllocateNode::RawAddress));
3008   assert(!type->maybe_null(), "result of an allocation should not be null");
3009   set_result(InlineTypeNode::make_from_oop(this, buffer, type->inline_klass()));
3010   return true;
3011 }
3012 
3013 //----------------------------inline_unsafe_load_store----------------------------
3014 // This method serves a couple of different customers (depending on LoadStoreKind):
3015 //
3016 // LS_cmp_swap:
3017 //
3018 //   boolean compareAndSetReference(Object o, long offset, Object expected, Object x);
3019 //   boolean compareAndSetInt(   Object o, long offset, int    expected, int    x);
3020 //   boolean compareAndSetLong(  Object o, long offset, long   expected, long   x);
3021 //
3022 // LS_cmp_swap_weak:
3023 //
3024 //   boolean weakCompareAndSetReference(       Object o, long offset, Object expected, Object x);
3025 //   boolean weakCompareAndSetReferencePlain(  Object o, long offset, Object expected, Object x);
3026 //   boolean weakCompareAndSetReferenceAcquire(Object o, long offset, Object expected, Object x);
3027 //   boolean weakCompareAndSetReferenceRelease(Object o, long offset, Object expected, Object x);
3028 //
3029 //   boolean weakCompareAndSetInt(          Object o, long offset, int    expected, int    x);
3030 //   boolean weakCompareAndSetIntPlain(     Object o, long offset, int    expected, int    x);
3031 //   boolean weakCompareAndSetIntAcquire(   Object o, long offset, int    expected, int    x);
3032 //   boolean weakCompareAndSetIntRelease(   Object o, long offset, int    expected, int    x);
3033 //
3034 //   boolean weakCompareAndSetLong(         Object o, long offset, long   expected, long   x);
3035 //   boolean weakCompareAndSetLongPlain(    Object o, long offset, long   expected, long   x);
3036 //   boolean weakCompareAndSetLongAcquire(  Object o, long offset, long   expected, long   x);
3037 //   boolean weakCompareAndSetLongRelease(  Object o, long offset, long   expected, long   x);
3038 //
3039 // LS_cmp_exchange:
3040 //
3041 //   Object compareAndExchangeReferenceVolatile(Object o, long offset, Object expected, Object x);
3042 //   Object compareAndExchangeReferenceAcquire( Object o, long offset, Object expected, Object x);
3043 //   Object compareAndExchangeReferenceRelease( Object o, long offset, Object expected, Object x);
3044 //
3045 //   Object compareAndExchangeIntVolatile(   Object o, long offset, Object expected, Object x);
3046 //   Object compareAndExchangeIntAcquire(    Object o, long offset, Object expected, Object x);
3047 //   Object compareAndExchangeIntRelease(    Object o, long offset, Object expected, Object x);
3048 //
3049 //   Object compareAndExchangeLongVolatile(  Object o, long offset, Object expected, Object x);
3050 //   Object compareAndExchangeLongAcquire(   Object o, long offset, Object expected, Object x);
3051 //   Object compareAndExchangeLongRelease(   Object o, long offset, Object expected, Object x);
3052 //
3053 // LS_get_add:
3054 //
3055 //   int  getAndAddInt( Object o, long offset, int  delta)
3056 //   long getAndAddLong(Object o, long offset, long delta)
3057 //
3058 // LS_get_set:
3059 //
3060 //   int    getAndSet(Object o, long offset, int    newValue)
3061 //   long   getAndSet(Object o, long offset, long   newValue)
3062 //   Object getAndSet(Object o, long offset, Object newValue)
3063 //
3064 bool LibraryCallKit::inline_unsafe_load_store(const BasicType type, const LoadStoreKind kind, const AccessKind access_kind) {
3065   // This basic scheme here is the same as inline_unsafe_access, but
3066   // differs in enough details that combining them would make the code
3067   // overly confusing.  (This is a true fact! I originally combined
3068   // them, but even I was confused by it!) As much code/comments as
3069   // possible are retained from inline_unsafe_access though to make
3070   // the correspondences clearer. - dl
3071 
3072   if (callee()->is_static())  return false;  // caller must have the capability!
3073 
3074   DecoratorSet decorators = C2_UNSAFE_ACCESS;
3075   decorators |= mo_decorator_for_access_kind(access_kind);
3076 
3077 #ifndef PRODUCT
3078   BasicType rtype;
3079   {
3080     ResourceMark rm;
3081     // Check the signatures.
3082     ciSignature* sig = callee()->signature();
3083     rtype = sig->return_type()->basic_type();
3084     switch(kind) {
3085       case LS_get_add:
3086       case LS_get_set: {
3087       // Check the signatures.
3088 #ifdef ASSERT
3089       assert(rtype == type, "get and set must return the expected type");
3090       assert(sig->count() == 3, "get and set has 3 arguments");
3091       assert(sig->type_at(0)->basic_type() == T_OBJECT, "get and set base is object");
3092       assert(sig->type_at(1)->basic_type() == T_LONG, "get and set offset is long");
3093       assert(sig->type_at(2)->basic_type() == type, "get and set must take expected type as new value/delta");
3094       assert(access_kind == Volatile, "mo is not passed to intrinsic nodes in current implementation");
3095 #endif // ASSERT
3096         break;
3097       }
3098       case LS_cmp_swap:
3099       case LS_cmp_swap_weak: {
3100       // Check the signatures.
3101 #ifdef ASSERT
3102       assert(rtype == T_BOOLEAN, "CAS must return boolean");
3103       assert(sig->count() == 4, "CAS has 4 arguments");
3104       assert(sig->type_at(0)->basic_type() == T_OBJECT, "CAS base is object");
3105       assert(sig->type_at(1)->basic_type() == T_LONG, "CAS offset is long");
3106 #endif // ASSERT
3107         break;
3108       }
3109       case LS_cmp_exchange: {
3110       // Check the signatures.
3111 #ifdef ASSERT
3112       assert(rtype == type, "CAS must return the expected type");
3113       assert(sig->count() == 4, "CAS has 4 arguments");
3114       assert(sig->type_at(0)->basic_type() == T_OBJECT, "CAS base is object");
3115       assert(sig->type_at(1)->basic_type() == T_LONG, "CAS offset is long");
3116 #endif // ASSERT
3117         break;
3118       }
3119       default:
3120         ShouldNotReachHere();
3121     }
3122   }
3123 #endif //PRODUCT
3124 
3125   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
3126 
3127   // Get arguments:
3128   Node* receiver = nullptr;
3129   Node* base     = nullptr;
3130   Node* offset   = nullptr;
3131   Node* oldval   = nullptr;
3132   Node* newval   = nullptr;
3133   switch(kind) {
3134     case LS_cmp_swap:
3135     case LS_cmp_swap_weak:
3136     case LS_cmp_exchange: {
3137       const bool two_slot_type = type2size[type] == 2;
3138       receiver = argument(0);  // type: oop
3139       base     = argument(1);  // type: oop
3140       offset   = argument(2);  // type: long
3141       oldval   = argument(4);  // type: oop, int, or long
3142       newval   = argument(two_slot_type ? 6 : 5);  // type: oop, int, or long
3143       break;
3144     }
3145     case LS_get_add:
3146     case LS_get_set: {
3147       receiver = argument(0);  // type: oop
3148       base     = argument(1);  // type: oop
3149       offset   = argument(2);  // type: long
3150       oldval   = nullptr;
3151       newval   = argument(4);  // type: oop, int, or long
3152       break;
3153     }
3154     default:
3155       ShouldNotReachHere();
3156   }
3157 
3158   // Build field offset expression.
3159   // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
3160   // to be plain byte offsets, which are also the same as those accepted
3161   // by oopDesc::field_addr.
3162   assert(Unsafe_field_offset_to_byte_offset(11) == 11, "fieldOffset must be byte-scaled");
3163   // 32-bit machines ignore the high half of long offsets
3164   offset = ConvL2X(offset);
3165   // Save state and restore on bailout
3166   SavedState old_state(this);
3167   Node* adr = make_unsafe_address(base, offset,type, false);
3168   const TypePtr *adr_type = _gvn.type(adr)->isa_ptr();
3169 
3170   Compile::AliasType* alias_type = C->alias_type(adr_type);
3171   BasicType bt = alias_type->basic_type();
3172   if (bt != T_ILLEGAL &&
3173       (is_reference_type(bt) != (type == T_OBJECT))) {
3174     // Don't intrinsify mismatched object accesses.
3175     return false;
3176   }
3177 
3178   old_state.discard();
3179 
3180   // For CAS, unlike inline_unsafe_access, there seems no point in
3181   // trying to refine types. Just use the coarse types here.
3182   assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
3183   const Type *value_type = Type::get_const_basic_type(type);
3184 
3185   switch (kind) {
3186     case LS_get_set:
3187     case LS_cmp_exchange: {
3188       if (type == T_OBJECT) {
3189         const TypeOopPtr* tjp = sharpen_unsafe_type(alias_type, adr_type);
3190         if (tjp != nullptr) {
3191           value_type = tjp;
3192         }
3193       }
3194       break;
3195     }
3196     case LS_cmp_swap:
3197     case LS_cmp_swap_weak:
3198     case LS_get_add:
3199       break;
3200     default:
3201       ShouldNotReachHere();
3202   }
3203 
3204   // Null check receiver.
3205   receiver = null_check(receiver);
3206   if (stopped()) {
3207     return true;
3208   }
3209 
3210   int alias_idx = C->get_alias_index(adr_type);
3211 
3212   if (is_reference_type(type)) {
3213     decorators |= IN_HEAP | ON_UNKNOWN_OOP_REF;
3214 
3215     if (oldval != nullptr && oldval->is_InlineType()) {
3216       // Re-execute the unsafe access if allocation triggers deoptimization.
3217       PreserveReexecuteState preexecs(this);
3218       jvms()->set_should_reexecute(true);
3219       oldval = oldval->as_InlineType()->buffer(this)->get_oop();
3220     }
3221     if (newval != nullptr && newval->is_InlineType()) {
3222       // Re-execute the unsafe access if allocation triggers deoptimization.
3223       PreserveReexecuteState preexecs(this);
3224       jvms()->set_should_reexecute(true);
3225       newval = newval->as_InlineType()->buffer(this)->get_oop();
3226     }
3227 
3228     // Transformation of a value which could be null pointer (CastPP #null)
3229     // could be delayed during Parse (for example, in adjust_map_after_if()).
3230     // Execute transformation here to avoid barrier generation in such case.
3231     if (_gvn.type(newval) == TypePtr::NULL_PTR)
3232       newval = _gvn.makecon(TypePtr::NULL_PTR);
3233 
3234     if (oldval != nullptr && _gvn.type(oldval) == TypePtr::NULL_PTR) {
3235       // Refine the value to a null constant, when it is known to be null
3236       oldval = _gvn.makecon(TypePtr::NULL_PTR);
3237     }
3238   }
3239 
3240   Node* result = nullptr;
3241   switch (kind) {
3242     case LS_cmp_exchange: {
3243       result = access_atomic_cmpxchg_val_at(base, adr, adr_type, alias_idx,
3244                                             oldval, newval, value_type, type, decorators);
3245       break;
3246     }
3247     case LS_cmp_swap_weak:
3248       decorators |= C2_WEAK_CMPXCHG;
3249     case LS_cmp_swap: {
3250       result = access_atomic_cmpxchg_bool_at(base, adr, adr_type, alias_idx,
3251                                              oldval, newval, value_type, type, decorators);
3252       break;
3253     }
3254     case LS_get_set: {
3255       result = access_atomic_xchg_at(base, adr, adr_type, alias_idx,
3256                                      newval, value_type, type, decorators);
3257       break;
3258     }
3259     case LS_get_add: {
3260       result = access_atomic_add_at(base, adr, adr_type, alias_idx,
3261                                     newval, value_type, type, decorators);
3262       break;
3263     }
3264     default:
3265       ShouldNotReachHere();
3266   }
3267 
3268   assert(type2size[result->bottom_type()->basic_type()] == type2size[rtype], "result type should match");
3269   set_result(result);
3270   return true;
3271 }
3272 
3273 bool LibraryCallKit::inline_unsafe_fence(vmIntrinsics::ID id) {
3274   // Regardless of form, don't allow previous ld/st to move down,
3275   // then issue acquire, release, or volatile mem_bar.
3276   insert_mem_bar(Op_MemBarCPUOrder);
3277   switch(id) {
3278     case vmIntrinsics::_loadFence:
3279       insert_mem_bar(Op_LoadFence);
3280       return true;
3281     case vmIntrinsics::_storeFence:
3282       insert_mem_bar(Op_StoreFence);
3283       return true;
3284     case vmIntrinsics::_storeStoreFence:
3285       insert_mem_bar(Op_StoreStoreFence);
3286       return true;
3287     case vmIntrinsics::_fullFence:
3288       insert_mem_bar(Op_MemBarVolatile);
3289       return true;
3290     default:
3291       fatal_unexpected_iid(id);
3292       return false;
3293   }
3294 }
3295 
3296 bool LibraryCallKit::inline_onspinwait() {
3297   insert_mem_bar(Op_OnSpinWait);
3298   return true;
3299 }
3300 
3301 bool LibraryCallKit::klass_needs_init_guard(Node* kls) {
3302   if (!kls->is_Con()) {
3303     return true;
3304   }
3305   const TypeInstKlassPtr* klsptr = kls->bottom_type()->isa_instklassptr();
3306   if (klsptr == nullptr) {
3307     return true;
3308   }
3309   ciInstanceKlass* ik = klsptr->instance_klass();
3310   // don't need a guard for a klass that is already initialized
3311   return !ik->is_initialized();
3312 }
3313 
3314 //----------------------------inline_unsafe_writeback0-------------------------
3315 // public native void Unsafe.writeback0(long address)
3316 bool LibraryCallKit::inline_unsafe_writeback0() {
3317   if (!Matcher::has_match_rule(Op_CacheWB)) {
3318     return false;
3319   }
3320 #ifndef PRODUCT
3321   assert(Matcher::has_match_rule(Op_CacheWBPreSync), "found match rule for CacheWB but not CacheWBPreSync");
3322   assert(Matcher::has_match_rule(Op_CacheWBPostSync), "found match rule for CacheWB but not CacheWBPostSync");
3323   ciSignature* sig = callee()->signature();
3324   assert(sig->type_at(0)->basic_type() == T_LONG, "Unsafe_writeback0 address is long!");
3325 #endif
3326   null_check_receiver();  // null-check, then ignore
3327   Node *addr = argument(1);
3328   addr = new CastX2PNode(addr);
3329   addr = _gvn.transform(addr);
3330   Node *flush = new CacheWBNode(control(), memory(TypeRawPtr::BOTTOM), addr);
3331   flush = _gvn.transform(flush);
3332   set_memory(flush, TypeRawPtr::BOTTOM);
3333   return true;
3334 }
3335 
3336 //----------------------------inline_unsafe_writeback0-------------------------
3337 // public native void Unsafe.writeback0(long address)
3338 bool LibraryCallKit::inline_unsafe_writebackSync0(bool is_pre) {
3339   if (is_pre && !Matcher::has_match_rule(Op_CacheWBPreSync)) {
3340     return false;
3341   }
3342   if (!is_pre && !Matcher::has_match_rule(Op_CacheWBPostSync)) {
3343     return false;
3344   }
3345 #ifndef PRODUCT
3346   assert(Matcher::has_match_rule(Op_CacheWB),
3347          (is_pre ? "found match rule for CacheWBPreSync but not CacheWB"
3348                 : "found match rule for CacheWBPostSync but not CacheWB"));
3349 
3350 #endif
3351   null_check_receiver();  // null-check, then ignore
3352   Node *sync;
3353   if (is_pre) {
3354     sync = new CacheWBPreSyncNode(control(), memory(TypeRawPtr::BOTTOM));
3355   } else {
3356     sync = new CacheWBPostSyncNode(control(), memory(TypeRawPtr::BOTTOM));
3357   }
3358   sync = _gvn.transform(sync);
3359   set_memory(sync, TypeRawPtr::BOTTOM);
3360   return true;
3361 }
3362 
3363 //----------------------------inline_unsafe_allocate---------------------------
3364 // public native Object Unsafe.allocateInstance(Class<?> cls);
3365 bool LibraryCallKit::inline_unsafe_allocate() {
3366 
3367 #if INCLUDE_JVMTI
3368   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
3369     return false;
3370   }
3371 #endif //INCLUDE_JVMTI
3372 
3373   if (callee()->is_static())  return false;  // caller must have the capability!
3374 
3375   null_check_receiver();  // null-check, then ignore
3376   Node* cls = null_check(argument(1));
3377   if (stopped())  return true;
3378 
3379   Node* kls = load_klass_from_mirror(cls, false, nullptr, 0);
3380   kls = null_check(kls);
3381   if (stopped())  return true;  // argument was like int.class
3382 
3383 #if INCLUDE_JVMTI
3384     // Don't try to access new allocated obj in the intrinsic.
3385     // It causes perfomance issues even when jvmti event VmObjectAlloc is disabled.
3386     // Deoptimize and allocate in interpreter instead.
3387     Node* addr = makecon(TypeRawPtr::make((address) &JvmtiExport::_should_notify_object_alloc));
3388     Node* should_post_vm_object_alloc = make_load(this->control(), addr, TypeInt::INT, T_INT, MemNode::unordered);
3389     Node* chk = _gvn.transform(new CmpINode(should_post_vm_object_alloc, intcon(0)));
3390     Node* tst = _gvn.transform(new BoolNode(chk, BoolTest::eq));
3391     {
3392       BuildCutout unless(this, tst, PROB_MAX);
3393       uncommon_trap(Deoptimization::Reason_intrinsic,
3394                     Deoptimization::Action_make_not_entrant);
3395     }
3396     if (stopped()) {
3397       return true;
3398     }
3399 #endif //INCLUDE_JVMTI
3400 
3401   Node* test = nullptr;
3402   if (LibraryCallKit::klass_needs_init_guard(kls)) {
3403     // Note:  The argument might still be an illegal value like
3404     // Serializable.class or Object[].class.   The runtime will handle it.
3405     // But we must make an explicit check for initialization.
3406     Node* insp = basic_plus_adr(kls, in_bytes(InstanceKlass::init_state_offset()));
3407     // Use T_BOOLEAN for InstanceKlass::_init_state so the compiler
3408     // can generate code to load it as unsigned byte.
3409     Node* inst = make_load(nullptr, insp, TypeInt::UBYTE, T_BOOLEAN, MemNode::acquire);
3410     Node* bits = intcon(InstanceKlass::fully_initialized);
3411     test = _gvn.transform(new SubINode(inst, bits));
3412     // The 'test' is non-zero if we need to take a slow path.
3413   }
3414   Node* obj = nullptr;
3415   const TypeInstKlassPtr* tkls = _gvn.type(kls)->isa_instklassptr();
3416   if (tkls != nullptr && tkls->instance_klass()->is_inlinetype()) {
3417     obj = InlineTypeNode::make_all_zero(_gvn, tkls->instance_klass()->as_inline_klass())->buffer(this);
3418   } else {
3419     obj = new_instance(kls, test);
3420   }
3421   set_result(obj);
3422   return true;
3423 }
3424 
3425 //------------------------inline_native_time_funcs--------------
3426 // inline code for System.currentTimeMillis() and System.nanoTime()
3427 // these have the same type and signature
3428 bool LibraryCallKit::inline_native_time_funcs(address funcAddr, const char* funcName) {
3429   const TypeFunc* tf = OptoRuntime::void_long_Type();
3430   const TypePtr* no_memory_effects = nullptr;
3431   Node* time = make_runtime_call(RC_LEAF, tf, funcAddr, funcName, no_memory_effects);
3432   Node* value = _gvn.transform(new ProjNode(time, TypeFunc::Parms+0));
3433 #ifdef ASSERT
3434   Node* value_top = _gvn.transform(new ProjNode(time, TypeFunc::Parms+1));
3435   assert(value_top == top(), "second value must be top");
3436 #endif
3437   set_result(value);
3438   return true;
3439 }
3440 
3441 
3442 #if INCLUDE_JVMTI
3443 
3444 // When notifications are disabled then just update the VTMS transition bit and return.
3445 // Otherwise, the bit is updated in the given function call implementing JVMTI notification protocol.
3446 bool LibraryCallKit::inline_native_notify_jvmti_funcs(address funcAddr, const char* funcName, bool is_start, bool is_end) {
3447   if (!DoJVMTIVirtualThreadTransitions) {
3448     return true;
3449   }
3450   Node* vt_oop = _gvn.transform(must_be_not_null(argument(0), true)); // VirtualThread this argument
3451   IdealKit ideal(this);
3452 
3453   Node* ONE = ideal.ConI(1);
3454   Node* hide = is_start ? ideal.ConI(0) : (is_end ? ideal.ConI(1) : _gvn.transform(argument(1)));
3455   Node* addr = makecon(TypeRawPtr::make((address)&JvmtiVTMSTransitionDisabler::_VTMS_notify_jvmti_events));
3456   Node* notify_jvmti_enabled = ideal.load(ideal.ctrl(), addr, TypeInt::BOOL, T_BOOLEAN, Compile::AliasIdxRaw);
3457 
3458   ideal.if_then(notify_jvmti_enabled, BoolTest::eq, ONE); {
3459     sync_kit(ideal);
3460     // if notifyJvmti enabled then make a call to the given SharedRuntime function
3461     const TypeFunc* tf = OptoRuntime::notify_jvmti_vthread_Type();
3462     make_runtime_call(RC_NO_LEAF, tf, funcAddr, funcName, TypePtr::BOTTOM, vt_oop, hide);
3463     ideal.sync_kit(this);
3464   } ideal.else_(); {
3465     // set hide value to the VTMS transition bit in current JavaThread and VirtualThread object
3466     Node* thread = ideal.thread();
3467     Node* jt_addr = basic_plus_adr(thread, in_bytes(JavaThread::is_in_VTMS_transition_offset()));
3468     Node* vt_addr = basic_plus_adr(vt_oop, java_lang_Thread::is_in_VTMS_transition_offset());
3469 
3470     sync_kit(ideal);
3471     access_store_at(nullptr, jt_addr, _gvn.type(jt_addr)->is_ptr(), hide, _gvn.type(hide), T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
3472     access_store_at(nullptr, vt_addr, _gvn.type(vt_addr)->is_ptr(), hide, _gvn.type(hide), T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
3473 
3474     ideal.sync_kit(this);
3475   } ideal.end_if();
3476   final_sync(ideal);
3477 
3478   return true;
3479 }
3480 
3481 // Always update the is_disable_suspend bit.
3482 bool LibraryCallKit::inline_native_notify_jvmti_sync() {
3483   if (!DoJVMTIVirtualThreadTransitions) {
3484     return true;
3485   }
3486   IdealKit ideal(this);
3487 
3488   {
3489     // unconditionally update the is_disable_suspend bit in current JavaThread
3490     Node* thread = ideal.thread();
3491     Node* arg = _gvn.transform(argument(0)); // argument for notification
3492     Node* addr = basic_plus_adr(thread, in_bytes(JavaThread::is_disable_suspend_offset()));
3493     const TypePtr *addr_type = _gvn.type(addr)->isa_ptr();
3494 
3495     sync_kit(ideal);
3496     access_store_at(nullptr, addr, addr_type, arg, _gvn.type(arg), T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
3497     ideal.sync_kit(this);
3498   }
3499   final_sync(ideal);
3500 
3501   return true;
3502 }
3503 
3504 #endif // INCLUDE_JVMTI
3505 
3506 #ifdef JFR_HAVE_INTRINSICS
3507 
3508 /**
3509  * if oop->klass != null
3510  *   // normal class
3511  *   epoch = _epoch_state ? 2 : 1
3512  *   if oop->klass->trace_id & ((epoch << META_SHIFT) | epoch)) != epoch {
3513  *     ... // enter slow path when the klass is first recorded or the epoch of JFR shifts
3514  *   }
3515  *   id = oop->klass->trace_id >> TRACE_ID_SHIFT // normal class path
3516  * else
3517  *   // primitive class
3518  *   if oop->array_klass != null
3519  *     id = (oop->array_klass->trace_id >> TRACE_ID_SHIFT) + 1 // primitive class path
3520  *   else
3521  *     id = LAST_TYPE_ID + 1 // void class path
3522  *   if (!signaled)
3523  *     signaled = true
3524  */
3525 bool LibraryCallKit::inline_native_classID() {
3526   Node* cls = argument(0);
3527 
3528   IdealKit ideal(this);
3529 #define __ ideal.
3530   IdealVariable result(ideal); __ declarations_done();
3531   Node* kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(),
3532                                                  basic_plus_adr(cls, java_lang_Class::klass_offset()),
3533                                                  TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
3534 
3535 
3536   __ if_then(kls, BoolTest::ne, null()); {
3537     Node* kls_trace_id_addr = basic_plus_adr(kls, in_bytes(KLASS_TRACE_ID_OFFSET));
3538     Node* kls_trace_id_raw = ideal.load(ideal.ctrl(), kls_trace_id_addr,TypeLong::LONG, T_LONG, Compile::AliasIdxRaw);
3539 
3540     Node* epoch_address = makecon(TypeRawPtr::make(JfrIntrinsicSupport::epoch_address()));
3541     Node* epoch = ideal.load(ideal.ctrl(), epoch_address, TypeInt::BOOL, T_BOOLEAN, Compile::AliasIdxRaw);
3542     epoch = _gvn.transform(new LShiftLNode(longcon(1), epoch));
3543     Node* mask = _gvn.transform(new LShiftLNode(epoch, intcon(META_SHIFT)));
3544     mask = _gvn.transform(new OrLNode(mask, epoch));
3545     Node* kls_trace_id_raw_and_mask = _gvn.transform(new AndLNode(kls_trace_id_raw, mask));
3546 
3547     float unlikely  = PROB_UNLIKELY(0.999);
3548     __ if_then(kls_trace_id_raw_and_mask, BoolTest::ne, epoch, unlikely); {
3549       sync_kit(ideal);
3550       make_runtime_call(RC_LEAF,
3551                         OptoRuntime::class_id_load_barrier_Type(),
3552                         CAST_FROM_FN_PTR(address, JfrIntrinsicSupport::load_barrier),
3553                         "class id load barrier",
3554                         TypePtr::BOTTOM,
3555                         kls);
3556       ideal.sync_kit(this);
3557     } __ end_if();
3558 
3559     ideal.set(result,  _gvn.transform(new URShiftLNode(kls_trace_id_raw, ideal.ConI(TRACE_ID_SHIFT))));
3560   } __ else_(); {
3561     Node* array_kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(),
3562                                                    basic_plus_adr(cls, java_lang_Class::array_klass_offset()),
3563                                                    TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
3564     __ if_then(array_kls, BoolTest::ne, null()); {
3565       Node* array_kls_trace_id_addr = basic_plus_adr(array_kls, in_bytes(KLASS_TRACE_ID_OFFSET));
3566       Node* array_kls_trace_id_raw = ideal.load(ideal.ctrl(), array_kls_trace_id_addr, TypeLong::LONG, T_LONG, Compile::AliasIdxRaw);
3567       Node* array_kls_trace_id = _gvn.transform(new URShiftLNode(array_kls_trace_id_raw, ideal.ConI(TRACE_ID_SHIFT)));
3568       ideal.set(result, _gvn.transform(new AddLNode(array_kls_trace_id, longcon(1))));
3569     } __ else_(); {
3570       // void class case
3571       ideal.set(result, _gvn.transform(longcon(LAST_TYPE_ID + 1)));
3572     } __ end_if();
3573 
3574     Node* signaled_flag_address = makecon(TypeRawPtr::make(JfrIntrinsicSupport::signal_address()));
3575     Node* signaled = ideal.load(ideal.ctrl(), signaled_flag_address, TypeInt::BOOL, T_BOOLEAN, Compile::AliasIdxRaw, true, MemNode::acquire);
3576     __ if_then(signaled, BoolTest::ne, ideal.ConI(1)); {
3577       ideal.store(ideal.ctrl(), signaled_flag_address, ideal.ConI(1), T_BOOLEAN, Compile::AliasIdxRaw, MemNode::release, true);
3578     } __ end_if();
3579   } __ end_if();
3580 
3581   final_sync(ideal);
3582   set_result(ideal.value(result));
3583 #undef __
3584   return true;
3585 }
3586 
3587 //------------------------inline_native_jvm_commit------------------
3588 bool LibraryCallKit::inline_native_jvm_commit() {
3589   enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
3590 
3591   // Save input memory and i_o state.
3592   Node* input_memory_state = reset_memory();
3593   set_all_memory(input_memory_state);
3594   Node* input_io_state = i_o();
3595 
3596   // TLS.
3597   Node* tls_ptr = _gvn.transform(new ThreadLocalNode());
3598   // Jfr java buffer.
3599   Node* java_buffer_offset = _gvn.transform(new AddPNode(top(), tls_ptr, _gvn.transform(MakeConX(in_bytes(JAVA_BUFFER_OFFSET_JFR)))));
3600   Node* java_buffer = _gvn.transform(new LoadPNode(control(), input_memory_state, java_buffer_offset, TypePtr::BOTTOM, TypeRawPtr::NOTNULL, MemNode::unordered));
3601   Node* java_buffer_pos_offset = _gvn.transform(new AddPNode(top(), java_buffer, _gvn.transform(MakeConX(in_bytes(JFR_BUFFER_POS_OFFSET)))));
3602 
3603   // Load the current value of the notified field in the JfrThreadLocal.
3604   Node* notified_offset = basic_plus_adr(top(), tls_ptr, in_bytes(NOTIFY_OFFSET_JFR));
3605   Node* notified = make_load(control(), notified_offset, TypeInt::BOOL, T_BOOLEAN, MemNode::unordered);
3606 
3607   // Test for notification.
3608   Node* notified_cmp = _gvn.transform(new CmpINode(notified, _gvn.intcon(1)));
3609   Node* test_notified = _gvn.transform(new BoolNode(notified_cmp, BoolTest::eq));
3610   IfNode* iff_notified = create_and_map_if(control(), test_notified, PROB_MIN, COUNT_UNKNOWN);
3611 
3612   // True branch, is notified.
3613   Node* is_notified = _gvn.transform(new IfTrueNode(iff_notified));
3614   set_control(is_notified);
3615 
3616   // Reset notified state.
3617   store_to_memory(control(), notified_offset, _gvn.intcon(0), T_BOOLEAN, MemNode::unordered);
3618   Node* notified_reset_memory = reset_memory();
3619 
3620   // 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.
3621   Node* current_pos_X = _gvn.transform(new LoadXNode(control(), input_memory_state, java_buffer_pos_offset, TypeRawPtr::NOTNULL, TypeX_X, MemNode::unordered));
3622   // Convert the machine-word to a long.
3623   Node* current_pos = _gvn.transform(ConvX2L(current_pos_X));
3624 
3625   // False branch, not notified.
3626   Node* not_notified = _gvn.transform(new IfFalseNode(iff_notified));
3627   set_control(not_notified);
3628   set_all_memory(input_memory_state);
3629 
3630   // Arg is the next position as a long.
3631   Node* arg = argument(0);
3632   // Convert long to machine-word.
3633   Node* next_pos_X = _gvn.transform(ConvL2X(arg));
3634 
3635   // Store the next_position to the underlying jfr java buffer.
3636   store_to_memory(control(), java_buffer_pos_offset, next_pos_X, LP64_ONLY(T_LONG) NOT_LP64(T_INT), MemNode::release);
3637 
3638   Node* commit_memory = reset_memory();
3639   set_all_memory(commit_memory);
3640 
3641   // 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.
3642   Node* java_buffer_flags_offset = _gvn.transform(new AddPNode(top(), java_buffer, _gvn.transform(MakeConX(in_bytes(JFR_BUFFER_FLAGS_OFFSET)))));
3643   Node* flags = make_load(control(), java_buffer_flags_offset, TypeInt::UBYTE, T_BYTE, MemNode::unordered);
3644   Node* lease_constant = _gvn.transform(_gvn.intcon(4));
3645 
3646   // And flags with lease constant.
3647   Node* lease = _gvn.transform(new AndINode(flags, lease_constant));
3648 
3649   // Branch on lease to conditionalize returning the leased java buffer.
3650   Node* lease_cmp = _gvn.transform(new CmpINode(lease, lease_constant));
3651   Node* test_lease = _gvn.transform(new BoolNode(lease_cmp, BoolTest::eq));
3652   IfNode* iff_lease = create_and_map_if(control(), test_lease, PROB_MIN, COUNT_UNKNOWN);
3653 
3654   // False branch, not a lease.
3655   Node* not_lease = _gvn.transform(new IfFalseNode(iff_lease));
3656 
3657   // True branch, is lease.
3658   Node* is_lease = _gvn.transform(new IfTrueNode(iff_lease));
3659   set_control(is_lease);
3660 
3661   // Make a runtime call, which can safepoint, to return the leased buffer. This updates both the JfrThreadLocal and the Java event writer oop.
3662   Node* call_return_lease = make_runtime_call(RC_NO_LEAF,
3663                                               OptoRuntime::void_void_Type(),
3664                                               SharedRuntime::jfr_return_lease(),
3665                                               "return_lease", TypePtr::BOTTOM);
3666   Node* call_return_lease_control = _gvn.transform(new ProjNode(call_return_lease, TypeFunc::Control));
3667 
3668   RegionNode* lease_compare_rgn = new RegionNode(PATH_LIMIT);
3669   record_for_igvn(lease_compare_rgn);
3670   PhiNode* lease_compare_mem = new PhiNode(lease_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3671   record_for_igvn(lease_compare_mem);
3672   PhiNode* lease_compare_io = new PhiNode(lease_compare_rgn, Type::ABIO);
3673   record_for_igvn(lease_compare_io);
3674   PhiNode* lease_result_value = new PhiNode(lease_compare_rgn, TypeLong::LONG);
3675   record_for_igvn(lease_result_value);
3676 
3677   // Update control and phi nodes.
3678   lease_compare_rgn->init_req(_true_path, call_return_lease_control);
3679   lease_compare_rgn->init_req(_false_path, not_lease);
3680 
3681   lease_compare_mem->init_req(_true_path, _gvn.transform(reset_memory()));
3682   lease_compare_mem->init_req(_false_path, commit_memory);
3683 
3684   lease_compare_io->init_req(_true_path, i_o());
3685   lease_compare_io->init_req(_false_path, input_io_state);
3686 
3687   lease_result_value->init_req(_true_path, _gvn.longcon(0)); // if the lease was returned, return 0L.
3688   lease_result_value->init_req(_false_path, arg); // if not lease, return new updated position.
3689 
3690   RegionNode* result_rgn = new RegionNode(PATH_LIMIT);
3691   PhiNode* result_mem = new PhiNode(result_rgn, Type::MEMORY, TypePtr::BOTTOM);
3692   PhiNode* result_io = new PhiNode(result_rgn, Type::ABIO);
3693   PhiNode* result_value = new PhiNode(result_rgn, TypeLong::LONG);
3694 
3695   // Update control and phi nodes.
3696   result_rgn->init_req(_true_path, is_notified);
3697   result_rgn->init_req(_false_path, _gvn.transform(lease_compare_rgn));
3698 
3699   result_mem->init_req(_true_path, notified_reset_memory);
3700   result_mem->init_req(_false_path, _gvn.transform(lease_compare_mem));
3701 
3702   result_io->init_req(_true_path, input_io_state);
3703   result_io->init_req(_false_path, _gvn.transform(lease_compare_io));
3704 
3705   result_value->init_req(_true_path, current_pos);
3706   result_value->init_req(_false_path, _gvn.transform(lease_result_value));
3707 
3708   // Set output state.
3709   set_control(_gvn.transform(result_rgn));
3710   set_all_memory(_gvn.transform(result_mem));
3711   set_i_o(_gvn.transform(result_io));
3712   set_result(result_rgn, result_value);
3713   return true;
3714 }
3715 
3716 /*
3717  * The intrinsic is a model of this pseudo-code:
3718  *
3719  * JfrThreadLocal* const tl = Thread::jfr_thread_local()
3720  * jobject h_event_writer = tl->java_event_writer();
3721  * if (h_event_writer == nullptr) {
3722  *   return nullptr;
3723  * }
3724  * oop threadObj = Thread::threadObj();
3725  * oop vthread = java_lang_Thread::vthread(threadObj);
3726  * traceid tid;
3727  * bool pinVirtualThread;
3728  * bool excluded;
3729  * if (vthread != threadObj) {  // i.e. current thread is virtual
3730  *   tid = java_lang_Thread::tid(vthread);
3731  *   u2 vthread_epoch_raw = java_lang_Thread::jfr_epoch(vthread);
3732  *   pinVirtualThread = VMContinuations;
3733  *   excluded = vthread_epoch_raw & excluded_mask;
3734  *   if (!excluded) {
3735  *     traceid current_epoch = JfrTraceIdEpoch::current_generation();
3736  *     u2 vthread_epoch = vthread_epoch_raw & epoch_mask;
3737  *     if (vthread_epoch != current_epoch) {
3738  *       write_checkpoint();
3739  *     }
3740  *   }
3741  * } else {
3742  *   tid = java_lang_Thread::tid(threadObj);
3743  *   u2 thread_epoch_raw = java_lang_Thread::jfr_epoch(threadObj);
3744  *   pinVirtualThread = false;
3745  *   excluded = thread_epoch_raw & excluded_mask;
3746  * }
3747  * oop event_writer = JNIHandles::resolve_non_null(h_event_writer);
3748  * traceid tid_in_event_writer = getField(event_writer, "threadID");
3749  * if (tid_in_event_writer != tid) {
3750  *   setField(event_writer, "pinVirtualThread", pinVirtualThread);
3751  *   setField(event_writer, "excluded", excluded);
3752  *   setField(event_writer, "threadID", tid);
3753  * }
3754  * return event_writer
3755  */
3756 bool LibraryCallKit::inline_native_getEventWriter() {
3757   enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
3758 
3759   // Save input memory and i_o state.
3760   Node* input_memory_state = reset_memory();
3761   set_all_memory(input_memory_state);
3762   Node* input_io_state = i_o();
3763 
3764   // The most significant bit of the u2 is used to denote thread exclusion
3765   Node* excluded_shift = _gvn.intcon(15);
3766   Node* excluded_mask = _gvn.intcon(1 << 15);
3767   // The epoch generation is the range [1-32767]
3768   Node* epoch_mask = _gvn.intcon(32767);
3769 
3770   // TLS
3771   Node* tls_ptr = _gvn.transform(new ThreadLocalNode());
3772 
3773   // Load the address of java event writer jobject handle from the jfr_thread_local structure.
3774   Node* jobj_ptr = basic_plus_adr(top(), tls_ptr, in_bytes(THREAD_LOCAL_WRITER_OFFSET_JFR));
3775 
3776   // Load the eventwriter jobject handle.
3777   Node* jobj = make_load(control(), jobj_ptr, TypeRawPtr::BOTTOM, T_ADDRESS, MemNode::unordered);
3778 
3779   // Null check the jobject handle.
3780   Node* jobj_cmp_null = _gvn.transform(new CmpPNode(jobj, null()));
3781   Node* test_jobj_not_equal_null = _gvn.transform(new BoolNode(jobj_cmp_null, BoolTest::ne));
3782   IfNode* iff_jobj_not_equal_null = create_and_map_if(control(), test_jobj_not_equal_null, PROB_MAX, COUNT_UNKNOWN);
3783 
3784   // False path, jobj is null.
3785   Node* jobj_is_null = _gvn.transform(new IfFalseNode(iff_jobj_not_equal_null));
3786 
3787   // True path, jobj is not null.
3788   Node* jobj_is_not_null = _gvn.transform(new IfTrueNode(iff_jobj_not_equal_null));
3789 
3790   set_control(jobj_is_not_null);
3791 
3792   // Load the threadObj for the CarrierThread.
3793   Node* threadObj = generate_current_thread(tls_ptr);
3794 
3795   // Load the vthread.
3796   Node* vthread = generate_virtual_thread(tls_ptr);
3797 
3798   // If vthread != threadObj, this is a virtual thread.
3799   Node* vthread_cmp_threadObj = _gvn.transform(new CmpPNode(vthread, threadObj));
3800   Node* test_vthread_not_equal_threadObj = _gvn.transform(new BoolNode(vthread_cmp_threadObj, BoolTest::ne));
3801   IfNode* iff_vthread_not_equal_threadObj =
3802     create_and_map_if(jobj_is_not_null, test_vthread_not_equal_threadObj, PROB_FAIR, COUNT_UNKNOWN);
3803 
3804   // False branch, fallback to threadObj.
3805   Node* vthread_equal_threadObj = _gvn.transform(new IfFalseNode(iff_vthread_not_equal_threadObj));
3806   set_control(vthread_equal_threadObj);
3807 
3808   // Load the tid field from the vthread object.
3809   Node* thread_obj_tid = load_field_from_object(threadObj, "tid", "J");
3810 
3811   // Load the raw epoch value from the threadObj.
3812   Node* threadObj_epoch_offset = basic_plus_adr(threadObj, java_lang_Thread::jfr_epoch_offset());
3813   Node* threadObj_epoch_raw = access_load_at(threadObj, threadObj_epoch_offset,
3814                                              _gvn.type(threadObj_epoch_offset)->isa_ptr(),
3815                                              TypeInt::CHAR, T_CHAR,
3816                                              IN_HEAP | MO_UNORDERED | C2_MISMATCHED | C2_CONTROL_DEPENDENT_LOAD);
3817 
3818   // Mask off the excluded information from the epoch.
3819   Node * threadObj_is_excluded = _gvn.transform(new AndINode(threadObj_epoch_raw, excluded_mask));
3820 
3821   // True branch, this is a virtual thread.
3822   Node* vthread_not_equal_threadObj = _gvn.transform(new IfTrueNode(iff_vthread_not_equal_threadObj));
3823   set_control(vthread_not_equal_threadObj);
3824 
3825   // Load the tid field from the vthread object.
3826   Node* vthread_tid = load_field_from_object(vthread, "tid", "J");
3827 
3828   // Continuation support determines if a virtual thread should be pinned.
3829   Node* global_addr = makecon(TypeRawPtr::make((address)&VMContinuations));
3830   Node* continuation_support = make_load(control(), global_addr, TypeInt::BOOL, T_BOOLEAN, MemNode::unordered);
3831 
3832   // Load the raw epoch value from the vthread.
3833   Node* vthread_epoch_offset = basic_plus_adr(vthread, java_lang_Thread::jfr_epoch_offset());
3834   Node* vthread_epoch_raw = access_load_at(vthread, vthread_epoch_offset, _gvn.type(vthread_epoch_offset)->is_ptr(),
3835                                            TypeInt::CHAR, T_CHAR,
3836                                            IN_HEAP | MO_UNORDERED | C2_MISMATCHED | C2_CONTROL_DEPENDENT_LOAD);
3837 
3838   // Mask off the excluded information from the epoch.
3839   Node * vthread_is_excluded = _gvn.transform(new AndINode(vthread_epoch_raw, _gvn.transform(excluded_mask)));
3840 
3841   // Branch on excluded to conditionalize updating the epoch for the virtual thread.
3842   Node* is_excluded_cmp = _gvn.transform(new CmpINode(vthread_is_excluded, _gvn.transform(excluded_mask)));
3843   Node* test_not_excluded = _gvn.transform(new BoolNode(is_excluded_cmp, BoolTest::ne));
3844   IfNode* iff_not_excluded = create_and_map_if(control(), test_not_excluded, PROB_MAX, COUNT_UNKNOWN);
3845 
3846   // False branch, vthread is excluded, no need to write epoch info.
3847   Node* excluded = _gvn.transform(new IfFalseNode(iff_not_excluded));
3848 
3849   // True branch, vthread is included, update epoch info.
3850   Node* included = _gvn.transform(new IfTrueNode(iff_not_excluded));
3851   set_control(included);
3852 
3853   // Get epoch value.
3854   Node* epoch = _gvn.transform(new AndINode(vthread_epoch_raw, _gvn.transform(epoch_mask)));
3855 
3856   // Load the current epoch generation. The value is unsigned 16-bit, so we type it as T_CHAR.
3857   Node* epoch_generation_address = makecon(TypeRawPtr::make(JfrIntrinsicSupport::epoch_generation_address()));
3858   Node* current_epoch_generation = make_load(control(), epoch_generation_address, TypeInt::CHAR, T_CHAR, MemNode::unordered);
3859 
3860   // Compare the epoch in the vthread to the current epoch generation.
3861   Node* const epoch_cmp = _gvn.transform(new CmpUNode(current_epoch_generation, epoch));
3862   Node* test_epoch_not_equal = _gvn.transform(new BoolNode(epoch_cmp, BoolTest::ne));
3863   IfNode* iff_epoch_not_equal = create_and_map_if(control(), test_epoch_not_equal, PROB_FAIR, COUNT_UNKNOWN);
3864 
3865   // False path, epoch is equal, checkpoint information is valid.
3866   Node* epoch_is_equal = _gvn.transform(new IfFalseNode(iff_epoch_not_equal));
3867 
3868   // True path, epoch is not equal, write a checkpoint for the vthread.
3869   Node* epoch_is_not_equal = _gvn.transform(new IfTrueNode(iff_epoch_not_equal));
3870 
3871   set_control(epoch_is_not_equal);
3872 
3873   // Make a runtime call, which can safepoint, to write a checkpoint for the vthread for this epoch.
3874   // The call also updates the native thread local thread id and the vthread with the current epoch.
3875   Node* call_write_checkpoint = make_runtime_call(RC_NO_LEAF,
3876                                                   OptoRuntime::jfr_write_checkpoint_Type(),
3877                                                   SharedRuntime::jfr_write_checkpoint(),
3878                                                   "write_checkpoint", TypePtr::BOTTOM);
3879   Node* call_write_checkpoint_control = _gvn.transform(new ProjNode(call_write_checkpoint, TypeFunc::Control));
3880 
3881   // vthread epoch != current epoch
3882   RegionNode* epoch_compare_rgn = new RegionNode(PATH_LIMIT);
3883   record_for_igvn(epoch_compare_rgn);
3884   PhiNode* epoch_compare_mem = new PhiNode(epoch_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3885   record_for_igvn(epoch_compare_mem);
3886   PhiNode* epoch_compare_io = new PhiNode(epoch_compare_rgn, Type::ABIO);
3887   record_for_igvn(epoch_compare_io);
3888 
3889   // Update control and phi nodes.
3890   epoch_compare_rgn->init_req(_true_path, call_write_checkpoint_control);
3891   epoch_compare_rgn->init_req(_false_path, epoch_is_equal);
3892   epoch_compare_mem->init_req(_true_path, _gvn.transform(reset_memory()));
3893   epoch_compare_mem->init_req(_false_path, input_memory_state);
3894   epoch_compare_io->init_req(_true_path, i_o());
3895   epoch_compare_io->init_req(_false_path, input_io_state);
3896 
3897   // excluded != true
3898   RegionNode* exclude_compare_rgn = new RegionNode(PATH_LIMIT);
3899   record_for_igvn(exclude_compare_rgn);
3900   PhiNode* exclude_compare_mem = new PhiNode(exclude_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3901   record_for_igvn(exclude_compare_mem);
3902   PhiNode* exclude_compare_io = new PhiNode(exclude_compare_rgn, Type::ABIO);
3903   record_for_igvn(exclude_compare_io);
3904 
3905   // Update control and phi nodes.
3906   exclude_compare_rgn->init_req(_true_path, _gvn.transform(epoch_compare_rgn));
3907   exclude_compare_rgn->init_req(_false_path, excluded);
3908   exclude_compare_mem->init_req(_true_path, _gvn.transform(epoch_compare_mem));
3909   exclude_compare_mem->init_req(_false_path, input_memory_state);
3910   exclude_compare_io->init_req(_true_path, _gvn.transform(epoch_compare_io));
3911   exclude_compare_io->init_req(_false_path, input_io_state);
3912 
3913   // vthread != threadObj
3914   RegionNode* vthread_compare_rgn = new RegionNode(PATH_LIMIT);
3915   record_for_igvn(vthread_compare_rgn);
3916   PhiNode* vthread_compare_mem = new PhiNode(vthread_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3917   PhiNode* vthread_compare_io = new PhiNode(vthread_compare_rgn, Type::ABIO);
3918   record_for_igvn(vthread_compare_io);
3919   PhiNode* tid = new PhiNode(vthread_compare_rgn, TypeLong::LONG);
3920   record_for_igvn(tid);
3921   PhiNode* exclusion = new PhiNode(vthread_compare_rgn, TypeInt::CHAR);
3922   record_for_igvn(exclusion);
3923   PhiNode* pinVirtualThread = new PhiNode(vthread_compare_rgn, TypeInt::BOOL);
3924   record_for_igvn(pinVirtualThread);
3925 
3926   // Update control and phi nodes.
3927   vthread_compare_rgn->init_req(_true_path, _gvn.transform(exclude_compare_rgn));
3928   vthread_compare_rgn->init_req(_false_path, vthread_equal_threadObj);
3929   vthread_compare_mem->init_req(_true_path, _gvn.transform(exclude_compare_mem));
3930   vthread_compare_mem->init_req(_false_path, input_memory_state);
3931   vthread_compare_io->init_req(_true_path, _gvn.transform(exclude_compare_io));
3932   vthread_compare_io->init_req(_false_path, input_io_state);
3933   tid->init_req(_true_path, _gvn.transform(vthread_tid));
3934   tid->init_req(_false_path, _gvn.transform(thread_obj_tid));
3935   exclusion->init_req(_true_path, _gvn.transform(vthread_is_excluded));
3936   exclusion->init_req(_false_path, _gvn.transform(threadObj_is_excluded));
3937   pinVirtualThread->init_req(_true_path, _gvn.transform(continuation_support));
3938   pinVirtualThread->init_req(_false_path, _gvn.intcon(0));
3939 
3940   // Update branch state.
3941   set_control(_gvn.transform(vthread_compare_rgn));
3942   set_all_memory(_gvn.transform(vthread_compare_mem));
3943   set_i_o(_gvn.transform(vthread_compare_io));
3944 
3945   // Load the event writer oop by dereferencing the jobject handle.
3946   ciKlass* klass_EventWriter = env()->find_system_klass(ciSymbol::make("jdk/jfr/internal/event/EventWriter"));
3947   assert(klass_EventWriter->is_loaded(), "invariant");
3948   ciInstanceKlass* const instklass_EventWriter = klass_EventWriter->as_instance_klass();
3949   const TypeKlassPtr* const aklass = TypeKlassPtr::make(instklass_EventWriter);
3950   const TypeOopPtr* const xtype = aklass->as_instance_type();
3951   Node* jobj_untagged = _gvn.transform(new AddPNode(top(), jobj, _gvn.MakeConX(-JNIHandles::TypeTag::global)));
3952   Node* event_writer = access_load(jobj_untagged, xtype, T_OBJECT, IN_NATIVE | C2_CONTROL_DEPENDENT_LOAD);
3953 
3954   // Load the current thread id from the event writer object.
3955   Node* const event_writer_tid = load_field_from_object(event_writer, "threadID", "J");
3956   // Get the field offset to, conditionally, store an updated tid value later.
3957   Node* const event_writer_tid_field = field_address_from_object(event_writer, "threadID", "J", false);
3958   // Get the field offset to, conditionally, store an updated exclusion value later.
3959   Node* const event_writer_excluded_field = field_address_from_object(event_writer, "excluded", "Z", false);
3960   // Get the field offset to, conditionally, store an updated pinVirtualThread value later.
3961   Node* const event_writer_pin_field = field_address_from_object(event_writer, "pinVirtualThread", "Z", false);
3962 
3963   RegionNode* event_writer_tid_compare_rgn = new RegionNode(PATH_LIMIT);
3964   record_for_igvn(event_writer_tid_compare_rgn);
3965   PhiNode* event_writer_tid_compare_mem = new PhiNode(event_writer_tid_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3966   record_for_igvn(event_writer_tid_compare_mem);
3967   PhiNode* event_writer_tid_compare_io = new PhiNode(event_writer_tid_compare_rgn, Type::ABIO);
3968   record_for_igvn(event_writer_tid_compare_io);
3969 
3970   // Compare the current tid from the thread object to what is currently stored in the event writer object.
3971   Node* const tid_cmp = _gvn.transform(new CmpLNode(event_writer_tid, _gvn.transform(tid)));
3972   Node* test_tid_not_equal = _gvn.transform(new BoolNode(tid_cmp, BoolTest::ne));
3973   IfNode* iff_tid_not_equal = create_and_map_if(_gvn.transform(vthread_compare_rgn), test_tid_not_equal, PROB_FAIR, COUNT_UNKNOWN);
3974 
3975   // False path, tids are the same.
3976   Node* tid_is_equal = _gvn.transform(new IfFalseNode(iff_tid_not_equal));
3977 
3978   // True path, tid is not equal, need to update the tid in the event writer.
3979   Node* tid_is_not_equal = _gvn.transform(new IfTrueNode(iff_tid_not_equal));
3980   record_for_igvn(tid_is_not_equal);
3981 
3982   // Store the pin state to the event writer.
3983   store_to_memory(tid_is_not_equal, event_writer_pin_field, _gvn.transform(pinVirtualThread), T_BOOLEAN, MemNode::unordered);
3984 
3985   // Store the exclusion state to the event writer.
3986   Node* excluded_bool = _gvn.transform(new URShiftINode(_gvn.transform(exclusion), excluded_shift));
3987   store_to_memory(tid_is_not_equal, event_writer_excluded_field, excluded_bool, T_BOOLEAN, MemNode::unordered);
3988 
3989   // Store the tid to the event writer.
3990   store_to_memory(tid_is_not_equal, event_writer_tid_field, tid, T_LONG, MemNode::unordered);
3991 
3992   // Update control and phi nodes.
3993   event_writer_tid_compare_rgn->init_req(_true_path, tid_is_not_equal);
3994   event_writer_tid_compare_rgn->init_req(_false_path, tid_is_equal);
3995   event_writer_tid_compare_mem->init_req(_true_path, _gvn.transform(reset_memory()));
3996   event_writer_tid_compare_mem->init_req(_false_path, _gvn.transform(vthread_compare_mem));
3997   event_writer_tid_compare_io->init_req(_true_path, _gvn.transform(i_o()));
3998   event_writer_tid_compare_io->init_req(_false_path, _gvn.transform(vthread_compare_io));
3999 
4000   // Result of top level CFG, Memory, IO and Value.
4001   RegionNode* result_rgn = new RegionNode(PATH_LIMIT);
4002   PhiNode* result_mem = new PhiNode(result_rgn, Type::MEMORY, TypePtr::BOTTOM);
4003   PhiNode* result_io = new PhiNode(result_rgn, Type::ABIO);
4004   PhiNode* result_value = new PhiNode(result_rgn, TypeInstPtr::BOTTOM);
4005 
4006   // Result control.
4007   result_rgn->init_req(_true_path, _gvn.transform(event_writer_tid_compare_rgn));
4008   result_rgn->init_req(_false_path, jobj_is_null);
4009 
4010   // Result memory.
4011   result_mem->init_req(_true_path, _gvn.transform(event_writer_tid_compare_mem));
4012   result_mem->init_req(_false_path, _gvn.transform(input_memory_state));
4013 
4014   // Result IO.
4015   result_io->init_req(_true_path, _gvn.transform(event_writer_tid_compare_io));
4016   result_io->init_req(_false_path, _gvn.transform(input_io_state));
4017 
4018   // Result value.
4019   result_value->init_req(_true_path, _gvn.transform(event_writer)); // return event writer oop
4020   result_value->init_req(_false_path, null()); // return null
4021 
4022   // Set output state.
4023   set_control(_gvn.transform(result_rgn));
4024   set_all_memory(_gvn.transform(result_mem));
4025   set_i_o(_gvn.transform(result_io));
4026   set_result(result_rgn, result_value);
4027   return true;
4028 }
4029 
4030 /*
4031  * The intrinsic is a model of this pseudo-code:
4032  *
4033  * JfrThreadLocal* const tl = thread->jfr_thread_local();
4034  * if (carrierThread != thread) { // is virtual thread
4035  *   const u2 vthread_epoch_raw = java_lang_Thread::jfr_epoch(thread);
4036  *   bool excluded = vthread_epoch_raw & excluded_mask;
4037  *   AtomicAccess::store(&tl->_contextual_tid, java_lang_Thread::tid(thread));
4038  *   AtomicAccess::store(&tl->_contextual_thread_excluded, is_excluded);
4039  *   if (!excluded) {
4040  *     const u2 vthread_epoch = vthread_epoch_raw & epoch_mask;
4041  *     AtomicAccess::store(&tl->_vthread_epoch, vthread_epoch);
4042  *   }
4043  *   AtomicAccess::release_store(&tl->_vthread, true);
4044  *   return;
4045  * }
4046  * AtomicAccess::release_store(&tl->_vthread, false);
4047  */
4048 void LibraryCallKit::extend_setCurrentThread(Node* jt, Node* thread) {
4049   enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
4050 
4051   Node* input_memory_state = reset_memory();
4052   set_all_memory(input_memory_state);
4053 
4054   // The most significant bit of the u2 is used to denote thread exclusion
4055   Node* excluded_mask = _gvn.intcon(1 << 15);
4056   // The epoch generation is the range [1-32767]
4057   Node* epoch_mask = _gvn.intcon(32767);
4058 
4059   Node* const carrierThread = generate_current_thread(jt);
4060   // If thread != carrierThread, this is a virtual thread.
4061   Node* thread_cmp_carrierThread = _gvn.transform(new CmpPNode(thread, carrierThread));
4062   Node* test_thread_not_equal_carrierThread = _gvn.transform(new BoolNode(thread_cmp_carrierThread, BoolTest::ne));
4063   IfNode* iff_thread_not_equal_carrierThread =
4064     create_and_map_if(control(), test_thread_not_equal_carrierThread, PROB_FAIR, COUNT_UNKNOWN);
4065 
4066   Node* vthread_offset = basic_plus_adr(jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_OFFSET_JFR));
4067 
4068   // False branch, is carrierThread.
4069   Node* thread_equal_carrierThread = _gvn.transform(new IfFalseNode(iff_thread_not_equal_carrierThread));
4070   // Store release
4071   Node* vthread_false_memory = store_to_memory(thread_equal_carrierThread, vthread_offset, _gvn.intcon(0), T_BOOLEAN, MemNode::release, true);
4072 
4073   set_all_memory(input_memory_state);
4074 
4075   // True branch, is virtual thread.
4076   Node* thread_not_equal_carrierThread = _gvn.transform(new IfTrueNode(iff_thread_not_equal_carrierThread));
4077   set_control(thread_not_equal_carrierThread);
4078 
4079   // Load the raw epoch value from the vthread.
4080   Node* epoch_offset = basic_plus_adr(thread, java_lang_Thread::jfr_epoch_offset());
4081   Node* epoch_raw = access_load_at(thread, epoch_offset, _gvn.type(epoch_offset)->is_ptr(), TypeInt::CHAR, T_CHAR,
4082                                    IN_HEAP | MO_UNORDERED | C2_MISMATCHED | C2_CONTROL_DEPENDENT_LOAD);
4083 
4084   // Mask off the excluded information from the epoch.
4085   Node * const is_excluded = _gvn.transform(new AndINode(epoch_raw, _gvn.transform(excluded_mask)));
4086 
4087   // Load the tid field from the thread.
4088   Node* tid = load_field_from_object(thread, "tid", "J");
4089 
4090   // Store the vthread tid to the jfr thread local.
4091   Node* thread_id_offset = basic_plus_adr(jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_ID_OFFSET_JFR));
4092   Node* tid_memory = store_to_memory(control(), thread_id_offset, tid, T_LONG, MemNode::unordered, true);
4093 
4094   // Branch is_excluded to conditionalize updating the epoch .
4095   Node* excluded_cmp = _gvn.transform(new CmpINode(is_excluded, _gvn.transform(excluded_mask)));
4096   Node* test_excluded = _gvn.transform(new BoolNode(excluded_cmp, BoolTest::eq));
4097   IfNode* iff_excluded = create_and_map_if(control(), test_excluded, PROB_MIN, COUNT_UNKNOWN);
4098 
4099   // True branch, vthread is excluded, no need to write epoch info.
4100   Node* excluded = _gvn.transform(new IfTrueNode(iff_excluded));
4101   set_control(excluded);
4102   Node* vthread_is_excluded = _gvn.intcon(1);
4103 
4104   // False branch, vthread is included, update epoch info.
4105   Node* included = _gvn.transform(new IfFalseNode(iff_excluded));
4106   set_control(included);
4107   Node* vthread_is_included = _gvn.intcon(0);
4108 
4109   // Get epoch value.
4110   Node* epoch = _gvn.transform(new AndINode(epoch_raw, _gvn.transform(epoch_mask)));
4111 
4112   // Store the vthread epoch to the jfr thread local.
4113   Node* vthread_epoch_offset = basic_plus_adr(jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_EPOCH_OFFSET_JFR));
4114   Node* included_memory = store_to_memory(control(), vthread_epoch_offset, epoch, T_CHAR, MemNode::unordered, true);
4115 
4116   RegionNode* excluded_rgn = new RegionNode(PATH_LIMIT);
4117   record_for_igvn(excluded_rgn);
4118   PhiNode* excluded_mem = new PhiNode(excluded_rgn, Type::MEMORY, TypePtr::BOTTOM);
4119   record_for_igvn(excluded_mem);
4120   PhiNode* exclusion = new PhiNode(excluded_rgn, TypeInt::BOOL);
4121   record_for_igvn(exclusion);
4122 
4123   // Merge the excluded control and memory.
4124   excluded_rgn->init_req(_true_path, excluded);
4125   excluded_rgn->init_req(_false_path, included);
4126   excluded_mem->init_req(_true_path, tid_memory);
4127   excluded_mem->init_req(_false_path, included_memory);
4128   exclusion->init_req(_true_path, _gvn.transform(vthread_is_excluded));
4129   exclusion->init_req(_false_path, _gvn.transform(vthread_is_included));
4130 
4131   // Set intermediate state.
4132   set_control(_gvn.transform(excluded_rgn));
4133   set_all_memory(excluded_mem);
4134 
4135   // Store the vthread exclusion state to the jfr thread local.
4136   Node* thread_local_excluded_offset = basic_plus_adr(jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_EXCLUDED_OFFSET_JFR));
4137   store_to_memory(control(), thread_local_excluded_offset, _gvn.transform(exclusion), T_BOOLEAN, MemNode::unordered, true);
4138 
4139   // Store release
4140   Node * vthread_true_memory = store_to_memory(control(), vthread_offset, _gvn.intcon(1), T_BOOLEAN, MemNode::release, true);
4141 
4142   RegionNode* thread_compare_rgn = new RegionNode(PATH_LIMIT);
4143   record_for_igvn(thread_compare_rgn);
4144   PhiNode* thread_compare_mem = new PhiNode(thread_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
4145   record_for_igvn(thread_compare_mem);
4146   PhiNode* vthread = new PhiNode(thread_compare_rgn, TypeInt::BOOL);
4147   record_for_igvn(vthread);
4148 
4149   // Merge the thread_compare control and memory.
4150   thread_compare_rgn->init_req(_true_path, control());
4151   thread_compare_rgn->init_req(_false_path, thread_equal_carrierThread);
4152   thread_compare_mem->init_req(_true_path, vthread_true_memory);
4153   thread_compare_mem->init_req(_false_path, vthread_false_memory);
4154 
4155   // Set output state.
4156   set_control(_gvn.transform(thread_compare_rgn));
4157   set_all_memory(_gvn.transform(thread_compare_mem));
4158 }
4159 
4160 #endif // JFR_HAVE_INTRINSICS
4161 
4162 //------------------------inline_native_currentCarrierThread------------------
4163 bool LibraryCallKit::inline_native_currentCarrierThread() {
4164   Node* junk = nullptr;
4165   set_result(generate_current_thread(junk));
4166   return true;
4167 }
4168 
4169 //------------------------inline_native_currentThread------------------
4170 bool LibraryCallKit::inline_native_currentThread() {
4171   Node* junk = nullptr;
4172   set_result(generate_virtual_thread(junk));
4173   return true;
4174 }
4175 
4176 //------------------------inline_native_setVthread------------------
4177 bool LibraryCallKit::inline_native_setCurrentThread() {
4178   assert(C->method()->changes_current_thread(),
4179          "method changes current Thread but is not annotated ChangesCurrentThread");
4180   Node* arr = argument(1);
4181   Node* thread = _gvn.transform(new ThreadLocalNode());
4182   Node* p = basic_plus_adr(top()/*!oop*/, thread, in_bytes(JavaThread::vthread_offset()));
4183   Node* thread_obj_handle
4184     = make_load(nullptr, p, p->bottom_type()->is_ptr(), T_OBJECT, MemNode::unordered);
4185   thread_obj_handle = _gvn.transform(thread_obj_handle);
4186   const TypePtr *adr_type = _gvn.type(thread_obj_handle)->isa_ptr();
4187   access_store_at(nullptr, thread_obj_handle, adr_type, arr, _gvn.type(arr), T_OBJECT, IN_NATIVE | MO_UNORDERED);
4188 
4189   // Change the _monitor_owner_id of the JavaThread
4190   Node* tid = load_field_from_object(arr, "tid", "J");
4191   Node* monitor_owner_id_offset = basic_plus_adr(thread, in_bytes(JavaThread::monitor_owner_id_offset()));
4192   store_to_memory(control(), monitor_owner_id_offset, tid, T_LONG, MemNode::unordered, true);
4193 
4194   JFR_ONLY(extend_setCurrentThread(thread, arr);)
4195   return true;
4196 }
4197 
4198 const Type* LibraryCallKit::scopedValueCache_type() {
4199   ciKlass* objects_klass = ciObjArrayKlass::make(env()->Object_klass());
4200   const TypeOopPtr* etype = TypeOopPtr::make_from_klass(env()->Object_klass());
4201   const TypeAry* arr0 = TypeAry::make(etype, TypeInt::POS, /* stable= */ false, /* flat= */ false, /* not_flat= */ true, /* not_null_free= */ true);
4202 
4203   // Because we create the scopedValue cache lazily we have to make the
4204   // type of the result BotPTR.
4205   bool xk = etype->klass_is_exact();
4206   const Type* objects_type = TypeAryPtr::make(TypePtr::BotPTR, arr0, objects_klass, xk, TypeAryPtr::Offset(0));
4207   return objects_type;
4208 }
4209 
4210 Node* LibraryCallKit::scopedValueCache_helper() {
4211   Node* thread = _gvn.transform(new ThreadLocalNode());
4212   Node* p = basic_plus_adr(top()/*!oop*/, thread, in_bytes(JavaThread::scopedValueCache_offset()));
4213   // We cannot use immutable_memory() because we might flip onto a
4214   // different carrier thread, at which point we'll need to use that
4215   // carrier thread's cache.
4216   // return _gvn.transform(LoadNode::make(_gvn, nullptr, immutable_memory(), p, p->bottom_type()->is_ptr(),
4217   //       TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered));
4218   return make_load(nullptr, p, p->bottom_type()->is_ptr(), T_ADDRESS, MemNode::unordered);
4219 }
4220 
4221 //------------------------inline_native_scopedValueCache------------------
4222 bool LibraryCallKit::inline_native_scopedValueCache() {
4223   Node* cache_obj_handle = scopedValueCache_helper();
4224   const Type* objects_type = scopedValueCache_type();
4225   set_result(access_load(cache_obj_handle, objects_type, T_OBJECT, IN_NATIVE));
4226 
4227   return true;
4228 }
4229 
4230 //------------------------inline_native_setScopedValueCache------------------
4231 bool LibraryCallKit::inline_native_setScopedValueCache() {
4232   Node* arr = argument(0);
4233   Node* cache_obj_handle = scopedValueCache_helper();
4234   const Type* objects_type = scopedValueCache_type();
4235 
4236   const TypePtr *adr_type = _gvn.type(cache_obj_handle)->isa_ptr();
4237   access_store_at(nullptr, cache_obj_handle, adr_type, arr, objects_type, T_OBJECT, IN_NATIVE | MO_UNORDERED);
4238 
4239   return true;
4240 }
4241 
4242 //------------------------inline_native_Continuation_pin and unpin-----------
4243 
4244 // Shared implementation routine for both pin and unpin.
4245 bool LibraryCallKit::inline_native_Continuation_pinning(bool unpin) {
4246   enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
4247 
4248   // Save input memory.
4249   Node* input_memory_state = reset_memory();
4250   set_all_memory(input_memory_state);
4251 
4252   // TLS
4253   Node* tls_ptr = _gvn.transform(new ThreadLocalNode());
4254   Node* last_continuation_offset = basic_plus_adr(top(), tls_ptr, in_bytes(JavaThread::cont_entry_offset()));
4255   Node* last_continuation = make_load(control(), last_continuation_offset, last_continuation_offset->get_ptr_type(), T_ADDRESS, MemNode::unordered);
4256 
4257   // Null check the last continuation object.
4258   Node* continuation_cmp_null = _gvn.transform(new CmpPNode(last_continuation, null()));
4259   Node* test_continuation_not_equal_null = _gvn.transform(new BoolNode(continuation_cmp_null, BoolTest::ne));
4260   IfNode* iff_continuation_not_equal_null = create_and_map_if(control(), test_continuation_not_equal_null, PROB_MAX, COUNT_UNKNOWN);
4261 
4262   // False path, last continuation is null.
4263   Node* continuation_is_null = _gvn.transform(new IfFalseNode(iff_continuation_not_equal_null));
4264 
4265   // True path, last continuation is not null.
4266   Node* continuation_is_not_null = _gvn.transform(new IfTrueNode(iff_continuation_not_equal_null));
4267 
4268   set_control(continuation_is_not_null);
4269 
4270   // Load the pin count from the last continuation.
4271   Node* pin_count_offset = basic_plus_adr(top(), last_continuation, in_bytes(ContinuationEntry::pin_count_offset()));
4272   Node* pin_count = make_load(control(), pin_count_offset, TypeInt::INT, T_INT, MemNode::unordered);
4273 
4274   // The loaded pin count is compared against a context specific rhs for over/underflow detection.
4275   Node* pin_count_rhs;
4276   if (unpin) {
4277     pin_count_rhs = _gvn.intcon(0);
4278   } else {
4279     pin_count_rhs = _gvn.intcon(UINT32_MAX);
4280   }
4281   Node* pin_count_cmp = _gvn.transform(new CmpUNode(_gvn.transform(pin_count), pin_count_rhs));
4282   Node* test_pin_count_over_underflow = _gvn.transform(new BoolNode(pin_count_cmp, BoolTest::eq));
4283   IfNode* iff_pin_count_over_underflow = create_and_map_if(control(), test_pin_count_over_underflow, PROB_MIN, COUNT_UNKNOWN);
4284 
4285   // True branch, pin count over/underflow.
4286   Node* pin_count_over_underflow = _gvn.transform(new IfTrueNode(iff_pin_count_over_underflow));
4287   {
4288     // Trap (but not deoptimize (Action_none)) and continue in the interpreter
4289     // which will throw IllegalStateException for pin count over/underflow.
4290     // No memory changed so far - we can use memory create by reset_memory()
4291     // at the beginning of this intrinsic. No need to call reset_memory() again.
4292     PreserveJVMState pjvms(this);
4293     set_control(pin_count_over_underflow);
4294     uncommon_trap(Deoptimization::Reason_intrinsic,
4295                   Deoptimization::Action_none);
4296     assert(stopped(), "invariant");
4297   }
4298 
4299   // False branch, no pin count over/underflow. Increment or decrement pin count and store back.
4300   Node* valid_pin_count = _gvn.transform(new IfFalseNode(iff_pin_count_over_underflow));
4301   set_control(valid_pin_count);
4302 
4303   Node* next_pin_count;
4304   if (unpin) {
4305     next_pin_count = _gvn.transform(new SubINode(pin_count, _gvn.intcon(1)));
4306   } else {
4307     next_pin_count = _gvn.transform(new AddINode(pin_count, _gvn.intcon(1)));
4308   }
4309 
4310   store_to_memory(control(), pin_count_offset, next_pin_count, T_INT, MemNode::unordered);
4311 
4312   // Result of top level CFG and Memory.
4313   RegionNode* result_rgn = new RegionNode(PATH_LIMIT);
4314   record_for_igvn(result_rgn);
4315   PhiNode* result_mem = new PhiNode(result_rgn, Type::MEMORY, TypePtr::BOTTOM);
4316   record_for_igvn(result_mem);
4317 
4318   result_rgn->init_req(_true_path, _gvn.transform(valid_pin_count));
4319   result_rgn->init_req(_false_path, _gvn.transform(continuation_is_null));
4320   result_mem->init_req(_true_path, _gvn.transform(reset_memory()));
4321   result_mem->init_req(_false_path, _gvn.transform(input_memory_state));
4322 
4323   // Set output state.
4324   set_control(_gvn.transform(result_rgn));
4325   set_all_memory(_gvn.transform(result_mem));
4326 
4327   return true;
4328 }
4329 
4330 //-----------------------load_klass_from_mirror_common-------------------------
4331 // Given a java mirror (a java.lang.Class oop), load its corresponding klass oop.
4332 // Test the klass oop for null (signifying a primitive Class like Integer.TYPE),
4333 // and branch to the given path on the region.
4334 // If never_see_null, take an uncommon trap on null, so we can optimistically
4335 // compile for the non-null case.
4336 // If the region is null, force never_see_null = true.
4337 Node* LibraryCallKit::load_klass_from_mirror_common(Node* mirror,
4338                                                     bool never_see_null,
4339                                                     RegionNode* region,
4340                                                     int null_path,
4341                                                     int offset) {
4342   if (region == nullptr)  never_see_null = true;
4343   Node* p = basic_plus_adr(mirror, offset);
4344   const TypeKlassPtr*  kls_type = TypeInstKlassPtr::OBJECT_OR_NULL;
4345   Node* kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), p, TypeRawPtr::BOTTOM, kls_type));
4346   Node* null_ctl = top();
4347   kls = null_check_oop(kls, &null_ctl, never_see_null);
4348   if (region != nullptr) {
4349     // Set region->in(null_path) if the mirror is a primitive (e.g, int.class).
4350     region->init_req(null_path, null_ctl);
4351   } else {
4352     assert(null_ctl == top(), "no loose ends");
4353   }
4354   return kls;
4355 }
4356 
4357 //--------------------(inline_native_Class_query helpers)---------------------
4358 // Use this for JVM_ACC_INTERFACE.
4359 // Fall through if (mods & mask) == bits, take the guard otherwise.
4360 Node* LibraryCallKit::generate_klass_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region,
4361                                                  ByteSize offset, const Type* type, BasicType bt) {
4362   // Branch around if the given klass has the given modifier bit set.
4363   // Like generate_guard, adds a new path onto the region.
4364   Node* modp = basic_plus_adr(kls, in_bytes(offset));
4365   Node* mods = make_load(nullptr, modp, type, bt, MemNode::unordered);
4366   Node* mask = intcon(modifier_mask);
4367   Node* bits = intcon(modifier_bits);
4368   Node* mbit = _gvn.transform(new AndINode(mods, mask));
4369   Node* cmp  = _gvn.transform(new CmpINode(mbit, bits));
4370   Node* bol  = _gvn.transform(new BoolNode(cmp, BoolTest::ne));
4371   return generate_fair_guard(bol, region);
4372 }
4373 
4374 Node* LibraryCallKit::generate_interface_guard(Node* kls, RegionNode* region) {
4375   return generate_klass_flags_guard(kls, JVM_ACC_INTERFACE, 0, region,
4376                                     Klass::access_flags_offset(), TypeInt::CHAR, T_CHAR);
4377 }
4378 
4379 // Use this for testing if Klass is_hidden, has_finalizer, and is_cloneable_fast.
4380 Node* LibraryCallKit::generate_misc_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region) {
4381   return generate_klass_flags_guard(kls, modifier_mask, modifier_bits, region,
4382                                     Klass::misc_flags_offset(), TypeInt::UBYTE, T_BOOLEAN);
4383 }
4384 
4385 Node* LibraryCallKit::generate_hidden_class_guard(Node* kls, RegionNode* region) {
4386   return generate_misc_flags_guard(kls, KlassFlags::_misc_is_hidden_class, 0, region);
4387 }
4388 
4389 //-------------------------inline_native_Class_query-------------------
4390 bool LibraryCallKit::inline_native_Class_query(vmIntrinsics::ID id) {
4391   const Type* return_type = TypeInt::BOOL;
4392   Node* prim_return_value = top();  // what happens if it's a primitive class?
4393   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
4394   bool expect_prim = false;     // most of these guys expect to work on refs
4395 
4396   enum { _normal_path = 1, _prim_path = 2, PATH_LIMIT };
4397 
4398   Node* mirror = argument(0);
4399   Node* obj    = top();
4400 
4401   switch (id) {
4402   case vmIntrinsics::_isInstance:
4403     // nothing is an instance of a primitive type
4404     prim_return_value = intcon(0);
4405     obj = argument(1);
4406     break;
4407   case vmIntrinsics::_isHidden:
4408     prim_return_value = intcon(0);
4409     break;
4410   case vmIntrinsics::_getSuperclass:
4411     prim_return_value = null();
4412     return_type = TypeInstPtr::MIRROR->cast_to_ptr_type(TypePtr::BotPTR);
4413     break;
4414   default:
4415     fatal_unexpected_iid(id);
4416     break;
4417   }
4418 
4419   const TypeInstPtr* mirror_con = _gvn.type(mirror)->isa_instptr();
4420   if (mirror_con == nullptr)  return false;  // cannot happen?
4421 
4422 #ifndef PRODUCT
4423   if (C->print_intrinsics() || C->print_inlining()) {
4424     ciType* k = mirror_con->java_mirror_type();
4425     if (k) {
4426       tty->print("Inlining %s on constant Class ", vmIntrinsics::name_at(intrinsic_id()));
4427       k->print_name();
4428       tty->cr();
4429     }
4430   }
4431 #endif
4432 
4433   // Null-check the mirror, and the mirror's klass ptr (in case it is a primitive).
4434   RegionNode* region = new RegionNode(PATH_LIMIT);
4435   record_for_igvn(region);
4436   PhiNode* phi = new PhiNode(region, return_type);
4437 
4438   // The mirror will never be null of Reflection.getClassAccessFlags, however
4439   // it may be null for Class.isInstance or Class.getModifiers. Throw a NPE
4440   // if it is. See bug 4774291.
4441 
4442   // For Reflection.getClassAccessFlags(), the null check occurs in
4443   // the wrong place; see inline_unsafe_access(), above, for a similar
4444   // situation.
4445   mirror = null_check(mirror);
4446   // If mirror or obj is dead, only null-path is taken.
4447   if (stopped())  return true;
4448 
4449   if (expect_prim)  never_see_null = false;  // expect nulls (meaning prims)
4450 
4451   // Now load the mirror's klass metaobject, and null-check it.
4452   // Side-effects region with the control path if the klass is null.
4453   Node* kls = load_klass_from_mirror(mirror, never_see_null, region, _prim_path);
4454   // If kls is null, we have a primitive mirror.
4455   phi->init_req(_prim_path, prim_return_value);
4456   if (stopped()) { set_result(region, phi); return true; }
4457   bool safe_for_replace = (region->in(_prim_path) == top());
4458 
4459   Node* p;  // handy temp
4460   Node* null_ctl;
4461 
4462   // Now that we have the non-null klass, we can perform the real query.
4463   // For constant classes, the query will constant-fold in LoadNode::Value.
4464   Node* query_value = top();
4465   switch (id) {
4466   case vmIntrinsics::_isInstance:
4467     // nothing is an instance of a primitive type
4468     query_value = gen_instanceof(obj, kls, safe_for_replace);
4469     break;
4470 
4471   case vmIntrinsics::_isHidden:
4472     // (To verify this code sequence, check the asserts in JVM_IsHiddenClass.)
4473     if (generate_hidden_class_guard(kls, region) != nullptr)
4474       // A guard was added.  If the guard is taken, it was an hidden class.
4475       phi->add_req(intcon(1));
4476     // If we fall through, it's a plain class.
4477     query_value = intcon(0);
4478     break;
4479 
4480 
4481   case vmIntrinsics::_getSuperclass:
4482     // The rules here are somewhat unfortunate, but we can still do better
4483     // with random logic than with a JNI call.
4484     // Interfaces store null or Object as _super, but must report null.
4485     // Arrays store an intermediate super as _super, but must report Object.
4486     // Other types can report the actual _super.
4487     // (To verify this code sequence, check the asserts in JVM_IsInterface.)
4488     if (generate_interface_guard(kls, region) != nullptr)
4489       // A guard was added.  If the guard is taken, it was an interface.
4490       phi->add_req(null());
4491     if (generate_array_guard(kls, region) != nullptr)
4492       // A guard was added.  If the guard is taken, it was an array.
4493       phi->add_req(makecon(TypeInstPtr::make(env()->Object_klass()->java_mirror())));
4494     // If we fall through, it's a plain class.  Get its _super.
4495     if (!stopped()) {
4496       p = basic_plus_adr(kls, in_bytes(Klass::super_offset()));
4497       kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), p, TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
4498       null_ctl = top();
4499       kls = null_check_oop(kls, &null_ctl);
4500       if (null_ctl != top()) {
4501         // If the guard is taken, Object.superClass is null (both klass and mirror).
4502         region->add_req(null_ctl);
4503         phi   ->add_req(null());
4504       }
4505       if (!stopped()) {
4506         query_value = load_mirror_from_klass(kls);
4507       }
4508     }
4509     break;
4510 
4511   default:
4512     fatal_unexpected_iid(id);
4513     break;
4514   }
4515 
4516   // Fall-through is the normal case of a query to a real class.
4517   phi->init_req(1, query_value);
4518   region->init_req(1, control());
4519 
4520   C->set_has_split_ifs(true); // Has chance for split-if optimization
4521   set_result(region, phi);
4522   return true;
4523 }
4524 
4525 
4526 //-------------------------inline_Class_cast-------------------
4527 bool LibraryCallKit::inline_Class_cast() {
4528   Node* mirror = argument(0); // Class
4529   Node* obj    = argument(1);
4530   const TypeInstPtr* mirror_con = _gvn.type(mirror)->isa_instptr();
4531   if (mirror_con == nullptr) {
4532     return false;  // dead path (mirror->is_top()).
4533   }
4534   if (obj == nullptr || obj->is_top()) {
4535     return false;  // dead path
4536   }
4537   const TypeOopPtr* tp = _gvn.type(obj)->isa_oopptr();
4538 
4539   // First, see if Class.cast() can be folded statically.
4540   // java_mirror_type() returns non-null for compile-time Class constants.
4541   ciType* tm = mirror_con->java_mirror_type();
4542   if (tm != nullptr && tm->is_klass() &&
4543       tp != nullptr) {
4544     if (!tp->is_loaded()) {
4545       // Don't use intrinsic when class is not loaded.
4546       return false;
4547     } else {
4548       const TypeKlassPtr* tklass = TypeKlassPtr::make(tm->as_klass(), Type::trust_interfaces);
4549       int static_res = C->static_subtype_check(tklass, tp->as_klass_type());
4550       if (static_res == Compile::SSC_always_true) {
4551         // isInstance() is true - fold the code.
4552         set_result(obj);
4553         return true;
4554       } else if (static_res == Compile::SSC_always_false) {
4555         // Don't use intrinsic, have to throw ClassCastException.
4556         // If the reference is null, the non-intrinsic bytecode will
4557         // be optimized appropriately.
4558         return false;
4559       }
4560     }
4561   }
4562 
4563   // Bailout intrinsic and do normal inlining if exception path is frequent.
4564   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
4565     return false;
4566   }
4567 
4568   // Generate dynamic checks.
4569   // Class.cast() is java implementation of _checkcast bytecode.
4570   // Do checkcast (Parse::do_checkcast()) optimizations here.
4571 
4572   mirror = null_check(mirror);
4573   // If mirror is dead, only null-path is taken.
4574   if (stopped()) {
4575     return true;
4576   }
4577 
4578   // Not-subtype or the mirror's klass ptr is nullptr (in case it is a primitive).
4579   enum { _bad_type_path = 1, _prim_path = 2, _npe_path = 3, PATH_LIMIT };
4580   RegionNode* region = new RegionNode(PATH_LIMIT);
4581   record_for_igvn(region);
4582 
4583   // Now load the mirror's klass metaobject, and null-check it.
4584   // If kls is null, we have a primitive mirror and
4585   // nothing is an instance of a primitive type.
4586   Node* kls = load_klass_from_mirror(mirror, false, region, _prim_path);
4587 
4588   Node* res = top();
4589   Node* io = i_o();
4590   Node* mem = merged_memory();
4591   if (!stopped()) {
4592 
4593     Node* bad_type_ctrl = top();
4594     // Do checkcast optimizations.
4595     res = gen_checkcast(obj, kls, &bad_type_ctrl);
4596     region->init_req(_bad_type_path, bad_type_ctrl);
4597   }
4598   if (region->in(_prim_path) != top() ||
4599       region->in(_bad_type_path) != top() ||
4600       region->in(_npe_path) != top()) {
4601     // Let Interpreter throw ClassCastException.
4602     PreserveJVMState pjvms(this);
4603     set_control(_gvn.transform(region));
4604     // Set IO and memory because gen_checkcast may override them when buffering inline types
4605     set_i_o(io);
4606     set_all_memory(mem);
4607     uncommon_trap(Deoptimization::Reason_intrinsic,
4608                   Deoptimization::Action_maybe_recompile);
4609   }
4610   if (!stopped()) {
4611     set_result(res);
4612   }
4613   return true;
4614 }
4615 
4616 
4617 //--------------------------inline_native_subtype_check------------------------
4618 // This intrinsic takes the JNI calls out of the heart of
4619 // UnsafeFieldAccessorImpl.set, which improves Field.set, readObject, etc.
4620 bool LibraryCallKit::inline_native_subtype_check() {
4621   // Pull both arguments off the stack.
4622   Node* args[2];                // two java.lang.Class mirrors: superc, subc
4623   args[0] = argument(0);
4624   args[1] = argument(1);
4625   Node* klasses[2];             // corresponding Klasses: superk, subk
4626   klasses[0] = klasses[1] = top();
4627 
4628   enum {
4629     // A full decision tree on {superc is prim, subc is prim}:
4630     _prim_0_path = 1,           // {P,N} => false
4631                                 // {P,P} & superc!=subc => false
4632     _prim_same_path,            // {P,P} & superc==subc => true
4633     _prim_1_path,               // {N,P} => false
4634     _ref_subtype_path,          // {N,N} & subtype check wins => true
4635     _both_ref_path,             // {N,N} & subtype check loses => false
4636     PATH_LIMIT
4637   };
4638 
4639   RegionNode* region = new RegionNode(PATH_LIMIT);
4640   RegionNode* prim_region = new RegionNode(2);
4641   Node*       phi    = new PhiNode(region, TypeInt::BOOL);
4642   record_for_igvn(region);
4643   record_for_igvn(prim_region);
4644 
4645   const TypePtr* adr_type = TypeRawPtr::BOTTOM;   // memory type of loads
4646   const TypeKlassPtr* kls_type = TypeInstKlassPtr::OBJECT_OR_NULL;
4647   int class_klass_offset = java_lang_Class::klass_offset();
4648 
4649   // First null-check both mirrors and load each mirror's klass metaobject.
4650   int which_arg;
4651   for (which_arg = 0; which_arg <= 1; which_arg++) {
4652     Node* arg = args[which_arg];
4653     arg = null_check(arg);
4654     if (stopped())  break;
4655     args[which_arg] = arg;
4656 
4657     Node* p = basic_plus_adr(arg, class_klass_offset);
4658     Node* kls = LoadKlassNode::make(_gvn, immutable_memory(), p, adr_type, kls_type);
4659     klasses[which_arg] = _gvn.transform(kls);
4660   }
4661 
4662   // Having loaded both klasses, test each for null.
4663   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
4664   for (which_arg = 0; which_arg <= 1; which_arg++) {
4665     Node* kls = klasses[which_arg];
4666     Node* null_ctl = top();
4667     kls = null_check_oop(kls, &null_ctl, never_see_null);
4668     if (which_arg == 0) {
4669       prim_region->init_req(1, null_ctl);
4670     } else {
4671       region->init_req(_prim_1_path, null_ctl);
4672     }
4673     if (stopped())  break;
4674     klasses[which_arg] = kls;
4675   }
4676 
4677   if (!stopped()) {
4678     // now we have two reference types, in klasses[0..1]
4679     Node* subk   = klasses[1];  // the argument to isAssignableFrom
4680     Node* superk = klasses[0];  // the receiver
4681     region->set_req(_both_ref_path, gen_subtype_check(subk, superk));
4682     region->set_req(_ref_subtype_path, control());
4683   }
4684 
4685   // If both operands are primitive (both klasses null), then
4686   // we must return true when they are identical primitives.
4687   // It is convenient to test this after the first null klass check.
4688   // This path is also used if superc is a value mirror.
4689   set_control(_gvn.transform(prim_region));
4690   if (!stopped()) {
4691     // Since superc is primitive, make a guard for the superc==subc case.
4692     Node* cmp_eq = _gvn.transform(new CmpPNode(args[0], args[1]));
4693     Node* bol_eq = _gvn.transform(new BoolNode(cmp_eq, BoolTest::eq));
4694     generate_fair_guard(bol_eq, region);
4695     if (region->req() == PATH_LIMIT+1) {
4696       // A guard was added.  If the added guard is taken, superc==subc.
4697       region->swap_edges(PATH_LIMIT, _prim_same_path);
4698       region->del_req(PATH_LIMIT);
4699     }
4700     region->set_req(_prim_0_path, control()); // Not equal after all.
4701   }
4702 
4703   // these are the only paths that produce 'true':
4704   phi->set_req(_prim_same_path,   intcon(1));
4705   phi->set_req(_ref_subtype_path, intcon(1));
4706 
4707   // pull together the cases:
4708   assert(region->req() == PATH_LIMIT, "sane region");
4709   for (uint i = 1; i < region->req(); i++) {
4710     Node* ctl = region->in(i);
4711     if (ctl == nullptr || ctl == top()) {
4712       region->set_req(i, top());
4713       phi   ->set_req(i, top());
4714     } else if (phi->in(i) == nullptr) {
4715       phi->set_req(i, intcon(0)); // all other paths produce 'false'
4716     }
4717   }
4718 
4719   set_control(_gvn.transform(region));
4720   set_result(_gvn.transform(phi));
4721   return true;
4722 }
4723 
4724 //---------------------generate_array_guard_common------------------------
4725 Node* LibraryCallKit::generate_array_guard_common(Node* kls, RegionNode* region, ArrayKind kind, Node** obj) {
4726 
4727   if (stopped()) {
4728     return nullptr;
4729   }
4730 
4731   // Like generate_guard, adds a new path onto the region.
4732   jint  layout_con = 0;
4733   Node* layout_val = get_layout_helper(kls, layout_con);
4734   if (layout_val == nullptr) {
4735     bool query = 0;
4736     switch(kind) {
4737       case RefArray:       query = Klass::layout_helper_is_refArray(layout_con); break;
4738       case NonRefArray:    query = !Klass::layout_helper_is_refArray(layout_con); break;
4739       case TypeArray:      query = Klass::layout_helper_is_typeArray(layout_con); break;
4740       case AnyArray:       query = Klass::layout_helper_is_array(layout_con); break;
4741       case NonArray:       query = !Klass::layout_helper_is_array(layout_con); break;
4742       default:
4743         ShouldNotReachHere();
4744     }
4745     if (!query) {
4746       return nullptr;                       // never a branch
4747     } else {                             // always a branch
4748       Node* always_branch = control();
4749       if (region != nullptr)
4750         region->add_req(always_branch);
4751       set_control(top());
4752       return always_branch;
4753     }
4754   }
4755   unsigned int value = 0;
4756   BoolTest::mask btest = BoolTest::illegal;
4757   switch(kind) {
4758     case RefArray:
4759     case NonRefArray: {
4760       value = Klass::_lh_array_tag_ref_value;
4761       layout_val = _gvn.transform(new RShiftINode(layout_val, intcon(Klass::_lh_array_tag_shift)));
4762       btest = (kind == RefArray) ? BoolTest::eq : BoolTest::ne;
4763       break;
4764     }
4765     case TypeArray: {
4766       value = Klass::_lh_array_tag_type_value;
4767       layout_val = _gvn.transform(new RShiftINode(layout_val, intcon(Klass::_lh_array_tag_shift)));
4768       btest = BoolTest::eq;
4769       break;
4770     }
4771     case AnyArray:    value = Klass::_lh_neutral_value; btest = BoolTest::lt; break;
4772     case NonArray:    value = Klass::_lh_neutral_value; btest = BoolTest::gt; break;
4773     default:
4774       ShouldNotReachHere();
4775   }
4776   // Now test the correct condition.
4777   jint nval = (jint)value;
4778   Node* cmp = _gvn.transform(new CmpINode(layout_val, intcon(nval)));
4779   Node* bol = _gvn.transform(new BoolNode(cmp, btest));
4780   Node* ctrl = generate_fair_guard(bol, region);
4781   Node* is_array_ctrl = kind == NonArray ? control() : ctrl;
4782   if (obj != nullptr && is_array_ctrl != nullptr && is_array_ctrl != top()) {
4783     // Keep track of the fact that 'obj' is an array to prevent
4784     // array specific accesses from floating above the guard.
4785     *obj = _gvn.transform(new CastPPNode(is_array_ctrl, *obj, TypeAryPtr::BOTTOM));
4786   }
4787   return ctrl;
4788 }
4789 
4790 // public static native Object[] ValueClass::newNullRestrictedAtomicArray(Class<?> componentType, int length, Object initVal);
4791 // public static native Object[] ValueClass::newNullRestrictedNonAtomicArray(Class<?> componentType, int length, Object initVal);
4792 // public static native Object[] ValueClass::newNullableAtomicArray(Class<?> componentType, int length);
4793 bool LibraryCallKit::inline_newArray(bool null_free, bool atomic) {
4794   assert(null_free || atomic, "nullable implies atomic");
4795   Node* componentType = argument(0);
4796   Node* length = argument(1);
4797   Node* init_val = null_free ? argument(2) : nullptr;
4798 
4799   const TypeInstPtr* tp = _gvn.type(componentType)->isa_instptr();
4800   if (tp != nullptr) {
4801     ciInstanceKlass* ik = tp->instance_klass();
4802     if (ik == C->env()->Class_klass()) {
4803       ciType* t = tp->java_mirror_type();
4804       if (t != nullptr && t->is_inlinetype()) {
4805 
4806         ciArrayKlass* array_klass = ciArrayKlass::make(t, null_free, atomic, true);
4807         assert(array_klass->is_elem_null_free() == null_free, "inconsistency");
4808         assert(array_klass->is_elem_atomic() == atomic, "inconsistency");
4809 
4810         // TOOD 8350865 ZGC needs card marks on initializing oop stores
4811         if (UseZGC && null_free && !array_klass->is_flat_array_klass()) {
4812           return false;
4813         }
4814 
4815         if (array_klass->is_loaded() && array_klass->element_klass()->as_inline_klass()->is_initialized()) {
4816           const TypeAryKlassPtr* array_klass_type = TypeAryKlassPtr::make(array_klass, Type::trust_interfaces, true);
4817           if (null_free) {
4818             if (init_val->is_InlineType()) {
4819               if (array_klass_type->is_flat() && init_val->as_InlineType()->is_all_zero(&gvn(), /* flat */ true)) {
4820                 // Zeroing is enough because the init value is the all-zero value
4821                 init_val = nullptr;
4822               } else {
4823                 init_val = init_val->as_InlineType()->buffer(this);
4824               }
4825             }
4826             // TODO 8350865 Should we add a check of the init_val type (maybe in debug only + halt)?
4827           }
4828           Node* obj = new_array(makecon(array_klass_type), length, 0, nullptr, false, init_val);
4829           const TypeAryPtr* arytype = gvn().type(obj)->is_aryptr();
4830           assert(arytype->is_null_free() == null_free, "inconsistency");
4831           assert(arytype->is_not_null_free() == !null_free, "inconsistency");
4832           assert(arytype->is_atomic() == atomic, "inconsistency");
4833           set_result(obj);
4834           return true;
4835         }
4836       }
4837     }
4838   }
4839   return false;
4840 }
4841 
4842 // public static native boolean ValueClass::isFlatArray(Object array);
4843 // public static native boolean ValueClass::isNullRestrictedArray(Object array);
4844 // public static native boolean ValueClass::isAtomicArray(Object array);
4845 bool LibraryCallKit::inline_getArrayProperties(ArrayPropertiesCheck check) {
4846   Node* array = argument(0);
4847 
4848   Node* bol;
4849   switch(check) {
4850     case IsFlat:
4851       // TODO 8350865 Use the object version here instead of loading the klass
4852       // 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
4853       bol = flat_array_test(load_object_klass(array));
4854       break;
4855     case IsNullRestricted:
4856       bol = null_free_array_test(array);
4857       break;
4858     case IsAtomic:
4859       // TODO 8350865 Implement this. It's a bit more complicated, see conditions in JVM_IsAtomicArray
4860       // Enable TestIntrinsics::test87/88 once this is implemented
4861       // bol = null_free_atomic_array_test
4862       return false;
4863     default:
4864       ShouldNotReachHere();
4865   }
4866 
4867   Node* res = gvn().transform(new CMoveINode(bol, intcon(0), intcon(1), TypeInt::BOOL));
4868   set_result(res);
4869   return true;
4870 }
4871 
4872 // Load the default refined array klass from an ObjArrayKlass. This relies on the first entry in the
4873 // '_next_refined_array_klass' linked list being the default (see ObjArrayKlass::klass_with_properties).
4874 Node* LibraryCallKit::load_default_refined_array_klass(Node* klass_node, bool type_array_guard) {
4875   RegionNode* region = new RegionNode(2);
4876   Node* phi = new PhiNode(region, TypeInstKlassPtr::OBJECT_OR_NULL);
4877 
4878   if (type_array_guard) {
4879     generate_typeArray_guard(klass_node, region);
4880     if (region->req() == 3) {
4881       phi->add_req(klass_node);
4882     }
4883   }
4884   Node* adr_refined_klass = basic_plus_adr(klass_node, in_bytes(ObjArrayKlass::next_refined_array_klass_offset()));
4885   Node* refined_klass = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), adr_refined_klass, TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
4886 
4887   // Can be null if not initialized yet, just deopt
4888   Node* null_ctl = top();
4889   refined_klass = null_check_oop(refined_klass, &null_ctl, /* never_see_null= */ true);
4890 
4891   region->init_req(1, control());
4892   phi->init_req(1, refined_klass);
4893 
4894   set_control(_gvn.transform(region));
4895   return _gvn.transform(phi);
4896 }
4897 
4898 // Load the non-refined array klass from an ObjArrayKlass.
4899 Node* LibraryCallKit::load_non_refined_array_klass(Node* klass_node) {
4900   const TypeAryKlassPtr* ary_klass_ptr = _gvn.type(klass_node)->isa_aryklassptr();
4901   if (ary_klass_ptr != nullptr && ary_klass_ptr->klass_is_exact()) {
4902     return _gvn.makecon(ary_klass_ptr->cast_to_refined_array_klass_ptr(false));
4903   }
4904 
4905   RegionNode* region = new RegionNode(2);
4906   Node* phi = new PhiNode(region, TypeInstKlassPtr::OBJECT);
4907 
4908   generate_typeArray_guard(klass_node, region);
4909   if (region->req() == 3) {
4910     phi->add_req(klass_node);
4911   }
4912   Node* super_adr = basic_plus_adr(klass_node, in_bytes(Klass::super_offset()));
4913   Node* super_klass = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), super_adr, TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT));
4914 
4915   region->init_req(1, control());
4916   phi->init_req(1, super_klass);
4917 
4918   set_control(_gvn.transform(region));
4919   return _gvn.transform(phi);
4920 }
4921 
4922 //-----------------------inline_native_newArray--------------------------
4923 // private static native Object java.lang.reflect.Array.newArray(Class<?> componentType, int length);
4924 // private        native Object Unsafe.allocateUninitializedArray0(Class<?> cls, int size);
4925 bool LibraryCallKit::inline_unsafe_newArray(bool uninitialized) {
4926   Node* mirror;
4927   Node* count_val;
4928   if (uninitialized) {
4929     null_check_receiver();
4930     mirror    = argument(1);
4931     count_val = argument(2);
4932   } else {
4933     mirror    = argument(0);
4934     count_val = argument(1);
4935   }
4936 
4937   mirror = null_check(mirror);
4938   // If mirror or obj is dead, only null-path is taken.
4939   if (stopped())  return true;
4940 
4941   enum { _normal_path = 1, _slow_path = 2, PATH_LIMIT };
4942   RegionNode* result_reg = new RegionNode(PATH_LIMIT);
4943   PhiNode*    result_val = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
4944   PhiNode*    result_io  = new PhiNode(result_reg, Type::ABIO);
4945   PhiNode*    result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
4946 
4947   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
4948   Node* klass_node = load_array_klass_from_mirror(mirror, never_see_null,
4949                                                   result_reg, _slow_path);
4950   Node* normal_ctl   = control();
4951   Node* no_array_ctl = result_reg->in(_slow_path);
4952 
4953   // Generate code for the slow case.  We make a call to newArray().
4954   set_control(no_array_ctl);
4955   if (!stopped()) {
4956     // Either the input type is void.class, or else the
4957     // array klass has not yet been cached.  Either the
4958     // ensuing call will throw an exception, or else it
4959     // will cache the array klass for next time.
4960     PreserveJVMState pjvms(this);
4961     CallJavaNode* slow_call = nullptr;
4962     if (uninitialized) {
4963       // Generate optimized virtual call (holder class 'Unsafe' is final)
4964       slow_call = generate_method_call(vmIntrinsics::_allocateUninitializedArray, false, false, true);
4965     } else {
4966       slow_call = generate_method_call_static(vmIntrinsics::_newArray, true);
4967     }
4968     Node* slow_result = set_results_for_java_call(slow_call);
4969     // this->control() comes from set_results_for_java_call
4970     result_reg->set_req(_slow_path, control());
4971     result_val->set_req(_slow_path, slow_result);
4972     result_io ->set_req(_slow_path, i_o());
4973     result_mem->set_req(_slow_path, reset_memory());
4974   }
4975 
4976   set_control(normal_ctl);
4977   if (!stopped()) {
4978     // Normal case:  The array type has been cached in the java.lang.Class.
4979     // The following call works fine even if the array type is polymorphic.
4980     // It could be a dynamic mix of int[], boolean[], Object[], etc.
4981 
4982     klass_node = load_default_refined_array_klass(klass_node);
4983 
4984     Node* obj = new_array(klass_node, count_val, 0);  // no arguments to push
4985     result_reg->init_req(_normal_path, control());
4986     result_val->init_req(_normal_path, obj);
4987     result_io ->init_req(_normal_path, i_o());
4988     result_mem->init_req(_normal_path, reset_memory());
4989 
4990     if (uninitialized) {
4991       // Mark the allocation so that zeroing is skipped
4992       AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(obj);
4993       alloc->maybe_set_complete(&_gvn);
4994     }
4995   }
4996 
4997   // Return the combined state.
4998   set_i_o(        _gvn.transform(result_io)  );
4999   set_all_memory( _gvn.transform(result_mem));
5000 
5001   C->set_has_split_ifs(true); // Has chance for split-if optimization
5002   set_result(result_reg, result_val);
5003   return true;
5004 }
5005 
5006 //----------------------inline_native_getLength--------------------------
5007 // public static native int java.lang.reflect.Array.getLength(Object array);
5008 bool LibraryCallKit::inline_native_getLength() {
5009   if (too_many_traps(Deoptimization::Reason_intrinsic))  return false;
5010 
5011   Node* array = null_check(argument(0));
5012   // If array is dead, only null-path is taken.
5013   if (stopped())  return true;
5014 
5015   // Deoptimize if it is a non-array.
5016   Node* non_array = generate_non_array_guard(load_object_klass(array), nullptr, &array);
5017 
5018   if (non_array != nullptr) {
5019     PreserveJVMState pjvms(this);
5020     set_control(non_array);
5021     uncommon_trap(Deoptimization::Reason_intrinsic,
5022                   Deoptimization::Action_maybe_recompile);
5023   }
5024 
5025   // If control is dead, only non-array-path is taken.
5026   if (stopped())  return true;
5027 
5028   // The works fine even if the array type is polymorphic.
5029   // It could be a dynamic mix of int[], boolean[], Object[], etc.
5030   Node* result = load_array_length(array);
5031 
5032   C->set_has_split_ifs(true);  // Has chance for split-if optimization
5033   set_result(result);
5034   return true;
5035 }
5036 
5037 //------------------------inline_array_copyOf----------------------------
5038 // public static <T,U> T[] java.util.Arrays.copyOf(     U[] original, int newLength,         Class<? extends T[]> newType);
5039 // public static <T,U> T[] java.util.Arrays.copyOfRange(U[] original, int from,      int to, Class<? extends T[]> newType);
5040 bool LibraryCallKit::inline_array_copyOf(bool is_copyOfRange) {
5041   if (too_many_traps(Deoptimization::Reason_intrinsic))  return false;
5042 
5043   // Get the arguments.
5044   Node* original          = argument(0);
5045   Node* start             = is_copyOfRange? argument(1): intcon(0);
5046   Node* end               = is_copyOfRange? argument(2): argument(1);
5047   Node* array_type_mirror = is_copyOfRange? argument(3): argument(2);
5048 
5049   Node* newcopy = nullptr;
5050 
5051   // Set the original stack and the reexecute bit for the interpreter to reexecute
5052   // the bytecode that invokes Arrays.copyOf if deoptimization happens.
5053   { PreserveReexecuteState preexecs(this);
5054     jvms()->set_should_reexecute(true);
5055 
5056     array_type_mirror = null_check(array_type_mirror);
5057     original          = null_check(original);
5058 
5059     // Check if a null path was taken unconditionally.
5060     if (stopped())  return true;
5061 
5062     Node* orig_length = load_array_length(original);
5063 
5064     Node* klass_node = load_klass_from_mirror(array_type_mirror, false, nullptr, 0);
5065     klass_node = null_check(klass_node);
5066 
5067     RegionNode* bailout = new RegionNode(1);
5068     record_for_igvn(bailout);
5069 
5070     // Despite the generic type of Arrays.copyOf, the mirror might be int, int[], etc.
5071     // Bail out if that is so.
5072     // Inline type array may have object field that would require a
5073     // write barrier. Conservatively, go to slow path.
5074     // TODO 8251971: Optimize for the case when flat src/dst are later found
5075     // to not contain oops (i.e., move this check to the macro expansion phase).
5076     BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
5077     const TypeAryPtr* orig_t = _gvn.type(original)->isa_aryptr();
5078     const TypeKlassPtr* tklass = _gvn.type(klass_node)->is_klassptr();
5079     bool exclude_flat = UseArrayFlattening && bs->array_copy_requires_gc_barriers(true, T_OBJECT, false, false, BarrierSetC2::Parsing) &&
5080                         // Can src array be flat and contain oops?
5081                         (orig_t == nullptr || (!orig_t->is_not_flat() && (!orig_t->is_flat() || orig_t->elem()->inline_klass()->contains_oops()))) &&
5082                         // Can dest array be flat and contain oops?
5083                         tklass->can_be_inline_array() && (!tklass->is_flat() || tklass->is_aryklassptr()->elem()->is_instklassptr()->instance_klass()->as_inline_klass()->contains_oops());
5084     Node* not_objArray = exclude_flat ? generate_non_refArray_guard(klass_node, bailout) : generate_typeArray_guard(klass_node, bailout);
5085 
5086     Node* refined_klass_node = load_default_refined_array_klass(klass_node, /* type_array_guard= */ false);
5087 
5088     if (not_objArray != nullptr) {
5089       // Improve the klass node's type from the new optimistic assumption:
5090       ciKlass* ak = ciArrayKlass::make(env()->Object_klass());
5091       const Type* akls = TypeKlassPtr::make(TypePtr::NotNull, ak, Type::Offset(0));
5092       Node* cast = new CastPPNode(control(), refined_klass_node, akls);
5093       refined_klass_node = _gvn.transform(cast);
5094     }
5095 
5096     // Bail out if either start or end is negative.
5097     generate_negative_guard(start, bailout, &start);
5098     generate_negative_guard(end,   bailout, &end);
5099 
5100     Node* length = end;
5101     if (_gvn.type(start) != TypeInt::ZERO) {
5102       length = _gvn.transform(new SubINode(end, start));
5103     }
5104 
5105     // Bail out if length is negative (i.e., if start > end).
5106     // Without this the new_array would throw
5107     // NegativeArraySizeException but IllegalArgumentException is what
5108     // should be thrown
5109     generate_negative_guard(length, bailout, &length);
5110 
5111     // Handle inline type arrays
5112     bool can_validate = !too_many_traps(Deoptimization::Reason_class_check);
5113     if (!stopped()) {
5114       // TODO JDK-8329224
5115       if (!orig_t->is_null_free()) {
5116         // Not statically known to be null free, add a check
5117         generate_fair_guard(null_free_array_test(original), bailout);
5118       }
5119       orig_t = _gvn.type(original)->isa_aryptr();
5120       if (orig_t != nullptr && orig_t->is_flat()) {
5121         // Src is flat, check that dest is flat as well
5122         if (exclude_flat) {
5123           // Dest can't be flat, bail out
5124           bailout->add_req(control());
5125           set_control(top());
5126         } else {
5127           generate_fair_guard(flat_array_test(refined_klass_node, /* flat = */ false), bailout);
5128         }
5129         // TODO 8350865 This is not correct anymore. Write tests and fix logic similar to arraycopy.
5130       } else if (UseArrayFlattening && (orig_t == nullptr || !orig_t->is_not_flat()) &&
5131                  // If dest is flat, src must be flat as well (guaranteed by src <: dest check if validated).
5132                  ((!tklass->is_flat() && tklass->can_be_inline_array()) || !can_validate)) {
5133         // Src might be flat and dest might not be flat. Go to the slow path if src is flat.
5134         // TODO 8251971: Optimize for the case when src/dest are later found to be both flat.
5135         generate_fair_guard(flat_array_test(load_object_klass(original)), bailout);
5136         if (orig_t != nullptr) {
5137           orig_t = orig_t->cast_to_not_flat();
5138           original = _gvn.transform(new CheckCastPPNode(control(), original, orig_t));
5139         }
5140       }
5141       if (!can_validate) {
5142         // No validation. The subtype check emitted at macro expansion time will not go to the slow
5143         // path but call checkcast_arraycopy which can not handle flat/null-free inline type arrays.
5144         // TODO 8251971: Optimize for the case when src/dest are later found to be both flat/null-free.
5145         generate_fair_guard(flat_array_test(refined_klass_node), bailout);
5146         generate_fair_guard(null_free_array_test(original), bailout);
5147       }
5148     }
5149 
5150     // Bail out if start is larger than the original length
5151     Node* orig_tail = _gvn.transform(new SubINode(orig_length, start));
5152     generate_negative_guard(orig_tail, bailout, &orig_tail);
5153 
5154     if (bailout->req() > 1) {
5155       PreserveJVMState pjvms(this);
5156       set_control(_gvn.transform(bailout));
5157       uncommon_trap(Deoptimization::Reason_intrinsic,
5158                     Deoptimization::Action_maybe_recompile);
5159     }
5160 
5161     if (!stopped()) {
5162       // How many elements will we copy from the original?
5163       // The answer is MinI(orig_tail, length).
5164       Node* moved = _gvn.transform(new MinINode(orig_tail, length));
5165 
5166       // Generate a direct call to the right arraycopy function(s).
5167       // We know the copy is disjoint but we might not know if the
5168       // oop stores need checking.
5169       // Extreme case:  Arrays.copyOf((Integer[])x, 10, String[].class).
5170       // This will fail a store-check if x contains any non-nulls.
5171 
5172       // ArrayCopyNode:Ideal may transform the ArrayCopyNode to
5173       // loads/stores but it is legal only if we're sure the
5174       // Arrays.copyOf would succeed. So we need all input arguments
5175       // to the copyOf to be validated, including that the copy to the
5176       // new array won't trigger an ArrayStoreException. That subtype
5177       // check can be optimized if we know something on the type of
5178       // the input array from type speculation.
5179       if (_gvn.type(klass_node)->singleton()) {
5180         const TypeKlassPtr* subk = _gvn.type(load_object_klass(original))->is_klassptr();
5181         const TypeKlassPtr* superk = _gvn.type(klass_node)->is_klassptr();
5182 
5183         int test = C->static_subtype_check(superk, subk);
5184         if (test != Compile::SSC_always_true && test != Compile::SSC_always_false) {
5185           const TypeOopPtr* t_original = _gvn.type(original)->is_oopptr();
5186           if (t_original->speculative_type() != nullptr) {
5187             original = maybe_cast_profiled_obj(original, t_original->speculative_type(), true);
5188           }
5189         }
5190       }
5191 
5192       bool validated = false;
5193       // Reason_class_check rather than Reason_intrinsic because we
5194       // want to intrinsify even if this traps.
5195       if (can_validate) {
5196         Node* not_subtype_ctrl = gen_subtype_check(original, klass_node);
5197 
5198         if (not_subtype_ctrl != top()) {
5199           PreserveJVMState pjvms(this);
5200           set_control(not_subtype_ctrl);
5201           uncommon_trap(Deoptimization::Reason_class_check,
5202                         Deoptimization::Action_make_not_entrant);
5203           assert(stopped(), "Should be stopped");
5204         }
5205         validated = true;
5206       }
5207 
5208       if (!stopped()) {
5209         newcopy = new_array(refined_klass_node, length, 0);  // no arguments to push
5210 
5211         ArrayCopyNode* ac = ArrayCopyNode::make(this, true, original, start, newcopy, intcon(0), moved, true, true,
5212                                                 load_object_klass(original), klass_node);
5213         if (!is_copyOfRange) {
5214           ac->set_copyof(validated);
5215         } else {
5216           ac->set_copyofrange(validated);
5217         }
5218         Node* n = _gvn.transform(ac);
5219         if (n == ac) {
5220           ac->connect_outputs(this);
5221         } else {
5222           assert(validated, "shouldn't transform if all arguments not validated");
5223           set_all_memory(n);
5224         }
5225       }
5226     }
5227   } // original reexecute is set back here
5228 
5229   C->set_has_split_ifs(true); // Has chance for split-if optimization
5230   if (!stopped()) {
5231     set_result(newcopy);
5232   }
5233   return true;
5234 }
5235 
5236 
5237 //----------------------generate_virtual_guard---------------------------
5238 // Helper for hashCode and clone.  Peeks inside the vtable to avoid a call.
5239 Node* LibraryCallKit::generate_virtual_guard(Node* obj_klass,
5240                                              RegionNode* slow_region) {
5241   ciMethod* method = callee();
5242   int vtable_index = method->vtable_index();
5243   assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index,
5244          "bad index %d", vtable_index);
5245   // Get the Method* out of the appropriate vtable entry.
5246   int entry_offset  = in_bytes(Klass::vtable_start_offset()) +
5247                      vtable_index*vtableEntry::size_in_bytes() +
5248                      in_bytes(vtableEntry::method_offset());
5249   Node* entry_addr  = basic_plus_adr(obj_klass, entry_offset);
5250   Node* target_call = make_load(nullptr, entry_addr, TypePtr::NOTNULL, T_ADDRESS, MemNode::unordered);
5251 
5252   // Compare the target method with the expected method (e.g., Object.hashCode).
5253   const TypePtr* native_call_addr = TypeMetadataPtr::make(method);
5254 
5255   Node* native_call = makecon(native_call_addr);
5256   Node* chk_native  = _gvn.transform(new CmpPNode(target_call, native_call));
5257   Node* test_native = _gvn.transform(new BoolNode(chk_native, BoolTest::ne));
5258 
5259   return generate_slow_guard(test_native, slow_region);
5260 }
5261 
5262 //-----------------------generate_method_call----------------------------
5263 // Use generate_method_call to make a slow-call to the real
5264 // method if the fast path fails.  An alternative would be to
5265 // use a stub like OptoRuntime::slow_arraycopy_Java.
5266 // This only works for expanding the current library call,
5267 // not another intrinsic.  (E.g., don't use this for making an
5268 // arraycopy call inside of the copyOf intrinsic.)
5269 CallJavaNode*
5270 LibraryCallKit::generate_method_call(vmIntrinsicID method_id, bool is_virtual, bool is_static, bool res_not_null) {
5271   // When compiling the intrinsic method itself, do not use this technique.
5272   guarantee(callee() != C->method(), "cannot make slow-call to self");
5273 
5274   ciMethod* method = callee();
5275   // ensure the JVMS we have will be correct for this call
5276   guarantee(method_id == method->intrinsic_id(), "must match");
5277 
5278   const TypeFunc* tf = TypeFunc::make(method);
5279   if (res_not_null) {
5280     assert(tf->return_type() == T_OBJECT, "");
5281     const TypeTuple* range = tf->range_cc();
5282     const Type** fields = TypeTuple::fields(range->cnt());
5283     fields[TypeFunc::Parms] = range->field_at(TypeFunc::Parms)->filter_speculative(TypePtr::NOTNULL);
5284     const TypeTuple* new_range = TypeTuple::make(range->cnt(), fields);
5285     tf = TypeFunc::make(tf->domain_cc(), new_range);
5286   }
5287   CallJavaNode* slow_call;
5288   if (is_static) {
5289     assert(!is_virtual, "");
5290     slow_call = new CallStaticJavaNode(C, tf,
5291                            SharedRuntime::get_resolve_static_call_stub(), method);
5292   } else if (is_virtual) {
5293     assert(!gvn().type(argument(0))->maybe_null(), "should not be null");
5294     int vtable_index = Method::invalid_vtable_index;
5295     if (UseInlineCaches) {
5296       // Suppress the vtable call
5297     } else {
5298       // hashCode and clone are not a miranda methods,
5299       // so the vtable index is fixed.
5300       // No need to use the linkResolver to get it.
5301        vtable_index = method->vtable_index();
5302        assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index,
5303               "bad index %d", vtable_index);
5304     }
5305     slow_call = new CallDynamicJavaNode(tf,
5306                           SharedRuntime::get_resolve_virtual_call_stub(),
5307                           method, vtable_index);
5308   } else {  // neither virtual nor static:  opt_virtual
5309     assert(!gvn().type(argument(0))->maybe_null(), "should not be null");
5310     slow_call = new CallStaticJavaNode(C, tf,
5311                                 SharedRuntime::get_resolve_opt_virtual_call_stub(), method);
5312     slow_call->set_optimized_virtual(true);
5313   }
5314   if (CallGenerator::is_inlined_method_handle_intrinsic(this->method(), bci(), callee())) {
5315     // To be able to issue a direct call (optimized virtual or virtual)
5316     // and skip a call to MH.linkTo*/invokeBasic adapter, additional information
5317     // about the method being invoked should be attached to the call site to
5318     // make resolution logic work (see SharedRuntime::resolve_{virtual,opt_virtual}_call_C).
5319     slow_call->set_override_symbolic_info(true);
5320   }
5321   set_arguments_for_java_call(slow_call);
5322   set_edges_for_java_call(slow_call);
5323   return slow_call;
5324 }
5325 
5326 
5327 /**
5328  * Build special case code for calls to hashCode on an object. This call may
5329  * be virtual (invokevirtual) or bound (invokespecial). For each case we generate
5330  * slightly different code.
5331  */
5332 bool LibraryCallKit::inline_native_hashcode(bool is_virtual, bool is_static) {
5333   assert(is_static == callee()->is_static(), "correct intrinsic selection");
5334   assert(!(is_virtual && is_static), "either virtual, special, or static");
5335 
5336   enum { _slow_path = 1, _fast_path, _null_path, PATH_LIMIT };
5337 
5338   RegionNode* result_reg = new RegionNode(PATH_LIMIT);
5339   PhiNode*    result_val = new PhiNode(result_reg, TypeInt::INT);
5340   PhiNode*    result_io  = new PhiNode(result_reg, Type::ABIO);
5341   PhiNode*    result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
5342   Node* obj = argument(0);
5343 
5344   // Don't intrinsify hashcode on inline types for now.
5345   // The "is locked" runtime check also subsumes the inline type check (as inline types cannot be locked) and goes to the slow path.
5346   if (gvn().type(obj)->is_inlinetypeptr()) {
5347     return false;
5348   }
5349 
5350   if (!is_static) {
5351     // Check for hashing null object
5352     obj = null_check_receiver();
5353     if (stopped())  return true;        // unconditionally null
5354     result_reg->init_req(_null_path, top());
5355     result_val->init_req(_null_path, top());
5356   } else {
5357     // Do a null check, and return zero if null.
5358     // System.identityHashCode(null) == 0
5359     Node* null_ctl = top();
5360     obj = null_check_oop(obj, &null_ctl);
5361     result_reg->init_req(_null_path, null_ctl);
5362     result_val->init_req(_null_path, _gvn.intcon(0));
5363   }
5364 
5365   // Unconditionally null?  Then return right away.
5366   if (stopped()) {
5367     set_control( result_reg->in(_null_path));
5368     if (!stopped())
5369       set_result(result_val->in(_null_path));
5370     return true;
5371   }
5372 
5373   // We only go to the fast case code if we pass a number of guards.  The
5374   // paths which do not pass are accumulated in the slow_region.
5375   RegionNode* slow_region = new RegionNode(1);
5376   record_for_igvn(slow_region);
5377 
5378   // If this is a virtual call, we generate a funny guard.  We pull out
5379   // the vtable entry corresponding to hashCode() from the target object.
5380   // If the target method which we are calling happens to be the native
5381   // Object hashCode() method, we pass the guard.  We do not need this
5382   // guard for non-virtual calls -- the caller is known to be the native
5383   // Object hashCode().
5384   if (is_virtual) {
5385     // After null check, get the object's klass.
5386     Node* obj_klass = load_object_klass(obj);
5387     generate_virtual_guard(obj_klass, slow_region);
5388   }
5389 
5390   // Get the header out of the object, use LoadMarkNode when available
5391   Node* header_addr = basic_plus_adr(obj, oopDesc::mark_offset_in_bytes());
5392   // The control of the load must be null. Otherwise, the load can move before
5393   // the null check after castPP removal.
5394   Node* no_ctrl = nullptr;
5395   Node* header = make_load(no_ctrl, header_addr, TypeX_X, TypeX_X->basic_type(), MemNode::unordered);
5396 
5397   if (!UseObjectMonitorTable) {
5398     // Test the header to see if it is safe to read w.r.t. locking.
5399     // We cannot use the inline type mask as this may check bits that are overriden
5400     // by an object monitor's pointer when inflating locking.
5401     Node *lock_mask      = _gvn.MakeConX(markWord::lock_mask_in_place);
5402     Node *lmasked_header = _gvn.transform(new AndXNode(header, lock_mask));
5403     Node *monitor_val   = _gvn.MakeConX(markWord::monitor_value);
5404     Node *chk_monitor   = _gvn.transform(new CmpXNode(lmasked_header, monitor_val));
5405     Node *test_monitor  = _gvn.transform(new BoolNode(chk_monitor, BoolTest::eq));
5406 
5407     generate_slow_guard(test_monitor, slow_region);
5408   }
5409 
5410   // Get the hash value and check to see that it has been properly assigned.
5411   // We depend on hash_mask being at most 32 bits and avoid the use of
5412   // hash_mask_in_place because it could be larger than 32 bits in a 64-bit
5413   // vm: see markWord.hpp.
5414   Node *hash_mask      = _gvn.intcon(markWord::hash_mask);
5415   Node *hash_shift     = _gvn.intcon(markWord::hash_shift);
5416   Node *hshifted_header= _gvn.transform(new URShiftXNode(header, hash_shift));
5417   // This hack lets the hash bits live anywhere in the mark object now, as long
5418   // as the shift drops the relevant bits into the low 32 bits.  Note that
5419   // Java spec says that HashCode is an int so there's no point in capturing
5420   // an 'X'-sized hashcode (32 in 32-bit build or 64 in 64-bit build).
5421   hshifted_header      = ConvX2I(hshifted_header);
5422   Node *hash_val       = _gvn.transform(new AndINode(hshifted_header, hash_mask));
5423 
5424   Node *no_hash_val    = _gvn.intcon(markWord::no_hash);
5425   Node *chk_assigned   = _gvn.transform(new CmpINode( hash_val, no_hash_val));
5426   Node *test_assigned  = _gvn.transform(new BoolNode( chk_assigned, BoolTest::eq));
5427 
5428   generate_slow_guard(test_assigned, slow_region);
5429 
5430   Node* init_mem = reset_memory();
5431   // fill in the rest of the null path:
5432   result_io ->init_req(_null_path, i_o());
5433   result_mem->init_req(_null_path, init_mem);
5434 
5435   result_val->init_req(_fast_path, hash_val);
5436   result_reg->init_req(_fast_path, control());
5437   result_io ->init_req(_fast_path, i_o());
5438   result_mem->init_req(_fast_path, init_mem);
5439 
5440   // Generate code for the slow case.  We make a call to hashCode().
5441   set_control(_gvn.transform(slow_region));
5442   if (!stopped()) {
5443     // No need for PreserveJVMState, because we're using up the present state.
5444     set_all_memory(init_mem);
5445     vmIntrinsics::ID hashCode_id = is_static ? vmIntrinsics::_identityHashCode : vmIntrinsics::_hashCode;
5446     CallJavaNode* slow_call = generate_method_call(hashCode_id, is_virtual, is_static, false);
5447     Node* slow_result = set_results_for_java_call(slow_call);
5448     // this->control() comes from set_results_for_java_call
5449     result_reg->init_req(_slow_path, control());
5450     result_val->init_req(_slow_path, slow_result);
5451     result_io  ->set_req(_slow_path, i_o());
5452     result_mem ->set_req(_slow_path, reset_memory());
5453   }
5454 
5455   // Return the combined state.
5456   set_i_o(        _gvn.transform(result_io)  );
5457   set_all_memory( _gvn.transform(result_mem));
5458 
5459   set_result(result_reg, result_val);
5460   return true;
5461 }
5462 
5463 //---------------------------inline_native_getClass----------------------------
5464 // public final native Class<?> java.lang.Object.getClass();
5465 //
5466 // Build special case code for calls to getClass on an object.
5467 bool LibraryCallKit::inline_native_getClass() {
5468   Node* obj = argument(0);
5469   if (obj->is_InlineType()) {
5470     const Type* t = _gvn.type(obj);
5471     if (t->maybe_null()) {
5472       null_check(obj);
5473     }
5474     set_result(makecon(TypeInstPtr::make(t->inline_klass()->java_mirror())));
5475     return true;
5476   }
5477   obj = null_check_receiver();
5478   if (stopped())  return true;
5479   set_result(load_mirror_from_klass(load_object_klass(obj)));
5480   return true;
5481 }
5482 
5483 //-----------------inline_native_Reflection_getCallerClass---------------------
5484 // public static native Class<?> sun.reflect.Reflection.getCallerClass();
5485 //
5486 // In the presence of deep enough inlining, getCallerClass() becomes a no-op.
5487 //
5488 // NOTE: This code must perform the same logic as JVM_GetCallerClass
5489 // in that it must skip particular security frames and checks for
5490 // caller sensitive methods.
5491 bool LibraryCallKit::inline_native_Reflection_getCallerClass() {
5492 #ifndef PRODUCT
5493   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5494     tty->print_cr("Attempting to inline sun.reflect.Reflection.getCallerClass");
5495   }
5496 #endif
5497 
5498   if (!jvms()->has_method()) {
5499 #ifndef PRODUCT
5500     if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5501       tty->print_cr("  Bailing out because intrinsic was inlined at top level");
5502     }
5503 #endif
5504     return false;
5505   }
5506 
5507   // Walk back up the JVM state to find the caller at the required
5508   // depth.
5509   JVMState* caller_jvms = jvms();
5510 
5511   // Cf. JVM_GetCallerClass
5512   // NOTE: Start the loop at depth 1 because the current JVM state does
5513   // not include the Reflection.getCallerClass() frame.
5514   for (int n = 1; caller_jvms != nullptr; caller_jvms = caller_jvms->caller(), n++) {
5515     ciMethod* m = caller_jvms->method();
5516     switch (n) {
5517     case 0:
5518       fatal("current JVM state does not include the Reflection.getCallerClass frame");
5519       break;
5520     case 1:
5521       // Frame 0 and 1 must be caller sensitive (see JVM_GetCallerClass).
5522       if (!m->caller_sensitive()) {
5523 #ifndef PRODUCT
5524         if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5525           tty->print_cr("  Bailing out: CallerSensitive annotation expected at frame %d", n);
5526         }
5527 #endif
5528         return false;  // bail-out; let JVM_GetCallerClass do the work
5529       }
5530       break;
5531     default:
5532       if (!m->is_ignored_by_security_stack_walk()) {
5533         // We have reached the desired frame; return the holder class.
5534         // Acquire method holder as java.lang.Class and push as constant.
5535         ciInstanceKlass* caller_klass = caller_jvms->method()->holder();
5536         ciInstance* caller_mirror = caller_klass->java_mirror();
5537         set_result(makecon(TypeInstPtr::make(caller_mirror)));
5538 
5539 #ifndef PRODUCT
5540         if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5541           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());
5542           tty->print_cr("  JVM state at this point:");
5543           for (int i = jvms()->depth(), n = 1; i >= 1; i--, n++) {
5544             ciMethod* m = jvms()->of_depth(i)->method();
5545             tty->print_cr("   %d) %s.%s", n, m->holder()->name()->as_utf8(), m->name()->as_utf8());
5546           }
5547         }
5548 #endif
5549         return true;
5550       }
5551       break;
5552     }
5553   }
5554 
5555 #ifndef PRODUCT
5556   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5557     tty->print_cr("  Bailing out because caller depth exceeded inlining depth = %d", jvms()->depth());
5558     tty->print_cr("  JVM state at this point:");
5559     for (int i = jvms()->depth(), n = 1; i >= 1; i--, n++) {
5560       ciMethod* m = jvms()->of_depth(i)->method();
5561       tty->print_cr("   %d) %s.%s", n, m->holder()->name()->as_utf8(), m->name()->as_utf8());
5562     }
5563   }
5564 #endif
5565 
5566   return false;  // bail-out; let JVM_GetCallerClass do the work
5567 }
5568 
5569 bool LibraryCallKit::inline_fp_conversions(vmIntrinsics::ID id) {
5570   Node* arg = argument(0);
5571   Node* result = nullptr;
5572 
5573   switch (id) {
5574   case vmIntrinsics::_floatToRawIntBits:    result = new MoveF2INode(arg);  break;
5575   case vmIntrinsics::_intBitsToFloat:       result = new MoveI2FNode(arg);  break;
5576   case vmIntrinsics::_doubleToRawLongBits:  result = new MoveD2LNode(arg);  break;
5577   case vmIntrinsics::_longBitsToDouble:     result = new MoveL2DNode(arg);  break;
5578   case vmIntrinsics::_floatToFloat16:       result = new ConvF2HFNode(arg); break;
5579   case vmIntrinsics::_float16ToFloat:       result = new ConvHF2FNode(arg); break;
5580 
5581   case vmIntrinsics::_doubleToLongBits: {
5582     // two paths (plus control) merge in a wood
5583     RegionNode *r = new RegionNode(3);
5584     Node *phi = new PhiNode(r, TypeLong::LONG);
5585 
5586     Node *cmpisnan = _gvn.transform(new CmpDNode(arg, arg));
5587     // Build the boolean node
5588     Node *bolisnan = _gvn.transform(new BoolNode(cmpisnan, BoolTest::ne));
5589 
5590     // Branch either way.
5591     // NaN case is less traveled, which makes all the difference.
5592     IfNode *ifisnan = create_and_xform_if(control(), bolisnan, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
5593     Node *opt_isnan = _gvn.transform(ifisnan);
5594     assert( opt_isnan->is_If(), "Expect an IfNode");
5595     IfNode *opt_ifisnan = (IfNode*)opt_isnan;
5596     Node *iftrue = _gvn.transform(new IfTrueNode(opt_ifisnan));
5597 
5598     set_control(iftrue);
5599 
5600     static const jlong nan_bits = CONST64(0x7ff8000000000000);
5601     Node *slow_result = longcon(nan_bits); // return NaN
5602     phi->init_req(1, _gvn.transform( slow_result ));
5603     r->init_req(1, iftrue);
5604 
5605     // Else fall through
5606     Node *iffalse = _gvn.transform(new IfFalseNode(opt_ifisnan));
5607     set_control(iffalse);
5608 
5609     phi->init_req(2, _gvn.transform(new MoveD2LNode(arg)));
5610     r->init_req(2, iffalse);
5611 
5612     // Post merge
5613     set_control(_gvn.transform(r));
5614     record_for_igvn(r);
5615 
5616     C->set_has_split_ifs(true); // Has chance for split-if optimization
5617     result = phi;
5618     assert(result->bottom_type()->isa_long(), "must be");
5619     break;
5620   }
5621 
5622   case vmIntrinsics::_floatToIntBits: {
5623     // two paths (plus control) merge in a wood
5624     RegionNode *r = new RegionNode(3);
5625     Node *phi = new PhiNode(r, TypeInt::INT);
5626 
5627     Node *cmpisnan = _gvn.transform(new CmpFNode(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 jint nan_bits = 0x7fc00000;
5642     Node *slow_result = makecon(TypeInt::make(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 MoveF2INode(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_int(), "must be");
5660     break;
5661   }
5662 
5663   default:
5664     fatal_unexpected_iid(id);
5665     break;
5666   }
5667   set_result(_gvn.transform(result));
5668   return true;
5669 }
5670 
5671 bool LibraryCallKit::inline_fp_range_check(vmIntrinsics::ID id) {
5672   Node* arg = argument(0);
5673   Node* result = nullptr;
5674 
5675   switch (id) {
5676   case vmIntrinsics::_floatIsInfinite:
5677     result = new IsInfiniteFNode(arg);
5678     break;
5679   case vmIntrinsics::_floatIsFinite:
5680     result = new IsFiniteFNode(arg);
5681     break;
5682   case vmIntrinsics::_doubleIsInfinite:
5683     result = new IsInfiniteDNode(arg);
5684     break;
5685   case vmIntrinsics::_doubleIsFinite:
5686     result = new IsFiniteDNode(arg);
5687     break;
5688   default:
5689     fatal_unexpected_iid(id);
5690     break;
5691   }
5692   set_result(_gvn.transform(result));
5693   return true;
5694 }
5695 
5696 //----------------------inline_unsafe_copyMemory-------------------------
5697 // public native void Unsafe.copyMemory0(Object srcBase, long srcOffset, Object destBase, long destOffset, long bytes);
5698 
5699 static bool has_wide_mem(PhaseGVN& gvn, Node* addr, Node* base) {
5700   const TypeAryPtr* addr_t = gvn.type(addr)->isa_aryptr();
5701   const Type*       base_t = gvn.type(base);
5702 
5703   bool in_native = (base_t == TypePtr::NULL_PTR);
5704   bool in_heap   = !TypePtr::NULL_PTR->higher_equal(base_t);
5705   bool is_mixed  = !in_heap && !in_native;
5706 
5707   if (is_mixed) {
5708     return true; // mixed accesses can touch both on-heap and off-heap memory
5709   }
5710   if (in_heap) {
5711     bool is_prim_array = (addr_t != nullptr) && (addr_t->elem() != Type::BOTTOM);
5712     if (!is_prim_array) {
5713       // Though Unsafe.copyMemory() ensures at runtime for on-heap accesses that base is a primitive array,
5714       // there's not enough type information available to determine proper memory slice for it.
5715       return true;
5716     }
5717   }
5718   return false;
5719 }
5720 
5721 bool LibraryCallKit::inline_unsafe_copyMemory() {
5722   if (callee()->is_static())  return false;  // caller must have the capability!
5723   null_check_receiver();  // null-check receiver
5724   if (stopped())  return true;
5725 
5726   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
5727 
5728   Node* src_base =         argument(1);  // type: oop
5729   Node* src_off  = ConvL2X(argument(2)); // type: long
5730   Node* dst_base =         argument(4);  // type: oop
5731   Node* dst_off  = ConvL2X(argument(5)); // type: long
5732   Node* size     = ConvL2X(argument(7)); // type: long
5733 
5734   assert(Unsafe_field_offset_to_byte_offset(11) == 11,
5735          "fieldOffset must be byte-scaled");
5736 
5737   Node* src_addr = make_unsafe_address(src_base, src_off);
5738   Node* dst_addr = make_unsafe_address(dst_base, dst_off);
5739 
5740   Node* thread = _gvn.transform(new ThreadLocalNode());
5741   Node* doing_unsafe_access_addr = basic_plus_adr(top(), thread, in_bytes(JavaThread::doing_unsafe_access_offset()));
5742   BasicType doing_unsafe_access_bt = T_BYTE;
5743   assert((sizeof(bool) * CHAR_BIT) == 8, "not implemented");
5744 
5745   // update volatile field
5746   store_to_memory(control(), doing_unsafe_access_addr, intcon(1), doing_unsafe_access_bt, MemNode::unordered);
5747 
5748   int flags = RC_LEAF | RC_NO_FP;
5749 
5750   const TypePtr* dst_type = TypePtr::BOTTOM;
5751 
5752   // Adjust memory effects of the runtime call based on input values.
5753   if (!has_wide_mem(_gvn, src_addr, src_base) &&
5754       !has_wide_mem(_gvn, dst_addr, dst_base)) {
5755     dst_type = _gvn.type(dst_addr)->is_ptr(); // narrow out memory
5756 
5757     const TypePtr* src_type = _gvn.type(src_addr)->is_ptr();
5758     if (C->get_alias_index(src_type) == C->get_alias_index(dst_type)) {
5759       flags |= RC_NARROW_MEM; // narrow in memory
5760     }
5761   }
5762 
5763   // Call it.  Note that the length argument is not scaled.
5764   make_runtime_call(flags,
5765                     OptoRuntime::fast_arraycopy_Type(),
5766                     StubRoutines::unsafe_arraycopy(),
5767                     "unsafe_arraycopy",
5768                     dst_type,
5769                     src_addr, dst_addr, size XTOP);
5770 
5771   store_to_memory(control(), doing_unsafe_access_addr, intcon(0), doing_unsafe_access_bt, MemNode::unordered);
5772 
5773   return true;
5774 }
5775 
5776 // unsafe_setmemory(void *base, ulong offset, size_t length, char fill_value);
5777 // Fill 'length' bytes starting from 'base[offset]' with 'fill_value'
5778 bool LibraryCallKit::inline_unsafe_setMemory() {
5779   if (callee()->is_static())  return false;  // caller must have the capability!
5780   null_check_receiver();  // null-check receiver
5781   if (stopped())  return true;
5782 
5783   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
5784 
5785   Node* dst_base =         argument(1);  // type: oop
5786   Node* dst_off  = ConvL2X(argument(2)); // type: long
5787   Node* size     = ConvL2X(argument(4)); // type: long
5788   Node* byte     =         argument(6);  // type: byte
5789 
5790   assert(Unsafe_field_offset_to_byte_offset(11) == 11,
5791          "fieldOffset must be byte-scaled");
5792 
5793   Node* dst_addr = make_unsafe_address(dst_base, dst_off);
5794 
5795   Node* thread = _gvn.transform(new ThreadLocalNode());
5796   Node* doing_unsafe_access_addr = basic_plus_adr(top(), thread, in_bytes(JavaThread::doing_unsafe_access_offset()));
5797   BasicType doing_unsafe_access_bt = T_BYTE;
5798   assert((sizeof(bool) * CHAR_BIT) == 8, "not implemented");
5799 
5800   // update volatile field
5801   store_to_memory(control(), doing_unsafe_access_addr, intcon(1), doing_unsafe_access_bt, MemNode::unordered);
5802 
5803   int flags = RC_LEAF | RC_NO_FP;
5804 
5805   const TypePtr* dst_type = TypePtr::BOTTOM;
5806 
5807   // Adjust memory effects of the runtime call based on input values.
5808   if (!has_wide_mem(_gvn, dst_addr, dst_base)) {
5809     dst_type = _gvn.type(dst_addr)->is_ptr(); // narrow out memory
5810 
5811     flags |= RC_NARROW_MEM; // narrow in memory
5812   }
5813 
5814   // Call it.  Note that the length argument is not scaled.
5815   make_runtime_call(flags,
5816                     OptoRuntime::unsafe_setmemory_Type(),
5817                     StubRoutines::unsafe_setmemory(),
5818                     "unsafe_setmemory",
5819                     dst_type,
5820                     dst_addr, size XTOP, byte);
5821 
5822   store_to_memory(control(), doing_unsafe_access_addr, intcon(0), doing_unsafe_access_bt, MemNode::unordered);
5823 
5824   return true;
5825 }
5826 
5827 #undef XTOP
5828 
5829 //------------------------clone_coping-----------------------------------
5830 // Helper function for inline_native_clone.
5831 void LibraryCallKit::copy_to_clone(Node* obj, Node* alloc_obj, Node* obj_size, bool is_array) {
5832   assert(obj_size != nullptr, "");
5833   Node* raw_obj = alloc_obj->in(1);
5834   assert(alloc_obj->is_CheckCastPP() && raw_obj->is_Proj() && raw_obj->in(0)->is_Allocate(), "");
5835 
5836   AllocateNode* alloc = nullptr;
5837   if (ReduceBulkZeroing &&
5838       // If we are implementing an array clone without knowing its source type
5839       // (can happen when compiling the array-guarded branch of a reflective
5840       // Object.clone() invocation), initialize the array within the allocation.
5841       // This is needed because some GCs (e.g. ZGC) might fall back in this case
5842       // to a runtime clone call that assumes fully initialized source arrays.
5843       (!is_array || obj->get_ptr_type()->isa_aryptr() != nullptr)) {
5844     // We will be completely responsible for initializing this object -
5845     // mark Initialize node as complete.
5846     alloc = AllocateNode::Ideal_allocation(alloc_obj);
5847     // The object was just allocated - there should be no any stores!
5848     guarantee(alloc != nullptr && alloc->maybe_set_complete(&_gvn), "");
5849     // Mark as complete_with_arraycopy so that on AllocateNode
5850     // expansion, we know this AllocateNode is initialized by an array
5851     // copy and a StoreStore barrier exists after the array copy.
5852     alloc->initialization()->set_complete_with_arraycopy();
5853   }
5854 
5855   Node* size = _gvn.transform(obj_size);
5856   access_clone(obj, alloc_obj, size, is_array);
5857 
5858   // Do not let reads from the cloned object float above the arraycopy.
5859   if (alloc != nullptr) {
5860     // Do not let stores that initialize this object be reordered with
5861     // a subsequent store that would make this object accessible by
5862     // other threads.
5863     // Record what AllocateNode this StoreStore protects so that
5864     // escape analysis can go from the MemBarStoreStoreNode to the
5865     // AllocateNode and eliminate the MemBarStoreStoreNode if possible
5866     // based on the escape status of the AllocateNode.
5867     insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
5868   } else {
5869     insert_mem_bar(Op_MemBarCPUOrder);
5870   }
5871 }
5872 
5873 //------------------------inline_native_clone----------------------------
5874 // protected native Object java.lang.Object.clone();
5875 //
5876 // Here are the simple edge cases:
5877 //  null receiver => normal trap
5878 //  virtual and clone was overridden => slow path to out-of-line clone
5879 //  not cloneable or finalizer => slow path to out-of-line Object.clone
5880 //
5881 // The general case has two steps, allocation and copying.
5882 // Allocation has two cases, and uses GraphKit::new_instance or new_array.
5883 //
5884 // Copying also has two cases, oop arrays and everything else.
5885 // Oop arrays use arrayof_oop_arraycopy (same as System.arraycopy).
5886 // Everything else uses the tight inline loop supplied by CopyArrayNode.
5887 //
5888 // These steps fold up nicely if and when the cloned object's klass
5889 // can be sharply typed as an object array, a type array, or an instance.
5890 //
5891 bool LibraryCallKit::inline_native_clone(bool is_virtual) {
5892   PhiNode* result_val;
5893 
5894   // Set the reexecute bit for the interpreter to reexecute
5895   // the bytecode that invokes Object.clone if deoptimization happens.
5896   { PreserveReexecuteState preexecs(this);
5897     jvms()->set_should_reexecute(true);
5898 
5899     Node* obj = argument(0);
5900     obj = null_check_receiver();
5901     if (stopped())  return true;
5902 
5903     const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
5904     if (obj_type->is_inlinetypeptr()) {
5905       // If the object to clone is an inline type, we can simply return it (i.e. a nop) since inline types have
5906       // no identity.
5907       set_result(obj);
5908       return true;
5909     }
5910 
5911     // If we are going to clone an instance, we need its exact type to
5912     // know the number and types of fields to convert the clone to
5913     // loads/stores. Maybe a speculative type can help us.
5914     if (!obj_type->klass_is_exact() &&
5915         obj_type->speculative_type() != nullptr &&
5916         obj_type->speculative_type()->is_instance_klass() &&
5917         !obj_type->speculative_type()->is_inlinetype()) {
5918       ciInstanceKlass* spec_ik = obj_type->speculative_type()->as_instance_klass();
5919       if (spec_ik->nof_nonstatic_fields() <= ArrayCopyLoadStoreMaxElem &&
5920           !spec_ik->has_injected_fields()) {
5921         if (!obj_type->isa_instptr() ||
5922             obj_type->is_instptr()->instance_klass()->has_subklass()) {
5923           obj = maybe_cast_profiled_obj(obj, obj_type->speculative_type(), false);
5924         }
5925       }
5926     }
5927 
5928     // Conservatively insert a memory barrier on all memory slices.
5929     // Do not let writes into the original float below the clone.
5930     insert_mem_bar(Op_MemBarCPUOrder);
5931 
5932     // paths into result_reg:
5933     enum {
5934       _slow_path = 1,     // out-of-line call to clone method (virtual or not)
5935       _objArray_path,     // plain array allocation, plus arrayof_oop_arraycopy
5936       _array_path,        // plain array allocation, plus arrayof_long_arraycopy
5937       _instance_path,     // plain instance allocation, plus arrayof_long_arraycopy
5938       PATH_LIMIT
5939     };
5940     RegionNode* result_reg = new RegionNode(PATH_LIMIT);
5941     result_val             = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
5942     PhiNode*    result_i_o = new PhiNode(result_reg, Type::ABIO);
5943     PhiNode*    result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
5944     record_for_igvn(result_reg);
5945 
5946     Node* obj_klass = load_object_klass(obj);
5947     // We only go to the fast case code if we pass a number of guards.
5948     // The paths which do not pass are accumulated in the slow_region.
5949     RegionNode* slow_region = new RegionNode(1);
5950     record_for_igvn(slow_region);
5951 
5952     Node* array_obj = obj;
5953     Node* array_ctl = generate_array_guard(obj_klass, (RegionNode*)nullptr, &array_obj);
5954     if (array_ctl != nullptr) {
5955       // It's an array.
5956       PreserveJVMState pjvms(this);
5957       set_control(array_ctl);
5958 
5959       BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
5960       const TypeAryPtr* ary_ptr = obj_type->isa_aryptr();
5961       if (UseArrayFlattening && bs->array_copy_requires_gc_barriers(true, T_OBJECT, true, false, BarrierSetC2::Expansion) &&
5962           obj_type->can_be_inline_array() &&
5963           (ary_ptr == nullptr || (!ary_ptr->is_not_flat() && (!ary_ptr->is_flat() || ary_ptr->elem()->inline_klass()->contains_oops())))) {
5964         // Flat inline type array may have object field that would require a
5965         // write barrier. Conservatively, go to slow path.
5966         generate_fair_guard(flat_array_test(obj_klass), slow_region);
5967       }
5968 
5969       if (!stopped()) {
5970         Node* obj_length = load_array_length(array_obj);
5971         Node* array_size = nullptr; // Size of the array without object alignment padding.
5972         Node* alloc_obj = new_array(obj_klass, obj_length, 0, &array_size, /*deoptimize_on_exception=*/true);
5973 
5974         BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
5975         if (bs->array_copy_requires_gc_barriers(true, T_OBJECT, true, false, BarrierSetC2::Parsing)) {
5976           // If it is an oop array, it requires very special treatment,
5977           // because gc barriers are required when accessing the array.
5978           Node* is_obja = generate_refArray_guard(obj_klass, (RegionNode*)nullptr);
5979           if (is_obja != nullptr) {
5980             PreserveJVMState pjvms2(this);
5981             set_control(is_obja);
5982             // Generate a direct call to the right arraycopy function(s).
5983             // Clones are always tightly coupled.
5984             ArrayCopyNode* ac = ArrayCopyNode::make(this, true, array_obj, intcon(0), alloc_obj, intcon(0), obj_length, true, false);
5985             ac->set_clone_oop_array();
5986             Node* n = _gvn.transform(ac);
5987             assert(n == ac, "cannot disappear");
5988             ac->connect_outputs(this, /*deoptimize_on_exception=*/true);
5989 
5990             result_reg->init_req(_objArray_path, control());
5991             result_val->init_req(_objArray_path, alloc_obj);
5992             result_i_o ->set_req(_objArray_path, i_o());
5993             result_mem ->set_req(_objArray_path, reset_memory());
5994           }
5995         }
5996         // Otherwise, there are no barriers to worry about.
5997         // (We can dispense with card marks if we know the allocation
5998         //  comes out of eden (TLAB)...  In fact, ReduceInitialCardMarks
5999         //  causes the non-eden paths to take compensating steps to
6000         //  simulate a fresh allocation, so that no further
6001         //  card marks are required in compiled code to initialize
6002         //  the object.)
6003 
6004         if (!stopped()) {
6005           copy_to_clone(obj, alloc_obj, array_size, true);
6006 
6007           // Present the results of the copy.
6008           result_reg->init_req(_array_path, control());
6009           result_val->init_req(_array_path, alloc_obj);
6010           result_i_o ->set_req(_array_path, i_o());
6011           result_mem ->set_req(_array_path, reset_memory());
6012         }
6013       }
6014     }
6015 
6016     if (!stopped()) {
6017       // It's an instance (we did array above).  Make the slow-path tests.
6018       // If this is a virtual call, we generate a funny guard.  We grab
6019       // the vtable entry corresponding to clone() from the target object.
6020       // If the target method which we are calling happens to be the
6021       // Object clone() method, we pass the guard.  We do not need this
6022       // guard for non-virtual calls; the caller is known to be the native
6023       // Object clone().
6024       if (is_virtual) {
6025         generate_virtual_guard(obj_klass, slow_region);
6026       }
6027 
6028       // The object must be easily cloneable and must not have a finalizer.
6029       // Both of these conditions may be checked in a single test.
6030       // We could optimize the test further, but we don't care.
6031       generate_misc_flags_guard(obj_klass,
6032                                 // Test both conditions:
6033                                 KlassFlags::_misc_is_cloneable_fast | KlassFlags::_misc_has_finalizer,
6034                                 // Must be cloneable but not finalizer:
6035                                 KlassFlags::_misc_is_cloneable_fast,
6036                                 slow_region);
6037     }
6038 
6039     if (!stopped()) {
6040       // It's an instance, and it passed the slow-path tests.
6041       PreserveJVMState pjvms(this);
6042       Node* obj_size = nullptr; // Total object size, including object alignment padding.
6043       // Need to deoptimize on exception from allocation since Object.clone intrinsic
6044       // is reexecuted if deoptimization occurs and there could be problems when merging
6045       // exception state between multiple Object.clone versions (reexecute=true vs reexecute=false).
6046       Node* alloc_obj = new_instance(obj_klass, nullptr, &obj_size, /*deoptimize_on_exception=*/true);
6047 
6048       copy_to_clone(obj, alloc_obj, obj_size, false);
6049 
6050       // Present the results of the slow call.
6051       result_reg->init_req(_instance_path, control());
6052       result_val->init_req(_instance_path, alloc_obj);
6053       result_i_o ->set_req(_instance_path, i_o());
6054       result_mem ->set_req(_instance_path, reset_memory());
6055     }
6056 
6057     // Generate code for the slow case.  We make a call to clone().
6058     set_control(_gvn.transform(slow_region));
6059     if (!stopped()) {
6060       PreserveJVMState pjvms(this);
6061       CallJavaNode* slow_call = generate_method_call(vmIntrinsics::_clone, is_virtual, false, true);
6062       // We need to deoptimize on exception (see comment above)
6063       Node* slow_result = set_results_for_java_call(slow_call, false, /* deoptimize */ true);
6064       // this->control() comes from set_results_for_java_call
6065       result_reg->init_req(_slow_path, control());
6066       result_val->init_req(_slow_path, slow_result);
6067       result_i_o ->set_req(_slow_path, i_o());
6068       result_mem ->set_req(_slow_path, reset_memory());
6069     }
6070 
6071     // Return the combined state.
6072     set_control(    _gvn.transform(result_reg));
6073     set_i_o(        _gvn.transform(result_i_o));
6074     set_all_memory( _gvn.transform(result_mem));
6075   } // original reexecute is set back here
6076 
6077   set_result(_gvn.transform(result_val));
6078   return true;
6079 }
6080 
6081 // If we have a tightly coupled allocation, the arraycopy may take care
6082 // of the array initialization. If one of the guards we insert between
6083 // the allocation and the arraycopy causes a deoptimization, an
6084 // uninitialized array will escape the compiled method. To prevent that
6085 // we set the JVM state for uncommon traps between the allocation and
6086 // the arraycopy to the state before the allocation so, in case of
6087 // deoptimization, we'll reexecute the allocation and the
6088 // initialization.
6089 JVMState* LibraryCallKit::arraycopy_restore_alloc_state(AllocateArrayNode* alloc, int& saved_reexecute_sp) {
6090   if (alloc != nullptr) {
6091     ciMethod* trap_method = alloc->jvms()->method();
6092     int trap_bci = alloc->jvms()->bci();
6093 
6094     if (!C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_intrinsic) &&
6095         !C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_null_check)) {
6096       // Make sure there's no store between the allocation and the
6097       // arraycopy otherwise visible side effects could be rexecuted
6098       // in case of deoptimization and cause incorrect execution.
6099       bool no_interfering_store = true;
6100       Node* mem = alloc->in(TypeFunc::Memory);
6101       if (mem->is_MergeMem()) {
6102         for (MergeMemStream mms(merged_memory(), mem->as_MergeMem()); mms.next_non_empty2(); ) {
6103           Node* n = mms.memory();
6104           if (n != mms.memory2() && !(n->is_Proj() && n->in(0) == alloc->initialization())) {
6105             assert(n->is_Store(), "what else?");
6106             no_interfering_store = false;
6107             break;
6108           }
6109         }
6110       } else {
6111         for (MergeMemStream mms(merged_memory()); mms.next_non_empty(); ) {
6112           Node* n = mms.memory();
6113           if (n != mem && !(n->is_Proj() && n->in(0) == alloc->initialization())) {
6114             assert(n->is_Store(), "what else?");
6115             no_interfering_store = false;
6116             break;
6117           }
6118         }
6119       }
6120 
6121       if (no_interfering_store) {
6122         SafePointNode* sfpt = create_safepoint_with_state_before_array_allocation(alloc);
6123 
6124         JVMState* saved_jvms = jvms();
6125         saved_reexecute_sp = _reexecute_sp;
6126 
6127         set_jvms(sfpt->jvms());
6128         _reexecute_sp = jvms()->sp();
6129 
6130         return saved_jvms;
6131       }
6132     }
6133   }
6134   return nullptr;
6135 }
6136 
6137 // Clone the JVMState of the array allocation and create a new safepoint with it. Re-push the array length to the stack
6138 // such that uncommon traps can be emitted to re-execute the array allocation in the interpreter.
6139 SafePointNode* LibraryCallKit::create_safepoint_with_state_before_array_allocation(const AllocateArrayNode* alloc) const {
6140   JVMState* old_jvms = alloc->jvms()->clone_shallow(C);
6141   uint size = alloc->req();
6142   SafePointNode* sfpt = new SafePointNode(size, old_jvms);
6143   old_jvms->set_map(sfpt);
6144   for (uint i = 0; i < size; i++) {
6145     sfpt->init_req(i, alloc->in(i));
6146   }
6147   int adjustment = 1;
6148   const TypeAryKlassPtr* ary_klass_ptr = alloc->in(AllocateNode::KlassNode)->bottom_type()->is_aryklassptr();
6149   if (ary_klass_ptr->is_null_free()) {
6150     // A null-free, tightly coupled array allocation can only come from LibraryCallKit::inline_newArray which
6151     // also requires the componentType and initVal on stack for re-execution.
6152     // Re-create and push the componentType.
6153     ciArrayKlass* klass = ary_klass_ptr->exact_klass()->as_array_klass();
6154     ciInstance* instance = klass->component_mirror_instance();
6155     const TypeInstPtr* t_instance = TypeInstPtr::make(instance);
6156     sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp(), makecon(t_instance));
6157     adjustment++;
6158   }
6159   // re-push array length for deoptimization
6160   sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp() + adjustment - 1, alloc->in(AllocateNode::ALength));
6161   if (ary_klass_ptr->is_null_free()) {
6162     // Re-create and push the initVal.
6163     Node* init_val = alloc->in(AllocateNode::InitValue);
6164     if (init_val == nullptr) {
6165       init_val = InlineTypeNode::make_all_zero(_gvn, ary_klass_ptr->elem()->is_instklassptr()->instance_klass()->as_inline_klass());
6166     } else if (UseCompressedOops) {
6167       init_val = _gvn.transform(new DecodeNNode(init_val, init_val->bottom_type()->make_ptr()));
6168     }
6169     sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp() + adjustment, init_val);
6170     adjustment++;
6171   }
6172   old_jvms->set_sp(old_jvms->sp() + adjustment);
6173   old_jvms->set_monoff(old_jvms->monoff() + adjustment);
6174   old_jvms->set_scloff(old_jvms->scloff() + adjustment);
6175   old_jvms->set_endoff(old_jvms->endoff() + adjustment);
6176   old_jvms->set_should_reexecute(true);
6177 
6178   sfpt->set_i_o(map()->i_o());
6179   sfpt->set_memory(map()->memory());
6180   sfpt->set_control(map()->control());
6181   return sfpt;
6182 }
6183 
6184 // In case of a deoptimization, we restart execution at the
6185 // allocation, allocating a new array. We would leave an uninitialized
6186 // array in the heap that GCs wouldn't expect. Move the allocation
6187 // after the traps so we don't allocate the array if we
6188 // deoptimize. This is possible because tightly_coupled_allocation()
6189 // guarantees there's no observer of the allocated array at this point
6190 // and the control flow is simple enough.
6191 void LibraryCallKit::arraycopy_move_allocation_here(AllocateArrayNode* alloc, Node* dest, JVMState* saved_jvms_before_guards,
6192                                                     int saved_reexecute_sp, uint new_idx) {
6193   if (saved_jvms_before_guards != nullptr && !stopped()) {
6194     replace_unrelated_uncommon_traps_with_alloc_state(alloc, saved_jvms_before_guards);
6195 
6196     assert(alloc != nullptr, "only with a tightly coupled allocation");
6197     // restore JVM state to the state at the arraycopy
6198     saved_jvms_before_guards->map()->set_control(map()->control());
6199     assert(saved_jvms_before_guards->map()->memory() == map()->memory(), "memory state changed?");
6200     assert(saved_jvms_before_guards->map()->i_o() == map()->i_o(), "IO state changed?");
6201     // If we've improved the types of some nodes (null check) while
6202     // emitting the guards, propagate them to the current state
6203     map()->replaced_nodes().apply(saved_jvms_before_guards->map(), new_idx);
6204     set_jvms(saved_jvms_before_guards);
6205     _reexecute_sp = saved_reexecute_sp;
6206 
6207     // Remove the allocation from above the guards
6208     CallProjections* callprojs = alloc->extract_projections(true);
6209     InitializeNode* init = alloc->initialization();
6210     Node* alloc_mem = alloc->in(TypeFunc::Memory);
6211     C->gvn_replace_by(callprojs->fallthrough_ioproj, alloc->in(TypeFunc::I_O));
6212     C->gvn_replace_by(init->proj_out(TypeFunc::Memory), alloc_mem);
6213 
6214     // The CastIINode created in GraphKit::new_array (in AllocateArrayNode::make_ideal_length) must stay below
6215     // the allocation (i.e. is only valid if the allocation succeeds):
6216     // 1) replace CastIINode with AllocateArrayNode's length here
6217     // 2) Create CastIINode again once allocation has moved (see below) at the end of this method
6218     //
6219     // Multiple identical CastIINodes might exist here. Each GraphKit::load_array_length() call will generate
6220     // new separate CastIINode (arraycopy guard checks or any array length use between array allocation and ararycopy)
6221     Node* init_control = init->proj_out(TypeFunc::Control);
6222     Node* alloc_length = alloc->Ideal_length();
6223 #ifdef ASSERT
6224     Node* prev_cast = nullptr;
6225 #endif
6226     for (uint i = 0; i < init_control->outcnt(); i++) {
6227       Node* init_out = init_control->raw_out(i);
6228       if (init_out->is_CastII() && init_out->in(TypeFunc::Control) == init_control && init_out->in(1) == alloc_length) {
6229 #ifdef ASSERT
6230         if (prev_cast == nullptr) {
6231           prev_cast = init_out;
6232         } else {
6233           if (prev_cast->cmp(*init_out) == false) {
6234             prev_cast->dump();
6235             init_out->dump();
6236             assert(false, "not equal CastIINode");
6237           }
6238         }
6239 #endif
6240         C->gvn_replace_by(init_out, alloc_length);
6241       }
6242     }
6243     C->gvn_replace_by(init->proj_out(TypeFunc::Control), alloc->in(0));
6244 
6245     // move the allocation here (after the guards)
6246     _gvn.hash_delete(alloc);
6247     alloc->set_req(TypeFunc::Control, control());
6248     alloc->set_req(TypeFunc::I_O, i_o());
6249     Node *mem = reset_memory();
6250     set_all_memory(mem);
6251     alloc->set_req(TypeFunc::Memory, mem);
6252     set_control(init->proj_out_or_null(TypeFunc::Control));
6253     set_i_o(callprojs->fallthrough_ioproj);
6254 
6255     // Update memory as done in GraphKit::set_output_for_allocation()
6256     const TypeInt* length_type = _gvn.find_int_type(alloc->in(AllocateNode::ALength));
6257     const TypeOopPtr* ary_type = _gvn.type(alloc->in(AllocateNode::KlassNode))->is_klassptr()->as_instance_type();
6258     if (ary_type->isa_aryptr() && length_type != nullptr) {
6259       ary_type = ary_type->is_aryptr()->cast_to_size(length_type);
6260     }
6261     const TypePtr* telemref = ary_type->add_offset(Type::OffsetBot);
6262     int            elemidx  = C->get_alias_index(telemref);
6263     set_memory(init->proj_out_or_null(TypeFunc::Memory), Compile::AliasIdxRaw);
6264     set_memory(init->proj_out_or_null(TypeFunc::Memory), elemidx);
6265 
6266     Node* allocx = _gvn.transform(alloc);
6267     assert(allocx == alloc, "where has the allocation gone?");
6268     assert(dest->is_CheckCastPP(), "not an allocation result?");
6269 
6270     _gvn.hash_delete(dest);
6271     dest->set_req(0, control());
6272     Node* destx = _gvn.transform(dest);
6273     assert(destx == dest, "where has the allocation result gone?");
6274 
6275     array_ideal_length(alloc, ary_type, true);
6276   }
6277 }
6278 
6279 // Unrelated UCTs between the array allocation and the array copy, which are considered safe by tightly_coupled_allocation(),
6280 // need to be replaced by an UCT with a state before the array allocation (including the array length). This is necessary
6281 // because we could hit one of these UCTs (which are executed before the emitted array copy guards and the actual array
6282 // allocation which is moved down in arraycopy_move_allocation_here()). When later resuming execution in the interpreter,
6283 // we would have wrongly skipped the array allocation. To prevent this, we resume execution at the array allocation in
6284 // the interpreter similar to what we are doing for the newly emitted guards for the array copy.
6285 void LibraryCallKit::replace_unrelated_uncommon_traps_with_alloc_state(AllocateArrayNode* alloc,
6286                                                                        JVMState* saved_jvms_before_guards) {
6287   if (saved_jvms_before_guards->map()->control()->is_IfProj()) {
6288     // There is at least one unrelated uncommon trap which needs to be replaced.
6289     SafePointNode* sfpt = create_safepoint_with_state_before_array_allocation(alloc);
6290 
6291     JVMState* saved_jvms = jvms();
6292     const int saved_reexecute_sp = _reexecute_sp;
6293     set_jvms(sfpt->jvms());
6294     _reexecute_sp = jvms()->sp();
6295 
6296     replace_unrelated_uncommon_traps_with_alloc_state(saved_jvms_before_guards);
6297 
6298     // Restore state
6299     set_jvms(saved_jvms);
6300     _reexecute_sp = saved_reexecute_sp;
6301   }
6302 }
6303 
6304 // Replace the unrelated uncommon traps with new uncommon trap nodes by reusing the action and reason. The new uncommon
6305 // traps will have the state of the array allocation. Let the old uncommon trap nodes die.
6306 void LibraryCallKit::replace_unrelated_uncommon_traps_with_alloc_state(JVMState* saved_jvms_before_guards) {
6307   Node* if_proj = saved_jvms_before_guards->map()->control(); // Start the search right before the newly emitted guards
6308   while (if_proj->is_IfProj()) {
6309     CallStaticJavaNode* uncommon_trap = get_uncommon_trap_from_success_proj(if_proj);
6310     if (uncommon_trap != nullptr) {
6311       create_new_uncommon_trap(uncommon_trap);
6312     }
6313     assert(if_proj->in(0)->is_If(), "must be If");
6314     if_proj = if_proj->in(0)->in(0);
6315   }
6316   assert(if_proj->is_Proj() && if_proj->in(0)->is_Initialize(),
6317          "must have reached control projection of init node");
6318 }
6319 
6320 void LibraryCallKit::create_new_uncommon_trap(CallStaticJavaNode* uncommon_trap_call) {
6321   const int trap_request = uncommon_trap_call->uncommon_trap_request();
6322   assert(trap_request != 0, "no valid UCT trap request");
6323   PreserveJVMState pjvms(this);
6324   set_control(uncommon_trap_call->in(0));
6325   uncommon_trap(Deoptimization::trap_request_reason(trap_request),
6326                 Deoptimization::trap_request_action(trap_request));
6327   assert(stopped(), "Should be stopped");
6328   _gvn.hash_delete(uncommon_trap_call);
6329   uncommon_trap_call->set_req(0, top()); // not used anymore, kill it
6330 }
6331 
6332 // Common checks for array sorting intrinsics arguments.
6333 // Returns `true` if checks passed.
6334 bool LibraryCallKit::check_array_sort_arguments(Node* elementType, Node* obj, BasicType& bt) {
6335   // check address of the class
6336   if (elementType == nullptr || elementType->is_top()) {
6337     return false;  // dead path
6338   }
6339   const TypeInstPtr* elem_klass = gvn().type(elementType)->isa_instptr();
6340   if (elem_klass == nullptr) {
6341     return false;  // dead path
6342   }
6343   // java_mirror_type() returns non-null for compile-time Class constants only
6344   ciType* elem_type = elem_klass->java_mirror_type();
6345   if (elem_type == nullptr) {
6346     return false;
6347   }
6348   bt = elem_type->basic_type();
6349   // Disable the intrinsic if the CPU does not support SIMD sort
6350   if (!Matcher::supports_simd_sort(bt)) {
6351     return false;
6352   }
6353   // check address of the array
6354   if (obj == nullptr || obj->is_top()) {
6355     return false;  // dead path
6356   }
6357   const TypeAryPtr* obj_t = _gvn.type(obj)->isa_aryptr();
6358   if (obj_t == nullptr || obj_t->elem() == Type::BOTTOM) {
6359     return false; // failed input validation
6360   }
6361   return true;
6362 }
6363 
6364 //------------------------------inline_array_partition-----------------------
6365 bool LibraryCallKit::inline_array_partition() {
6366   address stubAddr = StubRoutines::select_array_partition_function();
6367   if (stubAddr == nullptr) {
6368     return false; // Intrinsic's stub is not implemented on this platform
6369   }
6370   assert(callee()->signature()->size() == 9, "arrayPartition has 8 parameters (one long)");
6371 
6372   // no receiver because it is a static method
6373   Node* elementType     = argument(0);
6374   Node* obj             = argument(1);
6375   Node* offset          = argument(2); // long
6376   Node* fromIndex       = argument(4);
6377   Node* toIndex         = argument(5);
6378   Node* indexPivot1     = argument(6);
6379   Node* indexPivot2     = argument(7);
6380   // PartitionOperation:  argument(8) is ignored
6381 
6382   Node* pivotIndices = nullptr;
6383   BasicType bt = T_ILLEGAL;
6384 
6385   if (!check_array_sort_arguments(elementType, obj, bt)) {
6386     return false;
6387   }
6388   null_check(obj);
6389   // If obj is dead, only null-path is taken.
6390   if (stopped()) {
6391     return true;
6392   }
6393   // Set the original stack and the reexecute bit for the interpreter to reexecute
6394   // the bytecode that invokes DualPivotQuicksort.partition() if deoptimization happens.
6395   { PreserveReexecuteState preexecs(this);
6396     jvms()->set_should_reexecute(true);
6397 
6398     Node* obj_adr = make_unsafe_address(obj, offset);
6399 
6400     // create the pivotIndices array of type int and size = 2
6401     Node* size = intcon(2);
6402     Node* klass_node = makecon(TypeKlassPtr::make(ciTypeArrayKlass::make(T_INT)));
6403     pivotIndices = new_array(klass_node, size, 0);  // no arguments to push
6404     AllocateArrayNode* alloc = tightly_coupled_allocation(pivotIndices);
6405     guarantee(alloc != nullptr, "created above");
6406     Node* pivotIndices_adr = basic_plus_adr(pivotIndices, arrayOopDesc::base_offset_in_bytes(T_INT));
6407 
6408     // pass the basic type enum to the stub
6409     Node* elemType = intcon(bt);
6410 
6411     // Call the stub
6412     const char *stubName = "array_partition_stub";
6413     make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::array_partition_Type(),
6414                       stubAddr, stubName, TypePtr::BOTTOM,
6415                       obj_adr, elemType, fromIndex, toIndex, pivotIndices_adr,
6416                       indexPivot1, indexPivot2);
6417 
6418   } // original reexecute is set back here
6419 
6420   if (!stopped()) {
6421     set_result(pivotIndices);
6422   }
6423 
6424   return true;
6425 }
6426 
6427 
6428 //------------------------------inline_array_sort-----------------------
6429 bool LibraryCallKit::inline_array_sort() {
6430   address stubAddr = StubRoutines::select_arraysort_function();
6431   if (stubAddr == nullptr) {
6432     return false; // Intrinsic's stub is not implemented on this platform
6433   }
6434   assert(callee()->signature()->size() == 7, "arraySort has 6 parameters (one long)");
6435 
6436   // no receiver because it is a static method
6437   Node* elementType     = argument(0);
6438   Node* obj             = argument(1);
6439   Node* offset          = argument(2); // long
6440   Node* fromIndex       = argument(4);
6441   Node* toIndex         = argument(5);
6442   // SortOperation:       argument(6) is ignored
6443 
6444   BasicType bt = T_ILLEGAL;
6445 
6446   if (!check_array_sort_arguments(elementType, obj, bt)) {
6447     return false;
6448   }
6449   null_check(obj);
6450   // If obj is dead, only null-path is taken.
6451   if (stopped()) {
6452     return true;
6453   }
6454   Node* obj_adr = make_unsafe_address(obj, offset);
6455 
6456   // pass the basic type enum to the stub
6457   Node* elemType = intcon(bt);
6458 
6459   // Call the stub.
6460   const char *stubName = "arraysort_stub";
6461   make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::array_sort_Type(),
6462                     stubAddr, stubName, TypePtr::BOTTOM,
6463                     obj_adr, elemType, fromIndex, toIndex);
6464 
6465   return true;
6466 }
6467 
6468 
6469 //------------------------------inline_arraycopy-----------------------
6470 // public static native void java.lang.System.arraycopy(Object src,  int  srcPos,
6471 //                                                      Object dest, int destPos,
6472 //                                                      int length);
6473 bool LibraryCallKit::inline_arraycopy() {
6474   // Get the arguments.
6475   Node* src         = argument(0);  // type: oop
6476   Node* src_offset  = argument(1);  // type: int
6477   Node* dest        = argument(2);  // type: oop
6478   Node* dest_offset = argument(3);  // type: int
6479   Node* length      = argument(4);  // type: int
6480 
6481   uint new_idx = C->unique();
6482 
6483   // Check for allocation before we add nodes that would confuse
6484   // tightly_coupled_allocation()
6485   AllocateArrayNode* alloc = tightly_coupled_allocation(dest);
6486 
6487   int saved_reexecute_sp = -1;
6488   JVMState* saved_jvms_before_guards = arraycopy_restore_alloc_state(alloc, saved_reexecute_sp);
6489   // See arraycopy_restore_alloc_state() comment
6490   // if alloc == null we don't have to worry about a tightly coupled allocation so we can emit all needed guards
6491   // if saved_jvms_before_guards is not null (then alloc is not null) then we can handle guards and a tightly coupled allocation
6492   // if saved_jvms_before_guards is null and alloc is not null, we can't emit any guards
6493   bool can_emit_guards = (alloc == nullptr || saved_jvms_before_guards != nullptr);
6494 
6495   // The following tests must be performed
6496   // (1) src and dest are arrays.
6497   // (2) src and dest arrays must have elements of the same BasicType
6498   // (3) src and dest must not be null.
6499   // (4) src_offset must not be negative.
6500   // (5) dest_offset must not be negative.
6501   // (6) length must not be negative.
6502   // (7) src_offset + length must not exceed length of src.
6503   // (8) dest_offset + length must not exceed length of dest.
6504   // (9) each element of an oop array must be assignable
6505 
6506   // (3) src and dest must not be null.
6507   // always do this here because we need the JVM state for uncommon traps
6508   Node* null_ctl = top();
6509   src  = saved_jvms_before_guards != nullptr ? null_check_oop(src, &null_ctl, true, true) : null_check(src, T_ARRAY);
6510   assert(null_ctl->is_top(), "no null control here");
6511   dest = null_check(dest, T_ARRAY);
6512 
6513   if (!can_emit_guards) {
6514     // if saved_jvms_before_guards is null and alloc is not null, we don't emit any
6515     // guards but the arraycopy node could still take advantage of a
6516     // tightly allocated allocation. tightly_coupled_allocation() is
6517     // called again to make sure it takes the null check above into
6518     // account: the null check is mandatory and if it caused an
6519     // uncommon trap to be emitted then the allocation can't be
6520     // considered tightly coupled in this context.
6521     alloc = tightly_coupled_allocation(dest);
6522   }
6523 
6524   bool validated = false;
6525 
6526   const Type* src_type  = _gvn.type(src);
6527   const Type* dest_type = _gvn.type(dest);
6528   const TypeAryPtr* top_src  = src_type->isa_aryptr();
6529   const TypeAryPtr* top_dest = dest_type->isa_aryptr();
6530 
6531   // Do we have the type of src?
6532   bool has_src = (top_src != nullptr && top_src->elem() != Type::BOTTOM);
6533   // Do we have the type of dest?
6534   bool has_dest = (top_dest != nullptr && top_dest->elem() != Type::BOTTOM);
6535   // Is the type for src from speculation?
6536   bool src_spec = false;
6537   // Is the type for dest from speculation?
6538   bool dest_spec = false;
6539 
6540   if ((!has_src || !has_dest) && can_emit_guards) {
6541     // We don't have sufficient type information, let's see if
6542     // speculative types can help. We need to have types for both src
6543     // and dest so that it pays off.
6544 
6545     // Do we already have or could we have type information for src
6546     bool could_have_src = has_src;
6547     // Do we already have or could we have type information for dest
6548     bool could_have_dest = has_dest;
6549 
6550     ciKlass* src_k = nullptr;
6551     if (!has_src) {
6552       src_k = src_type->speculative_type_not_null();
6553       if (src_k != nullptr && src_k->is_array_klass()) {
6554         could_have_src = true;
6555       }
6556     }
6557 
6558     ciKlass* dest_k = nullptr;
6559     if (!has_dest) {
6560       dest_k = dest_type->speculative_type_not_null();
6561       if (dest_k != nullptr && dest_k->is_array_klass()) {
6562         could_have_dest = true;
6563       }
6564     }
6565 
6566     if (could_have_src && could_have_dest) {
6567       // This is going to pay off so emit the required guards
6568       if (!has_src) {
6569         src = maybe_cast_profiled_obj(src, src_k, true);
6570         src_type  = _gvn.type(src);
6571         top_src  = src_type->isa_aryptr();
6572         has_src = (top_src != nullptr && top_src->elem() != Type::BOTTOM);
6573         src_spec = true;
6574       }
6575       if (!has_dest) {
6576         dest = maybe_cast_profiled_obj(dest, dest_k, true);
6577         dest_type  = _gvn.type(dest);
6578         top_dest  = dest_type->isa_aryptr();
6579         has_dest = (top_dest != nullptr && top_dest->elem() != Type::BOTTOM);
6580         dest_spec = true;
6581       }
6582     }
6583   }
6584 
6585   if (has_src && has_dest && can_emit_guards) {
6586     BasicType src_elem = top_src->isa_aryptr()->elem()->array_element_basic_type();
6587     BasicType dest_elem = top_dest->isa_aryptr()->elem()->array_element_basic_type();
6588     if (is_reference_type(src_elem, true)) src_elem = T_OBJECT;
6589     if (is_reference_type(dest_elem, true)) dest_elem = T_OBJECT;
6590 
6591     if (src_elem == dest_elem && top_src->is_flat() == top_dest->is_flat() && src_elem == T_OBJECT) {
6592       // If both arrays are object arrays then having the exact types
6593       // for both will remove the need for a subtype check at runtime
6594       // before the call and may make it possible to pick a faster copy
6595       // routine (without a subtype check on every element)
6596       // Do we have the exact type of src?
6597       bool could_have_src = src_spec;
6598       // Do we have the exact type of dest?
6599       bool could_have_dest = dest_spec;
6600       ciKlass* src_k = nullptr;
6601       ciKlass* dest_k = nullptr;
6602       if (!src_spec) {
6603         src_k = src_type->speculative_type_not_null();
6604         if (src_k != nullptr && src_k->is_array_klass()) {
6605           could_have_src = true;
6606         }
6607       }
6608       if (!dest_spec) {
6609         dest_k = dest_type->speculative_type_not_null();
6610         if (dest_k != nullptr && dest_k->is_array_klass()) {
6611           could_have_dest = true;
6612         }
6613       }
6614       if (could_have_src && could_have_dest) {
6615         // If we can have both exact types, emit the missing guards
6616         if (could_have_src && !src_spec) {
6617           src = maybe_cast_profiled_obj(src, src_k, true);
6618           src_type = _gvn.type(src);
6619           top_src = src_type->isa_aryptr();
6620         }
6621         if (could_have_dest && !dest_spec) {
6622           dest = maybe_cast_profiled_obj(dest, dest_k, true);
6623           dest_type = _gvn.type(dest);
6624           top_dest = dest_type->isa_aryptr();
6625         }
6626       }
6627     }
6628   }
6629 
6630   ciMethod* trap_method = method();
6631   int trap_bci = bci();
6632   if (saved_jvms_before_guards != nullptr) {
6633     trap_method = alloc->jvms()->method();
6634     trap_bci = alloc->jvms()->bci();
6635   }
6636 
6637   bool negative_length_guard_generated = false;
6638 
6639   if (!C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_intrinsic) &&
6640       can_emit_guards && !src->is_top() && !dest->is_top()) {
6641     // validate arguments: enables transformation the ArrayCopyNode
6642     validated = true;
6643 
6644     RegionNode* slow_region = new RegionNode(1);
6645     record_for_igvn(slow_region);
6646 
6647     // (1) src and dest are arrays.
6648     generate_non_array_guard(load_object_klass(src), slow_region, &src);
6649     generate_non_array_guard(load_object_klass(dest), slow_region, &dest);
6650 
6651     // (2) src and dest arrays must have elements of the same BasicType
6652     // done at macro expansion or at Ideal transformation time
6653 
6654     // (4) src_offset must not be negative.
6655     generate_negative_guard(src_offset, slow_region);
6656 
6657     // (5) dest_offset must not be negative.
6658     generate_negative_guard(dest_offset, slow_region);
6659 
6660     // (7) src_offset + length must not exceed length of src.
6661     generate_limit_guard(src_offset, length,
6662                          load_array_length(src),
6663                          slow_region);
6664 
6665     // (8) dest_offset + length must not exceed length of dest.
6666     generate_limit_guard(dest_offset, length,
6667                          load_array_length(dest),
6668                          slow_region);
6669 
6670     // (6) length must not be negative.
6671     // This is also checked in generate_arraycopy() during macro expansion, but
6672     // we also have to check it here for the case where the ArrayCopyNode will
6673     // be eliminated by Escape Analysis.
6674     if (EliminateAllocations) {
6675       generate_negative_guard(length, slow_region);
6676       negative_length_guard_generated = true;
6677     }
6678 
6679     // (9) each element of an oop array must be assignable
6680     Node* dest_klass = load_object_klass(dest);
6681     Node* refined_dest_klass = dest_klass;
6682     if (src != dest) {
6683       dest_klass = load_non_refined_array_klass(refined_dest_klass);
6684       Node* not_subtype_ctrl = gen_subtype_check(src, dest_klass);
6685       slow_region->add_req(not_subtype_ctrl);
6686     }
6687 
6688     // TODO 8350865 Improve this. What about atomicity? Make sure this is always folded for type arrays.
6689     // If destination is null-restricted, source must be null-restricted as well: src_null_restricted || !dst_null_restricted
6690     Node* src_klass = load_object_klass(src);
6691     Node* adr_prop_src = basic_plus_adr(src_klass, in_bytes(ArrayKlass::properties_offset()));
6692     Node* prop_src = _gvn.transform(LoadNode::make(_gvn, control(), immutable_memory(), adr_prop_src, TypeRawPtr::BOTTOM, TypeInt::INT, T_INT, MemNode::unordered));
6693     Node* adr_prop_dest = basic_plus_adr(refined_dest_klass, in_bytes(ArrayKlass::properties_offset()));
6694     Node* prop_dest = _gvn.transform(LoadNode::make(_gvn, control(), immutable_memory(), adr_prop_dest, TypeRawPtr::BOTTOM, TypeInt::INT, T_INT, MemNode::unordered));
6695 
6696     prop_dest = _gvn.transform(new XorINode(prop_dest, intcon(ArrayKlass::ArrayProperties::NULL_RESTRICTED)));
6697     prop_src = _gvn.transform(new OrINode(prop_dest, prop_src));
6698     prop_src = _gvn.transform(new AndINode(prop_src, intcon(ArrayKlass::ArrayProperties::NULL_RESTRICTED)));
6699 
6700     Node* chk = _gvn.transform(new CmpINode(prop_src, intcon(ArrayKlass::ArrayProperties::NULL_RESTRICTED)));
6701     Node* tst = _gvn.transform(new BoolNode(chk, BoolTest::ne));
6702     generate_fair_guard(tst, slow_region);
6703 
6704     // TODO 8350865 This is too strong
6705     generate_fair_guard(flat_array_test(src), slow_region);
6706     generate_fair_guard(flat_array_test(dest), slow_region);
6707 
6708     {
6709       PreserveJVMState pjvms(this);
6710       set_control(_gvn.transform(slow_region));
6711       uncommon_trap(Deoptimization::Reason_intrinsic,
6712                     Deoptimization::Action_make_not_entrant);
6713       assert(stopped(), "Should be stopped");
6714     }
6715 
6716     const TypeKlassPtr* dest_klass_t = _gvn.type(refined_dest_klass)->is_klassptr();
6717     const Type* toop = dest_klass_t->cast_to_exactness(false)->as_instance_type();
6718     src = _gvn.transform(new CheckCastPPNode(control(), src, toop));
6719     arraycopy_move_allocation_here(alloc, dest, saved_jvms_before_guards, saved_reexecute_sp, new_idx);
6720   }
6721 
6722   if (stopped()) {
6723     return true;
6724   }
6725 
6726   Node* dest_klass = load_object_klass(dest);
6727   dest_klass = load_non_refined_array_klass(dest_klass);
6728 
6729   ArrayCopyNode* ac = ArrayCopyNode::make(this, true, src, src_offset, dest, dest_offset, length, alloc != nullptr, negative_length_guard_generated,
6730                                           // Create LoadRange and LoadKlass nodes for use during macro expansion here
6731                                           // so the compiler has a chance to eliminate them: during macro expansion,
6732                                           // we have to set their control (CastPP nodes are eliminated).
6733                                           load_object_klass(src), dest_klass,
6734                                           load_array_length(src), load_array_length(dest));
6735 
6736   ac->set_arraycopy(validated);
6737 
6738   Node* n = _gvn.transform(ac);
6739   if (n == ac) {
6740     ac->connect_outputs(this);
6741   } else {
6742     assert(validated, "shouldn't transform if all arguments not validated");
6743     set_all_memory(n);
6744   }
6745   clear_upper_avx();
6746 
6747 
6748   return true;
6749 }
6750 
6751 
6752 // Helper function which determines if an arraycopy immediately follows
6753 // an allocation, with no intervening tests or other escapes for the object.
6754 AllocateArrayNode*
6755 LibraryCallKit::tightly_coupled_allocation(Node* ptr) {
6756   if (stopped())             return nullptr;  // no fast path
6757   if (!C->do_aliasing())     return nullptr;  // no MergeMems around
6758 
6759   AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(ptr);
6760   if (alloc == nullptr)  return nullptr;
6761 
6762   Node* rawmem = memory(Compile::AliasIdxRaw);
6763   // Is the allocation's memory state untouched?
6764   if (!(rawmem->is_Proj() && rawmem->in(0)->is_Initialize())) {
6765     // Bail out if there have been raw-memory effects since the allocation.
6766     // (Example:  There might have been a call or safepoint.)
6767     return nullptr;
6768   }
6769   rawmem = rawmem->in(0)->as_Initialize()->memory(Compile::AliasIdxRaw);
6770   if (!(rawmem->is_Proj() && rawmem->in(0) == alloc)) {
6771     return nullptr;
6772   }
6773 
6774   // There must be no unexpected observers of this allocation.
6775   for (DUIterator_Fast imax, i = ptr->fast_outs(imax); i < imax; i++) {
6776     Node* obs = ptr->fast_out(i);
6777     if (obs != this->map()) {
6778       return nullptr;
6779     }
6780   }
6781 
6782   // This arraycopy must unconditionally follow the allocation of the ptr.
6783   Node* alloc_ctl = ptr->in(0);
6784   Node* ctl = control();
6785   while (ctl != alloc_ctl) {
6786     // There may be guards which feed into the slow_region.
6787     // Any other control flow means that we might not get a chance
6788     // to finish initializing the allocated object.
6789     // Various low-level checks bottom out in uncommon traps. These
6790     // are considered safe since we've already checked above that
6791     // there is no unexpected observer of this allocation.
6792     if (get_uncommon_trap_from_success_proj(ctl) != nullptr) {
6793       assert(ctl->in(0)->is_If(), "must be If");
6794       ctl = ctl->in(0)->in(0);
6795     } else {
6796       return nullptr;
6797     }
6798   }
6799 
6800   // If we get this far, we have an allocation which immediately
6801   // precedes the arraycopy, and we can take over zeroing the new object.
6802   // The arraycopy will finish the initialization, and provide
6803   // a new control state to which we will anchor the destination pointer.
6804 
6805   return alloc;
6806 }
6807 
6808 CallStaticJavaNode* LibraryCallKit::get_uncommon_trap_from_success_proj(Node* node) {
6809   if (node->is_IfProj()) {
6810     Node* other_proj = node->as_IfProj()->other_if_proj();
6811     for (DUIterator_Fast jmax, j = other_proj->fast_outs(jmax); j < jmax; j++) {
6812       Node* obs = other_proj->fast_out(j);
6813       if (obs->in(0) == other_proj && obs->is_CallStaticJava() &&
6814           (obs->as_CallStaticJava()->entry_point() == OptoRuntime::uncommon_trap_blob()->entry_point())) {
6815         return obs->as_CallStaticJava();
6816       }
6817     }
6818   }
6819   return nullptr;
6820 }
6821 
6822 //-------------inline_encodeISOArray-----------------------------------
6823 // int sun.nio.cs.ISO_8859_1.Encoder#encodeISOArray0(byte[] sa, int sp, byte[] da, int dp, int len)
6824 // int java.lang.StringCoding#encodeISOArray0(byte[] sa, int sp, byte[] da, int dp, int len)
6825 // int java.lang.StringCoding#encodeAsciiArray0(char[] sa, int sp, byte[] da, int dp, int len)
6826 // encode char[] to byte[] in ISO_8859_1 or ASCII
6827 bool LibraryCallKit::inline_encodeISOArray(bool ascii) {
6828   assert(callee()->signature()->size() == 5, "encodeISOArray has 5 parameters");
6829   // no receiver since it is static method
6830   Node *src         = argument(0);
6831   Node *src_offset  = argument(1);
6832   Node *dst         = argument(2);
6833   Node *dst_offset  = argument(3);
6834   Node *length      = argument(4);
6835 
6836   // Cast source & target arrays to not-null
6837   if (VerifyIntrinsicChecks) {
6838     src = must_be_not_null(src, true);
6839     dst = must_be_not_null(dst, true);
6840     if (stopped()) {
6841       return true;
6842     }
6843   }
6844 
6845   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
6846   const TypeAryPtr* dst_type = dst->Value(&_gvn)->isa_aryptr();
6847   if (src_type == nullptr || src_type->elem() == Type::BOTTOM ||
6848       dst_type == nullptr || dst_type->elem() == Type::BOTTOM) {
6849     // failed array check
6850     return false;
6851   }
6852 
6853   // Figure out the size and type of the elements we will be copying.
6854   BasicType src_elem = src_type->elem()->array_element_basic_type();
6855   BasicType dst_elem = dst_type->elem()->array_element_basic_type();
6856   if (!((src_elem == T_CHAR) || (src_elem== T_BYTE)) || dst_elem != T_BYTE) {
6857     return false;
6858   }
6859 
6860   // Check source & target bounds
6861   if (VerifyIntrinsicChecks) {
6862     generate_string_range_check(src, src_offset, length, src_elem == T_BYTE, true);
6863     generate_string_range_check(dst, dst_offset, length, false, true);
6864     if (stopped()) {
6865       return true;
6866     }
6867   }
6868 
6869   Node* src_start = array_element_address(src, src_offset, T_CHAR);
6870   Node* dst_start = array_element_address(dst, dst_offset, dst_elem);
6871   // 'src_start' points to src array + scaled offset
6872   // 'dst_start' points to dst array + scaled offset
6873 
6874   const TypeAryPtr* mtype = TypeAryPtr::BYTES;
6875   Node* enc = new EncodeISOArrayNode(control(), memory(mtype), src_start, dst_start, length, ascii);
6876   enc = _gvn.transform(enc);
6877   Node* res_mem = _gvn.transform(new SCMemProjNode(enc));
6878   set_memory(res_mem, mtype);
6879   set_result(enc);
6880   clear_upper_avx();
6881 
6882   return true;
6883 }
6884 
6885 //-------------inline_multiplyToLen-----------------------------------
6886 bool LibraryCallKit::inline_multiplyToLen() {
6887   assert(UseMultiplyToLenIntrinsic, "not implemented on this platform");
6888 
6889   address stubAddr = StubRoutines::multiplyToLen();
6890   if (stubAddr == nullptr) {
6891     return false; // Intrinsic's stub is not implemented on this platform
6892   }
6893   const char* stubName = "multiplyToLen";
6894 
6895   assert(callee()->signature()->size() == 5, "multiplyToLen has 5 parameters");
6896 
6897   // no receiver because it is a static method
6898   Node* x    = argument(0);
6899   Node* xlen = argument(1);
6900   Node* y    = argument(2);
6901   Node* ylen = argument(3);
6902   Node* z    = argument(4);
6903 
6904   x = must_be_not_null(x, true);
6905   y = must_be_not_null(y, true);
6906 
6907   const TypeAryPtr* x_type = x->Value(&_gvn)->isa_aryptr();
6908   const TypeAryPtr* y_type = y->Value(&_gvn)->isa_aryptr();
6909   if (x_type == nullptr || x_type->elem() == Type::BOTTOM ||
6910       y_type == nullptr || y_type->elem() == Type::BOTTOM) {
6911     // failed array check
6912     return false;
6913   }
6914 
6915   BasicType x_elem = x_type->elem()->array_element_basic_type();
6916   BasicType y_elem = y_type->elem()->array_element_basic_type();
6917   if (x_elem != T_INT || y_elem != T_INT) {
6918     return false;
6919   }
6920 
6921   Node* x_start = array_element_address(x, intcon(0), x_elem);
6922   Node* y_start = array_element_address(y, intcon(0), y_elem);
6923   // 'x_start' points to x array + scaled xlen
6924   // 'y_start' points to y array + scaled ylen
6925 
6926   Node* z_start = array_element_address(z, intcon(0), T_INT);
6927 
6928   Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
6929                                  OptoRuntime::multiplyToLen_Type(),
6930                                  stubAddr, stubName, TypePtr::BOTTOM,
6931                                  x_start, xlen, y_start, ylen, z_start);
6932 
6933   C->set_has_split_ifs(true); // Has chance for split-if optimization
6934   set_result(z);
6935   return true;
6936 }
6937 
6938 //-------------inline_squareToLen------------------------------------
6939 bool LibraryCallKit::inline_squareToLen() {
6940   assert(UseSquareToLenIntrinsic, "not implemented on this platform");
6941 
6942   address stubAddr = StubRoutines::squareToLen();
6943   if (stubAddr == nullptr) {
6944     return false; // Intrinsic's stub is not implemented on this platform
6945   }
6946   const char* stubName = "squareToLen";
6947 
6948   assert(callee()->signature()->size() == 4, "implSquareToLen has 4 parameters");
6949 
6950   Node* x    = argument(0);
6951   Node* len  = argument(1);
6952   Node* z    = argument(2);
6953   Node* zlen = argument(3);
6954 
6955   x = must_be_not_null(x, true);
6956   z = must_be_not_null(z, true);
6957 
6958   const TypeAryPtr* x_type = x->Value(&_gvn)->isa_aryptr();
6959   const TypeAryPtr* z_type = z->Value(&_gvn)->isa_aryptr();
6960   if (x_type == nullptr || x_type->elem() == Type::BOTTOM ||
6961       z_type == nullptr || z_type->elem() == Type::BOTTOM) {
6962     // failed array check
6963     return false;
6964   }
6965 
6966   BasicType x_elem = x_type->elem()->array_element_basic_type();
6967   BasicType z_elem = z_type->elem()->array_element_basic_type();
6968   if (x_elem != T_INT || z_elem != T_INT) {
6969     return false;
6970   }
6971 
6972 
6973   Node* x_start = array_element_address(x, intcon(0), x_elem);
6974   Node* z_start = array_element_address(z, intcon(0), z_elem);
6975 
6976   Node*  call = make_runtime_call(RC_LEAF|RC_NO_FP,
6977                                   OptoRuntime::squareToLen_Type(),
6978                                   stubAddr, stubName, TypePtr::BOTTOM,
6979                                   x_start, len, z_start, zlen);
6980 
6981   set_result(z);
6982   return true;
6983 }
6984 
6985 //-------------inline_mulAdd------------------------------------------
6986 bool LibraryCallKit::inline_mulAdd() {
6987   assert(UseMulAddIntrinsic, "not implemented on this platform");
6988 
6989   address stubAddr = StubRoutines::mulAdd();
6990   if (stubAddr == nullptr) {
6991     return false; // Intrinsic's stub is not implemented on this platform
6992   }
6993   const char* stubName = "mulAdd";
6994 
6995   assert(callee()->signature()->size() == 5, "mulAdd has 5 parameters");
6996 
6997   Node* out      = argument(0);
6998   Node* in       = argument(1);
6999   Node* offset   = argument(2);
7000   Node* len      = argument(3);
7001   Node* k        = argument(4);
7002 
7003   in = must_be_not_null(in, true);
7004   out = must_be_not_null(out, true);
7005 
7006   const TypeAryPtr* out_type = out->Value(&_gvn)->isa_aryptr();
7007   const TypeAryPtr* in_type = in->Value(&_gvn)->isa_aryptr();
7008   if (out_type == nullptr || out_type->elem() == Type::BOTTOM ||
7009        in_type == nullptr ||  in_type->elem() == Type::BOTTOM) {
7010     // failed array check
7011     return false;
7012   }
7013 
7014   BasicType out_elem = out_type->elem()->array_element_basic_type();
7015   BasicType in_elem = in_type->elem()->array_element_basic_type();
7016   if (out_elem != T_INT || in_elem != T_INT) {
7017     return false;
7018   }
7019 
7020   Node* outlen = load_array_length(out);
7021   Node* new_offset = _gvn.transform(new SubINode(outlen, offset));
7022   Node* out_start = array_element_address(out, intcon(0), out_elem);
7023   Node* in_start = array_element_address(in, intcon(0), in_elem);
7024 
7025   Node*  call = make_runtime_call(RC_LEAF|RC_NO_FP,
7026                                   OptoRuntime::mulAdd_Type(),
7027                                   stubAddr, stubName, TypePtr::BOTTOM,
7028                                   out_start,in_start, new_offset, len, k);
7029   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7030   set_result(result);
7031   return true;
7032 }
7033 
7034 //-------------inline_montgomeryMultiply-----------------------------------
7035 bool LibraryCallKit::inline_montgomeryMultiply() {
7036   address stubAddr = StubRoutines::montgomeryMultiply();
7037   if (stubAddr == nullptr) {
7038     return false; // Intrinsic's stub is not implemented on this platform
7039   }
7040 
7041   assert(UseMontgomeryMultiplyIntrinsic, "not implemented on this platform");
7042   const char* stubName = "montgomery_multiply";
7043 
7044   assert(callee()->signature()->size() == 7, "montgomeryMultiply has 7 parameters");
7045 
7046   Node* a    = argument(0);
7047   Node* b    = argument(1);
7048   Node* n    = argument(2);
7049   Node* len  = argument(3);
7050   Node* inv  = argument(4);
7051   Node* m    = argument(6);
7052 
7053   const TypeAryPtr* a_type = a->Value(&_gvn)->isa_aryptr();
7054   const TypeAryPtr* b_type = b->Value(&_gvn)->isa_aryptr();
7055   const TypeAryPtr* n_type = n->Value(&_gvn)->isa_aryptr();
7056   const TypeAryPtr* m_type = m->Value(&_gvn)->isa_aryptr();
7057   if (a_type == nullptr || a_type->elem() == Type::BOTTOM ||
7058       b_type == nullptr || b_type->elem() == Type::BOTTOM ||
7059       n_type == nullptr || n_type->elem() == Type::BOTTOM ||
7060       m_type == nullptr || m_type->elem() == Type::BOTTOM) {
7061     // failed array check
7062     return false;
7063   }
7064 
7065   BasicType a_elem = a_type->elem()->array_element_basic_type();
7066   BasicType b_elem = b_type->elem()->array_element_basic_type();
7067   BasicType n_elem = n_type->elem()->array_element_basic_type();
7068   BasicType m_elem = m_type->elem()->array_element_basic_type();
7069   if (a_elem != T_INT || b_elem != T_INT || n_elem != T_INT || m_elem != T_INT) {
7070     return false;
7071   }
7072 
7073   // Make the call
7074   {
7075     Node* a_start = array_element_address(a, intcon(0), a_elem);
7076     Node* b_start = array_element_address(b, intcon(0), b_elem);
7077     Node* n_start = array_element_address(n, intcon(0), n_elem);
7078     Node* m_start = array_element_address(m, intcon(0), m_elem);
7079 
7080     Node* call = make_runtime_call(RC_LEAF,
7081                                    OptoRuntime::montgomeryMultiply_Type(),
7082                                    stubAddr, stubName, TypePtr::BOTTOM,
7083                                    a_start, b_start, n_start, len, inv, top(),
7084                                    m_start);
7085     set_result(m);
7086   }
7087 
7088   return true;
7089 }
7090 
7091 bool LibraryCallKit::inline_montgomerySquare() {
7092   address stubAddr = StubRoutines::montgomerySquare();
7093   if (stubAddr == nullptr) {
7094     return false; // Intrinsic's stub is not implemented on this platform
7095   }
7096 
7097   assert(UseMontgomerySquareIntrinsic, "not implemented on this platform");
7098   const char* stubName = "montgomery_square";
7099 
7100   assert(callee()->signature()->size() == 6, "montgomerySquare has 6 parameters");
7101 
7102   Node* a    = argument(0);
7103   Node* n    = argument(1);
7104   Node* len  = argument(2);
7105   Node* inv  = argument(3);
7106   Node* m    = argument(5);
7107 
7108   const TypeAryPtr* a_type = a->Value(&_gvn)->isa_aryptr();
7109   const TypeAryPtr* n_type = n->Value(&_gvn)->isa_aryptr();
7110   const TypeAryPtr* m_type = m->Value(&_gvn)->isa_aryptr();
7111   if (a_type == nullptr || a_type->elem() == Type::BOTTOM ||
7112       n_type == nullptr || n_type->elem() == Type::BOTTOM ||
7113       m_type == nullptr || m_type->elem() == Type::BOTTOM) {
7114     // failed array check
7115     return false;
7116   }
7117 
7118   BasicType a_elem = a_type->elem()->array_element_basic_type();
7119   BasicType n_elem = n_type->elem()->array_element_basic_type();
7120   BasicType m_elem = m_type->elem()->array_element_basic_type();
7121   if (a_elem != T_INT || n_elem != T_INT || m_elem != T_INT) {
7122     return false;
7123   }
7124 
7125   // Make the call
7126   {
7127     Node* a_start = array_element_address(a, intcon(0), a_elem);
7128     Node* n_start = array_element_address(n, intcon(0), n_elem);
7129     Node* m_start = array_element_address(m, intcon(0), m_elem);
7130 
7131     Node* call = make_runtime_call(RC_LEAF,
7132                                    OptoRuntime::montgomerySquare_Type(),
7133                                    stubAddr, stubName, TypePtr::BOTTOM,
7134                                    a_start, n_start, len, inv, top(),
7135                                    m_start);
7136     set_result(m);
7137   }
7138 
7139   return true;
7140 }
7141 
7142 bool LibraryCallKit::inline_bigIntegerShift(bool isRightShift) {
7143   address stubAddr = nullptr;
7144   const char* stubName = nullptr;
7145 
7146   stubAddr = isRightShift? StubRoutines::bigIntegerRightShift(): StubRoutines::bigIntegerLeftShift();
7147   if (stubAddr == nullptr) {
7148     return false; // Intrinsic's stub is not implemented on this platform
7149   }
7150 
7151   stubName = isRightShift? "bigIntegerRightShiftWorker" : "bigIntegerLeftShiftWorker";
7152 
7153   assert(callee()->signature()->size() == 5, "expected 5 arguments");
7154 
7155   Node* newArr = argument(0);
7156   Node* oldArr = argument(1);
7157   Node* newIdx = argument(2);
7158   Node* shiftCount = argument(3);
7159   Node* numIter = argument(4);
7160 
7161   const TypeAryPtr* newArr_type = newArr->Value(&_gvn)->isa_aryptr();
7162   const TypeAryPtr* oldArr_type = oldArr->Value(&_gvn)->isa_aryptr();
7163   if (newArr_type == nullptr || newArr_type->elem() == Type::BOTTOM ||
7164       oldArr_type == nullptr || oldArr_type->elem() == Type::BOTTOM) {
7165     return false;
7166   }
7167 
7168   BasicType newArr_elem = newArr_type->elem()->array_element_basic_type();
7169   BasicType oldArr_elem = oldArr_type->elem()->array_element_basic_type();
7170   if (newArr_elem != T_INT || oldArr_elem != T_INT) {
7171     return false;
7172   }
7173 
7174   // Make the call
7175   {
7176     Node* newArr_start = array_element_address(newArr, intcon(0), newArr_elem);
7177     Node* oldArr_start = array_element_address(oldArr, intcon(0), oldArr_elem);
7178 
7179     Node* call = make_runtime_call(RC_LEAF,
7180                                    OptoRuntime::bigIntegerShift_Type(),
7181                                    stubAddr,
7182                                    stubName,
7183                                    TypePtr::BOTTOM,
7184                                    newArr_start,
7185                                    oldArr_start,
7186                                    newIdx,
7187                                    shiftCount,
7188                                    numIter);
7189   }
7190 
7191   return true;
7192 }
7193 
7194 //-------------inline_vectorizedMismatch------------------------------
7195 bool LibraryCallKit::inline_vectorizedMismatch() {
7196   assert(UseVectorizedMismatchIntrinsic, "not implemented on this platform");
7197 
7198   assert(callee()->signature()->size() == 8, "vectorizedMismatch has 6 parameters");
7199   Node* obja    = argument(0); // Object
7200   Node* aoffset = argument(1); // long
7201   Node* objb    = argument(3); // Object
7202   Node* boffset = argument(4); // long
7203   Node* length  = argument(6); // int
7204   Node* scale   = argument(7); // int
7205 
7206   const TypeAryPtr* obja_t = _gvn.type(obja)->isa_aryptr();
7207   const TypeAryPtr* objb_t = _gvn.type(objb)->isa_aryptr();
7208   if (obja_t == nullptr || obja_t->elem() == Type::BOTTOM ||
7209       objb_t == nullptr || objb_t->elem() == Type::BOTTOM ||
7210       scale == top()) {
7211     return false; // failed input validation
7212   }
7213 
7214   Node* obja_adr = make_unsafe_address(obja, aoffset);
7215   Node* objb_adr = make_unsafe_address(objb, boffset);
7216 
7217   // Partial inlining handling for inputs smaller than ArrayOperationPartialInlineSize bytes in size.
7218   //
7219   //    inline_limit = ArrayOperationPartialInlineSize / element_size;
7220   //    if (length <= inline_limit) {
7221   //      inline_path:
7222   //        vmask   = VectorMaskGen length
7223   //        vload1  = LoadVectorMasked obja, vmask
7224   //        vload2  = LoadVectorMasked objb, vmask
7225   //        result1 = VectorCmpMasked vload1, vload2, vmask
7226   //    } else {
7227   //      call_stub_path:
7228   //        result2 = call vectorizedMismatch_stub(obja, objb, length, scale)
7229   //    }
7230   //    exit_block:
7231   //      return Phi(result1, result2);
7232   //
7233   enum { inline_path = 1,  // input is small enough to process it all at once
7234          stub_path   = 2,  // input is too large; call into the VM
7235          PATH_LIMIT  = 3
7236   };
7237 
7238   Node* exit_block = new RegionNode(PATH_LIMIT);
7239   Node* result_phi = new PhiNode(exit_block, TypeInt::INT);
7240   Node* memory_phi = new PhiNode(exit_block, Type::MEMORY, TypePtr::BOTTOM);
7241 
7242   Node* call_stub_path = control();
7243 
7244   BasicType elem_bt = T_ILLEGAL;
7245 
7246   const TypeInt* scale_t = _gvn.type(scale)->is_int();
7247   if (scale_t->is_con()) {
7248     switch (scale_t->get_con()) {
7249       case 0: elem_bt = T_BYTE;  break;
7250       case 1: elem_bt = T_SHORT; break;
7251       case 2: elem_bt = T_INT;   break;
7252       case 3: elem_bt = T_LONG;  break;
7253 
7254       default: elem_bt = T_ILLEGAL; break; // not supported
7255     }
7256   }
7257 
7258   int inline_limit = 0;
7259   bool do_partial_inline = false;
7260 
7261   if (elem_bt != T_ILLEGAL && ArrayOperationPartialInlineSize > 0) {
7262     inline_limit = ArrayOperationPartialInlineSize / type2aelembytes(elem_bt);
7263     do_partial_inline = inline_limit >= 16;
7264   }
7265 
7266   if (do_partial_inline) {
7267     assert(elem_bt != T_ILLEGAL, "sanity");
7268 
7269     if (Matcher::match_rule_supported_vector(Op_VectorMaskGen,    inline_limit, elem_bt) &&
7270         Matcher::match_rule_supported_vector(Op_LoadVectorMasked, inline_limit, elem_bt) &&
7271         Matcher::match_rule_supported_vector(Op_VectorCmpMasked,  inline_limit, elem_bt)) {
7272 
7273       const TypeVect* vt = TypeVect::make(elem_bt, inline_limit);
7274       Node* cmp_length = _gvn.transform(new CmpINode(length, intcon(inline_limit)));
7275       Node* bol_gt     = _gvn.transform(new BoolNode(cmp_length, BoolTest::gt));
7276 
7277       call_stub_path = generate_guard(bol_gt, nullptr, PROB_MIN);
7278 
7279       if (!stopped()) {
7280         Node* casted_length = _gvn.transform(new CastIINode(control(), length, TypeInt::make(0, inline_limit, Type::WidenMin)));
7281 
7282         const TypePtr* obja_adr_t = _gvn.type(obja_adr)->isa_ptr();
7283         const TypePtr* objb_adr_t = _gvn.type(objb_adr)->isa_ptr();
7284         Node* obja_adr_mem = memory(C->get_alias_index(obja_adr_t));
7285         Node* objb_adr_mem = memory(C->get_alias_index(objb_adr_t));
7286 
7287         Node* vmask      = _gvn.transform(VectorMaskGenNode::make(ConvI2X(casted_length), elem_bt));
7288         Node* vload_obja = _gvn.transform(new LoadVectorMaskedNode(control(), obja_adr_mem, obja_adr, obja_adr_t, vt, vmask));
7289         Node* vload_objb = _gvn.transform(new LoadVectorMaskedNode(control(), objb_adr_mem, objb_adr, objb_adr_t, vt, vmask));
7290         Node* result     = _gvn.transform(new VectorCmpMaskedNode(vload_obja, vload_objb, vmask, TypeInt::INT));
7291 
7292         exit_block->init_req(inline_path, control());
7293         memory_phi->init_req(inline_path, map()->memory());
7294         result_phi->init_req(inline_path, result);
7295 
7296         C->set_max_vector_size(MAX2((uint)ArrayOperationPartialInlineSize, C->max_vector_size()));
7297         clear_upper_avx();
7298       }
7299     }
7300   }
7301 
7302   if (call_stub_path != nullptr) {
7303     set_control(call_stub_path);
7304 
7305     Node* call = make_runtime_call(RC_LEAF,
7306                                    OptoRuntime::vectorizedMismatch_Type(),
7307                                    StubRoutines::vectorizedMismatch(), "vectorizedMismatch", TypePtr::BOTTOM,
7308                                    obja_adr, objb_adr, length, scale);
7309 
7310     exit_block->init_req(stub_path, control());
7311     memory_phi->init_req(stub_path, map()->memory());
7312     result_phi->init_req(stub_path, _gvn.transform(new ProjNode(call, TypeFunc::Parms)));
7313   }
7314 
7315   exit_block = _gvn.transform(exit_block);
7316   memory_phi = _gvn.transform(memory_phi);
7317   result_phi = _gvn.transform(result_phi);
7318 
7319   record_for_igvn(exit_block);
7320   record_for_igvn(memory_phi);
7321   record_for_igvn(result_phi);
7322 
7323   set_control(exit_block);
7324   set_all_memory(memory_phi);
7325   set_result(result_phi);
7326 
7327   return true;
7328 }
7329 
7330 //------------------------------inline_vectorizedHashcode----------------------------
7331 bool LibraryCallKit::inline_vectorizedHashCode() {
7332   assert(UseVectorizedHashCodeIntrinsic, "not implemented on this platform");
7333 
7334   assert(callee()->signature()->size() == 5, "vectorizedHashCode has 5 parameters");
7335   Node* array          = argument(0);
7336   Node* offset         = argument(1);
7337   Node* length         = argument(2);
7338   Node* initialValue   = argument(3);
7339   Node* basic_type     = argument(4);
7340 
7341   if (basic_type == top()) {
7342     return false; // failed input validation
7343   }
7344 
7345   const TypeInt* basic_type_t = _gvn.type(basic_type)->is_int();
7346   if (!basic_type_t->is_con()) {
7347     return false; // Only intrinsify if mode argument is constant
7348   }
7349 
7350   array = must_be_not_null(array, true);
7351 
7352   BasicType bt = (BasicType)basic_type_t->get_con();
7353 
7354   // Resolve address of first element
7355   Node* array_start = array_element_address(array, offset, bt);
7356 
7357   set_result(_gvn.transform(new VectorizedHashCodeNode(control(), memory(TypeAryPtr::get_array_body_type(bt)),
7358     array_start, length, initialValue, basic_type)));
7359   clear_upper_avx();
7360 
7361   return true;
7362 }
7363 
7364 /**
7365  * Calculate CRC32 for byte.
7366  * int java.util.zip.CRC32.update(int crc, int b)
7367  */
7368 bool LibraryCallKit::inline_updateCRC32() {
7369   assert(UseCRC32Intrinsics, "need AVX and CLMUL instructions support");
7370   assert(callee()->signature()->size() == 2, "update has 2 parameters");
7371   // no receiver since it is static method
7372   Node* crc  = argument(0); // type: int
7373   Node* b    = argument(1); // type: int
7374 
7375   /*
7376    *    int c = ~ crc;
7377    *    b = timesXtoThe32[(b ^ c) & 0xFF];
7378    *    b = b ^ (c >>> 8);
7379    *    crc = ~b;
7380    */
7381 
7382   Node* M1 = intcon(-1);
7383   crc = _gvn.transform(new XorINode(crc, M1));
7384   Node* result = _gvn.transform(new XorINode(crc, b));
7385   result = _gvn.transform(new AndINode(result, intcon(0xFF)));
7386 
7387   Node* base = makecon(TypeRawPtr::make(StubRoutines::crc_table_addr()));
7388   Node* offset = _gvn.transform(new LShiftINode(result, intcon(0x2)));
7389   Node* adr = basic_plus_adr(top(), base, ConvI2X(offset));
7390   result = make_load(control(), adr, TypeInt::INT, T_INT, MemNode::unordered);
7391 
7392   crc = _gvn.transform(new URShiftINode(crc, intcon(8)));
7393   result = _gvn.transform(new XorINode(crc, result));
7394   result = _gvn.transform(new XorINode(result, M1));
7395   set_result(result);
7396   return true;
7397 }
7398 
7399 /**
7400  * Calculate CRC32 for byte[] array.
7401  * int java.util.zip.CRC32.updateBytes(int crc, byte[] buf, int off, int len)
7402  */
7403 bool LibraryCallKit::inline_updateBytesCRC32() {
7404   assert(UseCRC32Intrinsics, "need AVX and CLMUL instructions support");
7405   assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
7406   // no receiver since it is static method
7407   Node* crc     = argument(0); // type: int
7408   Node* src     = argument(1); // type: oop
7409   Node* offset  = argument(2); // type: int
7410   Node* length  = argument(3); // type: int
7411 
7412   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7413   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
7414     // failed array check
7415     return false;
7416   }
7417 
7418   // Figure out the size and type of the elements we will be copying.
7419   BasicType src_elem = src_type->elem()->array_element_basic_type();
7420   if (src_elem != T_BYTE) {
7421     return false;
7422   }
7423 
7424   // 'src_start' points to src array + scaled offset
7425   src = must_be_not_null(src, true);
7426   Node* src_start = array_element_address(src, offset, src_elem);
7427 
7428   // We assume that range check is done by caller.
7429   // TODO: generate range check (offset+length < src.length) in debug VM.
7430 
7431   // Call the stub.
7432   address stubAddr = StubRoutines::updateBytesCRC32();
7433   const char *stubName = "updateBytesCRC32";
7434 
7435   Node* call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::updateBytesCRC32_Type(),
7436                                  stubAddr, stubName, TypePtr::BOTTOM,
7437                                  crc, src_start, length);
7438   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7439   set_result(result);
7440   return true;
7441 }
7442 
7443 /**
7444  * Calculate CRC32 for ByteBuffer.
7445  * int java.util.zip.CRC32.updateByteBuffer(int crc, long buf, int off, int len)
7446  */
7447 bool LibraryCallKit::inline_updateByteBufferCRC32() {
7448   assert(UseCRC32Intrinsics, "need AVX and CLMUL instructions support");
7449   assert(callee()->signature()->size() == 5, "updateByteBuffer has 4 parameters and one is long");
7450   // no receiver since it is static method
7451   Node* crc     = argument(0); // type: int
7452   Node* src     = argument(1); // type: long
7453   Node* offset  = argument(3); // type: int
7454   Node* length  = argument(4); // type: int
7455 
7456   src = ConvL2X(src);  // adjust Java long to machine word
7457   Node* base = _gvn.transform(new CastX2PNode(src));
7458   offset = ConvI2X(offset);
7459 
7460   // 'src_start' points to src array + scaled offset
7461   Node* src_start = basic_plus_adr(top(), base, offset);
7462 
7463   // Call the stub.
7464   address stubAddr = StubRoutines::updateBytesCRC32();
7465   const char *stubName = "updateBytesCRC32";
7466 
7467   Node* call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::updateBytesCRC32_Type(),
7468                                  stubAddr, stubName, TypePtr::BOTTOM,
7469                                  crc, src_start, length);
7470   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7471   set_result(result);
7472   return true;
7473 }
7474 
7475 //------------------------------get_table_from_crc32c_class-----------------------
7476 Node * LibraryCallKit::get_table_from_crc32c_class(ciInstanceKlass *crc32c_class) {
7477   Node* table = load_field_from_object(nullptr, "byteTable", "[I", /*decorators*/ IN_HEAP, /*is_static*/ true, crc32c_class);
7478   assert (table != nullptr, "wrong version of java.util.zip.CRC32C");
7479 
7480   return table;
7481 }
7482 
7483 //------------------------------inline_updateBytesCRC32C-----------------------
7484 //
7485 // Calculate CRC32C for byte[] array.
7486 // int java.util.zip.CRC32C.updateBytes(int crc, byte[] buf, int off, int end)
7487 //
7488 bool LibraryCallKit::inline_updateBytesCRC32C() {
7489   assert(UseCRC32CIntrinsics, "need CRC32C instruction support");
7490   assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
7491   assert(callee()->holder()->is_loaded(), "CRC32C class must be loaded");
7492   // no receiver since it is a static method
7493   Node* crc     = argument(0); // type: int
7494   Node* src     = argument(1); // type: oop
7495   Node* offset  = argument(2); // type: int
7496   Node* end     = argument(3); // type: int
7497 
7498   Node* length = _gvn.transform(new SubINode(end, offset));
7499 
7500   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7501   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
7502     // failed array check
7503     return false;
7504   }
7505 
7506   // Figure out the size and type of the elements we will be copying.
7507   BasicType src_elem = src_type->elem()->array_element_basic_type();
7508   if (src_elem != T_BYTE) {
7509     return false;
7510   }
7511 
7512   // 'src_start' points to src array + scaled offset
7513   src = must_be_not_null(src, true);
7514   Node* src_start = array_element_address(src, offset, src_elem);
7515 
7516   // static final int[] byteTable in class CRC32C
7517   Node* table = get_table_from_crc32c_class(callee()->holder());
7518   table = must_be_not_null(table, true);
7519   Node* table_start = array_element_address(table, intcon(0), T_INT);
7520 
7521   // We assume that range check is done by caller.
7522   // TODO: generate range check (offset+length < src.length) in debug VM.
7523 
7524   // Call the stub.
7525   address stubAddr = StubRoutines::updateBytesCRC32C();
7526   const char *stubName = "updateBytesCRC32C";
7527 
7528   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesCRC32C_Type(),
7529                                  stubAddr, stubName, TypePtr::BOTTOM,
7530                                  crc, src_start, length, table_start);
7531   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7532   set_result(result);
7533   return true;
7534 }
7535 
7536 //------------------------------inline_updateDirectByteBufferCRC32C-----------------------
7537 //
7538 // Calculate CRC32C for DirectByteBuffer.
7539 // int java.util.zip.CRC32C.updateDirectByteBuffer(int crc, long buf, int off, int end)
7540 //
7541 bool LibraryCallKit::inline_updateDirectByteBufferCRC32C() {
7542   assert(UseCRC32CIntrinsics, "need CRC32C instruction support");
7543   assert(callee()->signature()->size() == 5, "updateDirectByteBuffer has 4 parameters and one is long");
7544   assert(callee()->holder()->is_loaded(), "CRC32C class must be loaded");
7545   // no receiver since it is a static method
7546   Node* crc     = argument(0); // type: int
7547   Node* src     = argument(1); // type: long
7548   Node* offset  = argument(3); // type: int
7549   Node* end     = argument(4); // type: int
7550 
7551   Node* length = _gvn.transform(new SubINode(end, offset));
7552 
7553   src = ConvL2X(src);  // adjust Java long to machine word
7554   Node* base = _gvn.transform(new CastX2PNode(src));
7555   offset = ConvI2X(offset);
7556 
7557   // 'src_start' points to src array + scaled offset
7558   Node* src_start = basic_plus_adr(top(), base, offset);
7559 
7560   // static final int[] byteTable in class CRC32C
7561   Node* table = get_table_from_crc32c_class(callee()->holder());
7562   table = must_be_not_null(table, true);
7563   Node* table_start = array_element_address(table, intcon(0), T_INT);
7564 
7565   // Call the stub.
7566   address stubAddr = StubRoutines::updateBytesCRC32C();
7567   const char *stubName = "updateBytesCRC32C";
7568 
7569   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesCRC32C_Type(),
7570                                  stubAddr, stubName, TypePtr::BOTTOM,
7571                                  crc, src_start, length, table_start);
7572   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7573   set_result(result);
7574   return true;
7575 }
7576 
7577 //------------------------------inline_updateBytesAdler32----------------------
7578 //
7579 // Calculate Adler32 checksum for byte[] array.
7580 // int java.util.zip.Adler32.updateBytes(int crc, byte[] buf, int off, int len)
7581 //
7582 bool LibraryCallKit::inline_updateBytesAdler32() {
7583   assert(UseAdler32Intrinsics, "Adler32 Intrinsic support need"); // check if we actually need to check this flag or check a different one
7584   assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
7585   assert(callee()->holder()->is_loaded(), "Adler32 class must be loaded");
7586   // no receiver since it is static method
7587   Node* crc     = argument(0); // type: int
7588   Node* src     = argument(1); // type: oop
7589   Node* offset  = argument(2); // type: int
7590   Node* length  = argument(3); // type: int
7591 
7592   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7593   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
7594     // failed array check
7595     return false;
7596   }
7597 
7598   // Figure out the size and type of the elements we will be copying.
7599   BasicType src_elem = src_type->elem()->array_element_basic_type();
7600   if (src_elem != T_BYTE) {
7601     return false;
7602   }
7603 
7604   // 'src_start' points to src array + scaled offset
7605   Node* src_start = array_element_address(src, offset, src_elem);
7606 
7607   // We assume that range check is done by caller.
7608   // TODO: generate range check (offset+length < src.length) in debug VM.
7609 
7610   // Call the stub.
7611   address stubAddr = StubRoutines::updateBytesAdler32();
7612   const char *stubName = "updateBytesAdler32";
7613 
7614   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesAdler32_Type(),
7615                                  stubAddr, stubName, TypePtr::BOTTOM,
7616                                  crc, src_start, length);
7617   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7618   set_result(result);
7619   return true;
7620 }
7621 
7622 //------------------------------inline_updateByteBufferAdler32---------------
7623 //
7624 // Calculate Adler32 checksum for DirectByteBuffer.
7625 // int java.util.zip.Adler32.updateByteBuffer(int crc, long buf, int off, int len)
7626 //
7627 bool LibraryCallKit::inline_updateByteBufferAdler32() {
7628   assert(UseAdler32Intrinsics, "Adler32 Intrinsic support need"); // check if we actually need to check this flag or check a different one
7629   assert(callee()->signature()->size() == 5, "updateByteBuffer has 4 parameters and one is long");
7630   assert(callee()->holder()->is_loaded(), "Adler32 class must be loaded");
7631   // no receiver since it is static method
7632   Node* crc     = argument(0); // type: int
7633   Node* src     = argument(1); // type: long
7634   Node* offset  = argument(3); // type: int
7635   Node* length  = argument(4); // type: int
7636 
7637   src = ConvL2X(src);  // adjust Java long to machine word
7638   Node* base = _gvn.transform(new CastX2PNode(src));
7639   offset = ConvI2X(offset);
7640 
7641   // 'src_start' points to src array + scaled offset
7642   Node* src_start = basic_plus_adr(top(), base, offset);
7643 
7644   // Call the stub.
7645   address stubAddr = StubRoutines::updateBytesAdler32();
7646   const char *stubName = "updateBytesAdler32";
7647 
7648   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesAdler32_Type(),
7649                                  stubAddr, stubName, TypePtr::BOTTOM,
7650                                  crc, src_start, length);
7651 
7652   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7653   set_result(result);
7654   return true;
7655 }
7656 
7657 //----------------------------inline_reference_get0----------------------------
7658 // public T java.lang.ref.Reference.get();
7659 bool LibraryCallKit::inline_reference_get0() {
7660   const int referent_offset = java_lang_ref_Reference::referent_offset();
7661 
7662   // Get the argument:
7663   Node* reference_obj = null_check_receiver();
7664   if (stopped()) return true;
7665 
7666   DecoratorSet decorators = IN_HEAP | ON_WEAK_OOP_REF;
7667   Node* result = load_field_from_object(reference_obj, "referent", "Ljava/lang/Object;",
7668                                         decorators, /*is_static*/ false, nullptr);
7669   if (result == nullptr) return false;
7670 
7671   // Add memory barrier to prevent commoning reads from this field
7672   // across safepoint since GC can change its value.
7673   insert_mem_bar(Op_MemBarCPUOrder);
7674 
7675   set_result(result);
7676   return true;
7677 }
7678 
7679 //----------------------------inline_reference_refersTo0----------------------------
7680 // bool java.lang.ref.Reference.refersTo0();
7681 // bool java.lang.ref.PhantomReference.refersTo0();
7682 bool LibraryCallKit::inline_reference_refersTo0(bool is_phantom) {
7683   // Get arguments:
7684   Node* reference_obj = null_check_receiver();
7685   Node* other_obj = argument(1);
7686   if (stopped()) return true;
7687 
7688   DecoratorSet decorators = IN_HEAP | AS_NO_KEEPALIVE;
7689   decorators |= (is_phantom ? ON_PHANTOM_OOP_REF : ON_WEAK_OOP_REF);
7690   Node* referent = load_field_from_object(reference_obj, "referent", "Ljava/lang/Object;",
7691                                           decorators, /*is_static*/ false, nullptr);
7692   if (referent == nullptr) return false;
7693 
7694   // Add memory barrier to prevent commoning reads from this field
7695   // across safepoint since GC can change its value.
7696   insert_mem_bar(Op_MemBarCPUOrder);
7697 
7698   Node* cmp = _gvn.transform(new CmpPNode(referent, other_obj));
7699   Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
7700   IfNode* if_node = create_and_map_if(control(), bol, PROB_FAIR, COUNT_UNKNOWN);
7701 
7702   RegionNode* region = new RegionNode(3);
7703   PhiNode* phi = new PhiNode(region, TypeInt::BOOL);
7704 
7705   Node* if_true = _gvn.transform(new IfTrueNode(if_node));
7706   region->init_req(1, if_true);
7707   phi->init_req(1, intcon(1));
7708 
7709   Node* if_false = _gvn.transform(new IfFalseNode(if_node));
7710   region->init_req(2, if_false);
7711   phi->init_req(2, intcon(0));
7712 
7713   set_control(_gvn.transform(region));
7714   record_for_igvn(region);
7715   set_result(_gvn.transform(phi));
7716   return true;
7717 }
7718 
7719 //----------------------------inline_reference_clear0----------------------------
7720 // void java.lang.ref.Reference.clear0();
7721 // void java.lang.ref.PhantomReference.clear0();
7722 bool LibraryCallKit::inline_reference_clear0(bool is_phantom) {
7723   // This matches the implementation in JVM_ReferenceClear, see the comments there.
7724 
7725   // Get arguments
7726   Node* reference_obj = null_check_receiver();
7727   if (stopped()) return true;
7728 
7729   // Common access parameters
7730   DecoratorSet decorators = IN_HEAP | AS_NO_KEEPALIVE;
7731   decorators |= (is_phantom ? ON_PHANTOM_OOP_REF : ON_WEAK_OOP_REF);
7732   Node* referent_field_addr = basic_plus_adr(reference_obj, java_lang_ref_Reference::referent_offset());
7733   const TypePtr* referent_field_addr_type = _gvn.type(referent_field_addr)->isa_ptr();
7734   const Type* val_type = TypeOopPtr::make_from_klass(env()->Object_klass());
7735 
7736   Node* referent = access_load_at(reference_obj,
7737                                   referent_field_addr,
7738                                   referent_field_addr_type,
7739                                   val_type,
7740                                   T_OBJECT,
7741                                   decorators);
7742 
7743   IdealKit ideal(this);
7744 #define __ ideal.
7745   __ if_then(referent, BoolTest::ne, null());
7746     sync_kit(ideal);
7747     access_store_at(reference_obj,
7748                     referent_field_addr,
7749                     referent_field_addr_type,
7750                     null(),
7751                     val_type,
7752                     T_OBJECT,
7753                     decorators);
7754     __ sync_kit(this);
7755   __ end_if();
7756   final_sync(ideal);
7757 #undef __
7758 
7759   return true;
7760 }
7761 
7762 Node* LibraryCallKit::load_field_from_object(Node* fromObj, const char* fieldName, const char* fieldTypeString,
7763                                              DecoratorSet decorators, bool is_static,
7764                                              ciInstanceKlass* fromKls) {
7765   if (fromKls == nullptr) {
7766     const TypeInstPtr* tinst = _gvn.type(fromObj)->isa_instptr();
7767     assert(tinst != nullptr, "obj is null");
7768     assert(tinst->is_loaded(), "obj is not loaded");
7769     fromKls = tinst->instance_klass();
7770   } else {
7771     assert(is_static, "only for static field access");
7772   }
7773   ciField* field = fromKls->get_field_by_name(ciSymbol::make(fieldName),
7774                                               ciSymbol::make(fieldTypeString),
7775                                               is_static);
7776 
7777   assert(field != nullptr, "undefined field %s %s %s", fieldTypeString, fromKls->name()->as_utf8(), fieldName);
7778   if (field == nullptr) return (Node *) nullptr;
7779 
7780   if (is_static) {
7781     const TypeInstPtr* tip = TypeInstPtr::make(fromKls->java_mirror());
7782     fromObj = makecon(tip);
7783   }
7784 
7785   // Next code  copied from Parse::do_get_xxx():
7786 
7787   // Compute address and memory type.
7788   int offset  = field->offset_in_bytes();
7789   bool is_vol = field->is_volatile();
7790   ciType* field_klass = field->type();
7791   assert(field_klass->is_loaded(), "should be loaded");
7792   const TypePtr* adr_type = C->alias_type(field)->adr_type();
7793   Node *adr = basic_plus_adr(fromObj, fromObj, offset);
7794   assert(C->get_alias_index(adr_type) == C->get_alias_index(_gvn.type(adr)->isa_ptr()),
7795     "slice of address and input slice don't match");
7796   BasicType bt = field->layout_type();
7797 
7798   // Build the resultant type of the load
7799   const Type *type;
7800   if (bt == T_OBJECT) {
7801     type = TypeOopPtr::make_from_klass(field_klass->as_klass());
7802   } else {
7803     type = Type::get_const_basic_type(bt);
7804   }
7805 
7806   if (is_vol) {
7807     decorators |= MO_SEQ_CST;
7808   }
7809 
7810   return access_load_at(fromObj, adr, adr_type, type, bt, decorators);
7811 }
7812 
7813 Node * LibraryCallKit::field_address_from_object(Node * fromObj, const char * fieldName, const char * fieldTypeString,
7814                                                  bool is_exact /* true */, bool is_static /* false */,
7815                                                  ciInstanceKlass * fromKls /* nullptr */) {
7816   if (fromKls == nullptr) {
7817     const TypeInstPtr* tinst = _gvn.type(fromObj)->isa_instptr();
7818     assert(tinst != nullptr, "obj is null");
7819     assert(tinst->is_loaded(), "obj is not loaded");
7820     assert(!is_exact || tinst->klass_is_exact(), "klass not exact");
7821     fromKls = tinst->instance_klass();
7822   }
7823   else {
7824     assert(is_static, "only for static field access");
7825   }
7826   ciField* field = fromKls->get_field_by_name(ciSymbol::make(fieldName),
7827     ciSymbol::make(fieldTypeString),
7828     is_static);
7829 
7830   assert(field != nullptr, "undefined field");
7831   assert(!field->is_volatile(), "not defined for volatile fields");
7832 
7833   if (is_static) {
7834     const TypeInstPtr* tip = TypeInstPtr::make(fromKls->java_mirror());
7835     fromObj = makecon(tip);
7836   }
7837 
7838   // Next code  copied from Parse::do_get_xxx():
7839 
7840   // Compute address and memory type.
7841   int offset = field->offset_in_bytes();
7842   Node *adr = basic_plus_adr(fromObj, fromObj, offset);
7843 
7844   return adr;
7845 }
7846 
7847 //------------------------------inline_aescrypt_Block-----------------------
7848 bool LibraryCallKit::inline_aescrypt_Block(vmIntrinsics::ID id) {
7849   address stubAddr = nullptr;
7850   const char *stubName;
7851   assert(UseAES, "need AES instruction support");
7852 
7853   switch(id) {
7854   case vmIntrinsics::_aescrypt_encryptBlock:
7855     stubAddr = StubRoutines::aescrypt_encryptBlock();
7856     stubName = "aescrypt_encryptBlock";
7857     break;
7858   case vmIntrinsics::_aescrypt_decryptBlock:
7859     stubAddr = StubRoutines::aescrypt_decryptBlock();
7860     stubName = "aescrypt_decryptBlock";
7861     break;
7862   default:
7863     break;
7864   }
7865   if (stubAddr == nullptr) return false;
7866 
7867   Node* aescrypt_object = argument(0);
7868   Node* src             = argument(1);
7869   Node* src_offset      = argument(2);
7870   Node* dest            = argument(3);
7871   Node* dest_offset     = argument(4);
7872 
7873   src = must_be_not_null(src, true);
7874   dest = must_be_not_null(dest, true);
7875 
7876   // (1) src and dest are arrays.
7877   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7878   const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
7879   assert( src_type != nullptr &&  src_type->elem() != Type::BOTTOM &&
7880          dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
7881 
7882   // for the quick and dirty code we will skip all the checks.
7883   // we are just trying to get the call to be generated.
7884   Node* src_start  = src;
7885   Node* dest_start = dest;
7886   if (src_offset != nullptr || dest_offset != nullptr) {
7887     assert(src_offset != nullptr && dest_offset != nullptr, "");
7888     src_start  = array_element_address(src,  src_offset,  T_BYTE);
7889     dest_start = array_element_address(dest, dest_offset, T_BYTE);
7890   }
7891 
7892   // now need to get the start of its expanded key array
7893   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
7894   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object);
7895   if (k_start == nullptr) return false;
7896 
7897   // Call the stub.
7898   make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::aescrypt_block_Type(),
7899                     stubAddr, stubName, TypePtr::BOTTOM,
7900                     src_start, dest_start, k_start);
7901 
7902   return true;
7903 }
7904 
7905 //------------------------------inline_cipherBlockChaining_AESCrypt-----------------------
7906 bool LibraryCallKit::inline_cipherBlockChaining_AESCrypt(vmIntrinsics::ID id) {
7907   address stubAddr = nullptr;
7908   const char *stubName = nullptr;
7909 
7910   assert(UseAES, "need AES instruction support");
7911 
7912   switch(id) {
7913   case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
7914     stubAddr = StubRoutines::cipherBlockChaining_encryptAESCrypt();
7915     stubName = "cipherBlockChaining_encryptAESCrypt";
7916     break;
7917   case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
7918     stubAddr = StubRoutines::cipherBlockChaining_decryptAESCrypt();
7919     stubName = "cipherBlockChaining_decryptAESCrypt";
7920     break;
7921   default:
7922     break;
7923   }
7924   if (stubAddr == nullptr) return false;
7925 
7926   Node* cipherBlockChaining_object = argument(0);
7927   Node* src                        = argument(1);
7928   Node* src_offset                 = argument(2);
7929   Node* len                        = argument(3);
7930   Node* dest                       = argument(4);
7931   Node* dest_offset                = argument(5);
7932 
7933   src = must_be_not_null(src, false);
7934   dest = must_be_not_null(dest, false);
7935 
7936   // (1) src and dest are arrays.
7937   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7938   const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
7939   assert( src_type != nullptr &&  src_type->elem() != Type::BOTTOM &&
7940          dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
7941 
7942   // checks are the responsibility of the caller
7943   Node* src_start  = src;
7944   Node* dest_start = dest;
7945   if (src_offset != nullptr || dest_offset != nullptr) {
7946     assert(src_offset != nullptr && dest_offset != nullptr, "");
7947     src_start  = array_element_address(src,  src_offset,  T_BYTE);
7948     dest_start = array_element_address(dest, dest_offset, T_BYTE);
7949   }
7950 
7951   // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
7952   // (because of the predicated logic executed earlier).
7953   // so we cast it here safely.
7954   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
7955 
7956   Node* embeddedCipherObj = load_field_from_object(cipherBlockChaining_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
7957   if (embeddedCipherObj == nullptr) return false;
7958 
7959   // cast it to what we know it will be at runtime
7960   const TypeInstPtr* tinst = _gvn.type(cipherBlockChaining_object)->isa_instptr();
7961   assert(tinst != nullptr, "CBC obj is null");
7962   assert(tinst->is_loaded(), "CBC obj is not loaded");
7963   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
7964   assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
7965 
7966   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
7967   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
7968   const TypeOopPtr* xtype = aklass->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
7969   Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
7970   aescrypt_object = _gvn.transform(aescrypt_object);
7971 
7972   // we need to get the start of the aescrypt_object's expanded key array
7973   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object);
7974   if (k_start == nullptr) return false;
7975 
7976   // similarly, get the start address of the r vector
7977   Node* objRvec = load_field_from_object(cipherBlockChaining_object, "r", "[B");
7978   if (objRvec == nullptr) return false;
7979   Node* r_start = array_element_address(objRvec, intcon(0), T_BYTE);
7980 
7981   // Call the stub, passing src_start, dest_start, k_start, r_start and src_len
7982   Node* cbcCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
7983                                      OptoRuntime::cipherBlockChaining_aescrypt_Type(),
7984                                      stubAddr, stubName, TypePtr::BOTTOM,
7985                                      src_start, dest_start, k_start, r_start, len);
7986 
7987   // return cipher length (int)
7988   Node* retvalue = _gvn.transform(new ProjNode(cbcCrypt, TypeFunc::Parms));
7989   set_result(retvalue);
7990   return true;
7991 }
7992 
7993 //------------------------------inline_electronicCodeBook_AESCrypt-----------------------
7994 bool LibraryCallKit::inline_electronicCodeBook_AESCrypt(vmIntrinsics::ID id) {
7995   address stubAddr = nullptr;
7996   const char *stubName = nullptr;
7997 
7998   assert(UseAES, "need AES instruction support");
7999 
8000   switch (id) {
8001   case vmIntrinsics::_electronicCodeBook_encryptAESCrypt:
8002     stubAddr = StubRoutines::electronicCodeBook_encryptAESCrypt();
8003     stubName = "electronicCodeBook_encryptAESCrypt";
8004     break;
8005   case vmIntrinsics::_electronicCodeBook_decryptAESCrypt:
8006     stubAddr = StubRoutines::electronicCodeBook_decryptAESCrypt();
8007     stubName = "electronicCodeBook_decryptAESCrypt";
8008     break;
8009   default:
8010     break;
8011   }
8012 
8013   if (stubAddr == nullptr) return false;
8014 
8015   Node* electronicCodeBook_object = argument(0);
8016   Node* src                       = argument(1);
8017   Node* src_offset                = argument(2);
8018   Node* len                       = argument(3);
8019   Node* dest                      = argument(4);
8020   Node* dest_offset               = argument(5);
8021 
8022   // (1) src and dest are arrays.
8023   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
8024   const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
8025   assert( src_type != nullptr &&  src_type->elem() != Type::BOTTOM &&
8026          dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
8027 
8028   // checks are the responsibility of the caller
8029   Node* src_start = src;
8030   Node* dest_start = dest;
8031   if (src_offset != nullptr || dest_offset != nullptr) {
8032     assert(src_offset != nullptr && dest_offset != nullptr, "");
8033     src_start = array_element_address(src, src_offset, T_BYTE);
8034     dest_start = array_element_address(dest, dest_offset, T_BYTE);
8035   }
8036 
8037   // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
8038   // (because of the predicated logic executed earlier).
8039   // so we cast it here safely.
8040   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
8041 
8042   Node* embeddedCipherObj = load_field_from_object(electronicCodeBook_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8043   if (embeddedCipherObj == nullptr) return false;
8044 
8045   // cast it to what we know it will be at runtime
8046   const TypeInstPtr* tinst = _gvn.type(electronicCodeBook_object)->isa_instptr();
8047   assert(tinst != nullptr, "ECB obj is null");
8048   assert(tinst->is_loaded(), "ECB obj is not loaded");
8049   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8050   assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
8051 
8052   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8053   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
8054   const TypeOopPtr* xtype = aklass->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
8055   Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
8056   aescrypt_object = _gvn.transform(aescrypt_object);
8057 
8058   // we need to get the start of the aescrypt_object's expanded key array
8059   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object);
8060   if (k_start == nullptr) return false;
8061 
8062   // Call the stub, passing src_start, dest_start, k_start, r_start and src_len
8063   Node* ecbCrypt = make_runtime_call(RC_LEAF | RC_NO_FP,
8064                                      OptoRuntime::electronicCodeBook_aescrypt_Type(),
8065                                      stubAddr, stubName, TypePtr::BOTTOM,
8066                                      src_start, dest_start, k_start, len);
8067 
8068   // return cipher length (int)
8069   Node* retvalue = _gvn.transform(new ProjNode(ecbCrypt, TypeFunc::Parms));
8070   set_result(retvalue);
8071   return true;
8072 }
8073 
8074 //------------------------------inline_counterMode_AESCrypt-----------------------
8075 bool LibraryCallKit::inline_counterMode_AESCrypt(vmIntrinsics::ID id) {
8076   assert(UseAES, "need AES instruction support");
8077   if (!UseAESCTRIntrinsics) return false;
8078 
8079   address stubAddr = nullptr;
8080   const char *stubName = nullptr;
8081   if (id == vmIntrinsics::_counterMode_AESCrypt) {
8082     stubAddr = StubRoutines::counterMode_AESCrypt();
8083     stubName = "counterMode_AESCrypt";
8084   }
8085   if (stubAddr == nullptr) return false;
8086 
8087   Node* counterMode_object = argument(0);
8088   Node* src = argument(1);
8089   Node* src_offset = argument(2);
8090   Node* len = argument(3);
8091   Node* dest = argument(4);
8092   Node* dest_offset = argument(5);
8093 
8094   // (1) src and dest are arrays.
8095   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
8096   const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
8097   assert( src_type != nullptr &&  src_type->elem() != Type::BOTTOM &&
8098          dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
8099 
8100   // checks are the responsibility of the caller
8101   Node* src_start = src;
8102   Node* dest_start = dest;
8103   if (src_offset != nullptr || dest_offset != nullptr) {
8104     assert(src_offset != nullptr && dest_offset != nullptr, "");
8105     src_start = array_element_address(src, src_offset, T_BYTE);
8106     dest_start = array_element_address(dest, dest_offset, T_BYTE);
8107   }
8108 
8109   // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
8110   // (because of the predicated logic executed earlier).
8111   // so we cast it here safely.
8112   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
8113   Node* embeddedCipherObj = load_field_from_object(counterMode_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8114   if (embeddedCipherObj == nullptr) return false;
8115   // cast it to what we know it will be at runtime
8116   const TypeInstPtr* tinst = _gvn.type(counterMode_object)->isa_instptr();
8117   assert(tinst != nullptr, "CTR obj is null");
8118   assert(tinst->is_loaded(), "CTR obj is not loaded");
8119   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8120   assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
8121   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8122   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
8123   const TypeOopPtr* xtype = aklass->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
8124   Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
8125   aescrypt_object = _gvn.transform(aescrypt_object);
8126   // we need to get the start of the aescrypt_object's expanded key array
8127   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object);
8128   if (k_start == nullptr) return false;
8129   // similarly, get the start address of the r vector
8130   Node* obj_counter = load_field_from_object(counterMode_object, "counter", "[B");
8131   if (obj_counter == nullptr) return false;
8132   Node* cnt_start = array_element_address(obj_counter, intcon(0), T_BYTE);
8133 
8134   Node* saved_encCounter = load_field_from_object(counterMode_object, "encryptedCounter", "[B");
8135   if (saved_encCounter == nullptr) return false;
8136   Node* saved_encCounter_start = array_element_address(saved_encCounter, intcon(0), T_BYTE);
8137   Node* used = field_address_from_object(counterMode_object, "used", "I", /*is_exact*/ false);
8138 
8139   // Call the stub, passing src_start, dest_start, k_start, r_start and src_len
8140   Node* ctrCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
8141                                      OptoRuntime::counterMode_aescrypt_Type(),
8142                                      stubAddr, stubName, TypePtr::BOTTOM,
8143                                      src_start, dest_start, k_start, cnt_start, len, saved_encCounter_start, used);
8144 
8145   // return cipher length (int)
8146   Node* retvalue = _gvn.transform(new ProjNode(ctrCrypt, TypeFunc::Parms));
8147   set_result(retvalue);
8148   return true;
8149 }
8150 
8151 //------------------------------get_key_start_from_aescrypt_object-----------------------
8152 Node * LibraryCallKit::get_key_start_from_aescrypt_object(Node *aescrypt_object) {
8153 #if defined(PPC64) || defined(S390) || defined(RISCV64)
8154   // MixColumns for decryption can be reduced by preprocessing MixColumns with round keys.
8155   // Intel's extension is based on this optimization and AESCrypt generates round keys by preprocessing MixColumns.
8156   // However, ppc64 vncipher processes MixColumns and requires the same round keys with encryption.
8157   // The ppc64 and riscv64 stubs of encryption and decryption use the same round keys (sessionK[0]).
8158   Node* objSessionK = load_field_from_object(aescrypt_object, "sessionK", "[[I");
8159   assert (objSessionK != nullptr, "wrong version of com.sun.crypto.provider.AES_Crypt");
8160   if (objSessionK == nullptr) {
8161     return (Node *) nullptr;
8162   }
8163   Node* objAESCryptKey = load_array_element(objSessionK, intcon(0), TypeAryPtr::OOPS, /* set_ctrl */ true);
8164 #else
8165   Node* objAESCryptKey = load_field_from_object(aescrypt_object, "K", "[I");
8166 #endif // PPC64
8167   assert (objAESCryptKey != nullptr, "wrong version of com.sun.crypto.provider.AES_Crypt");
8168   if (objAESCryptKey == nullptr) return (Node *) nullptr;
8169 
8170   // now have the array, need to get the start address of the K array
8171   Node* k_start = array_element_address(objAESCryptKey, intcon(0), T_INT);
8172   return k_start;
8173 }
8174 
8175 //----------------------------inline_cipherBlockChaining_AESCrypt_predicate----------------------------
8176 // Return node representing slow path of predicate check.
8177 // the pseudo code we want to emulate with this predicate is:
8178 // for encryption:
8179 //    if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
8180 // for decryption:
8181 //    if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
8182 //    note cipher==plain is more conservative than the original java code but that's OK
8183 //
8184 Node* LibraryCallKit::inline_cipherBlockChaining_AESCrypt_predicate(bool decrypting) {
8185   // The receiver was checked for null already.
8186   Node* objCBC = argument(0);
8187 
8188   Node* src = argument(1);
8189   Node* dest = argument(4);
8190 
8191   // Load embeddedCipher field of CipherBlockChaining object.
8192   Node* embeddedCipherObj = load_field_from_object(objCBC, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8193 
8194   // get AESCrypt klass for instanceOf check
8195   // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
8196   // will have same classloader as CipherBlockChaining object
8197   const TypeInstPtr* tinst = _gvn.type(objCBC)->isa_instptr();
8198   assert(tinst != nullptr, "CBCobj is null");
8199   assert(tinst->is_loaded(), "CBCobj is not loaded");
8200 
8201   // we want to do an instanceof comparison against the AESCrypt class
8202   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8203   if (!klass_AESCrypt->is_loaded()) {
8204     // if AESCrypt is not even loaded, we never take the intrinsic fast path
8205     Node* ctrl = control();
8206     set_control(top()); // no regular fast path
8207     return ctrl;
8208   }
8209 
8210   src = must_be_not_null(src, true);
8211   dest = must_be_not_null(dest, true);
8212 
8213   // Resolve oops to stable for CmpP below.
8214   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8215 
8216   Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
8217   Node* cmp_instof  = _gvn.transform(new CmpINode(instof, intcon(1)));
8218   Node* bool_instof  = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
8219 
8220   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
8221 
8222   // for encryption, we are done
8223   if (!decrypting)
8224     return instof_false;  // even if it is null
8225 
8226   // for decryption, we need to add a further check to avoid
8227   // taking the intrinsic path when cipher and plain are the same
8228   // see the original java code for why.
8229   RegionNode* region = new RegionNode(3);
8230   region->init_req(1, instof_false);
8231 
8232   Node* cmp_src_dest = _gvn.transform(new CmpPNode(src, dest));
8233   Node* bool_src_dest = _gvn.transform(new BoolNode(cmp_src_dest, BoolTest::eq));
8234   Node* src_dest_conjoint = generate_guard(bool_src_dest, nullptr, PROB_MIN);
8235   region->init_req(2, src_dest_conjoint);
8236 
8237   record_for_igvn(region);
8238   return _gvn.transform(region);
8239 }
8240 
8241 //----------------------------inline_electronicCodeBook_AESCrypt_predicate----------------------------
8242 // Return node representing slow path of predicate check.
8243 // the pseudo code we want to emulate with this predicate is:
8244 // for encryption:
8245 //    if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
8246 // for decryption:
8247 //    if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
8248 //    note cipher==plain is more conservative than the original java code but that's OK
8249 //
8250 Node* LibraryCallKit::inline_electronicCodeBook_AESCrypt_predicate(bool decrypting) {
8251   // The receiver was checked for null already.
8252   Node* objECB = argument(0);
8253 
8254   // Load embeddedCipher field of ElectronicCodeBook object.
8255   Node* embeddedCipherObj = load_field_from_object(objECB, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8256 
8257   // get AESCrypt klass for instanceOf check
8258   // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
8259   // will have same classloader as ElectronicCodeBook object
8260   const TypeInstPtr* tinst = _gvn.type(objECB)->isa_instptr();
8261   assert(tinst != nullptr, "ECBobj is null");
8262   assert(tinst->is_loaded(), "ECBobj is not loaded");
8263 
8264   // we want to do an instanceof comparison against the AESCrypt class
8265   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8266   if (!klass_AESCrypt->is_loaded()) {
8267     // if AESCrypt is not even loaded, we never take the intrinsic fast path
8268     Node* ctrl = control();
8269     set_control(top()); // no regular fast path
8270     return ctrl;
8271   }
8272   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8273 
8274   Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
8275   Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
8276   Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
8277 
8278   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
8279 
8280   // for encryption, we are done
8281   if (!decrypting)
8282     return instof_false;  // even if it is null
8283 
8284   // for decryption, we need to add a further check to avoid
8285   // taking the intrinsic path when cipher and plain are the same
8286   // see the original java code for why.
8287   RegionNode* region = new RegionNode(3);
8288   region->init_req(1, instof_false);
8289   Node* src = argument(1);
8290   Node* dest = argument(4);
8291   Node* cmp_src_dest = _gvn.transform(new CmpPNode(src, dest));
8292   Node* bool_src_dest = _gvn.transform(new BoolNode(cmp_src_dest, BoolTest::eq));
8293   Node* src_dest_conjoint = generate_guard(bool_src_dest, nullptr, PROB_MIN);
8294   region->init_req(2, src_dest_conjoint);
8295 
8296   record_for_igvn(region);
8297   return _gvn.transform(region);
8298 }
8299 
8300 //----------------------------inline_counterMode_AESCrypt_predicate----------------------------
8301 // Return node representing slow path of predicate check.
8302 // the pseudo code we want to emulate with this predicate is:
8303 // for encryption:
8304 //    if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
8305 // for decryption:
8306 //    if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
8307 //    note cipher==plain is more conservative than the original java code but that's OK
8308 //
8309 
8310 Node* LibraryCallKit::inline_counterMode_AESCrypt_predicate() {
8311   // The receiver was checked for null already.
8312   Node* objCTR = argument(0);
8313 
8314   // Load embeddedCipher field of CipherBlockChaining object.
8315   Node* embeddedCipherObj = load_field_from_object(objCTR, "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 CipherBlockChaining object
8320   const TypeInstPtr* tinst = _gvn.type(objCTR)->isa_instptr();
8321   assert(tinst != nullptr, "CTRobj is null");
8322   assert(tinst->is_loaded(), "CTRobj 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 
8333   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
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   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
8338 
8339   return instof_false; // even if it is null
8340 }
8341 
8342 //------------------------------inline_ghash_processBlocks
8343 bool LibraryCallKit::inline_ghash_processBlocks() {
8344   address stubAddr;
8345   const char *stubName;
8346   assert(UseGHASHIntrinsics, "need GHASH intrinsics support");
8347 
8348   stubAddr = StubRoutines::ghash_processBlocks();
8349   stubName = "ghash_processBlocks";
8350 
8351   Node* data           = argument(0);
8352   Node* offset         = argument(1);
8353   Node* len            = argument(2);
8354   Node* state          = argument(3);
8355   Node* subkeyH        = argument(4);
8356 
8357   state = must_be_not_null(state, true);
8358   subkeyH = must_be_not_null(subkeyH, true);
8359   data = must_be_not_null(data, true);
8360 
8361   Node* state_start  = array_element_address(state, intcon(0), T_LONG);
8362   assert(state_start, "state is null");
8363   Node* subkeyH_start  = array_element_address(subkeyH, intcon(0), T_LONG);
8364   assert(subkeyH_start, "subkeyH is null");
8365   Node* data_start  = array_element_address(data, offset, T_BYTE);
8366   assert(data_start, "data is null");
8367 
8368   Node* ghash = make_runtime_call(RC_LEAF|RC_NO_FP,
8369                                   OptoRuntime::ghash_processBlocks_Type(),
8370                                   stubAddr, stubName, TypePtr::BOTTOM,
8371                                   state_start, subkeyH_start, data_start, len);
8372   return true;
8373 }
8374 
8375 //------------------------------inline_chacha20Block
8376 bool LibraryCallKit::inline_chacha20Block() {
8377   address stubAddr;
8378   const char *stubName;
8379   assert(UseChaCha20Intrinsics, "need ChaCha20 intrinsics support");
8380 
8381   stubAddr = StubRoutines::chacha20Block();
8382   stubName = "chacha20Block";
8383 
8384   Node* state          = argument(0);
8385   Node* result         = argument(1);
8386 
8387   state = must_be_not_null(state, true);
8388   result = must_be_not_null(result, true);
8389 
8390   Node* state_start  = array_element_address(state, intcon(0), T_INT);
8391   assert(state_start, "state is null");
8392   Node* result_start  = array_element_address(result, intcon(0), T_BYTE);
8393   assert(result_start, "result is null");
8394 
8395   Node* cc20Blk = make_runtime_call(RC_LEAF|RC_NO_FP,
8396                                   OptoRuntime::chacha20Block_Type(),
8397                                   stubAddr, stubName, TypePtr::BOTTOM,
8398                                   state_start, result_start);
8399   // return key stream length (int)
8400   Node* retvalue = _gvn.transform(new ProjNode(cc20Blk, TypeFunc::Parms));
8401   set_result(retvalue);
8402   return true;
8403 }
8404 
8405 //------------------------------inline_kyberNtt
8406 bool LibraryCallKit::inline_kyberNtt() {
8407   address stubAddr;
8408   const char *stubName;
8409   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8410   assert(callee()->signature()->size() == 2, "kyberNtt has 2 parameters");
8411 
8412   stubAddr = StubRoutines::kyberNtt();
8413   stubName = "kyberNtt";
8414   if (!stubAddr) return false;
8415 
8416   Node* coeffs          = argument(0);
8417   Node* ntt_zetas        = argument(1);
8418 
8419   coeffs = must_be_not_null(coeffs, true);
8420   ntt_zetas = must_be_not_null(ntt_zetas, true);
8421 
8422   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_SHORT);
8423   assert(coeffs_start, "coeffs is null");
8424   Node* ntt_zetas_start  = array_element_address(ntt_zetas, intcon(0), T_SHORT);
8425   assert(ntt_zetas_start, "ntt_zetas is null");
8426   Node* kyberNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
8427                                   OptoRuntime::kyberNtt_Type(),
8428                                   stubAddr, stubName, TypePtr::BOTTOM,
8429                                   coeffs_start, ntt_zetas_start);
8430   // return an int
8431   Node* retvalue = _gvn.transform(new ProjNode(kyberNtt, TypeFunc::Parms));
8432   set_result(retvalue);
8433   return true;
8434 }
8435 
8436 //------------------------------inline_kyberInverseNtt
8437 bool LibraryCallKit::inline_kyberInverseNtt() {
8438   address stubAddr;
8439   const char *stubName;
8440   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8441   assert(callee()->signature()->size() == 2, "kyberInverseNtt has 2 parameters");
8442 
8443   stubAddr = StubRoutines::kyberInverseNtt();
8444   stubName = "kyberInverseNtt";
8445   if (!stubAddr) return false;
8446 
8447   Node* coeffs          = argument(0);
8448   Node* zetas           = argument(1);
8449 
8450   coeffs = must_be_not_null(coeffs, true);
8451   zetas = must_be_not_null(zetas, true);
8452 
8453   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_SHORT);
8454   assert(coeffs_start, "coeffs is null");
8455   Node* zetas_start  = array_element_address(zetas, intcon(0), T_SHORT);
8456   assert(zetas_start, "inverseNtt_zetas is null");
8457   Node* kyberInverseNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
8458                                   OptoRuntime::kyberInverseNtt_Type(),
8459                                   stubAddr, stubName, TypePtr::BOTTOM,
8460                                   coeffs_start, zetas_start);
8461 
8462   // return an int
8463   Node* retvalue = _gvn.transform(new ProjNode(kyberInverseNtt, TypeFunc::Parms));
8464   set_result(retvalue);
8465   return true;
8466 }
8467 
8468 //------------------------------inline_kyberNttMult
8469 bool LibraryCallKit::inline_kyberNttMult() {
8470   address stubAddr;
8471   const char *stubName;
8472   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8473   assert(callee()->signature()->size() == 4, "kyberNttMult has 4 parameters");
8474 
8475   stubAddr = StubRoutines::kyberNttMult();
8476   stubName = "kyberNttMult";
8477   if (!stubAddr) return false;
8478 
8479   Node* result          = argument(0);
8480   Node* ntta            = argument(1);
8481   Node* nttb            = argument(2);
8482   Node* zetas           = argument(3);
8483 
8484   result = must_be_not_null(result, true);
8485   ntta = must_be_not_null(ntta, true);
8486   nttb = must_be_not_null(nttb, true);
8487   zetas = must_be_not_null(zetas, true);
8488 
8489   Node* result_start  = array_element_address(result, intcon(0), T_SHORT);
8490   assert(result_start, "result is null");
8491   Node* ntta_start  = array_element_address(ntta, intcon(0), T_SHORT);
8492   assert(ntta_start, "ntta is null");
8493   Node* nttb_start  = array_element_address(nttb, intcon(0), T_SHORT);
8494   assert(nttb_start, "nttb is null");
8495   Node* zetas_start  = array_element_address(zetas, intcon(0), T_SHORT);
8496   assert(zetas_start, "nttMult_zetas is null");
8497   Node* kyberNttMult = make_runtime_call(RC_LEAF|RC_NO_FP,
8498                                   OptoRuntime::kyberNttMult_Type(),
8499                                   stubAddr, stubName, TypePtr::BOTTOM,
8500                                   result_start, ntta_start, nttb_start,
8501                                   zetas_start);
8502 
8503   // return an int
8504   Node* retvalue = _gvn.transform(new ProjNode(kyberNttMult, TypeFunc::Parms));
8505   set_result(retvalue);
8506 
8507   return true;
8508 }
8509 
8510 //------------------------------inline_kyberAddPoly_2
8511 bool LibraryCallKit::inline_kyberAddPoly_2() {
8512   address stubAddr;
8513   const char *stubName;
8514   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8515   assert(callee()->signature()->size() == 3, "kyberAddPoly_2 has 3 parameters");
8516 
8517   stubAddr = StubRoutines::kyberAddPoly_2();
8518   stubName = "kyberAddPoly_2";
8519   if (!stubAddr) return false;
8520 
8521   Node* result          = argument(0);
8522   Node* a               = argument(1);
8523   Node* b               = argument(2);
8524 
8525   result = must_be_not_null(result, true);
8526   a = must_be_not_null(a, true);
8527   b = must_be_not_null(b, true);
8528 
8529   Node* result_start  = array_element_address(result, intcon(0), T_SHORT);
8530   assert(result_start, "result is null");
8531   Node* a_start  = array_element_address(a, intcon(0), T_SHORT);
8532   assert(a_start, "a is null");
8533   Node* b_start  = array_element_address(b, intcon(0), T_SHORT);
8534   assert(b_start, "b is null");
8535   Node* kyberAddPoly_2 = make_runtime_call(RC_LEAF|RC_NO_FP,
8536                                   OptoRuntime::kyberAddPoly_2_Type(),
8537                                   stubAddr, stubName, TypePtr::BOTTOM,
8538                                   result_start, a_start, b_start);
8539   // return an int
8540   Node* retvalue = _gvn.transform(new ProjNode(kyberAddPoly_2, TypeFunc::Parms));
8541   set_result(retvalue);
8542   return true;
8543 }
8544 
8545 //------------------------------inline_kyberAddPoly_3
8546 bool LibraryCallKit::inline_kyberAddPoly_3() {
8547   address stubAddr;
8548   const char *stubName;
8549   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8550   assert(callee()->signature()->size() == 4, "kyberAddPoly_3 has 4 parameters");
8551 
8552   stubAddr = StubRoutines::kyberAddPoly_3();
8553   stubName = "kyberAddPoly_3";
8554   if (!stubAddr) return false;
8555 
8556   Node* result          = argument(0);
8557   Node* a               = argument(1);
8558   Node* b               = argument(2);
8559   Node* c               = argument(3);
8560 
8561   result = must_be_not_null(result, true);
8562   a = must_be_not_null(a, true);
8563   b = must_be_not_null(b, true);
8564   c = must_be_not_null(c, true);
8565 
8566   Node* result_start  = array_element_address(result, intcon(0), T_SHORT);
8567   assert(result_start, "result is null");
8568   Node* a_start  = array_element_address(a, intcon(0), T_SHORT);
8569   assert(a_start, "a is null");
8570   Node* b_start  = array_element_address(b, intcon(0), T_SHORT);
8571   assert(b_start, "b is null");
8572   Node* c_start  = array_element_address(c, intcon(0), T_SHORT);
8573   assert(c_start, "c is null");
8574   Node* kyberAddPoly_3 = make_runtime_call(RC_LEAF|RC_NO_FP,
8575                                   OptoRuntime::kyberAddPoly_3_Type(),
8576                                   stubAddr, stubName, TypePtr::BOTTOM,
8577                                   result_start, a_start, b_start, c_start);
8578   // return an int
8579   Node* retvalue = _gvn.transform(new ProjNode(kyberAddPoly_3, TypeFunc::Parms));
8580   set_result(retvalue);
8581   return true;
8582 }
8583 
8584 //------------------------------inline_kyber12To16
8585 bool LibraryCallKit::inline_kyber12To16() {
8586   address stubAddr;
8587   const char *stubName;
8588   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8589   assert(callee()->signature()->size() == 4, "kyber12To16 has 4 parameters");
8590 
8591   stubAddr = StubRoutines::kyber12To16();
8592   stubName = "kyber12To16";
8593   if (!stubAddr) return false;
8594 
8595   Node* condensed       = argument(0);
8596   Node* condensedOffs   = argument(1);
8597   Node* parsed          = argument(2);
8598   Node* parsedLength    = argument(3);
8599 
8600   condensed = must_be_not_null(condensed, true);
8601   parsed = must_be_not_null(parsed, true);
8602 
8603   Node* condensed_start  = array_element_address(condensed, intcon(0), T_BYTE);
8604   assert(condensed_start, "condensed is null");
8605   Node* parsed_start  = array_element_address(parsed, intcon(0), T_SHORT);
8606   assert(parsed_start, "parsed is null");
8607   Node* kyber12To16 = make_runtime_call(RC_LEAF|RC_NO_FP,
8608                                   OptoRuntime::kyber12To16_Type(),
8609                                   stubAddr, stubName, TypePtr::BOTTOM,
8610                                   condensed_start, condensedOffs, parsed_start, parsedLength);
8611   // return an int
8612   Node* retvalue = _gvn.transform(new ProjNode(kyber12To16, TypeFunc::Parms));
8613   set_result(retvalue);
8614   return true;
8615 
8616 }
8617 
8618 //------------------------------inline_kyberBarrettReduce
8619 bool LibraryCallKit::inline_kyberBarrettReduce() {
8620   address stubAddr;
8621   const char *stubName;
8622   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8623   assert(callee()->signature()->size() == 1, "kyberBarrettReduce has 1 parameters");
8624 
8625   stubAddr = StubRoutines::kyberBarrettReduce();
8626   stubName = "kyberBarrettReduce";
8627   if (!stubAddr) return false;
8628 
8629   Node* coeffs          = argument(0);
8630 
8631   coeffs = must_be_not_null(coeffs, true);
8632 
8633   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_SHORT);
8634   assert(coeffs_start, "coeffs is null");
8635   Node* kyberBarrettReduce = make_runtime_call(RC_LEAF|RC_NO_FP,
8636                                   OptoRuntime::kyberBarrettReduce_Type(),
8637                                   stubAddr, stubName, TypePtr::BOTTOM,
8638                                   coeffs_start);
8639   // return an int
8640   Node* retvalue = _gvn.transform(new ProjNode(kyberBarrettReduce, TypeFunc::Parms));
8641   set_result(retvalue);
8642   return true;
8643 }
8644 
8645 //------------------------------inline_dilithiumAlmostNtt
8646 bool LibraryCallKit::inline_dilithiumAlmostNtt() {
8647   address stubAddr;
8648   const char *stubName;
8649   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8650   assert(callee()->signature()->size() == 2, "dilithiumAlmostNtt has 2 parameters");
8651 
8652   stubAddr = StubRoutines::dilithiumAlmostNtt();
8653   stubName = "dilithiumAlmostNtt";
8654   if (!stubAddr) return false;
8655 
8656   Node* coeffs          = argument(0);
8657   Node* ntt_zetas        = argument(1);
8658 
8659   coeffs = must_be_not_null(coeffs, true);
8660   ntt_zetas = must_be_not_null(ntt_zetas, true);
8661 
8662   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_INT);
8663   assert(coeffs_start, "coeffs is null");
8664   Node* ntt_zetas_start  = array_element_address(ntt_zetas, intcon(0), T_INT);
8665   assert(ntt_zetas_start, "ntt_zetas is null");
8666   Node* dilithiumAlmostNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
8667                                   OptoRuntime::dilithiumAlmostNtt_Type(),
8668                                   stubAddr, stubName, TypePtr::BOTTOM,
8669                                   coeffs_start, ntt_zetas_start);
8670   // return an int
8671   Node* retvalue = _gvn.transform(new ProjNode(dilithiumAlmostNtt, TypeFunc::Parms));
8672   set_result(retvalue);
8673   return true;
8674 }
8675 
8676 //------------------------------inline_dilithiumAlmostInverseNtt
8677 bool LibraryCallKit::inline_dilithiumAlmostInverseNtt() {
8678   address stubAddr;
8679   const char *stubName;
8680   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8681   assert(callee()->signature()->size() == 2, "dilithiumAlmostInverseNtt has 2 parameters");
8682 
8683   stubAddr = StubRoutines::dilithiumAlmostInverseNtt();
8684   stubName = "dilithiumAlmostInverseNtt";
8685   if (!stubAddr) return false;
8686 
8687   Node* coeffs          = argument(0);
8688   Node* zetas           = argument(1);
8689 
8690   coeffs = must_be_not_null(coeffs, true);
8691   zetas = must_be_not_null(zetas, true);
8692 
8693   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_INT);
8694   assert(coeffs_start, "coeffs is null");
8695   Node* zetas_start  = array_element_address(zetas, intcon(0), T_INT);
8696   assert(zetas_start, "inverseNtt_zetas is null");
8697   Node* dilithiumAlmostInverseNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
8698                                   OptoRuntime::dilithiumAlmostInverseNtt_Type(),
8699                                   stubAddr, stubName, TypePtr::BOTTOM,
8700                                   coeffs_start, zetas_start);
8701   // return an int
8702   Node* retvalue = _gvn.transform(new ProjNode(dilithiumAlmostInverseNtt, TypeFunc::Parms));
8703   set_result(retvalue);
8704   return true;
8705 }
8706 
8707 //------------------------------inline_dilithiumNttMult
8708 bool LibraryCallKit::inline_dilithiumNttMult() {
8709   address stubAddr;
8710   const char *stubName;
8711   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8712   assert(callee()->signature()->size() == 3, "dilithiumNttMult has 3 parameters");
8713 
8714   stubAddr = StubRoutines::dilithiumNttMult();
8715   stubName = "dilithiumNttMult";
8716   if (!stubAddr) return false;
8717 
8718   Node* result          = argument(0);
8719   Node* ntta            = argument(1);
8720   Node* nttb            = argument(2);
8721   Node* zetas           = argument(3);
8722 
8723   result = must_be_not_null(result, true);
8724   ntta = must_be_not_null(ntta, true);
8725   nttb = must_be_not_null(nttb, true);
8726   zetas = must_be_not_null(zetas, true);
8727 
8728   Node* result_start  = array_element_address(result, intcon(0), T_INT);
8729   assert(result_start, "result is null");
8730   Node* ntta_start  = array_element_address(ntta, intcon(0), T_INT);
8731   assert(ntta_start, "ntta is null");
8732   Node* nttb_start  = array_element_address(nttb, intcon(0), T_INT);
8733   assert(nttb_start, "nttb is null");
8734   Node* dilithiumNttMult = make_runtime_call(RC_LEAF|RC_NO_FP,
8735                                   OptoRuntime::dilithiumNttMult_Type(),
8736                                   stubAddr, stubName, TypePtr::BOTTOM,
8737                                   result_start, ntta_start, nttb_start);
8738 
8739   // return an int
8740   Node* retvalue = _gvn.transform(new ProjNode(dilithiumNttMult, TypeFunc::Parms));
8741   set_result(retvalue);
8742 
8743   return true;
8744 }
8745 
8746 //------------------------------inline_dilithiumMontMulByConstant
8747 bool LibraryCallKit::inline_dilithiumMontMulByConstant() {
8748   address stubAddr;
8749   const char *stubName;
8750   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8751   assert(callee()->signature()->size() == 2, "dilithiumMontMulByConstant has 2 parameters");
8752 
8753   stubAddr = StubRoutines::dilithiumMontMulByConstant();
8754   stubName = "dilithiumMontMulByConstant";
8755   if (!stubAddr) return false;
8756 
8757   Node* coeffs          = argument(0);
8758   Node* constant        = argument(1);
8759 
8760   coeffs = must_be_not_null(coeffs, true);
8761 
8762   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_INT);
8763   assert(coeffs_start, "coeffs is null");
8764   Node* dilithiumMontMulByConstant = make_runtime_call(RC_LEAF|RC_NO_FP,
8765                                   OptoRuntime::dilithiumMontMulByConstant_Type(),
8766                                   stubAddr, stubName, TypePtr::BOTTOM,
8767                                   coeffs_start, constant);
8768 
8769   // return an int
8770   Node* retvalue = _gvn.transform(new ProjNode(dilithiumMontMulByConstant, TypeFunc::Parms));
8771   set_result(retvalue);
8772   return true;
8773 }
8774 
8775 
8776 //------------------------------inline_dilithiumDecomposePoly
8777 bool LibraryCallKit::inline_dilithiumDecomposePoly() {
8778   address stubAddr;
8779   const char *stubName;
8780   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8781   assert(callee()->signature()->size() == 5, "dilithiumDecomposePoly has 5 parameters");
8782 
8783   stubAddr = StubRoutines::dilithiumDecomposePoly();
8784   stubName = "dilithiumDecomposePoly";
8785   if (!stubAddr) return false;
8786 
8787   Node* input          = argument(0);
8788   Node* lowPart        = argument(1);
8789   Node* highPart       = argument(2);
8790   Node* twoGamma2      = argument(3);
8791   Node* multiplier     = argument(4);
8792 
8793   input = must_be_not_null(input, true);
8794   lowPart = must_be_not_null(lowPart, true);
8795   highPart = must_be_not_null(highPart, true);
8796 
8797   Node* input_start  = array_element_address(input, intcon(0), T_INT);
8798   assert(input_start, "input is null");
8799   Node* lowPart_start  = array_element_address(lowPart, intcon(0), T_INT);
8800   assert(lowPart_start, "lowPart is null");
8801   Node* highPart_start  = array_element_address(highPart, intcon(0), T_INT);
8802   assert(highPart_start, "highPart is null");
8803 
8804   Node* dilithiumDecomposePoly = make_runtime_call(RC_LEAF|RC_NO_FP,
8805                                   OptoRuntime::dilithiumDecomposePoly_Type(),
8806                                   stubAddr, stubName, TypePtr::BOTTOM,
8807                                   input_start, lowPart_start, highPart_start,
8808                                   twoGamma2, multiplier);
8809 
8810   // return an int
8811   Node* retvalue = _gvn.transform(new ProjNode(dilithiumDecomposePoly, TypeFunc::Parms));
8812   set_result(retvalue);
8813   return true;
8814 }
8815 
8816 bool LibraryCallKit::inline_base64_encodeBlock() {
8817   address stubAddr;
8818   const char *stubName;
8819   assert(UseBASE64Intrinsics, "need Base64 intrinsics support");
8820   assert(callee()->signature()->size() == 6, "base64_encodeBlock has 6 parameters");
8821   stubAddr = StubRoutines::base64_encodeBlock();
8822   stubName = "encodeBlock";
8823 
8824   if (!stubAddr) return false;
8825   Node* base64obj = argument(0);
8826   Node* src = argument(1);
8827   Node* offset = argument(2);
8828   Node* len = argument(3);
8829   Node* dest = argument(4);
8830   Node* dp = argument(5);
8831   Node* isURL = argument(6);
8832 
8833   src = must_be_not_null(src, true);
8834   dest = must_be_not_null(dest, true);
8835 
8836   Node* src_start = array_element_address(src, intcon(0), T_BYTE);
8837   assert(src_start, "source array is null");
8838   Node* dest_start = array_element_address(dest, intcon(0), T_BYTE);
8839   assert(dest_start, "destination array is null");
8840 
8841   Node* base64 = make_runtime_call(RC_LEAF,
8842                                    OptoRuntime::base64_encodeBlock_Type(),
8843                                    stubAddr, stubName, TypePtr::BOTTOM,
8844                                    src_start, offset, len, dest_start, dp, isURL);
8845   return true;
8846 }
8847 
8848 bool LibraryCallKit::inline_base64_decodeBlock() {
8849   address stubAddr;
8850   const char *stubName;
8851   assert(UseBASE64Intrinsics, "need Base64 intrinsics support");
8852   assert(callee()->signature()->size() == 7, "base64_decodeBlock has 7 parameters");
8853   stubAddr = StubRoutines::base64_decodeBlock();
8854   stubName = "decodeBlock";
8855 
8856   if (!stubAddr) return false;
8857   Node* base64obj = argument(0);
8858   Node* src = argument(1);
8859   Node* src_offset = argument(2);
8860   Node* len = argument(3);
8861   Node* dest = argument(4);
8862   Node* dest_offset = argument(5);
8863   Node* isURL = argument(6);
8864   Node* isMIME = argument(7);
8865 
8866   src = must_be_not_null(src, true);
8867   dest = must_be_not_null(dest, true);
8868 
8869   Node* src_start = array_element_address(src, intcon(0), T_BYTE);
8870   assert(src_start, "source array is null");
8871   Node* dest_start = array_element_address(dest, intcon(0), T_BYTE);
8872   assert(dest_start, "destination array is null");
8873 
8874   Node* call = make_runtime_call(RC_LEAF,
8875                                  OptoRuntime::base64_decodeBlock_Type(),
8876                                  stubAddr, stubName, TypePtr::BOTTOM,
8877                                  src_start, src_offset, len, dest_start, dest_offset, isURL, isMIME);
8878   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
8879   set_result(result);
8880   return true;
8881 }
8882 
8883 bool LibraryCallKit::inline_poly1305_processBlocks() {
8884   address stubAddr;
8885   const char *stubName;
8886   assert(UsePoly1305Intrinsics, "need Poly intrinsics support");
8887   assert(callee()->signature()->size() == 5, "poly1305_processBlocks has %d parameters", callee()->signature()->size());
8888   stubAddr = StubRoutines::poly1305_processBlocks();
8889   stubName = "poly1305_processBlocks";
8890 
8891   if (!stubAddr) return false;
8892   null_check_receiver();  // null-check receiver
8893   if (stopped())  return true;
8894 
8895   Node* input = argument(1);
8896   Node* input_offset = argument(2);
8897   Node* len = argument(3);
8898   Node* alimbs = argument(4);
8899   Node* rlimbs = argument(5);
8900 
8901   input = must_be_not_null(input, true);
8902   alimbs = must_be_not_null(alimbs, true);
8903   rlimbs = must_be_not_null(rlimbs, true);
8904 
8905   Node* input_start = array_element_address(input, input_offset, T_BYTE);
8906   assert(input_start, "input array is null");
8907   Node* acc_start = array_element_address(alimbs, intcon(0), T_LONG);
8908   assert(acc_start, "acc array is null");
8909   Node* r_start = array_element_address(rlimbs, intcon(0), T_LONG);
8910   assert(r_start, "r array is null");
8911 
8912   Node* call = make_runtime_call(RC_LEAF | RC_NO_FP,
8913                                  OptoRuntime::poly1305_processBlocks_Type(),
8914                                  stubAddr, stubName, TypePtr::BOTTOM,
8915                                  input_start, len, acc_start, r_start);
8916   return true;
8917 }
8918 
8919 bool LibraryCallKit::inline_intpoly_montgomeryMult_P256() {
8920   address stubAddr;
8921   const char *stubName;
8922   assert(UseIntPolyIntrinsics, "need intpoly intrinsics support");
8923   assert(callee()->signature()->size() == 3, "intpoly_montgomeryMult_P256 has %d parameters", callee()->signature()->size());
8924   stubAddr = StubRoutines::intpoly_montgomeryMult_P256();
8925   stubName = "intpoly_montgomeryMult_P256";
8926 
8927   if (!stubAddr) return false;
8928   null_check_receiver();  // null-check receiver
8929   if (stopped())  return true;
8930 
8931   Node* a = argument(1);
8932   Node* b = argument(2);
8933   Node* r = argument(3);
8934 
8935   a = must_be_not_null(a, true);
8936   b = must_be_not_null(b, true);
8937   r = must_be_not_null(r, true);
8938 
8939   Node* a_start = array_element_address(a, intcon(0), T_LONG);
8940   assert(a_start, "a array is null");
8941   Node* b_start = array_element_address(b, intcon(0), T_LONG);
8942   assert(b_start, "b array is null");
8943   Node* r_start = array_element_address(r, intcon(0), T_LONG);
8944   assert(r_start, "r array is null");
8945 
8946   Node* call = make_runtime_call(RC_LEAF | RC_NO_FP,
8947                                  OptoRuntime::intpoly_montgomeryMult_P256_Type(),
8948                                  stubAddr, stubName, TypePtr::BOTTOM,
8949                                  a_start, b_start, r_start);
8950   return true;
8951 }
8952 
8953 bool LibraryCallKit::inline_intpoly_assign() {
8954   assert(UseIntPolyIntrinsics, "need intpoly intrinsics support");
8955   assert(callee()->signature()->size() == 3, "intpoly_assign has %d parameters", callee()->signature()->size());
8956   const char *stubName = "intpoly_assign";
8957   address stubAddr = StubRoutines::intpoly_assign();
8958   if (!stubAddr) return false;
8959 
8960   Node* set = argument(0);
8961   Node* a = argument(1);
8962   Node* b = argument(2);
8963   Node* arr_length = load_array_length(a);
8964 
8965   a = must_be_not_null(a, true);
8966   b = must_be_not_null(b, true);
8967 
8968   Node* a_start = array_element_address(a, intcon(0), T_LONG);
8969   assert(a_start, "a array is null");
8970   Node* b_start = array_element_address(b, intcon(0), T_LONG);
8971   assert(b_start, "b array is null");
8972 
8973   Node* call = make_runtime_call(RC_LEAF | RC_NO_FP,
8974                                  OptoRuntime::intpoly_assign_Type(),
8975                                  stubAddr, stubName, TypePtr::BOTTOM,
8976                                  set, a_start, b_start, arr_length);
8977   return true;
8978 }
8979 
8980 //------------------------------inline_digestBase_implCompress-----------------------
8981 //
8982 // Calculate MD5 for single-block byte[] array.
8983 // void com.sun.security.provider.MD5.implCompress(byte[] buf, int ofs)
8984 //
8985 // Calculate SHA (i.e., SHA-1) for single-block byte[] array.
8986 // void com.sun.security.provider.SHA.implCompress(byte[] buf, int ofs)
8987 //
8988 // Calculate SHA2 (i.e., SHA-244 or SHA-256) for single-block byte[] array.
8989 // void com.sun.security.provider.SHA2.implCompress(byte[] buf, int ofs)
8990 //
8991 // Calculate SHA5 (i.e., SHA-384 or SHA-512) for single-block byte[] array.
8992 // void com.sun.security.provider.SHA5.implCompress(byte[] buf, int ofs)
8993 //
8994 // Calculate SHA3 (i.e., SHA3-224 or SHA3-256 or SHA3-384 or SHA3-512) for single-block byte[] array.
8995 // void com.sun.security.provider.SHA3.implCompress(byte[] buf, int ofs)
8996 //
8997 bool LibraryCallKit::inline_digestBase_implCompress(vmIntrinsics::ID id) {
8998   assert(callee()->signature()->size() == 2, "sha_implCompress has 2 parameters");
8999 
9000   Node* digestBase_obj = argument(0);
9001   Node* src            = argument(1); // type oop
9002   Node* ofs            = argument(2); // type int
9003 
9004   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
9005   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
9006     // failed array check
9007     return false;
9008   }
9009   // Figure out the size and type of the elements we will be copying.
9010   BasicType src_elem = src_type->elem()->array_element_basic_type();
9011   if (src_elem != T_BYTE) {
9012     return false;
9013   }
9014   // 'src_start' points to src array + offset
9015   src = must_be_not_null(src, true);
9016   Node* src_start = array_element_address(src, ofs, src_elem);
9017   Node* state = nullptr;
9018   Node* block_size = nullptr;
9019   address stubAddr;
9020   const char *stubName;
9021 
9022   switch(id) {
9023   case vmIntrinsics::_md5_implCompress:
9024     assert(UseMD5Intrinsics, "need MD5 instruction support");
9025     state = get_state_from_digest_object(digestBase_obj, T_INT);
9026     stubAddr = StubRoutines::md5_implCompress();
9027     stubName = "md5_implCompress";
9028     break;
9029   case vmIntrinsics::_sha_implCompress:
9030     assert(UseSHA1Intrinsics, "need SHA1 instruction support");
9031     state = get_state_from_digest_object(digestBase_obj, T_INT);
9032     stubAddr = StubRoutines::sha1_implCompress();
9033     stubName = "sha1_implCompress";
9034     break;
9035   case vmIntrinsics::_sha2_implCompress:
9036     assert(UseSHA256Intrinsics, "need SHA256 instruction support");
9037     state = get_state_from_digest_object(digestBase_obj, T_INT);
9038     stubAddr = StubRoutines::sha256_implCompress();
9039     stubName = "sha256_implCompress";
9040     break;
9041   case vmIntrinsics::_sha5_implCompress:
9042     assert(UseSHA512Intrinsics, "need SHA512 instruction support");
9043     state = get_state_from_digest_object(digestBase_obj, T_LONG);
9044     stubAddr = StubRoutines::sha512_implCompress();
9045     stubName = "sha512_implCompress";
9046     break;
9047   case vmIntrinsics::_sha3_implCompress:
9048     assert(UseSHA3Intrinsics, "need SHA3 instruction support");
9049     state = get_state_from_digest_object(digestBase_obj, T_LONG);
9050     stubAddr = StubRoutines::sha3_implCompress();
9051     stubName = "sha3_implCompress";
9052     block_size = get_block_size_from_digest_object(digestBase_obj);
9053     if (block_size == nullptr) return false;
9054     break;
9055   default:
9056     fatal_unexpected_iid(id);
9057     return false;
9058   }
9059   if (state == nullptr) return false;
9060 
9061   assert(stubAddr != nullptr, "Stub %s is not generated", stubName);
9062   if (stubAddr == nullptr) return false;
9063 
9064   // Call the stub.
9065   Node* call;
9066   if (block_size == nullptr) {
9067     call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::digestBase_implCompress_Type(false),
9068                              stubAddr, stubName, TypePtr::BOTTOM,
9069                              src_start, state);
9070   } else {
9071     call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::digestBase_implCompress_Type(true),
9072                              stubAddr, stubName, TypePtr::BOTTOM,
9073                              src_start, state, block_size);
9074   }
9075 
9076   return true;
9077 }
9078 
9079 //------------------------------inline_double_keccak
9080 bool LibraryCallKit::inline_double_keccak() {
9081   address stubAddr;
9082   const char *stubName;
9083   assert(UseSHA3Intrinsics, "need SHA3 intrinsics support");
9084   assert(callee()->signature()->size() == 2, "double_keccak has 2 parameters");
9085 
9086   stubAddr = StubRoutines::double_keccak();
9087   stubName = "double_keccak";
9088   if (!stubAddr) return false;
9089 
9090   Node* status0        = argument(0);
9091   Node* status1        = argument(1);
9092 
9093   status0 = must_be_not_null(status0, true);
9094   status1 = must_be_not_null(status1, true);
9095 
9096   Node* status0_start  = array_element_address(status0, intcon(0), T_LONG);
9097   assert(status0_start, "status0 is null");
9098   Node* status1_start  = array_element_address(status1, intcon(0), T_LONG);
9099   assert(status1_start, "status1 is null");
9100   Node* double_keccak = make_runtime_call(RC_LEAF|RC_NO_FP,
9101                                   OptoRuntime::double_keccak_Type(),
9102                                   stubAddr, stubName, TypePtr::BOTTOM,
9103                                   status0_start, status1_start);
9104   // return an int
9105   Node* retvalue = _gvn.transform(new ProjNode(double_keccak, TypeFunc::Parms));
9106   set_result(retvalue);
9107   return true;
9108 }
9109 
9110 
9111 //------------------------------inline_digestBase_implCompressMB-----------------------
9112 //
9113 // Calculate MD5/SHA/SHA2/SHA5/SHA3 for multi-block byte[] array.
9114 // int com.sun.security.provider.DigestBase.implCompressMultiBlock(byte[] b, int ofs, int limit)
9115 //
9116 bool LibraryCallKit::inline_digestBase_implCompressMB(int predicate) {
9117   assert(UseMD5Intrinsics || UseSHA1Intrinsics || UseSHA256Intrinsics || UseSHA512Intrinsics || UseSHA3Intrinsics,
9118          "need MD5/SHA1/SHA256/SHA512/SHA3 instruction support");
9119   assert((uint)predicate < 5, "sanity");
9120   assert(callee()->signature()->size() == 3, "digestBase_implCompressMB has 3 parameters");
9121 
9122   Node* digestBase_obj = argument(0); // The receiver was checked for null already.
9123   Node* src            = argument(1); // byte[] array
9124   Node* ofs            = argument(2); // type int
9125   Node* limit          = argument(3); // type int
9126 
9127   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
9128   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
9129     // failed array check
9130     return false;
9131   }
9132   // Figure out the size and type of the elements we will be copying.
9133   BasicType src_elem = src_type->elem()->array_element_basic_type();
9134   if (src_elem != T_BYTE) {
9135     return false;
9136   }
9137   // 'src_start' points to src array + offset
9138   src = must_be_not_null(src, false);
9139   Node* src_start = array_element_address(src, ofs, src_elem);
9140 
9141   const char* klass_digestBase_name = nullptr;
9142   const char* stub_name = nullptr;
9143   address     stub_addr = nullptr;
9144   BasicType elem_type = T_INT;
9145 
9146   switch (predicate) {
9147   case 0:
9148     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_md5_implCompress)) {
9149       klass_digestBase_name = "sun/security/provider/MD5";
9150       stub_name = "md5_implCompressMB";
9151       stub_addr = StubRoutines::md5_implCompressMB();
9152     }
9153     break;
9154   case 1:
9155     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha_implCompress)) {
9156       klass_digestBase_name = "sun/security/provider/SHA";
9157       stub_name = "sha1_implCompressMB";
9158       stub_addr = StubRoutines::sha1_implCompressMB();
9159     }
9160     break;
9161   case 2:
9162     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha2_implCompress)) {
9163       klass_digestBase_name = "sun/security/provider/SHA2";
9164       stub_name = "sha256_implCompressMB";
9165       stub_addr = StubRoutines::sha256_implCompressMB();
9166     }
9167     break;
9168   case 3:
9169     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha5_implCompress)) {
9170       klass_digestBase_name = "sun/security/provider/SHA5";
9171       stub_name = "sha512_implCompressMB";
9172       stub_addr = StubRoutines::sha512_implCompressMB();
9173       elem_type = T_LONG;
9174     }
9175     break;
9176   case 4:
9177     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha3_implCompress)) {
9178       klass_digestBase_name = "sun/security/provider/SHA3";
9179       stub_name = "sha3_implCompressMB";
9180       stub_addr = StubRoutines::sha3_implCompressMB();
9181       elem_type = T_LONG;
9182     }
9183     break;
9184   default:
9185     fatal("unknown DigestBase intrinsic predicate: %d", predicate);
9186   }
9187   if (klass_digestBase_name != nullptr) {
9188     assert(stub_addr != nullptr, "Stub is generated");
9189     if (stub_addr == nullptr) return false;
9190 
9191     // get DigestBase klass to lookup for SHA klass
9192     const TypeInstPtr* tinst = _gvn.type(digestBase_obj)->isa_instptr();
9193     assert(tinst != nullptr, "digestBase_obj is not instance???");
9194     assert(tinst->is_loaded(), "DigestBase is not loaded");
9195 
9196     ciKlass* klass_digestBase = tinst->instance_klass()->find_klass(ciSymbol::make(klass_digestBase_name));
9197     assert(klass_digestBase->is_loaded(), "predicate checks that this class is loaded");
9198     ciInstanceKlass* instklass_digestBase = klass_digestBase->as_instance_klass();
9199     return inline_digestBase_implCompressMB(digestBase_obj, instklass_digestBase, elem_type, stub_addr, stub_name, src_start, ofs, limit);
9200   }
9201   return false;
9202 }
9203 
9204 //------------------------------inline_digestBase_implCompressMB-----------------------
9205 bool LibraryCallKit::inline_digestBase_implCompressMB(Node* digestBase_obj, ciInstanceKlass* instklass_digestBase,
9206                                                       BasicType elem_type, address stubAddr, const char *stubName,
9207                                                       Node* src_start, Node* ofs, Node* limit) {
9208   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_digestBase);
9209   const TypeOopPtr* xtype = aklass->cast_to_exactness(false)->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
9210   Node* digest_obj = new CheckCastPPNode(control(), digestBase_obj, xtype);
9211   digest_obj = _gvn.transform(digest_obj);
9212 
9213   Node* state = get_state_from_digest_object(digest_obj, elem_type);
9214   if (state == nullptr) return false;
9215 
9216   Node* block_size = nullptr;
9217   if (strcmp("sha3_implCompressMB", stubName) == 0) {
9218     block_size = get_block_size_from_digest_object(digest_obj);
9219     if (block_size == nullptr) return false;
9220   }
9221 
9222   // Call the stub.
9223   Node* call;
9224   if (block_size == nullptr) {
9225     call = make_runtime_call(RC_LEAF|RC_NO_FP,
9226                              OptoRuntime::digestBase_implCompressMB_Type(false),
9227                              stubAddr, stubName, TypePtr::BOTTOM,
9228                              src_start, state, ofs, limit);
9229   } else {
9230      call = make_runtime_call(RC_LEAF|RC_NO_FP,
9231                              OptoRuntime::digestBase_implCompressMB_Type(true),
9232                              stubAddr, stubName, TypePtr::BOTTOM,
9233                              src_start, state, block_size, ofs, limit);
9234   }
9235 
9236   // return ofs (int)
9237   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
9238   set_result(result);
9239 
9240   return true;
9241 }
9242 
9243 //------------------------------inline_galoisCounterMode_AESCrypt-----------------------
9244 bool LibraryCallKit::inline_galoisCounterMode_AESCrypt() {
9245   assert(UseAES, "need AES instruction support");
9246   address stubAddr = nullptr;
9247   const char *stubName = nullptr;
9248   stubAddr = StubRoutines::galoisCounterMode_AESCrypt();
9249   stubName = "galoisCounterMode_AESCrypt";
9250 
9251   if (stubAddr == nullptr) return false;
9252 
9253   Node* in      = argument(0);
9254   Node* inOfs   = argument(1);
9255   Node* len     = argument(2);
9256   Node* ct      = argument(3);
9257   Node* ctOfs   = argument(4);
9258   Node* out     = argument(5);
9259   Node* outOfs  = argument(6);
9260   Node* gctr_object = argument(7);
9261   Node* ghash_object = argument(8);
9262 
9263   // (1) in, ct and out are arrays.
9264   const TypeAryPtr* in_type = in->Value(&_gvn)->isa_aryptr();
9265   const TypeAryPtr* ct_type = ct->Value(&_gvn)->isa_aryptr();
9266   const TypeAryPtr* out_type = out->Value(&_gvn)->isa_aryptr();
9267   assert( in_type != nullptr &&  in_type->elem() != Type::BOTTOM &&
9268           ct_type != nullptr &&  ct_type->elem() != Type::BOTTOM &&
9269          out_type != nullptr && out_type->elem() != Type::BOTTOM, "args are strange");
9270 
9271   // checks are the responsibility of the caller
9272   Node* in_start = in;
9273   Node* ct_start = ct;
9274   Node* out_start = out;
9275   if (inOfs != nullptr || ctOfs != nullptr || outOfs != nullptr) {
9276     assert(inOfs != nullptr && ctOfs != nullptr && outOfs != nullptr, "");
9277     in_start = array_element_address(in, inOfs, T_BYTE);
9278     ct_start = array_element_address(ct, ctOfs, T_BYTE);
9279     out_start = array_element_address(out, outOfs, T_BYTE);
9280   }
9281 
9282   // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
9283   // (because of the predicated logic executed earlier).
9284   // so we cast it here safely.
9285   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
9286   Node* embeddedCipherObj = load_field_from_object(gctr_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
9287   Node* counter = load_field_from_object(gctr_object, "counter", "[B");
9288   Node* subkeyHtbl = load_field_from_object(ghash_object, "subkeyHtbl", "[J");
9289   Node* state = load_field_from_object(ghash_object, "state", "[J");
9290 
9291   if (embeddedCipherObj == nullptr || counter == nullptr || subkeyHtbl == nullptr || state == nullptr) {
9292     return false;
9293   }
9294   // cast it to what we know it will be at runtime
9295   const TypeInstPtr* tinst = _gvn.type(gctr_object)->isa_instptr();
9296   assert(tinst != nullptr, "GCTR obj is null");
9297   assert(tinst->is_loaded(), "GCTR obj is not loaded");
9298   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
9299   assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
9300   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
9301   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
9302   const TypeOopPtr* xtype = aklass->as_instance_type();
9303   Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
9304   aescrypt_object = _gvn.transform(aescrypt_object);
9305   // we need to get the start of the aescrypt_object's expanded key array
9306   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object);
9307   if (k_start == nullptr) return false;
9308   // similarly, get the start address of the r vector
9309   Node* cnt_start = array_element_address(counter, intcon(0), T_BYTE);
9310   Node* state_start = array_element_address(state, intcon(0), T_LONG);
9311   Node* subkeyHtbl_start = array_element_address(subkeyHtbl, intcon(0), T_LONG);
9312 
9313 
9314   // Call the stub, passing params
9315   Node* gcmCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
9316                                OptoRuntime::galoisCounterMode_aescrypt_Type(),
9317                                stubAddr, stubName, TypePtr::BOTTOM,
9318                                in_start, len, ct_start, out_start, k_start, state_start, subkeyHtbl_start, cnt_start);
9319 
9320   // return cipher length (int)
9321   Node* retvalue = _gvn.transform(new ProjNode(gcmCrypt, TypeFunc::Parms));
9322   set_result(retvalue);
9323 
9324   return true;
9325 }
9326 
9327 //----------------------------inline_galoisCounterMode_AESCrypt_predicate----------------------------
9328 // Return node representing slow path of predicate check.
9329 // the pseudo code we want to emulate with this predicate is:
9330 // for encryption:
9331 //    if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
9332 // for decryption:
9333 //    if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
9334 //    note cipher==plain is more conservative than the original java code but that's OK
9335 //
9336 
9337 Node* LibraryCallKit::inline_galoisCounterMode_AESCrypt_predicate() {
9338   // The receiver was checked for null already.
9339   Node* objGCTR = argument(7);
9340   // Load embeddedCipher field of GCTR object.
9341   Node* embeddedCipherObj = load_field_from_object(objGCTR, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
9342   assert(embeddedCipherObj != nullptr, "embeddedCipherObj is null");
9343 
9344   // get AESCrypt klass for instanceOf check
9345   // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
9346   // will have same classloader as CipherBlockChaining object
9347   const TypeInstPtr* tinst = _gvn.type(objGCTR)->isa_instptr();
9348   assert(tinst != nullptr, "GCTR obj is null");
9349   assert(tinst->is_loaded(), "GCTR obj is not loaded");
9350 
9351   // we want to do an instanceof comparison against the AESCrypt class
9352   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
9353   if (!klass_AESCrypt->is_loaded()) {
9354     // if AESCrypt is not even loaded, we never take the intrinsic fast path
9355     Node* ctrl = control();
9356     set_control(top()); // no regular fast path
9357     return ctrl;
9358   }
9359 
9360   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
9361   Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
9362   Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
9363   Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
9364   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
9365 
9366   return instof_false; // even if it is null
9367 }
9368 
9369 //------------------------------get_state_from_digest_object-----------------------
9370 Node * LibraryCallKit::get_state_from_digest_object(Node *digest_object, BasicType elem_type) {
9371   const char* state_type;
9372   switch (elem_type) {
9373     case T_BYTE: state_type = "[B"; break;
9374     case T_INT:  state_type = "[I"; break;
9375     case T_LONG: state_type = "[J"; break;
9376     default: ShouldNotReachHere();
9377   }
9378   Node* digest_state = load_field_from_object(digest_object, "state", state_type);
9379   assert (digest_state != nullptr, "wrong version of sun.security.provider.MD5/SHA/SHA2/SHA5/SHA3");
9380   if (digest_state == nullptr) return (Node *) nullptr;
9381 
9382   // now have the array, need to get the start address of the state array
9383   Node* state = array_element_address(digest_state, intcon(0), elem_type);
9384   return state;
9385 }
9386 
9387 //------------------------------get_block_size_from_sha3_object----------------------------------
9388 Node * LibraryCallKit::get_block_size_from_digest_object(Node *digest_object) {
9389   Node* block_size = load_field_from_object(digest_object, "blockSize", "I");
9390   assert (block_size != nullptr, "sanity");
9391   return block_size;
9392 }
9393 
9394 //----------------------------inline_digestBase_implCompressMB_predicate----------------------------
9395 // Return node representing slow path of predicate check.
9396 // the pseudo code we want to emulate with this predicate is:
9397 //    if (digestBaseObj instanceof MD5/SHA/SHA2/SHA5/SHA3) do_intrinsic, else do_javapath
9398 //
9399 Node* LibraryCallKit::inline_digestBase_implCompressMB_predicate(int predicate) {
9400   assert(UseMD5Intrinsics || UseSHA1Intrinsics || UseSHA256Intrinsics || UseSHA512Intrinsics || UseSHA3Intrinsics,
9401          "need MD5/SHA1/SHA256/SHA512/SHA3 instruction support");
9402   assert((uint)predicate < 5, "sanity");
9403 
9404   // The receiver was checked for null already.
9405   Node* digestBaseObj = argument(0);
9406 
9407   // get DigestBase klass for instanceOf check
9408   const TypeInstPtr* tinst = _gvn.type(digestBaseObj)->isa_instptr();
9409   assert(tinst != nullptr, "digestBaseObj is null");
9410   assert(tinst->is_loaded(), "DigestBase is not loaded");
9411 
9412   const char* klass_name = nullptr;
9413   switch (predicate) {
9414   case 0:
9415     if (UseMD5Intrinsics) {
9416       // we want to do an instanceof comparison against the MD5 class
9417       klass_name = "sun/security/provider/MD5";
9418     }
9419     break;
9420   case 1:
9421     if (UseSHA1Intrinsics) {
9422       // we want to do an instanceof comparison against the SHA class
9423       klass_name = "sun/security/provider/SHA";
9424     }
9425     break;
9426   case 2:
9427     if (UseSHA256Intrinsics) {
9428       // we want to do an instanceof comparison against the SHA2 class
9429       klass_name = "sun/security/provider/SHA2";
9430     }
9431     break;
9432   case 3:
9433     if (UseSHA512Intrinsics) {
9434       // we want to do an instanceof comparison against the SHA5 class
9435       klass_name = "sun/security/provider/SHA5";
9436     }
9437     break;
9438   case 4:
9439     if (UseSHA3Intrinsics) {
9440       // we want to do an instanceof comparison against the SHA3 class
9441       klass_name = "sun/security/provider/SHA3";
9442     }
9443     break;
9444   default:
9445     fatal("unknown SHA intrinsic predicate: %d", predicate);
9446   }
9447 
9448   ciKlass* klass = nullptr;
9449   if (klass_name != nullptr) {
9450     klass = tinst->instance_klass()->find_klass(ciSymbol::make(klass_name));
9451   }
9452   if ((klass == nullptr) || !klass->is_loaded()) {
9453     // if none of MD5/SHA/SHA2/SHA5 is loaded, we never take the intrinsic fast path
9454     Node* ctrl = control();
9455     set_control(top()); // no intrinsic path
9456     return ctrl;
9457   }
9458   ciInstanceKlass* instklass = klass->as_instance_klass();
9459 
9460   Node* instof = gen_instanceof(digestBaseObj, makecon(TypeKlassPtr::make(instklass)));
9461   Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
9462   Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
9463   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
9464 
9465   return instof_false;  // even if it is null
9466 }
9467 
9468 //-------------inline_fma-----------------------------------
9469 bool LibraryCallKit::inline_fma(vmIntrinsics::ID id) {
9470   Node *a = nullptr;
9471   Node *b = nullptr;
9472   Node *c = nullptr;
9473   Node* result = nullptr;
9474   switch (id) {
9475   case vmIntrinsics::_fmaD:
9476     assert(callee()->signature()->size() == 6, "fma has 3 parameters of size 2 each.");
9477     // no receiver since it is static method
9478     a = argument(0);
9479     b = argument(2);
9480     c = argument(4);
9481     result = _gvn.transform(new FmaDNode(a, b, c));
9482     break;
9483   case vmIntrinsics::_fmaF:
9484     assert(callee()->signature()->size() == 3, "fma has 3 parameters of size 1 each.");
9485     a = argument(0);
9486     b = argument(1);
9487     c = argument(2);
9488     result = _gvn.transform(new FmaFNode(a, b, c));
9489     break;
9490   default:
9491     fatal_unexpected_iid(id);  break;
9492   }
9493   set_result(result);
9494   return true;
9495 }
9496 
9497 bool LibraryCallKit::inline_character_compare(vmIntrinsics::ID id) {
9498   // argument(0) is receiver
9499   Node* codePoint = argument(1);
9500   Node* n = nullptr;
9501 
9502   switch (id) {
9503     case vmIntrinsics::_isDigit :
9504       n = new DigitNode(control(), codePoint);
9505       break;
9506     case vmIntrinsics::_isLowerCase :
9507       n = new LowerCaseNode(control(), codePoint);
9508       break;
9509     case vmIntrinsics::_isUpperCase :
9510       n = new UpperCaseNode(control(), codePoint);
9511       break;
9512     case vmIntrinsics::_isWhitespace :
9513       n = new WhitespaceNode(control(), codePoint);
9514       break;
9515     default:
9516       fatal_unexpected_iid(id);
9517   }
9518 
9519   set_result(_gvn.transform(n));
9520   return true;
9521 }
9522 
9523 bool LibraryCallKit::inline_profileBoolean() {
9524   Node* counts = argument(1);
9525   const TypeAryPtr* ary = nullptr;
9526   ciArray* aobj = nullptr;
9527   if (counts->is_Con()
9528       && (ary = counts->bottom_type()->isa_aryptr()) != nullptr
9529       && (aobj = ary->const_oop()->as_array()) != nullptr
9530       && (aobj->length() == 2)) {
9531     // Profile is int[2] where [0] and [1] correspond to false and true value occurrences respectively.
9532     jint false_cnt = aobj->element_value(0).as_int();
9533     jint  true_cnt = aobj->element_value(1).as_int();
9534 
9535     if (C->log() != nullptr) {
9536       C->log()->elem("observe source='profileBoolean' false='%d' true='%d'",
9537                      false_cnt, true_cnt);
9538     }
9539 
9540     if (false_cnt + true_cnt == 0) {
9541       // According to profile, never executed.
9542       uncommon_trap_exact(Deoptimization::Reason_intrinsic,
9543                           Deoptimization::Action_reinterpret);
9544       return true;
9545     }
9546 
9547     // result is a boolean (0 or 1) and its profile (false_cnt & true_cnt)
9548     // is a number of each value occurrences.
9549     Node* result = argument(0);
9550     if (false_cnt == 0 || true_cnt == 0) {
9551       // According to profile, one value has been never seen.
9552       int expected_val = (false_cnt == 0) ? 1 : 0;
9553 
9554       Node* cmp  = _gvn.transform(new CmpINode(result, intcon(expected_val)));
9555       Node* test = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
9556 
9557       IfNode* check = create_and_map_if(control(), test, PROB_ALWAYS, COUNT_UNKNOWN);
9558       Node* fast_path = _gvn.transform(new IfTrueNode(check));
9559       Node* slow_path = _gvn.transform(new IfFalseNode(check));
9560 
9561       { // Slow path: uncommon trap for never seen value and then reexecute
9562         // MethodHandleImpl::profileBoolean() to bump the count, so JIT knows
9563         // the value has been seen at least once.
9564         PreserveJVMState pjvms(this);
9565         PreserveReexecuteState preexecs(this);
9566         jvms()->set_should_reexecute(true);
9567 
9568         set_control(slow_path);
9569         set_i_o(i_o());
9570 
9571         uncommon_trap_exact(Deoptimization::Reason_intrinsic,
9572                             Deoptimization::Action_reinterpret);
9573       }
9574       // The guard for never seen value enables sharpening of the result and
9575       // returning a constant. It allows to eliminate branches on the same value
9576       // later on.
9577       set_control(fast_path);
9578       result = intcon(expected_val);
9579     }
9580     // Stop profiling.
9581     // MethodHandleImpl::profileBoolean() has profiling logic in its bytecode.
9582     // By replacing method body with profile data (represented as ProfileBooleanNode
9583     // on IR level) we effectively disable profiling.
9584     // It enables full speed execution once optimized code is generated.
9585     Node* profile = _gvn.transform(new ProfileBooleanNode(result, false_cnt, true_cnt));
9586     C->record_for_igvn(profile);
9587     set_result(profile);
9588     return true;
9589   } else {
9590     // Continue profiling.
9591     // Profile data isn't available at the moment. So, execute method's bytecode version.
9592     // Usually, when GWT LambdaForms are profiled it means that a stand-alone nmethod
9593     // is compiled and counters aren't available since corresponding MethodHandle
9594     // isn't a compile-time constant.
9595     return false;
9596   }
9597 }
9598 
9599 bool LibraryCallKit::inline_isCompileConstant() {
9600   Node* n = argument(0);
9601   set_result(n->is_Con() ? intcon(1) : intcon(0));
9602   return true;
9603 }
9604 
9605 //------------------------------- inline_getObjectSize --------------------------------------
9606 //
9607 // Calculate the runtime size of the object/array.
9608 //   native long sun.instrument.InstrumentationImpl.getObjectSize0(long nativeAgent, Object objectToSize);
9609 //
9610 bool LibraryCallKit::inline_getObjectSize() {
9611   Node* obj = argument(3);
9612   Node* klass_node = load_object_klass(obj);
9613 
9614   jint  layout_con = Klass::_lh_neutral_value;
9615   Node* layout_val = get_layout_helper(klass_node, layout_con);
9616   int   layout_is_con = (layout_val == nullptr);
9617 
9618   if (layout_is_con) {
9619     // Layout helper is constant, can figure out things at compile time.
9620 
9621     if (Klass::layout_helper_is_instance(layout_con)) {
9622       // Instance case:  layout_con contains the size itself.
9623       Node *size = longcon(Klass::layout_helper_size_in_bytes(layout_con));
9624       set_result(size);
9625     } else {
9626       // Array case: size is round(header + element_size*arraylength).
9627       // Since arraylength is different for every array instance, we have to
9628       // compute the whole thing at runtime.
9629 
9630       Node* arr_length = load_array_length(obj);
9631 
9632       int round_mask = MinObjAlignmentInBytes - 1;
9633       int hsize  = Klass::layout_helper_header_size(layout_con);
9634       int eshift = Klass::layout_helper_log2_element_size(layout_con);
9635 
9636       if ((round_mask & ~right_n_bits(eshift)) == 0) {
9637         round_mask = 0;  // strength-reduce it if it goes away completely
9638       }
9639       assert((hsize & right_n_bits(eshift)) == 0, "hsize is pre-rounded");
9640       Node* header_size = intcon(hsize + round_mask);
9641 
9642       Node* lengthx = ConvI2X(arr_length);
9643       Node* headerx = ConvI2X(header_size);
9644 
9645       Node* abody = lengthx;
9646       if (eshift != 0) {
9647         abody = _gvn.transform(new LShiftXNode(lengthx, intcon(eshift)));
9648       }
9649       Node* size = _gvn.transform( new AddXNode(headerx, abody) );
9650       if (round_mask != 0) {
9651         size = _gvn.transform( new AndXNode(size, MakeConX(~round_mask)) );
9652       }
9653       size = ConvX2L(size);
9654       set_result(size);
9655     }
9656   } else {
9657     // Layout helper is not constant, need to test for array-ness at runtime.
9658 
9659     enum { _instance_path = 1, _array_path, PATH_LIMIT };
9660     RegionNode* result_reg = new RegionNode(PATH_LIMIT);
9661     PhiNode* result_val = new PhiNode(result_reg, TypeLong::LONG);
9662     record_for_igvn(result_reg);
9663 
9664     Node* array_ctl = generate_array_guard(klass_node, nullptr, &obj);
9665     if (array_ctl != nullptr) {
9666       // Array case: size is round(header + element_size*arraylength).
9667       // Since arraylength is different for every array instance, we have to
9668       // compute the whole thing at runtime.
9669 
9670       PreserveJVMState pjvms(this);
9671       set_control(array_ctl);
9672       Node* arr_length = load_array_length(obj);
9673 
9674       int round_mask = MinObjAlignmentInBytes - 1;
9675       Node* mask = intcon(round_mask);
9676 
9677       Node* hss = intcon(Klass::_lh_header_size_shift);
9678       Node* hsm = intcon(Klass::_lh_header_size_mask);
9679       Node* header_size = _gvn.transform(new URShiftINode(layout_val, hss));
9680       header_size = _gvn.transform(new AndINode(header_size, hsm));
9681       header_size = _gvn.transform(new AddINode(header_size, mask));
9682 
9683       // There is no need to mask or shift this value.
9684       // The semantics of LShiftINode include an implicit mask to 0x1F.
9685       assert(Klass::_lh_log2_element_size_shift == 0, "use shift in place");
9686       Node* elem_shift = layout_val;
9687 
9688       Node* lengthx = ConvI2X(arr_length);
9689       Node* headerx = ConvI2X(header_size);
9690 
9691       Node* abody = _gvn.transform(new LShiftXNode(lengthx, elem_shift));
9692       Node* size = _gvn.transform(new AddXNode(headerx, abody));
9693       if (round_mask != 0) {
9694         size = _gvn.transform(new AndXNode(size, MakeConX(~round_mask)));
9695       }
9696       size = ConvX2L(size);
9697 
9698       result_reg->init_req(_array_path, control());
9699       result_val->init_req(_array_path, size);
9700     }
9701 
9702     if (!stopped()) {
9703       // Instance case: the layout helper gives us instance size almost directly,
9704       // but we need to mask out the _lh_instance_slow_path_bit.
9705       Node* size = ConvI2X(layout_val);
9706       assert((int) Klass::_lh_instance_slow_path_bit < BytesPerLong, "clear bit");
9707       Node* mask = MakeConX(~(intptr_t) right_n_bits(LogBytesPerLong));
9708       size = _gvn.transform(new AndXNode(size, mask));
9709       size = ConvX2L(size);
9710 
9711       result_reg->init_req(_instance_path, control());
9712       result_val->init_req(_instance_path, size);
9713     }
9714 
9715     set_result(result_reg, result_val);
9716   }
9717 
9718   return true;
9719 }
9720 
9721 //------------------------------- inline_blackhole --------------------------------------
9722 //
9723 // Make sure all arguments to this node are alive.
9724 // This matches methods that were requested to be blackholed through compile commands.
9725 //
9726 bool LibraryCallKit::inline_blackhole() {
9727   assert(callee()->is_static(), "Should have been checked before: only static methods here");
9728   assert(callee()->is_empty(), "Should have been checked before: only empty methods here");
9729   assert(callee()->holder()->is_loaded(), "Should have been checked before: only methods for loaded classes here");
9730 
9731   // Blackhole node pinches only the control, not memory. This allows
9732   // the blackhole to be pinned in the loop that computes blackholed
9733   // values, but have no other side effects, like breaking the optimizations
9734   // across the blackhole.
9735 
9736   Node* bh = _gvn.transform(new BlackholeNode(control()));
9737   set_control(_gvn.transform(new ProjNode(bh, TypeFunc::Control)));
9738 
9739   // Bind call arguments as blackhole arguments to keep them alive
9740   uint nargs = callee()->arg_size();
9741   for (uint i = 0; i < nargs; i++) {
9742     bh->add_req(argument(i));
9743   }
9744 
9745   return true;
9746 }
9747 
9748 Node* LibraryCallKit::unbox_fp16_value(const TypeInstPtr* float16_box_type, ciField* field, Node* box) {
9749   const TypeInstPtr* box_type = _gvn.type(box)->isa_instptr();
9750   if (box_type == nullptr || box_type->instance_klass() != float16_box_type->instance_klass()) {
9751     return nullptr; // box klass is not Float16
9752   }
9753 
9754   // Null check; get notnull casted pointer
9755   Node* null_ctl = top();
9756   Node* not_null_box = null_check_oop(box, &null_ctl, true);
9757   // If not_null_box is dead, only null-path is taken
9758   if (stopped()) {
9759     set_control(null_ctl);
9760     return nullptr;
9761   }
9762   assert(not_null_box->bottom_type()->is_instptr()->maybe_null() == false, "");
9763   const TypePtr* adr_type = C->alias_type(field)->adr_type();
9764   Node* adr = basic_plus_adr(not_null_box, field->offset_in_bytes());
9765   return access_load_at(not_null_box, adr, adr_type, TypeInt::SHORT, T_SHORT, IN_HEAP);
9766 }
9767 
9768 Node* LibraryCallKit::box_fp16_value(const TypeInstPtr* float16_box_type, ciField* field, Node* value) {
9769   PreserveReexecuteState preexecs(this);
9770   jvms()->set_should_reexecute(true);
9771 
9772   const TypeKlassPtr* klass_type = float16_box_type->as_klass_type();
9773   Node* klass_node = makecon(klass_type);
9774   Node* box = new_instance(klass_node);
9775 
9776   Node* value_field = basic_plus_adr(box, field->offset_in_bytes());
9777   const TypePtr* value_adr_type = value_field->bottom_type()->is_ptr();
9778 
9779   Node* field_store = _gvn.transform(access_store_at(box,
9780                                                      value_field,
9781                                                      value_adr_type,
9782                                                      value,
9783                                                      TypeInt::SHORT,
9784                                                      T_SHORT,
9785                                                      IN_HEAP));
9786   set_memory(field_store, value_adr_type);
9787   return box;
9788 }
9789 
9790 bool LibraryCallKit::inline_fp16_operations(vmIntrinsics::ID id, int num_args) {
9791   if (!Matcher::match_rule_supported(Op_ReinterpretS2HF) ||
9792       !Matcher::match_rule_supported(Op_ReinterpretHF2S)) {
9793     return false;
9794   }
9795 
9796   const TypeInstPtr* box_type = _gvn.type(argument(0))->isa_instptr();
9797   if (box_type == nullptr || box_type->const_oop() == nullptr) {
9798     return false;
9799   }
9800 
9801   ciInstanceKlass* float16_klass = box_type->const_oop()->as_instance()->java_lang_Class_klass()->as_instance_klass();
9802   const TypeInstPtr* float16_box_type = TypeInstPtr::make_exact(TypePtr::NotNull, float16_klass);
9803   ciField* field = float16_klass->get_field_by_name(ciSymbols::value_name(),
9804                                                     ciSymbols::short_signature(),
9805                                                     false);
9806   assert(field != nullptr, "");
9807 
9808   // Transformed nodes
9809   Node* fld1 = nullptr;
9810   Node* fld2 = nullptr;
9811   Node* fld3 = nullptr;
9812   switch(num_args) {
9813     case 3:
9814       fld3 = unbox_fp16_value(float16_box_type, field, argument(3));
9815       if (fld3 == nullptr) {
9816         return false;
9817       }
9818       fld3 = _gvn.transform(new ReinterpretS2HFNode(fld3));
9819     // fall-through
9820     case 2:
9821       fld2 = unbox_fp16_value(float16_box_type, field, argument(2));
9822       if (fld2 == nullptr) {
9823         return false;
9824       }
9825       fld2 = _gvn.transform(new ReinterpretS2HFNode(fld2));
9826     // fall-through
9827     case 1:
9828       fld1 = unbox_fp16_value(float16_box_type, field, argument(1));
9829       if (fld1 == nullptr) {
9830         return false;
9831       }
9832       fld1 = _gvn.transform(new ReinterpretS2HFNode(fld1));
9833       break;
9834     default: fatal("Unsupported number of arguments %d", num_args);
9835   }
9836 
9837   Node* result = nullptr;
9838   switch (id) {
9839     // Unary operations
9840     case vmIntrinsics::_sqrt_float16:
9841       result = _gvn.transform(new SqrtHFNode(C, control(), fld1));
9842       break;
9843     // Ternary operations
9844     case vmIntrinsics::_fma_float16:
9845       result = _gvn.transform(new FmaHFNode(fld1, fld2, fld3));
9846       break;
9847     default:
9848       fatal_unexpected_iid(id);
9849       break;
9850   }
9851   result = _gvn.transform(new ReinterpretHF2SNode(result));
9852   set_result(box_fp16_value(float16_box_type, field, result));
9853   return true;
9854 }
9855