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