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