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