1 /*
   2  * Copyright (c) 1999, 2021, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "asm/macroAssembler.hpp"
  27 #include "ci/ciUtilities.inline.hpp"
  28 #include "classfile/vmIntrinsics.hpp"
  29 #include "compiler/compileBroker.hpp"
  30 #include "compiler/compileLog.hpp"
  31 #include "gc/shared/barrierSet.hpp"
  32 #include "jfr/support/jfrIntrinsics.hpp"
  33 #include "memory/resourceArea.hpp"
  34 #include "oops/klass.inline.hpp"
  35 #include "oops/objArrayKlass.hpp"
  36 #include "opto/addnode.hpp"
  37 #include "opto/arraycopynode.hpp"
  38 #include "opto/c2compiler.hpp"
  39 #include "opto/castnode.hpp"
  40 #include "opto/cfgnode.hpp"
  41 #include "opto/convertnode.hpp"
  42 #include "opto/countbitsnode.hpp"
  43 #include "opto/idealKit.hpp"
  44 #include "opto/library_call.hpp"
  45 #include "opto/mathexactnode.hpp"
  46 #include "opto/mulnode.hpp"
  47 #include "opto/narrowptrnode.hpp"
  48 #include "opto/opaquenode.hpp"
  49 #include "opto/parse.hpp"
  50 #include "opto/runtime.hpp"
  51 #include "opto/rootnode.hpp"
  52 #include "opto/subnode.hpp"
  53 #include "prims/unsafe.hpp"
  54 #include "runtime/objectMonitor.hpp"
  55 #include "runtime/sharedRuntime.hpp"
  56 #include "runtime/stubRoutines.hpp"
  57 #include "utilities/macros.hpp"
  58 #include "utilities/powerOfTwo.hpp"
  59 
  60 #if INCLUDE_JFR
  61 #include "jfr/jfr.hpp"
  62 #include "jfr/recorder/checkpoint/types/traceid/jfrTraceIdMacros.hpp" // FIXME
  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::_getReference:             return inline_unsafe_access(!is_store, T_OBJECT,   Relaxed, false);
 324   case vmIntrinsics::_getBoolean:               return inline_unsafe_access(!is_store, T_BOOLEAN,  Relaxed, false);
 325   case vmIntrinsics::_getByte:                  return inline_unsafe_access(!is_store, T_BYTE,     Relaxed, false);
 326   case vmIntrinsics::_getShort:                 return inline_unsafe_access(!is_store, T_SHORT,    Relaxed, false);
 327   case vmIntrinsics::_getChar:                  return inline_unsafe_access(!is_store, T_CHAR,     Relaxed, false);
 328   case vmIntrinsics::_getInt:                   return inline_unsafe_access(!is_store, T_INT,      Relaxed, false);
 329   case vmIntrinsics::_getLong:                  return inline_unsafe_access(!is_store, T_LONG,     Relaxed, false);
 330   case vmIntrinsics::_getFloat:                 return inline_unsafe_access(!is_store, T_FLOAT,    Relaxed, false);
 331   case vmIntrinsics::_getDouble:                return inline_unsafe_access(!is_store, T_DOUBLE,   Relaxed, false);
 332 
 333   case vmIntrinsics::_putReference:             return inline_unsafe_access( is_store, T_OBJECT,   Relaxed, false);
 334   case vmIntrinsics::_putBoolean:               return inline_unsafe_access( is_store, T_BOOLEAN,  Relaxed, false);
 335   case vmIntrinsics::_putByte:                  return inline_unsafe_access( is_store, T_BYTE,     Relaxed, false);
 336   case vmIntrinsics::_putShort:                 return inline_unsafe_access( is_store, T_SHORT,    Relaxed, false);
 337   case vmIntrinsics::_putChar:                  return inline_unsafe_access( is_store, T_CHAR,     Relaxed, false);
 338   case vmIntrinsics::_putInt:                   return inline_unsafe_access( is_store, T_INT,      Relaxed, false);
 339   case vmIntrinsics::_putLong:                  return inline_unsafe_access( is_store, T_LONG,     Relaxed, false);
 340   case vmIntrinsics::_putFloat:                 return inline_unsafe_access( is_store, T_FLOAT,    Relaxed, false);
 341   case vmIntrinsics::_putDouble:                return inline_unsafe_access( is_store, T_DOUBLE,   Relaxed, false);
 342 
 343   case vmIntrinsics::_getReferenceVolatile:     return inline_unsafe_access(!is_store, T_OBJECT,   Volatile, false);
 344   case vmIntrinsics::_getBooleanVolatile:       return inline_unsafe_access(!is_store, T_BOOLEAN,  Volatile, false);
 345   case vmIntrinsics::_getByteVolatile:          return inline_unsafe_access(!is_store, T_BYTE,     Volatile, false);
 346   case vmIntrinsics::_getShortVolatile:         return inline_unsafe_access(!is_store, T_SHORT,    Volatile, false);
 347   case vmIntrinsics::_getCharVolatile:          return inline_unsafe_access(!is_store, T_CHAR,     Volatile, false);
 348   case vmIntrinsics::_getIntVolatile:           return inline_unsafe_access(!is_store, T_INT,      Volatile, false);
 349   case vmIntrinsics::_getLongVolatile:          return inline_unsafe_access(!is_store, T_LONG,     Volatile, false);
 350   case vmIntrinsics::_getFloatVolatile:         return inline_unsafe_access(!is_store, T_FLOAT,    Volatile, false);
 351   case vmIntrinsics::_getDoubleVolatile:        return inline_unsafe_access(!is_store, T_DOUBLE,   Volatile, false);
 352 
 353   case vmIntrinsics::_putReferenceVolatile:     return inline_unsafe_access( is_store, T_OBJECT,   Volatile, false);
 354   case vmIntrinsics::_putBooleanVolatile:       return inline_unsafe_access( is_store, T_BOOLEAN,  Volatile, false);
 355   case vmIntrinsics::_putByteVolatile:          return inline_unsafe_access( is_store, T_BYTE,     Volatile, false);
 356   case vmIntrinsics::_putShortVolatile:         return inline_unsafe_access( is_store, T_SHORT,    Volatile, false);
 357   case vmIntrinsics::_putCharVolatile:          return inline_unsafe_access( is_store, T_CHAR,     Volatile, false);
 358   case vmIntrinsics::_putIntVolatile:           return inline_unsafe_access( is_store, T_INT,      Volatile, false);
 359   case vmIntrinsics::_putLongVolatile:          return inline_unsafe_access( is_store, T_LONG,     Volatile, false);
 360   case vmIntrinsics::_putFloatVolatile:         return inline_unsafe_access( is_store, T_FLOAT,    Volatile, false);
 361   case vmIntrinsics::_putDoubleVolatile:        return inline_unsafe_access( is_store, T_DOUBLE,   Volatile, false);
 362 
 363   case vmIntrinsics::_getShortUnaligned:        return inline_unsafe_access(!is_store, T_SHORT,    Relaxed, true);
 364   case vmIntrinsics::_getCharUnaligned:         return inline_unsafe_access(!is_store, T_CHAR,     Relaxed, true);
 365   case vmIntrinsics::_getIntUnaligned:          return inline_unsafe_access(!is_store, T_INT,      Relaxed, true);
 366   case vmIntrinsics::_getLongUnaligned:         return inline_unsafe_access(!is_store, T_LONG,     Relaxed, true);
 367 
 368   case vmIntrinsics::_putShortUnaligned:        return inline_unsafe_access( is_store, T_SHORT,    Relaxed, true);
 369   case vmIntrinsics::_putCharUnaligned:         return inline_unsafe_access( is_store, T_CHAR,     Relaxed, true);
 370   case vmIntrinsics::_putIntUnaligned:          return inline_unsafe_access( is_store, T_INT,      Relaxed, true);
 371   case vmIntrinsics::_putLongUnaligned:         return inline_unsafe_access( is_store, T_LONG,     Relaxed, true);
 372 
 373   case vmIntrinsics::_getReferenceAcquire:      return inline_unsafe_access(!is_store, T_OBJECT,   Acquire, false);
 374   case vmIntrinsics::_getBooleanAcquire:        return inline_unsafe_access(!is_store, T_BOOLEAN,  Acquire, false);
 375   case vmIntrinsics::_getByteAcquire:           return inline_unsafe_access(!is_store, T_BYTE,     Acquire, false);
 376   case vmIntrinsics::_getShortAcquire:          return inline_unsafe_access(!is_store, T_SHORT,    Acquire, false);
 377   case vmIntrinsics::_getCharAcquire:           return inline_unsafe_access(!is_store, T_CHAR,     Acquire, false);
 378   case vmIntrinsics::_getIntAcquire:            return inline_unsafe_access(!is_store, T_INT,      Acquire, false);
 379   case vmIntrinsics::_getLongAcquire:           return inline_unsafe_access(!is_store, T_LONG,     Acquire, false);
 380   case vmIntrinsics::_getFloatAcquire:          return inline_unsafe_access(!is_store, T_FLOAT,    Acquire, false);
 381   case vmIntrinsics::_getDoubleAcquire:         return inline_unsafe_access(!is_store, T_DOUBLE,   Acquire, false);
 382 
 383   case vmIntrinsics::_putReferenceRelease:      return inline_unsafe_access( is_store, T_OBJECT,   Release, false);
 384   case vmIntrinsics::_putBooleanRelease:        return inline_unsafe_access( is_store, T_BOOLEAN,  Release, false);
 385   case vmIntrinsics::_putByteRelease:           return inline_unsafe_access( is_store, T_BYTE,     Release, false);
 386   case vmIntrinsics::_putShortRelease:          return inline_unsafe_access( is_store, T_SHORT,    Release, false);
 387   case vmIntrinsics::_putCharRelease:           return inline_unsafe_access( is_store, T_CHAR,     Release, false);
 388   case vmIntrinsics::_putIntRelease:            return inline_unsafe_access( is_store, T_INT,      Release, false);
 389   case vmIntrinsics::_putLongRelease:           return inline_unsafe_access( is_store, T_LONG,     Release, false);
 390   case vmIntrinsics::_putFloatRelease:          return inline_unsafe_access( is_store, T_FLOAT,    Release, false);
 391   case vmIntrinsics::_putDoubleRelease:         return inline_unsafe_access( is_store, T_DOUBLE,   Release, false);
 392 
 393   case vmIntrinsics::_getReferenceOpaque:       return inline_unsafe_access(!is_store, T_OBJECT,   Opaque, false);
 394   case vmIntrinsics::_getBooleanOpaque:         return inline_unsafe_access(!is_store, T_BOOLEAN,  Opaque, false);
 395   case vmIntrinsics::_getByteOpaque:            return inline_unsafe_access(!is_store, T_BYTE,     Opaque, false);
 396   case vmIntrinsics::_getShortOpaque:           return inline_unsafe_access(!is_store, T_SHORT,    Opaque, false);
 397   case vmIntrinsics::_getCharOpaque:            return inline_unsafe_access(!is_store, T_CHAR,     Opaque, false);
 398   case vmIntrinsics::_getIntOpaque:             return inline_unsafe_access(!is_store, T_INT,      Opaque, false);
 399   case vmIntrinsics::_getLongOpaque:            return inline_unsafe_access(!is_store, T_LONG,     Opaque, false);
 400   case vmIntrinsics::_getFloatOpaque:           return inline_unsafe_access(!is_store, T_FLOAT,    Opaque, false);
 401   case vmIntrinsics::_getDoubleOpaque:          return inline_unsafe_access(!is_store, T_DOUBLE,   Opaque, false);
 402 
 403   case vmIntrinsics::_putReferenceOpaque:       return inline_unsafe_access( is_store, T_OBJECT,   Opaque, false);
 404   case vmIntrinsics::_putBooleanOpaque:         return inline_unsafe_access( is_store, T_BOOLEAN,  Opaque, false);
 405   case vmIntrinsics::_putByteOpaque:            return inline_unsafe_access( is_store, T_BYTE,     Opaque, false);
 406   case vmIntrinsics::_putShortOpaque:           return inline_unsafe_access( is_store, T_SHORT,    Opaque, false);
 407   case vmIntrinsics::_putCharOpaque:            return inline_unsafe_access( is_store, T_CHAR,     Opaque, false);
 408   case vmIntrinsics::_putIntOpaque:             return inline_unsafe_access( is_store, T_INT,      Opaque, false);
 409   case vmIntrinsics::_putLongOpaque:            return inline_unsafe_access( is_store, T_LONG,     Opaque, false);
 410   case vmIntrinsics::_putFloatOpaque:           return inline_unsafe_access( is_store, T_FLOAT,    Opaque, false);
 411   case vmIntrinsics::_putDoubleOpaque:          return inline_unsafe_access( is_store, T_DOUBLE,   Opaque, false);
 412 
 413   case vmIntrinsics::_compareAndSetReference:   return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap,      Volatile);
 414   case vmIntrinsics::_compareAndSetByte:        return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap,      Volatile);
 415   case vmIntrinsics::_compareAndSetShort:       return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap,      Volatile);
 416   case vmIntrinsics::_compareAndSetInt:         return inline_unsafe_load_store(T_INT,    LS_cmp_swap,      Volatile);
 417   case vmIntrinsics::_compareAndSetLong:        return inline_unsafe_load_store(T_LONG,   LS_cmp_swap,      Volatile);
 418 
 419   case vmIntrinsics::_weakCompareAndSetReferencePlain:     return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Relaxed);
 420   case vmIntrinsics::_weakCompareAndSetReferenceAcquire:   return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Acquire);
 421   case vmIntrinsics::_weakCompareAndSetReferenceRelease:   return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Release);
 422   case vmIntrinsics::_weakCompareAndSetReference:          return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Volatile);
 423   case vmIntrinsics::_weakCompareAndSetBytePlain:          return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap_weak, Relaxed);
 424   case vmIntrinsics::_weakCompareAndSetByteAcquire:        return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap_weak, Acquire);
 425   case vmIntrinsics::_weakCompareAndSetByteRelease:        return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap_weak, Release);
 426   case vmIntrinsics::_weakCompareAndSetByte:               return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap_weak, Volatile);
 427   case vmIntrinsics::_weakCompareAndSetShortPlain:         return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap_weak, Relaxed);
 428   case vmIntrinsics::_weakCompareAndSetShortAcquire:       return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap_weak, Acquire);
 429   case vmIntrinsics::_weakCompareAndSetShortRelease:       return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap_weak, Release);
 430   case vmIntrinsics::_weakCompareAndSetShort:              return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap_weak, Volatile);
 431   case vmIntrinsics::_weakCompareAndSetIntPlain:           return inline_unsafe_load_store(T_INT,    LS_cmp_swap_weak, Relaxed);
 432   case vmIntrinsics::_weakCompareAndSetIntAcquire:         return inline_unsafe_load_store(T_INT,    LS_cmp_swap_weak, Acquire);
 433   case vmIntrinsics::_weakCompareAndSetIntRelease:         return inline_unsafe_load_store(T_INT,    LS_cmp_swap_weak, Release);
 434   case vmIntrinsics::_weakCompareAndSetInt:                return inline_unsafe_load_store(T_INT,    LS_cmp_swap_weak, Volatile);
 435   case vmIntrinsics::_weakCompareAndSetLongPlain:          return inline_unsafe_load_store(T_LONG,   LS_cmp_swap_weak, Relaxed);
 436   case vmIntrinsics::_weakCompareAndSetLongAcquire:        return inline_unsafe_load_store(T_LONG,   LS_cmp_swap_weak, Acquire);
 437   case vmIntrinsics::_weakCompareAndSetLongRelease:        return inline_unsafe_load_store(T_LONG,   LS_cmp_swap_weak, Release);
 438   case vmIntrinsics::_weakCompareAndSetLong:               return inline_unsafe_load_store(T_LONG,   LS_cmp_swap_weak, Volatile);
 439 
 440   case vmIntrinsics::_compareAndExchangeReference:         return inline_unsafe_load_store(T_OBJECT, LS_cmp_exchange,  Volatile);
 441   case vmIntrinsics::_compareAndExchangeReferenceAcquire:  return inline_unsafe_load_store(T_OBJECT, LS_cmp_exchange,  Acquire);
 442   case vmIntrinsics::_compareAndExchangeReferenceRelease:  return inline_unsafe_load_store(T_OBJECT, LS_cmp_exchange,  Release);
 443   case vmIntrinsics::_compareAndExchangeByte:              return inline_unsafe_load_store(T_BYTE,   LS_cmp_exchange,  Volatile);
 444   case vmIntrinsics::_compareAndExchangeByteAcquire:       return inline_unsafe_load_store(T_BYTE,   LS_cmp_exchange,  Acquire);
 445   case vmIntrinsics::_compareAndExchangeByteRelease:       return inline_unsafe_load_store(T_BYTE,   LS_cmp_exchange,  Release);
 446   case vmIntrinsics::_compareAndExchangeShort:             return inline_unsafe_load_store(T_SHORT,  LS_cmp_exchange,  Volatile);
 447   case vmIntrinsics::_compareAndExchangeShortAcquire:      return inline_unsafe_load_store(T_SHORT,  LS_cmp_exchange,  Acquire);
 448   case vmIntrinsics::_compareAndExchangeShortRelease:      return inline_unsafe_load_store(T_SHORT,  LS_cmp_exchange,  Release);
 449   case vmIntrinsics::_compareAndExchangeInt:               return inline_unsafe_load_store(T_INT,    LS_cmp_exchange,  Volatile);
 450   case vmIntrinsics::_compareAndExchangeIntAcquire:        return inline_unsafe_load_store(T_INT,    LS_cmp_exchange,  Acquire);
 451   case vmIntrinsics::_compareAndExchangeIntRelease:        return inline_unsafe_load_store(T_INT,    LS_cmp_exchange,  Release);
 452   case vmIntrinsics::_compareAndExchangeLong:              return inline_unsafe_load_store(T_LONG,   LS_cmp_exchange,  Volatile);
 453   case vmIntrinsics::_compareAndExchangeLongAcquire:       return inline_unsafe_load_store(T_LONG,   LS_cmp_exchange,  Acquire);
 454   case vmIntrinsics::_compareAndExchangeLongRelease:       return inline_unsafe_load_store(T_LONG,   LS_cmp_exchange,  Release);
 455 
 456   case vmIntrinsics::_getAndAddByte:                    return inline_unsafe_load_store(T_BYTE,   LS_get_add,       Volatile);
 457   case vmIntrinsics::_getAndAddShort:                   return inline_unsafe_load_store(T_SHORT,  LS_get_add,       Volatile);
 458   case vmIntrinsics::_getAndAddInt:                     return inline_unsafe_load_store(T_INT,    LS_get_add,       Volatile);
 459   case vmIntrinsics::_getAndAddLong:                    return inline_unsafe_load_store(T_LONG,   LS_get_add,       Volatile);
 460 
 461   case vmIntrinsics::_getAndSetByte:                    return inline_unsafe_load_store(T_BYTE,   LS_get_set,       Volatile);
 462   case vmIntrinsics::_getAndSetShort:                   return inline_unsafe_load_store(T_SHORT,  LS_get_set,       Volatile);
 463   case vmIntrinsics::_getAndSetInt:                     return inline_unsafe_load_store(T_INT,    LS_get_set,       Volatile);
 464   case vmIntrinsics::_getAndSetLong:                    return inline_unsafe_load_store(T_LONG,   LS_get_set,       Volatile);
 465   case vmIntrinsics::_getAndSetReference:               return inline_unsafe_load_store(T_OBJECT, LS_get_set,       Volatile);
 466 
 467   case vmIntrinsics::_loadFence:
 468   case vmIntrinsics::_storeFence:
 469   case vmIntrinsics::_storeStoreFence:
 470   case vmIntrinsics::_fullFence:                return inline_unsafe_fence(intrinsic_id());
 471 
 472   case vmIntrinsics::_onSpinWait:               return inline_onspinwait();
 473 
 474   case vmIntrinsics::_currentThread0:           return inline_native_currentThread0();
 475   case vmIntrinsics::_currentThread:            return inline_native_currentThread();
 476   case vmIntrinsics::_setCurrentThread:         return inline_native_setCurrentThread();
 477 
 478   case vmIntrinsics::_scopeLocalCache:          return inline_native_scopeLocalCache();
 479   case vmIntrinsics::_setScopeLocalCache:       return inline_native_setScopeLocalCache();
 480 
 481 #ifdef JFR_HAVE_INTRINSICS
 482   case vmIntrinsics::_counterTime:              return inline_native_time_funcs(CAST_FROM_FN_PTR(address, JFR_TIME_FUNCTION), "counterTime");

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