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