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