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