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