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