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