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