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