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