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