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