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