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