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