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