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