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