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