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