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