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