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