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