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