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