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