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