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