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