1 /*
    2  * Copyright (c) 1999, 2026, Oracle and/or its affiliates. All rights reserved.
    3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    4  *
    5  * This code is free software; you can redistribute it and/or modify it
    6  * under the terms of the GNU General Public License version 2 only, as
    7  * published by the Free Software Foundation.
    8  *
    9  * This code is distributed in the hope that it will be useful, but WITHOUT
   10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
   11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
   12  * version 2 for more details (a copy is included in the LICENSE file that
   13  * accompanied this code).
   14  *
   15  * You should have received a copy of the GNU General Public License version
   16  * 2 along with this work; if not, write to the Free Software Foundation,
   17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
   18  *
   19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
   20  * or visit www.oracle.com if you need additional information or have any
   21  * questions.
   22  *
   23  */
   24 
   25 #include "asm/macroAssembler.hpp"
   26 #include "ci/ciArrayKlass.hpp"
   27 #include "ci/ciFlatArrayKlass.hpp"
   28 #include "ci/ciInstanceKlass.hpp"
   29 #include "ci/ciSymbols.hpp"
   30 #include "ci/ciUtilities.inline.hpp"
   31 #include "classfile/vmIntrinsics.hpp"
   32 #include "compiler/compileBroker.hpp"
   33 #include "compiler/compileLog.hpp"
   34 #include "gc/shared/barrierSet.hpp"
   35 #include "gc/shared/c2/barrierSetC2.hpp"
   36 #include "jfr/support/jfrIntrinsics.hpp"
   37 #include "memory/resourceArea.hpp"
   38 #include "oops/accessDecorators.hpp"
   39 #include "oops/klass.inline.hpp"
   40 #include "oops/layoutKind.hpp"
   41 #include "oops/objArrayKlass.hpp"
   42 #include "opto/addnode.hpp"
   43 #include "opto/arraycopynode.hpp"
   44 #include "opto/c2compiler.hpp"
   45 #include "opto/castnode.hpp"
   46 #include "opto/cfgnode.hpp"
   47 #include "opto/convertnode.hpp"
   48 #include "opto/countbitsnode.hpp"
   49 #include "opto/graphKit.hpp"
   50 #include "opto/idealKit.hpp"
   51 #include "opto/inlinetypenode.hpp"
   52 #include "opto/library_call.hpp"
   53 #include "opto/mathexactnode.hpp"
   54 #include "opto/mulnode.hpp"
   55 #include "opto/narrowptrnode.hpp"
   56 #include "opto/opaquenode.hpp"
   57 #include "opto/opcodes.hpp"
   58 #include "opto/parse.hpp"
   59 #include "opto/rootnode.hpp"
   60 #include "opto/runtime.hpp"
   61 #include "opto/subnode.hpp"
   62 #include "opto/type.hpp"
   63 #include "opto/vectornode.hpp"
   64 #include "prims/jvmtiExport.hpp"
   65 #include "prims/jvmtiThreadState.hpp"
   66 #include "prims/unsafe.hpp"
   67 #include "runtime/globals.hpp"
   68 #include "runtime/jniHandles.inline.hpp"
   69 #include "runtime/mountUnmountDisabler.hpp"
   70 #include "runtime/objectMonitor.hpp"
   71 #include "runtime/sharedRuntime.hpp"
   72 #include "runtime/stubRoutines.hpp"
   73 #include "utilities/globalDefinitions.hpp"
   74 #include "utilities/macros.hpp"
   75 #include "utilities/powerOfTwo.hpp"
   76 
   77 //---------------------------make_vm_intrinsic----------------------------
   78 CallGenerator* Compile::make_vm_intrinsic(ciMethod* m, bool is_virtual) {
   79   vmIntrinsicID id = m->intrinsic_id();
   80   assert(id != vmIntrinsics::_none, "must be a VM intrinsic");
   81 
   82   if (!m->is_loaded()) {
   83     // Do not attempt to inline unloaded methods.
   84     return nullptr;
   85   }
   86 
   87   C2Compiler* compiler = (C2Compiler*)CompileBroker::compiler(CompLevel_full_optimization);
   88   bool is_available = false;
   89 
   90   {
   91     // For calling is_intrinsic_supported and is_intrinsic_disabled_by_flag
   92     // the compiler must transition to '_thread_in_vm' state because both
   93     // methods access VM-internal data.
   94     VM_ENTRY_MARK;
   95     methodHandle mh(THREAD, m->get_Method());
   96     is_available = compiler != nullptr && compiler->is_intrinsic_available(mh, C->directive());
   97     if (is_available && is_virtual) {
   98       is_available = vmIntrinsics::does_virtual_dispatch(id);
   99     }
  100   }
  101 
  102   if (is_available) {
  103     assert(id <= vmIntrinsics::LAST_COMPILER_INLINE, "caller responsibility");
  104     assert(id != vmIntrinsics::_Object_init && id != vmIntrinsics::_invoke, "enum out of order?");
  105     return new LibraryIntrinsic(m, is_virtual,
  106                                 vmIntrinsics::predicates_needed(id),
  107                                 vmIntrinsics::does_virtual_dispatch(id),
  108                                 id);
  109   } else {
  110     return nullptr;
  111   }
  112 }
  113 
  114 JVMState* LibraryIntrinsic::generate(JVMState* jvms) {
  115   LibraryCallKit kit(jvms, this);
  116   Compile* C = kit.C;
  117   int nodes = C->unique();
  118 #ifndef PRODUCT
  119   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
  120     char buf[1000];
  121     const char* str = vmIntrinsics::short_name_as_C_string(intrinsic_id(), buf, sizeof(buf));
  122     tty->print_cr("Intrinsic %s", str);
  123   }
  124 #endif
  125   ciMethod* callee = kit.callee();
  126   const int bci    = kit.bci();
  127 #ifdef ASSERT
  128   Node* ctrl = kit.control();
  129 #endif
  130   // Try to inline the intrinsic.
  131   if (callee->check_intrinsic_candidate() &&
  132       kit.try_to_inline(_last_predicate)) {
  133     const char *inline_msg = is_virtual() ? "(intrinsic, virtual)"
  134                                           : "(intrinsic)";
  135     CompileTask::print_inlining_ul(callee, jvms->depth() - 1, bci, InliningResult::SUCCESS, inline_msg);
  136     C->inline_printer()->record(callee, jvms, InliningResult::SUCCESS, inline_msg);
  137     C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_worked);
  138     if (C->log()) {
  139       C->log()->elem("intrinsic id='%s'%s nodes='%d'",
  140                      vmIntrinsics::name_at(intrinsic_id()),
  141                      (is_virtual() ? " virtual='1'" : ""),
  142                      C->unique() - nodes);
  143     }
  144     // Push the result from the inlined method onto the stack.
  145     kit.push_result();
  146     return kit.transfer_exceptions_into_jvms();
  147   }
  148 
  149   // The intrinsic bailed out
  150   assert(ctrl == kit.control(), "Control flow was added although the intrinsic bailed out");
  151   assert(jvms->map() == kit.map(), "Out of sync JVM state");
  152   if (jvms->has_method()) {
  153     // Not a root compile.
  154     const char* msg;
  155     if (callee->intrinsic_candidate()) {
  156       msg = is_virtual() ? "failed to inline (intrinsic, virtual)" : "failed to inline (intrinsic)";
  157     } else {
  158       msg = is_virtual() ? "failed to inline (intrinsic, virtual), method not annotated"
  159                          : "failed to inline (intrinsic), method not annotated";
  160     }
  161     CompileTask::print_inlining_ul(callee, jvms->depth() - 1, bci, InliningResult::FAILURE, msg);
  162     C->inline_printer()->record(callee, jvms, InliningResult::FAILURE, msg);
  163   } else {
  164     // Root compile
  165     ResourceMark rm;
  166     stringStream msg_stream;
  167     msg_stream.print("Did not generate intrinsic %s%s at bci:%d in",
  168                      vmIntrinsics::name_at(intrinsic_id()),
  169                      is_virtual() ? " (virtual)" : "", bci);
  170     const char *msg = msg_stream.freeze();
  171     log_debug(jit, inlining)("%s", msg);
  172     if (C->print_intrinsics() || C->print_inlining()) {
  173       tty->print("%s", msg);
  174     }
  175   }
  176   C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_failed);
  177 
  178   return nullptr;
  179 }
  180 
  181 Node* LibraryIntrinsic::generate_predicate(JVMState* jvms, int predicate) {
  182   LibraryCallKit kit(jvms, this);
  183   Compile* C = kit.C;
  184   int nodes = C->unique();
  185   _last_predicate = predicate;
  186 #ifndef PRODUCT
  187   assert(is_predicated() && predicate < predicates_count(), "sanity");
  188   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
  189     char buf[1000];
  190     const char* str = vmIntrinsics::short_name_as_C_string(intrinsic_id(), buf, sizeof(buf));
  191     tty->print_cr("Predicate for intrinsic %s", str);
  192   }
  193 #endif
  194   ciMethod* callee = kit.callee();
  195   const int bci    = kit.bci();
  196 
  197   Node* slow_ctl = kit.try_to_predicate(predicate);
  198   if (!kit.failing()) {
  199     const char *inline_msg = is_virtual() ? "(intrinsic, virtual, predicate)"
  200                                           : "(intrinsic, predicate)";
  201     CompileTask::print_inlining_ul(callee, jvms->depth() - 1, bci, InliningResult::SUCCESS, inline_msg);
  202     C->inline_printer()->record(callee, jvms, InliningResult::SUCCESS, inline_msg);
  203 
  204     C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_worked);
  205     if (C->log()) {
  206       C->log()->elem("predicate_intrinsic id='%s'%s nodes='%d'",
  207                      vmIntrinsics::name_at(intrinsic_id()),
  208                      (is_virtual() ? " virtual='1'" : ""),
  209                      C->unique() - nodes);
  210     }
  211     return slow_ctl; // Could be null if the check folds.
  212   }
  213 
  214   // The intrinsic bailed out
  215   if (jvms->has_method()) {
  216     // Not a root compile.
  217     const char* msg = "failed to generate predicate for intrinsic";
  218     CompileTask::print_inlining_ul(kit.callee(), jvms->depth() - 1, bci, InliningResult::FAILURE, msg);
  219     C->inline_printer()->record(kit.callee(), jvms, InliningResult::FAILURE, msg);
  220   } else {
  221     // Root compile
  222     ResourceMark rm;
  223     stringStream msg_stream;
  224     msg_stream.print("Did not generate intrinsic %s%s at bci:%d in",
  225                      vmIntrinsics::name_at(intrinsic_id()),
  226                      is_virtual() ? " (virtual)" : "", bci);
  227     const char *msg = msg_stream.freeze();
  228     log_debug(jit, inlining)("%s", msg);
  229     C->inline_printer()->record(kit.callee(), jvms, InliningResult::FAILURE, msg);
  230   }
  231   C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_failed);
  232   return nullptr;
  233 }
  234 
  235 bool LibraryCallKit::try_to_inline(int predicate) {
  236   // Handle symbolic names for otherwise undistinguished boolean switches:
  237   const bool is_store       = true;
  238   const bool is_compress    = true;
  239   const bool is_static      = true;
  240   const bool is_volatile    = true;
  241 
  242   if (!jvms()->has_method()) {
  243     // Root JVMState has a null method.
  244     assert(map()->memory()->Opcode() == Op_Parm, "");
  245     // Insert the memory aliasing node
  246     set_all_memory(reset_memory());
  247   }
  248   assert(merged_memory(), "");
  249 
  250   switch (intrinsic_id()) {
  251   case vmIntrinsics::_hashCode:                 return inline_native_hashcode(intrinsic()->is_virtual(), !is_static);
  252   case vmIntrinsics::_identityHashCode:         return inline_native_hashcode(/*!virtual*/ false,         is_static);
  253   case vmIntrinsics::_getClass:                 return inline_native_getClass();
  254 
  255   case vmIntrinsics::_ceil:
  256   case vmIntrinsics::_floor:
  257   case vmIntrinsics::_rint:
  258   case vmIntrinsics::_dsin:
  259   case vmIntrinsics::_dcos:
  260   case vmIntrinsics::_dtan:
  261   case vmIntrinsics::_dsinh:
  262   case vmIntrinsics::_dtanh:
  263   case vmIntrinsics::_dcbrt:
  264   case vmIntrinsics::_dabs:
  265   case vmIntrinsics::_fabs:
  266   case vmIntrinsics::_iabs:
  267   case vmIntrinsics::_labs:
  268   case vmIntrinsics::_datan2:
  269   case vmIntrinsics::_dsqrt:
  270   case vmIntrinsics::_dsqrt_strict:
  271   case vmIntrinsics::_dexp:
  272   case vmIntrinsics::_dlog:
  273   case vmIntrinsics::_dlog10:
  274   case vmIntrinsics::_dpow:
  275   case vmIntrinsics::_dcopySign:
  276   case vmIntrinsics::_fcopySign:
  277   case vmIntrinsics::_dsignum:
  278   case vmIntrinsics::_roundF:
  279   case vmIntrinsics::_roundD:
  280   case vmIntrinsics::_fsignum:                  return inline_math_native(intrinsic_id());
  281 
  282   case vmIntrinsics::_notify:
  283   case vmIntrinsics::_notifyAll:
  284     return inline_notify(intrinsic_id());
  285 
  286   case vmIntrinsics::_addExactI:                return inline_math_addExactI(false /* add */);
  287   case vmIntrinsics::_addExactL:                return inline_math_addExactL(false /* add */);
  288   case vmIntrinsics::_decrementExactI:          return inline_math_subtractExactI(true /* decrement */);
  289   case vmIntrinsics::_decrementExactL:          return inline_math_subtractExactL(true /* decrement */);
  290   case vmIntrinsics::_incrementExactI:          return inline_math_addExactI(true /* increment */);
  291   case vmIntrinsics::_incrementExactL:          return inline_math_addExactL(true /* increment */);
  292   case vmIntrinsics::_multiplyExactI:           return inline_math_multiplyExactI();
  293   case vmIntrinsics::_multiplyExactL:           return inline_math_multiplyExactL();
  294   case vmIntrinsics::_multiplyHigh:             return inline_math_multiplyHigh();
  295   case vmIntrinsics::_unsignedMultiplyHigh:     return inline_math_unsignedMultiplyHigh();
  296   case vmIntrinsics::_negateExactI:             return inline_math_negateExactI();
  297   case vmIntrinsics::_negateExactL:             return inline_math_negateExactL();
  298   case vmIntrinsics::_subtractExactI:           return inline_math_subtractExactI(false /* subtract */);
  299   case vmIntrinsics::_subtractExactL:           return inline_math_subtractExactL(false /* subtract */);
  300 
  301   case vmIntrinsics::_arraycopy:                return inline_arraycopy();
  302 
  303   case vmIntrinsics::_arraySort:                return inline_array_sort();
  304   case vmIntrinsics::_arrayPartition:           return inline_array_partition();
  305 
  306   case vmIntrinsics::_compareToL:               return inline_string_compareTo(StrIntrinsicNode::LL);
  307   case vmIntrinsics::_compareToU:               return inline_string_compareTo(StrIntrinsicNode::UU);
  308   case vmIntrinsics::_compareToLU:              return inline_string_compareTo(StrIntrinsicNode::LU);
  309   case vmIntrinsics::_compareToUL:              return inline_string_compareTo(StrIntrinsicNode::UL);
  310 
  311   case vmIntrinsics::_indexOfL:                 return inline_string_indexOf(StrIntrinsicNode::LL);
  312   case vmIntrinsics::_indexOfU:                 return inline_string_indexOf(StrIntrinsicNode::UU);
  313   case vmIntrinsics::_indexOfUL:                return inline_string_indexOf(StrIntrinsicNode::UL);
  314   case vmIntrinsics::_indexOfIL:                return inline_string_indexOfI(StrIntrinsicNode::LL);
  315   case vmIntrinsics::_indexOfIU:                return inline_string_indexOfI(StrIntrinsicNode::UU);
  316   case vmIntrinsics::_indexOfIUL:               return inline_string_indexOfI(StrIntrinsicNode::UL);
  317   case vmIntrinsics::_indexOfU_char:            return inline_string_indexOfChar(StrIntrinsicNode::U);
  318   case vmIntrinsics::_indexOfL_char:            return inline_string_indexOfChar(StrIntrinsicNode::L);
  319 
  320   case vmIntrinsics::_equalsL:                  return inline_string_equals(StrIntrinsicNode::LL);
  321 
  322   case vmIntrinsics::_vectorizedHashCode:       return inline_vectorizedHashCode();
  323 
  324   case vmIntrinsics::_toBytesStringU:           return inline_string_toBytesU();
  325   case vmIntrinsics::_getCharsStringU:          return inline_string_getCharsU();
  326   case vmIntrinsics::_getCharStringU:           return inline_string_char_access(!is_store);
  327   case vmIntrinsics::_putCharStringU:           return inline_string_char_access( is_store);
  328 
  329   case vmIntrinsics::_compressStringC:
  330   case vmIntrinsics::_compressStringB:          return inline_string_copy( is_compress);
  331   case vmIntrinsics::_inflateStringC:
  332   case vmIntrinsics::_inflateStringB:           return inline_string_copy(!is_compress);
  333 
  334   case vmIntrinsics::_getReference:             return inline_unsafe_access(!is_store, T_OBJECT,   Relaxed, false);
  335   case vmIntrinsics::_getBoolean:               return inline_unsafe_access(!is_store, T_BOOLEAN,  Relaxed, false);
  336   case vmIntrinsics::_getByte:                  return inline_unsafe_access(!is_store, T_BYTE,     Relaxed, false);
  337   case vmIntrinsics::_getShort:                 return inline_unsafe_access(!is_store, T_SHORT,    Relaxed, false);
  338   case vmIntrinsics::_getChar:                  return inline_unsafe_access(!is_store, T_CHAR,     Relaxed, false);
  339   case vmIntrinsics::_getInt:                   return inline_unsafe_access(!is_store, T_INT,      Relaxed, false);
  340   case vmIntrinsics::_getLong:                  return inline_unsafe_access(!is_store, T_LONG,     Relaxed, false);
  341   case vmIntrinsics::_getFloat:                 return inline_unsafe_access(!is_store, T_FLOAT,    Relaxed, false);
  342   case vmIntrinsics::_getDouble:                return inline_unsafe_access(!is_store, T_DOUBLE,   Relaxed, false);
  343 
  344   case vmIntrinsics::_putReference:             return inline_unsafe_access( is_store, T_OBJECT,   Relaxed, false);
  345   case vmIntrinsics::_putBoolean:               return inline_unsafe_access( is_store, T_BOOLEAN,  Relaxed, false);
  346   case vmIntrinsics::_putByte:                  return inline_unsafe_access( is_store, T_BYTE,     Relaxed, false);
  347   case vmIntrinsics::_putShort:                 return inline_unsafe_access( is_store, T_SHORT,    Relaxed, false);
  348   case vmIntrinsics::_putChar:                  return inline_unsafe_access( is_store, T_CHAR,     Relaxed, false);
  349   case vmIntrinsics::_putInt:                   return inline_unsafe_access( is_store, T_INT,      Relaxed, false);
  350   case vmIntrinsics::_putLong:                  return inline_unsafe_access( is_store, T_LONG,     Relaxed, false);
  351   case vmIntrinsics::_putFloat:                 return inline_unsafe_access( is_store, T_FLOAT,    Relaxed, false);
  352   case vmIntrinsics::_putDouble:                return inline_unsafe_access( is_store, T_DOUBLE,   Relaxed, false);
  353 
  354   case vmIntrinsics::_getReferenceVolatile:     return inline_unsafe_access(!is_store, T_OBJECT,   Volatile, false);
  355   case vmIntrinsics::_getBooleanVolatile:       return inline_unsafe_access(!is_store, T_BOOLEAN,  Volatile, false);
  356   case vmIntrinsics::_getByteVolatile:          return inline_unsafe_access(!is_store, T_BYTE,     Volatile, false);
  357   case vmIntrinsics::_getShortVolatile:         return inline_unsafe_access(!is_store, T_SHORT,    Volatile, false);
  358   case vmIntrinsics::_getCharVolatile:          return inline_unsafe_access(!is_store, T_CHAR,     Volatile, false);
  359   case vmIntrinsics::_getIntVolatile:           return inline_unsafe_access(!is_store, T_INT,      Volatile, false);
  360   case vmIntrinsics::_getLongVolatile:          return inline_unsafe_access(!is_store, T_LONG,     Volatile, false);
  361   case vmIntrinsics::_getFloatVolatile:         return inline_unsafe_access(!is_store, T_FLOAT,    Volatile, false);
  362   case vmIntrinsics::_getDoubleVolatile:        return inline_unsafe_access(!is_store, T_DOUBLE,   Volatile, false);
  363 
  364   case vmIntrinsics::_putReferenceVolatile:     return inline_unsafe_access( is_store, T_OBJECT,   Volatile, false);
  365   case vmIntrinsics::_putBooleanVolatile:       return inline_unsafe_access( is_store, T_BOOLEAN,  Volatile, false);
  366   case vmIntrinsics::_putByteVolatile:          return inline_unsafe_access( is_store, T_BYTE,     Volatile, false);
  367   case vmIntrinsics::_putShortVolatile:         return inline_unsafe_access( is_store, T_SHORT,    Volatile, false);
  368   case vmIntrinsics::_putCharVolatile:          return inline_unsafe_access( is_store, T_CHAR,     Volatile, false);
  369   case vmIntrinsics::_putIntVolatile:           return inline_unsafe_access( is_store, T_INT,      Volatile, false);
  370   case vmIntrinsics::_putLongVolatile:          return inline_unsafe_access( is_store, T_LONG,     Volatile, false);
  371   case vmIntrinsics::_putFloatVolatile:         return inline_unsafe_access( is_store, T_FLOAT,    Volatile, false);
  372   case vmIntrinsics::_putDoubleVolatile:        return inline_unsafe_access( is_store, T_DOUBLE,   Volatile, false);
  373 
  374   case vmIntrinsics::_getShortUnaligned:        return inline_unsafe_access(!is_store, T_SHORT,    Relaxed, true);
  375   case vmIntrinsics::_getCharUnaligned:         return inline_unsafe_access(!is_store, T_CHAR,     Relaxed, true);
  376   case vmIntrinsics::_getIntUnaligned:          return inline_unsafe_access(!is_store, T_INT,      Relaxed, true);
  377   case vmIntrinsics::_getLongUnaligned:         return inline_unsafe_access(!is_store, T_LONG,     Relaxed, true);
  378 
  379   case vmIntrinsics::_putShortUnaligned:        return inline_unsafe_access( is_store, T_SHORT,    Relaxed, true);
  380   case vmIntrinsics::_putCharUnaligned:         return inline_unsafe_access( is_store, T_CHAR,     Relaxed, true);
  381   case vmIntrinsics::_putIntUnaligned:          return inline_unsafe_access( is_store, T_INT,      Relaxed, true);
  382   case vmIntrinsics::_putLongUnaligned:         return inline_unsafe_access( is_store, T_LONG,     Relaxed, true);
  383 
  384   case vmIntrinsics::_getReferenceAcquire:      return inline_unsafe_access(!is_store, T_OBJECT,   Acquire, false);
  385   case vmIntrinsics::_getBooleanAcquire:        return inline_unsafe_access(!is_store, T_BOOLEAN,  Acquire, false);
  386   case vmIntrinsics::_getByteAcquire:           return inline_unsafe_access(!is_store, T_BYTE,     Acquire, false);
  387   case vmIntrinsics::_getShortAcquire:          return inline_unsafe_access(!is_store, T_SHORT,    Acquire, false);
  388   case vmIntrinsics::_getCharAcquire:           return inline_unsafe_access(!is_store, T_CHAR,     Acquire, false);
  389   case vmIntrinsics::_getIntAcquire:            return inline_unsafe_access(!is_store, T_INT,      Acquire, false);
  390   case vmIntrinsics::_getLongAcquire:           return inline_unsafe_access(!is_store, T_LONG,     Acquire, false);
  391   case vmIntrinsics::_getFloatAcquire:          return inline_unsafe_access(!is_store, T_FLOAT,    Acquire, false);
  392   case vmIntrinsics::_getDoubleAcquire:         return inline_unsafe_access(!is_store, T_DOUBLE,   Acquire, false);
  393 
  394   case vmIntrinsics::_putReferenceRelease:      return inline_unsafe_access( is_store, T_OBJECT,   Release, false);
  395   case vmIntrinsics::_putBooleanRelease:        return inline_unsafe_access( is_store, T_BOOLEAN,  Release, false);
  396   case vmIntrinsics::_putByteRelease:           return inline_unsafe_access( is_store, T_BYTE,     Release, false);
  397   case vmIntrinsics::_putShortRelease:          return inline_unsafe_access( is_store, T_SHORT,    Release, false);
  398   case vmIntrinsics::_putCharRelease:           return inline_unsafe_access( is_store, T_CHAR,     Release, false);
  399   case vmIntrinsics::_putIntRelease:            return inline_unsafe_access( is_store, T_INT,      Release, false);
  400   case vmIntrinsics::_putLongRelease:           return inline_unsafe_access( is_store, T_LONG,     Release, false);
  401   case vmIntrinsics::_putFloatRelease:          return inline_unsafe_access( is_store, T_FLOAT,    Release, false);
  402   case vmIntrinsics::_putDoubleRelease:         return inline_unsafe_access( is_store, T_DOUBLE,   Release, false);
  403 
  404   case vmIntrinsics::_getReferenceOpaque:       return inline_unsafe_access(!is_store, T_OBJECT,   Opaque, false);
  405   case vmIntrinsics::_getBooleanOpaque:         return inline_unsafe_access(!is_store, T_BOOLEAN,  Opaque, false);
  406   case vmIntrinsics::_getByteOpaque:            return inline_unsafe_access(!is_store, T_BYTE,     Opaque, false);
  407   case vmIntrinsics::_getShortOpaque:           return inline_unsafe_access(!is_store, T_SHORT,    Opaque, false);
  408   case vmIntrinsics::_getCharOpaque:            return inline_unsafe_access(!is_store, T_CHAR,     Opaque, false);
  409   case vmIntrinsics::_getIntOpaque:             return inline_unsafe_access(!is_store, T_INT,      Opaque, false);
  410   case vmIntrinsics::_getLongOpaque:            return inline_unsafe_access(!is_store, T_LONG,     Opaque, false);
  411   case vmIntrinsics::_getFloatOpaque:           return inline_unsafe_access(!is_store, T_FLOAT,    Opaque, false);
  412   case vmIntrinsics::_getDoubleOpaque:          return inline_unsafe_access(!is_store, T_DOUBLE,   Opaque, false);
  413 
  414   case vmIntrinsics::_putReferenceOpaque:       return inline_unsafe_access( is_store, T_OBJECT,   Opaque, false);
  415   case vmIntrinsics::_putBooleanOpaque:         return inline_unsafe_access( is_store, T_BOOLEAN,  Opaque, false);
  416   case vmIntrinsics::_putByteOpaque:            return inline_unsafe_access( is_store, T_BYTE,     Opaque, false);
  417   case vmIntrinsics::_putShortOpaque:           return inline_unsafe_access( is_store, T_SHORT,    Opaque, false);
  418   case vmIntrinsics::_putCharOpaque:            return inline_unsafe_access( is_store, T_CHAR,     Opaque, false);
  419   case vmIntrinsics::_putIntOpaque:             return inline_unsafe_access( is_store, T_INT,      Opaque, false);
  420   case vmIntrinsics::_putLongOpaque:            return inline_unsafe_access( is_store, T_LONG,     Opaque, false);
  421   case vmIntrinsics::_putFloatOpaque:           return inline_unsafe_access( is_store, T_FLOAT,    Opaque, false);
  422   case vmIntrinsics::_putDoubleOpaque:          return inline_unsafe_access( is_store, T_DOUBLE,   Opaque, false);
  423 
  424   case vmIntrinsics::_getFlatValue:             return inline_unsafe_flat_access(!is_store, Relaxed);
  425   case vmIntrinsics::_putFlatValue:             return inline_unsafe_flat_access( is_store, Relaxed);
  426 
  427   case vmIntrinsics::_compareAndSetReference:   return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap,      Volatile);
  428   case vmIntrinsics::_compareAndSetByte:        return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap,      Volatile);
  429   case vmIntrinsics::_compareAndSetShort:       return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap,      Volatile);
  430   case vmIntrinsics::_compareAndSetInt:         return inline_unsafe_load_store(T_INT,    LS_cmp_swap,      Volatile);
  431   case vmIntrinsics::_compareAndSetLong:        return inline_unsafe_load_store(T_LONG,   LS_cmp_swap,      Volatile);
  432 
  433   case vmIntrinsics::_weakCompareAndSetReferencePlain:     return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Relaxed);
  434   case vmIntrinsics::_weakCompareAndSetReferenceAcquire:   return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Acquire);
  435   case vmIntrinsics::_weakCompareAndSetReferenceRelease:   return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Release);
  436   case vmIntrinsics::_weakCompareAndSetReference:          return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Volatile);
  437   case vmIntrinsics::_weakCompareAndSetBytePlain:          return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap_weak, Relaxed);
  438   case vmIntrinsics::_weakCompareAndSetByteAcquire:        return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap_weak, Acquire);
  439   case vmIntrinsics::_weakCompareAndSetByteRelease:        return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap_weak, Release);
  440   case vmIntrinsics::_weakCompareAndSetByte:               return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap_weak, Volatile);
  441   case vmIntrinsics::_weakCompareAndSetShortPlain:         return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap_weak, Relaxed);
  442   case vmIntrinsics::_weakCompareAndSetShortAcquire:       return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap_weak, Acquire);
  443   case vmIntrinsics::_weakCompareAndSetShortRelease:       return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap_weak, Release);
  444   case vmIntrinsics::_weakCompareAndSetShort:              return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap_weak, Volatile);
  445   case vmIntrinsics::_weakCompareAndSetIntPlain:           return inline_unsafe_load_store(T_INT,    LS_cmp_swap_weak, Relaxed);
  446   case vmIntrinsics::_weakCompareAndSetIntAcquire:         return inline_unsafe_load_store(T_INT,    LS_cmp_swap_weak, Acquire);
  447   case vmIntrinsics::_weakCompareAndSetIntRelease:         return inline_unsafe_load_store(T_INT,    LS_cmp_swap_weak, Release);
  448   case vmIntrinsics::_weakCompareAndSetInt:                return inline_unsafe_load_store(T_INT,    LS_cmp_swap_weak, Volatile);
  449   case vmIntrinsics::_weakCompareAndSetLongPlain:          return inline_unsafe_load_store(T_LONG,   LS_cmp_swap_weak, Relaxed);
  450   case vmIntrinsics::_weakCompareAndSetLongAcquire:        return inline_unsafe_load_store(T_LONG,   LS_cmp_swap_weak, Acquire);
  451   case vmIntrinsics::_weakCompareAndSetLongRelease:        return inline_unsafe_load_store(T_LONG,   LS_cmp_swap_weak, Release);
  452   case vmIntrinsics::_weakCompareAndSetLong:               return inline_unsafe_load_store(T_LONG,   LS_cmp_swap_weak, Volatile);
  453 
  454   case vmIntrinsics::_compareAndExchangeReference:         return inline_unsafe_load_store(T_OBJECT, LS_cmp_exchange,  Volatile);
  455   case vmIntrinsics::_compareAndExchangeReferenceAcquire:  return inline_unsafe_load_store(T_OBJECT, LS_cmp_exchange,  Acquire);
  456   case vmIntrinsics::_compareAndExchangeReferenceRelease:  return inline_unsafe_load_store(T_OBJECT, LS_cmp_exchange,  Release);
  457   case vmIntrinsics::_compareAndExchangeByte:              return inline_unsafe_load_store(T_BYTE,   LS_cmp_exchange,  Volatile);
  458   case vmIntrinsics::_compareAndExchangeByteAcquire:       return inline_unsafe_load_store(T_BYTE,   LS_cmp_exchange,  Acquire);
  459   case vmIntrinsics::_compareAndExchangeByteRelease:       return inline_unsafe_load_store(T_BYTE,   LS_cmp_exchange,  Release);
  460   case vmIntrinsics::_compareAndExchangeShort:             return inline_unsafe_load_store(T_SHORT,  LS_cmp_exchange,  Volatile);
  461   case vmIntrinsics::_compareAndExchangeShortAcquire:      return inline_unsafe_load_store(T_SHORT,  LS_cmp_exchange,  Acquire);
  462   case vmIntrinsics::_compareAndExchangeShortRelease:      return inline_unsafe_load_store(T_SHORT,  LS_cmp_exchange,  Release);
  463   case vmIntrinsics::_compareAndExchangeInt:               return inline_unsafe_load_store(T_INT,    LS_cmp_exchange,  Volatile);
  464   case vmIntrinsics::_compareAndExchangeIntAcquire:        return inline_unsafe_load_store(T_INT,    LS_cmp_exchange,  Acquire);
  465   case vmIntrinsics::_compareAndExchangeIntRelease:        return inline_unsafe_load_store(T_INT,    LS_cmp_exchange,  Release);
  466   case vmIntrinsics::_compareAndExchangeLong:              return inline_unsafe_load_store(T_LONG,   LS_cmp_exchange,  Volatile);
  467   case vmIntrinsics::_compareAndExchangeLongAcquire:       return inline_unsafe_load_store(T_LONG,   LS_cmp_exchange,  Acquire);
  468   case vmIntrinsics::_compareAndExchangeLongRelease:       return inline_unsafe_load_store(T_LONG,   LS_cmp_exchange,  Release);
  469 
  470   case vmIntrinsics::_getAndAddByte:                    return inline_unsafe_load_store(T_BYTE,   LS_get_add,       Volatile);
  471   case vmIntrinsics::_getAndAddShort:                   return inline_unsafe_load_store(T_SHORT,  LS_get_add,       Volatile);
  472   case vmIntrinsics::_getAndAddInt:                     return inline_unsafe_load_store(T_INT,    LS_get_add,       Volatile);
  473   case vmIntrinsics::_getAndAddLong:                    return inline_unsafe_load_store(T_LONG,   LS_get_add,       Volatile);
  474 
  475   case vmIntrinsics::_getAndSetByte:                    return inline_unsafe_load_store(T_BYTE,   LS_get_set,       Volatile);
  476   case vmIntrinsics::_getAndSetShort:                   return inline_unsafe_load_store(T_SHORT,  LS_get_set,       Volatile);
  477   case vmIntrinsics::_getAndSetInt:                     return inline_unsafe_load_store(T_INT,    LS_get_set,       Volatile);
  478   case vmIntrinsics::_getAndSetLong:                    return inline_unsafe_load_store(T_LONG,   LS_get_set,       Volatile);
  479   case vmIntrinsics::_getAndSetReference:               return inline_unsafe_load_store(T_OBJECT, LS_get_set,       Volatile);
  480 
  481   case vmIntrinsics::_loadFence:
  482   case vmIntrinsics::_storeFence:
  483   case vmIntrinsics::_storeStoreFence:
  484   case vmIntrinsics::_fullFence:                return inline_unsafe_fence(intrinsic_id());
  485 
  486   case vmIntrinsics::_arrayInstanceBaseOffset:  return inline_arrayInstanceBaseOffset();
  487   case vmIntrinsics::_arrayInstanceIndexScale:  return inline_arrayInstanceIndexScale();
  488   case vmIntrinsics::_arrayLayout:              return inline_arrayLayout();
  489   case vmIntrinsics::_getFieldMap:              return inline_getFieldMap();
  490 
  491   case vmIntrinsics::_onSpinWait:               return inline_onspinwait();
  492 
  493   case vmIntrinsics::_currentCarrierThread:     return inline_native_currentCarrierThread();
  494   case vmIntrinsics::_currentThread:            return inline_native_currentThread();
  495   case vmIntrinsics::_setCurrentThread:         return inline_native_setCurrentThread();
  496 
  497   case vmIntrinsics::_scopedValueCache:          return inline_native_scopedValueCache();
  498   case vmIntrinsics::_setScopedValueCache:       return inline_native_setScopedValueCache();
  499 
  500   case vmIntrinsics::_Continuation_pin:          return inline_native_Continuation_pinning(false);
  501   case vmIntrinsics::_Continuation_unpin:        return inline_native_Continuation_pinning(true);
  502 
  503   case vmIntrinsics::_vthreadEndFirstTransition:    return inline_native_vthread_end_transition(CAST_FROM_FN_PTR(address, OptoRuntime::vthread_end_first_transition_Java()),
  504                                                                                                 "endFirstTransition", true);
  505   case vmIntrinsics::_vthreadStartFinalTransition:  return inline_native_vthread_start_transition(CAST_FROM_FN_PTR(address, OptoRuntime::vthread_start_final_transition_Java()),
  506                                                                                                   "startFinalTransition", true);
  507   case vmIntrinsics::_vthreadStartTransition:       return inline_native_vthread_start_transition(CAST_FROM_FN_PTR(address, OptoRuntime::vthread_start_transition_Java()),
  508                                                                                                   "startTransition", false);
  509   case vmIntrinsics::_vthreadEndTransition:         return inline_native_vthread_end_transition(CAST_FROM_FN_PTR(address, OptoRuntime::vthread_end_transition_Java()),
  510                                                                                                 "endTransition", false);
  511 #if INCLUDE_JVMTI
  512   case vmIntrinsics::_notifyJvmtiVThreadDisableSuspend: return inline_native_notify_jvmti_sync();
  513 #endif
  514 
  515 #ifdef JFR_HAVE_INTRINSICS
  516   case vmIntrinsics::_counterTime:              return inline_native_time_funcs(CAST_FROM_FN_PTR(address, JfrTime::time_function()), "counterTime");
  517   case vmIntrinsics::_getEventWriter:           return inline_native_getEventWriter();
  518   case vmIntrinsics::_jvm_commit:               return inline_native_jvm_commit();
  519   case vmIntrinsics::_tryUpdateEpochField:      return inline_native_try_update_epoch();
  520 #endif
  521   case vmIntrinsics::_currentTimeMillis:        return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeMillis), "currentTimeMillis");
  522   case vmIntrinsics::_nanoTime:                 return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeNanos), "nanoTime");
  523   case vmIntrinsics::_writeback0:               return inline_unsafe_writeback0();
  524   case vmIntrinsics::_writebackPreSync0:        return inline_unsafe_writebackSync0(true);
  525   case vmIntrinsics::_writebackPostSync0:       return inline_unsafe_writebackSync0(false);
  526   case vmIntrinsics::_allocateInstance:         return inline_unsafe_allocate();
  527   case vmIntrinsics::_copyMemory:               return inline_unsafe_copyMemory();
  528   case vmIntrinsics::_setMemory:                return inline_unsafe_setMemory();
  529   case vmIntrinsics::_getLength:                return inline_native_getLength();
  530   case vmIntrinsics::_copyOf:                   return inline_array_copyOf(false);
  531   case vmIntrinsics::_copyOfRange:              return inline_array_copyOf(true);
  532   case vmIntrinsics::_equalsB:                  return inline_array_equals(StrIntrinsicNode::LL);
  533   case vmIntrinsics::_equalsC:                  return inline_array_equals(StrIntrinsicNode::UU);
  534   case vmIntrinsics::_Preconditions_checkIndex: return inline_preconditions_checkIndex(T_INT);
  535   case vmIntrinsics::_Preconditions_checkLongIndex: return inline_preconditions_checkIndex(T_LONG);
  536   case vmIntrinsics::_clone:                    return inline_native_clone(intrinsic()->is_virtual());
  537 
  538   case vmIntrinsics::_allocateUninitializedArray: return inline_unsafe_newArray(true);
  539   case vmIntrinsics::_newArray:                   return inline_unsafe_newArray(false);
  540   case vmIntrinsics::_newNullRestrictedNonAtomicArray: return inline_newArray(/* null_free */ true, /* atomic */ false);
  541   case vmIntrinsics::_newNullRestrictedAtomicArray: return inline_newArray(/* null_free */ true, /* atomic */ true);
  542   case vmIntrinsics::_newNullableAtomicArray:     return inline_newArray(/* null_free */ false, /* atomic */ true);
  543   case vmIntrinsics::_isFlatArray:              return inline_getArrayProperties(IsFlat);
  544   case vmIntrinsics::_isNullRestrictedArray:    return inline_getArrayProperties(IsNullRestricted);
  545   case vmIntrinsics::_isAtomicArray:            return inline_getArrayProperties(IsAtomic);
  546 
  547   case vmIntrinsics::_isAssignableFrom:         return inline_native_subtype_check();
  548 
  549   case vmIntrinsics::_isInstance:
  550   case vmIntrinsics::_isHidden:
  551   case vmIntrinsics::_getSuperclass:            return inline_native_Class_query(intrinsic_id());
  552 
  553   case vmIntrinsics::_floatToRawIntBits:
  554   case vmIntrinsics::_floatToIntBits:
  555   case vmIntrinsics::_intBitsToFloat:
  556   case vmIntrinsics::_doubleToRawLongBits:
  557   case vmIntrinsics::_doubleToLongBits:
  558   case vmIntrinsics::_longBitsToDouble:
  559   case vmIntrinsics::_floatToFloat16:
  560   case vmIntrinsics::_float16ToFloat:           return inline_fp_conversions(intrinsic_id());
  561   case vmIntrinsics::_sqrt_float16:             return inline_fp16_operations(intrinsic_id(), 1);
  562   case vmIntrinsics::_fma_float16:              return inline_fp16_operations(intrinsic_id(), 3);
  563   case vmIntrinsics::_floatIsFinite:
  564   case vmIntrinsics::_floatIsInfinite:
  565   case vmIntrinsics::_doubleIsFinite:
  566   case vmIntrinsics::_doubleIsInfinite:         return inline_fp_range_check(intrinsic_id());
  567 
  568   case vmIntrinsics::_numberOfLeadingZeros_i:
  569   case vmIntrinsics::_numberOfLeadingZeros_l:
  570   case vmIntrinsics::_numberOfTrailingZeros_i:
  571   case vmIntrinsics::_numberOfTrailingZeros_l:
  572   case vmIntrinsics::_bitCount_i:
  573   case vmIntrinsics::_bitCount_l:
  574   case vmIntrinsics::_reverse_i:
  575   case vmIntrinsics::_reverse_l:
  576   case vmIntrinsics::_reverseBytes_i:
  577   case vmIntrinsics::_reverseBytes_l:
  578   case vmIntrinsics::_reverseBytes_s:
  579   case vmIntrinsics::_reverseBytes_c:           return inline_number_methods(intrinsic_id());
  580 
  581   case vmIntrinsics::_compress_i:
  582   case vmIntrinsics::_compress_l:
  583   case vmIntrinsics::_expand_i:
  584   case vmIntrinsics::_expand_l:                 return inline_bitshuffle_methods(intrinsic_id());
  585 
  586   case vmIntrinsics::_compareUnsigned_i:
  587   case vmIntrinsics::_compareUnsigned_l:        return inline_compare_unsigned(intrinsic_id());
  588 
  589   case vmIntrinsics::_divideUnsigned_i:
  590   case vmIntrinsics::_divideUnsigned_l:
  591   case vmIntrinsics::_remainderUnsigned_i:
  592   case vmIntrinsics::_remainderUnsigned_l:      return inline_divmod_methods(intrinsic_id());
  593 
  594   case vmIntrinsics::_getCallerClass:           return inline_native_Reflection_getCallerClass();
  595 
  596   case vmIntrinsics::_Reference_get0:           return inline_reference_get0();
  597   case vmIntrinsics::_Reference_refersTo0:      return inline_reference_refersTo0(false);
  598   case vmIntrinsics::_Reference_reachabilityFence: return inline_reference_reachabilityFence();
  599   case vmIntrinsics::_PhantomReference_refersTo0: return inline_reference_refersTo0(true);
  600   case vmIntrinsics::_Reference_clear0:         return inline_reference_clear0(false);
  601   case vmIntrinsics::_PhantomReference_clear0:  return inline_reference_clear0(true);
  602 
  603   case vmIntrinsics::_Class_cast:               return inline_Class_cast();
  604 
  605   case vmIntrinsics::_aescrypt_encryptBlock:
  606   case vmIntrinsics::_aescrypt_decryptBlock:    return inline_aescrypt_Block(intrinsic_id());
  607 
  608   case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
  609   case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
  610     return inline_cipherBlockChaining_AESCrypt(intrinsic_id());
  611 
  612   case vmIntrinsics::_electronicCodeBook_encryptAESCrypt:
  613   case vmIntrinsics::_electronicCodeBook_decryptAESCrypt:
  614     return inline_electronicCodeBook_AESCrypt(intrinsic_id());
  615 
  616   case vmIntrinsics::_counterMode_AESCrypt:
  617     return inline_counterMode_AESCrypt(intrinsic_id());
  618 
  619   case vmIntrinsics::_galoisCounterMode_AESCrypt:
  620     return inline_galoisCounterMode_AESCrypt();
  621 
  622   case vmIntrinsics::_md5_implCompress:
  623   case vmIntrinsics::_sha_implCompress:
  624   case vmIntrinsics::_sha2_implCompress:
  625   case vmIntrinsics::_sha5_implCompress:
  626   case vmIntrinsics::_sha3_implCompress:
  627     return inline_digestBase_implCompress(intrinsic_id());
  628   case vmIntrinsics::_double_keccak:
  629   case vmIntrinsics::_quad_keccak:
  630     return inline_keccak(intrinsic_id());
  631 
  632   case vmIntrinsics::_digestBase_implCompressMB:
  633     return inline_digestBase_implCompressMB(predicate);
  634 
  635   case vmIntrinsics::_multiplyToLen:
  636     return inline_multiplyToLen();
  637 
  638   case vmIntrinsics::_squareToLen:
  639     return inline_squareToLen();
  640 
  641   case vmIntrinsics::_mulAdd:
  642     return inline_mulAdd();
  643 
  644   case vmIntrinsics::_montgomeryMultiply:
  645     return inline_montgomeryMultiply();
  646   case vmIntrinsics::_montgomerySquare:
  647     return inline_montgomerySquare();
  648 
  649   case vmIntrinsics::_bigIntegerRightShiftWorker:
  650     return inline_bigIntegerShift(true);
  651   case vmIntrinsics::_bigIntegerLeftShiftWorker:
  652     return inline_bigIntegerShift(false);
  653 
  654   case vmIntrinsics::_vectorizedMismatch:
  655     return inline_vectorizedMismatch();
  656 
  657   case vmIntrinsics::_ghash_processBlocks:
  658     return inline_ghash_processBlocks();
  659   case vmIntrinsics::_chacha20Block:
  660     return inline_chacha20Block();
  661   case vmIntrinsics::_kyberNtt:
  662     return inline_kyberNtt();
  663   case vmIntrinsics::_kyberInverseNtt:
  664     return inline_kyberInverseNtt();
  665   case vmIntrinsics::_kyberNttMult:
  666     return inline_kyberNttMult();
  667   case vmIntrinsics::_kyberAddPoly_2:
  668     return inline_kyberAddPoly_2();
  669   case vmIntrinsics::_kyberAddPoly_3:
  670     return inline_kyberAddPoly_3();
  671   case vmIntrinsics::_kyber12To16:
  672     return inline_kyber12To16();
  673   case vmIntrinsics::_kyberBarrettReduce:
  674     return inline_kyberBarrettReduce();
  675   case vmIntrinsics::_dilithiumAlmostNtt:
  676     return inline_dilithiumAlmostNtt();
  677   case vmIntrinsics::_dilithiumAlmostInverseNtt:
  678     return inline_dilithiumAlmostInverseNtt();
  679   case vmIntrinsics::_dilithiumNttMult:
  680     return inline_dilithiumNttMult();
  681   case vmIntrinsics::_dilithiumMontMulByConstant:
  682     return inline_dilithiumMontMulByConstant();
  683   case vmIntrinsics::_dilithiumDecomposePoly:
  684     return inline_dilithiumDecomposePoly();
  685   case vmIntrinsics::_base64_encodeBlock:
  686     return inline_base64_encodeBlock();
  687   case vmIntrinsics::_base64_decodeBlock:
  688     return inline_base64_decodeBlock();
  689   case vmIntrinsics::_poly1305_processBlocks:
  690     return inline_poly1305_processBlocks();
  691   case vmIntrinsics::_intpoly_montgomeryMult_P256:
  692     return inline_intpoly_montgomeryMult_P256();
  693   case vmIntrinsics::_intpoly_assign:
  694     return inline_intpoly_assign();
  695   case vmIntrinsics::_intpoly_mult_25519:
  696     return inline_intpoly_mult_25519();
  697   case vmIntrinsics::_intpoly_square_25519:
  698     return inline_intpoly_square_25519();
  699   case vmIntrinsics::_encodeISOArray:
  700   case vmIntrinsics::_encodeByteISOArray:
  701     return inline_encodeISOArray(false);
  702   case vmIntrinsics::_encodeAsciiArray:
  703     return inline_encodeISOArray(true);
  704 
  705   case vmIntrinsics::_updateCRC32:
  706     return inline_updateCRC32();
  707   case vmIntrinsics::_updateBytesCRC32:
  708     return inline_updateBytesCRC32();
  709   case vmIntrinsics::_updateByteBufferCRC32:
  710     return inline_updateByteBufferCRC32();
  711 
  712   case vmIntrinsics::_updateBytesCRC32C:
  713     return inline_updateBytesCRC32C();
  714   case vmIntrinsics::_updateDirectByteBufferCRC32C:
  715     return inline_updateDirectByteBufferCRC32C();
  716 
  717   case vmIntrinsics::_updateBytesAdler32:
  718     return inline_updateBytesAdler32();
  719   case vmIntrinsics::_updateByteBufferAdler32:
  720     return inline_updateByteBufferAdler32();
  721 
  722   case vmIntrinsics::_profileBoolean:
  723     return inline_profileBoolean();
  724   case vmIntrinsics::_isCompileConstant:
  725     return inline_isCompileConstant();
  726 
  727   case vmIntrinsics::_countPositives:
  728     return inline_countPositives();
  729 
  730   case vmIntrinsics::_fmaD:
  731   case vmIntrinsics::_fmaF:
  732     return inline_fma(intrinsic_id());
  733 
  734   case vmIntrinsics::_isDigit:
  735   case vmIntrinsics::_isLowerCase:
  736   case vmIntrinsics::_isUpperCase:
  737   case vmIntrinsics::_isWhitespace:
  738     return inline_character_compare(intrinsic_id());
  739 
  740   case vmIntrinsics::_min:
  741   case vmIntrinsics::_max:
  742   case vmIntrinsics::_min_strict:
  743   case vmIntrinsics::_max_strict:
  744   case vmIntrinsics::_minL:
  745   case vmIntrinsics::_maxL:
  746   case vmIntrinsics::_minF:
  747   case vmIntrinsics::_maxF:
  748   case vmIntrinsics::_minD:
  749   case vmIntrinsics::_maxD:
  750   case vmIntrinsics::_minF_strict:
  751   case vmIntrinsics::_maxF_strict:
  752   case vmIntrinsics::_minD_strict:
  753   case vmIntrinsics::_maxD_strict:
  754     return inline_min_max(intrinsic_id());
  755 
  756   case vmIntrinsics::_VectorUnaryOp:
  757     return inline_vector_nary_operation(1);
  758   case vmIntrinsics::_VectorBinaryOp:
  759     return inline_vector_nary_operation(2);
  760   case vmIntrinsics::_VectorUnaryLibOp:
  761     return inline_vector_call(1);
  762   case vmIntrinsics::_VectorBinaryLibOp:
  763     return inline_vector_call(2);
  764   case vmIntrinsics::_VectorTernaryOp:
  765     return inline_vector_nary_operation(3);
  766   case vmIntrinsics::_VectorFromBitsCoerced:
  767     return inline_vector_frombits_coerced();
  768   case vmIntrinsics::_VectorMaskOp:
  769     return inline_vector_mask_operation();
  770   case vmIntrinsics::_VectorLoadOp:
  771     return inline_vector_mem_operation(/*is_store=*/false);
  772   case vmIntrinsics::_VectorLoadMaskedOp:
  773     return inline_vector_mem_masked_operation(/*is_store*/false);
  774   case vmIntrinsics::_VectorStoreOp:
  775     return inline_vector_mem_operation(/*is_store=*/true);
  776   case vmIntrinsics::_VectorStoreMaskedOp:
  777     return inline_vector_mem_masked_operation(/*is_store=*/true);
  778   case vmIntrinsics::_VectorGatherOp:
  779     return inline_vector_gather_scatter(/*is_scatter*/ false);
  780   case vmIntrinsics::_VectorScatterOp:
  781     return inline_vector_gather_scatter(/*is_scatter*/ true);
  782   case vmIntrinsics::_VectorReductionCoerced:
  783     return inline_vector_reduction();
  784   case vmIntrinsics::_VectorTest:
  785     return inline_vector_test();
  786   case vmIntrinsics::_VectorBlend:
  787     return inline_vector_blend();
  788   case vmIntrinsics::_VectorRearrange:
  789     return inline_vector_rearrange();
  790   case vmIntrinsics::_VectorSelectFrom:
  791     return inline_vector_select_from();
  792   case vmIntrinsics::_VectorCompare:
  793     return inline_vector_compare();
  794   case vmIntrinsics::_VectorBroadcastInt:
  795     return inline_vector_broadcast_int();
  796   case vmIntrinsics::_VectorConvert:
  797     return inline_vector_convert();
  798   case vmIntrinsics::_VectorInsert:
  799     return inline_vector_insert();
  800   case vmIntrinsics::_VectorExtract:
  801     return inline_vector_extract();
  802   case vmIntrinsics::_VectorCompressExpand:
  803     return inline_vector_compress_expand();
  804   case vmIntrinsics::_VectorSelectFromTwoVectorOp:
  805     return inline_vector_select_from_two_vectors();
  806   case vmIntrinsics::_IndexVector:
  807     return inline_index_vector();
  808   case vmIntrinsics::_IndexPartiallyInUpperRange:
  809     return inline_index_partially_in_upper_range();
  810 
  811   case vmIntrinsics::_getObjectSize:
  812     return inline_getObjectSize();
  813 
  814   case vmIntrinsics::_blackhole:
  815     return inline_blackhole();
  816 
  817   default:
  818     // If you get here, it may be that someone has added a new intrinsic
  819     // to the list in vmIntrinsics.hpp without implementing it here.
  820 #ifndef PRODUCT
  821     if ((PrintMiscellaneous && (Verbose || WizardMode)) || PrintOpto) {
  822       tty->print_cr("*** Warning: Unimplemented intrinsic %s(%d)",
  823                     vmIntrinsics::name_at(intrinsic_id()), vmIntrinsics::as_int(intrinsic_id()));
  824     }
  825 #endif
  826     return false;
  827   }
  828 }
  829 
  830 Node* LibraryCallKit::try_to_predicate(int predicate) {
  831   if (!jvms()->has_method()) {
  832     // Root JVMState has a null method.
  833     assert(map()->memory()->Opcode() == Op_Parm, "");
  834     // Insert the memory aliasing node
  835     set_all_memory(reset_memory());
  836   }
  837   assert(merged_memory(), "");
  838 
  839   switch (intrinsic_id()) {
  840   case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
  841     return inline_cipherBlockChaining_AESCrypt_predicate(false);
  842   case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
  843     return inline_cipherBlockChaining_AESCrypt_predicate(true);
  844   case vmIntrinsics::_electronicCodeBook_encryptAESCrypt:
  845     return inline_electronicCodeBook_AESCrypt_predicate(false);
  846   case vmIntrinsics::_electronicCodeBook_decryptAESCrypt:
  847     return inline_electronicCodeBook_AESCrypt_predicate(true);
  848   case vmIntrinsics::_counterMode_AESCrypt:
  849     return inline_counterMode_AESCrypt_predicate();
  850   case vmIntrinsics::_digestBase_implCompressMB:
  851     return inline_digestBase_implCompressMB_predicate(predicate);
  852   case vmIntrinsics::_galoisCounterMode_AESCrypt:
  853     return inline_galoisCounterMode_AESCrypt_predicate();
  854 
  855   default:
  856     // If you get here, it may be that someone has added a new intrinsic
  857     // to the list in vmIntrinsics.hpp without implementing it here.
  858 #ifndef PRODUCT
  859     if ((PrintMiscellaneous && (Verbose || WizardMode)) || PrintOpto) {
  860       tty->print_cr("*** Warning: Unimplemented predicate for intrinsic %s(%d)",
  861                     vmIntrinsics::name_at(intrinsic_id()), vmIntrinsics::as_int(intrinsic_id()));
  862     }
  863 #endif
  864     Node* slow_ctl = control();
  865     set_control(top()); // No fast path intrinsic
  866     return slow_ctl;
  867   }
  868 }
  869 
  870 //------------------------------set_result-------------------------------
  871 // Helper function for finishing intrinsics.
  872 void LibraryCallKit::set_result(RegionNode* region, PhiNode* value) {
  873   record_for_igvn(region);
  874   set_control(_gvn.transform(region));
  875   set_result( _gvn.transform(value));
  876   assert(value->type()->basic_type() == result()->bottom_type()->basic_type(), "sanity");
  877 }
  878 
  879 RegionNode* LibraryCallKit::create_bailout() {
  880   RegionNode* bailout = new RegionNode(1);
  881   record_for_igvn(bailout);
  882   return bailout;
  883 }
  884 
  885 bool LibraryCallKit::check_bailout(RegionNode* bailout) {
  886   if (bailout->req() > 1) {
  887     bailout = _gvn.transform(bailout)->as_Region();
  888     Node* frame = _gvn.transform(new ParmNode(C->start(), TypeFunc::FramePtr));
  889     Node* halt = _gvn.transform(new HaltNode(bailout, frame, "unexpected guard failure in intrinsic"));
  890     C->root()->add_req(halt);
  891   }
  892   return stopped();
  893 }
  894 
  895 //------------------------------generate_guard---------------------------
  896 // Helper function for generating guarded fast-slow graph structures.
  897 // The given 'test', if true, guards a slow path.  If the test fails
  898 // then a fast path can be taken.  (We generally hope it fails.)
  899 // In all cases, GraphKit::control() is updated to the fast path.
  900 // The returned value represents the control for the slow path.
  901 // The return value is never 'top'; it is either a valid control
  902 // or null if it is obvious that the slow path can never be taken.
  903 // Also, if region and the slow control are not null, the slow edge
  904 // is appended to the region.
  905 Node* LibraryCallKit::generate_guard(Node* test, RegionNode* region, float true_prob) {
  906   if (stopped()) {
  907     // Already short circuited.
  908     return nullptr;
  909   }
  910 
  911   // Build an if node and its projections.
  912   // If test is true we take the slow path, which we assume is uncommon.
  913   if (_gvn.type(test) == TypeInt::ZERO) {
  914     // The slow branch is never taken.  No need to build this guard.
  915     return nullptr;
  916   }
  917 
  918   IfNode* iff = create_and_map_if(control(), test, true_prob, COUNT_UNKNOWN);
  919 
  920   Node* if_slow = _gvn.transform(new IfTrueNode(iff));
  921   if (if_slow == top()) {
  922     // The slow branch is never taken.  No need to build this guard.
  923     return nullptr;
  924   }
  925 
  926   if (region != nullptr)
  927     region->add_req(if_slow);
  928 
  929   Node* if_fast = _gvn.transform(new IfFalseNode(iff));
  930   set_control(if_fast);
  931 
  932   return if_slow;
  933 }
  934 
  935 inline Node* LibraryCallKit::generate_slow_guard(Node* test, RegionNode* region) {
  936   return generate_guard(test, region, PROB_UNLIKELY_MAG(3));
  937 }
  938 inline Node* LibraryCallKit::generate_fair_guard(Node* test, RegionNode* region) {
  939   return generate_guard(test, region, PROB_FAIR);
  940 }
  941 
  942 inline Node* LibraryCallKit::generate_negative_guard(Node* index, RegionNode* region,
  943                                                      Node** pos_index, bool with_opaque) {
  944   if (stopped())
  945     return nullptr;                // already stopped
  946   if (_gvn.type(index)->higher_equal(TypeInt::POS)) // [0,maxint]
  947     return nullptr;                // index is already adequately typed
  948   Node* cmp_lt = _gvn.transform(new CmpINode(index, intcon(0)));
  949   Node* bol_lt = _gvn.transform(new BoolNode(cmp_lt, BoolTest::lt));
  950   if (with_opaque) {
  951     bol_lt = _gvn.transform(new OpaqueConstantBoolNode(C, bol_lt, false));
  952   }
  953   Node* is_neg = generate_guard(bol_lt, region, PROB_MIN);
  954   if (is_neg != nullptr && pos_index != nullptr) {
  955     // Emulate effect of Parse::adjust_map_after_if.
  956     Node* ccast = new CastIINode(control(), index, TypeInt::POS);
  957     (*pos_index) = _gvn.transform(ccast);
  958   }
  959   return is_neg;
  960 }
  961 
  962 // Make sure that 'position' is a valid limit index, in [0..length].
  963 // There are two equivalent plans for checking this:
  964 //   A. (offset + copyLength)  unsigned<=  arrayLength
  965 //   B. offset  <=  (arrayLength - copyLength)
  966 // We require that all of the values above, except for the sum and
  967 // difference, are already known to be non-negative.
  968 // Plan A is robust in the face of overflow, if offset and copyLength
  969 // are both hugely positive.
  970 //
  971 // Plan B is less direct and intuitive, but it does not overflow at
  972 // all, since the difference of two non-negatives is always
  973 // representable.  Whenever Java methods must perform the equivalent
  974 // check they generally use Plan B instead of Plan A.
  975 // For the moment we use Plan A.
  976 inline Node* LibraryCallKit::generate_limit_guard(Node* offset,
  977                                                   Node* subseq_length,
  978                                                   Node* array_length,
  979                                                   RegionNode* region,
  980                                                   bool with_opaque) {
  981   if (stopped())
  982     return nullptr;                // already stopped
  983   bool zero_offset = _gvn.type(offset) == TypeInt::ZERO;
  984   if (zero_offset && subseq_length->eqv_uncast(array_length))
  985     return nullptr;                // common case of whole-array copy
  986   Node* last = subseq_length;
  987   if (!zero_offset)             // last += offset
  988     last = _gvn.transform(new AddINode(last, offset));
  989   Node* cmp_lt = _gvn.transform(new CmpUNode(array_length, last));
  990   Node* bol_lt = _gvn.transform(new BoolNode(cmp_lt, BoolTest::lt));
  991   if (with_opaque) {
  992     bol_lt = _gvn.transform(new OpaqueConstantBoolNode(C, bol_lt, false));
  993   }
  994   Node* is_over = generate_guard(bol_lt, region, PROB_MIN);
  995   return is_over;
  996 }
  997 
  998 // Emit range checks for the given String.value byte array
  999 void LibraryCallKit::generate_string_range_check(Node* array,
 1000                                                  Node* offset,
 1001                                                  Node* count,
 1002                                                  bool char_count,
 1003                                                  RegionNode* region) {
 1004   if (stopped()) {
 1005     return; // already stopped
 1006   }
 1007   if (char_count) {
 1008     // Convert char count to byte count
 1009     count = _gvn.transform(new LShiftINode(count, intcon(1)));
 1010   }
 1011   // Offset and count must not be negative
 1012   generate_negative_guard(offset, region, nullptr, true);
 1013   generate_negative_guard(count, region, nullptr, true);
 1014   // Offset + count must not exceed length of array
 1015   generate_limit_guard(offset, count, load_array_length(array), region, true);
 1016 }
 1017 
 1018 Node* LibraryCallKit::current_thread_helper(Node*& tls_output, ByteSize handle_offset,
 1019                                             bool is_immutable) {
 1020   ciKlass* thread_klass = env()->Thread_klass();
 1021   const Type* thread_type
 1022     = TypeOopPtr::make_from_klass(thread_klass)->cast_to_ptr_type(TypePtr::NotNull);
 1023 
 1024   Node* thread = _gvn.transform(new ThreadLocalNode());
 1025   Node* p = off_heap_plus_addr(thread, in_bytes(handle_offset));
 1026   tls_output = thread;
 1027 
 1028   Node* thread_obj_handle
 1029     = (is_immutable
 1030       ? LoadNode::make(_gvn, nullptr, immutable_memory(), p, p->bottom_type()->is_ptr(),
 1031         TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered)
 1032       : make_load(nullptr, p, p->bottom_type()->is_ptr(), T_ADDRESS, MemNode::unordered));
 1033   thread_obj_handle = _gvn.transform(thread_obj_handle);
 1034 
 1035   DecoratorSet decorators = IN_NATIVE;
 1036   if (is_immutable) {
 1037     decorators |= C2_IMMUTABLE_MEMORY;
 1038   }
 1039   return access_load(thread_obj_handle, thread_type, T_OBJECT, decorators);
 1040 }
 1041 
 1042 //--------------------------generate_current_thread--------------------
 1043 Node* LibraryCallKit::generate_current_thread(Node* &tls_output) {
 1044   return current_thread_helper(tls_output, JavaThread::threadObj_offset(),
 1045                                /*is_immutable*/false);
 1046 }
 1047 
 1048 //--------------------------generate_virtual_thread--------------------
 1049 Node* LibraryCallKit::generate_virtual_thread(Node* tls_output) {
 1050   return current_thread_helper(tls_output, JavaThread::vthread_offset(),
 1051                                !C->method()->changes_current_thread());
 1052 }
 1053 
 1054 //------------------------------make_string_method_node------------------------
 1055 // Helper method for String intrinsic functions. This version is called with
 1056 // str1 and str2 pointing to byte[] nodes containing Latin1 or UTF16 encoded
 1057 // characters (depending on 'is_byte'). cnt1 and cnt2 are pointing to Int nodes
 1058 // containing the lengths of str1 and str2.
 1059 Node* LibraryCallKit::make_string_method_node(int opcode, Node* str1_start, Node* cnt1, Node* str2_start, Node* cnt2, StrIntrinsicNode::ArgEnc ae) {
 1060   Node* result = nullptr;
 1061   switch (opcode) {
 1062   case Op_StrIndexOf:
 1063     result = new StrIndexOfNode(control(), memory(TypeAryPtr::BYTES),
 1064                                 str1_start, cnt1, str2_start, cnt2, ae);
 1065     break;
 1066   case Op_StrComp:
 1067     result = new StrCompNode(control(), memory(TypeAryPtr::BYTES),
 1068                              str1_start, cnt1, str2_start, cnt2, ae);
 1069     break;
 1070   case Op_StrEquals:
 1071     // We already know that cnt1 == cnt2 here (checked in 'inline_string_equals').
 1072     // Use the constant length if there is one because optimized match rule may exist.
 1073     result = new StrEqualsNode(control(), memory(TypeAryPtr::BYTES),
 1074                                str1_start, str2_start, cnt2->is_Con() ? cnt2 : cnt1, ae);
 1075     break;
 1076   default:
 1077     ShouldNotReachHere();
 1078     return nullptr;
 1079   }
 1080 
 1081   // All these intrinsics have checks.
 1082   C->set_has_split_ifs(true); // Has chance for split-if optimization
 1083   clear_upper_avx();
 1084 
 1085   return _gvn.transform(result);
 1086 }
 1087 
 1088 //------------------------------inline_string_compareTo------------------------
 1089 bool LibraryCallKit::inline_string_compareTo(StrIntrinsicNode::ArgEnc ae) {
 1090   Node* arg1 = argument(0);
 1091   Node* arg2 = argument(1);
 1092 
 1093   arg1 = must_be_not_null(arg1, true);
 1094   arg2 = must_be_not_null(arg2, true);
 1095 
 1096   // Get start addr and length of first argument
 1097   Node* arg1_start  = array_element_address(arg1, intcon(0), T_BYTE);
 1098   Node* arg1_cnt    = load_array_length(arg1);
 1099 
 1100   // Get start addr and length of second argument
 1101   Node* arg2_start  = array_element_address(arg2, intcon(0), T_BYTE);
 1102   Node* arg2_cnt    = load_array_length(arg2);
 1103 
 1104   Node* result = make_string_method_node(Op_StrComp, arg1_start, arg1_cnt, arg2_start, arg2_cnt, ae);
 1105   set_result(result);
 1106   return true;
 1107 }
 1108 
 1109 //------------------------------inline_string_equals------------------------
 1110 bool LibraryCallKit::inline_string_equals(StrIntrinsicNode::ArgEnc ae) {
 1111   Node* arg1 = argument(0);
 1112   Node* arg2 = argument(1);
 1113 
 1114   // paths (plus control) merge
 1115   RegionNode* region = new RegionNode(3);
 1116   Node* phi = new PhiNode(region, TypeInt::BOOL);
 1117 
 1118   if (!stopped()) {
 1119 
 1120     arg1 = must_be_not_null(arg1, true);
 1121     arg2 = must_be_not_null(arg2, true);
 1122 
 1123     // Get start addr and length of first argument
 1124     Node* arg1_start  = array_element_address(arg1, intcon(0), T_BYTE);
 1125     Node* arg1_cnt    = load_array_length(arg1);
 1126 
 1127     // Get start addr and length of second argument
 1128     Node* arg2_start  = array_element_address(arg2, intcon(0), T_BYTE);
 1129     Node* arg2_cnt    = load_array_length(arg2);
 1130 
 1131     // Check for arg1_cnt != arg2_cnt
 1132     Node* cmp = _gvn.transform(new CmpINode(arg1_cnt, arg2_cnt));
 1133     Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::ne));
 1134     Node* if_ne = generate_slow_guard(bol, nullptr);
 1135     if (if_ne != nullptr) {
 1136       phi->init_req(2, intcon(0));
 1137       region->init_req(2, if_ne);
 1138     }
 1139 
 1140     // Check for count == 0 is done by assembler code for StrEquals.
 1141 
 1142     if (!stopped()) {
 1143       Node* equals = make_string_method_node(Op_StrEquals, arg1_start, arg1_cnt, arg2_start, arg2_cnt, ae);
 1144       phi->init_req(1, equals);
 1145       region->init_req(1, control());
 1146     }
 1147   }
 1148 
 1149   // post merge
 1150   set_control(_gvn.transform(region));
 1151   record_for_igvn(region);
 1152 
 1153   set_result(_gvn.transform(phi));
 1154   return true;
 1155 }
 1156 
 1157 //------------------------------inline_array_equals----------------------------
 1158 bool LibraryCallKit::inline_array_equals(StrIntrinsicNode::ArgEnc ae) {
 1159   assert(ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::LL, "unsupported array types");
 1160   Node* arg1 = argument(0);
 1161   Node* arg2 = argument(1);
 1162 
 1163   const TypeAryPtr* mtype = (ae == StrIntrinsicNode::UU) ? TypeAryPtr::CHARS : TypeAryPtr::BYTES;
 1164   set_result(_gvn.transform(new AryEqNode(control(), memory(mtype), mtype, arg1, arg2, ae)));
 1165   clear_upper_avx();
 1166 
 1167   return true;
 1168 }
 1169 
 1170 
 1171 //------------------------------inline_countPositives------------------------------
 1172 // int java.lang.StringCoding#countPositives0(byte[] ba, int off, int len)
 1173 bool LibraryCallKit::inline_countPositives() {
 1174   assert(callee()->signature()->size() == 3, "countPositives has 3 parameters");
 1175   // no receiver since it is static method
 1176   Node* ba         = argument(0);
 1177   Node* offset     = argument(1);
 1178   Node* len        = argument(2);
 1179 
 1180   ba = must_be_not_null(ba, true);
 1181   RegionNode* bailout = create_bailout();
 1182   generate_string_range_check(ba, offset, len, false, bailout);
 1183   if (check_bailout(bailout)) {
 1184     return true;
 1185   }
 1186 
 1187   Node* ba_start = array_element_address(ba, offset, T_BYTE);
 1188   Node* result = new CountPositivesNode(control(), memory(TypeAryPtr::BYTES), ba_start, len);
 1189   set_result(_gvn.transform(result));
 1190   clear_upper_avx();
 1191   return true;
 1192 }
 1193 
 1194 bool LibraryCallKit::inline_preconditions_checkIndex(BasicType bt) {
 1195   Node* index = argument(0);
 1196   Node* length = bt == T_INT ? argument(1) : argument(2);
 1197   if (too_many_traps(Deoptimization::Reason_intrinsic) || too_many_traps(Deoptimization::Reason_range_check)) {
 1198     return false;
 1199   }
 1200 
 1201   // check that length is positive
 1202   Node* len_pos_cmp = _gvn.transform(CmpNode::make(length, integercon(0, bt), bt));
 1203   Node* len_pos_bol = _gvn.transform(new BoolNode(len_pos_cmp, BoolTest::ge));
 1204 
 1205   {
 1206     BuildCutout unless(this, len_pos_bol, PROB_MAX);
 1207     uncommon_trap(Deoptimization::Reason_intrinsic,
 1208                   Deoptimization::Action_make_not_entrant);
 1209   }
 1210 
 1211   if (stopped()) {
 1212     // Length is known to be always negative during compilation and the IR graph so far constructed is good so return success
 1213     return true;
 1214   }
 1215 
 1216   // length is now known positive, add a cast node to make this explicit
 1217   jlong upper_bound = _gvn.type(length)->is_integer(bt)->hi_as_long();
 1218   Node* casted_length = ConstraintCastNode::make_cast_for_basic_type(
 1219       control(), length, TypeInteger::make(0, upper_bound, Type::WidenMax, bt),
 1220       ConstraintCastNode::DependencyType::FloatingNarrowing, bt);
 1221   casted_length = _gvn.transform(casted_length);
 1222   replace_in_map(length, casted_length);
 1223   length = casted_length;
 1224 
 1225   // Use an unsigned comparison for the range check itself
 1226   Node* rc_cmp = _gvn.transform(CmpNode::make(index, length, bt, true));
 1227   BoolTest::mask btest = BoolTest::lt;
 1228   Node* rc_bool = _gvn.transform(new BoolNode(rc_cmp, btest));
 1229   RangeCheckNode* rc = new RangeCheckNode(control(), rc_bool, PROB_MAX, COUNT_UNKNOWN);
 1230   _gvn.set_type(rc, rc->Value(&_gvn));
 1231   if (!rc_bool->is_Con()) {
 1232     record_for_igvn(rc);
 1233   }
 1234   set_control(_gvn.transform(new IfTrueNode(rc)));
 1235   {
 1236     PreserveJVMState pjvms(this);
 1237     set_control(_gvn.transform(new IfFalseNode(rc)));
 1238     uncommon_trap(Deoptimization::Reason_range_check,
 1239                   Deoptimization::Action_make_not_entrant);
 1240   }
 1241 
 1242   if (stopped()) {
 1243     // Range check is known to always fail during compilation and the IR graph so far constructed is good so return success
 1244     return true;
 1245   }
 1246 
 1247   // index is now known to be >= 0 and < length, cast it
 1248   Node* result = ConstraintCastNode::make_cast_for_basic_type(
 1249       control(), index, TypeInteger::make(0, upper_bound, Type::WidenMax, bt),
 1250       ConstraintCastNode::DependencyType::FloatingNarrowing, bt);
 1251   result = _gvn.transform(result);
 1252   set_result(result);
 1253   replace_in_map(index, result);
 1254   return true;
 1255 }
 1256 
 1257 //------------------------------inline_string_indexOf------------------------
 1258 bool LibraryCallKit::inline_string_indexOf(StrIntrinsicNode::ArgEnc ae) {
 1259   if (!Matcher::match_rule_supported(Op_StrIndexOf)) {
 1260     return false;
 1261   }
 1262   Node* src = argument(0);
 1263   Node* tgt = argument(1);
 1264 
 1265   // Make the merge point
 1266   RegionNode* result_rgn = new RegionNode(4);
 1267   Node*       result_phi = new PhiNode(result_rgn, TypeInt::INT);
 1268 
 1269   src = must_be_not_null(src, true);
 1270   tgt = must_be_not_null(tgt, true);
 1271 
 1272   // Get start addr and length of source string
 1273   Node* src_start = array_element_address(src, intcon(0), T_BYTE);
 1274   Node* src_count = load_array_length(src);
 1275 
 1276   // Get start addr and length of substring
 1277   Node* tgt_start = array_element_address(tgt, intcon(0), T_BYTE);
 1278   Node* tgt_count = load_array_length(tgt);
 1279 
 1280   Node* result = nullptr;
 1281   bool call_opt_stub = (StubRoutines::_string_indexof_array[ae] != nullptr);
 1282 
 1283   if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
 1284     // Divide src size by 2 if String is UTF16 encoded
 1285     src_count = _gvn.transform(new RShiftINode(src_count, intcon(1)));
 1286   }
 1287   if (ae == StrIntrinsicNode::UU) {
 1288     // Divide substring size by 2 if String is UTF16 encoded
 1289     tgt_count = _gvn.transform(new RShiftINode(tgt_count, intcon(1)));
 1290   }
 1291 
 1292   if (call_opt_stub) {
 1293     Node* call = make_runtime_call(RC_LEAF, OptoRuntime::string_IndexOf_Type(),
 1294                                    StubRoutines::_string_indexof_array[ae],
 1295                                    "stringIndexOf", TypePtr::BOTTOM, src_start,
 1296                                    src_count, tgt_start, tgt_count);
 1297     result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
 1298   } else {
 1299     result = make_indexOf_node(src_start, src_count, tgt_start, tgt_count,
 1300                                result_rgn, result_phi, ae);
 1301   }
 1302   if (result != nullptr) {
 1303     result_phi->init_req(3, result);
 1304     result_rgn->init_req(3, control());
 1305   }
 1306   set_control(_gvn.transform(result_rgn));
 1307   record_for_igvn(result_rgn);
 1308   set_result(_gvn.transform(result_phi));
 1309 
 1310   return true;
 1311 }
 1312 
 1313 //-----------------------------inline_string_indexOfI-----------------------
 1314 bool LibraryCallKit::inline_string_indexOfI(StrIntrinsicNode::ArgEnc ae) {
 1315   if (!Matcher::match_rule_supported(Op_StrIndexOf)) {
 1316     return false;
 1317   }
 1318 
 1319   assert(callee()->signature()->size() == 5, "String.indexOf() has 5 arguments");
 1320   Node* src         = argument(0); // byte[]
 1321   Node* src_count   = argument(1); // char count
 1322   Node* tgt         = argument(2); // byte[]
 1323   Node* tgt_count   = argument(3); // char count
 1324   Node* from_index  = argument(4); // char index
 1325 
 1326   src = must_be_not_null(src, true);
 1327   tgt = must_be_not_null(tgt, true);
 1328 
 1329   // Multiply byte array index by 2 if String is UTF16 encoded
 1330   Node* src_offset = (ae == StrIntrinsicNode::LL) ? from_index : _gvn.transform(new LShiftINode(from_index, intcon(1)));
 1331   src_count = _gvn.transform(new SubINode(src_count, from_index));
 1332   Node* src_start = array_element_address(src, src_offset, T_BYTE);
 1333   Node* tgt_start = array_element_address(tgt, intcon(0), T_BYTE);
 1334 
 1335   // Range checks
 1336   RegionNode* bailout = create_bailout();
 1337   generate_string_range_check(src, src_offset, src_count, ae != StrIntrinsicNode::LL, bailout);
 1338   generate_string_range_check(tgt, intcon(0), tgt_count, ae == StrIntrinsicNode::UU, bailout);
 1339   if (check_bailout(bailout)) {
 1340     return true;
 1341   }
 1342 
 1343   RegionNode* region = new RegionNode(5);
 1344   Node* phi = new PhiNode(region, TypeInt::INT);
 1345   Node* result = nullptr;
 1346 
 1347   bool call_opt_stub = (StubRoutines::_string_indexof_array[ae] != nullptr);
 1348 
 1349   if (call_opt_stub) {
 1350     Node* call = make_runtime_call(RC_LEAF, OptoRuntime::string_IndexOf_Type(),
 1351                                    StubRoutines::_string_indexof_array[ae],
 1352                                    "stringIndexOf", TypePtr::BOTTOM, src_start,
 1353                                    src_count, tgt_start, tgt_count);
 1354     result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
 1355   } else {
 1356     result = make_indexOf_node(src_start, src_count, tgt_start, tgt_count,
 1357                                region, phi, ae);
 1358   }
 1359   if (result != nullptr) {
 1360     // The result is index relative to from_index if substring was found, -1 otherwise.
 1361     // Generate code which will fold into cmove.
 1362     Node* cmp = _gvn.transform(new CmpINode(result, intcon(0)));
 1363     Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::lt));
 1364 
 1365     Node* if_lt = generate_slow_guard(bol, nullptr);
 1366     if (if_lt != nullptr) {
 1367       // result == -1
 1368       phi->init_req(3, result);
 1369       region->init_req(3, if_lt);
 1370     }
 1371     if (!stopped()) {
 1372       result = _gvn.transform(new AddINode(result, from_index));
 1373       phi->init_req(4, result);
 1374       region->init_req(4, control());
 1375     }
 1376   }
 1377 
 1378   set_control(_gvn.transform(region));
 1379   record_for_igvn(region);
 1380   set_result(_gvn.transform(phi));
 1381   clear_upper_avx();
 1382 
 1383   return true;
 1384 }
 1385 
 1386 // Create StrIndexOfNode with fast path checks
 1387 Node* LibraryCallKit::make_indexOf_node(Node* src_start, Node* src_count, Node* tgt_start, Node* tgt_count,
 1388                                         RegionNode* region, Node* phi, StrIntrinsicNode::ArgEnc ae) {
 1389   // Check for substr count > string count
 1390   Node* cmp = _gvn.transform(new CmpINode(tgt_count, src_count));
 1391   Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::gt));
 1392   Node* if_gt = generate_slow_guard(bol, nullptr);
 1393   if (if_gt != nullptr) {
 1394     phi->init_req(1, intcon(-1));
 1395     region->init_req(1, if_gt);
 1396   }
 1397   if (!stopped()) {
 1398     // Check for substr count == 0
 1399     cmp = _gvn.transform(new CmpINode(tgt_count, intcon(0)));
 1400     bol = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
 1401     Node* if_zero = generate_slow_guard(bol, nullptr);
 1402     if (if_zero != nullptr) {
 1403       phi->init_req(2, intcon(0));
 1404       region->init_req(2, if_zero);
 1405     }
 1406   }
 1407   if (!stopped()) {
 1408     return make_string_method_node(Op_StrIndexOf, src_start, src_count, tgt_start, tgt_count, ae);
 1409   }
 1410   return nullptr;
 1411 }
 1412 
 1413 //-----------------------------inline_string_indexOfChar-----------------------
 1414 bool LibraryCallKit::inline_string_indexOfChar(StrIntrinsicNode::ArgEnc ae) {
 1415   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
 1416     return false;
 1417   }
 1418   if (!Matcher::match_rule_supported(Op_StrIndexOfChar)) {
 1419     return false;
 1420   }
 1421   assert(callee()->signature()->size() == 4, "String.indexOfChar() has 4 arguments");
 1422   Node* src         = argument(0); // byte[]
 1423   Node* int_ch      = argument(1);
 1424   Node* from_index  = argument(2);
 1425   Node* max         = argument(3);
 1426 
 1427   src = must_be_not_null(src, true);
 1428 
 1429   Node* src_offset = ae == StrIntrinsicNode::L ? from_index : _gvn.transform(new LShiftINode(from_index, intcon(1)));
 1430   Node* src_start = array_element_address(src, src_offset, T_BYTE);
 1431   Node* src_count = _gvn.transform(new SubINode(max, from_index));
 1432 
 1433   // Range checks
 1434   RegionNode* bailout = create_bailout();
 1435   generate_string_range_check(src, src_offset, src_count, ae == StrIntrinsicNode::U, bailout);
 1436   if (check_bailout(bailout)) {
 1437     return true;
 1438   }
 1439 
 1440   // Check for int_ch >= 0
 1441   Node* int_ch_cmp = _gvn.transform(new CmpINode(int_ch, intcon(0)));
 1442   Node* int_ch_bol = _gvn.transform(new BoolNode(int_ch_cmp, BoolTest::ge));
 1443   {
 1444     BuildCutout unless(this, int_ch_bol, PROB_MAX);
 1445     uncommon_trap(Deoptimization::Reason_intrinsic,
 1446                   Deoptimization::Action_maybe_recompile);
 1447   }
 1448   if (stopped()) {
 1449     return true;
 1450   }
 1451 
 1452   RegionNode* region = new RegionNode(3);
 1453   Node* phi = new PhiNode(region, TypeInt::INT);
 1454 
 1455   Node* result = new StrIndexOfCharNode(control(), memory(TypeAryPtr::BYTES), src_start, src_count, int_ch, ae);
 1456   C->set_has_split_ifs(true); // Has chance for split-if optimization
 1457   _gvn.transform(result);
 1458 
 1459   Node* cmp = _gvn.transform(new CmpINode(result, intcon(0)));
 1460   Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::lt));
 1461 
 1462   Node* if_lt = generate_slow_guard(bol, nullptr);
 1463   if (if_lt != nullptr) {
 1464     // result == -1
 1465     phi->init_req(2, result);
 1466     region->init_req(2, if_lt);
 1467   }
 1468   if (!stopped()) {
 1469     result = _gvn.transform(new AddINode(result, from_index));
 1470     phi->init_req(1, result);
 1471     region->init_req(1, control());
 1472   }
 1473   set_control(_gvn.transform(region));
 1474   record_for_igvn(region);
 1475   set_result(_gvn.transform(phi));
 1476   clear_upper_avx();
 1477 
 1478   return true;
 1479 }
 1480 //---------------------------inline_string_copy---------------------
 1481 // compressIt == true --> generate a compressed copy operation (compress char[]/byte[] to byte[])
 1482 //   int StringUTF16.compress0(char[] src, int srcOff, byte[] dst, int dstOff, int len)
 1483 //   int StringUTF16.compress0(byte[] src, int srcOff, byte[] dst, int dstOff, int len)
 1484 // compressIt == false --> generate an inflated copy operation (inflate byte[] to char[]/byte[])
 1485 //   void StringLatin1.inflate0(byte[] src, int srcOff, char[] dst, int dstOff, int len)
 1486 //   void StringLatin1.inflate0(byte[] src, int srcOff, byte[] dst, int dstOff, int len)
 1487 bool LibraryCallKit::inline_string_copy(bool compress) {
 1488   int nargs = 5;  // 2 oops, 3 ints
 1489   assert(callee()->signature()->size() == nargs, "string copy has 5 arguments");
 1490 
 1491   Node* src         = argument(0);
 1492   Node* src_offset  = argument(1);
 1493   Node* dst         = argument(2);
 1494   Node* dst_offset  = argument(3);
 1495   Node* length      = argument(4);
 1496 
 1497   // Check for allocation before we add nodes that would confuse
 1498   // tightly_coupled_allocation()
 1499   AllocateArrayNode* alloc = tightly_coupled_allocation(dst);
 1500 
 1501   // Figure out the size and type of the elements we will be copying.
 1502   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
 1503   const TypeAryPtr* dst_type = dst->Value(&_gvn)->isa_aryptr();
 1504   if (src_type == nullptr || dst_type == nullptr) {
 1505     return false;
 1506   }
 1507   BasicType src_elem = src_type->elem()->array_element_basic_type();
 1508   BasicType dst_elem = dst_type->elem()->array_element_basic_type();
 1509   assert((compress && dst_elem == T_BYTE && (src_elem == T_BYTE || src_elem == T_CHAR)) ||
 1510          (!compress && src_elem == T_BYTE && (dst_elem == T_BYTE || dst_elem == T_CHAR)),
 1511          "Unsupported array types for inline_string_copy");
 1512 
 1513   src = must_be_not_null(src, true);
 1514   dst = must_be_not_null(dst, true);
 1515 
 1516   // Convert char[] offsets to byte[] offsets
 1517   bool convert_src = (compress && src_elem == T_BYTE);
 1518   bool convert_dst = (!compress && dst_elem == T_BYTE);
 1519   if (convert_src) {
 1520     src_offset = _gvn.transform(new LShiftINode(src_offset, intcon(1)));
 1521   } else if (convert_dst) {
 1522     dst_offset = _gvn.transform(new LShiftINode(dst_offset, intcon(1)));
 1523   }
 1524 
 1525   // Range checks
 1526   RegionNode* bailout = create_bailout();
 1527   generate_string_range_check(src, src_offset, length, convert_src, bailout);
 1528   generate_string_range_check(dst, dst_offset, length, convert_dst, bailout);
 1529   if (check_bailout(bailout)) {
 1530     return true;
 1531   }
 1532 
 1533   Node* src_start = array_element_address(src, src_offset, src_elem);
 1534   Node* dst_start = array_element_address(dst, dst_offset, dst_elem);
 1535   // 'src_start' points to src array + scaled offset
 1536   // 'dst_start' points to dst array + scaled offset
 1537   Node* count = nullptr;
 1538   if (compress) {
 1539     count = compress_string(src_start, TypeAryPtr::get_array_body_type(src_elem), dst_start, length);
 1540   } else {
 1541     inflate_string(src_start, dst_start, TypeAryPtr::get_array_body_type(dst_elem), length);
 1542   }
 1543 
 1544   if (alloc != nullptr) {
 1545     if (alloc->maybe_set_complete(&_gvn)) {
 1546       // "You break it, you buy it."
 1547       InitializeNode* init = alloc->initialization();
 1548       assert(init->is_complete(), "we just did this");
 1549       init->set_complete_with_arraycopy();
 1550       assert(dst->is_CheckCastPP(), "sanity");
 1551       assert(dst->in(0)->in(0) == init, "dest pinned");
 1552     }
 1553     // Do not let stores that initialize this object be reordered with
 1554     // a subsequent store that would make this object accessible by
 1555     // other threads.
 1556     // Record what AllocateNode this StoreStore protects so that
 1557     // escape analysis can go from the MemBarStoreStoreNode to the
 1558     // AllocateNode and eliminate the MemBarStoreStoreNode if possible
 1559     // based on the escape status of the AllocateNode.
 1560     insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
 1561   }
 1562   if (compress) {
 1563     set_result(_gvn.transform(count));
 1564   }
 1565   clear_upper_avx();
 1566 
 1567   return true;
 1568 }
 1569 
 1570 #ifdef _LP64
 1571 #define XTOP ,top() /*additional argument*/
 1572 #else  //_LP64
 1573 #define XTOP        /*no additional argument*/
 1574 #endif //_LP64
 1575 
 1576 //------------------------inline_string_toBytesU--------------------------
 1577 // public static byte[] StringUTF16.toBytes0(char[] value, int off, int len)
 1578 bool LibraryCallKit::inline_string_toBytesU() {
 1579   // Get the arguments.
 1580   assert(callee()->signature()->size() == 3, "character array encoder requires 3 arguments");
 1581   Node* value     = argument(0);
 1582   Node* offset    = argument(1);
 1583   Node* length    = argument(2);
 1584 
 1585   Node* newcopy = nullptr;
 1586 
 1587   // Set the original stack and the reexecute bit for the interpreter to reexecute
 1588   // the bytecode that invokes StringUTF16.toBytes0() if deoptimization happens.
 1589   { PreserveReexecuteState preexecs(this);
 1590     jvms()->set_should_reexecute(true);
 1591 
 1592     value = must_be_not_null(value, true);
 1593     RegionNode* bailout = create_bailout();
 1594     generate_negative_guard(offset, bailout, nullptr, true);
 1595     generate_negative_guard(length, bailout, nullptr, true);
 1596     generate_limit_guard(offset, length, load_array_length(value), bailout, true);
 1597     // Make sure that resulting byte[] length does not overflow Integer.MAX_VALUE
 1598     generate_limit_guard(length, intcon(0), intcon(max_jint/2), bailout, true);
 1599     if (check_bailout(bailout)) {
 1600       return true;
 1601     }
 1602 
 1603     Node* size = _gvn.transform(new LShiftINode(length, intcon(1)));
 1604     Node* klass_node = makecon(TypeKlassPtr::make(ciTypeArrayKlass::make(T_BYTE)));
 1605     newcopy = new_array(klass_node, size, 0);  // no arguments to push
 1606     AllocateArrayNode* alloc = tightly_coupled_allocation(newcopy);
 1607     guarantee(alloc != nullptr, "created above");
 1608 
 1609     // Calculate starting addresses.
 1610     Node* src_start = array_element_address(value, offset, T_CHAR);
 1611     Node* dst_start = basic_plus_adr(newcopy, arrayOopDesc::base_offset_in_bytes(T_BYTE));
 1612 
 1613     // Check if dst array address is aligned to HeapWordSize
 1614     bool aligned = (arrayOopDesc::base_offset_in_bytes(T_BYTE) % HeapWordSize == 0);
 1615     // If true, then check if src array address is aligned to HeapWordSize
 1616     if (aligned) {
 1617       const TypeInt* toffset = gvn().type(offset)->is_int();
 1618       aligned = toffset->is_con() && ((arrayOopDesc::base_offset_in_bytes(T_CHAR) +
 1619                                        toffset->get_con() * type2aelembytes(T_CHAR)) % HeapWordSize == 0);
 1620     }
 1621 
 1622     // Figure out which arraycopy runtime method to call (disjoint, uninitialized).
 1623     const char* copyfunc_name = "arraycopy";
 1624     address     copyfunc_addr = StubRoutines::select_arraycopy_function(T_CHAR, aligned, true, copyfunc_name, true);
 1625     Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
 1626                       OptoRuntime::fast_arraycopy_Type(),
 1627                       copyfunc_addr, copyfunc_name, TypeRawPtr::BOTTOM,
 1628                       src_start, dst_start, ConvI2X(length) XTOP);
 1629     // Do not let reads from the cloned object float above the arraycopy.
 1630     if (alloc->maybe_set_complete(&_gvn)) {
 1631       // "You break it, you buy it."
 1632       InitializeNode* init = alloc->initialization();
 1633       assert(init->is_complete(), "we just did this");
 1634       init->set_complete_with_arraycopy();
 1635       assert(newcopy->is_CheckCastPP(), "sanity");
 1636       assert(newcopy->in(0)->in(0) == init, "dest pinned");
 1637     }
 1638     // Do not let stores that initialize this object be reordered with
 1639     // a subsequent store that would make this object accessible by
 1640     // other threads.
 1641     // Record what AllocateNode this StoreStore protects so that
 1642     // escape analysis can go from the MemBarStoreStoreNode to the
 1643     // AllocateNode and eliminate the MemBarStoreStoreNode if possible
 1644     // based on the escape status of the AllocateNode.
 1645     insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
 1646   } // original reexecute is set back here
 1647 
 1648   C->set_has_split_ifs(true); // Has chance for split-if optimization
 1649   if (!stopped()) {
 1650     set_result(newcopy);
 1651   }
 1652   clear_upper_avx();
 1653 
 1654   return true;
 1655 }
 1656 
 1657 //------------------------inline_string_getCharsU--------------------------
 1658 // public void StringUTF16.getChars0(byte[] src, int srcBegin, int srcEnd, char dst[], int dstBegin)
 1659 bool LibraryCallKit::inline_string_getCharsU() {
 1660   assert(callee()->signature()->size() == 5, "StringUTF16.getChars0() has 5 arguments");
 1661   // Get the arguments.
 1662   Node* src       = argument(0);
 1663   Node* src_begin = argument(1);
 1664   Node* src_end   = argument(2); // exclusive offset (i < src_end)
 1665   Node* dst       = argument(3);
 1666   Node* dst_begin = argument(4);
 1667 
 1668   // Check for allocation before we add nodes that would confuse
 1669   // tightly_coupled_allocation()
 1670   AllocateArrayNode* alloc = tightly_coupled_allocation(dst);
 1671 
 1672   // Check if a null path was taken unconditionally.
 1673   src = must_be_not_null(src, true);
 1674   dst = must_be_not_null(dst, true);
 1675   if (stopped()) {
 1676     return true;
 1677   }
 1678 
 1679   // Get length and convert char[] offset to byte[] offset
 1680   Node* length = _gvn.transform(new SubINode(src_end, src_begin));
 1681   src_begin = _gvn.transform(new LShiftINode(src_begin, intcon(1)));
 1682 
 1683   // Range checks
 1684   RegionNode* bailout = create_bailout();
 1685   generate_string_range_check(src, src_begin, length, true, bailout);
 1686   generate_string_range_check(dst, dst_begin, length, false, bailout);
 1687   if (check_bailout(bailout)) {
 1688     return true;
 1689   }
 1690 
 1691   // Calculate starting addresses.
 1692   Node* src_start = array_element_address(src, src_begin, T_BYTE);
 1693   Node* dst_start = array_element_address(dst, dst_begin, T_CHAR);
 1694 
 1695   // Check if array addresses are aligned to HeapWordSize
 1696   const TypeInt* tsrc = gvn().type(src_begin)->is_int();
 1697   const TypeInt* tdst = gvn().type(dst_begin)->is_int();
 1698   bool aligned = tsrc->is_con() && ((arrayOopDesc::base_offset_in_bytes(T_BYTE) + tsrc->get_con() * type2aelembytes(T_BYTE)) % HeapWordSize == 0) &&
 1699                  tdst->is_con() && ((arrayOopDesc::base_offset_in_bytes(T_CHAR) + tdst->get_con() * type2aelembytes(T_CHAR)) % HeapWordSize == 0);
 1700 
 1701   // Figure out which arraycopy runtime method to call (disjoint, uninitialized).
 1702   const char* copyfunc_name = "arraycopy";
 1703   address     copyfunc_addr = StubRoutines::select_arraycopy_function(T_CHAR, aligned, true, copyfunc_name, true);
 1704   Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
 1705                     OptoRuntime::fast_arraycopy_Type(),
 1706                     copyfunc_addr, copyfunc_name, TypeRawPtr::BOTTOM,
 1707                     src_start, dst_start, ConvI2X(length) XTOP);
 1708   // Do not let reads from the cloned object float above the arraycopy.
 1709   if (alloc != nullptr) {
 1710     if (alloc->maybe_set_complete(&_gvn)) {
 1711       // "You break it, you buy it."
 1712       InitializeNode* init = alloc->initialization();
 1713       assert(init->is_complete(), "we just did this");
 1714       init->set_complete_with_arraycopy();
 1715       assert(dst->is_CheckCastPP(), "sanity");
 1716       assert(dst->in(0)->in(0) == init, "dest pinned");
 1717     }
 1718     // Do not let stores that initialize this object be reordered with
 1719     // a subsequent store that would make this object accessible by
 1720     // other threads.
 1721     // Record what AllocateNode this StoreStore protects so that
 1722     // escape analysis can go from the MemBarStoreStoreNode to the
 1723     // AllocateNode and eliminate the MemBarStoreStoreNode if possible
 1724     // based on the escape status of the AllocateNode.
 1725     insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
 1726   } else {
 1727     insert_mem_bar(Op_MemBarCPUOrder);
 1728   }
 1729 
 1730   C->set_has_split_ifs(true); // Has chance for split-if optimization
 1731   return true;
 1732 }
 1733 
 1734 //----------------------inline_string_char_access----------------------------
 1735 // Store/Load char to/from byte[] array.
 1736 // static void StringUTF16.putChar(byte[] val, int index, int c)
 1737 // static char StringUTF16.getChar(byte[] val, int index)
 1738 bool LibraryCallKit::inline_string_char_access(bool is_store) {
 1739   Node* ch;
 1740   if (is_store) {
 1741     assert(callee()->signature()->size() == 3, "StringUTF16.putChar() has 3 arguments");
 1742     ch = argument(2);
 1743   } else {
 1744     assert(callee()->signature()->size() == 2, "StringUTF16.getChar() has 2 arguments");
 1745     ch = nullptr;
 1746   }
 1747   Node* value  = argument(0);
 1748   Node* index  = argument(1);
 1749 
 1750   // This intrinsic accesses byte[] array as char[] array. Computing the offsets
 1751   // correctly requires matched array shapes.
 1752   assert (arrayOopDesc::base_offset_in_bytes(T_CHAR) == arrayOopDesc::base_offset_in_bytes(T_BYTE),
 1753           "sanity: byte[] and char[] bases agree");
 1754   assert (type2aelembytes(T_CHAR) == type2aelembytes(T_BYTE)*2,
 1755           "sanity: byte[] and char[] scales agree");
 1756 
 1757   // Bail when getChar over constants is requested: constant folding would
 1758   // reject folding mismatched char access over byte[]. A normal inlining for getChar
 1759   // Java method would constant fold nicely instead.
 1760   if (!is_store && value->is_Con() && index->is_Con()) {
 1761     return false;
 1762   }
 1763 
 1764   // Save state and restore on bailout
 1765   SavedState old_state(this);
 1766 
 1767   value = must_be_not_null(value, true);
 1768 
 1769   Node* adr = array_element_address(value, index, T_CHAR);
 1770   if (adr->is_top()) {
 1771     return false;
 1772   }
 1773   old_state.discard();
 1774   if (is_store) {
 1775     access_store_at(value, adr, TypeAryPtr::BYTES, ch, TypeInt::CHAR, T_CHAR, IN_HEAP | MO_UNORDERED | C2_MISMATCHED);
 1776   } else {
 1777     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);
 1778     set_result(ch);
 1779   }
 1780   return true;
 1781 }
 1782 
 1783 
 1784 //------------------------------inline_math-----------------------------------
 1785 // public static double Math.abs(double)
 1786 // public static double Math.sqrt(double)
 1787 // public static double Math.log(double)
 1788 // public static double Math.log10(double)
 1789 // public static double Math.round(double)
 1790 bool LibraryCallKit::inline_double_math(vmIntrinsics::ID id) {
 1791   Node* arg = argument(0);
 1792   Node* n = nullptr;
 1793   switch (id) {
 1794   case vmIntrinsics::_dabs:   n = new AbsDNode(                arg);  break;
 1795   case vmIntrinsics::_dsqrt:
 1796   case vmIntrinsics::_dsqrt_strict:
 1797                               n = new SqrtDNode(C, control(),  arg);  break;
 1798   case vmIntrinsics::_ceil:   n = RoundDoubleModeNode::make(_gvn, arg, RoundDoubleModeNode::rmode_ceil); break;
 1799   case vmIntrinsics::_floor:  n = RoundDoubleModeNode::make(_gvn, arg, RoundDoubleModeNode::rmode_floor); break;
 1800   case vmIntrinsics::_rint:   n = RoundDoubleModeNode::make(_gvn, arg, RoundDoubleModeNode::rmode_rint); break;
 1801   case vmIntrinsics::_roundD: n = new RoundDNode(arg); break;
 1802   case vmIntrinsics::_dcopySign: n = CopySignDNode::make(_gvn, arg, argument(2)); break;
 1803   case vmIntrinsics::_dsignum: n = SignumDNode::make(_gvn, arg); break;
 1804   default:  fatal_unexpected_iid(id);  break;
 1805   }
 1806   set_result(_gvn.transform(n));
 1807   return true;
 1808 }
 1809 
 1810 //------------------------------inline_math-----------------------------------
 1811 // public static float Math.abs(float)
 1812 // public static int Math.abs(int)
 1813 // public static long Math.abs(long)
 1814 bool LibraryCallKit::inline_math(vmIntrinsics::ID id) {
 1815   Node* arg = argument(0);
 1816   Node* n = nullptr;
 1817   switch (id) {
 1818   case vmIntrinsics::_fabs:   n = new AbsFNode(                arg);  break;
 1819   case vmIntrinsics::_iabs:   n = new AbsINode(                arg);  break;
 1820   case vmIntrinsics::_labs:   n = new AbsLNode(                arg);  break;
 1821   case vmIntrinsics::_fcopySign: n = new CopySignFNode(arg, argument(1)); break;
 1822   case vmIntrinsics::_fsignum: n = SignumFNode::make(_gvn, arg); break;
 1823   case vmIntrinsics::_roundF: n = new RoundFNode(arg); break;
 1824   default:  fatal_unexpected_iid(id);  break;
 1825   }
 1826   set_result(_gvn.transform(n));
 1827   return true;
 1828 }
 1829 
 1830 //------------------------------runtime_math-----------------------------
 1831 bool LibraryCallKit::runtime_math(const TypeFunc* call_type, address funcAddr, const char* funcName) {
 1832   assert(call_type == OptoRuntime::Math_DD_D_Type() || call_type == OptoRuntime::Math_D_D_Type(),
 1833          "must be (DD)D or (D)D type");
 1834 
 1835   // Inputs
 1836   Node* a = argument(0);
 1837   Node* b = (call_type == OptoRuntime::Math_DD_D_Type()) ? argument(2) : nullptr;
 1838 
 1839   const TypePtr* no_memory_effects = nullptr;
 1840   Node* trig = make_runtime_call(RC_LEAF | RC_PURE, call_type, funcAddr, funcName,
 1841                                  no_memory_effects,
 1842                                  a, top(), b, b ? top() : nullptr);
 1843   Node* value = _gvn.transform(new ProjNode(trig, TypeFunc::Parms+0));
 1844 #ifdef ASSERT
 1845   Node* value_top = _gvn.transform(new ProjNode(trig, TypeFunc::Parms+1));
 1846   assert(value_top == top(), "second value must be top");
 1847 #endif
 1848 
 1849   set_result(value);
 1850   return true;
 1851 }
 1852 
 1853 //------------------------------inline_math_pow-----------------------------
 1854 bool LibraryCallKit::inline_math_pow() {
 1855   Node* base = argument(0);
 1856   Node* exp = argument(2);
 1857 
 1858   CallNode* pow = new PowDNode(C, base, exp);
 1859   set_predefined_input_for_runtime_call(pow);
 1860   pow = _gvn.transform(pow)->as_CallLeafPure();
 1861   set_predefined_output_for_runtime_call(pow);
 1862   Node* result = _gvn.transform(new ProjNode(pow, TypeFunc::Parms + 0));
 1863   record_for_igvn(pow);
 1864   set_result(result);
 1865   return true;
 1866 }
 1867 
 1868 //------------------------------inline_math_native-----------------------------
 1869 bool LibraryCallKit::inline_math_native(vmIntrinsics::ID id) {
 1870   switch (id) {
 1871   case vmIntrinsics::_dsin:
 1872     return StubRoutines::dsin() != nullptr ?
 1873       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dsin(), "dsin") :
 1874       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dsin),   "SIN");
 1875   case vmIntrinsics::_dcos:
 1876     return StubRoutines::dcos() != nullptr ?
 1877       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dcos(), "dcos") :
 1878       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dcos),   "COS");
 1879   case vmIntrinsics::_dtan:
 1880     return StubRoutines::dtan() != nullptr ?
 1881       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dtan(), "dtan") :
 1882       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dtan), "TAN");
 1883   case vmIntrinsics::_dsinh:
 1884     return StubRoutines::dsinh() != nullptr ?
 1885       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dsinh(), "dsinh") : false;
 1886   case vmIntrinsics::_dtanh:
 1887     return StubRoutines::dtanh() != nullptr ?
 1888       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dtanh(), "dtanh") : false;
 1889   case vmIntrinsics::_dcbrt:
 1890     return StubRoutines::dcbrt() != nullptr ?
 1891       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dcbrt(), "dcbrt") : false;
 1892   case vmIntrinsics::_dexp:
 1893     return StubRoutines::dexp() != nullptr ?
 1894       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dexp(),  "dexp") :
 1895       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dexp),  "EXP");
 1896   case vmIntrinsics::_dlog:
 1897     return StubRoutines::dlog() != nullptr ?
 1898       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dlog(), "dlog") :
 1899       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dlog),   "LOG");
 1900   case vmIntrinsics::_dlog10:
 1901     return StubRoutines::dlog10() != nullptr ?
 1902       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dlog10(), "dlog10") :
 1903       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dlog10), "LOG10");
 1904 
 1905   case vmIntrinsics::_roundD: return Matcher::match_rule_supported(Op_RoundD) ? inline_double_math(id) : false;
 1906   case vmIntrinsics::_ceil:
 1907   case vmIntrinsics::_floor:
 1908   case vmIntrinsics::_rint:   return Matcher::match_rule_supported(Op_RoundDoubleMode) ? inline_double_math(id) : false;
 1909 
 1910   case vmIntrinsics::_dsqrt:
 1911   case vmIntrinsics::_dsqrt_strict:
 1912                               return Matcher::match_rule_supported(Op_SqrtD) ? inline_double_math(id) : false;
 1913   case vmIntrinsics::_dabs:   return Matcher::has_match_rule(Op_AbsD)   ? inline_double_math(id) : false;
 1914   case vmIntrinsics::_fabs:   return Matcher::match_rule_supported(Op_AbsF)   ? inline_math(id) : false;
 1915   case vmIntrinsics::_iabs:   return Matcher::match_rule_supported(Op_AbsI)   ? inline_math(id) : false;
 1916   case vmIntrinsics::_labs:   return Matcher::match_rule_supported(Op_AbsL)   ? inline_math(id) : false;
 1917 
 1918   case vmIntrinsics::_dpow:      return inline_math_pow();
 1919   case vmIntrinsics::_dcopySign: return inline_double_math(id);
 1920   case vmIntrinsics::_fcopySign: return inline_math(id);
 1921   case vmIntrinsics::_dsignum: return Matcher::match_rule_supported(Op_SignumD) ? inline_double_math(id) : false;
 1922   case vmIntrinsics::_fsignum: return Matcher::match_rule_supported(Op_SignumF) ? inline_math(id) : false;
 1923   case vmIntrinsics::_roundF: return Matcher::match_rule_supported(Op_RoundF) ? inline_math(id) : false;
 1924 
 1925    // These intrinsics are not yet correctly implemented
 1926   case vmIntrinsics::_datan2:
 1927     return false;
 1928 
 1929   default:
 1930     fatal_unexpected_iid(id);
 1931     return false;
 1932   }
 1933 }
 1934 
 1935 //----------------------------inline_notify-----------------------------------*
 1936 bool LibraryCallKit::inline_notify(vmIntrinsics::ID id) {
 1937   const TypeFunc* ftype = OptoRuntime::monitor_notify_Type();
 1938   address func;
 1939   if (id == vmIntrinsics::_notify) {
 1940     func = OptoRuntime::monitor_notify_Java();
 1941   } else {
 1942     func = OptoRuntime::monitor_notifyAll_Java();
 1943   }
 1944   Node* call = make_runtime_call(RC_NO_LEAF, ftype, func, nullptr, TypeRawPtr::BOTTOM, argument(0));
 1945   make_slow_call_ex(call, env()->Throwable_klass(), false);
 1946   return true;
 1947 }
 1948 
 1949 
 1950 //----------------------------inline_min_max-----------------------------------
 1951 bool LibraryCallKit::inline_min_max(vmIntrinsics::ID id) {
 1952   Node* a = nullptr;
 1953   Node* b = nullptr;
 1954   Node* n = nullptr;
 1955   switch (id) {
 1956     case vmIntrinsics::_min:
 1957     case vmIntrinsics::_max:
 1958     case vmIntrinsics::_minF:
 1959     case vmIntrinsics::_maxF:
 1960     case vmIntrinsics::_minF_strict:
 1961     case vmIntrinsics::_maxF_strict:
 1962     case vmIntrinsics::_min_strict:
 1963     case vmIntrinsics::_max_strict:
 1964       assert(callee()->signature()->size() == 2, "minF/maxF has 2 parameters of size 1 each.");
 1965       a = argument(0);
 1966       b = argument(1);
 1967       break;
 1968     case vmIntrinsics::_minD:
 1969     case vmIntrinsics::_maxD:
 1970     case vmIntrinsics::_minD_strict:
 1971     case vmIntrinsics::_maxD_strict:
 1972       assert(callee()->signature()->size() == 4, "minD/maxD has 2 parameters of size 2 each.");
 1973       a = argument(0);
 1974       b = argument(2);
 1975       break;
 1976     case vmIntrinsics::_minL:
 1977     case vmIntrinsics::_maxL:
 1978       assert(callee()->signature()->size() == 4, "minL/maxL has 2 parameters of size 2 each.");
 1979       a = argument(0);
 1980       b = argument(2);
 1981       break;
 1982     default:
 1983       fatal_unexpected_iid(id);
 1984       break;
 1985   }
 1986 
 1987   switch (id) {
 1988     case vmIntrinsics::_min:
 1989     case vmIntrinsics::_min_strict:
 1990       n = new MinINode(a, b);
 1991       break;
 1992     case vmIntrinsics::_max:
 1993     case vmIntrinsics::_max_strict:
 1994       n = new MaxINode(a, b);
 1995       break;
 1996     case vmIntrinsics::_minF:
 1997     case vmIntrinsics::_minF_strict:
 1998       n = new MinFNode(a, b);
 1999       break;
 2000     case vmIntrinsics::_maxF:
 2001     case vmIntrinsics::_maxF_strict:
 2002       n = new MaxFNode(a, b);
 2003       break;
 2004     case vmIntrinsics::_minD:
 2005     case vmIntrinsics::_minD_strict:
 2006       n = new MinDNode(a, b);
 2007       break;
 2008     case vmIntrinsics::_maxD:
 2009     case vmIntrinsics::_maxD_strict:
 2010       n = new MaxDNode(a, b);
 2011       break;
 2012     case vmIntrinsics::_minL:
 2013       n = new MinLNode(_gvn.C, a, b);
 2014       break;
 2015     case vmIntrinsics::_maxL:
 2016       n = new MaxLNode(_gvn.C, a, b);
 2017       break;
 2018     default:
 2019       fatal_unexpected_iid(id);
 2020       break;
 2021   }
 2022 
 2023   set_result(_gvn.transform(n));
 2024   return true;
 2025 }
 2026 
 2027 bool LibraryCallKit::inline_math_mathExact(Node* math, Node* test) {
 2028   if (builtin_throw_too_many_traps(Deoptimization::Reason_intrinsic,
 2029                                    env()->ArithmeticException_instance())) {
 2030     // It has been already too many times, but we cannot use builtin_throw (e.g. we care about backtraces),
 2031     // so let's bail out intrinsic rather than risking deopting again.
 2032     return false;
 2033   }
 2034 
 2035   Node* bol = _gvn.transform( new BoolNode(test, BoolTest::overflow) );
 2036   IfNode* check = create_and_map_if(control(), bol, PROB_UNLIKELY_MAG(3), COUNT_UNKNOWN);
 2037   Node* fast_path = _gvn.transform( new IfFalseNode(check));
 2038   Node* slow_path = _gvn.transform( new IfTrueNode(check) );
 2039 
 2040   {
 2041     PreserveJVMState pjvms(this);
 2042     PreserveReexecuteState preexecs(this);
 2043     jvms()->set_should_reexecute(true);
 2044 
 2045     set_control(slow_path);
 2046     set_i_o(i_o());
 2047 
 2048     builtin_throw(Deoptimization::Reason_intrinsic,
 2049                   env()->ArithmeticException_instance(),
 2050                   /*allow_too_many_traps*/ false);
 2051   }
 2052 
 2053   set_control(fast_path);
 2054   set_result(math);
 2055   return true;
 2056 }
 2057 
 2058 template <typename OverflowOp>
 2059 bool LibraryCallKit::inline_math_overflow(Node* arg1, Node* arg2) {
 2060   typedef typename OverflowOp::MathOp MathOp;
 2061 
 2062   MathOp* mathOp = new MathOp(arg1, arg2);
 2063   Node* operation = _gvn.transform( mathOp );
 2064   Node* ofcheck = _gvn.transform( new OverflowOp(arg1, arg2) );
 2065   return inline_math_mathExact(operation, ofcheck);
 2066 }
 2067 
 2068 bool LibraryCallKit::inline_math_addExactI(bool is_increment) {
 2069   return inline_math_overflow<OverflowAddINode>(argument(0), is_increment ? intcon(1) : argument(1));
 2070 }
 2071 
 2072 bool LibraryCallKit::inline_math_addExactL(bool is_increment) {
 2073   return inline_math_overflow<OverflowAddLNode>(argument(0), is_increment ? longcon(1) : argument(2));
 2074 }
 2075 
 2076 bool LibraryCallKit::inline_math_subtractExactI(bool is_decrement) {
 2077   return inline_math_overflow<OverflowSubINode>(argument(0), is_decrement ? intcon(1) : argument(1));
 2078 }
 2079 
 2080 bool LibraryCallKit::inline_math_subtractExactL(bool is_decrement) {
 2081   return inline_math_overflow<OverflowSubLNode>(argument(0), is_decrement ? longcon(1) : argument(2));
 2082 }
 2083 
 2084 bool LibraryCallKit::inline_math_negateExactI() {
 2085   return inline_math_overflow<OverflowSubINode>(intcon(0), argument(0));
 2086 }
 2087 
 2088 bool LibraryCallKit::inline_math_negateExactL() {
 2089   return inline_math_overflow<OverflowSubLNode>(longcon(0), argument(0));
 2090 }
 2091 
 2092 bool LibraryCallKit::inline_math_multiplyExactI() {
 2093   return inline_math_overflow<OverflowMulINode>(argument(0), argument(1));
 2094 }
 2095 
 2096 bool LibraryCallKit::inline_math_multiplyExactL() {
 2097   return inline_math_overflow<OverflowMulLNode>(argument(0), argument(2));
 2098 }
 2099 
 2100 bool LibraryCallKit::inline_math_multiplyHigh() {
 2101   set_result(_gvn.transform(new MulHiLNode(argument(0), argument(2))));
 2102   return true;
 2103 }
 2104 
 2105 bool LibraryCallKit::inline_math_unsignedMultiplyHigh() {
 2106   set_result(_gvn.transform(new UMulHiLNode(argument(0), argument(2))));
 2107   return true;
 2108 }
 2109 
 2110 inline int
 2111 LibraryCallKit::classify_unsafe_addr(Node* &base, Node* &offset, BasicType type) {
 2112   const TypePtr* base_type = TypePtr::NULL_PTR;
 2113   if (base != nullptr)  base_type = _gvn.type(base)->isa_ptr();
 2114   if (base_type == nullptr) {
 2115     // Unknown type.
 2116     return Type::AnyPtr;
 2117   } else if (_gvn.type(base->uncast()) == TypePtr::NULL_PTR) {
 2118     // Since this is a null+long form, we have to switch to a rawptr.
 2119     base   = _gvn.transform(new CastX2PNode(offset));
 2120     offset = MakeConX(0);
 2121     return Type::RawPtr;
 2122   } else if (base_type->base() == Type::RawPtr) {
 2123     return Type::RawPtr;
 2124   } else if (base_type->isa_oopptr()) {
 2125     // Base is never null => always a heap address.
 2126     if (!TypePtr::NULL_PTR->higher_equal(base_type)) {
 2127       return Type::OopPtr;
 2128     }
 2129     // Offset is small => always a heap address.
 2130     const TypeX* offset_type = _gvn.type(offset)->isa_intptr_t();
 2131     if (offset_type != nullptr &&
 2132         base_type->offset() == 0 &&     // (should always be?)
 2133         offset_type->_lo >= 0 &&
 2134         !MacroAssembler::needs_explicit_null_check(offset_type->_hi)) {
 2135       return Type::OopPtr;
 2136     } else if (type == T_OBJECT) {
 2137       // off heap access to an oop doesn't make any sense. Has to be on
 2138       // heap.
 2139       return Type::OopPtr;
 2140     }
 2141     // Otherwise, it might either be oop+off or null+addr.
 2142     return Type::AnyPtr;
 2143   } else {
 2144     // No information:
 2145     return Type::AnyPtr;
 2146   }
 2147 }
 2148 
 2149 Node* LibraryCallKit::make_unsafe_address(Node*& base, Node* offset, BasicType type, bool can_cast) {
 2150   Node* uncasted_base = base;
 2151   int kind = classify_unsafe_addr(uncasted_base, offset, type);
 2152   if (kind == Type::RawPtr) {
 2153     return off_heap_plus_addr(uncasted_base, offset);
 2154   } else if (kind == Type::AnyPtr) {
 2155     assert(base == uncasted_base, "unexpected base change");
 2156     if (can_cast) {
 2157       if (!_gvn.type(base)->speculative_maybe_null() &&
 2158           !too_many_traps(Deoptimization::Reason_speculate_null_check)) {
 2159         // According to profiling, this access is always on
 2160         // heap. Casting the base to not null and thus avoiding membars
 2161         // around the access should allow better optimizations
 2162         Node* null_ctl = top();
 2163         base = null_check_oop(base, &null_ctl, true, true, true);
 2164         assert(null_ctl->is_top(), "no null control here");
 2165         return basic_plus_adr(base, offset);
 2166       } else if (_gvn.type(base)->speculative_always_null() &&
 2167                  !too_many_traps(Deoptimization::Reason_speculate_null_assert)) {
 2168         // According to profiling, this access is always off
 2169         // heap.
 2170         base = null_assert(base);
 2171         Node* raw_base = _gvn.transform(new CastX2PNode(offset));
 2172         offset = MakeConX(0);
 2173         return off_heap_plus_addr(raw_base, offset);
 2174       }
 2175     }
 2176     // We don't know if it's an on heap or off heap access. Fall back
 2177     // to raw memory access.
 2178     Node* raw = _gvn.transform(new CheckCastPPNode(control(), base, TypeRawPtr::BOTTOM));
 2179     return off_heap_plus_addr(raw, offset);
 2180   } else {
 2181     assert(base == uncasted_base, "unexpected base change");
 2182     // We know it's an on heap access so base can't be null
 2183     if (TypePtr::NULL_PTR->higher_equal(_gvn.type(base))) {
 2184       base = must_be_not_null(base, true);
 2185     }
 2186     return basic_plus_adr(base, offset);
 2187   }
 2188 }
 2189 
 2190 //--------------------------inline_number_methods-----------------------------
 2191 // inline int     Integer.numberOfLeadingZeros(int)
 2192 // inline int        Long.numberOfLeadingZeros(long)
 2193 //
 2194 // inline int     Integer.numberOfTrailingZeros(int)
 2195 // inline int        Long.numberOfTrailingZeros(long)
 2196 //
 2197 // inline int     Integer.bitCount(int)
 2198 // inline int        Long.bitCount(long)
 2199 //
 2200 // inline char  Character.reverseBytes(char)
 2201 // inline short     Short.reverseBytes(short)
 2202 // inline int     Integer.reverseBytes(int)
 2203 // inline long       Long.reverseBytes(long)
 2204 bool LibraryCallKit::inline_number_methods(vmIntrinsics::ID id) {
 2205   Node* arg = argument(0);
 2206   Node* n = nullptr;
 2207   switch (id) {
 2208   case vmIntrinsics::_numberOfLeadingZeros_i:   n = new CountLeadingZerosINode( arg); break;
 2209   case vmIntrinsics::_numberOfLeadingZeros_l:   n = new CountLeadingZerosLNode( arg); break;
 2210   case vmIntrinsics::_numberOfTrailingZeros_i:  n = new CountTrailingZerosINode(arg); break;
 2211   case vmIntrinsics::_numberOfTrailingZeros_l:  n = new CountTrailingZerosLNode(arg); break;
 2212   case vmIntrinsics::_bitCount_i:               n = new PopCountINode(          arg); break;
 2213   case vmIntrinsics::_bitCount_l:               n = new PopCountLNode(          arg); break;
 2214   case vmIntrinsics::_reverseBytes_c:           n = new ReverseBytesUSNode(     arg); break;
 2215   case vmIntrinsics::_reverseBytes_s:           n = new ReverseBytesSNode(      arg); break;
 2216   case vmIntrinsics::_reverseBytes_i:           n = new ReverseBytesINode(      arg); break;
 2217   case vmIntrinsics::_reverseBytes_l:           n = new ReverseBytesLNode(      arg); break;
 2218   case vmIntrinsics::_reverse_i:                n = new ReverseINode(           arg); break;
 2219   case vmIntrinsics::_reverse_l:                n = new ReverseLNode(           arg); break;
 2220   default:  fatal_unexpected_iid(id);  break;
 2221   }
 2222   set_result(_gvn.transform(n));
 2223   return true;
 2224 }
 2225 
 2226 //--------------------------inline_bitshuffle_methods-----------------------------
 2227 // inline int Integer.compress(int, int)
 2228 // inline int Integer.expand(int, int)
 2229 // inline long Long.compress(long, long)
 2230 // inline long Long.expand(long, long)
 2231 bool LibraryCallKit::inline_bitshuffle_methods(vmIntrinsics::ID id) {
 2232   Node* n = nullptr;
 2233   switch (id) {
 2234     case vmIntrinsics::_compress_i:  n = new CompressBitsNode(argument(0), argument(1), TypeInt::INT); break;
 2235     case vmIntrinsics::_expand_i:    n = new ExpandBitsNode(argument(0),  argument(1), TypeInt::INT); break;
 2236     case vmIntrinsics::_compress_l:  n = new CompressBitsNode(argument(0), argument(2), TypeLong::LONG); break;
 2237     case vmIntrinsics::_expand_l:    n = new ExpandBitsNode(argument(0), argument(2), TypeLong::LONG); break;
 2238     default:  fatal_unexpected_iid(id);  break;
 2239   }
 2240   set_result(_gvn.transform(n));
 2241   return true;
 2242 }
 2243 
 2244 //--------------------------inline_number_methods-----------------------------
 2245 // inline int Integer.compareUnsigned(int, int)
 2246 // inline int    Long.compareUnsigned(long, long)
 2247 bool LibraryCallKit::inline_compare_unsigned(vmIntrinsics::ID id) {
 2248   Node* arg1 = argument(0);
 2249   Node* arg2 = (id == vmIntrinsics::_compareUnsigned_l) ? argument(2) : argument(1);
 2250   Node* n = nullptr;
 2251   switch (id) {
 2252     case vmIntrinsics::_compareUnsigned_i:   n = new CmpU3Node(arg1, arg2);  break;
 2253     case vmIntrinsics::_compareUnsigned_l:   n = new CmpUL3Node(arg1, arg2); break;
 2254     default:  fatal_unexpected_iid(id);  break;
 2255   }
 2256   set_result(_gvn.transform(n));
 2257   return true;
 2258 }
 2259 
 2260 //--------------------------inline_unsigned_divmod_methods-----------------------------
 2261 // inline int Integer.divideUnsigned(int, int)
 2262 // inline int Integer.remainderUnsigned(int, int)
 2263 // inline long Long.divideUnsigned(long, long)
 2264 // inline long Long.remainderUnsigned(long, long)
 2265 bool LibraryCallKit::inline_divmod_methods(vmIntrinsics::ID id) {
 2266   Node* n = nullptr;
 2267   switch (id) {
 2268     case vmIntrinsics::_divideUnsigned_i: {
 2269       zero_check_int(argument(1));
 2270       // Compile-time detect of null-exception
 2271       if (stopped()) {
 2272         return true; // keep the graph constructed so far
 2273       }
 2274       n = new UDivINode(control(), argument(0), argument(1));
 2275       break;
 2276     }
 2277     case vmIntrinsics::_divideUnsigned_l: {
 2278       zero_check_long(argument(2));
 2279       // Compile-time detect of null-exception
 2280       if (stopped()) {
 2281         return true; // keep the graph constructed so far
 2282       }
 2283       n = new UDivLNode(control(), argument(0), argument(2));
 2284       break;
 2285     }
 2286     case vmIntrinsics::_remainderUnsigned_i: {
 2287       zero_check_int(argument(1));
 2288       // Compile-time detect of null-exception
 2289       if (stopped()) {
 2290         return true; // keep the graph constructed so far
 2291       }
 2292       n = new UModINode(control(), argument(0), argument(1));
 2293       break;
 2294     }
 2295     case vmIntrinsics::_remainderUnsigned_l: {
 2296       zero_check_long(argument(2));
 2297       // Compile-time detect of null-exception
 2298       if (stopped()) {
 2299         return true; // keep the graph constructed so far
 2300       }
 2301       n = new UModLNode(control(), argument(0), argument(2));
 2302       break;
 2303     }
 2304     default:  fatal_unexpected_iid(id);  break;
 2305   }
 2306   set_result(_gvn.transform(n));
 2307   return true;
 2308 }
 2309 
 2310 //----------------------------inline_unsafe_access----------------------------
 2311 
 2312 const TypeOopPtr* LibraryCallKit::sharpen_unsafe_type(Compile::AliasType* alias_type, const TypePtr *adr_type) {
 2313   // Attempt to infer a sharper value type from the offset and base type.
 2314   ciKlass* sharpened_klass = nullptr;
 2315   bool null_free = false;
 2316 
 2317   // See if it is an instance field, with an object type.
 2318   if (alias_type->field() != nullptr) {
 2319     if (alias_type->field()->type()->is_klass()) {
 2320       sharpened_klass = alias_type->field()->type()->as_klass();
 2321       null_free = alias_type->field()->is_null_free();
 2322     }
 2323   }
 2324 
 2325   const TypeOopPtr* result = nullptr;
 2326   // See if it is a narrow oop array.
 2327   if (adr_type->isa_aryptr()) {
 2328     if (adr_type->offset() >= refArrayOopDesc::base_offset_in_bytes()) {
 2329       const TypeOopPtr* elem_type = adr_type->is_aryptr()->elem()->make_oopptr();
 2330       null_free = adr_type->is_aryptr()->is_null_free();
 2331       if (elem_type != nullptr && elem_type->is_loaded()) {
 2332         // Sharpen the value type.
 2333         result = elem_type;
 2334       }
 2335     }
 2336   }
 2337 
 2338   // The sharpened class might be unloaded if there is no class loader
 2339   // contraint in place.
 2340   if (result == nullptr && sharpened_klass != nullptr && sharpened_klass->is_loaded()) {
 2341     // Sharpen the value type.
 2342     result = TypeOopPtr::make_from_klass(sharpened_klass);
 2343     if (null_free) {
 2344       result = result->join_speculative(TypePtr::NOTNULL)->is_oopptr();
 2345     }
 2346   }
 2347   if (result != nullptr) {
 2348 #ifndef PRODUCT
 2349     if (C->print_intrinsics() || C->print_inlining()) {
 2350       tty->print("  from base type:  ");  adr_type->dump(); tty->cr();
 2351       tty->print("  sharpened value: ");  result->dump();    tty->cr();
 2352     }
 2353 #endif
 2354   }
 2355   return result;
 2356 }
 2357 
 2358 DecoratorSet LibraryCallKit::mo_decorator_for_access_kind(AccessKind kind) {
 2359   switch (kind) {
 2360       case Relaxed:
 2361         return MO_UNORDERED;
 2362       case Opaque:
 2363         return MO_RELAXED;
 2364       case Acquire:
 2365         return MO_ACQUIRE;
 2366       case Release:
 2367         return MO_RELEASE;
 2368       case Volatile:
 2369         return MO_SEQ_CST;
 2370       default:
 2371         ShouldNotReachHere();
 2372         return 0;
 2373   }
 2374 }
 2375 
 2376 bool LibraryCallKit::inline_unsafe_access(bool is_store, const BasicType type, const AccessKind kind, const bool unaligned) {
 2377   if (callee()->is_static())  return false;  // caller must have the capability!
 2378   DecoratorSet decorators = C2_UNSAFE_ACCESS;
 2379   guarantee(!is_store || kind != Acquire, "Acquire accesses can be produced only for loads");
 2380   guarantee( is_store || kind != Release, "Release accesses can be produced only for stores");
 2381   assert(type != T_OBJECT || !unaligned, "unaligned access not supported with object type");
 2382 
 2383   if (is_reference_type(type)) {
 2384     decorators |= ON_UNKNOWN_OOP_REF;
 2385   }
 2386 
 2387   if (unaligned) {
 2388     decorators |= C2_UNALIGNED;
 2389   }
 2390 
 2391 #ifndef PRODUCT
 2392   {
 2393     ResourceMark rm;
 2394     // Check the signatures.
 2395     ciSignature* sig = callee()->signature();
 2396 #ifdef ASSERT
 2397     if (!is_store) {
 2398       // Object getReference(Object base, int/long offset), etc.
 2399       BasicType rtype = sig->return_type()->basic_type();
 2400       assert(rtype == type, "getter must return the expected value");
 2401       assert(sig->count() == 2, "oop getter has 2 arguments");
 2402       assert(sig->type_at(0)->basic_type() == T_OBJECT, "getter base is object");
 2403       assert(sig->type_at(1)->basic_type() == T_LONG, "getter offset is correct");
 2404     } else {
 2405       // void putReference(Object base, int/long offset, Object x), etc.
 2406       assert(sig->return_type()->basic_type() == T_VOID, "putter must not return a value");
 2407       assert(sig->count() == 3, "oop putter has 3 arguments");
 2408       assert(sig->type_at(0)->basic_type() == T_OBJECT, "putter base is object");
 2409       assert(sig->type_at(1)->basic_type() == T_LONG, "putter offset is correct");
 2410       BasicType vtype = sig->type_at(sig->count()-1)->basic_type();
 2411       assert(vtype == type, "putter must accept the expected value");
 2412     }
 2413 #endif // ASSERT
 2414  }
 2415 #endif //PRODUCT
 2416 
 2417   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
 2418 
 2419   Node* receiver = argument(0);  // type: oop
 2420 
 2421   // Build address expression.
 2422   Node* heap_base_oop = top();
 2423 
 2424   // The base is either a Java object or a value produced by Unsafe.staticFieldBase
 2425   Node* base = argument(1);  // type: oop
 2426   // The offset is a value produced by Unsafe.staticFieldOffset or Unsafe.objectFieldOffset
 2427   Node* offset = argument(2);  // type: long
 2428   // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
 2429   // to be plain byte offsets, which are also the same as those accepted
 2430   // by oopDesc::field_addr.
 2431   assert(Unsafe_field_offset_to_byte_offset(11) == 11,
 2432          "fieldOffset must be byte-scaled");
 2433 
 2434   if (base->is_InlineType()) {
 2435     assert(!is_store, "InlineTypeNodes are non-larval value objects");
 2436     InlineTypeNode* vt = base->as_InlineType();
 2437     if (offset->is_Con()) {
 2438       long off = find_long_con(offset, 0);
 2439       ciInlineKlass* vk = vt->type()->inline_klass();
 2440       if ((long)(int)off != off || !vk->contains_field_offset(off)) {
 2441         return false;
 2442       }
 2443 
 2444       ciField* field = vk->get_non_flat_field_by_offset(off);
 2445       if (field != nullptr) {
 2446         BasicType bt = type2field[field->type()->basic_type()];
 2447         if (bt == T_ARRAY || bt == T_NARROWOOP) {
 2448           bt = T_OBJECT;
 2449         }
 2450         if (bt == type && !field->is_flat()) {
 2451           Node* value = vt->field_value_by_offset(off, false);
 2452           const Type* value_type = _gvn.type(value);
 2453           if (value_type->is_inlinetypeptr()) {
 2454             value = InlineTypeNode::make_from_oop(this, value, value_type->inline_klass());
 2455           }
 2456           set_result(value);
 2457           return true;
 2458         }
 2459       }
 2460     }
 2461     {
 2462       // Re-execute the unsafe access if allocation triggers deoptimization.
 2463       PreserveReexecuteState preexecs(this);
 2464       jvms()->set_should_reexecute(true);
 2465       vt = vt->buffer(this);
 2466     }
 2467     base = vt->get_oop();
 2468   }
 2469 
 2470   // 32-bit machines ignore the high half!
 2471   offset = ConvL2X(offset);
 2472 
 2473   // Save state and restore on bailout
 2474   SavedState old_state(this);
 2475 
 2476   Node* adr = make_unsafe_address(base, offset, type, kind == Relaxed);
 2477   assert(!stopped(), "Inlining of unsafe access failed: address construction stopped unexpectedly");
 2478 
 2479   bool is_non_heap_access = (_gvn.type(base->uncast())->isa_ptr() == TypePtr::NULL_PTR);
 2480   if (is_non_heap_access) {
 2481     if (type != T_OBJECT) {
 2482       decorators |= IN_NATIVE; // off-heap primitive access
 2483     } else {
 2484       return false; // off-heap oop accesses are not supported
 2485     }
 2486   } else {
 2487     heap_base_oop = base; // on-heap or mixed access
 2488   }
 2489 
 2490   // Can base be null? Otherwise, always on-heap access.
 2491   bool can_access_non_heap = TypePtr::NULL_PTR->higher_equal(_gvn.type(base));
 2492 
 2493   assert(!is_non_heap_access || can_access_non_heap, "sanity"); // is_non_heap_access implies can_access_non_heap
 2494 
 2495   if (!can_access_non_heap) {
 2496     decorators |= IN_HEAP;
 2497   }
 2498 
 2499   Node* val = is_store ? argument(4) : nullptr;
 2500 
 2501   const TypePtr* adr_type = _gvn.type(adr)->isa_ptr();
 2502   if (adr_type == TypePtr::NULL_PTR) {
 2503     return false; // off-heap access with zero address
 2504   }
 2505 
 2506   // Try to categorize the address.
 2507   Compile::AliasType* alias_type = C->alias_type(adr_type);
 2508   assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
 2509 
 2510   assert((alias_type->index() == Compile::AliasIdxRaw) ==
 2511          (is_non_heap_access || (can_access_non_heap && alias_type->field() == nullptr)), "wrong alias");
 2512 
 2513   if (alias_type->adr_type() == TypeInstPtr::KLASS ||
 2514       alias_type->adr_type() == TypeAryPtr::RANGE) {
 2515     return false; // not supported
 2516   }
 2517 
 2518   bool mismatched = false;
 2519   BasicType bt = T_ILLEGAL;
 2520   ciField* field = nullptr;
 2521   if (adr_type->isa_instptr()) {
 2522     const TypeInstPtr* instptr = adr_type->is_instptr();
 2523     ciInstanceKlass* k = instptr->instance_klass();
 2524     int off = instptr->offset();
 2525     if (instptr->const_oop() != nullptr &&
 2526         k == ciEnv::current()->Class_klass() &&
 2527         instptr->offset() >= (k->size_helper() * wordSize)) {
 2528       k = instptr->const_oop()->as_instance()->java_lang_Class_klass()->as_instance_klass();
 2529       field = k->get_field_by_offset(off, true);
 2530     } else {
 2531       field = k->get_non_flat_field_by_offset(off);
 2532     }
 2533     if (field != nullptr) {
 2534       bt = type2field[field->type()->basic_type()];
 2535     }
 2536     if (bt != alias_type->basic_type()) {
 2537       // Type mismatch. Is it an access to a nested flat field?
 2538       field = k->get_field_by_offset(off, false);
 2539       if (field != nullptr) {
 2540         bt = type2field[field->type()->basic_type()];
 2541       }
 2542     }
 2543     assert(bt == alias_type->basic_type(), "should match");
 2544   } else {
 2545     bt = alias_type->basic_type();
 2546   }
 2547 
 2548   if (bt != T_ILLEGAL) {
 2549     assert(alias_type->adr_type()->is_oopptr(), "should be on-heap access");
 2550     if (bt == T_BYTE && adr_type->isa_aryptr()) {
 2551       // Alias type doesn't differentiate between byte[] and boolean[]).
 2552       // Use address type to get the element type.
 2553       bt = adr_type->is_aryptr()->elem()->array_element_basic_type();
 2554     }
 2555     if (is_reference_type(bt, true)) {
 2556       // accessing an array field with getReference is not a mismatch
 2557       bt = T_OBJECT;
 2558     }
 2559     if ((bt == T_OBJECT) != (type == T_OBJECT)) {
 2560       // Don't intrinsify mismatched object accesses
 2561       return false;
 2562     }
 2563     mismatched = (bt != type);
 2564   } else if (alias_type->adr_type()->isa_oopptr()) {
 2565     mismatched = true; // conservatively mark all "wide" on-heap accesses as mismatched
 2566   }
 2567 
 2568   old_state.discard();
 2569   assert(!mismatched || alias_type->adr_type()->is_oopptr(), "off-heap access can't be mismatched");
 2570 
 2571   if (mismatched) {
 2572     decorators |= C2_MISMATCHED;
 2573   }
 2574 
 2575   // First guess at the value type.
 2576   const Type *value_type = Type::get_const_basic_type(type);
 2577 
 2578   // Figure out the memory ordering.
 2579   decorators |= mo_decorator_for_access_kind(kind);
 2580 
 2581   if (!is_store) {
 2582     if (type == T_OBJECT) {
 2583       const TypeOopPtr* tjp = sharpen_unsafe_type(alias_type, adr_type);
 2584       if (tjp != nullptr) {
 2585         value_type = tjp;
 2586       }
 2587     } else if (type == T_BOOLEAN) {
 2588       if (mismatched || alias_type->index() == Compile::AliasIdxRaw) {
 2589         value_type = TypeInt::UBYTE;
 2590       }
 2591     }
 2592   }
 2593 
 2594   receiver = null_check(receiver);
 2595   if (stopped()) {
 2596     return true;
 2597   }
 2598   // Heap pointers get a null-check from the interpreter,
 2599   // as a courtesy.  However, this is not guaranteed by Unsafe,
 2600   // and it is not possible to fully distinguish unintended nulls
 2601   // from intended ones in this API.
 2602 
 2603   if (!is_store) {
 2604     Node* p = nullptr;
 2605     // Try to constant fold a load from a constant field
 2606 
 2607     if (heap_base_oop != top() && field != nullptr && field->is_constant() && !field->is_flat() && !mismatched) {
 2608       // final or stable field
 2609       p = make_constant_from_field(field, heap_base_oop);
 2610     }
 2611 
 2612     if (p == nullptr) { // Could not constant fold the load
 2613       p = access_load_at(heap_base_oop, adr, adr_type, value_type, type, decorators);
 2614       const TypeOopPtr* ptr = value_type->make_oopptr();
 2615       if (ptr != nullptr && ptr->is_inlinetypeptr()) {
 2616         // Load a non-flattened inline type from memory
 2617         p = InlineTypeNode::make_from_oop(this, p, ptr->inline_klass());
 2618       }
 2619     }
 2620     if (type == T_ADDRESS) {
 2621       p = gvn().transform(new CastP2XNode(nullptr, p));
 2622       p = ConvX2UL(p);
 2623     } else if (type == T_BOOLEAN) {
 2624       // Truncate boolean values returned by unsafe operations.
 2625       p = gvn().transform(new AndINode(p, gvn().intcon(0x1)));
 2626     }
 2627     // The load node has the control of the preceding MemBarCPUOrder.  All
 2628     // following nodes will have the control of the MemBarCPUOrder inserted at
 2629     // the end of this method.  So, pushing the load onto the stack at a later
 2630     // point is fine.
 2631     set_result(p);
 2632   } else {
 2633     if (bt == T_ADDRESS) {
 2634       // Repackage the long as a pointer.
 2635       val = ConvL2X(val);
 2636       val = gvn().transform(new CastX2PNode(val));
 2637     }
 2638     access_store_at(heap_base_oop, adr, adr_type, val, value_type, type, decorators);
 2639   }
 2640 
 2641   return true;
 2642 }
 2643 
 2644 bool LibraryCallKit::inline_unsafe_flat_access(bool is_store, AccessKind kind) {
 2645 #ifdef ASSERT
 2646   {
 2647     ResourceMark rm;
 2648     // Check the signatures.
 2649     ciSignature* sig = callee()->signature();
 2650     assert(sig->type_at(0)->basic_type() == T_OBJECT, "base should be object, but is %s", type2name(sig->type_at(0)->basic_type()));
 2651     assert(sig->type_at(1)->basic_type() == T_LONG, "offset should be long, but is %s", type2name(sig->type_at(1)->basic_type()));
 2652     assert(sig->type_at(2)->basic_type() == T_INT, "layout kind should be int, but is %s", type2name(sig->type_at(3)->basic_type()));
 2653     assert(sig->type_at(3)->basic_type() == T_OBJECT, "value klass should be object, but is %s", type2name(sig->type_at(4)->basic_type()));
 2654     if (is_store) {
 2655       assert(sig->return_type()->basic_type() == T_VOID, "putter must not return a value, but returns %s", type2name(sig->return_type()->basic_type()));
 2656       assert(sig->count() == 5, "flat putter should have 5 arguments, but has %d", sig->count());
 2657       assert(sig->type_at(4)->basic_type() == T_OBJECT, "put value should be object, but is %s", type2name(sig->type_at(5)->basic_type()));
 2658     } else {
 2659       assert(sig->return_type()->basic_type() == T_OBJECT, "getter must return an object, but returns %s", type2name(sig->return_type()->basic_type()));
 2660       assert(sig->count() == 4, "flat getter should have 4 arguments, but has %d", sig->count());
 2661     }
 2662  }
 2663 #endif // ASSERT
 2664 
 2665   assert(kind == Relaxed, "Only plain accesses for now");
 2666   if (callee()->is_static()) {
 2667     // caller must have the capability!
 2668     return false;
 2669   }
 2670   C->set_has_unsafe_access(true);
 2671 
 2672   const TypeInstPtr* value_klass_node = _gvn.type(argument(5))->isa_instptr();
 2673   if (value_klass_node == nullptr || value_klass_node->const_oop() == nullptr) {
 2674     // parameter valueType is not a constant
 2675     return false;
 2676   }
 2677   ciType* mirror_type = value_klass_node->const_oop()->as_instance()->java_mirror_type();
 2678   if (!mirror_type->is_inlinetype()) {
 2679     // Dead code
 2680     return false;
 2681   }
 2682   ciInlineKlass* value_klass = mirror_type->as_inline_klass();
 2683 
 2684   const TypeInt* layout_type = _gvn.type(argument(4))->isa_int();
 2685   if (layout_type == nullptr || !layout_type->is_con()) {
 2686     // parameter layoutKind is not a constant
 2687     return false;
 2688   }
 2689   assert(layout_type->get_con() >= static_cast<int>(LayoutKind::REFERENCE) &&
 2690          layout_type->get_con() < static_cast<int>(LayoutKind::UNKNOWN),
 2691          "invalid layoutKind %d", layout_type->get_con());
 2692   LayoutKind layout = static_cast<LayoutKind>(layout_type->get_con());
 2693   assert(layout == LayoutKind::REFERENCE || LayoutKindHelper::is_flat(layout),
 2694          "unexpected layoutKind %d", layout_type->get_con());
 2695 
 2696   null_check(argument(0));
 2697   if (stopped()) {
 2698     return true;
 2699   }
 2700 
 2701   Node* base = must_be_not_null(argument(1), true);
 2702   Node* offset = argument(2);
 2703   const Type* base_type = _gvn.type(base);
 2704 
 2705   Node* ptr;
 2706   bool immutable_memory = false;
 2707   DecoratorSet decorators = C2_UNSAFE_ACCESS | IN_HEAP | MO_UNORDERED;
 2708   if (base_type->isa_instptr()) {
 2709     const TypeLong* offset_type = _gvn.type(offset)->isa_long();
 2710     if (offset_type == nullptr || !offset_type->is_con()) {
 2711       // Offset into a non-array should be a constant
 2712       decorators |= C2_MISMATCHED;
 2713     } else {
 2714       int offset_con = checked_cast<int>(offset_type->get_con());
 2715       ciInstanceKlass* base_klass = base_type->is_instptr()->instance_klass();
 2716       ciField* field = base_klass->get_non_flat_field_by_offset(offset_con);
 2717       if (field == nullptr) {
 2718         assert(!base_klass->is_final(), "non-existence field at offset %d of class %s", offset_con, base_klass->name()->as_utf8());
 2719         decorators |= C2_MISMATCHED;
 2720       } else {
 2721         assert(field->type() == value_klass, "field at offset %d of %s is of type %s, but valueType is %s",
 2722                offset_con, base_klass->name()->as_utf8(), field->type()->name(), value_klass->name()->as_utf8());
 2723         immutable_memory = field->is_strict() && field->is_final();
 2724 
 2725         if (base->is_InlineType()) {
 2726           assert(!is_store, "Cannot store into a non-larval value object");
 2727           set_result(base->as_InlineType()->field_value_by_offset(offset_con, false));
 2728           return true;
 2729         }
 2730       }
 2731     }
 2732 
 2733     if (base->is_InlineType()) {
 2734       assert(!is_store, "Cannot store into a non-larval value object");
 2735       base = base->as_InlineType()->buffer(this, true);
 2736     }
 2737     ptr = basic_plus_adr(base, ConvL2X(offset));
 2738   } else if (base_type->isa_aryptr()) {
 2739     decorators |= IS_ARRAY;
 2740     if (layout == LayoutKind::REFERENCE) {
 2741       if (!base_type->is_aryptr()->is_not_flat()) {
 2742         const TypeAryPtr* array_type = base_type->is_aryptr()->cast_to_not_flat();
 2743         // TODO 8350865 This should be a CheckCastPP, can we add a test?
 2744         Node* new_base = _gvn.transform(new CastPPNode(control(), base, array_type, ConstraintCastNode::DependencyType::NonFloatingNarrowing));
 2745         replace_in_map(base, new_base);
 2746         base = new_base;
 2747       }
 2748       ptr = basic_plus_adr(base, ConvL2X(offset));
 2749     } else {
 2750       if (UseArrayFlattening) {
 2751         // Flat array must have an exact type
 2752         bool is_null_free = !LayoutKindHelper::is_nullable_flat(layout);
 2753         bool is_atomic = LayoutKindHelper::is_atomic_flat(layout);
 2754         Node* new_base = cast_to_flat_array_exact(base, value_klass, is_null_free, is_atomic);
 2755         replace_in_map(base, new_base);
 2756         base = new_base;
 2757         ptr = basic_plus_adr(base, ConvL2X(offset));
 2758         const TypeAryPtr* ptr_type = _gvn.type(ptr)->is_aryptr();
 2759         if (ptr_type->field_offset().get() != 0) {
 2760           // TODO 8350865 This should be a CheckCastPP, can we add a test?
 2761           ptr = _gvn.transform(new CastPPNode(control(), ptr, ptr_type->with_field_offset(0), ConstraintCastNode::DependencyType::NonFloatingNarrowing));
 2762         }
 2763       } else {
 2764         uncommon_trap(Deoptimization::Reason_intrinsic,
 2765                       Deoptimization::Action_none);
 2766         return true;
 2767       }
 2768     }
 2769   } else {
 2770     decorators |= C2_MISMATCHED;
 2771     ptr = basic_plus_adr(base, ConvL2X(offset));
 2772   }
 2773 
 2774   if (is_store) {
 2775     Node* value = argument(6);
 2776     const Type* value_type = _gvn.type(value);
 2777     if (!value_type->is_inlinetypeptr()) {
 2778       value_type = Type::get_const_type(value_klass)->filter_speculative(value_type);
 2779       Node* new_value = _gvn.transform(new CheckCastPPNode(control(), value, value_type, ConstraintCastNode::DependencyType::NonFloatingNarrowing));
 2780       new_value = InlineTypeNode::make_from_oop(this, new_value, value_klass);
 2781       replace_in_map(value, new_value);
 2782       value = new_value;
 2783     }
 2784 
 2785     assert(value_type->inline_klass() == value_klass, "value is of type %s while valueType is %s", value_type->inline_klass()->name()->as_utf8(), value_klass->name()->as_utf8());
 2786     if (layout == LayoutKind::REFERENCE) {
 2787       const TypePtr* ptr_type = (decorators & C2_MISMATCHED) != 0 ? TypeRawPtr::BOTTOM : _gvn.type(ptr)->is_ptr();
 2788       access_store_at(base, ptr, ptr_type, value, value_type, T_OBJECT, decorators);
 2789     } else {
 2790       bool atomic = LayoutKindHelper::is_atomic_flat(layout);
 2791       bool null_free = !LayoutKindHelper::is_nullable_flat(layout);
 2792       value->as_InlineType()->store_flat(this, base, ptr, atomic, immutable_memory, null_free, decorators);
 2793     }
 2794 
 2795     return true;
 2796   } else {
 2797     decorators |= (C2_CONTROL_DEPENDENT_LOAD | C2_UNKNOWN_CONTROL_LOAD);
 2798     InlineTypeNode* result;
 2799     if (layout == LayoutKind::REFERENCE) {
 2800       const TypePtr* ptr_type = (decorators & C2_MISMATCHED) != 0 ? TypeRawPtr::BOTTOM : _gvn.type(ptr)->is_ptr();
 2801       Node* oop = access_load_at(base, ptr, ptr_type, Type::get_const_type(value_klass), T_OBJECT, decorators);
 2802       result = InlineTypeNode::make_from_oop(this, oop, value_klass);
 2803     } else {
 2804       bool atomic = LayoutKindHelper::is_atomic_flat(layout);
 2805       bool null_free = !LayoutKindHelper::is_nullable_flat(layout);
 2806       result = InlineTypeNode::make_from_flat(this, value_klass, base, ptr, atomic, immutable_memory, null_free, decorators);
 2807     }
 2808 
 2809     set_result(result);
 2810     return true;
 2811   }
 2812 }
 2813 
 2814 //----------------------------inline_unsafe_load_store----------------------------
 2815 // This method serves a couple of different customers (depending on LoadStoreKind):
 2816 //
 2817 // LS_cmp_swap:
 2818 //
 2819 //   boolean compareAndSetReference(Object o, long offset, Object expected, Object x);
 2820 //   boolean compareAndSetInt(   Object o, long offset, int    expected, int    x);
 2821 //   boolean compareAndSetLong(  Object o, long offset, long   expected, long   x);
 2822 //
 2823 // LS_cmp_swap_weak:
 2824 //
 2825 //   boolean weakCompareAndSetReference(       Object o, long offset, Object expected, Object x);
 2826 //   boolean weakCompareAndSetReferencePlain(  Object o, long offset, Object expected, Object x);
 2827 //   boolean weakCompareAndSetReferenceAcquire(Object o, long offset, Object expected, Object x);
 2828 //   boolean weakCompareAndSetReferenceRelease(Object o, long offset, Object expected, Object x);
 2829 //
 2830 //   boolean weakCompareAndSetInt(          Object o, long offset, int    expected, int    x);
 2831 //   boolean weakCompareAndSetIntPlain(     Object o, long offset, int    expected, int    x);
 2832 //   boolean weakCompareAndSetIntAcquire(   Object o, long offset, int    expected, int    x);
 2833 //   boolean weakCompareAndSetIntRelease(   Object o, long offset, int    expected, int    x);
 2834 //
 2835 //   boolean weakCompareAndSetLong(         Object o, long offset, long   expected, long   x);
 2836 //   boolean weakCompareAndSetLongPlain(    Object o, long offset, long   expected, long   x);
 2837 //   boolean weakCompareAndSetLongAcquire(  Object o, long offset, long   expected, long   x);
 2838 //   boolean weakCompareAndSetLongRelease(  Object o, long offset, long   expected, long   x);
 2839 //
 2840 // LS_cmp_exchange:
 2841 //
 2842 //   Object compareAndExchangeReferenceVolatile(Object o, long offset, Object expected, Object x);
 2843 //   Object compareAndExchangeReferenceAcquire( Object o, long offset, Object expected, Object x);
 2844 //   Object compareAndExchangeReferenceRelease( Object o, long offset, Object expected, Object x);
 2845 //
 2846 //   Object compareAndExchangeIntVolatile(   Object o, long offset, Object expected, Object x);
 2847 //   Object compareAndExchangeIntAcquire(    Object o, long offset, Object expected, Object x);
 2848 //   Object compareAndExchangeIntRelease(    Object o, long offset, Object expected, Object x);
 2849 //
 2850 //   Object compareAndExchangeLongVolatile(  Object o, long offset, Object expected, Object x);
 2851 //   Object compareAndExchangeLongAcquire(   Object o, long offset, Object expected, Object x);
 2852 //   Object compareAndExchangeLongRelease(   Object o, long offset, Object expected, Object x);
 2853 //
 2854 // LS_get_add:
 2855 //
 2856 //   int  getAndAddInt( Object o, long offset, int  delta)
 2857 //   long getAndAddLong(Object o, long offset, long delta)
 2858 //
 2859 // LS_get_set:
 2860 //
 2861 //   int    getAndSet(Object o, long offset, int    newValue)
 2862 //   long   getAndSet(Object o, long offset, long   newValue)
 2863 //   Object getAndSet(Object o, long offset, Object newValue)
 2864 //
 2865 bool LibraryCallKit::inline_unsafe_load_store(const BasicType type, const LoadStoreKind kind, const AccessKind access_kind) {
 2866   // This basic scheme here is the same as inline_unsafe_access, but
 2867   // differs in enough details that combining them would make the code
 2868   // overly confusing.  (This is a true fact! I originally combined
 2869   // them, but even I was confused by it!) As much code/comments as
 2870   // possible are retained from inline_unsafe_access though to make
 2871   // the correspondences clearer. - dl
 2872 
 2873   if (callee()->is_static())  return false;  // caller must have the capability!
 2874 
 2875   DecoratorSet decorators = C2_UNSAFE_ACCESS;
 2876   decorators |= mo_decorator_for_access_kind(access_kind);
 2877 
 2878 #ifndef PRODUCT
 2879   BasicType rtype;
 2880   {
 2881     ResourceMark rm;
 2882     // Check the signatures.
 2883     ciSignature* sig = callee()->signature();
 2884     rtype = sig->return_type()->basic_type();
 2885     switch(kind) {
 2886       case LS_get_add:
 2887       case LS_get_set: {
 2888       // Check the signatures.
 2889 #ifdef ASSERT
 2890       assert(rtype == type, "get and set must return the expected type");
 2891       assert(sig->count() == 3, "get and set has 3 arguments");
 2892       assert(sig->type_at(0)->basic_type() == T_OBJECT, "get and set base is object");
 2893       assert(sig->type_at(1)->basic_type() == T_LONG, "get and set offset is long");
 2894       assert(sig->type_at(2)->basic_type() == type, "get and set must take expected type as new value/delta");
 2895       assert(access_kind == Volatile, "mo is not passed to intrinsic nodes in current implementation");
 2896 #endif // ASSERT
 2897         break;
 2898       }
 2899       case LS_cmp_swap:
 2900       case LS_cmp_swap_weak: {
 2901       // Check the signatures.
 2902 #ifdef ASSERT
 2903       assert(rtype == T_BOOLEAN, "CAS must return boolean");
 2904       assert(sig->count() == 4, "CAS has 4 arguments");
 2905       assert(sig->type_at(0)->basic_type() == T_OBJECT, "CAS base is object");
 2906       assert(sig->type_at(1)->basic_type() == T_LONG, "CAS offset is long");
 2907 #endif // ASSERT
 2908         break;
 2909       }
 2910       case LS_cmp_exchange: {
 2911       // Check the signatures.
 2912 #ifdef ASSERT
 2913       assert(rtype == type, "CAS must return the expected type");
 2914       assert(sig->count() == 4, "CAS has 4 arguments");
 2915       assert(sig->type_at(0)->basic_type() == T_OBJECT, "CAS base is object");
 2916       assert(sig->type_at(1)->basic_type() == T_LONG, "CAS offset is long");
 2917 #endif // ASSERT
 2918         break;
 2919       }
 2920       default:
 2921         ShouldNotReachHere();
 2922     }
 2923   }
 2924 #endif //PRODUCT
 2925 
 2926   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
 2927 
 2928   // Get arguments:
 2929   Node* receiver = nullptr;
 2930   Node* base     = nullptr;
 2931   Node* offset   = nullptr;
 2932   Node* oldval   = nullptr;
 2933   Node* newval   = nullptr;
 2934   switch(kind) {
 2935     case LS_cmp_swap:
 2936     case LS_cmp_swap_weak:
 2937     case LS_cmp_exchange: {
 2938       const bool two_slot_type = type2size[type] == 2;
 2939       receiver = argument(0);  // type: oop
 2940       base     = argument(1);  // type: oop
 2941       offset   = argument(2);  // type: long
 2942       oldval   = argument(4);  // type: oop, int, or long
 2943       newval   = argument(two_slot_type ? 6 : 5);  // type: oop, int, or long
 2944       break;
 2945     }
 2946     case LS_get_add:
 2947     case LS_get_set: {
 2948       receiver = argument(0);  // type: oop
 2949       base     = argument(1);  // type: oop
 2950       offset   = argument(2);  // type: long
 2951       oldval   = nullptr;
 2952       newval   = argument(4);  // type: oop, int, or long
 2953       break;
 2954     }
 2955     default:
 2956       ShouldNotReachHere();
 2957   }
 2958 
 2959   // Build field offset expression.
 2960   // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
 2961   // to be plain byte offsets, which are also the same as those accepted
 2962   // by oopDesc::field_addr.
 2963   assert(Unsafe_field_offset_to_byte_offset(11) == 11, "fieldOffset must be byte-scaled");
 2964   // 32-bit machines ignore the high half of long offsets
 2965   offset = ConvL2X(offset);
 2966   // Save state and restore on bailout
 2967   SavedState old_state(this);
 2968   Node* adr = make_unsafe_address(base, offset,type, false);
 2969   const TypePtr *adr_type = _gvn.type(adr)->isa_ptr();
 2970 
 2971   Compile::AliasType* alias_type = C->alias_type(adr_type);
 2972   BasicType bt = alias_type->basic_type();
 2973   if (bt != T_ILLEGAL &&
 2974       (is_reference_type(bt) != (type == T_OBJECT))) {
 2975     // Don't intrinsify mismatched object accesses.
 2976     return false;
 2977   }
 2978 
 2979   old_state.discard();
 2980 
 2981   // For CAS, unlike inline_unsafe_access, there seems no point in
 2982   // trying to refine types. Just use the coarse types here.
 2983   assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
 2984   const Type *value_type = Type::get_const_basic_type(type);
 2985 
 2986   switch (kind) {
 2987     case LS_get_set:
 2988     case LS_cmp_exchange: {
 2989       if (type == T_OBJECT) {
 2990         const TypeOopPtr* tjp = sharpen_unsafe_type(alias_type, adr_type);
 2991         if (tjp != nullptr) {
 2992           value_type = tjp;
 2993         }
 2994       }
 2995       break;
 2996     }
 2997     case LS_cmp_swap:
 2998     case LS_cmp_swap_weak:
 2999     case LS_get_add:
 3000       break;
 3001     default:
 3002       ShouldNotReachHere();
 3003   }
 3004 
 3005   // Null check receiver.
 3006   receiver = null_check(receiver);
 3007   if (stopped()) {
 3008     return true;
 3009   }
 3010 
 3011   int alias_idx = C->get_alias_index(adr_type);
 3012 
 3013   if (is_reference_type(type)) {
 3014     decorators |= IN_HEAP | ON_UNKNOWN_OOP_REF;
 3015 
 3016     if (oldval != nullptr && oldval->is_InlineType()) {
 3017       // Re-execute the unsafe access if allocation triggers deoptimization.
 3018       PreserveReexecuteState preexecs(this);
 3019       jvms()->set_should_reexecute(true);
 3020       oldval = oldval->as_InlineType()->buffer(this)->get_oop();
 3021     }
 3022     if (newval != nullptr && newval->is_InlineType()) {
 3023       // Re-execute the unsafe access if allocation triggers deoptimization.
 3024       PreserveReexecuteState preexecs(this);
 3025       jvms()->set_should_reexecute(true);
 3026       newval = newval->as_InlineType()->buffer(this)->get_oop();
 3027     }
 3028 
 3029     // Transformation of a value which could be null pointer (CastPP #null)
 3030     // could be delayed during Parse (for example, in adjust_map_after_if()).
 3031     // Execute transformation here to avoid barrier generation in such case.
 3032     if (_gvn.type(newval) == TypePtr::NULL_PTR)
 3033       newval = _gvn.makecon(TypePtr::NULL_PTR);
 3034 
 3035     if (oldval != nullptr && _gvn.type(oldval) == TypePtr::NULL_PTR) {
 3036       // Refine the value to a null constant, when it is known to be null
 3037       oldval = _gvn.makecon(TypePtr::NULL_PTR);
 3038     }
 3039   }
 3040 
 3041   Node* result = nullptr;
 3042   switch (kind) {
 3043     case LS_cmp_exchange: {
 3044       result = access_atomic_cmpxchg_val_at(base, adr, adr_type, alias_idx,
 3045                                             oldval, newval, value_type, type, decorators);
 3046       break;
 3047     }
 3048     case LS_cmp_swap_weak:
 3049       decorators |= C2_WEAK_CMPXCHG;
 3050     case LS_cmp_swap: {
 3051       result = access_atomic_cmpxchg_bool_at(base, adr, adr_type, alias_idx,
 3052                                              oldval, newval, value_type, type, decorators);
 3053       break;
 3054     }
 3055     case LS_get_set: {
 3056       result = access_atomic_xchg_at(base, adr, adr_type, alias_idx,
 3057                                      newval, value_type, type, decorators);
 3058       break;
 3059     }
 3060     case LS_get_add: {
 3061       result = access_atomic_add_at(base, adr, adr_type, alias_idx,
 3062                                     newval, value_type, type, decorators);
 3063       break;
 3064     }
 3065     default:
 3066       ShouldNotReachHere();
 3067   }
 3068 
 3069   assert(type2size[result->bottom_type()->basic_type()] == type2size[rtype], "result type should match");
 3070   set_result(result);
 3071   return true;
 3072 }
 3073 
 3074 bool LibraryCallKit::inline_unsafe_fence(vmIntrinsics::ID id) {
 3075   // Regardless of form, don't allow previous ld/st to move down,
 3076   // then issue acquire, release, or volatile mem_bar.
 3077   insert_mem_bar(Op_MemBarCPUOrder);
 3078   switch(id) {
 3079     case vmIntrinsics::_loadFence:
 3080       insert_mem_bar(Op_LoadFence);
 3081       return true;
 3082     case vmIntrinsics::_storeFence:
 3083       insert_mem_bar(Op_StoreFence);
 3084       return true;
 3085     case vmIntrinsics::_storeStoreFence:
 3086       insert_mem_bar(Op_StoreStoreFence);
 3087       return true;
 3088     case vmIntrinsics::_fullFence:
 3089       insert_mem_bar(Op_MemBarFull);
 3090       return true;
 3091     default:
 3092       fatal_unexpected_iid(id);
 3093       return false;
 3094   }
 3095 }
 3096 
 3097 // private native int arrayInstanceBaseOffset0(Object[] array);
 3098 bool LibraryCallKit::inline_arrayInstanceBaseOffset() {
 3099   Node* array = argument(1);
 3100   Node* klass_node = load_object_klass(array);
 3101 
 3102   jint  layout_con = Klass::_lh_neutral_value;
 3103   Node* layout_val = get_layout_helper(klass_node, layout_con);
 3104   int   layout_is_con = (layout_val == nullptr);
 3105 
 3106   Node* header_size = nullptr;
 3107   if (layout_is_con) {
 3108     int hsize = Klass::layout_helper_header_size(layout_con);
 3109     header_size = intcon(hsize);
 3110   } else {
 3111     Node* hss = intcon(Klass::_lh_header_size_shift);
 3112     Node* hsm = intcon(Klass::_lh_header_size_mask);
 3113     header_size = _gvn.transform(new URShiftINode(layout_val, hss));
 3114     header_size = _gvn.transform(new AndINode(header_size, hsm));
 3115   }
 3116   set_result(header_size);
 3117   return true;
 3118 }
 3119 
 3120 // private native int arrayInstanceIndexScale0(Object[] array);
 3121 bool LibraryCallKit::inline_arrayInstanceIndexScale() {
 3122   Node* array = argument(1);
 3123   Node* klass_node = load_object_klass(array);
 3124 
 3125   jint  layout_con = Klass::_lh_neutral_value;
 3126   Node* layout_val = get_layout_helper(klass_node, layout_con);
 3127   int   layout_is_con = (layout_val == nullptr);
 3128 
 3129   Node* element_size = nullptr;
 3130   if (layout_is_con) {
 3131     int log_element_size  = Klass::layout_helper_log2_element_size(layout_con);
 3132     int elem_size = 1 << log_element_size;
 3133     element_size = intcon(elem_size);
 3134   } else {
 3135     Node* ess = intcon(Klass::_lh_log2_element_size_shift);
 3136     Node* esm = intcon(Klass::_lh_log2_element_size_mask);
 3137     Node* log_element_size = _gvn.transform(new URShiftINode(layout_val, ess));
 3138     log_element_size = _gvn.transform(new AndINode(log_element_size, esm));
 3139     element_size = _gvn.transform(new LShiftINode(intcon(1), log_element_size));
 3140   }
 3141   set_result(element_size);
 3142   return true;
 3143 }
 3144 
 3145 // private native int arrayLayout0(Object[] array);
 3146 bool LibraryCallKit::inline_arrayLayout() {
 3147   RegionNode* region = new RegionNode(2);
 3148   Node* phi = new PhiNode(region, TypeInt::POS);
 3149 
 3150   Node* array = argument(1);
 3151   Node* klass_node = load_object_klass(array);
 3152   generate_refArray_guard(klass_node, region);
 3153   if (region->req() == 3) {
 3154     phi->add_req(intcon((jint)LayoutKind::REFERENCE));
 3155   }
 3156 
 3157   int layout_kind_offset = in_bytes(FlatArrayKlass::layout_kind_offset());
 3158   Node* layout_kind_addr = basic_plus_adr(top(), klass_node, layout_kind_offset);
 3159   Node* layout_kind = make_load(nullptr, layout_kind_addr, TypeInt::POS, T_INT, MemNode::unordered);
 3160 
 3161   region->init_req(1, control());
 3162   phi->init_req(1, layout_kind);
 3163 
 3164   set_control(_gvn.transform(region));
 3165   set_result(_gvn.transform(phi));
 3166   return true;
 3167 }
 3168 
 3169 // private native int[] getFieldMap0(Class <?> c);
 3170 //   int offset = c._klass._acmp_maps_offset;
 3171 //   return (int[])c.obj_field(offset);
 3172 bool LibraryCallKit::inline_getFieldMap() {
 3173   Node* mirror = argument(1);
 3174   Node* klass = load_klass_from_mirror(mirror, false, nullptr, 0);
 3175 
 3176   int field_map_offset_offset = in_bytes(InstanceKlass::acmp_maps_offset_offset());
 3177   Node* field_map_offset_addr = basic_plus_adr(top(), klass, field_map_offset_offset);
 3178   Node* field_map_offset = make_load(nullptr, field_map_offset_addr, TypeInt::INT, T_INT, MemNode::unordered);
 3179   field_map_offset = _gvn.transform(ConvI2L(field_map_offset));
 3180 
 3181   Node* map_addr = basic_plus_adr(mirror, field_map_offset);
 3182   const TypeAryPtr* val_type = TypeAryPtr::INTS->cast_to_ptr_type(TypePtr::NotNull)->with_offset(0);
 3183   Node* map = access_load_at(mirror, map_addr, TypeAryPtr::INTS, val_type, T_ARRAY, IN_HEAP | MO_UNORDERED);
 3184 
 3185   set_result(map);
 3186   return true;
 3187 }
 3188 
 3189 bool LibraryCallKit::inline_onspinwait() {
 3190   insert_mem_bar(Op_OnSpinWait);
 3191   return true;
 3192 }
 3193 
 3194 bool LibraryCallKit::klass_needs_init_guard(Node* kls) {
 3195   if (!kls->is_Con()) {
 3196     return true;
 3197   }
 3198   const TypeInstKlassPtr* klsptr = kls->bottom_type()->isa_instklassptr();
 3199   if (klsptr == nullptr) {
 3200     return true;
 3201   }
 3202   ciInstanceKlass* ik = klsptr->instance_klass();
 3203   // don't need a guard for a klass that is already initialized
 3204   return !ik->is_initialized();
 3205 }
 3206 
 3207 //----------------------------inline_unsafe_writeback0-------------------------
 3208 // public native void Unsafe.writeback0(long address)
 3209 bool LibraryCallKit::inline_unsafe_writeback0() {
 3210   if (!Matcher::has_match_rule(Op_CacheWB)) {
 3211     return false;
 3212   }
 3213 #ifndef PRODUCT
 3214   assert(Matcher::has_match_rule(Op_CacheWBPreSync), "found match rule for CacheWB but not CacheWBPreSync");
 3215   assert(Matcher::has_match_rule(Op_CacheWBPostSync), "found match rule for CacheWB but not CacheWBPostSync");
 3216   ciSignature* sig = callee()->signature();
 3217   assert(sig->type_at(0)->basic_type() == T_LONG, "Unsafe_writeback0 address is long!");
 3218 #endif
 3219   null_check_receiver();  // null-check, then ignore
 3220   Node *addr = argument(1);
 3221   addr = new CastX2PNode(addr);
 3222   addr = _gvn.transform(addr);
 3223   Node *flush = new CacheWBNode(control(), memory(TypeRawPtr::BOTTOM), addr);
 3224   flush = _gvn.transform(flush);
 3225   set_memory(flush, TypeRawPtr::BOTTOM);
 3226   return true;
 3227 }
 3228 
 3229 //----------------------------inline_unsafe_writeback0-------------------------
 3230 // public native void Unsafe.writeback0(long address)
 3231 bool LibraryCallKit::inline_unsafe_writebackSync0(bool is_pre) {
 3232   if (is_pre && !Matcher::has_match_rule(Op_CacheWBPreSync)) {
 3233     return false;
 3234   }
 3235   if (!is_pre && !Matcher::has_match_rule(Op_CacheWBPostSync)) {
 3236     return false;
 3237   }
 3238 #ifndef PRODUCT
 3239   assert(Matcher::has_match_rule(Op_CacheWB),
 3240          (is_pre ? "found match rule for CacheWBPreSync but not CacheWB"
 3241                 : "found match rule for CacheWBPostSync but not CacheWB"));
 3242 
 3243 #endif
 3244   null_check_receiver();  // null-check, then ignore
 3245   Node *sync;
 3246   if (is_pre) {
 3247     sync = new CacheWBPreSyncNode(control(), memory(TypeRawPtr::BOTTOM));
 3248   } else {
 3249     sync = new CacheWBPostSyncNode(control(), memory(TypeRawPtr::BOTTOM));
 3250   }
 3251   sync = _gvn.transform(sync);
 3252   set_memory(sync, TypeRawPtr::BOTTOM);
 3253   return true;
 3254 }
 3255 
 3256 //----------------------------inline_unsafe_allocate---------------------------
 3257 // public native Object Unsafe.allocateInstance(Class<?> cls);
 3258 bool LibraryCallKit::inline_unsafe_allocate() {
 3259 
 3260 #if INCLUDE_JVMTI
 3261   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
 3262     return false;
 3263   }
 3264 #endif //INCLUDE_JVMTI
 3265 
 3266   if (callee()->is_static())  return false;  // caller must have the capability!
 3267 
 3268   null_check_receiver();  // null-check, then ignore
 3269   Node* cls = null_check(argument(1));
 3270   if (stopped())  return true;
 3271 
 3272   Node* kls = load_klass_from_mirror(cls, false, nullptr, 0);
 3273   kls = null_check(kls);
 3274   if (stopped())  return true;  // argument was like int.class
 3275 
 3276 #if INCLUDE_JVMTI
 3277     // Don't try to access new allocated obj in the intrinsic.
 3278     // It causes perfomance issues even when jvmti event VmObjectAlloc is disabled.
 3279     // Deoptimize and allocate in interpreter instead.
 3280     Node* addr = makecon(TypeRawPtr::make((address) &JvmtiExport::_should_notify_object_alloc));
 3281     Node* should_post_vm_object_alloc = make_load(this->control(), addr, TypeInt::INT, T_INT, MemNode::unordered);
 3282     Node* chk = _gvn.transform(new CmpINode(should_post_vm_object_alloc, intcon(0)));
 3283     Node* tst = _gvn.transform(new BoolNode(chk, BoolTest::eq));
 3284     {
 3285       BuildCutout unless(this, tst, PROB_MAX);
 3286       uncommon_trap(Deoptimization::Reason_intrinsic,
 3287                     Deoptimization::Action_make_not_entrant);
 3288     }
 3289     if (stopped()) {
 3290       return true;
 3291     }
 3292 #endif //INCLUDE_JVMTI
 3293 
 3294   Node* test = nullptr;
 3295   if (LibraryCallKit::klass_needs_init_guard(kls)) {
 3296     // Note:  The argument might still be an illegal value like
 3297     // Serializable.class or Object[].class.   The runtime will handle it.
 3298     // But we must make an explicit check for initialization.
 3299     Node* insp = off_heap_plus_addr(kls, in_bytes(InstanceKlass::init_state_offset()));
 3300     // Use T_BOOLEAN for InstanceKlass::_init_state so the compiler
 3301     // can generate code to load it as unsigned byte.
 3302     Node* inst = make_load(nullptr, insp, TypeInt::UBYTE, T_BOOLEAN, MemNode::acquire);
 3303     Node* bits = intcon(InstanceKlass::fully_initialized);
 3304     test = _gvn.transform(new SubINode(inst, bits));
 3305     // The 'test' is non-zero if we need to take a slow path.
 3306   }
 3307   Node* obj = new_instance(kls, test);
 3308   set_result(obj);
 3309   return true;
 3310 }
 3311 
 3312 //------------------------inline_native_time_funcs--------------
 3313 // inline code for System.currentTimeMillis() and System.nanoTime()
 3314 // these have the same type and signature
 3315 bool LibraryCallKit::inline_native_time_funcs(address funcAddr, const char* funcName) {
 3316   const TypeFunc* tf = OptoRuntime::void_long_Type();
 3317   const TypePtr* no_memory_effects = nullptr;
 3318   Node* time = make_runtime_call(RC_LEAF, tf, funcAddr, funcName, no_memory_effects);
 3319   Node* value = _gvn.transform(new ProjNode(time, TypeFunc::Parms+0));
 3320 #ifdef ASSERT
 3321   Node* value_top = _gvn.transform(new ProjNode(time, TypeFunc::Parms+1));
 3322   assert(value_top == top(), "second value must be top");
 3323 #endif
 3324   set_result(value);
 3325   return true;
 3326 }
 3327 
 3328 //--------------------inline_native_vthread_start_transition--------------------
 3329 // inline void startTransition(boolean is_mount);
 3330 // inline void startFinalTransition();
 3331 // Pseudocode of implementation:
 3332 //
 3333 // java_lang_Thread::set_is_in_vthread_transition(vthread, true);
 3334 // carrier->set_is_in_vthread_transition(true);
 3335 // OrderAccess::storeload();
 3336 // int disable_requests = java_lang_Thread::vthread_transition_disable_count(vthread)
 3337 //                        + global_vthread_transition_disable_count();
 3338 // if (disable_requests > 0) {
 3339 //   slow path: runtime call
 3340 // }
 3341 bool LibraryCallKit::inline_native_vthread_start_transition(address funcAddr, const char* funcName, bool is_final_transition) {
 3342   Node* vt_oop = must_be_not_null(argument(0), true); // VirtualThread this argument
 3343   IdealKit ideal(this);
 3344 
 3345   Node* thread = ideal.thread();
 3346   Node* jt_addr = off_heap_plus_addr(thread, in_bytes(JavaThread::is_in_vthread_transition_offset()));
 3347   Node* vt_addr = basic_plus_adr(vt_oop, java_lang_Thread::is_in_vthread_transition_offset());
 3348   access_store_at(nullptr, jt_addr, _gvn.type(jt_addr)->is_ptr(), ideal.ConI(1), TypeInt::BOOL, T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
 3349   access_store_at(nullptr, vt_addr, _gvn.type(vt_addr)->is_ptr(), ideal.ConI(1), TypeInt::BOOL, T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
 3350   insert_mem_bar(Op_MemBarStoreLoad);
 3351   ideal.sync_kit(this);
 3352 
 3353   Node* global_disable_addr = makecon(TypeRawPtr::make((address)MountUnmountDisabler::global_vthread_transition_disable_count_address()));
 3354   Node* global_disable = ideal.load(ideal.ctrl(), global_disable_addr, TypeInt::INT, T_INT, Compile::AliasIdxRaw, true /*require_atomic_access*/);
 3355   Node* vt_disable_addr = basic_plus_adr(vt_oop, java_lang_Thread::vthread_transition_disable_count_offset());
 3356   const TypePtr* vt_disable_addr_t = _gvn.type(vt_disable_addr)->is_ptr();
 3357   Node* vt_disable = ideal.load(ideal.ctrl(), vt_disable_addr, TypeInt::INT, T_INT, C->get_alias_index(vt_disable_addr_t), true /*require_atomic_access*/);
 3358   Node* disabled = _gvn.transform(new AddINode(global_disable, vt_disable));
 3359 
 3360   ideal.if_then(disabled, BoolTest::ne, ideal.ConI(0)); {
 3361     sync_kit(ideal);
 3362     Node* is_mount = is_final_transition ? ideal.ConI(0) : argument(1);
 3363     const TypeFunc* tf = OptoRuntime::vthread_transition_Type();
 3364     make_runtime_call(RC_NO_LEAF, tf, funcAddr, funcName, TypePtr::BOTTOM, vt_oop, is_mount);
 3365     ideal.sync_kit(this);
 3366   }
 3367   ideal.end_if();
 3368 
 3369   final_sync(ideal);
 3370   return true;
 3371 }
 3372 
 3373 bool LibraryCallKit::inline_native_vthread_end_transition(address funcAddr, const char* funcName, bool is_first_transition) {
 3374   Node* vt_oop = must_be_not_null(argument(0), true); // VirtualThread this argument
 3375   IdealKit ideal(this);
 3376 
 3377   Node* _notify_jvmti_addr = makecon(TypeRawPtr::make((address)MountUnmountDisabler::notify_jvmti_events_address()));
 3378   Node* _notify_jvmti = ideal.load(ideal.ctrl(), _notify_jvmti_addr, TypeInt::BOOL, T_BOOLEAN, Compile::AliasIdxRaw);
 3379 
 3380   ideal.if_then(_notify_jvmti, BoolTest::eq, ideal.ConI(1)); {
 3381     sync_kit(ideal);
 3382     Node* is_mount = is_first_transition ? ideal.ConI(1) : argument(1);
 3383     const TypeFunc* tf = OptoRuntime::vthread_transition_Type();
 3384     make_runtime_call(RC_NO_LEAF, tf, funcAddr, funcName, TypePtr::BOTTOM, vt_oop, is_mount);
 3385     ideal.sync_kit(this);
 3386   } ideal.else_(); {
 3387     Node* thread = ideal.thread();
 3388     Node* jt_addr = off_heap_plus_addr(thread, in_bytes(JavaThread::is_in_vthread_transition_offset()));
 3389     Node* vt_addr = basic_plus_adr(vt_oop, java_lang_Thread::is_in_vthread_transition_offset());
 3390 
 3391     sync_kit(ideal);
 3392     access_store_at(nullptr, jt_addr, _gvn.type(jt_addr)->is_ptr(), ideal.ConI(0), TypeInt::BOOL, T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
 3393     access_store_at(nullptr, vt_addr, _gvn.type(vt_addr)->is_ptr(), ideal.ConI(0), TypeInt::BOOL, T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
 3394     ideal.sync_kit(this);
 3395   } ideal.end_if();
 3396 
 3397   final_sync(ideal);
 3398   return true;
 3399 }
 3400 
 3401 #if INCLUDE_JVMTI
 3402 
 3403 // Always update the is_disable_suspend bit.
 3404 bool LibraryCallKit::inline_native_notify_jvmti_sync() {
 3405   if (!DoJVMTIVirtualThreadTransitions) {
 3406     return true;
 3407   }
 3408   IdealKit ideal(this);
 3409 
 3410   {
 3411     // unconditionally update the is_disable_suspend bit in current JavaThread
 3412     Node* thread = ideal.thread();
 3413     Node* arg = argument(0); // argument for notification
 3414     Node* addr = off_heap_plus_addr(thread, in_bytes(JavaThread::is_disable_suspend_offset()));
 3415     const TypePtr *addr_type = _gvn.type(addr)->isa_ptr();
 3416 
 3417     sync_kit(ideal);
 3418     access_store_at(nullptr, addr, addr_type, arg, _gvn.type(arg), T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
 3419     ideal.sync_kit(this);
 3420   }
 3421   final_sync(ideal);
 3422 
 3423   return true;
 3424 }
 3425 
 3426 #endif // INCLUDE_JVMTI
 3427 
 3428 #ifdef JFR_HAVE_INTRINSICS
 3429 
 3430 /**
 3431  * if oop->klass != null
 3432  *   // normal class
 3433  *   epoch = _epoch_state ? 2 : 1
 3434  *   if oop->klass->trace_id & ((epoch << META_SHIFT) | epoch)) != epoch {
 3435  *     ... // enter slow path when the klass is first recorded or the epoch of JFR shifts
 3436  *   }
 3437  *   id = oop->klass->trace_id >> TRACE_ID_SHIFT // normal class path
 3438  * else
 3439  *   // primitive class
 3440  *   if oop->array_klass != null
 3441  *     id = (oop->array_klass->trace_id >> TRACE_ID_SHIFT) + 1 // primitive class path
 3442  *   else
 3443  *     id = LAST_TYPE_ID + 1 // void class path
 3444  *   if (!signaled)
 3445  *     signaled = true
 3446  */
 3447 bool LibraryCallKit::inline_native_classID() {
 3448   Node* cls = argument(0);
 3449 
 3450   IdealKit ideal(this);
 3451 #define __ ideal.
 3452   IdealVariable result(ideal); __ declarations_done();
 3453   Node* kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(),
 3454                                                  basic_plus_adr(cls, java_lang_Class::klass_offset()),
 3455                                                  TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
 3456 
 3457 
 3458   __ if_then(kls, BoolTest::ne, null()); {
 3459     Node* kls_trace_id_addr = basic_plus_adr(kls, in_bytes(KLASS_TRACE_ID_OFFSET));
 3460     Node* kls_trace_id_raw = ideal.load(ideal.ctrl(), kls_trace_id_addr,TypeLong::LONG, T_LONG, Compile::AliasIdxRaw);
 3461 
 3462     Node* epoch_address = makecon(TypeRawPtr::make(JfrIntrinsicSupport::epoch_address()));
 3463     Node* epoch = ideal.load(ideal.ctrl(), epoch_address, TypeInt::BOOL, T_BOOLEAN, Compile::AliasIdxRaw);
 3464     epoch = _gvn.transform(new LShiftLNode(longcon(1), epoch));
 3465     Node* mask = _gvn.transform(new LShiftLNode(epoch, intcon(META_SHIFT)));
 3466     mask = _gvn.transform(new OrLNode(mask, epoch));
 3467     Node* kls_trace_id_raw_and_mask = _gvn.transform(new AndLNode(kls_trace_id_raw, mask));
 3468 
 3469     float unlikely  = PROB_UNLIKELY(0.999);
 3470     __ if_then(kls_trace_id_raw_and_mask, BoolTest::ne, epoch, unlikely); {
 3471       sync_kit(ideal);
 3472       make_runtime_call(RC_LEAF,
 3473                         OptoRuntime::class_id_load_barrier_Type(),
 3474                         CAST_FROM_FN_PTR(address, JfrIntrinsicSupport::load_barrier),
 3475                         "class id load barrier",
 3476                         TypePtr::BOTTOM,
 3477                         kls);
 3478       ideal.sync_kit(this);
 3479     } __ end_if();
 3480 
 3481     ideal.set(result,  _gvn.transform(new URShiftLNode(kls_trace_id_raw, ideal.ConI(TRACE_ID_SHIFT))));
 3482   } __ else_(); {
 3483     Node* array_kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(),
 3484                                                    basic_plus_adr(cls, java_lang_Class::array_klass_offset()),
 3485                                                    TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
 3486     __ if_then(array_kls, BoolTest::ne, null()); {
 3487       Node* array_kls_trace_id_addr = basic_plus_adr(array_kls, in_bytes(KLASS_TRACE_ID_OFFSET));
 3488       Node* array_kls_trace_id_raw = ideal.load(ideal.ctrl(), array_kls_trace_id_addr, TypeLong::LONG, T_LONG, Compile::AliasIdxRaw);
 3489       Node* array_kls_trace_id = _gvn.transform(new URShiftLNode(array_kls_trace_id_raw, ideal.ConI(TRACE_ID_SHIFT)));
 3490       ideal.set(result, _gvn.transform(new AddLNode(array_kls_trace_id, longcon(1))));
 3491     } __ else_(); {
 3492       // void class case
 3493       ideal.set(result, longcon(LAST_TYPE_ID + 1));
 3494     } __ end_if();
 3495 
 3496     Node* signaled_flag_address = makecon(TypeRawPtr::make(JfrIntrinsicSupport::signal_address()));
 3497     Node* signaled = ideal.load(ideal.ctrl(), signaled_flag_address, TypeInt::BOOL, T_BOOLEAN, Compile::AliasIdxRaw, true, MemNode::acquire);
 3498     __ if_then(signaled, BoolTest::ne, ideal.ConI(1)); {
 3499       ideal.store(ideal.ctrl(), signaled_flag_address, ideal.ConI(1), T_BOOLEAN, Compile::AliasIdxRaw, MemNode::release, true);
 3500     } __ end_if();
 3501   } __ end_if();
 3502 
 3503   final_sync(ideal);
 3504   set_result(ideal.value(result));
 3505 #undef __
 3506   return true;
 3507 }
 3508 
 3509 //------------------------inline_native_jvm_commit------------------
 3510 bool LibraryCallKit::inline_native_jvm_commit() {
 3511   enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
 3512 
 3513   // Save input memory and i_o state.
 3514   Node* input_memory_state = reset_memory();
 3515   set_all_memory(input_memory_state);
 3516   Node* input_io_state = i_o();
 3517 
 3518   // TLS.
 3519   Node* tls_ptr = _gvn.transform(new ThreadLocalNode());
 3520   // Jfr java buffer.
 3521   Node* java_buffer_offset = _gvn.transform(AddPNode::make_off_heap(tls_ptr, MakeConX(in_bytes(JAVA_BUFFER_OFFSET_JFR))));
 3522   Node* java_buffer = _gvn.transform(new LoadPNode(control(), input_memory_state, java_buffer_offset, TypePtr::BOTTOM, TypeRawPtr::NOTNULL, MemNode::unordered));
 3523   Node* java_buffer_pos_offset = _gvn.transform(AddPNode::make_off_heap(java_buffer, MakeConX(in_bytes(JFR_BUFFER_POS_OFFSET))));
 3524 
 3525   // Load the current value of the notified field in the JfrThreadLocal.
 3526   Node* notified_offset = off_heap_plus_addr(tls_ptr, in_bytes(NOTIFY_OFFSET_JFR));
 3527   Node* notified = make_load(control(), notified_offset, TypeInt::BOOL, T_BOOLEAN, MemNode::unordered);
 3528 
 3529   // Test for notification.
 3530   Node* notified_cmp = _gvn.transform(new CmpINode(notified, _gvn.intcon(1)));
 3531   Node* test_notified = _gvn.transform(new BoolNode(notified_cmp, BoolTest::eq));
 3532   IfNode* iff_notified = create_and_map_if(control(), test_notified, PROB_MIN, COUNT_UNKNOWN);
 3533 
 3534   // True branch, is notified.
 3535   Node* is_notified = _gvn.transform(new IfTrueNode(iff_notified));
 3536   set_control(is_notified);
 3537 
 3538   // Reset notified state.
 3539   store_to_memory(control(), notified_offset, _gvn.intcon(0), T_BOOLEAN, MemNode::unordered);
 3540   Node* notified_reset_memory = reset_memory();
 3541 
 3542   // 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.
 3543   Node* current_pos_X = _gvn.transform(new LoadXNode(control(), input_memory_state, java_buffer_pos_offset, TypeRawPtr::NOTNULL, TypeX_X, MemNode::unordered));
 3544   // Convert the machine-word to a long.
 3545   Node* current_pos = ConvX2L(current_pos_X);
 3546 
 3547   // False branch, not notified.
 3548   Node* not_notified = _gvn.transform(new IfFalseNode(iff_notified));
 3549   set_control(not_notified);
 3550   set_all_memory(input_memory_state);
 3551 
 3552   // Arg is the next position as a long.
 3553   Node* arg = argument(0);
 3554   // Convert long to machine-word.
 3555   Node* next_pos_X = ConvL2X(arg);
 3556 
 3557   // Store the next_position to the underlying jfr java buffer.
 3558   store_to_memory(control(), java_buffer_pos_offset, next_pos_X, LP64_ONLY(T_LONG) NOT_LP64(T_INT), MemNode::release);
 3559 
 3560   Node* commit_memory = reset_memory();
 3561   set_all_memory(commit_memory);
 3562 
 3563   // 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.
 3564   Node* java_buffer_flags_offset = _gvn.transform(AddPNode::make_off_heap(java_buffer, MakeConX(in_bytes(JFR_BUFFER_FLAGS_OFFSET))));
 3565   Node* flags = make_load(control(), java_buffer_flags_offset, TypeInt::UBYTE, T_BYTE, MemNode::unordered);
 3566   Node* lease_constant = _gvn.intcon(4);
 3567 
 3568   // And flags with lease constant.
 3569   Node* lease = _gvn.transform(new AndINode(flags, lease_constant));
 3570 
 3571   // Branch on lease to conditionalize returning the leased java buffer.
 3572   Node* lease_cmp = _gvn.transform(new CmpINode(lease, lease_constant));
 3573   Node* test_lease = _gvn.transform(new BoolNode(lease_cmp, BoolTest::eq));
 3574   IfNode* iff_lease = create_and_map_if(control(), test_lease, PROB_MIN, COUNT_UNKNOWN);
 3575 
 3576   // False branch, not a lease.
 3577   Node* not_lease = _gvn.transform(new IfFalseNode(iff_lease));
 3578 
 3579   // True branch, is lease.
 3580   Node* is_lease = _gvn.transform(new IfTrueNode(iff_lease));
 3581   set_control(is_lease);
 3582 
 3583   // Make a runtime call, which can safepoint, to return the leased buffer. This updates both the JfrThreadLocal and the Java event writer oop.
 3584   Node* call_return_lease = make_runtime_call(RC_NO_LEAF,
 3585                                               OptoRuntime::void_void_Type(),
 3586                                               SharedRuntime::jfr_return_lease(),
 3587                                               "return_lease", TypePtr::BOTTOM);
 3588   Node* call_return_lease_control = _gvn.transform(new ProjNode(call_return_lease, TypeFunc::Control));
 3589 
 3590   RegionNode* lease_compare_rgn = new RegionNode(PATH_LIMIT);
 3591   record_for_igvn(lease_compare_rgn);
 3592   PhiNode* lease_compare_mem = new PhiNode(lease_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
 3593   record_for_igvn(lease_compare_mem);
 3594   PhiNode* lease_compare_io = new PhiNode(lease_compare_rgn, Type::ABIO);
 3595   record_for_igvn(lease_compare_io);
 3596   PhiNode* lease_result_value = new PhiNode(lease_compare_rgn, TypeLong::LONG);
 3597   record_for_igvn(lease_result_value);
 3598 
 3599   // Update control and phi nodes.
 3600   lease_compare_rgn->init_req(_true_path, call_return_lease_control);
 3601   lease_compare_rgn->init_req(_false_path, not_lease);
 3602 
 3603   lease_compare_mem->init_req(_true_path, reset_memory());
 3604   lease_compare_mem->init_req(_false_path, commit_memory);
 3605 
 3606   lease_compare_io->init_req(_true_path, i_o());
 3607   lease_compare_io->init_req(_false_path, input_io_state);
 3608 
 3609   lease_result_value->init_req(_true_path, _gvn.longcon(0)); // if the lease was returned, return 0L.
 3610   lease_result_value->init_req(_false_path, arg); // if not lease, return new updated position.
 3611 
 3612   RegionNode* result_rgn = new RegionNode(PATH_LIMIT);
 3613   PhiNode* result_mem = new PhiNode(result_rgn, Type::MEMORY, TypePtr::BOTTOM);
 3614   PhiNode* result_io = new PhiNode(result_rgn, Type::ABIO);
 3615   PhiNode* result_value = new PhiNode(result_rgn, TypeLong::LONG);
 3616 
 3617   // Update control and phi nodes.
 3618   result_rgn->init_req(_true_path, is_notified);
 3619   result_rgn->init_req(_false_path, _gvn.transform(lease_compare_rgn));
 3620 
 3621   result_mem->init_req(_true_path, notified_reset_memory);
 3622   result_mem->init_req(_false_path, _gvn.transform(lease_compare_mem));
 3623 
 3624   result_io->init_req(_true_path, input_io_state);
 3625   result_io->init_req(_false_path, _gvn.transform(lease_compare_io));
 3626 
 3627   result_value->init_req(_true_path, current_pos);
 3628   result_value->init_req(_false_path, _gvn.transform(lease_result_value));
 3629 
 3630   // Set output state.
 3631   set_control(_gvn.transform(result_rgn));
 3632   set_all_memory(_gvn.transform(result_mem));
 3633   set_i_o(_gvn.transform(result_io));
 3634   set_result(result_rgn, result_value);
 3635   return true;
 3636 }
 3637 
 3638 /*
 3639  * The intrinsic is a model of this pseudo-code:
 3640  *
 3641  * JfrThreadLocal* const tl = Thread::jfr_thread_local()
 3642  * jobject h_event_writer = tl->java_event_writer();
 3643  * if (h_event_writer == nullptr) {
 3644  *   return nullptr;
 3645  * }
 3646  * oop threadObj = Thread::threadObj();
 3647  * oop vthread = java_lang_Thread::vthread(threadObj);
 3648  * traceid tid;
 3649  * bool pinVirtualThread;
 3650  * bool excluded;
 3651  * if (vthread != threadObj) {  // i.e. current thread is virtual
 3652  *   tid = java_lang_Thread::tid(vthread);
 3653  *   u2 vthread_epoch_raw = java_lang_Thread::jfr_epoch(vthread);
 3654  *   pinVirtualThread = VMContinuations;
 3655  *   excluded = vthread_epoch_raw & excluded_mask;
 3656  *   if (!excluded) {
 3657  *     traceid current_epoch = JfrTraceIdEpoch::current_generation();
 3658  *     u2 vthread_epoch = vthread_epoch_raw & epoch_mask;
 3659  *     if (vthread_epoch != current_epoch) {
 3660  *       write_checkpoint();
 3661  *     }
 3662  *   }
 3663  * } else {
 3664  *   tid = java_lang_Thread::tid(threadObj);
 3665  *   u2 thread_epoch_raw = java_lang_Thread::jfr_epoch(threadObj);
 3666  *   pinVirtualThread = false;
 3667  *   excluded = thread_epoch_raw & excluded_mask;
 3668  * }
 3669  * oop event_writer = JNIHandles::resolve_non_null(h_event_writer);
 3670  * traceid tid_in_event_writer = getField(event_writer, "threadID");
 3671  * if (tid_in_event_writer != tid) {
 3672  *   setField(event_writer, "pinVirtualThread", pinVirtualThread);
 3673  *   setField(event_writer, "excluded", excluded);
 3674  *   setField(event_writer, "threadID", tid);
 3675  * }
 3676  * return event_writer
 3677  */
 3678 bool LibraryCallKit::inline_native_getEventWriter() {
 3679   enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
 3680 
 3681   // Save input memory and i_o state.
 3682   Node* input_memory_state = reset_memory();
 3683   set_all_memory(input_memory_state);
 3684   Node* input_io_state = i_o();
 3685 
 3686   // The most significant bit of the u2 is used to denote thread exclusion
 3687   Node* excluded_shift = _gvn.intcon(15);
 3688   Node* excluded_mask = _gvn.intcon(1 << 15);
 3689   // The epoch generation is the range [1-32767]
 3690   Node* epoch_mask = _gvn.intcon(32767);
 3691 
 3692   // TLS
 3693   Node* tls_ptr = _gvn.transform(new ThreadLocalNode());
 3694 
 3695   // Load the address of java event writer jobject handle from the jfr_thread_local structure.
 3696   Node* jobj_ptr = off_heap_plus_addr(tls_ptr, in_bytes(THREAD_LOCAL_WRITER_OFFSET_JFR));
 3697 
 3698   // Load the eventwriter jobject handle.
 3699   Node* jobj = make_load(control(), jobj_ptr, TypeRawPtr::BOTTOM, T_ADDRESS, MemNode::unordered);
 3700 
 3701   // Null check the jobject handle.
 3702   Node* jobj_cmp_null = _gvn.transform(new CmpPNode(jobj, null()));
 3703   Node* test_jobj_not_equal_null = _gvn.transform(new BoolNode(jobj_cmp_null, BoolTest::ne));
 3704   IfNode* iff_jobj_not_equal_null = create_and_map_if(control(), test_jobj_not_equal_null, PROB_MAX, COUNT_UNKNOWN);
 3705 
 3706   // False path, jobj is null.
 3707   Node* jobj_is_null = _gvn.transform(new IfFalseNode(iff_jobj_not_equal_null));
 3708 
 3709   // True path, jobj is not null.
 3710   Node* jobj_is_not_null = _gvn.transform(new IfTrueNode(iff_jobj_not_equal_null));
 3711 
 3712   set_control(jobj_is_not_null);
 3713 
 3714   // Load the threadObj for the CarrierThread.
 3715   Node* threadObj = generate_current_thread(tls_ptr);
 3716 
 3717   // Load the vthread.
 3718   Node* vthread = generate_virtual_thread(tls_ptr);
 3719 
 3720   // If vthread != threadObj, this is a virtual thread.
 3721   Node* vthread_cmp_threadObj = _gvn.transform(new CmpPNode(vthread, threadObj));
 3722   Node* test_vthread_not_equal_threadObj = _gvn.transform(new BoolNode(vthread_cmp_threadObj, BoolTest::ne));
 3723   IfNode* iff_vthread_not_equal_threadObj =
 3724     create_and_map_if(jobj_is_not_null, test_vthread_not_equal_threadObj, PROB_FAIR, COUNT_UNKNOWN);
 3725 
 3726   // False branch, fallback to threadObj.
 3727   Node* vthread_equal_threadObj = _gvn.transform(new IfFalseNode(iff_vthread_not_equal_threadObj));
 3728   set_control(vthread_equal_threadObj);
 3729 
 3730   // Load the tid field from the vthread object.
 3731   Node* thread_obj_tid = load_field_from_object(threadObj, "tid", "J");
 3732 
 3733   // Load the raw epoch value from the threadObj.
 3734   Node* threadObj_epoch_offset = basic_plus_adr(threadObj, java_lang_Thread::jfr_epoch_offset());
 3735   Node* threadObj_epoch_raw = access_load_at(threadObj, threadObj_epoch_offset,
 3736                                              _gvn.type(threadObj_epoch_offset)->isa_ptr(),
 3737                                              TypeInt::CHAR, T_CHAR,
 3738                                              IN_HEAP | MO_UNORDERED | C2_MISMATCHED | C2_CONTROL_DEPENDENT_LOAD);
 3739 
 3740   // Mask off the excluded information from the epoch.
 3741   Node * threadObj_is_excluded = _gvn.transform(new AndINode(threadObj_epoch_raw, excluded_mask));
 3742 
 3743   // True branch, this is a virtual thread.
 3744   Node* vthread_not_equal_threadObj = _gvn.transform(new IfTrueNode(iff_vthread_not_equal_threadObj));
 3745   set_control(vthread_not_equal_threadObj);
 3746 
 3747   // Load the tid field from the vthread object.
 3748   Node* vthread_tid = load_field_from_object(vthread, "tid", "J");
 3749 
 3750   // Continuation support determines if a virtual thread should be pinned.
 3751   Node* global_addr = makecon(TypeRawPtr::make((address)&VMContinuations));
 3752   Node* continuation_support = make_load(control(), global_addr, TypeInt::BOOL, T_BOOLEAN, MemNode::unordered);
 3753 
 3754   // Load the raw epoch value from the vthread.
 3755   Node* vthread_epoch_offset = basic_plus_adr(vthread, java_lang_Thread::jfr_epoch_offset());
 3756   Node* vthread_epoch_raw = access_load_at(vthread, vthread_epoch_offset, _gvn.type(vthread_epoch_offset)->is_ptr(),
 3757                                            TypeInt::CHAR, T_CHAR,
 3758                                            IN_HEAP | MO_UNORDERED | C2_MISMATCHED | C2_CONTROL_DEPENDENT_LOAD);
 3759 
 3760   // Mask off the excluded information from the epoch.
 3761   Node * vthread_is_excluded = _gvn.transform(new AndINode(vthread_epoch_raw, excluded_mask));
 3762 
 3763   // Branch on excluded to conditionalize updating the epoch for the virtual thread.
 3764   Node* is_excluded_cmp = _gvn.transform(new CmpINode(vthread_is_excluded, excluded_mask));
 3765   Node* test_not_excluded = _gvn.transform(new BoolNode(is_excluded_cmp, BoolTest::ne));
 3766   IfNode* iff_not_excluded = create_and_map_if(control(), test_not_excluded, PROB_MAX, COUNT_UNKNOWN);
 3767 
 3768   // False branch, vthread is excluded, no need to write epoch info.
 3769   Node* excluded = _gvn.transform(new IfFalseNode(iff_not_excluded));
 3770 
 3771   // True branch, vthread is included, update epoch info.
 3772   Node* included = _gvn.transform(new IfTrueNode(iff_not_excluded));
 3773   set_control(included);
 3774 
 3775   // Get epoch value.
 3776   Node* epoch = _gvn.transform(new AndINode(vthread_epoch_raw, epoch_mask));
 3777 
 3778   // Load the current epoch generation. The value is unsigned 16-bit, so we type it as T_CHAR.
 3779   Node* epoch_generation_address = makecon(TypeRawPtr::make(JfrIntrinsicSupport::epoch_generation_address()));
 3780   Node* current_epoch_generation = make_load(control(), epoch_generation_address, TypeInt::CHAR, T_CHAR, MemNode::unordered);
 3781 
 3782   // Compare the epoch in the vthread to the current epoch generation.
 3783   Node* const epoch_cmp = _gvn.transform(new CmpUNode(current_epoch_generation, epoch));
 3784   Node* test_epoch_not_equal = _gvn.transform(new BoolNode(epoch_cmp, BoolTest::ne));
 3785   IfNode* iff_epoch_not_equal = create_and_map_if(control(), test_epoch_not_equal, PROB_FAIR, COUNT_UNKNOWN);
 3786 
 3787   // False path, epoch is equal, checkpoint information is valid.
 3788   Node* epoch_is_equal = _gvn.transform(new IfFalseNode(iff_epoch_not_equal));
 3789 
 3790   // True path, epoch is not equal, write a checkpoint for the vthread.
 3791   Node* epoch_is_not_equal = _gvn.transform(new IfTrueNode(iff_epoch_not_equal));
 3792 
 3793   set_control(epoch_is_not_equal);
 3794 
 3795   // Make a runtime call, which can safepoint, to write a checkpoint for the vthread for this epoch.
 3796   // The call also updates the native thread local thread id and the vthread with the current epoch.
 3797   Node* call_write_checkpoint = make_runtime_call(RC_NO_LEAF,
 3798                                                   OptoRuntime::jfr_write_checkpoint_Type(),
 3799                                                   SharedRuntime::jfr_write_checkpoint(),
 3800                                                   "write_checkpoint", TypePtr::BOTTOM);
 3801   Node* call_write_checkpoint_control = _gvn.transform(new ProjNode(call_write_checkpoint, TypeFunc::Control));
 3802 
 3803   // vthread epoch != current epoch
 3804   RegionNode* epoch_compare_rgn = new RegionNode(PATH_LIMIT);
 3805   record_for_igvn(epoch_compare_rgn);
 3806   PhiNode* epoch_compare_mem = new PhiNode(epoch_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
 3807   record_for_igvn(epoch_compare_mem);
 3808   PhiNode* epoch_compare_io = new PhiNode(epoch_compare_rgn, Type::ABIO);
 3809   record_for_igvn(epoch_compare_io);
 3810 
 3811   // Update control and phi nodes.
 3812   epoch_compare_rgn->init_req(_true_path, call_write_checkpoint_control);
 3813   epoch_compare_rgn->init_req(_false_path, epoch_is_equal);
 3814   epoch_compare_mem->init_req(_true_path, reset_memory());
 3815   epoch_compare_mem->init_req(_false_path, input_memory_state);
 3816   epoch_compare_io->init_req(_true_path, i_o());
 3817   epoch_compare_io->init_req(_false_path, input_io_state);
 3818 
 3819   // excluded != true
 3820   RegionNode* exclude_compare_rgn = new RegionNode(PATH_LIMIT);
 3821   record_for_igvn(exclude_compare_rgn);
 3822   PhiNode* exclude_compare_mem = new PhiNode(exclude_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
 3823   record_for_igvn(exclude_compare_mem);
 3824   PhiNode* exclude_compare_io = new PhiNode(exclude_compare_rgn, Type::ABIO);
 3825   record_for_igvn(exclude_compare_io);
 3826 
 3827   // Update control and phi nodes.
 3828   exclude_compare_rgn->init_req(_true_path, _gvn.transform(epoch_compare_rgn));
 3829   exclude_compare_rgn->init_req(_false_path, excluded);
 3830   exclude_compare_mem->init_req(_true_path, _gvn.transform(epoch_compare_mem));
 3831   exclude_compare_mem->init_req(_false_path, input_memory_state);
 3832   exclude_compare_io->init_req(_true_path, _gvn.transform(epoch_compare_io));
 3833   exclude_compare_io->init_req(_false_path, input_io_state);
 3834 
 3835   // vthread != threadObj
 3836   RegionNode* vthread_compare_rgn = new RegionNode(PATH_LIMIT);
 3837   record_for_igvn(vthread_compare_rgn);
 3838   PhiNode* vthread_compare_mem = new PhiNode(vthread_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
 3839   PhiNode* vthread_compare_io = new PhiNode(vthread_compare_rgn, Type::ABIO);
 3840   record_for_igvn(vthread_compare_io);
 3841   PhiNode* tid = new PhiNode(vthread_compare_rgn, TypeLong::LONG);
 3842   record_for_igvn(tid);
 3843   PhiNode* exclusion = new PhiNode(vthread_compare_rgn, TypeInt::CHAR);
 3844   record_for_igvn(exclusion);
 3845   PhiNode* pinVirtualThread = new PhiNode(vthread_compare_rgn, TypeInt::BOOL);
 3846   record_for_igvn(pinVirtualThread);
 3847 
 3848   // Update control and phi nodes.
 3849   vthread_compare_rgn->init_req(_true_path, _gvn.transform(exclude_compare_rgn));
 3850   vthread_compare_rgn->init_req(_false_path, vthread_equal_threadObj);
 3851   vthread_compare_mem->init_req(_true_path, _gvn.transform(exclude_compare_mem));
 3852   vthread_compare_mem->init_req(_false_path, input_memory_state);
 3853   vthread_compare_io->init_req(_true_path, _gvn.transform(exclude_compare_io));
 3854   vthread_compare_io->init_req(_false_path, input_io_state);
 3855   tid->init_req(_true_path, vthread_tid);
 3856   tid->init_req(_false_path, thread_obj_tid);
 3857   exclusion->init_req(_true_path, vthread_is_excluded);
 3858   exclusion->init_req(_false_path, threadObj_is_excluded);
 3859   pinVirtualThread->init_req(_true_path, continuation_support);
 3860   pinVirtualThread->init_req(_false_path, _gvn.intcon(0));
 3861 
 3862   // Update branch state.
 3863   set_control(_gvn.transform(vthread_compare_rgn));
 3864   set_all_memory(_gvn.transform(vthread_compare_mem));
 3865   set_i_o(_gvn.transform(vthread_compare_io));
 3866 
 3867   // Load the event writer oop by dereferencing the jobject handle.
 3868   ciKlass* klass_EventWriter = env()->find_system_klass(ciSymbol::make("jdk/jfr/internal/event/EventWriter"));
 3869   assert(klass_EventWriter->is_loaded(), "invariant");
 3870   ciInstanceKlass* const instklass_EventWriter = klass_EventWriter->as_instance_klass();
 3871   const TypeKlassPtr* const aklass = TypeKlassPtr::make(instklass_EventWriter);
 3872   const TypeOopPtr* const xtype = aklass->as_exact_instance_type();
 3873   Node* jobj_untagged = _gvn.transform(AddPNode::make_off_heap(jobj, _gvn.MakeConX(-JNIHandles::TypeTag::global)));
 3874   Node* event_writer = access_load(jobj_untagged, xtype, T_OBJECT, IN_NATIVE | C2_CONTROL_DEPENDENT_LOAD);
 3875 
 3876   // Load the current thread id from the event writer object.
 3877   Node* const event_writer_tid = load_field_from_object(event_writer, "threadID", "J");
 3878   // Get the field offset to, conditionally, store an updated tid value later.
 3879   Node* const event_writer_tid_field = field_address_from_object(event_writer, "threadID", "J", false);
 3880   // Get the field offset to, conditionally, store an updated exclusion value later.
 3881   Node* const event_writer_excluded_field = field_address_from_object(event_writer, "excluded", "Z", false);
 3882   // Get the field offset to, conditionally, store an updated pinVirtualThread value later.
 3883   Node* const event_writer_pin_field = field_address_from_object(event_writer, "pinVirtualThread", "Z", false);
 3884 
 3885   RegionNode* event_writer_tid_compare_rgn = new RegionNode(PATH_LIMIT);
 3886   record_for_igvn(event_writer_tid_compare_rgn);
 3887   PhiNode* event_writer_tid_compare_mem = new PhiNode(event_writer_tid_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
 3888   record_for_igvn(event_writer_tid_compare_mem);
 3889   PhiNode* event_writer_tid_compare_io = new PhiNode(event_writer_tid_compare_rgn, Type::ABIO);
 3890   record_for_igvn(event_writer_tid_compare_io);
 3891 
 3892   // Compare the current tid from the thread object to what is currently stored in the event writer object.
 3893   Node* const tid_cmp = _gvn.transform(new CmpLNode(event_writer_tid, _gvn.transform(tid)));
 3894   Node* test_tid_not_equal = _gvn.transform(new BoolNode(tid_cmp, BoolTest::ne));
 3895   IfNode* iff_tid_not_equal = create_and_map_if(_gvn.transform(vthread_compare_rgn), test_tid_not_equal, PROB_FAIR, COUNT_UNKNOWN);
 3896 
 3897   // False path, tids are the same.
 3898   Node* tid_is_equal = _gvn.transform(new IfFalseNode(iff_tid_not_equal));
 3899 
 3900   // True path, tid is not equal, need to update the tid in the event writer.
 3901   Node* tid_is_not_equal = _gvn.transform(new IfTrueNode(iff_tid_not_equal));
 3902   record_for_igvn(tid_is_not_equal);
 3903 
 3904   // Store the pin state to the event writer.
 3905   store_to_memory(tid_is_not_equal, event_writer_pin_field, _gvn.transform(pinVirtualThread), T_BOOLEAN, MemNode::unordered);
 3906 
 3907   // Store the exclusion state to the event writer.
 3908   Node* excluded_bool = _gvn.transform(new URShiftINode(_gvn.transform(exclusion), excluded_shift));
 3909   store_to_memory(tid_is_not_equal, event_writer_excluded_field, excluded_bool, T_BOOLEAN, MemNode::unordered);
 3910 
 3911   // Store the tid to the event writer.
 3912   store_to_memory(tid_is_not_equal, event_writer_tid_field, tid, T_LONG, MemNode::unordered);
 3913 
 3914   // Update control and phi nodes.
 3915   event_writer_tid_compare_rgn->init_req(_true_path, tid_is_not_equal);
 3916   event_writer_tid_compare_rgn->init_req(_false_path, tid_is_equal);
 3917   event_writer_tid_compare_mem->init_req(_true_path, reset_memory());
 3918   event_writer_tid_compare_mem->init_req(_false_path, _gvn.transform(vthread_compare_mem));
 3919   event_writer_tid_compare_io->init_req(_true_path, i_o());
 3920   event_writer_tid_compare_io->init_req(_false_path, _gvn.transform(vthread_compare_io));
 3921 
 3922   // Result of top level CFG, Memory, IO and Value.
 3923   RegionNode* result_rgn = new RegionNode(PATH_LIMIT);
 3924   PhiNode* result_mem = new PhiNode(result_rgn, Type::MEMORY, TypePtr::BOTTOM);
 3925   PhiNode* result_io = new PhiNode(result_rgn, Type::ABIO);
 3926   PhiNode* result_value = new PhiNode(result_rgn, TypeInstPtr::BOTTOM);
 3927 
 3928   // Result control.
 3929   result_rgn->init_req(_true_path, _gvn.transform(event_writer_tid_compare_rgn));
 3930   result_rgn->init_req(_false_path, jobj_is_null);
 3931 
 3932   // Result memory.
 3933   result_mem->init_req(_true_path, _gvn.transform(event_writer_tid_compare_mem));
 3934   result_mem->init_req(_false_path, input_memory_state);
 3935 
 3936   // Result IO.
 3937   result_io->init_req(_true_path, _gvn.transform(event_writer_tid_compare_io));
 3938   result_io->init_req(_false_path, input_io_state);
 3939 
 3940   // Result value.
 3941   result_value->init_req(_true_path, event_writer); // return event writer oop
 3942   result_value->init_req(_false_path, null()); // return null
 3943 
 3944   // Set output state.
 3945   set_control(_gvn.transform(result_rgn));
 3946   set_all_memory(_gvn.transform(result_mem));
 3947   set_i_o(_gvn.transform(result_io));
 3948   set_result(result_rgn, result_value);
 3949   return true;
 3950 }
 3951 
 3952 /*
 3953  * The intrinsic is a model of this pseudo-code:
 3954  *
 3955  * JfrThreadLocal* const tl = thread->jfr_thread_local();
 3956  * if (carrierThread != thread) { // is virtual thread
 3957  *   const u2 vthread_epoch_raw = java_lang_Thread::jfr_epoch(thread);
 3958  *   bool excluded = vthread_epoch_raw & excluded_mask;
 3959  *   AtomicAccess::store(&tl->_contextual_tid, java_lang_Thread::tid(thread));
 3960  *   AtomicAccess::store(&tl->_contextual_thread_excluded, is_excluded);
 3961  *   if (!excluded) {
 3962  *     const u2 vthread_epoch = vthread_epoch_raw & epoch_mask;
 3963  *     AtomicAccess::store(&tl->_vthread_epoch, vthread_epoch);
 3964  *   }
 3965  *   AtomicAccess::release_store(&tl->_vthread, true);
 3966  *   return;
 3967  * }
 3968  * AtomicAccess::release_store(&tl->_vthread, false);
 3969  */
 3970 void LibraryCallKit::extend_setCurrentThread(Node* jt, Node* thread) {
 3971   enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
 3972 
 3973   Node* input_memory_state = reset_memory();
 3974   set_all_memory(input_memory_state);
 3975 
 3976   // The most significant bit of the u2 is used to denote thread exclusion
 3977   Node* excluded_mask = _gvn.intcon(1 << 15);
 3978   // The epoch generation is the range [1-32767]
 3979   Node* epoch_mask = _gvn.intcon(32767);
 3980 
 3981   Node* const carrierThread = generate_current_thread(jt);
 3982   // If thread != carrierThread, this is a virtual thread.
 3983   Node* thread_cmp_carrierThread = _gvn.transform(new CmpPNode(thread, carrierThread));
 3984   Node* test_thread_not_equal_carrierThread = _gvn.transform(new BoolNode(thread_cmp_carrierThread, BoolTest::ne));
 3985   IfNode* iff_thread_not_equal_carrierThread =
 3986     create_and_map_if(control(), test_thread_not_equal_carrierThread, PROB_FAIR, COUNT_UNKNOWN);
 3987 
 3988   Node* vthread_offset = off_heap_plus_addr(jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_OFFSET_JFR));
 3989 
 3990   // False branch, is carrierThread.
 3991   Node* thread_equal_carrierThread = _gvn.transform(new IfFalseNode(iff_thread_not_equal_carrierThread));
 3992   // Store release
 3993   Node* vthread_false_memory = store_to_memory(thread_equal_carrierThread, vthread_offset, _gvn.intcon(0), T_BOOLEAN, MemNode::release, true);
 3994 
 3995   set_all_memory(input_memory_state);
 3996 
 3997   // True branch, is virtual thread.
 3998   Node* thread_not_equal_carrierThread = _gvn.transform(new IfTrueNode(iff_thread_not_equal_carrierThread));
 3999   set_control(thread_not_equal_carrierThread);
 4000 
 4001   // Load the raw epoch value from the vthread.
 4002   Node* epoch_offset = basic_plus_adr(thread, java_lang_Thread::jfr_epoch_offset());
 4003   Node* epoch_raw = access_load_at(thread, epoch_offset, _gvn.type(epoch_offset)->is_ptr(), TypeInt::CHAR, T_CHAR,
 4004                                    IN_HEAP | MO_UNORDERED | C2_MISMATCHED | C2_CONTROL_DEPENDENT_LOAD);
 4005 
 4006   // Mask off the excluded information from the epoch.
 4007   Node * const is_excluded = _gvn.transform(new AndINode(epoch_raw, excluded_mask));
 4008 
 4009   // Load the tid field from the thread.
 4010   Node* tid = load_field_from_object(thread, "tid", "J");
 4011 
 4012   // Store the vthread tid to the jfr thread local.
 4013   Node* thread_id_offset = off_heap_plus_addr(jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_ID_OFFSET_JFR));
 4014   Node* tid_memory = store_to_memory(control(), thread_id_offset, tid, T_LONG, MemNode::unordered, true);
 4015 
 4016   // Branch is_excluded to conditionalize updating the epoch .
 4017   Node* excluded_cmp = _gvn.transform(new CmpINode(is_excluded, excluded_mask));
 4018   Node* test_excluded = _gvn.transform(new BoolNode(excluded_cmp, BoolTest::eq));
 4019   IfNode* iff_excluded = create_and_map_if(control(), test_excluded, PROB_MIN, COUNT_UNKNOWN);
 4020 
 4021   // True branch, vthread is excluded, no need to write epoch info.
 4022   Node* excluded = _gvn.transform(new IfTrueNode(iff_excluded));
 4023   set_control(excluded);
 4024   Node* vthread_is_excluded = _gvn.intcon(1);
 4025 
 4026   // False branch, vthread is included, update epoch info.
 4027   Node* included = _gvn.transform(new IfFalseNode(iff_excluded));
 4028   set_control(included);
 4029   Node* vthread_is_included = _gvn.intcon(0);
 4030 
 4031   // Get epoch value.
 4032   Node* epoch = _gvn.transform(new AndINode(epoch_raw, epoch_mask));
 4033 
 4034   // Store the vthread epoch to the jfr thread local.
 4035   Node* vthread_epoch_offset = off_heap_plus_addr(jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_EPOCH_OFFSET_JFR));
 4036   Node* included_memory = store_to_memory(control(), vthread_epoch_offset, epoch, T_CHAR, MemNode::unordered, true);
 4037 
 4038   RegionNode* excluded_rgn = new RegionNode(PATH_LIMIT);
 4039   record_for_igvn(excluded_rgn);
 4040   PhiNode* excluded_mem = new PhiNode(excluded_rgn, Type::MEMORY, TypePtr::BOTTOM);
 4041   record_for_igvn(excluded_mem);
 4042   PhiNode* exclusion = new PhiNode(excluded_rgn, TypeInt::BOOL);
 4043   record_for_igvn(exclusion);
 4044 
 4045   // Merge the excluded control and memory.
 4046   excluded_rgn->init_req(_true_path, excluded);
 4047   excluded_rgn->init_req(_false_path, included);
 4048   excluded_mem->init_req(_true_path, tid_memory);
 4049   excluded_mem->init_req(_false_path, included_memory);
 4050   exclusion->init_req(_true_path, vthread_is_excluded);
 4051   exclusion->init_req(_false_path, vthread_is_included);
 4052 
 4053   // Set intermediate state.
 4054   set_control(_gvn.transform(excluded_rgn));
 4055   set_all_memory(excluded_mem);
 4056 
 4057   // Store the vthread exclusion state to the jfr thread local.
 4058   Node* thread_local_excluded_offset = off_heap_plus_addr(jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_EXCLUDED_OFFSET_JFR));
 4059   store_to_memory(control(), thread_local_excluded_offset, _gvn.transform(exclusion), T_BOOLEAN, MemNode::unordered, true);
 4060 
 4061   // Store release
 4062   Node * vthread_true_memory = store_to_memory(control(), vthread_offset, _gvn.intcon(1), T_BOOLEAN, MemNode::release, true);
 4063 
 4064   RegionNode* thread_compare_rgn = new RegionNode(PATH_LIMIT);
 4065   record_for_igvn(thread_compare_rgn);
 4066   PhiNode* thread_compare_mem = new PhiNode(thread_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
 4067   record_for_igvn(thread_compare_mem);
 4068   PhiNode* vthread = new PhiNode(thread_compare_rgn, TypeInt::BOOL);
 4069   record_for_igvn(vthread);
 4070 
 4071   // Merge the thread_compare control and memory.
 4072   thread_compare_rgn->init_req(_true_path, control());
 4073   thread_compare_rgn->init_req(_false_path, thread_equal_carrierThread);
 4074   thread_compare_mem->init_req(_true_path, vthread_true_memory);
 4075   thread_compare_mem->init_req(_false_path, vthread_false_memory);
 4076 
 4077   // Set output state.
 4078   set_control(_gvn.transform(thread_compare_rgn));
 4079   set_all_memory(_gvn.transform(thread_compare_mem));
 4080 }
 4081 
 4082 //------------------------inline_native_try_update_epoch------------------
 4083 //
 4084 // The generated code is a function of the argument type.
 4085 //
 4086 bool LibraryCallKit::inline_native_try_update_epoch() {
 4087   enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
 4088 
 4089   // Save input memory.
 4090   Node* input_memory_state = reset_memory();
 4091   set_all_memory(input_memory_state);
 4092 
 4093   // Argument is an oop whose class has an injected instance field,
 4094   // called 'jfr_epoch' of type T_INT, used for holding a jfr epoch value.
 4095   Node* oop = argument(0);
 4096   const TypeInstPtr* tinst = _gvn.type(oop)->isa_instptr();
 4097   assert(tinst != nullptr, "oop is null");
 4098   assert(tinst->is_loaded(), "klass is not loaded");
 4099   ciInstanceKlass* const ik = tinst->instance_klass();
 4100 
 4101   ciField* const field = ik->get_injected_instance_field_by_name(ciSymbol::make("jfr_epoch"),
 4102                                                                  ciSymbol::make("I"));
 4103 
 4104   assert(field != nullptr, "field 'jfr_epoch' of type I not injected in klass %s", ik->name()->as_utf8());
 4105 
 4106   const int jfr_epoch_field_offset = field->offset_in_bytes();
 4107   Node* oop_epoch_field_offset = basic_plus_adr(oop, jfr_epoch_field_offset);
 4108   const TypePtr* adr_type = _gvn.type(oop_epoch_field_offset)->isa_ptr();
 4109   const int alias_idx = C->get_alias_index(adr_type);
 4110   BasicType bt = field->layout_type();
 4111   const Type * oop_epoch_field_type = Type::get_const_basic_type(bt);
 4112 
 4113   // Load the epoch value from the oop.
 4114   Node* oop_epoch = access_load_at(oop,
 4115                                    oop_epoch_field_offset,
 4116                                    adr_type, oop_epoch_field_type,
 4117                                    bt, IN_HEAP | MO_UNORDERED);
 4118 
 4119   // Load the current JFR epoch generation. The value is unsigned 16-bit, so we type it as T_CHAR.
 4120   Node* epoch_generation_address = makecon(TypeRawPtr::make(JfrIntrinsicSupport::epoch_generation_address()));
 4121   Node* current_epoch_generation = make_load(control(), epoch_generation_address, TypeInt::CHAR, T_CHAR, MemNode::unordered);
 4122 
 4123   // Compare the epoch in the oop against the current JFR epoch generation.
 4124   Node* const epochs_cmp = _gvn.transform(new CmpINode(current_epoch_generation, oop_epoch));
 4125   Node* epochs_equal_test = _gvn.transform(new BoolNode(epochs_cmp, BoolTest::eq));
 4126   IfNode* iff_epochs_equal = create_and_map_if(control(), epochs_equal_test, PROB_LIKELY(0.999), COUNT_UNKNOWN);
 4127 
 4128   // True path.
 4129   Node* epochs_are_equal = _gvn.transform(new IfTrueNode(iff_epochs_equal));
 4130 
 4131   // False path.
 4132   Node* epochs_are_not_equal = _gvn.transform(new IfFalseNode(iff_epochs_equal));
 4133 
 4134   set_control(_gvn.transform(epochs_are_not_equal));
 4135 
 4136   // Attempt to cas the current JFR epoch generation into the oop epoch field.
 4137   DecoratorSet decorators = IN_HEAP;
 4138   decorators |= mo_decorator_for_access_kind(Volatile);
 4139 
 4140   Node* result = access_atomic_cmpxchg_val_at(oop,
 4141                                               oop_epoch_field_offset,
 4142                                               adr_type, alias_idx,
 4143                                               oop_epoch, // expected value
 4144                                               current_epoch_generation, // new value
 4145                                               oop_epoch_field_type,
 4146                                               bt,
 4147                                               decorators);
 4148 
 4149   // Compare the result of the cas operation to the expected value.
 4150   Node* const cas_cmp_to_expected_value = _gvn.transform(new CmpINode(result, oop_epoch));
 4151   Node* cas_operation_test = _gvn.transform(new BoolNode(cas_cmp_to_expected_value, BoolTest::eq));
 4152   IfNode* iff_cas_success = create_and_map_if(control(), cas_operation_test, PROB_LIKELY(0.999), COUNT_UNKNOWN);
 4153 
 4154   // True path.
 4155   Node* cas_success = _gvn.transform(new IfTrueNode(iff_cas_success));
 4156 
 4157   // False path.
 4158   Node* cas_failure = _gvn.transform(new IfFalseNode(iff_cas_success));
 4159 
 4160   // Cas result region and phi nodes.
 4161   RegionNode* cas_operation_rgn = new RegionNode(PATH_LIMIT);
 4162   record_for_igvn(cas_operation_rgn);
 4163   PhiNode* cas_operation_mem = new PhiNode(cas_operation_rgn, Type::MEMORY, TypePtr::BOTTOM);
 4164   record_for_igvn(cas_operation_mem);
 4165   PhiNode* cas_result = new PhiNode(cas_operation_rgn, TypeInt::BOOL);
 4166   record_for_igvn(cas_result);
 4167 
 4168   cas_operation_rgn->init_req(_true_path, _gvn.transform(cas_success));
 4169   cas_operation_rgn->init_req(_false_path, _gvn.transform(cas_failure));
 4170   cas_operation_mem->init_req(_true_path, reset_memory());
 4171   cas_operation_mem->init_req(_false_path, input_memory_state);
 4172   cas_result->init_req(_true_path, _gvn.intcon(1));
 4173   cas_result->init_req(_false_path, _gvn.intcon(0));
 4174 
 4175   // Epoch compare region and phi nodes.
 4176   RegionNode* epoch_compare_rgn = new RegionNode(PATH_LIMIT);
 4177   record_for_igvn(epoch_compare_rgn);
 4178   PhiNode* epoch_compare_mem = new PhiNode(epoch_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
 4179   record_for_igvn(epoch_compare_mem);
 4180   PhiNode* result_value = new PhiNode(epoch_compare_rgn, TypeInt::BOOL);
 4181   record_for_igvn(result_value);
 4182 
 4183   epoch_compare_rgn->init_req(_true_path, _gvn.transform(epochs_are_equal));
 4184   epoch_compare_rgn->init_req(_false_path, _gvn.transform(cas_operation_rgn));
 4185   epoch_compare_mem->init_req(_true_path, _gvn.transform(input_memory_state));
 4186   epoch_compare_mem->init_req(_false_path, _gvn.transform(cas_operation_mem));
 4187   result_value->init_req(_true_path, _gvn.intcon(0));
 4188   result_value->init_req(_false_path, _gvn.transform(cas_result));
 4189 
 4190   // Set output state.
 4191   set_result(epoch_compare_rgn, result_value);
 4192   set_all_memory(_gvn.transform(epoch_compare_mem));
 4193 
 4194   return true;
 4195 }
 4196 
 4197 #endif // JFR_HAVE_INTRINSICS
 4198 
 4199 //------------------------inline_native_currentCarrierThread------------------
 4200 bool LibraryCallKit::inline_native_currentCarrierThread() {
 4201   Node* junk = nullptr;
 4202   set_result(generate_current_thread(junk));
 4203   return true;
 4204 }
 4205 
 4206 //------------------------inline_native_currentThread------------------
 4207 bool LibraryCallKit::inline_native_currentThread() {
 4208   Node* junk = nullptr;
 4209   set_result(generate_virtual_thread(junk));
 4210   return true;
 4211 }
 4212 
 4213 //------------------------inline_native_setVthread------------------
 4214 bool LibraryCallKit::inline_native_setCurrentThread() {
 4215   assert(C->method()->changes_current_thread(),
 4216          "method changes current Thread but is not annotated ChangesCurrentThread");
 4217   Node* arr = argument(1);
 4218   Node* thread = _gvn.transform(new ThreadLocalNode());
 4219   Node* p = off_heap_plus_addr(thread, in_bytes(JavaThread::vthread_offset()));
 4220   Node* thread_obj_handle
 4221     = make_load(nullptr, p, p->bottom_type()->is_ptr(), T_OBJECT, MemNode::unordered);
 4222   const TypePtr *adr_type = _gvn.type(thread_obj_handle)->isa_ptr();
 4223   access_store_at(nullptr, thread_obj_handle, adr_type, arr, _gvn.type(arr), T_OBJECT, IN_NATIVE | MO_UNORDERED);
 4224 
 4225   // Change the _monitor_owner_id of the JavaThread
 4226   Node* tid = load_field_from_object(arr, "tid", "J");
 4227   Node* monitor_owner_id_offset = off_heap_plus_addr(thread, in_bytes(JavaThread::monitor_owner_id_offset()));
 4228   store_to_memory(control(), monitor_owner_id_offset, tid, T_LONG, MemNode::unordered, true);
 4229 
 4230   JFR_ONLY(extend_setCurrentThread(thread, arr);)
 4231   return true;
 4232 }
 4233 
 4234 const Type* LibraryCallKit::scopedValueCache_type() {
 4235   ciKlass* objects_klass = ciObjArrayKlass::make(env()->Object_klass());
 4236   const TypeOopPtr* etype = TypeOopPtr::make_from_klass(env()->Object_klass());
 4237   const TypeAry* arr0 = TypeAry::make(etype, TypeInt::POS, /* stable= */ false, /* flat= */ false, /* not_flat= */ true, /* not_null_free= */ true, true);
 4238 
 4239   // Because we create the scopedValue cache lazily we have to make the
 4240   // type of the result BotPTR.
 4241   bool xk = etype->klass_is_exact();
 4242   const Type* objects_type = TypeAryPtr::make(TypePtr::BotPTR, arr0, objects_klass, xk, TypeAryPtr::Offset(0));
 4243   return objects_type;
 4244 }
 4245 
 4246 Node* LibraryCallKit::scopedValueCache_helper() {
 4247   Node* thread = _gvn.transform(new ThreadLocalNode());
 4248   Node* p = off_heap_plus_addr(thread, in_bytes(JavaThread::scopedValueCache_offset()));
 4249   // We cannot use immutable_memory() because we might flip onto a
 4250   // different carrier thread, at which point we'll need to use that
 4251   // carrier thread's cache.
 4252   // return _gvn.transform(LoadNode::make(_gvn, nullptr, immutable_memory(), p, p->bottom_type()->is_ptr(),
 4253   //       TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered));
 4254   return make_load(nullptr, p, p->bottom_type()->is_ptr(), T_ADDRESS, MemNode::unordered);
 4255 }
 4256 
 4257 //------------------------inline_native_scopedValueCache------------------
 4258 bool LibraryCallKit::inline_native_scopedValueCache() {
 4259   Node* cache_obj_handle = scopedValueCache_helper();
 4260   const Type* objects_type = scopedValueCache_type();
 4261   set_result(access_load(cache_obj_handle, objects_type, T_OBJECT, IN_NATIVE));
 4262 
 4263   return true;
 4264 }
 4265 
 4266 //------------------------inline_native_setScopedValueCache------------------
 4267 bool LibraryCallKit::inline_native_setScopedValueCache() {
 4268   Node* arr = argument(0);
 4269   Node* cache_obj_handle = scopedValueCache_helper();
 4270   const Type* objects_type = scopedValueCache_type();
 4271 
 4272   const TypePtr *adr_type = _gvn.type(cache_obj_handle)->isa_ptr();
 4273   access_store_at(nullptr, cache_obj_handle, adr_type, arr, objects_type, T_OBJECT, IN_NATIVE | MO_UNORDERED);
 4274 
 4275   return true;
 4276 }
 4277 
 4278 //------------------------inline_native_Continuation_pin and unpin-----------
 4279 
 4280 // Shared implementation routine for both pin and unpin.
 4281 bool LibraryCallKit::inline_native_Continuation_pinning(bool unpin) {
 4282   enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
 4283 
 4284   // Save input memory.
 4285   Node* input_memory_state = reset_memory();
 4286   set_all_memory(input_memory_state);
 4287 
 4288   // TLS
 4289   Node* tls_ptr = _gvn.transform(new ThreadLocalNode());
 4290   Node* last_continuation_offset = off_heap_plus_addr(tls_ptr, in_bytes(JavaThread::cont_entry_offset()));
 4291   Node* last_continuation = make_load(control(), last_continuation_offset, last_continuation_offset->get_ptr_type(), T_ADDRESS, MemNode::unordered);
 4292 
 4293   // Null check the last continuation object.
 4294   Node* continuation_cmp_null = _gvn.transform(new CmpPNode(last_continuation, null()));
 4295   Node* test_continuation_not_equal_null = _gvn.transform(new BoolNode(continuation_cmp_null, BoolTest::ne));
 4296   IfNode* iff_continuation_not_equal_null = create_and_map_if(control(), test_continuation_not_equal_null, PROB_MAX, COUNT_UNKNOWN);
 4297 
 4298   // False path, last continuation is null.
 4299   Node* continuation_is_null = _gvn.transform(new IfFalseNode(iff_continuation_not_equal_null));
 4300 
 4301   // True path, last continuation is not null.
 4302   Node* continuation_is_not_null = _gvn.transform(new IfTrueNode(iff_continuation_not_equal_null));
 4303 
 4304   set_control(continuation_is_not_null);
 4305 
 4306   // Load the pin count from the last continuation.
 4307   Node* pin_count_offset = off_heap_plus_addr(last_continuation, in_bytes(ContinuationEntry::pin_count_offset()));
 4308   Node* pin_count = make_load(control(), pin_count_offset, TypeInt::INT, T_INT, MemNode::unordered);
 4309 
 4310   // The loaded pin count is compared against a context specific rhs for over/underflow detection.
 4311   Node* pin_count_rhs;
 4312   if (unpin) {
 4313     pin_count_rhs = _gvn.intcon(0);
 4314   } else {
 4315     pin_count_rhs = _gvn.intcon(UINT32_MAX);
 4316   }
 4317   Node* pin_count_cmp = _gvn.transform(new CmpUNode(pin_count, pin_count_rhs));
 4318   Node* test_pin_count_over_underflow = _gvn.transform(new BoolNode(pin_count_cmp, BoolTest::eq));
 4319   IfNode* iff_pin_count_over_underflow = create_and_map_if(control(), test_pin_count_over_underflow, PROB_MIN, COUNT_UNKNOWN);
 4320 
 4321   // True branch, pin count over/underflow.
 4322   Node* pin_count_over_underflow = _gvn.transform(new IfTrueNode(iff_pin_count_over_underflow));
 4323   {
 4324     // Trap (but not deoptimize (Action_none)) and continue in the interpreter
 4325     // which will throw IllegalStateException for pin count over/underflow.
 4326     // No memory changed so far - we can use memory create by reset_memory()
 4327     // at the beginning of this intrinsic. No need to call reset_memory() again.
 4328     PreserveJVMState pjvms(this);
 4329     set_control(pin_count_over_underflow);
 4330     uncommon_trap(Deoptimization::Reason_intrinsic,
 4331                   Deoptimization::Action_none);
 4332     assert(stopped(), "invariant");
 4333   }
 4334 
 4335   // False branch, no pin count over/underflow. Increment or decrement pin count and store back.
 4336   Node* valid_pin_count = _gvn.transform(new IfFalseNode(iff_pin_count_over_underflow));
 4337   set_control(valid_pin_count);
 4338 
 4339   Node* next_pin_count;
 4340   if (unpin) {
 4341     next_pin_count = _gvn.transform(new SubINode(pin_count, _gvn.intcon(1)));
 4342   } else {
 4343     next_pin_count = _gvn.transform(new AddINode(pin_count, _gvn.intcon(1)));
 4344   }
 4345 
 4346   store_to_memory(control(), pin_count_offset, next_pin_count, T_INT, MemNode::unordered);
 4347 
 4348   // Result of top level CFG and Memory.
 4349   RegionNode* result_rgn = new RegionNode(PATH_LIMIT);
 4350   record_for_igvn(result_rgn);
 4351   PhiNode* result_mem = new PhiNode(result_rgn, Type::MEMORY, TypePtr::BOTTOM);
 4352   record_for_igvn(result_mem);
 4353 
 4354   result_rgn->init_req(_true_path, valid_pin_count);
 4355   result_rgn->init_req(_false_path, continuation_is_null);
 4356   result_mem->init_req(_true_path, reset_memory());
 4357   result_mem->init_req(_false_path, input_memory_state);
 4358 
 4359   // Set output state.
 4360   set_control(_gvn.transform(result_rgn));
 4361   set_all_memory(_gvn.transform(result_mem));
 4362 
 4363   return true;
 4364 }
 4365 
 4366 //---------------------------load_mirror_from_klass----------------------------
 4367 // Given a klass oop, load its java mirror (a java.lang.Class oop).
 4368 Node* LibraryCallKit::load_mirror_from_klass(Node* klass) {
 4369   Node* p = off_heap_plus_addr(klass, in_bytes(Klass::java_mirror_offset()));
 4370   Node* load = make_load(nullptr, p, TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered);
 4371   // mirror = ((OopHandle)mirror)->resolve();
 4372   return access_load(load, TypeInstPtr::MIRROR, T_OBJECT, IN_NATIVE);
 4373 }
 4374 
 4375 //-----------------------load_klass_from_mirror_common-------------------------
 4376 // Given a java mirror (a java.lang.Class oop), load its corresponding klass oop.
 4377 // Test the klass oop for null (signifying a primitive Class like Integer.TYPE),
 4378 // and branch to the given path on the region.
 4379 // If never_see_null, take an uncommon trap on null, so we can optimistically
 4380 // compile for the non-null case.
 4381 // If the region is null, force never_see_null = true.
 4382 Node* LibraryCallKit::load_klass_from_mirror_common(Node* mirror,
 4383                                                     bool never_see_null,
 4384                                                     RegionNode* region,
 4385                                                     int null_path,
 4386                                                     int offset) {
 4387   if (region == nullptr)  never_see_null = true;
 4388   Node* p = basic_plus_adr(mirror, offset);
 4389   const TypeKlassPtr*  kls_type = TypeInstKlassPtr::OBJECT_OR_NULL;
 4390   Node* kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), p, TypeRawPtr::BOTTOM, kls_type));
 4391   Node* null_ctl = top();
 4392   kls = null_check_oop(kls, &null_ctl, never_see_null);
 4393   if (region != nullptr) {
 4394     // Set region->in(null_path) if the mirror is a primitive (e.g, int.class).
 4395     region->init_req(null_path, null_ctl);
 4396   } else {
 4397     assert(null_ctl == top(), "no loose ends");
 4398   }
 4399   return kls;
 4400 }
 4401 
 4402 //--------------------(inline_native_Class_query helpers)---------------------
 4403 // Use this for JVM_ACC_INTERFACE.
 4404 // Fall through if (mods & mask) == bits, take the guard otherwise.
 4405 Node* LibraryCallKit::generate_klass_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region,
 4406                                                  ByteSize offset, const Type* type, BasicType bt) {
 4407   // Branch around if the given klass has the given modifier bit set.
 4408   // Like generate_guard, adds a new path onto the region.
 4409   Node* modp = off_heap_plus_addr(kls, in_bytes(offset));
 4410   Node* mods = make_load(nullptr, modp, type, bt, MemNode::unordered);
 4411   Node* mask = intcon(modifier_mask);
 4412   Node* bits = intcon(modifier_bits);
 4413   Node* mbit = _gvn.transform(new AndINode(mods, mask));
 4414   Node* cmp  = _gvn.transform(new CmpINode(mbit, bits));
 4415   Node* bol  = _gvn.transform(new BoolNode(cmp, BoolTest::ne));
 4416   return generate_fair_guard(bol, region);
 4417 }
 4418 
 4419 Node* LibraryCallKit::generate_interface_guard(Node* kls, RegionNode* region) {
 4420   return generate_klass_flags_guard(kls, JVM_ACC_INTERFACE, 0, region,
 4421                                     InstanceKlass::access_flags_offset(), TypeInt::CHAR, T_CHAR);
 4422 }
 4423 
 4424 // Use this for testing if Klass is_hidden, has_finalizer, and is_cloneable_fast.
 4425 Node* LibraryCallKit::generate_misc_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region) {
 4426   return generate_klass_flags_guard(kls, modifier_mask, modifier_bits, region,
 4427                                     Klass::misc_flags_offset(), TypeInt::UBYTE, T_BOOLEAN);
 4428 }
 4429 
 4430 Node* LibraryCallKit::generate_hidden_class_guard(Node* kls, RegionNode* region) {
 4431   return generate_misc_flags_guard(kls, KlassFlags::_misc_is_hidden_class, 0, region);
 4432 }
 4433 
 4434 //-------------------------inline_native_Class_query-------------------
 4435 bool LibraryCallKit::inline_native_Class_query(vmIntrinsics::ID id) {
 4436   const Type* return_type = TypeInt::BOOL;
 4437   Node* prim_return_value = top();  // what happens if it's a primitive class?
 4438   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
 4439   bool expect_prim = false;     // most of these guys expect to work on refs
 4440 
 4441   enum { _normal_path = 1, _prim_path = 2, PATH_LIMIT };
 4442 
 4443   Node* mirror = argument(0);
 4444   Node* obj    = top();
 4445 
 4446   switch (id) {
 4447   case vmIntrinsics::_isInstance:
 4448     // nothing is an instance of a primitive type
 4449     prim_return_value = intcon(0);
 4450     obj = argument(1);
 4451     break;
 4452   case vmIntrinsics::_isHidden:
 4453     prim_return_value = intcon(0);
 4454     break;
 4455   case vmIntrinsics::_getSuperclass:
 4456     prim_return_value = null();
 4457     return_type = TypeInstPtr::MIRROR->cast_to_ptr_type(TypePtr::BotPTR);
 4458     break;
 4459   default:
 4460     fatal_unexpected_iid(id);
 4461     break;
 4462   }
 4463 
 4464   const TypeInstPtr* mirror_con = _gvn.type(mirror)->isa_instptr();
 4465   if (mirror_con == nullptr)  return false;  // cannot happen?
 4466 
 4467 #ifndef PRODUCT
 4468   if (C->print_intrinsics() || C->print_inlining()) {
 4469     ciType* k = mirror_con->java_mirror_type();
 4470     if (k) {
 4471       tty->print("Inlining %s on constant Class ", vmIntrinsics::name_at(intrinsic_id()));
 4472       k->print_name();
 4473       tty->cr();
 4474     }
 4475   }
 4476 #endif
 4477 
 4478   // Null-check the mirror, and the mirror's klass ptr (in case it is a primitive).
 4479   RegionNode* region = new RegionNode(PATH_LIMIT);
 4480   record_for_igvn(region);
 4481   PhiNode* phi = new PhiNode(region, return_type);
 4482 
 4483   // The mirror will never be null of Reflection.getClassAccessFlags, however
 4484   // it may be null for Class.isInstance or Class.getModifiers. Throw a NPE
 4485   // if it is. See bug 4774291.
 4486 
 4487   // For Reflection.getClassAccessFlags(), the null check occurs in
 4488   // the wrong place; see inline_unsafe_access(), above, for a similar
 4489   // situation.
 4490   mirror = null_check(mirror);
 4491   // If mirror or obj is dead, only null-path is taken.
 4492   if (stopped())  return true;
 4493 
 4494   if (expect_prim)  never_see_null = false;  // expect nulls (meaning prims)
 4495 
 4496   // Now load the mirror's klass metaobject, and null-check it.
 4497   // Side-effects region with the control path if the klass is null.
 4498   Node* kls = load_klass_from_mirror(mirror, never_see_null, region, _prim_path);
 4499   // If kls is null, we have a primitive mirror.
 4500   phi->init_req(_prim_path, prim_return_value);
 4501   if (stopped()) { set_result(region, phi); return true; }
 4502   bool safe_for_replace = (region->in(_prim_path) == top());
 4503 
 4504   Node* p;  // handy temp
 4505   Node* null_ctl;
 4506 
 4507   // Now that we have the non-null klass, we can perform the real query.
 4508   // For constant classes, the query will constant-fold in LoadNode::Value.
 4509   Node* query_value = top();
 4510   switch (id) {
 4511   case vmIntrinsics::_isInstance:
 4512     // nothing is an instance of a primitive type
 4513     query_value = gen_instanceof(obj, kls, safe_for_replace);
 4514     break;
 4515 
 4516   case vmIntrinsics::_isHidden:
 4517     // (To verify this code sequence, check the asserts in JVM_IsHiddenClass.)
 4518     if (generate_hidden_class_guard(kls, region) != nullptr)
 4519       // A guard was added.  If the guard is taken, it was an hidden class.
 4520       phi->add_req(intcon(1));
 4521     // If we fall through, it's a plain class.
 4522     query_value = intcon(0);
 4523     break;
 4524 
 4525 
 4526   case vmIntrinsics::_getSuperclass:
 4527     // The rules here are somewhat unfortunate, but we can still do better
 4528     // with random logic than with a JNI call.
 4529     // Interfaces store null or Object as _super, but must report null.
 4530     // Arrays store an intermediate super as _super, but must report Object.
 4531     // Other types can report the actual _super.
 4532     // (To verify this code sequence, check the asserts in JVM_IsInterface.)
 4533     if (generate_array_guard(kls, region) != nullptr) {
 4534       // A guard was added.  If the guard is taken, it was an array.
 4535       phi->add_req(makecon(TypeInstPtr::make(env()->Object_klass()->java_mirror())));
 4536     }
 4537     // Check for interface after array since this checks AccessFlags offset into InstanceKlass.
 4538     // In other words, we are accessing subtype-specific information, so we need to determine the subtype first.
 4539     if (generate_interface_guard(kls, region) != nullptr) {
 4540       // A guard was added.  If the guard is taken, it was an interface.
 4541       phi->add_req(null());
 4542     }
 4543     // If we fall through, it's a plain class.  Get its _super.
 4544     if (!stopped()) {
 4545       p = basic_plus_adr(top(), kls, in_bytes(Klass::super_offset()));
 4546       kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), p, TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
 4547       null_ctl = top();
 4548       kls = null_check_oop(kls, &null_ctl);
 4549       if (null_ctl != top()) {
 4550         // If the guard is taken, Object.superClass is null (both klass and mirror).
 4551         region->add_req(null_ctl);
 4552         phi   ->add_req(null());
 4553       }
 4554       if (!stopped()) {
 4555         query_value = load_mirror_from_klass(kls);
 4556       }
 4557     }
 4558     break;
 4559 
 4560   default:
 4561     fatal_unexpected_iid(id);
 4562     break;
 4563   }
 4564 
 4565   // Fall-through is the normal case of a query to a real class.
 4566   phi->init_req(1, query_value);
 4567   region->init_req(1, control());
 4568 
 4569   C->set_has_split_ifs(true); // Has chance for split-if optimization
 4570   set_result(region, phi);
 4571   return true;
 4572 }
 4573 
 4574 
 4575 //-------------------------inline_Class_cast-------------------
 4576 bool LibraryCallKit::inline_Class_cast() {
 4577   Node* mirror = argument(0); // Class
 4578   Node* obj    = argument(1);
 4579   const TypeInstPtr* mirror_con = _gvn.type(mirror)->isa_instptr();
 4580   if (mirror_con == nullptr) {
 4581     return false;  // dead path (mirror->is_top()).
 4582   }
 4583   if (obj == nullptr || obj->is_top()) {
 4584     return false;  // dead path
 4585   }
 4586   const TypeOopPtr* tp = _gvn.type(obj)->isa_oopptr();
 4587 
 4588   // First, see if Class.cast() can be folded statically.
 4589   // java_mirror_type() returns non-null for compile-time Class constants.
 4590   ciType* tm = mirror_con->java_mirror_type();
 4591   if (tm != nullptr && tm->is_klass() &&
 4592       tp != nullptr) {
 4593     if (!tp->is_loaded()) {
 4594       // Don't use intrinsic when class is not loaded.
 4595       return false;
 4596     } else {
 4597       const TypeKlassPtr* tklass = TypeKlassPtr::make(tm->as_klass(), Type::trust_interfaces);
 4598       int static_res = C->static_subtype_check(tklass, tp->as_klass_type());
 4599       if (static_res == Compile::SSC_always_true) {
 4600         // isInstance() is true - fold the code.
 4601         set_result(obj);
 4602         return true;
 4603       } else if (static_res == Compile::SSC_always_false) {
 4604         // Don't use intrinsic, have to throw ClassCastException.
 4605         // If the reference is null, the non-intrinsic bytecode will
 4606         // be optimized appropriately.
 4607         return false;
 4608       }
 4609     }
 4610   }
 4611 
 4612   // Bailout intrinsic and do normal inlining if exception path is frequent.
 4613   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
 4614     return false;
 4615   }
 4616 
 4617   // Generate dynamic checks.
 4618   // Class.cast() is java implementation of _checkcast bytecode.
 4619   // Do checkcast (Parse::do_checkcast()) optimizations here.
 4620 
 4621   mirror = null_check(mirror);
 4622   // If mirror is dead, only null-path is taken.
 4623   if (stopped()) {
 4624     return true;
 4625   }
 4626 
 4627   // Not-subtype or the mirror's klass ptr is nullptr (in case it is a primitive).
 4628   enum { _bad_type_path = 1, _prim_path = 2, _npe_path = 3, PATH_LIMIT };
 4629   RegionNode* region = new RegionNode(PATH_LIMIT);
 4630   record_for_igvn(region);
 4631 
 4632   // Now load the mirror's klass metaobject, and null-check it.
 4633   // If kls is null, we have a primitive mirror and
 4634   // nothing is an instance of a primitive type.
 4635   Node* kls = load_klass_from_mirror(mirror, false, region, _prim_path);
 4636 
 4637   Node* res = top();
 4638   Node* io = i_o();
 4639   Node* mem = merged_memory();
 4640   SafePointNode* new_cast_failure_map = nullptr;
 4641 
 4642   if (!stopped()) {
 4643 
 4644     Node* bad_type_ctrl = top();
 4645     // Do checkcast optimizations.
 4646     res = gen_checkcast(obj, kls, &bad_type_ctrl, &new_cast_failure_map);
 4647     region->init_req(_bad_type_path, bad_type_ctrl);
 4648   }
 4649   if (region->in(_prim_path) != top() ||
 4650       region->in(_bad_type_path) != top() ||
 4651       region->in(_npe_path) != top()) {
 4652     // Let Interpreter throw ClassCastException.
 4653     PreserveJVMState pjvms(this);
 4654     if (new_cast_failure_map != nullptr) {
 4655       // The current map on the success path could have been modified. Use the dedicated failure path map.
 4656       set_map(new_cast_failure_map);
 4657     }
 4658     set_control(_gvn.transform(region));
 4659     // Set IO and memory because gen_checkcast may override them when buffering inline types
 4660     set_i_o(io);
 4661     set_all_memory(mem);
 4662     uncommon_trap(Deoptimization::Reason_intrinsic,
 4663                   Deoptimization::Action_maybe_recompile);
 4664   }
 4665   if (!stopped()) {
 4666     set_result(res);
 4667   }
 4668   return true;
 4669 }
 4670 
 4671 
 4672 //--------------------------inline_native_subtype_check------------------------
 4673 // This intrinsic takes the JNI calls out of the heart of
 4674 // UnsafeFieldAccessorImpl.set, which improves Field.set, readObject, etc.
 4675 bool LibraryCallKit::inline_native_subtype_check() {
 4676   // Pull both arguments off the stack.
 4677   Node* args[2];                // two java.lang.Class mirrors: superc, subc
 4678   args[0] = argument(0);
 4679   args[1] = argument(1);
 4680   Node* klasses[2];             // corresponding Klasses: superk, subk
 4681   klasses[0] = klasses[1] = top();
 4682 
 4683   enum {
 4684     // A full decision tree on {superc is prim, subc is prim}:
 4685     _prim_0_path = 1,           // {P,N} => false
 4686                                 // {P,P} & superc!=subc => false
 4687     _prim_same_path,            // {P,P} & superc==subc => true
 4688     _prim_1_path,               // {N,P} => false
 4689     _ref_subtype_path,          // {N,N} & subtype check wins => true
 4690     _both_ref_path,             // {N,N} & subtype check loses => false
 4691     PATH_LIMIT
 4692   };
 4693 
 4694   RegionNode* region = new RegionNode(PATH_LIMIT);
 4695   RegionNode* prim_region = new RegionNode(2);
 4696   Node*       phi    = new PhiNode(region, TypeInt::BOOL);
 4697   record_for_igvn(region);
 4698   record_for_igvn(prim_region);
 4699 
 4700   const TypePtr* adr_type = TypeRawPtr::BOTTOM;   // memory type of loads
 4701   const TypeKlassPtr* kls_type = TypeInstKlassPtr::OBJECT_OR_NULL;
 4702   int class_klass_offset = java_lang_Class::klass_offset();
 4703 
 4704   // First null-check both mirrors and load each mirror's klass metaobject.
 4705   int which_arg;
 4706   for (which_arg = 0; which_arg <= 1; which_arg++) {
 4707     Node* arg = args[which_arg];
 4708     arg = null_check(arg);
 4709     if (stopped())  break;
 4710     args[which_arg] = arg;
 4711 
 4712     Node* p = basic_plus_adr(arg, class_klass_offset);
 4713     Node* kls = LoadKlassNode::make(_gvn, immutable_memory(), p, adr_type, kls_type);
 4714     klasses[which_arg] = _gvn.transform(kls);
 4715   }
 4716 
 4717   // Having loaded both klasses, test each for null.
 4718   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
 4719   for (which_arg = 0; which_arg <= 1; which_arg++) {
 4720     Node* kls = klasses[which_arg];
 4721     Node* null_ctl = top();
 4722     kls = null_check_oop(kls, &null_ctl, never_see_null);
 4723     if (which_arg == 0) {
 4724       prim_region->init_req(1, null_ctl);
 4725     } else {
 4726       region->init_req(_prim_1_path, null_ctl);
 4727     }
 4728     if (stopped())  break;
 4729     klasses[which_arg] = kls;
 4730   }
 4731 
 4732   if (!stopped()) {
 4733     // now we have two reference types, in klasses[0..1]
 4734     Node* subk   = klasses[1];  // the argument to isAssignableFrom
 4735     Node* superk = klasses[0];  // the receiver
 4736     region->set_req(_both_ref_path, gen_subtype_check(subk, superk));
 4737     region->set_req(_ref_subtype_path, control());
 4738   }
 4739 
 4740   // If both operands are primitive (both klasses null), then
 4741   // we must return true when they are identical primitives.
 4742   // It is convenient to test this after the first null klass check.
 4743   // This path is also used if superc is a value mirror.
 4744   set_control(_gvn.transform(prim_region));
 4745   if (!stopped()) {
 4746     // Since superc is primitive, make a guard for the superc==subc case.
 4747     Node* cmp_eq = _gvn.transform(new CmpPNode(args[0], args[1]));
 4748     Node* bol_eq = _gvn.transform(new BoolNode(cmp_eq, BoolTest::eq));
 4749     generate_fair_guard(bol_eq, region);
 4750     if (region->req() == PATH_LIMIT+1) {
 4751       // A guard was added.  If the added guard is taken, superc==subc.
 4752       region->swap_edges(PATH_LIMIT, _prim_same_path);
 4753       region->del_req(PATH_LIMIT);
 4754     }
 4755     region->set_req(_prim_0_path, control()); // Not equal after all.
 4756   }
 4757 
 4758   // these are the only paths that produce 'true':
 4759   phi->set_req(_prim_same_path,   intcon(1));
 4760   phi->set_req(_ref_subtype_path, intcon(1));
 4761 
 4762   // pull together the cases:
 4763   assert(region->req() == PATH_LIMIT, "sane region");
 4764   for (uint i = 1; i < region->req(); i++) {
 4765     Node* ctl = region->in(i);
 4766     if (ctl == nullptr || ctl == top()) {
 4767       region->set_req(i, top());
 4768       phi   ->set_req(i, top());
 4769     } else if (phi->in(i) == nullptr) {
 4770       phi->set_req(i, intcon(0)); // all other paths produce 'false'
 4771     }
 4772   }
 4773 
 4774   set_control(_gvn.transform(region));
 4775   set_result(_gvn.transform(phi));
 4776   return true;
 4777 }
 4778 
 4779 //---------------------generate_array_guard_common------------------------
 4780 Node* LibraryCallKit::generate_array_guard_common(Node* kls, RegionNode* region, ArrayKind kind, Node** obj) {
 4781 
 4782   if (stopped()) {
 4783     return nullptr;
 4784   }
 4785 
 4786   // Like generate_guard, adds a new path onto the region.
 4787   jint  layout_con = 0;
 4788   Node* layout_val = get_layout_helper(kls, layout_con);
 4789   if (layout_val == nullptr) {
 4790     bool query = 0;
 4791     switch(kind) {
 4792       case RefArray:       query = Klass::layout_helper_is_refArray(layout_con); break;
 4793       case NonRefArray:    query = !Klass::layout_helper_is_refArray(layout_con); break;
 4794       case TypeArray:      query = Klass::layout_helper_is_typeArray(layout_con); break;
 4795       case AnyArray:       query = Klass::layout_helper_is_array(layout_con); break;
 4796       case NonArray:       query = !Klass::layout_helper_is_array(layout_con); break;
 4797       default:
 4798         ShouldNotReachHere();
 4799     }
 4800     if (!query) {
 4801       return nullptr;                       // never a branch
 4802     } else {                             // always a branch
 4803       Node* always_branch = control();
 4804       if (region != nullptr)
 4805         region->add_req(always_branch);
 4806       set_control(top());
 4807       return always_branch;
 4808     }
 4809   }
 4810   unsigned int value = 0;
 4811   BoolTest::mask btest = BoolTest::illegal;
 4812   switch(kind) {
 4813     case RefArray:
 4814     case NonRefArray: {
 4815       value = Klass::_lh_array_tag_ref_value;
 4816       layout_val = _gvn.transform(new RShiftINode(layout_val, intcon(Klass::_lh_array_tag_shift)));
 4817       btest = (kind == RefArray) ? BoolTest::eq : BoolTest::ne;
 4818       break;
 4819     }
 4820     case TypeArray: {
 4821       value = Klass::_lh_array_tag_type_value;
 4822       layout_val = _gvn.transform(new RShiftINode(layout_val, intcon(Klass::_lh_array_tag_shift)));
 4823       btest = BoolTest::eq;
 4824       break;
 4825     }
 4826     case AnyArray:    value = Klass::_lh_neutral_value; btest = BoolTest::lt; break;
 4827     case NonArray:    value = Klass::_lh_neutral_value; btest = BoolTest::gt; break;
 4828     default:
 4829       ShouldNotReachHere();
 4830   }
 4831   // Now test the correct condition.
 4832   jint nval = (jint)value;
 4833   Node* cmp = _gvn.transform(new CmpINode(layout_val, intcon(nval)));
 4834   Node* bol = _gvn.transform(new BoolNode(cmp, btest));
 4835   Node* ctrl = generate_fair_guard(bol, region);
 4836   Node* is_array_ctrl = kind == NonArray ? control() : ctrl;
 4837   if (obj != nullptr && is_array_ctrl != nullptr && is_array_ctrl != top()) {
 4838     // Keep track of the fact that 'obj' is an array to prevent
 4839     // array specific accesses from floating above the guard.
 4840     *obj = _gvn.transform(new CheckCastPPNode(is_array_ctrl, *obj, TypeAryPtr::BOTTOM));
 4841   }
 4842   return ctrl;
 4843 }
 4844 
 4845 // public static native Object[] ValueClass::newNullRestrictedAtomicArray(Class<?> componentType, int length, Object initVal);
 4846 // public static native Object[] ValueClass::newNullRestrictedNonAtomicArray(Class<?> componentType, int length, Object initVal);
 4847 // public static native Object[] ValueClass::newNullableAtomicArray(Class<?> componentType, int length);
 4848 bool LibraryCallKit::inline_newArray(bool null_free, bool atomic) {
 4849   assert(null_free || atomic, "nullable implies atomic");
 4850   Node* componentType = argument(0);
 4851   Node* length = argument(1);
 4852   Node* init_val = null_free ? argument(2) : nullptr;
 4853 
 4854   const TypeInstPtr* tp = _gvn.type(componentType)->isa_instptr();
 4855   if (tp != nullptr) {
 4856     ciInstanceKlass* ik = tp->instance_klass();
 4857     if (ik == C->env()->Class_klass()) {
 4858       ciType* t = tp->java_mirror_type();
 4859       if (t != nullptr && t->is_inlinetype()) {
 4860 
 4861         ciArrayKlass* array_klass = ciArrayKlass::make(t, null_free, atomic, true);
 4862         assert(array_klass->is_elem_null_free() == null_free, "inconsistency");
 4863 
 4864         // TODO 8350865 ZGC needs card marks on initializing oop stores
 4865         if ((UseZGC || UseShenandoahGC) && null_free && !array_klass->is_flat_array_klass()) {
 4866           return false;
 4867         }
 4868 
 4869         if (array_klass->is_loaded() && array_klass->element_klass()->as_inline_klass()->is_initialized()) {
 4870           const TypeAryKlassPtr* array_klass_type = TypeAryKlassPtr::make(array_klass, Type::trust_interfaces);
 4871           if (null_free) {
 4872             if (init_val->is_InlineType()) {
 4873               if (array_klass_type->is_flat() && init_val->as_InlineType()->is_all_zero(&gvn(), /* flat */ true)) {
 4874                 // Zeroing is enough because the init value is the all-zero value
 4875                 init_val = nullptr;
 4876               } else {
 4877                 init_val = init_val->as_InlineType()->buffer(this);
 4878               }
 4879             }
 4880             if (init_val != nullptr) {
 4881 #ifdef ASSERT
 4882               init_val = null_check(init_val);
 4883               Node* wrong_type_ctl = gen_subtype_check(init_val, makecon(TypeKlassPtr::make(array_klass->element_klass())));
 4884               {
 4885                 PreserveJVMState pjvms(this);
 4886                 set_control(wrong_type_ctl);
 4887                 halt(control(), frameptr(), "incompatible type for initVal in newArray");
 4888                 stop_and_kill_map();
 4889               }
 4890 #endif
 4891               init_val = _gvn.transform(new CheckCastPPNode(control(), init_val, TypeOopPtr::make_from_klass(array_klass->element_klass()), ConstraintCastNode::DependencyType::NonFloatingNarrowing));
 4892             }
 4893           }
 4894           Node* obj = new_array(makecon(array_klass_type), length, 0, nullptr, false, init_val);
 4895           const TypeAryPtr* arytype = gvn().type(obj)->is_aryptr();
 4896           assert(arytype->is_null_free() == null_free, "inconsistency");
 4897           assert(arytype->is_not_null_free() == !null_free, "inconsistency");
 4898           set_result(obj);
 4899           return true;
 4900         }
 4901       }
 4902     }
 4903   }
 4904   return false;
 4905 }
 4906 
 4907 // public static native boolean ValueClass::isFlatArray(Object array);
 4908 // public static native boolean ValueClass::isNullRestrictedArray(Object array);
 4909 // public static native boolean ValueClass::isAtomicArray(Object array);
 4910 bool LibraryCallKit::inline_getArrayProperties(ArrayPropertiesCheck check) {
 4911   Node* array = argument(0);
 4912 
 4913   Node* bol;
 4914   switch(check) {
 4915     case IsFlat:
 4916       bol = flat_array_test(load_object_klass(array));
 4917       break;
 4918     case IsNullRestricted:
 4919       bol = null_free_array_test(array);
 4920       break;
 4921     case IsAtomic: {
 4922       // See conditions in JVM_IsAtomicArray
 4923       // 1. If not flat, then atomic, or else...
 4924       RegionNode* atomic_region = new RegionNode(1);
 4925       RegionNode* non_atomic_region = new RegionNode(1);
 4926       Node* array_klass = load_object_klass(array);
 4927       Node* is_flat_bol = flat_array_test(array_klass);
 4928       IfNode* iff_is_flat = create_and_xform_if(control(), is_flat_bol, PROB_FAIR, COUNT_UNKNOWN);
 4929       atomic_region->add_req(_gvn.transform(new IfFalseNode(iff_is_flat)));
 4930       set_control(_gvn.transform(new IfTrueNode(iff_is_flat)));
 4931 
 4932       // 2. ...if the layout is atomic, then atomic, or else...
 4933       Node* layout_kind = atomic_layout_array_test_and_get_layout_kind(array, atomic_region);
 4934 
 4935       // 3. ...if the element type is naturally atomic and null-free OR empty and nullable, then atomic, or else...
 4936       int element_klass_offset = in_bytes(ObjArrayKlass::element_klass_offset());
 4937       Node* array_element_klass_addr = off_heap_plus_addr(array_klass, element_klass_offset);
 4938       Node* array_element_klass = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), array_element_klass_addr, _gvn.type(array_klass)->is_klassptr()));
 4939       int klass_flags_offset = in_bytes(InstanceKlass::misc_flags_offset() + InstanceKlassFlags::flags_offset());
 4940       Node* array_element_klass_flags_addr = off_heap_plus_addr(array_element_klass, klass_flags_offset);
 4941       Node* array_element_klass_flags = make_load(control(), array_element_klass_flags_addr, TypeInt::INT, T_INT, MemNode::unordered);
 4942 
 4943       // Here, layout can only be non-atomic, otherwise atomic_layout_array_test_and_get_layout_kind already decides the array to be atomic.
 4944       Node* is_null_free_cmp = _gvn.transform(new CmpINode(layout_kind, intcon(static_cast<jint>(LayoutKind::NULL_FREE_NON_ATOMIC_FLAT))));
 4945       Node* is_null_free_bol = _gvn.transform(new BoolNode(is_null_free_cmp, BoolTest::eq));
 4946       IfNode* iff_is_null_free_bol = create_and_xform_if(control(), is_null_free_bol, PROB_FAIR, COUNT_UNKNOWN);
 4947       Node* is_null_free_ctl = _gvn.transform(new IfTrueNode(iff_is_null_free_bol));
 4948       Node* is_nullable_ctl = _gvn.transform(new IfFalseNode(iff_is_null_free_bol));
 4949 
 4950       Node* is_naturally_atomic_flag = _gvn.transform(new AndINode(array_element_klass_flags, intcon(InstanceKlassFlags::_misc_is_naturally_atomic)));
 4951       Node* is_naturally_atomic_cmp = _gvn.transform(new CmpINode(is_naturally_atomic_flag, intcon(0)));
 4952       Node* is_naturally_atomic_bol = _gvn.transform(new BoolNode(is_naturally_atomic_cmp, BoolTest::ne));
 4953       IfNode* iff_is_naturally_atomic = create_and_xform_if(is_null_free_ctl, is_naturally_atomic_bol, PROB_FAIR, COUNT_UNKNOWN);
 4954       Node* is_naturally_atomic_ctl = _gvn.transform(new IfTrueNode(iff_is_naturally_atomic));
 4955       Node* is_not_naturally_atomic_ctl = _gvn.transform(new IfFalseNode(iff_is_naturally_atomic));
 4956       atomic_region->add_req(is_naturally_atomic_ctl);
 4957       non_atomic_region->add_req(is_not_naturally_atomic_ctl);
 4958 
 4959       Node* is_empty_inline_type_flag = _gvn.transform(new AndINode(array_element_klass_flags, intcon(InstanceKlassFlags::_misc_is_empty_inline_type)));
 4960       Node* is_empty_inline_type_cmp = _gvn.transform(new CmpINode(is_empty_inline_type_flag, intcon(0)));
 4961       Node* is_empty_inline_type_bol = _gvn.transform(new BoolNode(is_empty_inline_type_cmp, BoolTest::ne));
 4962       IfNode* iff_is_empty_inline_type = create_and_xform_if(is_nullable_ctl, is_empty_inline_type_bol, PROB_FAIR, COUNT_UNKNOWN);
 4963       Node* is_empty_inline_type_ctl = _gvn.transform(new IfTrueNode(iff_is_empty_inline_type));
 4964       Node* is_nonempty_inline_type_ctl = _gvn.transform(new IfFalseNode(iff_is_empty_inline_type));
 4965       atomic_region->add_req(is_empty_inline_type_ctl);
 4966       non_atomic_region->add_req(is_nonempty_inline_type_ctl);
 4967 
 4968       // ...non-atomic, but we tried everything.
 4969       RegionNode* decision = new RegionNode(3);
 4970       decision->set_req(1, _gvn.transform(atomic_region));
 4971       decision->set_req(2, _gvn.transform(non_atomic_region));
 4972       PhiNode* result = PhiNode::make(decision, intcon(1), TypeInt::BOOL);
 4973       result->set_req(2, intcon(0));
 4974       set_control(_gvn.transform(decision));
 4975       set_result(_gvn.transform(result));
 4976       return true;
 4977     }
 4978     default:
 4979       ShouldNotReachHere();
 4980   }
 4981 
 4982   Node* res = gvn().transform(new CMoveINode(bol, intcon(0), intcon(1), TypeInt::BOOL));
 4983   set_result(res);
 4984   return true;
 4985 }
 4986 
 4987 // Load the default refined array klass from an ObjArrayKlass. This relies on the first entry in the
 4988 // '_next_refined_array_klass' linked list being the default (see ObjArrayKlass::klass_with_properties).
 4989 Node* LibraryCallKit::load_default_refined_array_klass(Node* klass_node, bool type_array_guard) {
 4990   RegionNode* region = new RegionNode(2);
 4991   Node* phi = new PhiNode(region, TypeInstKlassPtr::OBJECT_OR_NULL);
 4992 
 4993   if (type_array_guard) {
 4994     generate_typeArray_guard(klass_node, region);
 4995     if (region->req() == 3) {
 4996       phi->add_req(klass_node);
 4997     }
 4998   }
 4999   Node* adr_refined_klass = basic_plus_adr(top(), klass_node, in_bytes(ObjArrayKlass::next_refined_array_klass_offset()));
 5000   Node* refined_klass = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), adr_refined_klass, TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
 5001 
 5002   // Can be null if not initialized yet, just deopt
 5003   Node* null_ctl = top();
 5004   refined_klass = null_check_oop(refined_klass, &null_ctl, /* never_see_null= */ true);
 5005 
 5006   region->init_req(1, control());
 5007   phi->init_req(1, refined_klass);
 5008 
 5009   set_control(_gvn.transform(region));
 5010   return _gvn.transform(phi);
 5011 }
 5012 
 5013 // Load the non-refined array klass from an ObjArrayKlass.
 5014 Node* LibraryCallKit::load_non_refined_array_klass(Node* klass_node) {
 5015   const TypeAryKlassPtr* ary_klass_ptr = _gvn.type(klass_node)->isa_aryklassptr();
 5016   if (ary_klass_ptr != nullptr && ary_klass_ptr->klass_is_exact()) {
 5017     return _gvn.makecon(ary_klass_ptr->cast_to_refined_array_klass_ptr(false));
 5018   }
 5019 
 5020   RegionNode* region = new RegionNode(2);
 5021   Node* phi = new PhiNode(region, TypeInstKlassPtr::OBJECT);
 5022 
 5023   generate_typeArray_guard(klass_node, region);
 5024   if (region->req() == 3) {
 5025     phi->add_req(klass_node);
 5026   }
 5027   Node* super_adr = basic_plus_adr(top(), klass_node, in_bytes(Klass::super_offset()));
 5028   Node* super_klass = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), super_adr, TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT));
 5029 
 5030   region->init_req(1, control());
 5031   phi->init_req(1, super_klass);
 5032 
 5033   set_control(_gvn.transform(region));
 5034   return _gvn.transform(phi);
 5035 }
 5036 
 5037 //-----------------------inline_native_newArray--------------------------
 5038 // private static native Object java.lang.reflect.Array.newArray(Class<?> componentType, int length);
 5039 // private        native Object Unsafe.allocateUninitializedArray0(Class<?> cls, int size);
 5040 bool LibraryCallKit::inline_unsafe_newArray(bool uninitialized) {
 5041   Node* mirror;
 5042   Node* count_val;
 5043   if (uninitialized) {
 5044     null_check_receiver();
 5045     mirror    = argument(1);
 5046     count_val = argument(2);
 5047   } else {
 5048     mirror    = argument(0);
 5049     count_val = argument(1);
 5050   }
 5051 
 5052   mirror = null_check(mirror);
 5053   // If mirror or obj is dead, only null-path is taken.
 5054   if (stopped())  return true;
 5055 
 5056   enum { _normal_path = 1, _slow_path = 2, PATH_LIMIT };
 5057   RegionNode* result_reg = new RegionNode(PATH_LIMIT);
 5058   PhiNode*    result_val = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
 5059   PhiNode*    result_io  = new PhiNode(result_reg, Type::ABIO);
 5060   PhiNode*    result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
 5061 
 5062   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
 5063   Node* klass_node = load_array_klass_from_mirror(mirror, never_see_null,
 5064                                                   result_reg, _slow_path);
 5065   Node* normal_ctl   = control();
 5066   Node* no_array_ctl = result_reg->in(_slow_path);
 5067 
 5068   // Generate code for the slow case.  We make a call to newArray().
 5069   set_control(no_array_ctl);
 5070   if (!stopped()) {
 5071     // Either the input type is void.class, or else the
 5072     // array klass has not yet been cached.  Either the
 5073     // ensuing call will throw an exception, or else it
 5074     // will cache the array klass for next time.
 5075     PreserveJVMState pjvms(this);
 5076     CallJavaNode* slow_call = nullptr;
 5077     if (uninitialized) {
 5078       // Generate optimized virtual call (holder class 'Unsafe' is final)
 5079       slow_call = generate_method_call(vmIntrinsics::_allocateUninitializedArray, false, false, true);
 5080     } else {
 5081       slow_call = generate_method_call_static(vmIntrinsics::_newArray, true);
 5082     }
 5083     Node* slow_result = set_results_for_java_call(slow_call);
 5084     // this->control() comes from set_results_for_java_call
 5085     result_reg->set_req(_slow_path, control());
 5086     result_val->set_req(_slow_path, slow_result);
 5087     result_io ->set_req(_slow_path, i_o());
 5088     result_mem->set_req(_slow_path, reset_memory());
 5089   }
 5090 
 5091   set_control(normal_ctl);
 5092   if (!stopped()) {
 5093     // Normal case:  The array type has been cached in the java.lang.Class.
 5094     // The following call works fine even if the array type is polymorphic.
 5095     // It could be a dynamic mix of int[], boolean[], Object[], etc.
 5096 
 5097     klass_node = load_default_refined_array_klass(klass_node);
 5098 
 5099     Node* obj = new_array(klass_node, count_val, 0);  // no arguments to push
 5100     result_reg->init_req(_normal_path, control());
 5101     result_val->init_req(_normal_path, obj);
 5102     result_io ->init_req(_normal_path, i_o());
 5103     result_mem->init_req(_normal_path, reset_memory());
 5104 
 5105     if (uninitialized) {
 5106       // Mark the allocation so that zeroing is skipped
 5107       AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(obj);
 5108       alloc->maybe_set_complete(&_gvn);
 5109     }
 5110   }
 5111 
 5112   // Return the combined state.
 5113   set_i_o(        _gvn.transform(result_io)  );
 5114   set_all_memory( _gvn.transform(result_mem));
 5115 
 5116   C->set_has_split_ifs(true); // Has chance for split-if optimization
 5117   set_result(result_reg, result_val);
 5118   return true;
 5119 }
 5120 
 5121 //----------------------inline_native_getLength--------------------------
 5122 // public static native int java.lang.reflect.Array.getLength(Object array);
 5123 bool LibraryCallKit::inline_native_getLength() {
 5124   if (too_many_traps(Deoptimization::Reason_intrinsic))  return false;
 5125 
 5126   Node* array = null_check(argument(0));
 5127   // If array is dead, only null-path is taken.
 5128   if (stopped())  return true;
 5129 
 5130   // Deoptimize if it is a non-array.
 5131   Node* non_array = generate_non_array_guard(load_object_klass(array), nullptr, &array);
 5132 
 5133   if (non_array != nullptr) {
 5134     PreserveJVMState pjvms(this);
 5135     set_control(non_array);
 5136     uncommon_trap(Deoptimization::Reason_intrinsic,
 5137                   Deoptimization::Action_maybe_recompile);
 5138   }
 5139 
 5140   // If control is dead, only non-array-path is taken.
 5141   if (stopped())  return true;
 5142 
 5143   // The works fine even if the array type is polymorphic.
 5144   // It could be a dynamic mix of int[], boolean[], Object[], etc.
 5145   Node* result = load_array_length(array);
 5146 
 5147   C->set_has_split_ifs(true);  // Has chance for split-if optimization
 5148   set_result(result);
 5149   return true;
 5150 }
 5151 
 5152 //------------------------inline_array_copyOf----------------------------
 5153 // public static <T,U> T[] java.util.Arrays.copyOf(     U[] original, int newLength,         Class<? extends T[]> newType);
 5154 // public static <T,U> T[] java.util.Arrays.copyOfRange(U[] original, int from,      int to, Class<? extends T[]> newType);
 5155 bool LibraryCallKit::inline_array_copyOf(bool is_copyOfRange) {
 5156   if (too_many_traps(Deoptimization::Reason_intrinsic))  return false;
 5157 
 5158   // Get the arguments.
 5159   Node* original          = argument(0);
 5160   Node* start             = is_copyOfRange? argument(1): intcon(0);
 5161   Node* end               = is_copyOfRange? argument(2): argument(1);
 5162   Node* array_type_mirror = is_copyOfRange? argument(3): argument(2);
 5163 
 5164   Node* newcopy = nullptr;
 5165 
 5166   // Set the original stack and the reexecute bit for the interpreter to reexecute
 5167   // the bytecode that invokes Arrays.copyOf if deoptimization happens.
 5168   { PreserveReexecuteState preexecs(this);
 5169     jvms()->set_should_reexecute(true);
 5170 
 5171     array_type_mirror = null_check(array_type_mirror);
 5172     original          = null_check(original);
 5173 
 5174     // Check if a null path was taken unconditionally.
 5175     if (stopped())  return true;
 5176 
 5177     Node* orig_length = load_array_length(original);
 5178 
 5179     RegionNode* bailout = new RegionNode(2);
 5180     record_for_igvn(bailout);
 5181 
 5182     Node* klass_node = load_klass_from_mirror(array_type_mirror, false, bailout, 1);
 5183     if (stopped()) {
 5184       // Arrays.copyOf() uses a generic Class parameter which is erased to the raw type Class. This also allows
 5185       // passing in primitive class mirrors like int.class which do not have corresponding Klass* pointers.
 5186       // In these cases, klass_node will be top. Emit a trap to throw in the interpreter in this case.
 5187       bail_out_from_array_copyOf(bailout);
 5188       return true;
 5189     }
 5190 
 5191     klass_node = null_check(klass_node);
 5192 
 5193     const TypeAryPtr* src_t = _gvn.type(original)->is_aryptr();
 5194     const TypeKlassPtr* dest_klass_t = _gvn.type(klass_node)->is_klassptr()->is_klassptr();
 5195 
 5196     Node* success_proj;
 5197     if (should_bail_out_on_non_ref_arrays(src_t, dest_klass_t)) {
 5198       success_proj = generate_non_refArray_guard(klass_node, bailout);
 5199     } else {
 5200       success_proj = generate_typeArray_guard(klass_node, bailout);
 5201     }
 5202 
 5203     Node* refined_klass_node = load_default_refined_array_klass(klass_node, /* type_array_guard= */ false);
 5204 
 5205     if (success_proj != nullptr) {
 5206       // Improve the klass node's type from the new optimistic assumption:
 5207       ciKlass* ak = ciArrayKlass::make(env()->Object_klass());
 5208       bool not_flat = !UseArrayFlattening;
 5209       bool not_null_free = !Arguments::is_valhalla_enabled();
 5210       const Type* akls = TypeAryKlassPtr::make(TypePtr::NotNull, ak, Type::Offset(0), Type::trust_interfaces, not_flat, not_null_free, false, false, not_flat, true);
 5211       Node* cast = new CastPPNode(control(), refined_klass_node, akls);
 5212       refined_klass_node = _gvn.transform(cast);
 5213     }
 5214 
 5215     // Bail out if either start or end is negative.
 5216     generate_negative_guard(start, bailout, &start);
 5217     generate_negative_guard(end,   bailout, &end);
 5218 
 5219     Node* length = end;
 5220     if (_gvn.type(start) != TypeInt::ZERO) {
 5221       length = _gvn.transform(new SubINode(end, start));
 5222     }
 5223 
 5224     // Bail out if length is negative (i.e., if start > end).
 5225     // Without this the new_array would throw
 5226     // NegativeArraySizeException but IllegalArgumentException is what
 5227     // should be thrown
 5228     generate_negative_guard(length, bailout, &length);
 5229 
 5230     // Handle inline type arrays
 5231     // TODO 8251971 This is too strong
 5232     generate_fair_guard(flat_array_test(load_object_klass(original)), bailout);
 5233     generate_fair_guard(flat_array_test(refined_klass_node), bailout);
 5234     generate_fair_guard(null_free_array_test(original), bailout);
 5235 
 5236     // Bail out if start is larger than the original length
 5237     Node* orig_tail = _gvn.transform(new SubINode(orig_length, start));
 5238     generate_negative_guard(orig_tail, bailout, &orig_tail);
 5239 
 5240     if (bailout->req() > 1) {
 5241       bail_out_from_array_copyOf(bailout);
 5242     }
 5243 
 5244     if (!stopped()) {
 5245       // How many elements will we copy from the original?
 5246       // The answer is MinI(orig_tail, length).
 5247       Node* moved = _gvn.transform(new MinINode(orig_tail, length));
 5248 
 5249       // Generate a direct call to the right arraycopy function(s).
 5250       // We know the copy is disjoint but we might not know if the
 5251       // oop stores need checking.
 5252       // Extreme case:  Arrays.copyOf((Integer[])x, 10, String[].class).
 5253       // This will fail a store-check if x contains any non-nulls.
 5254 
 5255       // ArrayCopyNode:Ideal may transform the ArrayCopyNode to
 5256       // loads/stores but it is legal only if we're sure the
 5257       // Arrays.copyOf would succeed. So we need all input arguments
 5258       // to the copyOf to be validated, including that the copy to the
 5259       // new array won't trigger an ArrayStoreException. That subtype
 5260       // check can be optimized if we know something on the type of
 5261       // the input array from type speculation.
 5262       if (_gvn.type(klass_node)->singleton()) {
 5263         const TypeKlassPtr* subk = _gvn.type(load_object_klass(original))->is_klassptr();
 5264         const TypeKlassPtr* superk = _gvn.type(klass_node)->is_klassptr();
 5265 
 5266         int test = C->static_subtype_check(superk, subk);
 5267         if (test != Compile::SSC_always_true && test != Compile::SSC_always_false) {
 5268           const TypeOopPtr* t_original = _gvn.type(original)->is_oopptr();
 5269           if (t_original->speculative_type() != nullptr) {
 5270             original = maybe_cast_profiled_obj(original, t_original->speculative_type(), true);
 5271           }
 5272         }
 5273       }
 5274 
 5275       bool validated = false;
 5276       // Reason_class_check rather than Reason_intrinsic because we
 5277       // want to intrinsify even if this traps.
 5278       if (!too_many_traps(Deoptimization::Reason_class_check)) {
 5279         Node* not_subtype_ctrl = gen_subtype_check(original, klass_node);
 5280 
 5281         if (not_subtype_ctrl != top()) {
 5282           PreserveJVMState pjvms(this);
 5283           set_control(not_subtype_ctrl);
 5284           uncommon_trap(Deoptimization::Reason_class_check,
 5285                         Deoptimization::Action_make_not_entrant);
 5286           assert(stopped(), "Should be stopped");
 5287         }
 5288         validated = true;
 5289       }
 5290 
 5291       if (!stopped()) {
 5292         newcopy = new_array(refined_klass_node, length, 0);  // no arguments to push
 5293 
 5294         ArrayCopyNode* ac = ArrayCopyNode::make(this, true, original, start, newcopy, intcon(0), moved, true, true,
 5295                                                 load_object_klass(original), klass_node);
 5296         if (!is_copyOfRange) {
 5297           ac->set_copyof(validated);
 5298         } else {
 5299           ac->set_copyofrange(validated);
 5300         }
 5301         Node* n = _gvn.transform(ac);
 5302         if (n == ac) {
 5303           ac->connect_outputs(this);
 5304         } else {
 5305           assert(validated, "shouldn't transform if all arguments not validated");
 5306           set_all_memory(n);
 5307         }
 5308       }
 5309     }
 5310   } // original reexecute is set back here
 5311 
 5312   C->set_has_split_ifs(true); // Has chance for split-if optimization
 5313   if (!stopped()) {
 5314     set_result(newcopy);
 5315   }
 5316   return true;
 5317 }
 5318 
 5319 void LibraryCallKit::bail_out_from_array_copyOf(RegionNode* bailout_region) {
 5320   PreserveJVMState pjvms(this);
 5321   set_control(_gvn.transform(bailout_region));
 5322   uncommon_trap(Deoptimization::Reason_intrinsic,
 5323                 Deoptimization::Action_maybe_recompile);
 5324 }
 5325 
 5326 bool LibraryCallKit::should_bail_out_on_non_ref_arrays(const TypeAryPtr* src_type, const TypeKlassPtr* dest_klass_type) {
 5327   const TypeAryKlassPtr* dest_ary_klass_type = dest_klass_type->isa_aryklassptr();
 5328   if (dest_ary_klass_type == nullptr) {
 5329     // Dest klass is not known to be an array class. There are multiple cases:
 5330     // - Primitive class mirror: We already bailed out before.
 5331     // - Instance class mirror: We should bail out.
 5332     // - java.lang.Object (possible due to type erasure): Could be anything including primitive or instance class mirror
 5333     //   or also flat arrays. Bail out.
 5334     return true;
 5335   }
 5336 
 5337   if (UseArrayFlattening) {
 5338     // The remaining checks revolve around array flatness. Without array flatness, we don't need the stronger non-ref
 5339     // runtime check excluding flat arrays.
 5340     return false;
 5341   }
 5342 
 5343   // We now know that src and dest are proper array pointers.
 5344   const bool src_maybe_flat = !src_type->is_not_flat();
 5345   const bool dest_maybe_flat = !dest_ary_klass_type->is_not_flat();
 5346 
 5347   // We could have abstract flat value class arrays whose layout we don't know. Bail out.
 5348   const bool can_src_be_abstract_flat_value_class_array = src_maybe_flat && !src_type->elem()->is_inlinetypeptr();
 5349   const bool can_dest_be_abstract_flat_value_class_array = dest_maybe_flat &&
 5350                                                            !dest_ary_klass_type->elem()->is_instklassptr()->instance_klass()->is_inlinetype();
 5351   if (can_src_be_abstract_flat_value_class_array || can_dest_be_abstract_flat_value_class_array) {
 5352     return true;
 5353   }
 5354 
 5355   // Value class array may have object field that would require a write barrier. Conservatively bail out.
 5356   // TODO 8251971: Optimize for the case when flat src/dst are later found to not contain
 5357   //               oops (i.e., move this check to the macro expansion phase).
 5358   BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
 5359   if (bs->array_copy_requires_gc_barriers(true, T_OBJECT, false, false, BarrierSetC2::Parsing)) {
 5360     // No barriers required.
 5361     return false;
 5362   }
 5363 
 5364   const bool can_src_be_flat_with_oops = src_maybe_flat && src_type->elem()->inline_klass()->contains_oops();
 5365   const bool can_dest_be_flat_with_oops = dest_maybe_flat && dest_ary_klass_type->elem()->is_instklassptr()->instance_klass()->as_inline_klass()->contains_oops();
 5366   if (can_src_be_flat_with_oops || can_dest_be_flat_with_oops) {
 5367     return true;
 5368   }
 5369 
 5370   // Can handle remaining flat arrays.
 5371   return false;
 5372 }
 5373 
 5374 //----------------------generate_virtual_guard---------------------------
 5375 // Helper for hashCode and clone.  Peeks inside the vtable to avoid a call.
 5376 Node* LibraryCallKit::generate_virtual_guard(Node* obj_klass,
 5377                                              RegionNode* slow_region) {
 5378   ciMethod* method = callee();
 5379   int vtable_index = method->vtable_index();
 5380   assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index,
 5381          "bad index %d", vtable_index);
 5382   // Get the Method* out of the appropriate vtable entry.
 5383   int entry_offset = in_bytes(Klass::vtable_start_offset()) +
 5384                      vtable_index*vtableEntry::size_in_bytes() +
 5385                      in_bytes(vtableEntry::method_offset());
 5386   Node* entry_addr = off_heap_plus_addr(obj_klass, entry_offset);
 5387   Node* target_call = make_load(nullptr, entry_addr, TypePtr::NOTNULL, T_ADDRESS, MemNode::unordered);
 5388 
 5389   // Compare the target method with the expected method (e.g., Object.hashCode).
 5390   const TypePtr* native_call_addr = TypeMetadataPtr::make(method);
 5391 
 5392   Node* native_call = makecon(native_call_addr);
 5393   Node* chk_native  = _gvn.transform(new CmpPNode(target_call, native_call));
 5394   Node* test_native = _gvn.transform(new BoolNode(chk_native, BoolTest::ne));
 5395 
 5396   return generate_slow_guard(test_native, slow_region);
 5397 }
 5398 
 5399 //-----------------------generate_method_call----------------------------
 5400 // Use generate_method_call to make a slow-call to the real
 5401 // method if the fast path fails.  An alternative would be to
 5402 // use a stub like OptoRuntime::slow_arraycopy_Java.
 5403 // This only works for expanding the current library call,
 5404 // not another intrinsic.  (E.g., don't use this for making an
 5405 // arraycopy call inside of the copyOf intrinsic.)
 5406 CallJavaNode*
 5407 LibraryCallKit::generate_method_call(vmIntrinsicID method_id, bool is_virtual, bool is_static, bool res_not_null) {
 5408   // When compiling the intrinsic method itself, do not use this technique.
 5409   guarantee(callee() != C->method(), "cannot make slow-call to self");
 5410 
 5411   ciMethod* method = callee();
 5412   // ensure the JVMS we have will be correct for this call
 5413   guarantee(method_id == method->intrinsic_id(), "must match");
 5414 
 5415   const TypeFunc* tf = TypeFunc::make(method);
 5416   if (res_not_null) {
 5417     assert(tf->return_type() == T_OBJECT, "");
 5418     const TypeTuple* range = tf->range_cc();
 5419     const Type** fields = TypeTuple::fields(range->cnt());
 5420     fields[TypeFunc::Parms] = range->field_at(TypeFunc::Parms)->filter_speculative(TypePtr::NOTNULL);
 5421     const TypeTuple* new_range = TypeTuple::make(range->cnt(), fields);
 5422     tf = TypeFunc::make(tf->domain_cc(), new_range);
 5423   }
 5424   CallJavaNode* slow_call;
 5425   if (is_static) {
 5426     assert(!is_virtual, "");
 5427     slow_call = new CallStaticJavaNode(C, tf,
 5428                            SharedRuntime::get_resolve_static_call_stub(), method);
 5429   } else if (is_virtual) {
 5430     assert(!gvn().type(argument(0))->maybe_null(), "should not be null");
 5431     int vtable_index = Method::invalid_vtable_index;
 5432     if (UseInlineCaches) {
 5433       // Suppress the vtable call
 5434     } else {
 5435       // hashCode and clone are not a miranda methods,
 5436       // so the vtable index is fixed.
 5437       // No need to use the linkResolver to get it.
 5438        vtable_index = method->vtable_index();
 5439        assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index,
 5440               "bad index %d", vtable_index);
 5441     }
 5442     slow_call = new CallDynamicJavaNode(tf,
 5443                           SharedRuntime::get_resolve_virtual_call_stub(),
 5444                           method, vtable_index);
 5445   } else {  // neither virtual nor static:  opt_virtual
 5446     assert(!gvn().type(argument(0))->maybe_null(), "should not be null");
 5447     slow_call = new CallStaticJavaNode(C, tf,
 5448                                 SharedRuntime::get_resolve_opt_virtual_call_stub(), method);
 5449     slow_call->set_optimized_virtual(true);
 5450   }
 5451   if (CallGenerator::is_inlined_method_handle_intrinsic(this->method(), bci(), callee())) {
 5452     // To be able to issue a direct call (optimized virtual or virtual)
 5453     // and skip a call to MH.linkTo*/invokeBasic adapter, additional information
 5454     // about the method being invoked should be attached to the call site to
 5455     // make resolution logic work (see SharedRuntime::resolve_{virtual,opt_virtual}_call_C).
 5456     slow_call->set_override_symbolic_info(true);
 5457   }
 5458   set_arguments_for_java_call(slow_call);
 5459   set_edges_for_java_call(slow_call);
 5460   return slow_call;
 5461 }
 5462 
 5463 
 5464 /**
 5465  * Build special case code for calls to hashCode on an object. This call may
 5466  * be virtual (invokevirtual) or bound (invokespecial). For each case we generate
 5467  * slightly different code.
 5468  */
 5469 bool LibraryCallKit::inline_native_hashcode(bool is_virtual, bool is_static) {
 5470   assert(is_static == callee()->is_static(), "correct intrinsic selection");
 5471   assert(!(is_virtual && is_static), "either virtual, special, or static");
 5472 
 5473   enum { _slow_path = 1, _fast_path, _null_path, PATH_LIMIT };
 5474 
 5475   RegionNode* result_reg = new RegionNode(PATH_LIMIT);
 5476   PhiNode*    result_val = new PhiNode(result_reg, TypeInt::INT);
 5477   PhiNode*    result_io  = new PhiNode(result_reg, Type::ABIO);
 5478   PhiNode*    result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
 5479   Node* obj = argument(0);
 5480 
 5481   // Don't intrinsify hashcode on inline types for now.
 5482   // The "is locked" runtime check also subsumes the inline type check (as inline types cannot be locked) and goes to the slow path.
 5483   if (gvn().type(obj)->is_inlinetypeptr()) {
 5484     return false;
 5485   }
 5486 
 5487   if (!is_static) {
 5488     // Check for hashing null object
 5489     obj = null_check_receiver();
 5490     if (stopped())  return true;        // unconditionally null
 5491     result_reg->init_req(_null_path, top());
 5492     result_val->init_req(_null_path, top());
 5493   } else {
 5494     // Do a null check, and return zero if null.
 5495     // System.identityHashCode(null) == 0
 5496     Node* null_ctl = top();
 5497     obj = null_check_oop(obj, &null_ctl);
 5498     result_reg->init_req(_null_path, null_ctl);
 5499     result_val->init_req(_null_path, _gvn.intcon(0));
 5500   }
 5501 
 5502   // Unconditionally null?  Then return right away.
 5503   if (stopped()) {
 5504     set_control( result_reg->in(_null_path));
 5505     if (!stopped())
 5506       set_result(result_val->in(_null_path));
 5507     return true;
 5508   }
 5509 
 5510   // We only go to the fast case code if we pass a number of guards.  The
 5511   // paths which do not pass are accumulated in the slow_region.
 5512   RegionNode* slow_region = new RegionNode(1);
 5513   record_for_igvn(slow_region);
 5514 
 5515   // If this is a virtual call, we generate a funny guard.  We pull out
 5516   // the vtable entry corresponding to hashCode() from the target object.
 5517   // If the target method which we are calling happens to be the native
 5518   // Object hashCode() method, we pass the guard.  We do not need this
 5519   // guard for non-virtual calls -- the caller is known to be the native
 5520   // Object hashCode().
 5521   if (is_virtual) {
 5522     // After null check, get the object's klass.
 5523     Node* obj_klass = load_object_klass(obj);
 5524     generate_virtual_guard(obj_klass, slow_region);
 5525   }
 5526 
 5527   // Get the header out of the object, use LoadMarkNode when available
 5528   Node* header_addr = basic_plus_adr(obj, oopDesc::mark_offset_in_bytes());
 5529   // The control of the load must be null. Otherwise, the load can move before
 5530   // the null check after castPP removal.
 5531   Node* no_ctrl = nullptr;
 5532   Node* header = make_load(no_ctrl, header_addr, TypeX_X, TypeX_X->basic_type(), MemNode::unordered);
 5533 
 5534   if (!UseObjectMonitorTable) {
 5535     // Test the header to see if it is safe to read w.r.t. locking.
 5536     // We cannot use the inline type mask as this may check bits that are overridden
 5537     // by an object monitor's pointer when inflating locking.
 5538     Node *lock_mask      = _gvn.MakeConX(markWord::lock_mask_in_place);
 5539     Node *lmasked_header = _gvn.transform(new AndXNode(header, lock_mask));
 5540     Node *monitor_val   = _gvn.MakeConX(markWord::monitor_value);
 5541     Node *chk_monitor   = _gvn.transform(new CmpXNode(lmasked_header, monitor_val));
 5542     Node *test_monitor  = _gvn.transform(new BoolNode(chk_monitor, BoolTest::eq));
 5543 
 5544     generate_slow_guard(test_monitor, slow_region);
 5545   }
 5546 
 5547   // Get the hash value and check to see that it has been properly assigned.
 5548   // We depend on hash_mask being at most 32 bits and avoid the use of
 5549   // hash_mask_in_place because it could be larger than 32 bits in a 64-bit
 5550   // vm: see markWord.hpp.
 5551   Node *hash_mask      = _gvn.intcon(markWord::hash_mask);
 5552   Node *hash_shift     = _gvn.intcon(markWord::hash_shift);
 5553   Node *hshifted_header= _gvn.transform(new URShiftXNode(header, hash_shift));
 5554   // This hack lets the hash bits live anywhere in the mark object now, as long
 5555   // as the shift drops the relevant bits into the low 32 bits.  Note that
 5556   // Java spec says that HashCode is an int so there's no point in capturing
 5557   // an 'X'-sized hashcode (32 in 32-bit build or 64 in 64-bit build).
 5558   hshifted_header      = ConvX2I(hshifted_header);
 5559   Node *hash_val       = _gvn.transform(new AndINode(hshifted_header, hash_mask));
 5560 
 5561   Node *no_hash_val    = _gvn.intcon(markWord::no_hash);
 5562   Node *chk_assigned   = _gvn.transform(new CmpINode( hash_val, no_hash_val));
 5563   Node *test_assigned  = _gvn.transform(new BoolNode( chk_assigned, BoolTest::eq));
 5564 
 5565   generate_slow_guard(test_assigned, slow_region);
 5566 
 5567   Node* init_mem = reset_memory();
 5568   // fill in the rest of the null path:
 5569   result_io ->init_req(_null_path, i_o());
 5570   result_mem->init_req(_null_path, init_mem);
 5571 
 5572   result_val->init_req(_fast_path, hash_val);
 5573   result_reg->init_req(_fast_path, control());
 5574   result_io ->init_req(_fast_path, i_o());
 5575   result_mem->init_req(_fast_path, init_mem);
 5576 
 5577   // Generate code for the slow case.  We make a call to hashCode().
 5578   set_control(_gvn.transform(slow_region));
 5579   if (!stopped()) {
 5580     // No need for PreserveJVMState, because we're using up the present state.
 5581     set_all_memory(init_mem);
 5582     vmIntrinsics::ID hashCode_id = is_static ? vmIntrinsics::_identityHashCode : vmIntrinsics::_hashCode;
 5583     CallJavaNode* slow_call = generate_method_call(hashCode_id, is_virtual, is_static, false);
 5584     Node* slow_result = set_results_for_java_call(slow_call);
 5585     // this->control() comes from set_results_for_java_call
 5586     result_reg->init_req(_slow_path, control());
 5587     result_val->init_req(_slow_path, slow_result);
 5588     result_io  ->set_req(_slow_path, i_o());
 5589     result_mem ->set_req(_slow_path, reset_memory());
 5590   }
 5591 
 5592   // Return the combined state.
 5593   set_i_o(        _gvn.transform(result_io)  );
 5594   set_all_memory( _gvn.transform(result_mem));
 5595 
 5596   set_result(result_reg, result_val);
 5597   return true;
 5598 }
 5599 
 5600 //---------------------------inline_native_getClass----------------------------
 5601 // public final native Class<?> java.lang.Object.getClass();
 5602 //
 5603 // Build special case code for calls to getClass on an object.
 5604 bool LibraryCallKit::inline_native_getClass() {
 5605   Node* obj = argument(0);
 5606   if (obj->is_InlineType()) {
 5607     const Type* t = _gvn.type(obj);
 5608     if (t->maybe_null()) {
 5609       null_check(obj);
 5610     }
 5611     set_result(makecon(TypeInstPtr::make(t->inline_klass()->java_mirror())));
 5612     return true;
 5613   }
 5614   obj = null_check_receiver();
 5615   if (stopped())  return true;
 5616   set_result(load_mirror_from_klass(load_object_klass(obj)));
 5617   return true;
 5618 }
 5619 
 5620 //-----------------inline_native_Reflection_getCallerClass---------------------
 5621 // public static native Class<?> sun.reflect.Reflection.getCallerClass();
 5622 //
 5623 // In the presence of deep enough inlining, getCallerClass() becomes a no-op.
 5624 //
 5625 // NOTE: This code must perform the same logic as JVM_GetCallerClass
 5626 // in that it must skip particular security frames and checks for
 5627 // caller sensitive methods.
 5628 bool LibraryCallKit::inline_native_Reflection_getCallerClass() {
 5629 #ifndef PRODUCT
 5630   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
 5631     tty->print_cr("Attempting to inline sun.reflect.Reflection.getCallerClass");
 5632   }
 5633 #endif
 5634 
 5635   if (!jvms()->has_method()) {
 5636 #ifndef PRODUCT
 5637     if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
 5638       tty->print_cr("  Bailing out because intrinsic was inlined at top level");
 5639     }
 5640 #endif
 5641     return false;
 5642   }
 5643 
 5644   // Walk back up the JVM state to find the caller at the required
 5645   // depth.
 5646   JVMState* caller_jvms = jvms();
 5647 
 5648   // Cf. JVM_GetCallerClass
 5649   // NOTE: Start the loop at depth 1 because the current JVM state does
 5650   // not include the Reflection.getCallerClass() frame.
 5651   for (int n = 1; caller_jvms != nullptr; caller_jvms = caller_jvms->caller(), n++) {
 5652     ciMethod* m = caller_jvms->method();
 5653     switch (n) {
 5654     case 0:
 5655       fatal("current JVM state does not include the Reflection.getCallerClass frame");
 5656       break;
 5657     case 1:
 5658       // Frame 0 and 1 must be caller sensitive (see JVM_GetCallerClass).
 5659       if (!m->caller_sensitive()) {
 5660 #ifndef PRODUCT
 5661         if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
 5662           tty->print_cr("  Bailing out: CallerSensitive annotation expected at frame %d", n);
 5663         }
 5664 #endif
 5665         return false;  // bail-out; let JVM_GetCallerClass do the work
 5666       }
 5667       break;
 5668     default:
 5669       if (!m->is_ignored_by_security_stack_walk()) {
 5670         // We have reached the desired frame; return the holder class.
 5671         // Acquire method holder as java.lang.Class and push as constant.
 5672         ciInstanceKlass* caller_klass = caller_jvms->method()->holder();
 5673         ciInstance* caller_mirror = caller_klass->java_mirror();
 5674         set_result(makecon(TypeInstPtr::make(caller_mirror)));
 5675 
 5676 #ifndef PRODUCT
 5677         if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
 5678           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());
 5679           tty->print_cr("  JVM state at this point:");
 5680           for (int i = jvms()->depth(), n = 1; i >= 1; i--, n++) {
 5681             ciMethod* m = jvms()->of_depth(i)->method();
 5682             tty->print_cr("   %d) %s.%s", n, m->holder()->name()->as_utf8(), m->name()->as_utf8());
 5683           }
 5684         }
 5685 #endif
 5686         return true;
 5687       }
 5688       break;
 5689     }
 5690   }
 5691 
 5692 #ifndef PRODUCT
 5693   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
 5694     tty->print_cr("  Bailing out because caller depth exceeded inlining depth = %d", jvms()->depth());
 5695     tty->print_cr("  JVM state at this point:");
 5696     for (int i = jvms()->depth(), n = 1; i >= 1; i--, n++) {
 5697       ciMethod* m = jvms()->of_depth(i)->method();
 5698       tty->print_cr("   %d) %s.%s", n, m->holder()->name()->as_utf8(), m->name()->as_utf8());
 5699     }
 5700   }
 5701 #endif
 5702 
 5703   return false;  // bail-out; let JVM_GetCallerClass do the work
 5704 }
 5705 
 5706 bool LibraryCallKit::inline_fp_conversions(vmIntrinsics::ID id) {
 5707   Node* arg = argument(0);
 5708   Node* result = nullptr;
 5709 
 5710   switch (id) {
 5711   case vmIntrinsics::_floatToRawIntBits:    result = new MoveF2INode(arg);  break;
 5712   case vmIntrinsics::_intBitsToFloat:       result = new MoveI2FNode(arg);  break;
 5713   case vmIntrinsics::_doubleToRawLongBits:  result = new MoveD2LNode(arg);  break;
 5714   case vmIntrinsics::_longBitsToDouble:     result = new MoveL2DNode(arg);  break;
 5715   case vmIntrinsics::_floatToFloat16:       result = new ConvF2HFNode(arg); break;
 5716   case vmIntrinsics::_float16ToFloat:       result = new ConvHF2FNode(arg); break;
 5717 
 5718   case vmIntrinsics::_doubleToLongBits: {
 5719     // two paths (plus control) merge in a wood
 5720     RegionNode *r = new RegionNode(3);
 5721     Node *phi = new PhiNode(r, TypeLong::LONG);
 5722 
 5723     Node *cmpisnan = _gvn.transform(new CmpDNode(arg, arg));
 5724     // Build the boolean node
 5725     Node *bolisnan = _gvn.transform(new BoolNode(cmpisnan, BoolTest::ne));
 5726 
 5727     // Branch either way.
 5728     // NaN case is less traveled, which makes all the difference.
 5729     IfNode *ifisnan = create_and_xform_if(control(), bolisnan, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
 5730     Node *opt_isnan = _gvn.transform(ifisnan);
 5731     assert( opt_isnan->is_If(), "Expect an IfNode");
 5732     IfNode *opt_ifisnan = (IfNode*)opt_isnan;
 5733     Node *iftrue = _gvn.transform(new IfTrueNode(opt_ifisnan));
 5734 
 5735     set_control(iftrue);
 5736 
 5737     static const jlong nan_bits = CONST64(0x7ff8000000000000);
 5738     Node *slow_result = longcon(nan_bits); // return NaN
 5739     phi->init_req(1, _gvn.transform( slow_result ));
 5740     r->init_req(1, iftrue);
 5741 
 5742     // Else fall through
 5743     Node *iffalse = _gvn.transform(new IfFalseNode(opt_ifisnan));
 5744     set_control(iffalse);
 5745 
 5746     phi->init_req(2, _gvn.transform(new MoveD2LNode(arg)));
 5747     r->init_req(2, iffalse);
 5748 
 5749     // Post merge
 5750     set_control(_gvn.transform(r));
 5751     record_for_igvn(r);
 5752 
 5753     C->set_has_split_ifs(true); // Has chance for split-if optimization
 5754     result = phi;
 5755     assert(result->bottom_type()->isa_long(), "must be");
 5756     break;
 5757   }
 5758 
 5759   case vmIntrinsics::_floatToIntBits: {
 5760     // two paths (plus control) merge in a wood
 5761     RegionNode *r = new RegionNode(3);
 5762     Node *phi = new PhiNode(r, TypeInt::INT);
 5763 
 5764     Node *cmpisnan = _gvn.transform(new CmpFNode(arg, arg));
 5765     // Build the boolean node
 5766     Node *bolisnan = _gvn.transform(new BoolNode(cmpisnan, BoolTest::ne));
 5767 
 5768     // Branch either way.
 5769     // NaN case is less traveled, which makes all the difference.
 5770     IfNode *ifisnan = create_and_xform_if(control(), bolisnan, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
 5771     Node *opt_isnan = _gvn.transform(ifisnan);
 5772     assert( opt_isnan->is_If(), "Expect an IfNode");
 5773     IfNode *opt_ifisnan = (IfNode*)opt_isnan;
 5774     Node *iftrue = _gvn.transform(new IfTrueNode(opt_ifisnan));
 5775 
 5776     set_control(iftrue);
 5777 
 5778     static const jint nan_bits = 0x7fc00000;
 5779     Node *slow_result = makecon(TypeInt::make(nan_bits)); // return NaN
 5780     phi->init_req(1, _gvn.transform( slow_result ));
 5781     r->init_req(1, iftrue);
 5782 
 5783     // Else fall through
 5784     Node *iffalse = _gvn.transform(new IfFalseNode(opt_ifisnan));
 5785     set_control(iffalse);
 5786 
 5787     phi->init_req(2, _gvn.transform(new MoveF2INode(arg)));
 5788     r->init_req(2, iffalse);
 5789 
 5790     // Post merge
 5791     set_control(_gvn.transform(r));
 5792     record_for_igvn(r);
 5793 
 5794     C->set_has_split_ifs(true); // Has chance for split-if optimization
 5795     result = phi;
 5796     assert(result->bottom_type()->isa_int(), "must be");
 5797     break;
 5798   }
 5799 
 5800   default:
 5801     fatal_unexpected_iid(id);
 5802     break;
 5803   }
 5804   set_result(_gvn.transform(result));
 5805   return true;
 5806 }
 5807 
 5808 bool LibraryCallKit::inline_fp_range_check(vmIntrinsics::ID id) {
 5809   Node* arg = argument(0);
 5810   Node* result = nullptr;
 5811 
 5812   switch (id) {
 5813   case vmIntrinsics::_floatIsInfinite:
 5814     result = new IsInfiniteFNode(arg);
 5815     break;
 5816   case vmIntrinsics::_floatIsFinite:
 5817     result = new IsFiniteFNode(arg);
 5818     break;
 5819   case vmIntrinsics::_doubleIsInfinite:
 5820     result = new IsInfiniteDNode(arg);
 5821     break;
 5822   case vmIntrinsics::_doubleIsFinite:
 5823     result = new IsFiniteDNode(arg);
 5824     break;
 5825   default:
 5826     fatal_unexpected_iid(id);
 5827     break;
 5828   }
 5829   set_result(_gvn.transform(result));
 5830   return true;
 5831 }
 5832 
 5833 //----------------------inline_unsafe_copyMemory-------------------------
 5834 // public native void Unsafe.copyMemory0(Object srcBase, long srcOffset, Object destBase, long destOffset, long bytes);
 5835 
 5836 static bool has_wide_mem(PhaseGVN& gvn, Node* addr, Node* base) {
 5837   const TypeAryPtr* addr_t = gvn.type(addr)->isa_aryptr();
 5838   const Type*       base_t = gvn.type(base);
 5839 
 5840   bool in_native = (base_t == TypePtr::NULL_PTR);
 5841   bool in_heap   = !TypePtr::NULL_PTR->higher_equal(base_t);
 5842   bool is_mixed  = !in_heap && !in_native;
 5843 
 5844   if (is_mixed) {
 5845     return true; // mixed accesses can touch both on-heap and off-heap memory
 5846   }
 5847   if (in_heap) {
 5848     bool is_prim_array = (addr_t != nullptr) && (addr_t->elem() != Type::BOTTOM);
 5849     if (!is_prim_array) {
 5850       // Though Unsafe.copyMemory() ensures at runtime for on-heap accesses that base is a primitive array,
 5851       // there's not enough type information available to determine proper memory slice for it.
 5852       return true;
 5853     }
 5854   }
 5855   return false;
 5856 }
 5857 
 5858 bool LibraryCallKit::inline_unsafe_copyMemory() {
 5859   if (callee()->is_static())  return false;  // caller must have the capability!
 5860   null_check_receiver();  // null-check receiver
 5861   if (stopped())  return true;
 5862 
 5863   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
 5864 
 5865   Node* src_base =         argument(1);  // type: oop
 5866   Node* src_off  = ConvL2X(argument(2)); // type: long
 5867   Node* dst_base =         argument(4);  // type: oop
 5868   Node* dst_off  = ConvL2X(argument(5)); // type: long
 5869   Node* size     = ConvL2X(argument(7)); // type: long
 5870 
 5871   assert(Unsafe_field_offset_to_byte_offset(11) == 11,
 5872          "fieldOffset must be byte-scaled");
 5873 
 5874   Node* src_addr = make_unsafe_address(src_base, src_off);
 5875   Node* dst_addr = make_unsafe_address(dst_base, dst_off);
 5876 
 5877   Node* thread = _gvn.transform(new ThreadLocalNode());
 5878   Node* doing_unsafe_access_addr = off_heap_plus_addr(thread, in_bytes(JavaThread::doing_unsafe_access_offset()));
 5879   BasicType doing_unsafe_access_bt = T_BYTE;
 5880   assert((sizeof(bool) * CHAR_BIT) == 8, "not implemented");
 5881 
 5882   // update volatile field
 5883   store_to_memory(control(), doing_unsafe_access_addr, intcon(1), doing_unsafe_access_bt, MemNode::unordered);
 5884 
 5885   int flags = RC_LEAF | RC_NO_FP;
 5886 
 5887   const TypePtr* dst_type = TypePtr::BOTTOM;
 5888 
 5889   // Adjust memory effects of the runtime call based on input values.
 5890   if (!has_wide_mem(_gvn, src_addr, src_base) &&
 5891       !has_wide_mem(_gvn, dst_addr, dst_base)) {
 5892     dst_type = _gvn.type(dst_addr)->is_ptr(); // narrow out memory
 5893 
 5894     const TypePtr* src_type = _gvn.type(src_addr)->is_ptr();
 5895     if (C->get_alias_index(src_type) == C->get_alias_index(dst_type)) {
 5896       flags |= RC_NARROW_MEM; // narrow in memory
 5897     }
 5898   }
 5899 
 5900   // Call it.  Note that the length argument is not scaled.
 5901   make_runtime_call(flags,
 5902                     OptoRuntime::fast_arraycopy_Type(),
 5903                     StubRoutines::unsafe_arraycopy(),
 5904                     "unsafe_arraycopy",
 5905                     dst_type,
 5906                     src_addr, dst_addr, size XTOP);
 5907 
 5908   store_to_memory(control(), doing_unsafe_access_addr, intcon(0), doing_unsafe_access_bt, MemNode::unordered);
 5909 
 5910   return true;
 5911 }
 5912 
 5913 // unsafe_setmemory(void *base, ulong offset, size_t length, char fill_value);
 5914 // Fill 'length' bytes starting from 'base[offset]' with 'fill_value'
 5915 bool LibraryCallKit::inline_unsafe_setMemory() {
 5916   if (callee()->is_static())  return false;  // caller must have the capability!
 5917   null_check_receiver();  // null-check receiver
 5918   if (stopped())  return true;
 5919 
 5920   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
 5921 
 5922   Node* dst_base =         argument(1);  // type: oop
 5923   Node* dst_off  = ConvL2X(argument(2)); // type: long
 5924   Node* size     = ConvL2X(argument(4)); // type: long
 5925   Node* byte     =         argument(6);  // type: byte
 5926 
 5927   assert(Unsafe_field_offset_to_byte_offset(11) == 11,
 5928          "fieldOffset must be byte-scaled");
 5929 
 5930   Node* dst_addr = make_unsafe_address(dst_base, dst_off);
 5931 
 5932   Node* thread = _gvn.transform(new ThreadLocalNode());
 5933   Node* doing_unsafe_access_addr = off_heap_plus_addr(thread, in_bytes(JavaThread::doing_unsafe_access_offset()));
 5934   BasicType doing_unsafe_access_bt = T_BYTE;
 5935   assert((sizeof(bool) * CHAR_BIT) == 8, "not implemented");
 5936 
 5937   // update volatile field
 5938   store_to_memory(control(), doing_unsafe_access_addr, intcon(1), doing_unsafe_access_bt, MemNode::unordered);
 5939 
 5940   int flags = RC_LEAF | RC_NO_FP;
 5941 
 5942   const TypePtr* dst_type = TypePtr::BOTTOM;
 5943 
 5944   // Adjust memory effects of the runtime call based on input values.
 5945   if (!has_wide_mem(_gvn, dst_addr, dst_base)) {
 5946     dst_type = _gvn.type(dst_addr)->is_ptr(); // narrow out memory
 5947 
 5948     flags |= RC_NARROW_MEM; // narrow in memory
 5949   }
 5950 
 5951   // Call it.  Note that the length argument is not scaled.
 5952   make_runtime_call(flags,
 5953                     OptoRuntime::unsafe_setmemory_Type(),
 5954                     StubRoutines::unsafe_setmemory(),
 5955                     "unsafe_setmemory",
 5956                     dst_type,
 5957                     dst_addr, size XTOP, byte);
 5958 
 5959   store_to_memory(control(), doing_unsafe_access_addr, intcon(0), doing_unsafe_access_bt, MemNode::unordered);
 5960 
 5961   return true;
 5962 }
 5963 
 5964 #undef XTOP
 5965 
 5966 //------------------------clone_coping-----------------------------------
 5967 // Helper function for inline_native_clone.
 5968 void LibraryCallKit::copy_to_clone(Node* obj, Node* alloc_obj, Node* obj_size, bool is_array) {
 5969   assert(obj_size != nullptr, "");
 5970   Node* raw_obj = alloc_obj->in(1);
 5971   assert(alloc_obj->is_CheckCastPP() && raw_obj->is_Proj() && raw_obj->in(0)->is_Allocate(), "");
 5972 
 5973   AllocateNode* alloc = nullptr;
 5974   if (ReduceBulkZeroing &&
 5975       // If we are implementing an array clone without knowing its source type
 5976       // (can happen when compiling the array-guarded branch of a reflective
 5977       // Object.clone() invocation), initialize the array within the allocation.
 5978       // This is needed because some GCs (e.g. ZGC) might fall back in this case
 5979       // to a runtime clone call that assumes fully initialized source arrays.
 5980       (!is_array || obj->get_ptr_type()->isa_aryptr() != nullptr)) {
 5981     // We will be completely responsible for initializing this object -
 5982     // mark Initialize node as complete.
 5983     alloc = AllocateNode::Ideal_allocation(alloc_obj);
 5984     // The object was just allocated - there should be no any stores!
 5985     guarantee(alloc != nullptr && alloc->maybe_set_complete(&_gvn), "");
 5986     // Mark as complete_with_arraycopy so that on AllocateNode
 5987     // expansion, we know this AllocateNode is initialized by an array
 5988     // copy and a StoreStore barrier exists after the array copy.
 5989     alloc->initialization()->set_complete_with_arraycopy();
 5990   }
 5991 
 5992   Node* size = _gvn.transform(obj_size);
 5993   access_clone(obj, alloc_obj, size, is_array);
 5994 
 5995   // Do not let reads from the cloned object float above the arraycopy.
 5996   if (alloc != nullptr) {
 5997     // Do not let stores that initialize this object be reordered with
 5998     // a subsequent store that would make this object accessible by
 5999     // other threads.
 6000     // Record what AllocateNode this StoreStore protects so that
 6001     // escape analysis can go from the MemBarStoreStoreNode to the
 6002     // AllocateNode and eliminate the MemBarStoreStoreNode if possible
 6003     // based on the escape status of the AllocateNode.
 6004     insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
 6005   } else {
 6006     insert_mem_bar(Op_MemBarCPUOrder);
 6007   }
 6008 }
 6009 
 6010 //------------------------inline_native_clone----------------------------
 6011 // protected native Object java.lang.Object.clone();
 6012 //
 6013 // Here are the simple edge cases:
 6014 //  null receiver => normal trap
 6015 //  virtual and clone was overridden => slow path to out-of-line clone
 6016 //  not cloneable or finalizer => slow path to out-of-line Object.clone
 6017 //
 6018 // The general case has two steps, allocation and copying.
 6019 // Allocation has two cases, and uses GraphKit::new_instance or new_array.
 6020 //
 6021 // Copying also has two cases, oop arrays and everything else.
 6022 // Oop arrays use arrayof_oop_arraycopy (same as System.arraycopy).
 6023 // Everything else uses the tight inline loop supplied by CopyArrayNode.
 6024 //
 6025 // These steps fold up nicely if and when the cloned object's klass
 6026 // can be sharply typed as an object array, a type array, or an instance.
 6027 //
 6028 bool LibraryCallKit::inline_native_clone(bool is_virtual) {
 6029   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
 6030     return false;
 6031   }
 6032 
 6033   PhiNode* result_val;
 6034 
 6035   // Set the reexecute bit for the interpreter to reexecute
 6036   // the bytecode that invokes Object.clone if deoptimization happens.
 6037   { PreserveReexecuteState preexecs(this);
 6038     jvms()->set_should_reexecute(true);
 6039 
 6040     Node* obj = argument(0);
 6041     obj = null_check_receiver();
 6042     if (stopped())  return true;
 6043 
 6044     const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
 6045     if (obj_type->is_inlinetypeptr()) {
 6046       // If the object to clone is an inline type, we can simply return it (i.e. a nop) since inline types have
 6047       // no identity. But we first need to check whether the value class is actually implementing the Cloneable
 6048       // interface. If not, we trap.
 6049       if (obj_type->inline_klass()->is_cloneable()) {
 6050         set_result(obj);
 6051       } else {
 6052         uncommon_trap(Deoptimization::Reason_intrinsic,
 6053                       Deoptimization::Action_maybe_recompile);
 6054       }
 6055       return true;
 6056     }
 6057 
 6058     // If we are going to clone an instance, we need its exact type to
 6059     // know the number and types of fields to convert the clone to
 6060     // loads/stores. Maybe a speculative type can help us.
 6061     if (!obj_type->klass_is_exact() &&
 6062         obj_type->speculative_type() != nullptr &&
 6063         obj_type->speculative_type()->is_instance_klass() &&
 6064         !obj_type->speculative_type()->is_inlinetype()) {
 6065       ciInstanceKlass* spec_ik = obj_type->speculative_type()->as_instance_klass();
 6066       if (spec_ik->nof_nonstatic_fields() <= ArrayCopyLoadStoreMaxElem &&
 6067           !spec_ik->has_injected_fields()) {
 6068         if (!obj_type->isa_instptr() ||
 6069             obj_type->is_instptr()->instance_klass()->has_subklass()) {
 6070           obj = maybe_cast_profiled_obj(obj, obj_type->speculative_type(), false);
 6071         }
 6072       }
 6073     }
 6074 
 6075     // Conservatively insert a memory barrier on all memory slices.
 6076     // Do not let writes into the original float below the clone.
 6077     insert_mem_bar(Op_MemBarCPUOrder);
 6078 
 6079     // paths into result_reg:
 6080     enum {
 6081       _slow_path = 1,     // out-of-line call to clone method (virtual or not)
 6082       _objArray_path,     // plain array allocation, plus arrayof_oop_arraycopy
 6083       _array_path,        // plain array allocation, plus arrayof_long_arraycopy
 6084       _instance_path,     // plain instance allocation, plus arrayof_long_arraycopy
 6085       PATH_LIMIT
 6086     };
 6087     RegionNode* result_reg = new RegionNode(PATH_LIMIT);
 6088     result_val             = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
 6089     PhiNode*    result_i_o = new PhiNode(result_reg, Type::ABIO);
 6090     PhiNode*    result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
 6091     record_for_igvn(result_reg);
 6092 
 6093     Node* obj_klass = load_object_klass(obj);
 6094     // We only go to the fast case code if we pass a number of guards.
 6095     // The paths which do not pass are accumulated in the slow_region.
 6096     RegionNode* slow_region = new RegionNode(1);
 6097     record_for_igvn(slow_region);
 6098 
 6099     Node* array_obj = obj;
 6100     Node* array_ctl = generate_array_guard(obj_klass, (RegionNode*)nullptr, &array_obj);
 6101     if (array_ctl != nullptr) {
 6102       // It's an array.
 6103       PreserveJVMState pjvms(this);
 6104       set_control(array_ctl);
 6105 
 6106       BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
 6107       const TypeAryPtr* ary_ptr = obj_type->isa_aryptr();
 6108       if (UseArrayFlattening && bs->array_copy_requires_gc_barriers(true, T_OBJECT, true, false, BarrierSetC2::Expansion) &&
 6109           obj_type->can_be_inline_array() &&
 6110           (ary_ptr == nullptr || (!ary_ptr->is_not_flat() && (!ary_ptr->is_flat() || ary_ptr->elem()->inline_klass()->contains_oops())))) {
 6111         // Flat inline type array may have object field that would require a
 6112         // write barrier. Conservatively, go to slow path.
 6113         generate_fair_guard(flat_array_test(obj_klass), slow_region);
 6114       }
 6115 
 6116       if (!stopped()) {
 6117         Node* obj_length = load_array_length(array_obj);
 6118         Node* array_size = nullptr; // Size of the array without object alignment padding.
 6119         Node* alloc_obj = new_array(obj_klass, obj_length, 0, &array_size, /*deoptimize_on_exception=*/true);
 6120 
 6121         BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
 6122         if (bs->array_copy_requires_gc_barriers(true, T_OBJECT, true, false, BarrierSetC2::Parsing)) {
 6123           // If it is an oop array, it requires very special treatment,
 6124           // because gc barriers are required when accessing the array.
 6125           Node* is_obja = generate_refArray_guard(obj_klass, (RegionNode*)nullptr);
 6126           if (is_obja != nullptr) {
 6127             PreserveJVMState pjvms2(this);
 6128             set_control(is_obja);
 6129             // Generate a direct call to the right arraycopy function(s).
 6130             // Clones are always tightly coupled.
 6131             ArrayCopyNode* ac = ArrayCopyNode::make(this, true, array_obj, intcon(0), alloc_obj, intcon(0), obj_length, true, false);
 6132             ac->set_clone_oop_array();
 6133             Node* n = _gvn.transform(ac);
 6134             assert(n == ac, "cannot disappear");
 6135             ac->connect_outputs(this, /*deoptimize_on_exception=*/true);
 6136 
 6137             result_reg->init_req(_objArray_path, control());
 6138             result_val->init_req(_objArray_path, alloc_obj);
 6139             result_i_o ->set_req(_objArray_path, i_o());
 6140             result_mem ->set_req(_objArray_path, reset_memory());
 6141           }
 6142         }
 6143         // Otherwise, there are no barriers to worry about.
 6144         // (We can dispense with card marks if we know the allocation
 6145         //  comes out of eden (TLAB)...  In fact, ReduceInitialCardMarks
 6146         //  causes the non-eden paths to take compensating steps to
 6147         //  simulate a fresh allocation, so that no further
 6148         //  card marks are required in compiled code to initialize
 6149         //  the object.)
 6150 
 6151         if (!stopped()) {
 6152           copy_to_clone(obj, alloc_obj, array_size, true);
 6153 
 6154           // Present the results of the copy.
 6155           result_reg->init_req(_array_path, control());
 6156           result_val->init_req(_array_path, alloc_obj);
 6157           result_i_o ->set_req(_array_path, i_o());
 6158           result_mem ->set_req(_array_path, reset_memory());
 6159         }
 6160       }
 6161     }
 6162 
 6163     if (!stopped()) {
 6164       // It's an instance (we did array above).  Make the slow-path tests.
 6165       // If this is a virtual call, we generate a funny guard.  We grab
 6166       // the vtable entry corresponding to clone() from the target object.
 6167       // If the target method which we are calling happens to be the
 6168       // Object clone() method, we pass the guard.  We do not need this
 6169       // guard for non-virtual calls; the caller is known to be the native
 6170       // Object clone().
 6171       if (is_virtual) {
 6172         generate_virtual_guard(obj_klass, slow_region);
 6173       }
 6174 
 6175       // The object must be easily cloneable and must not have a finalizer.
 6176       // Both of these conditions may be checked in a single test.
 6177       // We could optimize the test further, but we don't care.
 6178       generate_misc_flags_guard(obj_klass,
 6179                                 // Test both conditions:
 6180                                 KlassFlags::_misc_is_cloneable_fast | KlassFlags::_misc_has_finalizer,
 6181                                 // Must be cloneable but not finalizer:
 6182                                 KlassFlags::_misc_is_cloneable_fast,
 6183                                 slow_region);
 6184     }
 6185 
 6186     if (!stopped()) {
 6187       // It's an instance, and it passed the slow-path tests.
 6188       PreserveJVMState pjvms(this);
 6189       Node* obj_size = nullptr; // Total object size, including object alignment padding.
 6190       // Need to deoptimize on exception from allocation since Object.clone intrinsic
 6191       // is reexecuted if deoptimization occurs and there could be problems when merging
 6192       // exception state between multiple Object.clone versions (reexecute=true vs reexecute=false).
 6193       Node* alloc_obj = new_instance(obj_klass, nullptr, &obj_size, /*deoptimize_on_exception=*/true);
 6194 
 6195       copy_to_clone(obj, alloc_obj, obj_size, false);
 6196 
 6197       // Present the results of the slow call.
 6198       result_reg->init_req(_instance_path, control());
 6199       result_val->init_req(_instance_path, alloc_obj);
 6200       result_i_o ->set_req(_instance_path, i_o());
 6201       result_mem ->set_req(_instance_path, reset_memory());
 6202     }
 6203 
 6204     // Generate code for the slow case.  We make a call to clone().
 6205     set_control(_gvn.transform(slow_region));
 6206     if (!stopped()) {
 6207       PreserveJVMState pjvms(this);
 6208       CallJavaNode* slow_call = generate_method_call(vmIntrinsics::_clone, is_virtual, false, true);
 6209       // We need to deoptimize on exception (see comment above)
 6210       Node* slow_result = set_results_for_java_call(slow_call, false, /* deoptimize */ true);
 6211       // this->control() comes from set_results_for_java_call
 6212       result_reg->init_req(_slow_path, control());
 6213       result_val->init_req(_slow_path, slow_result);
 6214       result_i_o ->set_req(_slow_path, i_o());
 6215       result_mem ->set_req(_slow_path, reset_memory());
 6216     }
 6217 
 6218     // Return the combined state.
 6219     set_control(    _gvn.transform(result_reg));
 6220     set_i_o(        _gvn.transform(result_i_o));
 6221     set_all_memory( _gvn.transform(result_mem));
 6222   } // original reexecute is set back here
 6223 
 6224   set_result(_gvn.transform(result_val));
 6225   return true;
 6226 }
 6227 
 6228 // If we have a tightly coupled allocation, the arraycopy may take care
 6229 // of the array initialization. If one of the guards we insert between
 6230 // the allocation and the arraycopy causes a deoptimization, an
 6231 // uninitialized array will escape the compiled method. To prevent that
 6232 // we set the JVM state for uncommon traps between the allocation and
 6233 // the arraycopy to the state before the allocation so, in case of
 6234 // deoptimization, we'll reexecute the allocation and the
 6235 // initialization.
 6236 JVMState* LibraryCallKit::arraycopy_restore_alloc_state(AllocateArrayNode* alloc, int& saved_reexecute_sp) {
 6237   if (alloc != nullptr) {
 6238     ciMethod* trap_method = alloc->jvms()->method();
 6239     int trap_bci = alloc->jvms()->bci();
 6240 
 6241     if (!C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_intrinsic) &&
 6242         !C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_null_check)) {
 6243       // Make sure there's no store between the allocation and the
 6244       // arraycopy otherwise visible side effects could be rexecuted
 6245       // in case of deoptimization and cause incorrect execution.
 6246       bool no_interfering_store = true;
 6247       Node* mem = alloc->in(TypeFunc::Memory);
 6248       if (mem->is_MergeMem()) {
 6249         for (MergeMemStream mms(merged_memory(), mem->as_MergeMem()); mms.next_non_empty2(); ) {
 6250           Node* n = mms.memory();
 6251           if (n != mms.memory2() && !(n->is_Proj() && n->in(0) == alloc->initialization())) {
 6252             assert(n->is_Store(), "what else?");
 6253             no_interfering_store = false;
 6254             break;
 6255           }
 6256         }
 6257       } else {
 6258         for (MergeMemStream mms(merged_memory()); mms.next_non_empty(); ) {
 6259           Node* n = mms.memory();
 6260           if (n != mem && !(n->is_Proj() && n->in(0) == alloc->initialization())) {
 6261             assert(n->is_Store(), "what else?");
 6262             no_interfering_store = false;
 6263             break;
 6264           }
 6265         }
 6266       }
 6267 
 6268       if (no_interfering_store) {
 6269         SafePointNode* sfpt = create_safepoint_with_state_before_array_allocation(alloc);
 6270 
 6271         JVMState* saved_jvms = jvms();
 6272         saved_reexecute_sp = _reexecute_sp;
 6273 
 6274         set_jvms(sfpt->jvms());
 6275         _reexecute_sp = jvms()->sp();
 6276 
 6277         return saved_jvms;
 6278       }
 6279     }
 6280   }
 6281   return nullptr;
 6282 }
 6283 
 6284 // Clone the JVMState of the array allocation and create a new safepoint with it. Re-push the array length to the stack
 6285 // such that uncommon traps can be emitted to re-execute the array allocation in the interpreter.
 6286 SafePointNode* LibraryCallKit::create_safepoint_with_state_before_array_allocation(const AllocateArrayNode* alloc) const {
 6287   JVMState* old_jvms = alloc->jvms()->clone_shallow(C);
 6288   uint size = alloc->req();
 6289   SafePointNode* sfpt = new SafePointNode(size, old_jvms);
 6290   old_jvms->set_map(sfpt);
 6291   for (uint i = 0; i < size; i++) {
 6292     sfpt->init_req(i, alloc->in(i));
 6293   }
 6294   int adjustment = 1;
 6295   const TypeAryKlassPtr* ary_klass_ptr = alloc->in(AllocateNode::KlassNode)->bottom_type()->is_aryklassptr();
 6296   if (ary_klass_ptr->is_null_free()) {
 6297     // A null-free, tightly coupled array allocation can only come from LibraryCallKit::inline_newArray which
 6298     // also requires the componentType and initVal on stack for re-execution.
 6299     // Re-create and push the componentType.
 6300     ciArrayKlass* klass = ary_klass_ptr->exact_klass()->as_array_klass();
 6301     ciInstance* instance = klass->component_mirror_instance();
 6302     const TypeInstPtr* t_instance = TypeInstPtr::make(instance);
 6303     sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp(), makecon(t_instance));
 6304     adjustment++;
 6305   }
 6306   // re-push array length for deoptimization
 6307   sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp() + adjustment - 1, alloc->in(AllocateNode::ALength));
 6308   if (ary_klass_ptr->is_null_free()) {
 6309     // Re-create and push the initVal.
 6310     Node* init_val = alloc->in(AllocateNode::InitValue);
 6311     if (init_val == nullptr) {
 6312       init_val = InlineTypeNode::make_all_zero(_gvn, ary_klass_ptr->elem()->is_instklassptr()->instance_klass()->as_inline_klass());
 6313     } else if (UseCompressedOops) {
 6314       init_val = _gvn.transform(new DecodeNNode(init_val, init_val->bottom_type()->make_ptr()));
 6315     }
 6316     sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp() + adjustment, init_val);
 6317     adjustment++;
 6318   }
 6319   old_jvms->set_sp(old_jvms->sp() + adjustment);
 6320   old_jvms->set_monoff(old_jvms->monoff() + adjustment);
 6321   old_jvms->set_scloff(old_jvms->scloff() + adjustment);
 6322   old_jvms->set_endoff(old_jvms->endoff() + adjustment);
 6323   old_jvms->set_should_reexecute(true);
 6324 
 6325   sfpt->set_i_o(map()->i_o());
 6326   sfpt->set_memory(map()->memory());
 6327   sfpt->set_control(map()->control());
 6328   return sfpt;
 6329 }
 6330 
 6331 // In case of a deoptimization, we restart execution at the
 6332 // allocation, allocating a new array. We would leave an uninitialized
 6333 // array in the heap that GCs wouldn't expect. Move the allocation
 6334 // after the traps so we don't allocate the array if we
 6335 // deoptimize. This is possible because tightly_coupled_allocation()
 6336 // guarantees there's no observer of the allocated array at this point
 6337 // and the control flow is simple enough.
 6338 void LibraryCallKit::arraycopy_move_allocation_here(AllocateArrayNode* alloc, Node* dest, JVMState* saved_jvms_before_guards,
 6339                                                     int saved_reexecute_sp, uint new_idx) {
 6340   if (saved_jvms_before_guards != nullptr && !stopped()) {
 6341     replace_unrelated_uncommon_traps_with_alloc_state(alloc, saved_jvms_before_guards);
 6342 
 6343     assert(alloc != nullptr, "only with a tightly coupled allocation");
 6344     // restore JVM state to the state at the arraycopy
 6345     saved_jvms_before_guards->map()->set_control(map()->control());
 6346     assert(saved_jvms_before_guards->map()->memory() == map()->memory(), "memory state changed?");
 6347     assert(saved_jvms_before_guards->map()->i_o() == map()->i_o(), "IO state changed?");
 6348     // If we've improved the types of some nodes (null check) while
 6349     // emitting the guards, propagate them to the current state
 6350     map()->replaced_nodes().apply(saved_jvms_before_guards->map(), new_idx);
 6351     set_jvms(saved_jvms_before_guards);
 6352     _reexecute_sp = saved_reexecute_sp;
 6353 
 6354     // Remove the allocation from above the guards
 6355     CallProjections* callprojs = alloc->extract_projections(true);
 6356     InitializeNode* init = alloc->initialization();
 6357     Node* alloc_mem = alloc->in(TypeFunc::Memory);
 6358     C->gvn_replace_by(callprojs->fallthrough_ioproj, alloc->in(TypeFunc::I_O));
 6359     init->replace_mem_projs_by(alloc_mem, C);
 6360 
 6361     // The CastIINode created in GraphKit::new_array (in AllocateArrayNode::make_ideal_length) must stay below
 6362     // the allocation (i.e. is only valid if the allocation succeeds):
 6363     // 1) replace CastIINode with AllocateArrayNode's length here
 6364     // 2) Create CastIINode again once allocation has moved (see below) at the end of this method
 6365     //
 6366     // Multiple identical CastIINodes might exist here. Each GraphKit::load_array_length() call will generate
 6367     // new separate CastIINode (arraycopy guard checks or any array length use between array allocation and ararycopy)
 6368     Node* init_control = init->proj_out(TypeFunc::Control);
 6369     Node* alloc_length = alloc->Ideal_length();
 6370 #ifdef ASSERT
 6371     Node* prev_cast = nullptr;
 6372 #endif
 6373     for (uint i = 0; i < init_control->outcnt(); i++) {
 6374       Node* init_out = init_control->raw_out(i);
 6375       if (init_out->is_CastII() && init_out->in(TypeFunc::Control) == init_control && init_out->in(1) == alloc_length) {
 6376 #ifdef ASSERT
 6377         if (prev_cast == nullptr) {
 6378           prev_cast = init_out;
 6379         } else {
 6380           if (prev_cast->cmp(*init_out) == false) {
 6381             prev_cast->dump();
 6382             init_out->dump();
 6383             assert(false, "not equal CastIINode");
 6384           }
 6385         }
 6386 #endif
 6387         C->gvn_replace_by(init_out, alloc_length);
 6388       }
 6389     }
 6390     C->gvn_replace_by(init->proj_out(TypeFunc::Control), alloc->in(0));
 6391 
 6392     // move the allocation here (after the guards)
 6393     _gvn.hash_delete(alloc);
 6394     alloc->set_req(TypeFunc::Control, control());
 6395     alloc->set_req(TypeFunc::I_O, i_o());
 6396     Node *mem = reset_memory();
 6397     set_all_memory(mem);
 6398     alloc->set_req(TypeFunc::Memory, mem);
 6399     set_control(init->proj_out_or_null(TypeFunc::Control));
 6400     set_i_o(callprojs->fallthrough_ioproj);
 6401 
 6402     // Update memory as done in GraphKit::set_output_for_allocation()
 6403     const TypeInt* length_type = _gvn.find_int_type(alloc->in(AllocateNode::ALength));
 6404     const TypeOopPtr* ary_type = _gvn.type(alloc->in(AllocateNode::KlassNode))->is_klassptr()->as_exact_instance_type();
 6405     if (ary_type->isa_aryptr() && length_type != nullptr) {
 6406       ary_type = ary_type->is_aryptr()->cast_to_size(length_type);
 6407     }
 6408     const TypePtr* telemref = ary_type->add_offset(Type::OffsetBot);
 6409     int            elemidx  = C->get_alias_index(telemref);
 6410     // Need to properly move every memory projection for the Initialize
 6411 #ifdef ASSERT
 6412     int mark_idx = C->get_alias_index(ary_type->add_offset(oopDesc::mark_offset_in_bytes()));
 6413     int klass_idx = C->get_alias_index(ary_type->add_offset(oopDesc::klass_offset_in_bytes()));
 6414 #endif
 6415     auto move_proj = [&](ProjNode* proj) {
 6416       int alias_idx = C->get_alias_index(proj->adr_type());
 6417       assert(alias_idx == Compile::AliasIdxRaw ||
 6418              alias_idx == elemidx ||
 6419              alias_idx == mark_idx ||
 6420              alias_idx == klass_idx, "should be raw memory or array element type");
 6421       set_memory(proj, alias_idx);
 6422     };
 6423     init->for_each_proj(move_proj, TypeFunc::Memory);
 6424 
 6425     Node* allocx = _gvn.transform(alloc);
 6426     assert(allocx == alloc, "where has the allocation gone?");
 6427     assert(dest->is_CheckCastPP(), "not an allocation result?");
 6428 
 6429     _gvn.hash_delete(dest);
 6430     dest->set_req(0, control());
 6431     Node* destx = _gvn.transform(dest);
 6432     assert(destx == dest, "where has the allocation result gone?");
 6433 
 6434     array_ideal_length(alloc, ary_type, true);
 6435   }
 6436 }
 6437 
 6438 // Unrelated UCTs between the array allocation and the array copy, which are considered safe by tightly_coupled_allocation(),
 6439 // need to be replaced by an UCT with a state before the array allocation (including the array length). This is necessary
 6440 // because we could hit one of these UCTs (which are executed before the emitted array copy guards and the actual array
 6441 // allocation which is moved down in arraycopy_move_allocation_here()). When later resuming execution in the interpreter,
 6442 // we would have wrongly skipped the array allocation. To prevent this, we resume execution at the array allocation in
 6443 // the interpreter similar to what we are doing for the newly emitted guards for the array copy.
 6444 void LibraryCallKit::replace_unrelated_uncommon_traps_with_alloc_state(AllocateArrayNode* alloc,
 6445                                                                        JVMState* saved_jvms_before_guards) {
 6446   if (saved_jvms_before_guards->map()->control()->is_IfProj()) {
 6447     // There is at least one unrelated uncommon trap which needs to be replaced.
 6448     SafePointNode* sfpt = create_safepoint_with_state_before_array_allocation(alloc);
 6449 
 6450     JVMState* saved_jvms = jvms();
 6451     const int saved_reexecute_sp = _reexecute_sp;
 6452     set_jvms(sfpt->jvms());
 6453     _reexecute_sp = jvms()->sp();
 6454 
 6455     replace_unrelated_uncommon_traps_with_alloc_state(saved_jvms_before_guards);
 6456 
 6457     // Restore state
 6458     set_jvms(saved_jvms);
 6459     _reexecute_sp = saved_reexecute_sp;
 6460   }
 6461 }
 6462 
 6463 // Replace the unrelated uncommon traps with new uncommon trap nodes by reusing the action and reason. The new uncommon
 6464 // traps will have the state of the array allocation. Let the old uncommon trap nodes die.
 6465 void LibraryCallKit::replace_unrelated_uncommon_traps_with_alloc_state(JVMState* saved_jvms_before_guards) {
 6466   Node* if_proj = saved_jvms_before_guards->map()->control(); // Start the search right before the newly emitted guards
 6467   while (if_proj->is_IfProj()) {
 6468     CallStaticJavaNode* uncommon_trap = get_uncommon_trap_from_success_proj(if_proj);
 6469     if (uncommon_trap != nullptr) {
 6470       create_new_uncommon_trap(uncommon_trap);
 6471     }
 6472     assert(if_proj->in(0)->is_If(), "must be If");
 6473     if_proj = if_proj->in(0)->in(0);
 6474   }
 6475   assert(if_proj->is_Proj() && if_proj->in(0)->is_Initialize(),
 6476          "must have reached control projection of init node");
 6477 }
 6478 
 6479 void LibraryCallKit::create_new_uncommon_trap(CallStaticJavaNode* uncommon_trap_call) {
 6480   const int trap_request = uncommon_trap_call->uncommon_trap_request();
 6481   assert(trap_request != 0, "no valid UCT trap request");
 6482   PreserveJVMState pjvms(this);
 6483   set_control(uncommon_trap_call->in(0));
 6484   uncommon_trap(Deoptimization::trap_request_reason(trap_request),
 6485                 Deoptimization::trap_request_action(trap_request));
 6486   assert(stopped(), "Should be stopped");
 6487   _gvn.hash_delete(uncommon_trap_call);
 6488   uncommon_trap_call->set_req(0, top()); // not used anymore, kill it
 6489 }
 6490 
 6491 // Common checks for array sorting intrinsics arguments.
 6492 // Returns `true` if checks passed.
 6493 bool LibraryCallKit::check_array_sort_arguments(Node* elementType, Node* obj, BasicType& bt) {
 6494   // check address of the class
 6495   if (elementType == nullptr || elementType->is_top()) {
 6496     return false;  // dead path
 6497   }
 6498   const TypeInstPtr* elem_klass = gvn().type(elementType)->isa_instptr();
 6499   if (elem_klass == nullptr) {
 6500     return false;  // dead path
 6501   }
 6502   // java_mirror_type() returns non-null for compile-time Class constants only
 6503   ciType* elem_type = elem_klass->java_mirror_type();
 6504   if (elem_type == nullptr) {
 6505     return false;
 6506   }
 6507   bt = elem_type->basic_type();
 6508   // Disable the intrinsic if the CPU does not support SIMD sort
 6509   if (!Matcher::supports_simd_sort(bt)) {
 6510     return false;
 6511   }
 6512   // check address of the array
 6513   if (obj == nullptr || obj->is_top()) {
 6514     return false;  // dead path
 6515   }
 6516   const TypeAryPtr* obj_t = _gvn.type(obj)->isa_aryptr();
 6517   if (obj_t == nullptr || obj_t->elem() == Type::BOTTOM) {
 6518     return false; // failed input validation
 6519   }
 6520   return true;
 6521 }
 6522 
 6523 //------------------------------inline_array_partition-----------------------
 6524 bool LibraryCallKit::inline_array_partition() {
 6525   address stubAddr = StubRoutines::select_array_partition_function();
 6526   if (stubAddr == nullptr) {
 6527     return false; // Intrinsic's stub is not implemented on this platform
 6528   }
 6529   assert(callee()->signature()->size() == 9, "arrayPartition has 8 parameters (one long)");
 6530 
 6531   // no receiver because it is a static method
 6532   Node* elementType     = argument(0);
 6533   Node* obj             = argument(1);
 6534   Node* offset          = argument(2); // long
 6535   Node* fromIndex       = argument(4);
 6536   Node* toIndex         = argument(5);
 6537   Node* indexPivot1     = argument(6);
 6538   Node* indexPivot2     = argument(7);
 6539   // PartitionOperation:  argument(8) is ignored
 6540 
 6541   Node* pivotIndices = nullptr;
 6542   BasicType bt = T_ILLEGAL;
 6543 
 6544   if (!check_array_sort_arguments(elementType, obj, bt)) {
 6545     return false;
 6546   }
 6547   null_check(obj);
 6548   // If obj is dead, only null-path is taken.
 6549   if (stopped()) {
 6550     return true;
 6551   }
 6552   // Set the original stack and the reexecute bit for the interpreter to reexecute
 6553   // the bytecode that invokes DualPivotQuicksort.partition() if deoptimization happens.
 6554   { PreserveReexecuteState preexecs(this);
 6555     jvms()->set_should_reexecute(true);
 6556 
 6557     Node* obj_adr = make_unsafe_address(obj, offset);
 6558 
 6559     // create the pivotIndices array of type int and size = 2
 6560     Node* size = intcon(2);
 6561     Node* klass_node = makecon(TypeKlassPtr::make(ciTypeArrayKlass::make(T_INT)));
 6562     pivotIndices = new_array(klass_node, size, 0);  // no arguments to push
 6563     AllocateArrayNode* alloc = tightly_coupled_allocation(pivotIndices);
 6564     guarantee(alloc != nullptr, "created above");
 6565     Node* pivotIndices_adr = basic_plus_adr(pivotIndices, arrayOopDesc::base_offset_in_bytes(T_INT));
 6566 
 6567     // pass the basic type enum to the stub
 6568     Node* elemType = intcon(bt);
 6569 
 6570     // Call the stub
 6571     const char *stubName = "array_partition_stub";
 6572     make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::array_partition_Type(),
 6573                       stubAddr, stubName, TypePtr::BOTTOM,
 6574                       obj_adr, elemType, fromIndex, toIndex, pivotIndices_adr,
 6575                       indexPivot1, indexPivot2);
 6576 
 6577   } // original reexecute is set back here
 6578 
 6579   if (!stopped()) {
 6580     set_result(pivotIndices);
 6581   }
 6582 
 6583   return true;
 6584 }
 6585 
 6586 
 6587 //------------------------------inline_array_sort-----------------------
 6588 bool LibraryCallKit::inline_array_sort() {
 6589   address stubAddr = StubRoutines::select_arraysort_function();
 6590   if (stubAddr == nullptr) {
 6591     return false; // Intrinsic's stub is not implemented on this platform
 6592   }
 6593   assert(callee()->signature()->size() == 7, "arraySort has 6 parameters (one long)");
 6594 
 6595   // no receiver because it is a static method
 6596   Node* elementType     = argument(0);
 6597   Node* obj             = argument(1);
 6598   Node* offset          = argument(2); // long
 6599   Node* fromIndex       = argument(4);
 6600   Node* toIndex         = argument(5);
 6601   // SortOperation:       argument(6) is ignored
 6602 
 6603   BasicType bt = T_ILLEGAL;
 6604 
 6605   if (!check_array_sort_arguments(elementType, obj, bt)) {
 6606     return false;
 6607   }
 6608   null_check(obj);
 6609   // If obj is dead, only null-path is taken.
 6610   if (stopped()) {
 6611     return true;
 6612   }
 6613   Node* obj_adr = make_unsafe_address(obj, offset);
 6614 
 6615   // pass the basic type enum to the stub
 6616   Node* elemType = intcon(bt);
 6617 
 6618   // Call the stub.
 6619   const char *stubName = "arraysort_stub";
 6620   make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::array_sort_Type(),
 6621                     stubAddr, stubName, TypePtr::BOTTOM,
 6622                     obj_adr, elemType, fromIndex, toIndex);
 6623 
 6624   return true;
 6625 }
 6626 
 6627 
 6628 //------------------------------inline_arraycopy-----------------------
 6629 // public static native void java.lang.System.arraycopy(Object src,  int  srcPos,
 6630 //                                                      Object dest, int destPos,
 6631 //                                                      int length);
 6632 bool LibraryCallKit::inline_arraycopy() {
 6633   // Get the arguments.
 6634   Node* src         = argument(0);  // type: oop
 6635   Node* src_offset  = argument(1);  // type: int
 6636   Node* dest        = argument(2);  // type: oop
 6637   Node* dest_offset = argument(3);  // type: int
 6638   Node* length      = argument(4);  // type: int
 6639 
 6640   uint new_idx = C->unique();
 6641 
 6642   // Check for allocation before we add nodes that would confuse
 6643   // tightly_coupled_allocation()
 6644   AllocateArrayNode* alloc = tightly_coupled_allocation(dest);
 6645 
 6646   int saved_reexecute_sp = -1;
 6647   JVMState* saved_jvms_before_guards = arraycopy_restore_alloc_state(alloc, saved_reexecute_sp);
 6648   // See arraycopy_restore_alloc_state() comment
 6649   // if alloc == null we don't have to worry about a tightly coupled allocation so we can emit all needed guards
 6650   // if saved_jvms_before_guards is not null (then alloc is not null) then we can handle guards and a tightly coupled allocation
 6651   // if saved_jvms_before_guards is null and alloc is not null, we can't emit any guards
 6652   bool can_emit_guards = (alloc == nullptr || saved_jvms_before_guards != nullptr);
 6653 
 6654   // The following tests must be performed
 6655   // (1) src and dest are arrays.
 6656   // (2) src and dest arrays must have elements of the same BasicType
 6657   // (3) src and dest must not be null.
 6658   // (4) src_offset must not be negative.
 6659   // (5) dest_offset must not be negative.
 6660   // (6) length must not be negative.
 6661   // (7) src_offset + length must not exceed length of src.
 6662   // (8) dest_offset + length must not exceed length of dest.
 6663   // (9) each element of an oop array must be assignable
 6664 
 6665   // (3) src and dest must not be null.
 6666   // always do this here because we need the JVM state for uncommon traps
 6667   Node* null_ctl = top();
 6668   src  = saved_jvms_before_guards != nullptr ? null_check_oop(src, &null_ctl, true, true) : null_check(src, T_ARRAY);
 6669   assert(null_ctl->is_top(), "no null control here");
 6670   dest = null_check(dest, T_ARRAY);
 6671 
 6672   if (!can_emit_guards) {
 6673     // if saved_jvms_before_guards is null and alloc is not null, we don't emit any
 6674     // guards but the arraycopy node could still take advantage of a
 6675     // tightly allocated allocation. tightly_coupled_allocation() is
 6676     // called again to make sure it takes the null check above into
 6677     // account: the null check is mandatory and if it caused an
 6678     // uncommon trap to be emitted then the allocation can't be
 6679     // considered tightly coupled in this context.
 6680     alloc = tightly_coupled_allocation(dest);
 6681   }
 6682 
 6683   bool validated = false;
 6684 
 6685   const Type* src_type  = _gvn.type(src);
 6686   const Type* dest_type = _gvn.type(dest);
 6687   const TypeAryPtr* top_src  = src_type->isa_aryptr();
 6688   const TypeAryPtr* top_dest = dest_type->isa_aryptr();
 6689 
 6690   // Do we have the type of src?
 6691   bool has_src = (top_src != nullptr && top_src->elem() != Type::BOTTOM);
 6692   // Do we have the type of dest?
 6693   bool has_dest = (top_dest != nullptr && top_dest->elem() != Type::BOTTOM);
 6694   // Is the type for src from speculation?
 6695   bool src_spec = false;
 6696   // Is the type for dest from speculation?
 6697   bool dest_spec = false;
 6698 
 6699   if ((!has_src || !has_dest) && can_emit_guards) {
 6700     // We don't have sufficient type information, let's see if
 6701     // speculative types can help. We need to have types for both src
 6702     // and dest so that it pays off.
 6703 
 6704     // Do we already have or could we have type information for src
 6705     bool could_have_src = has_src;
 6706     // Do we already have or could we have type information for dest
 6707     bool could_have_dest = has_dest;
 6708 
 6709     ciKlass* src_k = nullptr;
 6710     if (!has_src) {
 6711       src_k = src_type->speculative_type_not_null();
 6712       if (src_k != nullptr && src_k->is_array_klass()) {
 6713         could_have_src = true;
 6714       }
 6715     }
 6716 
 6717     ciKlass* dest_k = nullptr;
 6718     if (!has_dest) {
 6719       dest_k = dest_type->speculative_type_not_null();
 6720       if (dest_k != nullptr && dest_k->is_array_klass()) {
 6721         could_have_dest = true;
 6722       }
 6723     }
 6724 
 6725     if (could_have_src && could_have_dest) {
 6726       // This is going to pay off so emit the required guards
 6727       if (!has_src) {
 6728         src = maybe_cast_profiled_obj(src, src_k, true);
 6729         src_type  = _gvn.type(src);
 6730         top_src  = src_type->isa_aryptr();
 6731         has_src = (top_src != nullptr && top_src->elem() != Type::BOTTOM);
 6732         src_spec = true;
 6733       }
 6734       if (!has_dest) {
 6735         dest = maybe_cast_profiled_obj(dest, dest_k, true);
 6736         dest_type  = _gvn.type(dest);
 6737         top_dest  = dest_type->isa_aryptr();
 6738         has_dest = (top_dest != nullptr && top_dest->elem() != Type::BOTTOM);
 6739         dest_spec = true;
 6740       }
 6741     }
 6742   }
 6743 
 6744   if (has_src && has_dest && can_emit_guards) {
 6745     BasicType src_elem = top_src->isa_aryptr()->elem()->array_element_basic_type();
 6746     BasicType dest_elem = top_dest->isa_aryptr()->elem()->array_element_basic_type();
 6747     if (is_reference_type(src_elem, true)) src_elem = T_OBJECT;
 6748     if (is_reference_type(dest_elem, true)) dest_elem = T_OBJECT;
 6749 
 6750     if (src_elem == dest_elem && top_src->is_flat() == top_dest->is_flat() && src_elem == T_OBJECT) {
 6751       // If both arrays are object arrays then having the exact types
 6752       // for both will remove the need for a subtype check at runtime
 6753       // before the call and may make it possible to pick a faster copy
 6754       // routine (without a subtype check on every element)
 6755       // Do we have the exact type of src?
 6756       bool could_have_src = src_spec;
 6757       // Do we have the exact type of dest?
 6758       bool could_have_dest = dest_spec;
 6759       ciKlass* src_k = nullptr;
 6760       ciKlass* dest_k = nullptr;
 6761       if (!src_spec) {
 6762         src_k = src_type->speculative_type_not_null();
 6763         if (src_k != nullptr && src_k->is_array_klass()) {
 6764           could_have_src = true;
 6765         }
 6766       }
 6767       if (!dest_spec) {
 6768         dest_k = dest_type->speculative_type_not_null();
 6769         if (dest_k != nullptr && dest_k->is_array_klass()) {
 6770           could_have_dest = true;
 6771         }
 6772       }
 6773       if (could_have_src && could_have_dest) {
 6774         // If we can have both exact types, emit the missing guards
 6775         if (could_have_src && !src_spec) {
 6776           src = maybe_cast_profiled_obj(src, src_k, true);
 6777           src_type = _gvn.type(src);
 6778           top_src = src_type->isa_aryptr();
 6779         }
 6780         if (could_have_dest && !dest_spec) {
 6781           dest = maybe_cast_profiled_obj(dest, dest_k, true);
 6782           dest_type = _gvn.type(dest);
 6783           top_dest = dest_type->isa_aryptr();
 6784         }
 6785       }
 6786     }
 6787   }
 6788 
 6789   ciMethod* trap_method = method();
 6790   int trap_bci = bci();
 6791   if (saved_jvms_before_guards != nullptr) {
 6792     trap_method = alloc->jvms()->method();
 6793     trap_bci = alloc->jvms()->bci();
 6794   }
 6795 
 6796   bool negative_length_guard_generated = false;
 6797 
 6798   if (!C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_intrinsic) &&
 6799       can_emit_guards && !src->is_top() && !dest->is_top()) {
 6800     // validate arguments: enables transformation the ArrayCopyNode
 6801     validated = true;
 6802 
 6803     RegionNode* slow_region = new RegionNode(1);
 6804     record_for_igvn(slow_region);
 6805 
 6806     // (1) src and dest are arrays.
 6807     generate_non_array_guard(load_object_klass(src), slow_region, &src);
 6808     generate_non_array_guard(load_object_klass(dest), slow_region, &dest);
 6809 
 6810     // (2) src and dest arrays must have elements of the same BasicType
 6811     // done at macro expansion or at Ideal transformation time
 6812 
 6813     // (4) src_offset must not be negative.
 6814     generate_negative_guard(src_offset, slow_region);
 6815 
 6816     // (5) dest_offset must not be negative.
 6817     generate_negative_guard(dest_offset, slow_region);
 6818 
 6819     // (7) src_offset + length must not exceed length of src.
 6820     generate_limit_guard(src_offset, length,
 6821                          load_array_length(src),
 6822                          slow_region);
 6823 
 6824     // (8) dest_offset + length must not exceed length of dest.
 6825     generate_limit_guard(dest_offset, length,
 6826                          load_array_length(dest),
 6827                          slow_region);
 6828 
 6829     // (6) length must not be negative.
 6830     // This is also checked in generate_arraycopy() during macro expansion, but
 6831     // we also have to check it here for the case where the ArrayCopyNode will
 6832     // be eliminated by Escape Analysis.
 6833     if (EliminateAllocations) {
 6834       generate_negative_guard(length, slow_region);
 6835       negative_length_guard_generated = true;
 6836     }
 6837 
 6838     // (9) each element of an oop array must be assignable
 6839     Node* dest_klass = load_object_klass(dest);
 6840     Node* refined_dest_klass = dest_klass;
 6841     if (src != dest) {
 6842       dest_klass = load_non_refined_array_klass(refined_dest_klass);
 6843       Node* not_subtype_ctrl = gen_subtype_check(src, dest_klass);
 6844       slow_region->add_req(not_subtype_ctrl);
 6845     }
 6846 
 6847     // TODO 8251971 Improve this. What about atomicity? Make sure this is always folded for type arrays.
 6848     // If destination is null-restricted, source must be null-restricted as well: src_null_restricted || !dst_null_restricted
 6849     Node* src_klass = load_object_klass(src);
 6850     Node* adr_prop_src = basic_plus_adr(top(), src_klass, in_bytes(ArrayKlass::properties_offset()));
 6851     Node* prop_src = _gvn.transform(LoadNode::make(_gvn, control(), immutable_memory(), adr_prop_src,
 6852                                                    _gvn.type(adr_prop_src)->is_ptr(), TypeInt::INT, T_INT,
 6853                                                    MemNode::unordered));
 6854     Node* adr_prop_dest = basic_plus_adr(top(), refined_dest_klass, in_bytes(ArrayKlass::properties_offset()));
 6855     Node* prop_dest = _gvn.transform(LoadNode::make(_gvn, control(), immutable_memory(), adr_prop_dest,
 6856                                                     _gvn.type(adr_prop_dest)->is_ptr(), TypeInt::INT, T_INT,
 6857                                                     MemNode::unordered));
 6858 
 6859     const ArrayProperties props_null_restricted = ArrayProperties::Default().with_null_restricted();
 6860     jint props_value = (jint)props_null_restricted.value();
 6861 
 6862     prop_dest = _gvn.transform(new XorINode(prop_dest, intcon(props_value)));
 6863     prop_src = _gvn.transform(new OrINode(prop_dest, prop_src));
 6864     prop_src = _gvn.transform(new AndINode(prop_src, intcon(props_value)));
 6865 
 6866     Node* chk = _gvn.transform(new CmpINode(prop_src, intcon(props_value)));
 6867     Node* tst = _gvn.transform(new BoolNode(chk, BoolTest::ne));
 6868     generate_fair_guard(tst, slow_region);
 6869 
 6870     // TODO 8251971 This is too strong
 6871     generate_fair_guard(flat_array_test(src), slow_region);
 6872     generate_fair_guard(flat_array_test(dest), slow_region);
 6873 
 6874     {
 6875       PreserveJVMState pjvms(this);
 6876       set_control(_gvn.transform(slow_region));
 6877       uncommon_trap(Deoptimization::Reason_intrinsic,
 6878                     Deoptimization::Action_make_not_entrant);
 6879       assert(stopped(), "Should be stopped");
 6880     }
 6881 
 6882     const TypeKlassPtr* dest_klass_t = _gvn.type(dest_klass)->isa_klassptr();
 6883     if (dest_klass_t == nullptr) {
 6884       // refined_dest_klass may not be an array, which leads to dest_klass being top. This means we
 6885       // are in a dead path.
 6886       uncommon_trap(Deoptimization::Reason_intrinsic,
 6887                     Deoptimization::Action_make_not_entrant);
 6888       return true;
 6889     }
 6890 
 6891     const Type* toop = dest_klass_t->as_subtype_instance_type();
 6892     src = _gvn.transform(new CheckCastPPNode(control(), src, toop));
 6893     arraycopy_move_allocation_here(alloc, dest, saved_jvms_before_guards, saved_reexecute_sp, new_idx);
 6894   }
 6895 
 6896   if (stopped()) {
 6897     return true;
 6898   }
 6899 
 6900   Node* dest_klass = load_object_klass(dest);
 6901   dest_klass = load_non_refined_array_klass(dest_klass);
 6902 
 6903   ArrayCopyNode* ac = ArrayCopyNode::make(this, true, src, src_offset, dest, dest_offset, length, alloc != nullptr, negative_length_guard_generated,
 6904                                           // Create LoadRange and LoadKlass nodes for use during macro expansion here
 6905                                           // so the compiler has a chance to eliminate them: during macro expansion,
 6906                                           // we have to set their control (CastPP nodes are eliminated).
 6907                                           load_object_klass(src), dest_klass,
 6908                                           load_array_length(src), load_array_length(dest));
 6909 
 6910   ac->set_arraycopy(validated);
 6911 
 6912   Node* n = _gvn.transform(ac);
 6913   if (n == ac) {
 6914     ac->connect_outputs(this);
 6915   } else {
 6916     assert(validated, "shouldn't transform if all arguments not validated");
 6917     set_all_memory(n);
 6918   }
 6919   clear_upper_avx();
 6920 
 6921 
 6922   return true;
 6923 }
 6924 
 6925 
 6926 // Helper function which determines if an arraycopy immediately follows
 6927 // an allocation, with no intervening tests or other escapes for the object.
 6928 AllocateArrayNode*
 6929 LibraryCallKit::tightly_coupled_allocation(Node* ptr) {
 6930   if (stopped())             return nullptr;  // no fast path
 6931   if (!C->do_aliasing())     return nullptr;  // no MergeMems around
 6932 
 6933   AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(ptr);
 6934   if (alloc == nullptr)  return nullptr;
 6935 
 6936   Node* rawmem = memory(Compile::AliasIdxRaw);
 6937   // Is the allocation's memory state untouched?
 6938   if (!(rawmem->is_Proj() && rawmem->in(0)->is_Initialize())) {
 6939     // Bail out if there have been raw-memory effects since the allocation.
 6940     // (Example:  There might have been a call or safepoint.)
 6941     return nullptr;
 6942   }
 6943   rawmem = rawmem->in(0)->as_Initialize()->memory(Compile::AliasIdxRaw);
 6944   if (!(rawmem->is_Proj() && rawmem->in(0) == alloc)) {
 6945     return nullptr;
 6946   }
 6947 
 6948   // There must be no unexpected observers of this allocation.
 6949   for (DUIterator_Fast imax, i = ptr->fast_outs(imax); i < imax; i++) {
 6950     Node* obs = ptr->fast_out(i);
 6951     if (obs != this->map()) {
 6952       return nullptr;
 6953     }
 6954   }
 6955 
 6956   // This arraycopy must unconditionally follow the allocation of the ptr.
 6957   Node* alloc_ctl = ptr->in(0);
 6958   Node* ctl = control();
 6959   while (ctl != alloc_ctl) {
 6960     // There may be guards which feed into the slow_region.
 6961     // Any other control flow means that we might not get a chance
 6962     // to finish initializing the allocated object.
 6963     // Various low-level checks bottom out in uncommon traps. These
 6964     // are considered safe since we've already checked above that
 6965     // there is no unexpected observer of this allocation.
 6966     if (get_uncommon_trap_from_success_proj(ctl) != nullptr) {
 6967       assert(ctl->in(0)->is_If(), "must be If");
 6968       ctl = ctl->in(0)->in(0);
 6969     } else {
 6970       return nullptr;
 6971     }
 6972   }
 6973 
 6974   // If we get this far, we have an allocation which immediately
 6975   // precedes the arraycopy, and we can take over zeroing the new object.
 6976   // The arraycopy will finish the initialization, and provide
 6977   // a new control state to which we will anchor the destination pointer.
 6978 
 6979   return alloc;
 6980 }
 6981 
 6982 CallStaticJavaNode* LibraryCallKit::get_uncommon_trap_from_success_proj(Node* node) {
 6983   if (node->is_IfProj()) {
 6984     IfProjNode* other_proj = node->as_IfProj()->other_if_proj();
 6985     for (DUIterator_Fast jmax, j = other_proj->fast_outs(jmax); j < jmax; j++) {
 6986       Node* obs = other_proj->fast_out(j);
 6987       if (obs->in(0) == other_proj && obs->is_CallStaticJava() &&
 6988           (obs->as_CallStaticJava()->entry_point() == OptoRuntime::uncommon_trap_blob()->entry_point())) {
 6989         return obs->as_CallStaticJava();
 6990       }
 6991     }
 6992   }
 6993   return nullptr;
 6994 }
 6995 
 6996 //-------------inline_encodeISOArray-----------------------------------
 6997 // int sun.nio.cs.ISO_8859_1.Encoder#encodeISOArray0(byte[] sa, int sp, byte[] da, int dp, int len)
 6998 // int java.lang.StringCoding#encodeISOArray0(byte[] sa, int sp, byte[] da, int dp, int len)
 6999 // int java.lang.StringCoding#encodeAsciiArray0(char[] sa, int sp, byte[] da, int dp, int len)
 7000 // encode char[] to byte[] in ISO_8859_1 or ASCII
 7001 bool LibraryCallKit::inline_encodeISOArray(bool ascii) {
 7002   assert(callee()->signature()->size() == 5, "encodeISOArray has 5 parameters");
 7003   // no receiver since it is static method
 7004   Node *src         = argument(0);
 7005   Node *src_offset  = argument(1);
 7006   Node *dst         = argument(2);
 7007   Node *dst_offset  = argument(3);
 7008   Node *length      = argument(4);
 7009 
 7010   // Cast source & target arrays to not-null
 7011   src = must_be_not_null(src, true);
 7012   dst = must_be_not_null(dst, true);
 7013   if (stopped()) {
 7014     return true;
 7015   }
 7016 
 7017   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
 7018   const TypeAryPtr* dst_type = dst->Value(&_gvn)->isa_aryptr();
 7019   if (src_type == nullptr || src_type->elem() == Type::BOTTOM ||
 7020       dst_type == nullptr || dst_type->elem() == Type::BOTTOM) {
 7021     // failed array check
 7022     return false;
 7023   }
 7024 
 7025   // Figure out the size and type of the elements we will be copying.
 7026   BasicType src_elem = src_type->elem()->array_element_basic_type();
 7027   BasicType dst_elem = dst_type->elem()->array_element_basic_type();
 7028   if (!((src_elem == T_CHAR) || (src_elem== T_BYTE)) || dst_elem != T_BYTE) {
 7029     return false;
 7030   }
 7031 
 7032   // Check source & target bounds
 7033   RegionNode* bailout = create_bailout();
 7034   generate_string_range_check(src, src_offset, length, src_elem == T_BYTE, bailout);
 7035   generate_string_range_check(dst, dst_offset, length, false, bailout);
 7036   if (check_bailout(bailout)) {
 7037     return true;
 7038   }
 7039 
 7040   Node* src_start = array_element_address(src, src_offset, T_CHAR);
 7041   Node* dst_start = array_element_address(dst, dst_offset, dst_elem);
 7042   // 'src_start' points to src array + scaled offset
 7043   // 'dst_start' points to dst array + scaled offset
 7044 
 7045   // See GraphKit::compress_string
 7046   const TypePtr* adr_type;
 7047   Node* mem = capture_memory(adr_type, src_type, dst_type);
 7048   Node* enc = new EncodeISOArrayNode(control(), mem, adr_type, src_start, dst_start, length, ascii);
 7049   enc = _gvn.transform(enc);
 7050   Node* res_mem = _gvn.transform(new SCMemProjNode(enc));
 7051   memory_effect(res_mem, src_type, dst_type);
 7052 
 7053   set_result(enc);
 7054   clear_upper_avx();
 7055 
 7056   return true;
 7057 }
 7058 
 7059 //-------------inline_multiplyToLen-----------------------------------
 7060 bool LibraryCallKit::inline_multiplyToLen() {
 7061   assert(UseMultiplyToLenIntrinsic, "not implemented on this platform");
 7062 
 7063   address stubAddr = StubRoutines::multiplyToLen();
 7064   if (stubAddr == nullptr) {
 7065     return false; // Intrinsic's stub is not implemented on this platform
 7066   }
 7067   const char* stubName = "multiplyToLen";
 7068 
 7069   assert(callee()->signature()->size() == 5, "multiplyToLen has 5 parameters");
 7070 
 7071   // no receiver because it is a static method
 7072   Node* x    = argument(0);
 7073   Node* xlen = argument(1);
 7074   Node* y    = argument(2);
 7075   Node* ylen = argument(3);
 7076   Node* z    = argument(4);
 7077 
 7078   x = must_be_not_null(x, true);
 7079   y = must_be_not_null(y, true);
 7080 
 7081   const TypeAryPtr* x_type = x->Value(&_gvn)->isa_aryptr();
 7082   const TypeAryPtr* y_type = y->Value(&_gvn)->isa_aryptr();
 7083   if (x_type == nullptr || x_type->elem() == Type::BOTTOM ||
 7084       y_type == nullptr || y_type->elem() == Type::BOTTOM) {
 7085     // failed array check
 7086     return false;
 7087   }
 7088 
 7089   BasicType x_elem = x_type->elem()->array_element_basic_type();
 7090   BasicType y_elem = y_type->elem()->array_element_basic_type();
 7091   if (x_elem != T_INT || y_elem != T_INT) {
 7092     return false;
 7093   }
 7094 
 7095   Node* x_start = array_element_address(x, intcon(0), x_elem);
 7096   Node* y_start = array_element_address(y, intcon(0), y_elem);
 7097   // 'x_start' points to x array + scaled xlen
 7098   // 'y_start' points to y array + scaled ylen
 7099 
 7100   Node* z_start = array_element_address(z, intcon(0), T_INT);
 7101 
 7102   Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
 7103                                  OptoRuntime::multiplyToLen_Type(),
 7104                                  stubAddr, stubName, TypePtr::BOTTOM,
 7105                                  x_start, xlen, y_start, ylen, z_start);
 7106 
 7107   C->set_has_split_ifs(true); // Has chance for split-if optimization
 7108   set_result(z);
 7109   return true;
 7110 }
 7111 
 7112 //-------------inline_squareToLen------------------------------------
 7113 bool LibraryCallKit::inline_squareToLen() {
 7114   assert(UseSquareToLenIntrinsic, "not implemented on this platform");
 7115 
 7116   address stubAddr = StubRoutines::squareToLen();
 7117   if (stubAddr == nullptr) {
 7118     return false; // Intrinsic's stub is not implemented on this platform
 7119   }
 7120   const char* stubName = "squareToLen";
 7121 
 7122   assert(callee()->signature()->size() == 4, "implSquareToLen has 4 parameters");
 7123 
 7124   Node* x    = argument(0);
 7125   Node* len  = argument(1);
 7126   Node* z    = argument(2);
 7127   Node* zlen = argument(3);
 7128 
 7129   x = must_be_not_null(x, true);
 7130   z = must_be_not_null(z, true);
 7131 
 7132   const TypeAryPtr* x_type = x->Value(&_gvn)->isa_aryptr();
 7133   const TypeAryPtr* z_type = z->Value(&_gvn)->isa_aryptr();
 7134   if (x_type == nullptr || x_type->elem() == Type::BOTTOM ||
 7135       z_type == nullptr || z_type->elem() == Type::BOTTOM) {
 7136     // failed array check
 7137     return false;
 7138   }
 7139 
 7140   BasicType x_elem = x_type->elem()->array_element_basic_type();
 7141   BasicType z_elem = z_type->elem()->array_element_basic_type();
 7142   if (x_elem != T_INT || z_elem != T_INT) {
 7143     return false;
 7144   }
 7145 
 7146 
 7147   Node* x_start = array_element_address(x, intcon(0), x_elem);
 7148   Node* z_start = array_element_address(z, intcon(0), z_elem);
 7149 
 7150   Node*  call = make_runtime_call(RC_LEAF|RC_NO_FP,
 7151                                   OptoRuntime::squareToLen_Type(),
 7152                                   stubAddr, stubName, TypePtr::BOTTOM,
 7153                                   x_start, len, z_start, zlen);
 7154 
 7155   set_result(z);
 7156   return true;
 7157 }
 7158 
 7159 //-------------inline_mulAdd------------------------------------------
 7160 bool LibraryCallKit::inline_mulAdd() {
 7161   assert(UseMulAddIntrinsic, "not implemented on this platform");
 7162 
 7163   address stubAddr = StubRoutines::mulAdd();
 7164   if (stubAddr == nullptr) {
 7165     return false; // Intrinsic's stub is not implemented on this platform
 7166   }
 7167   const char* stubName = "mulAdd";
 7168 
 7169   assert(callee()->signature()->size() == 5, "mulAdd has 5 parameters");
 7170 
 7171   Node* out      = argument(0);
 7172   Node* in       = argument(1);
 7173   Node* offset   = argument(2);
 7174   Node* len      = argument(3);
 7175   Node* k        = argument(4);
 7176 
 7177   in = must_be_not_null(in, true);
 7178   out = must_be_not_null(out, true);
 7179 
 7180   const TypeAryPtr* out_type = out->Value(&_gvn)->isa_aryptr();
 7181   const TypeAryPtr* in_type = in->Value(&_gvn)->isa_aryptr();
 7182   if (out_type == nullptr || out_type->elem() == Type::BOTTOM ||
 7183        in_type == nullptr ||  in_type->elem() == Type::BOTTOM) {
 7184     // failed array check
 7185     return false;
 7186   }
 7187 
 7188   BasicType out_elem = out_type->elem()->array_element_basic_type();
 7189   BasicType in_elem = in_type->elem()->array_element_basic_type();
 7190   if (out_elem != T_INT || in_elem != T_INT) {
 7191     return false;
 7192   }
 7193 
 7194   Node* outlen = load_array_length(out);
 7195   Node* new_offset = _gvn.transform(new SubINode(outlen, offset));
 7196   Node* out_start = array_element_address(out, intcon(0), out_elem);
 7197   Node* in_start = array_element_address(in, intcon(0), in_elem);
 7198 
 7199   Node*  call = make_runtime_call(RC_LEAF|RC_NO_FP,
 7200                                   OptoRuntime::mulAdd_Type(),
 7201                                   stubAddr, stubName, TypePtr::BOTTOM,
 7202                                   out_start,in_start, new_offset, len, k);
 7203   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
 7204   set_result(result);
 7205   return true;
 7206 }
 7207 
 7208 //-------------inline_montgomeryMultiply-----------------------------------
 7209 bool LibraryCallKit::inline_montgomeryMultiply() {
 7210   address stubAddr = StubRoutines::montgomeryMultiply();
 7211   if (stubAddr == nullptr) {
 7212     return false; // Intrinsic's stub is not implemented on this platform
 7213   }
 7214 
 7215   assert(UseMontgomeryMultiplyIntrinsic, "not implemented on this platform");
 7216   const char* stubName = "montgomery_multiply";
 7217 
 7218   assert(callee()->signature()->size() == 7, "montgomeryMultiply has 7 parameters");
 7219 
 7220   Node* a    = argument(0);
 7221   Node* b    = argument(1);
 7222   Node* n    = argument(2);
 7223   Node* len  = argument(3);
 7224   Node* inv  = argument(4);
 7225   Node* m    = argument(6);
 7226 
 7227   const TypeAryPtr* a_type = a->Value(&_gvn)->isa_aryptr();
 7228   const TypeAryPtr* b_type = b->Value(&_gvn)->isa_aryptr();
 7229   const TypeAryPtr* n_type = n->Value(&_gvn)->isa_aryptr();
 7230   const TypeAryPtr* m_type = m->Value(&_gvn)->isa_aryptr();
 7231   if (a_type == nullptr || a_type->elem() == Type::BOTTOM ||
 7232       b_type == nullptr || b_type->elem() == Type::BOTTOM ||
 7233       n_type == nullptr || n_type->elem() == Type::BOTTOM ||
 7234       m_type == nullptr || m_type->elem() == Type::BOTTOM) {
 7235     // failed array check
 7236     return false;
 7237   }
 7238 
 7239   BasicType a_elem = a_type->elem()->array_element_basic_type();
 7240   BasicType b_elem = b_type->elem()->array_element_basic_type();
 7241   BasicType n_elem = n_type->elem()->array_element_basic_type();
 7242   BasicType m_elem = m_type->elem()->array_element_basic_type();
 7243   if (a_elem != T_INT || b_elem != T_INT || n_elem != T_INT || m_elem != T_INT) {
 7244     return false;
 7245   }
 7246 
 7247   // Make the call
 7248   {
 7249     Node* a_start = array_element_address(a, intcon(0), a_elem);
 7250     Node* b_start = array_element_address(b, intcon(0), b_elem);
 7251     Node* n_start = array_element_address(n, intcon(0), n_elem);
 7252     Node* m_start = array_element_address(m, intcon(0), m_elem);
 7253 
 7254     Node* call = make_runtime_call(RC_LEAF,
 7255                                    OptoRuntime::montgomeryMultiply_Type(),
 7256                                    stubAddr, stubName, TypePtr::BOTTOM,
 7257                                    a_start, b_start, n_start, len, inv, top(),
 7258                                    m_start);
 7259     set_result(m);
 7260   }
 7261 
 7262   return true;
 7263 }
 7264 
 7265 bool LibraryCallKit::inline_montgomerySquare() {
 7266   address stubAddr = StubRoutines::montgomerySquare();
 7267   if (stubAddr == nullptr) {
 7268     return false; // Intrinsic's stub is not implemented on this platform
 7269   }
 7270 
 7271   assert(UseMontgomerySquareIntrinsic, "not implemented on this platform");
 7272   const char* stubName = "montgomery_square";
 7273 
 7274   assert(callee()->signature()->size() == 6, "montgomerySquare has 6 parameters");
 7275 
 7276   Node* a    = argument(0);
 7277   Node* n    = argument(1);
 7278   Node* len  = argument(2);
 7279   Node* inv  = argument(3);
 7280   Node* m    = argument(5);
 7281 
 7282   const TypeAryPtr* a_type = a->Value(&_gvn)->isa_aryptr();
 7283   const TypeAryPtr* n_type = n->Value(&_gvn)->isa_aryptr();
 7284   const TypeAryPtr* m_type = m->Value(&_gvn)->isa_aryptr();
 7285   if (a_type == nullptr || a_type->elem() == Type::BOTTOM ||
 7286       n_type == nullptr || n_type->elem() == Type::BOTTOM ||
 7287       m_type == nullptr || m_type->elem() == Type::BOTTOM) {
 7288     // failed array check
 7289     return false;
 7290   }
 7291 
 7292   BasicType a_elem = a_type->elem()->array_element_basic_type();
 7293   BasicType n_elem = n_type->elem()->array_element_basic_type();
 7294   BasicType m_elem = m_type->elem()->array_element_basic_type();
 7295   if (a_elem != T_INT || n_elem != T_INT || m_elem != T_INT) {
 7296     return false;
 7297   }
 7298 
 7299   // Make the call
 7300   {
 7301     Node* a_start = array_element_address(a, intcon(0), a_elem);
 7302     Node* n_start = array_element_address(n, intcon(0), n_elem);
 7303     Node* m_start = array_element_address(m, intcon(0), m_elem);
 7304 
 7305     Node* call = make_runtime_call(RC_LEAF,
 7306                                    OptoRuntime::montgomerySquare_Type(),
 7307                                    stubAddr, stubName, TypePtr::BOTTOM,
 7308                                    a_start, n_start, len, inv, top(),
 7309                                    m_start);
 7310     set_result(m);
 7311   }
 7312 
 7313   return true;
 7314 }
 7315 
 7316 bool LibraryCallKit::inline_bigIntegerShift(bool isRightShift) {
 7317   address stubAddr = nullptr;
 7318   const char* stubName = nullptr;
 7319 
 7320   stubAddr = isRightShift? StubRoutines::bigIntegerRightShift(): StubRoutines::bigIntegerLeftShift();
 7321   if (stubAddr == nullptr) {
 7322     return false; // Intrinsic's stub is not implemented on this platform
 7323   }
 7324 
 7325   stubName = isRightShift? "bigIntegerRightShiftWorker" : "bigIntegerLeftShiftWorker";
 7326 
 7327   assert(callee()->signature()->size() == 5, "expected 5 arguments");
 7328 
 7329   Node* newArr = argument(0);
 7330   Node* oldArr = argument(1);
 7331   Node* newIdx = argument(2);
 7332   Node* shiftCount = argument(3);
 7333   Node* numIter = argument(4);
 7334 
 7335   const TypeAryPtr* newArr_type = newArr->Value(&_gvn)->isa_aryptr();
 7336   const TypeAryPtr* oldArr_type = oldArr->Value(&_gvn)->isa_aryptr();
 7337   if (newArr_type == nullptr || newArr_type->elem() == Type::BOTTOM ||
 7338       oldArr_type == nullptr || oldArr_type->elem() == Type::BOTTOM) {
 7339     return false;
 7340   }
 7341 
 7342   BasicType newArr_elem = newArr_type->elem()->array_element_basic_type();
 7343   BasicType oldArr_elem = oldArr_type->elem()->array_element_basic_type();
 7344   if (newArr_elem != T_INT || oldArr_elem != T_INT) {
 7345     return false;
 7346   }
 7347 
 7348   // Make the call
 7349   {
 7350     Node* newArr_start = array_element_address(newArr, intcon(0), newArr_elem);
 7351     Node* oldArr_start = array_element_address(oldArr, intcon(0), oldArr_elem);
 7352 
 7353     Node* call = make_runtime_call(RC_LEAF,
 7354                                    OptoRuntime::bigIntegerShift_Type(),
 7355                                    stubAddr,
 7356                                    stubName,
 7357                                    TypePtr::BOTTOM,
 7358                                    newArr_start,
 7359                                    oldArr_start,
 7360                                    newIdx,
 7361                                    shiftCount,
 7362                                    numIter);
 7363   }
 7364 
 7365   return true;
 7366 }
 7367 
 7368 //-------------inline_vectorizedMismatch------------------------------
 7369 bool LibraryCallKit::inline_vectorizedMismatch() {
 7370   assert(UseVectorizedMismatchIntrinsic, "not implemented on this platform");
 7371 
 7372   assert(callee()->signature()->size() == 8, "vectorizedMismatch has 6 parameters");
 7373   Node* obja    = argument(0); // Object
 7374   Node* aoffset = argument(1); // long
 7375   Node* objb    = argument(3); // Object
 7376   Node* boffset = argument(4); // long
 7377   Node* length  = argument(6); // int
 7378   Node* scale   = argument(7); // int
 7379 
 7380   const TypeAryPtr* obja_t = _gvn.type(obja)->isa_aryptr();
 7381   const TypeAryPtr* objb_t = _gvn.type(objb)->isa_aryptr();
 7382   if (obja_t == nullptr || obja_t->elem() == Type::BOTTOM ||
 7383       objb_t == nullptr || objb_t->elem() == Type::BOTTOM ||
 7384       scale == top()) {
 7385     return false; // failed input validation
 7386   }
 7387 
 7388   Node* obja_adr = make_unsafe_address(obja, aoffset);
 7389   Node* objb_adr = make_unsafe_address(objb, boffset);
 7390 
 7391   // Partial inlining handling for inputs smaller than ArrayOperationPartialInlineSize bytes in size.
 7392   //
 7393   //    inline_limit = ArrayOperationPartialInlineSize / element_size;
 7394   //    if (length <= inline_limit) {
 7395   //      inline_path:
 7396   //        vmask   = VectorMaskGen length
 7397   //        vload1  = LoadVectorMasked obja, vmask
 7398   //        vload2  = LoadVectorMasked objb, vmask
 7399   //        result1 = VectorCmpMasked vload1, vload2, vmask
 7400   //    } else {
 7401   //      call_stub_path:
 7402   //        result2 = call vectorizedMismatch_stub(obja, objb, length, scale)
 7403   //    }
 7404   //    exit_block:
 7405   //      return Phi(result1, result2);
 7406   //
 7407   enum { inline_path = 1,  // input is small enough to process it all at once
 7408          stub_path   = 2,  // input is too large; call into the VM
 7409          PATH_LIMIT  = 3
 7410   };
 7411 
 7412   Node* exit_block = new RegionNode(PATH_LIMIT);
 7413   Node* result_phi = new PhiNode(exit_block, TypeInt::INT);
 7414   Node* memory_phi = new PhiNode(exit_block, Type::MEMORY, TypePtr::BOTTOM);
 7415 
 7416   Node* call_stub_path = control();
 7417 
 7418   BasicType elem_bt = T_ILLEGAL;
 7419 
 7420   const TypeInt* scale_t = _gvn.type(scale)->is_int();
 7421   if (scale_t->is_con()) {
 7422     switch (scale_t->get_con()) {
 7423       case 0: elem_bt = T_BYTE;  break;
 7424       case 1: elem_bt = T_SHORT; break;
 7425       case 2: elem_bt = T_INT;   break;
 7426       case 3: elem_bt = T_LONG;  break;
 7427 
 7428       default: elem_bt = T_ILLEGAL; break; // not supported
 7429     }
 7430   }
 7431 
 7432   int inline_limit = 0;
 7433   bool do_partial_inline = false;
 7434 
 7435   if (elem_bt != T_ILLEGAL && ArrayOperationPartialInlineSize > 0) {
 7436     inline_limit = ArrayOperationPartialInlineSize / type2aelembytes(elem_bt);
 7437     do_partial_inline = inline_limit >= 16;
 7438   }
 7439 
 7440   if (do_partial_inline) {
 7441     assert(elem_bt != T_ILLEGAL, "sanity");
 7442 
 7443     if (Matcher::match_rule_supported_vector(Op_VectorMaskGen,    inline_limit, elem_bt) &&
 7444         Matcher::match_rule_supported_vector(Op_LoadVectorMasked, inline_limit, elem_bt) &&
 7445         Matcher::match_rule_supported_vector(Op_VectorCmpMasked,  inline_limit, elem_bt)) {
 7446 
 7447       const TypeVect* vt = TypeVect::make(elem_bt, inline_limit);
 7448       Node* cmp_length = _gvn.transform(new CmpINode(length, intcon(inline_limit)));
 7449       Node* bol_gt     = _gvn.transform(new BoolNode(cmp_length, BoolTest::gt));
 7450 
 7451       call_stub_path = generate_guard(bol_gt, nullptr, PROB_MIN);
 7452 
 7453       if (!stopped()) {
 7454         Node* casted_length = _gvn.transform(new CastIINode(control(), length, TypeInt::make(0, inline_limit, Type::WidenMin)));
 7455 
 7456         const TypePtr* obja_adr_t = _gvn.type(obja_adr)->isa_ptr();
 7457         const TypePtr* objb_adr_t = _gvn.type(objb_adr)->isa_ptr();
 7458         Node* obja_adr_mem = memory(C->get_alias_index(obja_adr_t));
 7459         Node* objb_adr_mem = memory(C->get_alias_index(objb_adr_t));
 7460 
 7461         Node* vmask      = _gvn.transform(VectorMaskGenNode::make(ConvI2X(casted_length), elem_bt));
 7462         Node* vload_obja = _gvn.transform(new LoadVectorMaskedNode(control(), obja_adr_mem, obja_adr, obja_adr_t, vt, vmask));
 7463         Node* vload_objb = _gvn.transform(new LoadVectorMaskedNode(control(), objb_adr_mem, objb_adr, objb_adr_t, vt, vmask));
 7464         Node* result     = _gvn.transform(new VectorCmpMaskedNode(vload_obja, vload_objb, vmask, TypeInt::INT));
 7465 
 7466         exit_block->init_req(inline_path, control());
 7467         memory_phi->init_req(inline_path, map()->memory());
 7468         result_phi->init_req(inline_path, result);
 7469 
 7470         C->set_max_vector_size(MAX2((uint)ArrayOperationPartialInlineSize, C->max_vector_size()));
 7471         clear_upper_avx();
 7472       }
 7473     }
 7474   }
 7475 
 7476   if (call_stub_path != nullptr) {
 7477     set_control(call_stub_path);
 7478 
 7479     Node* call = make_runtime_call(RC_LEAF,
 7480                                    OptoRuntime::vectorizedMismatch_Type(),
 7481                                    StubRoutines::vectorizedMismatch(), "vectorizedMismatch", TypePtr::BOTTOM,
 7482                                    obja_adr, objb_adr, length, scale);
 7483 
 7484     exit_block->init_req(stub_path, control());
 7485     memory_phi->init_req(stub_path, map()->memory());
 7486     result_phi->init_req(stub_path, _gvn.transform(new ProjNode(call, TypeFunc::Parms)));
 7487   }
 7488 
 7489   exit_block = _gvn.transform(exit_block);
 7490   memory_phi = _gvn.transform(memory_phi);
 7491   result_phi = _gvn.transform(result_phi);
 7492 
 7493   record_for_igvn(exit_block);
 7494   record_for_igvn(memory_phi);
 7495   record_for_igvn(result_phi);
 7496 
 7497   set_control(exit_block);
 7498   set_all_memory(memory_phi);
 7499   set_result(result_phi);
 7500 
 7501   return true;
 7502 }
 7503 
 7504 //------------------------------inline_vectorizedHashcode----------------------------
 7505 bool LibraryCallKit::inline_vectorizedHashCode() {
 7506   assert(UseVectorizedHashCodeIntrinsic, "not implemented on this platform");
 7507 
 7508   assert(callee()->signature()->size() == 5, "vectorizedHashCode has 5 parameters");
 7509   Node* array          = argument(0);
 7510   Node* offset         = argument(1);
 7511   Node* length         = argument(2);
 7512   Node* initialValue   = argument(3);
 7513   Node* basic_type     = argument(4);
 7514 
 7515   if (basic_type == top()) {
 7516     return false; // failed input validation
 7517   }
 7518 
 7519   const TypeInt* basic_type_t = _gvn.type(basic_type)->is_int();
 7520   if (!basic_type_t->is_con()) {
 7521     return false; // Only intrinsify if mode argument is constant
 7522   }
 7523 
 7524   array = must_be_not_null(array, true);
 7525 
 7526   BasicType bt = (BasicType)basic_type_t->get_con();
 7527 
 7528   // Resolve address of first element
 7529   Node* array_start = array_element_address(array, offset, bt);
 7530 
 7531   const TypeAryPtr* in_adr_type = TypeAryPtr::get_array_body_type(bt);
 7532   set_result(_gvn.transform(new VectorizedHashCodeNode(control(), memory(in_adr_type), in_adr_type,
 7533     array_start, length, initialValue, basic_type)));
 7534   clear_upper_avx();
 7535 
 7536   return true;
 7537 }
 7538 
 7539 /**
 7540  * Calculate CRC32 for byte.
 7541  * int java.util.zip.CRC32.update(int crc, int b)
 7542  */
 7543 bool LibraryCallKit::inline_updateCRC32() {
 7544   assert(UseCRC32Intrinsics, "need AVX and CLMUL instructions support");
 7545   assert(callee()->signature()->size() == 2, "update has 2 parameters");
 7546   // no receiver since it is static method
 7547   Node* crc  = argument(0); // type: int
 7548   Node* b    = argument(1); // type: int
 7549 
 7550   /*
 7551    *    int c = ~ crc;
 7552    *    b = timesXtoThe32[(b ^ c) & 0xFF];
 7553    *    b = b ^ (c >>> 8);
 7554    *    crc = ~b;
 7555    */
 7556 
 7557   Node* M1 = intcon(-1);
 7558   crc = _gvn.transform(new XorINode(crc, M1));
 7559   Node* result = _gvn.transform(new XorINode(crc, b));
 7560   result = _gvn.transform(new AndINode(result, intcon(0xFF)));
 7561 
 7562   Node* base = makecon(TypeRawPtr::make(StubRoutines::crc_table_addr()));
 7563   Node* offset = _gvn.transform(new LShiftINode(result, intcon(0x2)));
 7564   Node* adr = off_heap_plus_addr(base, ConvI2X(offset));
 7565   result = make_load(control(), adr, TypeInt::INT, T_INT, MemNode::unordered);
 7566 
 7567   crc = _gvn.transform(new URShiftINode(crc, intcon(8)));
 7568   result = _gvn.transform(new XorINode(crc, result));
 7569   result = _gvn.transform(new XorINode(result, M1));
 7570   set_result(result);
 7571   return true;
 7572 }
 7573 
 7574 /**
 7575  * Calculate CRC32 for byte[] array.
 7576  * int java.util.zip.CRC32.updateBytes(int crc, byte[] buf, int off, int len)
 7577  */
 7578 bool LibraryCallKit::inline_updateBytesCRC32() {
 7579   assert(UseCRC32Intrinsics, "need AVX and CLMUL instructions support");
 7580   assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
 7581   // no receiver since it is static method
 7582   Node* crc     = argument(0); // type: int
 7583   Node* src     = argument(1); // type: oop
 7584   Node* offset  = argument(2); // type: int
 7585   Node* length  = argument(3); // type: int
 7586 
 7587   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
 7588   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
 7589     // failed array check
 7590     return false;
 7591   }
 7592 
 7593   // Figure out the size and type of the elements we will be copying.
 7594   BasicType src_elem = src_type->elem()->array_element_basic_type();
 7595   if (src_elem != T_BYTE) {
 7596     return false;
 7597   }
 7598 
 7599   // 'src_start' points to src array + scaled offset
 7600   src = must_be_not_null(src, true);
 7601   Node* src_start = array_element_address(src, offset, src_elem);
 7602 
 7603   // We assume that range check is done by caller.
 7604   // TODO: generate range check (offset+length < src.length) in debug VM.
 7605 
 7606   // Call the stub.
 7607   address stubAddr = StubRoutines::updateBytesCRC32();
 7608   const char *stubName = "updateBytesCRC32";
 7609 
 7610   Node* call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::updateBytesCRC32_Type(),
 7611                                  stubAddr, stubName, TypePtr::BOTTOM,
 7612                                  crc, src_start, length);
 7613   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
 7614   set_result(result);
 7615   return true;
 7616 }
 7617 
 7618 /**
 7619  * Calculate CRC32 for ByteBuffer.
 7620  * int java.util.zip.CRC32.updateByteBuffer(int crc, long buf, int off, int len)
 7621  */
 7622 bool LibraryCallKit::inline_updateByteBufferCRC32() {
 7623   assert(UseCRC32Intrinsics, "need AVX and CLMUL instructions support");
 7624   assert(callee()->signature()->size() == 5, "updateByteBuffer has 4 parameters and one is long");
 7625   // no receiver since it is static method
 7626   Node* crc     = argument(0); // type: int
 7627   Node* src     = argument(1); // type: long
 7628   Node* offset  = argument(3); // type: int
 7629   Node* length  = argument(4); // type: int
 7630 
 7631   src = ConvL2X(src);  // adjust Java long to machine word
 7632   Node* base = _gvn.transform(new CastX2PNode(src));
 7633   offset = ConvI2X(offset);
 7634 
 7635   // 'src_start' points to src array + scaled offset
 7636   Node* src_start = off_heap_plus_addr(base, offset);
 7637 
 7638   // Call the stub.
 7639   address stubAddr = StubRoutines::updateBytesCRC32();
 7640   const char *stubName = "updateBytesCRC32";
 7641 
 7642   Node* call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::updateBytesCRC32_Type(),
 7643                                  stubAddr, stubName, TypePtr::BOTTOM,
 7644                                  crc, src_start, length);
 7645   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
 7646   set_result(result);
 7647   return true;
 7648 }
 7649 
 7650 //------------------------------get_table_from_crc32c_class-----------------------
 7651 Node * LibraryCallKit::get_table_from_crc32c_class(ciInstanceKlass *crc32c_class) {
 7652   Node* table = load_field_from_object(nullptr, "byteTable", "[I", /*decorators*/ IN_HEAP, /*is_static*/ true, crc32c_class);
 7653   assert (table != nullptr, "wrong version of java.util.zip.CRC32C");
 7654 
 7655   return table;
 7656 }
 7657 
 7658 //------------------------------inline_updateBytesCRC32C-----------------------
 7659 //
 7660 // Calculate CRC32C for byte[] array.
 7661 // int java.util.zip.CRC32C.updateBytes(int crc, byte[] buf, int off, int end)
 7662 //
 7663 bool LibraryCallKit::inline_updateBytesCRC32C() {
 7664   assert(UseCRC32CIntrinsics, "need CRC32C instruction support");
 7665   assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
 7666   assert(callee()->holder()->is_loaded(), "CRC32C class must be loaded");
 7667   // no receiver since it is a static method
 7668   Node* crc     = argument(0); // type: int
 7669   Node* src     = argument(1); // type: oop
 7670   Node* offset  = argument(2); // type: int
 7671   Node* end     = argument(3); // type: int
 7672 
 7673   Node* length = _gvn.transform(new SubINode(end, offset));
 7674 
 7675   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
 7676   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
 7677     // failed array check
 7678     return false;
 7679   }
 7680 
 7681   // Figure out the size and type of the elements we will be copying.
 7682   BasicType src_elem = src_type->elem()->array_element_basic_type();
 7683   if (src_elem != T_BYTE) {
 7684     return false;
 7685   }
 7686 
 7687   // 'src_start' points to src array + scaled offset
 7688   src = must_be_not_null(src, true);
 7689   Node* src_start = array_element_address(src, offset, src_elem);
 7690 
 7691   // static final int[] byteTable in class CRC32C
 7692   Node* table = get_table_from_crc32c_class(callee()->holder());
 7693   table = must_be_not_null(table, true);
 7694   Node* table_start = array_element_address(table, intcon(0), T_INT);
 7695 
 7696   // We assume that range check is done by caller.
 7697   // TODO: generate range check (offset+length < src.length) in debug VM.
 7698 
 7699   // Call the stub.
 7700   address stubAddr = StubRoutines::updateBytesCRC32C();
 7701   const char *stubName = "updateBytesCRC32C";
 7702 
 7703   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesCRC32C_Type(),
 7704                                  stubAddr, stubName, TypePtr::BOTTOM,
 7705                                  crc, src_start, length, table_start);
 7706   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
 7707   set_result(result);
 7708   return true;
 7709 }
 7710 
 7711 //------------------------------inline_updateDirectByteBufferCRC32C-----------------------
 7712 //
 7713 // Calculate CRC32C for DirectByteBuffer.
 7714 // int java.util.zip.CRC32C.updateDirectByteBuffer(int crc, long buf, int off, int end)
 7715 //
 7716 bool LibraryCallKit::inline_updateDirectByteBufferCRC32C() {
 7717   assert(UseCRC32CIntrinsics, "need CRC32C instruction support");
 7718   assert(callee()->signature()->size() == 5, "updateDirectByteBuffer has 4 parameters and one is long");
 7719   assert(callee()->holder()->is_loaded(), "CRC32C class must be loaded");
 7720   // no receiver since it is a static method
 7721   Node* crc     = argument(0); // type: int
 7722   Node* src     = argument(1); // type: long
 7723   Node* offset  = argument(3); // type: int
 7724   Node* end     = argument(4); // type: int
 7725 
 7726   Node* length = _gvn.transform(new SubINode(end, offset));
 7727 
 7728   src = ConvL2X(src);  // adjust Java long to machine word
 7729   Node* base = _gvn.transform(new CastX2PNode(src));
 7730   offset = ConvI2X(offset);
 7731 
 7732   // 'src_start' points to src array + scaled offset
 7733   Node* src_start = off_heap_plus_addr(base, offset);
 7734 
 7735   // static final int[] byteTable in class CRC32C
 7736   Node* table = get_table_from_crc32c_class(callee()->holder());
 7737   table = must_be_not_null(table, true);
 7738   Node* table_start = array_element_address(table, intcon(0), T_INT);
 7739 
 7740   // Call the stub.
 7741   address stubAddr = StubRoutines::updateBytesCRC32C();
 7742   const char *stubName = "updateBytesCRC32C";
 7743 
 7744   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesCRC32C_Type(),
 7745                                  stubAddr, stubName, TypePtr::BOTTOM,
 7746                                  crc, src_start, length, table_start);
 7747   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
 7748   set_result(result);
 7749   return true;
 7750 }
 7751 
 7752 //------------------------------inline_updateBytesAdler32----------------------
 7753 //
 7754 // Calculate Adler32 checksum for byte[] array.
 7755 // int java.util.zip.Adler32.updateBytes(int crc, byte[] buf, int off, int len)
 7756 //
 7757 bool LibraryCallKit::inline_updateBytesAdler32() {
 7758   assert(UseAdler32Intrinsics, "Adler32 Intrinsic support need"); // check if we actually need to check this flag or check a different one
 7759   assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
 7760   assert(callee()->holder()->is_loaded(), "Adler32 class must be loaded");
 7761   // no receiver since it is static method
 7762   Node* crc     = argument(0); // type: int
 7763   Node* src     = argument(1); // type: oop
 7764   Node* offset  = argument(2); // type: int
 7765   Node* length  = argument(3); // type: int
 7766 
 7767   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
 7768   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
 7769     // failed array check
 7770     return false;
 7771   }
 7772 
 7773   // Figure out the size and type of the elements we will be copying.
 7774   BasicType src_elem = src_type->elem()->array_element_basic_type();
 7775   if (src_elem != T_BYTE) {
 7776     return false;
 7777   }
 7778 
 7779   // 'src_start' points to src array + scaled offset
 7780   Node* src_start = array_element_address(src, offset, src_elem);
 7781 
 7782   // We assume that range check is done by caller.
 7783   // TODO: generate range check (offset+length < src.length) in debug VM.
 7784 
 7785   // Call the stub.
 7786   address stubAddr = StubRoutines::updateBytesAdler32();
 7787   const char *stubName = "updateBytesAdler32";
 7788 
 7789   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesAdler32_Type(),
 7790                                  stubAddr, stubName, TypePtr::BOTTOM,
 7791                                  crc, src_start, length);
 7792   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
 7793   set_result(result);
 7794   return true;
 7795 }
 7796 
 7797 //------------------------------inline_updateByteBufferAdler32---------------
 7798 //
 7799 // Calculate Adler32 checksum for DirectByteBuffer.
 7800 // int java.util.zip.Adler32.updateByteBuffer(int crc, long buf, int off, int len)
 7801 //
 7802 bool LibraryCallKit::inline_updateByteBufferAdler32() {
 7803   assert(UseAdler32Intrinsics, "Adler32 Intrinsic support need"); // check if we actually need to check this flag or check a different one
 7804   assert(callee()->signature()->size() == 5, "updateByteBuffer has 4 parameters and one is long");
 7805   assert(callee()->holder()->is_loaded(), "Adler32 class must be loaded");
 7806   // no receiver since it is static method
 7807   Node* crc     = argument(0); // type: int
 7808   Node* src     = argument(1); // type: long
 7809   Node* offset  = argument(3); // type: int
 7810   Node* length  = argument(4); // type: int
 7811 
 7812   src = ConvL2X(src);  // adjust Java long to machine word
 7813   Node* base = _gvn.transform(new CastX2PNode(src));
 7814   offset = ConvI2X(offset);
 7815 
 7816   // 'src_start' points to src array + scaled offset
 7817   Node* src_start = off_heap_plus_addr(base, offset);
 7818 
 7819   // Call the stub.
 7820   address stubAddr = StubRoutines::updateBytesAdler32();
 7821   const char *stubName = "updateBytesAdler32";
 7822 
 7823   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesAdler32_Type(),
 7824                                  stubAddr, stubName, TypePtr::BOTTOM,
 7825                                  crc, src_start, length);
 7826 
 7827   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
 7828   set_result(result);
 7829   return true;
 7830 }
 7831 
 7832 //----------------------------inline_reference_get0----------------------------
 7833 // public T java.lang.ref.Reference.get();
 7834 bool LibraryCallKit::inline_reference_get0() {
 7835   const int referent_offset = java_lang_ref_Reference::referent_offset();
 7836 
 7837   // Get the argument:
 7838   Node* reference_obj = null_check_receiver();
 7839   if (stopped()) return true;
 7840 
 7841   DecoratorSet decorators = IN_HEAP | ON_WEAK_OOP_REF;
 7842   Node* result = load_field_from_object(reference_obj, "referent", "Ljava/lang/Object;",
 7843                                         decorators, /*is_static*/ false,
 7844                                         env()->Reference_klass());
 7845   if (result == nullptr) return false;
 7846 
 7847   // Add memory barrier to prevent commoning reads from this field
 7848   // across safepoint since GC can change its value.
 7849   insert_mem_bar(Op_MemBarCPUOrder);
 7850 
 7851   set_result(result);
 7852   return true;
 7853 }
 7854 
 7855 //----------------------------inline_reference_refersTo0----------------------------
 7856 // bool java.lang.ref.Reference.refersTo0();
 7857 // bool java.lang.ref.PhantomReference.refersTo0();
 7858 bool LibraryCallKit::inline_reference_refersTo0(bool is_phantom) {
 7859   // Get arguments:
 7860   Node* reference_obj = null_check_receiver();
 7861   Node* other_obj = argument(1);
 7862   if (stopped()) return true;
 7863 
 7864   DecoratorSet decorators = IN_HEAP | AS_NO_KEEPALIVE;
 7865   decorators |= (is_phantom ? ON_PHANTOM_OOP_REF : ON_WEAK_OOP_REF);
 7866   Node* referent = load_field_from_object(reference_obj, "referent", "Ljava/lang/Object;",
 7867                                           decorators, /*is_static*/ false,
 7868                                           env()->Reference_klass());
 7869   if (referent == nullptr) return false;
 7870 
 7871   // Add memory barrier to prevent commoning reads from this field
 7872   // across safepoint since GC can change its value.
 7873   insert_mem_bar(Op_MemBarCPUOrder);
 7874 
 7875   Node* cmp = _gvn.transform(new CmpPNode(referent, other_obj));
 7876   Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
 7877   IfNode* if_node = create_and_map_if(control(), bol, PROB_FAIR, COUNT_UNKNOWN);
 7878 
 7879   RegionNode* region = new RegionNode(3);
 7880   PhiNode* phi = new PhiNode(region, TypeInt::BOOL);
 7881 
 7882   Node* if_true = _gvn.transform(new IfTrueNode(if_node));
 7883   region->init_req(1, if_true);
 7884   phi->init_req(1, intcon(1));
 7885 
 7886   Node* if_false = _gvn.transform(new IfFalseNode(if_node));
 7887   region->init_req(2, if_false);
 7888   phi->init_req(2, intcon(0));
 7889 
 7890   set_control(_gvn.transform(region));
 7891   record_for_igvn(region);
 7892   set_result(_gvn.transform(phi));
 7893   return true;
 7894 }
 7895 
 7896 //----------------------------inline_reference_clear0----------------------------
 7897 // void java.lang.ref.Reference.clear0();
 7898 // void java.lang.ref.PhantomReference.clear0();
 7899 bool LibraryCallKit::inline_reference_clear0(bool is_phantom) {
 7900   // This matches the implementation in JVM_ReferenceClear, see the comments there.
 7901 
 7902   // Get arguments
 7903   Node* reference_obj = null_check_receiver();
 7904   if (stopped()) return true;
 7905 
 7906   // Common access parameters
 7907   DecoratorSet decorators = IN_HEAP | AS_NO_KEEPALIVE;
 7908   decorators |= (is_phantom ? ON_PHANTOM_OOP_REF : ON_WEAK_OOP_REF);
 7909   Node* referent_field_addr = basic_plus_adr(reference_obj, java_lang_ref_Reference::referent_offset());
 7910   const TypePtr* referent_field_addr_type = _gvn.type(referent_field_addr)->isa_ptr();
 7911   const Type* val_type = TypeOopPtr::make_from_klass(env()->Object_klass());
 7912 
 7913   Node* referent = access_load_at(reference_obj,
 7914                                   referent_field_addr,
 7915                                   referent_field_addr_type,
 7916                                   val_type,
 7917                                   T_OBJECT,
 7918                                   decorators);
 7919 
 7920   IdealKit ideal(this);
 7921 #define __ ideal.
 7922   __ if_then(referent, BoolTest::ne, null());
 7923     sync_kit(ideal);
 7924     access_store_at(reference_obj,
 7925                     referent_field_addr,
 7926                     referent_field_addr_type,
 7927                     null(),
 7928                     val_type,
 7929                     T_OBJECT,
 7930                     decorators);
 7931     __ sync_kit(this);
 7932   __ end_if();
 7933   final_sync(ideal);
 7934 #undef __
 7935 
 7936   return true;
 7937 }
 7938 
 7939 //-----------------------inline_reference_reachabilityFence-----------------
 7940 // bool java.lang.ref.Reference.reachabilityFence();
 7941 bool LibraryCallKit::inline_reference_reachabilityFence() {
 7942   Node* referent = argument(0);
 7943   insert_reachability_fence(referent);
 7944   return true;
 7945 }
 7946 
 7947 Node* LibraryCallKit::load_field_from_object(Node* fromObj, const char* fieldName, const char* fieldTypeString,
 7948                                              DecoratorSet decorators, bool is_static,
 7949                                              ciInstanceKlass* fromKls) {
 7950   if (fromKls == nullptr) {
 7951     const TypeInstPtr* tinst = _gvn.type(fromObj)->isa_instptr();
 7952     assert(tinst != nullptr, "obj is null");
 7953     assert(tinst->is_loaded(), "obj is not loaded");
 7954     fromKls = tinst->instance_klass();
 7955   }
 7956   ciField* field = fromKls->get_field_by_name(ciSymbol::make(fieldName),
 7957                                               ciSymbol::make(fieldTypeString),
 7958                                               is_static);
 7959 
 7960   assert(field != nullptr, "undefined field %s %s %s", fieldTypeString, fromKls->name()->as_utf8(), fieldName);
 7961   if (field == nullptr) return (Node *) nullptr;
 7962 
 7963   if (is_static) {
 7964     const TypeInstPtr* tip = TypeInstPtr::make(fromKls->java_mirror());
 7965     fromObj = makecon(tip);
 7966   }
 7967 
 7968   // Next code  copied from Parse::do_get_xxx():
 7969 
 7970   // Compute address and memory type.
 7971   int offset  = field->offset_in_bytes();
 7972   bool is_vol = field->is_volatile();
 7973   ciType* field_klass = field->type();
 7974   assert(field_klass->is_loaded(), "should be loaded");
 7975   const TypePtr* adr_type = C->alias_type(field)->adr_type();
 7976   Node *adr = basic_plus_adr(fromObj, fromObj, offset);
 7977   assert(C->get_alias_index(adr_type) == C->get_alias_index(_gvn.type(adr)->isa_ptr()),
 7978     "slice of address and input slice don't match");
 7979   BasicType bt = field->layout_type();
 7980 
 7981   // Build the resultant type of the load
 7982   const Type *type;
 7983   if (bt == T_OBJECT) {
 7984     type = TypeOopPtr::make_from_klass(field_klass->as_klass());
 7985   } else {
 7986     type = Type::get_const_basic_type(bt);
 7987   }
 7988 
 7989   if (is_vol) {
 7990     decorators |= MO_SEQ_CST;
 7991   }
 7992 
 7993   return access_load_at(fromObj, adr, adr_type, type, bt, decorators);
 7994 }
 7995 
 7996 Node * LibraryCallKit::field_address_from_object(Node * fromObj, const char * fieldName, const char * fieldTypeString,
 7997                                                  bool is_exact /* true */, bool is_static /* false */,
 7998                                                  ciInstanceKlass * fromKls /* nullptr */) {
 7999   if (fromKls == nullptr) {
 8000     const TypeInstPtr* tinst = _gvn.type(fromObj)->isa_instptr();
 8001     assert(tinst != nullptr, "obj is null");
 8002     assert(tinst->is_loaded(), "obj is not loaded");
 8003     assert(!is_exact || tinst->klass_is_exact(), "klass not exact");
 8004     fromKls = tinst->instance_klass();
 8005   }
 8006   else {
 8007     assert(is_static, "only for static field access");
 8008   }
 8009   ciField* field = fromKls->get_field_by_name(ciSymbol::make(fieldName),
 8010     ciSymbol::make(fieldTypeString),
 8011     is_static);
 8012 
 8013   assert(field != nullptr, "undefined field");
 8014   assert(!field->is_volatile(), "not defined for volatile fields");
 8015 
 8016   if (is_static) {
 8017     const TypeInstPtr* tip = TypeInstPtr::make(fromKls->java_mirror());
 8018     fromObj = makecon(tip);
 8019   }
 8020 
 8021   // Next code  copied from Parse::do_get_xxx():
 8022 
 8023   // Compute address and memory type.
 8024   int offset = field->offset_in_bytes();
 8025   Node *adr = basic_plus_adr(fromObj, fromObj, offset);
 8026 
 8027   return adr;
 8028 }
 8029 
 8030 //------------------------------inline_aescrypt_Block-----------------------
 8031 bool LibraryCallKit::inline_aescrypt_Block(vmIntrinsics::ID id) {
 8032   address stubAddr = nullptr;
 8033   const char *stubName;
 8034   bool is_decrypt = false;
 8035   assert(UseAES, "need AES instruction support");
 8036 
 8037   switch(id) {
 8038   case vmIntrinsics::_aescrypt_encryptBlock:
 8039     stubAddr = StubRoutines::aescrypt_encryptBlock();
 8040     stubName = "aescrypt_encryptBlock";
 8041     break;
 8042   case vmIntrinsics::_aescrypt_decryptBlock:
 8043     stubAddr = StubRoutines::aescrypt_decryptBlock();
 8044     stubName = "aescrypt_decryptBlock";
 8045     is_decrypt = true;
 8046     break;
 8047   default:
 8048     break;
 8049   }
 8050   if (stubAddr == nullptr) return false;
 8051 
 8052   Node* aescrypt_object = argument(0);
 8053   Node* src             = argument(1);
 8054   Node* src_offset      = argument(2);
 8055   Node* dest            = argument(3);
 8056   Node* dest_offset     = argument(4);
 8057 
 8058   src = must_be_not_null(src, true);
 8059   dest = must_be_not_null(dest, true);
 8060 
 8061   // (1) src and dest are arrays.
 8062   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
 8063   const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
 8064   assert( src_type != nullptr &&  src_type->elem() != Type::BOTTOM &&
 8065          dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
 8066 
 8067   // for the quick and dirty code we will skip all the checks.
 8068   // we are just trying to get the call to be generated.
 8069   Node* src_start  = src;
 8070   Node* dest_start = dest;
 8071   if (src_offset != nullptr || dest_offset != nullptr) {
 8072     assert(src_offset != nullptr && dest_offset != nullptr, "");
 8073     src_start  = array_element_address(src,  src_offset,  T_BYTE);
 8074     dest_start = array_element_address(dest, dest_offset, T_BYTE);
 8075   }
 8076 
 8077   // now need to get the start of its expanded key array
 8078   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
 8079   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object, is_decrypt);
 8080   if (k_start == nullptr) return false;
 8081 
 8082   // Call the stub.
 8083   make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::aescrypt_block_Type(),
 8084                     stubAddr, stubName, TypePtr::BOTTOM,
 8085                     src_start, dest_start, k_start);
 8086 
 8087   return true;
 8088 }
 8089 
 8090 //------------------------------inline_cipherBlockChaining_AESCrypt-----------------------
 8091 bool LibraryCallKit::inline_cipherBlockChaining_AESCrypt(vmIntrinsics::ID id) {
 8092   address stubAddr = nullptr;
 8093   const char *stubName = nullptr;
 8094   bool is_decrypt = false;
 8095   assert(UseAES, "need AES instruction support");
 8096 
 8097   switch(id) {
 8098   case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
 8099     stubAddr = StubRoutines::cipherBlockChaining_encryptAESCrypt();
 8100     stubName = "cipherBlockChaining_encryptAESCrypt";
 8101     break;
 8102   case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
 8103     stubAddr = StubRoutines::cipherBlockChaining_decryptAESCrypt();
 8104     stubName = "cipherBlockChaining_decryptAESCrypt";
 8105     is_decrypt = true;
 8106     break;
 8107   default:
 8108     break;
 8109   }
 8110   if (stubAddr == nullptr) return false;
 8111 
 8112   Node* cipherBlockChaining_object = argument(0);
 8113   Node* src                        = argument(1);
 8114   Node* src_offset                 = argument(2);
 8115   Node* len                        = argument(3);
 8116   Node* dest                       = argument(4);
 8117   Node* dest_offset                = argument(5);
 8118 
 8119   src = must_be_not_null(src, false);
 8120   dest = must_be_not_null(dest, false);
 8121 
 8122   // (1) src and dest are arrays.
 8123   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
 8124   const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
 8125   assert( src_type != nullptr &&  src_type->elem() != Type::BOTTOM &&
 8126          dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
 8127 
 8128   // checks are the responsibility of the caller
 8129   Node* src_start  = src;
 8130   Node* dest_start = dest;
 8131   if (src_offset != nullptr || dest_offset != nullptr) {
 8132     assert(src_offset != nullptr && dest_offset != nullptr, "");
 8133     src_start  = array_element_address(src,  src_offset,  T_BYTE);
 8134     dest_start = array_element_address(dest, dest_offset, T_BYTE);
 8135   }
 8136 
 8137   // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
 8138   // (because of the predicated logic executed earlier).
 8139   // so we cast it here safely.
 8140   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
 8141 
 8142   Node* embeddedCipherObj = load_field_from_object(cipherBlockChaining_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
 8143   if (embeddedCipherObj == nullptr) return false;
 8144 
 8145   // cast it to what we know it will be at runtime
 8146   const TypeInstPtr* tinst = _gvn.type(cipherBlockChaining_object)->isa_instptr();
 8147   assert(tinst != nullptr, "CBC obj is null");
 8148   assert(tinst->is_loaded(), "CBC obj is not loaded");
 8149   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
 8150   assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
 8151 
 8152   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
 8153   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
 8154   const TypeOopPtr* xtype = aklass->as_exact_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
 8155   Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
 8156   aescrypt_object = _gvn.transform(aescrypt_object);
 8157 
 8158   // we need to get the start of the aescrypt_object's expanded key array
 8159   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object, is_decrypt);
 8160   if (k_start == nullptr) return false;
 8161 
 8162   // similarly, get the start address of the r vector
 8163   Node* objRvec = load_field_from_object(cipherBlockChaining_object, "r", "[B");
 8164   if (objRvec == nullptr) return false;
 8165   Node* r_start = array_element_address(objRvec, intcon(0), T_BYTE);
 8166 
 8167   // Call the stub, passing src_start, dest_start, k_start, r_start and src_len
 8168   Node* cbcCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
 8169                                      OptoRuntime::cipherBlockChaining_aescrypt_Type(),
 8170                                      stubAddr, stubName, TypePtr::BOTTOM,
 8171                                      src_start, dest_start, k_start, r_start, len);
 8172 
 8173   // return cipher length (int)
 8174   Node* retvalue = _gvn.transform(new ProjNode(cbcCrypt, TypeFunc::Parms));
 8175   set_result(retvalue);
 8176   return true;
 8177 }
 8178 
 8179 //------------------------------inline_electronicCodeBook_AESCrypt-----------------------
 8180 bool LibraryCallKit::inline_electronicCodeBook_AESCrypt(vmIntrinsics::ID id) {
 8181   address stubAddr = nullptr;
 8182   const char *stubName = nullptr;
 8183   bool is_decrypt = false;
 8184   assert(UseAES, "need AES instruction support");
 8185 
 8186   switch (id) {
 8187   case vmIntrinsics::_electronicCodeBook_encryptAESCrypt:
 8188     stubAddr = StubRoutines::electronicCodeBook_encryptAESCrypt();
 8189     stubName = "electronicCodeBook_encryptAESCrypt";
 8190     break;
 8191   case vmIntrinsics::_electronicCodeBook_decryptAESCrypt:
 8192     stubAddr = StubRoutines::electronicCodeBook_decryptAESCrypt();
 8193     stubName = "electronicCodeBook_decryptAESCrypt";
 8194     is_decrypt = true;
 8195     break;
 8196   default:
 8197     break;
 8198   }
 8199 
 8200   if (stubAddr == nullptr) return false;
 8201 
 8202   Node* electronicCodeBook_object = argument(0);
 8203   Node* src                       = argument(1);
 8204   Node* src_offset                = argument(2);
 8205   Node* len                       = argument(3);
 8206   Node* dest                      = argument(4);
 8207   Node* dest_offset               = argument(5);
 8208 
 8209   // (1) src and dest are arrays.
 8210   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
 8211   const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
 8212   assert( src_type != nullptr &&  src_type->elem() != Type::BOTTOM &&
 8213          dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
 8214 
 8215   // checks are the responsibility of the caller
 8216   Node* src_start = src;
 8217   Node* dest_start = dest;
 8218   if (src_offset != nullptr || dest_offset != nullptr) {
 8219     assert(src_offset != nullptr && dest_offset != nullptr, "");
 8220     src_start = array_element_address(src, src_offset, T_BYTE);
 8221     dest_start = array_element_address(dest, dest_offset, T_BYTE);
 8222   }
 8223 
 8224   // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
 8225   // (because of the predicated logic executed earlier).
 8226   // so we cast it here safely.
 8227   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
 8228 
 8229   Node* embeddedCipherObj = load_field_from_object(electronicCodeBook_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
 8230   if (embeddedCipherObj == nullptr) return false;
 8231 
 8232   // cast it to what we know it will be at runtime
 8233   const TypeInstPtr* tinst = _gvn.type(electronicCodeBook_object)->isa_instptr();
 8234   assert(tinst != nullptr, "ECB obj is null");
 8235   assert(tinst->is_loaded(), "ECB obj is not loaded");
 8236   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
 8237   assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
 8238 
 8239   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
 8240   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
 8241   const TypeOopPtr* xtype = aklass->as_exact_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
 8242   Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
 8243   aescrypt_object = _gvn.transform(aescrypt_object);
 8244 
 8245   // we need to get the start of the aescrypt_object's expanded key array
 8246   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object, is_decrypt);
 8247   if (k_start == nullptr) return false;
 8248 
 8249   // Call the stub, passing src_start, dest_start, k_start, r_start and src_len
 8250   Node* ecbCrypt = make_runtime_call(RC_LEAF | RC_NO_FP,
 8251                                      OptoRuntime::electronicCodeBook_aescrypt_Type(),
 8252                                      stubAddr, stubName, TypePtr::BOTTOM,
 8253                                      src_start, dest_start, k_start, len);
 8254 
 8255   // return cipher length (int)
 8256   Node* retvalue = _gvn.transform(new ProjNode(ecbCrypt, TypeFunc::Parms));
 8257   set_result(retvalue);
 8258   return true;
 8259 }
 8260 
 8261 //------------------------------inline_counterMode_AESCrypt-----------------------
 8262 bool LibraryCallKit::inline_counterMode_AESCrypt(vmIntrinsics::ID id) {
 8263   assert(UseAES, "need AES instruction support");
 8264   if (!UseAESCTRIntrinsics) return false;
 8265 
 8266   address stubAddr = nullptr;
 8267   const char *stubName = nullptr;
 8268   if (id == vmIntrinsics::_counterMode_AESCrypt) {
 8269     stubAddr = StubRoutines::counterMode_AESCrypt();
 8270     stubName = "counterMode_AESCrypt";
 8271   }
 8272   if (stubAddr == nullptr) return false;
 8273 
 8274   Node* counterMode_object = argument(0);
 8275   Node* src = argument(1);
 8276   Node* src_offset = argument(2);
 8277   Node* len = argument(3);
 8278   Node* dest = argument(4);
 8279   Node* dest_offset = argument(5);
 8280 
 8281   // (1) src and dest are arrays.
 8282   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
 8283   const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
 8284   assert( src_type != nullptr &&  src_type->elem() != Type::BOTTOM &&
 8285          dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
 8286 
 8287   // checks are the responsibility of the caller
 8288   Node* src_start = src;
 8289   Node* dest_start = dest;
 8290   if (src_offset != nullptr || dest_offset != nullptr) {
 8291     assert(src_offset != nullptr && dest_offset != nullptr, "");
 8292     src_start = array_element_address(src, src_offset, T_BYTE);
 8293     dest_start = array_element_address(dest, dest_offset, T_BYTE);
 8294   }
 8295 
 8296   // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
 8297   // (because of the predicated logic executed earlier).
 8298   // so we cast it here safely.
 8299   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
 8300   Node* embeddedCipherObj = load_field_from_object(counterMode_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
 8301   if (embeddedCipherObj == nullptr) return false;
 8302   // cast it to what we know it will be at runtime
 8303   const TypeInstPtr* tinst = _gvn.type(counterMode_object)->isa_instptr();
 8304   assert(tinst != nullptr, "CTR obj is null");
 8305   assert(tinst->is_loaded(), "CTR obj is not loaded");
 8306   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
 8307   assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
 8308   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
 8309   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
 8310   const TypeOopPtr* xtype = aklass->as_exact_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
 8311   Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
 8312   aescrypt_object = _gvn.transform(aescrypt_object);
 8313   // we need to get the start of the aescrypt_object's expanded key array
 8314   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object, /* is_decrypt */ false);
 8315   if (k_start == nullptr) return false;
 8316   // similarly, get the start address of the r vector
 8317   Node* obj_counter = load_field_from_object(counterMode_object, "counter", "[B");
 8318   if (obj_counter == nullptr) return false;
 8319   Node* cnt_start = array_element_address(obj_counter, intcon(0), T_BYTE);
 8320 
 8321   Node* saved_encCounter = load_field_from_object(counterMode_object, "encryptedCounter", "[B");
 8322   if (saved_encCounter == nullptr) return false;
 8323   Node* saved_encCounter_start = array_element_address(saved_encCounter, intcon(0), T_BYTE);
 8324   Node* used = field_address_from_object(counterMode_object, "used", "I", /*is_exact*/ false);
 8325 
 8326   // Call the stub, passing src_start, dest_start, k_start, r_start and src_len
 8327   Node* ctrCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
 8328                                      OptoRuntime::counterMode_aescrypt_Type(),
 8329                                      stubAddr, stubName, TypePtr::BOTTOM,
 8330                                      src_start, dest_start, k_start, cnt_start, len, saved_encCounter_start, used);
 8331 
 8332   // return cipher length (int)
 8333   Node* retvalue = _gvn.transform(new ProjNode(ctrCrypt, TypeFunc::Parms));
 8334   set_result(retvalue);
 8335   return true;
 8336 }
 8337 
 8338 //------------------------------get_key_start_from_aescrypt_object-----------------------
 8339 Node* LibraryCallKit::get_key_start_from_aescrypt_object(Node* aescrypt_object, bool is_decrypt) {
 8340   // MixColumns for decryption can be reduced by preprocessing MixColumns with round keys.
 8341   // Intel's extension is based on this optimization and AESCrypt generates round keys by preprocessing MixColumns.
 8342   // However, ppc64 vncipher processes MixColumns and requires the same round keys with encryption.
 8343   // The following platform specific stubs of encryption and decryption use the same round keys.
 8344 #if defined(PPC64) || defined(S390) || defined(RISCV64)
 8345   bool use_decryption_key = false;
 8346 #else
 8347   bool use_decryption_key = is_decrypt;
 8348 #endif
 8349   Node* objAESCryptKey = load_field_from_object(aescrypt_object, use_decryption_key ? "sessionKd" : "sessionKe", "[I");
 8350   assert(objAESCryptKey != nullptr, "wrong version of com.sun.crypto.provider.AES_Crypt");
 8351   if (objAESCryptKey == nullptr) return (Node *) nullptr;
 8352 
 8353   // now have the array, need to get the start address of the selected key array
 8354   Node* k_start = array_element_address(objAESCryptKey, intcon(0), T_INT);
 8355   return k_start;
 8356 }
 8357 
 8358 //----------------------------inline_cipherBlockChaining_AESCrypt_predicate----------------------------
 8359 // Return node representing slow path of predicate check.
 8360 // the pseudo code we want to emulate with this predicate is:
 8361 // for encryption:
 8362 //    if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
 8363 // for decryption:
 8364 //    if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
 8365 //    note cipher==plain is more conservative than the original java code but that's OK
 8366 //
 8367 Node* LibraryCallKit::inline_cipherBlockChaining_AESCrypt_predicate(bool decrypting) {
 8368   // The receiver was checked for null already.
 8369   Node* objCBC = argument(0);
 8370 
 8371   Node* src = argument(1);
 8372   Node* dest = argument(4);
 8373 
 8374   // Load embeddedCipher field of CipherBlockChaining object.
 8375   Node* embeddedCipherObj = load_field_from_object(objCBC, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
 8376 
 8377   // get AESCrypt klass for instanceOf check
 8378   // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
 8379   // will have same classloader as CipherBlockChaining object
 8380   const TypeInstPtr* tinst = _gvn.type(objCBC)->isa_instptr();
 8381   assert(tinst != nullptr, "CBCobj is null");
 8382   assert(tinst->is_loaded(), "CBCobj is not loaded");
 8383 
 8384   // we want to do an instanceof comparison against the AESCrypt class
 8385   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
 8386   if (!klass_AESCrypt->is_loaded()) {
 8387     // if AESCrypt is not even loaded, we never take the intrinsic fast path
 8388     Node* ctrl = control();
 8389     set_control(top()); // no regular fast path
 8390     return ctrl;
 8391   }
 8392 
 8393   src = must_be_not_null(src, true);
 8394   dest = must_be_not_null(dest, true);
 8395 
 8396   // Resolve oops to stable for CmpP below.
 8397   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
 8398 
 8399   Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
 8400   Node* cmp_instof  = _gvn.transform(new CmpINode(instof, intcon(1)));
 8401   Node* bool_instof  = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
 8402 
 8403   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
 8404 
 8405   // for encryption, we are done
 8406   if (!decrypting)
 8407     return instof_false;  // even if it is null
 8408 
 8409   // for decryption, we need to add a further check to avoid
 8410   // taking the intrinsic path when cipher and plain are the same
 8411   // see the original java code for why.
 8412   RegionNode* region = new RegionNode(3);
 8413   region->init_req(1, instof_false);
 8414 
 8415   Node* cmp_src_dest = _gvn.transform(new CmpPNode(src, dest));
 8416   Node* bool_src_dest = _gvn.transform(new BoolNode(cmp_src_dest, BoolTest::eq));
 8417   Node* src_dest_conjoint = generate_guard(bool_src_dest, nullptr, PROB_MIN);
 8418   region->init_req(2, src_dest_conjoint);
 8419 
 8420   record_for_igvn(region);
 8421   return _gvn.transform(region);
 8422 }
 8423 
 8424 //----------------------------inline_electronicCodeBook_AESCrypt_predicate----------------------------
 8425 // Return node representing slow path of predicate check.
 8426 // the pseudo code we want to emulate with this predicate is:
 8427 // for encryption:
 8428 //    if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
 8429 // for decryption:
 8430 //    if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
 8431 //    note cipher==plain is more conservative than the original java code but that's OK
 8432 //
 8433 Node* LibraryCallKit::inline_electronicCodeBook_AESCrypt_predicate(bool decrypting) {
 8434   // The receiver was checked for null already.
 8435   Node* objECB = argument(0);
 8436 
 8437   // Load embeddedCipher field of ElectronicCodeBook object.
 8438   Node* embeddedCipherObj = load_field_from_object(objECB, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
 8439 
 8440   // get AESCrypt klass for instanceOf check
 8441   // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
 8442   // will have same classloader as ElectronicCodeBook object
 8443   const TypeInstPtr* tinst = _gvn.type(objECB)->isa_instptr();
 8444   assert(tinst != nullptr, "ECBobj is null");
 8445   assert(tinst->is_loaded(), "ECBobj is not loaded");
 8446 
 8447   // we want to do an instanceof comparison against the AESCrypt class
 8448   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
 8449   if (!klass_AESCrypt->is_loaded()) {
 8450     // if AESCrypt is not even loaded, we never take the intrinsic fast path
 8451     Node* ctrl = control();
 8452     set_control(top()); // no regular fast path
 8453     return ctrl;
 8454   }
 8455   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
 8456 
 8457   Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
 8458   Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
 8459   Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
 8460 
 8461   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
 8462 
 8463   // for encryption, we are done
 8464   if (!decrypting)
 8465     return instof_false;  // even if it is null
 8466 
 8467   // for decryption, we need to add a further check to avoid
 8468   // taking the intrinsic path when cipher and plain are the same
 8469   // see the original java code for why.
 8470   RegionNode* region = new RegionNode(3);
 8471   region->init_req(1, instof_false);
 8472   Node* src = argument(1);
 8473   Node* dest = argument(4);
 8474   Node* cmp_src_dest = _gvn.transform(new CmpPNode(src, dest));
 8475   Node* bool_src_dest = _gvn.transform(new BoolNode(cmp_src_dest, BoolTest::eq));
 8476   Node* src_dest_conjoint = generate_guard(bool_src_dest, nullptr, PROB_MIN);
 8477   region->init_req(2, src_dest_conjoint);
 8478 
 8479   record_for_igvn(region);
 8480   return _gvn.transform(region);
 8481 }
 8482 
 8483 //----------------------------inline_counterMode_AESCrypt_predicate----------------------------
 8484 // Return node representing slow path of predicate check.
 8485 // the pseudo code we want to emulate with this predicate is:
 8486 // for encryption:
 8487 //    if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
 8488 // for decryption:
 8489 //    if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
 8490 //    note cipher==plain is more conservative than the original java code but that's OK
 8491 //
 8492 
 8493 Node* LibraryCallKit::inline_counterMode_AESCrypt_predicate() {
 8494   // The receiver was checked for null already.
 8495   Node* objCTR = argument(0);
 8496 
 8497   // Load embeddedCipher field of CipherBlockChaining object.
 8498   Node* embeddedCipherObj = load_field_from_object(objCTR, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
 8499 
 8500   // get AESCrypt klass for instanceOf check
 8501   // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
 8502   // will have same classloader as CipherBlockChaining object
 8503   const TypeInstPtr* tinst = _gvn.type(objCTR)->isa_instptr();
 8504   assert(tinst != nullptr, "CTRobj is null");
 8505   assert(tinst->is_loaded(), "CTRobj is not loaded");
 8506 
 8507   // we want to do an instanceof comparison against the AESCrypt class
 8508   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
 8509   if (!klass_AESCrypt->is_loaded()) {
 8510     // if AESCrypt is not even loaded, we never take the intrinsic fast path
 8511     Node* ctrl = control();
 8512     set_control(top()); // no regular fast path
 8513     return ctrl;
 8514   }
 8515 
 8516   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
 8517   Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
 8518   Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
 8519   Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
 8520   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
 8521 
 8522   return instof_false; // even if it is null
 8523 }
 8524 
 8525 //------------------------------inline_ghash_processBlocks
 8526 bool LibraryCallKit::inline_ghash_processBlocks() {
 8527   address stubAddr;
 8528   const char *stubName;
 8529   assert(UseGHASHIntrinsics, "need GHASH intrinsics support");
 8530 
 8531   stubAddr = StubRoutines::ghash_processBlocks();
 8532   stubName = "ghash_processBlocks";
 8533 
 8534   Node* data           = argument(0);
 8535   Node* offset         = argument(1);
 8536   Node* len            = argument(2);
 8537   Node* state          = argument(3);
 8538   Node* subkeyH        = argument(4);
 8539 
 8540   state = must_be_not_null(state, true);
 8541   subkeyH = must_be_not_null(subkeyH, true);
 8542   data = must_be_not_null(data, true);
 8543 
 8544   Node* state_start  = array_element_address(state, intcon(0), T_LONG);
 8545   assert(state_start, "state is null");
 8546   Node* subkeyH_start  = array_element_address(subkeyH, intcon(0), T_LONG);
 8547   assert(subkeyH_start, "subkeyH is null");
 8548   Node* data_start  = array_element_address(data, offset, T_BYTE);
 8549   assert(data_start, "data is null");
 8550 
 8551   Node* ghash = make_runtime_call(RC_LEAF|RC_NO_FP,
 8552                                   OptoRuntime::ghash_processBlocks_Type(),
 8553                                   stubAddr, stubName, TypePtr::BOTTOM,
 8554                                   state_start, subkeyH_start, data_start, len);
 8555   return true;
 8556 }
 8557 
 8558 //------------------------------inline_chacha20Block
 8559 bool LibraryCallKit::inline_chacha20Block() {
 8560   address stubAddr;
 8561   const char *stubName;
 8562   assert(UseChaCha20Intrinsics, "need ChaCha20 intrinsics support");
 8563 
 8564   stubAddr = StubRoutines::chacha20Block();
 8565   stubName = "chacha20Block";
 8566 
 8567   Node* state          = argument(0);
 8568   Node* result         = argument(1);
 8569 
 8570   state = must_be_not_null(state, true);
 8571   result = must_be_not_null(result, true);
 8572 
 8573   Node* state_start  = array_element_address(state, intcon(0), T_INT);
 8574   assert(state_start, "state is null");
 8575   Node* result_start  = array_element_address(result, intcon(0), T_BYTE);
 8576   assert(result_start, "result is null");
 8577 
 8578   Node* cc20Blk = make_runtime_call(RC_LEAF|RC_NO_FP,
 8579                                   OptoRuntime::chacha20Block_Type(),
 8580                                   stubAddr, stubName, TypePtr::BOTTOM,
 8581                                   state_start, result_start);
 8582   // return key stream length (int)
 8583   Node* retvalue = _gvn.transform(new ProjNode(cc20Blk, TypeFunc::Parms));
 8584   set_result(retvalue);
 8585   return true;
 8586 }
 8587 
 8588 //------------------------------inline_kyberNtt
 8589 bool LibraryCallKit::inline_kyberNtt() {
 8590   address stubAddr;
 8591   const char *stubName;
 8592   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
 8593   assert(callee()->signature()->size() == 2, "kyberNtt has 2 parameters");
 8594 
 8595   stubAddr = StubRoutines::kyberNtt();
 8596   stubName = "kyberNtt";
 8597   if (!stubAddr) return false;
 8598 
 8599   Node* coeffs          = argument(0);
 8600   Node* ntt_zetas        = argument(1);
 8601 
 8602   coeffs = must_be_not_null(coeffs, true);
 8603   ntt_zetas = must_be_not_null(ntt_zetas, true);
 8604 
 8605   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_SHORT);
 8606   assert(coeffs_start, "coeffs is null");
 8607   Node* ntt_zetas_start  = array_element_address(ntt_zetas, intcon(0), T_SHORT);
 8608   assert(ntt_zetas_start, "ntt_zetas is null");
 8609   Node* kyberNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
 8610                                   OptoRuntime::kyberNtt_Type(),
 8611                                   stubAddr, stubName, TypePtr::BOTTOM,
 8612                                   coeffs_start, ntt_zetas_start);
 8613   // return an int
 8614   Node* retvalue = _gvn.transform(new ProjNode(kyberNtt, TypeFunc::Parms));
 8615   set_result(retvalue);
 8616   return true;
 8617 }
 8618 
 8619 //------------------------------inline_kyberInverseNtt
 8620 bool LibraryCallKit::inline_kyberInverseNtt() {
 8621   address stubAddr;
 8622   const char *stubName;
 8623   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
 8624   assert(callee()->signature()->size() == 2, "kyberInverseNtt has 2 parameters");
 8625 
 8626   stubAddr = StubRoutines::kyberInverseNtt();
 8627   stubName = "kyberInverseNtt";
 8628   if (!stubAddr) return false;
 8629 
 8630   Node* coeffs          = argument(0);
 8631   Node* zetas           = argument(1);
 8632 
 8633   coeffs = must_be_not_null(coeffs, true);
 8634   zetas = must_be_not_null(zetas, true);
 8635 
 8636   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_SHORT);
 8637   assert(coeffs_start, "coeffs is null");
 8638   Node* zetas_start  = array_element_address(zetas, intcon(0), T_SHORT);
 8639   assert(zetas_start, "inverseNtt_zetas is null");
 8640   Node* kyberInverseNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
 8641                                   OptoRuntime::kyberInverseNtt_Type(),
 8642                                   stubAddr, stubName, TypePtr::BOTTOM,
 8643                                   coeffs_start, zetas_start);
 8644 
 8645   // return an int
 8646   Node* retvalue = _gvn.transform(new ProjNode(kyberInverseNtt, TypeFunc::Parms));
 8647   set_result(retvalue);
 8648   return true;
 8649 }
 8650 
 8651 //------------------------------inline_kyberNttMult
 8652 bool LibraryCallKit::inline_kyberNttMult() {
 8653   address stubAddr;
 8654   const char *stubName;
 8655   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
 8656   assert(callee()->signature()->size() == 4, "kyberNttMult has 4 parameters");
 8657 
 8658   stubAddr = StubRoutines::kyberNttMult();
 8659   stubName = "kyberNttMult";
 8660   if (!stubAddr) return false;
 8661 
 8662   Node* result          = argument(0);
 8663   Node* ntta            = argument(1);
 8664   Node* nttb            = argument(2);
 8665   Node* zetas           = argument(3);
 8666 
 8667   result = must_be_not_null(result, true);
 8668   ntta = must_be_not_null(ntta, true);
 8669   nttb = must_be_not_null(nttb, true);
 8670   zetas = must_be_not_null(zetas, true);
 8671 
 8672   Node* result_start  = array_element_address(result, intcon(0), T_SHORT);
 8673   assert(result_start, "result is null");
 8674   Node* ntta_start  = array_element_address(ntta, intcon(0), T_SHORT);
 8675   assert(ntta_start, "ntta is null");
 8676   Node* nttb_start  = array_element_address(nttb, intcon(0), T_SHORT);
 8677   assert(nttb_start, "nttb is null");
 8678   Node* zetas_start  = array_element_address(zetas, intcon(0), T_SHORT);
 8679   assert(zetas_start, "nttMult_zetas is null");
 8680   Node* kyberNttMult = make_runtime_call(RC_LEAF|RC_NO_FP,
 8681                                   OptoRuntime::kyberNttMult_Type(),
 8682                                   stubAddr, stubName, TypePtr::BOTTOM,
 8683                                   result_start, ntta_start, nttb_start,
 8684                                   zetas_start);
 8685 
 8686   // return an int
 8687   Node* retvalue = _gvn.transform(new ProjNode(kyberNttMult, TypeFunc::Parms));
 8688   set_result(retvalue);
 8689 
 8690   return true;
 8691 }
 8692 
 8693 //------------------------------inline_kyberAddPoly_2
 8694 bool LibraryCallKit::inline_kyberAddPoly_2() {
 8695   address stubAddr;
 8696   const char *stubName;
 8697   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
 8698   assert(callee()->signature()->size() == 3, "kyberAddPoly_2 has 3 parameters");
 8699 
 8700   stubAddr = StubRoutines::kyberAddPoly_2();
 8701   stubName = "kyberAddPoly_2";
 8702   if (!stubAddr) return false;
 8703 
 8704   Node* result          = argument(0);
 8705   Node* a               = argument(1);
 8706   Node* b               = argument(2);
 8707 
 8708   result = must_be_not_null(result, true);
 8709   a = must_be_not_null(a, true);
 8710   b = must_be_not_null(b, true);
 8711 
 8712   Node* result_start  = array_element_address(result, intcon(0), T_SHORT);
 8713   assert(result_start, "result is null");
 8714   Node* a_start  = array_element_address(a, intcon(0), T_SHORT);
 8715   assert(a_start, "a is null");
 8716   Node* b_start  = array_element_address(b, intcon(0), T_SHORT);
 8717   assert(b_start, "b is null");
 8718   Node* kyberAddPoly_2 = make_runtime_call(RC_LEAF|RC_NO_FP,
 8719                                   OptoRuntime::kyberAddPoly_2_Type(),
 8720                                   stubAddr, stubName, TypePtr::BOTTOM,
 8721                                   result_start, a_start, b_start);
 8722   // return an int
 8723   Node* retvalue = _gvn.transform(new ProjNode(kyberAddPoly_2, TypeFunc::Parms));
 8724   set_result(retvalue);
 8725   return true;
 8726 }
 8727 
 8728 //------------------------------inline_kyberAddPoly_3
 8729 bool LibraryCallKit::inline_kyberAddPoly_3() {
 8730   address stubAddr;
 8731   const char *stubName;
 8732   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
 8733   assert(callee()->signature()->size() == 4, "kyberAddPoly_3 has 4 parameters");
 8734 
 8735   stubAddr = StubRoutines::kyberAddPoly_3();
 8736   stubName = "kyberAddPoly_3";
 8737   if (!stubAddr) return false;
 8738 
 8739   Node* result          = argument(0);
 8740   Node* a               = argument(1);
 8741   Node* b               = argument(2);
 8742   Node* c               = argument(3);
 8743 
 8744   result = must_be_not_null(result, true);
 8745   a = must_be_not_null(a, true);
 8746   b = must_be_not_null(b, true);
 8747   c = must_be_not_null(c, true);
 8748 
 8749   Node* result_start  = array_element_address(result, intcon(0), T_SHORT);
 8750   assert(result_start, "result is null");
 8751   Node* a_start  = array_element_address(a, intcon(0), T_SHORT);
 8752   assert(a_start, "a is null");
 8753   Node* b_start  = array_element_address(b, intcon(0), T_SHORT);
 8754   assert(b_start, "b is null");
 8755   Node* c_start  = array_element_address(c, intcon(0), T_SHORT);
 8756   assert(c_start, "c is null");
 8757   Node* kyberAddPoly_3 = make_runtime_call(RC_LEAF|RC_NO_FP,
 8758                                   OptoRuntime::kyberAddPoly_3_Type(),
 8759                                   stubAddr, stubName, TypePtr::BOTTOM,
 8760                                   result_start, a_start, b_start, c_start);
 8761   // return an int
 8762   Node* retvalue = _gvn.transform(new ProjNode(kyberAddPoly_3, TypeFunc::Parms));
 8763   set_result(retvalue);
 8764   return true;
 8765 }
 8766 
 8767 //------------------------------inline_kyber12To16
 8768 bool LibraryCallKit::inline_kyber12To16() {
 8769   address stubAddr;
 8770   const char *stubName;
 8771   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
 8772   assert(callee()->signature()->size() == 4, "kyber12To16 has 4 parameters");
 8773 
 8774   stubAddr = StubRoutines::kyber12To16();
 8775   stubName = "kyber12To16";
 8776   if (!stubAddr) return false;
 8777 
 8778   Node* condensed       = argument(0);
 8779   Node* condensedOffs   = argument(1);
 8780   Node* parsed          = argument(2);
 8781   Node* parsedLength    = argument(3);
 8782 
 8783   condensed = must_be_not_null(condensed, true);
 8784   parsed = must_be_not_null(parsed, true);
 8785 
 8786   Node* condensed_start  = array_element_address(condensed, intcon(0), T_BYTE);
 8787   assert(condensed_start, "condensed is null");
 8788   Node* parsed_start  = array_element_address(parsed, intcon(0), T_SHORT);
 8789   assert(parsed_start, "parsed is null");
 8790   Node* kyber12To16 = make_runtime_call(RC_LEAF|RC_NO_FP,
 8791                                   OptoRuntime::kyber12To16_Type(),
 8792                                   stubAddr, stubName, TypePtr::BOTTOM,
 8793                                   condensed_start, condensedOffs, parsed_start, parsedLength);
 8794   // return an int
 8795   Node* retvalue = _gvn.transform(new ProjNode(kyber12To16, TypeFunc::Parms));
 8796   set_result(retvalue);
 8797   return true;
 8798 
 8799 }
 8800 
 8801 //------------------------------inline_kyberBarrettReduce
 8802 bool LibraryCallKit::inline_kyberBarrettReduce() {
 8803   address stubAddr;
 8804   const char *stubName;
 8805   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
 8806   assert(callee()->signature()->size() == 1, "kyberBarrettReduce has 1 parameters");
 8807 
 8808   stubAddr = StubRoutines::kyberBarrettReduce();
 8809   stubName = "kyberBarrettReduce";
 8810   if (!stubAddr) return false;
 8811 
 8812   Node* coeffs          = argument(0);
 8813 
 8814   coeffs = must_be_not_null(coeffs, true);
 8815 
 8816   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_SHORT);
 8817   assert(coeffs_start, "coeffs is null");
 8818   Node* kyberBarrettReduce = make_runtime_call(RC_LEAF|RC_NO_FP,
 8819                                   OptoRuntime::kyberBarrettReduce_Type(),
 8820                                   stubAddr, stubName, TypePtr::BOTTOM,
 8821                                   coeffs_start);
 8822   // return an int
 8823   Node* retvalue = _gvn.transform(new ProjNode(kyberBarrettReduce, TypeFunc::Parms));
 8824   set_result(retvalue);
 8825   return true;
 8826 }
 8827 
 8828 //------------------------------inline_dilithiumAlmostNtt
 8829 bool LibraryCallKit::inline_dilithiumAlmostNtt() {
 8830   address stubAddr;
 8831   const char *stubName;
 8832   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
 8833   assert(callee()->signature()->size() == 2, "dilithiumAlmostNtt has 2 parameters");
 8834 
 8835   stubAddr = StubRoutines::dilithiumAlmostNtt();
 8836   stubName = "dilithiumAlmostNtt";
 8837   if (!stubAddr) return false;
 8838 
 8839   Node* coeffs          = argument(0);
 8840   Node* ntt_zetas        = argument(1);
 8841 
 8842   coeffs = must_be_not_null(coeffs, true);
 8843   ntt_zetas = must_be_not_null(ntt_zetas, true);
 8844 
 8845   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_INT);
 8846   assert(coeffs_start, "coeffs is null");
 8847   Node* ntt_zetas_start  = array_element_address(ntt_zetas, intcon(0), T_INT);
 8848   assert(ntt_zetas_start, "ntt_zetas is null");
 8849   Node* dilithiumAlmostNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
 8850                                   OptoRuntime::dilithiumAlmostNtt_Type(),
 8851                                   stubAddr, stubName, TypePtr::BOTTOM,
 8852                                   coeffs_start, ntt_zetas_start);
 8853   // return an int
 8854   Node* retvalue = _gvn.transform(new ProjNode(dilithiumAlmostNtt, TypeFunc::Parms));
 8855   set_result(retvalue);
 8856   return true;
 8857 }
 8858 
 8859 //------------------------------inline_dilithiumAlmostInverseNtt
 8860 bool LibraryCallKit::inline_dilithiumAlmostInverseNtt() {
 8861   address stubAddr;
 8862   const char *stubName;
 8863   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
 8864   assert(callee()->signature()->size() == 2, "dilithiumAlmostInverseNtt has 2 parameters");
 8865 
 8866   stubAddr = StubRoutines::dilithiumAlmostInverseNtt();
 8867   stubName = "dilithiumAlmostInverseNtt";
 8868   if (!stubAddr) return false;
 8869 
 8870   Node* coeffs          = argument(0);
 8871   Node* zetas           = argument(1);
 8872 
 8873   coeffs = must_be_not_null(coeffs, true);
 8874   zetas = must_be_not_null(zetas, true);
 8875 
 8876   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_INT);
 8877   assert(coeffs_start, "coeffs is null");
 8878   Node* zetas_start  = array_element_address(zetas, intcon(0), T_INT);
 8879   assert(zetas_start, "inverseNtt_zetas is null");
 8880   Node* dilithiumAlmostInverseNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
 8881                                   OptoRuntime::dilithiumAlmostInverseNtt_Type(),
 8882                                   stubAddr, stubName, TypePtr::BOTTOM,
 8883                                   coeffs_start, zetas_start);
 8884   // return an int
 8885   Node* retvalue = _gvn.transform(new ProjNode(dilithiumAlmostInverseNtt, TypeFunc::Parms));
 8886   set_result(retvalue);
 8887   return true;
 8888 }
 8889 
 8890 //------------------------------inline_dilithiumNttMult
 8891 bool LibraryCallKit::inline_dilithiumNttMult() {
 8892   address stubAddr;
 8893   const char *stubName;
 8894   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
 8895   assert(callee()->signature()->size() == 3, "dilithiumNttMult has 3 parameters");
 8896 
 8897   stubAddr = StubRoutines::dilithiumNttMult();
 8898   stubName = "dilithiumNttMult";
 8899   if (!stubAddr) return false;
 8900 
 8901   Node* result          = argument(0);
 8902   Node* ntta            = argument(1);
 8903   Node* nttb            = argument(2);
 8904   Node* zetas           = argument(3);
 8905 
 8906   result = must_be_not_null(result, true);
 8907   ntta = must_be_not_null(ntta, true);
 8908   nttb = must_be_not_null(nttb, true);
 8909   zetas = must_be_not_null(zetas, true);
 8910 
 8911   Node* result_start  = array_element_address(result, intcon(0), T_INT);
 8912   assert(result_start, "result is null");
 8913   Node* ntta_start  = array_element_address(ntta, intcon(0), T_INT);
 8914   assert(ntta_start, "ntta is null");
 8915   Node* nttb_start  = array_element_address(nttb, intcon(0), T_INT);
 8916   assert(nttb_start, "nttb is null");
 8917   Node* dilithiumNttMult = make_runtime_call(RC_LEAF|RC_NO_FP,
 8918                                   OptoRuntime::dilithiumNttMult_Type(),
 8919                                   stubAddr, stubName, TypePtr::BOTTOM,
 8920                                   result_start, ntta_start, nttb_start);
 8921 
 8922   // return an int
 8923   Node* retvalue = _gvn.transform(new ProjNode(dilithiumNttMult, TypeFunc::Parms));
 8924   set_result(retvalue);
 8925 
 8926   return true;
 8927 }
 8928 
 8929 //------------------------------inline_dilithiumMontMulByConstant
 8930 bool LibraryCallKit::inline_dilithiumMontMulByConstant() {
 8931   address stubAddr;
 8932   const char *stubName;
 8933   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
 8934   assert(callee()->signature()->size() == 2, "dilithiumMontMulByConstant has 2 parameters");
 8935 
 8936   stubAddr = StubRoutines::dilithiumMontMulByConstant();
 8937   stubName = "dilithiumMontMulByConstant";
 8938   if (!stubAddr) return false;
 8939 
 8940   Node* coeffs          = argument(0);
 8941   Node* constant        = argument(1);
 8942 
 8943   coeffs = must_be_not_null(coeffs, true);
 8944 
 8945   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_INT);
 8946   assert(coeffs_start, "coeffs is null");
 8947   Node* dilithiumMontMulByConstant = make_runtime_call(RC_LEAF|RC_NO_FP,
 8948                                   OptoRuntime::dilithiumMontMulByConstant_Type(),
 8949                                   stubAddr, stubName, TypePtr::BOTTOM,
 8950                                   coeffs_start, constant);
 8951 
 8952   // return an int
 8953   Node* retvalue = _gvn.transform(new ProjNode(dilithiumMontMulByConstant, TypeFunc::Parms));
 8954   set_result(retvalue);
 8955   return true;
 8956 }
 8957 
 8958 
 8959 //------------------------------inline_dilithiumDecomposePoly
 8960 bool LibraryCallKit::inline_dilithiumDecomposePoly() {
 8961   address stubAddr;
 8962   const char *stubName;
 8963   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
 8964   assert(callee()->signature()->size() == 5, "dilithiumDecomposePoly has 5 parameters");
 8965 
 8966   stubAddr = StubRoutines::dilithiumDecomposePoly();
 8967   stubName = "dilithiumDecomposePoly";
 8968   if (!stubAddr) return false;
 8969 
 8970   Node* input          = argument(0);
 8971   Node* lowPart        = argument(1);
 8972   Node* highPart       = argument(2);
 8973   Node* twoGamma2      = argument(3);
 8974   Node* multiplier     = argument(4);
 8975 
 8976   input = must_be_not_null(input, true);
 8977   lowPart = must_be_not_null(lowPart, true);
 8978   highPart = must_be_not_null(highPart, true);
 8979 
 8980   Node* input_start  = array_element_address(input, intcon(0), T_INT);
 8981   assert(input_start, "input is null");
 8982   Node* lowPart_start  = array_element_address(lowPart, intcon(0), T_INT);
 8983   assert(lowPart_start, "lowPart is null");
 8984   Node* highPart_start  = array_element_address(highPart, intcon(0), T_INT);
 8985   assert(highPart_start, "highPart is null");
 8986 
 8987   Node* dilithiumDecomposePoly = make_runtime_call(RC_LEAF|RC_NO_FP,
 8988                                   OptoRuntime::dilithiumDecomposePoly_Type(),
 8989                                   stubAddr, stubName, TypePtr::BOTTOM,
 8990                                   input_start, lowPart_start, highPart_start,
 8991                                   twoGamma2, multiplier);
 8992 
 8993   // return an int
 8994   Node* retvalue = _gvn.transform(new ProjNode(dilithiumDecomposePoly, TypeFunc::Parms));
 8995   set_result(retvalue);
 8996   return true;
 8997 }
 8998 
 8999 bool LibraryCallKit::inline_base64_encodeBlock() {
 9000   address stubAddr;
 9001   const char *stubName;
 9002   assert(UseBASE64Intrinsics, "need Base64 intrinsics support");
 9003   assert(callee()->signature()->size() == 6, "base64_encodeBlock has 6 parameters");
 9004   stubAddr = StubRoutines::base64_encodeBlock();
 9005   stubName = "encodeBlock";
 9006 
 9007   if (!stubAddr) return false;
 9008   Node* base64obj = argument(0);
 9009   Node* src = argument(1);
 9010   Node* offset = argument(2);
 9011   Node* len = argument(3);
 9012   Node* dest = argument(4);
 9013   Node* dp = argument(5);
 9014   Node* isURL = argument(6);
 9015 
 9016   src = must_be_not_null(src, true);
 9017   dest = must_be_not_null(dest, true);
 9018 
 9019   Node* src_start = array_element_address(src, intcon(0), T_BYTE);
 9020   assert(src_start, "source array is null");
 9021   Node* dest_start = array_element_address(dest, intcon(0), T_BYTE);
 9022   assert(dest_start, "destination array is null");
 9023 
 9024   Node* base64 = make_runtime_call(RC_LEAF,
 9025                                    OptoRuntime::base64_encodeBlock_Type(),
 9026                                    stubAddr, stubName, TypePtr::BOTTOM,
 9027                                    src_start, offset, len, dest_start, dp, isURL);
 9028   return true;
 9029 }
 9030 
 9031 bool LibraryCallKit::inline_base64_decodeBlock() {
 9032   address stubAddr;
 9033   const char *stubName;
 9034   assert(UseBASE64Intrinsics, "need Base64 intrinsics support");
 9035   assert(callee()->signature()->size() == 7, "base64_decodeBlock has 7 parameters");
 9036   stubAddr = StubRoutines::base64_decodeBlock();
 9037   stubName = "decodeBlock";
 9038 
 9039   if (!stubAddr) return false;
 9040   Node* base64obj = argument(0);
 9041   Node* src = argument(1);
 9042   Node* src_offset = argument(2);
 9043   Node* len = argument(3);
 9044   Node* dest = argument(4);
 9045   Node* dest_offset = argument(5);
 9046   Node* isURL = argument(6);
 9047   Node* isMIME = argument(7);
 9048 
 9049   src = must_be_not_null(src, true);
 9050   dest = must_be_not_null(dest, true);
 9051 
 9052   Node* src_start = array_element_address(src, intcon(0), T_BYTE);
 9053   assert(src_start, "source array is null");
 9054   Node* dest_start = array_element_address(dest, intcon(0), T_BYTE);
 9055   assert(dest_start, "destination array is null");
 9056 
 9057   Node* call = make_runtime_call(RC_LEAF,
 9058                                  OptoRuntime::base64_decodeBlock_Type(),
 9059                                  stubAddr, stubName, TypePtr::BOTTOM,
 9060                                  src_start, src_offset, len, dest_start, dest_offset, isURL, isMIME);
 9061   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
 9062   set_result(result);
 9063   return true;
 9064 }
 9065 
 9066 bool LibraryCallKit::inline_poly1305_processBlocks() {
 9067   address stubAddr;
 9068   const char *stubName;
 9069   assert(UsePoly1305Intrinsics, "need Poly intrinsics support");
 9070   assert(callee()->signature()->size() == 5, "poly1305_processBlocks has %d parameters", callee()->signature()->size());
 9071   stubAddr = StubRoutines::poly1305_processBlocks();
 9072   stubName = "poly1305_processBlocks";
 9073 
 9074   if (!stubAddr) return false;
 9075   null_check_receiver();  // null-check receiver
 9076   if (stopped())  return true;
 9077 
 9078   Node* input = argument(1);
 9079   Node* input_offset = argument(2);
 9080   Node* len = argument(3);
 9081   Node* alimbs = argument(4);
 9082   Node* rlimbs = argument(5);
 9083 
 9084   input = must_be_not_null(input, true);
 9085   alimbs = must_be_not_null(alimbs, true);
 9086   rlimbs = must_be_not_null(rlimbs, true);
 9087 
 9088   Node* input_start = array_element_address(input, input_offset, T_BYTE);
 9089   assert(input_start, "input array is null");
 9090   Node* acc_start = array_element_address(alimbs, intcon(0), T_LONG);
 9091   assert(acc_start, "acc array is null");
 9092   Node* r_start = array_element_address(rlimbs, intcon(0), T_LONG);
 9093   assert(r_start, "r array is null");
 9094 
 9095   Node* call = make_runtime_call(RC_LEAF | RC_NO_FP,
 9096                                  OptoRuntime::poly1305_processBlocks_Type(),
 9097                                  stubAddr, stubName, TypePtr::BOTTOM,
 9098                                  input_start, len, acc_start, r_start);
 9099   return true;
 9100 }
 9101 
 9102 bool LibraryCallKit::inline_intpoly_montgomeryMult_P256() {
 9103   address stubAddr;
 9104   const char *stubName;
 9105   assert(UseIntPolyIntrinsics, "need intpoly intrinsics support");
 9106   assert(callee()->signature()->size() == 3, "intpoly_montgomeryMult_P256 has %d parameters", callee()->signature()->size());
 9107   stubAddr = StubRoutines::intpoly_montgomeryMult_P256();
 9108   stubName = "intpoly_montgomeryMult_P256";
 9109 
 9110   if (!stubAddr) return false;
 9111   null_check_receiver();  // null-check receiver
 9112   if (stopped())  return true;
 9113 
 9114   Node* a = argument(1);
 9115   Node* b = argument(2);
 9116   Node* r = argument(3);
 9117 
 9118   a = must_be_not_null(a, true);
 9119   b = must_be_not_null(b, true);
 9120   r = must_be_not_null(r, true);
 9121 
 9122   Node* a_start = array_element_address(a, intcon(0), T_LONG);
 9123   assert(a_start, "a array is null");
 9124   Node* b_start = array_element_address(b, intcon(0), T_LONG);
 9125   assert(b_start, "b array is null");
 9126   Node* r_start = array_element_address(r, intcon(0), T_LONG);
 9127   assert(r_start, "r array is null");
 9128 
 9129   Node* call = make_runtime_call(RC_LEAF | RC_NO_FP,
 9130                                  OptoRuntime::intpoly_montgomeryMult_P256_Type(),
 9131                                  stubAddr, stubName, TypePtr::BOTTOM,
 9132                                  a_start, b_start, r_start);
 9133   return true;
 9134 }
 9135 
 9136 bool LibraryCallKit::inline_intpoly_assign() {
 9137   assert(UseIntPolyIntrinsics, "need intpoly intrinsics support");
 9138   assert(callee()->signature()->size() == 3, "intpoly_assign has %d parameters", callee()->signature()->size());
 9139   const char *stubName = "intpoly_assign";
 9140   address stubAddr = StubRoutines::intpoly_assign();
 9141   if (!stubAddr) return false;
 9142 
 9143   Node* set = argument(0);
 9144   Node* a = argument(1);
 9145   Node* b = argument(2);
 9146   Node* arr_length = load_array_length(a);
 9147 
 9148   a = must_be_not_null(a, true);
 9149   b = must_be_not_null(b, true);
 9150 
 9151   Node* a_start = array_element_address(a, intcon(0), T_LONG);
 9152   assert(a_start, "a array is null");
 9153   Node* b_start = array_element_address(b, intcon(0), T_LONG);
 9154   assert(b_start, "b array is null");
 9155 
 9156   Node* call = make_runtime_call(RC_LEAF | RC_NO_FP,
 9157                                  OptoRuntime::intpoly_assign_Type(),
 9158                                  stubAddr, stubName, TypePtr::BOTTOM,
 9159                                  set, a_start, b_start, arr_length);
 9160   return true;
 9161 }
 9162 
 9163 bool LibraryCallKit::inline_intpoly_mult_25519() {
 9164   address stubAddr;
 9165   const char *stubName;
 9166   assert(UseIntPoly25519Intrinsics, "need intpoly25519 intrinsics support");
 9167   assert(callee()->signature()->size() == 3, "intpoly_mult_25519 has %d parameters", callee()->signature()->size());
 9168   stubAddr = StubRoutines::intpoly_mult_25519();
 9169   stubName = "intpoly_mult_25519";
 9170 
 9171   if (!stubAddr) return false;
 9172   null_check_receiver();  // null-check receiver
 9173   if (stopped())  return true;
 9174 
 9175   Node* a = argument(1);
 9176   Node* b = argument(2);
 9177   Node* r = argument(3);
 9178 
 9179   a = must_be_not_null(a, true);
 9180   b = must_be_not_null(b, true);
 9181   r = must_be_not_null(r, true);
 9182 
 9183   Node* a_start = array_element_address(a, intcon(0), T_LONG);
 9184   assert(a_start, "a array is null");
 9185   Node* b_start = array_element_address(b, intcon(0), T_LONG);
 9186   assert(b_start, "b array is null");
 9187   Node* r_start = array_element_address(r, intcon(0), T_LONG);
 9188   assert(r_start, "r array is null");
 9189 
 9190   Node* call = make_runtime_call(RC_LEAF | RC_NO_FP,
 9191                                  OptoRuntime::intpoly_mult_25519_Type(),
 9192                                  stubAddr, stubName, TypePtr::BOTTOM,
 9193                                  a_start, b_start, r_start);
 9194   return true;
 9195 }
 9196 
 9197 bool LibraryCallKit::inline_intpoly_square_25519() {
 9198   address stubAddr;
 9199   const char *stubName;
 9200   assert(UseIntPoly25519Intrinsics, "need intpoly25519 intrinsics support");
 9201   assert(callee()->signature()->size() == 2, "intpoly_mult_25519 has %d parameters", callee()->signature()->size());
 9202   stubAddr = StubRoutines::intpoly_square_25519();
 9203   stubName = "intpoly_square_25519";
 9204 
 9205   if (!stubAddr) return false;
 9206   null_check_receiver();  // null-check receiver
 9207   if (stopped())  return true;
 9208 
 9209   Node* a = argument(1);
 9210   Node* r = argument(2);
 9211 
 9212   a = must_be_not_null(a, true);
 9213   r = must_be_not_null(r, true);
 9214 
 9215   Node* a_start = array_element_address(a, intcon(0), T_LONG);
 9216   assert(a_start, "a array is null");
 9217   Node* r_start = array_element_address(r, intcon(0), T_LONG);
 9218   assert(r_start, "r array is null");
 9219 
 9220   Node* call = make_runtime_call(RC_LEAF | RC_NO_FP,
 9221                                  OptoRuntime::intpoly_square_25519_Type(),
 9222                                  stubAddr, stubName, TypePtr::BOTTOM,
 9223                                  a_start, r_start);
 9224   return true;
 9225 }
 9226 
 9227 //------------------------------inline_digestBase_implCompress-----------------------
 9228 //
 9229 // Calculate MD5 for single-block byte[] array.
 9230 // void com.sun.security.provider.MD5.implCompress(byte[] buf, int ofs)
 9231 //
 9232 // Calculate SHA (i.e., SHA-1) for single-block byte[] array.
 9233 // void com.sun.security.provider.SHA.implCompress(byte[] buf, int ofs)
 9234 //
 9235 // Calculate SHA2 (i.e., SHA-244 or SHA-256) for single-block byte[] array.
 9236 // void com.sun.security.provider.SHA2.implCompress(byte[] buf, int ofs)
 9237 //
 9238 // Calculate SHA5 (i.e., SHA-384 or SHA-512) for single-block byte[] array.
 9239 // void com.sun.security.provider.SHA5.implCompress(byte[] buf, int ofs)
 9240 //
 9241 // Calculate SHA3 (i.e., SHA3-224 or SHA3-256 or SHA3-384 or SHA3-512) for single-block byte[] array.
 9242 // void com.sun.security.provider.SHA3.implCompress(byte[] buf, int ofs)
 9243 //
 9244 bool LibraryCallKit::inline_digestBase_implCompress(vmIntrinsics::ID id) {
 9245   assert(callee()->signature()->size() == 2, "sha_implCompress has 2 parameters");
 9246 
 9247   Node* digestBase_obj = argument(0);
 9248   Node* src            = argument(1); // type oop
 9249   Node* ofs            = argument(2); // type int
 9250 
 9251   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
 9252   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
 9253     // failed array check
 9254     return false;
 9255   }
 9256   // Figure out the size and type of the elements we will be copying.
 9257   BasicType src_elem = src_type->elem()->array_element_basic_type();
 9258   if (src_elem != T_BYTE) {
 9259     return false;
 9260   }
 9261   // 'src_start' points to src array + offset
 9262   src = must_be_not_null(src, true);
 9263   Node* src_start = array_element_address(src, ofs, src_elem);
 9264   Node* state = nullptr;
 9265   Node* block_size = nullptr;
 9266   address stubAddr;
 9267   const char *stubName;
 9268 
 9269   switch(id) {
 9270   case vmIntrinsics::_md5_implCompress:
 9271     assert(UseMD5Intrinsics, "need MD5 instruction support");
 9272     state = get_state_from_digest_object(digestBase_obj, T_INT);
 9273     stubAddr = StubRoutines::md5_implCompress();
 9274     stubName = "md5_implCompress";
 9275     break;
 9276   case vmIntrinsics::_sha_implCompress:
 9277     assert(UseSHA1Intrinsics, "need SHA1 instruction support");
 9278     state = get_state_from_digest_object(digestBase_obj, T_INT);
 9279     stubAddr = StubRoutines::sha1_implCompress();
 9280     stubName = "sha1_implCompress";
 9281     break;
 9282   case vmIntrinsics::_sha2_implCompress:
 9283     assert(UseSHA256Intrinsics, "need SHA256 instruction support");
 9284     state = get_state_from_digest_object(digestBase_obj, T_INT);
 9285     stubAddr = StubRoutines::sha256_implCompress();
 9286     stubName = "sha256_implCompress";
 9287     break;
 9288   case vmIntrinsics::_sha5_implCompress:
 9289     assert(UseSHA512Intrinsics, "need SHA512 instruction support");
 9290     state = get_state_from_digest_object(digestBase_obj, T_LONG);
 9291     stubAddr = StubRoutines::sha512_implCompress();
 9292     stubName = "sha512_implCompress";
 9293     break;
 9294   case vmIntrinsics::_sha3_implCompress:
 9295     assert(UseSHA3Intrinsics, "need SHA3 instruction support");
 9296     state = get_state_from_digest_object(digestBase_obj, T_LONG);
 9297     stubAddr = StubRoutines::sha3_implCompress();
 9298     stubName = "sha3_implCompress";
 9299     block_size = get_block_size_from_digest_object(digestBase_obj);
 9300     if (block_size == nullptr) return false;
 9301     break;
 9302   default:
 9303     fatal_unexpected_iid(id);
 9304     return false;
 9305   }
 9306   if (state == nullptr) return false;
 9307 
 9308   assert(stubAddr != nullptr, "Stub %s is not generated", stubName);
 9309   if (stubAddr == nullptr) return false;
 9310 
 9311   // Call the stub.
 9312   Node* call;
 9313   if (block_size == nullptr) {
 9314     call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::digestBase_implCompress_Type(false),
 9315                              stubAddr, stubName, TypePtr::BOTTOM,
 9316                              src_start, state);
 9317   } else {
 9318     call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::digestBase_implCompress_Type(true),
 9319                              stubAddr, stubName, TypePtr::BOTTOM,
 9320                              src_start, state, block_size);
 9321   }
 9322 
 9323   return true;
 9324 }
 9325 
 9326 //------------------------------inline_keccak
 9327 bool LibraryCallKit::inline_keccak(vmIntrinsics::ID id) {
 9328   address stubAddr = nullptr;
 9329   const char *stubName;
 9330   assert(UseSHA3Intrinsics, "need SHA3 intrinsics support");
 9331   assert((id == vmIntrinsics::_double_keccak && callee()->signature()->size() == 2) ||
 9332          (id == vmIntrinsics::_quad_keccak && callee()->signature()->size() == 4),
 9333           "double_keccak wrong number of parameters");
 9334 
 9335   int parmCnt = 0;
 9336   switch (id) {
 9337     case vmIntrinsics::_double_keccak:
 9338       stubAddr = StubRoutines::double_keccak();
 9339       stubName = "double_keccak";
 9340       parmCnt = 2;
 9341       break;
 9342     case vmIntrinsics::_quad_keccak:
 9343       stubAddr = StubRoutines::quad_keccak();
 9344       stubName = "quad_keccak";
 9345       parmCnt = 4;
 9346       break;
 9347     default:
 9348       ShouldNotReachHere();
 9349   }
 9350 
 9351   if (!stubAddr) return false;
 9352 
 9353   Node* state[4];
 9354   for (int i = 0; i<parmCnt; i++) {
 9355       state[i] = must_be_not_null(argument(i), true);
 9356       state[i] = array_element_address(state[i], intcon(0), T_LONG);
 9357       assert(state[i], "state[%d] is null", i);
 9358   }
 9359 
 9360   Node* keccak;
 9361   switch (id) {
 9362     case vmIntrinsics::_double_keccak:
 9363       keccak = make_runtime_call(RC_LEAF|RC_NO_FP,
 9364                                   OptoRuntime::double_keccak_Type(),
 9365                                   stubAddr, stubName, TypePtr::BOTTOM,
 9366                                   state[0], state[1]);
 9367       break;
 9368     case vmIntrinsics::_quad_keccak:
 9369       keccak = make_runtime_call(RC_LEAF|RC_NO_FP,
 9370                                   OptoRuntime::quad_keccak_Type(),
 9371                                   stubAddr, stubName, TypePtr::BOTTOM,
 9372                                   state[0], state[1], state[2], state[3]);
 9373       break;
 9374     default:
 9375       ShouldNotReachHere();
 9376   }
 9377 
 9378   // return an int
 9379   Node* retvalue = _gvn.transform(new ProjNode(keccak, TypeFunc::Parms));
 9380   set_result(retvalue);
 9381   return true;
 9382 }
 9383 
 9384 
 9385 //------------------------------inline_digestBase_implCompressMB-----------------------
 9386 //
 9387 // Calculate MD5/SHA/SHA2/SHA5/SHA3 for multi-block byte[] array.
 9388 // int com.sun.security.provider.DigestBase.implCompressMultiBlock(byte[] b, int ofs, int limit)
 9389 //
 9390 bool LibraryCallKit::inline_digestBase_implCompressMB(int predicate) {
 9391   assert(UseMD5Intrinsics || UseSHA1Intrinsics || UseSHA256Intrinsics || UseSHA512Intrinsics || UseSHA3Intrinsics,
 9392          "need MD5/SHA1/SHA256/SHA512/SHA3 instruction support");
 9393   assert((uint)predicate < 5, "sanity");
 9394   assert(callee()->signature()->size() == 3, "digestBase_implCompressMB has 3 parameters");
 9395 
 9396   Node* digestBase_obj = argument(0); // The receiver was checked for null already.
 9397   Node* src            = argument(1); // byte[] array
 9398   Node* ofs            = argument(2); // type int
 9399   Node* limit          = argument(3); // type int
 9400 
 9401   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
 9402   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
 9403     // failed array check
 9404     return false;
 9405   }
 9406   // Figure out the size and type of the elements we will be copying.
 9407   BasicType src_elem = src_type->elem()->array_element_basic_type();
 9408   if (src_elem != T_BYTE) {
 9409     return false;
 9410   }
 9411   // 'src_start' points to src array + offset
 9412   src = must_be_not_null(src, false);
 9413   Node* src_start = array_element_address(src, ofs, src_elem);
 9414 
 9415   const char* klass_digestBase_name = nullptr;
 9416   const char* stub_name = nullptr;
 9417   address     stub_addr = nullptr;
 9418   BasicType elem_type = T_INT;
 9419 
 9420   switch (predicate) {
 9421   case 0:
 9422     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_md5_implCompress)) {
 9423       klass_digestBase_name = "sun/security/provider/MD5";
 9424       stub_name = "md5_implCompressMB";
 9425       stub_addr = StubRoutines::md5_implCompressMB();
 9426     }
 9427     break;
 9428   case 1:
 9429     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha_implCompress)) {
 9430       klass_digestBase_name = "sun/security/provider/SHA";
 9431       stub_name = "sha1_implCompressMB";
 9432       stub_addr = StubRoutines::sha1_implCompressMB();
 9433     }
 9434     break;
 9435   case 2:
 9436     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha2_implCompress)) {
 9437       klass_digestBase_name = "sun/security/provider/SHA2";
 9438       stub_name = "sha256_implCompressMB";
 9439       stub_addr = StubRoutines::sha256_implCompressMB();
 9440     }
 9441     break;
 9442   case 3:
 9443     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha5_implCompress)) {
 9444       klass_digestBase_name = "sun/security/provider/SHA5";
 9445       stub_name = "sha512_implCompressMB";
 9446       stub_addr = StubRoutines::sha512_implCompressMB();
 9447       elem_type = T_LONG;
 9448     }
 9449     break;
 9450   case 4:
 9451     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha3_implCompress)) {
 9452       klass_digestBase_name = "sun/security/provider/SHA3";
 9453       stub_name = "sha3_implCompressMB";
 9454       stub_addr = StubRoutines::sha3_implCompressMB();
 9455       elem_type = T_LONG;
 9456     }
 9457     break;
 9458   default:
 9459     fatal("unknown DigestBase intrinsic predicate: %d", predicate);
 9460   }
 9461   if (klass_digestBase_name != nullptr) {
 9462     assert(stub_addr != nullptr, "Stub is generated");
 9463     if (stub_addr == nullptr) return false;
 9464 
 9465     // get DigestBase klass to lookup for SHA klass
 9466     const TypeInstPtr* tinst = _gvn.type(digestBase_obj)->isa_instptr();
 9467     assert(tinst != nullptr, "digestBase_obj is not instance???");
 9468     assert(tinst->is_loaded(), "DigestBase is not loaded");
 9469 
 9470     ciKlass* klass_digestBase = tinst->instance_klass()->find_klass(ciSymbol::make(klass_digestBase_name));
 9471     assert(klass_digestBase->is_loaded(), "predicate checks that this class is loaded");
 9472     ciInstanceKlass* instklass_digestBase = klass_digestBase->as_instance_klass();
 9473     return inline_digestBase_implCompressMB(digestBase_obj, instklass_digestBase, elem_type, stub_addr, stub_name, src_start, ofs, limit);
 9474   }
 9475   return false;
 9476 }
 9477 
 9478 //------------------------------inline_digestBase_implCompressMB-----------------------
 9479 bool LibraryCallKit::inline_digestBase_implCompressMB(Node* digestBase_obj, ciInstanceKlass* instklass_digestBase,
 9480                                                       BasicType elem_type, address stubAddr, const char *stubName,
 9481                                                       Node* src_start, Node* ofs, Node* limit) {
 9482   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_digestBase);
 9483   const TypeOopPtr* xtype = aklass->as_subtype_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
 9484   Node* digest_obj = new CheckCastPPNode(control(), digestBase_obj, xtype);
 9485   digest_obj = _gvn.transform(digest_obj);
 9486 
 9487   Node* state = get_state_from_digest_object(digest_obj, elem_type);
 9488   if (state == nullptr) return false;
 9489 
 9490   Node* block_size = nullptr;
 9491   if (strcmp("sha3_implCompressMB", stubName) == 0) {
 9492     block_size = get_block_size_from_digest_object(digest_obj);
 9493     if (block_size == nullptr) return false;
 9494   }
 9495 
 9496   // Call the stub.
 9497   Node* call;
 9498   if (block_size == nullptr) {
 9499     call = make_runtime_call(RC_LEAF|RC_NO_FP,
 9500                              OptoRuntime::digestBase_implCompressMB_Type(false),
 9501                              stubAddr, stubName, TypePtr::BOTTOM,
 9502                              src_start, state, ofs, limit);
 9503   } else {
 9504      call = make_runtime_call(RC_LEAF|RC_NO_FP,
 9505                              OptoRuntime::digestBase_implCompressMB_Type(true),
 9506                              stubAddr, stubName, TypePtr::BOTTOM,
 9507                              src_start, state, block_size, ofs, limit);
 9508   }
 9509 
 9510   // return ofs (int)
 9511   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
 9512   set_result(result);
 9513 
 9514   return true;
 9515 }
 9516 
 9517 //------------------------------inline_galoisCounterMode_AESCrypt-----------------------
 9518 bool LibraryCallKit::inline_galoisCounterMode_AESCrypt() {
 9519   assert(UseAES, "need AES instruction support");
 9520   address stubAddr = nullptr;
 9521   const char *stubName = nullptr;
 9522   stubAddr = StubRoutines::galoisCounterMode_AESCrypt();
 9523   stubName = "galoisCounterMode_AESCrypt";
 9524 
 9525   if (stubAddr == nullptr) return false;
 9526 
 9527   Node* in      = argument(0);
 9528   Node* inOfs   = argument(1);
 9529   Node* len     = argument(2);
 9530   Node* ct      = argument(3);
 9531   Node* ctOfs   = argument(4);
 9532   Node* out     = argument(5);
 9533   Node* outOfs  = argument(6);
 9534   Node* gctr_object = argument(7);
 9535   Node* ghash_object = argument(8);
 9536 
 9537   // (1) in, ct and out are arrays.
 9538   const TypeAryPtr* in_type = in->Value(&_gvn)->isa_aryptr();
 9539   const TypeAryPtr* ct_type = ct->Value(&_gvn)->isa_aryptr();
 9540   const TypeAryPtr* out_type = out->Value(&_gvn)->isa_aryptr();
 9541   assert( in_type != nullptr &&  in_type->elem() != Type::BOTTOM &&
 9542           ct_type != nullptr &&  ct_type->elem() != Type::BOTTOM &&
 9543          out_type != nullptr && out_type->elem() != Type::BOTTOM, "args are strange");
 9544 
 9545   // checks are the responsibility of the caller
 9546   Node* in_start = in;
 9547   Node* ct_start = ct;
 9548   Node* out_start = out;
 9549   if (inOfs != nullptr || ctOfs != nullptr || outOfs != nullptr) {
 9550     assert(inOfs != nullptr && ctOfs != nullptr && outOfs != nullptr, "");
 9551     in_start = array_element_address(in, inOfs, T_BYTE);
 9552     ct_start = array_element_address(ct, ctOfs, T_BYTE);
 9553     out_start = array_element_address(out, outOfs, T_BYTE);
 9554   }
 9555 
 9556   // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
 9557   // (because of the predicated logic executed earlier).
 9558   // so we cast it here safely.
 9559   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
 9560   Node* embeddedCipherObj = load_field_from_object(gctr_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
 9561   Node* counter = load_field_from_object(gctr_object, "counter", "[B");
 9562   Node* subkeyHtbl = load_field_from_object(ghash_object, "subkeyHtbl", "[J");
 9563   Node* state = load_field_from_object(ghash_object, "state", "[J");
 9564 
 9565   if (embeddedCipherObj == nullptr || counter == nullptr || subkeyHtbl == nullptr || state == nullptr) {
 9566     return false;
 9567   }
 9568   // cast it to what we know it will be at runtime
 9569   const TypeInstPtr* tinst = _gvn.type(gctr_object)->isa_instptr();
 9570   assert(tinst != nullptr, "GCTR obj is null");
 9571   assert(tinst->is_loaded(), "GCTR obj is not loaded");
 9572   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
 9573   assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
 9574   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
 9575   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
 9576   const TypeOopPtr* xtype = aklass->as_exact_instance_type();
 9577   Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
 9578   aescrypt_object = _gvn.transform(aescrypt_object);
 9579   // we need to get the start of the aescrypt_object's expanded key array
 9580   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object, /* is_decrypt */ false);
 9581   if (k_start == nullptr) return false;
 9582   // similarly, get the start address of the r vector
 9583   Node* cnt_start = array_element_address(counter, intcon(0), T_BYTE);
 9584   Node* state_start = array_element_address(state, intcon(0), T_LONG);
 9585   Node* subkeyHtbl_start = array_element_address(subkeyHtbl, intcon(0), T_LONG);
 9586 
 9587 
 9588   // Call the stub, passing params
 9589   Node* gcmCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
 9590                                OptoRuntime::galoisCounterMode_aescrypt_Type(),
 9591                                stubAddr, stubName, TypePtr::BOTTOM,
 9592                                in_start, len, ct_start, out_start, k_start, state_start, subkeyHtbl_start, cnt_start);
 9593 
 9594   // return cipher length (int)
 9595   Node* retvalue = _gvn.transform(new ProjNode(gcmCrypt, TypeFunc::Parms));
 9596   set_result(retvalue);
 9597 
 9598   return true;
 9599 }
 9600 
 9601 //----------------------------inline_galoisCounterMode_AESCrypt_predicate----------------------------
 9602 // Return node representing slow path of predicate check.
 9603 // the pseudo code we want to emulate with this predicate is:
 9604 // for encryption:
 9605 //    if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
 9606 // for decryption:
 9607 //    if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
 9608 //    note cipher==plain is more conservative than the original java code but that's OK
 9609 //
 9610 
 9611 Node* LibraryCallKit::inline_galoisCounterMode_AESCrypt_predicate() {
 9612   // The receiver was checked for null already.
 9613   Node* objGCTR = argument(7);
 9614   // Load embeddedCipher field of GCTR object.
 9615   Node* embeddedCipherObj = load_field_from_object(objGCTR, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
 9616   assert(embeddedCipherObj != nullptr, "embeddedCipherObj is null");
 9617 
 9618   // get AESCrypt klass for instanceOf check
 9619   // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
 9620   // will have same classloader as CipherBlockChaining object
 9621   const TypeInstPtr* tinst = _gvn.type(objGCTR)->isa_instptr();
 9622   assert(tinst != nullptr, "GCTR obj is null");
 9623   assert(tinst->is_loaded(), "GCTR obj is not loaded");
 9624 
 9625   // we want to do an instanceof comparison against the AESCrypt class
 9626   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
 9627   if (!klass_AESCrypt->is_loaded()) {
 9628     // if AESCrypt is not even loaded, we never take the intrinsic fast path
 9629     Node* ctrl = control();
 9630     set_control(top()); // no regular fast path
 9631     return ctrl;
 9632   }
 9633 
 9634   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
 9635   Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
 9636   Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
 9637   Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
 9638   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
 9639 
 9640   return instof_false; // even if it is null
 9641 }
 9642 
 9643 //------------------------------get_state_from_digest_object-----------------------
 9644 Node * LibraryCallKit::get_state_from_digest_object(Node *digest_object, BasicType elem_type) {
 9645   const char* state_type;
 9646   switch (elem_type) {
 9647     case T_BYTE: state_type = "[B"; break;
 9648     case T_INT:  state_type = "[I"; break;
 9649     case T_LONG: state_type = "[J"; break;
 9650     default: ShouldNotReachHere();
 9651   }
 9652   Node* digest_state = load_field_from_object(digest_object, "state", state_type);
 9653   assert (digest_state != nullptr, "wrong version of sun.security.provider.MD5/SHA/SHA2/SHA5/SHA3");
 9654   if (digest_state == nullptr) return (Node *) nullptr;
 9655 
 9656   // now have the array, need to get the start address of the state array
 9657   Node* state = array_element_address(digest_state, intcon(0), elem_type);
 9658   return state;
 9659 }
 9660 
 9661 //------------------------------get_block_size_from_sha3_object----------------------------------
 9662 Node * LibraryCallKit::get_block_size_from_digest_object(Node *digest_object) {
 9663   Node* block_size = load_field_from_object(digest_object, "blockSize", "I");
 9664   assert (block_size != nullptr, "sanity");
 9665   return block_size;
 9666 }
 9667 
 9668 //----------------------------inline_digestBase_implCompressMB_predicate----------------------------
 9669 // Return node representing slow path of predicate check.
 9670 // the pseudo code we want to emulate with this predicate is:
 9671 //    if (digestBaseObj instanceof MD5/SHA/SHA2/SHA5/SHA3) do_intrinsic, else do_javapath
 9672 //
 9673 Node* LibraryCallKit::inline_digestBase_implCompressMB_predicate(int predicate) {
 9674   assert(UseMD5Intrinsics || UseSHA1Intrinsics || UseSHA256Intrinsics || UseSHA512Intrinsics || UseSHA3Intrinsics,
 9675          "need MD5/SHA1/SHA256/SHA512/SHA3 instruction support");
 9676   assert((uint)predicate < 5, "sanity");
 9677 
 9678   // The receiver was checked for null already.
 9679   Node* digestBaseObj = argument(0);
 9680 
 9681   // get DigestBase klass for instanceOf check
 9682   const TypeInstPtr* tinst = _gvn.type(digestBaseObj)->isa_instptr();
 9683   assert(tinst != nullptr, "digestBaseObj is null");
 9684   assert(tinst->is_loaded(), "DigestBase is not loaded");
 9685 
 9686   const char* klass_name = nullptr;
 9687   switch (predicate) {
 9688   case 0:
 9689     if (UseMD5Intrinsics) {
 9690       // we want to do an instanceof comparison against the MD5 class
 9691       klass_name = "sun/security/provider/MD5";
 9692     }
 9693     break;
 9694   case 1:
 9695     if (UseSHA1Intrinsics) {
 9696       // we want to do an instanceof comparison against the SHA class
 9697       klass_name = "sun/security/provider/SHA";
 9698     }
 9699     break;
 9700   case 2:
 9701     if (UseSHA256Intrinsics) {
 9702       // we want to do an instanceof comparison against the SHA2 class
 9703       klass_name = "sun/security/provider/SHA2";
 9704     }
 9705     break;
 9706   case 3:
 9707     if (UseSHA512Intrinsics) {
 9708       // we want to do an instanceof comparison against the SHA5 class
 9709       klass_name = "sun/security/provider/SHA5";
 9710     }
 9711     break;
 9712   case 4:
 9713     if (UseSHA3Intrinsics) {
 9714       // we want to do an instanceof comparison against the SHA3 class
 9715       klass_name = "sun/security/provider/SHA3";
 9716     }
 9717     break;
 9718   default:
 9719     fatal("unknown SHA intrinsic predicate: %d", predicate);
 9720   }
 9721 
 9722   ciKlass* klass = nullptr;
 9723   if (klass_name != nullptr) {
 9724     klass = tinst->instance_klass()->find_klass(ciSymbol::make(klass_name));
 9725   }
 9726   if ((klass == nullptr) || !klass->is_loaded()) {
 9727     // if none of MD5/SHA/SHA2/SHA5 is loaded, we never take the intrinsic fast path
 9728     Node* ctrl = control();
 9729     set_control(top()); // no intrinsic path
 9730     return ctrl;
 9731   }
 9732   ciInstanceKlass* instklass = klass->as_instance_klass();
 9733 
 9734   Node* instof = gen_instanceof(digestBaseObj, makecon(TypeKlassPtr::make(instklass)));
 9735   Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
 9736   Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
 9737   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
 9738 
 9739   return instof_false;  // even if it is null
 9740 }
 9741 
 9742 //-------------inline_fma-----------------------------------
 9743 bool LibraryCallKit::inline_fma(vmIntrinsics::ID id) {
 9744   Node *a = nullptr;
 9745   Node *b = nullptr;
 9746   Node *c = nullptr;
 9747   Node* result = nullptr;
 9748   switch (id) {
 9749   case vmIntrinsics::_fmaD:
 9750     assert(callee()->signature()->size() == 6, "fma has 3 parameters of size 2 each.");
 9751     // no receiver since it is static method
 9752     a = argument(0);
 9753     b = argument(2);
 9754     c = argument(4);
 9755     result = _gvn.transform(new FmaDNode(a, b, c));
 9756     break;
 9757   case vmIntrinsics::_fmaF:
 9758     assert(callee()->signature()->size() == 3, "fma has 3 parameters of size 1 each.");
 9759     a = argument(0);
 9760     b = argument(1);
 9761     c = argument(2);
 9762     result = _gvn.transform(new FmaFNode(a, b, c));
 9763     break;
 9764   default:
 9765     fatal_unexpected_iid(id);  break;
 9766   }
 9767   set_result(result);
 9768   return true;
 9769 }
 9770 
 9771 bool LibraryCallKit::inline_character_compare(vmIntrinsics::ID id) {
 9772   // argument(0) is receiver
 9773   Node* codePoint = argument(1);
 9774   Node* n = nullptr;
 9775 
 9776   switch (id) {
 9777     case vmIntrinsics::_isDigit :
 9778       n = new DigitNode(control(), codePoint);
 9779       break;
 9780     case vmIntrinsics::_isLowerCase :
 9781       n = new LowerCaseNode(control(), codePoint);
 9782       break;
 9783     case vmIntrinsics::_isUpperCase :
 9784       n = new UpperCaseNode(control(), codePoint);
 9785       break;
 9786     case vmIntrinsics::_isWhitespace :
 9787       n = new WhitespaceNode(control(), codePoint);
 9788       break;
 9789     default:
 9790       fatal_unexpected_iid(id);
 9791   }
 9792 
 9793   set_result(_gvn.transform(n));
 9794   return true;
 9795 }
 9796 
 9797 bool LibraryCallKit::inline_profileBoolean() {
 9798   Node* counts = argument(1);
 9799   const TypeAryPtr* ary = nullptr;
 9800   ciArray* aobj = nullptr;
 9801   if (counts->is_Con()
 9802       && (ary = counts->bottom_type()->isa_aryptr()) != nullptr
 9803       && (aobj = ary->const_oop()->as_array()) != nullptr
 9804       && (aobj->length() == 2)) {
 9805     // Profile is int[2] where [0] and [1] correspond to false and true value occurrences respectively.
 9806     jint false_cnt = aobj->element_value(0).as_int();
 9807     jint  true_cnt = aobj->element_value(1).as_int();
 9808 
 9809     if (C->log() != nullptr) {
 9810       C->log()->elem("observe source='profileBoolean' false='%d' true='%d'",
 9811                      false_cnt, true_cnt);
 9812     }
 9813 
 9814     if (false_cnt + true_cnt == 0) {
 9815       // According to profile, never executed.
 9816       uncommon_trap_exact(Deoptimization::Reason_intrinsic,
 9817                           Deoptimization::Action_reinterpret);
 9818       return true;
 9819     }
 9820 
 9821     // result is a boolean (0 or 1) and its profile (false_cnt & true_cnt)
 9822     // is a number of each value occurrences.
 9823     Node* result = argument(0);
 9824     if (false_cnt == 0 || true_cnt == 0) {
 9825       // According to profile, one value has been never seen.
 9826       int expected_val = (false_cnt == 0) ? 1 : 0;
 9827 
 9828       Node* cmp  = _gvn.transform(new CmpINode(result, intcon(expected_val)));
 9829       Node* test = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
 9830 
 9831       IfNode* check = create_and_map_if(control(), test, PROB_ALWAYS, COUNT_UNKNOWN);
 9832       Node* fast_path = _gvn.transform(new IfTrueNode(check));
 9833       Node* slow_path = _gvn.transform(new IfFalseNode(check));
 9834 
 9835       { // Slow path: uncommon trap for never seen value and then reexecute
 9836         // MethodHandleImpl::profileBoolean() to bump the count, so JIT knows
 9837         // the value has been seen at least once.
 9838         PreserveJVMState pjvms(this);
 9839         PreserveReexecuteState preexecs(this);
 9840         jvms()->set_should_reexecute(true);
 9841 
 9842         set_control(slow_path);
 9843         set_i_o(i_o());
 9844 
 9845         uncommon_trap_exact(Deoptimization::Reason_intrinsic,
 9846                             Deoptimization::Action_reinterpret);
 9847       }
 9848       // The guard for never seen value enables sharpening of the result and
 9849       // returning a constant. It allows to eliminate branches on the same value
 9850       // later on.
 9851       set_control(fast_path);
 9852       result = intcon(expected_val);
 9853     }
 9854     // Stop profiling.
 9855     // MethodHandleImpl::profileBoolean() has profiling logic in its bytecode.
 9856     // By replacing method body with profile data (represented as ProfileBooleanNode
 9857     // on IR level) we effectively disable profiling.
 9858     // It enables full speed execution once optimized code is generated.
 9859     Node* profile = _gvn.transform(new ProfileBooleanNode(result, false_cnt, true_cnt));
 9860     C->record_for_igvn(profile);
 9861     set_result(profile);
 9862     return true;
 9863   } else {
 9864     // Continue profiling.
 9865     // Profile data isn't available at the moment. So, execute method's bytecode version.
 9866     // Usually, when GWT LambdaForms are profiled it means that a stand-alone nmethod
 9867     // is compiled and counters aren't available since corresponding MethodHandle
 9868     // isn't a compile-time constant.
 9869     return false;
 9870   }
 9871 }
 9872 
 9873 bool LibraryCallKit::inline_isCompileConstant() {
 9874   Node* n = argument(0);
 9875   set_result(n->is_Con() ? intcon(1) : intcon(0));
 9876   return true;
 9877 }
 9878 
 9879 //------------------------------- inline_getObjectSize --------------------------------------
 9880 //
 9881 // Calculate the runtime size of the object/array.
 9882 //   native long sun.instrument.InstrumentationImpl.getObjectSize0(long nativeAgent, Object objectToSize);
 9883 //
 9884 bool LibraryCallKit::inline_getObjectSize() {
 9885   Node* obj = argument(3);
 9886   Node* klass_node = load_object_klass(obj);
 9887 
 9888   jint  layout_con = Klass::_lh_neutral_value;
 9889   Node* layout_val = get_layout_helper(klass_node, layout_con);
 9890   int   layout_is_con = (layout_val == nullptr);
 9891 
 9892   if (layout_is_con) {
 9893     // Layout helper is constant, can figure out things at compile time.
 9894 
 9895     if (Klass::layout_helper_is_instance(layout_con)) {
 9896       // Instance case:  layout_con contains the size itself.
 9897       Node *size = longcon(Klass::layout_helper_size_in_bytes(layout_con));
 9898       set_result(size);
 9899     } else {
 9900       // Array case: size is round(header + element_size*arraylength).
 9901       // Since arraylength is different for every array instance, we have to
 9902       // compute the whole thing at runtime.
 9903 
 9904       Node* arr_length = load_array_length(obj);
 9905 
 9906       int round_mask = MinObjAlignmentInBytes - 1;
 9907       int hsize  = Klass::layout_helper_header_size(layout_con);
 9908       int eshift = Klass::layout_helper_log2_element_size(layout_con);
 9909 
 9910       if ((round_mask & ~right_n_bits(eshift)) == 0) {
 9911         round_mask = 0;  // strength-reduce it if it goes away completely
 9912       }
 9913       assert((hsize & right_n_bits(eshift)) == 0, "hsize is pre-rounded");
 9914       Node* header_size = intcon(hsize + round_mask);
 9915 
 9916       Node* lengthx = ConvI2X(arr_length);
 9917       Node* headerx = ConvI2X(header_size);
 9918 
 9919       Node* abody = lengthx;
 9920       if (eshift != 0) {
 9921         abody = _gvn.transform(new LShiftXNode(lengthx, intcon(eshift)));
 9922       }
 9923       Node* size = _gvn.transform( new AddXNode(headerx, abody) );
 9924       if (round_mask != 0) {
 9925         size = _gvn.transform( new AndXNode(size, MakeConX(~round_mask)) );
 9926       }
 9927       size = ConvX2L(size);
 9928       set_result(size);
 9929     }
 9930   } else {
 9931     // Layout helper is not constant, need to test for array-ness at runtime.
 9932 
 9933     enum { _instance_path = 1, _array_path, PATH_LIMIT };
 9934     RegionNode* result_reg = new RegionNode(PATH_LIMIT);
 9935     PhiNode* result_val = new PhiNode(result_reg, TypeLong::LONG);
 9936     record_for_igvn(result_reg);
 9937 
 9938     Node* array_ctl = generate_array_guard(klass_node, nullptr, &obj);
 9939     if (array_ctl != nullptr) {
 9940       // Array case: size is round(header + element_size*arraylength).
 9941       // Since arraylength is different for every array instance, we have to
 9942       // compute the whole thing at runtime.
 9943 
 9944       PreserveJVMState pjvms(this);
 9945       set_control(array_ctl);
 9946       Node* arr_length = load_array_length(obj);
 9947 
 9948       int round_mask = MinObjAlignmentInBytes - 1;
 9949       Node* mask = intcon(round_mask);
 9950 
 9951       Node* hss = intcon(Klass::_lh_header_size_shift);
 9952       Node* hsm = intcon(Klass::_lh_header_size_mask);
 9953       Node* header_size = _gvn.transform(new URShiftINode(layout_val, hss));
 9954       header_size = _gvn.transform(new AndINode(header_size, hsm));
 9955       header_size = _gvn.transform(new AddINode(header_size, mask));
 9956 
 9957       // There is no need to mask or shift this value.
 9958       // The semantics of LShiftINode include an implicit mask to 0x1F.
 9959       assert(Klass::_lh_log2_element_size_shift == 0, "use shift in place");
 9960       Node* elem_shift = layout_val;
 9961 
 9962       Node* lengthx = ConvI2X(arr_length);
 9963       Node* headerx = ConvI2X(header_size);
 9964 
 9965       Node* abody = _gvn.transform(new LShiftXNode(lengthx, elem_shift));
 9966       Node* size = _gvn.transform(new AddXNode(headerx, abody));
 9967       if (round_mask != 0) {
 9968         size = _gvn.transform(new AndXNode(size, MakeConX(~round_mask)));
 9969       }
 9970       size = ConvX2L(size);
 9971 
 9972       result_reg->init_req(_array_path, control());
 9973       result_val->init_req(_array_path, size);
 9974     }
 9975 
 9976     if (!stopped()) {
 9977       // Instance case: the layout helper gives us instance size almost directly,
 9978       // but we need to mask out the _lh_instance_slow_path_bit.
 9979       Node* size = ConvI2X(layout_val);
 9980       assert((int) Klass::_lh_instance_slow_path_bit < BytesPerLong, "clear bit");
 9981       Node* mask = MakeConX(~(intptr_t) right_n_bits(LogBytesPerLong));
 9982       size = _gvn.transform(new AndXNode(size, mask));
 9983       size = ConvX2L(size);
 9984 
 9985       result_reg->init_req(_instance_path, control());
 9986       result_val->init_req(_instance_path, size);
 9987     }
 9988 
 9989     set_result(result_reg, result_val);
 9990   }
 9991 
 9992   return true;
 9993 }
 9994 
 9995 //------------------------------- inline_blackhole --------------------------------------
 9996 //
 9997 // Make sure all arguments to this node are alive.
 9998 // This matches methods that were requested to be blackholed through compile commands.
 9999 //
10000 bool LibraryCallKit::inline_blackhole() {
10001   assert(callee()->is_static(), "Should have been checked before: only static methods here");
10002   assert(callee()->is_empty(), "Should have been checked before: only empty methods here");
10003   assert(callee()->holder()->is_loaded(), "Should have been checked before: only methods for loaded classes here");
10004 
10005   // Blackhole node pinches only the control, not memory. This allows
10006   // the blackhole to be pinned in the loop that computes blackholed
10007   // values, but have no other side effects, like breaking the optimizations
10008   // across the blackhole.
10009 
10010   Node* bh = _gvn.transform(new BlackholeNode(control()));
10011   set_control(_gvn.transform(new ProjNode(bh, TypeFunc::Control)));
10012 
10013   // Bind call arguments as blackhole arguments to keep them alive
10014   uint nargs = callee()->arg_size();
10015   for (uint i = 0; i < nargs; i++) {
10016     bh->add_req(argument(i));
10017   }
10018 
10019   return true;
10020 }
10021 
10022 Node* LibraryCallKit::unbox_fp16_value(const TypeInstPtr* float16_box_type, ciField* field, Node* box) {
10023   const TypeInstPtr* box_type = _gvn.type(box)->isa_instptr();
10024   if (box_type == nullptr || box_type->instance_klass() != float16_box_type->instance_klass()) {
10025     return nullptr; // box klass is not Float16
10026   }
10027 
10028   // Null check; get notnull casted pointer
10029   Node* null_ctl = top();
10030   Node* not_null_box = null_check_oop(box, &null_ctl, true);
10031   // If not_null_box is dead, only null-path is taken
10032   if (stopped()) {
10033     set_control(null_ctl);
10034     return nullptr;
10035   }
10036   assert(not_null_box->bottom_type()->is_instptr()->maybe_null() == false, "");
10037   const TypePtr* adr_type = C->alias_type(field)->adr_type();
10038   Node* adr = basic_plus_adr(not_null_box, field->offset_in_bytes());
10039   return access_load_at(not_null_box, adr, adr_type, TypeInt::SHORT, T_SHORT, IN_HEAP);
10040 }
10041 
10042 Node* LibraryCallKit::box_fp16_value(const TypeInstPtr* float16_box_type, ciField* field, Node* value) {
10043   PreserveReexecuteState preexecs(this);
10044   jvms()->set_should_reexecute(true);
10045 
10046   const TypeKlassPtr* klass_type = float16_box_type->as_klass_type();
10047   Node* klass_node = makecon(klass_type);
10048   Node* box = new_instance(klass_node);
10049 
10050   Node* value_field = basic_plus_adr(box, field->offset_in_bytes());
10051   const TypePtr* value_adr_type = value_field->bottom_type()->is_ptr();
10052 
10053   Node* field_store = _gvn.transform(access_store_at(box,
10054                                                      value_field,
10055                                                      value_adr_type,
10056                                                      value,
10057                                                      TypeInt::SHORT,
10058                                                      T_SHORT,
10059                                                      IN_HEAP));
10060   set_memory(field_store, value_adr_type);
10061   return box;
10062 }
10063 
10064 bool LibraryCallKit::inline_fp16_operations(vmIntrinsics::ID id, int num_args) {
10065   if (!Matcher::match_rule_supported(Op_ReinterpretS2HF) ||
10066       !Matcher::match_rule_supported(Op_ReinterpretHF2S)) {
10067     return false;
10068   }
10069 
10070   const TypeInstPtr* box_type = _gvn.type(argument(0))->isa_instptr();
10071   if (box_type == nullptr || box_type->const_oop() == nullptr) {
10072     return false;
10073   }
10074 
10075   ciInstanceKlass* float16_klass = box_type->const_oop()->as_instance()->java_lang_Class_klass()->as_instance_klass();
10076   const TypeInstPtr* float16_box_type = TypeInstPtr::make_exact(TypePtr::NotNull, float16_klass);
10077   ciField* field = float16_klass->get_field_by_name(ciSymbols::value_name(),
10078                                                     ciSymbols::short_signature(),
10079                                                     false);
10080   assert(field != nullptr, "");
10081 
10082   // Transformed nodes
10083   Node* fld1 = nullptr;
10084   Node* fld2 = nullptr;
10085   Node* fld3 = nullptr;
10086   switch(num_args) {
10087     case 3:
10088       fld3 = unbox_fp16_value(float16_box_type, field, argument(3));
10089       if (fld3 == nullptr) {
10090         return false;
10091       }
10092       fld3 = _gvn.transform(new ReinterpretS2HFNode(fld3));
10093     // fall-through
10094     case 2:
10095       fld2 = unbox_fp16_value(float16_box_type, field, argument(2));
10096       if (fld2 == nullptr) {
10097         return false;
10098       }
10099       fld2 = _gvn.transform(new ReinterpretS2HFNode(fld2));
10100     // fall-through
10101     case 1:
10102       fld1 = unbox_fp16_value(float16_box_type, field, argument(1));
10103       if (fld1 == nullptr) {
10104         return false;
10105       }
10106       fld1 = _gvn.transform(new ReinterpretS2HFNode(fld1));
10107       break;
10108     default: fatal("Unsupported number of arguments %d", num_args);
10109   }
10110 
10111   Node* result = nullptr;
10112   switch (id) {
10113     // Unary operations
10114     case vmIntrinsics::_sqrt_float16:
10115       result = _gvn.transform(new SqrtHFNode(C, control(), fld1));
10116       break;
10117     // Ternary operations
10118     case vmIntrinsics::_fma_float16:
10119       result = _gvn.transform(new FmaHFNode(fld1, fld2, fld3));
10120       break;
10121     default:
10122       fatal_unexpected_iid(id);
10123       break;
10124   }
10125   result = _gvn.transform(new ReinterpretHF2SNode(result));
10126   set_result(box_fp16_value(float16_box_type, field, result));
10127   return true;
10128 }
10129