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