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