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