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