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