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