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/ciFlatArrayKlass.hpp"
  27 #include "ci/ciUtilities.inline.hpp"
  28 #include "ci/ciSymbols.hpp"
  29 #include "classfile/vmIntrinsics.hpp"
  30 #include "compiler/compileBroker.hpp"
  31 #include "compiler/compileLog.hpp"
  32 #include "gc/shared/barrierSet.hpp"
  33 #include "jfr/support/jfrIntrinsics.hpp"
  34 #include "memory/resourceArea.hpp"
  35 #include "oops/accessDecorators.hpp"
  36 #include "oops/klass.inline.hpp"
  37 #include "oops/objArrayKlass.hpp"
  38 #include "opto/addnode.hpp"
  39 #include "opto/arraycopynode.hpp"
  40 #include "opto/c2compiler.hpp"
  41 #include "opto/castnode.hpp"
  42 #include "opto/cfgnode.hpp"
  43 #include "opto/convertnode.hpp"
  44 #include "opto/countbitsnode.hpp"
  45 #include "opto/idealKit.hpp"
  46 #include "opto/library_call.hpp"
  47 #include "opto/mathexactnode.hpp"
  48 #include "opto/mulnode.hpp"
  49 #include "opto/narrowptrnode.hpp"
  50 #include "opto/opaquenode.hpp"
  51 #include "opto/parse.hpp"
  52 #include "opto/runtime.hpp"
  53 #include "opto/rootnode.hpp"
  54 #include "opto/subnode.hpp"
  55 #include "opto/vectornode.hpp"
  56 #include "prims/jvmtiExport.hpp"
  57 #include "prims/jvmtiThreadState.hpp"
  58 #include "prims/unsafe.hpp"
  59 #include "runtime/jniHandles.inline.hpp"
  60 #include "runtime/objectMonitor.hpp"
  61 #include "runtime/sharedRuntime.hpp"
  62 #include "runtime/stubRoutines.hpp"
  63 #include "utilities/macros.hpp"
  64 #include "utilities/powerOfTwo.hpp"
  65 
  66 //---------------------------make_vm_intrinsic----------------------------
  67 CallGenerator* Compile::make_vm_intrinsic(ciMethod* m, bool is_virtual) {
  68   vmIntrinsicID id = m->intrinsic_id();
  69   assert(id != vmIntrinsics::_none, "must be a VM intrinsic");
  70 
  71   if (!m->is_loaded()) {
  72     // Do not attempt to inline unloaded methods.
  73     return nullptr;
  74   }
  75 
  76   C2Compiler* compiler = (C2Compiler*)CompileBroker::compiler(CompLevel_full_optimization);
  77   bool is_available = false;
  78 
  79   {
  80     // For calling is_intrinsic_supported and is_intrinsic_disabled_by_flag
  81     // the compiler must transition to '_thread_in_vm' state because both
  82     // methods access VM-internal data.
  83     VM_ENTRY_MARK;
  84     methodHandle mh(THREAD, m->get_Method());
  85     is_available = compiler != nullptr && compiler->is_intrinsic_available(mh, C->directive());
  86     if (is_available && is_virtual) {
  87       is_available = vmIntrinsics::does_virtual_dispatch(id);
  88     }
  89   }
  90 
  91   if (is_available) {
  92     assert(id <= vmIntrinsics::LAST_COMPILER_INLINE, "caller responsibility");
  93     assert(id != vmIntrinsics::_Object_init && id != vmIntrinsics::_invoke, "enum out of order?");
  94     return new LibraryIntrinsic(m, is_virtual,
  95                                 vmIntrinsics::predicates_needed(id),
  96                                 vmIntrinsics::does_virtual_dispatch(id),
  97                                 id);
  98   } else {
  99     return nullptr;
 100   }
 101 }
 102 
 103 JVMState* LibraryIntrinsic::generate(JVMState* jvms) {
 104   LibraryCallKit kit(jvms, this);
 105   Compile* C = kit.C;
 106   int nodes = C->unique();
 107 #ifndef PRODUCT
 108   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
 109     char buf[1000];
 110     const char* str = vmIntrinsics::short_name_as_C_string(intrinsic_id(), buf, sizeof(buf));
 111     tty->print_cr("Intrinsic %s", str);
 112   }
 113 #endif
 114   ciMethod* callee = kit.callee();
 115   const int bci    = kit.bci();
 116 #ifdef ASSERT
 117   Node* ctrl = kit.control();
 118 #endif
 119   // Try to inline the intrinsic.
 120   if (callee->check_intrinsic_candidate() &&
 121       kit.try_to_inline(_last_predicate)) {
 122     const char *inline_msg = is_virtual() ? "(intrinsic, virtual)"
 123                                           : "(intrinsic)";
 124     CompileTask::print_inlining_ul(callee, jvms->depth() - 1, bci, InliningResult::SUCCESS, inline_msg);
 125     C->inline_printer()->record(callee, jvms, InliningResult::SUCCESS, inline_msg);
 126     C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_worked);
 127     if (C->log()) {
 128       C->log()->elem("intrinsic id='%s'%s nodes='%d'",
 129                      vmIntrinsics::name_at(intrinsic_id()),
 130                      (is_virtual() ? " virtual='1'" : ""),
 131                      C->unique() - nodes);
 132     }
 133     // Push the result from the inlined method onto the stack.
 134     kit.push_result();
 135     return kit.transfer_exceptions_into_jvms();
 136   }
 137 
 138   // The intrinsic bailed out
 139   assert(ctrl == kit.control(), "Control flow was added although the intrinsic bailed out");
 140   if (jvms->has_method()) {
 141     // Not a root compile.
 142     const char* msg;
 143     if (callee->intrinsic_candidate()) {
 144       msg = is_virtual() ? "failed to inline (intrinsic, virtual)" : "failed to inline (intrinsic)";
 145     } else {
 146       msg = is_virtual() ? "failed to inline (intrinsic, virtual), method not annotated"
 147                          : "failed to inline (intrinsic), method not annotated";
 148     }
 149     CompileTask::print_inlining_ul(callee, jvms->depth() - 1, bci, InliningResult::FAILURE, msg);
 150     C->inline_printer()->record(callee, jvms, InliningResult::FAILURE, msg);
 151   } else {
 152     // Root compile
 153     ResourceMark rm;
 154     stringStream msg_stream;
 155     msg_stream.print("Did not generate intrinsic %s%s at bci:%d in",
 156                      vmIntrinsics::name_at(intrinsic_id()),
 157                      is_virtual() ? " (virtual)" : "", bci);
 158     const char *msg = msg_stream.freeze();
 159     log_debug(jit, inlining)("%s", msg);
 160     if (C->print_intrinsics() || C->print_inlining()) {
 161       tty->print("%s", msg);
 162     }
 163   }
 164   C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_failed);
 165 
 166   return nullptr;
 167 }
 168 
 169 Node* LibraryIntrinsic::generate_predicate(JVMState* jvms, int predicate) {
 170   LibraryCallKit kit(jvms, this);
 171   Compile* C = kit.C;
 172   int nodes = C->unique();
 173   _last_predicate = predicate;
 174 #ifndef PRODUCT
 175   assert(is_predicated() && predicate < predicates_count(), "sanity");
 176   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
 177     char buf[1000];
 178     const char* str = vmIntrinsics::short_name_as_C_string(intrinsic_id(), buf, sizeof(buf));
 179     tty->print_cr("Predicate for intrinsic %s", str);
 180   }
 181 #endif
 182   ciMethod* callee = kit.callee();
 183   const int bci    = kit.bci();
 184 
 185   Node* slow_ctl = kit.try_to_predicate(predicate);
 186   if (!kit.failing()) {
 187     const char *inline_msg = is_virtual() ? "(intrinsic, virtual, predicate)"
 188                                           : "(intrinsic, predicate)";
 189     CompileTask::print_inlining_ul(callee, jvms->depth() - 1, bci, InliningResult::SUCCESS, inline_msg);
 190     C->inline_printer()->record(callee, jvms, InliningResult::SUCCESS, inline_msg);
 191 
 192     C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_worked);
 193     if (C->log()) {
 194       C->log()->elem("predicate_intrinsic id='%s'%s nodes='%d'",
 195                      vmIntrinsics::name_at(intrinsic_id()),
 196                      (is_virtual() ? " virtual='1'" : ""),
 197                      C->unique() - nodes);
 198     }
 199     return slow_ctl; // Could be null if the check folds.
 200   }
 201 
 202   // The intrinsic bailed out
 203   if (jvms->has_method()) {
 204     // Not a root compile.
 205     const char* msg = "failed to generate predicate for intrinsic";
 206     CompileTask::print_inlining_ul(kit.callee(), jvms->depth() - 1, bci, InliningResult::FAILURE, msg);
 207     C->inline_printer()->record(kit.callee(), jvms, InliningResult::FAILURE, msg);
 208   } else {
 209     // Root compile
 210     ResourceMark rm;
 211     stringStream msg_stream;
 212     msg_stream.print("Did not generate intrinsic %s%s at bci:%d in",
 213                      vmIntrinsics::name_at(intrinsic_id()),
 214                      is_virtual() ? " (virtual)" : "", bci);
 215     const char *msg = msg_stream.freeze();
 216     log_debug(jit, inlining)("%s", msg);
 217     C->inline_printer()->record(kit.callee(), jvms, InliningResult::FAILURE, msg);
 218   }
 219   C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_failed);
 220   return nullptr;
 221 }
 222 
 223 bool LibraryCallKit::try_to_inline(int predicate) {
 224   // Handle symbolic names for otherwise undistinguished boolean switches:
 225   const bool is_store       = true;
 226   const bool is_compress    = true;
 227   const bool is_static      = true;
 228   const bool is_volatile    = true;
 229 
 230   if (!jvms()->has_method()) {
 231     // Root JVMState has a null method.
 232     assert(map()->memory()->Opcode() == Op_Parm, "");
 233     // Insert the memory aliasing node
 234     set_all_memory(reset_memory());
 235   }
 236   assert(merged_memory(), "");
 237 
 238   switch (intrinsic_id()) {
 239   case vmIntrinsics::_hashCode:                 return inline_native_hashcode(intrinsic()->is_virtual(), !is_static);
 240   case vmIntrinsics::_identityHashCode:         return inline_native_hashcode(/*!virtual*/ false,         is_static);
 241   case vmIntrinsics::_getClass:                 return inline_native_getClass();
 242 
 243   case vmIntrinsics::_ceil:
 244   case vmIntrinsics::_floor:
 245   case vmIntrinsics::_rint:
 246   case vmIntrinsics::_dsin:
 247   case vmIntrinsics::_dcos:
 248   case vmIntrinsics::_dtan:
 249   case vmIntrinsics::_dtanh:
 250   case vmIntrinsics::_dabs:
 251   case vmIntrinsics::_fabs:
 252   case vmIntrinsics::_iabs:
 253   case vmIntrinsics::_labs:
 254   case vmIntrinsics::_datan2:
 255   case vmIntrinsics::_dsqrt:
 256   case vmIntrinsics::_dsqrt_strict:
 257   case vmIntrinsics::_dexp:
 258   case vmIntrinsics::_dlog:
 259   case vmIntrinsics::_dlog10:
 260   case vmIntrinsics::_dpow:
 261   case vmIntrinsics::_dcopySign:
 262   case vmIntrinsics::_fcopySign:
 263   case vmIntrinsics::_dsignum:
 264   case vmIntrinsics::_roundF:
 265   case vmIntrinsics::_roundD:
 266   case vmIntrinsics::_fsignum:                  return inline_math_native(intrinsic_id());
 267 
 268   case vmIntrinsics::_notify:
 269   case vmIntrinsics::_notifyAll:
 270     return inline_notify(intrinsic_id());
 271 
 272   case vmIntrinsics::_addExactI:                return inline_math_addExactI(false /* add */);
 273   case vmIntrinsics::_addExactL:                return inline_math_addExactL(false /* add */);
 274   case vmIntrinsics::_decrementExactI:          return inline_math_subtractExactI(true /* decrement */);
 275   case vmIntrinsics::_decrementExactL:          return inline_math_subtractExactL(true /* decrement */);
 276   case vmIntrinsics::_incrementExactI:          return inline_math_addExactI(true /* increment */);
 277   case vmIntrinsics::_incrementExactL:          return inline_math_addExactL(true /* increment */);
 278   case vmIntrinsics::_multiplyExactI:           return inline_math_multiplyExactI();
 279   case vmIntrinsics::_multiplyExactL:           return inline_math_multiplyExactL();
 280   case vmIntrinsics::_multiplyHigh:             return inline_math_multiplyHigh();
 281   case vmIntrinsics::_unsignedMultiplyHigh:     return inline_math_unsignedMultiplyHigh();
 282   case vmIntrinsics::_negateExactI:             return inline_math_negateExactI();
 283   case vmIntrinsics::_negateExactL:             return inline_math_negateExactL();
 284   case vmIntrinsics::_subtractExactI:           return inline_math_subtractExactI(false /* subtract */);
 285   case vmIntrinsics::_subtractExactL:           return inline_math_subtractExactL(false /* subtract */);
 286 
 287   case vmIntrinsics::_arraycopy:                return inline_arraycopy();
 288 
 289   case vmIntrinsics::_arraySort:                return inline_array_sort();
 290   case vmIntrinsics::_arrayPartition:           return inline_array_partition();
 291 
 292   case vmIntrinsics::_compareToL:               return inline_string_compareTo(StrIntrinsicNode::LL);
 293   case vmIntrinsics::_compareToU:               return inline_string_compareTo(StrIntrinsicNode::UU);
 294   case vmIntrinsics::_compareToLU:              return inline_string_compareTo(StrIntrinsicNode::LU);
 295   case vmIntrinsics::_compareToUL:              return inline_string_compareTo(StrIntrinsicNode::UL);
 296 
 297   case vmIntrinsics::_indexOfL:                 return inline_string_indexOf(StrIntrinsicNode::LL);
 298   case vmIntrinsics::_indexOfU:                 return inline_string_indexOf(StrIntrinsicNode::UU);
 299   case vmIntrinsics::_indexOfUL:                return inline_string_indexOf(StrIntrinsicNode::UL);
 300   case vmIntrinsics::_indexOfIL:                return inline_string_indexOfI(StrIntrinsicNode::LL);
 301   case vmIntrinsics::_indexOfIU:                return inline_string_indexOfI(StrIntrinsicNode::UU);
 302   case vmIntrinsics::_indexOfIUL:               return inline_string_indexOfI(StrIntrinsicNode::UL);
 303   case vmIntrinsics::_indexOfU_char:            return inline_string_indexOfChar(StrIntrinsicNode::U);
 304   case vmIntrinsics::_indexOfL_char:            return inline_string_indexOfChar(StrIntrinsicNode::L);
 305 
 306   case vmIntrinsics::_equalsL:                  return inline_string_equals(StrIntrinsicNode::LL);
 307 
 308   case vmIntrinsics::_vectorizedHashCode:       return inline_vectorizedHashCode();
 309 
 310   case vmIntrinsics::_toBytesStringU:           return inline_string_toBytesU();
 311   case vmIntrinsics::_getCharsStringU:          return inline_string_getCharsU();
 312   case vmIntrinsics::_getCharStringU:           return inline_string_char_access(!is_store);
 313   case vmIntrinsics::_putCharStringU:           return inline_string_char_access( is_store);
 314 
 315   case vmIntrinsics::_compressStringC:
 316   case vmIntrinsics::_compressStringB:          return inline_string_copy( is_compress);
 317   case vmIntrinsics::_inflateStringC:
 318   case vmIntrinsics::_inflateStringB:           return inline_string_copy(!is_compress);
 319 
 320   case vmIntrinsics::_makePrivateBuffer:        return inline_unsafe_make_private_buffer();
 321   case vmIntrinsics::_finishPrivateBuffer:      return inline_unsafe_finish_private_buffer();
 322   case vmIntrinsics::_getReference:             return inline_unsafe_access(!is_store, T_OBJECT,   Relaxed, false);
 323   case vmIntrinsics::_getBoolean:               return inline_unsafe_access(!is_store, T_BOOLEAN,  Relaxed, false);
 324   case vmIntrinsics::_getByte:                  return inline_unsafe_access(!is_store, T_BYTE,     Relaxed, false);
 325   case vmIntrinsics::_getShort:                 return inline_unsafe_access(!is_store, T_SHORT,    Relaxed, false);
 326   case vmIntrinsics::_getChar:                  return inline_unsafe_access(!is_store, T_CHAR,     Relaxed, false);
 327   case vmIntrinsics::_getInt:                   return inline_unsafe_access(!is_store, T_INT,      Relaxed, false);
 328   case vmIntrinsics::_getLong:                  return inline_unsafe_access(!is_store, T_LONG,     Relaxed, false);
 329   case vmIntrinsics::_getFloat:                 return inline_unsafe_access(!is_store, T_FLOAT,    Relaxed, false);
 330   case vmIntrinsics::_getDouble:                return inline_unsafe_access(!is_store, T_DOUBLE,   Relaxed, false);
 331   case vmIntrinsics::_getValue:                 return inline_unsafe_access(!is_store, T_OBJECT,   Relaxed, false, true);
 332 
 333   case vmIntrinsics::_putReference:             return inline_unsafe_access( is_store, T_OBJECT,   Relaxed, false);
 334   case vmIntrinsics::_putBoolean:               return inline_unsafe_access( is_store, T_BOOLEAN,  Relaxed, false);
 335   case vmIntrinsics::_putByte:                  return inline_unsafe_access( is_store, T_BYTE,     Relaxed, false);
 336   case vmIntrinsics::_putShort:                 return inline_unsafe_access( is_store, T_SHORT,    Relaxed, false);
 337   case vmIntrinsics::_putChar:                  return inline_unsafe_access( is_store, T_CHAR,     Relaxed, false);
 338   case vmIntrinsics::_putInt:                   return inline_unsafe_access( is_store, T_INT,      Relaxed, false);
 339   case vmIntrinsics::_putLong:                  return inline_unsafe_access( is_store, T_LONG,     Relaxed, false);
 340   case vmIntrinsics::_putFloat:                 return inline_unsafe_access( is_store, T_FLOAT,    Relaxed, false);
 341   case vmIntrinsics::_putDouble:                return inline_unsafe_access( is_store, T_DOUBLE,   Relaxed, false);
 342   case vmIntrinsics::_putValue:                 return inline_unsafe_access( is_store, T_OBJECT,   Relaxed, false, true);
 343 
 344   case vmIntrinsics::_getReferenceVolatile:     return inline_unsafe_access(!is_store, T_OBJECT,   Volatile, false);
 345   case vmIntrinsics::_getBooleanVolatile:       return inline_unsafe_access(!is_store, T_BOOLEAN,  Volatile, false);
 346   case vmIntrinsics::_getByteVolatile:          return inline_unsafe_access(!is_store, T_BYTE,     Volatile, false);
 347   case vmIntrinsics::_getShortVolatile:         return inline_unsafe_access(!is_store, T_SHORT,    Volatile, false);
 348   case vmIntrinsics::_getCharVolatile:          return inline_unsafe_access(!is_store, T_CHAR,     Volatile, false);
 349   case vmIntrinsics::_getIntVolatile:           return inline_unsafe_access(!is_store, T_INT,      Volatile, false);
 350   case vmIntrinsics::_getLongVolatile:          return inline_unsafe_access(!is_store, T_LONG,     Volatile, false);
 351   case vmIntrinsics::_getFloatVolatile:         return inline_unsafe_access(!is_store, T_FLOAT,    Volatile, false);
 352   case vmIntrinsics::_getDoubleVolatile:        return inline_unsafe_access(!is_store, T_DOUBLE,   Volatile, false);
 353 
 354   case vmIntrinsics::_putReferenceVolatile:     return inline_unsafe_access( is_store, T_OBJECT,   Volatile, false);
 355   case vmIntrinsics::_putBooleanVolatile:       return inline_unsafe_access( is_store, T_BOOLEAN,  Volatile, false);
 356   case vmIntrinsics::_putByteVolatile:          return inline_unsafe_access( is_store, T_BYTE,     Volatile, false);
 357   case vmIntrinsics::_putShortVolatile:         return inline_unsafe_access( is_store, T_SHORT,    Volatile, false);
 358   case vmIntrinsics::_putCharVolatile:          return inline_unsafe_access( is_store, T_CHAR,     Volatile, false);
 359   case vmIntrinsics::_putIntVolatile:           return inline_unsafe_access( is_store, T_INT,      Volatile, false);
 360   case vmIntrinsics::_putLongVolatile:          return inline_unsafe_access( is_store, T_LONG,     Volatile, false);
 361   case vmIntrinsics::_putFloatVolatile:         return inline_unsafe_access( is_store, T_FLOAT,    Volatile, false);
 362   case vmIntrinsics::_putDoubleVolatile:        return inline_unsafe_access( is_store, T_DOUBLE,   Volatile, false);
 363 
 364   case vmIntrinsics::_getShortUnaligned:        return inline_unsafe_access(!is_store, T_SHORT,    Relaxed, true);
 365   case vmIntrinsics::_getCharUnaligned:         return inline_unsafe_access(!is_store, T_CHAR,     Relaxed, true);
 366   case vmIntrinsics::_getIntUnaligned:          return inline_unsafe_access(!is_store, T_INT,      Relaxed, true);
 367   case vmIntrinsics::_getLongUnaligned:         return inline_unsafe_access(!is_store, T_LONG,     Relaxed, true);
 368 
 369   case vmIntrinsics::_putShortUnaligned:        return inline_unsafe_access( is_store, T_SHORT,    Relaxed, true);
 370   case vmIntrinsics::_putCharUnaligned:         return inline_unsafe_access( is_store, T_CHAR,     Relaxed, true);
 371   case vmIntrinsics::_putIntUnaligned:          return inline_unsafe_access( is_store, T_INT,      Relaxed, true);
 372   case vmIntrinsics::_putLongUnaligned:         return inline_unsafe_access( is_store, T_LONG,     Relaxed, true);
 373 
 374   case vmIntrinsics::_getReferenceAcquire:      return inline_unsafe_access(!is_store, T_OBJECT,   Acquire, false);
 375   case vmIntrinsics::_getBooleanAcquire:        return inline_unsafe_access(!is_store, T_BOOLEAN,  Acquire, false);
 376   case vmIntrinsics::_getByteAcquire:           return inline_unsafe_access(!is_store, T_BYTE,     Acquire, false);
 377   case vmIntrinsics::_getShortAcquire:          return inline_unsafe_access(!is_store, T_SHORT,    Acquire, false);
 378   case vmIntrinsics::_getCharAcquire:           return inline_unsafe_access(!is_store, T_CHAR,     Acquire, false);
 379   case vmIntrinsics::_getIntAcquire:            return inline_unsafe_access(!is_store, T_INT,      Acquire, false);
 380   case vmIntrinsics::_getLongAcquire:           return inline_unsafe_access(!is_store, T_LONG,     Acquire, false);
 381   case vmIntrinsics::_getFloatAcquire:          return inline_unsafe_access(!is_store, T_FLOAT,    Acquire, false);
 382   case vmIntrinsics::_getDoubleAcquire:         return inline_unsafe_access(!is_store, T_DOUBLE,   Acquire, false);
 383 
 384   case vmIntrinsics::_putReferenceRelease:      return inline_unsafe_access( is_store, T_OBJECT,   Release, false);
 385   case vmIntrinsics::_putBooleanRelease:        return inline_unsafe_access( is_store, T_BOOLEAN,  Release, false);
 386   case vmIntrinsics::_putByteRelease:           return inline_unsafe_access( is_store, T_BYTE,     Release, false);
 387   case vmIntrinsics::_putShortRelease:          return inline_unsafe_access( is_store, T_SHORT,    Release, false);
 388   case vmIntrinsics::_putCharRelease:           return inline_unsafe_access( is_store, T_CHAR,     Release, false);
 389   case vmIntrinsics::_putIntRelease:            return inline_unsafe_access( is_store, T_INT,      Release, false);
 390   case vmIntrinsics::_putLongRelease:           return inline_unsafe_access( is_store, T_LONG,     Release, false);
 391   case vmIntrinsics::_putFloatRelease:          return inline_unsafe_access( is_store, T_FLOAT,    Release, false);
 392   case vmIntrinsics::_putDoubleRelease:         return inline_unsafe_access( is_store, T_DOUBLE,   Release, false);
 393 
 394   case vmIntrinsics::_getReferenceOpaque:       return inline_unsafe_access(!is_store, T_OBJECT,   Opaque, false);
 395   case vmIntrinsics::_getBooleanOpaque:         return inline_unsafe_access(!is_store, T_BOOLEAN,  Opaque, false);
 396   case vmIntrinsics::_getByteOpaque:            return inline_unsafe_access(!is_store, T_BYTE,     Opaque, false);
 397   case vmIntrinsics::_getShortOpaque:           return inline_unsafe_access(!is_store, T_SHORT,    Opaque, false);
 398   case vmIntrinsics::_getCharOpaque:            return inline_unsafe_access(!is_store, T_CHAR,     Opaque, false);
 399   case vmIntrinsics::_getIntOpaque:             return inline_unsafe_access(!is_store, T_INT,      Opaque, false);
 400   case vmIntrinsics::_getLongOpaque:            return inline_unsafe_access(!is_store, T_LONG,     Opaque, false);
 401   case vmIntrinsics::_getFloatOpaque:           return inline_unsafe_access(!is_store, T_FLOAT,    Opaque, false);
 402   case vmIntrinsics::_getDoubleOpaque:          return inline_unsafe_access(!is_store, T_DOUBLE,   Opaque, false);
 403 
 404   case vmIntrinsics::_putReferenceOpaque:       return inline_unsafe_access( is_store, T_OBJECT,   Opaque, false);
 405   case vmIntrinsics::_putBooleanOpaque:         return inline_unsafe_access( is_store, T_BOOLEAN,  Opaque, false);
 406   case vmIntrinsics::_putByteOpaque:            return inline_unsafe_access( is_store, T_BYTE,     Opaque, false);
 407   case vmIntrinsics::_putShortOpaque:           return inline_unsafe_access( is_store, T_SHORT,    Opaque, false);
 408   case vmIntrinsics::_putCharOpaque:            return inline_unsafe_access( is_store, T_CHAR,     Opaque, false);
 409   case vmIntrinsics::_putIntOpaque:             return inline_unsafe_access( is_store, T_INT,      Opaque, false);
 410   case vmIntrinsics::_putLongOpaque:            return inline_unsafe_access( is_store, T_LONG,     Opaque, false);
 411   case vmIntrinsics::_putFloatOpaque:           return inline_unsafe_access( is_store, T_FLOAT,    Opaque, false);
 412   case vmIntrinsics::_putDoubleOpaque:          return inline_unsafe_access( is_store, T_DOUBLE,   Opaque, false);
 413 
 414   case vmIntrinsics::_compareAndSetReference:   return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap,      Volatile);
 415   case vmIntrinsics::_compareAndSetByte:        return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap,      Volatile);
 416   case vmIntrinsics::_compareAndSetShort:       return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap,      Volatile);
 417   case vmIntrinsics::_compareAndSetInt:         return inline_unsafe_load_store(T_INT,    LS_cmp_swap,      Volatile);
 418   case vmIntrinsics::_compareAndSetLong:        return inline_unsafe_load_store(T_LONG,   LS_cmp_swap,      Volatile);
 419 
 420   case vmIntrinsics::_weakCompareAndSetReferencePlain:     return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Relaxed);
 421   case vmIntrinsics::_weakCompareAndSetReferenceAcquire:   return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Acquire);
 422   case vmIntrinsics::_weakCompareAndSetReferenceRelease:   return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Release);
 423   case vmIntrinsics::_weakCompareAndSetReference:          return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Volatile);
 424   case vmIntrinsics::_weakCompareAndSetBytePlain:          return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap_weak, Relaxed);
 425   case vmIntrinsics::_weakCompareAndSetByteAcquire:        return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap_weak, Acquire);
 426   case vmIntrinsics::_weakCompareAndSetByteRelease:        return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap_weak, Release);
 427   case vmIntrinsics::_weakCompareAndSetByte:               return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap_weak, Volatile);
 428   case vmIntrinsics::_weakCompareAndSetShortPlain:         return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap_weak, Relaxed);
 429   case vmIntrinsics::_weakCompareAndSetShortAcquire:       return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap_weak, Acquire);
 430   case vmIntrinsics::_weakCompareAndSetShortRelease:       return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap_weak, Release);
 431   case vmIntrinsics::_weakCompareAndSetShort:              return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap_weak, Volatile);
 432   case vmIntrinsics::_weakCompareAndSetIntPlain:           return inline_unsafe_load_store(T_INT,    LS_cmp_swap_weak, Relaxed);
 433   case vmIntrinsics::_weakCompareAndSetIntAcquire:         return inline_unsafe_load_store(T_INT,    LS_cmp_swap_weak, Acquire);
 434   case vmIntrinsics::_weakCompareAndSetIntRelease:         return inline_unsafe_load_store(T_INT,    LS_cmp_swap_weak, Release);
 435   case vmIntrinsics::_weakCompareAndSetInt:                return inline_unsafe_load_store(T_INT,    LS_cmp_swap_weak, Volatile);
 436   case vmIntrinsics::_weakCompareAndSetLongPlain:          return inline_unsafe_load_store(T_LONG,   LS_cmp_swap_weak, Relaxed);
 437   case vmIntrinsics::_weakCompareAndSetLongAcquire:        return inline_unsafe_load_store(T_LONG,   LS_cmp_swap_weak, Acquire);
 438   case vmIntrinsics::_weakCompareAndSetLongRelease:        return inline_unsafe_load_store(T_LONG,   LS_cmp_swap_weak, Release);
 439   case vmIntrinsics::_weakCompareAndSetLong:               return inline_unsafe_load_store(T_LONG,   LS_cmp_swap_weak, Volatile);
 440 
 441   case vmIntrinsics::_compareAndExchangeReference:         return inline_unsafe_load_store(T_OBJECT, LS_cmp_exchange,  Volatile);
 442   case vmIntrinsics::_compareAndExchangeReferenceAcquire:  return inline_unsafe_load_store(T_OBJECT, LS_cmp_exchange,  Acquire);
 443   case vmIntrinsics::_compareAndExchangeReferenceRelease:  return inline_unsafe_load_store(T_OBJECT, LS_cmp_exchange,  Release);
 444   case vmIntrinsics::_compareAndExchangeByte:              return inline_unsafe_load_store(T_BYTE,   LS_cmp_exchange,  Volatile);
 445   case vmIntrinsics::_compareAndExchangeByteAcquire:       return inline_unsafe_load_store(T_BYTE,   LS_cmp_exchange,  Acquire);
 446   case vmIntrinsics::_compareAndExchangeByteRelease:       return inline_unsafe_load_store(T_BYTE,   LS_cmp_exchange,  Release);
 447   case vmIntrinsics::_compareAndExchangeShort:             return inline_unsafe_load_store(T_SHORT,  LS_cmp_exchange,  Volatile);
 448   case vmIntrinsics::_compareAndExchangeShortAcquire:      return inline_unsafe_load_store(T_SHORT,  LS_cmp_exchange,  Acquire);
 449   case vmIntrinsics::_compareAndExchangeShortRelease:      return inline_unsafe_load_store(T_SHORT,  LS_cmp_exchange,  Release);
 450   case vmIntrinsics::_compareAndExchangeInt:               return inline_unsafe_load_store(T_INT,    LS_cmp_exchange,  Volatile);
 451   case vmIntrinsics::_compareAndExchangeIntAcquire:        return inline_unsafe_load_store(T_INT,    LS_cmp_exchange,  Acquire);
 452   case vmIntrinsics::_compareAndExchangeIntRelease:        return inline_unsafe_load_store(T_INT,    LS_cmp_exchange,  Release);
 453   case vmIntrinsics::_compareAndExchangeLong:              return inline_unsafe_load_store(T_LONG,   LS_cmp_exchange,  Volatile);
 454   case vmIntrinsics::_compareAndExchangeLongAcquire:       return inline_unsafe_load_store(T_LONG,   LS_cmp_exchange,  Acquire);
 455   case vmIntrinsics::_compareAndExchangeLongRelease:       return inline_unsafe_load_store(T_LONG,   LS_cmp_exchange,  Release);
 456 
 457   case vmIntrinsics::_getAndAddByte:                    return inline_unsafe_load_store(T_BYTE,   LS_get_add,       Volatile);
 458   case vmIntrinsics::_getAndAddShort:                   return inline_unsafe_load_store(T_SHORT,  LS_get_add,       Volatile);
 459   case vmIntrinsics::_getAndAddInt:                     return inline_unsafe_load_store(T_INT,    LS_get_add,       Volatile);
 460   case vmIntrinsics::_getAndAddLong:                    return inline_unsafe_load_store(T_LONG,   LS_get_add,       Volatile);
 461 
 462   case vmIntrinsics::_getAndSetByte:                    return inline_unsafe_load_store(T_BYTE,   LS_get_set,       Volatile);
 463   case vmIntrinsics::_getAndSetShort:                   return inline_unsafe_load_store(T_SHORT,  LS_get_set,       Volatile);
 464   case vmIntrinsics::_getAndSetInt:                     return inline_unsafe_load_store(T_INT,    LS_get_set,       Volatile);
 465   case vmIntrinsics::_getAndSetLong:                    return inline_unsafe_load_store(T_LONG,   LS_get_set,       Volatile);
 466   case vmIntrinsics::_getAndSetReference:               return inline_unsafe_load_store(T_OBJECT, LS_get_set,       Volatile);
 467 
 468   case vmIntrinsics::_loadFence:
 469   case vmIntrinsics::_storeFence:
 470   case vmIntrinsics::_storeStoreFence:
 471   case vmIntrinsics::_fullFence:                return inline_unsafe_fence(intrinsic_id());
 472 
 473   case vmIntrinsics::_onSpinWait:               return inline_onspinwait();
 474 
 475   case vmIntrinsics::_currentCarrierThread:     return inline_native_currentCarrierThread();
 476   case vmIntrinsics::_currentThread:            return inline_native_currentThread();
 477   case vmIntrinsics::_setCurrentThread:         return inline_native_setCurrentThread();
 478 
 479   case vmIntrinsics::_scopedValueCache:          return inline_native_scopedValueCache();
 480   case vmIntrinsics::_setScopedValueCache:       return inline_native_setScopedValueCache();
 481 
 482   case vmIntrinsics::_Continuation_pin:          return inline_native_Continuation_pinning(false);
 483   case vmIntrinsics::_Continuation_unpin:        return inline_native_Continuation_pinning(true);
 484 
 485 #if INCLUDE_JVMTI
 486   case vmIntrinsics::_notifyJvmtiVThreadStart:   return inline_native_notify_jvmti_funcs(CAST_FROM_FN_PTR(address, OptoRuntime::notify_jvmti_vthread_start()),
 487                                                                                          "notifyJvmtiStart", true, false);
 488   case vmIntrinsics::_notifyJvmtiVThreadEnd:     return inline_native_notify_jvmti_funcs(CAST_FROM_FN_PTR(address, OptoRuntime::notify_jvmti_vthread_end()),
 489                                                                                          "notifyJvmtiEnd", false, true);
 490   case vmIntrinsics::_notifyJvmtiVThreadMount:   return inline_native_notify_jvmti_funcs(CAST_FROM_FN_PTR(address, OptoRuntime::notify_jvmti_vthread_mount()),
 491                                                                                          "notifyJvmtiMount", false, false);
 492   case vmIntrinsics::_notifyJvmtiVThreadUnmount: return inline_native_notify_jvmti_funcs(CAST_FROM_FN_PTR(address, OptoRuntime::notify_jvmti_vthread_unmount()),
 493                                                                                          "notifyJvmtiUnmount", false, false);
 494   case vmIntrinsics::_notifyJvmtiVThreadDisableSuspend: return inline_native_notify_jvmti_sync();
 495 #endif
 496 
 497 #ifdef JFR_HAVE_INTRINSICS
 498   case vmIntrinsics::_counterTime:              return inline_native_time_funcs(CAST_FROM_FN_PTR(address, JfrTime::time_function()), "counterTime");
 499   case vmIntrinsics::_getEventWriter:           return inline_native_getEventWriter();
 500   case vmIntrinsics::_jvm_commit:               return inline_native_jvm_commit();
 501 #endif
 502   case vmIntrinsics::_currentTimeMillis:        return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeMillis), "currentTimeMillis");
 503   case vmIntrinsics::_nanoTime:                 return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeNanos), "nanoTime");
 504   case vmIntrinsics::_writeback0:               return inline_unsafe_writeback0();
 505   case vmIntrinsics::_writebackPreSync0:        return inline_unsafe_writebackSync0(true);
 506   case vmIntrinsics::_writebackPostSync0:       return inline_unsafe_writebackSync0(false);
 507   case vmIntrinsics::_allocateInstance:         return inline_unsafe_allocate();
 508   case vmIntrinsics::_copyMemory:               return inline_unsafe_copyMemory();
 509   case vmIntrinsics::_isFlatArray:              return inline_unsafe_isFlatArray();
 510   case vmIntrinsics::_setMemory:                return inline_unsafe_setMemory();
 511   case vmIntrinsics::_getLength:                return inline_native_getLength();
 512   case vmIntrinsics::_copyOf:                   return inline_array_copyOf(false);
 513   case vmIntrinsics::_copyOfRange:              return inline_array_copyOf(true);
 514   case vmIntrinsics::_equalsB:                  return inline_array_equals(StrIntrinsicNode::LL);
 515   case vmIntrinsics::_equalsC:                  return inline_array_equals(StrIntrinsicNode::UU);
 516   case vmIntrinsics::_Preconditions_checkIndex: return inline_preconditions_checkIndex(T_INT);
 517   case vmIntrinsics::_Preconditions_checkLongIndex: return inline_preconditions_checkIndex(T_LONG);
 518   case vmIntrinsics::_clone:                    return inline_native_clone(intrinsic()->is_virtual());
 519 
 520   case vmIntrinsics::_allocateUninitializedArray: return inline_unsafe_newArray(true);
 521   case vmIntrinsics::_newArray:                   return inline_unsafe_newArray(false);
 522   case vmIntrinsics::_newNullRestrictedNonAtomicArray: return inline_newArray(/* null_free */ true, /* atomic */ false);
 523   case vmIntrinsics::_newNullRestrictedAtomicArray: return inline_newArray(/* null_free */ true, /* atomic */ true);
 524   case vmIntrinsics::_newNullableAtomicArray:     return inline_newArray(/* null_free */ false, /* atomic */ true);
 525 
 526   case vmIntrinsics::_isAssignableFrom:         return inline_native_subtype_check();
 527 
 528   case vmIntrinsics::_isInstance:
 529   case vmIntrinsics::_isHidden:
 530   case vmIntrinsics::_getSuperclass:
 531   case vmIntrinsics::_getClassAccessFlags:      return inline_native_Class_query(intrinsic_id());
 532 
 533   case vmIntrinsics::_floatToRawIntBits:
 534   case vmIntrinsics::_floatToIntBits:
 535   case vmIntrinsics::_intBitsToFloat:
 536   case vmIntrinsics::_doubleToRawLongBits:
 537   case vmIntrinsics::_doubleToLongBits:
 538   case vmIntrinsics::_longBitsToDouble:
 539   case vmIntrinsics::_floatToFloat16:
 540   case vmIntrinsics::_float16ToFloat:           return inline_fp_conversions(intrinsic_id());
 541   case vmIntrinsics::_sqrt_float16:             return inline_fp16_operations(intrinsic_id(), 1);
 542   case vmIntrinsics::_fma_float16:              return inline_fp16_operations(intrinsic_id(), 3);
 543   case vmIntrinsics::_floatIsFinite:
 544   case vmIntrinsics::_floatIsInfinite:
 545   case vmIntrinsics::_doubleIsFinite:
 546   case vmIntrinsics::_doubleIsInfinite:         return inline_fp_range_check(intrinsic_id());
 547 
 548   case vmIntrinsics::_numberOfLeadingZeros_i:
 549   case vmIntrinsics::_numberOfLeadingZeros_l:
 550   case vmIntrinsics::_numberOfTrailingZeros_i:
 551   case vmIntrinsics::_numberOfTrailingZeros_l:
 552   case vmIntrinsics::_bitCount_i:
 553   case vmIntrinsics::_bitCount_l:
 554   case vmIntrinsics::_reverse_i:
 555   case vmIntrinsics::_reverse_l:
 556   case vmIntrinsics::_reverseBytes_i:
 557   case vmIntrinsics::_reverseBytes_l:
 558   case vmIntrinsics::_reverseBytes_s:
 559   case vmIntrinsics::_reverseBytes_c:           return inline_number_methods(intrinsic_id());
 560 
 561   case vmIntrinsics::_compress_i:
 562   case vmIntrinsics::_compress_l:
 563   case vmIntrinsics::_expand_i:
 564   case vmIntrinsics::_expand_l:                 return inline_bitshuffle_methods(intrinsic_id());
 565 
 566   case vmIntrinsics::_compareUnsigned_i:
 567   case vmIntrinsics::_compareUnsigned_l:        return inline_compare_unsigned(intrinsic_id());
 568 
 569   case vmIntrinsics::_divideUnsigned_i:
 570   case vmIntrinsics::_divideUnsigned_l:
 571   case vmIntrinsics::_remainderUnsigned_i:
 572   case vmIntrinsics::_remainderUnsigned_l:      return inline_divmod_methods(intrinsic_id());
 573 
 574   case vmIntrinsics::_getCallerClass:           return inline_native_Reflection_getCallerClass();
 575 
 576   case vmIntrinsics::_Reference_get:            return inline_reference_get();
 577   case vmIntrinsics::_Reference_refersTo0:      return inline_reference_refersTo0(false);
 578   case vmIntrinsics::_PhantomReference_refersTo0: return inline_reference_refersTo0(true);
 579   case vmIntrinsics::_Reference_clear0:         return inline_reference_clear0(false);
 580   case vmIntrinsics::_PhantomReference_clear0:  return inline_reference_clear0(true);
 581 
 582   case vmIntrinsics::_Class_cast:               return inline_Class_cast();
 583 
 584   case vmIntrinsics::_aescrypt_encryptBlock:
 585   case vmIntrinsics::_aescrypt_decryptBlock:    return inline_aescrypt_Block(intrinsic_id());
 586 
 587   case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
 588   case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
 589     return inline_cipherBlockChaining_AESCrypt(intrinsic_id());
 590 
 591   case vmIntrinsics::_electronicCodeBook_encryptAESCrypt:
 592   case vmIntrinsics::_electronicCodeBook_decryptAESCrypt:
 593     return inline_electronicCodeBook_AESCrypt(intrinsic_id());
 594 
 595   case vmIntrinsics::_counterMode_AESCrypt:
 596     return inline_counterMode_AESCrypt(intrinsic_id());
 597 
 598   case vmIntrinsics::_galoisCounterMode_AESCrypt:
 599     return inline_galoisCounterMode_AESCrypt();
 600 
 601   case vmIntrinsics::_md5_implCompress:
 602   case vmIntrinsics::_sha_implCompress:
 603   case vmIntrinsics::_sha2_implCompress:
 604   case vmIntrinsics::_sha5_implCompress:
 605   case vmIntrinsics::_sha3_implCompress:
 606     return inline_digestBase_implCompress(intrinsic_id());
 607   case vmIntrinsics::_double_keccak:
 608     return inline_double_keccak();
 609 
 610   case vmIntrinsics::_digestBase_implCompressMB:
 611     return inline_digestBase_implCompressMB(predicate);
 612 
 613   case vmIntrinsics::_multiplyToLen:
 614     return inline_multiplyToLen();
 615 
 616   case vmIntrinsics::_squareToLen:
 617     return inline_squareToLen();
 618 
 619   case vmIntrinsics::_mulAdd:
 620     return inline_mulAdd();
 621 
 622   case vmIntrinsics::_montgomeryMultiply:
 623     return inline_montgomeryMultiply();
 624   case vmIntrinsics::_montgomerySquare:
 625     return inline_montgomerySquare();
 626 
 627   case vmIntrinsics::_bigIntegerRightShiftWorker:
 628     return inline_bigIntegerShift(true);
 629   case vmIntrinsics::_bigIntegerLeftShiftWorker:
 630     return inline_bigIntegerShift(false);
 631 
 632   case vmIntrinsics::_vectorizedMismatch:
 633     return inline_vectorizedMismatch();
 634 
 635   case vmIntrinsics::_ghash_processBlocks:
 636     return inline_ghash_processBlocks();
 637   case vmIntrinsics::_chacha20Block:
 638     return inline_chacha20Block();
 639   case vmIntrinsics::_kyberNtt:
 640     return inline_kyberNtt();
 641   case vmIntrinsics::_kyberInverseNtt:
 642     return inline_kyberInverseNtt();
 643   case vmIntrinsics::_kyberNttMult:
 644     return inline_kyberNttMult();
 645   case vmIntrinsics::_kyberAddPoly_2:
 646     return inline_kyberAddPoly_2();
 647   case vmIntrinsics::_kyberAddPoly_3:
 648     return inline_kyberAddPoly_3();
 649   case vmIntrinsics::_kyber12To16:
 650     return inline_kyber12To16();
 651   case vmIntrinsics::_kyberBarrettReduce:
 652     return inline_kyberBarrettReduce();
 653   case vmIntrinsics::_dilithiumAlmostNtt:
 654     return inline_dilithiumAlmostNtt();
 655   case vmIntrinsics::_dilithiumAlmostInverseNtt:
 656     return inline_dilithiumAlmostInverseNtt();
 657   case vmIntrinsics::_dilithiumNttMult:
 658     return inline_dilithiumNttMult();
 659   case vmIntrinsics::_dilithiumMontMulByConstant:
 660     return inline_dilithiumMontMulByConstant();
 661   case vmIntrinsics::_dilithiumDecomposePoly:
 662     return inline_dilithiumDecomposePoly();
 663   case vmIntrinsics::_base64_encodeBlock:
 664     return inline_base64_encodeBlock();
 665   case vmIntrinsics::_base64_decodeBlock:
 666     return inline_base64_decodeBlock();
 667   case vmIntrinsics::_poly1305_processBlocks:
 668     return inline_poly1305_processBlocks();
 669   case vmIntrinsics::_intpoly_montgomeryMult_P256:
 670     return inline_intpoly_montgomeryMult_P256();
 671   case vmIntrinsics::_intpoly_assign:
 672     return inline_intpoly_assign();
 673   case vmIntrinsics::_encodeISOArray:
 674   case vmIntrinsics::_encodeByteISOArray:
 675     return inline_encodeISOArray(false);
 676   case vmIntrinsics::_encodeAsciiArray:
 677     return inline_encodeISOArray(true);
 678 
 679   case vmIntrinsics::_updateCRC32:
 680     return inline_updateCRC32();
 681   case vmIntrinsics::_updateBytesCRC32:
 682     return inline_updateBytesCRC32();
 683   case vmIntrinsics::_updateByteBufferCRC32:
 684     return inline_updateByteBufferCRC32();
 685 
 686   case vmIntrinsics::_updateBytesCRC32C:
 687     return inline_updateBytesCRC32C();
 688   case vmIntrinsics::_updateDirectByteBufferCRC32C:
 689     return inline_updateDirectByteBufferCRC32C();
 690 
 691   case vmIntrinsics::_updateBytesAdler32:
 692     return inline_updateBytesAdler32();
 693   case vmIntrinsics::_updateByteBufferAdler32:
 694     return inline_updateByteBufferAdler32();
 695 
 696   case vmIntrinsics::_profileBoolean:
 697     return inline_profileBoolean();
 698   case vmIntrinsics::_isCompileConstant:
 699     return inline_isCompileConstant();
 700 
 701   case vmIntrinsics::_countPositives:
 702     return inline_countPositives();
 703 
 704   case vmIntrinsics::_fmaD:
 705   case vmIntrinsics::_fmaF:
 706     return inline_fma(intrinsic_id());
 707 
 708   case vmIntrinsics::_isDigit:
 709   case vmIntrinsics::_isLowerCase:
 710   case vmIntrinsics::_isUpperCase:
 711   case vmIntrinsics::_isWhitespace:
 712     return inline_character_compare(intrinsic_id());
 713 
 714   case vmIntrinsics::_min:
 715   case vmIntrinsics::_max:
 716   case vmIntrinsics::_min_strict:
 717   case vmIntrinsics::_max_strict:
 718   case vmIntrinsics::_minL:
 719   case vmIntrinsics::_maxL:
 720   case vmIntrinsics::_minF:
 721   case vmIntrinsics::_maxF:
 722   case vmIntrinsics::_minD:
 723   case vmIntrinsics::_maxD:
 724   case vmIntrinsics::_minF_strict:
 725   case vmIntrinsics::_maxF_strict:
 726   case vmIntrinsics::_minD_strict:
 727   case vmIntrinsics::_maxD_strict:
 728     return inline_min_max(intrinsic_id());
 729 
 730   case vmIntrinsics::_VectorUnaryOp:
 731     return inline_vector_nary_operation(1);
 732   case vmIntrinsics::_VectorBinaryOp:
 733     return inline_vector_nary_operation(2);
 734   case vmIntrinsics::_VectorTernaryOp:
 735     return inline_vector_nary_operation(3);
 736   case vmIntrinsics::_VectorFromBitsCoerced:
 737     return inline_vector_frombits_coerced();
 738   case vmIntrinsics::_VectorMaskOp:
 739     return inline_vector_mask_operation();
 740   case vmIntrinsics::_VectorLoadOp:
 741     return inline_vector_mem_operation(/*is_store=*/false);
 742   case vmIntrinsics::_VectorLoadMaskedOp:
 743     return inline_vector_mem_masked_operation(/*is_store*/false);
 744   case vmIntrinsics::_VectorStoreOp:
 745     return inline_vector_mem_operation(/*is_store=*/true);
 746   case vmIntrinsics::_VectorStoreMaskedOp:
 747     return inline_vector_mem_masked_operation(/*is_store=*/true);
 748   case vmIntrinsics::_VectorGatherOp:
 749     return inline_vector_gather_scatter(/*is_scatter*/ false);
 750   case vmIntrinsics::_VectorScatterOp:
 751     return inline_vector_gather_scatter(/*is_scatter*/ true);
 752   case vmIntrinsics::_VectorReductionCoerced:
 753     return inline_vector_reduction();
 754   case vmIntrinsics::_VectorTest:
 755     return inline_vector_test();
 756   case vmIntrinsics::_VectorBlend:
 757     return inline_vector_blend();
 758   case vmIntrinsics::_VectorRearrange:
 759     return inline_vector_rearrange();
 760   case vmIntrinsics::_VectorSelectFrom:
 761     return inline_vector_select_from();
 762   case vmIntrinsics::_VectorCompare:
 763     return inline_vector_compare();
 764   case vmIntrinsics::_VectorBroadcastInt:
 765     return inline_vector_broadcast_int();
 766   case vmIntrinsics::_VectorConvert:
 767     return inline_vector_convert();
 768   case vmIntrinsics::_VectorInsert:
 769     return inline_vector_insert();
 770   case vmIntrinsics::_VectorExtract:
 771     return inline_vector_extract();
 772   case vmIntrinsics::_VectorCompressExpand:
 773     return inline_vector_compress_expand();
 774   case vmIntrinsics::_VectorSelectFromTwoVectorOp:
 775     return inline_vector_select_from_two_vectors();
 776   case vmIntrinsics::_IndexVector:
 777     return inline_index_vector();
 778   case vmIntrinsics::_IndexPartiallyInUpperRange:
 779     return inline_index_partially_in_upper_range();
 780 
 781   case vmIntrinsics::_getObjectSize:
 782     return inline_getObjectSize();
 783 
 784   case vmIntrinsics::_blackhole:
 785     return inline_blackhole();
 786 
 787   default:
 788     // If you get here, it may be that someone has added a new intrinsic
 789     // to the list in vmIntrinsics.hpp without implementing it here.
 790 #ifndef PRODUCT
 791     if ((PrintMiscellaneous && (Verbose || WizardMode)) || PrintOpto) {
 792       tty->print_cr("*** Warning: Unimplemented intrinsic %s(%d)",
 793                     vmIntrinsics::name_at(intrinsic_id()), vmIntrinsics::as_int(intrinsic_id()));
 794     }
 795 #endif
 796     return false;
 797   }
 798 }
 799 
 800 Node* LibraryCallKit::try_to_predicate(int predicate) {
 801   if (!jvms()->has_method()) {
 802     // Root JVMState has a null method.
 803     assert(map()->memory()->Opcode() == Op_Parm, "");
 804     // Insert the memory aliasing node
 805     set_all_memory(reset_memory());
 806   }
 807   assert(merged_memory(), "");
 808 
 809   switch (intrinsic_id()) {
 810   case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
 811     return inline_cipherBlockChaining_AESCrypt_predicate(false);
 812   case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
 813     return inline_cipherBlockChaining_AESCrypt_predicate(true);
 814   case vmIntrinsics::_electronicCodeBook_encryptAESCrypt:
 815     return inline_electronicCodeBook_AESCrypt_predicate(false);
 816   case vmIntrinsics::_electronicCodeBook_decryptAESCrypt:
 817     return inline_electronicCodeBook_AESCrypt_predicate(true);
 818   case vmIntrinsics::_counterMode_AESCrypt:
 819     return inline_counterMode_AESCrypt_predicate();
 820   case vmIntrinsics::_digestBase_implCompressMB:
 821     return inline_digestBase_implCompressMB_predicate(predicate);
 822   case vmIntrinsics::_galoisCounterMode_AESCrypt:
 823     return inline_galoisCounterMode_AESCrypt_predicate();
 824 
 825   default:
 826     // If you get here, it may be that someone has added a new intrinsic
 827     // to the list in vmIntrinsics.hpp without implementing it here.
 828 #ifndef PRODUCT
 829     if ((PrintMiscellaneous && (Verbose || WizardMode)) || PrintOpto) {
 830       tty->print_cr("*** Warning: Unimplemented predicate for intrinsic %s(%d)",
 831                     vmIntrinsics::name_at(intrinsic_id()), vmIntrinsics::as_int(intrinsic_id()));
 832     }
 833 #endif
 834     Node* slow_ctl = control();
 835     set_control(top()); // No fast path intrinsic
 836     return slow_ctl;
 837   }
 838 }
 839 
 840 //------------------------------set_result-------------------------------
 841 // Helper function for finishing intrinsics.
 842 void LibraryCallKit::set_result(RegionNode* region, PhiNode* value) {
 843   record_for_igvn(region);
 844   set_control(_gvn.transform(region));
 845   set_result( _gvn.transform(value));
 846   assert(value->type()->basic_type() == result()->bottom_type()->basic_type(), "sanity");
 847 }
 848 
 849 //------------------------------generate_guard---------------------------
 850 // Helper function for generating guarded fast-slow graph structures.
 851 // The given 'test', if true, guards a slow path.  If the test fails
 852 // then a fast path can be taken.  (We generally hope it fails.)
 853 // In all cases, GraphKit::control() is updated to the fast path.
 854 // The returned value represents the control for the slow path.
 855 // The return value is never 'top'; it is either a valid control
 856 // or null if it is obvious that the slow path can never be taken.
 857 // Also, if region and the slow control are not null, the slow edge
 858 // is appended to the region.
 859 Node* LibraryCallKit::generate_guard(Node* test, RegionNode* region, float true_prob) {
 860   if (stopped()) {
 861     // Already short circuited.
 862     return nullptr;
 863   }
 864 
 865   // Build an if node and its projections.
 866   // If test is true we take the slow path, which we assume is uncommon.
 867   if (_gvn.type(test) == TypeInt::ZERO) {
 868     // The slow branch is never taken.  No need to build this guard.
 869     return nullptr;
 870   }
 871 
 872   IfNode* iff = create_and_map_if(control(), test, true_prob, COUNT_UNKNOWN);
 873 
 874   Node* if_slow = _gvn.transform(new IfTrueNode(iff));
 875   if (if_slow == top()) {
 876     // The slow branch is never taken.  No need to build this guard.
 877     return nullptr;
 878   }
 879 
 880   if (region != nullptr)
 881     region->add_req(if_slow);
 882 
 883   Node* if_fast = _gvn.transform(new IfFalseNode(iff));
 884   set_control(if_fast);
 885 
 886   return if_slow;
 887 }
 888 
 889 inline Node* LibraryCallKit::generate_slow_guard(Node* test, RegionNode* region) {
 890   return generate_guard(test, region, PROB_UNLIKELY_MAG(3));
 891 }
 892 inline Node* LibraryCallKit::generate_fair_guard(Node* test, RegionNode* region) {
 893   return generate_guard(test, region, PROB_FAIR);
 894 }
 895 
 896 inline Node* LibraryCallKit::generate_negative_guard(Node* index, RegionNode* region,
 897                                                      Node* *pos_index) {
 898   if (stopped())
 899     return nullptr;                // already stopped
 900   if (_gvn.type(index)->higher_equal(TypeInt::POS)) // [0,maxint]
 901     return nullptr;                // index is already adequately typed
 902   Node* cmp_lt = _gvn.transform(new CmpINode(index, intcon(0)));
 903   Node* bol_lt = _gvn.transform(new BoolNode(cmp_lt, BoolTest::lt));
 904   Node* is_neg = generate_guard(bol_lt, region, PROB_MIN);
 905   if (is_neg != nullptr && pos_index != nullptr) {
 906     // Emulate effect of Parse::adjust_map_after_if.
 907     Node* ccast = new CastIINode(control(), index, TypeInt::POS);
 908     (*pos_index) = _gvn.transform(ccast);
 909   }
 910   return is_neg;
 911 }
 912 
 913 // Make sure that 'position' is a valid limit index, in [0..length].
 914 // There are two equivalent plans for checking this:
 915 //   A. (offset + copyLength)  unsigned<=  arrayLength
 916 //   B. offset  <=  (arrayLength - copyLength)
 917 // We require that all of the values above, except for the sum and
 918 // difference, are already known to be non-negative.
 919 // Plan A is robust in the face of overflow, if offset and copyLength
 920 // are both hugely positive.
 921 //
 922 // Plan B is less direct and intuitive, but it does not overflow at
 923 // all, since the difference of two non-negatives is always
 924 // representable.  Whenever Java methods must perform the equivalent
 925 // check they generally use Plan B instead of Plan A.
 926 // For the moment we use Plan A.
 927 inline Node* LibraryCallKit::generate_limit_guard(Node* offset,
 928                                                   Node* subseq_length,
 929                                                   Node* array_length,
 930                                                   RegionNode* region) {
 931   if (stopped())
 932     return nullptr;                // already stopped
 933   bool zero_offset = _gvn.type(offset) == TypeInt::ZERO;
 934   if (zero_offset && subseq_length->eqv_uncast(array_length))
 935     return nullptr;                // common case of whole-array copy
 936   Node* last = subseq_length;
 937   if (!zero_offset)             // last += offset
 938     last = _gvn.transform(new AddINode(last, offset));
 939   Node* cmp_lt = _gvn.transform(new CmpUNode(array_length, last));
 940   Node* bol_lt = _gvn.transform(new BoolNode(cmp_lt, BoolTest::lt));
 941   Node* is_over = generate_guard(bol_lt, region, PROB_MIN);
 942   return is_over;
 943 }
 944 
 945 // Emit range checks for the given String.value byte array
 946 void LibraryCallKit::generate_string_range_check(Node* array, Node* offset, Node* count, bool char_count) {
 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     PreserveJVMState pjvms(this);
 965     set_control(_gvn.transform(bailout));
 966     uncommon_trap(Deoptimization::Reason_intrinsic,
 967                   Deoptimization::Action_maybe_recompile);
 968   }
 969 }
 970 
 971 Node* LibraryCallKit::current_thread_helper(Node*& tls_output, ByteSize handle_offset,
 972                                             bool is_immutable) {
 973   ciKlass* thread_klass = env()->Thread_klass();
 974   const Type* thread_type
 975     = TypeOopPtr::make_from_klass(thread_klass)->cast_to_ptr_type(TypePtr::NotNull);
 976 
 977   Node* thread = _gvn.transform(new ThreadLocalNode());
 978   Node* p = basic_plus_adr(top()/*!oop*/, thread, in_bytes(handle_offset));
 979   tls_output = thread;
 980 
 981   Node* thread_obj_handle
 982     = (is_immutable
 983       ? LoadNode::make(_gvn, nullptr, immutable_memory(), p, p->bottom_type()->is_ptr(),
 984         TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered)
 985       : make_load(nullptr, p, p->bottom_type()->is_ptr(), T_ADDRESS, MemNode::unordered));
 986   thread_obj_handle = _gvn.transform(thread_obj_handle);
 987 
 988   DecoratorSet decorators = IN_NATIVE;
 989   if (is_immutable) {
 990     decorators |= C2_IMMUTABLE_MEMORY;
 991   }
 992   return access_load(thread_obj_handle, thread_type, T_OBJECT, decorators);
 993 }
 994 
 995 //--------------------------generate_current_thread--------------------
 996 Node* LibraryCallKit::generate_current_thread(Node* &tls_output) {
 997   return current_thread_helper(tls_output, JavaThread::threadObj_offset(),
 998                                /*is_immutable*/false);
 999 }
1000 
1001 //--------------------------generate_virtual_thread--------------------
1002 Node* LibraryCallKit::generate_virtual_thread(Node* tls_output) {
1003   return current_thread_helper(tls_output, JavaThread::vthread_offset(),
1004                                !C->method()->changes_current_thread());
1005 }
1006 
1007 //------------------------------make_string_method_node------------------------
1008 // Helper method for String intrinsic functions. This version is called with
1009 // str1 and str2 pointing to byte[] nodes containing Latin1 or UTF16 encoded
1010 // characters (depending on 'is_byte'). cnt1 and cnt2 are pointing to Int nodes
1011 // containing the lengths of str1 and str2.
1012 Node* LibraryCallKit::make_string_method_node(int opcode, Node* str1_start, Node* cnt1, Node* str2_start, Node* cnt2, StrIntrinsicNode::ArgEnc ae) {
1013   Node* result = nullptr;
1014   switch (opcode) {
1015   case Op_StrIndexOf:
1016     result = new StrIndexOfNode(control(), memory(TypeAryPtr::BYTES),
1017                                 str1_start, cnt1, str2_start, cnt2, ae);
1018     break;
1019   case Op_StrComp:
1020     result = new StrCompNode(control(), memory(TypeAryPtr::BYTES),
1021                              str1_start, cnt1, str2_start, cnt2, ae);
1022     break;
1023   case Op_StrEquals:
1024     // We already know that cnt1 == cnt2 here (checked in 'inline_string_equals').
1025     // Use the constant length if there is one because optimized match rule may exist.
1026     result = new StrEqualsNode(control(), memory(TypeAryPtr::BYTES),
1027                                str1_start, str2_start, cnt2->is_Con() ? cnt2 : cnt1, ae);
1028     break;
1029   default:
1030     ShouldNotReachHere();
1031     return nullptr;
1032   }
1033 
1034   // All these intrinsics have checks.
1035   C->set_has_split_ifs(true); // Has chance for split-if optimization
1036   clear_upper_avx();
1037 
1038   return _gvn.transform(result);
1039 }
1040 
1041 //------------------------------inline_string_compareTo------------------------
1042 bool LibraryCallKit::inline_string_compareTo(StrIntrinsicNode::ArgEnc ae) {
1043   Node* arg1 = argument(0);
1044   Node* arg2 = argument(1);
1045 
1046   arg1 = must_be_not_null(arg1, true);
1047   arg2 = must_be_not_null(arg2, true);
1048 
1049   // Get start addr and length of first argument
1050   Node* arg1_start  = array_element_address(arg1, intcon(0), T_BYTE);
1051   Node* arg1_cnt    = load_array_length(arg1);
1052 
1053   // Get start addr and length of second argument
1054   Node* arg2_start  = array_element_address(arg2, intcon(0), T_BYTE);
1055   Node* arg2_cnt    = load_array_length(arg2);
1056 
1057   Node* result = make_string_method_node(Op_StrComp, arg1_start, arg1_cnt, arg2_start, arg2_cnt, ae);
1058   set_result(result);
1059   return true;
1060 }
1061 
1062 //------------------------------inline_string_equals------------------------
1063 bool LibraryCallKit::inline_string_equals(StrIntrinsicNode::ArgEnc ae) {
1064   Node* arg1 = argument(0);
1065   Node* arg2 = argument(1);
1066 
1067   // paths (plus control) merge
1068   RegionNode* region = new RegionNode(3);
1069   Node* phi = new PhiNode(region, TypeInt::BOOL);
1070 
1071   if (!stopped()) {
1072 
1073     arg1 = must_be_not_null(arg1, true);
1074     arg2 = must_be_not_null(arg2, true);
1075 
1076     // Get start addr and length of first argument
1077     Node* arg1_start  = array_element_address(arg1, intcon(0), T_BYTE);
1078     Node* arg1_cnt    = load_array_length(arg1);
1079 
1080     // Get start addr and length of second argument
1081     Node* arg2_start  = array_element_address(arg2, intcon(0), T_BYTE);
1082     Node* arg2_cnt    = load_array_length(arg2);
1083 
1084     // Check for arg1_cnt != arg2_cnt
1085     Node* cmp = _gvn.transform(new CmpINode(arg1_cnt, arg2_cnt));
1086     Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::ne));
1087     Node* if_ne = generate_slow_guard(bol, nullptr);
1088     if (if_ne != nullptr) {
1089       phi->init_req(2, intcon(0));
1090       region->init_req(2, if_ne);
1091     }
1092 
1093     // Check for count == 0 is done by assembler code for StrEquals.
1094 
1095     if (!stopped()) {
1096       Node* equals = make_string_method_node(Op_StrEquals, arg1_start, arg1_cnt, arg2_start, arg2_cnt, ae);
1097       phi->init_req(1, equals);
1098       region->init_req(1, control());
1099     }
1100   }
1101 
1102   // post merge
1103   set_control(_gvn.transform(region));
1104   record_for_igvn(region);
1105 
1106   set_result(_gvn.transform(phi));
1107   return true;
1108 }
1109 
1110 //------------------------------inline_array_equals----------------------------
1111 bool LibraryCallKit::inline_array_equals(StrIntrinsicNode::ArgEnc ae) {
1112   assert(ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::LL, "unsupported array types");
1113   Node* arg1 = argument(0);
1114   Node* arg2 = argument(1);
1115 
1116   const TypeAryPtr* mtype = (ae == StrIntrinsicNode::UU) ? TypeAryPtr::CHARS : TypeAryPtr::BYTES;
1117   set_result(_gvn.transform(new AryEqNode(control(), memory(mtype), arg1, arg2, ae)));
1118   clear_upper_avx();
1119 
1120   return true;
1121 }
1122 
1123 
1124 //------------------------------inline_countPositives------------------------------
1125 bool LibraryCallKit::inline_countPositives() {
1126   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1127     return false;
1128   }
1129 
1130   assert(callee()->signature()->size() == 3, "countPositives has 3 parameters");
1131   // no receiver since it is static method
1132   Node* ba         = argument(0);
1133   Node* offset     = argument(1);
1134   Node* len        = argument(2);
1135 
1136   ba = must_be_not_null(ba, true);
1137 
1138   // Range checks
1139   generate_string_range_check(ba, offset, len, false);
1140   if (stopped()) {
1141     return true;
1142   }
1143   Node* ba_start = array_element_address(ba, offset, T_BYTE);
1144   Node* result = new CountPositivesNode(control(), memory(TypeAryPtr::BYTES), ba_start, len);
1145   set_result(_gvn.transform(result));
1146   clear_upper_avx();
1147   return true;
1148 }
1149 
1150 bool LibraryCallKit::inline_preconditions_checkIndex(BasicType bt) {
1151   Node* index = argument(0);
1152   Node* length = bt == T_INT ? argument(1) : argument(2);
1153   if (too_many_traps(Deoptimization::Reason_intrinsic) || too_many_traps(Deoptimization::Reason_range_check)) {
1154     return false;
1155   }
1156 
1157   // check that length is positive
1158   Node* len_pos_cmp = _gvn.transform(CmpNode::make(length, integercon(0, bt), bt));
1159   Node* len_pos_bol = _gvn.transform(new BoolNode(len_pos_cmp, BoolTest::ge));
1160 
1161   {
1162     BuildCutout unless(this, len_pos_bol, PROB_MAX);
1163     uncommon_trap(Deoptimization::Reason_intrinsic,
1164                   Deoptimization::Action_make_not_entrant);
1165   }
1166 
1167   if (stopped()) {
1168     // Length is known to be always negative during compilation and the IR graph so far constructed is good so return success
1169     return true;
1170   }
1171 
1172   // length is now known positive, add a cast node to make this explicit
1173   jlong upper_bound = _gvn.type(length)->is_integer(bt)->hi_as_long();
1174   Node* casted_length = ConstraintCastNode::make_cast_for_basic_type(
1175       control(), length, TypeInteger::make(0, upper_bound, Type::WidenMax, bt),
1176       ConstraintCastNode::RegularDependency, bt);
1177   casted_length = _gvn.transform(casted_length);
1178   replace_in_map(length, casted_length);
1179   length = casted_length;
1180 
1181   // Use an unsigned comparison for the range check itself
1182   Node* rc_cmp = _gvn.transform(CmpNode::make(index, length, bt, true));
1183   BoolTest::mask btest = BoolTest::lt;
1184   Node* rc_bool = _gvn.transform(new BoolNode(rc_cmp, btest));
1185   RangeCheckNode* rc = new RangeCheckNode(control(), rc_bool, PROB_MAX, COUNT_UNKNOWN);
1186   _gvn.set_type(rc, rc->Value(&_gvn));
1187   if (!rc_bool->is_Con()) {
1188     record_for_igvn(rc);
1189   }
1190   set_control(_gvn.transform(new IfTrueNode(rc)));
1191   {
1192     PreserveJVMState pjvms(this);
1193     set_control(_gvn.transform(new IfFalseNode(rc)));
1194     uncommon_trap(Deoptimization::Reason_range_check,
1195                   Deoptimization::Action_make_not_entrant);
1196   }
1197 
1198   if (stopped()) {
1199     // Range check is known to always fail during compilation and the IR graph so far constructed is good so return success
1200     return true;
1201   }
1202 
1203   // index is now known to be >= 0 and < length, cast it
1204   Node* result = ConstraintCastNode::make_cast_for_basic_type(
1205       control(), index, TypeInteger::make(0, upper_bound, Type::WidenMax, bt),
1206       ConstraintCastNode::RegularDependency, bt);
1207   result = _gvn.transform(result);
1208   set_result(result);
1209   replace_in_map(index, result);
1210   return true;
1211 }
1212 
1213 //------------------------------inline_string_indexOf------------------------
1214 bool LibraryCallKit::inline_string_indexOf(StrIntrinsicNode::ArgEnc ae) {
1215   if (!Matcher::match_rule_supported(Op_StrIndexOf)) {
1216     return false;
1217   }
1218   Node* src = argument(0);
1219   Node* tgt = argument(1);
1220 
1221   // Make the merge point
1222   RegionNode* result_rgn = new RegionNode(4);
1223   Node*       result_phi = new PhiNode(result_rgn, TypeInt::INT);
1224 
1225   src = must_be_not_null(src, true);
1226   tgt = must_be_not_null(tgt, true);
1227 
1228   // Get start addr and length of source string
1229   Node* src_start = array_element_address(src, intcon(0), T_BYTE);
1230   Node* src_count = load_array_length(src);
1231 
1232   // Get start addr and length of substring
1233   Node* tgt_start = array_element_address(tgt, intcon(0), T_BYTE);
1234   Node* tgt_count = load_array_length(tgt);
1235 
1236   Node* result = nullptr;
1237   bool call_opt_stub = (StubRoutines::_string_indexof_array[ae] != nullptr);
1238 
1239   if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
1240     // Divide src size by 2 if String is UTF16 encoded
1241     src_count = _gvn.transform(new RShiftINode(src_count, intcon(1)));
1242   }
1243   if (ae == StrIntrinsicNode::UU) {
1244     // Divide substring size by 2 if String is UTF16 encoded
1245     tgt_count = _gvn.transform(new RShiftINode(tgt_count, intcon(1)));
1246   }
1247 
1248   if (call_opt_stub) {
1249     Node* call = make_runtime_call(RC_LEAF, OptoRuntime::string_IndexOf_Type(),
1250                                    StubRoutines::_string_indexof_array[ae],
1251                                    "stringIndexOf", TypePtr::BOTTOM, src_start,
1252                                    src_count, tgt_start, tgt_count);
1253     result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
1254   } else {
1255     result = make_indexOf_node(src_start, src_count, tgt_start, tgt_count,
1256                                result_rgn, result_phi, ae);
1257   }
1258   if (result != nullptr) {
1259     result_phi->init_req(3, result);
1260     result_rgn->init_req(3, control());
1261   }
1262   set_control(_gvn.transform(result_rgn));
1263   record_for_igvn(result_rgn);
1264   set_result(_gvn.transform(result_phi));
1265 
1266   return true;
1267 }
1268 
1269 //-----------------------------inline_string_indexOfI-----------------------
1270 bool LibraryCallKit::inline_string_indexOfI(StrIntrinsicNode::ArgEnc ae) {
1271   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1272     return false;
1273   }
1274   if (!Matcher::match_rule_supported(Op_StrIndexOf)) {
1275     return false;
1276   }
1277 
1278   assert(callee()->signature()->size() == 5, "String.indexOf() has 5 arguments");
1279   Node* src         = argument(0); // byte[]
1280   Node* src_count   = argument(1); // char count
1281   Node* tgt         = argument(2); // byte[]
1282   Node* tgt_count   = argument(3); // char count
1283   Node* from_index  = argument(4); // char index
1284 
1285   src = must_be_not_null(src, true);
1286   tgt = must_be_not_null(tgt, true);
1287 
1288   // Multiply byte array index by 2 if String is UTF16 encoded
1289   Node* src_offset = (ae == StrIntrinsicNode::LL) ? from_index : _gvn.transform(new LShiftINode(from_index, intcon(1)));
1290   src_count = _gvn.transform(new SubINode(src_count, from_index));
1291   Node* src_start = array_element_address(src, src_offset, T_BYTE);
1292   Node* tgt_start = array_element_address(tgt, intcon(0), T_BYTE);
1293 
1294   // Range checks
1295   generate_string_range_check(src, src_offset, src_count, ae != StrIntrinsicNode::LL);
1296   generate_string_range_check(tgt, intcon(0), tgt_count, ae == StrIntrinsicNode::UU);
1297   if (stopped()) {
1298     return true;
1299   }
1300 
1301   RegionNode* region = new RegionNode(5);
1302   Node* phi = new PhiNode(region, TypeInt::INT);
1303   Node* result = nullptr;
1304 
1305   bool call_opt_stub = (StubRoutines::_string_indexof_array[ae] != nullptr);
1306 
1307   if (call_opt_stub) {
1308     Node* call = make_runtime_call(RC_LEAF, OptoRuntime::string_IndexOf_Type(),
1309                                    StubRoutines::_string_indexof_array[ae],
1310                                    "stringIndexOf", TypePtr::BOTTOM, src_start,
1311                                    src_count, tgt_start, tgt_count);
1312     result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
1313   } else {
1314     result = make_indexOf_node(src_start, src_count, tgt_start, tgt_count,
1315                                region, phi, ae);
1316   }
1317   if (result != nullptr) {
1318     // The result is index relative to from_index if substring was found, -1 otherwise.
1319     // Generate code which will fold into cmove.
1320     Node* cmp = _gvn.transform(new CmpINode(result, intcon(0)));
1321     Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::lt));
1322 
1323     Node* if_lt = generate_slow_guard(bol, nullptr);
1324     if (if_lt != nullptr) {
1325       // result == -1
1326       phi->init_req(3, result);
1327       region->init_req(3, if_lt);
1328     }
1329     if (!stopped()) {
1330       result = _gvn.transform(new AddINode(result, from_index));
1331       phi->init_req(4, result);
1332       region->init_req(4, control());
1333     }
1334   }
1335 
1336   set_control(_gvn.transform(region));
1337   record_for_igvn(region);
1338   set_result(_gvn.transform(phi));
1339   clear_upper_avx();
1340 
1341   return true;
1342 }
1343 
1344 // Create StrIndexOfNode with fast path checks
1345 Node* LibraryCallKit::make_indexOf_node(Node* src_start, Node* src_count, Node* tgt_start, Node* tgt_count,
1346                                         RegionNode* region, Node* phi, StrIntrinsicNode::ArgEnc ae) {
1347   // Check for substr count > string count
1348   Node* cmp = _gvn.transform(new CmpINode(tgt_count, src_count));
1349   Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::gt));
1350   Node* if_gt = generate_slow_guard(bol, nullptr);
1351   if (if_gt != nullptr) {
1352     phi->init_req(1, intcon(-1));
1353     region->init_req(1, if_gt);
1354   }
1355   if (!stopped()) {
1356     // Check for substr count == 0
1357     cmp = _gvn.transform(new CmpINode(tgt_count, intcon(0)));
1358     bol = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
1359     Node* if_zero = generate_slow_guard(bol, nullptr);
1360     if (if_zero != nullptr) {
1361       phi->init_req(2, intcon(0));
1362       region->init_req(2, if_zero);
1363     }
1364   }
1365   if (!stopped()) {
1366     return make_string_method_node(Op_StrIndexOf, src_start, src_count, tgt_start, tgt_count, ae);
1367   }
1368   return nullptr;
1369 }
1370 
1371 //-----------------------------inline_string_indexOfChar-----------------------
1372 bool LibraryCallKit::inline_string_indexOfChar(StrIntrinsicNode::ArgEnc ae) {
1373   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1374     return false;
1375   }
1376   if (!Matcher::match_rule_supported(Op_StrIndexOfChar)) {
1377     return false;
1378   }
1379   assert(callee()->signature()->size() == 4, "String.indexOfChar() has 4 arguments");
1380   Node* src         = argument(0); // byte[]
1381   Node* int_ch      = argument(1);
1382   Node* from_index  = argument(2);
1383   Node* max         = argument(3);
1384 
1385   src = must_be_not_null(src, true);
1386 
1387   Node* src_offset = ae == StrIntrinsicNode::L ? from_index : _gvn.transform(new LShiftINode(from_index, intcon(1)));
1388   Node* src_start = array_element_address(src, src_offset, T_BYTE);
1389   Node* src_count = _gvn.transform(new SubINode(max, from_index));
1390 
1391   // Range checks
1392   generate_string_range_check(src, src_offset, src_count, ae == StrIntrinsicNode::U);
1393 
1394   // Check for int_ch >= 0
1395   Node* int_ch_cmp = _gvn.transform(new CmpINode(int_ch, intcon(0)));
1396   Node* int_ch_bol = _gvn.transform(new BoolNode(int_ch_cmp, BoolTest::ge));
1397   {
1398     BuildCutout unless(this, int_ch_bol, PROB_MAX);
1399     uncommon_trap(Deoptimization::Reason_intrinsic,
1400                   Deoptimization::Action_maybe_recompile);
1401   }
1402   if (stopped()) {
1403     return true;
1404   }
1405 
1406   RegionNode* region = new RegionNode(3);
1407   Node* phi = new PhiNode(region, TypeInt::INT);
1408 
1409   Node* result = new StrIndexOfCharNode(control(), memory(TypeAryPtr::BYTES), src_start, src_count, int_ch, ae);
1410   C->set_has_split_ifs(true); // Has chance for split-if optimization
1411   _gvn.transform(result);
1412 
1413   Node* cmp = _gvn.transform(new CmpINode(result, intcon(0)));
1414   Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::lt));
1415 
1416   Node* if_lt = generate_slow_guard(bol, nullptr);
1417   if (if_lt != nullptr) {
1418     // result == -1
1419     phi->init_req(2, result);
1420     region->init_req(2, if_lt);
1421   }
1422   if (!stopped()) {
1423     result = _gvn.transform(new AddINode(result, from_index));
1424     phi->init_req(1, result);
1425     region->init_req(1, control());
1426   }
1427   set_control(_gvn.transform(region));
1428   record_for_igvn(region);
1429   set_result(_gvn.transform(phi));
1430   clear_upper_avx();
1431 
1432   return true;
1433 }
1434 //---------------------------inline_string_copy---------------------
1435 // compressIt == true --> generate a compressed copy operation (compress char[]/byte[] to byte[])
1436 //   int StringUTF16.compress(char[] src, int srcOff, byte[] dst, int dstOff, int len)
1437 //   int StringUTF16.compress(byte[] src, int srcOff, byte[] dst, int dstOff, int len)
1438 // compressIt == false --> generate an inflated copy operation (inflate byte[] to char[]/byte[])
1439 //   void StringLatin1.inflate(byte[] src, int srcOff, char[] dst, int dstOff, int len)
1440 //   void StringLatin1.inflate(byte[] src, int srcOff, byte[] dst, int dstOff, int len)
1441 bool LibraryCallKit::inline_string_copy(bool compress) {
1442   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1443     return false;
1444   }
1445   int nargs = 5;  // 2 oops, 3 ints
1446   assert(callee()->signature()->size() == nargs, "string copy has 5 arguments");
1447 
1448   Node* src         = argument(0);
1449   Node* src_offset  = argument(1);
1450   Node* dst         = argument(2);
1451   Node* dst_offset  = argument(3);
1452   Node* length      = argument(4);
1453 
1454   // Check for allocation before we add nodes that would confuse
1455   // tightly_coupled_allocation()
1456   AllocateArrayNode* alloc = tightly_coupled_allocation(dst);
1457 
1458   // Figure out the size and type of the elements we will be copying.
1459   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
1460   const TypeAryPtr* dst_type = dst->Value(&_gvn)->isa_aryptr();
1461   if (src_type == nullptr || dst_type == nullptr) {
1462     return false;
1463   }
1464   BasicType src_elem = src_type->elem()->array_element_basic_type();
1465   BasicType dst_elem = dst_type->elem()->array_element_basic_type();
1466   assert((compress && dst_elem == T_BYTE && (src_elem == T_BYTE || src_elem == T_CHAR)) ||
1467          (!compress && src_elem == T_BYTE && (dst_elem == T_BYTE || dst_elem == T_CHAR)),
1468          "Unsupported array types for inline_string_copy");
1469 
1470   src = must_be_not_null(src, true);
1471   dst = must_be_not_null(dst, true);
1472 
1473   // Convert char[] offsets to byte[] offsets
1474   bool convert_src = (compress && src_elem == T_BYTE);
1475   bool convert_dst = (!compress && dst_elem == T_BYTE);
1476   if (convert_src) {
1477     src_offset = _gvn.transform(new LShiftINode(src_offset, intcon(1)));
1478   } else if (convert_dst) {
1479     dst_offset = _gvn.transform(new LShiftINode(dst_offset, intcon(1)));
1480   }
1481 
1482   // Range checks
1483   generate_string_range_check(src, src_offset, length, convert_src);
1484   generate_string_range_check(dst, dst_offset, length, convert_dst);
1485   if (stopped()) {
1486     return true;
1487   }
1488 
1489   Node* src_start = array_element_address(src, src_offset, src_elem);
1490   Node* dst_start = array_element_address(dst, dst_offset, dst_elem);
1491   // 'src_start' points to src array + scaled offset
1492   // 'dst_start' points to dst array + scaled offset
1493   Node* count = nullptr;
1494   if (compress) {
1495     count = compress_string(src_start, TypeAryPtr::get_array_body_type(src_elem), dst_start, length);
1496   } else {
1497     inflate_string(src_start, dst_start, TypeAryPtr::get_array_body_type(dst_elem), length);
1498   }
1499 
1500   if (alloc != nullptr) {
1501     if (alloc->maybe_set_complete(&_gvn)) {
1502       // "You break it, you buy it."
1503       InitializeNode* init = alloc->initialization();
1504       assert(init->is_complete(), "we just did this");
1505       init->set_complete_with_arraycopy();
1506       assert(dst->is_CheckCastPP(), "sanity");
1507       assert(dst->in(0)->in(0) == init, "dest pinned");
1508     }
1509     // Do not let stores that initialize this object be reordered with
1510     // a subsequent store that would make this object accessible by
1511     // other threads.
1512     // Record what AllocateNode this StoreStore protects so that
1513     // escape analysis can go from the MemBarStoreStoreNode to the
1514     // AllocateNode and eliminate the MemBarStoreStoreNode if possible
1515     // based on the escape status of the AllocateNode.
1516     insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
1517   }
1518   if (compress) {
1519     set_result(_gvn.transform(count));
1520   }
1521   clear_upper_avx();
1522 
1523   return true;
1524 }
1525 
1526 #ifdef _LP64
1527 #define XTOP ,top() /*additional argument*/
1528 #else  //_LP64
1529 #define XTOP        /*no additional argument*/
1530 #endif //_LP64
1531 
1532 //------------------------inline_string_toBytesU--------------------------
1533 // public static byte[] StringUTF16.toBytes(char[] value, int off, int len)
1534 bool LibraryCallKit::inline_string_toBytesU() {
1535   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1536     return false;
1537   }
1538   // Get the arguments.
1539   Node* value     = argument(0);
1540   Node* offset    = argument(1);
1541   Node* length    = argument(2);
1542 
1543   Node* newcopy = nullptr;
1544 
1545   // Set the original stack and the reexecute bit for the interpreter to reexecute
1546   // the bytecode that invokes StringUTF16.toBytes() if deoptimization happens.
1547   { PreserveReexecuteState preexecs(this);
1548     jvms()->set_should_reexecute(true);
1549 
1550     // Check if a null path was taken unconditionally.
1551     value = null_check(value);
1552 
1553     RegionNode* bailout = new RegionNode(1);
1554     record_for_igvn(bailout);
1555 
1556     // Range checks
1557     generate_negative_guard(offset, bailout);
1558     generate_negative_guard(length, bailout);
1559     generate_limit_guard(offset, length, load_array_length(value), bailout);
1560     // Make sure that resulting byte[] length does not overflow Integer.MAX_VALUE
1561     generate_limit_guard(length, intcon(0), intcon(max_jint/2), bailout);
1562 
1563     if (bailout->req() > 1) {
1564       PreserveJVMState pjvms(this);
1565       set_control(_gvn.transform(bailout));
1566       uncommon_trap(Deoptimization::Reason_intrinsic,
1567                     Deoptimization::Action_maybe_recompile);
1568     }
1569     if (stopped()) {
1570       return true;
1571     }
1572 
1573     Node* size = _gvn.transform(new LShiftINode(length, intcon(1)));
1574     Node* klass_node = makecon(TypeKlassPtr::make(ciTypeArrayKlass::make(T_BYTE)));
1575     newcopy = new_array(klass_node, size, 0);  // no arguments to push
1576     AllocateArrayNode* alloc = tightly_coupled_allocation(newcopy);
1577     guarantee(alloc != nullptr, "created above");
1578 
1579     // Calculate starting addresses.
1580     Node* src_start = array_element_address(value, offset, T_CHAR);
1581     Node* dst_start = basic_plus_adr(newcopy, arrayOopDesc::base_offset_in_bytes(T_BYTE));
1582 
1583     // Check if src array address is aligned to HeapWordSize (dst is always aligned)
1584     const TypeInt* toffset = gvn().type(offset)->is_int();
1585     bool aligned = toffset->is_con() && ((toffset->get_con() * type2aelembytes(T_CHAR)) % HeapWordSize == 0);
1586 
1587     // Figure out which arraycopy runtime method to call (disjoint, uninitialized).
1588     const char* copyfunc_name = "arraycopy";
1589     address     copyfunc_addr = StubRoutines::select_arraycopy_function(T_CHAR, aligned, true, copyfunc_name, true);
1590     Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
1591                       OptoRuntime::fast_arraycopy_Type(),
1592                       copyfunc_addr, copyfunc_name, TypeRawPtr::BOTTOM,
1593                       src_start, dst_start, ConvI2X(length) XTOP);
1594     // Do not let reads from the cloned object float above the arraycopy.
1595     if (alloc->maybe_set_complete(&_gvn)) {
1596       // "You break it, you buy it."
1597       InitializeNode* init = alloc->initialization();
1598       assert(init->is_complete(), "we just did this");
1599       init->set_complete_with_arraycopy();
1600       assert(newcopy->is_CheckCastPP(), "sanity");
1601       assert(newcopy->in(0)->in(0) == init, "dest pinned");
1602     }
1603     // Do not let stores that initialize this object be reordered with
1604     // a subsequent store that would make this object accessible by
1605     // other threads.
1606     // Record what AllocateNode this StoreStore protects so that
1607     // escape analysis can go from the MemBarStoreStoreNode to the
1608     // AllocateNode and eliminate the MemBarStoreStoreNode if possible
1609     // based on the escape status of the AllocateNode.
1610     insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
1611   } // original reexecute is set back here
1612 
1613   C->set_has_split_ifs(true); // Has chance for split-if optimization
1614   if (!stopped()) {
1615     set_result(newcopy);
1616   }
1617   clear_upper_avx();
1618 
1619   return true;
1620 }
1621 
1622 //------------------------inline_string_getCharsU--------------------------
1623 // public void StringUTF16.getChars(byte[] src, int srcBegin, int srcEnd, char dst[], int dstBegin)
1624 bool LibraryCallKit::inline_string_getCharsU() {
1625   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1626     return false;
1627   }
1628 
1629   // Get the arguments.
1630   Node* src       = argument(0);
1631   Node* src_begin = argument(1);
1632   Node* src_end   = argument(2); // exclusive offset (i < src_end)
1633   Node* dst       = argument(3);
1634   Node* dst_begin = argument(4);
1635 
1636   // Check for allocation before we add nodes that would confuse
1637   // tightly_coupled_allocation()
1638   AllocateArrayNode* alloc = tightly_coupled_allocation(dst);
1639 
1640   // Check if a null path was taken unconditionally.
1641   src = null_check(src);
1642   dst = null_check(dst);
1643   if (stopped()) {
1644     return true;
1645   }
1646 
1647   // Get length and convert char[] offset to byte[] offset
1648   Node* length = _gvn.transform(new SubINode(src_end, src_begin));
1649   src_begin = _gvn.transform(new LShiftINode(src_begin, intcon(1)));
1650 
1651   // Range checks
1652   generate_string_range_check(src, src_begin, length, true);
1653   generate_string_range_check(dst, dst_begin, length, false);
1654   if (stopped()) {
1655     return true;
1656   }
1657 
1658   if (!stopped()) {
1659     // Calculate starting addresses.
1660     Node* src_start = array_element_address(src, src_begin, T_BYTE);
1661     Node* dst_start = array_element_address(dst, dst_begin, T_CHAR);
1662 
1663     // Check if array addresses are aligned to HeapWordSize
1664     const TypeInt* tsrc = gvn().type(src_begin)->is_int();
1665     const TypeInt* tdst = gvn().type(dst_begin)->is_int();
1666     bool aligned = tsrc->is_con() && ((tsrc->get_con() * type2aelembytes(T_BYTE)) % HeapWordSize == 0) &&
1667                    tdst->is_con() && ((tdst->get_con() * type2aelembytes(T_CHAR)) % HeapWordSize == 0);
1668 
1669     // Figure out which arraycopy runtime method to call (disjoint, uninitialized).
1670     const char* copyfunc_name = "arraycopy";
1671     address     copyfunc_addr = StubRoutines::select_arraycopy_function(T_CHAR, aligned, true, copyfunc_name, true);
1672     Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
1673                       OptoRuntime::fast_arraycopy_Type(),
1674                       copyfunc_addr, copyfunc_name, TypeRawPtr::BOTTOM,
1675                       src_start, dst_start, ConvI2X(length) XTOP);
1676     // Do not let reads from the cloned object float above the arraycopy.
1677     if (alloc != nullptr) {
1678       if (alloc->maybe_set_complete(&_gvn)) {
1679         // "You break it, you buy it."
1680         InitializeNode* init = alloc->initialization();
1681         assert(init->is_complete(), "we just did this");
1682         init->set_complete_with_arraycopy();
1683         assert(dst->is_CheckCastPP(), "sanity");
1684         assert(dst->in(0)->in(0) == init, "dest pinned");
1685       }
1686       // Do not let stores that initialize this object be reordered with
1687       // a subsequent store that would make this object accessible by
1688       // other threads.
1689       // Record what AllocateNode this StoreStore protects so that
1690       // escape analysis can go from the MemBarStoreStoreNode to the
1691       // AllocateNode and eliminate the MemBarStoreStoreNode if possible
1692       // based on the escape status of the AllocateNode.
1693       insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
1694     } else {
1695       insert_mem_bar(Op_MemBarCPUOrder);
1696     }
1697   }
1698 
1699   C->set_has_split_ifs(true); // Has chance for split-if optimization
1700   return true;
1701 }
1702 
1703 //----------------------inline_string_char_access----------------------------
1704 // Store/Load char to/from byte[] array.
1705 // static void StringUTF16.putChar(byte[] val, int index, int c)
1706 // static char StringUTF16.getChar(byte[] val, int index)
1707 bool LibraryCallKit::inline_string_char_access(bool is_store) {
1708   Node* value  = argument(0);
1709   Node* index  = argument(1);
1710   Node* ch = is_store ? argument(2) : nullptr;
1711 
1712   // This intrinsic accesses byte[] array as char[] array. Computing the offsets
1713   // correctly requires matched array shapes.
1714   assert (arrayOopDesc::base_offset_in_bytes(T_CHAR) == arrayOopDesc::base_offset_in_bytes(T_BYTE),
1715           "sanity: byte[] and char[] bases agree");
1716   assert (type2aelembytes(T_CHAR) == type2aelembytes(T_BYTE)*2,
1717           "sanity: byte[] and char[] scales agree");
1718 
1719   // Bail when getChar over constants is requested: constant folding would
1720   // reject folding mismatched char access over byte[]. A normal inlining for getChar
1721   // Java method would constant fold nicely instead.
1722   if (!is_store && value->is_Con() && index->is_Con()) {
1723     return false;
1724   }
1725 
1726   // Save state and restore on bailout
1727   uint old_sp = sp();
1728   SafePointNode* old_map = clone_map();
1729 
1730   value = must_be_not_null(value, true);
1731 
1732   Node* adr = array_element_address(value, index, T_CHAR);
1733   if (adr->is_top()) {
1734     set_map(old_map);
1735     set_sp(old_sp);
1736     return false;
1737   }
1738   destruct_map_clone(old_map);
1739   if (is_store) {
1740     access_store_at(value, adr, TypeAryPtr::BYTES, ch, TypeInt::CHAR, T_CHAR, IN_HEAP | MO_UNORDERED | C2_MISMATCHED);
1741   } else {
1742     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);
1743     set_result(ch);
1744   }
1745   return true;
1746 }
1747 
1748 
1749 //------------------------------inline_math-----------------------------------
1750 // public static double Math.abs(double)
1751 // public static double Math.sqrt(double)
1752 // public static double Math.log(double)
1753 // public static double Math.log10(double)
1754 // public static double Math.round(double)
1755 bool LibraryCallKit::inline_double_math(vmIntrinsics::ID id) {
1756   Node* arg = argument(0);
1757   Node* n = nullptr;
1758   switch (id) {
1759   case vmIntrinsics::_dabs:   n = new AbsDNode(                arg);  break;
1760   case vmIntrinsics::_dsqrt:
1761   case vmIntrinsics::_dsqrt_strict:
1762                               n = new SqrtDNode(C, control(),  arg);  break;
1763   case vmIntrinsics::_ceil:   n = RoundDoubleModeNode::make(_gvn, arg, RoundDoubleModeNode::rmode_ceil); break;
1764   case vmIntrinsics::_floor:  n = RoundDoubleModeNode::make(_gvn, arg, RoundDoubleModeNode::rmode_floor); break;
1765   case vmIntrinsics::_rint:   n = RoundDoubleModeNode::make(_gvn, arg, RoundDoubleModeNode::rmode_rint); break;
1766   case vmIntrinsics::_roundD: n = new RoundDNode(arg); break;
1767   case vmIntrinsics::_dcopySign: n = CopySignDNode::make(_gvn, arg, argument(2)); break;
1768   case vmIntrinsics::_dsignum: n = SignumDNode::make(_gvn, arg); break;
1769   default:  fatal_unexpected_iid(id);  break;
1770   }
1771   set_result(_gvn.transform(n));
1772   return true;
1773 }
1774 
1775 //------------------------------inline_math-----------------------------------
1776 // public static float Math.abs(float)
1777 // public static int Math.abs(int)
1778 // public static long Math.abs(long)
1779 bool LibraryCallKit::inline_math(vmIntrinsics::ID id) {
1780   Node* arg = argument(0);
1781   Node* n = nullptr;
1782   switch (id) {
1783   case vmIntrinsics::_fabs:   n = new AbsFNode(                arg);  break;
1784   case vmIntrinsics::_iabs:   n = new AbsINode(                arg);  break;
1785   case vmIntrinsics::_labs:   n = new AbsLNode(                arg);  break;
1786   case vmIntrinsics::_fcopySign: n = new CopySignFNode(arg, argument(1)); break;
1787   case vmIntrinsics::_fsignum: n = SignumFNode::make(_gvn, arg); break;
1788   case vmIntrinsics::_roundF: n = new RoundFNode(arg); break;
1789   default:  fatal_unexpected_iid(id);  break;
1790   }
1791   set_result(_gvn.transform(n));
1792   return true;
1793 }
1794 
1795 //------------------------------runtime_math-----------------------------
1796 bool LibraryCallKit::runtime_math(const TypeFunc* call_type, address funcAddr, const char* funcName) {
1797   assert(call_type == OptoRuntime::Math_DD_D_Type() || call_type == OptoRuntime::Math_D_D_Type(),
1798          "must be (DD)D or (D)D type");
1799 
1800   // Inputs
1801   Node* a = argument(0);
1802   Node* b = (call_type == OptoRuntime::Math_DD_D_Type()) ? argument(2) : nullptr;
1803 
1804   const TypePtr* no_memory_effects = nullptr;
1805   Node* trig = make_runtime_call(RC_LEAF, call_type, funcAddr, funcName,
1806                                  no_memory_effects,
1807                                  a, top(), b, b ? top() : nullptr);
1808   Node* value = _gvn.transform(new ProjNode(trig, TypeFunc::Parms+0));
1809 #ifdef ASSERT
1810   Node* value_top = _gvn.transform(new ProjNode(trig, TypeFunc::Parms+1));
1811   assert(value_top == top(), "second value must be top");
1812 #endif
1813 
1814   set_result(value);
1815   return true;
1816 }
1817 
1818 //------------------------------inline_math_pow-----------------------------
1819 bool LibraryCallKit::inline_math_pow() {
1820   Node* exp = argument(2);
1821   const TypeD* d = _gvn.type(exp)->isa_double_constant();
1822   if (d != nullptr) {
1823     if (d->getd() == 2.0) {
1824       // Special case: pow(x, 2.0) => x * x
1825       Node* base = argument(0);
1826       set_result(_gvn.transform(new MulDNode(base, base)));
1827       return true;
1828     } else if (d->getd() == 0.5 && Matcher::match_rule_supported(Op_SqrtD)) {
1829       // Special case: pow(x, 0.5) => sqrt(x)
1830       Node* base = argument(0);
1831       Node* zero = _gvn.zerocon(T_DOUBLE);
1832 
1833       RegionNode* region = new RegionNode(3);
1834       Node* phi = new PhiNode(region, Type::DOUBLE);
1835 
1836       Node* cmp  = _gvn.transform(new CmpDNode(base, zero));
1837       // According to the API specs, pow(-0.0, 0.5) = 0.0 and sqrt(-0.0) = -0.0.
1838       // So pow(-0.0, 0.5) shouldn't be replaced with sqrt(-0.0).
1839       // -0.0/+0.0 are both excluded since floating-point comparison doesn't distinguish -0.0 from +0.0.
1840       Node* test = _gvn.transform(new BoolNode(cmp, BoolTest::le));
1841 
1842       Node* if_pow = generate_slow_guard(test, nullptr);
1843       Node* value_sqrt = _gvn.transform(new SqrtDNode(C, control(), base));
1844       phi->init_req(1, value_sqrt);
1845       region->init_req(1, control());
1846 
1847       if (if_pow != nullptr) {
1848         set_control(if_pow);
1849         address target = StubRoutines::dpow() != nullptr ? StubRoutines::dpow() :
1850                                                         CAST_FROM_FN_PTR(address, SharedRuntime::dpow);
1851         const TypePtr* no_memory_effects = nullptr;
1852         Node* trig = make_runtime_call(RC_LEAF, OptoRuntime::Math_DD_D_Type(), target, "POW",
1853                                        no_memory_effects, base, top(), exp, top());
1854         Node* value_pow = _gvn.transform(new ProjNode(trig, TypeFunc::Parms+0));
1855 #ifdef ASSERT
1856         Node* value_top = _gvn.transform(new ProjNode(trig, TypeFunc::Parms+1));
1857         assert(value_top == top(), "second value must be top");
1858 #endif
1859         phi->init_req(2, value_pow);
1860         region->init_req(2, _gvn.transform(new ProjNode(trig, TypeFunc::Control)));
1861       }
1862 
1863       C->set_has_split_ifs(true); // Has chance for split-if optimization
1864       set_control(_gvn.transform(region));
1865       record_for_igvn(region);
1866       set_result(_gvn.transform(phi));
1867 
1868       return true;
1869     }
1870   }
1871 
1872   return StubRoutines::dpow() != nullptr ?
1873     runtime_math(OptoRuntime::Math_DD_D_Type(), StubRoutines::dpow(),  "dpow") :
1874     runtime_math(OptoRuntime::Math_DD_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dpow),  "POW");
1875 }
1876 
1877 //------------------------------inline_math_native-----------------------------
1878 bool LibraryCallKit::inline_math_native(vmIntrinsics::ID id) {
1879   switch (id) {
1880   case vmIntrinsics::_dsin:
1881     return StubRoutines::dsin() != nullptr ?
1882       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dsin(), "dsin") :
1883       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dsin),   "SIN");
1884   case vmIntrinsics::_dcos:
1885     return StubRoutines::dcos() != nullptr ?
1886       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dcos(), "dcos") :
1887       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dcos),   "COS");
1888   case vmIntrinsics::_dtan:
1889     return StubRoutines::dtan() != nullptr ?
1890       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dtan(), "dtan") :
1891       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dtan), "TAN");
1892   case vmIntrinsics::_dtanh:
1893     return StubRoutines::dtanh() != nullptr ?
1894       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dtanh(), "dtanh") : false;
1895   case vmIntrinsics::_dexp:
1896     return StubRoutines::dexp() != nullptr ?
1897       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dexp(),  "dexp") :
1898       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dexp),  "EXP");
1899   case vmIntrinsics::_dlog:
1900     return StubRoutines::dlog() != nullptr ?
1901       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dlog(), "dlog") :
1902       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dlog),   "LOG");
1903   case vmIntrinsics::_dlog10:
1904     return StubRoutines::dlog10() != nullptr ?
1905       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dlog10(), "dlog10") :
1906       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dlog10), "LOG10");
1907 
1908   case vmIntrinsics::_roundD: return Matcher::match_rule_supported(Op_RoundD) ? inline_double_math(id) : false;
1909   case vmIntrinsics::_ceil:
1910   case vmIntrinsics::_floor:
1911   case vmIntrinsics::_rint:   return Matcher::match_rule_supported(Op_RoundDoubleMode) ? inline_double_math(id) : false;
1912 
1913   case vmIntrinsics::_dsqrt:
1914   case vmIntrinsics::_dsqrt_strict:
1915                               return Matcher::match_rule_supported(Op_SqrtD) ? inline_double_math(id) : false;
1916   case vmIntrinsics::_dabs:   return Matcher::has_match_rule(Op_AbsD)   ? inline_double_math(id) : false;
1917   case vmIntrinsics::_fabs:   return Matcher::match_rule_supported(Op_AbsF)   ? inline_math(id) : false;
1918   case vmIntrinsics::_iabs:   return Matcher::match_rule_supported(Op_AbsI)   ? inline_math(id) : false;
1919   case vmIntrinsics::_labs:   return Matcher::match_rule_supported(Op_AbsL)   ? inline_math(id) : false;
1920 
1921   case vmIntrinsics::_dpow:      return inline_math_pow();
1922   case vmIntrinsics::_dcopySign: return inline_double_math(id);
1923   case vmIntrinsics::_fcopySign: return inline_math(id);
1924   case vmIntrinsics::_dsignum: return Matcher::match_rule_supported(Op_SignumD) ? inline_double_math(id) : false;
1925   case vmIntrinsics::_fsignum: return Matcher::match_rule_supported(Op_SignumF) ? inline_math(id) : false;
1926   case vmIntrinsics::_roundF: return Matcher::match_rule_supported(Op_RoundF) ? inline_math(id) : false;
1927 
1928    // These intrinsics are not yet correctly implemented
1929   case vmIntrinsics::_datan2:
1930     return false;
1931 
1932   default:
1933     fatal_unexpected_iid(id);
1934     return false;
1935   }
1936 }
1937 
1938 //----------------------------inline_notify-----------------------------------*
1939 bool LibraryCallKit::inline_notify(vmIntrinsics::ID id) {
1940   const TypeFunc* ftype = OptoRuntime::monitor_notify_Type();
1941   address func;
1942   if (id == vmIntrinsics::_notify) {
1943     func = OptoRuntime::monitor_notify_Java();
1944   } else {
1945     func = OptoRuntime::monitor_notifyAll_Java();
1946   }
1947   Node* call = make_runtime_call(RC_NO_LEAF, ftype, func, nullptr, TypeRawPtr::BOTTOM, argument(0));
1948   make_slow_call_ex(call, env()->Throwable_klass(), false);
1949   return true;
1950 }
1951 
1952 
1953 //----------------------------inline_min_max-----------------------------------
1954 bool LibraryCallKit::inline_min_max(vmIntrinsics::ID id) {
1955   Node* a = nullptr;
1956   Node* b = nullptr;
1957   Node* n = nullptr;
1958   switch (id) {
1959     case vmIntrinsics::_min:
1960     case vmIntrinsics::_max:
1961     case vmIntrinsics::_minF:
1962     case vmIntrinsics::_maxF:
1963     case vmIntrinsics::_minF_strict:
1964     case vmIntrinsics::_maxF_strict:
1965     case vmIntrinsics::_min_strict:
1966     case vmIntrinsics::_max_strict:
1967       assert(callee()->signature()->size() == 2, "minF/maxF has 2 parameters of size 1 each.");
1968       a = argument(0);
1969       b = argument(1);
1970       break;
1971     case vmIntrinsics::_minD:
1972     case vmIntrinsics::_maxD:
1973     case vmIntrinsics::_minD_strict:
1974     case vmIntrinsics::_maxD_strict:
1975       assert(callee()->signature()->size() == 4, "minD/maxD has 2 parameters of size 2 each.");
1976       a = argument(0);
1977       b = argument(2);
1978       break;
1979     case vmIntrinsics::_minL:
1980     case vmIntrinsics::_maxL:
1981       assert(callee()->signature()->size() == 4, "minL/maxL has 2 parameters of size 2 each.");
1982       a = argument(0);
1983       b = argument(2);
1984       break;
1985     default:
1986       fatal_unexpected_iid(id);
1987       break;
1988   }
1989 
1990   switch (id) {
1991     case vmIntrinsics::_min:
1992     case vmIntrinsics::_min_strict:
1993       n = new MinINode(a, b);
1994       break;
1995     case vmIntrinsics::_max:
1996     case vmIntrinsics::_max_strict:
1997       n = new MaxINode(a, b);
1998       break;
1999     case vmIntrinsics::_minF:
2000     case vmIntrinsics::_minF_strict:
2001       n = new MinFNode(a, b);
2002       break;
2003     case vmIntrinsics::_maxF:
2004     case vmIntrinsics::_maxF_strict:
2005       n = new MaxFNode(a, b);
2006       break;
2007     case vmIntrinsics::_minD:
2008     case vmIntrinsics::_minD_strict:
2009       n = new MinDNode(a, b);
2010       break;
2011     case vmIntrinsics::_maxD:
2012     case vmIntrinsics::_maxD_strict:
2013       n = new MaxDNode(a, b);
2014       break;
2015     case vmIntrinsics::_minL:
2016       n = new MinLNode(_gvn.C, a, b);
2017       break;
2018     case vmIntrinsics::_maxL:
2019       n = new MaxLNode(_gvn.C, a, b);
2020       break;
2021     default:
2022       fatal_unexpected_iid(id);
2023       break;
2024   }
2025 
2026   set_result(_gvn.transform(n));
2027   return true;
2028 }
2029 
2030 bool LibraryCallKit::inline_math_mathExact(Node* math, Node* test) {
2031   if (builtin_throw_too_many_traps(Deoptimization::Reason_intrinsic,
2032                                    env()->ArithmeticException_instance())) {
2033     // It has been already too many times, but we cannot use builtin_throw (e.g. we care about backtraces),
2034     // so let's bail out intrinsic rather than risking deopting again.
2035     return false;
2036   }
2037 
2038   Node* bol = _gvn.transform( new BoolNode(test, BoolTest::overflow) );
2039   IfNode* check = create_and_map_if(control(), bol, PROB_UNLIKELY_MAG(3), COUNT_UNKNOWN);
2040   Node* fast_path = _gvn.transform( new IfFalseNode(check));
2041   Node* slow_path = _gvn.transform( new IfTrueNode(check) );
2042 
2043   {
2044     PreserveJVMState pjvms(this);
2045     PreserveReexecuteState preexecs(this);
2046     jvms()->set_should_reexecute(true);
2047 
2048     set_control(slow_path);
2049     set_i_o(i_o());
2050 
2051     builtin_throw(Deoptimization::Reason_intrinsic,
2052                   env()->ArithmeticException_instance(),
2053                   /*allow_too_many_traps*/ false);
2054   }
2055 
2056   set_control(fast_path);
2057   set_result(math);
2058   return true;
2059 }
2060 
2061 template <typename OverflowOp>
2062 bool LibraryCallKit::inline_math_overflow(Node* arg1, Node* arg2) {
2063   typedef typename OverflowOp::MathOp MathOp;
2064 
2065   MathOp* mathOp = new MathOp(arg1, arg2);
2066   Node* operation = _gvn.transform( mathOp );
2067   Node* ofcheck = _gvn.transform( new OverflowOp(arg1, arg2) );
2068   return inline_math_mathExact(operation, ofcheck);
2069 }
2070 
2071 bool LibraryCallKit::inline_math_addExactI(bool is_increment) {
2072   return inline_math_overflow<OverflowAddINode>(argument(0), is_increment ? intcon(1) : argument(1));
2073 }
2074 
2075 bool LibraryCallKit::inline_math_addExactL(bool is_increment) {
2076   return inline_math_overflow<OverflowAddLNode>(argument(0), is_increment ? longcon(1) : argument(2));
2077 }
2078 
2079 bool LibraryCallKit::inline_math_subtractExactI(bool is_decrement) {
2080   return inline_math_overflow<OverflowSubINode>(argument(0), is_decrement ? intcon(1) : argument(1));
2081 }
2082 
2083 bool LibraryCallKit::inline_math_subtractExactL(bool is_decrement) {
2084   return inline_math_overflow<OverflowSubLNode>(argument(0), is_decrement ? longcon(1) : argument(2));
2085 }
2086 
2087 bool LibraryCallKit::inline_math_negateExactI() {
2088   return inline_math_overflow<OverflowSubINode>(intcon(0), argument(0));
2089 }
2090 
2091 bool LibraryCallKit::inline_math_negateExactL() {
2092   return inline_math_overflow<OverflowSubLNode>(longcon(0), argument(0));
2093 }
2094 
2095 bool LibraryCallKit::inline_math_multiplyExactI() {
2096   return inline_math_overflow<OverflowMulINode>(argument(0), argument(1));
2097 }
2098 
2099 bool LibraryCallKit::inline_math_multiplyExactL() {
2100   return inline_math_overflow<OverflowMulLNode>(argument(0), argument(2));
2101 }
2102 
2103 bool LibraryCallKit::inline_math_multiplyHigh() {
2104   set_result(_gvn.transform(new MulHiLNode(argument(0), argument(2))));
2105   return true;
2106 }
2107 
2108 bool LibraryCallKit::inline_math_unsignedMultiplyHigh() {
2109   set_result(_gvn.transform(new UMulHiLNode(argument(0), argument(2))));
2110   return true;
2111 }
2112 
2113 inline int
2114 LibraryCallKit::classify_unsafe_addr(Node* &base, Node* &offset, BasicType type) {
2115   const TypePtr* base_type = TypePtr::NULL_PTR;
2116   if (base != nullptr)  base_type = _gvn.type(base)->isa_ptr();
2117   if (base_type == nullptr) {
2118     // Unknown type.
2119     return Type::AnyPtr;
2120   } else if (_gvn.type(base->uncast()) == TypePtr::NULL_PTR) {
2121     // Since this is a null+long form, we have to switch to a rawptr.
2122     base   = _gvn.transform(new CastX2PNode(offset));
2123     offset = MakeConX(0);
2124     return Type::RawPtr;
2125   } else if (base_type->base() == Type::RawPtr) {
2126     return Type::RawPtr;
2127   } else if (base_type->isa_oopptr()) {
2128     // Base is never null => always a heap address.
2129     if (!TypePtr::NULL_PTR->higher_equal(base_type)) {
2130       return Type::OopPtr;
2131     }
2132     // Offset is small => always a heap address.
2133     const TypeX* offset_type = _gvn.type(offset)->isa_intptr_t();
2134     if (offset_type != nullptr &&
2135         base_type->offset() == 0 &&     // (should always be?)
2136         offset_type->_lo >= 0 &&
2137         !MacroAssembler::needs_explicit_null_check(offset_type->_hi)) {
2138       return Type::OopPtr;
2139     } else if (type == T_OBJECT) {
2140       // off heap access to an oop doesn't make any sense. Has to be on
2141       // heap.
2142       return Type::OopPtr;
2143     }
2144     // Otherwise, it might either be oop+off or null+addr.
2145     return Type::AnyPtr;
2146   } else {
2147     // No information:
2148     return Type::AnyPtr;
2149   }
2150 }
2151 
2152 Node* LibraryCallKit::make_unsafe_address(Node*& base, Node* offset, BasicType type, bool can_cast) {
2153   Node* uncasted_base = base;
2154   int kind = classify_unsafe_addr(uncasted_base, offset, type);
2155   if (kind == Type::RawPtr) {
2156     return basic_plus_adr(top(), uncasted_base, offset);
2157   } else if (kind == Type::AnyPtr) {
2158     assert(base == uncasted_base, "unexpected base change");
2159     if (can_cast) {
2160       if (!_gvn.type(base)->speculative_maybe_null() &&
2161           !too_many_traps(Deoptimization::Reason_speculate_null_check)) {
2162         // According to profiling, this access is always on
2163         // heap. Casting the base to not null and thus avoiding membars
2164         // around the access should allow better optimizations
2165         Node* null_ctl = top();
2166         base = null_check_oop(base, &null_ctl, true, true, true);
2167         assert(null_ctl->is_top(), "no null control here");
2168         return basic_plus_adr(base, offset);
2169       } else if (_gvn.type(base)->speculative_always_null() &&
2170                  !too_many_traps(Deoptimization::Reason_speculate_null_assert)) {
2171         // According to profiling, this access is always off
2172         // heap.
2173         base = null_assert(base);
2174         Node* raw_base = _gvn.transform(new CastX2PNode(offset));
2175         offset = MakeConX(0);
2176         return basic_plus_adr(top(), raw_base, offset);
2177       }
2178     }
2179     // We don't know if it's an on heap or off heap access. Fall back
2180     // to raw memory access.
2181     Node* raw = _gvn.transform(new CheckCastPPNode(control(), base, TypeRawPtr::BOTTOM));
2182     return basic_plus_adr(top(), raw, offset);
2183   } else {
2184     assert(base == uncasted_base, "unexpected base change");
2185     // We know it's an on heap access so base can't be null
2186     if (TypePtr::NULL_PTR->higher_equal(_gvn.type(base))) {
2187       base = must_be_not_null(base, true);
2188     }
2189     return basic_plus_adr(base, offset);
2190   }
2191 }
2192 
2193 //--------------------------inline_number_methods-----------------------------
2194 // inline int     Integer.numberOfLeadingZeros(int)
2195 // inline int        Long.numberOfLeadingZeros(long)
2196 //
2197 // inline int     Integer.numberOfTrailingZeros(int)
2198 // inline int        Long.numberOfTrailingZeros(long)
2199 //
2200 // inline int     Integer.bitCount(int)
2201 // inline int        Long.bitCount(long)
2202 //
2203 // inline char  Character.reverseBytes(char)
2204 // inline short     Short.reverseBytes(short)
2205 // inline int     Integer.reverseBytes(int)
2206 // inline long       Long.reverseBytes(long)
2207 bool LibraryCallKit::inline_number_methods(vmIntrinsics::ID id) {
2208   Node* arg = argument(0);
2209   Node* n = nullptr;
2210   switch (id) {
2211   case vmIntrinsics::_numberOfLeadingZeros_i:   n = new CountLeadingZerosINode( arg); break;
2212   case vmIntrinsics::_numberOfLeadingZeros_l:   n = new CountLeadingZerosLNode( arg); break;
2213   case vmIntrinsics::_numberOfTrailingZeros_i:  n = new CountTrailingZerosINode(arg); break;
2214   case vmIntrinsics::_numberOfTrailingZeros_l:  n = new CountTrailingZerosLNode(arg); break;
2215   case vmIntrinsics::_bitCount_i:               n = new PopCountINode(          arg); break;
2216   case vmIntrinsics::_bitCount_l:               n = new PopCountLNode(          arg); break;
2217   case vmIntrinsics::_reverseBytes_c:           n = new ReverseBytesUSNode(     arg); break;
2218   case vmIntrinsics::_reverseBytes_s:           n = new ReverseBytesSNode(      arg); break;
2219   case vmIntrinsics::_reverseBytes_i:           n = new ReverseBytesINode(      arg); break;
2220   case vmIntrinsics::_reverseBytes_l:           n = new ReverseBytesLNode(      arg); break;
2221   case vmIntrinsics::_reverse_i:                n = new ReverseINode(           arg); break;
2222   case vmIntrinsics::_reverse_l:                n = new ReverseLNode(           arg); break;
2223   default:  fatal_unexpected_iid(id);  break;
2224   }
2225   set_result(_gvn.transform(n));
2226   return true;
2227 }
2228 
2229 //--------------------------inline_bitshuffle_methods-----------------------------
2230 // inline int Integer.compress(int, int)
2231 // inline int Integer.expand(int, int)
2232 // inline long Long.compress(long, long)
2233 // inline long Long.expand(long, long)
2234 bool LibraryCallKit::inline_bitshuffle_methods(vmIntrinsics::ID id) {
2235   Node* n = nullptr;
2236   switch (id) {
2237     case vmIntrinsics::_compress_i:  n = new CompressBitsNode(argument(0), argument(1), TypeInt::INT); break;
2238     case vmIntrinsics::_expand_i:    n = new ExpandBitsNode(argument(0),  argument(1), TypeInt::INT); break;
2239     case vmIntrinsics::_compress_l:  n = new CompressBitsNode(argument(0), argument(2), TypeLong::LONG); break;
2240     case vmIntrinsics::_expand_l:    n = new ExpandBitsNode(argument(0), argument(2), TypeLong::LONG); break;
2241     default:  fatal_unexpected_iid(id);  break;
2242   }
2243   set_result(_gvn.transform(n));
2244   return true;
2245 }
2246 
2247 //--------------------------inline_number_methods-----------------------------
2248 // inline int Integer.compareUnsigned(int, int)
2249 // inline int    Long.compareUnsigned(long, long)
2250 bool LibraryCallKit::inline_compare_unsigned(vmIntrinsics::ID id) {
2251   Node* arg1 = argument(0);
2252   Node* arg2 = (id == vmIntrinsics::_compareUnsigned_l) ? argument(2) : argument(1);
2253   Node* n = nullptr;
2254   switch (id) {
2255     case vmIntrinsics::_compareUnsigned_i:   n = new CmpU3Node(arg1, arg2);  break;
2256     case vmIntrinsics::_compareUnsigned_l:   n = new CmpUL3Node(arg1, arg2); break;
2257     default:  fatal_unexpected_iid(id);  break;
2258   }
2259   set_result(_gvn.transform(n));
2260   return true;
2261 }
2262 
2263 //--------------------------inline_unsigned_divmod_methods-----------------------------
2264 // inline int Integer.divideUnsigned(int, int)
2265 // inline int Integer.remainderUnsigned(int, int)
2266 // inline long Long.divideUnsigned(long, long)
2267 // inline long Long.remainderUnsigned(long, long)
2268 bool LibraryCallKit::inline_divmod_methods(vmIntrinsics::ID id) {
2269   Node* n = nullptr;
2270   switch (id) {
2271     case vmIntrinsics::_divideUnsigned_i: {
2272       zero_check_int(argument(1));
2273       // Compile-time detect of null-exception
2274       if (stopped()) {
2275         return true; // keep the graph constructed so far
2276       }
2277       n = new UDivINode(control(), argument(0), argument(1));
2278       break;
2279     }
2280     case vmIntrinsics::_divideUnsigned_l: {
2281       zero_check_long(argument(2));
2282       // Compile-time detect of null-exception
2283       if (stopped()) {
2284         return true; // keep the graph constructed so far
2285       }
2286       n = new UDivLNode(control(), argument(0), argument(2));
2287       break;
2288     }
2289     case vmIntrinsics::_remainderUnsigned_i: {
2290       zero_check_int(argument(1));
2291       // Compile-time detect of null-exception
2292       if (stopped()) {
2293         return true; // keep the graph constructed so far
2294       }
2295       n = new UModINode(control(), argument(0), argument(1));
2296       break;
2297     }
2298     case vmIntrinsics::_remainderUnsigned_l: {
2299       zero_check_long(argument(2));
2300       // Compile-time detect of null-exception
2301       if (stopped()) {
2302         return true; // keep the graph constructed so far
2303       }
2304       n = new UModLNode(control(), argument(0), argument(2));
2305       break;
2306     }
2307     default:  fatal_unexpected_iid(id);  break;
2308   }
2309   set_result(_gvn.transform(n));
2310   return true;
2311 }
2312 
2313 //----------------------------inline_unsafe_access----------------------------
2314 
2315 const TypeOopPtr* LibraryCallKit::sharpen_unsafe_type(Compile::AliasType* alias_type, const TypePtr *adr_type) {
2316   // Attempt to infer a sharper value type from the offset and base type.
2317   ciKlass* sharpened_klass = nullptr;
2318   bool null_free = false;
2319 
2320   // See if it is an instance field, with an object type.
2321   if (alias_type->field() != nullptr) {
2322     if (alias_type->field()->type()->is_klass()) {
2323       sharpened_klass = alias_type->field()->type()->as_klass();
2324       null_free = alias_type->field()->is_null_free();
2325     }
2326   }
2327 
2328   const TypeOopPtr* result = nullptr;
2329   // See if it is a narrow oop array.
2330   if (adr_type->isa_aryptr()) {
2331     if (adr_type->offset() >= objArrayOopDesc::base_offset_in_bytes()) {
2332       const TypeOopPtr* elem_type = adr_type->is_aryptr()->elem()->make_oopptr();
2333       null_free = adr_type->is_aryptr()->is_null_free();
2334       if (elem_type != nullptr && elem_type->is_loaded()) {
2335         // Sharpen the value type.
2336         result = elem_type;
2337       }
2338     }
2339   }
2340 
2341   // The sharpened class might be unloaded if there is no class loader
2342   // contraint in place.
2343   if (result == nullptr && sharpened_klass != nullptr && sharpened_klass->is_loaded()) {
2344     // Sharpen the value type.
2345     result = TypeOopPtr::make_from_klass(sharpened_klass);
2346     if (null_free) {
2347       result = result->join_speculative(TypePtr::NOTNULL)->is_oopptr();
2348     }
2349   }
2350   if (result != nullptr) {
2351 #ifndef PRODUCT
2352     if (C->print_intrinsics() || C->print_inlining()) {
2353       tty->print("  from base type:  ");  adr_type->dump(); tty->cr();
2354       tty->print("  sharpened value: ");  result->dump();    tty->cr();
2355     }
2356 #endif
2357   }
2358   return result;
2359 }
2360 
2361 DecoratorSet LibraryCallKit::mo_decorator_for_access_kind(AccessKind kind) {
2362   switch (kind) {
2363       case Relaxed:
2364         return MO_UNORDERED;
2365       case Opaque:
2366         return MO_RELAXED;
2367       case Acquire:
2368         return MO_ACQUIRE;
2369       case Release:
2370         return MO_RELEASE;
2371       case Volatile:
2372         return MO_SEQ_CST;
2373       default:
2374         ShouldNotReachHere();
2375         return 0;
2376   }
2377 }
2378 
2379 bool LibraryCallKit::inline_unsafe_access(bool is_store, const BasicType type, const AccessKind kind, const bool unaligned, const bool is_flat) {
2380   if (callee()->is_static())  return false;  // caller must have the capability!
2381   DecoratorSet decorators = C2_UNSAFE_ACCESS;
2382   guarantee(!is_store || kind != Acquire, "Acquire accesses can be produced only for loads");
2383   guarantee( is_store || kind != Release, "Release accesses can be produced only for stores");
2384   assert(type != T_OBJECT || !unaligned, "unaligned access not supported with object type");
2385 
2386   if (is_reference_type(type)) {
2387     decorators |= ON_UNKNOWN_OOP_REF;
2388   }
2389 
2390   if (unaligned) {
2391     decorators |= C2_UNALIGNED;
2392   }
2393 
2394 #ifndef PRODUCT
2395   {
2396     ResourceMark rm;
2397     // Check the signatures.
2398     ciSignature* sig = callee()->signature();
2399 #ifdef ASSERT
2400     if (!is_store) {
2401       // Object getReference(Object base, int/long offset), etc.
2402       BasicType rtype = sig->return_type()->basic_type();
2403       assert(rtype == type, "getter must return the expected value");
2404       assert(sig->count() == 2 || (is_flat && sig->count() == 3), "oop getter has 2 or 3 arguments");
2405       assert(sig->type_at(0)->basic_type() == T_OBJECT, "getter base is object");
2406       assert(sig->type_at(1)->basic_type() == T_LONG, "getter offset is correct");
2407     } else {
2408       // void putReference(Object base, int/long offset, Object x), etc.
2409       assert(sig->return_type()->basic_type() == T_VOID, "putter must not return a value");
2410       assert(sig->count() == 3 || (is_flat && sig->count() == 4), "oop putter has 3 arguments");
2411       assert(sig->type_at(0)->basic_type() == T_OBJECT, "putter base is object");
2412       assert(sig->type_at(1)->basic_type() == T_LONG, "putter offset is correct");
2413       BasicType vtype = sig->type_at(sig->count()-1)->basic_type();
2414       assert(vtype == type, "putter must accept the expected value");
2415     }
2416 #endif // ASSERT
2417  }
2418 #endif //PRODUCT
2419 
2420   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
2421 
2422   Node* receiver = argument(0);  // type: oop
2423 
2424   // Build address expression.
2425   Node* heap_base_oop = top();
2426 
2427   // The base is either a Java object or a value produced by Unsafe.staticFieldBase
2428   Node* base = argument(1);  // type: oop
2429   // The offset is a value produced by Unsafe.staticFieldOffset or Unsafe.objectFieldOffset
2430   Node* offset = argument(2);  // type: long
2431   // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
2432   // to be plain byte offsets, which are also the same as those accepted
2433   // by oopDesc::field_addr.
2434   assert(Unsafe_field_offset_to_byte_offset(11) == 11,
2435          "fieldOffset must be byte-scaled");
2436 
2437   ciInlineKlass* inline_klass = nullptr;
2438   if (is_flat) {
2439     const TypeInstPtr* cls = _gvn.type(argument(4))->isa_instptr();
2440     if (cls == nullptr || cls->const_oop() == nullptr) {
2441       return false;
2442     }
2443     ciType* mirror_type = cls->const_oop()->as_instance()->java_mirror_type();
2444     if (!mirror_type->is_inlinetype()) {
2445       return false;
2446     }
2447     inline_klass = mirror_type->as_inline_klass();
2448   }
2449 
2450   if (base->is_InlineType()) {
2451     assert(!is_store, "InlineTypeNodes are non-larval value objects");
2452     InlineTypeNode* vt = base->as_InlineType();
2453     if (offset->is_Con()) {
2454       long off = find_long_con(offset, 0);
2455       ciInlineKlass* vk = vt->type()->inline_klass();
2456       if ((long)(int)off != off || !vk->contains_field_offset(off)) {
2457         return false;
2458       }
2459 
2460       ciField* field = vk->get_non_flat_field_by_offset(off);
2461       if (field != nullptr) {
2462         BasicType bt = type2field[field->type()->basic_type()];
2463         if (bt == T_ARRAY || bt == T_NARROWOOP) {
2464           bt = T_OBJECT;
2465         }
2466         if (bt == type && (!field->is_flat() || field->type() == inline_klass)) {
2467           Node* value = vt->field_value_by_offset(off, false);
2468           if (value->is_InlineType()) {
2469             value = value->as_InlineType()->adjust_scalarization_depth(this);
2470           }
2471           set_result(value);
2472           return true;
2473         }
2474       }
2475     }
2476     {
2477       // Re-execute the unsafe access if allocation triggers deoptimization.
2478       PreserveReexecuteState preexecs(this);
2479       jvms()->set_should_reexecute(true);
2480       vt = vt->buffer(this);
2481     }
2482     base = vt->get_oop();
2483   }
2484 
2485   // 32-bit machines ignore the high half!
2486   offset = ConvL2X(offset);
2487 
2488   // Save state and restore on bailout
2489   uint old_sp = sp();
2490   SafePointNode* old_map = clone_map();
2491 
2492   Node* adr = make_unsafe_address(base, offset, type, kind == Relaxed);
2493   assert(!stopped(), "Inlining of unsafe access failed: address construction stopped unexpectedly");
2494 
2495   if (_gvn.type(base->uncast())->isa_ptr() == TypePtr::NULL_PTR) {
2496     if (type != T_OBJECT && (inline_klass == nullptr || !inline_klass->has_object_fields())) {
2497       decorators |= IN_NATIVE; // off-heap primitive access
2498     } else {
2499       set_map(old_map);
2500       set_sp(old_sp);
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 + (is_flat ? 1 : 0)) : nullptr;
2515 
2516   const TypePtr* adr_type = _gvn.type(adr)->isa_ptr();
2517   if (adr_type == TypePtr::NULL_PTR) {
2518     set_map(old_map);
2519     set_sp(old_sp);
2520     return false; // off-heap access with zero address
2521   }
2522 
2523   // Try to categorize the address.
2524   Compile::AliasType* alias_type = C->alias_type(adr_type);
2525   assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
2526 
2527   if (alias_type->adr_type() == TypeInstPtr::KLASS ||
2528       alias_type->adr_type() == TypeAryPtr::RANGE) {
2529     set_map(old_map);
2530     set_sp(old_sp);
2531     return false; // not supported
2532   }
2533 
2534   bool mismatched = false;
2535   BasicType bt = T_ILLEGAL;
2536   ciField* field = nullptr;
2537   if (adr_type->isa_instptr()) {
2538     const TypeInstPtr* instptr = adr_type->is_instptr();
2539     ciInstanceKlass* k = instptr->instance_klass();
2540     int off = instptr->offset();
2541     if (instptr->const_oop() != nullptr &&
2542         k == ciEnv::current()->Class_klass() &&
2543         instptr->offset() >= (k->size_helper() * wordSize)) {
2544       k = instptr->const_oop()->as_instance()->java_lang_Class_klass()->as_instance_klass();
2545       field = k->get_field_by_offset(off, true);
2546     } else {
2547       field = k->get_non_flat_field_by_offset(off);
2548     }
2549     if (field != nullptr) {
2550       bt = type2field[field->type()->basic_type()];
2551     }
2552     if (bt != alias_type->basic_type()) {
2553       // Type mismatch. Is it an access to a nested flat field?
2554       field = k->get_field_by_offset(off, false);
2555       if (field != nullptr) {
2556         bt = type2field[field->type()->basic_type()];
2557       }
2558     }
2559     assert(bt == alias_type->basic_type() || is_flat, "should match");
2560   } else {
2561     bt = alias_type->basic_type();
2562   }
2563 
2564   if (bt != T_ILLEGAL) {
2565     assert(alias_type->adr_type()->is_oopptr(), "should be on-heap access");
2566     if (bt == T_BYTE && adr_type->isa_aryptr()) {
2567       // Alias type doesn't differentiate between byte[] and boolean[]).
2568       // Use address type to get the element type.
2569       bt = adr_type->is_aryptr()->elem()->array_element_basic_type();
2570     }
2571     if (is_reference_type(bt, true)) {
2572       // accessing an array field with getReference is not a mismatch
2573       bt = T_OBJECT;
2574     }
2575     if ((bt == T_OBJECT) != (type == T_OBJECT)) {
2576       // Don't intrinsify mismatched object accesses
2577       set_map(old_map);
2578       set_sp(old_sp);
2579       return false;
2580     }
2581     mismatched = (bt != type);
2582   } else if (alias_type->adr_type()->isa_oopptr()) {
2583     mismatched = true; // conservatively mark all "wide" on-heap accesses as mismatched
2584   }
2585 
2586   if (is_flat) {
2587     if (adr_type->isa_instptr()) {
2588       if (field == nullptr || field->type() != inline_klass) {
2589         mismatched = true;
2590       }
2591     } else if (adr_type->isa_aryptr()) {
2592       const Type* elem = adr_type->is_aryptr()->elem();
2593       if (!adr_type->is_flat() || elem->inline_klass() != inline_klass) {
2594         mismatched = true;
2595       }
2596     } else {
2597       mismatched = true;
2598     }
2599     if (is_store) {
2600       const Type* val_t = _gvn.type(val);
2601       if (!val_t->is_inlinetypeptr() || val_t->inline_klass() != inline_klass) {
2602         set_map(old_map);
2603         set_sp(old_sp);
2604         return false;
2605       }
2606     }
2607   }
2608 
2609   destruct_map_clone(old_map);
2610   assert(!mismatched || is_flat || alias_type->adr_type()->is_oopptr(), "off-heap access can't be mismatched");
2611 
2612   if (mismatched) {
2613     decorators |= C2_MISMATCHED;
2614   }
2615 
2616   // First guess at the value type.
2617   const Type *value_type = Type::get_const_basic_type(type);
2618 
2619   // Figure out the memory ordering.
2620   decorators |= mo_decorator_for_access_kind(kind);
2621 
2622   if (!is_store) {
2623     if (type == T_OBJECT && !is_flat) {
2624       const TypeOopPtr* tjp = sharpen_unsafe_type(alias_type, adr_type);
2625       if (tjp != nullptr) {
2626         value_type = tjp;
2627       }
2628     }
2629   }
2630 
2631   receiver = null_check(receiver);
2632   if (stopped()) {
2633     return true;
2634   }
2635   // Heap pointers get a null-check from the interpreter,
2636   // as a courtesy.  However, this is not guaranteed by Unsafe,
2637   // and it is not possible to fully distinguish unintended nulls
2638   // from intended ones in this API.
2639 
2640   if (!is_store) {
2641     Node* p = nullptr;
2642     // Try to constant fold a load from a constant field
2643 
2644     if (heap_base_oop != top() && field != nullptr && field->is_constant() && !field->is_flat() && !mismatched) {
2645       // final or stable field
2646       p = make_constant_from_field(field, heap_base_oop);
2647     }
2648 
2649     if (p == nullptr) { // Could not constant fold the load
2650       if (is_flat) {
2651         p = InlineTypeNode::make_from_flat(this, inline_klass, base, adr, adr_type, false, false, true);
2652       } else {
2653         p = access_load_at(heap_base_oop, adr, adr_type, value_type, type, decorators);
2654         const TypeOopPtr* ptr = value_type->make_oopptr();
2655         if (ptr != nullptr && ptr->is_inlinetypeptr()) {
2656           // Load a non-flattened inline type from memory
2657           p = InlineTypeNode::make_from_oop(this, p, ptr->inline_klass());
2658         }
2659       }
2660       // Normalize the value returned by getBoolean in the following cases
2661       if (type == T_BOOLEAN &&
2662           (mismatched ||
2663            heap_base_oop == top() ||                  // - heap_base_oop is null or
2664            (can_access_non_heap && field == nullptr)) // - heap_base_oop is potentially null
2665                                                       //   and the unsafe access is made to large offset
2666                                                       //   (i.e., larger than the maximum offset necessary for any
2667                                                       //   field access)
2668             ) {
2669           IdealKit ideal = IdealKit(this);
2670 #define __ ideal.
2671           IdealVariable normalized_result(ideal);
2672           __ declarations_done();
2673           __ set(normalized_result, p);
2674           __ if_then(p, BoolTest::ne, ideal.ConI(0));
2675           __ set(normalized_result, ideal.ConI(1));
2676           ideal.end_if();
2677           final_sync(ideal);
2678           p = __ value(normalized_result);
2679 #undef __
2680       }
2681     }
2682     if (type == T_ADDRESS) {
2683       p = gvn().transform(new CastP2XNode(nullptr, p));
2684       p = ConvX2UL(p);
2685     }
2686     // The load node has the control of the preceding MemBarCPUOrder.  All
2687     // following nodes will have the control of the MemBarCPUOrder inserted at
2688     // the end of this method.  So, pushing the load onto the stack at a later
2689     // point is fine.
2690     set_result(p);
2691   } else {
2692     if (bt == T_ADDRESS) {
2693       // Repackage the long as a pointer.
2694       val = ConvL2X(val);
2695       val = gvn().transform(new CastX2PNode(val));
2696     }
2697     if (is_flat) {
2698       val->as_InlineType()->store_flat(this, base, adr, false, false, true, decorators);
2699     } else {
2700       access_store_at(heap_base_oop, adr, adr_type, val, value_type, type, decorators);
2701     }
2702   }
2703 
2704   return true;
2705 }
2706 
2707 bool LibraryCallKit::inline_unsafe_make_private_buffer() {
2708   Node* receiver = argument(0);
2709   Node* value = argument(1);
2710 
2711   const Type* type = gvn().type(value);
2712   if (!type->is_inlinetypeptr()) {
2713     C->record_method_not_compilable("value passed to Unsafe::makePrivateBuffer is not of a constant value type");
2714     return false;
2715   }
2716 
2717   null_check(receiver);
2718   if (stopped()) {
2719     return true;
2720   }
2721 
2722   value = null_check(value);
2723   if (stopped()) {
2724     return true;
2725   }
2726 
2727   ciInlineKlass* vk = type->inline_klass();
2728   Node* klass = makecon(TypeKlassPtr::make(vk));
2729   Node* obj = new_instance(klass);
2730   AllocateNode::Ideal_allocation(obj)->_larval = true;
2731 
2732   assert(value->is_InlineType(), "must be an InlineTypeNode");
2733   Node* payload_ptr = basic_plus_adr(obj, vk->payload_offset());
2734   value->as_InlineType()->store_flat(this, obj, payload_ptr, false, true, true, IN_HEAP | MO_UNORDERED);
2735 
2736   set_result(obj);
2737   return true;
2738 }
2739 
2740 bool LibraryCallKit::inline_unsafe_finish_private_buffer() {
2741   Node* receiver = argument(0);
2742   Node* buffer = argument(1);
2743 
2744   const Type* type = gvn().type(buffer);
2745   if (!type->is_inlinetypeptr()) {
2746     C->record_method_not_compilable("value passed to Unsafe::finishPrivateBuffer is not of a constant value type");
2747     return false;
2748   }
2749 
2750   AllocateNode* alloc = AllocateNode::Ideal_allocation(buffer);
2751   if (alloc == nullptr) {
2752     C->record_method_not_compilable("value passed to Unsafe::finishPrivateBuffer must be allocated by Unsafe::makePrivateBuffer");
2753     return false;
2754   }
2755 
2756   null_check(receiver);
2757   if (stopped()) {
2758     return true;
2759   }
2760 
2761   // Unset the larval bit in the object header
2762   Node* old_header = make_load(control(), buffer, TypeX_X, TypeX_X->basic_type(), MemNode::unordered, LoadNode::Pinned);
2763   Node* new_header = gvn().transform(new AndXNode(old_header, MakeConX(~markWord::larval_bit_in_place)));
2764   access_store_at(buffer, buffer, type->is_ptr(), new_header, TypeX_X, TypeX_X->basic_type(), MO_UNORDERED | IN_HEAP);
2765 
2766   // We must ensure that the buffer is properly published
2767   insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out(AllocateNode::RawAddress));
2768   assert(!type->maybe_null(), "result of an allocation should not be null");
2769   set_result(InlineTypeNode::make_from_oop(this, buffer, type->inline_klass()));
2770   return true;
2771 }
2772 
2773 //----------------------------inline_unsafe_load_store----------------------------
2774 // This method serves a couple of different customers (depending on LoadStoreKind):
2775 //
2776 // LS_cmp_swap:
2777 //
2778 //   boolean compareAndSetReference(Object o, long offset, Object expected, Object x);
2779 //   boolean compareAndSetInt(   Object o, long offset, int    expected, int    x);
2780 //   boolean compareAndSetLong(  Object o, long offset, long   expected, long   x);
2781 //
2782 // LS_cmp_swap_weak:
2783 //
2784 //   boolean weakCompareAndSetReference(       Object o, long offset, Object expected, Object x);
2785 //   boolean weakCompareAndSetReferencePlain(  Object o, long offset, Object expected, Object x);
2786 //   boolean weakCompareAndSetReferenceAcquire(Object o, long offset, Object expected, Object x);
2787 //   boolean weakCompareAndSetReferenceRelease(Object o, long offset, Object expected, Object x);
2788 //
2789 //   boolean weakCompareAndSetInt(          Object o, long offset, int    expected, int    x);
2790 //   boolean weakCompareAndSetIntPlain(     Object o, long offset, int    expected, int    x);
2791 //   boolean weakCompareAndSetIntAcquire(   Object o, long offset, int    expected, int    x);
2792 //   boolean weakCompareAndSetIntRelease(   Object o, long offset, int    expected, int    x);
2793 //
2794 //   boolean weakCompareAndSetLong(         Object o, long offset, long   expected, long   x);
2795 //   boolean weakCompareAndSetLongPlain(    Object o, long offset, long   expected, long   x);
2796 //   boolean weakCompareAndSetLongAcquire(  Object o, long offset, long   expected, long   x);
2797 //   boolean weakCompareAndSetLongRelease(  Object o, long offset, long   expected, long   x);
2798 //
2799 // LS_cmp_exchange:
2800 //
2801 //   Object compareAndExchangeReferenceVolatile(Object o, long offset, Object expected, Object x);
2802 //   Object compareAndExchangeReferenceAcquire( Object o, long offset, Object expected, Object x);
2803 //   Object compareAndExchangeReferenceRelease( Object o, long offset, Object expected, Object x);
2804 //
2805 //   Object compareAndExchangeIntVolatile(   Object o, long offset, Object expected, Object x);
2806 //   Object compareAndExchangeIntAcquire(    Object o, long offset, Object expected, Object x);
2807 //   Object compareAndExchangeIntRelease(    Object o, long offset, Object expected, Object x);
2808 //
2809 //   Object compareAndExchangeLongVolatile(  Object o, long offset, Object expected, Object x);
2810 //   Object compareAndExchangeLongAcquire(   Object o, long offset, Object expected, Object x);
2811 //   Object compareAndExchangeLongRelease(   Object o, long offset, Object expected, Object x);
2812 //
2813 // LS_get_add:
2814 //
2815 //   int  getAndAddInt( Object o, long offset, int  delta)
2816 //   long getAndAddLong(Object o, long offset, long delta)
2817 //
2818 // LS_get_set:
2819 //
2820 //   int    getAndSet(Object o, long offset, int    newValue)
2821 //   long   getAndSet(Object o, long offset, long   newValue)
2822 //   Object getAndSet(Object o, long offset, Object newValue)
2823 //
2824 bool LibraryCallKit::inline_unsafe_load_store(const BasicType type, const LoadStoreKind kind, const AccessKind access_kind) {
2825   // This basic scheme here is the same as inline_unsafe_access, but
2826   // differs in enough details that combining them would make the code
2827   // overly confusing.  (This is a true fact! I originally combined
2828   // them, but even I was confused by it!) As much code/comments as
2829   // possible are retained from inline_unsafe_access though to make
2830   // the correspondences clearer. - dl
2831 
2832   if (callee()->is_static())  return false;  // caller must have the capability!
2833 
2834   DecoratorSet decorators = C2_UNSAFE_ACCESS;
2835   decorators |= mo_decorator_for_access_kind(access_kind);
2836 
2837 #ifndef PRODUCT
2838   BasicType rtype;
2839   {
2840     ResourceMark rm;
2841     // Check the signatures.
2842     ciSignature* sig = callee()->signature();
2843     rtype = sig->return_type()->basic_type();
2844     switch(kind) {
2845       case LS_get_add:
2846       case LS_get_set: {
2847       // Check the signatures.
2848 #ifdef ASSERT
2849       assert(rtype == type, "get and set must return the expected type");
2850       assert(sig->count() == 3, "get and set has 3 arguments");
2851       assert(sig->type_at(0)->basic_type() == T_OBJECT, "get and set base is object");
2852       assert(sig->type_at(1)->basic_type() == T_LONG, "get and set offset is long");
2853       assert(sig->type_at(2)->basic_type() == type, "get and set must take expected type as new value/delta");
2854       assert(access_kind == Volatile, "mo is not passed to intrinsic nodes in current implementation");
2855 #endif // ASSERT
2856         break;
2857       }
2858       case LS_cmp_swap:
2859       case LS_cmp_swap_weak: {
2860       // Check the signatures.
2861 #ifdef ASSERT
2862       assert(rtype == T_BOOLEAN, "CAS must return boolean");
2863       assert(sig->count() == 4, "CAS has 4 arguments");
2864       assert(sig->type_at(0)->basic_type() == T_OBJECT, "CAS base is object");
2865       assert(sig->type_at(1)->basic_type() == T_LONG, "CAS offset is long");
2866 #endif // ASSERT
2867         break;
2868       }
2869       case LS_cmp_exchange: {
2870       // Check the signatures.
2871 #ifdef ASSERT
2872       assert(rtype == type, "CAS must return the expected type");
2873       assert(sig->count() == 4, "CAS has 4 arguments");
2874       assert(sig->type_at(0)->basic_type() == T_OBJECT, "CAS base is object");
2875       assert(sig->type_at(1)->basic_type() == T_LONG, "CAS offset is long");
2876 #endif // ASSERT
2877         break;
2878       }
2879       default:
2880         ShouldNotReachHere();
2881     }
2882   }
2883 #endif //PRODUCT
2884 
2885   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
2886 
2887   // Get arguments:
2888   Node* receiver = nullptr;
2889   Node* base     = nullptr;
2890   Node* offset   = nullptr;
2891   Node* oldval   = nullptr;
2892   Node* newval   = nullptr;
2893   switch(kind) {
2894     case LS_cmp_swap:
2895     case LS_cmp_swap_weak:
2896     case LS_cmp_exchange: {
2897       const bool two_slot_type = type2size[type] == 2;
2898       receiver = argument(0);  // type: oop
2899       base     = argument(1);  // type: oop
2900       offset   = argument(2);  // type: long
2901       oldval   = argument(4);  // type: oop, int, or long
2902       newval   = argument(two_slot_type ? 6 : 5);  // type: oop, int, or long
2903       break;
2904     }
2905     case LS_get_add:
2906     case LS_get_set: {
2907       receiver = argument(0);  // type: oop
2908       base     = argument(1);  // type: oop
2909       offset   = argument(2);  // type: long
2910       oldval   = nullptr;
2911       newval   = argument(4);  // type: oop, int, or long
2912       break;
2913     }
2914     default:
2915       ShouldNotReachHere();
2916   }
2917 
2918   // Build field offset expression.
2919   // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
2920   // to be plain byte offsets, which are also the same as those accepted
2921   // by oopDesc::field_addr.
2922   assert(Unsafe_field_offset_to_byte_offset(11) == 11, "fieldOffset must be byte-scaled");
2923   // 32-bit machines ignore the high half of long offsets
2924   offset = ConvL2X(offset);
2925   // Save state and restore on bailout
2926   uint old_sp = sp();
2927   SafePointNode* old_map = clone_map();
2928   Node* adr = make_unsafe_address(base, offset,type, false);
2929   const TypePtr *adr_type = _gvn.type(adr)->isa_ptr();
2930 
2931   Compile::AliasType* alias_type = C->alias_type(adr_type);
2932   BasicType bt = alias_type->basic_type();
2933   if (bt != T_ILLEGAL &&
2934       (is_reference_type(bt) != (type == T_OBJECT))) {
2935     // Don't intrinsify mismatched object accesses.
2936     set_map(old_map);
2937     set_sp(old_sp);
2938     return false;
2939   }
2940 
2941   destruct_map_clone(old_map);
2942 
2943   // For CAS, unlike inline_unsafe_access, there seems no point in
2944   // trying to refine types. Just use the coarse types here.
2945   assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
2946   const Type *value_type = Type::get_const_basic_type(type);
2947 
2948   switch (kind) {
2949     case LS_get_set:
2950     case LS_cmp_exchange: {
2951       if (type == T_OBJECT) {
2952         const TypeOopPtr* tjp = sharpen_unsafe_type(alias_type, adr_type);
2953         if (tjp != nullptr) {
2954           value_type = tjp;
2955         }
2956       }
2957       break;
2958     }
2959     case LS_cmp_swap:
2960     case LS_cmp_swap_weak:
2961     case LS_get_add:
2962       break;
2963     default:
2964       ShouldNotReachHere();
2965   }
2966 
2967   // Null check receiver.
2968   receiver = null_check(receiver);
2969   if (stopped()) {
2970     return true;
2971   }
2972 
2973   int alias_idx = C->get_alias_index(adr_type);
2974 
2975   if (is_reference_type(type)) {
2976     decorators |= IN_HEAP | ON_UNKNOWN_OOP_REF;
2977 
2978     if (oldval != nullptr && oldval->is_InlineType()) {
2979       // Re-execute the unsafe access if allocation triggers deoptimization.
2980       PreserveReexecuteState preexecs(this);
2981       jvms()->set_should_reexecute(true);
2982       oldval = oldval->as_InlineType()->buffer(this)->get_oop();
2983     }
2984     if (newval != nullptr && newval->is_InlineType()) {
2985       // Re-execute the unsafe access if allocation triggers deoptimization.
2986       PreserveReexecuteState preexecs(this);
2987       jvms()->set_should_reexecute(true);
2988       newval = newval->as_InlineType()->buffer(this)->get_oop();
2989     }
2990 
2991     // Transformation of a value which could be null pointer (CastPP #null)
2992     // could be delayed during Parse (for example, in adjust_map_after_if()).
2993     // Execute transformation here to avoid barrier generation in such case.
2994     if (_gvn.type(newval) == TypePtr::NULL_PTR)
2995       newval = _gvn.makecon(TypePtr::NULL_PTR);
2996 
2997     if (oldval != nullptr && _gvn.type(oldval) == TypePtr::NULL_PTR) {
2998       // Refine the value to a null constant, when it is known to be null
2999       oldval = _gvn.makecon(TypePtr::NULL_PTR);
3000     }
3001   }
3002 
3003   Node* result = nullptr;
3004   switch (kind) {
3005     case LS_cmp_exchange: {
3006       result = access_atomic_cmpxchg_val_at(base, adr, adr_type, alias_idx,
3007                                             oldval, newval, value_type, type, decorators);
3008       break;
3009     }
3010     case LS_cmp_swap_weak:
3011       decorators |= C2_WEAK_CMPXCHG;
3012     case LS_cmp_swap: {
3013       result = access_atomic_cmpxchg_bool_at(base, adr, adr_type, alias_idx,
3014                                              oldval, newval, value_type, type, decorators);
3015       break;
3016     }
3017     case LS_get_set: {
3018       result = access_atomic_xchg_at(base, adr, adr_type, alias_idx,
3019                                      newval, value_type, type, decorators);
3020       break;
3021     }
3022     case LS_get_add: {
3023       result = access_atomic_add_at(base, adr, adr_type, alias_idx,
3024                                     newval, value_type, type, decorators);
3025       break;
3026     }
3027     default:
3028       ShouldNotReachHere();
3029   }
3030 
3031   assert(type2size[result->bottom_type()->basic_type()] == type2size[rtype], "result type should match");
3032   set_result(result);
3033   return true;
3034 }
3035 
3036 bool LibraryCallKit::inline_unsafe_fence(vmIntrinsics::ID id) {
3037   // Regardless of form, don't allow previous ld/st to move down,
3038   // then issue acquire, release, or volatile mem_bar.
3039   insert_mem_bar(Op_MemBarCPUOrder);
3040   switch(id) {
3041     case vmIntrinsics::_loadFence:
3042       insert_mem_bar(Op_LoadFence);
3043       return true;
3044     case vmIntrinsics::_storeFence:
3045       insert_mem_bar(Op_StoreFence);
3046       return true;
3047     case vmIntrinsics::_storeStoreFence:
3048       insert_mem_bar(Op_StoreStoreFence);
3049       return true;
3050     case vmIntrinsics::_fullFence:
3051       insert_mem_bar(Op_MemBarVolatile);
3052       return true;
3053     default:
3054       fatal_unexpected_iid(id);
3055       return false;
3056   }
3057 }
3058 
3059 bool LibraryCallKit::inline_onspinwait() {
3060   insert_mem_bar(Op_OnSpinWait);
3061   return true;
3062 }
3063 
3064 bool LibraryCallKit::klass_needs_init_guard(Node* kls) {
3065   if (!kls->is_Con()) {
3066     return true;
3067   }
3068   const TypeInstKlassPtr* klsptr = kls->bottom_type()->isa_instklassptr();
3069   if (klsptr == nullptr) {
3070     return true;
3071   }
3072   ciInstanceKlass* ik = klsptr->instance_klass();
3073   // don't need a guard for a klass that is already initialized
3074   return !ik->is_initialized();
3075 }
3076 
3077 //----------------------------inline_unsafe_writeback0-------------------------
3078 // public native void Unsafe.writeback0(long address)
3079 bool LibraryCallKit::inline_unsafe_writeback0() {
3080   if (!Matcher::has_match_rule(Op_CacheWB)) {
3081     return false;
3082   }
3083 #ifndef PRODUCT
3084   assert(Matcher::has_match_rule(Op_CacheWBPreSync), "found match rule for CacheWB but not CacheWBPreSync");
3085   assert(Matcher::has_match_rule(Op_CacheWBPostSync), "found match rule for CacheWB but not CacheWBPostSync");
3086   ciSignature* sig = callee()->signature();
3087   assert(sig->type_at(0)->basic_type() == T_LONG, "Unsafe_writeback0 address is long!");
3088 #endif
3089   null_check_receiver();  // null-check, then ignore
3090   Node *addr = argument(1);
3091   addr = new CastX2PNode(addr);
3092   addr = _gvn.transform(addr);
3093   Node *flush = new CacheWBNode(control(), memory(TypeRawPtr::BOTTOM), addr);
3094   flush = _gvn.transform(flush);
3095   set_memory(flush, TypeRawPtr::BOTTOM);
3096   return true;
3097 }
3098 
3099 //----------------------------inline_unsafe_writeback0-------------------------
3100 // public native void Unsafe.writeback0(long address)
3101 bool LibraryCallKit::inline_unsafe_writebackSync0(bool is_pre) {
3102   if (is_pre && !Matcher::has_match_rule(Op_CacheWBPreSync)) {
3103     return false;
3104   }
3105   if (!is_pre && !Matcher::has_match_rule(Op_CacheWBPostSync)) {
3106     return false;
3107   }
3108 #ifndef PRODUCT
3109   assert(Matcher::has_match_rule(Op_CacheWB),
3110          (is_pre ? "found match rule for CacheWBPreSync but not CacheWB"
3111                 : "found match rule for CacheWBPostSync but not CacheWB"));
3112 
3113 #endif
3114   null_check_receiver();  // null-check, then ignore
3115   Node *sync;
3116   if (is_pre) {
3117     sync = new CacheWBPreSyncNode(control(), memory(TypeRawPtr::BOTTOM));
3118   } else {
3119     sync = new CacheWBPostSyncNode(control(), memory(TypeRawPtr::BOTTOM));
3120   }
3121   sync = _gvn.transform(sync);
3122   set_memory(sync, TypeRawPtr::BOTTOM);
3123   return true;
3124 }
3125 
3126 //----------------------------inline_unsafe_allocate---------------------------
3127 // public native Object Unsafe.allocateInstance(Class<?> cls);
3128 bool LibraryCallKit::inline_unsafe_allocate() {
3129 
3130 #if INCLUDE_JVMTI
3131   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
3132     return false;
3133   }
3134 #endif //INCLUDE_JVMTI
3135 
3136   if (callee()->is_static())  return false;  // caller must have the capability!
3137 
3138   null_check_receiver();  // null-check, then ignore
3139   Node* cls = null_check(argument(1));
3140   if (stopped())  return true;
3141 
3142   Node* kls = load_klass_from_mirror(cls, false, nullptr, 0);
3143   kls = null_check(kls);
3144   if (stopped())  return true;  // argument was like int.class
3145 
3146 #if INCLUDE_JVMTI
3147     // Don't try to access new allocated obj in the intrinsic.
3148     // It causes perfomance issues even when jvmti event VmObjectAlloc is disabled.
3149     // Deoptimize and allocate in interpreter instead.
3150     Node* addr = makecon(TypeRawPtr::make((address) &JvmtiExport::_should_notify_object_alloc));
3151     Node* should_post_vm_object_alloc = make_load(this->control(), addr, TypeInt::INT, T_INT, MemNode::unordered);
3152     Node* chk = _gvn.transform(new CmpINode(should_post_vm_object_alloc, intcon(0)));
3153     Node* tst = _gvn.transform(new BoolNode(chk, BoolTest::eq));
3154     {
3155       BuildCutout unless(this, tst, PROB_MAX);
3156       uncommon_trap(Deoptimization::Reason_intrinsic,
3157                     Deoptimization::Action_make_not_entrant);
3158     }
3159     if (stopped()) {
3160       return true;
3161     }
3162 #endif //INCLUDE_JVMTI
3163 
3164   Node* test = nullptr;
3165   if (LibraryCallKit::klass_needs_init_guard(kls)) {
3166     // Note:  The argument might still be an illegal value like
3167     // Serializable.class or Object[].class.   The runtime will handle it.
3168     // But we must make an explicit check for initialization.
3169     Node* insp = basic_plus_adr(kls, in_bytes(InstanceKlass::init_state_offset()));
3170     // Use T_BOOLEAN for InstanceKlass::_init_state so the compiler
3171     // can generate code to load it as unsigned byte.
3172     Node* inst = make_load(nullptr, insp, TypeInt::UBYTE, T_BOOLEAN, MemNode::acquire);
3173     Node* bits = intcon(InstanceKlass::fully_initialized);
3174     test = _gvn.transform(new SubINode(inst, bits));
3175     // The 'test' is non-zero if we need to take a slow path.
3176   }
3177   Node* obj = nullptr;
3178   const TypeInstKlassPtr* tkls = _gvn.type(kls)->isa_instklassptr();
3179   if (tkls != nullptr && tkls->instance_klass()->is_inlinetype()) {
3180     obj = InlineTypeNode::make_all_zero(_gvn, tkls->instance_klass()->as_inline_klass())->buffer(this);
3181   } else {
3182     obj = new_instance(kls, test);
3183   }
3184   set_result(obj);
3185   return true;
3186 }
3187 
3188 //------------------------inline_native_time_funcs--------------
3189 // inline code for System.currentTimeMillis() and System.nanoTime()
3190 // these have the same type and signature
3191 bool LibraryCallKit::inline_native_time_funcs(address funcAddr, const char* funcName) {
3192   const TypeFunc* tf = OptoRuntime::void_long_Type();
3193   const TypePtr* no_memory_effects = nullptr;
3194   Node* time = make_runtime_call(RC_LEAF, tf, funcAddr, funcName, no_memory_effects);
3195   Node* value = _gvn.transform(new ProjNode(time, TypeFunc::Parms+0));
3196 #ifdef ASSERT
3197   Node* value_top = _gvn.transform(new ProjNode(time, TypeFunc::Parms+1));
3198   assert(value_top == top(), "second value must be top");
3199 #endif
3200   set_result(value);
3201   return true;
3202 }
3203 
3204 
3205 #if INCLUDE_JVMTI
3206 
3207 // When notifications are disabled then just update the VTMS transition bit and return.
3208 // Otherwise, the bit is updated in the given function call implementing JVMTI notification protocol.
3209 bool LibraryCallKit::inline_native_notify_jvmti_funcs(address funcAddr, const char* funcName, bool is_start, bool is_end) {
3210   if (!DoJVMTIVirtualThreadTransitions) {
3211     return true;
3212   }
3213   Node* vt_oop = _gvn.transform(must_be_not_null(argument(0), true)); // VirtualThread this argument
3214   IdealKit ideal(this);
3215 
3216   Node* ONE = ideal.ConI(1);
3217   Node* hide = is_start ? ideal.ConI(0) : (is_end ? ideal.ConI(1) : _gvn.transform(argument(1)));
3218   Node* addr = makecon(TypeRawPtr::make((address)&JvmtiVTMSTransitionDisabler::_VTMS_notify_jvmti_events));
3219   Node* notify_jvmti_enabled = ideal.load(ideal.ctrl(), addr, TypeInt::BOOL, T_BOOLEAN, Compile::AliasIdxRaw);
3220 
3221   ideal.if_then(notify_jvmti_enabled, BoolTest::eq, ONE); {
3222     sync_kit(ideal);
3223     // if notifyJvmti enabled then make a call to the given SharedRuntime function
3224     const TypeFunc* tf = OptoRuntime::notify_jvmti_vthread_Type();
3225     make_runtime_call(RC_NO_LEAF, tf, funcAddr, funcName, TypePtr::BOTTOM, vt_oop, hide);
3226     ideal.sync_kit(this);
3227   } ideal.else_(); {
3228     // set hide value to the VTMS transition bit in current JavaThread and VirtualThread object
3229     Node* thread = ideal.thread();
3230     Node* jt_addr = basic_plus_adr(thread, in_bytes(JavaThread::is_in_VTMS_transition_offset()));
3231     Node* vt_addr = basic_plus_adr(vt_oop, java_lang_Thread::is_in_VTMS_transition_offset());
3232 
3233     sync_kit(ideal);
3234     access_store_at(nullptr, jt_addr, _gvn.type(jt_addr)->is_ptr(), hide, _gvn.type(hide), T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
3235     access_store_at(nullptr, vt_addr, _gvn.type(vt_addr)->is_ptr(), hide, _gvn.type(hide), T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
3236 
3237     ideal.sync_kit(this);
3238   } ideal.end_if();
3239   final_sync(ideal);
3240 
3241   return true;
3242 }
3243 
3244 // Always update the is_disable_suspend bit.
3245 bool LibraryCallKit::inline_native_notify_jvmti_sync() {
3246   if (!DoJVMTIVirtualThreadTransitions) {
3247     return true;
3248   }
3249   IdealKit ideal(this);
3250 
3251   {
3252     // unconditionally update the is_disable_suspend bit in current JavaThread
3253     Node* thread = ideal.thread();
3254     Node* arg = _gvn.transform(argument(0)); // argument for notification
3255     Node* addr = basic_plus_adr(thread, in_bytes(JavaThread::is_disable_suspend_offset()));
3256     const TypePtr *addr_type = _gvn.type(addr)->isa_ptr();
3257 
3258     sync_kit(ideal);
3259     access_store_at(nullptr, addr, addr_type, arg, _gvn.type(arg), T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
3260     ideal.sync_kit(this);
3261   }
3262   final_sync(ideal);
3263 
3264   return true;
3265 }
3266 
3267 #endif // INCLUDE_JVMTI
3268 
3269 #ifdef JFR_HAVE_INTRINSICS
3270 
3271 /**
3272  * if oop->klass != null
3273  *   // normal class
3274  *   epoch = _epoch_state ? 2 : 1
3275  *   if oop->klass->trace_id & ((epoch << META_SHIFT) | epoch)) != epoch {
3276  *     ... // enter slow path when the klass is first recorded or the epoch of JFR shifts
3277  *   }
3278  *   id = oop->klass->trace_id >> TRACE_ID_SHIFT // normal class path
3279  * else
3280  *   // primitive class
3281  *   if oop->array_klass != null
3282  *     id = (oop->array_klass->trace_id >> TRACE_ID_SHIFT) + 1 // primitive class path
3283  *   else
3284  *     id = LAST_TYPE_ID + 1 // void class path
3285  *   if (!signaled)
3286  *     signaled = true
3287  */
3288 bool LibraryCallKit::inline_native_classID() {
3289   Node* cls = argument(0);
3290 
3291   IdealKit ideal(this);
3292 #define __ ideal.
3293   IdealVariable result(ideal); __ declarations_done();
3294   Node* kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(),
3295                                                  basic_plus_adr(cls, java_lang_Class::klass_offset()),
3296                                                  TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
3297 
3298 
3299   __ if_then(kls, BoolTest::ne, null()); {
3300     Node* kls_trace_id_addr = basic_plus_adr(kls, in_bytes(KLASS_TRACE_ID_OFFSET));
3301     Node* kls_trace_id_raw = ideal.load(ideal.ctrl(), kls_trace_id_addr,TypeLong::LONG, T_LONG, Compile::AliasIdxRaw);
3302 
3303     Node* epoch_address = makecon(TypeRawPtr::make(JfrIntrinsicSupport::epoch_address()));
3304     Node* epoch = ideal.load(ideal.ctrl(), epoch_address, TypeInt::BOOL, T_BOOLEAN, Compile::AliasIdxRaw);
3305     epoch = _gvn.transform(new LShiftLNode(longcon(1), epoch));
3306     Node* mask = _gvn.transform(new LShiftLNode(epoch, intcon(META_SHIFT)));
3307     mask = _gvn.transform(new OrLNode(mask, epoch));
3308     Node* kls_trace_id_raw_and_mask = _gvn.transform(new AndLNode(kls_trace_id_raw, mask));
3309 
3310     float unlikely  = PROB_UNLIKELY(0.999);
3311     __ if_then(kls_trace_id_raw_and_mask, BoolTest::ne, epoch, unlikely); {
3312       sync_kit(ideal);
3313       make_runtime_call(RC_LEAF,
3314                         OptoRuntime::class_id_load_barrier_Type(),
3315                         CAST_FROM_FN_PTR(address, JfrIntrinsicSupport::load_barrier),
3316                         "class id load barrier",
3317                         TypePtr::BOTTOM,
3318                         kls);
3319       ideal.sync_kit(this);
3320     } __ end_if();
3321 
3322     ideal.set(result,  _gvn.transform(new URShiftLNode(kls_trace_id_raw, ideal.ConI(TRACE_ID_SHIFT))));
3323   } __ else_(); {
3324     Node* array_kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(),
3325                                                    basic_plus_adr(cls, java_lang_Class::array_klass_offset()),
3326                                                    TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
3327     __ if_then(array_kls, BoolTest::ne, null()); {
3328       Node* array_kls_trace_id_addr = basic_plus_adr(array_kls, in_bytes(KLASS_TRACE_ID_OFFSET));
3329       Node* array_kls_trace_id_raw = ideal.load(ideal.ctrl(), array_kls_trace_id_addr, TypeLong::LONG, T_LONG, Compile::AliasIdxRaw);
3330       Node* array_kls_trace_id = _gvn.transform(new URShiftLNode(array_kls_trace_id_raw, ideal.ConI(TRACE_ID_SHIFT)));
3331       ideal.set(result, _gvn.transform(new AddLNode(array_kls_trace_id, longcon(1))));
3332     } __ else_(); {
3333       // void class case
3334       ideal.set(result, _gvn.transform(longcon(LAST_TYPE_ID + 1)));
3335     } __ end_if();
3336 
3337     Node* signaled_flag_address = makecon(TypeRawPtr::make(JfrIntrinsicSupport::signal_address()));
3338     Node* signaled = ideal.load(ideal.ctrl(), signaled_flag_address, TypeInt::BOOL, T_BOOLEAN, Compile::AliasIdxRaw, true, MemNode::acquire);
3339     __ if_then(signaled, BoolTest::ne, ideal.ConI(1)); {
3340       ideal.store(ideal.ctrl(), signaled_flag_address, ideal.ConI(1), T_BOOLEAN, Compile::AliasIdxRaw, MemNode::release, true);
3341     } __ end_if();
3342   } __ end_if();
3343 
3344   final_sync(ideal);
3345   set_result(ideal.value(result));
3346 #undef __
3347   return true;
3348 }
3349 
3350 //------------------------inline_native_jvm_commit------------------
3351 bool LibraryCallKit::inline_native_jvm_commit() {
3352   enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
3353 
3354   // Save input memory and i_o state.
3355   Node* input_memory_state = reset_memory();
3356   set_all_memory(input_memory_state);
3357   Node* input_io_state = i_o();
3358 
3359   // TLS.
3360   Node* tls_ptr = _gvn.transform(new ThreadLocalNode());
3361   // Jfr java buffer.
3362   Node* java_buffer_offset = _gvn.transform(new AddPNode(top(), tls_ptr, _gvn.transform(MakeConX(in_bytes(JAVA_BUFFER_OFFSET_JFR)))));
3363   Node* java_buffer = _gvn.transform(new LoadPNode(control(), input_memory_state, java_buffer_offset, TypePtr::BOTTOM, TypeRawPtr::NOTNULL, MemNode::unordered));
3364   Node* java_buffer_pos_offset = _gvn.transform(new AddPNode(top(), java_buffer, _gvn.transform(MakeConX(in_bytes(JFR_BUFFER_POS_OFFSET)))));
3365 
3366   // Load the current value of the notified field in the JfrThreadLocal.
3367   Node* notified_offset = basic_plus_adr(top(), tls_ptr, in_bytes(NOTIFY_OFFSET_JFR));
3368   Node* notified = make_load(control(), notified_offset, TypeInt::BOOL, T_BOOLEAN, MemNode::unordered);
3369 
3370   // Test for notification.
3371   Node* notified_cmp = _gvn.transform(new CmpINode(notified, _gvn.intcon(1)));
3372   Node* test_notified = _gvn.transform(new BoolNode(notified_cmp, BoolTest::eq));
3373   IfNode* iff_notified = create_and_map_if(control(), test_notified, PROB_MIN, COUNT_UNKNOWN);
3374 
3375   // True branch, is notified.
3376   Node* is_notified = _gvn.transform(new IfTrueNode(iff_notified));
3377   set_control(is_notified);
3378 
3379   // Reset notified state.
3380   store_to_memory(control(), notified_offset, _gvn.intcon(0), T_BOOLEAN, MemNode::unordered);
3381   Node* notified_reset_memory = reset_memory();
3382 
3383   // 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.
3384   Node* current_pos_X = _gvn.transform(new LoadXNode(control(), input_memory_state, java_buffer_pos_offset, TypeRawPtr::NOTNULL, TypeX_X, MemNode::unordered));
3385   // Convert the machine-word to a long.
3386   Node* current_pos = _gvn.transform(ConvX2L(current_pos_X));
3387 
3388   // False branch, not notified.
3389   Node* not_notified = _gvn.transform(new IfFalseNode(iff_notified));
3390   set_control(not_notified);
3391   set_all_memory(input_memory_state);
3392 
3393   // Arg is the next position as a long.
3394   Node* arg = argument(0);
3395   // Convert long to machine-word.
3396   Node* next_pos_X = _gvn.transform(ConvL2X(arg));
3397 
3398   // Store the next_position to the underlying jfr java buffer.
3399   store_to_memory(control(), java_buffer_pos_offset, next_pos_X, LP64_ONLY(T_LONG) NOT_LP64(T_INT), MemNode::release);
3400 
3401   Node* commit_memory = reset_memory();
3402   set_all_memory(commit_memory);
3403 
3404   // 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.
3405   Node* java_buffer_flags_offset = _gvn.transform(new AddPNode(top(), java_buffer, _gvn.transform(MakeConX(in_bytes(JFR_BUFFER_FLAGS_OFFSET)))));
3406   Node* flags = make_load(control(), java_buffer_flags_offset, TypeInt::UBYTE, T_BYTE, MemNode::unordered);
3407   Node* lease_constant = _gvn.transform(_gvn.intcon(4));
3408 
3409   // And flags with lease constant.
3410   Node* lease = _gvn.transform(new AndINode(flags, lease_constant));
3411 
3412   // Branch on lease to conditionalize returning the leased java buffer.
3413   Node* lease_cmp = _gvn.transform(new CmpINode(lease, lease_constant));
3414   Node* test_lease = _gvn.transform(new BoolNode(lease_cmp, BoolTest::eq));
3415   IfNode* iff_lease = create_and_map_if(control(), test_lease, PROB_MIN, COUNT_UNKNOWN);
3416 
3417   // False branch, not a lease.
3418   Node* not_lease = _gvn.transform(new IfFalseNode(iff_lease));
3419 
3420   // True branch, is lease.
3421   Node* is_lease = _gvn.transform(new IfTrueNode(iff_lease));
3422   set_control(is_lease);
3423 
3424   // Make a runtime call, which can safepoint, to return the leased buffer. This updates both the JfrThreadLocal and the Java event writer oop.
3425   Node* call_return_lease = make_runtime_call(RC_NO_LEAF,
3426                                               OptoRuntime::void_void_Type(),
3427                                               SharedRuntime::jfr_return_lease(),
3428                                               "return_lease", TypePtr::BOTTOM);
3429   Node* call_return_lease_control = _gvn.transform(new ProjNode(call_return_lease, TypeFunc::Control));
3430 
3431   RegionNode* lease_compare_rgn = new RegionNode(PATH_LIMIT);
3432   record_for_igvn(lease_compare_rgn);
3433   PhiNode* lease_compare_mem = new PhiNode(lease_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3434   record_for_igvn(lease_compare_mem);
3435   PhiNode* lease_compare_io = new PhiNode(lease_compare_rgn, Type::ABIO);
3436   record_for_igvn(lease_compare_io);
3437   PhiNode* lease_result_value = new PhiNode(lease_compare_rgn, TypeLong::LONG);
3438   record_for_igvn(lease_result_value);
3439 
3440   // Update control and phi nodes.
3441   lease_compare_rgn->init_req(_true_path, call_return_lease_control);
3442   lease_compare_rgn->init_req(_false_path, not_lease);
3443 
3444   lease_compare_mem->init_req(_true_path, _gvn.transform(reset_memory()));
3445   lease_compare_mem->init_req(_false_path, commit_memory);
3446 
3447   lease_compare_io->init_req(_true_path, i_o());
3448   lease_compare_io->init_req(_false_path, input_io_state);
3449 
3450   lease_result_value->init_req(_true_path, null()); // if the lease was returned, return 0.
3451   lease_result_value->init_req(_false_path, arg); // if not lease, return new updated position.
3452 
3453   RegionNode* result_rgn = new RegionNode(PATH_LIMIT);
3454   PhiNode* result_mem = new PhiNode(result_rgn, Type::MEMORY, TypePtr::BOTTOM);
3455   PhiNode* result_io = new PhiNode(result_rgn, Type::ABIO);
3456   PhiNode* result_value = new PhiNode(result_rgn, TypeLong::LONG);
3457 
3458   // Update control and phi nodes.
3459   result_rgn->init_req(_true_path, is_notified);
3460   result_rgn->init_req(_false_path, _gvn.transform(lease_compare_rgn));
3461 
3462   result_mem->init_req(_true_path, notified_reset_memory);
3463   result_mem->init_req(_false_path, _gvn.transform(lease_compare_mem));
3464 
3465   result_io->init_req(_true_path, input_io_state);
3466   result_io->init_req(_false_path, _gvn.transform(lease_compare_io));
3467 
3468   result_value->init_req(_true_path, current_pos);
3469   result_value->init_req(_false_path, _gvn.transform(lease_result_value));
3470 
3471   // Set output state.
3472   set_control(_gvn.transform(result_rgn));
3473   set_all_memory(_gvn.transform(result_mem));
3474   set_i_o(_gvn.transform(result_io));
3475   set_result(result_rgn, result_value);
3476   return true;
3477 }
3478 
3479 /*
3480  * The intrinsic is a model of this pseudo-code:
3481  *
3482  * JfrThreadLocal* const tl = Thread::jfr_thread_local()
3483  * jobject h_event_writer = tl->java_event_writer();
3484  * if (h_event_writer == nullptr) {
3485  *   return nullptr;
3486  * }
3487  * oop threadObj = Thread::threadObj();
3488  * oop vthread = java_lang_Thread::vthread(threadObj);
3489  * traceid tid;
3490  * bool pinVirtualThread;
3491  * bool excluded;
3492  * if (vthread != threadObj) {  // i.e. current thread is virtual
3493  *   tid = java_lang_Thread::tid(vthread);
3494  *   u2 vthread_epoch_raw = java_lang_Thread::jfr_epoch(vthread);
3495  *   pinVirtualThread = VMContinuations;
3496  *   excluded = vthread_epoch_raw & excluded_mask;
3497  *   if (!excluded) {
3498  *     traceid current_epoch = JfrTraceIdEpoch::current_generation();
3499  *     u2 vthread_epoch = vthread_epoch_raw & epoch_mask;
3500  *     if (vthread_epoch != current_epoch) {
3501  *       write_checkpoint();
3502  *     }
3503  *   }
3504  * } else {
3505  *   tid = java_lang_Thread::tid(threadObj);
3506  *   u2 thread_epoch_raw = java_lang_Thread::jfr_epoch(threadObj);
3507  *   pinVirtualThread = false;
3508  *   excluded = thread_epoch_raw & excluded_mask;
3509  * }
3510  * oop event_writer = JNIHandles::resolve_non_null(h_event_writer);
3511  * traceid tid_in_event_writer = getField(event_writer, "threadID");
3512  * if (tid_in_event_writer != tid) {
3513  *   setField(event_writer, "pinVirtualThread", pinVirtualThread);
3514  *   setField(event_writer, "excluded", excluded);
3515  *   setField(event_writer, "threadID", tid);
3516  * }
3517  * return event_writer
3518  */
3519 bool LibraryCallKit::inline_native_getEventWriter() {
3520   enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
3521 
3522   // Save input memory and i_o state.
3523   Node* input_memory_state = reset_memory();
3524   set_all_memory(input_memory_state);
3525   Node* input_io_state = i_o();
3526 
3527   // The most significant bit of the u2 is used to denote thread exclusion
3528   Node* excluded_shift = _gvn.intcon(15);
3529   Node* excluded_mask = _gvn.intcon(1 << 15);
3530   // The epoch generation is the range [1-32767]
3531   Node* epoch_mask = _gvn.intcon(32767);
3532 
3533   // TLS
3534   Node* tls_ptr = _gvn.transform(new ThreadLocalNode());
3535 
3536   // Load the address of java event writer jobject handle from the jfr_thread_local structure.
3537   Node* jobj_ptr = basic_plus_adr(top(), tls_ptr, in_bytes(THREAD_LOCAL_WRITER_OFFSET_JFR));
3538 
3539   // Load the eventwriter jobject handle.
3540   Node* jobj = make_load(control(), jobj_ptr, TypeRawPtr::BOTTOM, T_ADDRESS, MemNode::unordered);
3541 
3542   // Null check the jobject handle.
3543   Node* jobj_cmp_null = _gvn.transform(new CmpPNode(jobj, null()));
3544   Node* test_jobj_not_equal_null = _gvn.transform(new BoolNode(jobj_cmp_null, BoolTest::ne));
3545   IfNode* iff_jobj_not_equal_null = create_and_map_if(control(), test_jobj_not_equal_null, PROB_MAX, COUNT_UNKNOWN);
3546 
3547   // False path, jobj is null.
3548   Node* jobj_is_null = _gvn.transform(new IfFalseNode(iff_jobj_not_equal_null));
3549 
3550   // True path, jobj is not null.
3551   Node* jobj_is_not_null = _gvn.transform(new IfTrueNode(iff_jobj_not_equal_null));
3552 
3553   set_control(jobj_is_not_null);
3554 
3555   // Load the threadObj for the CarrierThread.
3556   Node* threadObj = generate_current_thread(tls_ptr);
3557 
3558   // Load the vthread.
3559   Node* vthread = generate_virtual_thread(tls_ptr);
3560 
3561   // If vthread != threadObj, this is a virtual thread.
3562   Node* vthread_cmp_threadObj = _gvn.transform(new CmpPNode(vthread, threadObj));
3563   Node* test_vthread_not_equal_threadObj = _gvn.transform(new BoolNode(vthread_cmp_threadObj, BoolTest::ne));
3564   IfNode* iff_vthread_not_equal_threadObj =
3565     create_and_map_if(jobj_is_not_null, test_vthread_not_equal_threadObj, PROB_FAIR, COUNT_UNKNOWN);
3566 
3567   // False branch, fallback to threadObj.
3568   Node* vthread_equal_threadObj = _gvn.transform(new IfFalseNode(iff_vthread_not_equal_threadObj));
3569   set_control(vthread_equal_threadObj);
3570 
3571   // Load the tid field from the vthread object.
3572   Node* thread_obj_tid = load_field_from_object(threadObj, "tid", "J");
3573 
3574   // Load the raw epoch value from the threadObj.
3575   Node* threadObj_epoch_offset = basic_plus_adr(threadObj, java_lang_Thread::jfr_epoch_offset());
3576   Node* threadObj_epoch_raw = access_load_at(threadObj, threadObj_epoch_offset,
3577                                              _gvn.type(threadObj_epoch_offset)->isa_ptr(),
3578                                              TypeInt::CHAR, T_CHAR,
3579                                              IN_HEAP | MO_UNORDERED | C2_MISMATCHED | C2_CONTROL_DEPENDENT_LOAD);
3580 
3581   // Mask off the excluded information from the epoch.
3582   Node * threadObj_is_excluded = _gvn.transform(new AndINode(threadObj_epoch_raw, excluded_mask));
3583 
3584   // True branch, this is a virtual thread.
3585   Node* vthread_not_equal_threadObj = _gvn.transform(new IfTrueNode(iff_vthread_not_equal_threadObj));
3586   set_control(vthread_not_equal_threadObj);
3587 
3588   // Load the tid field from the vthread object.
3589   Node* vthread_tid = load_field_from_object(vthread, "tid", "J");
3590 
3591   // Continuation support determines if a virtual thread should be pinned.
3592   Node* global_addr = makecon(TypeRawPtr::make((address)&VMContinuations));
3593   Node* continuation_support = make_load(control(), global_addr, TypeInt::BOOL, T_BOOLEAN, MemNode::unordered);
3594 
3595   // Load the raw epoch value from the vthread.
3596   Node* vthread_epoch_offset = basic_plus_adr(vthread, java_lang_Thread::jfr_epoch_offset());
3597   Node* vthread_epoch_raw = access_load_at(vthread, vthread_epoch_offset, _gvn.type(vthread_epoch_offset)->is_ptr(),
3598                                            TypeInt::CHAR, T_CHAR,
3599                                            IN_HEAP | MO_UNORDERED | C2_MISMATCHED | C2_CONTROL_DEPENDENT_LOAD);
3600 
3601   // Mask off the excluded information from the epoch.
3602   Node * vthread_is_excluded = _gvn.transform(new AndINode(vthread_epoch_raw, _gvn.transform(excluded_mask)));
3603 
3604   // Branch on excluded to conditionalize updating the epoch for the virtual thread.
3605   Node* is_excluded_cmp = _gvn.transform(new CmpINode(vthread_is_excluded, _gvn.transform(excluded_mask)));
3606   Node* test_not_excluded = _gvn.transform(new BoolNode(is_excluded_cmp, BoolTest::ne));
3607   IfNode* iff_not_excluded = create_and_map_if(control(), test_not_excluded, PROB_MAX, COUNT_UNKNOWN);
3608 
3609   // False branch, vthread is excluded, no need to write epoch info.
3610   Node* excluded = _gvn.transform(new IfFalseNode(iff_not_excluded));
3611 
3612   // True branch, vthread is included, update epoch info.
3613   Node* included = _gvn.transform(new IfTrueNode(iff_not_excluded));
3614   set_control(included);
3615 
3616   // Get epoch value.
3617   Node* epoch = _gvn.transform(new AndINode(vthread_epoch_raw, _gvn.transform(epoch_mask)));
3618 
3619   // Load the current epoch generation. The value is unsigned 16-bit, so we type it as T_CHAR.
3620   Node* epoch_generation_address = makecon(TypeRawPtr::make(JfrIntrinsicSupport::epoch_generation_address()));
3621   Node* current_epoch_generation = make_load(control(), epoch_generation_address, TypeInt::CHAR, T_CHAR, MemNode::unordered);
3622 
3623   // Compare the epoch in the vthread to the current epoch generation.
3624   Node* const epoch_cmp = _gvn.transform(new CmpUNode(current_epoch_generation, epoch));
3625   Node* test_epoch_not_equal = _gvn.transform(new BoolNode(epoch_cmp, BoolTest::ne));
3626   IfNode* iff_epoch_not_equal = create_and_map_if(control(), test_epoch_not_equal, PROB_FAIR, COUNT_UNKNOWN);
3627 
3628   // False path, epoch is equal, checkpoint information is valid.
3629   Node* epoch_is_equal = _gvn.transform(new IfFalseNode(iff_epoch_not_equal));
3630 
3631   // True path, epoch is not equal, write a checkpoint for the vthread.
3632   Node* epoch_is_not_equal = _gvn.transform(new IfTrueNode(iff_epoch_not_equal));
3633 
3634   set_control(epoch_is_not_equal);
3635 
3636   // Make a runtime call, which can safepoint, to write a checkpoint for the vthread for this epoch.
3637   // The call also updates the native thread local thread id and the vthread with the current epoch.
3638   Node* call_write_checkpoint = make_runtime_call(RC_NO_LEAF,
3639                                                   OptoRuntime::jfr_write_checkpoint_Type(),
3640                                                   SharedRuntime::jfr_write_checkpoint(),
3641                                                   "write_checkpoint", TypePtr::BOTTOM);
3642   Node* call_write_checkpoint_control = _gvn.transform(new ProjNode(call_write_checkpoint, TypeFunc::Control));
3643 
3644   // vthread epoch != current epoch
3645   RegionNode* epoch_compare_rgn = new RegionNode(PATH_LIMIT);
3646   record_for_igvn(epoch_compare_rgn);
3647   PhiNode* epoch_compare_mem = new PhiNode(epoch_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3648   record_for_igvn(epoch_compare_mem);
3649   PhiNode* epoch_compare_io = new PhiNode(epoch_compare_rgn, Type::ABIO);
3650   record_for_igvn(epoch_compare_io);
3651 
3652   // Update control and phi nodes.
3653   epoch_compare_rgn->init_req(_true_path, call_write_checkpoint_control);
3654   epoch_compare_rgn->init_req(_false_path, epoch_is_equal);
3655   epoch_compare_mem->init_req(_true_path, _gvn.transform(reset_memory()));
3656   epoch_compare_mem->init_req(_false_path, input_memory_state);
3657   epoch_compare_io->init_req(_true_path, i_o());
3658   epoch_compare_io->init_req(_false_path, input_io_state);
3659 
3660   // excluded != true
3661   RegionNode* exclude_compare_rgn = new RegionNode(PATH_LIMIT);
3662   record_for_igvn(exclude_compare_rgn);
3663   PhiNode* exclude_compare_mem = new PhiNode(exclude_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3664   record_for_igvn(exclude_compare_mem);
3665   PhiNode* exclude_compare_io = new PhiNode(exclude_compare_rgn, Type::ABIO);
3666   record_for_igvn(exclude_compare_io);
3667 
3668   // Update control and phi nodes.
3669   exclude_compare_rgn->init_req(_true_path, _gvn.transform(epoch_compare_rgn));
3670   exclude_compare_rgn->init_req(_false_path, excluded);
3671   exclude_compare_mem->init_req(_true_path, _gvn.transform(epoch_compare_mem));
3672   exclude_compare_mem->init_req(_false_path, input_memory_state);
3673   exclude_compare_io->init_req(_true_path, _gvn.transform(epoch_compare_io));
3674   exclude_compare_io->init_req(_false_path, input_io_state);
3675 
3676   // vthread != threadObj
3677   RegionNode* vthread_compare_rgn = new RegionNode(PATH_LIMIT);
3678   record_for_igvn(vthread_compare_rgn);
3679   PhiNode* vthread_compare_mem = new PhiNode(vthread_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3680   PhiNode* vthread_compare_io = new PhiNode(vthread_compare_rgn, Type::ABIO);
3681   record_for_igvn(vthread_compare_io);
3682   PhiNode* tid = new PhiNode(vthread_compare_rgn, TypeLong::LONG);
3683   record_for_igvn(tid);
3684   PhiNode* exclusion = new PhiNode(vthread_compare_rgn, TypeInt::CHAR);
3685   record_for_igvn(exclusion);
3686   PhiNode* pinVirtualThread = new PhiNode(vthread_compare_rgn, TypeInt::BOOL);
3687   record_for_igvn(pinVirtualThread);
3688 
3689   // Update control and phi nodes.
3690   vthread_compare_rgn->init_req(_true_path, _gvn.transform(exclude_compare_rgn));
3691   vthread_compare_rgn->init_req(_false_path, vthread_equal_threadObj);
3692   vthread_compare_mem->init_req(_true_path, _gvn.transform(exclude_compare_mem));
3693   vthread_compare_mem->init_req(_false_path, input_memory_state);
3694   vthread_compare_io->init_req(_true_path, _gvn.transform(exclude_compare_io));
3695   vthread_compare_io->init_req(_false_path, input_io_state);
3696   tid->init_req(_true_path, _gvn.transform(vthread_tid));
3697   tid->init_req(_false_path, _gvn.transform(thread_obj_tid));
3698   exclusion->init_req(_true_path, _gvn.transform(vthread_is_excluded));
3699   exclusion->init_req(_false_path, _gvn.transform(threadObj_is_excluded));
3700   pinVirtualThread->init_req(_true_path, _gvn.transform(continuation_support));
3701   pinVirtualThread->init_req(_false_path, _gvn.intcon(0));
3702 
3703   // Update branch state.
3704   set_control(_gvn.transform(vthread_compare_rgn));
3705   set_all_memory(_gvn.transform(vthread_compare_mem));
3706   set_i_o(_gvn.transform(vthread_compare_io));
3707 
3708   // Load the event writer oop by dereferencing the jobject handle.
3709   ciKlass* klass_EventWriter = env()->find_system_klass(ciSymbol::make("jdk/jfr/internal/event/EventWriter"));
3710   assert(klass_EventWriter->is_loaded(), "invariant");
3711   ciInstanceKlass* const instklass_EventWriter = klass_EventWriter->as_instance_klass();
3712   const TypeKlassPtr* const aklass = TypeKlassPtr::make(instklass_EventWriter);
3713   const TypeOopPtr* const xtype = aklass->as_instance_type();
3714   Node* jobj_untagged = _gvn.transform(new AddPNode(top(), jobj, _gvn.MakeConX(-JNIHandles::TypeTag::global)));
3715   Node* event_writer = access_load(jobj_untagged, xtype, T_OBJECT, IN_NATIVE | C2_CONTROL_DEPENDENT_LOAD);
3716 
3717   // Load the current thread id from the event writer object.
3718   Node* const event_writer_tid = load_field_from_object(event_writer, "threadID", "J");
3719   // Get the field offset to, conditionally, store an updated tid value later.
3720   Node* const event_writer_tid_field = field_address_from_object(event_writer, "threadID", "J", false);
3721   // Get the field offset to, conditionally, store an updated exclusion value later.
3722   Node* const event_writer_excluded_field = field_address_from_object(event_writer, "excluded", "Z", false);
3723   // Get the field offset to, conditionally, store an updated pinVirtualThread value later.
3724   Node* const event_writer_pin_field = field_address_from_object(event_writer, "pinVirtualThread", "Z", false);
3725 
3726   RegionNode* event_writer_tid_compare_rgn = new RegionNode(PATH_LIMIT);
3727   record_for_igvn(event_writer_tid_compare_rgn);
3728   PhiNode* event_writer_tid_compare_mem = new PhiNode(event_writer_tid_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3729   record_for_igvn(event_writer_tid_compare_mem);
3730   PhiNode* event_writer_tid_compare_io = new PhiNode(event_writer_tid_compare_rgn, Type::ABIO);
3731   record_for_igvn(event_writer_tid_compare_io);
3732 
3733   // Compare the current tid from the thread object to what is currently stored in the event writer object.
3734   Node* const tid_cmp = _gvn.transform(new CmpLNode(event_writer_tid, _gvn.transform(tid)));
3735   Node* test_tid_not_equal = _gvn.transform(new BoolNode(tid_cmp, BoolTest::ne));
3736   IfNode* iff_tid_not_equal = create_and_map_if(_gvn.transform(vthread_compare_rgn), test_tid_not_equal, PROB_FAIR, COUNT_UNKNOWN);
3737 
3738   // False path, tids are the same.
3739   Node* tid_is_equal = _gvn.transform(new IfFalseNode(iff_tid_not_equal));
3740 
3741   // True path, tid is not equal, need to update the tid in the event writer.
3742   Node* tid_is_not_equal = _gvn.transform(new IfTrueNode(iff_tid_not_equal));
3743   record_for_igvn(tid_is_not_equal);
3744 
3745   // Store the pin state to the event writer.
3746   store_to_memory(tid_is_not_equal, event_writer_pin_field, _gvn.transform(pinVirtualThread), T_BOOLEAN, MemNode::unordered);
3747 
3748   // Store the exclusion state to the event writer.
3749   Node* excluded_bool = _gvn.transform(new URShiftINode(_gvn.transform(exclusion), excluded_shift));
3750   store_to_memory(tid_is_not_equal, event_writer_excluded_field, excluded_bool, T_BOOLEAN, MemNode::unordered);
3751 
3752   // Store the tid to the event writer.
3753   store_to_memory(tid_is_not_equal, event_writer_tid_field, tid, T_LONG, MemNode::unordered);
3754 
3755   // Update control and phi nodes.
3756   event_writer_tid_compare_rgn->init_req(_true_path, tid_is_not_equal);
3757   event_writer_tid_compare_rgn->init_req(_false_path, tid_is_equal);
3758   event_writer_tid_compare_mem->init_req(_true_path, _gvn.transform(reset_memory()));
3759   event_writer_tid_compare_mem->init_req(_false_path, _gvn.transform(vthread_compare_mem));
3760   event_writer_tid_compare_io->init_req(_true_path, _gvn.transform(i_o()));
3761   event_writer_tid_compare_io->init_req(_false_path, _gvn.transform(vthread_compare_io));
3762 
3763   // Result of top level CFG, Memory, IO and Value.
3764   RegionNode* result_rgn = new RegionNode(PATH_LIMIT);
3765   PhiNode* result_mem = new PhiNode(result_rgn, Type::MEMORY, TypePtr::BOTTOM);
3766   PhiNode* result_io = new PhiNode(result_rgn, Type::ABIO);
3767   PhiNode* result_value = new PhiNode(result_rgn, TypeInstPtr::BOTTOM);
3768 
3769   // Result control.
3770   result_rgn->init_req(_true_path, _gvn.transform(event_writer_tid_compare_rgn));
3771   result_rgn->init_req(_false_path, jobj_is_null);
3772 
3773   // Result memory.
3774   result_mem->init_req(_true_path, _gvn.transform(event_writer_tid_compare_mem));
3775   result_mem->init_req(_false_path, _gvn.transform(input_memory_state));
3776 
3777   // Result IO.
3778   result_io->init_req(_true_path, _gvn.transform(event_writer_tid_compare_io));
3779   result_io->init_req(_false_path, _gvn.transform(input_io_state));
3780 
3781   // Result value.
3782   result_value->init_req(_true_path, _gvn.transform(event_writer)); // return event writer oop
3783   result_value->init_req(_false_path, null()); // return null
3784 
3785   // Set output state.
3786   set_control(_gvn.transform(result_rgn));
3787   set_all_memory(_gvn.transform(result_mem));
3788   set_i_o(_gvn.transform(result_io));
3789   set_result(result_rgn, result_value);
3790   return true;
3791 }
3792 
3793 /*
3794  * The intrinsic is a model of this pseudo-code:
3795  *
3796  * JfrThreadLocal* const tl = thread->jfr_thread_local();
3797  * if (carrierThread != thread) { // is virtual thread
3798  *   const u2 vthread_epoch_raw = java_lang_Thread::jfr_epoch(thread);
3799  *   bool excluded = vthread_epoch_raw & excluded_mask;
3800  *   Atomic::store(&tl->_contextual_tid, java_lang_Thread::tid(thread));
3801  *   Atomic::store(&tl->_contextual_thread_excluded, is_excluded);
3802  *   if (!excluded) {
3803  *     const u2 vthread_epoch = vthread_epoch_raw & epoch_mask;
3804  *     Atomic::store(&tl->_vthread_epoch, vthread_epoch);
3805  *   }
3806  *   Atomic::release_store(&tl->_vthread, true);
3807  *   return;
3808  * }
3809  * Atomic::release_store(&tl->_vthread, false);
3810  */
3811 void LibraryCallKit::extend_setCurrentThread(Node* jt, Node* thread) {
3812   enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
3813 
3814   Node* input_memory_state = reset_memory();
3815   set_all_memory(input_memory_state);
3816 
3817   // The most significant bit of the u2 is used to denote thread exclusion
3818   Node* excluded_mask = _gvn.intcon(1 << 15);
3819   // The epoch generation is the range [1-32767]
3820   Node* epoch_mask = _gvn.intcon(32767);
3821 
3822   Node* const carrierThread = generate_current_thread(jt);
3823   // If thread != carrierThread, this is a virtual thread.
3824   Node* thread_cmp_carrierThread = _gvn.transform(new CmpPNode(thread, carrierThread));
3825   Node* test_thread_not_equal_carrierThread = _gvn.transform(new BoolNode(thread_cmp_carrierThread, BoolTest::ne));
3826   IfNode* iff_thread_not_equal_carrierThread =
3827     create_and_map_if(control(), test_thread_not_equal_carrierThread, PROB_FAIR, COUNT_UNKNOWN);
3828 
3829   Node* vthread_offset = basic_plus_adr(jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_OFFSET_JFR));
3830 
3831   // False branch, is carrierThread.
3832   Node* thread_equal_carrierThread = _gvn.transform(new IfFalseNode(iff_thread_not_equal_carrierThread));
3833   // Store release
3834   Node* vthread_false_memory = store_to_memory(thread_equal_carrierThread, vthread_offset, _gvn.intcon(0), T_BOOLEAN, MemNode::release, true);
3835 
3836   set_all_memory(input_memory_state);
3837 
3838   // True branch, is virtual thread.
3839   Node* thread_not_equal_carrierThread = _gvn.transform(new IfTrueNode(iff_thread_not_equal_carrierThread));
3840   set_control(thread_not_equal_carrierThread);
3841 
3842   // Load the raw epoch value from the vthread.
3843   Node* epoch_offset = basic_plus_adr(thread, java_lang_Thread::jfr_epoch_offset());
3844   Node* epoch_raw = access_load_at(thread, epoch_offset, _gvn.type(epoch_offset)->is_ptr(), TypeInt::CHAR, T_CHAR,
3845                                    IN_HEAP | MO_UNORDERED | C2_MISMATCHED | C2_CONTROL_DEPENDENT_LOAD);
3846 
3847   // Mask off the excluded information from the epoch.
3848   Node * const is_excluded = _gvn.transform(new AndINode(epoch_raw, _gvn.transform(excluded_mask)));
3849 
3850   // Load the tid field from the thread.
3851   Node* tid = load_field_from_object(thread, "tid", "J");
3852 
3853   // Store the vthread tid to the jfr thread local.
3854   Node* thread_id_offset = basic_plus_adr(jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_ID_OFFSET_JFR));
3855   Node* tid_memory = store_to_memory(control(), thread_id_offset, tid, T_LONG, MemNode::unordered, true);
3856 
3857   // Branch is_excluded to conditionalize updating the epoch .
3858   Node* excluded_cmp = _gvn.transform(new CmpINode(is_excluded, _gvn.transform(excluded_mask)));
3859   Node* test_excluded = _gvn.transform(new BoolNode(excluded_cmp, BoolTest::eq));
3860   IfNode* iff_excluded = create_and_map_if(control(), test_excluded, PROB_MIN, COUNT_UNKNOWN);
3861 
3862   // True branch, vthread is excluded, no need to write epoch info.
3863   Node* excluded = _gvn.transform(new IfTrueNode(iff_excluded));
3864   set_control(excluded);
3865   Node* vthread_is_excluded = _gvn.intcon(1);
3866 
3867   // False branch, vthread is included, update epoch info.
3868   Node* included = _gvn.transform(new IfFalseNode(iff_excluded));
3869   set_control(included);
3870   Node* vthread_is_included = _gvn.intcon(0);
3871 
3872   // Get epoch value.
3873   Node* epoch = _gvn.transform(new AndINode(epoch_raw, _gvn.transform(epoch_mask)));
3874 
3875   // Store the vthread epoch to the jfr thread local.
3876   Node* vthread_epoch_offset = basic_plus_adr(jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_EPOCH_OFFSET_JFR));
3877   Node* included_memory = store_to_memory(control(), vthread_epoch_offset, epoch, T_CHAR, MemNode::unordered, true);
3878 
3879   RegionNode* excluded_rgn = new RegionNode(PATH_LIMIT);
3880   record_for_igvn(excluded_rgn);
3881   PhiNode* excluded_mem = new PhiNode(excluded_rgn, Type::MEMORY, TypePtr::BOTTOM);
3882   record_for_igvn(excluded_mem);
3883   PhiNode* exclusion = new PhiNode(excluded_rgn, TypeInt::BOOL);
3884   record_for_igvn(exclusion);
3885 
3886   // Merge the excluded control and memory.
3887   excluded_rgn->init_req(_true_path, excluded);
3888   excluded_rgn->init_req(_false_path, included);
3889   excluded_mem->init_req(_true_path, tid_memory);
3890   excluded_mem->init_req(_false_path, included_memory);
3891   exclusion->init_req(_true_path, _gvn.transform(vthread_is_excluded));
3892   exclusion->init_req(_false_path, _gvn.transform(vthread_is_included));
3893 
3894   // Set intermediate state.
3895   set_control(_gvn.transform(excluded_rgn));
3896   set_all_memory(excluded_mem);
3897 
3898   // Store the vthread exclusion state to the jfr thread local.
3899   Node* thread_local_excluded_offset = basic_plus_adr(jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_EXCLUDED_OFFSET_JFR));
3900   store_to_memory(control(), thread_local_excluded_offset, _gvn.transform(exclusion), T_BOOLEAN, MemNode::unordered, true);
3901 
3902   // Store release
3903   Node * vthread_true_memory = store_to_memory(control(), vthread_offset, _gvn.intcon(1), T_BOOLEAN, MemNode::release, true);
3904 
3905   RegionNode* thread_compare_rgn = new RegionNode(PATH_LIMIT);
3906   record_for_igvn(thread_compare_rgn);
3907   PhiNode* thread_compare_mem = new PhiNode(thread_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3908   record_for_igvn(thread_compare_mem);
3909   PhiNode* vthread = new PhiNode(thread_compare_rgn, TypeInt::BOOL);
3910   record_for_igvn(vthread);
3911 
3912   // Merge the thread_compare control and memory.
3913   thread_compare_rgn->init_req(_true_path, control());
3914   thread_compare_rgn->init_req(_false_path, thread_equal_carrierThread);
3915   thread_compare_mem->init_req(_true_path, vthread_true_memory);
3916   thread_compare_mem->init_req(_false_path, vthread_false_memory);
3917 
3918   // Set output state.
3919   set_control(_gvn.transform(thread_compare_rgn));
3920   set_all_memory(_gvn.transform(thread_compare_mem));
3921 }
3922 
3923 #endif // JFR_HAVE_INTRINSICS
3924 
3925 //------------------------inline_native_currentCarrierThread------------------
3926 bool LibraryCallKit::inline_native_currentCarrierThread() {
3927   Node* junk = nullptr;
3928   set_result(generate_current_thread(junk));
3929   return true;
3930 }
3931 
3932 //------------------------inline_native_currentThread------------------
3933 bool LibraryCallKit::inline_native_currentThread() {
3934   Node* junk = nullptr;
3935   set_result(generate_virtual_thread(junk));
3936   return true;
3937 }
3938 
3939 //------------------------inline_native_setVthread------------------
3940 bool LibraryCallKit::inline_native_setCurrentThread() {
3941   assert(C->method()->changes_current_thread(),
3942          "method changes current Thread but is not annotated ChangesCurrentThread");
3943   Node* arr = argument(1);
3944   Node* thread = _gvn.transform(new ThreadLocalNode());
3945   Node* p = basic_plus_adr(top()/*!oop*/, thread, in_bytes(JavaThread::vthread_offset()));
3946   Node* thread_obj_handle
3947     = make_load(nullptr, p, p->bottom_type()->is_ptr(), T_OBJECT, MemNode::unordered);
3948   thread_obj_handle = _gvn.transform(thread_obj_handle);
3949   const TypePtr *adr_type = _gvn.type(thread_obj_handle)->isa_ptr();
3950   access_store_at(nullptr, thread_obj_handle, adr_type, arr, _gvn.type(arr), T_OBJECT, IN_NATIVE | MO_UNORDERED);
3951 
3952   // Change the _monitor_owner_id of the JavaThread
3953   Node* tid = load_field_from_object(arr, "tid", "J");
3954   Node* monitor_owner_id_offset = basic_plus_adr(thread, in_bytes(JavaThread::monitor_owner_id_offset()));
3955   store_to_memory(control(), monitor_owner_id_offset, tid, T_LONG, MemNode::unordered, true);
3956 
3957   JFR_ONLY(extend_setCurrentThread(thread, arr);)
3958   return true;
3959 }
3960 
3961 const Type* LibraryCallKit::scopedValueCache_type() {
3962   ciKlass* objects_klass = ciObjArrayKlass::make(env()->Object_klass());
3963   const TypeOopPtr* etype = TypeOopPtr::make_from_klass(env()->Object_klass());
3964   const TypeAry* arr0 = TypeAry::make(etype, TypeInt::POS, /* stable= */ false, /* flat= */ false, /* not_flat= */ true, /* not_null_free= */ true);
3965 
3966   // Because we create the scopedValue cache lazily we have to make the
3967   // type of the result BotPTR.
3968   bool xk = etype->klass_is_exact();
3969   const Type* objects_type = TypeAryPtr::make(TypePtr::BotPTR, arr0, objects_klass, xk, TypeAryPtr::Offset(0));
3970   return objects_type;
3971 }
3972 
3973 Node* LibraryCallKit::scopedValueCache_helper() {
3974   Node* thread = _gvn.transform(new ThreadLocalNode());
3975   Node* p = basic_plus_adr(top()/*!oop*/, thread, in_bytes(JavaThread::scopedValueCache_offset()));
3976   // We cannot use immutable_memory() because we might flip onto a
3977   // different carrier thread, at which point we'll need to use that
3978   // carrier thread's cache.
3979   // return _gvn.transform(LoadNode::make(_gvn, nullptr, immutable_memory(), p, p->bottom_type()->is_ptr(),
3980   //       TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered));
3981   return make_load(nullptr, p, p->bottom_type()->is_ptr(), T_ADDRESS, MemNode::unordered);
3982 }
3983 
3984 //------------------------inline_native_scopedValueCache------------------
3985 bool LibraryCallKit::inline_native_scopedValueCache() {
3986   Node* cache_obj_handle = scopedValueCache_helper();
3987   const Type* objects_type = scopedValueCache_type();
3988   set_result(access_load(cache_obj_handle, objects_type, T_OBJECT, IN_NATIVE));
3989 
3990   return true;
3991 }
3992 
3993 //------------------------inline_native_setScopedValueCache------------------
3994 bool LibraryCallKit::inline_native_setScopedValueCache() {
3995   Node* arr = argument(0);
3996   Node* cache_obj_handle = scopedValueCache_helper();
3997   const Type* objects_type = scopedValueCache_type();
3998 
3999   const TypePtr *adr_type = _gvn.type(cache_obj_handle)->isa_ptr();
4000   access_store_at(nullptr, cache_obj_handle, adr_type, arr, objects_type, T_OBJECT, IN_NATIVE | MO_UNORDERED);
4001 
4002   return true;
4003 }
4004 
4005 //------------------------inline_native_Continuation_pin and unpin-----------
4006 
4007 // Shared implementation routine for both pin and unpin.
4008 bool LibraryCallKit::inline_native_Continuation_pinning(bool unpin) {
4009   enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
4010 
4011   // Save input memory.
4012   Node* input_memory_state = reset_memory();
4013   set_all_memory(input_memory_state);
4014 
4015   // TLS
4016   Node* tls_ptr = _gvn.transform(new ThreadLocalNode());
4017   Node* last_continuation_offset = basic_plus_adr(top(), tls_ptr, in_bytes(JavaThread::cont_entry_offset()));
4018   Node* last_continuation = make_load(control(), last_continuation_offset, last_continuation_offset->get_ptr_type(), T_ADDRESS, MemNode::unordered);
4019 
4020   // Null check the last continuation object.
4021   Node* continuation_cmp_null = _gvn.transform(new CmpPNode(last_continuation, null()));
4022   Node* test_continuation_not_equal_null = _gvn.transform(new BoolNode(continuation_cmp_null, BoolTest::ne));
4023   IfNode* iff_continuation_not_equal_null = create_and_map_if(control(), test_continuation_not_equal_null, PROB_MAX, COUNT_UNKNOWN);
4024 
4025   // False path, last continuation is null.
4026   Node* continuation_is_null = _gvn.transform(new IfFalseNode(iff_continuation_not_equal_null));
4027 
4028   // True path, last continuation is not null.
4029   Node* continuation_is_not_null = _gvn.transform(new IfTrueNode(iff_continuation_not_equal_null));
4030 
4031   set_control(continuation_is_not_null);
4032 
4033   // Load the pin count from the last continuation.
4034   Node* pin_count_offset = basic_plus_adr(top(), last_continuation, in_bytes(ContinuationEntry::pin_count_offset()));
4035   Node* pin_count = make_load(control(), pin_count_offset, TypeInt::INT, T_INT, MemNode::unordered);
4036 
4037   // The loaded pin count is compared against a context specific rhs for over/underflow detection.
4038   Node* pin_count_rhs;
4039   if (unpin) {
4040     pin_count_rhs = _gvn.intcon(0);
4041   } else {
4042     pin_count_rhs = _gvn.intcon(UINT32_MAX);
4043   }
4044   Node* pin_count_cmp = _gvn.transform(new CmpUNode(_gvn.transform(pin_count), pin_count_rhs));
4045   Node* test_pin_count_over_underflow = _gvn.transform(new BoolNode(pin_count_cmp, BoolTest::eq));
4046   IfNode* iff_pin_count_over_underflow = create_and_map_if(control(), test_pin_count_over_underflow, PROB_MIN, COUNT_UNKNOWN);
4047 
4048   // True branch, pin count over/underflow.
4049   Node* pin_count_over_underflow = _gvn.transform(new IfTrueNode(iff_pin_count_over_underflow));
4050   {
4051     // Trap (but not deoptimize (Action_none)) and continue in the interpreter
4052     // which will throw IllegalStateException for pin count over/underflow.
4053     // No memory changed so far - we can use memory create by reset_memory()
4054     // at the beginning of this intrinsic. No need to call reset_memory() again.
4055     PreserveJVMState pjvms(this);
4056     set_control(pin_count_over_underflow);
4057     uncommon_trap(Deoptimization::Reason_intrinsic,
4058                   Deoptimization::Action_none);
4059     assert(stopped(), "invariant");
4060   }
4061 
4062   // False branch, no pin count over/underflow. Increment or decrement pin count and store back.
4063   Node* valid_pin_count = _gvn.transform(new IfFalseNode(iff_pin_count_over_underflow));
4064   set_control(valid_pin_count);
4065 
4066   Node* next_pin_count;
4067   if (unpin) {
4068     next_pin_count = _gvn.transform(new SubINode(pin_count, _gvn.intcon(1)));
4069   } else {
4070     next_pin_count = _gvn.transform(new AddINode(pin_count, _gvn.intcon(1)));
4071   }
4072 
4073   store_to_memory(control(), pin_count_offset, next_pin_count, T_INT, MemNode::unordered);
4074 
4075   // Result of top level CFG and Memory.
4076   RegionNode* result_rgn = new RegionNode(PATH_LIMIT);
4077   record_for_igvn(result_rgn);
4078   PhiNode* result_mem = new PhiNode(result_rgn, Type::MEMORY, TypePtr::BOTTOM);
4079   record_for_igvn(result_mem);
4080 
4081   result_rgn->init_req(_true_path, _gvn.transform(valid_pin_count));
4082   result_rgn->init_req(_false_path, _gvn.transform(continuation_is_null));
4083   result_mem->init_req(_true_path, _gvn.transform(reset_memory()));
4084   result_mem->init_req(_false_path, _gvn.transform(input_memory_state));
4085 
4086   // Set output state.
4087   set_control(_gvn.transform(result_rgn));
4088   set_all_memory(_gvn.transform(result_mem));
4089 
4090   return true;
4091 }
4092 
4093 //-----------------------load_klass_from_mirror_common-------------------------
4094 // Given a java mirror (a java.lang.Class oop), load its corresponding klass oop.
4095 // Test the klass oop for null (signifying a primitive Class like Integer.TYPE),
4096 // and branch to the given path on the region.
4097 // If never_see_null, take an uncommon trap on null, so we can optimistically
4098 // compile for the non-null case.
4099 // If the region is null, force never_see_null = true.
4100 Node* LibraryCallKit::load_klass_from_mirror_common(Node* mirror,
4101                                                     bool never_see_null,
4102                                                     RegionNode* region,
4103                                                     int null_path,
4104                                                     int offset) {
4105   if (region == nullptr)  never_see_null = true;
4106   Node* p = basic_plus_adr(mirror, offset);
4107   const TypeKlassPtr*  kls_type = TypeInstKlassPtr::OBJECT_OR_NULL;
4108   Node* kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), p, TypeRawPtr::BOTTOM, kls_type));
4109   Node* null_ctl = top();
4110   kls = null_check_oop(kls, &null_ctl, never_see_null);
4111   if (region != nullptr) {
4112     // Set region->in(null_path) if the mirror is a primitive (e.g, int.class).
4113     region->init_req(null_path, null_ctl);
4114   } else {
4115     assert(null_ctl == top(), "no loose ends");
4116   }
4117   return kls;
4118 }
4119 
4120 //--------------------(inline_native_Class_query helpers)---------------------
4121 // Use this for JVM_ACC_INTERFACE.
4122 // Fall through if (mods & mask) == bits, take the guard otherwise.
4123 Node* LibraryCallKit::generate_klass_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region,
4124                                                  ByteSize offset, const Type* type, BasicType bt) {
4125   // Branch around if the given klass has the given modifier bit set.
4126   // Like generate_guard, adds a new path onto the region.
4127   Node* modp = basic_plus_adr(kls, in_bytes(offset));
4128   Node* mods = make_load(nullptr, modp, type, bt, MemNode::unordered);
4129   Node* mask = intcon(modifier_mask);
4130   Node* bits = intcon(modifier_bits);
4131   Node* mbit = _gvn.transform(new AndINode(mods, mask));
4132   Node* cmp  = _gvn.transform(new CmpINode(mbit, bits));
4133   Node* bol  = _gvn.transform(new BoolNode(cmp, BoolTest::ne));
4134   return generate_fair_guard(bol, region);
4135 }
4136 
4137 Node* LibraryCallKit::generate_interface_guard(Node* kls, RegionNode* region) {
4138   return generate_klass_flags_guard(kls, JVM_ACC_INTERFACE, 0, region,
4139                                     Klass::access_flags_offset(), TypeInt::CHAR, T_CHAR);
4140 }
4141 
4142 // Use this for testing if Klass is_hidden, has_finalizer, and is_cloneable_fast.
4143 Node* LibraryCallKit::generate_misc_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region) {
4144   return generate_klass_flags_guard(kls, modifier_mask, modifier_bits, region,
4145                                     Klass::misc_flags_offset(), TypeInt::UBYTE, T_BOOLEAN);
4146 }
4147 
4148 Node* LibraryCallKit::generate_hidden_class_guard(Node* kls, RegionNode* region) {
4149   return generate_misc_flags_guard(kls, KlassFlags::_misc_is_hidden_class, 0, region);
4150 }
4151 
4152 //-------------------------inline_native_Class_query-------------------
4153 bool LibraryCallKit::inline_native_Class_query(vmIntrinsics::ID id) {
4154   const Type* return_type = TypeInt::BOOL;
4155   Node* prim_return_value = top();  // what happens if it's a primitive class?
4156   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
4157   bool expect_prim = false;     // most of these guys expect to work on refs
4158 
4159   enum { _normal_path = 1, _prim_path = 2, PATH_LIMIT };
4160 
4161   Node* mirror = argument(0);
4162   Node* obj    = top();
4163 
4164   switch (id) {
4165   case vmIntrinsics::_isInstance:
4166     // nothing is an instance of a primitive type
4167     prim_return_value = intcon(0);
4168     obj = argument(1);
4169     break;
4170   case vmIntrinsics::_isHidden:
4171     prim_return_value = intcon(0);
4172     break;
4173   case vmIntrinsics::_getSuperclass:
4174     prim_return_value = null();
4175     return_type = TypeInstPtr::MIRROR->cast_to_ptr_type(TypePtr::BotPTR);
4176     break;
4177   case vmIntrinsics::_getClassAccessFlags:
4178     prim_return_value = intcon(JVM_ACC_ABSTRACT | JVM_ACC_FINAL | JVM_ACC_PUBLIC);
4179     return_type = TypeInt::CHAR;
4180     break;
4181   default:
4182     fatal_unexpected_iid(id);
4183     break;
4184   }
4185 
4186   const TypeInstPtr* mirror_con = _gvn.type(mirror)->isa_instptr();
4187   if (mirror_con == nullptr)  return false;  // cannot happen?
4188 
4189 #ifndef PRODUCT
4190   if (C->print_intrinsics() || C->print_inlining()) {
4191     ciType* k = mirror_con->java_mirror_type();
4192     if (k) {
4193       tty->print("Inlining %s on constant Class ", vmIntrinsics::name_at(intrinsic_id()));
4194       k->print_name();
4195       tty->cr();
4196     }
4197   }
4198 #endif
4199 
4200   // Null-check the mirror, and the mirror's klass ptr (in case it is a primitive).
4201   RegionNode* region = new RegionNode(PATH_LIMIT);
4202   record_for_igvn(region);
4203   PhiNode* phi = new PhiNode(region, return_type);
4204 
4205   // The mirror will never be null of Reflection.getClassAccessFlags, however
4206   // it may be null for Class.isInstance or Class.getModifiers. Throw a NPE
4207   // if it is. See bug 4774291.
4208 
4209   // For Reflection.getClassAccessFlags(), the null check occurs in
4210   // the wrong place; see inline_unsafe_access(), above, for a similar
4211   // situation.
4212   mirror = null_check(mirror);
4213   // If mirror or obj is dead, only null-path is taken.
4214   if (stopped())  return true;
4215 
4216   if (expect_prim)  never_see_null = false;  // expect nulls (meaning prims)
4217 
4218   // Now load the mirror's klass metaobject, and null-check it.
4219   // Side-effects region with the control path if the klass is null.
4220   Node* kls = load_klass_from_mirror(mirror, never_see_null, region, _prim_path);
4221   // If kls is null, we have a primitive mirror.
4222   phi->init_req(_prim_path, prim_return_value);
4223   if (stopped()) { set_result(region, phi); return true; }
4224   bool safe_for_replace = (region->in(_prim_path) == top());
4225 
4226   Node* p;  // handy temp
4227   Node* null_ctl;
4228 
4229   // Now that we have the non-null klass, we can perform the real query.
4230   // For constant classes, the query will constant-fold in LoadNode::Value.
4231   Node* query_value = top();
4232   switch (id) {
4233   case vmIntrinsics::_isInstance:
4234     // nothing is an instance of a primitive type
4235     query_value = gen_instanceof(obj, kls, safe_for_replace);
4236     break;
4237 
4238   case vmIntrinsics::_isHidden:
4239     // (To verify this code sequence, check the asserts in JVM_IsHiddenClass.)
4240     if (generate_hidden_class_guard(kls, region) != nullptr)
4241       // A guard was added.  If the guard is taken, it was an hidden class.
4242       phi->add_req(intcon(1));
4243     // If we fall through, it's a plain class.
4244     query_value = intcon(0);
4245     break;
4246 
4247 
4248   case vmIntrinsics::_getSuperclass:
4249     // The rules here are somewhat unfortunate, but we can still do better
4250     // with random logic than with a JNI call.
4251     // Interfaces store null or Object as _super, but must report null.
4252     // Arrays store an intermediate super as _super, but must report Object.
4253     // Other types can report the actual _super.
4254     // (To verify this code sequence, check the asserts in JVM_IsInterface.)
4255     if (generate_interface_guard(kls, region) != nullptr)
4256       // A guard was added.  If the guard is taken, it was an interface.
4257       phi->add_req(null());
4258     if (generate_array_guard(kls, region) != nullptr)
4259       // A guard was added.  If the guard is taken, it was an array.
4260       phi->add_req(makecon(TypeInstPtr::make(env()->Object_klass()->java_mirror())));
4261     // If we fall through, it's a plain class.  Get its _super.
4262     p = basic_plus_adr(kls, in_bytes(Klass::super_offset()));
4263     kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), p, TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
4264     null_ctl = top();
4265     kls = null_check_oop(kls, &null_ctl);
4266     if (null_ctl != top()) {
4267       // If the guard is taken, Object.superClass is null (both klass and mirror).
4268       region->add_req(null_ctl);
4269       phi   ->add_req(null());
4270     }
4271     if (!stopped()) {
4272       query_value = load_mirror_from_klass(kls);
4273     }
4274     break;
4275 
4276   case vmIntrinsics::_getClassAccessFlags:
4277     p = basic_plus_adr(kls, in_bytes(Klass::access_flags_offset()));
4278     query_value = make_load(nullptr, p, TypeInt::CHAR, T_CHAR, MemNode::unordered);
4279     break;
4280 
4281   default:
4282     fatal_unexpected_iid(id);
4283     break;
4284   }
4285 
4286   // Fall-through is the normal case of a query to a real class.
4287   phi->init_req(1, query_value);
4288   region->init_req(1, control());
4289 
4290   C->set_has_split_ifs(true); // Has chance for split-if optimization
4291   set_result(region, phi);
4292   return true;
4293 }
4294 
4295 
4296 //-------------------------inline_Class_cast-------------------
4297 bool LibraryCallKit::inline_Class_cast() {
4298   Node* mirror = argument(0); // Class
4299   Node* obj    = argument(1);
4300   const TypeInstPtr* mirror_con = _gvn.type(mirror)->isa_instptr();
4301   if (mirror_con == nullptr) {
4302     return false;  // dead path (mirror->is_top()).
4303   }
4304   if (obj == nullptr || obj->is_top()) {
4305     return false;  // dead path
4306   }
4307   const TypeOopPtr* tp = _gvn.type(obj)->isa_oopptr();
4308 
4309   // First, see if Class.cast() can be folded statically.
4310   // java_mirror_type() returns non-null for compile-time Class constants.
4311   bool is_null_free_array = false;
4312   ciType* tm = mirror_con->java_mirror_type(&is_null_free_array);
4313   if (tm != nullptr && tm->is_klass() &&
4314       tp != nullptr) {
4315     if (!tp->is_loaded()) {
4316       // Don't use intrinsic when class is not loaded.
4317       return false;
4318     } else {
4319       const TypeKlassPtr* tklass = TypeKlassPtr::make(tm->as_klass(), Type::trust_interfaces);
4320       if (is_null_free_array) {
4321         tklass = tklass->is_aryklassptr()->cast_to_null_free();
4322       }
4323       int static_res = C->static_subtype_check(tklass, tp->as_klass_type());
4324       if (static_res == Compile::SSC_always_true) {
4325         // isInstance() is true - fold the code.
4326         set_result(obj);
4327         return true;
4328       } else if (static_res == Compile::SSC_always_false) {
4329         // Don't use intrinsic, have to throw ClassCastException.
4330         // If the reference is null, the non-intrinsic bytecode will
4331         // be optimized appropriately.
4332         return false;
4333       }
4334     }
4335   }
4336 
4337   // Bailout intrinsic and do normal inlining if exception path is frequent.
4338   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
4339     return false;
4340   }
4341 
4342   // Generate dynamic checks.
4343   // Class.cast() is java implementation of _checkcast bytecode.
4344   // Do checkcast (Parse::do_checkcast()) optimizations here.
4345 
4346   mirror = null_check(mirror);
4347   // If mirror is dead, only null-path is taken.
4348   if (stopped()) {
4349     return true;
4350   }
4351 
4352   // Not-subtype or the mirror's klass ptr is nullptr (in case it is a primitive).
4353   enum { _bad_type_path = 1, _prim_path = 2, _npe_path = 3, PATH_LIMIT };
4354   RegionNode* region = new RegionNode(PATH_LIMIT);
4355   record_for_igvn(region);
4356 
4357   // Now load the mirror's klass metaobject, and null-check it.
4358   // If kls is null, we have a primitive mirror and
4359   // nothing is an instance of a primitive type.
4360   Node* kls = load_klass_from_mirror(mirror, false, region, _prim_path);
4361 
4362   Node* res = top();
4363   Node* io = i_o();
4364   Node* mem = merged_memory();
4365   if (!stopped()) {
4366 
4367     Node* bad_type_ctrl = top();
4368     // Do checkcast optimizations.
4369     res = gen_checkcast(obj, kls, &bad_type_ctrl);
4370     region->init_req(_bad_type_path, bad_type_ctrl);
4371   }
4372   if (region->in(_prim_path) != top() ||
4373       region->in(_bad_type_path) != top() ||
4374       region->in(_npe_path) != top()) {
4375     // Let Interpreter throw ClassCastException.
4376     PreserveJVMState pjvms(this);
4377     set_control(_gvn.transform(region));
4378     // Set IO and memory because gen_checkcast may override them when buffering inline types
4379     set_i_o(io);
4380     set_all_memory(mem);
4381     uncommon_trap(Deoptimization::Reason_intrinsic,
4382                   Deoptimization::Action_maybe_recompile);
4383   }
4384   if (!stopped()) {
4385     set_result(res);
4386   }
4387   return true;
4388 }
4389 
4390 
4391 //--------------------------inline_native_subtype_check------------------------
4392 // This intrinsic takes the JNI calls out of the heart of
4393 // UnsafeFieldAccessorImpl.set, which improves Field.set, readObject, etc.
4394 bool LibraryCallKit::inline_native_subtype_check() {
4395   // Pull both arguments off the stack.
4396   Node* args[2];                // two java.lang.Class mirrors: superc, subc
4397   args[0] = argument(0);
4398   args[1] = argument(1);
4399   Node* klasses[2];             // corresponding Klasses: superk, subk
4400   klasses[0] = klasses[1] = top();
4401 
4402   enum {
4403     // A full decision tree on {superc is prim, subc is prim}:
4404     _prim_0_path = 1,           // {P,N} => false
4405                                 // {P,P} & superc!=subc => false
4406     _prim_same_path,            // {P,P} & superc==subc => true
4407     _prim_1_path,               // {N,P} => false
4408     _ref_subtype_path,          // {N,N} & subtype check wins => true
4409     _both_ref_path,             // {N,N} & subtype check loses => false
4410     PATH_LIMIT
4411   };
4412 
4413   RegionNode* region = new RegionNode(PATH_LIMIT);
4414   RegionNode* prim_region = new RegionNode(2);
4415   Node*       phi    = new PhiNode(region, TypeInt::BOOL);
4416   record_for_igvn(region);
4417   record_for_igvn(prim_region);
4418 
4419   const TypePtr* adr_type = TypeRawPtr::BOTTOM;   // memory type of loads
4420   const TypeKlassPtr* kls_type = TypeInstKlassPtr::OBJECT_OR_NULL;
4421   int class_klass_offset = java_lang_Class::klass_offset();
4422 
4423   // First null-check both mirrors and load each mirror's klass metaobject.
4424   int which_arg;
4425   for (which_arg = 0; which_arg <= 1; which_arg++) {
4426     Node* arg = args[which_arg];
4427     arg = null_check(arg);
4428     if (stopped())  break;
4429     args[which_arg] = arg;
4430 
4431     Node* p = basic_plus_adr(arg, class_klass_offset);
4432     Node* kls = LoadKlassNode::make(_gvn, immutable_memory(), p, adr_type, kls_type);
4433     klasses[which_arg] = _gvn.transform(kls);
4434   }
4435 
4436   // Having loaded both klasses, test each for null.
4437   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
4438   for (which_arg = 0; which_arg <= 1; which_arg++) {
4439     Node* kls = klasses[which_arg];
4440     Node* null_ctl = top();
4441     kls = null_check_oop(kls, &null_ctl, never_see_null);
4442     if (which_arg == 0) {
4443       prim_region->init_req(1, null_ctl);
4444     } else {
4445       region->init_req(_prim_1_path, null_ctl);
4446     }
4447     if (stopped())  break;
4448     klasses[which_arg] = kls;
4449   }
4450 
4451   if (!stopped()) {
4452     // now we have two reference types, in klasses[0..1]
4453     Node* subk   = klasses[1];  // the argument to isAssignableFrom
4454     Node* superk = klasses[0];  // the receiver
4455     region->set_req(_both_ref_path, gen_subtype_check(subk, superk));
4456     region->set_req(_ref_subtype_path, control());
4457   }
4458 
4459   // If both operands are primitive (both klasses null), then
4460   // we must return true when they are identical primitives.
4461   // It is convenient to test this after the first null klass check.
4462   // This path is also used if superc is a value mirror.
4463   set_control(_gvn.transform(prim_region));
4464   if (!stopped()) {
4465     // Since superc is primitive, make a guard for the superc==subc case.
4466     Node* cmp_eq = _gvn.transform(new CmpPNode(args[0], args[1]));
4467     Node* bol_eq = _gvn.transform(new BoolNode(cmp_eq, BoolTest::eq));
4468     generate_fair_guard(bol_eq, region);
4469     if (region->req() == PATH_LIMIT+1) {
4470       // A guard was added.  If the added guard is taken, superc==subc.
4471       region->swap_edges(PATH_LIMIT, _prim_same_path);
4472       region->del_req(PATH_LIMIT);
4473     }
4474     region->set_req(_prim_0_path, control()); // Not equal after all.
4475   }
4476 
4477   // these are the only paths that produce 'true':
4478   phi->set_req(_prim_same_path,   intcon(1));
4479   phi->set_req(_ref_subtype_path, intcon(1));
4480 
4481   // pull together the cases:
4482   assert(region->req() == PATH_LIMIT, "sane region");
4483   for (uint i = 1; i < region->req(); i++) {
4484     Node* ctl = region->in(i);
4485     if (ctl == nullptr || ctl == top()) {
4486       region->set_req(i, top());
4487       phi   ->set_req(i, top());
4488     } else if (phi->in(i) == nullptr) {
4489       phi->set_req(i, intcon(0)); // all other paths produce 'false'
4490     }
4491   }
4492 
4493   set_control(_gvn.transform(region));
4494   set_result(_gvn.transform(phi));
4495   return true;
4496 }
4497 
4498 //---------------------generate_array_guard_common------------------------
4499 Node* LibraryCallKit::generate_array_guard_common(Node* kls, RegionNode* region, ArrayKind kind, Node** obj) {
4500 
4501   if (stopped()) {
4502     return nullptr;
4503   }
4504 
4505   // Like generate_guard, adds a new path onto the region.
4506   jint  layout_con = 0;
4507   Node* layout_val = get_layout_helper(kls, layout_con);
4508   if (layout_val == nullptr) {
4509     bool query = 0;
4510     switch(kind) {
4511       case ObjectArray:    query = Klass::layout_helper_is_objArray(layout_con); break;
4512       case NonObjectArray: query = !Klass::layout_helper_is_objArray(layout_con); break;
4513       case TypeArray:      query = Klass::layout_helper_is_typeArray(layout_con); break;
4514       case AnyArray:       query = Klass::layout_helper_is_array(layout_con); break;
4515       case NonArray:       query = !Klass::layout_helper_is_array(layout_con); break;
4516       default:
4517         ShouldNotReachHere();
4518     }
4519     if (!query) {
4520       return nullptr;                       // never a branch
4521     } else {                             // always a branch
4522       Node* always_branch = control();
4523       if (region != nullptr)
4524         region->add_req(always_branch);
4525       set_control(top());
4526       return always_branch;
4527     }
4528   }
4529   unsigned int value = 0;
4530   BoolTest::mask btest = BoolTest::illegal;
4531   switch(kind) {
4532     case ObjectArray:
4533     case NonObjectArray: {
4534       value = Klass::_lh_array_tag_obj_value;
4535       layout_val = _gvn.transform(new RShiftINode(layout_val, intcon(Klass::_lh_array_tag_shift)));
4536       btest = (kind == ObjectArray) ? BoolTest::eq : BoolTest::ne;
4537       break;
4538     }
4539     case TypeArray: {
4540       value = Klass::_lh_array_tag_type_value;
4541       layout_val = _gvn.transform(new RShiftINode(layout_val, intcon(Klass::_lh_array_tag_shift)));
4542       btest = BoolTest::eq;
4543       break;
4544     }
4545     case AnyArray:    value = Klass::_lh_neutral_value; btest = BoolTest::lt; break;
4546     case NonArray:    value = Klass::_lh_neutral_value; btest = BoolTest::gt; break;
4547     default:
4548       ShouldNotReachHere();
4549   }
4550   // Now test the correct condition.
4551   jint nval = (jint)value;
4552   Node* cmp = _gvn.transform(new CmpINode(layout_val, intcon(nval)));
4553   Node* bol = _gvn.transform(new BoolNode(cmp, btest));
4554   Node* ctrl = generate_fair_guard(bol, region);
4555   Node* is_array_ctrl = kind == NonArray ? control() : ctrl;
4556   if (obj != nullptr && is_array_ctrl != nullptr && is_array_ctrl != top()) {
4557     // Keep track of the fact that 'obj' is an array to prevent
4558     // array specific accesses from floating above the guard.
4559     *obj = _gvn.transform(new CastPPNode(is_array_ctrl, *obj, TypeAryPtr::BOTTOM));
4560   }
4561   return ctrl;
4562 }
4563 
4564 // public static native Object[] newNullRestrictedAtomicArray(Class<?> componentType, int length, Object initVal);
4565 // public static native Object[] newNullRestrictedNonAtomicArray(Class<?> componentType, int length, Object initVal);
4566 // public static native Object[] newNullableAtomicArray(Class<?> componentType, int length);
4567 bool LibraryCallKit::inline_newArray(bool null_free, bool atomic) {
4568   assert(null_free || atomic, "nullable implies atomic");
4569   Node* componentType = argument(0);
4570   Node* length = argument(1);
4571   Node* init_val = null_free ? argument(2) : nullptr;
4572 
4573   const TypeInstPtr* tp = _gvn.type(componentType)->isa_instptr();
4574   if (tp != nullptr) {
4575     ciInstanceKlass* ik = tp->instance_klass();
4576     if (ik == C->env()->Class_klass()) {
4577       ciType* t = tp->java_mirror_type();
4578       if (t != nullptr && t->is_inlinetype()) {
4579         ciInlineKlass* vk = t->as_inline_klass();
4580         bool flat = vk->maybe_flat_in_array();
4581         if (flat && atomic) {
4582           // Only flat if we have a corresponding atomic layout
4583           flat = null_free ? vk->has_atomic_layout() : vk->has_nullable_atomic_layout();
4584         }
4585         // TODO 8350865 refactor
4586         if (flat && !atomic) {
4587           flat = vk->has_non_atomic_layout();
4588         }
4589 
4590         // TOOD 8350865 ZGC needs card marks on initializing oop stores
4591         if (UseZGC && null_free && !flat) {
4592           return false;
4593         }
4594 
4595         ciArrayKlass* array_klass = ciArrayKlass::make(t, flat, null_free, atomic);
4596         if (array_klass->is_loaded() && array_klass->element_klass()->as_inline_klass()->is_initialized()) {
4597           const TypeAryKlassPtr* array_klass_type = TypeAryKlassPtr::make(array_klass, Type::trust_interfaces);
4598           if (null_free) {
4599             if (init_val->is_InlineType()) {
4600               if (array_klass_type->is_flat() && init_val->as_InlineType()->is_all_zero(&gvn(), /* flat */ true)) {
4601                 // Zeroing is enough because the init value is the all-zero value
4602                 init_val = nullptr;
4603               } else {
4604                 init_val = init_val->as_InlineType()->buffer(this);
4605               }
4606             }
4607             // TODO 8350865 Should we add a check of the init_val type (maybe in debug only + halt)?
4608           }
4609           Node* obj = new_array(makecon(array_klass_type), length, 0, nullptr, false, init_val);
4610           const TypeAryPtr* arytype = gvn().type(obj)->is_aryptr();
4611           assert(arytype->is_null_free() == null_free, "inconsistency");
4612           assert(arytype->is_not_null_free() == !null_free, "inconsistency");
4613           assert(arytype->is_flat() == flat, "inconsistency");
4614           assert(arytype->is_aryptr()->is_not_flat() == !flat, "inconsistency");
4615           set_result(obj);
4616           return true;
4617         }
4618       }
4619     }
4620   }
4621   return false;
4622 }
4623 
4624 //-----------------------inline_native_newArray--------------------------
4625 // private static native Object java.lang.reflect.Array.newArray(Class<?> componentType, int length);
4626 // private        native Object Unsafe.allocateUninitializedArray0(Class<?> cls, int size);
4627 bool LibraryCallKit::inline_unsafe_newArray(bool uninitialized) {
4628   Node* mirror;
4629   Node* count_val;
4630   if (uninitialized) {
4631     null_check_receiver();
4632     mirror    = argument(1);
4633     count_val = argument(2);
4634   } else {
4635     mirror    = argument(0);
4636     count_val = argument(1);
4637   }
4638 
4639   mirror = null_check(mirror);
4640   // If mirror or obj is dead, only null-path is taken.
4641   if (stopped())  return true;
4642 
4643   enum { _normal_path = 1, _slow_path = 2, PATH_LIMIT };
4644   RegionNode* result_reg = new RegionNode(PATH_LIMIT);
4645   PhiNode*    result_val = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
4646   PhiNode*    result_io  = new PhiNode(result_reg, Type::ABIO);
4647   PhiNode*    result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
4648 
4649   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
4650   Node* klass_node = load_array_klass_from_mirror(mirror, never_see_null,
4651                                                   result_reg, _slow_path);
4652   Node* normal_ctl   = control();
4653   Node* no_array_ctl = result_reg->in(_slow_path);
4654 
4655   // Generate code for the slow case.  We make a call to newArray().
4656   set_control(no_array_ctl);
4657   if (!stopped()) {
4658     // Either the input type is void.class, or else the
4659     // array klass has not yet been cached.  Either the
4660     // ensuing call will throw an exception, or else it
4661     // will cache the array klass for next time.
4662     PreserveJVMState pjvms(this);
4663     CallJavaNode* slow_call = nullptr;
4664     if (uninitialized) {
4665       // Generate optimized virtual call (holder class 'Unsafe' is final)
4666       slow_call = generate_method_call(vmIntrinsics::_allocateUninitializedArray, false, false, true);
4667     } else {
4668       slow_call = generate_method_call_static(vmIntrinsics::_newArray, true);
4669     }
4670     Node* slow_result = set_results_for_java_call(slow_call);
4671     // this->control() comes from set_results_for_java_call
4672     result_reg->set_req(_slow_path, control());
4673     result_val->set_req(_slow_path, slow_result);
4674     result_io ->set_req(_slow_path, i_o());
4675     result_mem->set_req(_slow_path, reset_memory());
4676   }
4677 
4678   set_control(normal_ctl);
4679   if (!stopped()) {
4680     // Normal case:  The array type has been cached in the java.lang.Class.
4681     // The following call works fine even if the array type is polymorphic.
4682     // It could be a dynamic mix of int[], boolean[], Object[], etc.
4683     Node* obj = new_array(klass_node, count_val, 0);  // no arguments to push
4684     result_reg->init_req(_normal_path, control());
4685     result_val->init_req(_normal_path, obj);
4686     result_io ->init_req(_normal_path, i_o());
4687     result_mem->init_req(_normal_path, reset_memory());
4688 
4689     if (uninitialized) {
4690       // Mark the allocation so that zeroing is skipped
4691       AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(obj);
4692       alloc->maybe_set_complete(&_gvn);
4693     }
4694   }
4695 
4696   // Return the combined state.
4697   set_i_o(        _gvn.transform(result_io)  );
4698   set_all_memory( _gvn.transform(result_mem));
4699 
4700   C->set_has_split_ifs(true); // Has chance for split-if optimization
4701   set_result(result_reg, result_val);
4702   return true;
4703 }
4704 
4705 //----------------------inline_native_getLength--------------------------
4706 // public static native int java.lang.reflect.Array.getLength(Object array);
4707 bool LibraryCallKit::inline_native_getLength() {
4708   if (too_many_traps(Deoptimization::Reason_intrinsic))  return false;
4709 
4710   Node* array = null_check(argument(0));
4711   // If array is dead, only null-path is taken.
4712   if (stopped())  return true;
4713 
4714   // Deoptimize if it is a non-array.
4715   Node* non_array = generate_non_array_guard(load_object_klass(array), nullptr, &array);
4716 
4717   if (non_array != nullptr) {
4718     PreserveJVMState pjvms(this);
4719     set_control(non_array);
4720     uncommon_trap(Deoptimization::Reason_intrinsic,
4721                   Deoptimization::Action_maybe_recompile);
4722   }
4723 
4724   // If control is dead, only non-array-path is taken.
4725   if (stopped())  return true;
4726 
4727   // The works fine even if the array type is polymorphic.
4728   // It could be a dynamic mix of int[], boolean[], Object[], etc.
4729   Node* result = load_array_length(array);
4730 
4731   C->set_has_split_ifs(true);  // Has chance for split-if optimization
4732   set_result(result);
4733   return true;
4734 }
4735 
4736 //------------------------inline_array_copyOf----------------------------
4737 // public static <T,U> T[] java.util.Arrays.copyOf(     U[] original, int newLength,         Class<? extends T[]> newType);
4738 // public static <T,U> T[] java.util.Arrays.copyOfRange(U[] original, int from,      int to, Class<? extends T[]> newType);
4739 bool LibraryCallKit::inline_array_copyOf(bool is_copyOfRange) {
4740   if (too_many_traps(Deoptimization::Reason_intrinsic))  return false;
4741 
4742   // Get the arguments.
4743   Node* original          = argument(0);
4744   Node* start             = is_copyOfRange? argument(1): intcon(0);
4745   Node* end               = is_copyOfRange? argument(2): argument(1);
4746   Node* array_type_mirror = is_copyOfRange? argument(3): argument(2);
4747 
4748   Node* newcopy = nullptr;
4749 
4750   // Set the original stack and the reexecute bit for the interpreter to reexecute
4751   // the bytecode that invokes Arrays.copyOf if deoptimization happens.
4752   { PreserveReexecuteState preexecs(this);
4753     jvms()->set_should_reexecute(true);
4754 
4755     array_type_mirror = null_check(array_type_mirror);
4756     original          = null_check(original);
4757 
4758     // Check if a null path was taken unconditionally.
4759     if (stopped())  return true;
4760 
4761     Node* orig_length = load_array_length(original);
4762 
4763     Node* klass_node = load_klass_from_mirror(array_type_mirror, false, nullptr, 0);
4764     klass_node = null_check(klass_node);
4765 
4766     RegionNode* bailout = new RegionNode(1);
4767     record_for_igvn(bailout);
4768 
4769     // Despite the generic type of Arrays.copyOf, the mirror might be int, int[], etc.
4770     // Bail out if that is so.
4771     // Inline type array may have object field that would require a
4772     // write barrier. Conservatively, go to slow path.
4773     // TODO 8251971: Optimize for the case when flat src/dst are later found
4774     // to not contain oops (i.e., move this check to the macro expansion phase).
4775     BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
4776     const TypeAryPtr* orig_t = _gvn.type(original)->isa_aryptr();
4777     const TypeKlassPtr* tklass = _gvn.type(klass_node)->is_klassptr();
4778     bool exclude_flat = UseArrayFlattening && bs->array_copy_requires_gc_barriers(true, T_OBJECT, false, false, BarrierSetC2::Parsing) &&
4779                         // Can src array be flat and contain oops?
4780                         (orig_t == nullptr || (!orig_t->is_not_flat() && (!orig_t->is_flat() || orig_t->elem()->inline_klass()->contains_oops()))) &&
4781                         // Can dest array be flat and contain oops?
4782                         tklass->can_be_inline_array() && (!tklass->is_flat() || tklass->is_aryklassptr()->elem()->is_instklassptr()->instance_klass()->as_inline_klass()->contains_oops());
4783     Node* not_objArray = exclude_flat ? generate_non_objArray_guard(klass_node, bailout) : generate_typeArray_guard(klass_node, bailout);
4784     if (not_objArray != nullptr) {
4785       // Improve the klass node's type from the new optimistic assumption:
4786       ciKlass* ak = ciArrayKlass::make(env()->Object_klass());
4787       const Type* akls = TypeKlassPtr::make(TypePtr::NotNull, ak, Type::Offset(0));
4788       Node* cast = new CastPPNode(control(), klass_node, akls);
4789       klass_node = _gvn.transform(cast);
4790     }
4791 
4792     // Bail out if either start or end is negative.
4793     generate_negative_guard(start, bailout, &start);
4794     generate_negative_guard(end,   bailout, &end);
4795 
4796     Node* length = end;
4797     if (_gvn.type(start) != TypeInt::ZERO) {
4798       length = _gvn.transform(new SubINode(end, start));
4799     }
4800 
4801     // Bail out if length is negative (i.e., if start > end).
4802     // Without this the new_array would throw
4803     // NegativeArraySizeException but IllegalArgumentException is what
4804     // should be thrown
4805     generate_negative_guard(length, bailout, &length);
4806 
4807     // Handle inline type arrays
4808     bool can_validate = !too_many_traps(Deoptimization::Reason_class_check);
4809     if (!stopped()) {
4810       // TODO JDK-8329224
4811       if (!orig_t->is_null_free()) {
4812         // Not statically known to be null free, add a check
4813         generate_fair_guard(null_free_array_test(original), bailout);
4814       }
4815       orig_t = _gvn.type(original)->isa_aryptr();
4816       if (orig_t != nullptr && orig_t->is_flat()) {
4817         // Src is flat, check that dest is flat as well
4818         if (exclude_flat) {
4819           // Dest can't be flat, bail out
4820           bailout->add_req(control());
4821           set_control(top());
4822         } else {
4823           generate_fair_guard(flat_array_test(klass_node, /* flat = */ false), bailout);
4824         }
4825         // TODO 8350865 This is not correct anymore. Write tests and fix logic similar to arraycopy.
4826       } else if (UseArrayFlattening && (orig_t == nullptr || !orig_t->is_not_flat()) &&
4827                  // If dest is flat, src must be flat as well (guaranteed by src <: dest check if validated).
4828                  ((!tklass->is_flat() && tklass->can_be_inline_array()) || !can_validate)) {
4829         // Src might be flat and dest might not be flat. Go to the slow path if src is flat.
4830         // TODO 8251971: Optimize for the case when src/dest are later found to be both flat.
4831         generate_fair_guard(flat_array_test(load_object_klass(original)), bailout);
4832         if (orig_t != nullptr) {
4833           orig_t = orig_t->cast_to_not_flat();
4834           original = _gvn.transform(new CheckCastPPNode(control(), original, orig_t));
4835         }
4836       }
4837       if (!can_validate) {
4838         // No validation. The subtype check emitted at macro expansion time will not go to the slow
4839         // path but call checkcast_arraycopy which can not handle flat/null-free inline type arrays.
4840         // TODO 8251971: Optimize for the case when src/dest are later found to be both flat/null-free.
4841         generate_fair_guard(flat_array_test(klass_node), bailout);
4842         generate_fair_guard(null_free_array_test(original), bailout);
4843       }
4844     }
4845 
4846     // Bail out if start is larger than the original length
4847     Node* orig_tail = _gvn.transform(new SubINode(orig_length, start));
4848     generate_negative_guard(orig_tail, bailout, &orig_tail);
4849 
4850     if (bailout->req() > 1) {
4851       PreserveJVMState pjvms(this);
4852       set_control(_gvn.transform(bailout));
4853       uncommon_trap(Deoptimization::Reason_intrinsic,
4854                     Deoptimization::Action_maybe_recompile);
4855     }
4856 
4857     if (!stopped()) {
4858       // How many elements will we copy from the original?
4859       // The answer is MinI(orig_tail, length).
4860       Node* moved = _gvn.transform(new MinINode(orig_tail, length));
4861 
4862       // Generate a direct call to the right arraycopy function(s).
4863       // We know the copy is disjoint but we might not know if the
4864       // oop stores need checking.
4865       // Extreme case:  Arrays.copyOf((Integer[])x, 10, String[].class).
4866       // This will fail a store-check if x contains any non-nulls.
4867 
4868       // ArrayCopyNode:Ideal may transform the ArrayCopyNode to
4869       // loads/stores but it is legal only if we're sure the
4870       // Arrays.copyOf would succeed. So we need all input arguments
4871       // to the copyOf to be validated, including that the copy to the
4872       // new array won't trigger an ArrayStoreException. That subtype
4873       // check can be optimized if we know something on the type of
4874       // the input array from type speculation.
4875       if (_gvn.type(klass_node)->singleton()) {
4876         const TypeKlassPtr* subk = _gvn.type(load_object_klass(original))->is_klassptr();
4877         const TypeKlassPtr* superk = _gvn.type(klass_node)->is_klassptr();
4878 
4879         int test = C->static_subtype_check(superk, subk);
4880         if (test != Compile::SSC_always_true && test != Compile::SSC_always_false) {
4881           const TypeOopPtr* t_original = _gvn.type(original)->is_oopptr();
4882           if (t_original->speculative_type() != nullptr) {
4883             original = maybe_cast_profiled_obj(original, t_original->speculative_type(), true);
4884           }
4885         }
4886       }
4887 
4888       bool validated = false;
4889       // Reason_class_check rather than Reason_intrinsic because we
4890       // want to intrinsify even if this traps.
4891       if (can_validate) {
4892         Node* not_subtype_ctrl = gen_subtype_check(original, klass_node);
4893 
4894         if (not_subtype_ctrl != top()) {
4895           PreserveJVMState pjvms(this);
4896           set_control(not_subtype_ctrl);
4897           uncommon_trap(Deoptimization::Reason_class_check,
4898                         Deoptimization::Action_make_not_entrant);
4899           assert(stopped(), "Should be stopped");
4900         }
4901         validated = true;
4902       }
4903 
4904       if (!stopped()) {
4905         newcopy = new_array(klass_node, length, 0);  // no arguments to push
4906 
4907         ArrayCopyNode* ac = ArrayCopyNode::make(this, true, original, start, newcopy, intcon(0), moved, true, true,
4908                                                 load_object_klass(original), klass_node);
4909         if (!is_copyOfRange) {
4910           ac->set_copyof(validated);
4911         } else {
4912           ac->set_copyofrange(validated);
4913         }
4914         Node* n = _gvn.transform(ac);
4915         if (n == ac) {
4916           ac->connect_outputs(this);
4917         } else {
4918           assert(validated, "shouldn't transform if all arguments not validated");
4919           set_all_memory(n);
4920         }
4921       }
4922     }
4923   } // original reexecute is set back here
4924 
4925   C->set_has_split_ifs(true); // Has chance for split-if optimization
4926   if (!stopped()) {
4927     set_result(newcopy);
4928   }
4929   return true;
4930 }
4931 
4932 
4933 //----------------------generate_virtual_guard---------------------------
4934 // Helper for hashCode and clone.  Peeks inside the vtable to avoid a call.
4935 Node* LibraryCallKit::generate_virtual_guard(Node* obj_klass,
4936                                              RegionNode* slow_region) {
4937   ciMethod* method = callee();
4938   int vtable_index = method->vtable_index();
4939   assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index,
4940          "bad index %d", vtable_index);
4941   // Get the Method* out of the appropriate vtable entry.
4942   int entry_offset  = in_bytes(Klass::vtable_start_offset()) +
4943                      vtable_index*vtableEntry::size_in_bytes() +
4944                      in_bytes(vtableEntry::method_offset());
4945   Node* entry_addr  = basic_plus_adr(obj_klass, entry_offset);
4946   Node* target_call = make_load(nullptr, entry_addr, TypePtr::NOTNULL, T_ADDRESS, MemNode::unordered);
4947 
4948   // Compare the target method with the expected method (e.g., Object.hashCode).
4949   const TypePtr* native_call_addr = TypeMetadataPtr::make(method);
4950 
4951   Node* native_call = makecon(native_call_addr);
4952   Node* chk_native  = _gvn.transform(new CmpPNode(target_call, native_call));
4953   Node* test_native = _gvn.transform(new BoolNode(chk_native, BoolTest::ne));
4954 
4955   return generate_slow_guard(test_native, slow_region);
4956 }
4957 
4958 //-----------------------generate_method_call----------------------------
4959 // Use generate_method_call to make a slow-call to the real
4960 // method if the fast path fails.  An alternative would be to
4961 // use a stub like OptoRuntime::slow_arraycopy_Java.
4962 // This only works for expanding the current library call,
4963 // not another intrinsic.  (E.g., don't use this for making an
4964 // arraycopy call inside of the copyOf intrinsic.)
4965 CallJavaNode*
4966 LibraryCallKit::generate_method_call(vmIntrinsicID method_id, bool is_virtual, bool is_static, bool res_not_null) {
4967   // When compiling the intrinsic method itself, do not use this technique.
4968   guarantee(callee() != C->method(), "cannot make slow-call to self");
4969 
4970   ciMethod* method = callee();
4971   // ensure the JVMS we have will be correct for this call
4972   guarantee(method_id == method->intrinsic_id(), "must match");
4973 
4974   const TypeFunc* tf = TypeFunc::make(method);
4975   if (res_not_null) {
4976     assert(tf->return_type() == T_OBJECT, "");
4977     const TypeTuple* range = tf->range_cc();
4978     const Type** fields = TypeTuple::fields(range->cnt());
4979     fields[TypeFunc::Parms] = range->field_at(TypeFunc::Parms)->filter_speculative(TypePtr::NOTNULL);
4980     const TypeTuple* new_range = TypeTuple::make(range->cnt(), fields);
4981     tf = TypeFunc::make(tf->domain_cc(), new_range);
4982   }
4983   CallJavaNode* slow_call;
4984   if (is_static) {
4985     assert(!is_virtual, "");
4986     slow_call = new CallStaticJavaNode(C, tf,
4987                            SharedRuntime::get_resolve_static_call_stub(), method);
4988   } else if (is_virtual) {
4989     assert(!gvn().type(argument(0))->maybe_null(), "should not be null");
4990     int vtable_index = Method::invalid_vtable_index;
4991     if (UseInlineCaches) {
4992       // Suppress the vtable call
4993     } else {
4994       // hashCode and clone are not a miranda methods,
4995       // so the vtable index is fixed.
4996       // No need to use the linkResolver to get it.
4997        vtable_index = method->vtable_index();
4998        assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index,
4999               "bad index %d", vtable_index);
5000     }
5001     slow_call = new CallDynamicJavaNode(tf,
5002                           SharedRuntime::get_resolve_virtual_call_stub(),
5003                           method, vtable_index);
5004   } else {  // neither virtual nor static:  opt_virtual
5005     assert(!gvn().type(argument(0))->maybe_null(), "should not be null");
5006     slow_call = new CallStaticJavaNode(C, tf,
5007                                 SharedRuntime::get_resolve_opt_virtual_call_stub(), method);
5008     slow_call->set_optimized_virtual(true);
5009   }
5010   if (CallGenerator::is_inlined_method_handle_intrinsic(this->method(), bci(), callee())) {
5011     // To be able to issue a direct call (optimized virtual or virtual)
5012     // and skip a call to MH.linkTo*/invokeBasic adapter, additional information
5013     // about the method being invoked should be attached to the call site to
5014     // make resolution logic work (see SharedRuntime::resolve_{virtual,opt_virtual}_call_C).
5015     slow_call->set_override_symbolic_info(true);
5016   }
5017   set_arguments_for_java_call(slow_call);
5018   set_edges_for_java_call(slow_call);
5019   return slow_call;
5020 }
5021 
5022 
5023 /**
5024  * Build special case code for calls to hashCode on an object. This call may
5025  * be virtual (invokevirtual) or bound (invokespecial). For each case we generate
5026  * slightly different code.
5027  */
5028 bool LibraryCallKit::inline_native_hashcode(bool is_virtual, bool is_static) {
5029   assert(is_static == callee()->is_static(), "correct intrinsic selection");
5030   assert(!(is_virtual && is_static), "either virtual, special, or static");
5031 
5032   enum { _slow_path = 1, _fast_path, _null_path, PATH_LIMIT };
5033 
5034   RegionNode* result_reg = new RegionNode(PATH_LIMIT);
5035   PhiNode*    result_val = new PhiNode(result_reg, TypeInt::INT);
5036   PhiNode*    result_io  = new PhiNode(result_reg, Type::ABIO);
5037   PhiNode*    result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
5038   Node* obj = argument(0);
5039 
5040   // Don't intrinsify hashcode on inline types for now.
5041   // The "is locked" runtime check below also serves as inline type check and goes to the slow path.
5042   if (gvn().type(obj)->is_inlinetypeptr()) {
5043     return false;
5044   }
5045 
5046   if (!is_static) {
5047     // Check for hashing null object
5048     obj = null_check_receiver();
5049     if (stopped())  return true;        // unconditionally null
5050     result_reg->init_req(_null_path, top());
5051     result_val->init_req(_null_path, top());
5052   } else {
5053     // Do a null check, and return zero if null.
5054     // System.identityHashCode(null) == 0
5055     Node* null_ctl = top();
5056     obj = null_check_oop(obj, &null_ctl);
5057     result_reg->init_req(_null_path, null_ctl);
5058     result_val->init_req(_null_path, _gvn.intcon(0));
5059   }
5060 
5061   // Unconditionally null?  Then return right away.
5062   if (stopped()) {
5063     set_control( result_reg->in(_null_path));
5064     if (!stopped())
5065       set_result(result_val->in(_null_path));
5066     return true;
5067   }
5068 
5069   // We only go to the fast case code if we pass a number of guards.  The
5070   // paths which do not pass are accumulated in the slow_region.
5071   RegionNode* slow_region = new RegionNode(1);
5072   record_for_igvn(slow_region);
5073 
5074   // If this is a virtual call, we generate a funny guard.  We pull out
5075   // the vtable entry corresponding to hashCode() from the target object.
5076   // If the target method which we are calling happens to be the native
5077   // Object hashCode() method, we pass the guard.  We do not need this
5078   // guard for non-virtual calls -- the caller is known to be the native
5079   // Object hashCode().
5080   if (is_virtual) {
5081     // After null check, get the object's klass.
5082     Node* obj_klass = load_object_klass(obj);
5083     generate_virtual_guard(obj_klass, slow_region);
5084   }
5085 
5086   // Get the header out of the object, use LoadMarkNode when available
5087   Node* header_addr = basic_plus_adr(obj, oopDesc::mark_offset_in_bytes());
5088   // The control of the load must be null. Otherwise, the load can move before
5089   // the null check after castPP removal.
5090   Node* no_ctrl = nullptr;
5091   Node* header = make_load(no_ctrl, header_addr, TypeX_X, TypeX_X->basic_type(), MemNode::unordered);
5092 
5093   if (!UseObjectMonitorTable) {
5094     // Test the header to see if it is safe to read w.r.t. locking.
5095   // This also serves as guard against inline types
5096     Node *lock_mask      = _gvn.MakeConX(markWord::inline_type_mask_in_place);
5097     Node *lmasked_header = _gvn.transform(new AndXNode(header, lock_mask));
5098     if (LockingMode == LM_LIGHTWEIGHT) {
5099       Node *monitor_val   = _gvn.MakeConX(markWord::monitor_value);
5100       Node *chk_monitor   = _gvn.transform(new CmpXNode(lmasked_header, monitor_val));
5101       Node *test_monitor  = _gvn.transform(new BoolNode(chk_monitor, BoolTest::eq));
5102 
5103       generate_slow_guard(test_monitor, slow_region);
5104     } else {
5105       Node *unlocked_val      = _gvn.MakeConX(markWord::unlocked_value);
5106       Node *chk_unlocked      = _gvn.transform(new CmpXNode(lmasked_header, unlocked_val));
5107       Node *test_not_unlocked = _gvn.transform(new BoolNode(chk_unlocked, BoolTest::ne));
5108 
5109       generate_slow_guard(test_not_unlocked, slow_region);
5110     }
5111   }
5112 
5113   // Get the hash value and check to see that it has been properly assigned.
5114   // We depend on hash_mask being at most 32 bits and avoid the use of
5115   // hash_mask_in_place because it could be larger than 32 bits in a 64-bit
5116   // vm: see markWord.hpp.
5117   Node *hash_mask      = _gvn.intcon(markWord::hash_mask);
5118   Node *hash_shift     = _gvn.intcon(markWord::hash_shift);
5119   Node *hshifted_header= _gvn.transform(new URShiftXNode(header, hash_shift));
5120   // This hack lets the hash bits live anywhere in the mark object now, as long
5121   // as the shift drops the relevant bits into the low 32 bits.  Note that
5122   // Java spec says that HashCode is an int so there's no point in capturing
5123   // an 'X'-sized hashcode (32 in 32-bit build or 64 in 64-bit build).
5124   hshifted_header      = ConvX2I(hshifted_header);
5125   Node *hash_val       = _gvn.transform(new AndINode(hshifted_header, hash_mask));
5126 
5127   Node *no_hash_val    = _gvn.intcon(markWord::no_hash);
5128   Node *chk_assigned   = _gvn.transform(new CmpINode( hash_val, no_hash_val));
5129   Node *test_assigned  = _gvn.transform(new BoolNode( chk_assigned, BoolTest::eq));
5130 
5131   generate_slow_guard(test_assigned, slow_region);
5132 
5133   Node* init_mem = reset_memory();
5134   // fill in the rest of the null path:
5135   result_io ->init_req(_null_path, i_o());
5136   result_mem->init_req(_null_path, init_mem);
5137 
5138   result_val->init_req(_fast_path, hash_val);
5139   result_reg->init_req(_fast_path, control());
5140   result_io ->init_req(_fast_path, i_o());
5141   result_mem->init_req(_fast_path, init_mem);
5142 
5143   // Generate code for the slow case.  We make a call to hashCode().
5144   set_control(_gvn.transform(slow_region));
5145   if (!stopped()) {
5146     // No need for PreserveJVMState, because we're using up the present state.
5147     set_all_memory(init_mem);
5148     vmIntrinsics::ID hashCode_id = is_static ? vmIntrinsics::_identityHashCode : vmIntrinsics::_hashCode;
5149     CallJavaNode* slow_call = generate_method_call(hashCode_id, is_virtual, is_static, false);
5150     Node* slow_result = set_results_for_java_call(slow_call);
5151     // this->control() comes from set_results_for_java_call
5152     result_reg->init_req(_slow_path, control());
5153     result_val->init_req(_slow_path, slow_result);
5154     result_io  ->set_req(_slow_path, i_o());
5155     result_mem ->set_req(_slow_path, reset_memory());
5156   }
5157 
5158   // Return the combined state.
5159   set_i_o(        _gvn.transform(result_io)  );
5160   set_all_memory( _gvn.transform(result_mem));
5161 
5162   set_result(result_reg, result_val);
5163   return true;
5164 }
5165 
5166 //---------------------------inline_native_getClass----------------------------
5167 // public final native Class<?> java.lang.Object.getClass();
5168 //
5169 // Build special case code for calls to getClass on an object.
5170 bool LibraryCallKit::inline_native_getClass() {
5171   Node* obj = argument(0);
5172   if (obj->is_InlineType()) {
5173     const Type* t = _gvn.type(obj);
5174     if (t->maybe_null()) {
5175       null_check(obj);
5176     }
5177     set_result(makecon(TypeInstPtr::make(t->inline_klass()->java_mirror())));
5178     return true;
5179   }
5180   obj = null_check_receiver();
5181   if (stopped())  return true;
5182   set_result(load_mirror_from_klass(load_object_klass(obj)));
5183   return true;
5184 }
5185 
5186 //-----------------inline_native_Reflection_getCallerClass---------------------
5187 // public static native Class<?> sun.reflect.Reflection.getCallerClass();
5188 //
5189 // In the presence of deep enough inlining, getCallerClass() becomes a no-op.
5190 //
5191 // NOTE: This code must perform the same logic as JVM_GetCallerClass
5192 // in that it must skip particular security frames and checks for
5193 // caller sensitive methods.
5194 bool LibraryCallKit::inline_native_Reflection_getCallerClass() {
5195 #ifndef PRODUCT
5196   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5197     tty->print_cr("Attempting to inline sun.reflect.Reflection.getCallerClass");
5198   }
5199 #endif
5200 
5201   if (!jvms()->has_method()) {
5202 #ifndef PRODUCT
5203     if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5204       tty->print_cr("  Bailing out because intrinsic was inlined at top level");
5205     }
5206 #endif
5207     return false;
5208   }
5209 
5210   // Walk back up the JVM state to find the caller at the required
5211   // depth.
5212   JVMState* caller_jvms = jvms();
5213 
5214   // Cf. JVM_GetCallerClass
5215   // NOTE: Start the loop at depth 1 because the current JVM state does
5216   // not include the Reflection.getCallerClass() frame.
5217   for (int n = 1; caller_jvms != nullptr; caller_jvms = caller_jvms->caller(), n++) {
5218     ciMethod* m = caller_jvms->method();
5219     switch (n) {
5220     case 0:
5221       fatal("current JVM state does not include the Reflection.getCallerClass frame");
5222       break;
5223     case 1:
5224       // Frame 0 and 1 must be caller sensitive (see JVM_GetCallerClass).
5225       if (!m->caller_sensitive()) {
5226 #ifndef PRODUCT
5227         if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5228           tty->print_cr("  Bailing out: CallerSensitive annotation expected at frame %d", n);
5229         }
5230 #endif
5231         return false;  // bail-out; let JVM_GetCallerClass do the work
5232       }
5233       break;
5234     default:
5235       if (!m->is_ignored_by_security_stack_walk()) {
5236         // We have reached the desired frame; return the holder class.
5237         // Acquire method holder as java.lang.Class and push as constant.
5238         ciInstanceKlass* caller_klass = caller_jvms->method()->holder();
5239         ciInstance* caller_mirror = caller_klass->java_mirror();
5240         set_result(makecon(TypeInstPtr::make(caller_mirror)));
5241 
5242 #ifndef PRODUCT
5243         if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5244           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());
5245           tty->print_cr("  JVM state at this point:");
5246           for (int i = jvms()->depth(), n = 1; i >= 1; i--, n++) {
5247             ciMethod* m = jvms()->of_depth(i)->method();
5248             tty->print_cr("   %d) %s.%s", n, m->holder()->name()->as_utf8(), m->name()->as_utf8());
5249           }
5250         }
5251 #endif
5252         return true;
5253       }
5254       break;
5255     }
5256   }
5257 
5258 #ifndef PRODUCT
5259   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5260     tty->print_cr("  Bailing out because caller depth exceeded inlining depth = %d", jvms()->depth());
5261     tty->print_cr("  JVM state at this point:");
5262     for (int i = jvms()->depth(), n = 1; i >= 1; i--, n++) {
5263       ciMethod* m = jvms()->of_depth(i)->method();
5264       tty->print_cr("   %d) %s.%s", n, m->holder()->name()->as_utf8(), m->name()->as_utf8());
5265     }
5266   }
5267 #endif
5268 
5269   return false;  // bail-out; let JVM_GetCallerClass do the work
5270 }
5271 
5272 bool LibraryCallKit::inline_fp_conversions(vmIntrinsics::ID id) {
5273   Node* arg = argument(0);
5274   Node* result = nullptr;
5275 
5276   switch (id) {
5277   case vmIntrinsics::_floatToRawIntBits:    result = new MoveF2INode(arg);  break;
5278   case vmIntrinsics::_intBitsToFloat:       result = new MoveI2FNode(arg);  break;
5279   case vmIntrinsics::_doubleToRawLongBits:  result = new MoveD2LNode(arg);  break;
5280   case vmIntrinsics::_longBitsToDouble:     result = new MoveL2DNode(arg);  break;
5281   case vmIntrinsics::_floatToFloat16:       result = new ConvF2HFNode(arg); break;
5282   case vmIntrinsics::_float16ToFloat:       result = new ConvHF2FNode(arg); break;
5283 
5284   case vmIntrinsics::_doubleToLongBits: {
5285     // two paths (plus control) merge in a wood
5286     RegionNode *r = new RegionNode(3);
5287     Node *phi = new PhiNode(r, TypeLong::LONG);
5288 
5289     Node *cmpisnan = _gvn.transform(new CmpDNode(arg, arg));
5290     // Build the boolean node
5291     Node *bolisnan = _gvn.transform(new BoolNode(cmpisnan, BoolTest::ne));
5292 
5293     // Branch either way.
5294     // NaN case is less traveled, which makes all the difference.
5295     IfNode *ifisnan = create_and_xform_if(control(), bolisnan, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
5296     Node *opt_isnan = _gvn.transform(ifisnan);
5297     assert( opt_isnan->is_If(), "Expect an IfNode");
5298     IfNode *opt_ifisnan = (IfNode*)opt_isnan;
5299     Node *iftrue = _gvn.transform(new IfTrueNode(opt_ifisnan));
5300 
5301     set_control(iftrue);
5302 
5303     static const jlong nan_bits = CONST64(0x7ff8000000000000);
5304     Node *slow_result = longcon(nan_bits); // return NaN
5305     phi->init_req(1, _gvn.transform( slow_result ));
5306     r->init_req(1, iftrue);
5307 
5308     // Else fall through
5309     Node *iffalse = _gvn.transform(new IfFalseNode(opt_ifisnan));
5310     set_control(iffalse);
5311 
5312     phi->init_req(2, _gvn.transform(new MoveD2LNode(arg)));
5313     r->init_req(2, iffalse);
5314 
5315     // Post merge
5316     set_control(_gvn.transform(r));
5317     record_for_igvn(r);
5318 
5319     C->set_has_split_ifs(true); // Has chance for split-if optimization
5320     result = phi;
5321     assert(result->bottom_type()->isa_long(), "must be");
5322     break;
5323   }
5324 
5325   case vmIntrinsics::_floatToIntBits: {
5326     // two paths (plus control) merge in a wood
5327     RegionNode *r = new RegionNode(3);
5328     Node *phi = new PhiNode(r, TypeInt::INT);
5329 
5330     Node *cmpisnan = _gvn.transform(new CmpFNode(arg, arg));
5331     // Build the boolean node
5332     Node *bolisnan = _gvn.transform(new BoolNode(cmpisnan, BoolTest::ne));
5333 
5334     // Branch either way.
5335     // NaN case is less traveled, which makes all the difference.
5336     IfNode *ifisnan = create_and_xform_if(control(), bolisnan, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
5337     Node *opt_isnan = _gvn.transform(ifisnan);
5338     assert( opt_isnan->is_If(), "Expect an IfNode");
5339     IfNode *opt_ifisnan = (IfNode*)opt_isnan;
5340     Node *iftrue = _gvn.transform(new IfTrueNode(opt_ifisnan));
5341 
5342     set_control(iftrue);
5343 
5344     static const jint nan_bits = 0x7fc00000;
5345     Node *slow_result = makecon(TypeInt::make(nan_bits)); // return NaN
5346     phi->init_req(1, _gvn.transform( slow_result ));
5347     r->init_req(1, iftrue);
5348 
5349     // Else fall through
5350     Node *iffalse = _gvn.transform(new IfFalseNode(opt_ifisnan));
5351     set_control(iffalse);
5352 
5353     phi->init_req(2, _gvn.transform(new MoveF2INode(arg)));
5354     r->init_req(2, iffalse);
5355 
5356     // Post merge
5357     set_control(_gvn.transform(r));
5358     record_for_igvn(r);
5359 
5360     C->set_has_split_ifs(true); // Has chance for split-if optimization
5361     result = phi;
5362     assert(result->bottom_type()->isa_int(), "must be");
5363     break;
5364   }
5365 
5366   default:
5367     fatal_unexpected_iid(id);
5368     break;
5369   }
5370   set_result(_gvn.transform(result));
5371   return true;
5372 }
5373 
5374 bool LibraryCallKit::inline_fp_range_check(vmIntrinsics::ID id) {
5375   Node* arg = argument(0);
5376   Node* result = nullptr;
5377 
5378   switch (id) {
5379   case vmIntrinsics::_floatIsInfinite:
5380     result = new IsInfiniteFNode(arg);
5381     break;
5382   case vmIntrinsics::_floatIsFinite:
5383     result = new IsFiniteFNode(arg);
5384     break;
5385   case vmIntrinsics::_doubleIsInfinite:
5386     result = new IsInfiniteDNode(arg);
5387     break;
5388   case vmIntrinsics::_doubleIsFinite:
5389     result = new IsFiniteDNode(arg);
5390     break;
5391   default:
5392     fatal_unexpected_iid(id);
5393     break;
5394   }
5395   set_result(_gvn.transform(result));
5396   return true;
5397 }
5398 
5399 //----------------------inline_unsafe_copyMemory-------------------------
5400 // public native void Unsafe.copyMemory0(Object srcBase, long srcOffset, Object destBase, long destOffset, long bytes);
5401 
5402 static bool has_wide_mem(PhaseGVN& gvn, Node* addr, Node* base) {
5403   const TypeAryPtr* addr_t = gvn.type(addr)->isa_aryptr();
5404   const Type*       base_t = gvn.type(base);
5405 
5406   bool in_native = (base_t == TypePtr::NULL_PTR);
5407   bool in_heap   = !TypePtr::NULL_PTR->higher_equal(base_t);
5408   bool is_mixed  = !in_heap && !in_native;
5409 
5410   if (is_mixed) {
5411     return true; // mixed accesses can touch both on-heap and off-heap memory
5412   }
5413   if (in_heap) {
5414     bool is_prim_array = (addr_t != nullptr) && (addr_t->elem() != Type::BOTTOM);
5415     if (!is_prim_array) {
5416       // Though Unsafe.copyMemory() ensures at runtime for on-heap accesses that base is a primitive array,
5417       // there's not enough type information available to determine proper memory slice for it.
5418       return true;
5419     }
5420   }
5421   return false;
5422 }
5423 
5424 bool LibraryCallKit::inline_unsafe_copyMemory() {
5425   if (callee()->is_static())  return false;  // caller must have the capability!
5426   null_check_receiver();  // null-check receiver
5427   if (stopped())  return true;
5428 
5429   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
5430 
5431   Node* src_base =         argument(1);  // type: oop
5432   Node* src_off  = ConvL2X(argument(2)); // type: long
5433   Node* dst_base =         argument(4);  // type: oop
5434   Node* dst_off  = ConvL2X(argument(5)); // type: long
5435   Node* size     = ConvL2X(argument(7)); // type: long
5436 
5437   assert(Unsafe_field_offset_to_byte_offset(11) == 11,
5438          "fieldOffset must be byte-scaled");
5439 
5440   Node* src_addr = make_unsafe_address(src_base, src_off);
5441   Node* dst_addr = make_unsafe_address(dst_base, dst_off);
5442 
5443   Node* thread = _gvn.transform(new ThreadLocalNode());
5444   Node* doing_unsafe_access_addr = basic_plus_adr(top(), thread, in_bytes(JavaThread::doing_unsafe_access_offset()));
5445   BasicType doing_unsafe_access_bt = T_BYTE;
5446   assert((sizeof(bool) * CHAR_BIT) == 8, "not implemented");
5447 
5448   // update volatile field
5449   store_to_memory(control(), doing_unsafe_access_addr, intcon(1), doing_unsafe_access_bt, MemNode::unordered);
5450 
5451   int flags = RC_LEAF | RC_NO_FP;
5452 
5453   const TypePtr* dst_type = TypePtr::BOTTOM;
5454 
5455   // Adjust memory effects of the runtime call based on input values.
5456   if (!has_wide_mem(_gvn, src_addr, src_base) &&
5457       !has_wide_mem(_gvn, dst_addr, dst_base)) {
5458     dst_type = _gvn.type(dst_addr)->is_ptr(); // narrow out memory
5459 
5460     const TypePtr* src_type = _gvn.type(src_addr)->is_ptr();
5461     if (C->get_alias_index(src_type) == C->get_alias_index(dst_type)) {
5462       flags |= RC_NARROW_MEM; // narrow in memory
5463     }
5464   }
5465 
5466   // Call it.  Note that the length argument is not scaled.
5467   make_runtime_call(flags,
5468                     OptoRuntime::fast_arraycopy_Type(),
5469                     StubRoutines::unsafe_arraycopy(),
5470                     "unsafe_arraycopy",
5471                     dst_type,
5472                     src_addr, dst_addr, size XTOP);
5473 
5474   store_to_memory(control(), doing_unsafe_access_addr, intcon(0), doing_unsafe_access_bt, MemNode::unordered);
5475 
5476   return true;
5477 }
5478 
5479 // unsafe_setmemory(void *base, ulong offset, size_t length, char fill_value);
5480 // Fill 'length' bytes starting from 'base[offset]' with 'fill_value'
5481 bool LibraryCallKit::inline_unsafe_setMemory() {
5482   if (callee()->is_static())  return false;  // caller must have the capability!
5483   null_check_receiver();  // null-check receiver
5484   if (stopped())  return true;
5485 
5486   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
5487 
5488   Node* dst_base =         argument(1);  // type: oop
5489   Node* dst_off  = ConvL2X(argument(2)); // type: long
5490   Node* size     = ConvL2X(argument(4)); // type: long
5491   Node* byte     =         argument(6);  // type: byte
5492 
5493   assert(Unsafe_field_offset_to_byte_offset(11) == 11,
5494          "fieldOffset must be byte-scaled");
5495 
5496   Node* dst_addr = make_unsafe_address(dst_base, dst_off);
5497 
5498   Node* thread = _gvn.transform(new ThreadLocalNode());
5499   Node* doing_unsafe_access_addr = basic_plus_adr(top(), thread, in_bytes(JavaThread::doing_unsafe_access_offset()));
5500   BasicType doing_unsafe_access_bt = T_BYTE;
5501   assert((sizeof(bool) * CHAR_BIT) == 8, "not implemented");
5502 
5503   // update volatile field
5504   store_to_memory(control(), doing_unsafe_access_addr, intcon(1), doing_unsafe_access_bt, MemNode::unordered);
5505 
5506   int flags = RC_LEAF | RC_NO_FP;
5507 
5508   const TypePtr* dst_type = TypePtr::BOTTOM;
5509 
5510   // Adjust memory effects of the runtime call based on input values.
5511   if (!has_wide_mem(_gvn, dst_addr, dst_base)) {
5512     dst_type = _gvn.type(dst_addr)->is_ptr(); // narrow out memory
5513 
5514     flags |= RC_NARROW_MEM; // narrow in memory
5515   }
5516 
5517   // Call it.  Note that the length argument is not scaled.
5518   make_runtime_call(flags,
5519                     OptoRuntime::unsafe_setmemory_Type(),
5520                     StubRoutines::unsafe_setmemory(),
5521                     "unsafe_setmemory",
5522                     dst_type,
5523                     dst_addr, size XTOP, byte);
5524 
5525   store_to_memory(control(), doing_unsafe_access_addr, intcon(0), doing_unsafe_access_bt, MemNode::unordered);
5526 
5527   return true;
5528 }
5529 
5530 #undef XTOP
5531 
5532 //----------------------inline_unsafe_isFlatArray------------------------
5533 // public native boolean Unsafe.isFlatArray(Class<?> arrayClass);
5534 // This intrinsic exploits assumptions made by the native implementation
5535 // (arrayClass is neither null nor primitive) to avoid unnecessary null checks.
5536 bool LibraryCallKit::inline_unsafe_isFlatArray() {
5537   Node* cls = argument(1);
5538   Node* p = basic_plus_adr(cls, java_lang_Class::klass_offset());
5539   Node* kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), p,
5540                                                  TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT));
5541   Node* result = flat_array_test(kls);
5542   set_result(result);
5543   return true;
5544 }
5545 
5546 //------------------------clone_coping-----------------------------------
5547 // Helper function for inline_native_clone.
5548 void LibraryCallKit::copy_to_clone(Node* obj, Node* alloc_obj, Node* obj_size, bool is_array) {
5549   assert(obj_size != nullptr, "");
5550   Node* raw_obj = alloc_obj->in(1);
5551   assert(alloc_obj->is_CheckCastPP() && raw_obj->is_Proj() && raw_obj->in(0)->is_Allocate(), "");
5552 
5553   AllocateNode* alloc = nullptr;
5554   if (ReduceBulkZeroing &&
5555       // If we are implementing an array clone without knowing its source type
5556       // (can happen when compiling the array-guarded branch of a reflective
5557       // Object.clone() invocation), initialize the array within the allocation.
5558       // This is needed because some GCs (e.g. ZGC) might fall back in this case
5559       // to a runtime clone call that assumes fully initialized source arrays.
5560       (!is_array || obj->get_ptr_type()->isa_aryptr() != nullptr)) {
5561     // We will be completely responsible for initializing this object -
5562     // mark Initialize node as complete.
5563     alloc = AllocateNode::Ideal_allocation(alloc_obj);
5564     // The object was just allocated - there should be no any stores!
5565     guarantee(alloc != nullptr && alloc->maybe_set_complete(&_gvn), "");
5566     // Mark as complete_with_arraycopy so that on AllocateNode
5567     // expansion, we know this AllocateNode is initialized by an array
5568     // copy and a StoreStore barrier exists after the array copy.
5569     alloc->initialization()->set_complete_with_arraycopy();
5570   }
5571 
5572   Node* size = _gvn.transform(obj_size);
5573   access_clone(obj, alloc_obj, size, is_array);
5574 
5575   // Do not let reads from the cloned object float above the arraycopy.
5576   if (alloc != nullptr) {
5577     // Do not let stores that initialize this object be reordered with
5578     // a subsequent store that would make this object accessible by
5579     // other threads.
5580     // Record what AllocateNode this StoreStore protects so that
5581     // escape analysis can go from the MemBarStoreStoreNode to the
5582     // AllocateNode and eliminate the MemBarStoreStoreNode if possible
5583     // based on the escape status of the AllocateNode.
5584     insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
5585   } else {
5586     insert_mem_bar(Op_MemBarCPUOrder);
5587   }
5588 }
5589 
5590 //------------------------inline_native_clone----------------------------
5591 // protected native Object java.lang.Object.clone();
5592 //
5593 // Here are the simple edge cases:
5594 //  null receiver => normal trap
5595 //  virtual and clone was overridden => slow path to out-of-line clone
5596 //  not cloneable or finalizer => slow path to out-of-line Object.clone
5597 //
5598 // The general case has two steps, allocation and copying.
5599 // Allocation has two cases, and uses GraphKit::new_instance or new_array.
5600 //
5601 // Copying also has two cases, oop arrays and everything else.
5602 // Oop arrays use arrayof_oop_arraycopy (same as System.arraycopy).
5603 // Everything else uses the tight inline loop supplied by CopyArrayNode.
5604 //
5605 // These steps fold up nicely if and when the cloned object's klass
5606 // can be sharply typed as an object array, a type array, or an instance.
5607 //
5608 bool LibraryCallKit::inline_native_clone(bool is_virtual) {
5609   PhiNode* result_val;
5610 
5611   // Set the reexecute bit for the interpreter to reexecute
5612   // the bytecode that invokes Object.clone if deoptimization happens.
5613   { PreserveReexecuteState preexecs(this);
5614     jvms()->set_should_reexecute(true);
5615 
5616     Node* obj = argument(0);
5617     obj = null_check_receiver();
5618     if (stopped())  return true;
5619 
5620     const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
5621     if (obj_type->is_inlinetypeptr()) {
5622       // If the object to clone is an inline type, we can simply return it (i.e. a nop) since inline types have
5623       // no identity.
5624       set_result(obj);
5625       return true;
5626     }
5627 
5628     // If we are going to clone an instance, we need its exact type to
5629     // know the number and types of fields to convert the clone to
5630     // loads/stores. Maybe a speculative type can help us.
5631     if (!obj_type->klass_is_exact() &&
5632         obj_type->speculative_type() != nullptr &&
5633         obj_type->speculative_type()->is_instance_klass() &&
5634         !obj_type->speculative_type()->is_inlinetype()) {
5635       ciInstanceKlass* spec_ik = obj_type->speculative_type()->as_instance_klass();
5636       if (spec_ik->nof_nonstatic_fields() <= ArrayCopyLoadStoreMaxElem &&
5637           !spec_ik->has_injected_fields()) {
5638         if (!obj_type->isa_instptr() ||
5639             obj_type->is_instptr()->instance_klass()->has_subklass()) {
5640           obj = maybe_cast_profiled_obj(obj, obj_type->speculative_type(), false);
5641         }
5642       }
5643     }
5644 
5645     // Conservatively insert a memory barrier on all memory slices.
5646     // Do not let writes into the original float below the clone.
5647     insert_mem_bar(Op_MemBarCPUOrder);
5648 
5649     // paths into result_reg:
5650     enum {
5651       _slow_path = 1,     // out-of-line call to clone method (virtual or not)
5652       _objArray_path,     // plain array allocation, plus arrayof_oop_arraycopy
5653       _array_path,        // plain array allocation, plus arrayof_long_arraycopy
5654       _instance_path,     // plain instance allocation, plus arrayof_long_arraycopy
5655       PATH_LIMIT
5656     };
5657     RegionNode* result_reg = new RegionNode(PATH_LIMIT);
5658     result_val             = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
5659     PhiNode*    result_i_o = new PhiNode(result_reg, Type::ABIO);
5660     PhiNode*    result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
5661     record_for_igvn(result_reg);
5662 
5663     // TODO 8350865 For arrays, this might be folded and then not account for atomic arrays
5664     Node* obj_klass = load_object_klass(obj);
5665     // We only go to the fast case code if we pass a number of guards.
5666     // The paths which do not pass are accumulated in the slow_region.
5667     RegionNode* slow_region = new RegionNode(1);
5668     record_for_igvn(slow_region);
5669 
5670     Node* array_obj = obj;
5671     Node* array_ctl = generate_array_guard(obj_klass, (RegionNode*)nullptr, &array_obj);
5672     if (array_ctl != nullptr) {
5673       // It's an array.
5674       PreserveJVMState pjvms(this);
5675       set_control(array_ctl);
5676 
5677       BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
5678       const TypeAryPtr* ary_ptr = obj_type->isa_aryptr();
5679       if (UseArrayFlattening && bs->array_copy_requires_gc_barriers(true, T_OBJECT, true, false, BarrierSetC2::Expansion) &&
5680           obj_type->can_be_inline_array() &&
5681           (ary_ptr == nullptr || (!ary_ptr->is_not_flat() && (!ary_ptr->is_flat() || ary_ptr->elem()->inline_klass()->contains_oops())))) {
5682         // Flat inline type array may have object field that would require a
5683         // write barrier. Conservatively, go to slow path.
5684         generate_fair_guard(flat_array_test(obj_klass), slow_region);
5685       }
5686 
5687       if (!stopped()) {
5688         Node* obj_length = load_array_length(array_obj);
5689         Node* array_size = nullptr; // Size of the array without object alignment padding.
5690         Node* alloc_obj = new_array(obj_klass, obj_length, 0, &array_size, /*deoptimize_on_exception=*/true);
5691 
5692         BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
5693         if (bs->array_copy_requires_gc_barriers(true, T_OBJECT, true, false, BarrierSetC2::Parsing)) {
5694           // If it is an oop array, it requires very special treatment,
5695           // because gc barriers are required when accessing the array.
5696           Node* is_obja = generate_objArray_guard(obj_klass, (RegionNode*)nullptr);
5697           if (is_obja != nullptr) {
5698             PreserveJVMState pjvms2(this);
5699             set_control(is_obja);
5700             // Generate a direct call to the right arraycopy function(s).
5701             // Clones are always tightly coupled.
5702             ArrayCopyNode* ac = ArrayCopyNode::make(this, true, array_obj, intcon(0), alloc_obj, intcon(0), obj_length, true, false);
5703             ac->set_clone_oop_array();
5704             Node* n = _gvn.transform(ac);
5705             assert(n == ac, "cannot disappear");
5706             ac->connect_outputs(this, /*deoptimize_on_exception=*/true);
5707 
5708             result_reg->init_req(_objArray_path, control());
5709             result_val->init_req(_objArray_path, alloc_obj);
5710             result_i_o ->set_req(_objArray_path, i_o());
5711             result_mem ->set_req(_objArray_path, reset_memory());
5712           }
5713         }
5714         // Otherwise, there are no barriers to worry about.
5715         // (We can dispense with card marks if we know the allocation
5716         //  comes out of eden (TLAB)...  In fact, ReduceInitialCardMarks
5717         //  causes the non-eden paths to take compensating steps to
5718         //  simulate a fresh allocation, so that no further
5719         //  card marks are required in compiled code to initialize
5720         //  the object.)
5721 
5722         if (!stopped()) {
5723           copy_to_clone(obj, alloc_obj, array_size, true);
5724 
5725           // Present the results of the copy.
5726           result_reg->init_req(_array_path, control());
5727           result_val->init_req(_array_path, alloc_obj);
5728           result_i_o ->set_req(_array_path, i_o());
5729           result_mem ->set_req(_array_path, reset_memory());
5730         }
5731       }
5732     }
5733 
5734     if (!stopped()) {
5735       // It's an instance (we did array above).  Make the slow-path tests.
5736       // If this is a virtual call, we generate a funny guard.  We grab
5737       // the vtable entry corresponding to clone() from the target object.
5738       // If the target method which we are calling happens to be the
5739       // Object clone() method, we pass the guard.  We do not need this
5740       // guard for non-virtual calls; the caller is known to be the native
5741       // Object clone().
5742       if (is_virtual) {
5743         generate_virtual_guard(obj_klass, slow_region);
5744       }
5745 
5746       // The object must be easily cloneable and must not have a finalizer.
5747       // Both of these conditions may be checked in a single test.
5748       // We could optimize the test further, but we don't care.
5749       generate_misc_flags_guard(obj_klass,
5750                                 // Test both conditions:
5751                                 KlassFlags::_misc_is_cloneable_fast | KlassFlags::_misc_has_finalizer,
5752                                 // Must be cloneable but not finalizer:
5753                                 KlassFlags::_misc_is_cloneable_fast,
5754                                 slow_region);
5755     }
5756 
5757     if (!stopped()) {
5758       // It's an instance, and it passed the slow-path tests.
5759       PreserveJVMState pjvms(this);
5760       Node* obj_size = nullptr; // Total object size, including object alignment padding.
5761       // Need to deoptimize on exception from allocation since Object.clone intrinsic
5762       // is reexecuted if deoptimization occurs and there could be problems when merging
5763       // exception state between multiple Object.clone versions (reexecute=true vs reexecute=false).
5764       Node* alloc_obj = new_instance(obj_klass, nullptr, &obj_size, /*deoptimize_on_exception=*/true);
5765 
5766       copy_to_clone(obj, alloc_obj, obj_size, false);
5767 
5768       // Present the results of the slow call.
5769       result_reg->init_req(_instance_path, control());
5770       result_val->init_req(_instance_path, alloc_obj);
5771       result_i_o ->set_req(_instance_path, i_o());
5772       result_mem ->set_req(_instance_path, reset_memory());
5773     }
5774 
5775     // Generate code for the slow case.  We make a call to clone().
5776     set_control(_gvn.transform(slow_region));
5777     if (!stopped()) {
5778       PreserveJVMState pjvms(this);
5779       CallJavaNode* slow_call = generate_method_call(vmIntrinsics::_clone, is_virtual, false, true);
5780       // We need to deoptimize on exception (see comment above)
5781       Node* slow_result = set_results_for_java_call(slow_call, false, /* deoptimize */ true);
5782       // this->control() comes from set_results_for_java_call
5783       result_reg->init_req(_slow_path, control());
5784       result_val->init_req(_slow_path, slow_result);
5785       result_i_o ->set_req(_slow_path, i_o());
5786       result_mem ->set_req(_slow_path, reset_memory());
5787     }
5788 
5789     // Return the combined state.
5790     set_control(    _gvn.transform(result_reg));
5791     set_i_o(        _gvn.transform(result_i_o));
5792     set_all_memory( _gvn.transform(result_mem));
5793   } // original reexecute is set back here
5794 
5795   set_result(_gvn.transform(result_val));
5796   return true;
5797 }
5798 
5799 // If we have a tightly coupled allocation, the arraycopy may take care
5800 // of the array initialization. If one of the guards we insert between
5801 // the allocation and the arraycopy causes a deoptimization, an
5802 // uninitialized array will escape the compiled method. To prevent that
5803 // we set the JVM state for uncommon traps between the allocation and
5804 // the arraycopy to the state before the allocation so, in case of
5805 // deoptimization, we'll reexecute the allocation and the
5806 // initialization.
5807 JVMState* LibraryCallKit::arraycopy_restore_alloc_state(AllocateArrayNode* alloc, int& saved_reexecute_sp) {
5808   if (alloc != nullptr) {
5809     ciMethod* trap_method = alloc->jvms()->method();
5810     int trap_bci = alloc->jvms()->bci();
5811 
5812     if (!C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_intrinsic) &&
5813         !C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_null_check)) {
5814       // Make sure there's no store between the allocation and the
5815       // arraycopy otherwise visible side effects could be rexecuted
5816       // in case of deoptimization and cause incorrect execution.
5817       bool no_interfering_store = true;
5818       Node* mem = alloc->in(TypeFunc::Memory);
5819       if (mem->is_MergeMem()) {
5820         for (MergeMemStream mms(merged_memory(), mem->as_MergeMem()); mms.next_non_empty2(); ) {
5821           Node* n = mms.memory();
5822           if (n != mms.memory2() && !(n->is_Proj() && n->in(0) == alloc->initialization())) {
5823             assert(n->is_Store(), "what else?");
5824             no_interfering_store = false;
5825             break;
5826           }
5827         }
5828       } else {
5829         for (MergeMemStream mms(merged_memory()); mms.next_non_empty(); ) {
5830           Node* n = mms.memory();
5831           if (n != mem && !(n->is_Proj() && n->in(0) == alloc->initialization())) {
5832             assert(n->is_Store(), "what else?");
5833             no_interfering_store = false;
5834             break;
5835           }
5836         }
5837       }
5838 
5839       if (no_interfering_store) {
5840         SafePointNode* sfpt = create_safepoint_with_state_before_array_allocation(alloc);
5841 
5842         JVMState* saved_jvms = jvms();
5843         saved_reexecute_sp = _reexecute_sp;
5844 
5845         set_jvms(sfpt->jvms());
5846         _reexecute_sp = jvms()->sp();
5847 
5848         return saved_jvms;
5849       }
5850     }
5851   }
5852   return nullptr;
5853 }
5854 
5855 // Clone the JVMState of the array allocation and create a new safepoint with it. Re-push the array length to the stack
5856 // such that uncommon traps can be emitted to re-execute the array allocation in the interpreter.
5857 SafePointNode* LibraryCallKit::create_safepoint_with_state_before_array_allocation(const AllocateArrayNode* alloc) const {
5858   JVMState* old_jvms = alloc->jvms()->clone_shallow(C);
5859   uint size = alloc->req();
5860   SafePointNode* sfpt = new SafePointNode(size, old_jvms);
5861   old_jvms->set_map(sfpt);
5862   for (uint i = 0; i < size; i++) {
5863     sfpt->init_req(i, alloc->in(i));
5864   }
5865   int adjustment = 1;
5866   const TypeAryKlassPtr* ary_klass_ptr = alloc->in(AllocateNode::KlassNode)->bottom_type()->is_aryklassptr();
5867   if (ary_klass_ptr->is_null_free()) {
5868     // A null-free, tightly coupled array allocation can only come from LibraryCallKit::inline_newArray which
5869     // also requires the componentType and initVal on stack for re-execution.
5870     // Re-create and push the componentType.
5871     ciArrayKlass* klass = ary_klass_ptr->exact_klass()->as_array_klass();
5872     ciInstance* instance = klass->component_mirror_instance();
5873     const TypeInstPtr* t_instance = TypeInstPtr::make(instance);
5874     sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp(), makecon(t_instance));
5875     adjustment++;
5876   }
5877   // re-push array length for deoptimization
5878   sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp() + adjustment - 1, alloc->in(AllocateNode::ALength));
5879   if (ary_klass_ptr->is_null_free()) {
5880     // Re-create and push the initVal.
5881     Node* init_val = alloc->in(AllocateNode::InitValue);
5882     if (init_val == nullptr) {
5883       init_val = InlineTypeNode::make_all_zero(_gvn, ary_klass_ptr->elem()->is_instklassptr()->instance_klass()->as_inline_klass());
5884     } else if (UseCompressedOops) {
5885       init_val = _gvn.transform(new DecodeNNode(init_val, init_val->bottom_type()->make_ptr()));
5886     }
5887     sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp() + adjustment, init_val);
5888     adjustment++;
5889   }
5890   old_jvms->set_sp(old_jvms->sp() + adjustment);
5891   old_jvms->set_monoff(old_jvms->monoff() + adjustment);
5892   old_jvms->set_scloff(old_jvms->scloff() + adjustment);
5893   old_jvms->set_endoff(old_jvms->endoff() + adjustment);
5894   old_jvms->set_should_reexecute(true);
5895 
5896   sfpt->set_i_o(map()->i_o());
5897   sfpt->set_memory(map()->memory());
5898   sfpt->set_control(map()->control());
5899   return sfpt;
5900 }
5901 
5902 // In case of a deoptimization, we restart execution at the
5903 // allocation, allocating a new array. We would leave an uninitialized
5904 // array in the heap that GCs wouldn't expect. Move the allocation
5905 // after the traps so we don't allocate the array if we
5906 // deoptimize. This is possible because tightly_coupled_allocation()
5907 // guarantees there's no observer of the allocated array at this point
5908 // and the control flow is simple enough.
5909 void LibraryCallKit::arraycopy_move_allocation_here(AllocateArrayNode* alloc, Node* dest, JVMState* saved_jvms_before_guards,
5910                                                     int saved_reexecute_sp, uint new_idx) {
5911   if (saved_jvms_before_guards != nullptr && !stopped()) {
5912     replace_unrelated_uncommon_traps_with_alloc_state(alloc, saved_jvms_before_guards);
5913 
5914     assert(alloc != nullptr, "only with a tightly coupled allocation");
5915     // restore JVM state to the state at the arraycopy
5916     saved_jvms_before_guards->map()->set_control(map()->control());
5917     assert(saved_jvms_before_guards->map()->memory() == map()->memory(), "memory state changed?");
5918     assert(saved_jvms_before_guards->map()->i_o() == map()->i_o(), "IO state changed?");
5919     // If we've improved the types of some nodes (null check) while
5920     // emitting the guards, propagate them to the current state
5921     map()->replaced_nodes().apply(saved_jvms_before_guards->map(), new_idx);
5922     set_jvms(saved_jvms_before_guards);
5923     _reexecute_sp = saved_reexecute_sp;
5924 
5925     // Remove the allocation from above the guards
5926     CallProjections* callprojs = alloc->extract_projections(true);
5927     InitializeNode* init = alloc->initialization();
5928     Node* alloc_mem = alloc->in(TypeFunc::Memory);
5929     C->gvn_replace_by(callprojs->fallthrough_ioproj, alloc->in(TypeFunc::I_O));
5930     C->gvn_replace_by(init->proj_out(TypeFunc::Memory), alloc_mem);
5931 
5932     // The CastIINode created in GraphKit::new_array (in AllocateArrayNode::make_ideal_length) must stay below
5933     // the allocation (i.e. is only valid if the allocation succeeds):
5934     // 1) replace CastIINode with AllocateArrayNode's length here
5935     // 2) Create CastIINode again once allocation has moved (see below) at the end of this method
5936     //
5937     // Multiple identical CastIINodes might exist here. Each GraphKit::load_array_length() call will generate
5938     // new separate CastIINode (arraycopy guard checks or any array length use between array allocation and ararycopy)
5939     Node* init_control = init->proj_out(TypeFunc::Control);
5940     Node* alloc_length = alloc->Ideal_length();
5941 #ifdef ASSERT
5942     Node* prev_cast = nullptr;
5943 #endif
5944     for (uint i = 0; i < init_control->outcnt(); i++) {
5945       Node* init_out = init_control->raw_out(i);
5946       if (init_out->is_CastII() && init_out->in(TypeFunc::Control) == init_control && init_out->in(1) == alloc_length) {
5947 #ifdef ASSERT
5948         if (prev_cast == nullptr) {
5949           prev_cast = init_out;
5950         } else {
5951           if (prev_cast->cmp(*init_out) == false) {
5952             prev_cast->dump();
5953             init_out->dump();
5954             assert(false, "not equal CastIINode");
5955           }
5956         }
5957 #endif
5958         C->gvn_replace_by(init_out, alloc_length);
5959       }
5960     }
5961     C->gvn_replace_by(init->proj_out(TypeFunc::Control), alloc->in(0));
5962 
5963     // move the allocation here (after the guards)
5964     _gvn.hash_delete(alloc);
5965     alloc->set_req(TypeFunc::Control, control());
5966     alloc->set_req(TypeFunc::I_O, i_o());
5967     Node *mem = reset_memory();
5968     set_all_memory(mem);
5969     alloc->set_req(TypeFunc::Memory, mem);
5970     set_control(init->proj_out_or_null(TypeFunc::Control));
5971     set_i_o(callprojs->fallthrough_ioproj);
5972 
5973     // Update memory as done in GraphKit::set_output_for_allocation()
5974     const TypeInt* length_type = _gvn.find_int_type(alloc->in(AllocateNode::ALength));
5975     const TypeOopPtr* ary_type = _gvn.type(alloc->in(AllocateNode::KlassNode))->is_klassptr()->as_instance_type();
5976     if (ary_type->isa_aryptr() && length_type != nullptr) {
5977       ary_type = ary_type->is_aryptr()->cast_to_size(length_type);
5978     }
5979     const TypePtr* telemref = ary_type->add_offset(Type::OffsetBot);
5980     int            elemidx  = C->get_alias_index(telemref);
5981     set_memory(init->proj_out_or_null(TypeFunc::Memory), Compile::AliasIdxRaw);
5982     set_memory(init->proj_out_or_null(TypeFunc::Memory), elemidx);
5983 
5984     Node* allocx = _gvn.transform(alloc);
5985     assert(allocx == alloc, "where has the allocation gone?");
5986     assert(dest->is_CheckCastPP(), "not an allocation result?");
5987 
5988     _gvn.hash_delete(dest);
5989     dest->set_req(0, control());
5990     Node* destx = _gvn.transform(dest);
5991     assert(destx == dest, "where has the allocation result gone?");
5992 
5993     array_ideal_length(alloc, ary_type, true);
5994   }
5995 }
5996 
5997 // Unrelated UCTs between the array allocation and the array copy, which are considered safe by tightly_coupled_allocation(),
5998 // need to be replaced by an UCT with a state before the array allocation (including the array length). This is necessary
5999 // because we could hit one of these UCTs (which are executed before the emitted array copy guards and the actual array
6000 // allocation which is moved down in arraycopy_move_allocation_here()). When later resuming execution in the interpreter,
6001 // we would have wrongly skipped the array allocation. To prevent this, we resume execution at the array allocation in
6002 // the interpreter similar to what we are doing for the newly emitted guards for the array copy.
6003 void LibraryCallKit::replace_unrelated_uncommon_traps_with_alloc_state(AllocateArrayNode* alloc,
6004                                                                        JVMState* saved_jvms_before_guards) {
6005   if (saved_jvms_before_guards->map()->control()->is_IfProj()) {
6006     // There is at least one unrelated uncommon trap which needs to be replaced.
6007     SafePointNode* sfpt = create_safepoint_with_state_before_array_allocation(alloc);
6008 
6009     JVMState* saved_jvms = jvms();
6010     const int saved_reexecute_sp = _reexecute_sp;
6011     set_jvms(sfpt->jvms());
6012     _reexecute_sp = jvms()->sp();
6013 
6014     replace_unrelated_uncommon_traps_with_alloc_state(saved_jvms_before_guards);
6015 
6016     // Restore state
6017     set_jvms(saved_jvms);
6018     _reexecute_sp = saved_reexecute_sp;
6019   }
6020 }
6021 
6022 // Replace the unrelated uncommon traps with new uncommon trap nodes by reusing the action and reason. The new uncommon
6023 // traps will have the state of the array allocation. Let the old uncommon trap nodes die.
6024 void LibraryCallKit::replace_unrelated_uncommon_traps_with_alloc_state(JVMState* saved_jvms_before_guards) {
6025   Node* if_proj = saved_jvms_before_guards->map()->control(); // Start the search right before the newly emitted guards
6026   while (if_proj->is_IfProj()) {
6027     CallStaticJavaNode* uncommon_trap = get_uncommon_trap_from_success_proj(if_proj);
6028     if (uncommon_trap != nullptr) {
6029       create_new_uncommon_trap(uncommon_trap);
6030     }
6031     assert(if_proj->in(0)->is_If(), "must be If");
6032     if_proj = if_proj->in(0)->in(0);
6033   }
6034   assert(if_proj->is_Proj() && if_proj->in(0)->is_Initialize(),
6035          "must have reached control projection of init node");
6036 }
6037 
6038 void LibraryCallKit::create_new_uncommon_trap(CallStaticJavaNode* uncommon_trap_call) {
6039   const int trap_request = uncommon_trap_call->uncommon_trap_request();
6040   assert(trap_request != 0, "no valid UCT trap request");
6041   PreserveJVMState pjvms(this);
6042   set_control(uncommon_trap_call->in(0));
6043   uncommon_trap(Deoptimization::trap_request_reason(trap_request),
6044                 Deoptimization::trap_request_action(trap_request));
6045   assert(stopped(), "Should be stopped");
6046   _gvn.hash_delete(uncommon_trap_call);
6047   uncommon_trap_call->set_req(0, top()); // not used anymore, kill it
6048 }
6049 
6050 // Common checks for array sorting intrinsics arguments.
6051 // Returns `true` if checks passed.
6052 bool LibraryCallKit::check_array_sort_arguments(Node* elementType, Node* obj, BasicType& bt) {
6053   // check address of the class
6054   if (elementType == nullptr || elementType->is_top()) {
6055     return false;  // dead path
6056   }
6057   const TypeInstPtr* elem_klass = gvn().type(elementType)->isa_instptr();
6058   if (elem_klass == nullptr) {
6059     return false;  // dead path
6060   }
6061   // java_mirror_type() returns non-null for compile-time Class constants only
6062   ciType* elem_type = elem_klass->java_mirror_type();
6063   if (elem_type == nullptr) {
6064     return false;
6065   }
6066   bt = elem_type->basic_type();
6067   // Disable the intrinsic if the CPU does not support SIMD sort
6068   if (!Matcher::supports_simd_sort(bt)) {
6069     return false;
6070   }
6071   // check address of the array
6072   if (obj == nullptr || obj->is_top()) {
6073     return false;  // dead path
6074   }
6075   const TypeAryPtr* obj_t = _gvn.type(obj)->isa_aryptr();
6076   if (obj_t == nullptr || obj_t->elem() == Type::BOTTOM) {
6077     return false; // failed input validation
6078   }
6079   return true;
6080 }
6081 
6082 //------------------------------inline_array_partition-----------------------
6083 bool LibraryCallKit::inline_array_partition() {
6084   address stubAddr = StubRoutines::select_array_partition_function();
6085   if (stubAddr == nullptr) {
6086     return false; // Intrinsic's stub is not implemented on this platform
6087   }
6088   assert(callee()->signature()->size() == 9, "arrayPartition has 8 parameters (one long)");
6089 
6090   // no receiver because it is a static method
6091   Node* elementType     = argument(0);
6092   Node* obj             = argument(1);
6093   Node* offset          = argument(2); // long
6094   Node* fromIndex       = argument(4);
6095   Node* toIndex         = argument(5);
6096   Node* indexPivot1     = argument(6);
6097   Node* indexPivot2     = argument(7);
6098   // PartitionOperation:  argument(8) is ignored
6099 
6100   Node* pivotIndices = nullptr;
6101   BasicType bt = T_ILLEGAL;
6102 
6103   if (!check_array_sort_arguments(elementType, obj, bt)) {
6104     return false;
6105   }
6106   null_check(obj);
6107   // If obj is dead, only null-path is taken.
6108   if (stopped()) {
6109     return true;
6110   }
6111   // Set the original stack and the reexecute bit for the interpreter to reexecute
6112   // the bytecode that invokes DualPivotQuicksort.partition() if deoptimization happens.
6113   { PreserveReexecuteState preexecs(this);
6114     jvms()->set_should_reexecute(true);
6115 
6116     Node* obj_adr = make_unsafe_address(obj, offset);
6117 
6118     // create the pivotIndices array of type int and size = 2
6119     Node* size = intcon(2);
6120     Node* klass_node = makecon(TypeKlassPtr::make(ciTypeArrayKlass::make(T_INT)));
6121     pivotIndices = new_array(klass_node, size, 0);  // no arguments to push
6122     AllocateArrayNode* alloc = tightly_coupled_allocation(pivotIndices);
6123     guarantee(alloc != nullptr, "created above");
6124     Node* pivotIndices_adr = basic_plus_adr(pivotIndices, arrayOopDesc::base_offset_in_bytes(T_INT));
6125 
6126     // pass the basic type enum to the stub
6127     Node* elemType = intcon(bt);
6128 
6129     // Call the stub
6130     const char *stubName = "array_partition_stub";
6131     make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::array_partition_Type(),
6132                       stubAddr, stubName, TypePtr::BOTTOM,
6133                       obj_adr, elemType, fromIndex, toIndex, pivotIndices_adr,
6134                       indexPivot1, indexPivot2);
6135 
6136   } // original reexecute is set back here
6137 
6138   if (!stopped()) {
6139     set_result(pivotIndices);
6140   }
6141 
6142   return true;
6143 }
6144 
6145 
6146 //------------------------------inline_array_sort-----------------------
6147 bool LibraryCallKit::inline_array_sort() {
6148   address stubAddr = StubRoutines::select_arraysort_function();
6149   if (stubAddr == nullptr) {
6150     return false; // Intrinsic's stub is not implemented on this platform
6151   }
6152   assert(callee()->signature()->size() == 7, "arraySort has 6 parameters (one long)");
6153 
6154   // no receiver because it is a static method
6155   Node* elementType     = argument(0);
6156   Node* obj             = argument(1);
6157   Node* offset          = argument(2); // long
6158   Node* fromIndex       = argument(4);
6159   Node* toIndex         = argument(5);
6160   // SortOperation:       argument(6) is ignored
6161 
6162   BasicType bt = T_ILLEGAL;
6163 
6164   if (!check_array_sort_arguments(elementType, obj, bt)) {
6165     return false;
6166   }
6167   null_check(obj);
6168   // If obj is dead, only null-path is taken.
6169   if (stopped()) {
6170     return true;
6171   }
6172   Node* obj_adr = make_unsafe_address(obj, offset);
6173 
6174   // pass the basic type enum to the stub
6175   Node* elemType = intcon(bt);
6176 
6177   // Call the stub.
6178   const char *stubName = "arraysort_stub";
6179   make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::array_sort_Type(),
6180                     stubAddr, stubName, TypePtr::BOTTOM,
6181                     obj_adr, elemType, fromIndex, toIndex);
6182 
6183   return true;
6184 }
6185 
6186 
6187 //------------------------------inline_arraycopy-----------------------
6188 // public static native void java.lang.System.arraycopy(Object src,  int  srcPos,
6189 //                                                      Object dest, int destPos,
6190 //                                                      int length);
6191 bool LibraryCallKit::inline_arraycopy() {
6192   // Get the arguments.
6193   Node* src         = argument(0);  // type: oop
6194   Node* src_offset  = argument(1);  // type: int
6195   Node* dest        = argument(2);  // type: oop
6196   Node* dest_offset = argument(3);  // type: int
6197   Node* length      = argument(4);  // type: int
6198 
6199   uint new_idx = C->unique();
6200 
6201   // Check for allocation before we add nodes that would confuse
6202   // tightly_coupled_allocation()
6203   AllocateArrayNode* alloc = tightly_coupled_allocation(dest);
6204 
6205   int saved_reexecute_sp = -1;
6206   JVMState* saved_jvms_before_guards = arraycopy_restore_alloc_state(alloc, saved_reexecute_sp);
6207   // See arraycopy_restore_alloc_state() comment
6208   // if alloc == null we don't have to worry about a tightly coupled allocation so we can emit all needed guards
6209   // if saved_jvms_before_guards is not null (then alloc is not null) then we can handle guards and a tightly coupled allocation
6210   // if saved_jvms_before_guards is null and alloc is not null, we can't emit any guards
6211   bool can_emit_guards = (alloc == nullptr || saved_jvms_before_guards != nullptr);
6212 
6213   // The following tests must be performed
6214   // (1) src and dest are arrays.
6215   // (2) src and dest arrays must have elements of the same BasicType
6216   // (3) src and dest must not be null.
6217   // (4) src_offset must not be negative.
6218   // (5) dest_offset must not be negative.
6219   // (6) length must not be negative.
6220   // (7) src_offset + length must not exceed length of src.
6221   // (8) dest_offset + length must not exceed length of dest.
6222   // (9) each element of an oop array must be assignable
6223 
6224   // (3) src and dest must not be null.
6225   // always do this here because we need the JVM state for uncommon traps
6226   Node* null_ctl = top();
6227   src  = saved_jvms_before_guards != nullptr ? null_check_oop(src, &null_ctl, true, true) : null_check(src, T_ARRAY);
6228   assert(null_ctl->is_top(), "no null control here");
6229   dest = null_check(dest, T_ARRAY);
6230 
6231   if (!can_emit_guards) {
6232     // if saved_jvms_before_guards is null and alloc is not null, we don't emit any
6233     // guards but the arraycopy node could still take advantage of a
6234     // tightly allocated allocation. tightly_coupled_allocation() is
6235     // called again to make sure it takes the null check above into
6236     // account: the null check is mandatory and if it caused an
6237     // uncommon trap to be emitted then the allocation can't be
6238     // considered tightly coupled in this context.
6239     alloc = tightly_coupled_allocation(dest);
6240   }
6241 
6242   bool validated = false;
6243 
6244   const Type* src_type  = _gvn.type(src);
6245   const Type* dest_type = _gvn.type(dest);
6246   const TypeAryPtr* top_src  = src_type->isa_aryptr();
6247   const TypeAryPtr* top_dest = dest_type->isa_aryptr();
6248 
6249   // Do we have the type of src?
6250   bool has_src = (top_src != nullptr && top_src->elem() != Type::BOTTOM);
6251   // Do we have the type of dest?
6252   bool has_dest = (top_dest != nullptr && top_dest->elem() != Type::BOTTOM);
6253   // Is the type for src from speculation?
6254   bool src_spec = false;
6255   // Is the type for dest from speculation?
6256   bool dest_spec = false;
6257 
6258   if ((!has_src || !has_dest) && can_emit_guards) {
6259     // We don't have sufficient type information, let's see if
6260     // speculative types can help. We need to have types for both src
6261     // and dest so that it pays off.
6262 
6263     // Do we already have or could we have type information for src
6264     bool could_have_src = has_src;
6265     // Do we already have or could we have type information for dest
6266     bool could_have_dest = has_dest;
6267 
6268     ciKlass* src_k = nullptr;
6269     if (!has_src) {
6270       src_k = src_type->speculative_type_not_null();
6271       if (src_k != nullptr && src_k->is_array_klass()) {
6272         could_have_src = true;
6273       }
6274     }
6275 
6276     ciKlass* dest_k = nullptr;
6277     if (!has_dest) {
6278       dest_k = dest_type->speculative_type_not_null();
6279       if (dest_k != nullptr && dest_k->is_array_klass()) {
6280         could_have_dest = true;
6281       }
6282     }
6283 
6284     if (could_have_src && could_have_dest) {
6285       // This is going to pay off so emit the required guards
6286       if (!has_src) {
6287         src = maybe_cast_profiled_obj(src, src_k, true);
6288         src_type  = _gvn.type(src);
6289         top_src  = src_type->isa_aryptr();
6290         has_src = (top_src != nullptr && top_src->elem() != Type::BOTTOM);
6291         src_spec = true;
6292       }
6293       if (!has_dest) {
6294         dest = maybe_cast_profiled_obj(dest, dest_k, true);
6295         dest_type  = _gvn.type(dest);
6296         top_dest  = dest_type->isa_aryptr();
6297         has_dest = (top_dest != nullptr && top_dest->elem() != Type::BOTTOM);
6298         dest_spec = true;
6299       }
6300     }
6301   }
6302 
6303   if (has_src && has_dest && can_emit_guards) {
6304     BasicType src_elem = top_src->isa_aryptr()->elem()->array_element_basic_type();
6305     BasicType dest_elem = top_dest->isa_aryptr()->elem()->array_element_basic_type();
6306     if (is_reference_type(src_elem, true)) src_elem = T_OBJECT;
6307     if (is_reference_type(dest_elem, true)) dest_elem = T_OBJECT;
6308 
6309     if (src_elem == dest_elem && top_src->is_flat() == top_dest->is_flat() && src_elem == T_OBJECT) {
6310       // If both arrays are object arrays then having the exact types
6311       // for both will remove the need for a subtype check at runtime
6312       // before the call and may make it possible to pick a faster copy
6313       // routine (without a subtype check on every element)
6314       // Do we have the exact type of src?
6315       bool could_have_src = src_spec;
6316       // Do we have the exact type of dest?
6317       bool could_have_dest = dest_spec;
6318       ciKlass* src_k = nullptr;
6319       ciKlass* dest_k = nullptr;
6320       if (!src_spec) {
6321         src_k = src_type->speculative_type_not_null();
6322         if (src_k != nullptr && src_k->is_array_klass()) {
6323           could_have_src = true;
6324         }
6325       }
6326       if (!dest_spec) {
6327         dest_k = dest_type->speculative_type_not_null();
6328         if (dest_k != nullptr && dest_k->is_array_klass()) {
6329           could_have_dest = true;
6330         }
6331       }
6332       if (could_have_src && could_have_dest) {
6333         // If we can have both exact types, emit the missing guards
6334         if (could_have_src && !src_spec) {
6335           src = maybe_cast_profiled_obj(src, src_k, true);
6336           src_type = _gvn.type(src);
6337           top_src = src_type->isa_aryptr();
6338         }
6339         if (could_have_dest && !dest_spec) {
6340           dest = maybe_cast_profiled_obj(dest, dest_k, true);
6341           dest_type = _gvn.type(dest);
6342           top_dest = dest_type->isa_aryptr();
6343         }
6344       }
6345     }
6346   }
6347 
6348   ciMethod* trap_method = method();
6349   int trap_bci = bci();
6350   if (saved_jvms_before_guards != nullptr) {
6351     trap_method = alloc->jvms()->method();
6352     trap_bci = alloc->jvms()->bci();
6353   }
6354 
6355   bool negative_length_guard_generated = false;
6356 
6357   if (!C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_intrinsic) &&
6358       can_emit_guards && !src->is_top() && !dest->is_top()) {
6359     // validate arguments: enables transformation the ArrayCopyNode
6360     validated = true;
6361 
6362     RegionNode* slow_region = new RegionNode(1);
6363     record_for_igvn(slow_region);
6364 
6365     // (1) src and dest are arrays.
6366     generate_non_array_guard(load_object_klass(src), slow_region, &src);
6367     generate_non_array_guard(load_object_klass(dest), slow_region, &dest);
6368 
6369     // (2) src and dest arrays must have elements of the same BasicType
6370     // done at macro expansion or at Ideal transformation time
6371 
6372     // (4) src_offset must not be negative.
6373     generate_negative_guard(src_offset, slow_region);
6374 
6375     // (5) dest_offset must not be negative.
6376     generate_negative_guard(dest_offset, slow_region);
6377 
6378     // (7) src_offset + length must not exceed length of src.
6379     generate_limit_guard(src_offset, length,
6380                          load_array_length(src),
6381                          slow_region);
6382 
6383     // (8) dest_offset + length must not exceed length of dest.
6384     generate_limit_guard(dest_offset, length,
6385                          load_array_length(dest),
6386                          slow_region);
6387 
6388     // (6) length must not be negative.
6389     // This is also checked in generate_arraycopy() during macro expansion, but
6390     // we also have to check it here for the case where the ArrayCopyNode will
6391     // be eliminated by Escape Analysis.
6392     if (EliminateAllocations) {
6393       generate_negative_guard(length, slow_region);
6394       negative_length_guard_generated = true;
6395     }
6396 
6397     // (9) each element of an oop array must be assignable
6398     Node* dest_klass = load_object_klass(dest);
6399     if (src != dest) {
6400       Node* not_subtype_ctrl = gen_subtype_check(src, dest_klass);
6401       slow_region->add_req(not_subtype_ctrl);
6402     }
6403 
6404     // TODO 8350865 Fix below logic. Also handle atomicity.
6405     generate_fair_guard(flat_array_test(src), slow_region);
6406     generate_fair_guard(flat_array_test(dest), slow_region);
6407 
6408     const TypeKlassPtr* dest_klass_t = _gvn.type(dest_klass)->is_klassptr();
6409     const Type* toop = dest_klass_t->cast_to_exactness(false)->as_instance_type();
6410     src = _gvn.transform(new CheckCastPPNode(control(), src, toop));
6411     src_type = _gvn.type(src);
6412     top_src  = src_type->isa_aryptr();
6413 
6414     // Handle flat inline type arrays (null-free arrays are handled by the subtype check above)
6415     if (!stopped() && UseArrayFlattening) {
6416       // If dest is flat, src must be flat as well (guaranteed by src <: dest check). Handle flat src here.
6417       assert(top_dest == nullptr || !top_dest->is_flat() || top_src->is_flat(), "src array must be flat");
6418       if (top_src != nullptr && top_src->is_flat()) {
6419         // Src is flat, check that dest is flat as well
6420         if (top_dest != nullptr && !top_dest->is_flat()) {
6421           generate_fair_guard(flat_array_test(dest_klass, /* flat = */ false), slow_region);
6422           // Since dest is flat and src <: dest, dest must have the same type as src.
6423           top_dest = top_src->cast_to_exactness(false);
6424           assert(top_dest->is_flat(), "dest must be flat");
6425           dest = _gvn.transform(new CheckCastPPNode(control(), dest, top_dest));
6426         }
6427       } else if (top_src == nullptr || !top_src->is_not_flat()) {
6428         // Src might be flat and dest might not be flat. Go to the slow path if src is flat.
6429         // TODO 8251971: Optimize for the case when src/dest are later found to be both flat.
6430         assert(top_dest == nullptr || !top_dest->is_flat(), "dest array must not be flat");
6431         generate_fair_guard(flat_array_test(src), slow_region);
6432         if (top_src != nullptr) {
6433           top_src = top_src->cast_to_not_flat();
6434           src = _gvn.transform(new CheckCastPPNode(control(), src, top_src));
6435         }
6436       }
6437     }
6438 
6439     {
6440       PreserveJVMState pjvms(this);
6441       set_control(_gvn.transform(slow_region));
6442       uncommon_trap(Deoptimization::Reason_intrinsic,
6443                     Deoptimization::Action_make_not_entrant);
6444       assert(stopped(), "Should be stopped");
6445     }
6446     arraycopy_move_allocation_here(alloc, dest, saved_jvms_before_guards, saved_reexecute_sp, new_idx);
6447   }
6448 
6449   if (stopped()) {
6450     return true;
6451   }
6452 
6453   ArrayCopyNode* ac = ArrayCopyNode::make(this, true, src, src_offset, dest, dest_offset, length, alloc != nullptr, negative_length_guard_generated,
6454                                           // Create LoadRange and LoadKlass nodes for use during macro expansion here
6455                                           // so the compiler has a chance to eliminate them: during macro expansion,
6456                                           // we have to set their control (CastPP nodes are eliminated).
6457                                           load_object_klass(src), load_object_klass(dest),
6458                                           load_array_length(src), load_array_length(dest));
6459 
6460   ac->set_arraycopy(validated);
6461 
6462   Node* n = _gvn.transform(ac);
6463   if (n == ac) {
6464     ac->connect_outputs(this);
6465   } else {
6466     assert(validated, "shouldn't transform if all arguments not validated");
6467     set_all_memory(n);
6468   }
6469   clear_upper_avx();
6470 
6471 
6472   return true;
6473 }
6474 
6475 
6476 // Helper function which determines if an arraycopy immediately follows
6477 // an allocation, with no intervening tests or other escapes for the object.
6478 AllocateArrayNode*
6479 LibraryCallKit::tightly_coupled_allocation(Node* ptr) {
6480   if (stopped())             return nullptr;  // no fast path
6481   if (!C->do_aliasing())     return nullptr;  // no MergeMems around
6482 
6483   AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(ptr);
6484   if (alloc == nullptr)  return nullptr;
6485 
6486   Node* rawmem = memory(Compile::AliasIdxRaw);
6487   // Is the allocation's memory state untouched?
6488   if (!(rawmem->is_Proj() && rawmem->in(0)->is_Initialize())) {
6489     // Bail out if there have been raw-memory effects since the allocation.
6490     // (Example:  There might have been a call or safepoint.)
6491     return nullptr;
6492   }
6493   rawmem = rawmem->in(0)->as_Initialize()->memory(Compile::AliasIdxRaw);
6494   if (!(rawmem->is_Proj() && rawmem->in(0) == alloc)) {
6495     return nullptr;
6496   }
6497 
6498   // There must be no unexpected observers of this allocation.
6499   for (DUIterator_Fast imax, i = ptr->fast_outs(imax); i < imax; i++) {
6500     Node* obs = ptr->fast_out(i);
6501     if (obs != this->map()) {
6502       return nullptr;
6503     }
6504   }
6505 
6506   // This arraycopy must unconditionally follow the allocation of the ptr.
6507   Node* alloc_ctl = ptr->in(0);
6508   Node* ctl = control();
6509   while (ctl != alloc_ctl) {
6510     // There may be guards which feed into the slow_region.
6511     // Any other control flow means that we might not get a chance
6512     // to finish initializing the allocated object.
6513     // Various low-level checks bottom out in uncommon traps. These
6514     // are considered safe since we've already checked above that
6515     // there is no unexpected observer of this allocation.
6516     if (get_uncommon_trap_from_success_proj(ctl) != nullptr) {
6517       assert(ctl->in(0)->is_If(), "must be If");
6518       ctl = ctl->in(0)->in(0);
6519     } else {
6520       return nullptr;
6521     }
6522   }
6523 
6524   // If we get this far, we have an allocation which immediately
6525   // precedes the arraycopy, and we can take over zeroing the new object.
6526   // The arraycopy will finish the initialization, and provide
6527   // a new control state to which we will anchor the destination pointer.
6528 
6529   return alloc;
6530 }
6531 
6532 CallStaticJavaNode* LibraryCallKit::get_uncommon_trap_from_success_proj(Node* node) {
6533   if (node->is_IfProj()) {
6534     Node* other_proj = node->as_IfProj()->other_if_proj();
6535     for (DUIterator_Fast jmax, j = other_proj->fast_outs(jmax); j < jmax; j++) {
6536       Node* obs = other_proj->fast_out(j);
6537       if (obs->in(0) == other_proj && obs->is_CallStaticJava() &&
6538           (obs->as_CallStaticJava()->entry_point() == OptoRuntime::uncommon_trap_blob()->entry_point())) {
6539         return obs->as_CallStaticJava();
6540       }
6541     }
6542   }
6543   return nullptr;
6544 }
6545 
6546 //-------------inline_encodeISOArray-----------------------------------
6547 // encode char[] to byte[] in ISO_8859_1 or ASCII
6548 bool LibraryCallKit::inline_encodeISOArray(bool ascii) {
6549   assert(callee()->signature()->size() == 5, "encodeISOArray has 5 parameters");
6550   // no receiver since it is static method
6551   Node *src         = argument(0);
6552   Node *src_offset  = argument(1);
6553   Node *dst         = argument(2);
6554   Node *dst_offset  = argument(3);
6555   Node *length      = argument(4);
6556 
6557   src = must_be_not_null(src, true);
6558   dst = must_be_not_null(dst, true);
6559 
6560   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
6561   const TypeAryPtr* dst_type = dst->Value(&_gvn)->isa_aryptr();
6562   if (src_type == nullptr || src_type->elem() == Type::BOTTOM ||
6563       dst_type == nullptr || dst_type->elem() == Type::BOTTOM) {
6564     // failed array check
6565     return false;
6566   }
6567 
6568   // Figure out the size and type of the elements we will be copying.
6569   BasicType src_elem = src_type->elem()->array_element_basic_type();
6570   BasicType dst_elem = dst_type->elem()->array_element_basic_type();
6571   if (!((src_elem == T_CHAR) || (src_elem== T_BYTE)) || dst_elem != T_BYTE) {
6572     return false;
6573   }
6574 
6575   Node* src_start = array_element_address(src, src_offset, T_CHAR);
6576   Node* dst_start = array_element_address(dst, dst_offset, dst_elem);
6577   // 'src_start' points to src array + scaled offset
6578   // 'dst_start' points to dst array + scaled offset
6579 
6580   const TypeAryPtr* mtype = TypeAryPtr::BYTES;
6581   Node* enc = new EncodeISOArrayNode(control(), memory(mtype), src_start, dst_start, length, ascii);
6582   enc = _gvn.transform(enc);
6583   Node* res_mem = _gvn.transform(new SCMemProjNode(enc));
6584   set_memory(res_mem, mtype);
6585   set_result(enc);
6586   clear_upper_avx();
6587 
6588   return true;
6589 }
6590 
6591 //-------------inline_multiplyToLen-----------------------------------
6592 bool LibraryCallKit::inline_multiplyToLen() {
6593   assert(UseMultiplyToLenIntrinsic, "not implemented on this platform");
6594 
6595   address stubAddr = StubRoutines::multiplyToLen();
6596   if (stubAddr == nullptr) {
6597     return false; // Intrinsic's stub is not implemented on this platform
6598   }
6599   const char* stubName = "multiplyToLen";
6600 
6601   assert(callee()->signature()->size() == 5, "multiplyToLen has 5 parameters");
6602 
6603   // no receiver because it is a static method
6604   Node* x    = argument(0);
6605   Node* xlen = argument(1);
6606   Node* y    = argument(2);
6607   Node* ylen = argument(3);
6608   Node* z    = argument(4);
6609 
6610   x = must_be_not_null(x, true);
6611   y = must_be_not_null(y, true);
6612 
6613   const TypeAryPtr* x_type = x->Value(&_gvn)->isa_aryptr();
6614   const TypeAryPtr* y_type = y->Value(&_gvn)->isa_aryptr();
6615   if (x_type == nullptr || x_type->elem() == Type::BOTTOM ||
6616       y_type == nullptr || y_type->elem() == Type::BOTTOM) {
6617     // failed array check
6618     return false;
6619   }
6620 
6621   BasicType x_elem = x_type->elem()->array_element_basic_type();
6622   BasicType y_elem = y_type->elem()->array_element_basic_type();
6623   if (x_elem != T_INT || y_elem != T_INT) {
6624     return false;
6625   }
6626 
6627   Node* x_start = array_element_address(x, intcon(0), x_elem);
6628   Node* y_start = array_element_address(y, intcon(0), y_elem);
6629   // 'x_start' points to x array + scaled xlen
6630   // 'y_start' points to y array + scaled ylen
6631 
6632   Node* z_start = array_element_address(z, intcon(0), T_INT);
6633 
6634   Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
6635                                  OptoRuntime::multiplyToLen_Type(),
6636                                  stubAddr, stubName, TypePtr::BOTTOM,
6637                                  x_start, xlen, y_start, ylen, z_start);
6638 
6639   C->set_has_split_ifs(true); // Has chance for split-if optimization
6640   set_result(z);
6641   return true;
6642 }
6643 
6644 //-------------inline_squareToLen------------------------------------
6645 bool LibraryCallKit::inline_squareToLen() {
6646   assert(UseSquareToLenIntrinsic, "not implemented on this platform");
6647 
6648   address stubAddr = StubRoutines::squareToLen();
6649   if (stubAddr == nullptr) {
6650     return false; // Intrinsic's stub is not implemented on this platform
6651   }
6652   const char* stubName = "squareToLen";
6653 
6654   assert(callee()->signature()->size() == 4, "implSquareToLen has 4 parameters");
6655 
6656   Node* x    = argument(0);
6657   Node* len  = argument(1);
6658   Node* z    = argument(2);
6659   Node* zlen = argument(3);
6660 
6661   x = must_be_not_null(x, true);
6662   z = must_be_not_null(z, true);
6663 
6664   const TypeAryPtr* x_type = x->Value(&_gvn)->isa_aryptr();
6665   const TypeAryPtr* z_type = z->Value(&_gvn)->isa_aryptr();
6666   if (x_type == nullptr || x_type->elem() == Type::BOTTOM ||
6667       z_type == nullptr || z_type->elem() == Type::BOTTOM) {
6668     // failed array check
6669     return false;
6670   }
6671 
6672   BasicType x_elem = x_type->elem()->array_element_basic_type();
6673   BasicType z_elem = z_type->elem()->array_element_basic_type();
6674   if (x_elem != T_INT || z_elem != T_INT) {
6675     return false;
6676   }
6677 
6678 
6679   Node* x_start = array_element_address(x, intcon(0), x_elem);
6680   Node* z_start = array_element_address(z, intcon(0), z_elem);
6681 
6682   Node*  call = make_runtime_call(RC_LEAF|RC_NO_FP,
6683                                   OptoRuntime::squareToLen_Type(),
6684                                   stubAddr, stubName, TypePtr::BOTTOM,
6685                                   x_start, len, z_start, zlen);
6686 
6687   set_result(z);
6688   return true;
6689 }
6690 
6691 //-------------inline_mulAdd------------------------------------------
6692 bool LibraryCallKit::inline_mulAdd() {
6693   assert(UseMulAddIntrinsic, "not implemented on this platform");
6694 
6695   address stubAddr = StubRoutines::mulAdd();
6696   if (stubAddr == nullptr) {
6697     return false; // Intrinsic's stub is not implemented on this platform
6698   }
6699   const char* stubName = "mulAdd";
6700 
6701   assert(callee()->signature()->size() == 5, "mulAdd has 5 parameters");
6702 
6703   Node* out      = argument(0);
6704   Node* in       = argument(1);
6705   Node* offset   = argument(2);
6706   Node* len      = argument(3);
6707   Node* k        = argument(4);
6708 
6709   in = must_be_not_null(in, true);
6710   out = must_be_not_null(out, true);
6711 
6712   const TypeAryPtr* out_type = out->Value(&_gvn)->isa_aryptr();
6713   const TypeAryPtr* in_type = in->Value(&_gvn)->isa_aryptr();
6714   if (out_type == nullptr || out_type->elem() == Type::BOTTOM ||
6715        in_type == nullptr ||  in_type->elem() == Type::BOTTOM) {
6716     // failed array check
6717     return false;
6718   }
6719 
6720   BasicType out_elem = out_type->elem()->array_element_basic_type();
6721   BasicType in_elem = in_type->elem()->array_element_basic_type();
6722   if (out_elem != T_INT || in_elem != T_INT) {
6723     return false;
6724   }
6725 
6726   Node* outlen = load_array_length(out);
6727   Node* new_offset = _gvn.transform(new SubINode(outlen, offset));
6728   Node* out_start = array_element_address(out, intcon(0), out_elem);
6729   Node* in_start = array_element_address(in, intcon(0), in_elem);
6730 
6731   Node*  call = make_runtime_call(RC_LEAF|RC_NO_FP,
6732                                   OptoRuntime::mulAdd_Type(),
6733                                   stubAddr, stubName, TypePtr::BOTTOM,
6734                                   out_start,in_start, new_offset, len, k);
6735   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
6736   set_result(result);
6737   return true;
6738 }
6739 
6740 //-------------inline_montgomeryMultiply-----------------------------------
6741 bool LibraryCallKit::inline_montgomeryMultiply() {
6742   address stubAddr = StubRoutines::montgomeryMultiply();
6743   if (stubAddr == nullptr) {
6744     return false; // Intrinsic's stub is not implemented on this platform
6745   }
6746 
6747   assert(UseMontgomeryMultiplyIntrinsic, "not implemented on this platform");
6748   const char* stubName = "montgomery_multiply";
6749 
6750   assert(callee()->signature()->size() == 7, "montgomeryMultiply has 7 parameters");
6751 
6752   Node* a    = argument(0);
6753   Node* b    = argument(1);
6754   Node* n    = argument(2);
6755   Node* len  = argument(3);
6756   Node* inv  = argument(4);
6757   Node* m    = argument(6);
6758 
6759   const TypeAryPtr* a_type = a->Value(&_gvn)->isa_aryptr();
6760   const TypeAryPtr* b_type = b->Value(&_gvn)->isa_aryptr();
6761   const TypeAryPtr* n_type = n->Value(&_gvn)->isa_aryptr();
6762   const TypeAryPtr* m_type = m->Value(&_gvn)->isa_aryptr();
6763   if (a_type == nullptr || a_type->elem() == Type::BOTTOM ||
6764       b_type == nullptr || b_type->elem() == Type::BOTTOM ||
6765       n_type == nullptr || n_type->elem() == Type::BOTTOM ||
6766       m_type == nullptr || m_type->elem() == Type::BOTTOM) {
6767     // failed array check
6768     return false;
6769   }
6770 
6771   BasicType a_elem = a_type->elem()->array_element_basic_type();
6772   BasicType b_elem = b_type->elem()->array_element_basic_type();
6773   BasicType n_elem = n_type->elem()->array_element_basic_type();
6774   BasicType m_elem = m_type->elem()->array_element_basic_type();
6775   if (a_elem != T_INT || b_elem != T_INT || n_elem != T_INT || m_elem != T_INT) {
6776     return false;
6777   }
6778 
6779   // Make the call
6780   {
6781     Node* a_start = array_element_address(a, intcon(0), a_elem);
6782     Node* b_start = array_element_address(b, intcon(0), b_elem);
6783     Node* n_start = array_element_address(n, intcon(0), n_elem);
6784     Node* m_start = array_element_address(m, intcon(0), m_elem);
6785 
6786     Node* call = make_runtime_call(RC_LEAF,
6787                                    OptoRuntime::montgomeryMultiply_Type(),
6788                                    stubAddr, stubName, TypePtr::BOTTOM,
6789                                    a_start, b_start, n_start, len, inv, top(),
6790                                    m_start);
6791     set_result(m);
6792   }
6793 
6794   return true;
6795 }
6796 
6797 bool LibraryCallKit::inline_montgomerySquare() {
6798   address stubAddr = StubRoutines::montgomerySquare();
6799   if (stubAddr == nullptr) {
6800     return false; // Intrinsic's stub is not implemented on this platform
6801   }
6802 
6803   assert(UseMontgomerySquareIntrinsic, "not implemented on this platform");
6804   const char* stubName = "montgomery_square";
6805 
6806   assert(callee()->signature()->size() == 6, "montgomerySquare has 6 parameters");
6807 
6808   Node* a    = argument(0);
6809   Node* n    = argument(1);
6810   Node* len  = argument(2);
6811   Node* inv  = argument(3);
6812   Node* m    = argument(5);
6813 
6814   const TypeAryPtr* a_type = a->Value(&_gvn)->isa_aryptr();
6815   const TypeAryPtr* n_type = n->Value(&_gvn)->isa_aryptr();
6816   const TypeAryPtr* m_type = m->Value(&_gvn)->isa_aryptr();
6817   if (a_type == nullptr || a_type->elem() == Type::BOTTOM ||
6818       n_type == nullptr || n_type->elem() == Type::BOTTOM ||
6819       m_type == nullptr || m_type->elem() == Type::BOTTOM) {
6820     // failed array check
6821     return false;
6822   }
6823 
6824   BasicType a_elem = a_type->elem()->array_element_basic_type();
6825   BasicType n_elem = n_type->elem()->array_element_basic_type();
6826   BasicType m_elem = m_type->elem()->array_element_basic_type();
6827   if (a_elem != T_INT || n_elem != T_INT || m_elem != T_INT) {
6828     return false;
6829   }
6830 
6831   // Make the call
6832   {
6833     Node* a_start = array_element_address(a, intcon(0), a_elem);
6834     Node* n_start = array_element_address(n, intcon(0), n_elem);
6835     Node* m_start = array_element_address(m, intcon(0), m_elem);
6836 
6837     Node* call = make_runtime_call(RC_LEAF,
6838                                    OptoRuntime::montgomerySquare_Type(),
6839                                    stubAddr, stubName, TypePtr::BOTTOM,
6840                                    a_start, n_start, len, inv, top(),
6841                                    m_start);
6842     set_result(m);
6843   }
6844 
6845   return true;
6846 }
6847 
6848 bool LibraryCallKit::inline_bigIntegerShift(bool isRightShift) {
6849   address stubAddr = nullptr;
6850   const char* stubName = nullptr;
6851 
6852   stubAddr = isRightShift? StubRoutines::bigIntegerRightShift(): StubRoutines::bigIntegerLeftShift();
6853   if (stubAddr == nullptr) {
6854     return false; // Intrinsic's stub is not implemented on this platform
6855   }
6856 
6857   stubName = isRightShift? "bigIntegerRightShiftWorker" : "bigIntegerLeftShiftWorker";
6858 
6859   assert(callee()->signature()->size() == 5, "expected 5 arguments");
6860 
6861   Node* newArr = argument(0);
6862   Node* oldArr = argument(1);
6863   Node* newIdx = argument(2);
6864   Node* shiftCount = argument(3);
6865   Node* numIter = argument(4);
6866 
6867   const TypeAryPtr* newArr_type = newArr->Value(&_gvn)->isa_aryptr();
6868   const TypeAryPtr* oldArr_type = oldArr->Value(&_gvn)->isa_aryptr();
6869   if (newArr_type == nullptr || newArr_type->elem() == Type::BOTTOM ||
6870       oldArr_type == nullptr || oldArr_type->elem() == Type::BOTTOM) {
6871     return false;
6872   }
6873 
6874   BasicType newArr_elem = newArr_type->elem()->array_element_basic_type();
6875   BasicType oldArr_elem = oldArr_type->elem()->array_element_basic_type();
6876   if (newArr_elem != T_INT || oldArr_elem != T_INT) {
6877     return false;
6878   }
6879 
6880   // Make the call
6881   {
6882     Node* newArr_start = array_element_address(newArr, intcon(0), newArr_elem);
6883     Node* oldArr_start = array_element_address(oldArr, intcon(0), oldArr_elem);
6884 
6885     Node* call = make_runtime_call(RC_LEAF,
6886                                    OptoRuntime::bigIntegerShift_Type(),
6887                                    stubAddr,
6888                                    stubName,
6889                                    TypePtr::BOTTOM,
6890                                    newArr_start,
6891                                    oldArr_start,
6892                                    newIdx,
6893                                    shiftCount,
6894                                    numIter);
6895   }
6896 
6897   return true;
6898 }
6899 
6900 //-------------inline_vectorizedMismatch------------------------------
6901 bool LibraryCallKit::inline_vectorizedMismatch() {
6902   assert(UseVectorizedMismatchIntrinsic, "not implemented on this platform");
6903 
6904   assert(callee()->signature()->size() == 8, "vectorizedMismatch has 6 parameters");
6905   Node* obja    = argument(0); // Object
6906   Node* aoffset = argument(1); // long
6907   Node* objb    = argument(3); // Object
6908   Node* boffset = argument(4); // long
6909   Node* length  = argument(6); // int
6910   Node* scale   = argument(7); // int
6911 
6912   const TypeAryPtr* obja_t = _gvn.type(obja)->isa_aryptr();
6913   const TypeAryPtr* objb_t = _gvn.type(objb)->isa_aryptr();
6914   if (obja_t == nullptr || obja_t->elem() == Type::BOTTOM ||
6915       objb_t == nullptr || objb_t->elem() == Type::BOTTOM ||
6916       scale == top()) {
6917     return false; // failed input validation
6918   }
6919 
6920   Node* obja_adr = make_unsafe_address(obja, aoffset);
6921   Node* objb_adr = make_unsafe_address(objb, boffset);
6922 
6923   // Partial inlining handling for inputs smaller than ArrayOperationPartialInlineSize bytes in size.
6924   //
6925   //    inline_limit = ArrayOperationPartialInlineSize / element_size;
6926   //    if (length <= inline_limit) {
6927   //      inline_path:
6928   //        vmask   = VectorMaskGen length
6929   //        vload1  = LoadVectorMasked obja, vmask
6930   //        vload2  = LoadVectorMasked objb, vmask
6931   //        result1 = VectorCmpMasked vload1, vload2, vmask
6932   //    } else {
6933   //      call_stub_path:
6934   //        result2 = call vectorizedMismatch_stub(obja, objb, length, scale)
6935   //    }
6936   //    exit_block:
6937   //      return Phi(result1, result2);
6938   //
6939   enum { inline_path = 1,  // input is small enough to process it all at once
6940          stub_path   = 2,  // input is too large; call into the VM
6941          PATH_LIMIT  = 3
6942   };
6943 
6944   Node* exit_block = new RegionNode(PATH_LIMIT);
6945   Node* result_phi = new PhiNode(exit_block, TypeInt::INT);
6946   Node* memory_phi = new PhiNode(exit_block, Type::MEMORY, TypePtr::BOTTOM);
6947 
6948   Node* call_stub_path = control();
6949 
6950   BasicType elem_bt = T_ILLEGAL;
6951 
6952   const TypeInt* scale_t = _gvn.type(scale)->is_int();
6953   if (scale_t->is_con()) {
6954     switch (scale_t->get_con()) {
6955       case 0: elem_bt = T_BYTE;  break;
6956       case 1: elem_bt = T_SHORT; break;
6957       case 2: elem_bt = T_INT;   break;
6958       case 3: elem_bt = T_LONG;  break;
6959 
6960       default: elem_bt = T_ILLEGAL; break; // not supported
6961     }
6962   }
6963 
6964   int inline_limit = 0;
6965   bool do_partial_inline = false;
6966 
6967   if (elem_bt != T_ILLEGAL && ArrayOperationPartialInlineSize > 0) {
6968     inline_limit = ArrayOperationPartialInlineSize / type2aelembytes(elem_bt);
6969     do_partial_inline = inline_limit >= 16;
6970   }
6971 
6972   if (do_partial_inline) {
6973     assert(elem_bt != T_ILLEGAL, "sanity");
6974 
6975     if (Matcher::match_rule_supported_vector(Op_VectorMaskGen,    inline_limit, elem_bt) &&
6976         Matcher::match_rule_supported_vector(Op_LoadVectorMasked, inline_limit, elem_bt) &&
6977         Matcher::match_rule_supported_vector(Op_VectorCmpMasked,  inline_limit, elem_bt)) {
6978 
6979       const TypeVect* vt = TypeVect::make(elem_bt, inline_limit);
6980       Node* cmp_length = _gvn.transform(new CmpINode(length, intcon(inline_limit)));
6981       Node* bol_gt     = _gvn.transform(new BoolNode(cmp_length, BoolTest::gt));
6982 
6983       call_stub_path = generate_guard(bol_gt, nullptr, PROB_MIN);
6984 
6985       if (!stopped()) {
6986         Node* casted_length = _gvn.transform(new CastIINode(control(), length, TypeInt::make(0, inline_limit, Type::WidenMin)));
6987 
6988         const TypePtr* obja_adr_t = _gvn.type(obja_adr)->isa_ptr();
6989         const TypePtr* objb_adr_t = _gvn.type(objb_adr)->isa_ptr();
6990         Node* obja_adr_mem = memory(C->get_alias_index(obja_adr_t));
6991         Node* objb_adr_mem = memory(C->get_alias_index(objb_adr_t));
6992 
6993         Node* vmask      = _gvn.transform(VectorMaskGenNode::make(ConvI2X(casted_length), elem_bt));
6994         Node* vload_obja = _gvn.transform(new LoadVectorMaskedNode(control(), obja_adr_mem, obja_adr, obja_adr_t, vt, vmask));
6995         Node* vload_objb = _gvn.transform(new LoadVectorMaskedNode(control(), objb_adr_mem, objb_adr, objb_adr_t, vt, vmask));
6996         Node* result     = _gvn.transform(new VectorCmpMaskedNode(vload_obja, vload_objb, vmask, TypeInt::INT));
6997 
6998         exit_block->init_req(inline_path, control());
6999         memory_phi->init_req(inline_path, map()->memory());
7000         result_phi->init_req(inline_path, result);
7001 
7002         C->set_max_vector_size(MAX2((uint)ArrayOperationPartialInlineSize, C->max_vector_size()));
7003         clear_upper_avx();
7004       }
7005     }
7006   }
7007 
7008   if (call_stub_path != nullptr) {
7009     set_control(call_stub_path);
7010 
7011     Node* call = make_runtime_call(RC_LEAF,
7012                                    OptoRuntime::vectorizedMismatch_Type(),
7013                                    StubRoutines::vectorizedMismatch(), "vectorizedMismatch", TypePtr::BOTTOM,
7014                                    obja_adr, objb_adr, length, scale);
7015 
7016     exit_block->init_req(stub_path, control());
7017     memory_phi->init_req(stub_path, map()->memory());
7018     result_phi->init_req(stub_path, _gvn.transform(new ProjNode(call, TypeFunc::Parms)));
7019   }
7020 
7021   exit_block = _gvn.transform(exit_block);
7022   memory_phi = _gvn.transform(memory_phi);
7023   result_phi = _gvn.transform(result_phi);
7024 
7025   set_control(exit_block);
7026   set_all_memory(memory_phi);
7027   set_result(result_phi);
7028 
7029   return true;
7030 }
7031 
7032 //------------------------------inline_vectorizedHashcode----------------------------
7033 bool LibraryCallKit::inline_vectorizedHashCode() {
7034   assert(UseVectorizedHashCodeIntrinsic, "not implemented on this platform");
7035 
7036   assert(callee()->signature()->size() == 5, "vectorizedHashCode has 5 parameters");
7037   Node* array          = argument(0);
7038   Node* offset         = argument(1);
7039   Node* length         = argument(2);
7040   Node* initialValue   = argument(3);
7041   Node* basic_type     = argument(4);
7042 
7043   if (basic_type == top()) {
7044     return false; // failed input validation
7045   }
7046 
7047   const TypeInt* basic_type_t = _gvn.type(basic_type)->is_int();
7048   if (!basic_type_t->is_con()) {
7049     return false; // Only intrinsify if mode argument is constant
7050   }
7051 
7052   array = must_be_not_null(array, true);
7053 
7054   BasicType bt = (BasicType)basic_type_t->get_con();
7055 
7056   // Resolve address of first element
7057   Node* array_start = array_element_address(array, offset, bt);
7058 
7059   set_result(_gvn.transform(new VectorizedHashCodeNode(control(), memory(TypeAryPtr::get_array_body_type(bt)),
7060     array_start, length, initialValue, basic_type)));
7061   clear_upper_avx();
7062 
7063   return true;
7064 }
7065 
7066 /**
7067  * Calculate CRC32 for byte.
7068  * int java.util.zip.CRC32.update(int crc, int b)
7069  */
7070 bool LibraryCallKit::inline_updateCRC32() {
7071   assert(UseCRC32Intrinsics, "need AVX and CLMUL instructions support");
7072   assert(callee()->signature()->size() == 2, "update has 2 parameters");
7073   // no receiver since it is static method
7074   Node* crc  = argument(0); // type: int
7075   Node* b    = argument(1); // type: int
7076 
7077   /*
7078    *    int c = ~ crc;
7079    *    b = timesXtoThe32[(b ^ c) & 0xFF];
7080    *    b = b ^ (c >>> 8);
7081    *    crc = ~b;
7082    */
7083 
7084   Node* M1 = intcon(-1);
7085   crc = _gvn.transform(new XorINode(crc, M1));
7086   Node* result = _gvn.transform(new XorINode(crc, b));
7087   result = _gvn.transform(new AndINode(result, intcon(0xFF)));
7088 
7089   Node* base = makecon(TypeRawPtr::make(StubRoutines::crc_table_addr()));
7090   Node* offset = _gvn.transform(new LShiftINode(result, intcon(0x2)));
7091   Node* adr = basic_plus_adr(top(), base, ConvI2X(offset));
7092   result = make_load(control(), adr, TypeInt::INT, T_INT, MemNode::unordered);
7093 
7094   crc = _gvn.transform(new URShiftINode(crc, intcon(8)));
7095   result = _gvn.transform(new XorINode(crc, result));
7096   result = _gvn.transform(new XorINode(result, M1));
7097   set_result(result);
7098   return true;
7099 }
7100 
7101 /**
7102  * Calculate CRC32 for byte[] array.
7103  * int java.util.zip.CRC32.updateBytes(int crc, byte[] buf, int off, int len)
7104  */
7105 bool LibraryCallKit::inline_updateBytesCRC32() {
7106   assert(UseCRC32Intrinsics, "need AVX and CLMUL instructions support");
7107   assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
7108   // no receiver since it is static method
7109   Node* crc     = argument(0); // type: int
7110   Node* src     = argument(1); // type: oop
7111   Node* offset  = argument(2); // type: int
7112   Node* length  = argument(3); // type: int
7113 
7114   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7115   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
7116     // failed array check
7117     return false;
7118   }
7119 
7120   // Figure out the size and type of the elements we will be copying.
7121   BasicType src_elem = src_type->elem()->array_element_basic_type();
7122   if (src_elem != T_BYTE) {
7123     return false;
7124   }
7125 
7126   // 'src_start' points to src array + scaled offset
7127   src = must_be_not_null(src, true);
7128   Node* src_start = array_element_address(src, offset, src_elem);
7129 
7130   // We assume that range check is done by caller.
7131   // TODO: generate range check (offset+length < src.length) in debug VM.
7132 
7133   // Call the stub.
7134   address stubAddr = StubRoutines::updateBytesCRC32();
7135   const char *stubName = "updateBytesCRC32";
7136 
7137   Node* call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::updateBytesCRC32_Type(),
7138                                  stubAddr, stubName, TypePtr::BOTTOM,
7139                                  crc, src_start, length);
7140   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7141   set_result(result);
7142   return true;
7143 }
7144 
7145 /**
7146  * Calculate CRC32 for ByteBuffer.
7147  * int java.util.zip.CRC32.updateByteBuffer(int crc, long buf, int off, int len)
7148  */
7149 bool LibraryCallKit::inline_updateByteBufferCRC32() {
7150   assert(UseCRC32Intrinsics, "need AVX and CLMUL instructions support");
7151   assert(callee()->signature()->size() == 5, "updateByteBuffer has 4 parameters and one is long");
7152   // no receiver since it is static method
7153   Node* crc     = argument(0); // type: int
7154   Node* src     = argument(1); // type: long
7155   Node* offset  = argument(3); // type: int
7156   Node* length  = argument(4); // type: int
7157 
7158   src = ConvL2X(src);  // adjust Java long to machine word
7159   Node* base = _gvn.transform(new CastX2PNode(src));
7160   offset = ConvI2X(offset);
7161 
7162   // 'src_start' points to src array + scaled offset
7163   Node* src_start = basic_plus_adr(top(), base, offset);
7164 
7165   // Call the stub.
7166   address stubAddr = StubRoutines::updateBytesCRC32();
7167   const char *stubName = "updateBytesCRC32";
7168 
7169   Node* call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::updateBytesCRC32_Type(),
7170                                  stubAddr, stubName, TypePtr::BOTTOM,
7171                                  crc, src_start, length);
7172   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7173   set_result(result);
7174   return true;
7175 }
7176 
7177 //------------------------------get_table_from_crc32c_class-----------------------
7178 Node * LibraryCallKit::get_table_from_crc32c_class(ciInstanceKlass *crc32c_class) {
7179   Node* table = load_field_from_object(nullptr, "byteTable", "[I", /*decorators*/ IN_HEAP, /*is_static*/ true, crc32c_class);
7180   assert (table != nullptr, "wrong version of java.util.zip.CRC32C");
7181 
7182   return table;
7183 }
7184 
7185 //------------------------------inline_updateBytesCRC32C-----------------------
7186 //
7187 // Calculate CRC32C for byte[] array.
7188 // int java.util.zip.CRC32C.updateBytes(int crc, byte[] buf, int off, int end)
7189 //
7190 bool LibraryCallKit::inline_updateBytesCRC32C() {
7191   assert(UseCRC32CIntrinsics, "need CRC32C instruction support");
7192   assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
7193   assert(callee()->holder()->is_loaded(), "CRC32C class must be loaded");
7194   // no receiver since it is a static method
7195   Node* crc     = argument(0); // type: int
7196   Node* src     = argument(1); // type: oop
7197   Node* offset  = argument(2); // type: int
7198   Node* end     = argument(3); // type: int
7199 
7200   Node* length = _gvn.transform(new SubINode(end, offset));
7201 
7202   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7203   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
7204     // failed array check
7205     return false;
7206   }
7207 
7208   // Figure out the size and type of the elements we will be copying.
7209   BasicType src_elem = src_type->elem()->array_element_basic_type();
7210   if (src_elem != T_BYTE) {
7211     return false;
7212   }
7213 
7214   // 'src_start' points to src array + scaled offset
7215   src = must_be_not_null(src, true);
7216   Node* src_start = array_element_address(src, offset, src_elem);
7217 
7218   // static final int[] byteTable in class CRC32C
7219   Node* table = get_table_from_crc32c_class(callee()->holder());
7220   table = must_be_not_null(table, true);
7221   Node* table_start = array_element_address(table, intcon(0), T_INT);
7222 
7223   // We assume that range check is done by caller.
7224   // TODO: generate range check (offset+length < src.length) in debug VM.
7225 
7226   // Call the stub.
7227   address stubAddr = StubRoutines::updateBytesCRC32C();
7228   const char *stubName = "updateBytesCRC32C";
7229 
7230   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesCRC32C_Type(),
7231                                  stubAddr, stubName, TypePtr::BOTTOM,
7232                                  crc, src_start, length, table_start);
7233   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7234   set_result(result);
7235   return true;
7236 }
7237 
7238 //------------------------------inline_updateDirectByteBufferCRC32C-----------------------
7239 //
7240 // Calculate CRC32C for DirectByteBuffer.
7241 // int java.util.zip.CRC32C.updateDirectByteBuffer(int crc, long buf, int off, int end)
7242 //
7243 bool LibraryCallKit::inline_updateDirectByteBufferCRC32C() {
7244   assert(UseCRC32CIntrinsics, "need CRC32C instruction support");
7245   assert(callee()->signature()->size() == 5, "updateDirectByteBuffer has 4 parameters and one is long");
7246   assert(callee()->holder()->is_loaded(), "CRC32C class must be loaded");
7247   // no receiver since it is a static method
7248   Node* crc     = argument(0); // type: int
7249   Node* src     = argument(1); // type: long
7250   Node* offset  = argument(3); // type: int
7251   Node* end     = argument(4); // type: int
7252 
7253   Node* length = _gvn.transform(new SubINode(end, offset));
7254 
7255   src = ConvL2X(src);  // adjust Java long to machine word
7256   Node* base = _gvn.transform(new CastX2PNode(src));
7257   offset = ConvI2X(offset);
7258 
7259   // 'src_start' points to src array + scaled offset
7260   Node* src_start = basic_plus_adr(top(), base, offset);
7261 
7262   // static final int[] byteTable in class CRC32C
7263   Node* table = get_table_from_crc32c_class(callee()->holder());
7264   table = must_be_not_null(table, true);
7265   Node* table_start = array_element_address(table, intcon(0), T_INT);
7266 
7267   // Call the stub.
7268   address stubAddr = StubRoutines::updateBytesCRC32C();
7269   const char *stubName = "updateBytesCRC32C";
7270 
7271   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesCRC32C_Type(),
7272                                  stubAddr, stubName, TypePtr::BOTTOM,
7273                                  crc, src_start, length, table_start);
7274   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7275   set_result(result);
7276   return true;
7277 }
7278 
7279 //------------------------------inline_updateBytesAdler32----------------------
7280 //
7281 // Calculate Adler32 checksum for byte[] array.
7282 // int java.util.zip.Adler32.updateBytes(int crc, byte[] buf, int off, int len)
7283 //
7284 bool LibraryCallKit::inline_updateBytesAdler32() {
7285   assert(UseAdler32Intrinsics, "Adler32 Intrinsic support need"); // check if we actually need to check this flag or check a different one
7286   assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
7287   assert(callee()->holder()->is_loaded(), "Adler32 class must be loaded");
7288   // no receiver since it is static method
7289   Node* crc     = argument(0); // type: int
7290   Node* src     = argument(1); // type: oop
7291   Node* offset  = argument(2); // type: int
7292   Node* length  = argument(3); // type: int
7293 
7294   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7295   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
7296     // failed array check
7297     return false;
7298   }
7299 
7300   // Figure out the size and type of the elements we will be copying.
7301   BasicType src_elem = src_type->elem()->array_element_basic_type();
7302   if (src_elem != T_BYTE) {
7303     return false;
7304   }
7305 
7306   // 'src_start' points to src array + scaled offset
7307   Node* src_start = array_element_address(src, offset, src_elem);
7308 
7309   // We assume that range check is done by caller.
7310   // TODO: generate range check (offset+length < src.length) in debug VM.
7311 
7312   // Call the stub.
7313   address stubAddr = StubRoutines::updateBytesAdler32();
7314   const char *stubName = "updateBytesAdler32";
7315 
7316   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesAdler32_Type(),
7317                                  stubAddr, stubName, TypePtr::BOTTOM,
7318                                  crc, src_start, length);
7319   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7320   set_result(result);
7321   return true;
7322 }
7323 
7324 //------------------------------inline_updateByteBufferAdler32---------------
7325 //
7326 // Calculate Adler32 checksum for DirectByteBuffer.
7327 // int java.util.zip.Adler32.updateByteBuffer(int crc, long buf, int off, int len)
7328 //
7329 bool LibraryCallKit::inline_updateByteBufferAdler32() {
7330   assert(UseAdler32Intrinsics, "Adler32 Intrinsic support need"); // check if we actually need to check this flag or check a different one
7331   assert(callee()->signature()->size() == 5, "updateByteBuffer has 4 parameters and one is long");
7332   assert(callee()->holder()->is_loaded(), "Adler32 class must be loaded");
7333   // no receiver since it is static method
7334   Node* crc     = argument(0); // type: int
7335   Node* src     = argument(1); // type: long
7336   Node* offset  = argument(3); // type: int
7337   Node* length  = argument(4); // type: int
7338 
7339   src = ConvL2X(src);  // adjust Java long to machine word
7340   Node* base = _gvn.transform(new CastX2PNode(src));
7341   offset = ConvI2X(offset);
7342 
7343   // 'src_start' points to src array + scaled offset
7344   Node* src_start = basic_plus_adr(top(), base, offset);
7345 
7346   // Call the stub.
7347   address stubAddr = StubRoutines::updateBytesAdler32();
7348   const char *stubName = "updateBytesAdler32";
7349 
7350   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesAdler32_Type(),
7351                                  stubAddr, stubName, TypePtr::BOTTOM,
7352                                  crc, src_start, length);
7353 
7354   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7355   set_result(result);
7356   return true;
7357 }
7358 
7359 //----------------------------inline_reference_get----------------------------
7360 // public T java.lang.ref.Reference.get();
7361 bool LibraryCallKit::inline_reference_get() {
7362   const int referent_offset = java_lang_ref_Reference::referent_offset();
7363 
7364   // Get the argument:
7365   Node* reference_obj = null_check_receiver();
7366   if (stopped()) return true;
7367 
7368   DecoratorSet decorators = IN_HEAP | ON_WEAK_OOP_REF;
7369   Node* result = load_field_from_object(reference_obj, "referent", "Ljava/lang/Object;",
7370                                         decorators, /*is_static*/ false, nullptr);
7371   if (result == nullptr) return false;
7372 
7373   // Add memory barrier to prevent commoning reads from this field
7374   // across safepoint since GC can change its value.
7375   insert_mem_bar(Op_MemBarCPUOrder);
7376 
7377   set_result(result);
7378   return true;
7379 }
7380 
7381 //----------------------------inline_reference_refersTo0----------------------------
7382 // bool java.lang.ref.Reference.refersTo0();
7383 // bool java.lang.ref.PhantomReference.refersTo0();
7384 bool LibraryCallKit::inline_reference_refersTo0(bool is_phantom) {
7385   // Get arguments:
7386   Node* reference_obj = null_check_receiver();
7387   Node* other_obj = argument(1);
7388   if (stopped()) return true;
7389 
7390   DecoratorSet decorators = IN_HEAP | AS_NO_KEEPALIVE;
7391   decorators |= (is_phantom ? ON_PHANTOM_OOP_REF : ON_WEAK_OOP_REF);
7392   Node* referent = load_field_from_object(reference_obj, "referent", "Ljava/lang/Object;",
7393                                           decorators, /*is_static*/ false, nullptr);
7394   if (referent == nullptr) return false;
7395 
7396   // Add memory barrier to prevent commoning reads from this field
7397   // across safepoint since GC can change its value.
7398   insert_mem_bar(Op_MemBarCPUOrder);
7399 
7400   Node* cmp = _gvn.transform(new CmpPNode(referent, other_obj));
7401   Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
7402   IfNode* if_node = create_and_map_if(control(), bol, PROB_FAIR, COUNT_UNKNOWN);
7403 
7404   RegionNode* region = new RegionNode(3);
7405   PhiNode* phi = new PhiNode(region, TypeInt::BOOL);
7406 
7407   Node* if_true = _gvn.transform(new IfTrueNode(if_node));
7408   region->init_req(1, if_true);
7409   phi->init_req(1, intcon(1));
7410 
7411   Node* if_false = _gvn.transform(new IfFalseNode(if_node));
7412   region->init_req(2, if_false);
7413   phi->init_req(2, intcon(0));
7414 
7415   set_control(_gvn.transform(region));
7416   record_for_igvn(region);
7417   set_result(_gvn.transform(phi));
7418   return true;
7419 }
7420 
7421 //----------------------------inline_reference_clear0----------------------------
7422 // void java.lang.ref.Reference.clear0();
7423 // void java.lang.ref.PhantomReference.clear0();
7424 bool LibraryCallKit::inline_reference_clear0(bool is_phantom) {
7425   // This matches the implementation in JVM_ReferenceClear, see the comments there.
7426 
7427   // Get arguments
7428   Node* reference_obj = null_check_receiver();
7429   if (stopped()) return true;
7430 
7431   // Common access parameters
7432   DecoratorSet decorators = IN_HEAP | AS_NO_KEEPALIVE;
7433   decorators |= (is_phantom ? ON_PHANTOM_OOP_REF : ON_WEAK_OOP_REF);
7434   Node* referent_field_addr = basic_plus_adr(reference_obj, java_lang_ref_Reference::referent_offset());
7435   const TypePtr* referent_field_addr_type = _gvn.type(referent_field_addr)->isa_ptr();
7436   const Type* val_type = TypeOopPtr::make_from_klass(env()->Object_klass());
7437 
7438   Node* referent = access_load_at(reference_obj,
7439                                   referent_field_addr,
7440                                   referent_field_addr_type,
7441                                   val_type,
7442                                   T_OBJECT,
7443                                   decorators);
7444 
7445   IdealKit ideal(this);
7446 #define __ ideal.
7447   __ if_then(referent, BoolTest::ne, null());
7448     sync_kit(ideal);
7449     access_store_at(reference_obj,
7450                     referent_field_addr,
7451                     referent_field_addr_type,
7452                     null(),
7453                     val_type,
7454                     T_OBJECT,
7455                     decorators);
7456     __ sync_kit(this);
7457   __ end_if();
7458   final_sync(ideal);
7459 #undef __
7460 
7461   return true;
7462 }
7463 
7464 Node* LibraryCallKit::load_field_from_object(Node* fromObj, const char* fieldName, const char* fieldTypeString,
7465                                              DecoratorSet decorators, bool is_static,
7466                                              ciInstanceKlass* fromKls) {
7467   if (fromKls == nullptr) {
7468     const TypeInstPtr* tinst = _gvn.type(fromObj)->isa_instptr();
7469     assert(tinst != nullptr, "obj is null");
7470     assert(tinst->is_loaded(), "obj is not loaded");
7471     fromKls = tinst->instance_klass();
7472   } else {
7473     assert(is_static, "only for static field access");
7474   }
7475   ciField* field = fromKls->get_field_by_name(ciSymbol::make(fieldName),
7476                                               ciSymbol::make(fieldTypeString),
7477                                               is_static);
7478 
7479   assert(field != nullptr, "undefined field %s %s %s", fieldTypeString, fromKls->name()->as_utf8(), fieldName);
7480   if (field == nullptr) return (Node *) nullptr;
7481 
7482   if (is_static) {
7483     const TypeInstPtr* tip = TypeInstPtr::make(fromKls->java_mirror());
7484     fromObj = makecon(tip);
7485   }
7486 
7487   // Next code  copied from Parse::do_get_xxx():
7488 
7489   // Compute address and memory type.
7490   int offset  = field->offset_in_bytes();
7491   bool is_vol = field->is_volatile();
7492   ciType* field_klass = field->type();
7493   assert(field_klass->is_loaded(), "should be loaded");
7494   const TypePtr* adr_type = C->alias_type(field)->adr_type();
7495   Node *adr = basic_plus_adr(fromObj, fromObj, offset);
7496   assert(C->get_alias_index(adr_type) == C->get_alias_index(_gvn.type(adr)->isa_ptr()),
7497     "slice of address and input slice don't match");
7498   BasicType bt = field->layout_type();
7499 
7500   // Build the resultant type of the load
7501   const Type *type;
7502   if (bt == T_OBJECT) {
7503     type = TypeOopPtr::make_from_klass(field_klass->as_klass());
7504   } else {
7505     type = Type::get_const_basic_type(bt);
7506   }
7507 
7508   if (is_vol) {
7509     decorators |= MO_SEQ_CST;
7510   }
7511 
7512   return access_load_at(fromObj, adr, adr_type, type, bt, decorators);
7513 }
7514 
7515 Node * LibraryCallKit::field_address_from_object(Node * fromObj, const char * fieldName, const char * fieldTypeString,
7516                                                  bool is_exact /* true */, bool is_static /* false */,
7517                                                  ciInstanceKlass * fromKls /* nullptr */) {
7518   if (fromKls == nullptr) {
7519     const TypeInstPtr* tinst = _gvn.type(fromObj)->isa_instptr();
7520     assert(tinst != nullptr, "obj is null");
7521     assert(tinst->is_loaded(), "obj is not loaded");
7522     assert(!is_exact || tinst->klass_is_exact(), "klass not exact");
7523     fromKls = tinst->instance_klass();
7524   }
7525   else {
7526     assert(is_static, "only for static field access");
7527   }
7528   ciField* field = fromKls->get_field_by_name(ciSymbol::make(fieldName),
7529     ciSymbol::make(fieldTypeString),
7530     is_static);
7531 
7532   assert(field != nullptr, "undefined field");
7533   assert(!field->is_volatile(), "not defined for volatile fields");
7534 
7535   if (is_static) {
7536     const TypeInstPtr* tip = TypeInstPtr::make(fromKls->java_mirror());
7537     fromObj = makecon(tip);
7538   }
7539 
7540   // Next code  copied from Parse::do_get_xxx():
7541 
7542   // Compute address and memory type.
7543   int offset = field->offset_in_bytes();
7544   Node *adr = basic_plus_adr(fromObj, fromObj, offset);
7545 
7546   return adr;
7547 }
7548 
7549 //------------------------------inline_aescrypt_Block-----------------------
7550 bool LibraryCallKit::inline_aescrypt_Block(vmIntrinsics::ID id) {
7551   address stubAddr = nullptr;
7552   const char *stubName;
7553   assert(UseAES, "need AES instruction support");
7554 
7555   switch(id) {
7556   case vmIntrinsics::_aescrypt_encryptBlock:
7557     stubAddr = StubRoutines::aescrypt_encryptBlock();
7558     stubName = "aescrypt_encryptBlock";
7559     break;
7560   case vmIntrinsics::_aescrypt_decryptBlock:
7561     stubAddr = StubRoutines::aescrypt_decryptBlock();
7562     stubName = "aescrypt_decryptBlock";
7563     break;
7564   default:
7565     break;
7566   }
7567   if (stubAddr == nullptr) return false;
7568 
7569   Node* aescrypt_object = argument(0);
7570   Node* src             = argument(1);
7571   Node* src_offset      = argument(2);
7572   Node* dest            = argument(3);
7573   Node* dest_offset     = argument(4);
7574 
7575   src = must_be_not_null(src, true);
7576   dest = must_be_not_null(dest, true);
7577 
7578   // (1) src and dest are arrays.
7579   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7580   const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
7581   assert( src_type != nullptr &&  src_type->elem() != Type::BOTTOM &&
7582          dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
7583 
7584   // for the quick and dirty code we will skip all the checks.
7585   // we are just trying to get the call to be generated.
7586   Node* src_start  = src;
7587   Node* dest_start = dest;
7588   if (src_offset != nullptr || dest_offset != nullptr) {
7589     assert(src_offset != nullptr && dest_offset != nullptr, "");
7590     src_start  = array_element_address(src,  src_offset,  T_BYTE);
7591     dest_start = array_element_address(dest, dest_offset, T_BYTE);
7592   }
7593 
7594   // now need to get the start of its expanded key array
7595   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
7596   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object);
7597   if (k_start == nullptr) return false;
7598 
7599   // Call the stub.
7600   make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::aescrypt_block_Type(),
7601                     stubAddr, stubName, TypePtr::BOTTOM,
7602                     src_start, dest_start, k_start);
7603 
7604   return true;
7605 }
7606 
7607 //------------------------------inline_cipherBlockChaining_AESCrypt-----------------------
7608 bool LibraryCallKit::inline_cipherBlockChaining_AESCrypt(vmIntrinsics::ID id) {
7609   address stubAddr = nullptr;
7610   const char *stubName = nullptr;
7611 
7612   assert(UseAES, "need AES instruction support");
7613 
7614   switch(id) {
7615   case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
7616     stubAddr = StubRoutines::cipherBlockChaining_encryptAESCrypt();
7617     stubName = "cipherBlockChaining_encryptAESCrypt";
7618     break;
7619   case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
7620     stubAddr = StubRoutines::cipherBlockChaining_decryptAESCrypt();
7621     stubName = "cipherBlockChaining_decryptAESCrypt";
7622     break;
7623   default:
7624     break;
7625   }
7626   if (stubAddr == nullptr) return false;
7627 
7628   Node* cipherBlockChaining_object = argument(0);
7629   Node* src                        = argument(1);
7630   Node* src_offset                 = argument(2);
7631   Node* len                        = argument(3);
7632   Node* dest                       = argument(4);
7633   Node* dest_offset                = argument(5);
7634 
7635   src = must_be_not_null(src, false);
7636   dest = must_be_not_null(dest, false);
7637 
7638   // (1) src and dest are arrays.
7639   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7640   const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
7641   assert( src_type != nullptr &&  src_type->elem() != Type::BOTTOM &&
7642          dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
7643 
7644   // checks are the responsibility of the caller
7645   Node* src_start  = src;
7646   Node* dest_start = dest;
7647   if (src_offset != nullptr || dest_offset != nullptr) {
7648     assert(src_offset != nullptr && dest_offset != nullptr, "");
7649     src_start  = array_element_address(src,  src_offset,  T_BYTE);
7650     dest_start = array_element_address(dest, dest_offset, T_BYTE);
7651   }
7652 
7653   // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
7654   // (because of the predicated logic executed earlier).
7655   // so we cast it here safely.
7656   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
7657 
7658   Node* embeddedCipherObj = load_field_from_object(cipherBlockChaining_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
7659   if (embeddedCipherObj == nullptr) return false;
7660 
7661   // cast it to what we know it will be at runtime
7662   const TypeInstPtr* tinst = _gvn.type(cipherBlockChaining_object)->isa_instptr();
7663   assert(tinst != nullptr, "CBC obj is null");
7664   assert(tinst->is_loaded(), "CBC obj is not loaded");
7665   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AESCrypt"));
7666   assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
7667 
7668   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
7669   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
7670   const TypeOopPtr* xtype = aklass->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
7671   Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
7672   aescrypt_object = _gvn.transform(aescrypt_object);
7673 
7674   // we need to get the start of the aescrypt_object's expanded key array
7675   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object);
7676   if (k_start == nullptr) return false;
7677 
7678   // similarly, get the start address of the r vector
7679   Node* objRvec = load_field_from_object(cipherBlockChaining_object, "r", "[B");
7680   if (objRvec == nullptr) return false;
7681   Node* r_start = array_element_address(objRvec, intcon(0), T_BYTE);
7682 
7683   // Call the stub, passing src_start, dest_start, k_start, r_start and src_len
7684   Node* cbcCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
7685                                      OptoRuntime::cipherBlockChaining_aescrypt_Type(),
7686                                      stubAddr, stubName, TypePtr::BOTTOM,
7687                                      src_start, dest_start, k_start, r_start, len);
7688 
7689   // return cipher length (int)
7690   Node* retvalue = _gvn.transform(new ProjNode(cbcCrypt, TypeFunc::Parms));
7691   set_result(retvalue);
7692   return true;
7693 }
7694 
7695 //------------------------------inline_electronicCodeBook_AESCrypt-----------------------
7696 bool LibraryCallKit::inline_electronicCodeBook_AESCrypt(vmIntrinsics::ID id) {
7697   address stubAddr = nullptr;
7698   const char *stubName = nullptr;
7699 
7700   assert(UseAES, "need AES instruction support");
7701 
7702   switch (id) {
7703   case vmIntrinsics::_electronicCodeBook_encryptAESCrypt:
7704     stubAddr = StubRoutines::electronicCodeBook_encryptAESCrypt();
7705     stubName = "electronicCodeBook_encryptAESCrypt";
7706     break;
7707   case vmIntrinsics::_electronicCodeBook_decryptAESCrypt:
7708     stubAddr = StubRoutines::electronicCodeBook_decryptAESCrypt();
7709     stubName = "electronicCodeBook_decryptAESCrypt";
7710     break;
7711   default:
7712     break;
7713   }
7714 
7715   if (stubAddr == nullptr) return false;
7716 
7717   Node* electronicCodeBook_object = argument(0);
7718   Node* src                       = argument(1);
7719   Node* src_offset                = argument(2);
7720   Node* len                       = argument(3);
7721   Node* dest                      = argument(4);
7722   Node* dest_offset               = argument(5);
7723 
7724   // (1) src and dest are arrays.
7725   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7726   const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
7727   assert( src_type != nullptr &&  src_type->elem() != Type::BOTTOM &&
7728          dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
7729 
7730   // checks are the responsibility of the caller
7731   Node* src_start = src;
7732   Node* dest_start = dest;
7733   if (src_offset != nullptr || dest_offset != nullptr) {
7734     assert(src_offset != nullptr && dest_offset != nullptr, "");
7735     src_start = array_element_address(src, src_offset, T_BYTE);
7736     dest_start = array_element_address(dest, dest_offset, T_BYTE);
7737   }
7738 
7739   // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
7740   // (because of the predicated logic executed earlier).
7741   // so we cast it here safely.
7742   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
7743 
7744   Node* embeddedCipherObj = load_field_from_object(electronicCodeBook_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
7745   if (embeddedCipherObj == nullptr) return false;
7746 
7747   // cast it to what we know it will be at runtime
7748   const TypeInstPtr* tinst = _gvn.type(electronicCodeBook_object)->isa_instptr();
7749   assert(tinst != nullptr, "ECB obj is null");
7750   assert(tinst->is_loaded(), "ECB obj is not loaded");
7751   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AESCrypt"));
7752   assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
7753 
7754   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
7755   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
7756   const TypeOopPtr* xtype = aklass->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
7757   Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
7758   aescrypt_object = _gvn.transform(aescrypt_object);
7759 
7760   // we need to get the start of the aescrypt_object's expanded key array
7761   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object);
7762   if (k_start == nullptr) return false;
7763 
7764   // Call the stub, passing src_start, dest_start, k_start, r_start and src_len
7765   Node* ecbCrypt = make_runtime_call(RC_LEAF | RC_NO_FP,
7766                                      OptoRuntime::electronicCodeBook_aescrypt_Type(),
7767                                      stubAddr, stubName, TypePtr::BOTTOM,
7768                                      src_start, dest_start, k_start, len);
7769 
7770   // return cipher length (int)
7771   Node* retvalue = _gvn.transform(new ProjNode(ecbCrypt, TypeFunc::Parms));
7772   set_result(retvalue);
7773   return true;
7774 }
7775 
7776 //------------------------------inline_counterMode_AESCrypt-----------------------
7777 bool LibraryCallKit::inline_counterMode_AESCrypt(vmIntrinsics::ID id) {
7778   assert(UseAES, "need AES instruction support");
7779   if (!UseAESCTRIntrinsics) return false;
7780 
7781   address stubAddr = nullptr;
7782   const char *stubName = nullptr;
7783   if (id == vmIntrinsics::_counterMode_AESCrypt) {
7784     stubAddr = StubRoutines::counterMode_AESCrypt();
7785     stubName = "counterMode_AESCrypt";
7786   }
7787   if (stubAddr == nullptr) return false;
7788 
7789   Node* counterMode_object = argument(0);
7790   Node* src = argument(1);
7791   Node* src_offset = argument(2);
7792   Node* len = argument(3);
7793   Node* dest = argument(4);
7794   Node* dest_offset = argument(5);
7795 
7796   // (1) src and dest are arrays.
7797   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7798   const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
7799   assert( src_type != nullptr &&  src_type->elem() != Type::BOTTOM &&
7800          dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
7801 
7802   // checks are the responsibility of the caller
7803   Node* src_start = src;
7804   Node* dest_start = dest;
7805   if (src_offset != nullptr || dest_offset != nullptr) {
7806     assert(src_offset != nullptr && dest_offset != nullptr, "");
7807     src_start = array_element_address(src, src_offset, T_BYTE);
7808     dest_start = array_element_address(dest, dest_offset, T_BYTE);
7809   }
7810 
7811   // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
7812   // (because of the predicated logic executed earlier).
7813   // so we cast it here safely.
7814   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
7815   Node* embeddedCipherObj = load_field_from_object(counterMode_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
7816   if (embeddedCipherObj == nullptr) return false;
7817   // cast it to what we know it will be at runtime
7818   const TypeInstPtr* tinst = _gvn.type(counterMode_object)->isa_instptr();
7819   assert(tinst != nullptr, "CTR obj is null");
7820   assert(tinst->is_loaded(), "CTR obj is not loaded");
7821   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AESCrypt"));
7822   assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
7823   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
7824   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
7825   const TypeOopPtr* xtype = aklass->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
7826   Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
7827   aescrypt_object = _gvn.transform(aescrypt_object);
7828   // we need to get the start of the aescrypt_object's expanded key array
7829   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object);
7830   if (k_start == nullptr) return false;
7831   // similarly, get the start address of the r vector
7832   Node* obj_counter = load_field_from_object(counterMode_object, "counter", "[B");
7833   if (obj_counter == nullptr) return false;
7834   Node* cnt_start = array_element_address(obj_counter, intcon(0), T_BYTE);
7835 
7836   Node* saved_encCounter = load_field_from_object(counterMode_object, "encryptedCounter", "[B");
7837   if (saved_encCounter == nullptr) return false;
7838   Node* saved_encCounter_start = array_element_address(saved_encCounter, intcon(0), T_BYTE);
7839   Node* used = field_address_from_object(counterMode_object, "used", "I", /*is_exact*/ false);
7840 
7841   // Call the stub, passing src_start, dest_start, k_start, r_start and src_len
7842   Node* ctrCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
7843                                      OptoRuntime::counterMode_aescrypt_Type(),
7844                                      stubAddr, stubName, TypePtr::BOTTOM,
7845                                      src_start, dest_start, k_start, cnt_start, len, saved_encCounter_start, used);
7846 
7847   // return cipher length (int)
7848   Node* retvalue = _gvn.transform(new ProjNode(ctrCrypt, TypeFunc::Parms));
7849   set_result(retvalue);
7850   return true;
7851 }
7852 
7853 //------------------------------get_key_start_from_aescrypt_object-----------------------
7854 Node * LibraryCallKit::get_key_start_from_aescrypt_object(Node *aescrypt_object) {
7855 #if defined(PPC64) || defined(S390) || defined(RISCV64)
7856   // MixColumns for decryption can be reduced by preprocessing MixColumns with round keys.
7857   // Intel's extension is based on this optimization and AESCrypt generates round keys by preprocessing MixColumns.
7858   // However, ppc64 vncipher processes MixColumns and requires the same round keys with encryption.
7859   // The ppc64 and riscv64 stubs of encryption and decryption use the same round keys (sessionK[0]).
7860   Node* objSessionK = load_field_from_object(aescrypt_object, "sessionK", "[[I");
7861   assert (objSessionK != nullptr, "wrong version of com.sun.crypto.provider.AESCrypt");
7862   if (objSessionK == nullptr) {
7863     return (Node *) nullptr;
7864   }
7865   Node* objAESCryptKey = load_array_element(objSessionK, intcon(0), TypeAryPtr::OOPS, /* set_ctrl */ true);
7866 #else
7867   Node* objAESCryptKey = load_field_from_object(aescrypt_object, "K", "[I");
7868 #endif // PPC64
7869   assert (objAESCryptKey != nullptr, "wrong version of com.sun.crypto.provider.AESCrypt");
7870   if (objAESCryptKey == nullptr) return (Node *) nullptr;
7871 
7872   // now have the array, need to get the start address of the K array
7873   Node* k_start = array_element_address(objAESCryptKey, intcon(0), T_INT);
7874   return k_start;
7875 }
7876 
7877 //----------------------------inline_cipherBlockChaining_AESCrypt_predicate----------------------------
7878 // Return node representing slow path of predicate check.
7879 // the pseudo code we want to emulate with this predicate is:
7880 // for encryption:
7881 //    if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
7882 // for decryption:
7883 //    if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
7884 //    note cipher==plain is more conservative than the original java code but that's OK
7885 //
7886 Node* LibraryCallKit::inline_cipherBlockChaining_AESCrypt_predicate(bool decrypting) {
7887   // The receiver was checked for null already.
7888   Node* objCBC = argument(0);
7889 
7890   Node* src = argument(1);
7891   Node* dest = argument(4);
7892 
7893   // Load embeddedCipher field of CipherBlockChaining object.
7894   Node* embeddedCipherObj = load_field_from_object(objCBC, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
7895 
7896   // get AESCrypt klass for instanceOf check
7897   // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
7898   // will have same classloader as CipherBlockChaining object
7899   const TypeInstPtr* tinst = _gvn.type(objCBC)->isa_instptr();
7900   assert(tinst != nullptr, "CBCobj is null");
7901   assert(tinst->is_loaded(), "CBCobj is not loaded");
7902 
7903   // we want to do an instanceof comparison against the AESCrypt class
7904   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AESCrypt"));
7905   if (!klass_AESCrypt->is_loaded()) {
7906     // if AESCrypt is not even loaded, we never take the intrinsic fast path
7907     Node* ctrl = control();
7908     set_control(top()); // no regular fast path
7909     return ctrl;
7910   }
7911 
7912   src = must_be_not_null(src, true);
7913   dest = must_be_not_null(dest, true);
7914 
7915   // Resolve oops to stable for CmpP below.
7916   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
7917 
7918   Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
7919   Node* cmp_instof  = _gvn.transform(new CmpINode(instof, intcon(1)));
7920   Node* bool_instof  = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
7921 
7922   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
7923 
7924   // for encryption, we are done
7925   if (!decrypting)
7926     return instof_false;  // even if it is null
7927 
7928   // for decryption, we need to add a further check to avoid
7929   // taking the intrinsic path when cipher and plain are the same
7930   // see the original java code for why.
7931   RegionNode* region = new RegionNode(3);
7932   region->init_req(1, instof_false);
7933 
7934   Node* cmp_src_dest = _gvn.transform(new CmpPNode(src, dest));
7935   Node* bool_src_dest = _gvn.transform(new BoolNode(cmp_src_dest, BoolTest::eq));
7936   Node* src_dest_conjoint = generate_guard(bool_src_dest, nullptr, PROB_MIN);
7937   region->init_req(2, src_dest_conjoint);
7938 
7939   record_for_igvn(region);
7940   return _gvn.transform(region);
7941 }
7942 
7943 //----------------------------inline_electronicCodeBook_AESCrypt_predicate----------------------------
7944 // Return node representing slow path of predicate check.
7945 // the pseudo code we want to emulate with this predicate is:
7946 // for encryption:
7947 //    if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
7948 // for decryption:
7949 //    if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
7950 //    note cipher==plain is more conservative than the original java code but that's OK
7951 //
7952 Node* LibraryCallKit::inline_electronicCodeBook_AESCrypt_predicate(bool decrypting) {
7953   // The receiver was checked for null already.
7954   Node* objECB = argument(0);
7955 
7956   // Load embeddedCipher field of ElectronicCodeBook object.
7957   Node* embeddedCipherObj = load_field_from_object(objECB, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
7958 
7959   // get AESCrypt klass for instanceOf check
7960   // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
7961   // will have same classloader as ElectronicCodeBook object
7962   const TypeInstPtr* tinst = _gvn.type(objECB)->isa_instptr();
7963   assert(tinst != nullptr, "ECBobj is null");
7964   assert(tinst->is_loaded(), "ECBobj is not loaded");
7965 
7966   // we want to do an instanceof comparison against the AESCrypt class
7967   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AESCrypt"));
7968   if (!klass_AESCrypt->is_loaded()) {
7969     // if AESCrypt is not even loaded, we never take the intrinsic fast path
7970     Node* ctrl = control();
7971     set_control(top()); // no regular fast path
7972     return ctrl;
7973   }
7974   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
7975 
7976   Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
7977   Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
7978   Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
7979 
7980   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
7981 
7982   // for encryption, we are done
7983   if (!decrypting)
7984     return instof_false;  // even if it is null
7985 
7986   // for decryption, we need to add a further check to avoid
7987   // taking the intrinsic path when cipher and plain are the same
7988   // see the original java code for why.
7989   RegionNode* region = new RegionNode(3);
7990   region->init_req(1, instof_false);
7991   Node* src = argument(1);
7992   Node* dest = argument(4);
7993   Node* cmp_src_dest = _gvn.transform(new CmpPNode(src, dest));
7994   Node* bool_src_dest = _gvn.transform(new BoolNode(cmp_src_dest, BoolTest::eq));
7995   Node* src_dest_conjoint = generate_guard(bool_src_dest, nullptr, PROB_MIN);
7996   region->init_req(2, src_dest_conjoint);
7997 
7998   record_for_igvn(region);
7999   return _gvn.transform(region);
8000 }
8001 
8002 //----------------------------inline_counterMode_AESCrypt_predicate----------------------------
8003 // Return node representing slow path of predicate check.
8004 // the pseudo code we want to emulate with this predicate is:
8005 // for encryption:
8006 //    if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
8007 // for decryption:
8008 //    if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
8009 //    note cipher==plain is more conservative than the original java code but that's OK
8010 //
8011 
8012 Node* LibraryCallKit::inline_counterMode_AESCrypt_predicate() {
8013   // The receiver was checked for null already.
8014   Node* objCTR = argument(0);
8015 
8016   // Load embeddedCipher field of CipherBlockChaining object.
8017   Node* embeddedCipherObj = load_field_from_object(objCTR, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8018 
8019   // get AESCrypt klass for instanceOf check
8020   // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
8021   // will have same classloader as CipherBlockChaining object
8022   const TypeInstPtr* tinst = _gvn.type(objCTR)->isa_instptr();
8023   assert(tinst != nullptr, "CTRobj is null");
8024   assert(tinst->is_loaded(), "CTRobj is not loaded");
8025 
8026   // we want to do an instanceof comparison against the AESCrypt class
8027   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AESCrypt"));
8028   if (!klass_AESCrypt->is_loaded()) {
8029     // if AESCrypt is not even loaded, we never take the intrinsic fast path
8030     Node* ctrl = control();
8031     set_control(top()); // no regular fast path
8032     return ctrl;
8033   }
8034 
8035   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8036   Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
8037   Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
8038   Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
8039   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
8040 
8041   return instof_false; // even if it is null
8042 }
8043 
8044 //------------------------------inline_ghash_processBlocks
8045 bool LibraryCallKit::inline_ghash_processBlocks() {
8046   address stubAddr;
8047   const char *stubName;
8048   assert(UseGHASHIntrinsics, "need GHASH intrinsics support");
8049 
8050   stubAddr = StubRoutines::ghash_processBlocks();
8051   stubName = "ghash_processBlocks";
8052 
8053   Node* data           = argument(0);
8054   Node* offset         = argument(1);
8055   Node* len            = argument(2);
8056   Node* state          = argument(3);
8057   Node* subkeyH        = argument(4);
8058 
8059   state = must_be_not_null(state, true);
8060   subkeyH = must_be_not_null(subkeyH, true);
8061   data = must_be_not_null(data, true);
8062 
8063   Node* state_start  = array_element_address(state, intcon(0), T_LONG);
8064   assert(state_start, "state is null");
8065   Node* subkeyH_start  = array_element_address(subkeyH, intcon(0), T_LONG);
8066   assert(subkeyH_start, "subkeyH is null");
8067   Node* data_start  = array_element_address(data, offset, T_BYTE);
8068   assert(data_start, "data is null");
8069 
8070   Node* ghash = make_runtime_call(RC_LEAF|RC_NO_FP,
8071                                   OptoRuntime::ghash_processBlocks_Type(),
8072                                   stubAddr, stubName, TypePtr::BOTTOM,
8073                                   state_start, subkeyH_start, data_start, len);
8074   return true;
8075 }
8076 
8077 //------------------------------inline_chacha20Block
8078 bool LibraryCallKit::inline_chacha20Block() {
8079   address stubAddr;
8080   const char *stubName;
8081   assert(UseChaCha20Intrinsics, "need ChaCha20 intrinsics support");
8082 
8083   stubAddr = StubRoutines::chacha20Block();
8084   stubName = "chacha20Block";
8085 
8086   Node* state          = argument(0);
8087   Node* result         = argument(1);
8088 
8089   state = must_be_not_null(state, true);
8090   result = must_be_not_null(result, true);
8091 
8092   Node* state_start  = array_element_address(state, intcon(0), T_INT);
8093   assert(state_start, "state is null");
8094   Node* result_start  = array_element_address(result, intcon(0), T_BYTE);
8095   assert(result_start, "result is null");
8096 
8097   Node* cc20Blk = make_runtime_call(RC_LEAF|RC_NO_FP,
8098                                   OptoRuntime::chacha20Block_Type(),
8099                                   stubAddr, stubName, TypePtr::BOTTOM,
8100                                   state_start, result_start);
8101   // return key stream length (int)
8102   Node* retvalue = _gvn.transform(new ProjNode(cc20Blk, TypeFunc::Parms));
8103   set_result(retvalue);
8104   return true;
8105 }
8106 
8107 //------------------------------inline_kyberNtt
8108 bool LibraryCallKit::inline_kyberNtt() {
8109   address stubAddr;
8110   const char *stubName;
8111   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8112   assert(callee()->signature()->size() == 2, "kyberNtt has 2 parameters");
8113 
8114   stubAddr = StubRoutines::kyberNtt();
8115   stubName = "kyberNtt";
8116   if (!stubAddr) return false;
8117 
8118   Node* coeffs          = argument(0);
8119   Node* ntt_zetas        = argument(1);
8120 
8121   coeffs = must_be_not_null(coeffs, true);
8122   ntt_zetas = must_be_not_null(ntt_zetas, true);
8123 
8124   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_SHORT);
8125   assert(coeffs_start, "coeffs is null");
8126   Node* ntt_zetas_start  = array_element_address(ntt_zetas, intcon(0), T_SHORT);
8127   assert(ntt_zetas_start, "ntt_zetas is null");
8128   Node* kyberNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
8129                                   OptoRuntime::kyberNtt_Type(),
8130                                   stubAddr, stubName, TypePtr::BOTTOM,
8131                                   coeffs_start, ntt_zetas_start);
8132   // return an int
8133   Node* retvalue = _gvn.transform(new ProjNode(kyberNtt, TypeFunc::Parms));
8134   set_result(retvalue);
8135   return true;
8136 }
8137 
8138 //------------------------------inline_kyberInverseNtt
8139 bool LibraryCallKit::inline_kyberInverseNtt() {
8140   address stubAddr;
8141   const char *stubName;
8142   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8143   assert(callee()->signature()->size() == 2, "kyberInverseNtt has 2 parameters");
8144 
8145   stubAddr = StubRoutines::kyberInverseNtt();
8146   stubName = "kyberInverseNtt";
8147   if (!stubAddr) return false;
8148 
8149   Node* coeffs          = argument(0);
8150   Node* zetas           = argument(1);
8151 
8152   coeffs = must_be_not_null(coeffs, true);
8153   zetas = must_be_not_null(zetas, true);
8154 
8155   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_SHORT);
8156   assert(coeffs_start, "coeffs is null");
8157   Node* zetas_start  = array_element_address(zetas, intcon(0), T_SHORT);
8158   assert(zetas_start, "inverseNtt_zetas is null");
8159   Node* kyberInverseNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
8160                                   OptoRuntime::kyberInverseNtt_Type(),
8161                                   stubAddr, stubName, TypePtr::BOTTOM,
8162                                   coeffs_start, zetas_start);
8163 
8164   // return an int
8165   Node* retvalue = _gvn.transform(new ProjNode(kyberInverseNtt, TypeFunc::Parms));
8166   set_result(retvalue);
8167   return true;
8168 }
8169 
8170 //------------------------------inline_kyberNttMult
8171 bool LibraryCallKit::inline_kyberNttMult() {
8172   address stubAddr;
8173   const char *stubName;
8174   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8175   assert(callee()->signature()->size() == 4, "kyberNttMult has 4 parameters");
8176 
8177   stubAddr = StubRoutines::kyberNttMult();
8178   stubName = "kyberNttMult";
8179   if (!stubAddr) return false;
8180 
8181   Node* result          = argument(0);
8182   Node* ntta            = argument(1);
8183   Node* nttb            = argument(2);
8184   Node* zetas           = argument(3);
8185 
8186   result = must_be_not_null(result, true);
8187   ntta = must_be_not_null(ntta, true);
8188   nttb = must_be_not_null(nttb, true);
8189   zetas = must_be_not_null(zetas, true);
8190   Node* result_start  = array_element_address(result, intcon(0), T_SHORT);
8191   assert(result_start, "result is null");
8192   Node* ntta_start  = array_element_address(ntta, intcon(0), T_SHORT);
8193   assert(ntta_start, "ntta is null");
8194   Node* nttb_start  = array_element_address(nttb, intcon(0), T_SHORT);
8195   assert(nttb_start, "nttb is null");
8196   Node* zetas_start  = array_element_address(zetas, intcon(0), T_SHORT);
8197   assert(zetas_start, "nttMult_zetas is null");
8198   Node* kyberNttMult = make_runtime_call(RC_LEAF|RC_NO_FP,
8199                                   OptoRuntime::kyberNttMult_Type(),
8200                                   stubAddr, stubName, TypePtr::BOTTOM,
8201                                   result_start, ntta_start, nttb_start,
8202                                   zetas_start);
8203 
8204   // return an int
8205   Node* retvalue = _gvn.transform(new ProjNode(kyberNttMult, TypeFunc::Parms));
8206   set_result(retvalue);
8207 
8208   return true;
8209 }
8210 
8211 //------------------------------inline_kyberAddPoly_2
8212 bool LibraryCallKit::inline_kyberAddPoly_2() {
8213   address stubAddr;
8214   const char *stubName;
8215   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8216   assert(callee()->signature()->size() == 3, "kyberAddPoly_2 has 3 parameters");
8217 
8218   stubAddr = StubRoutines::kyberAddPoly_2();
8219   stubName = "kyberAddPoly_2";
8220   if (!stubAddr) return false;
8221 
8222   Node* result          = argument(0);
8223   Node* a               = argument(1);
8224   Node* b               = argument(2);
8225 
8226   result = must_be_not_null(result, true);
8227   a = must_be_not_null(a, true);
8228   b = must_be_not_null(b, true);
8229 
8230   Node* result_start  = array_element_address(result, intcon(0), T_SHORT);
8231   assert(result_start, "result is null");
8232   Node* a_start  = array_element_address(a, intcon(0), T_SHORT);
8233   assert(a_start, "a is null");
8234   Node* b_start  = array_element_address(b, intcon(0), T_SHORT);
8235   assert(b_start, "b is null");
8236   Node* kyberAddPoly_2 = make_runtime_call(RC_LEAF|RC_NO_FP,
8237                                   OptoRuntime::kyberAddPoly_2_Type(),
8238                                   stubAddr, stubName, TypePtr::BOTTOM,
8239                                   result_start, a_start, b_start);
8240   // return an int
8241   Node* retvalue = _gvn.transform(new ProjNode(kyberAddPoly_2, TypeFunc::Parms));
8242   set_result(retvalue);
8243   return true;
8244 }
8245 
8246 //------------------------------inline_kyberAddPoly_3
8247 bool LibraryCallKit::inline_kyberAddPoly_3() {
8248   address stubAddr;
8249   const char *stubName;
8250   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8251   assert(callee()->signature()->size() == 4, "kyberAddPoly_3 has 4 parameters");
8252 
8253   stubAddr = StubRoutines::kyberAddPoly_3();
8254   stubName = "kyberAddPoly_3";
8255   if (!stubAddr) return false;
8256 
8257   Node* result          = argument(0);
8258   Node* a               = argument(1);
8259   Node* b               = argument(2);
8260   Node* c               = argument(3);
8261 
8262   result = must_be_not_null(result, true);
8263   a = must_be_not_null(a, true);
8264   b = must_be_not_null(b, true);
8265   c = must_be_not_null(c, true);
8266 
8267   Node* result_start  = array_element_address(result, intcon(0), T_SHORT);
8268   assert(result_start, "result is null");
8269   Node* a_start  = array_element_address(a, intcon(0), T_SHORT);
8270   assert(a_start, "a is null");
8271   Node* b_start  = array_element_address(b, intcon(0), T_SHORT);
8272   assert(b_start, "b is null");
8273   Node* c_start  = array_element_address(c, intcon(0), T_SHORT);
8274   assert(c_start, "c is null");
8275   Node* kyberAddPoly_3 = make_runtime_call(RC_LEAF|RC_NO_FP,
8276                                   OptoRuntime::kyberAddPoly_3_Type(),
8277                                   stubAddr, stubName, TypePtr::BOTTOM,
8278                                   result_start, a_start, b_start, c_start);
8279   // return an int
8280   Node* retvalue = _gvn.transform(new ProjNode(kyberAddPoly_3, TypeFunc::Parms));
8281   set_result(retvalue);
8282   return true;
8283 }
8284 
8285 //------------------------------inline_kyber12To16
8286 bool LibraryCallKit::inline_kyber12To16() {
8287   address stubAddr;
8288   const char *stubName;
8289   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8290   assert(callee()->signature()->size() == 4, "kyber12To16 has 4 parameters");
8291 
8292   stubAddr = StubRoutines::kyber12To16();
8293   stubName = "kyber12To16";
8294   if (!stubAddr) return false;
8295 
8296   Node* condensed       = argument(0);
8297   Node* condensedOffs   = argument(1);
8298   Node* parsed          = argument(2);
8299   Node* parsedLength    = argument(3);
8300 
8301   condensed = must_be_not_null(condensed, true);
8302   parsed = must_be_not_null(parsed, true);
8303 
8304   Node* condensed_start  = array_element_address(condensed, intcon(0), T_BYTE);
8305   assert(condensed_start, "condensed is null");
8306   Node* parsed_start  = array_element_address(parsed, intcon(0), T_SHORT);
8307   assert(parsed_start, "parsed is null");
8308   Node* kyber12To16 = make_runtime_call(RC_LEAF|RC_NO_FP,
8309                                   OptoRuntime::kyber12To16_Type(),
8310                                   stubAddr, stubName, TypePtr::BOTTOM,
8311                                   condensed_start, condensedOffs, parsed_start, parsedLength);
8312   // return an int
8313   Node* retvalue = _gvn.transform(new ProjNode(kyber12To16, TypeFunc::Parms));
8314   set_result(retvalue);
8315   return true;
8316 
8317 }
8318 
8319 //------------------------------inline_kyberBarrettReduce
8320 bool LibraryCallKit::inline_kyberBarrettReduce() {
8321   address stubAddr;
8322   const char *stubName;
8323   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8324   assert(callee()->signature()->size() == 1, "kyberBarrettReduce has 1 parameters");
8325 
8326   stubAddr = StubRoutines::kyberBarrettReduce();
8327   stubName = "kyberBarrettReduce";
8328   if (!stubAddr) return false;
8329 
8330   Node* coeffs          = argument(0);
8331 
8332   coeffs = must_be_not_null(coeffs, true);
8333 
8334   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_SHORT);
8335   assert(coeffs_start, "coeffs is null");
8336   Node* kyberBarrettReduce = make_runtime_call(RC_LEAF|RC_NO_FP,
8337                                   OptoRuntime::kyberBarrettReduce_Type(),
8338                                   stubAddr, stubName, TypePtr::BOTTOM,
8339                                   coeffs_start);
8340   // return an int
8341   Node* retvalue = _gvn.transform(new ProjNode(kyberBarrettReduce, TypeFunc::Parms));
8342   set_result(retvalue);
8343   return true;
8344 }
8345 
8346 //------------------------------inline_dilithiumAlmostNtt
8347 bool LibraryCallKit::inline_dilithiumAlmostNtt() {
8348   address stubAddr;
8349   const char *stubName;
8350   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8351   assert(callee()->signature()->size() == 2, "dilithiumAlmostNtt has 2 parameters");
8352 
8353   stubAddr = StubRoutines::dilithiumAlmostNtt();
8354   stubName = "dilithiumAlmostNtt";
8355   if (!stubAddr) return false;
8356 
8357   Node* coeffs          = argument(0);
8358   Node* ntt_zetas        = argument(1);
8359 
8360   coeffs = must_be_not_null(coeffs, true);
8361   ntt_zetas = must_be_not_null(ntt_zetas, true);
8362 
8363   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_INT);
8364   assert(coeffs_start, "coeffs is null");
8365   Node* ntt_zetas_start  = array_element_address(ntt_zetas, intcon(0), T_INT);
8366   assert(ntt_zetas_start, "ntt_zetas is null");
8367   Node* dilithiumAlmostNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
8368                                   OptoRuntime::dilithiumAlmostNtt_Type(),
8369                                   stubAddr, stubName, TypePtr::BOTTOM,
8370                                   coeffs_start, ntt_zetas_start);
8371   // return an int
8372   Node* retvalue = _gvn.transform(new ProjNode(dilithiumAlmostNtt, TypeFunc::Parms));
8373   set_result(retvalue);
8374   return true;
8375 }
8376 
8377 //------------------------------inline_dilithiumAlmostInverseNtt
8378 bool LibraryCallKit::inline_dilithiumAlmostInverseNtt() {
8379   address stubAddr;
8380   const char *stubName;
8381   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8382   assert(callee()->signature()->size() == 2, "dilithiumAlmostInverseNtt has 2 parameters");
8383 
8384   stubAddr = StubRoutines::dilithiumAlmostInverseNtt();
8385   stubName = "dilithiumAlmostInverseNtt";
8386   if (!stubAddr) return false;
8387 
8388   Node* coeffs          = argument(0);
8389   Node* zetas           = argument(1);
8390 
8391   coeffs = must_be_not_null(coeffs, true);
8392   zetas = must_be_not_null(zetas, true);
8393 
8394   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_INT);
8395   assert(coeffs_start, "coeffs is null");
8396   Node* zetas_start  = array_element_address(zetas, intcon(0), T_INT);
8397   assert(zetas_start, "inverseNtt_zetas is null");
8398   Node* dilithiumAlmostInverseNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
8399                                   OptoRuntime::dilithiumAlmostInverseNtt_Type(),
8400                                   stubAddr, stubName, TypePtr::BOTTOM,
8401                                   coeffs_start, zetas_start);
8402   // return an int
8403   Node* retvalue = _gvn.transform(new ProjNode(dilithiumAlmostInverseNtt, TypeFunc::Parms));
8404   set_result(retvalue);
8405   return true;
8406 }
8407 
8408 //------------------------------inline_dilithiumNttMult
8409 bool LibraryCallKit::inline_dilithiumNttMult() {
8410   address stubAddr;
8411   const char *stubName;
8412   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8413   assert(callee()->signature()->size() == 3, "dilithiumNttMult has 3 parameters");
8414 
8415   stubAddr = StubRoutines::dilithiumNttMult();
8416   stubName = "dilithiumNttMult";
8417   if (!stubAddr) return false;
8418 
8419   Node* result          = argument(0);
8420   Node* ntta            = argument(1);
8421   Node* nttb            = argument(2);
8422   Node* zetas           = argument(3);
8423 
8424   result = must_be_not_null(result, true);
8425   ntta = must_be_not_null(ntta, true);
8426   nttb = must_be_not_null(nttb, true);
8427   zetas = must_be_not_null(zetas, true);
8428 
8429   Node* result_start  = array_element_address(result, intcon(0), T_INT);
8430   assert(result_start, "result is null");
8431   Node* ntta_start  = array_element_address(ntta, intcon(0), T_INT);
8432   assert(ntta_start, "ntta is null");
8433   Node* nttb_start  = array_element_address(nttb, intcon(0), T_INT);
8434   assert(nttb_start, "nttb is null");
8435   Node* dilithiumNttMult = make_runtime_call(RC_LEAF|RC_NO_FP,
8436                                   OptoRuntime::dilithiumNttMult_Type(),
8437                                   stubAddr, stubName, TypePtr::BOTTOM,
8438                                   result_start, ntta_start, nttb_start);
8439 
8440   // return an int
8441   Node* retvalue = _gvn.transform(new ProjNode(dilithiumNttMult, TypeFunc::Parms));
8442   set_result(retvalue);
8443 
8444   return true;
8445 }
8446 
8447 //------------------------------inline_dilithiumMontMulByConstant
8448 bool LibraryCallKit::inline_dilithiumMontMulByConstant() {
8449   address stubAddr;
8450   const char *stubName;
8451   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8452   assert(callee()->signature()->size() == 2, "dilithiumMontMulByConstant has 2 parameters");
8453 
8454   stubAddr = StubRoutines::dilithiumMontMulByConstant();
8455   stubName = "dilithiumMontMulByConstant";
8456   if (!stubAddr) return false;
8457 
8458   Node* coeffs          = argument(0);
8459   Node* constant        = argument(1);
8460 
8461   coeffs = must_be_not_null(coeffs, true);
8462 
8463   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_INT);
8464   assert(coeffs_start, "coeffs is null");
8465   Node* dilithiumMontMulByConstant = make_runtime_call(RC_LEAF|RC_NO_FP,
8466                                   OptoRuntime::dilithiumMontMulByConstant_Type(),
8467                                   stubAddr, stubName, TypePtr::BOTTOM,
8468                                   coeffs_start, constant);
8469 
8470   // return an int
8471   Node* retvalue = _gvn.transform(new ProjNode(dilithiumMontMulByConstant, TypeFunc::Parms));
8472   set_result(retvalue);
8473   return true;
8474 }
8475 
8476 
8477 //------------------------------inline_dilithiumDecomposePoly
8478 bool LibraryCallKit::inline_dilithiumDecomposePoly() {
8479   address stubAddr;
8480   const char *stubName;
8481   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8482   assert(callee()->signature()->size() == 5, "dilithiumDecomposePoly has 5 parameters");
8483 
8484   stubAddr = StubRoutines::dilithiumDecomposePoly();
8485   stubName = "dilithiumDecomposePoly";
8486   if (!stubAddr) return false;
8487 
8488   Node* input          = argument(0);
8489   Node* lowPart        = argument(1);
8490   Node* highPart       = argument(2);
8491   Node* twoGamma2      = argument(3);
8492   Node* multiplier     = argument(4);
8493 
8494   input = must_be_not_null(input, true);
8495   lowPart = must_be_not_null(lowPart, true);
8496   highPart = must_be_not_null(highPart, true);
8497 
8498   Node* input_start  = array_element_address(input, intcon(0), T_INT);
8499   assert(input_start, "input is null");
8500   Node* lowPart_start  = array_element_address(lowPart, intcon(0), T_INT);
8501   assert(lowPart_start, "lowPart is null");
8502   Node* highPart_start  = array_element_address(highPart, intcon(0), T_INT);
8503   assert(highPart_start, "highPart is null");
8504 
8505   Node* dilithiumDecomposePoly = make_runtime_call(RC_LEAF|RC_NO_FP,
8506                                   OptoRuntime::dilithiumDecomposePoly_Type(),
8507                                   stubAddr, stubName, TypePtr::BOTTOM,
8508                                   input_start, lowPart_start, highPart_start,
8509                                   twoGamma2, multiplier);
8510 
8511   // return an int
8512   Node* retvalue = _gvn.transform(new ProjNode(dilithiumDecomposePoly, TypeFunc::Parms));
8513   set_result(retvalue);
8514   return true;
8515 }
8516 
8517 bool LibraryCallKit::inline_base64_encodeBlock() {
8518   address stubAddr;
8519   const char *stubName;
8520   assert(UseBASE64Intrinsics, "need Base64 intrinsics support");
8521   assert(callee()->signature()->size() == 6, "base64_encodeBlock has 6 parameters");
8522   stubAddr = StubRoutines::base64_encodeBlock();
8523   stubName = "encodeBlock";
8524 
8525   if (!stubAddr) return false;
8526   Node* base64obj = argument(0);
8527   Node* src = argument(1);
8528   Node* offset = argument(2);
8529   Node* len = argument(3);
8530   Node* dest = argument(4);
8531   Node* dp = argument(5);
8532   Node* isURL = argument(6);
8533 
8534   src = must_be_not_null(src, true);
8535   dest = must_be_not_null(dest, true);
8536 
8537   Node* src_start = array_element_address(src, intcon(0), T_BYTE);
8538   assert(src_start, "source array is null");
8539   Node* dest_start = array_element_address(dest, intcon(0), T_BYTE);
8540   assert(dest_start, "destination array is null");
8541 
8542   Node* base64 = make_runtime_call(RC_LEAF,
8543                                    OptoRuntime::base64_encodeBlock_Type(),
8544                                    stubAddr, stubName, TypePtr::BOTTOM,
8545                                    src_start, offset, len, dest_start, dp, isURL);
8546   return true;
8547 }
8548 
8549 bool LibraryCallKit::inline_base64_decodeBlock() {
8550   address stubAddr;
8551   const char *stubName;
8552   assert(UseBASE64Intrinsics, "need Base64 intrinsics support");
8553   assert(callee()->signature()->size() == 7, "base64_decodeBlock has 7 parameters");
8554   stubAddr = StubRoutines::base64_decodeBlock();
8555   stubName = "decodeBlock";
8556 
8557   if (!stubAddr) return false;
8558   Node* base64obj = argument(0);
8559   Node* src = argument(1);
8560   Node* src_offset = argument(2);
8561   Node* len = argument(3);
8562   Node* dest = argument(4);
8563   Node* dest_offset = argument(5);
8564   Node* isURL = argument(6);
8565   Node* isMIME = argument(7);
8566 
8567   src = must_be_not_null(src, true);
8568   dest = must_be_not_null(dest, true);
8569 
8570   Node* src_start = array_element_address(src, intcon(0), T_BYTE);
8571   assert(src_start, "source array is null");
8572   Node* dest_start = array_element_address(dest, intcon(0), T_BYTE);
8573   assert(dest_start, "destination array is null");
8574 
8575   Node* call = make_runtime_call(RC_LEAF,
8576                                  OptoRuntime::base64_decodeBlock_Type(),
8577                                  stubAddr, stubName, TypePtr::BOTTOM,
8578                                  src_start, src_offset, len, dest_start, dest_offset, isURL, isMIME);
8579   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
8580   set_result(result);
8581   return true;
8582 }
8583 
8584 bool LibraryCallKit::inline_poly1305_processBlocks() {
8585   address stubAddr;
8586   const char *stubName;
8587   assert(UsePoly1305Intrinsics, "need Poly intrinsics support");
8588   assert(callee()->signature()->size() == 5, "poly1305_processBlocks has %d parameters", callee()->signature()->size());
8589   stubAddr = StubRoutines::poly1305_processBlocks();
8590   stubName = "poly1305_processBlocks";
8591 
8592   if (!stubAddr) return false;
8593   null_check_receiver();  // null-check receiver
8594   if (stopped())  return true;
8595 
8596   Node* input = argument(1);
8597   Node* input_offset = argument(2);
8598   Node* len = argument(3);
8599   Node* alimbs = argument(4);
8600   Node* rlimbs = argument(5);
8601 
8602   input = must_be_not_null(input, true);
8603   alimbs = must_be_not_null(alimbs, true);
8604   rlimbs = must_be_not_null(rlimbs, true);
8605 
8606   Node* input_start = array_element_address(input, input_offset, T_BYTE);
8607   assert(input_start, "input array is null");
8608   Node* acc_start = array_element_address(alimbs, intcon(0), T_LONG);
8609   assert(acc_start, "acc array is null");
8610   Node* r_start = array_element_address(rlimbs, intcon(0), T_LONG);
8611   assert(r_start, "r array is null");
8612 
8613   Node* call = make_runtime_call(RC_LEAF | RC_NO_FP,
8614                                  OptoRuntime::poly1305_processBlocks_Type(),
8615                                  stubAddr, stubName, TypePtr::BOTTOM,
8616                                  input_start, len, acc_start, r_start);
8617   return true;
8618 }
8619 
8620 bool LibraryCallKit::inline_intpoly_montgomeryMult_P256() {
8621   address stubAddr;
8622   const char *stubName;
8623   assert(UseIntPolyIntrinsics, "need intpoly intrinsics support");
8624   assert(callee()->signature()->size() == 3, "intpoly_montgomeryMult_P256 has %d parameters", callee()->signature()->size());
8625   stubAddr = StubRoutines::intpoly_montgomeryMult_P256();
8626   stubName = "intpoly_montgomeryMult_P256";
8627 
8628   if (!stubAddr) return false;
8629   null_check_receiver();  // null-check receiver
8630   if (stopped())  return true;
8631 
8632   Node* a = argument(1);
8633   Node* b = argument(2);
8634   Node* r = argument(3);
8635 
8636   a = must_be_not_null(a, true);
8637   b = must_be_not_null(b, true);
8638   r = must_be_not_null(r, true);
8639 
8640   Node* a_start = array_element_address(a, intcon(0), T_LONG);
8641   assert(a_start, "a array is null");
8642   Node* b_start = array_element_address(b, intcon(0), T_LONG);
8643   assert(b_start, "b array is null");
8644   Node* r_start = array_element_address(r, intcon(0), T_LONG);
8645   assert(r_start, "r array is null");
8646 
8647   Node* call = make_runtime_call(RC_LEAF | RC_NO_FP,
8648                                  OptoRuntime::intpoly_montgomeryMult_P256_Type(),
8649                                  stubAddr, stubName, TypePtr::BOTTOM,
8650                                  a_start, b_start, r_start);
8651   return true;
8652 }
8653 
8654 bool LibraryCallKit::inline_intpoly_assign() {
8655   assert(UseIntPolyIntrinsics, "need intpoly intrinsics support");
8656   assert(callee()->signature()->size() == 3, "intpoly_assign has %d parameters", callee()->signature()->size());
8657   const char *stubName = "intpoly_assign";
8658   address stubAddr = StubRoutines::intpoly_assign();
8659   if (!stubAddr) return false;
8660 
8661   Node* set = argument(0);
8662   Node* a = argument(1);
8663   Node* b = argument(2);
8664   Node* arr_length = load_array_length(a);
8665 
8666   a = must_be_not_null(a, true);
8667   b = must_be_not_null(b, true);
8668 
8669   Node* a_start = array_element_address(a, intcon(0), T_LONG);
8670   assert(a_start, "a array is null");
8671   Node* b_start = array_element_address(b, intcon(0), T_LONG);
8672   assert(b_start, "b array is null");
8673 
8674   Node* call = make_runtime_call(RC_LEAF | RC_NO_FP,
8675                                  OptoRuntime::intpoly_assign_Type(),
8676                                  stubAddr, stubName, TypePtr::BOTTOM,
8677                                  set, a_start, b_start, arr_length);
8678   return true;
8679 }
8680 
8681 //------------------------------inline_digestBase_implCompress-----------------------
8682 //
8683 // Calculate MD5 for single-block byte[] array.
8684 // void com.sun.security.provider.MD5.implCompress(byte[] buf, int ofs)
8685 //
8686 // Calculate SHA (i.e., SHA-1) for single-block byte[] array.
8687 // void com.sun.security.provider.SHA.implCompress(byte[] buf, int ofs)
8688 //
8689 // Calculate SHA2 (i.e., SHA-244 or SHA-256) for single-block byte[] array.
8690 // void com.sun.security.provider.SHA2.implCompress(byte[] buf, int ofs)
8691 //
8692 // Calculate SHA5 (i.e., SHA-384 or SHA-512) for single-block byte[] array.
8693 // void com.sun.security.provider.SHA5.implCompress(byte[] buf, int ofs)
8694 //
8695 // Calculate SHA3 (i.e., SHA3-224 or SHA3-256 or SHA3-384 or SHA3-512) for single-block byte[] array.
8696 // void com.sun.security.provider.SHA3.implCompress(byte[] buf, int ofs)
8697 //
8698 bool LibraryCallKit::inline_digestBase_implCompress(vmIntrinsics::ID id) {
8699   assert(callee()->signature()->size() == 2, "sha_implCompress has 2 parameters");
8700 
8701   Node* digestBase_obj = argument(0);
8702   Node* src            = argument(1); // type oop
8703   Node* ofs            = argument(2); // type int
8704 
8705   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
8706   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
8707     // failed array check
8708     return false;
8709   }
8710   // Figure out the size and type of the elements we will be copying.
8711   BasicType src_elem = src_type->elem()->array_element_basic_type();
8712   if (src_elem != T_BYTE) {
8713     return false;
8714   }
8715   // 'src_start' points to src array + offset
8716   src = must_be_not_null(src, true);
8717   Node* src_start = array_element_address(src, ofs, src_elem);
8718   Node* state = nullptr;
8719   Node* block_size = nullptr;
8720   address stubAddr;
8721   const char *stubName;
8722 
8723   switch(id) {
8724   case vmIntrinsics::_md5_implCompress:
8725     assert(UseMD5Intrinsics, "need MD5 instruction support");
8726     state = get_state_from_digest_object(digestBase_obj, T_INT);
8727     stubAddr = StubRoutines::md5_implCompress();
8728     stubName = "md5_implCompress";
8729     break;
8730   case vmIntrinsics::_sha_implCompress:
8731     assert(UseSHA1Intrinsics, "need SHA1 instruction support");
8732     state = get_state_from_digest_object(digestBase_obj, T_INT);
8733     stubAddr = StubRoutines::sha1_implCompress();
8734     stubName = "sha1_implCompress";
8735     break;
8736   case vmIntrinsics::_sha2_implCompress:
8737     assert(UseSHA256Intrinsics, "need SHA256 instruction support");
8738     state = get_state_from_digest_object(digestBase_obj, T_INT);
8739     stubAddr = StubRoutines::sha256_implCompress();
8740     stubName = "sha256_implCompress";
8741     break;
8742   case vmIntrinsics::_sha5_implCompress:
8743     assert(UseSHA512Intrinsics, "need SHA512 instruction support");
8744     state = get_state_from_digest_object(digestBase_obj, T_LONG);
8745     stubAddr = StubRoutines::sha512_implCompress();
8746     stubName = "sha512_implCompress";
8747     break;
8748   case vmIntrinsics::_sha3_implCompress:
8749     assert(UseSHA3Intrinsics, "need SHA3 instruction support");
8750     state = get_state_from_digest_object(digestBase_obj, T_LONG);
8751     stubAddr = StubRoutines::sha3_implCompress();
8752     stubName = "sha3_implCompress";
8753     block_size = get_block_size_from_digest_object(digestBase_obj);
8754     if (block_size == nullptr) return false;
8755     break;
8756   default:
8757     fatal_unexpected_iid(id);
8758     return false;
8759   }
8760   if (state == nullptr) return false;
8761 
8762   assert(stubAddr != nullptr, "Stub %s is not generated", stubName);
8763   if (stubAddr == nullptr) return false;
8764 
8765   // Call the stub.
8766   Node* call;
8767   if (block_size == nullptr) {
8768     call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::digestBase_implCompress_Type(false),
8769                              stubAddr, stubName, TypePtr::BOTTOM,
8770                              src_start, state);
8771   } else {
8772     call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::digestBase_implCompress_Type(true),
8773                              stubAddr, stubName, TypePtr::BOTTOM,
8774                              src_start, state, block_size);
8775   }
8776 
8777   return true;
8778 }
8779 
8780 //------------------------------inline_double_keccak
8781 bool LibraryCallKit::inline_double_keccak() {
8782   address stubAddr;
8783   const char *stubName;
8784   assert(UseSHA3Intrinsics, "need SHA3 intrinsics support");
8785   assert(callee()->signature()->size() == 2, "double_keccak has 2 parameters");
8786 
8787   stubAddr = StubRoutines::double_keccak();
8788   stubName = "double_keccak";
8789   if (!stubAddr) return false;
8790 
8791   Node* status0        = argument(0);
8792   Node* status1        = argument(1);
8793 
8794   status0 = must_be_not_null(status0, true);
8795   status1 = must_be_not_null(status1, true);
8796 
8797   Node* status0_start  = array_element_address(status0, intcon(0), T_LONG);
8798   assert(status0_start, "status0 is null");
8799   Node* status1_start  = array_element_address(status1, intcon(0), T_LONG);
8800   assert(status1_start, "status1 is null");
8801   Node* double_keccak = make_runtime_call(RC_LEAF|RC_NO_FP,
8802                                   OptoRuntime::double_keccak_Type(),
8803                                   stubAddr, stubName, TypePtr::BOTTOM,
8804                                   status0_start, status1_start);
8805   // return an int
8806   Node* retvalue = _gvn.transform(new ProjNode(double_keccak, TypeFunc::Parms));
8807   set_result(retvalue);
8808   return true;
8809 }
8810 
8811 
8812 //------------------------------inline_digestBase_implCompressMB-----------------------
8813 //
8814 // Calculate MD5/SHA/SHA2/SHA5/SHA3 for multi-block byte[] array.
8815 // int com.sun.security.provider.DigestBase.implCompressMultiBlock(byte[] b, int ofs, int limit)
8816 //
8817 bool LibraryCallKit::inline_digestBase_implCompressMB(int predicate) {
8818   assert(UseMD5Intrinsics || UseSHA1Intrinsics || UseSHA256Intrinsics || UseSHA512Intrinsics || UseSHA3Intrinsics,
8819          "need MD5/SHA1/SHA256/SHA512/SHA3 instruction support");
8820   assert((uint)predicate < 5, "sanity");
8821   assert(callee()->signature()->size() == 3, "digestBase_implCompressMB has 3 parameters");
8822 
8823   Node* digestBase_obj = argument(0); // The receiver was checked for null already.
8824   Node* src            = argument(1); // byte[] array
8825   Node* ofs            = argument(2); // type int
8826   Node* limit          = argument(3); // type int
8827 
8828   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
8829   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
8830     // failed array check
8831     return false;
8832   }
8833   // Figure out the size and type of the elements we will be copying.
8834   BasicType src_elem = src_type->elem()->array_element_basic_type();
8835   if (src_elem != T_BYTE) {
8836     return false;
8837   }
8838   // 'src_start' points to src array + offset
8839   src = must_be_not_null(src, false);
8840   Node* src_start = array_element_address(src, ofs, src_elem);
8841 
8842   const char* klass_digestBase_name = nullptr;
8843   const char* stub_name = nullptr;
8844   address     stub_addr = nullptr;
8845   BasicType elem_type = T_INT;
8846 
8847   switch (predicate) {
8848   case 0:
8849     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_md5_implCompress)) {
8850       klass_digestBase_name = "sun/security/provider/MD5";
8851       stub_name = "md5_implCompressMB";
8852       stub_addr = StubRoutines::md5_implCompressMB();
8853     }
8854     break;
8855   case 1:
8856     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha_implCompress)) {
8857       klass_digestBase_name = "sun/security/provider/SHA";
8858       stub_name = "sha1_implCompressMB";
8859       stub_addr = StubRoutines::sha1_implCompressMB();
8860     }
8861     break;
8862   case 2:
8863     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha2_implCompress)) {
8864       klass_digestBase_name = "sun/security/provider/SHA2";
8865       stub_name = "sha256_implCompressMB";
8866       stub_addr = StubRoutines::sha256_implCompressMB();
8867     }
8868     break;
8869   case 3:
8870     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha5_implCompress)) {
8871       klass_digestBase_name = "sun/security/provider/SHA5";
8872       stub_name = "sha512_implCompressMB";
8873       stub_addr = StubRoutines::sha512_implCompressMB();
8874       elem_type = T_LONG;
8875     }
8876     break;
8877   case 4:
8878     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha3_implCompress)) {
8879       klass_digestBase_name = "sun/security/provider/SHA3";
8880       stub_name = "sha3_implCompressMB";
8881       stub_addr = StubRoutines::sha3_implCompressMB();
8882       elem_type = T_LONG;
8883     }
8884     break;
8885   default:
8886     fatal("unknown DigestBase intrinsic predicate: %d", predicate);
8887   }
8888   if (klass_digestBase_name != nullptr) {
8889     assert(stub_addr != nullptr, "Stub is generated");
8890     if (stub_addr == nullptr) return false;
8891 
8892     // get DigestBase klass to lookup for SHA klass
8893     const TypeInstPtr* tinst = _gvn.type(digestBase_obj)->isa_instptr();
8894     assert(tinst != nullptr, "digestBase_obj is not instance???");
8895     assert(tinst->is_loaded(), "DigestBase is not loaded");
8896 
8897     ciKlass* klass_digestBase = tinst->instance_klass()->find_klass(ciSymbol::make(klass_digestBase_name));
8898     assert(klass_digestBase->is_loaded(), "predicate checks that this class is loaded");
8899     ciInstanceKlass* instklass_digestBase = klass_digestBase->as_instance_klass();
8900     return inline_digestBase_implCompressMB(digestBase_obj, instklass_digestBase, elem_type, stub_addr, stub_name, src_start, ofs, limit);
8901   }
8902   return false;
8903 }
8904 
8905 //------------------------------inline_digestBase_implCompressMB-----------------------
8906 bool LibraryCallKit::inline_digestBase_implCompressMB(Node* digestBase_obj, ciInstanceKlass* instklass_digestBase,
8907                                                       BasicType elem_type, address stubAddr, const char *stubName,
8908                                                       Node* src_start, Node* ofs, Node* limit) {
8909   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_digestBase);
8910   const TypeOopPtr* xtype = aklass->cast_to_exactness(false)->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
8911   Node* digest_obj = new CheckCastPPNode(control(), digestBase_obj, xtype);
8912   digest_obj = _gvn.transform(digest_obj);
8913 
8914   Node* state = get_state_from_digest_object(digest_obj, elem_type);
8915   if (state == nullptr) return false;
8916 
8917   Node* block_size = nullptr;
8918   if (strcmp("sha3_implCompressMB", stubName) == 0) {
8919     block_size = get_block_size_from_digest_object(digest_obj);
8920     if (block_size == nullptr) return false;
8921   }
8922 
8923   // Call the stub.
8924   Node* call;
8925   if (block_size == nullptr) {
8926     call = make_runtime_call(RC_LEAF|RC_NO_FP,
8927                              OptoRuntime::digestBase_implCompressMB_Type(false),
8928                              stubAddr, stubName, TypePtr::BOTTOM,
8929                              src_start, state, ofs, limit);
8930   } else {
8931      call = make_runtime_call(RC_LEAF|RC_NO_FP,
8932                              OptoRuntime::digestBase_implCompressMB_Type(true),
8933                              stubAddr, stubName, TypePtr::BOTTOM,
8934                              src_start, state, block_size, ofs, limit);
8935   }
8936 
8937   // return ofs (int)
8938   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
8939   set_result(result);
8940 
8941   return true;
8942 }
8943 
8944 //------------------------------inline_galoisCounterMode_AESCrypt-----------------------
8945 bool LibraryCallKit::inline_galoisCounterMode_AESCrypt() {
8946   assert(UseAES, "need AES instruction support");
8947   address stubAddr = nullptr;
8948   const char *stubName = nullptr;
8949   stubAddr = StubRoutines::galoisCounterMode_AESCrypt();
8950   stubName = "galoisCounterMode_AESCrypt";
8951 
8952   if (stubAddr == nullptr) return false;
8953 
8954   Node* in      = argument(0);
8955   Node* inOfs   = argument(1);
8956   Node* len     = argument(2);
8957   Node* ct      = argument(3);
8958   Node* ctOfs   = argument(4);
8959   Node* out     = argument(5);
8960   Node* outOfs  = argument(6);
8961   Node* gctr_object = argument(7);
8962   Node* ghash_object = argument(8);
8963 
8964   // (1) in, ct and out are arrays.
8965   const TypeAryPtr* in_type = in->Value(&_gvn)->isa_aryptr();
8966   const TypeAryPtr* ct_type = ct->Value(&_gvn)->isa_aryptr();
8967   const TypeAryPtr* out_type = out->Value(&_gvn)->isa_aryptr();
8968   assert( in_type != nullptr &&  in_type->elem() != Type::BOTTOM &&
8969           ct_type != nullptr &&  ct_type->elem() != Type::BOTTOM &&
8970          out_type != nullptr && out_type->elem() != Type::BOTTOM, "args are strange");
8971 
8972   // checks are the responsibility of the caller
8973   Node* in_start = in;
8974   Node* ct_start = ct;
8975   Node* out_start = out;
8976   if (inOfs != nullptr || ctOfs != nullptr || outOfs != nullptr) {
8977     assert(inOfs != nullptr && ctOfs != nullptr && outOfs != nullptr, "");
8978     in_start = array_element_address(in, inOfs, T_BYTE);
8979     ct_start = array_element_address(ct, ctOfs, T_BYTE);
8980     out_start = array_element_address(out, outOfs, T_BYTE);
8981   }
8982 
8983   // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
8984   // (because of the predicated logic executed earlier).
8985   // so we cast it here safely.
8986   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
8987   Node* embeddedCipherObj = load_field_from_object(gctr_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8988   Node* counter = load_field_from_object(gctr_object, "counter", "[B");
8989   Node* subkeyHtbl = load_field_from_object(ghash_object, "subkeyHtbl", "[J");
8990   Node* state = load_field_from_object(ghash_object, "state", "[J");
8991 
8992   if (embeddedCipherObj == nullptr || counter == nullptr || subkeyHtbl == nullptr || state == nullptr) {
8993     return false;
8994   }
8995   // cast it to what we know it will be at runtime
8996   const TypeInstPtr* tinst = _gvn.type(gctr_object)->isa_instptr();
8997   assert(tinst != nullptr, "GCTR obj is null");
8998   assert(tinst->is_loaded(), "GCTR obj is not loaded");
8999   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AESCrypt"));
9000   assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
9001   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
9002   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
9003   const TypeOopPtr* xtype = aklass->as_instance_type();
9004   Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
9005   aescrypt_object = _gvn.transform(aescrypt_object);
9006   // we need to get the start of the aescrypt_object's expanded key array
9007   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object);
9008   if (k_start == nullptr) return false;
9009   // similarly, get the start address of the r vector
9010   Node* cnt_start = array_element_address(counter, intcon(0), T_BYTE);
9011   Node* state_start = array_element_address(state, intcon(0), T_LONG);
9012   Node* subkeyHtbl_start = array_element_address(subkeyHtbl, intcon(0), T_LONG);
9013 
9014 
9015   // Call the stub, passing params
9016   Node* gcmCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
9017                                OptoRuntime::galoisCounterMode_aescrypt_Type(),
9018                                stubAddr, stubName, TypePtr::BOTTOM,
9019                                in_start, len, ct_start, out_start, k_start, state_start, subkeyHtbl_start, cnt_start);
9020 
9021   // return cipher length (int)
9022   Node* retvalue = _gvn.transform(new ProjNode(gcmCrypt, TypeFunc::Parms));
9023   set_result(retvalue);
9024 
9025   return true;
9026 }
9027 
9028 //----------------------------inline_galoisCounterMode_AESCrypt_predicate----------------------------
9029 // Return node representing slow path of predicate check.
9030 // the pseudo code we want to emulate with this predicate is:
9031 // for encryption:
9032 //    if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
9033 // for decryption:
9034 //    if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
9035 //    note cipher==plain is more conservative than the original java code but that's OK
9036 //
9037 
9038 Node* LibraryCallKit::inline_galoisCounterMode_AESCrypt_predicate() {
9039   // The receiver was checked for null already.
9040   Node* objGCTR = argument(7);
9041   // Load embeddedCipher field of GCTR object.
9042   Node* embeddedCipherObj = load_field_from_object(objGCTR, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
9043   assert(embeddedCipherObj != nullptr, "embeddedCipherObj is null");
9044 
9045   // get AESCrypt klass for instanceOf check
9046   // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
9047   // will have same classloader as CipherBlockChaining object
9048   const TypeInstPtr* tinst = _gvn.type(objGCTR)->isa_instptr();
9049   assert(tinst != nullptr, "GCTR obj is null");
9050   assert(tinst->is_loaded(), "GCTR obj is not loaded");
9051 
9052   // we want to do an instanceof comparison against the AESCrypt class
9053   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AESCrypt"));
9054   if (!klass_AESCrypt->is_loaded()) {
9055     // if AESCrypt is not even loaded, we never take the intrinsic fast path
9056     Node* ctrl = control();
9057     set_control(top()); // no regular fast path
9058     return ctrl;
9059   }
9060 
9061   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
9062   Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
9063   Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
9064   Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
9065   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
9066 
9067   return instof_false; // even if it is null
9068 }
9069 
9070 //------------------------------get_state_from_digest_object-----------------------
9071 Node * LibraryCallKit::get_state_from_digest_object(Node *digest_object, BasicType elem_type) {
9072   const char* state_type;
9073   switch (elem_type) {
9074     case T_BYTE: state_type = "[B"; break;
9075     case T_INT:  state_type = "[I"; break;
9076     case T_LONG: state_type = "[J"; break;
9077     default: ShouldNotReachHere();
9078   }
9079   Node* digest_state = load_field_from_object(digest_object, "state", state_type);
9080   assert (digest_state != nullptr, "wrong version of sun.security.provider.MD5/SHA/SHA2/SHA5/SHA3");
9081   if (digest_state == nullptr) return (Node *) nullptr;
9082 
9083   // now have the array, need to get the start address of the state array
9084   Node* state = array_element_address(digest_state, intcon(0), elem_type);
9085   return state;
9086 }
9087 
9088 //------------------------------get_block_size_from_sha3_object----------------------------------
9089 Node * LibraryCallKit::get_block_size_from_digest_object(Node *digest_object) {
9090   Node* block_size = load_field_from_object(digest_object, "blockSize", "I");
9091   assert (block_size != nullptr, "sanity");
9092   return block_size;
9093 }
9094 
9095 //----------------------------inline_digestBase_implCompressMB_predicate----------------------------
9096 // Return node representing slow path of predicate check.
9097 // the pseudo code we want to emulate with this predicate is:
9098 //    if (digestBaseObj instanceof MD5/SHA/SHA2/SHA5/SHA3) do_intrinsic, else do_javapath
9099 //
9100 Node* LibraryCallKit::inline_digestBase_implCompressMB_predicate(int predicate) {
9101   assert(UseMD5Intrinsics || UseSHA1Intrinsics || UseSHA256Intrinsics || UseSHA512Intrinsics || UseSHA3Intrinsics,
9102          "need MD5/SHA1/SHA256/SHA512/SHA3 instruction support");
9103   assert((uint)predicate < 5, "sanity");
9104 
9105   // The receiver was checked for null already.
9106   Node* digestBaseObj = argument(0);
9107 
9108   // get DigestBase klass for instanceOf check
9109   const TypeInstPtr* tinst = _gvn.type(digestBaseObj)->isa_instptr();
9110   assert(tinst != nullptr, "digestBaseObj is null");
9111   assert(tinst->is_loaded(), "DigestBase is not loaded");
9112 
9113   const char* klass_name = nullptr;
9114   switch (predicate) {
9115   case 0:
9116     if (UseMD5Intrinsics) {
9117       // we want to do an instanceof comparison against the MD5 class
9118       klass_name = "sun/security/provider/MD5";
9119     }
9120     break;
9121   case 1:
9122     if (UseSHA1Intrinsics) {
9123       // we want to do an instanceof comparison against the SHA class
9124       klass_name = "sun/security/provider/SHA";
9125     }
9126     break;
9127   case 2:
9128     if (UseSHA256Intrinsics) {
9129       // we want to do an instanceof comparison against the SHA2 class
9130       klass_name = "sun/security/provider/SHA2";
9131     }
9132     break;
9133   case 3:
9134     if (UseSHA512Intrinsics) {
9135       // we want to do an instanceof comparison against the SHA5 class
9136       klass_name = "sun/security/provider/SHA5";
9137     }
9138     break;
9139   case 4:
9140     if (UseSHA3Intrinsics) {
9141       // we want to do an instanceof comparison against the SHA3 class
9142       klass_name = "sun/security/provider/SHA3";
9143     }
9144     break;
9145   default:
9146     fatal("unknown SHA intrinsic predicate: %d", predicate);
9147   }
9148 
9149   ciKlass* klass = nullptr;
9150   if (klass_name != nullptr) {
9151     klass = tinst->instance_klass()->find_klass(ciSymbol::make(klass_name));
9152   }
9153   if ((klass == nullptr) || !klass->is_loaded()) {
9154     // if none of MD5/SHA/SHA2/SHA5 is loaded, we never take the intrinsic fast path
9155     Node* ctrl = control();
9156     set_control(top()); // no intrinsic path
9157     return ctrl;
9158   }
9159   ciInstanceKlass* instklass = klass->as_instance_klass();
9160 
9161   Node* instof = gen_instanceof(digestBaseObj, makecon(TypeKlassPtr::make(instklass)));
9162   Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
9163   Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
9164   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
9165 
9166   return instof_false;  // even if it is null
9167 }
9168 
9169 //-------------inline_fma-----------------------------------
9170 bool LibraryCallKit::inline_fma(vmIntrinsics::ID id) {
9171   Node *a = nullptr;
9172   Node *b = nullptr;
9173   Node *c = nullptr;
9174   Node* result = nullptr;
9175   switch (id) {
9176   case vmIntrinsics::_fmaD:
9177     assert(callee()->signature()->size() == 6, "fma has 3 parameters of size 2 each.");
9178     // no receiver since it is static method
9179     a = argument(0);
9180     b = argument(2);
9181     c = argument(4);
9182     result = _gvn.transform(new FmaDNode(a, b, c));
9183     break;
9184   case vmIntrinsics::_fmaF:
9185     assert(callee()->signature()->size() == 3, "fma has 3 parameters of size 1 each.");
9186     a = argument(0);
9187     b = argument(1);
9188     c = argument(2);
9189     result = _gvn.transform(new FmaFNode(a, b, c));
9190     break;
9191   default:
9192     fatal_unexpected_iid(id);  break;
9193   }
9194   set_result(result);
9195   return true;
9196 }
9197 
9198 bool LibraryCallKit::inline_character_compare(vmIntrinsics::ID id) {
9199   // argument(0) is receiver
9200   Node* codePoint = argument(1);
9201   Node* n = nullptr;
9202 
9203   switch (id) {
9204     case vmIntrinsics::_isDigit :
9205       n = new DigitNode(control(), codePoint);
9206       break;
9207     case vmIntrinsics::_isLowerCase :
9208       n = new LowerCaseNode(control(), codePoint);
9209       break;
9210     case vmIntrinsics::_isUpperCase :
9211       n = new UpperCaseNode(control(), codePoint);
9212       break;
9213     case vmIntrinsics::_isWhitespace :
9214       n = new WhitespaceNode(control(), codePoint);
9215       break;
9216     default:
9217       fatal_unexpected_iid(id);
9218   }
9219 
9220   set_result(_gvn.transform(n));
9221   return true;
9222 }
9223 
9224 bool LibraryCallKit::inline_profileBoolean() {
9225   Node* counts = argument(1);
9226   const TypeAryPtr* ary = nullptr;
9227   ciArray* aobj = nullptr;
9228   if (counts->is_Con()
9229       && (ary = counts->bottom_type()->isa_aryptr()) != nullptr
9230       && (aobj = ary->const_oop()->as_array()) != nullptr
9231       && (aobj->length() == 2)) {
9232     // Profile is int[2] where [0] and [1] correspond to false and true value occurrences respectively.
9233     jint false_cnt = aobj->element_value(0).as_int();
9234     jint  true_cnt = aobj->element_value(1).as_int();
9235 
9236     if (C->log() != nullptr) {
9237       C->log()->elem("observe source='profileBoolean' false='%d' true='%d'",
9238                      false_cnt, true_cnt);
9239     }
9240 
9241     if (false_cnt + true_cnt == 0) {
9242       // According to profile, never executed.
9243       uncommon_trap_exact(Deoptimization::Reason_intrinsic,
9244                           Deoptimization::Action_reinterpret);
9245       return true;
9246     }
9247 
9248     // result is a boolean (0 or 1) and its profile (false_cnt & true_cnt)
9249     // is a number of each value occurrences.
9250     Node* result = argument(0);
9251     if (false_cnt == 0 || true_cnt == 0) {
9252       // According to profile, one value has been never seen.
9253       int expected_val = (false_cnt == 0) ? 1 : 0;
9254 
9255       Node* cmp  = _gvn.transform(new CmpINode(result, intcon(expected_val)));
9256       Node* test = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
9257 
9258       IfNode* check = create_and_map_if(control(), test, PROB_ALWAYS, COUNT_UNKNOWN);
9259       Node* fast_path = _gvn.transform(new IfTrueNode(check));
9260       Node* slow_path = _gvn.transform(new IfFalseNode(check));
9261 
9262       { // Slow path: uncommon trap for never seen value and then reexecute
9263         // MethodHandleImpl::profileBoolean() to bump the count, so JIT knows
9264         // the value has been seen at least once.
9265         PreserveJVMState pjvms(this);
9266         PreserveReexecuteState preexecs(this);
9267         jvms()->set_should_reexecute(true);
9268 
9269         set_control(slow_path);
9270         set_i_o(i_o());
9271 
9272         uncommon_trap_exact(Deoptimization::Reason_intrinsic,
9273                             Deoptimization::Action_reinterpret);
9274       }
9275       // The guard for never seen value enables sharpening of the result and
9276       // returning a constant. It allows to eliminate branches on the same value
9277       // later on.
9278       set_control(fast_path);
9279       result = intcon(expected_val);
9280     }
9281     // Stop profiling.
9282     // MethodHandleImpl::profileBoolean() has profiling logic in its bytecode.
9283     // By replacing method body with profile data (represented as ProfileBooleanNode
9284     // on IR level) we effectively disable profiling.
9285     // It enables full speed execution once optimized code is generated.
9286     Node* profile = _gvn.transform(new ProfileBooleanNode(result, false_cnt, true_cnt));
9287     C->record_for_igvn(profile);
9288     set_result(profile);
9289     return true;
9290   } else {
9291     // Continue profiling.
9292     // Profile data isn't available at the moment. So, execute method's bytecode version.
9293     // Usually, when GWT LambdaForms are profiled it means that a stand-alone nmethod
9294     // is compiled and counters aren't available since corresponding MethodHandle
9295     // isn't a compile-time constant.
9296     return false;
9297   }
9298 }
9299 
9300 bool LibraryCallKit::inline_isCompileConstant() {
9301   Node* n = argument(0);
9302   set_result(n->is_Con() ? intcon(1) : intcon(0));
9303   return true;
9304 }
9305 
9306 //------------------------------- inline_getObjectSize --------------------------------------
9307 //
9308 // Calculate the runtime size of the object/array.
9309 //   native long sun.instrument.InstrumentationImpl.getObjectSize0(long nativeAgent, Object objectToSize);
9310 //
9311 bool LibraryCallKit::inline_getObjectSize() {
9312   Node* obj = argument(3);
9313   Node* klass_node = load_object_klass(obj);
9314 
9315   jint  layout_con = Klass::_lh_neutral_value;
9316   Node* layout_val = get_layout_helper(klass_node, layout_con);
9317   int   layout_is_con = (layout_val == nullptr);
9318 
9319   if (layout_is_con) {
9320     // Layout helper is constant, can figure out things at compile time.
9321 
9322     if (Klass::layout_helper_is_instance(layout_con)) {
9323       // Instance case:  layout_con contains the size itself.
9324       Node *size = longcon(Klass::layout_helper_size_in_bytes(layout_con));
9325       set_result(size);
9326     } else {
9327       // Array case: size is round(header + element_size*arraylength).
9328       // Since arraylength is different for every array instance, we have to
9329       // compute the whole thing at runtime.
9330 
9331       Node* arr_length = load_array_length(obj);
9332 
9333       int round_mask = MinObjAlignmentInBytes - 1;
9334       int hsize  = Klass::layout_helper_header_size(layout_con);
9335       int eshift = Klass::layout_helper_log2_element_size(layout_con);
9336 
9337       if ((round_mask & ~right_n_bits(eshift)) == 0) {
9338         round_mask = 0;  // strength-reduce it if it goes away completely
9339       }
9340       assert((hsize & right_n_bits(eshift)) == 0, "hsize is pre-rounded");
9341       Node* header_size = intcon(hsize + round_mask);
9342 
9343       Node* lengthx = ConvI2X(arr_length);
9344       Node* headerx = ConvI2X(header_size);
9345 
9346       Node* abody = lengthx;
9347       if (eshift != 0) {
9348         abody = _gvn.transform(new LShiftXNode(lengthx, intcon(eshift)));
9349       }
9350       Node* size = _gvn.transform( new AddXNode(headerx, abody) );
9351       if (round_mask != 0) {
9352         size = _gvn.transform( new AndXNode(size, MakeConX(~round_mask)) );
9353       }
9354       size = ConvX2L(size);
9355       set_result(size);
9356     }
9357   } else {
9358     // Layout helper is not constant, need to test for array-ness at runtime.
9359 
9360     enum { _instance_path = 1, _array_path, PATH_LIMIT };
9361     RegionNode* result_reg = new RegionNode(PATH_LIMIT);
9362     PhiNode* result_val = new PhiNode(result_reg, TypeLong::LONG);
9363     record_for_igvn(result_reg);
9364 
9365     Node* array_ctl = generate_array_guard(klass_node, nullptr, &obj);
9366     if (array_ctl != nullptr) {
9367       // Array case: size is round(header + element_size*arraylength).
9368       // Since arraylength is different for every array instance, we have to
9369       // compute the whole thing at runtime.
9370 
9371       PreserveJVMState pjvms(this);
9372       set_control(array_ctl);
9373       Node* arr_length = load_array_length(obj);
9374 
9375       int round_mask = MinObjAlignmentInBytes - 1;
9376       Node* mask = intcon(round_mask);
9377 
9378       Node* hss = intcon(Klass::_lh_header_size_shift);
9379       Node* hsm = intcon(Klass::_lh_header_size_mask);
9380       Node* header_size = _gvn.transform(new URShiftINode(layout_val, hss));
9381       header_size = _gvn.transform(new AndINode(header_size, hsm));
9382       header_size = _gvn.transform(new AddINode(header_size, mask));
9383 
9384       // There is no need to mask or shift this value.
9385       // The semantics of LShiftINode include an implicit mask to 0x1F.
9386       assert(Klass::_lh_log2_element_size_shift == 0, "use shift in place");
9387       Node* elem_shift = layout_val;
9388 
9389       Node* lengthx = ConvI2X(arr_length);
9390       Node* headerx = ConvI2X(header_size);
9391 
9392       Node* abody = _gvn.transform(new LShiftXNode(lengthx, elem_shift));
9393       Node* size = _gvn.transform(new AddXNode(headerx, abody));
9394       if (round_mask != 0) {
9395         size = _gvn.transform(new AndXNode(size, MakeConX(~round_mask)));
9396       }
9397       size = ConvX2L(size);
9398 
9399       result_reg->init_req(_array_path, control());
9400       result_val->init_req(_array_path, size);
9401     }
9402 
9403     if (!stopped()) {
9404       // Instance case: the layout helper gives us instance size almost directly,
9405       // but we need to mask out the _lh_instance_slow_path_bit.
9406       Node* size = ConvI2X(layout_val);
9407       assert((int) Klass::_lh_instance_slow_path_bit < BytesPerLong, "clear bit");
9408       Node* mask = MakeConX(~(intptr_t) right_n_bits(LogBytesPerLong));
9409       size = _gvn.transform(new AndXNode(size, mask));
9410       size = ConvX2L(size);
9411 
9412       result_reg->init_req(_instance_path, control());
9413       result_val->init_req(_instance_path, size);
9414     }
9415 
9416     set_result(result_reg, result_val);
9417   }
9418 
9419   return true;
9420 }
9421 
9422 //------------------------------- inline_blackhole --------------------------------------
9423 //
9424 // Make sure all arguments to this node are alive.
9425 // This matches methods that were requested to be blackholed through compile commands.
9426 //
9427 bool LibraryCallKit::inline_blackhole() {
9428   assert(callee()->is_static(), "Should have been checked before: only static methods here");
9429   assert(callee()->is_empty(), "Should have been checked before: only empty methods here");
9430   assert(callee()->holder()->is_loaded(), "Should have been checked before: only methods for loaded classes here");
9431 
9432   // Blackhole node pinches only the control, not memory. This allows
9433   // the blackhole to be pinned in the loop that computes blackholed
9434   // values, but have no other side effects, like breaking the optimizations
9435   // across the blackhole.
9436 
9437   Node* bh = _gvn.transform(new BlackholeNode(control()));
9438   set_control(_gvn.transform(new ProjNode(bh, TypeFunc::Control)));
9439 
9440   // Bind call arguments as blackhole arguments to keep them alive
9441   uint nargs = callee()->arg_size();
9442   for (uint i = 0; i < nargs; i++) {
9443     bh->add_req(argument(i));
9444   }
9445 
9446   return true;
9447 }
9448 
9449 Node* LibraryCallKit::unbox_fp16_value(const TypeInstPtr* float16_box_type, ciField* field, Node* box) {
9450   const TypeInstPtr* box_type = _gvn.type(box)->isa_instptr();
9451   if (box_type == nullptr || box_type->instance_klass() != float16_box_type->instance_klass()) {
9452     return nullptr; // box klass is not Float16
9453   }
9454 
9455   // Null check; get notnull casted pointer
9456   Node* null_ctl = top();
9457   Node* not_null_box = null_check_oop(box, &null_ctl, true);
9458   // If not_null_box is dead, only null-path is taken
9459   if (stopped()) {
9460     set_control(null_ctl);
9461     return nullptr;
9462   }
9463   assert(not_null_box->bottom_type()->is_instptr()->maybe_null() == false, "");
9464   const TypePtr* adr_type = C->alias_type(field)->adr_type();
9465   Node* adr = basic_plus_adr(not_null_box, field->offset_in_bytes());
9466   return access_load_at(not_null_box, adr, adr_type, TypeInt::SHORT, T_SHORT, IN_HEAP);
9467 }
9468 
9469 Node* LibraryCallKit::box_fp16_value(const TypeInstPtr* float16_box_type, ciField* field, Node* value) {
9470   PreserveReexecuteState preexecs(this);
9471   jvms()->set_should_reexecute(true);
9472 
9473   const TypeKlassPtr* klass_type = float16_box_type->as_klass_type();
9474   Node* klass_node = makecon(klass_type);
9475   Node* box = new_instance(klass_node);
9476 
9477   Node* value_field = basic_plus_adr(box, field->offset_in_bytes());
9478   const TypePtr* value_adr_type = value_field->bottom_type()->is_ptr();
9479 
9480   Node* field_store = _gvn.transform(access_store_at(box,
9481                                                      value_field,
9482                                                      value_adr_type,
9483                                                      value,
9484                                                      TypeInt::SHORT,
9485                                                      T_SHORT,
9486                                                      IN_HEAP));
9487   set_memory(field_store, value_adr_type);
9488   return box;
9489 }
9490 
9491 bool LibraryCallKit::inline_fp16_operations(vmIntrinsics::ID id, int num_args) {
9492   if (!Matcher::match_rule_supported(Op_ReinterpretS2HF) ||
9493       !Matcher::match_rule_supported(Op_ReinterpretHF2S)) {
9494     return false;
9495   }
9496 
9497   const TypeInstPtr* box_type = _gvn.type(argument(0))->isa_instptr();
9498   if (box_type == nullptr || box_type->const_oop() == nullptr) {
9499     return false;
9500   }
9501 
9502   ciInstanceKlass* float16_klass = box_type->const_oop()->as_instance()->java_lang_Class_klass()->as_instance_klass();
9503   const TypeInstPtr* float16_box_type = TypeInstPtr::make_exact(TypePtr::NotNull, float16_klass);
9504   ciField* field = float16_klass->get_field_by_name(ciSymbols::value_name(),
9505                                                     ciSymbols::short_signature(),
9506                                                     false);
9507   assert(field != nullptr, "");
9508 
9509   // Transformed nodes
9510   Node* fld1 = nullptr;
9511   Node* fld2 = nullptr;
9512   Node* fld3 = nullptr;
9513   switch(num_args) {
9514     case 3:
9515       fld3 = unbox_fp16_value(float16_box_type, field, argument(3));
9516       if (fld3 == nullptr) {
9517         return false;
9518       }
9519       fld3 = _gvn.transform(new ReinterpretS2HFNode(fld3));
9520     // fall-through
9521     case 2:
9522       fld2 = unbox_fp16_value(float16_box_type, field, argument(2));
9523       if (fld2 == nullptr) {
9524         return false;
9525       }
9526       fld2 = _gvn.transform(new ReinterpretS2HFNode(fld2));
9527     // fall-through
9528     case 1:
9529       fld1 = unbox_fp16_value(float16_box_type, field, argument(1));
9530       if (fld1 == nullptr) {
9531         return false;
9532       }
9533       fld1 = _gvn.transform(new ReinterpretS2HFNode(fld1));
9534       break;
9535     default: fatal("Unsupported number of arguments %d", num_args);
9536   }
9537 
9538   Node* result = nullptr;
9539   switch (id) {
9540     // Unary operations
9541     case vmIntrinsics::_sqrt_float16:
9542       result = _gvn.transform(new SqrtHFNode(C, control(), fld1));
9543       break;
9544     // Ternary operations
9545     case vmIntrinsics::_fma_float16:
9546       result = _gvn.transform(new FmaHFNode(fld1, fld2, fld3));
9547       break;
9548     default:
9549       fatal_unexpected_iid(id);
9550       break;
9551   }
9552   result = _gvn.transform(new ReinterpretHF2SNode(result));
9553   set_result(box_fp16_value(float16_box_type, field, result));
9554   return true;
9555 }
9556