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