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