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