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::_compareAndSwapObject:             return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap,      Volatile);
 675   case vmIntrinsics::_compareAndSwapByte:               return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap,      Volatile);
 676   case vmIntrinsics::_compareAndSwapShort:              return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap,      Volatile);
 677   case vmIntrinsics::_compareAndSwapInt:                return inline_unsafe_load_store(T_INT,    LS_cmp_swap,      Volatile);
 678   case vmIntrinsics::_compareAndSwapLong:               return inline_unsafe_load_store(T_LONG,   LS_cmp_swap,      Volatile);
 679 
 680   case vmIntrinsics::_weakCompareAndSwapObject:         return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Relaxed);
 681   case vmIntrinsics::_weakCompareAndSwapObjectAcquire:  return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Acquire);
 682   case vmIntrinsics::_weakCompareAndSwapObjectRelease:  return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Release);
 683   case vmIntrinsics::_weakCompareAndSwapObjectVolatile: return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Volatile);
 684   case vmIntrinsics::_weakCompareAndSwapByte:           return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap_weak, Relaxed);
 685   case vmIntrinsics::_weakCompareAndSwapByteAcquire:    return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap_weak, Acquire);
 686   case vmIntrinsics::_weakCompareAndSwapByteRelease:    return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap_weak, Release);
 687   case vmIntrinsics::_weakCompareAndSwapByteVolatile:   return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap_weak, Volatile);
 688   case vmIntrinsics::_weakCompareAndSwapShort:          return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap_weak, Relaxed);
 689   case vmIntrinsics::_weakCompareAndSwapShortAcquire:   return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap_weak, Acquire);
 690   case vmIntrinsics::_weakCompareAndSwapShortRelease:   return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap_weak, Release);
 691   case vmIntrinsics::_weakCompareAndSwapShortVolatile:  return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap_weak, Volatile);
 692   case vmIntrinsics::_weakCompareAndSwapInt:            return inline_unsafe_load_store(T_INT,    LS_cmp_swap_weak, Relaxed);
 693   case vmIntrinsics::_weakCompareAndSwapIntAcquire:     return inline_unsafe_load_store(T_INT,    LS_cmp_swap_weak, Acquire);
 694   case vmIntrinsics::_weakCompareAndSwapIntRelease:     return inline_unsafe_load_store(T_INT,    LS_cmp_swap_weak, Release);
 695   case vmIntrinsics::_weakCompareAndSwapIntVolatile:    return inline_unsafe_load_store(T_INT,    LS_cmp_swap_weak, Volatile);
 696   case vmIntrinsics::_weakCompareAndSwapLong:           return inline_unsafe_load_store(T_LONG,   LS_cmp_swap_weak, Relaxed);
 697   case vmIntrinsics::_weakCompareAndSwapLongAcquire:    return inline_unsafe_load_store(T_LONG,   LS_cmp_swap_weak, Acquire);
 698   case vmIntrinsics::_weakCompareAndSwapLongRelease:    return inline_unsafe_load_store(T_LONG,   LS_cmp_swap_weak, Release);
 699   case vmIntrinsics::_weakCompareAndSwapLongVolatile:   return inline_unsafe_load_store(T_LONG,   LS_cmp_swap_weak, Volatile);
 700 
 701   case vmIntrinsics::_compareAndExchangeObjectVolatile: 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::_compareAndExchangeByteVolatile:   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::_compareAndExchangeShortVolatile:  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::_compareAndExchangeIntVolatile:    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::_compareAndExchangeLongVolatile:   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 compareAndSwapObject(Object o, long offset, Object expected, Object x);
2613 //   boolean compareAndSwapInt(   Object o, long offset, int    expected, int    x);
2614 //   boolean compareAndSwapLong(  Object o, long offset, long   expected, long   x);
2615 //
2616 // LS_cmp_swap_weak:
2617 //
2618 //   boolean weakCompareAndSwapObject(       Object o, long offset, Object expected, Object x);
2619 //   boolean weakCompareAndSwapObjectAcquire(Object o, long offset, Object expected, Object x);
2620 //   boolean weakCompareAndSwapObjectRelease(Object o, long offset, Object expected, Object x);
2621 //
2622 //   boolean weakCompareAndSwapInt(          Object o, long offset, int    expected, int    x);
2623 //   boolean weakCompareAndSwapIntAcquire(   Object o, long offset, int    expected, int    x);
2624 //   boolean weakCompareAndSwapIntRelease(   Object o, long offset, int    expected, int    x);
2625 //
2626 //   boolean weakCompareAndSwapLong(         Object o, long offset, long   expected, long   x);
2627 //   boolean weakCompareAndSwapLongAcquire(  Object o, long offset, long   expected, long   x);
2628 //   boolean weakCompareAndSwapLongRelease(  Object o, long offset, long   expected, long   x);
2629 //
2630 // LS_cmp_exchange:
2631 //
2632 //   Object compareAndExchangeObjectVolatile(Object o, long offset, Object expected, Object x);
2633 //   Object compareAndExchangeObjectAcquire( Object o, long offset, Object expected, Object x);
2634 //   Object compareAndExchangeObjectRelease( Object o, long offset, Object expected, Object x);
2635 //
2636 //   Object compareAndExchangeIntVolatile(   Object o, long offset, Object expected, Object x);
2637 //   Object compareAndExchangeIntAcquire(    Object o, long offset, Object expected, Object x);
2638 //   Object compareAndExchangeIntRelease(    Object o, long offset, Object expected, Object x);
2639 //
2640 //   Object compareAndExchangeLongVolatile(  Object o, long offset, Object expected, Object x);
2641 //   Object compareAndExchangeLongAcquire(   Object o, long offset, Object expected, Object x);
2642 //   Object compareAndExchangeLongRelease(   Object o, long offset, Object expected, Object x);
2643 //
2644 // LS_get_add:
2645 //
2646 //   int  getAndAddInt( Object o, long offset, int  delta)
2647 //   long getAndAddLong(Object o, long offset, long delta)
2648 //
2649 // LS_get_set:
2650 //
2651 //   int    getAndSet(Object o, long offset, int    newValue)
2652 //   long   getAndSet(Object o, long offset, long   newValue)
2653 //   Object getAndSet(Object o, long offset, Object newValue)
2654 //
2655 bool LibraryCallKit::inline_unsafe_load_store(const BasicType type, const LoadStoreKind kind, const AccessKind access_kind) {
2656   // This basic scheme here is the same as inline_unsafe_access, but
2657   // differs in enough details that combining them would make the code
2658   // overly confusing.  (This is a true fact! I originally combined
2659   // them, but even I was confused by it!) As much code/comments as
2660   // possible are retained from inline_unsafe_access though to make
2661   // the correspondences clearer. - dl
2662 
2663   if (callee()->is_static())  return false;  // caller must have the capability!
2664 
2665 #ifndef PRODUCT
2666   BasicType rtype;
2667   {
2668     ResourceMark rm;
2669     // Check the signatures.
2670     ciSignature* sig = callee()->signature();
2671     rtype = sig->return_type()->basic_type();
2672     switch(kind) {
2673       case LS_get_add:
2674       case LS_get_set: {
2675       // Check the signatures.
2676 #ifdef ASSERT
2677       assert(rtype == type, "get and set must return the expected type");
2678       assert(sig->count() == 3, "get and set has 3 arguments");
2679       assert(sig->type_at(0)->basic_type() == T_OBJECT, "get and set base is object");
2680       assert(sig->type_at(1)->basic_type() == T_LONG, "get and set offset is long");
2681       assert(sig->type_at(2)->basic_type() == type, "get and set must take expected type as new value/delta");
2682       assert(access_kind == Volatile, "mo is not passed to intrinsic nodes in current implementation");
2683 #endif // ASSERT
2684         break;
2685       }
2686       case LS_cmp_swap:
2687       case LS_cmp_swap_weak: {
2688       // Check the signatures.
2689 #ifdef ASSERT
2690       assert(rtype == T_BOOLEAN, "CAS must return boolean");
2691       assert(sig->count() == 4, "CAS has 4 arguments");
2692       assert(sig->type_at(0)->basic_type() == T_OBJECT, "CAS base is object");
2693       assert(sig->type_at(1)->basic_type() == T_LONG, "CAS offset is long");
2694 #endif // ASSERT
2695         break;
2696       }
2697       case LS_cmp_exchange: {
2698       // Check the signatures.
2699 #ifdef ASSERT
2700       assert(rtype == type, "CAS must return the expected type");
2701       assert(sig->count() == 4, "CAS has 4 arguments");
2702       assert(sig->type_at(0)->basic_type() == T_OBJECT, "CAS base is object");
2703       assert(sig->type_at(1)->basic_type() == T_LONG, "CAS offset is long");
2704 #endif // ASSERT
2705         break;
2706       }
2707       default:
2708         ShouldNotReachHere();
2709     }
2710   }
2711 #endif //PRODUCT
2712 
2713   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
2714 
2715   // Get arguments:
2716   Node* receiver = NULL;
2717   Node* base     = NULL;
2718   Node* offset   = NULL;
2719   Node* oldval   = NULL;
2720   Node* newval   = NULL;
2721   switch(kind) {
2722     case LS_cmp_swap:
2723     case LS_cmp_swap_weak:
2724     case LS_cmp_exchange: {
2725       const bool two_slot_type = type2size[type] == 2;
2726       receiver = argument(0);  // type: oop
2727       base     = argument(1);  // type: oop
2728       offset   = argument(2);  // type: long
2729       oldval   = argument(4);  // type: oop, int, or long
2730       newval   = argument(two_slot_type ? 6 : 5);  // type: oop, int, or long
2731       break;
2732     }
2733     case LS_get_add:
2734     case LS_get_set: {
2735       receiver = argument(0);  // type: oop
2736       base     = argument(1);  // type: oop
2737       offset   = argument(2);  // type: long
2738       oldval   = NULL;
2739       newval   = argument(4);  // type: oop, int, or long
2740       break;
2741     }
2742     default:
2743       ShouldNotReachHere();
2744   }
2745 
2746   // Build field offset expression.
2747   // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
2748   // to be plain byte offsets, which are also the same as those accepted
2749   // by oopDesc::field_base.
2750   assert(Unsafe_field_offset_to_byte_offset(11) == 11, "fieldOffset must be byte-scaled");
2751   // 32-bit machines ignore the high half of long offsets
2752   offset = ConvL2X(offset);
2753   Node* adr = make_unsafe_address(base, offset);
2754   const TypePtr *adr_type = _gvn.type(adr)->isa_ptr();
2755 
2756   Compile::AliasType* alias_type = C->alias_type(adr_type);
2757   BasicType bt = alias_type->basic_type();
2758   if (bt != T_ILLEGAL &&
2759       ((bt == T_OBJECT || bt == T_ARRAY) != (type == T_OBJECT))) {
2760     // Don't intrinsify mismatched object accesses.
2761     return false;
2762   }
2763 
2764   // For CAS, unlike inline_unsafe_access, there seems no point in
2765   // trying to refine types. Just use the coarse types here.
2766   assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
2767   const Type *value_type = Type::get_const_basic_type(type);
2768 
2769   switch (kind) {
2770     case LS_get_set:
2771     case LS_cmp_exchange: {
2772       if (type == T_OBJECT) {
2773         const TypeOopPtr* tjp = sharpen_unsafe_type(alias_type, adr_type);
2774         if (tjp != NULL) {
2775           value_type = tjp;
2776         }
2777       }
2778       break;
2779     }
2780     case LS_cmp_swap:
2781     case LS_cmp_swap_weak:
2782     case LS_get_add:
2783       break;
2784     default:
2785       ShouldNotReachHere();
2786   }
2787 
2788   // Null check receiver.
2789   receiver = null_check(receiver);
2790   if (stopped()) {
2791     return true;
2792   }
2793 
2794   int alias_idx = C->get_alias_index(adr_type);
2795 
2796   // Memory-model-wise, a LoadStore acts like a little synchronized
2797   // block, so needs barriers on each side.  These don't translate
2798   // into actual barriers on most machines, but we still need rest of
2799   // compiler to respect ordering.
2800 
2801   switch (access_kind) {
2802     case Relaxed:
2803     case Acquire:
2804       break;
2805     case Release:
2806       insert_mem_bar(Op_MemBarRelease);
2807       break;
2808     case Volatile:
2809       if (support_IRIW_for_not_multiple_copy_atomic_cpu) {
2810         insert_mem_bar(Op_MemBarVolatile);
2811       } else {
2812         insert_mem_bar(Op_MemBarRelease);
2813       }
2814       break;
2815     default:
2816       ShouldNotReachHere();
2817   }
2818   insert_mem_bar(Op_MemBarCPUOrder);
2819 
2820   // Figure out the memory ordering.
2821   MemNode::MemOrd mo = access_kind_to_memord(access_kind);
2822 
2823   // 4984716: MemBars must be inserted before this
2824   //          memory node in order to avoid a false
2825   //          dependency which will confuse the scheduler.
2826   Node *mem = memory(alias_idx);
2827 
2828   // For now, we handle only those cases that actually exist: ints,
2829   // longs, and Object. Adding others should be straightforward.
2830   Node* load_store = NULL;
2831   switch(type) {
2832   case T_BYTE:
2833     switch(kind) {
2834       case LS_get_add:
2835         load_store = _gvn.transform(new GetAndAddBNode(control(), mem, adr, newval, adr_type));
2836         break;
2837       case LS_get_set:
2838         load_store = _gvn.transform(new GetAndSetBNode(control(), mem, adr, newval, adr_type));
2839         break;
2840       case LS_cmp_swap_weak:
2841         load_store = _gvn.transform(new WeakCompareAndSwapBNode(control(), mem, adr, newval, oldval, mo));
2842         break;
2843       case LS_cmp_swap:
2844         load_store = _gvn.transform(new CompareAndSwapBNode(control(), mem, adr, newval, oldval, mo));
2845         break;
2846       case LS_cmp_exchange:
2847         load_store = _gvn.transform(new CompareAndExchangeBNode(control(), mem, adr, newval, oldval, adr_type, mo));
2848         break;
2849       default:
2850         ShouldNotReachHere();
2851     }
2852     break;
2853   case T_SHORT:
2854     switch(kind) {
2855       case LS_get_add:
2856         load_store = _gvn.transform(new GetAndAddSNode(control(), mem, adr, newval, adr_type));
2857         break;
2858       case LS_get_set:
2859         load_store = _gvn.transform(new GetAndSetSNode(control(), mem, adr, newval, adr_type));
2860         break;
2861       case LS_cmp_swap_weak:
2862         load_store = _gvn.transform(new WeakCompareAndSwapSNode(control(), mem, adr, newval, oldval, mo));
2863         break;
2864       case LS_cmp_swap:
2865         load_store = _gvn.transform(new CompareAndSwapSNode(control(), mem, adr, newval, oldval, mo));
2866         break;
2867       case LS_cmp_exchange:
2868         load_store = _gvn.transform(new CompareAndExchangeSNode(control(), mem, adr, newval, oldval, adr_type, mo));
2869         break;
2870       default:
2871         ShouldNotReachHere();
2872     }
2873     break;
2874   case T_INT:
2875     switch(kind) {
2876       case LS_get_add:
2877         load_store = _gvn.transform(new GetAndAddINode(control(), mem, adr, newval, adr_type));
2878         break;
2879       case LS_get_set:
2880         load_store = _gvn.transform(new GetAndSetINode(control(), mem, adr, newval, adr_type));
2881         break;
2882       case LS_cmp_swap_weak:
2883         load_store = _gvn.transform(new WeakCompareAndSwapINode(control(), mem, adr, newval, oldval, mo));
2884         break;
2885       case LS_cmp_swap:
2886         load_store = _gvn.transform(new CompareAndSwapINode(control(), mem, adr, newval, oldval, mo));
2887         break;
2888       case LS_cmp_exchange:
2889         load_store = _gvn.transform(new CompareAndExchangeINode(control(), mem, adr, newval, oldval, adr_type, mo));
2890         break;
2891       default:
2892         ShouldNotReachHere();
2893     }
2894     break;
2895   case T_LONG:
2896     switch(kind) {
2897       case LS_get_add:
2898         load_store = _gvn.transform(new GetAndAddLNode(control(), mem, adr, newval, adr_type));
2899         break;
2900       case LS_get_set:
2901         load_store = _gvn.transform(new GetAndSetLNode(control(), mem, adr, newval, adr_type));
2902         break;
2903       case LS_cmp_swap_weak:
2904         load_store = _gvn.transform(new WeakCompareAndSwapLNode(control(), mem, adr, newval, oldval, mo));
2905         break;
2906       case LS_cmp_swap:
2907         load_store = _gvn.transform(new CompareAndSwapLNode(control(), mem, adr, newval, oldval, mo));
2908         break;
2909       case LS_cmp_exchange:
2910         load_store = _gvn.transform(new CompareAndExchangeLNode(control(), mem, adr, newval, oldval, adr_type, mo));
2911         break;
2912       default:
2913         ShouldNotReachHere();
2914     }
2915     break;
2916   case T_OBJECT:
2917     // Transformation of a value which could be NULL pointer (CastPP #NULL)
2918     // could be delayed during Parse (for example, in adjust_map_after_if()).
2919     // Execute transformation here to avoid barrier generation in such case.
2920     if (_gvn.type(newval) == TypePtr::NULL_PTR)
2921       newval = _gvn.makecon(TypePtr::NULL_PTR);
2922 
2923     // Reference stores need a store barrier.
2924     switch(kind) {
2925       case LS_get_set: {
2926         // If pre-barrier must execute before the oop store, old value will require do_load here.
2927         if (!can_move_pre_barrier()) {
2928           pre_barrier(true /* do_load*/,
2929                       control(), base, adr, alias_idx, newval, value_type->make_oopptr(),
2930                       NULL /* pre_val*/,
2931                       T_OBJECT);
2932         } // Else move pre_barrier to use load_store value, see below.
2933         break;
2934       }
2935       case LS_cmp_swap_weak:
2936       case LS_cmp_swap:
2937       case LS_cmp_exchange: {
2938         // Same as for newval above:
2939         if (_gvn.type(oldval) == TypePtr::NULL_PTR) {
2940           oldval = _gvn.makecon(TypePtr::NULL_PTR);
2941         }
2942         // The only known value which might get overwritten is oldval.
2943         pre_barrier(false /* do_load */,
2944                     control(), NULL, NULL, max_juint, NULL, NULL,
2945                     oldval /* pre_val */,
2946                     T_OBJECT);
2947         break;
2948       }
2949       default:
2950         ShouldNotReachHere();
2951     }
2952 
2953 #ifdef _LP64
2954     if (adr->bottom_type()->is_ptr_to_narrowoop()) {
2955       Node *newval_enc = _gvn.transform(new EncodePNode(newval, newval->bottom_type()->make_narrowoop()));
2956 
2957       switch(kind) {
2958         case LS_get_set:
2959           load_store = _gvn.transform(new GetAndSetNNode(control(), mem, adr, newval_enc, adr_type, value_type->make_narrowoop()));
2960           break;
2961         case LS_cmp_swap_weak: {
2962           Node *oldval_enc = _gvn.transform(new EncodePNode(oldval, oldval->bottom_type()->make_narrowoop()));
2963           load_store = _gvn.transform(new WeakCompareAndSwapNNode(control(), mem, adr, newval_enc, oldval_enc, mo));
2964           break;
2965         }
2966         case LS_cmp_swap: {
2967           Node *oldval_enc = _gvn.transform(new EncodePNode(oldval, oldval->bottom_type()->make_narrowoop()));
2968           load_store = _gvn.transform(new CompareAndSwapNNode(control(), mem, adr, newval_enc, oldval_enc, mo));
2969           break;
2970         }
2971         case LS_cmp_exchange: {
2972           Node *oldval_enc = _gvn.transform(new EncodePNode(oldval, oldval->bottom_type()->make_narrowoop()));
2973           load_store = _gvn.transform(new CompareAndExchangeNNode(control(), mem, adr, newval_enc, oldval_enc, adr_type, value_type->make_narrowoop(), mo));
2974           break;
2975         }
2976         default:
2977           ShouldNotReachHere();
2978       }
2979     } else
2980 #endif
2981     switch (kind) {
2982       case LS_get_set:
2983         load_store = _gvn.transform(new GetAndSetPNode(control(), mem, adr, newval, adr_type, value_type->is_oopptr()));
2984         break;
2985       case LS_cmp_swap_weak:
2986         load_store = _gvn.transform(new WeakCompareAndSwapPNode(control(), mem, adr, newval, oldval, mo));
2987         break;
2988       case LS_cmp_swap:
2989         load_store = _gvn.transform(new CompareAndSwapPNode(control(), mem, adr, newval, oldval, mo));
2990         break;
2991       case LS_cmp_exchange:
2992         load_store = _gvn.transform(new CompareAndExchangePNode(control(), mem, adr, newval, oldval, adr_type, value_type->is_oopptr(), mo));
2993         break;
2994       default:
2995         ShouldNotReachHere();
2996     }
2997 
2998     // Emit the post barrier only when the actual store happened. This makes sense
2999     // to check only for LS_cmp_* that can fail to set the value.
3000     // LS_cmp_exchange does not produce any branches by default, so there is no
3001     // boolean result to piggyback on. TODO: When we merge CompareAndSwap with
3002     // CompareAndExchange and move branches here, it would make sense to conditionalize
3003     // post_barriers for LS_cmp_exchange as well.
3004     //
3005     // CAS success path is marked more likely since we anticipate this is a performance
3006     // critical path, while CAS failure path can use the penalty for going through unlikely
3007     // path as backoff. Which is still better than doing a store barrier there.
3008     switch (kind) {
3009       case LS_get_set:
3010       case LS_cmp_exchange: {
3011         post_barrier(control(), load_store, base, adr, alias_idx, newval, T_OBJECT, true);
3012         break;
3013       }
3014       case LS_cmp_swap_weak:
3015       case LS_cmp_swap: {
3016         IdealKit ideal(this);
3017         ideal.if_then(load_store, BoolTest::ne, ideal.ConI(0), PROB_STATIC_FREQUENT); {
3018           sync_kit(ideal);
3019           post_barrier(ideal.ctrl(), load_store, base, adr, alias_idx, newval, T_OBJECT, true);
3020           ideal.sync_kit(this);
3021         } ideal.end_if();
3022         final_sync(ideal);
3023         break;
3024       }
3025       default:
3026         ShouldNotReachHere();
3027     }
3028     break;
3029   default:
3030     fatal("unexpected type %d: %s", type, type2name(type));
3031     break;
3032   }
3033 
3034   // SCMemProjNodes represent the memory state of a LoadStore. Their
3035   // main role is to prevent LoadStore nodes from being optimized away
3036   // when their results aren't used.
3037   Node* proj = _gvn.transform(new SCMemProjNode(load_store));
3038   set_memory(proj, alias_idx);
3039 
3040   if (type == T_OBJECT && (kind == LS_get_set || kind == LS_cmp_exchange)) {
3041 #ifdef _LP64
3042     if (adr->bottom_type()->is_ptr_to_narrowoop()) {
3043       load_store = _gvn.transform(new DecodeNNode(load_store, load_store->get_ptr_type()));
3044     }
3045 #endif
3046     if (can_move_pre_barrier() && kind == LS_get_set) {
3047       // Don't need to load pre_val. The old value is returned by load_store.
3048       // The pre_barrier can execute after the xchg as long as no safepoint
3049       // gets inserted between them.
3050       pre_barrier(false /* do_load */,
3051                   control(), NULL, NULL, max_juint, NULL, NULL,
3052                   load_store /* pre_val */,
3053                   T_OBJECT);
3054     }
3055   }
3056 
3057   // Add the trailing membar surrounding the access
3058   insert_mem_bar(Op_MemBarCPUOrder);
3059 
3060   switch (access_kind) {
3061     case Relaxed:
3062     case Release:
3063       break; // do nothing
3064     case Acquire:
3065     case Volatile:
3066       insert_mem_bar(Op_MemBarAcquire);
3067       // !support_IRIW_for_not_multiple_copy_atomic_cpu handled in platform code
3068       break;
3069     default:
3070       ShouldNotReachHere();
3071   }
3072 
3073   assert(type2size[load_store->bottom_type()->basic_type()] == type2size[rtype], "result type should match");
3074   set_result(load_store);
3075   return true;
3076 }
3077 
3078 MemNode::MemOrd LibraryCallKit::access_kind_to_memord_LS(AccessKind kind, bool is_store) {
3079   MemNode::MemOrd mo = MemNode::unset;
3080   switch(kind) {
3081     case Opaque:
3082     case Relaxed:  mo = MemNode::unordered; break;
3083     case Acquire:  mo = MemNode::acquire;   break;
3084     case Release:  mo = MemNode::release;   break;
3085     case Volatile: mo = is_store ? MemNode::release : MemNode::acquire; break;
3086     default:
3087       ShouldNotReachHere();
3088   }
3089   guarantee(mo != MemNode::unset, "Should select memory ordering");
3090   return mo;
3091 }
3092 
3093 MemNode::MemOrd LibraryCallKit::access_kind_to_memord(AccessKind kind) {
3094   MemNode::MemOrd mo = MemNode::unset;
3095   switch(kind) {
3096     case Opaque:
3097     case Relaxed:  mo = MemNode::unordered; break;
3098     case Acquire:  mo = MemNode::acquire;   break;
3099     case Release:  mo = MemNode::release;   break;
3100     case Volatile: mo = MemNode::seqcst;    break;
3101     default:
3102       ShouldNotReachHere();
3103   }
3104   guarantee(mo != MemNode::unset, "Should select memory ordering");
3105   return mo;
3106 }
3107 
3108 bool LibraryCallKit::inline_unsafe_fence(vmIntrinsics::ID id) {
3109   // Regardless of form, don't allow previous ld/st to move down,
3110   // then issue acquire, release, or volatile mem_bar.
3111   insert_mem_bar(Op_MemBarCPUOrder);
3112   switch(id) {
3113     case vmIntrinsics::_loadFence:
3114       insert_mem_bar(Op_LoadFence);
3115       return true;
3116     case vmIntrinsics::_storeFence:
3117       insert_mem_bar(Op_StoreFence);
3118       return true;
3119     case vmIntrinsics::_fullFence:
3120       insert_mem_bar(Op_MemBarVolatile);
3121       return true;
3122     default:
3123       fatal_unexpected_iid(id);
3124       return false;
3125   }
3126 }
3127 
3128 bool LibraryCallKit::inline_onspinwait() {
3129   insert_mem_bar(Op_OnSpinWait);
3130   return true;
3131 }
3132 
3133 bool LibraryCallKit::klass_needs_init_guard(Node* kls) {
3134   if (!kls->is_Con()) {
3135     return true;
3136   }
3137   const TypeKlassPtr* klsptr = kls->bottom_type()->isa_klassptr();
3138   if (klsptr == NULL) {
3139     return true;
3140   }
3141   ciInstanceKlass* ik = klsptr->klass()->as_instance_klass();
3142   // don't need a guard for a klass that is already initialized
3143   return !ik->is_initialized();
3144 }
3145 
3146 //----------------------------inline_unsafe_allocate---------------------------
3147 // public native Object Unsafe.allocateInstance(Class<?> cls);
3148 bool LibraryCallKit::inline_unsafe_allocate() {
3149   if (callee()->is_static())  return false;  // caller must have the capability!
3150 
3151   null_check_receiver();  // null-check, then ignore
3152   Node* cls = null_check(argument(1));
3153   if (stopped())  return true;
3154 
3155   Node* kls = load_klass_from_mirror(cls, false, NULL, 0);
3156   kls = null_check(kls);
3157   if (stopped())  return true;  // argument was like int.class
3158 
3159   Node* test = NULL;
3160   if (LibraryCallKit::klass_needs_init_guard(kls)) {
3161     // Note:  The argument might still be an illegal value like
3162     // Serializable.class or Object[].class.   The runtime will handle it.
3163     // But we must make an explicit check for initialization.
3164     Node* insp = basic_plus_adr(kls, in_bytes(InstanceKlass::init_state_offset()));
3165     // Use T_BOOLEAN for InstanceKlass::_init_state so the compiler
3166     // can generate code to load it as unsigned byte.
3167     Node* inst = make_load(NULL, insp, TypeInt::UBYTE, T_BOOLEAN, MemNode::unordered);
3168     Node* bits = intcon(InstanceKlass::fully_initialized);
3169     test = _gvn.transform(new SubINode(inst, bits));
3170     // The 'test' is non-zero if we need to take a slow path.
3171   }
3172 
3173   Node* obj = new_instance(kls, test);
3174   set_result(obj);
3175   return true;
3176 }
3177 
3178 //------------------------inline_native_time_funcs--------------
3179 // inline code for System.currentTimeMillis() and System.nanoTime()
3180 // these have the same type and signature
3181 bool LibraryCallKit::inline_native_time_funcs(address funcAddr, const char* funcName) {
3182   const TypeFunc* tf = OptoRuntime::void_long_Type();
3183   const TypePtr* no_memory_effects = NULL;
3184   Node* time = make_runtime_call(RC_LEAF, tf, funcAddr, funcName, no_memory_effects);
3185   Node* value = _gvn.transform(new ProjNode(time, TypeFunc::Parms+0));
3186 #ifdef ASSERT
3187   Node* value_top = _gvn.transform(new ProjNode(time, TypeFunc::Parms+1));
3188   assert(value_top == top(), "second value must be top");
3189 #endif
3190   set_result(value);
3191   return true;
3192 }
3193 
3194 #ifdef TRACE_HAVE_INTRINSICS
3195 
3196 /*
3197 * oop -> myklass
3198 * myklass->trace_id |= USED
3199 * return myklass->trace_id & ~0x3
3200 */
3201 bool LibraryCallKit::inline_native_classID() {
3202   Node* cls = null_check(argument(0), T_OBJECT);
3203   Node* kls = load_klass_from_mirror(cls, false, NULL, 0);
3204   kls = null_check(kls, T_OBJECT);
3205 
3206   ByteSize offset = TRACE_KLASS_TRACE_ID_OFFSET;
3207   Node* insp = basic_plus_adr(kls, in_bytes(offset));
3208   Node* tvalue = make_load(NULL, insp, TypeLong::LONG, T_LONG, MemNode::unordered);
3209 
3210   Node* clsused = longcon(0x01l); // set the class bit
3211   Node* orl = _gvn.transform(new OrLNode(tvalue, clsused));
3212   const TypePtr *adr_type = _gvn.type(insp)->isa_ptr();
3213   store_to_memory(control(), insp, orl, T_LONG, adr_type, MemNode::unordered);
3214 
3215 #ifdef TRACE_ID_META_BITS
3216   Node* mbits = longcon(~TRACE_ID_META_BITS);
3217   tvalue = _gvn.transform(new AndLNode(tvalue, mbits));
3218 #endif
3219 #ifdef TRACE_ID_CLASS_SHIFT
3220   Node* cbits = intcon(TRACE_ID_CLASS_SHIFT);
3221   tvalue = _gvn.transform(new URShiftLNode(tvalue, cbits));
3222 #endif
3223 
3224   set_result(tvalue);
3225   return true;
3226 
3227 }
3228 
3229 bool LibraryCallKit::inline_native_getBufferWriter() {
3230   Node* tls_ptr = _gvn.transform(new ThreadLocalNode());
3231 
3232   Node* jobj_ptr = basic_plus_adr(top(), tls_ptr,
3233                                   in_bytes(TRACE_THREAD_DATA_WRITER_OFFSET)
3234                                   );
3235 
3236   Node* jobj = make_load(control(), jobj_ptr, TypeRawPtr::BOTTOM, T_ADDRESS, MemNode::unordered);
3237 
3238   Node* jobj_cmp_null = _gvn.transform( new CmpPNode(jobj, null()) );
3239   Node* test_jobj_eq_null  = _gvn.transform( new BoolNode(jobj_cmp_null, BoolTest::eq) );
3240 
3241   IfNode* iff_jobj_null =
3242     create_and_map_if(control(), test_jobj_eq_null, PROB_MIN, COUNT_UNKNOWN);
3243 
3244   enum { _normal_path = 1,
3245          _null_path = 2,
3246          PATH_LIMIT };
3247 
3248   RegionNode* result_rgn = new RegionNode(PATH_LIMIT);
3249   PhiNode*    result_val = new PhiNode(result_rgn, TypePtr::BOTTOM);
3250 
3251   Node* jobj_is_null = _gvn.transform(new IfTrueNode(iff_jobj_null));
3252   result_rgn->init_req(_null_path, jobj_is_null);
3253   result_val->init_req(_null_path, null());
3254 
3255   Node* jobj_is_not_null = _gvn.transform(new IfFalseNode(iff_jobj_null));
3256   result_rgn->init_req(_normal_path, jobj_is_not_null);
3257 
3258   Node* res = make_load(jobj_is_not_null, jobj, TypeInstPtr::NOTNULL, T_OBJECT, MemNode::unordered);
3259   result_val->init_req(_normal_path, res);
3260 
3261   set_result(result_rgn, result_val);
3262 
3263   return true;
3264 }
3265 
3266 #endif
3267 
3268 //------------------------inline_native_currentThread------------------
3269 bool LibraryCallKit::inline_native_currentThread() {
3270   Node* junk = NULL;
3271   set_result(generate_current_thread(junk));
3272   return true;
3273 }
3274 
3275 //------------------------inline_native_isInterrupted------------------
3276 // private native boolean java.lang.Thread.isInterrupted(boolean ClearInterrupted);
3277 bool LibraryCallKit::inline_native_isInterrupted() {
3278   // Add a fast path to t.isInterrupted(clear_int):
3279   //   (t == Thread.current() &&
3280   //    (!TLS._osthread._interrupted || WINDOWS_ONLY(false) NOT_WINDOWS(!clear_int)))
3281   //   ? TLS._osthread._interrupted : /*slow path:*/ t.isInterrupted(clear_int)
3282   // So, in the common case that the interrupt bit is false,
3283   // we avoid making a call into the VM.  Even if the interrupt bit
3284   // is true, if the clear_int argument is false, we avoid the VM call.
3285   // However, if the receiver is not currentThread, we must call the VM,
3286   // because there must be some locking done around the operation.
3287 
3288   // We only go to the fast case code if we pass two guards.
3289   // Paths which do not pass are accumulated in the slow_region.
3290 
3291   enum {
3292     no_int_result_path   = 1, // t == Thread.current() && !TLS._osthread._interrupted
3293     no_clear_result_path = 2, // t == Thread.current() &&  TLS._osthread._interrupted && !clear_int
3294     slow_result_path     = 3, // slow path: t.isInterrupted(clear_int)
3295     PATH_LIMIT
3296   };
3297 
3298   // Ensure that it's not possible to move the load of TLS._osthread._interrupted flag
3299   // out of the function.
3300   insert_mem_bar(Op_MemBarCPUOrder);
3301 
3302   RegionNode* result_rgn = new RegionNode(PATH_LIMIT);
3303   PhiNode*    result_val = new PhiNode(result_rgn, TypeInt::BOOL);
3304 
3305   RegionNode* slow_region = new RegionNode(1);
3306   record_for_igvn(slow_region);
3307 
3308   // (a) Receiving thread must be the current thread.
3309   Node* rec_thr = argument(0);
3310   Node* tls_ptr = NULL;
3311   Node* cur_thr = generate_current_thread(tls_ptr);
3312   Node* cmp_thr = _gvn.transform(new CmpPNode(cur_thr, rec_thr));
3313   Node* bol_thr = _gvn.transform(new BoolNode(cmp_thr, BoolTest::ne));
3314 
3315   generate_slow_guard(bol_thr, slow_region);
3316 
3317   // (b) Interrupt bit on TLS must be false.
3318   Node* p = basic_plus_adr(top()/*!oop*/, tls_ptr, in_bytes(JavaThread::osthread_offset()));
3319   Node* osthread = make_load(NULL, p, TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered);
3320   p = basic_plus_adr(top()/*!oop*/, osthread, in_bytes(OSThread::interrupted_offset()));
3321 
3322   // Set the control input on the field _interrupted read to prevent it floating up.
3323   Node* int_bit = make_load(control(), p, TypeInt::BOOL, T_INT, MemNode::unordered);
3324   Node* cmp_bit = _gvn.transform(new CmpINode(int_bit, intcon(0)));
3325   Node* bol_bit = _gvn.transform(new BoolNode(cmp_bit, BoolTest::ne));
3326 
3327   IfNode* iff_bit = create_and_map_if(control(), bol_bit, PROB_UNLIKELY_MAG(3), COUNT_UNKNOWN);
3328 
3329   // First fast path:  if (!TLS._interrupted) return false;
3330   Node* false_bit = _gvn.transform(new IfFalseNode(iff_bit));
3331   result_rgn->init_req(no_int_result_path, false_bit);
3332   result_val->init_req(no_int_result_path, intcon(0));
3333 
3334   // drop through to next case
3335   set_control( _gvn.transform(new IfTrueNode(iff_bit)));
3336 
3337 #ifndef _WINDOWS
3338   // (c) Or, if interrupt bit is set and clear_int is false, use 2nd fast path.
3339   Node* clr_arg = argument(1);
3340   Node* cmp_arg = _gvn.transform(new CmpINode(clr_arg, intcon(0)));
3341   Node* bol_arg = _gvn.transform(new BoolNode(cmp_arg, BoolTest::ne));
3342   IfNode* iff_arg = create_and_map_if(control(), bol_arg, PROB_FAIR, COUNT_UNKNOWN);
3343 
3344   // Second fast path:  ... else if (!clear_int) return true;
3345   Node* false_arg = _gvn.transform(new IfFalseNode(iff_arg));
3346   result_rgn->init_req(no_clear_result_path, false_arg);
3347   result_val->init_req(no_clear_result_path, intcon(1));
3348 
3349   // drop through to next case
3350   set_control( _gvn.transform(new IfTrueNode(iff_arg)));
3351 #else
3352   // To return true on Windows you must read the _interrupted field
3353   // and check the event state i.e. take the slow path.
3354 #endif // _WINDOWS
3355 
3356   // (d) Otherwise, go to the slow path.
3357   slow_region->add_req(control());
3358   set_control( _gvn.transform(slow_region));
3359 
3360   if (stopped()) {
3361     // There is no slow path.
3362     result_rgn->init_req(slow_result_path, top());
3363     result_val->init_req(slow_result_path, top());
3364   } else {
3365     // non-virtual because it is a private non-static
3366     CallJavaNode* slow_call = generate_method_call(vmIntrinsics::_isInterrupted);
3367 
3368     Node* slow_val = set_results_for_java_call(slow_call);
3369     // this->control() comes from set_results_for_java_call
3370 
3371     Node* fast_io  = slow_call->in(TypeFunc::I_O);
3372     Node* fast_mem = slow_call->in(TypeFunc::Memory);
3373 
3374     // These two phis are pre-filled with copies of of the fast IO and Memory
3375     PhiNode* result_mem  = PhiNode::make(result_rgn, fast_mem, Type::MEMORY, TypePtr::BOTTOM);
3376     PhiNode* result_io   = PhiNode::make(result_rgn, fast_io,  Type::ABIO);
3377 
3378     result_rgn->init_req(slow_result_path, control());
3379     result_io ->init_req(slow_result_path, i_o());
3380     result_mem->init_req(slow_result_path, reset_memory());
3381     result_val->init_req(slow_result_path, slow_val);
3382 
3383     set_all_memory(_gvn.transform(result_mem));
3384     set_i_o(       _gvn.transform(result_io));
3385   }
3386 
3387   C->set_has_split_ifs(true); // Has chance for split-if optimization
3388   set_result(result_rgn, result_val);
3389   return true;
3390 }
3391 
3392 //---------------------------load_mirror_from_klass----------------------------
3393 // Given a klass oop, load its java mirror (a java.lang.Class oop).
3394 Node* LibraryCallKit::load_mirror_from_klass(Node* klass) {
3395   Node* p = basic_plus_adr(klass, in_bytes(Klass::java_mirror_offset()));
3396   return make_load(NULL, p, TypeInstPtr::MIRROR, T_OBJECT, MemNode::unordered);
3397 }
3398 
3399 //-----------------------load_klass_from_mirror_common-------------------------
3400 // Given a java mirror (a java.lang.Class oop), load its corresponding klass oop.
3401 // Test the klass oop for null (signifying a primitive Class like Integer.TYPE),
3402 // and branch to the given path on the region.
3403 // If never_see_null, take an uncommon trap on null, so we can optimistically
3404 // compile for the non-null case.
3405 // If the region is NULL, force never_see_null = true.
3406 Node* LibraryCallKit::load_klass_from_mirror_common(Node* mirror,
3407                                                     bool never_see_null,
3408                                                     RegionNode* region,
3409                                                     int null_path,
3410                                                     int offset) {
3411   if (region == NULL)  never_see_null = true;
3412   Node* p = basic_plus_adr(mirror, offset);
3413   const TypeKlassPtr*  kls_type = TypeKlassPtr::OBJECT_OR_NULL;
3414   Node* kls = _gvn.transform(LoadKlassNode::make(_gvn, NULL, immutable_memory(), p, TypeRawPtr::BOTTOM, kls_type));
3415   Node* null_ctl = top();
3416   kls = null_check_oop(kls, &null_ctl, never_see_null);
3417   if (region != NULL) {
3418     // Set region->in(null_path) if the mirror is a primitive (e.g, int.class).
3419     region->init_req(null_path, null_ctl);
3420   } else {
3421     assert(null_ctl == top(), "no loose ends");
3422   }
3423   return kls;
3424 }
3425 
3426 //--------------------(inline_native_Class_query helpers)---------------------
3427 // Use this for JVM_ACC_INTERFACE, JVM_ACC_IS_CLONEABLE_FAST, JVM_ACC_HAS_FINALIZER.
3428 // Fall through if (mods & mask) == bits, take the guard otherwise.
3429 Node* LibraryCallKit::generate_access_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region) {
3430   // Branch around if the given klass has the given modifier bit set.
3431   // Like generate_guard, adds a new path onto the region.
3432   Node* modp = basic_plus_adr(kls, in_bytes(Klass::access_flags_offset()));
3433   Node* mods = make_load(NULL, modp, TypeInt::INT, T_INT, MemNode::unordered);
3434   Node* mask = intcon(modifier_mask);
3435   Node* bits = intcon(modifier_bits);
3436   Node* mbit = _gvn.transform(new AndINode(mods, mask));
3437   Node* cmp  = _gvn.transform(new CmpINode(mbit, bits));
3438   Node* bol  = _gvn.transform(new BoolNode(cmp, BoolTest::ne));
3439   return generate_fair_guard(bol, region);
3440 }
3441 Node* LibraryCallKit::generate_interface_guard(Node* kls, RegionNode* region) {
3442   return generate_access_flags_guard(kls, JVM_ACC_INTERFACE, 0, region);
3443 }
3444 
3445 //-------------------------inline_native_Class_query-------------------
3446 bool LibraryCallKit::inline_native_Class_query(vmIntrinsics::ID id) {
3447   const Type* return_type = TypeInt::BOOL;
3448   Node* prim_return_value = top();  // what happens if it's a primitive class?
3449   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
3450   bool expect_prim = false;     // most of these guys expect to work on refs
3451 
3452   enum { _normal_path = 1, _prim_path = 2, PATH_LIMIT };
3453 
3454   Node* mirror = argument(0);
3455   Node* obj    = top();
3456 
3457   switch (id) {
3458   case vmIntrinsics::_isInstance:
3459     // nothing is an instance of a primitive type
3460     prim_return_value = intcon(0);
3461     obj = argument(1);
3462     break;
3463   case vmIntrinsics::_getModifiers:
3464     prim_return_value = intcon(JVM_ACC_ABSTRACT | JVM_ACC_FINAL | JVM_ACC_PUBLIC);
3465     assert(is_power_of_2((int)JVM_ACC_WRITTEN_FLAGS+1), "change next line");
3466     return_type = TypeInt::make(0, JVM_ACC_WRITTEN_FLAGS, Type::WidenMin);
3467     break;
3468   case vmIntrinsics::_isInterface:
3469     prim_return_value = intcon(0);
3470     break;
3471   case vmIntrinsics::_isArray:
3472     prim_return_value = intcon(0);
3473     expect_prim = true;  // cf. ObjectStreamClass.getClassSignature
3474     break;
3475   case vmIntrinsics::_isPrimitive:
3476     prim_return_value = intcon(1);
3477     expect_prim = true;  // obviously
3478     break;
3479   case vmIntrinsics::_getSuperclass:
3480     prim_return_value = null();
3481     return_type = TypeInstPtr::MIRROR->cast_to_ptr_type(TypePtr::BotPTR);
3482     break;
3483   case vmIntrinsics::_getClassAccessFlags:
3484     prim_return_value = intcon(JVM_ACC_ABSTRACT | JVM_ACC_FINAL | JVM_ACC_PUBLIC);
3485     return_type = TypeInt::INT;  // not bool!  6297094
3486     break;
3487   default:
3488     fatal_unexpected_iid(id);
3489     break;
3490   }
3491 
3492   const TypeInstPtr* mirror_con = _gvn.type(mirror)->isa_instptr();
3493   if (mirror_con == NULL)  return false;  // cannot happen?
3494 
3495 #ifndef PRODUCT
3496   if (C->print_intrinsics() || C->print_inlining()) {
3497     ciType* k = mirror_con->java_mirror_type();
3498     if (k) {
3499       tty->print("Inlining %s on constant Class ", vmIntrinsics::name_at(intrinsic_id()));
3500       k->print_name();
3501       tty->cr();
3502     }
3503   }
3504 #endif
3505 
3506   // Null-check the mirror, and the mirror's klass ptr (in case it is a primitive).
3507   RegionNode* region = new RegionNode(PATH_LIMIT);
3508   record_for_igvn(region);
3509   PhiNode* phi = new PhiNode(region, return_type);
3510 
3511   // The mirror will never be null of Reflection.getClassAccessFlags, however
3512   // it may be null for Class.isInstance or Class.getModifiers. Throw a NPE
3513   // if it is. See bug 4774291.
3514 
3515   // For Reflection.getClassAccessFlags(), the null check occurs in
3516   // the wrong place; see inline_unsafe_access(), above, for a similar
3517   // situation.
3518   mirror = null_check(mirror);
3519   // If mirror or obj is dead, only null-path is taken.
3520   if (stopped())  return true;
3521 
3522   if (expect_prim)  never_see_null = false;  // expect nulls (meaning prims)
3523 
3524   // Now load the mirror's klass metaobject, and null-check it.
3525   // Side-effects region with the control path if the klass is null.
3526   Node* kls = load_klass_from_mirror(mirror, never_see_null, region, _prim_path);
3527   // If kls is null, we have a primitive mirror.
3528   phi->init_req(_prim_path, prim_return_value);
3529   if (stopped()) { set_result(region, phi); return true; }
3530   bool safe_for_replace = (region->in(_prim_path) == top());
3531 
3532   Node* p;  // handy temp
3533   Node* null_ctl;
3534 
3535   // Now that we have the non-null klass, we can perform the real query.
3536   // For constant classes, the query will constant-fold in LoadNode::Value.
3537   Node* query_value = top();
3538   switch (id) {
3539   case vmIntrinsics::_isInstance:
3540     // nothing is an instance of a primitive type
3541     query_value = gen_instanceof(obj, kls, safe_for_replace);
3542     break;
3543 
3544   case vmIntrinsics::_getModifiers:
3545     p = basic_plus_adr(kls, in_bytes(Klass::modifier_flags_offset()));
3546     query_value = make_load(NULL, p, TypeInt::INT, T_INT, MemNode::unordered);
3547     break;
3548 
3549   case vmIntrinsics::_isInterface:
3550     // (To verify this code sequence, check the asserts in JVM_IsInterface.)
3551     if (generate_interface_guard(kls, region) != NULL)
3552       // A guard was added.  If the guard is taken, it was an interface.
3553       phi->add_req(intcon(1));
3554     // If we fall through, it's a plain class.
3555     query_value = intcon(0);
3556     break;
3557 
3558   case vmIntrinsics::_isArray:
3559     // (To verify this code sequence, check the asserts in JVM_IsArrayClass.)
3560     if (generate_array_guard(kls, region) != NULL)
3561       // A guard was added.  If the guard is taken, it was an array.
3562       phi->add_req(intcon(1));
3563     // If we fall through, it's a plain class.
3564     query_value = intcon(0);
3565     break;
3566 
3567   case vmIntrinsics::_isPrimitive:
3568     query_value = intcon(0); // "normal" path produces false
3569     break;
3570 
3571   case vmIntrinsics::_getSuperclass:
3572     // The rules here are somewhat unfortunate, but we can still do better
3573     // with random logic than with a JNI call.
3574     // Interfaces store null or Object as _super, but must report null.
3575     // Arrays store an intermediate super as _super, but must report Object.
3576     // Other types can report the actual _super.
3577     // (To verify this code sequence, check the asserts in JVM_IsInterface.)
3578     if (generate_interface_guard(kls, region) != NULL)
3579       // A guard was added.  If the guard is taken, it was an interface.
3580       phi->add_req(null());
3581     if (generate_array_guard(kls, region) != NULL)
3582       // A guard was added.  If the guard is taken, it was an array.
3583       phi->add_req(makecon(TypeInstPtr::make(env()->Object_klass()->java_mirror())));
3584     // If we fall through, it's a plain class.  Get its _super.
3585     p = basic_plus_adr(kls, in_bytes(Klass::super_offset()));
3586     kls = _gvn.transform(LoadKlassNode::make(_gvn, NULL, immutable_memory(), p, TypeRawPtr::BOTTOM, TypeKlassPtr::OBJECT_OR_NULL));
3587     null_ctl = top();
3588     kls = null_check_oop(kls, &null_ctl);
3589     if (null_ctl != top()) {
3590       // If the guard is taken, Object.superClass is null (both klass and mirror).
3591       region->add_req(null_ctl);
3592       phi   ->add_req(null());
3593     }
3594     if (!stopped()) {
3595       query_value = load_mirror_from_klass(kls);
3596     }
3597     break;
3598 
3599   case vmIntrinsics::_getClassAccessFlags:
3600     p = basic_plus_adr(kls, in_bytes(Klass::access_flags_offset()));
3601     query_value = make_load(NULL, p, TypeInt::INT, T_INT, MemNode::unordered);
3602     break;
3603 
3604   default:
3605     fatal_unexpected_iid(id);
3606     break;
3607   }
3608 
3609   // Fall-through is the normal case of a query to a real class.
3610   phi->init_req(1, query_value);
3611   region->init_req(1, control());
3612 
3613   C->set_has_split_ifs(true); // Has chance for split-if optimization
3614   set_result(region, phi);
3615   return true;
3616 }
3617 
3618 //-------------------------inline_Class_cast-------------------
3619 bool LibraryCallKit::inline_Class_cast() {
3620   Node* mirror = argument(0); // Class
3621   Node* obj    = argument(1);
3622   const TypeInstPtr* mirror_con = _gvn.type(mirror)->isa_instptr();
3623   if (mirror_con == NULL) {
3624     return false;  // dead path (mirror->is_top()).
3625   }
3626   if (obj == NULL || obj->is_top()) {
3627     return false;  // dead path
3628   }
3629   const TypeOopPtr* tp = _gvn.type(obj)->isa_oopptr();
3630 
3631   // First, see if Class.cast() can be folded statically.
3632   // java_mirror_type() returns non-null for compile-time Class constants.
3633   ciType* tm = mirror_con->java_mirror_type();
3634   if (tm != NULL && tm->is_klass() &&
3635       tp != NULL && tp->klass() != NULL) {
3636     if (!tp->klass()->is_loaded()) {
3637       // Don't use intrinsic when class is not loaded.
3638       return false;
3639     } else {
3640       int static_res = C->static_subtype_check(tm->as_klass(), tp->klass());
3641       if (static_res == Compile::SSC_always_true) {
3642         // isInstance() is true - fold the code.
3643         set_result(obj);
3644         return true;
3645       } else if (static_res == Compile::SSC_always_false) {
3646         // Don't use intrinsic, have to throw ClassCastException.
3647         // If the reference is null, the non-intrinsic bytecode will
3648         // be optimized appropriately.
3649         return false;
3650       }
3651     }
3652   }
3653 
3654   // Bailout intrinsic and do normal inlining if exception path is frequent.
3655   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
3656     return false;
3657   }
3658 
3659   // Generate dynamic checks.
3660   // Class.cast() is java implementation of _checkcast bytecode.
3661   // Do checkcast (Parse::do_checkcast()) optimizations here.
3662 
3663   mirror = null_check(mirror);
3664   // If mirror is dead, only null-path is taken.
3665   if (stopped()) {
3666     return true;
3667   }
3668 
3669   // Not-subtype or the mirror's klass ptr is NULL (in case it is a primitive).
3670   enum { _bad_type_path = 1, _prim_path = 2, PATH_LIMIT };
3671   RegionNode* region = new RegionNode(PATH_LIMIT);
3672   record_for_igvn(region);
3673 
3674   // Now load the mirror's klass metaobject, and null-check it.
3675   // If kls is null, we have a primitive mirror and
3676   // nothing is an instance of a primitive type.
3677   Node* kls = load_klass_from_mirror(mirror, false, region, _prim_path);
3678 
3679   Node* res = top();
3680   if (!stopped()) {
3681     Node* bad_type_ctrl = top();
3682     // Do checkcast optimizations.
3683     res = gen_checkcast(obj, kls, &bad_type_ctrl);
3684     region->init_req(_bad_type_path, bad_type_ctrl);
3685   }
3686   if (region->in(_prim_path) != top() ||
3687       region->in(_bad_type_path) != top()) {
3688     // Let Interpreter throw ClassCastException.
3689     PreserveJVMState pjvms(this);
3690     set_control(_gvn.transform(region));
3691     uncommon_trap(Deoptimization::Reason_intrinsic,
3692                   Deoptimization::Action_maybe_recompile);
3693   }
3694   if (!stopped()) {
3695     set_result(res);
3696   }
3697   return true;
3698 }
3699 
3700 
3701 //--------------------------inline_native_subtype_check------------------------
3702 // This intrinsic takes the JNI calls out of the heart of
3703 // UnsafeFieldAccessorImpl.set, which improves Field.set, readObject, etc.
3704 bool LibraryCallKit::inline_native_subtype_check() {
3705   // Pull both arguments off the stack.
3706   Node* args[2];                // two java.lang.Class mirrors: superc, subc
3707   args[0] = argument(0);
3708   args[1] = argument(1);
3709   Node* klasses[2];             // corresponding Klasses: superk, subk
3710   klasses[0] = klasses[1] = top();
3711 
3712   enum {
3713     // A full decision tree on {superc is prim, subc is prim}:
3714     _prim_0_path = 1,           // {P,N} => false
3715                                 // {P,P} & superc!=subc => false
3716     _prim_same_path,            // {P,P} & superc==subc => true
3717     _prim_1_path,               // {N,P} => false
3718     _ref_subtype_path,          // {N,N} & subtype check wins => true
3719     _both_ref_path,             // {N,N} & subtype check loses => false
3720     PATH_LIMIT
3721   };
3722 
3723   RegionNode* region = new RegionNode(PATH_LIMIT);
3724   Node*       phi    = new PhiNode(region, TypeInt::BOOL);
3725   record_for_igvn(region);
3726 
3727   const TypePtr* adr_type = TypeRawPtr::BOTTOM;   // memory type of loads
3728   const TypeKlassPtr* kls_type = TypeKlassPtr::OBJECT_OR_NULL;
3729   int class_klass_offset = java_lang_Class::klass_offset_in_bytes();
3730 
3731   // First null-check both mirrors and load each mirror's klass metaobject.
3732   int which_arg;
3733   for (which_arg = 0; which_arg <= 1; which_arg++) {
3734     Node* arg = args[which_arg];
3735     arg = null_check(arg);
3736     if (stopped())  break;
3737     args[which_arg] = arg;
3738 
3739     Node* p = basic_plus_adr(arg, class_klass_offset);
3740     Node* kls = LoadKlassNode::make(_gvn, NULL, immutable_memory(), p, adr_type, kls_type);
3741     klasses[which_arg] = _gvn.transform(kls);
3742   }
3743 
3744   // Having loaded both klasses, test each for null.
3745   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
3746   for (which_arg = 0; which_arg <= 1; which_arg++) {
3747     Node* kls = klasses[which_arg];
3748     Node* null_ctl = top();
3749     kls = null_check_oop(kls, &null_ctl, never_see_null);
3750     int prim_path = (which_arg == 0 ? _prim_0_path : _prim_1_path);
3751     region->init_req(prim_path, null_ctl);
3752     if (stopped())  break;
3753     klasses[which_arg] = kls;
3754   }
3755 
3756   if (!stopped()) {
3757     // now we have two reference types, in klasses[0..1]
3758     Node* subk   = klasses[1];  // the argument to isAssignableFrom
3759     Node* superk = klasses[0];  // the receiver
3760     region->set_req(_both_ref_path, gen_subtype_check(subk, superk));
3761     // now we have a successful reference subtype check
3762     region->set_req(_ref_subtype_path, control());
3763   }
3764 
3765   // If both operands are primitive (both klasses null), then
3766   // we must return true when they are identical primitives.
3767   // It is convenient to test this after the first null klass check.
3768   set_control(region->in(_prim_0_path)); // go back to first null check
3769   if (!stopped()) {
3770     // Since superc is primitive, make a guard for the superc==subc case.
3771     Node* cmp_eq = _gvn.transform(new CmpPNode(args[0], args[1]));
3772     Node* bol_eq = _gvn.transform(new BoolNode(cmp_eq, BoolTest::eq));
3773     generate_guard(bol_eq, region, PROB_FAIR);
3774     if (region->req() == PATH_LIMIT+1) {
3775       // A guard was added.  If the added guard is taken, superc==subc.
3776       region->swap_edges(PATH_LIMIT, _prim_same_path);
3777       region->del_req(PATH_LIMIT);
3778     }
3779     region->set_req(_prim_0_path, control()); // Not equal after all.
3780   }
3781 
3782   // these are the only paths that produce 'true':
3783   phi->set_req(_prim_same_path,   intcon(1));
3784   phi->set_req(_ref_subtype_path, intcon(1));
3785 
3786   // pull together the cases:
3787   assert(region->req() == PATH_LIMIT, "sane region");
3788   for (uint i = 1; i < region->req(); i++) {
3789     Node* ctl = region->in(i);
3790     if (ctl == NULL || ctl == top()) {
3791       region->set_req(i, top());
3792       phi   ->set_req(i, top());
3793     } else if (phi->in(i) == NULL) {
3794       phi->set_req(i, intcon(0)); // all other paths produce 'false'
3795     }
3796   }
3797 
3798   set_control(_gvn.transform(region));
3799   set_result(_gvn.transform(phi));
3800   return true;
3801 }
3802 
3803 //---------------------generate_array_guard_common------------------------
3804 Node* LibraryCallKit::generate_array_guard_common(Node* kls, RegionNode* region,
3805                                                   bool obj_array, bool not_array) {
3806 
3807   if (stopped()) {
3808     return NULL;
3809   }
3810 
3811   // If obj_array/non_array==false/false:
3812   // Branch around if the given klass is in fact an array (either obj or prim).
3813   // If obj_array/non_array==false/true:
3814   // Branch around if the given klass is not an array klass of any kind.
3815   // If obj_array/non_array==true/true:
3816   // Branch around if the kls is not an oop array (kls is int[], String, etc.)
3817   // If obj_array/non_array==true/false:
3818   // Branch around if the kls is an oop array (Object[] or subtype)
3819   //
3820   // Like generate_guard, adds a new path onto the region.
3821   jint  layout_con = 0;
3822   Node* layout_val = get_layout_helper(kls, layout_con);
3823   if (layout_val == NULL) {
3824     bool query = (obj_array
3825                   ? Klass::layout_helper_is_objArray(layout_con)
3826                   : Klass::layout_helper_is_array(layout_con));
3827     if (query == not_array) {
3828       return NULL;                       // never a branch
3829     } else {                             // always a branch
3830       Node* always_branch = control();
3831       if (region != NULL)
3832         region->add_req(always_branch);
3833       set_control(top());
3834       return always_branch;
3835     }
3836   }
3837   // Now test the correct condition.
3838   jint  nval = (obj_array
3839                 ? (jint)(Klass::_lh_array_tag_type_value
3840                    <<    Klass::_lh_array_tag_shift)
3841                 : Klass::_lh_neutral_value);
3842   Node* cmp = _gvn.transform(new CmpINode(layout_val, intcon(nval)));
3843   BoolTest::mask btest = BoolTest::lt;  // correct for testing is_[obj]array
3844   // invert the test if we are looking for a non-array
3845   if (not_array)  btest = BoolTest(btest).negate();
3846   Node* bol = _gvn.transform(new BoolNode(cmp, btest));
3847   return generate_fair_guard(bol, region);
3848 }
3849 
3850 
3851 //-----------------------inline_native_newArray--------------------------
3852 // private static native Object java.lang.reflect.newArray(Class<?> componentType, int length);
3853 // private        native Object Unsafe.allocateUninitializedArray0(Class<?> cls, int size);
3854 bool LibraryCallKit::inline_unsafe_newArray(bool uninitialized) {
3855   Node* mirror;
3856   Node* count_val;
3857   if (uninitialized) {
3858     mirror    = argument(1);
3859     count_val = argument(2);
3860   } else {
3861     mirror    = argument(0);
3862     count_val = argument(1);
3863   }
3864 
3865   mirror = null_check(mirror);
3866   // If mirror or obj is dead, only null-path is taken.
3867   if (stopped())  return true;
3868 
3869   enum { _normal_path = 1, _slow_path = 2, PATH_LIMIT };
3870   RegionNode* result_reg = new RegionNode(PATH_LIMIT);
3871   PhiNode*    result_val = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
3872   PhiNode*    result_io  = new PhiNode(result_reg, Type::ABIO);
3873   PhiNode*    result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
3874 
3875   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
3876   Node* klass_node = load_array_klass_from_mirror(mirror, never_see_null,
3877                                                   result_reg, _slow_path);
3878   Node* normal_ctl   = control();
3879   Node* no_array_ctl = result_reg->in(_slow_path);
3880 
3881   // Generate code for the slow case.  We make a call to newArray().
3882   set_control(no_array_ctl);
3883   if (!stopped()) {
3884     // Either the input type is void.class, or else the
3885     // array klass has not yet been cached.  Either the
3886     // ensuing call will throw an exception, or else it
3887     // will cache the array klass for next time.
3888     PreserveJVMState pjvms(this);
3889     CallJavaNode* slow_call = generate_method_call_static(vmIntrinsics::_newArray);
3890     Node* slow_result = set_results_for_java_call(slow_call);
3891     // this->control() comes from set_results_for_java_call
3892     result_reg->set_req(_slow_path, control());
3893     result_val->set_req(_slow_path, slow_result);
3894     result_io ->set_req(_slow_path, i_o());
3895     result_mem->set_req(_slow_path, reset_memory());
3896   }
3897 
3898   set_control(normal_ctl);
3899   if (!stopped()) {
3900     // Normal case:  The array type has been cached in the java.lang.Class.
3901     // The following call works fine even if the array type is polymorphic.
3902     // It could be a dynamic mix of int[], boolean[], Object[], etc.
3903     Node* obj = new_array(klass_node, count_val, 0);  // no arguments to push
3904     result_reg->init_req(_normal_path, control());
3905     result_val->init_req(_normal_path, obj);
3906     result_io ->init_req(_normal_path, i_o());
3907     result_mem->init_req(_normal_path, reset_memory());
3908 
3909     if (uninitialized) {
3910       // Mark the allocation so that zeroing is skipped
3911       AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(obj, &_gvn);
3912       alloc->maybe_set_complete(&_gvn);
3913     }
3914   }
3915 
3916   // Return the combined state.
3917   set_i_o(        _gvn.transform(result_io)  );
3918   set_all_memory( _gvn.transform(result_mem));
3919 
3920   C->set_has_split_ifs(true); // Has chance for split-if optimization
3921   set_result(result_reg, result_val);
3922   return true;
3923 }
3924 
3925 //----------------------inline_native_getLength--------------------------
3926 // public static native int java.lang.reflect.Array.getLength(Object array);
3927 bool LibraryCallKit::inline_native_getLength() {
3928   if (too_many_traps(Deoptimization::Reason_intrinsic))  return false;
3929 
3930   Node* array = null_check(argument(0));
3931   // If array is dead, only null-path is taken.
3932   if (stopped())  return true;
3933 
3934   // Deoptimize if it is a non-array.
3935   Node* non_array = generate_non_array_guard(load_object_klass(array), NULL);
3936 
3937   if (non_array != NULL) {
3938     PreserveJVMState pjvms(this);
3939     set_control(non_array);
3940     uncommon_trap(Deoptimization::Reason_intrinsic,
3941                   Deoptimization::Action_maybe_recompile);
3942   }
3943 
3944   // If control is dead, only non-array-path is taken.
3945   if (stopped())  return true;
3946 
3947   // The works fine even if the array type is polymorphic.
3948   // It could be a dynamic mix of int[], boolean[], Object[], etc.
3949   Node* result = load_array_length(array);
3950 
3951   C->set_has_split_ifs(true);  // Has chance for split-if optimization
3952   set_result(result);
3953   return true;
3954 }
3955 
3956 //------------------------inline_array_copyOf----------------------------
3957 // public static <T,U> T[] java.util.Arrays.copyOf(     U[] original, int newLength,         Class<? extends T[]> newType);
3958 // public static <T,U> T[] java.util.Arrays.copyOfRange(U[] original, int from,      int to, Class<? extends T[]> newType);
3959 bool LibraryCallKit::inline_array_copyOf(bool is_copyOfRange) {
3960   if (too_many_traps(Deoptimization::Reason_intrinsic))  return false;
3961 
3962   // Get the arguments.
3963   Node* original          = argument(0);
3964   Node* start             = is_copyOfRange? argument(1): intcon(0);
3965   Node* end               = is_copyOfRange? argument(2): argument(1);
3966   Node* array_type_mirror = is_copyOfRange? argument(3): argument(2);
3967 
3968   Node* newcopy = NULL;
3969 
3970   // Set the original stack and the reexecute bit for the interpreter to reexecute
3971   // the bytecode that invokes Arrays.copyOf if deoptimization happens.
3972   { PreserveReexecuteState preexecs(this);
3973     jvms()->set_should_reexecute(true);
3974 
3975     array_type_mirror = null_check(array_type_mirror);
3976     original          = null_check(original);
3977 
3978     // Check if a null path was taken unconditionally.
3979     if (stopped())  return true;
3980 
3981     Node* orig_length = load_array_length(original);
3982 
3983     Node* klass_node = load_klass_from_mirror(array_type_mirror, false, NULL, 0);
3984     klass_node = null_check(klass_node);
3985 
3986     RegionNode* bailout = new RegionNode(1);
3987     record_for_igvn(bailout);
3988 
3989     // Despite the generic type of Arrays.copyOf, the mirror might be int, int[], etc.
3990     // Bail out if that is so.
3991     Node* not_objArray = generate_non_objArray_guard(klass_node, bailout);
3992     if (not_objArray != NULL) {
3993       // Improve the klass node's type from the new optimistic assumption:
3994       ciKlass* ak = ciArrayKlass::make(env()->Object_klass());
3995       const Type* akls = TypeKlassPtr::make(TypePtr::NotNull, ak, 0/*offset*/);
3996       Node* cast = new CastPPNode(klass_node, akls);
3997       cast->init_req(0, control());
3998       klass_node = _gvn.transform(cast);
3999     }
4000 
4001     // Bail out if either start or end is negative.
4002     generate_negative_guard(start, bailout, &start);
4003     generate_negative_guard(end,   bailout, &end);
4004 
4005     Node* length = end;
4006     if (_gvn.type(start) != TypeInt::ZERO) {
4007       length = _gvn.transform(new SubINode(end, start));
4008     }
4009 
4010     // Bail out if length is negative.
4011     // Without this the new_array would throw
4012     // NegativeArraySizeException but IllegalArgumentException is what
4013     // should be thrown
4014     generate_negative_guard(length, bailout, &length);
4015 
4016     if (bailout->req() > 1) {
4017       PreserveJVMState pjvms(this);
4018       set_control(_gvn.transform(bailout));
4019       uncommon_trap(Deoptimization::Reason_intrinsic,
4020                     Deoptimization::Action_maybe_recompile);
4021     }
4022 
4023     if (!stopped()) {
4024       // How many elements will we copy from the original?
4025       // The answer is MinI(orig_length - start, length).
4026       Node* orig_tail = _gvn.transform(new SubINode(orig_length, start));
4027       Node* moved = generate_min_max(vmIntrinsics::_min, orig_tail, length);
4028 
4029       // Generate a direct call to the right arraycopy function(s).
4030       // We know the copy is disjoint but we might not know if the
4031       // oop stores need checking.
4032       // Extreme case:  Arrays.copyOf((Integer[])x, 10, String[].class).
4033       // This will fail a store-check if x contains any non-nulls.
4034 
4035       // ArrayCopyNode:Ideal may transform the ArrayCopyNode to
4036       // loads/stores but it is legal only if we're sure the
4037       // Arrays.copyOf would succeed. So we need all input arguments
4038       // to the copyOf to be validated, including that the copy to the
4039       // new array won't trigger an ArrayStoreException. That subtype
4040       // check can be optimized if we know something on the type of
4041       // the input array from type speculation.
4042       if (_gvn.type(klass_node)->singleton()) {
4043         ciKlass* subk   = _gvn.type(load_object_klass(original))->is_klassptr()->klass();
4044         ciKlass* superk = _gvn.type(klass_node)->is_klassptr()->klass();
4045 
4046         int test = C->static_subtype_check(superk, subk);
4047         if (test != Compile::SSC_always_true && test != Compile::SSC_always_false) {
4048           const TypeOopPtr* t_original = _gvn.type(original)->is_oopptr();
4049           if (t_original->speculative_type() != NULL) {
4050             original = maybe_cast_profiled_obj(original, t_original->speculative_type(), true);
4051           }
4052         }
4053       }
4054 
4055       bool validated = false;
4056       // Reason_class_check rather than Reason_intrinsic because we
4057       // want to intrinsify even if this traps.
4058       if (!too_many_traps(Deoptimization::Reason_class_check)) {
4059         Node* not_subtype_ctrl = gen_subtype_check(load_object_klass(original),
4060                                                    klass_node);
4061 
4062         if (not_subtype_ctrl != top()) {
4063           PreserveJVMState pjvms(this);
4064           set_control(not_subtype_ctrl);
4065           uncommon_trap(Deoptimization::Reason_class_check,
4066                         Deoptimization::Action_make_not_entrant);
4067           assert(stopped(), "Should be stopped");
4068         }
4069         validated = true;
4070       }
4071 
4072       if (!stopped()) {
4073         newcopy = new_array(klass_node, length, 0);  // no arguments to push
4074 
4075         ArrayCopyNode* ac = ArrayCopyNode::make(this, true, original, start, newcopy, intcon(0), moved, true, false,
4076                                                 load_object_klass(original), klass_node);
4077         if (!is_copyOfRange) {
4078           ac->set_copyof(validated);
4079         } else {
4080           ac->set_copyofrange(validated);
4081         }
4082         Node* n = _gvn.transform(ac);
4083         if (n == ac) {
4084           ac->connect_outputs(this);
4085         } else {
4086           assert(validated, "shouldn't transform if all arguments not validated");
4087           set_all_memory(n);
4088         }
4089       }
4090     }
4091   } // original reexecute is set back here
4092 
4093   C->set_has_split_ifs(true); // Has chance for split-if optimization
4094   if (!stopped()) {
4095     set_result(newcopy);
4096   }
4097   return true;
4098 }
4099 
4100 
4101 //----------------------generate_virtual_guard---------------------------
4102 // Helper for hashCode and clone.  Peeks inside the vtable to avoid a call.
4103 Node* LibraryCallKit::generate_virtual_guard(Node* obj_klass,
4104                                              RegionNode* slow_region) {
4105   ciMethod* method = callee();
4106   int vtable_index = method->vtable_index();
4107   assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index,
4108          "bad index %d", vtable_index);
4109   // Get the Method* out of the appropriate vtable entry.
4110   int entry_offset  = in_bytes(Klass::vtable_start_offset()) +
4111                      vtable_index*vtableEntry::size_in_bytes() +
4112                      vtableEntry::method_offset_in_bytes();
4113   Node* entry_addr  = basic_plus_adr(obj_klass, entry_offset);
4114   Node* target_call = make_load(NULL, entry_addr, TypePtr::NOTNULL, T_ADDRESS, MemNode::unordered);
4115 
4116   // Compare the target method with the expected method (e.g., Object.hashCode).
4117   const TypePtr* native_call_addr = TypeMetadataPtr::make(method);
4118 
4119   Node* native_call = makecon(native_call_addr);
4120   Node* chk_native  = _gvn.transform(new CmpPNode(target_call, native_call));
4121   Node* test_native = _gvn.transform(new BoolNode(chk_native, BoolTest::ne));
4122 
4123   return generate_slow_guard(test_native, slow_region);
4124 }
4125 
4126 //-----------------------generate_method_call----------------------------
4127 // Use generate_method_call to make a slow-call to the real
4128 // method if the fast path fails.  An alternative would be to
4129 // use a stub like OptoRuntime::slow_arraycopy_Java.
4130 // This only works for expanding the current library call,
4131 // not another intrinsic.  (E.g., don't use this for making an
4132 // arraycopy call inside of the copyOf intrinsic.)
4133 CallJavaNode*
4134 LibraryCallKit::generate_method_call(vmIntrinsics::ID method_id, bool is_virtual, bool is_static) {
4135   // When compiling the intrinsic method itself, do not use this technique.
4136   guarantee(callee() != C->method(), "cannot make slow-call to self");
4137 
4138   ciMethod* method = callee();
4139   // ensure the JVMS we have will be correct for this call
4140   guarantee(method_id == method->intrinsic_id(), "must match");
4141 
4142   const TypeFunc* tf = TypeFunc::make(method);
4143   CallJavaNode* slow_call;
4144   if (is_static) {
4145     assert(!is_virtual, "");
4146     slow_call = new CallStaticJavaNode(C, tf,
4147                            SharedRuntime::get_resolve_static_call_stub(),
4148                            method, bci());
4149   } else if (is_virtual) {
4150     null_check_receiver();
4151     int vtable_index = Method::invalid_vtable_index;
4152     if (UseInlineCaches) {
4153       // Suppress the vtable call
4154     } else {
4155       // hashCode and clone are not a miranda methods,
4156       // so the vtable index is fixed.
4157       // No need to use the linkResolver to get it.
4158        vtable_index = method->vtable_index();
4159        assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index,
4160               "bad index %d", vtable_index);
4161     }
4162     slow_call = new CallDynamicJavaNode(tf,
4163                           SharedRuntime::get_resolve_virtual_call_stub(),
4164                           method, vtable_index, bci());
4165   } else {  // neither virtual nor static:  opt_virtual
4166     null_check_receiver();
4167     slow_call = new CallStaticJavaNode(C, tf,
4168                                 SharedRuntime::get_resolve_opt_virtual_call_stub(),
4169                                 method, bci());
4170     slow_call->set_optimized_virtual(true);
4171   }
4172   set_arguments_for_java_call(slow_call);
4173   set_edges_for_java_call(slow_call);
4174   return slow_call;
4175 }
4176 
4177 
4178 /**
4179  * Build special case code for calls to hashCode on an object. This call may
4180  * be virtual (invokevirtual) or bound (invokespecial). For each case we generate
4181  * slightly different code.
4182  */
4183 bool LibraryCallKit::inline_native_hashcode(bool is_virtual, bool is_static) {
4184   assert(is_static == callee()->is_static(), "correct intrinsic selection");
4185   assert(!(is_virtual && is_static), "either virtual, special, or static");
4186 
4187   enum { _slow_path = 1, _fast_path, _null_path, PATH_LIMIT };
4188 
4189   RegionNode* result_reg = new RegionNode(PATH_LIMIT);
4190   PhiNode*    result_val = new PhiNode(result_reg, TypeInt::INT);
4191   PhiNode*    result_io  = new PhiNode(result_reg, Type::ABIO);
4192   PhiNode*    result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
4193   Node* obj = NULL;
4194   if (!is_static) {
4195     // Check for hashing null object
4196     obj = null_check_receiver();
4197     if (stopped())  return true;        // unconditionally null
4198     result_reg->init_req(_null_path, top());
4199     result_val->init_req(_null_path, top());
4200   } else {
4201     // Do a null check, and return zero if null.
4202     // System.identityHashCode(null) == 0
4203     obj = argument(0);
4204     Node* null_ctl = top();
4205     obj = null_check_oop(obj, &null_ctl);
4206     result_reg->init_req(_null_path, null_ctl);
4207     result_val->init_req(_null_path, _gvn.intcon(0));
4208   }
4209 
4210   // Unconditionally null?  Then return right away.
4211   if (stopped()) {
4212     set_control( result_reg->in(_null_path));
4213     if (!stopped())
4214       set_result(result_val->in(_null_path));
4215     return true;
4216   }
4217 
4218   // We only go to the fast case code if we pass a number of guards.  The
4219   // paths which do not pass are accumulated in the slow_region.
4220   RegionNode* slow_region = new RegionNode(1);
4221   record_for_igvn(slow_region);
4222 
4223   // If this is a virtual call, we generate a funny guard.  We pull out
4224   // the vtable entry corresponding to hashCode() from the target object.
4225   // If the target method which we are calling happens to be the native
4226   // Object hashCode() method, we pass the guard.  We do not need this
4227   // guard for non-virtual calls -- the caller is known to be the native
4228   // Object hashCode().
4229   if (is_virtual) {
4230     // After null check, get the object's klass.
4231     Node* obj_klass = load_object_klass(obj);
4232     generate_virtual_guard(obj_klass, slow_region);
4233   }
4234 
4235   // Get the header out of the object, use LoadMarkNode when available
4236   Node* header_addr = basic_plus_adr(obj, oopDesc::mark_offset_in_bytes());
4237   // The control of the load must be NULL. Otherwise, the load can move before
4238   // the null check after castPP removal.
4239   Node* no_ctrl = NULL;
4240   Node* header = make_load(no_ctrl, header_addr, TypeX_X, TypeX_X->basic_type(), MemNode::unordered);
4241 
4242   // Test the header to see if it is unlocked.
4243   Node *lock_mask      = _gvn.MakeConX(markOopDesc::biased_lock_mask_in_place);
4244   Node *lmasked_header = _gvn.transform(new AndXNode(header, lock_mask));
4245   Node *unlocked_val   = _gvn.MakeConX(markOopDesc::unlocked_value);
4246   Node *chk_unlocked   = _gvn.transform(new CmpXNode( lmasked_header, unlocked_val));
4247   Node *test_unlocked  = _gvn.transform(new BoolNode( chk_unlocked, BoolTest::ne));
4248 
4249   generate_slow_guard(test_unlocked, slow_region);
4250 
4251   // Get the hash value and check to see that it has been properly assigned.
4252   // We depend on hash_mask being at most 32 bits and avoid the use of
4253   // hash_mask_in_place because it could be larger than 32 bits in a 64-bit
4254   // vm: see markOop.hpp.
4255   Node *hash_mask      = _gvn.intcon(markOopDesc::hash_mask);
4256   Node *hash_shift     = _gvn.intcon(markOopDesc::hash_shift);
4257   Node *hshifted_header= _gvn.transform(new URShiftXNode(header, hash_shift));
4258   // This hack lets the hash bits live anywhere in the mark object now, as long
4259   // as the shift drops the relevant bits into the low 32 bits.  Note that
4260   // Java spec says that HashCode is an int so there's no point in capturing
4261   // an 'X'-sized hashcode (32 in 32-bit build or 64 in 64-bit build).
4262   hshifted_header      = ConvX2I(hshifted_header);
4263   Node *hash_val       = _gvn.transform(new AndINode(hshifted_header, hash_mask));
4264 
4265   Node *no_hash_val    = _gvn.intcon(markOopDesc::no_hash);
4266   Node *chk_assigned   = _gvn.transform(new CmpINode( hash_val, no_hash_val));
4267   Node *test_assigned  = _gvn.transform(new BoolNode( chk_assigned, BoolTest::eq));
4268 
4269   generate_slow_guard(test_assigned, slow_region);
4270 
4271   Node* init_mem = reset_memory();
4272   // fill in the rest of the null path:
4273   result_io ->init_req(_null_path, i_o());
4274   result_mem->init_req(_null_path, init_mem);
4275 
4276   result_val->init_req(_fast_path, hash_val);
4277   result_reg->init_req(_fast_path, control());
4278   result_io ->init_req(_fast_path, i_o());
4279   result_mem->init_req(_fast_path, init_mem);
4280 
4281   // Generate code for the slow case.  We make a call to hashCode().
4282   set_control(_gvn.transform(slow_region));
4283   if (!stopped()) {
4284     // No need for PreserveJVMState, because we're using up the present state.
4285     set_all_memory(init_mem);
4286     vmIntrinsics::ID hashCode_id = is_static ? vmIntrinsics::_identityHashCode : vmIntrinsics::_hashCode;
4287     CallJavaNode* slow_call = generate_method_call(hashCode_id, is_virtual, is_static);
4288     Node* slow_result = set_results_for_java_call(slow_call);
4289     // this->control() comes from set_results_for_java_call
4290     result_reg->init_req(_slow_path, control());
4291     result_val->init_req(_slow_path, slow_result);
4292     result_io  ->set_req(_slow_path, i_o());
4293     result_mem ->set_req(_slow_path, reset_memory());
4294   }
4295 
4296   // Return the combined state.
4297   set_i_o(        _gvn.transform(result_io)  );
4298   set_all_memory( _gvn.transform(result_mem));
4299 
4300   set_result(result_reg, result_val);
4301   return true;
4302 }
4303 
4304 //---------------------------inline_native_getClass----------------------------
4305 // public final native Class<?> java.lang.Object.getClass();
4306 //
4307 // Build special case code for calls to getClass on an object.
4308 bool LibraryCallKit::inline_native_getClass() {
4309   Node* obj = null_check_receiver();
4310   if (stopped())  return true;
4311   set_result(load_mirror_from_klass(load_object_klass(obj)));
4312   return true;
4313 }
4314 
4315 //-----------------inline_native_Reflection_getCallerClass---------------------
4316 // public static native Class<?> sun.reflect.Reflection.getCallerClass();
4317 //
4318 // In the presence of deep enough inlining, getCallerClass() becomes a no-op.
4319 //
4320 // NOTE: This code must perform the same logic as JVM_GetCallerClass
4321 // in that it must skip particular security frames and checks for
4322 // caller sensitive methods.
4323 bool LibraryCallKit::inline_native_Reflection_getCallerClass() {
4324 #ifndef PRODUCT
4325   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
4326     tty->print_cr("Attempting to inline sun.reflect.Reflection.getCallerClass");
4327   }
4328 #endif
4329 
4330   if (!jvms()->has_method()) {
4331 #ifndef PRODUCT
4332     if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
4333       tty->print_cr("  Bailing out because intrinsic was inlined at top level");
4334     }
4335 #endif
4336     return false;
4337   }
4338 
4339   // Walk back up the JVM state to find the caller at the required
4340   // depth.
4341   JVMState* caller_jvms = jvms();
4342 
4343   // Cf. JVM_GetCallerClass
4344   // NOTE: Start the loop at depth 1 because the current JVM state does
4345   // not include the Reflection.getCallerClass() frame.
4346   for (int n = 1; caller_jvms != NULL; caller_jvms = caller_jvms->caller(), n++) {
4347     ciMethod* m = caller_jvms->method();
4348     switch (n) {
4349     case 0:
4350       fatal("current JVM state does not include the Reflection.getCallerClass frame");
4351       break;
4352     case 1:
4353       // Frame 0 and 1 must be caller sensitive (see JVM_GetCallerClass).
4354       if (!m->caller_sensitive()) {
4355 #ifndef PRODUCT
4356         if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
4357           tty->print_cr("  Bailing out: CallerSensitive annotation expected at frame %d", n);
4358         }
4359 #endif
4360         return false;  // bail-out; let JVM_GetCallerClass do the work
4361       }
4362       break;
4363     default:
4364       if (!m->is_ignored_by_security_stack_walk()) {
4365         // We have reached the desired frame; return the holder class.
4366         // Acquire method holder as java.lang.Class and push as constant.
4367         ciInstanceKlass* caller_klass = caller_jvms->method()->holder();
4368         ciInstance* caller_mirror = caller_klass->java_mirror();
4369         set_result(makecon(TypeInstPtr::make(caller_mirror)));
4370 
4371 #ifndef PRODUCT
4372         if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
4373           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());
4374           tty->print_cr("  JVM state at this point:");
4375           for (int i = jvms()->depth(), n = 1; i >= 1; i--, n++) {
4376             ciMethod* m = jvms()->of_depth(i)->method();
4377             tty->print_cr("   %d) %s.%s", n, m->holder()->name()->as_utf8(), m->name()->as_utf8());
4378           }
4379         }
4380 #endif
4381         return true;
4382       }
4383       break;
4384     }
4385   }
4386 
4387 #ifndef PRODUCT
4388   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
4389     tty->print_cr("  Bailing out because caller depth exceeded inlining depth = %d", jvms()->depth());
4390     tty->print_cr("  JVM state at this point:");
4391     for (int i = jvms()->depth(), n = 1; i >= 1; i--, n++) {
4392       ciMethod* m = jvms()->of_depth(i)->method();
4393       tty->print_cr("   %d) %s.%s", n, m->holder()->name()->as_utf8(), m->name()->as_utf8());
4394     }
4395   }
4396 #endif
4397 
4398   return false;  // bail-out; let JVM_GetCallerClass do the work
4399 }
4400 
4401 bool LibraryCallKit::inline_fp_conversions(vmIntrinsics::ID id) {
4402   Node* arg = argument(0);
4403   Node* result = NULL;
4404 
4405   switch (id) {
4406   case vmIntrinsics::_floatToRawIntBits:    result = new MoveF2INode(arg);  break;
4407   case vmIntrinsics::_intBitsToFloat:       result = new MoveI2FNode(arg);  break;
4408   case vmIntrinsics::_doubleToRawLongBits:  result = new MoveD2LNode(arg);  break;
4409   case vmIntrinsics::_longBitsToDouble:     result = new MoveL2DNode(arg);  break;
4410 
4411   case vmIntrinsics::_doubleToLongBits: {
4412     // two paths (plus control) merge in a wood
4413     RegionNode *r = new RegionNode(3);
4414     Node *phi = new PhiNode(r, TypeLong::LONG);
4415 
4416     Node *cmpisnan = _gvn.transform(new CmpDNode(arg, arg));
4417     // Build the boolean node
4418     Node *bolisnan = _gvn.transform(new BoolNode(cmpisnan, BoolTest::ne));
4419 
4420     // Branch either way.
4421     // NaN case is less traveled, which makes all the difference.
4422     IfNode *ifisnan = create_and_xform_if(control(), bolisnan, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
4423     Node *opt_isnan = _gvn.transform(ifisnan);
4424     assert( opt_isnan->is_If(), "Expect an IfNode");
4425     IfNode *opt_ifisnan = (IfNode*)opt_isnan;
4426     Node *iftrue = _gvn.transform(new IfTrueNode(opt_ifisnan));
4427 
4428     set_control(iftrue);
4429 
4430     static const jlong nan_bits = CONST64(0x7ff8000000000000);
4431     Node *slow_result = longcon(nan_bits); // return NaN
4432     phi->init_req(1, _gvn.transform( slow_result ));
4433     r->init_req(1, iftrue);
4434 
4435     // Else fall through
4436     Node *iffalse = _gvn.transform(new IfFalseNode(opt_ifisnan));
4437     set_control(iffalse);
4438 
4439     phi->init_req(2, _gvn.transform(new MoveD2LNode(arg)));
4440     r->init_req(2, iffalse);
4441 
4442     // Post merge
4443     set_control(_gvn.transform(r));
4444     record_for_igvn(r);
4445 
4446     C->set_has_split_ifs(true); // Has chance for split-if optimization
4447     result = phi;
4448     assert(result->bottom_type()->isa_long(), "must be");
4449     break;
4450   }
4451 
4452   case vmIntrinsics::_floatToIntBits: {
4453     // two paths (plus control) merge in a wood
4454     RegionNode *r = new RegionNode(3);
4455     Node *phi = new PhiNode(r, TypeInt::INT);
4456 
4457     Node *cmpisnan = _gvn.transform(new CmpFNode(arg, arg));
4458     // Build the boolean node
4459     Node *bolisnan = _gvn.transform(new BoolNode(cmpisnan, BoolTest::ne));
4460 
4461     // Branch either way.
4462     // NaN case is less traveled, which makes all the difference.
4463     IfNode *ifisnan = create_and_xform_if(control(), bolisnan, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
4464     Node *opt_isnan = _gvn.transform(ifisnan);
4465     assert( opt_isnan->is_If(), "Expect an IfNode");
4466     IfNode *opt_ifisnan = (IfNode*)opt_isnan;
4467     Node *iftrue = _gvn.transform(new IfTrueNode(opt_ifisnan));
4468 
4469     set_control(iftrue);
4470 
4471     static const jint nan_bits = 0x7fc00000;
4472     Node *slow_result = makecon(TypeInt::make(nan_bits)); // return NaN
4473     phi->init_req(1, _gvn.transform( slow_result ));
4474     r->init_req(1, iftrue);
4475 
4476     // Else fall through
4477     Node *iffalse = _gvn.transform(new IfFalseNode(opt_ifisnan));
4478     set_control(iffalse);
4479 
4480     phi->init_req(2, _gvn.transform(new MoveF2INode(arg)));
4481     r->init_req(2, iffalse);
4482 
4483     // Post merge
4484     set_control(_gvn.transform(r));
4485     record_for_igvn(r);
4486 
4487     C->set_has_split_ifs(true); // Has chance for split-if optimization
4488     result = phi;
4489     assert(result->bottom_type()->isa_int(), "must be");
4490     break;
4491   }
4492 
4493   default:
4494     fatal_unexpected_iid(id);
4495     break;
4496   }
4497   set_result(_gvn.transform(result));
4498   return true;
4499 }
4500 
4501 //----------------------inline_unsafe_copyMemory-------------------------
4502 // public native void Unsafe.copyMemory0(Object srcBase, long srcOffset, Object destBase, long destOffset, long bytes);
4503 bool LibraryCallKit::inline_unsafe_copyMemory() {
4504   if (callee()->is_static())  return false;  // caller must have the capability!
4505   null_check_receiver();  // null-check receiver
4506   if (stopped())  return true;
4507 
4508   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
4509 
4510   Node* src_ptr =         argument(1);   // type: oop
4511   Node* src_off = ConvL2X(argument(2));  // type: long
4512   Node* dst_ptr =         argument(4);   // type: oop
4513   Node* dst_off = ConvL2X(argument(5));  // type: long
4514   Node* size    = ConvL2X(argument(7));  // type: long
4515 
4516   assert(Unsafe_field_offset_to_byte_offset(11) == 11,
4517          "fieldOffset must be byte-scaled");
4518 
4519   Node* src = make_unsafe_address(src_ptr, src_off);
4520   Node* dst = make_unsafe_address(dst_ptr, dst_off);
4521 
4522   // Conservatively insert a memory barrier on all memory slices.
4523   // Do not let writes of the copy source or destination float below the copy.
4524   insert_mem_bar(Op_MemBarCPUOrder);
4525 
4526   // Call it.  Note that the length argument is not scaled.
4527   make_runtime_call(RC_LEAF|RC_NO_FP,
4528                     OptoRuntime::fast_arraycopy_Type(),
4529                     StubRoutines::unsafe_arraycopy(),
4530                     "unsafe_arraycopy",
4531                     TypeRawPtr::BOTTOM,
4532                     src, dst, size XTOP);
4533 
4534   // Do not let reads of the copy destination float above the copy.
4535   insert_mem_bar(Op_MemBarCPUOrder);
4536 
4537   return true;
4538 }
4539 
4540 //------------------------clone_coping-----------------------------------
4541 // Helper function for inline_native_clone.
4542 void LibraryCallKit::copy_to_clone(Node* obj, Node* alloc_obj, Node* obj_size, bool is_array, bool card_mark) {
4543   assert(obj_size != NULL, "");
4544   Node* raw_obj = alloc_obj->in(1);
4545   assert(alloc_obj->is_CheckCastPP() && raw_obj->is_Proj() && raw_obj->in(0)->is_Allocate(), "");
4546 
4547   AllocateNode* alloc = NULL;
4548   if (ReduceBulkZeroing) {
4549     // We will be completely responsible for initializing this object -
4550     // mark Initialize node as complete.
4551     alloc = AllocateNode::Ideal_allocation(alloc_obj, &_gvn);
4552     // The object was just allocated - there should be no any stores!
4553     guarantee(alloc != NULL && alloc->maybe_set_complete(&_gvn), "");
4554     // Mark as complete_with_arraycopy so that on AllocateNode
4555     // expansion, we know this AllocateNode is initialized by an array
4556     // copy and a StoreStore barrier exists after the array copy.
4557     alloc->initialization()->set_complete_with_arraycopy();
4558   }
4559 
4560   // Copy the fastest available way.
4561   // TODO: generate fields copies for small objects instead.
4562   Node* src  = obj;
4563   Node* dest = alloc_obj;
4564   Node* size = _gvn.transform(obj_size);
4565 
4566   // Exclude the header but include array length to copy by 8 bytes words.
4567   // Can't use base_offset_in_bytes(bt) since basic type is unknown.
4568   int base_off = is_array ? arrayOopDesc::length_offset_in_bytes() :
4569                             instanceOopDesc::base_offset_in_bytes();
4570   // base_off:
4571   // 8  - 32-bit VM
4572   // 12 - 64-bit VM, compressed klass
4573   // 16 - 64-bit VM, normal klass
4574   if (base_off % BytesPerLong != 0) {
4575     assert(UseCompressedClassPointers, "");
4576     if (is_array) {
4577       // Exclude length to copy by 8 bytes words.
4578       base_off += sizeof(int);
4579     } else {
4580       // Include klass to copy by 8 bytes words.
4581       base_off = instanceOopDesc::klass_offset_in_bytes();
4582     }
4583     assert(base_off % BytesPerLong == 0, "expect 8 bytes alignment");
4584   }
4585   src  = basic_plus_adr(src,  base_off);
4586   dest = basic_plus_adr(dest, base_off);
4587 
4588   // Compute the length also, if needed:
4589   Node* countx = size;
4590   countx = _gvn.transform(new SubXNode(countx, MakeConX(base_off)));
4591   countx = _gvn.transform(new URShiftXNode(countx, intcon(LogBytesPerLong) ));
4592 
4593   const TypePtr* raw_adr_type = TypeRawPtr::BOTTOM;
4594 
4595   ArrayCopyNode* ac = ArrayCopyNode::make(this, false, src, NULL, dest, NULL, countx, false, false);
4596   ac->set_clonebasic();
4597   Node* n = _gvn.transform(ac);
4598   if (n == ac) {
4599     set_predefined_output_for_runtime_call(ac, ac->in(TypeFunc::Memory), raw_adr_type);
4600   } else {
4601     set_all_memory(n);
4602   }
4603 
4604   // If necessary, emit some card marks afterwards.  (Non-arrays only.)
4605   if (card_mark) {
4606     assert(!is_array, "");
4607     // Put in store barrier for any and all oops we are sticking
4608     // into this object.  (We could avoid this if we could prove
4609     // that the object type contains no oop fields at all.)
4610     Node* no_particular_value = NULL;
4611     Node* no_particular_field = NULL;
4612     int raw_adr_idx = Compile::AliasIdxRaw;
4613     post_barrier(control(),
4614                  memory(raw_adr_type),
4615                  alloc_obj,
4616                  no_particular_field,
4617                  raw_adr_idx,
4618                  no_particular_value,
4619                  T_OBJECT,
4620                  false);
4621   }
4622 
4623   // Do not let reads from the cloned object float above the arraycopy.
4624   if (alloc != NULL) {
4625     // Do not let stores that initialize this object be reordered with
4626     // a subsequent store that would make this object accessible by
4627     // other threads.
4628     // Record what AllocateNode this StoreStore protects so that
4629     // escape analysis can go from the MemBarStoreStoreNode to the
4630     // AllocateNode and eliminate the MemBarStoreStoreNode if possible
4631     // based on the escape status of the AllocateNode.
4632     insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out(AllocateNode::RawAddress));
4633   } else {
4634     insert_mem_bar(Op_MemBarCPUOrder);
4635   }
4636 }
4637 
4638 //------------------------inline_native_clone----------------------------
4639 // protected native Object java.lang.Object.clone();
4640 //
4641 // Here are the simple edge cases:
4642 //  null receiver => normal trap
4643 //  virtual and clone was overridden => slow path to out-of-line clone
4644 //  not cloneable or finalizer => slow path to out-of-line Object.clone
4645 //
4646 // The general case has two steps, allocation and copying.
4647 // Allocation has two cases, and uses GraphKit::new_instance or new_array.
4648 //
4649 // Copying also has two cases, oop arrays and everything else.
4650 // Oop arrays use arrayof_oop_arraycopy (same as System.arraycopy).
4651 // Everything else uses the tight inline loop supplied by CopyArrayNode.
4652 //
4653 // These steps fold up nicely if and when the cloned object's klass
4654 // can be sharply typed as an object array, a type array, or an instance.
4655 //
4656 bool LibraryCallKit::inline_native_clone(bool is_virtual) {
4657   PhiNode* result_val;
4658 
4659   // Set the reexecute bit for the interpreter to reexecute
4660   // the bytecode that invokes Object.clone if deoptimization happens.
4661   { PreserveReexecuteState preexecs(this);
4662     jvms()->set_should_reexecute(true);
4663 
4664     Node* obj = null_check_receiver();
4665     if (stopped())  return true;
4666 
4667     const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
4668 
4669     // If we are going to clone an instance, we need its exact type to
4670     // know the number and types of fields to convert the clone to
4671     // loads/stores. Maybe a speculative type can help us.
4672     if (!obj_type->klass_is_exact() &&
4673         obj_type->speculative_type() != NULL &&
4674         obj_type->speculative_type()->is_instance_klass()) {
4675       ciInstanceKlass* spec_ik = obj_type->speculative_type()->as_instance_klass();
4676       if (spec_ik->nof_nonstatic_fields() <= ArrayCopyLoadStoreMaxElem &&
4677           !spec_ik->has_injected_fields()) {
4678         ciKlass* k = obj_type->klass();
4679         if (!k->is_instance_klass() ||
4680             k->as_instance_klass()->is_interface() ||
4681             k->as_instance_klass()->has_subklass()) {
4682           obj = maybe_cast_profiled_obj(obj, obj_type->speculative_type(), false);
4683         }
4684       }
4685     }
4686 
4687     Node* obj_klass = load_object_klass(obj);
4688     const TypeKlassPtr* tklass = _gvn.type(obj_klass)->isa_klassptr();
4689     const TypeOopPtr*   toop   = ((tklass != NULL)
4690                                 ? tklass->as_instance_type()
4691                                 : TypeInstPtr::NOTNULL);
4692 
4693     // Conservatively insert a memory barrier on all memory slices.
4694     // Do not let writes into the original float below the clone.
4695     insert_mem_bar(Op_MemBarCPUOrder);
4696 
4697     // paths into result_reg:
4698     enum {
4699       _slow_path = 1,     // out-of-line call to clone method (virtual or not)
4700       _objArray_path,     // plain array allocation, plus arrayof_oop_arraycopy
4701       _array_path,        // plain array allocation, plus arrayof_long_arraycopy
4702       _instance_path,     // plain instance allocation, plus arrayof_long_arraycopy
4703       PATH_LIMIT
4704     };
4705     RegionNode* result_reg = new RegionNode(PATH_LIMIT);
4706     result_val             = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
4707     PhiNode*    result_i_o = new PhiNode(result_reg, Type::ABIO);
4708     PhiNode*    result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
4709     record_for_igvn(result_reg);
4710 
4711     const TypePtr* raw_adr_type = TypeRawPtr::BOTTOM;
4712     int raw_adr_idx = Compile::AliasIdxRaw;
4713 
4714     Node* array_ctl = generate_array_guard(obj_klass, (RegionNode*)NULL);
4715     if (array_ctl != NULL) {
4716       // It's an array.
4717       PreserveJVMState pjvms(this);
4718       set_control(array_ctl);
4719       Node* obj_length = load_array_length(obj);
4720       Node* obj_size  = NULL;
4721       Node* alloc_obj = new_array(obj_klass, obj_length, 0, &obj_size);  // no arguments to push
4722 
4723       if (!use_ReduceInitialCardMarks()) {
4724         // If it is an oop array, it requires very special treatment,
4725         // because card marking is required on each card of the array.
4726         Node* is_obja = generate_objArray_guard(obj_klass, (RegionNode*)NULL);
4727         if (is_obja != NULL) {
4728           PreserveJVMState pjvms2(this);
4729           set_control(is_obja);
4730           // Generate a direct call to the right arraycopy function(s).
4731           Node* alloc = tightly_coupled_allocation(alloc_obj, NULL);
4732           ArrayCopyNode* ac = ArrayCopyNode::make(this, true, obj, intcon(0), alloc_obj, intcon(0), obj_length, alloc != NULL, false);
4733           ac->set_cloneoop();
4734           Node* n = _gvn.transform(ac);
4735           assert(n == ac, "cannot disappear");
4736           ac->connect_outputs(this);
4737 
4738           result_reg->init_req(_objArray_path, control());
4739           result_val->init_req(_objArray_path, alloc_obj);
4740           result_i_o ->set_req(_objArray_path, i_o());
4741           result_mem ->set_req(_objArray_path, reset_memory());
4742         }
4743       }
4744       // Otherwise, there are no card marks to worry about.
4745       // (We can dispense with card marks if we know the allocation
4746       //  comes out of eden (TLAB)...  In fact, ReduceInitialCardMarks
4747       //  causes the non-eden paths to take compensating steps to
4748       //  simulate a fresh allocation, so that no further
4749       //  card marks are required in compiled code to initialize
4750       //  the object.)
4751 
4752       if (!stopped()) {
4753         copy_to_clone(obj, alloc_obj, obj_size, true, false);
4754 
4755         // Present the results of the copy.
4756         result_reg->init_req(_array_path, control());
4757         result_val->init_req(_array_path, alloc_obj);
4758         result_i_o ->set_req(_array_path, i_o());
4759         result_mem ->set_req(_array_path, reset_memory());
4760       }
4761     }
4762 
4763     // We only go to the instance fast case code if we pass a number of guards.
4764     // The paths which do not pass are accumulated in the slow_region.
4765     RegionNode* slow_region = new RegionNode(1);
4766     record_for_igvn(slow_region);
4767     if (!stopped()) {
4768       // It's an instance (we did array above).  Make the slow-path tests.
4769       // If this is a virtual call, we generate a funny guard.  We grab
4770       // the vtable entry corresponding to clone() from the target object.
4771       // If the target method which we are calling happens to be the
4772       // Object clone() method, we pass the guard.  We do not need this
4773       // guard for non-virtual calls; the caller is known to be the native
4774       // Object clone().
4775       if (is_virtual) {
4776         generate_virtual_guard(obj_klass, slow_region);
4777       }
4778 
4779       // The object must be easily cloneable and must not have a finalizer.
4780       // Both of these conditions may be checked in a single test.
4781       // We could optimize the test further, but we don't care.
4782       generate_access_flags_guard(obj_klass,
4783                                   // Test both conditions:
4784                                   JVM_ACC_IS_CLONEABLE_FAST | JVM_ACC_HAS_FINALIZER,
4785                                   // Must be cloneable but not finalizer:
4786                                   JVM_ACC_IS_CLONEABLE_FAST,
4787                                   slow_region);
4788     }
4789 
4790     if (!stopped()) {
4791       // It's an instance, and it passed the slow-path tests.
4792       PreserveJVMState pjvms(this);
4793       Node* obj_size  = NULL;
4794       // Need to deoptimize on exception from allocation since Object.clone intrinsic
4795       // is reexecuted if deoptimization occurs and there could be problems when merging
4796       // exception state between multiple Object.clone versions (reexecute=true vs reexecute=false).
4797       Node* alloc_obj = new_instance(obj_klass, NULL, &obj_size, /*deoptimize_on_exception=*/true);
4798 
4799       copy_to_clone(obj, alloc_obj, obj_size, false, !use_ReduceInitialCardMarks());
4800 
4801       // Present the results of the slow call.
4802       result_reg->init_req(_instance_path, control());
4803       result_val->init_req(_instance_path, alloc_obj);
4804       result_i_o ->set_req(_instance_path, i_o());
4805       result_mem ->set_req(_instance_path, reset_memory());
4806     }
4807 
4808     // Generate code for the slow case.  We make a call to clone().
4809     set_control(_gvn.transform(slow_region));
4810     if (!stopped()) {
4811       PreserveJVMState pjvms(this);
4812       CallJavaNode* slow_call = generate_method_call(vmIntrinsics::_clone, is_virtual);
4813       Node* slow_result = set_results_for_java_call(slow_call);
4814       // this->control() comes from set_results_for_java_call
4815       result_reg->init_req(_slow_path, control());
4816       result_val->init_req(_slow_path, slow_result);
4817       result_i_o ->set_req(_slow_path, i_o());
4818       result_mem ->set_req(_slow_path, reset_memory());
4819     }
4820 
4821     // Return the combined state.
4822     set_control(    _gvn.transform(result_reg));
4823     set_i_o(        _gvn.transform(result_i_o));
4824     set_all_memory( _gvn.transform(result_mem));
4825   } // original reexecute is set back here
4826 
4827   set_result(_gvn.transform(result_val));
4828   return true;
4829 }
4830 
4831 // If we have a tighly coupled allocation, the arraycopy may take care
4832 // of the array initialization. If one of the guards we insert between
4833 // the allocation and the arraycopy causes a deoptimization, an
4834 // unitialized array will escape the compiled method. To prevent that
4835 // we set the JVM state for uncommon traps between the allocation and
4836 // the arraycopy to the state before the allocation so, in case of
4837 // deoptimization, we'll reexecute the allocation and the
4838 // initialization.
4839 JVMState* LibraryCallKit::arraycopy_restore_alloc_state(AllocateArrayNode* alloc, int& saved_reexecute_sp) {
4840   if (alloc != NULL) {
4841     ciMethod* trap_method = alloc->jvms()->method();
4842     int trap_bci = alloc->jvms()->bci();
4843 
4844     if (!C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_intrinsic) &
4845           !C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_null_check)) {
4846       // Make sure there's no store between the allocation and the
4847       // arraycopy otherwise visible side effects could be rexecuted
4848       // in case of deoptimization and cause incorrect execution.
4849       bool no_interfering_store = true;
4850       Node* mem = alloc->in(TypeFunc::Memory);
4851       if (mem->is_MergeMem()) {
4852         for (MergeMemStream mms(merged_memory(), mem->as_MergeMem()); mms.next_non_empty2(); ) {
4853           Node* n = mms.memory();
4854           if (n != mms.memory2() && !(n->is_Proj() && n->in(0) == alloc->initialization())) {
4855             assert(n->is_Store(), "what else?");
4856             no_interfering_store = false;
4857             break;
4858           }
4859         }
4860       } else {
4861         for (MergeMemStream mms(merged_memory()); mms.next_non_empty(); ) {
4862           Node* n = mms.memory();
4863           if (n != mem && !(n->is_Proj() && n->in(0) == alloc->initialization())) {
4864             assert(n->is_Store(), "what else?");
4865             no_interfering_store = false;
4866             break;
4867           }
4868         }
4869       }
4870 
4871       if (no_interfering_store) {
4872         JVMState* old_jvms = alloc->jvms()->clone_shallow(C);
4873         uint size = alloc->req();
4874         SafePointNode* sfpt = new SafePointNode(size, old_jvms);
4875         old_jvms->set_map(sfpt);
4876         for (uint i = 0; i < size; i++) {
4877           sfpt->init_req(i, alloc->in(i));
4878         }
4879         // re-push array length for deoptimization
4880         sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp(), alloc->in(AllocateNode::ALength));
4881         old_jvms->set_sp(old_jvms->sp()+1);
4882         old_jvms->set_monoff(old_jvms->monoff()+1);
4883         old_jvms->set_scloff(old_jvms->scloff()+1);
4884         old_jvms->set_endoff(old_jvms->endoff()+1);
4885         old_jvms->set_should_reexecute(true);
4886 
4887         sfpt->set_i_o(map()->i_o());
4888         sfpt->set_memory(map()->memory());
4889         sfpt->set_control(map()->control());
4890 
4891         JVMState* saved_jvms = jvms();
4892         saved_reexecute_sp = _reexecute_sp;
4893 
4894         set_jvms(sfpt->jvms());
4895         _reexecute_sp = jvms()->sp();
4896 
4897         return saved_jvms;
4898       }
4899     }
4900   }
4901   return NULL;
4902 }
4903 
4904 // In case of a deoptimization, we restart execution at the
4905 // allocation, allocating a new array. We would leave an uninitialized
4906 // array in the heap that GCs wouldn't expect. Move the allocation
4907 // after the traps so we don't allocate the array if we
4908 // deoptimize. This is possible because tightly_coupled_allocation()
4909 // guarantees there's no observer of the allocated array at this point
4910 // and the control flow is simple enough.
4911 void LibraryCallKit::arraycopy_move_allocation_here(AllocateArrayNode* alloc, Node* dest, JVMState* saved_jvms,
4912                                                     int saved_reexecute_sp, uint new_idx) {
4913   if (saved_jvms != NULL && !stopped()) {
4914     assert(alloc != NULL, "only with a tightly coupled allocation");
4915     // restore JVM state to the state at the arraycopy
4916     saved_jvms->map()->set_control(map()->control());
4917     assert(saved_jvms->map()->memory() == map()->memory(), "memory state changed?");
4918     assert(saved_jvms->map()->i_o() == map()->i_o(), "IO state changed?");
4919     // If we've improved the types of some nodes (null check) while
4920     // emitting the guards, propagate them to the current state
4921     map()->replaced_nodes().apply(saved_jvms->map(), new_idx);
4922     set_jvms(saved_jvms);
4923     _reexecute_sp = saved_reexecute_sp;
4924 
4925     // Remove the allocation from above the guards
4926     CallProjections callprojs;
4927     alloc->extract_projections(&callprojs, true);
4928     InitializeNode* init = alloc->initialization();
4929     Node* alloc_mem = alloc->in(TypeFunc::Memory);
4930     C->gvn_replace_by(callprojs.fallthrough_ioproj, alloc->in(TypeFunc::I_O));
4931     C->gvn_replace_by(init->proj_out(TypeFunc::Memory), alloc_mem);
4932     C->gvn_replace_by(init->proj_out(TypeFunc::Control), alloc->in(0));
4933 
4934     // move the allocation here (after the guards)
4935     _gvn.hash_delete(alloc);
4936     alloc->set_req(TypeFunc::Control, control());
4937     alloc->set_req(TypeFunc::I_O, i_o());
4938     Node *mem = reset_memory();
4939     set_all_memory(mem);
4940     alloc->set_req(TypeFunc::Memory, mem);
4941     set_control(init->proj_out(TypeFunc::Control));
4942     set_i_o(callprojs.fallthrough_ioproj);
4943 
4944     // Update memory as done in GraphKit::set_output_for_allocation()
4945     const TypeInt* length_type = _gvn.find_int_type(alloc->in(AllocateNode::ALength));
4946     const TypeOopPtr* ary_type = _gvn.type(alloc->in(AllocateNode::KlassNode))->is_klassptr()->as_instance_type();
4947     if (ary_type->isa_aryptr() && length_type != NULL) {
4948       ary_type = ary_type->is_aryptr()->cast_to_size(length_type);
4949     }
4950     const TypePtr* telemref = ary_type->add_offset(Type::OffsetBot);
4951     int            elemidx  = C->get_alias_index(telemref);
4952     set_memory(init->proj_out(TypeFunc::Memory), Compile::AliasIdxRaw);
4953     set_memory(init->proj_out(TypeFunc::Memory), elemidx);
4954 
4955     Node* allocx = _gvn.transform(alloc);
4956     assert(allocx == alloc, "where has the allocation gone?");
4957     assert(dest->is_CheckCastPP(), "not an allocation result?");
4958 
4959     _gvn.hash_delete(dest);
4960     dest->set_req(0, control());
4961     Node* destx = _gvn.transform(dest);
4962     assert(destx == dest, "where has the allocation result gone?");
4963   }
4964 }
4965 
4966 
4967 //------------------------------inline_arraycopy-----------------------
4968 // public static native void java.lang.System.arraycopy(Object src,  int  srcPos,
4969 //                                                      Object dest, int destPos,
4970 //                                                      int length);
4971 bool LibraryCallKit::inline_arraycopy() {
4972   // Get the arguments.
4973   Node* src         = argument(0);  // type: oop
4974   Node* src_offset  = argument(1);  // type: int
4975   Node* dest        = argument(2);  // type: oop
4976   Node* dest_offset = argument(3);  // type: int
4977   Node* length      = argument(4);  // type: int
4978 
4979   uint new_idx = C->unique();
4980 
4981   // Check for allocation before we add nodes that would confuse
4982   // tightly_coupled_allocation()
4983   AllocateArrayNode* alloc = tightly_coupled_allocation(dest, NULL);
4984 
4985   int saved_reexecute_sp = -1;
4986   JVMState* saved_jvms = arraycopy_restore_alloc_state(alloc, saved_reexecute_sp);
4987   // See arraycopy_restore_alloc_state() comment
4988   // if alloc == NULL we don't have to worry about a tightly coupled allocation so we can emit all needed guards
4989   // if saved_jvms != NULL (then alloc != NULL) then we can handle guards and a tightly coupled allocation
4990   // if saved_jvms == NULL and alloc != NULL, we can’t emit any guards
4991   bool can_emit_guards = (alloc == NULL || saved_jvms != NULL);
4992 
4993   // The following tests must be performed
4994   // (1) src and dest are arrays.
4995   // (2) src and dest arrays must have elements of the same BasicType
4996   // (3) src and dest must not be null.
4997   // (4) src_offset must not be negative.
4998   // (5) dest_offset must not be negative.
4999   // (6) length must not be negative.
5000   // (7) src_offset + length must not exceed length of src.
5001   // (8) dest_offset + length must not exceed length of dest.
5002   // (9) each element of an oop array must be assignable
5003 
5004   // (3) src and dest must not be null.
5005   // always do this here because we need the JVM state for uncommon traps
5006   Node* null_ctl = top();
5007   src  = saved_jvms != NULL ? null_check_oop(src, &null_ctl, true, true) : null_check(src,  T_ARRAY);
5008   assert(null_ctl->is_top(), "no null control here");
5009   dest = null_check(dest, T_ARRAY);
5010 
5011   if (!can_emit_guards) {
5012     // if saved_jvms == NULL and alloc != NULL, we don't emit any
5013     // guards but the arraycopy node could still take advantage of a
5014     // tightly allocated allocation. tightly_coupled_allocation() is
5015     // called again to make sure it takes the null check above into
5016     // account: the null check is mandatory and if it caused an
5017     // uncommon trap to be emitted then the allocation can't be
5018     // considered tightly coupled in this context.
5019     alloc = tightly_coupled_allocation(dest, NULL);
5020   }
5021 
5022   bool validated = false;
5023 
5024   const Type* src_type  = _gvn.type(src);
5025   const Type* dest_type = _gvn.type(dest);
5026   const TypeAryPtr* top_src  = src_type->isa_aryptr();
5027   const TypeAryPtr* top_dest = dest_type->isa_aryptr();
5028 
5029   // Do we have the type of src?
5030   bool has_src = (top_src != NULL && top_src->klass() != NULL);
5031   // Do we have the type of dest?
5032   bool has_dest = (top_dest != NULL && top_dest->klass() != NULL);
5033   // Is the type for src from speculation?
5034   bool src_spec = false;
5035   // Is the type for dest from speculation?
5036   bool dest_spec = false;
5037 
5038   if ((!has_src || !has_dest) && can_emit_guards) {
5039     // We don't have sufficient type information, let's see if
5040     // speculative types can help. We need to have types for both src
5041     // and dest so that it pays off.
5042 
5043     // Do we already have or could we have type information for src
5044     bool could_have_src = has_src;
5045     // Do we already have or could we have type information for dest
5046     bool could_have_dest = has_dest;
5047 
5048     ciKlass* src_k = NULL;
5049     if (!has_src) {
5050       src_k = src_type->speculative_type_not_null();
5051       if (src_k != NULL && src_k->is_array_klass()) {
5052         could_have_src = true;
5053       }
5054     }
5055 
5056     ciKlass* dest_k = NULL;
5057     if (!has_dest) {
5058       dest_k = dest_type->speculative_type_not_null();
5059       if (dest_k != NULL && dest_k->is_array_klass()) {
5060         could_have_dest = true;
5061       }
5062     }
5063 
5064     if (could_have_src && could_have_dest) {
5065       // This is going to pay off so emit the required guards
5066       if (!has_src) {
5067         src = maybe_cast_profiled_obj(src, src_k, true);
5068         src_type  = _gvn.type(src);
5069         top_src  = src_type->isa_aryptr();
5070         has_src = (top_src != NULL && top_src->klass() != NULL);
5071         src_spec = true;
5072       }
5073       if (!has_dest) {
5074         dest = maybe_cast_profiled_obj(dest, dest_k, true);
5075         dest_type  = _gvn.type(dest);
5076         top_dest  = dest_type->isa_aryptr();
5077         has_dest = (top_dest != NULL && top_dest->klass() != NULL);
5078         dest_spec = true;
5079       }
5080     }
5081   }
5082 
5083   if (has_src && has_dest && can_emit_guards) {
5084     BasicType src_elem  = top_src->klass()->as_array_klass()->element_type()->basic_type();
5085     BasicType dest_elem = top_dest->klass()->as_array_klass()->element_type()->basic_type();
5086     if (src_elem  == T_ARRAY)  src_elem  = T_OBJECT;
5087     if (dest_elem == T_ARRAY)  dest_elem = T_OBJECT;
5088 
5089     if (src_elem == dest_elem && src_elem == T_OBJECT) {
5090       // If both arrays are object arrays then having the exact types
5091       // for both will remove the need for a subtype check at runtime
5092       // before the call and may make it possible to pick a faster copy
5093       // routine (without a subtype check on every element)
5094       // Do we have the exact type of src?
5095       bool could_have_src = src_spec;
5096       // Do we have the exact type of dest?
5097       bool could_have_dest = dest_spec;
5098       ciKlass* src_k = top_src->klass();
5099       ciKlass* dest_k = top_dest->klass();
5100       if (!src_spec) {
5101         src_k = src_type->speculative_type_not_null();
5102         if (src_k != NULL && src_k->is_array_klass()) {
5103           could_have_src = true;
5104         }
5105       }
5106       if (!dest_spec) {
5107         dest_k = dest_type->speculative_type_not_null();
5108         if (dest_k != NULL && dest_k->is_array_klass()) {
5109           could_have_dest = true;
5110         }
5111       }
5112       if (could_have_src && could_have_dest) {
5113         // If we can have both exact types, emit the missing guards
5114         if (could_have_src && !src_spec) {
5115           src = maybe_cast_profiled_obj(src, src_k, true);
5116         }
5117         if (could_have_dest && !dest_spec) {
5118           dest = maybe_cast_profiled_obj(dest, dest_k, true);
5119         }
5120       }
5121     }
5122   }
5123 
5124   ciMethod* trap_method = method();
5125   int trap_bci = bci();
5126   if (saved_jvms != NULL) {
5127     trap_method = alloc->jvms()->method();
5128     trap_bci = alloc->jvms()->bci();
5129   }
5130 
5131   bool negative_length_guard_generated = false;
5132 
5133   if (!C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_intrinsic) &&
5134       can_emit_guards &&
5135       !src->is_top() && !dest->is_top()) {
5136     // validate arguments: enables transformation the ArrayCopyNode
5137     validated = true;
5138 
5139     RegionNode* slow_region = new RegionNode(1);
5140     record_for_igvn(slow_region);
5141 
5142     // (1) src and dest are arrays.
5143     generate_non_array_guard(load_object_klass(src), slow_region);
5144     generate_non_array_guard(load_object_klass(dest), slow_region);
5145 
5146     // (2) src and dest arrays must have elements of the same BasicType
5147     // done at macro expansion or at Ideal transformation time
5148 
5149     // (4) src_offset must not be negative.
5150     generate_negative_guard(src_offset, slow_region);
5151 
5152     // (5) dest_offset must not be negative.
5153     generate_negative_guard(dest_offset, slow_region);
5154 
5155     // (7) src_offset + length must not exceed length of src.
5156     generate_limit_guard(src_offset, length,
5157                          load_array_length(src),
5158                          slow_region);
5159 
5160     // (8) dest_offset + length must not exceed length of dest.
5161     generate_limit_guard(dest_offset, length,
5162                          load_array_length(dest),
5163                          slow_region);
5164 
5165     // (6) length must not be negative.
5166     // This is also checked in generate_arraycopy() during macro expansion, but
5167     // we also have to check it here for the case where the ArrayCopyNode will
5168     // be eliminated by Escape Analysis.
5169     if (EliminateAllocations) {
5170       generate_negative_guard(length, slow_region);
5171       negative_length_guard_generated = true;
5172     }
5173 
5174     // (9) each element of an oop array must be assignable
5175     Node* src_klass  = load_object_klass(src);
5176     Node* dest_klass = load_object_klass(dest);
5177     Node* not_subtype_ctrl = gen_subtype_check(src_klass, dest_klass);
5178 
5179     if (not_subtype_ctrl != top()) {
5180       PreserveJVMState pjvms(this);
5181       set_control(not_subtype_ctrl);
5182       uncommon_trap(Deoptimization::Reason_intrinsic,
5183                     Deoptimization::Action_make_not_entrant);
5184       assert(stopped(), "Should be stopped");
5185     }
5186     {
5187       PreserveJVMState pjvms(this);
5188       set_control(_gvn.transform(slow_region));
5189       uncommon_trap(Deoptimization::Reason_intrinsic,
5190                     Deoptimization::Action_make_not_entrant);
5191       assert(stopped(), "Should be stopped");
5192     }
5193   }
5194 
5195   arraycopy_move_allocation_here(alloc, dest, saved_jvms, saved_reexecute_sp, new_idx);
5196 
5197   if (stopped()) {
5198     return true;
5199   }
5200 
5201   ArrayCopyNode* ac = ArrayCopyNode::make(this, true, src, src_offset, dest, dest_offset, length, alloc != NULL, negative_length_guard_generated,
5202                                           // Create LoadRange and LoadKlass nodes for use during macro expansion here
5203                                           // so the compiler has a chance to eliminate them: during macro expansion,
5204                                           // we have to set their control (CastPP nodes are eliminated).
5205                                           load_object_klass(src), load_object_klass(dest),
5206                                           load_array_length(src), load_array_length(dest));
5207 
5208   ac->set_arraycopy(validated);
5209 
5210   Node* n = _gvn.transform(ac);
5211   if (n == ac) {
5212     ac->connect_outputs(this);
5213   } else {
5214     assert(validated, "shouldn't transform if all arguments not validated");
5215     set_all_memory(n);
5216   }
5217 
5218   return true;
5219 }
5220 
5221 
5222 // Helper function which determines if an arraycopy immediately follows
5223 // an allocation, with no intervening tests or other escapes for the object.
5224 AllocateArrayNode*
5225 LibraryCallKit::tightly_coupled_allocation(Node* ptr,
5226                                            RegionNode* slow_region) {
5227   if (stopped())             return NULL;  // no fast path
5228   if (C->AliasLevel() == 0)  return NULL;  // no MergeMems around
5229 
5230   AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(ptr, &_gvn);
5231   if (alloc == NULL)  return NULL;
5232 
5233   Node* rawmem = memory(Compile::AliasIdxRaw);
5234   // Is the allocation's memory state untouched?
5235   if (!(rawmem->is_Proj() && rawmem->in(0)->is_Initialize())) {
5236     // Bail out if there have been raw-memory effects since the allocation.
5237     // (Example:  There might have been a call or safepoint.)
5238     return NULL;
5239   }
5240   rawmem = rawmem->in(0)->as_Initialize()->memory(Compile::AliasIdxRaw);
5241   if (!(rawmem->is_Proj() && rawmem->in(0) == alloc)) {
5242     return NULL;
5243   }
5244 
5245   // There must be no unexpected observers of this allocation.
5246   for (DUIterator_Fast imax, i = ptr->fast_outs(imax); i < imax; i++) {
5247     Node* obs = ptr->fast_out(i);
5248     if (obs != this->map()) {
5249       return NULL;
5250     }
5251   }
5252 
5253   // This arraycopy must unconditionally follow the allocation of the ptr.
5254   Node* alloc_ctl = ptr->in(0);
5255   assert(just_allocated_object(alloc_ctl) == ptr, "most recent allo");
5256 
5257   Node* ctl = control();
5258   while (ctl != alloc_ctl) {
5259     // There may be guards which feed into the slow_region.
5260     // Any other control flow means that we might not get a chance
5261     // to finish initializing the allocated object.
5262     if ((ctl->is_IfFalse() || ctl->is_IfTrue()) && ctl->in(0)->is_If()) {
5263       IfNode* iff = ctl->in(0)->as_If();
5264       Node* not_ctl = iff->proj_out(1 - ctl->as_Proj()->_con);
5265       assert(not_ctl != NULL && not_ctl != ctl, "found alternate");
5266       if (slow_region != NULL && slow_region->find_edge(not_ctl) >= 1) {
5267         ctl = iff->in(0);       // This test feeds the known slow_region.
5268         continue;
5269       }
5270       // One more try:  Various low-level checks bottom out in
5271       // uncommon traps.  If the debug-info of the trap omits
5272       // any reference to the allocation, as we've already
5273       // observed, then there can be no objection to the trap.
5274       bool found_trap = false;
5275       for (DUIterator_Fast jmax, j = not_ctl->fast_outs(jmax); j < jmax; j++) {
5276         Node* obs = not_ctl->fast_out(j);
5277         if (obs->in(0) == not_ctl && obs->is_Call() &&
5278             (obs->as_Call()->entry_point() == SharedRuntime::uncommon_trap_blob()->entry_point())) {
5279           found_trap = true; break;
5280         }
5281       }
5282       if (found_trap) {
5283         ctl = iff->in(0);       // This test feeds a harmless uncommon trap.
5284         continue;
5285       }
5286     }
5287     return NULL;
5288   }
5289 
5290   // If we get this far, we have an allocation which immediately
5291   // precedes the arraycopy, and we can take over zeroing the new object.
5292   // The arraycopy will finish the initialization, and provide
5293   // a new control state to which we will anchor the destination pointer.
5294 
5295   return alloc;
5296 }
5297 
5298 //-------------inline_encodeISOArray-----------------------------------
5299 // encode char[] to byte[] in ISO_8859_1
5300 bool LibraryCallKit::inline_encodeISOArray() {
5301   assert(callee()->signature()->size() == 5, "encodeISOArray has 5 parameters");
5302   // no receiver since it is static method
5303   Node *src         = argument(0);
5304   Node *src_offset  = argument(1);
5305   Node *dst         = argument(2);
5306   Node *dst_offset  = argument(3);
5307   Node *length      = argument(4);
5308 
5309   const Type* src_type = src->Value(&_gvn);
5310   const Type* dst_type = dst->Value(&_gvn);
5311   const TypeAryPtr* top_src = src_type->isa_aryptr();
5312   const TypeAryPtr* top_dest = dst_type->isa_aryptr();
5313   if (top_src  == NULL || top_src->klass()  == NULL ||
5314       top_dest == NULL || top_dest->klass() == NULL) {
5315     // failed array check
5316     return false;
5317   }
5318 
5319   // Figure out the size and type of the elements we will be copying.
5320   BasicType src_elem = src_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5321   BasicType dst_elem = dst_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5322   if (!((src_elem == T_CHAR) || (src_elem== T_BYTE)) || dst_elem != T_BYTE) {
5323     return false;
5324   }
5325 
5326   Node* src_start = array_element_address(src, src_offset, T_CHAR);
5327   Node* dst_start = array_element_address(dst, dst_offset, dst_elem);
5328   // 'src_start' points to src array + scaled offset
5329   // 'dst_start' points to dst array + scaled offset
5330 
5331   const TypeAryPtr* mtype = TypeAryPtr::BYTES;
5332   Node* enc = new EncodeISOArrayNode(control(), memory(mtype), src_start, dst_start, length);
5333   enc = _gvn.transform(enc);
5334   Node* res_mem = _gvn.transform(new SCMemProjNode(enc));
5335   set_memory(res_mem, mtype);
5336   set_result(enc);
5337   return true;
5338 }
5339 
5340 //-------------inline_multiplyToLen-----------------------------------
5341 bool LibraryCallKit::inline_multiplyToLen() {
5342   assert(UseMultiplyToLenIntrinsic, "not implemented on this platform");
5343 
5344   address stubAddr = StubRoutines::multiplyToLen();
5345   if (stubAddr == NULL) {
5346     return false; // Intrinsic's stub is not implemented on this platform
5347   }
5348   const char* stubName = "multiplyToLen";
5349 
5350   assert(callee()->signature()->size() == 5, "multiplyToLen has 5 parameters");
5351 
5352   // no receiver because it is a static method
5353   Node* x    = argument(0);
5354   Node* xlen = argument(1);
5355   Node* y    = argument(2);
5356   Node* ylen = argument(3);
5357   Node* z    = argument(4);
5358 
5359   const Type* x_type = x->Value(&_gvn);
5360   const Type* y_type = y->Value(&_gvn);
5361   const TypeAryPtr* top_x = x_type->isa_aryptr();
5362   const TypeAryPtr* top_y = y_type->isa_aryptr();
5363   if (top_x  == NULL || top_x->klass()  == NULL ||
5364       top_y == NULL || top_y->klass() == NULL) {
5365     // failed array check
5366     return false;
5367   }
5368 
5369   BasicType x_elem = x_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5370   BasicType y_elem = y_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5371   if (x_elem != T_INT || y_elem != T_INT) {
5372     return false;
5373   }
5374 
5375   // Set the original stack and the reexecute bit for the interpreter to reexecute
5376   // the bytecode that invokes BigInteger.multiplyToLen() if deoptimization happens
5377   // on the return from z array allocation in runtime.
5378   { PreserveReexecuteState preexecs(this);
5379     jvms()->set_should_reexecute(true);
5380 
5381     Node* x_start = array_element_address(x, intcon(0), x_elem);
5382     Node* y_start = array_element_address(y, intcon(0), y_elem);
5383     // 'x_start' points to x array + scaled xlen
5384     // 'y_start' points to y array + scaled ylen
5385 
5386     // Allocate the result array
5387     Node* zlen = _gvn.transform(new AddINode(xlen, ylen));
5388     ciKlass* klass = ciTypeArrayKlass::make(T_INT);
5389     Node* klass_node = makecon(TypeKlassPtr::make(klass));
5390 
5391     IdealKit ideal(this);
5392 
5393 #define __ ideal.
5394      Node* one = __ ConI(1);
5395      Node* zero = __ ConI(0);
5396      IdealVariable need_alloc(ideal), z_alloc(ideal);  __ declarations_done();
5397      __ set(need_alloc, zero);
5398      __ set(z_alloc, z);
5399      __ if_then(z, BoolTest::eq, null()); {
5400        __ increment (need_alloc, one);
5401      } __ else_(); {
5402        // Update graphKit memory and control from IdealKit.
5403        sync_kit(ideal);
5404        Node* zlen_arg = load_array_length(z);
5405        // Update IdealKit memory and control from graphKit.
5406        __ sync_kit(this);
5407        __ if_then(zlen_arg, BoolTest::lt, zlen); {
5408          __ increment (need_alloc, one);
5409        } __ end_if();
5410      } __ end_if();
5411 
5412      __ if_then(__ value(need_alloc), BoolTest::ne, zero); {
5413        // Update graphKit memory and control from IdealKit.
5414        sync_kit(ideal);
5415        Node * narr = new_array(klass_node, zlen, 1);
5416        // Update IdealKit memory and control from graphKit.
5417        __ sync_kit(this);
5418        __ set(z_alloc, narr);
5419      } __ end_if();
5420 
5421      sync_kit(ideal);
5422      z = __ value(z_alloc);
5423      // Can't use TypeAryPtr::INTS which uses Bottom offset.
5424      _gvn.set_type(z, TypeOopPtr::make_from_klass(klass));
5425      // Final sync IdealKit and GraphKit.
5426      final_sync(ideal);
5427 #undef __
5428 
5429     Node* z_start = array_element_address(z, intcon(0), T_INT);
5430 
5431     Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
5432                                    OptoRuntime::multiplyToLen_Type(),
5433                                    stubAddr, stubName, TypePtr::BOTTOM,
5434                                    x_start, xlen, y_start, ylen, z_start, zlen);
5435   } // original reexecute is set back here
5436 
5437   C->set_has_split_ifs(true); // Has chance for split-if optimization
5438   set_result(z);
5439   return true;
5440 }
5441 
5442 //-------------inline_squareToLen------------------------------------
5443 bool LibraryCallKit::inline_squareToLen() {
5444   assert(UseSquareToLenIntrinsic, "not implemented on this platform");
5445 
5446   address stubAddr = StubRoutines::squareToLen();
5447   if (stubAddr == NULL) {
5448     return false; // Intrinsic's stub is not implemented on this platform
5449   }
5450   const char* stubName = "squareToLen";
5451 
5452   assert(callee()->signature()->size() == 4, "implSquareToLen has 4 parameters");
5453 
5454   Node* x    = argument(0);
5455   Node* len  = argument(1);
5456   Node* z    = argument(2);
5457   Node* zlen = argument(3);
5458 
5459   const Type* x_type = x->Value(&_gvn);
5460   const Type* z_type = z->Value(&_gvn);
5461   const TypeAryPtr* top_x = x_type->isa_aryptr();
5462   const TypeAryPtr* top_z = z_type->isa_aryptr();
5463   if (top_x  == NULL || top_x->klass()  == NULL ||
5464       top_z  == NULL || top_z->klass()  == NULL) {
5465     // failed array check
5466     return false;
5467   }
5468 
5469   BasicType x_elem = x_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5470   BasicType z_elem = z_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5471   if (x_elem != T_INT || z_elem != T_INT) {
5472     return false;
5473   }
5474 
5475 
5476   Node* x_start = array_element_address(x, intcon(0), x_elem);
5477   Node* z_start = array_element_address(z, intcon(0), z_elem);
5478 
5479   Node*  call = make_runtime_call(RC_LEAF|RC_NO_FP,
5480                                   OptoRuntime::squareToLen_Type(),
5481                                   stubAddr, stubName, TypePtr::BOTTOM,
5482                                   x_start, len, z_start, zlen);
5483 
5484   set_result(z);
5485   return true;
5486 }
5487 
5488 //-------------inline_mulAdd------------------------------------------
5489 bool LibraryCallKit::inline_mulAdd() {
5490   assert(UseMulAddIntrinsic, "not implemented on this platform");
5491 
5492   address stubAddr = StubRoutines::mulAdd();
5493   if (stubAddr == NULL) {
5494     return false; // Intrinsic's stub is not implemented on this platform
5495   }
5496   const char* stubName = "mulAdd";
5497 
5498   assert(callee()->signature()->size() == 5, "mulAdd has 5 parameters");
5499 
5500   Node* out      = argument(0);
5501   Node* in       = argument(1);
5502   Node* offset   = argument(2);
5503   Node* len      = argument(3);
5504   Node* k        = argument(4);
5505 
5506   const Type* out_type = out->Value(&_gvn);
5507   const Type* in_type = in->Value(&_gvn);
5508   const TypeAryPtr* top_out = out_type->isa_aryptr();
5509   const TypeAryPtr* top_in = in_type->isa_aryptr();
5510   if (top_out  == NULL || top_out->klass()  == NULL ||
5511       top_in == NULL || top_in->klass() == NULL) {
5512     // failed array check
5513     return false;
5514   }
5515 
5516   BasicType out_elem = out_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5517   BasicType in_elem = in_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5518   if (out_elem != T_INT || in_elem != T_INT) {
5519     return false;
5520   }
5521 
5522   Node* outlen = load_array_length(out);
5523   Node* new_offset = _gvn.transform(new SubINode(outlen, offset));
5524   Node* out_start = array_element_address(out, intcon(0), out_elem);
5525   Node* in_start = array_element_address(in, intcon(0), in_elem);
5526 
5527   Node*  call = make_runtime_call(RC_LEAF|RC_NO_FP,
5528                                   OptoRuntime::mulAdd_Type(),
5529                                   stubAddr, stubName, TypePtr::BOTTOM,
5530                                   out_start,in_start, new_offset, len, k);
5531   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
5532   set_result(result);
5533   return true;
5534 }
5535 
5536 //-------------inline_montgomeryMultiply-----------------------------------
5537 bool LibraryCallKit::inline_montgomeryMultiply() {
5538   address stubAddr = StubRoutines::montgomeryMultiply();
5539   if (stubAddr == NULL) {
5540     return false; // Intrinsic's stub is not implemented on this platform
5541   }
5542 
5543   assert(UseMontgomeryMultiplyIntrinsic, "not implemented on this platform");
5544   const char* stubName = "montgomery_multiply";
5545 
5546   assert(callee()->signature()->size() == 7, "montgomeryMultiply has 7 parameters");
5547 
5548   Node* a    = argument(0);
5549   Node* b    = argument(1);
5550   Node* n    = argument(2);
5551   Node* len  = argument(3);
5552   Node* inv  = argument(4);
5553   Node* m    = argument(6);
5554 
5555   const Type* a_type = a->Value(&_gvn);
5556   const TypeAryPtr* top_a = a_type->isa_aryptr();
5557   const Type* b_type = b->Value(&_gvn);
5558   const TypeAryPtr* top_b = b_type->isa_aryptr();
5559   const Type* n_type = a->Value(&_gvn);
5560   const TypeAryPtr* top_n = n_type->isa_aryptr();
5561   const Type* m_type = a->Value(&_gvn);
5562   const TypeAryPtr* top_m = m_type->isa_aryptr();
5563   if (top_a  == NULL || top_a->klass()  == NULL ||
5564       top_b == NULL || top_b->klass()  == NULL ||
5565       top_n == NULL || top_n->klass()  == NULL ||
5566       top_m == NULL || top_m->klass()  == NULL) {
5567     // failed array check
5568     return false;
5569   }
5570 
5571   BasicType a_elem = a_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5572   BasicType b_elem = b_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5573   BasicType n_elem = n_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5574   BasicType m_elem = m_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5575   if (a_elem != T_INT || b_elem != T_INT || n_elem != T_INT || m_elem != T_INT) {
5576     return false;
5577   }
5578 
5579   // Make the call
5580   {
5581     Node* a_start = array_element_address(a, intcon(0), a_elem);
5582     Node* b_start = array_element_address(b, intcon(0), b_elem);
5583     Node* n_start = array_element_address(n, intcon(0), n_elem);
5584     Node* m_start = array_element_address(m, intcon(0), m_elem);
5585 
5586     Node* call = make_runtime_call(RC_LEAF,
5587                                    OptoRuntime::montgomeryMultiply_Type(),
5588                                    stubAddr, stubName, TypePtr::BOTTOM,
5589                                    a_start, b_start, n_start, len, inv, top(),
5590                                    m_start);
5591     set_result(m);
5592   }
5593 
5594   return true;
5595 }
5596 
5597 bool LibraryCallKit::inline_montgomerySquare() {
5598   address stubAddr = StubRoutines::montgomerySquare();
5599   if (stubAddr == NULL) {
5600     return false; // Intrinsic's stub is not implemented on this platform
5601   }
5602 
5603   assert(UseMontgomerySquareIntrinsic, "not implemented on this platform");
5604   const char* stubName = "montgomery_square";
5605 
5606   assert(callee()->signature()->size() == 6, "montgomerySquare has 6 parameters");
5607 
5608   Node* a    = argument(0);
5609   Node* n    = argument(1);
5610   Node* len  = argument(2);
5611   Node* inv  = argument(3);
5612   Node* m    = argument(5);
5613 
5614   const Type* a_type = a->Value(&_gvn);
5615   const TypeAryPtr* top_a = a_type->isa_aryptr();
5616   const Type* n_type = a->Value(&_gvn);
5617   const TypeAryPtr* top_n = n_type->isa_aryptr();
5618   const Type* m_type = a->Value(&_gvn);
5619   const TypeAryPtr* top_m = m_type->isa_aryptr();
5620   if (top_a  == NULL || top_a->klass()  == NULL ||
5621       top_n == NULL || top_n->klass()  == NULL ||
5622       top_m == NULL || top_m->klass()  == NULL) {
5623     // failed array check
5624     return false;
5625   }
5626 
5627   BasicType a_elem = a_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5628   BasicType n_elem = n_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5629   BasicType m_elem = m_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5630   if (a_elem != T_INT || n_elem != T_INT || m_elem != T_INT) {
5631     return false;
5632   }
5633 
5634   // Make the call
5635   {
5636     Node* a_start = array_element_address(a, intcon(0), a_elem);
5637     Node* n_start = array_element_address(n, intcon(0), n_elem);
5638     Node* m_start = array_element_address(m, intcon(0), m_elem);
5639 
5640     Node* call = make_runtime_call(RC_LEAF,
5641                                    OptoRuntime::montgomerySquare_Type(),
5642                                    stubAddr, stubName, TypePtr::BOTTOM,
5643                                    a_start, n_start, len, inv, top(),
5644                                    m_start);
5645     set_result(m);
5646   }
5647 
5648   return true;
5649 }
5650 
5651 //-------------inline_vectorizedMismatch------------------------------
5652 bool LibraryCallKit::inline_vectorizedMismatch() {
5653   assert(UseVectorizedMismatchIntrinsic, "not implementated on this platform");
5654 
5655   address stubAddr = StubRoutines::vectorizedMismatch();
5656   if (stubAddr == NULL) {
5657     return false; // Intrinsic's stub is not implemented on this platform
5658   }
5659   const char* stubName = "vectorizedMismatch";
5660   int size_l = callee()->signature()->size();
5661   assert(callee()->signature()->size() == 8, "vectorizedMismatch has 6 parameters");
5662 
5663   Node* obja = argument(0);
5664   Node* aoffset = argument(1);
5665   Node* objb = argument(3);
5666   Node* boffset = argument(4);
5667   Node* length = argument(6);
5668   Node* scale = argument(7);
5669 
5670   const Type* a_type = obja->Value(&_gvn);
5671   const Type* b_type = objb->Value(&_gvn);
5672   const TypeAryPtr* top_a = a_type->isa_aryptr();
5673   const TypeAryPtr* top_b = b_type->isa_aryptr();
5674   if (top_a == NULL || top_a->klass() == NULL ||
5675     top_b == NULL || top_b->klass() == NULL) {
5676     // failed array check
5677     return false;
5678   }
5679 
5680   Node* call;
5681   jvms()->set_should_reexecute(true);
5682 
5683   Node* obja_adr = make_unsafe_address(obja, aoffset);
5684   Node* objb_adr = make_unsafe_address(objb, boffset);
5685 
5686   call = make_runtime_call(RC_LEAF,
5687     OptoRuntime::vectorizedMismatch_Type(),
5688     stubAddr, stubName, TypePtr::BOTTOM,
5689     obja_adr, objb_adr, length, scale);
5690 
5691   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
5692   set_result(result);
5693   return true;
5694 }
5695 
5696 /**
5697  * Calculate CRC32 for byte.
5698  * int java.util.zip.CRC32.update(int crc, int b)
5699  */
5700 bool LibraryCallKit::inline_updateCRC32() {
5701   assert(UseCRC32Intrinsics, "need AVX and LCMUL instructions support");
5702   assert(callee()->signature()->size() == 2, "update has 2 parameters");
5703   // no receiver since it is static method
5704   Node* crc  = argument(0); // type: int
5705   Node* b    = argument(1); // type: int
5706 
5707   /*
5708    *    int c = ~ crc;
5709    *    b = timesXtoThe32[(b ^ c) & 0xFF];
5710    *    b = b ^ (c >>> 8);
5711    *    crc = ~b;
5712    */
5713 
5714   Node* M1 = intcon(-1);
5715   crc = _gvn.transform(new XorINode(crc, M1));
5716   Node* result = _gvn.transform(new XorINode(crc, b));
5717   result = _gvn.transform(new AndINode(result, intcon(0xFF)));
5718 
5719   Node* base = makecon(TypeRawPtr::make(StubRoutines::crc_table_addr()));
5720   Node* offset = _gvn.transform(new LShiftINode(result, intcon(0x2)));
5721   Node* adr = basic_plus_adr(top(), base, ConvI2X(offset));
5722   result = make_load(control(), adr, TypeInt::INT, T_INT, MemNode::unordered);
5723 
5724   crc = _gvn.transform(new URShiftINode(crc, intcon(8)));
5725   result = _gvn.transform(new XorINode(crc, result));
5726   result = _gvn.transform(new XorINode(result, M1));
5727   set_result(result);
5728   return true;
5729 }
5730 
5731 /**
5732  * Calculate CRC32 for byte[] array.
5733  * int java.util.zip.CRC32.updateBytes(int crc, byte[] buf, int off, int len)
5734  */
5735 bool LibraryCallKit::inline_updateBytesCRC32() {
5736   assert(UseCRC32Intrinsics, "need AVX and LCMUL instructions support");
5737   assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
5738   // no receiver since it is static method
5739   Node* crc     = argument(0); // type: int
5740   Node* src     = argument(1); // type: oop
5741   Node* offset  = argument(2); // type: int
5742   Node* length  = argument(3); // type: int
5743 
5744   const Type* src_type = src->Value(&_gvn);
5745   const TypeAryPtr* top_src = src_type->isa_aryptr();
5746   if (top_src  == NULL || top_src->klass()  == NULL) {
5747     // failed array check
5748     return false;
5749   }
5750 
5751   // Figure out the size and type of the elements we will be copying.
5752   BasicType src_elem = src_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5753   if (src_elem != T_BYTE) {
5754     return false;
5755   }
5756 
5757   // 'src_start' points to src array + scaled offset
5758   Node* src_start = array_element_address(src, offset, src_elem);
5759 
5760   // We assume that range check is done by caller.
5761   // TODO: generate range check (offset+length < src.length) in debug VM.
5762 
5763   // Call the stub.
5764   address stubAddr = StubRoutines::updateBytesCRC32();
5765   const char *stubName = "updateBytesCRC32";
5766 
5767   Node* call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::updateBytesCRC32_Type(),
5768                                  stubAddr, stubName, TypePtr::BOTTOM,
5769                                  crc, src_start, length);
5770   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
5771   set_result(result);
5772   return true;
5773 }
5774 
5775 /**
5776  * Calculate CRC32 for ByteBuffer.
5777  * int java.util.zip.CRC32.updateByteBuffer(int crc, long buf, int off, int len)
5778  */
5779 bool LibraryCallKit::inline_updateByteBufferCRC32() {
5780   assert(UseCRC32Intrinsics, "need AVX and LCMUL instructions support");
5781   assert(callee()->signature()->size() == 5, "updateByteBuffer has 4 parameters and one is long");
5782   // no receiver since it is static method
5783   Node* crc     = argument(0); // type: int
5784   Node* src     = argument(1); // type: long
5785   Node* offset  = argument(3); // type: int
5786   Node* length  = argument(4); // type: int
5787 
5788   src = ConvL2X(src);  // adjust Java long to machine word
5789   Node* base = _gvn.transform(new CastX2PNode(src));
5790   offset = ConvI2X(offset);
5791 
5792   // 'src_start' points to src array + scaled offset
5793   Node* src_start = basic_plus_adr(top(), base, offset);
5794 
5795   // Call the stub.
5796   address stubAddr = StubRoutines::updateBytesCRC32();
5797   const char *stubName = "updateBytesCRC32";
5798 
5799   Node* call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::updateBytesCRC32_Type(),
5800                                  stubAddr, stubName, TypePtr::BOTTOM,
5801                                  crc, src_start, length);
5802   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
5803   set_result(result);
5804   return true;
5805 }
5806 
5807 //------------------------------get_table_from_crc32c_class-----------------------
5808 Node * LibraryCallKit::get_table_from_crc32c_class(ciInstanceKlass *crc32c_class) {
5809   Node* table = load_field_from_object(NULL, "byteTable", "[I", /*is_exact*/ false, /*is_static*/ true, crc32c_class);
5810   assert (table != NULL, "wrong version of java.util.zip.CRC32C");
5811 
5812   return table;
5813 }
5814 
5815 //------------------------------inline_updateBytesCRC32C-----------------------
5816 //
5817 // Calculate CRC32C for byte[] array.
5818 // int java.util.zip.CRC32C.updateBytes(int crc, byte[] buf, int off, int end)
5819 //
5820 bool LibraryCallKit::inline_updateBytesCRC32C() {
5821   assert(UseCRC32CIntrinsics, "need CRC32C instruction support");
5822   assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
5823   assert(callee()->holder()->is_loaded(), "CRC32C class must be loaded");
5824   // no receiver since it is a static method
5825   Node* crc     = argument(0); // type: int
5826   Node* src     = argument(1); // type: oop
5827   Node* offset  = argument(2); // type: int
5828   Node* end     = argument(3); // type: int
5829 
5830   Node* length = _gvn.transform(new SubINode(end, offset));
5831 
5832   const Type* src_type = src->Value(&_gvn);
5833   const TypeAryPtr* top_src = src_type->isa_aryptr();
5834   if (top_src  == NULL || top_src->klass()  == NULL) {
5835     // failed array check
5836     return false;
5837   }
5838 
5839   // Figure out the size and type of the elements we will be copying.
5840   BasicType src_elem = src_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5841   if (src_elem != T_BYTE) {
5842     return false;
5843   }
5844 
5845   // 'src_start' points to src array + scaled offset
5846   Node* src_start = array_element_address(src, offset, src_elem);
5847 
5848   // static final int[] byteTable in class CRC32C
5849   Node* table = get_table_from_crc32c_class(callee()->holder());
5850   Node* table_start = array_element_address(table, intcon(0), T_INT);
5851 
5852   // We assume that range check is done by caller.
5853   // TODO: generate range check (offset+length < src.length) in debug VM.
5854 
5855   // Call the stub.
5856   address stubAddr = StubRoutines::updateBytesCRC32C();
5857   const char *stubName = "updateBytesCRC32C";
5858 
5859   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesCRC32C_Type(),
5860                                  stubAddr, stubName, TypePtr::BOTTOM,
5861                                  crc, src_start, length, table_start);
5862   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
5863   set_result(result);
5864   return true;
5865 }
5866 
5867 //------------------------------inline_updateDirectByteBufferCRC32C-----------------------
5868 //
5869 // Calculate CRC32C for DirectByteBuffer.
5870 // int java.util.zip.CRC32C.updateDirectByteBuffer(int crc, long buf, int off, int end)
5871 //
5872 bool LibraryCallKit::inline_updateDirectByteBufferCRC32C() {
5873   assert(UseCRC32CIntrinsics, "need CRC32C instruction support");
5874   assert(callee()->signature()->size() == 5, "updateDirectByteBuffer has 4 parameters and one is long");
5875   assert(callee()->holder()->is_loaded(), "CRC32C class must be loaded");
5876   // no receiver since it is a static method
5877   Node* crc     = argument(0); // type: int
5878   Node* src     = argument(1); // type: long
5879   Node* offset  = argument(3); // type: int
5880   Node* end     = argument(4); // type: int
5881 
5882   Node* length = _gvn.transform(new SubINode(end, offset));
5883 
5884   src = ConvL2X(src);  // adjust Java long to machine word
5885   Node* base = _gvn.transform(new CastX2PNode(src));
5886   offset = ConvI2X(offset);
5887 
5888   // 'src_start' points to src array + scaled offset
5889   Node* src_start = basic_plus_adr(top(), base, offset);
5890 
5891   // static final int[] byteTable in class CRC32C
5892   Node* table = get_table_from_crc32c_class(callee()->holder());
5893   Node* table_start = array_element_address(table, intcon(0), T_INT);
5894 
5895   // Call the stub.
5896   address stubAddr = StubRoutines::updateBytesCRC32C();
5897   const char *stubName = "updateBytesCRC32C";
5898 
5899   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesCRC32C_Type(),
5900                                  stubAddr, stubName, TypePtr::BOTTOM,
5901                                  crc, src_start, length, table_start);
5902   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
5903   set_result(result);
5904   return true;
5905 }
5906 
5907 //------------------------------inline_updateBytesAdler32----------------------
5908 //
5909 // Calculate Adler32 checksum for byte[] array.
5910 // int java.util.zip.Adler32.updateBytes(int crc, byte[] buf, int off, int len)
5911 //
5912 bool LibraryCallKit::inline_updateBytesAdler32() {
5913   assert(UseAdler32Intrinsics, "Adler32 Instrinsic support need"); // check if we actually need to check this flag or check a different one
5914   assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
5915   assert(callee()->holder()->is_loaded(), "Adler32 class must be loaded");
5916   // no receiver since it is static method
5917   Node* crc     = argument(0); // type: int
5918   Node* src     = argument(1); // type: oop
5919   Node* offset  = argument(2); // type: int
5920   Node* length  = argument(3); // type: int
5921 
5922   const Type* src_type = src->Value(&_gvn);
5923   const TypeAryPtr* top_src = src_type->isa_aryptr();
5924   if (top_src  == NULL || top_src->klass()  == NULL) {
5925     // failed array check
5926     return false;
5927   }
5928 
5929   // Figure out the size and type of the elements we will be copying.
5930   BasicType src_elem = src_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5931   if (src_elem != T_BYTE) {
5932     return false;
5933   }
5934 
5935   // 'src_start' points to src array + scaled offset
5936   Node* src_start = array_element_address(src, offset, src_elem);
5937 
5938   // We assume that range check is done by caller.
5939   // TODO: generate range check (offset+length < src.length) in debug VM.
5940 
5941   // Call the stub.
5942   address stubAddr = StubRoutines::updateBytesAdler32();
5943   const char *stubName = "updateBytesAdler32";
5944 
5945   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesAdler32_Type(),
5946                                  stubAddr, stubName, TypePtr::BOTTOM,
5947                                  crc, src_start, length);
5948   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
5949   set_result(result);
5950   return true;
5951 }
5952 
5953 //------------------------------inline_updateByteBufferAdler32---------------
5954 //
5955 // Calculate Adler32 checksum for DirectByteBuffer.
5956 // int java.util.zip.Adler32.updateByteBuffer(int crc, long buf, int off, int len)
5957 //
5958 bool LibraryCallKit::inline_updateByteBufferAdler32() {
5959   assert(UseAdler32Intrinsics, "Adler32 Instrinsic support need"); // check if we actually need to check this flag or check a different one
5960   assert(callee()->signature()->size() == 5, "updateByteBuffer has 4 parameters and one is long");
5961   assert(callee()->holder()->is_loaded(), "Adler32 class must be loaded");
5962   // no receiver since it is static method
5963   Node* crc     = argument(0); // type: int
5964   Node* src     = argument(1); // type: long
5965   Node* offset  = argument(3); // type: int
5966   Node* length  = argument(4); // type: int
5967 
5968   src = ConvL2X(src);  // adjust Java long to machine word
5969   Node* base = _gvn.transform(new CastX2PNode(src));
5970   offset = ConvI2X(offset);
5971 
5972   // 'src_start' points to src array + scaled offset
5973   Node* src_start = basic_plus_adr(top(), base, offset);
5974 
5975   // Call the stub.
5976   address stubAddr = StubRoutines::updateBytesAdler32();
5977   const char *stubName = "updateBytesAdler32";
5978 
5979   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesAdler32_Type(),
5980                                  stubAddr, stubName, TypePtr::BOTTOM,
5981                                  crc, src_start, length);
5982 
5983   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
5984   set_result(result);
5985   return true;
5986 }
5987 
5988 //----------------------------inline_reference_get----------------------------
5989 // public T java.lang.ref.Reference.get();
5990 bool LibraryCallKit::inline_reference_get() {
5991   const int referent_offset = java_lang_ref_Reference::referent_offset;
5992   guarantee(referent_offset > 0, "should have already been set");
5993 
5994   // Get the argument:
5995   Node* reference_obj = null_check_receiver();
5996   if (stopped()) return true;
5997 
5998   Node* adr = basic_plus_adr(reference_obj, reference_obj, referent_offset);
5999 
6000   ciInstanceKlass* klass = env()->Object_klass();
6001   const TypeOopPtr* object_type = TypeOopPtr::make_from_klass(klass);
6002 
6003   Node* no_ctrl = NULL;
6004   Node* result = make_load(no_ctrl, adr, object_type, T_OBJECT, MemNode::unordered);
6005 
6006   // Use the pre-barrier to record the value in the referent field
6007   pre_barrier(false /* do_load */,
6008               control(),
6009               NULL /* obj */, NULL /* adr */, max_juint /* alias_idx */, NULL /* val */, NULL /* val_type */,
6010               result /* pre_val */,
6011               T_OBJECT);
6012 
6013   // Add memory barrier to prevent commoning reads from this field
6014   // across safepoint since GC can change its value.
6015   insert_mem_bar(Op_MemBarCPUOrder);
6016 
6017   set_result(result);
6018   return true;
6019 }
6020 
6021 
6022 Node * LibraryCallKit::load_field_from_object(Node * fromObj, const char * fieldName, const char * fieldTypeString,
6023                                               bool is_exact=true, bool is_static=false,
6024                                               ciInstanceKlass * fromKls=NULL) {
6025   if (fromKls == NULL) {
6026     const TypeInstPtr* tinst = _gvn.type(fromObj)->isa_instptr();
6027     assert(tinst != NULL, "obj is null");
6028     assert(tinst->klass()->is_loaded(), "obj is not loaded");
6029     assert(!is_exact || tinst->klass_is_exact(), "klass not exact");
6030     fromKls = tinst->klass()->as_instance_klass();
6031   } else {
6032     assert(is_static, "only for static field access");
6033   }
6034   ciField* field = fromKls->get_field_by_name(ciSymbol::make(fieldName),
6035                                               ciSymbol::make(fieldTypeString),
6036                                               is_static);
6037 
6038   assert (field != NULL, "undefined field");
6039   if (field == NULL) return (Node *) NULL;
6040 
6041   if (is_static) {
6042     const TypeInstPtr* tip = TypeInstPtr::make(fromKls->java_mirror());
6043     fromObj = makecon(tip);
6044   }
6045 
6046   // Next code  copied from Parse::do_get_xxx():
6047 
6048   // Compute address and memory type.
6049   int offset  = field->offset_in_bytes();
6050   bool is_vol = field->is_volatile();
6051   ciType* field_klass = field->type();
6052   assert(field_klass->is_loaded(), "should be loaded");
6053   const TypePtr* adr_type = C->alias_type(field)->adr_type();
6054   Node *adr = basic_plus_adr(fromObj, fromObj, offset);
6055   BasicType bt = field->layout_type();
6056 
6057   // Build the resultant type of the load
6058   const Type *type;
6059   if (bt == T_OBJECT) {
6060     type = TypeOopPtr::make_from_klass(field_klass->as_klass());
6061   } else {
6062     type = Type::get_const_basic_type(bt);
6063   }
6064 
6065   if (support_IRIW_for_not_multiple_copy_atomic_cpu && is_vol) {
6066     insert_mem_bar(Op_MemBarVolatile);   // StoreLoad barrier
6067   }
6068   // Build the load.
6069   MemNode::MemOrd mo = is_vol ? MemNode::acquire : MemNode::unordered;
6070   Node* loadedField = make_load(NULL, adr, type, bt, adr_type, mo, LoadNode::DependsOnlyOnTest, is_vol);
6071   // If reference is volatile, prevent following memory ops from
6072   // floating up past the volatile read.  Also prevents commoning
6073   // another volatile read.
6074   if (is_vol) {
6075     // Memory barrier includes bogus read of value to force load BEFORE membar
6076     insert_mem_bar(Op_MemBarAcquire, loadedField);
6077   }
6078   return loadedField;
6079 }
6080 
6081 Node * LibraryCallKit::field_address_from_object(Node * fromObj, const char * fieldName, const char * fieldTypeString,
6082                                                  bool is_exact = true, bool is_static = false,
6083                                                  ciInstanceKlass * fromKls = NULL) {
6084   if (fromKls == NULL) {
6085     const TypeInstPtr* tinst = _gvn.type(fromObj)->isa_instptr();
6086     assert(tinst != NULL, "obj is null");
6087     assert(tinst->klass()->is_loaded(), "obj is not loaded");
6088     assert(!is_exact || tinst->klass_is_exact(), "klass not exact");
6089     fromKls = tinst->klass()->as_instance_klass();
6090   }
6091   else {
6092     assert(is_static, "only for static field access");
6093   }
6094   ciField* field = fromKls->get_field_by_name(ciSymbol::make(fieldName),
6095     ciSymbol::make(fieldTypeString),
6096     is_static);
6097 
6098   assert(field != NULL, "undefined field");
6099   assert(!field->is_volatile(), "not defined for volatile fields");
6100 
6101   if (is_static) {
6102     const TypeInstPtr* tip = TypeInstPtr::make(fromKls->java_mirror());
6103     fromObj = makecon(tip);
6104   }
6105 
6106   // Next code  copied from Parse::do_get_xxx():
6107 
6108   // Compute address and memory type.
6109   int offset = field->offset_in_bytes();
6110   Node *adr = basic_plus_adr(fromObj, fromObj, offset);
6111 
6112   return adr;
6113 }
6114 
6115 //------------------------------inline_aescrypt_Block-----------------------
6116 bool LibraryCallKit::inline_aescrypt_Block(vmIntrinsics::ID id) {
6117   address stubAddr = NULL;
6118   const char *stubName;
6119   assert(UseAES, "need AES instruction support");
6120 
6121   switch(id) {
6122   case vmIntrinsics::_aescrypt_encryptBlock:
6123     stubAddr = StubRoutines::aescrypt_encryptBlock();
6124     stubName = "aescrypt_encryptBlock";
6125     break;
6126   case vmIntrinsics::_aescrypt_decryptBlock:
6127     stubAddr = StubRoutines::aescrypt_decryptBlock();
6128     stubName = "aescrypt_decryptBlock";
6129     break;
6130   }
6131   if (stubAddr == NULL) return false;
6132 
6133   Node* aescrypt_object = argument(0);
6134   Node* src             = argument(1);
6135   Node* src_offset      = argument(2);
6136   Node* dest            = argument(3);
6137   Node* dest_offset     = argument(4);
6138 
6139   // (1) src and dest are arrays.
6140   const Type* src_type = src->Value(&_gvn);
6141   const Type* dest_type = dest->Value(&_gvn);
6142   const TypeAryPtr* top_src = src_type->isa_aryptr();
6143   const TypeAryPtr* top_dest = dest_type->isa_aryptr();
6144   assert (top_src  != NULL && top_src->klass()  != NULL &&  top_dest != NULL && top_dest->klass() != NULL, "args are strange");
6145 
6146   // for the quick and dirty code we will skip all the checks.
6147   // we are just trying to get the call to be generated.
6148   Node* src_start  = src;
6149   Node* dest_start = dest;
6150   if (src_offset != NULL || dest_offset != NULL) {
6151     assert(src_offset != NULL && dest_offset != NULL, "");
6152     src_start  = array_element_address(src,  src_offset,  T_BYTE);
6153     dest_start = array_element_address(dest, dest_offset, T_BYTE);
6154   }
6155 
6156   // now need to get the start of its expanded key array
6157   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
6158   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object);
6159   if (k_start == NULL) return false;
6160 
6161   if (Matcher::pass_original_key_for_aes()) {
6162     // on SPARC we need to pass the original key since key expansion needs to happen in intrinsics due to
6163     // compatibility issues between Java key expansion and SPARC crypto instructions
6164     Node* original_k_start = get_original_key_start_from_aescrypt_object(aescrypt_object);
6165     if (original_k_start == NULL) return false;
6166 
6167     // Call the stub.
6168     make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::aescrypt_block_Type(),
6169                       stubAddr, stubName, TypePtr::BOTTOM,
6170                       src_start, dest_start, k_start, original_k_start);
6171   } else {
6172     // Call the stub.
6173     make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::aescrypt_block_Type(),
6174                       stubAddr, stubName, TypePtr::BOTTOM,
6175                       src_start, dest_start, k_start);
6176   }
6177 
6178   return true;
6179 }
6180 
6181 //------------------------------inline_cipherBlockChaining_AESCrypt-----------------------
6182 bool LibraryCallKit::inline_cipherBlockChaining_AESCrypt(vmIntrinsics::ID id) {
6183   address stubAddr = NULL;
6184   const char *stubName = NULL;
6185 
6186   assert(UseAES, "need AES instruction support");
6187 
6188   switch(id) {
6189   case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
6190     stubAddr = StubRoutines::cipherBlockChaining_encryptAESCrypt();
6191     stubName = "cipherBlockChaining_encryptAESCrypt";
6192     break;
6193   case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
6194     stubAddr = StubRoutines::cipherBlockChaining_decryptAESCrypt();
6195     stubName = "cipherBlockChaining_decryptAESCrypt";
6196     break;
6197   }
6198   if (stubAddr == NULL) return false;
6199 
6200   Node* cipherBlockChaining_object = argument(0);
6201   Node* src                        = argument(1);
6202   Node* src_offset                 = argument(2);
6203   Node* len                        = argument(3);
6204   Node* dest                       = argument(4);
6205   Node* dest_offset                = argument(5);
6206 
6207   // (1) src and dest are arrays.
6208   const Type* src_type = src->Value(&_gvn);
6209   const Type* dest_type = dest->Value(&_gvn);
6210   const TypeAryPtr* top_src = src_type->isa_aryptr();
6211   const TypeAryPtr* top_dest = dest_type->isa_aryptr();
6212   assert (top_src  != NULL && top_src->klass()  != NULL
6213           &&  top_dest != NULL && top_dest->klass() != NULL, "args are strange");
6214 
6215   // checks are the responsibility of the caller
6216   Node* src_start  = src;
6217   Node* dest_start = dest;
6218   if (src_offset != NULL || dest_offset != NULL) {
6219     assert(src_offset != NULL && dest_offset != NULL, "");
6220     src_start  = array_element_address(src,  src_offset,  T_BYTE);
6221     dest_start = array_element_address(dest, dest_offset, T_BYTE);
6222   }
6223 
6224   // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
6225   // (because of the predicated logic executed earlier).
6226   // so we cast it here safely.
6227   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
6228 
6229   Node* embeddedCipherObj = load_field_from_object(cipherBlockChaining_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;", /*is_exact*/ false);
6230   if (embeddedCipherObj == NULL) return false;
6231 
6232   // cast it to what we know it will be at runtime
6233   const TypeInstPtr* tinst = _gvn.type(cipherBlockChaining_object)->isa_instptr();
6234   assert(tinst != NULL, "CBC obj is null");
6235   assert(tinst->klass()->is_loaded(), "CBC obj is not loaded");
6236   ciKlass* klass_AESCrypt = tinst->klass()->as_instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AESCrypt"));
6237   assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
6238 
6239   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
6240   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
6241   const TypeOopPtr* xtype = aklass->as_instance_type();
6242   Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
6243   aescrypt_object = _gvn.transform(aescrypt_object);
6244 
6245   // we need to get the start of the aescrypt_object's expanded key array
6246   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object);
6247   if (k_start == NULL) return false;
6248 
6249   // similarly, get the start address of the r vector
6250   Node* objRvec = load_field_from_object(cipherBlockChaining_object, "r", "[B", /*is_exact*/ false);
6251   if (objRvec == NULL) return false;
6252   Node* r_start = array_element_address(objRvec, intcon(0), T_BYTE);
6253 
6254   Node* cbcCrypt;
6255   if (Matcher::pass_original_key_for_aes()) {
6256     // on SPARC we need to pass the original key since key expansion needs to happen in intrinsics due to
6257     // compatibility issues between Java key expansion and SPARC crypto instructions
6258     Node* original_k_start = get_original_key_start_from_aescrypt_object(aescrypt_object);
6259     if (original_k_start == NULL) return false;
6260 
6261     // Call the stub, passing src_start, dest_start, k_start, r_start, src_len and original_k_start
6262     cbcCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
6263                                  OptoRuntime::cipherBlockChaining_aescrypt_Type(),
6264                                  stubAddr, stubName, TypePtr::BOTTOM,
6265                                  src_start, dest_start, k_start, r_start, len, original_k_start);
6266   } else {
6267     // Call the stub, passing src_start, dest_start, k_start, r_start and src_len
6268     cbcCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
6269                                  OptoRuntime::cipherBlockChaining_aescrypt_Type(),
6270                                  stubAddr, stubName, TypePtr::BOTTOM,
6271                                  src_start, dest_start, k_start, r_start, len);
6272   }
6273 
6274   // return cipher length (int)
6275   Node* retvalue = _gvn.transform(new ProjNode(cbcCrypt, TypeFunc::Parms));
6276   set_result(retvalue);
6277   return true;
6278 }
6279 
6280 //------------------------------inline_counterMode_AESCrypt-----------------------
6281 bool LibraryCallKit::inline_counterMode_AESCrypt(vmIntrinsics::ID id) {
6282   assert(UseAES, "need AES instruction support");
6283   if (!UseAESCTRIntrinsics) return false;
6284 
6285   address stubAddr = NULL;
6286   const char *stubName = NULL;
6287   if (id == vmIntrinsics::_counterMode_AESCrypt) {
6288     stubAddr = StubRoutines::counterMode_AESCrypt();
6289     stubName = "counterMode_AESCrypt";
6290   }
6291   if (stubAddr == NULL) return false;
6292 
6293   Node* counterMode_object = argument(0);
6294   Node* src = argument(1);
6295   Node* src_offset = argument(2);
6296   Node* len = argument(3);
6297   Node* dest = argument(4);
6298   Node* dest_offset = argument(5);
6299 
6300   // (1) src and dest are arrays.
6301   const Type* src_type = src->Value(&_gvn);
6302   const Type* dest_type = dest->Value(&_gvn);
6303   const TypeAryPtr* top_src = src_type->isa_aryptr();
6304   const TypeAryPtr* top_dest = dest_type->isa_aryptr();
6305   assert(top_src != NULL && top_src->klass() != NULL &&
6306          top_dest != NULL && top_dest->klass() != NULL, "args are strange");
6307 
6308   // checks are the responsibility of the caller
6309   Node* src_start = src;
6310   Node* dest_start = dest;
6311   if (src_offset != NULL || dest_offset != NULL) {
6312     assert(src_offset != NULL && dest_offset != NULL, "");
6313     src_start = array_element_address(src, src_offset, T_BYTE);
6314     dest_start = array_element_address(dest, dest_offset, T_BYTE);
6315   }
6316 
6317   // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
6318   // (because of the predicated logic executed earlier).
6319   // so we cast it here safely.
6320   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
6321   Node* embeddedCipherObj = load_field_from_object(counterMode_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;", /*is_exact*/ false);
6322   if (embeddedCipherObj == NULL) return false;
6323   // cast it to what we know it will be at runtime
6324   const TypeInstPtr* tinst = _gvn.type(counterMode_object)->isa_instptr();
6325   assert(tinst != NULL, "CTR obj is null");
6326   assert(tinst->klass()->is_loaded(), "CTR obj is not loaded");
6327   ciKlass* klass_AESCrypt = tinst->klass()->as_instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AESCrypt"));
6328   assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
6329   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
6330   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
6331   const TypeOopPtr* xtype = aklass->as_instance_type();
6332   Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
6333   aescrypt_object = _gvn.transform(aescrypt_object);
6334   // we need to get the start of the aescrypt_object's expanded key array
6335   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object);
6336   if (k_start == NULL) return false;
6337   // similarly, get the start address of the r vector
6338   Node* obj_counter = load_field_from_object(counterMode_object, "counter", "[B", /*is_exact*/ false);
6339   if (obj_counter == NULL) return false;
6340   Node* cnt_start = array_element_address(obj_counter, intcon(0), T_BYTE);
6341 
6342   Node* saved_encCounter = load_field_from_object(counterMode_object, "encryptedCounter", "[B", /*is_exact*/ false);
6343   if (saved_encCounter == NULL) return false;
6344   Node* saved_encCounter_start = array_element_address(saved_encCounter, intcon(0), T_BYTE);
6345   Node* used = field_address_from_object(counterMode_object, "used", "I", /*is_exact*/ false);
6346 
6347   Node* ctrCrypt;
6348   if (Matcher::pass_original_key_for_aes()) {
6349     // no SPARC version for AES/CTR intrinsics now.
6350     return false;
6351   }
6352   // Call the stub, passing src_start, dest_start, k_start, r_start and src_len
6353   ctrCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
6354                                OptoRuntime::counterMode_aescrypt_Type(),
6355                                stubAddr, stubName, TypePtr::BOTTOM,
6356                                src_start, dest_start, k_start, cnt_start, len, saved_encCounter_start, used);
6357 
6358   // return cipher length (int)
6359   Node* retvalue = _gvn.transform(new ProjNode(ctrCrypt, TypeFunc::Parms));
6360   set_result(retvalue);
6361   return true;
6362 }
6363 
6364 //------------------------------get_key_start_from_aescrypt_object-----------------------
6365 Node * LibraryCallKit::get_key_start_from_aescrypt_object(Node *aescrypt_object) {
6366 #if defined(PPC64) || defined(S390)
6367   // MixColumns for decryption can be reduced by preprocessing MixColumns with round keys.
6368   // Intel's extention is based on this optimization and AESCrypt generates round keys by preprocessing MixColumns.
6369   // However, ppc64 vncipher processes MixColumns and requires the same round keys with encryption.
6370   // The ppc64 stubs of encryption and decryption use the same round keys (sessionK[0]).
6371   Node* objSessionK = load_field_from_object(aescrypt_object, "sessionK", "[[I", /*is_exact*/ false);
6372   assert (objSessionK != NULL, "wrong version of com.sun.crypto.provider.AESCrypt");
6373   if (objSessionK == NULL) {
6374     return (Node *) NULL;
6375   }
6376   Node* objAESCryptKey = load_array_element(control(), objSessionK, intcon(0), TypeAryPtr::OOPS);
6377 #else
6378   Node* objAESCryptKey = load_field_from_object(aescrypt_object, "K", "[I", /*is_exact*/ false);
6379 #endif // PPC64
6380   assert (objAESCryptKey != NULL, "wrong version of com.sun.crypto.provider.AESCrypt");
6381   if (objAESCryptKey == NULL) return (Node *) NULL;
6382 
6383   // now have the array, need to get the start address of the K array
6384   Node* k_start = array_element_address(objAESCryptKey, intcon(0), T_INT);
6385   return k_start;
6386 }
6387 
6388 //------------------------------get_original_key_start_from_aescrypt_object-----------------------
6389 Node * LibraryCallKit::get_original_key_start_from_aescrypt_object(Node *aescrypt_object) {
6390   Node* objAESCryptKey = load_field_from_object(aescrypt_object, "lastKey", "[B", /*is_exact*/ false);
6391   assert (objAESCryptKey != NULL, "wrong version of com.sun.crypto.provider.AESCrypt");
6392   if (objAESCryptKey == NULL) return (Node *) NULL;
6393 
6394   // now have the array, need to get the start address of the lastKey array
6395   Node* original_k_start = array_element_address(objAESCryptKey, intcon(0), T_BYTE);
6396   return original_k_start;
6397 }
6398 
6399 //----------------------------inline_cipherBlockChaining_AESCrypt_predicate----------------------------
6400 // Return node representing slow path of predicate check.
6401 // the pseudo code we want to emulate with this predicate is:
6402 // for encryption:
6403 //    if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
6404 // for decryption:
6405 //    if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
6406 //    note cipher==plain is more conservative than the original java code but that's OK
6407 //
6408 Node* LibraryCallKit::inline_cipherBlockChaining_AESCrypt_predicate(bool decrypting) {
6409   // The receiver was checked for NULL already.
6410   Node* objCBC = argument(0);
6411 
6412   // Load embeddedCipher field of CipherBlockChaining object.
6413   Node* embeddedCipherObj = load_field_from_object(objCBC, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;", /*is_exact*/ false);
6414 
6415   // get AESCrypt klass for instanceOf check
6416   // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
6417   // will have same classloader as CipherBlockChaining object
6418   const TypeInstPtr* tinst = _gvn.type(objCBC)->isa_instptr();
6419   assert(tinst != NULL, "CBCobj is null");
6420   assert(tinst->klass()->is_loaded(), "CBCobj is not loaded");
6421 
6422   // we want to do an instanceof comparison against the AESCrypt class
6423   ciKlass* klass_AESCrypt = tinst->klass()->as_instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AESCrypt"));
6424   if (!klass_AESCrypt->is_loaded()) {
6425     // if AESCrypt is not even loaded, we never take the intrinsic fast path
6426     Node* ctrl = control();
6427     set_control(top()); // no regular fast path
6428     return ctrl;
6429   }
6430   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
6431 
6432   Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
6433   Node* cmp_instof  = _gvn.transform(new CmpINode(instof, intcon(1)));
6434   Node* bool_instof  = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
6435 
6436   Node* instof_false = generate_guard(bool_instof, NULL, PROB_MIN);
6437 
6438   // for encryption, we are done
6439   if (!decrypting)
6440     return instof_false;  // even if it is NULL
6441 
6442   // for decryption, we need to add a further check to avoid
6443   // taking the intrinsic path when cipher and plain are the same
6444   // see the original java code for why.
6445   RegionNode* region = new RegionNode(3);
6446   region->init_req(1, instof_false);
6447   Node* src = argument(1);
6448   Node* dest = argument(4);
6449   Node* cmp_src_dest = _gvn.transform(new CmpPNode(src, dest));
6450   Node* bool_src_dest = _gvn.transform(new BoolNode(cmp_src_dest, BoolTest::eq));
6451   Node* src_dest_conjoint = generate_guard(bool_src_dest, NULL, PROB_MIN);
6452   region->init_req(2, src_dest_conjoint);
6453 
6454   record_for_igvn(region);
6455   return _gvn.transform(region);
6456 }
6457 
6458 //----------------------------inline_counterMode_AESCrypt_predicate----------------------------
6459 // Return node representing slow path of predicate check.
6460 // the pseudo code we want to emulate with this predicate is:
6461 // for encryption:
6462 //    if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
6463 // for decryption:
6464 //    if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
6465 //    note cipher==plain is more conservative than the original java code but that's OK
6466 //
6467 
6468 Node* LibraryCallKit::inline_counterMode_AESCrypt_predicate() {
6469   // The receiver was checked for NULL already.
6470   Node* objCTR = argument(0);
6471 
6472   // Load embeddedCipher field of CipherBlockChaining object.
6473   Node* embeddedCipherObj = load_field_from_object(objCTR, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;", /*is_exact*/ false);
6474 
6475   // get AESCrypt klass for instanceOf check
6476   // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
6477   // will have same classloader as CipherBlockChaining object
6478   const TypeInstPtr* tinst = _gvn.type(objCTR)->isa_instptr();
6479   assert(tinst != NULL, "CTRobj is null");
6480   assert(tinst->klass()->is_loaded(), "CTRobj is not loaded");
6481 
6482   // we want to do an instanceof comparison against the AESCrypt class
6483   ciKlass* klass_AESCrypt = tinst->klass()->as_instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AESCrypt"));
6484   if (!klass_AESCrypt->is_loaded()) {
6485     // if AESCrypt is not even loaded, we never take the intrinsic fast path
6486     Node* ctrl = control();
6487     set_control(top()); // no regular fast path
6488     return ctrl;
6489   }
6490 
6491   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
6492   Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
6493   Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
6494   Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
6495   Node* instof_false = generate_guard(bool_instof, NULL, PROB_MIN);
6496 
6497   return instof_false; // even if it is NULL
6498 }
6499 
6500 //------------------------------inline_ghash_processBlocks
6501 bool LibraryCallKit::inline_ghash_processBlocks() {
6502   address stubAddr;
6503   const char *stubName;
6504   assert(UseGHASHIntrinsics, "need GHASH intrinsics support");
6505 
6506   stubAddr = StubRoutines::ghash_processBlocks();
6507   stubName = "ghash_processBlocks";
6508 
6509   Node* data           = argument(0);
6510   Node* offset         = argument(1);
6511   Node* len            = argument(2);
6512   Node* state          = argument(3);
6513   Node* subkeyH        = argument(4);
6514 
6515   Node* state_start  = array_element_address(state, intcon(0), T_LONG);
6516   assert(state_start, "state is NULL");
6517   Node* subkeyH_start  = array_element_address(subkeyH, intcon(0), T_LONG);
6518   assert(subkeyH_start, "subkeyH is NULL");
6519   Node* data_start  = array_element_address(data, offset, T_BYTE);
6520   assert(data_start, "data is NULL");
6521 
6522   Node* ghash = make_runtime_call(RC_LEAF|RC_NO_FP,
6523                                   OptoRuntime::ghash_processBlocks_Type(),
6524                                   stubAddr, stubName, TypePtr::BOTTOM,
6525                                   state_start, subkeyH_start, data_start, len);
6526   return true;
6527 }
6528 
6529 //------------------------------inline_sha_implCompress-----------------------
6530 //
6531 // Calculate SHA (i.e., SHA-1) for single-block byte[] array.
6532 // void com.sun.security.provider.SHA.implCompress(byte[] buf, int ofs)
6533 //
6534 // Calculate SHA2 (i.e., SHA-244 or SHA-256) for single-block byte[] array.
6535 // void com.sun.security.provider.SHA2.implCompress(byte[] buf, int ofs)
6536 //
6537 // Calculate SHA5 (i.e., SHA-384 or SHA-512) for single-block byte[] array.
6538 // void com.sun.security.provider.SHA5.implCompress(byte[] buf, int ofs)
6539 //
6540 bool LibraryCallKit::inline_sha_implCompress(vmIntrinsics::ID id) {
6541   assert(callee()->signature()->size() == 2, "sha_implCompress has 2 parameters");
6542 
6543   Node* sha_obj = argument(0);
6544   Node* src     = argument(1); // type oop
6545   Node* ofs     = argument(2); // type int
6546 
6547   const Type* src_type = src->Value(&_gvn);
6548   const TypeAryPtr* top_src = src_type->isa_aryptr();
6549   if (top_src  == NULL || top_src->klass()  == NULL) {
6550     // failed array check
6551     return false;
6552   }
6553   // Figure out the size and type of the elements we will be copying.
6554   BasicType src_elem = src_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
6555   if (src_elem != T_BYTE) {
6556     return false;
6557   }
6558   // 'src_start' points to src array + offset
6559   Node* src_start = array_element_address(src, ofs, src_elem);
6560   Node* state = NULL;
6561   address stubAddr;
6562   const char *stubName;
6563 
6564   switch(id) {
6565   case vmIntrinsics::_sha_implCompress:
6566     assert(UseSHA1Intrinsics, "need SHA1 instruction support");
6567     state = get_state_from_sha_object(sha_obj);
6568     stubAddr = StubRoutines::sha1_implCompress();
6569     stubName = "sha1_implCompress";
6570     break;
6571   case vmIntrinsics::_sha2_implCompress:
6572     assert(UseSHA256Intrinsics, "need SHA256 instruction support");
6573     state = get_state_from_sha_object(sha_obj);
6574     stubAddr = StubRoutines::sha256_implCompress();
6575     stubName = "sha256_implCompress";
6576     break;
6577   case vmIntrinsics::_sha5_implCompress:
6578     assert(UseSHA512Intrinsics, "need SHA512 instruction support");
6579     state = get_state_from_sha5_object(sha_obj);
6580     stubAddr = StubRoutines::sha512_implCompress();
6581     stubName = "sha512_implCompress";
6582     break;
6583   default:
6584     fatal_unexpected_iid(id);
6585     return false;
6586   }
6587   if (state == NULL) return false;
6588 
6589   // Call the stub.
6590   Node* call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::sha_implCompress_Type(),
6591                                  stubAddr, stubName, TypePtr::BOTTOM,
6592                                  src_start, state);
6593 
6594   return true;
6595 }
6596 
6597 //------------------------------inline_digestBase_implCompressMB-----------------------
6598 //
6599 // Calculate SHA/SHA2/SHA5 for multi-block byte[] array.
6600 // int com.sun.security.provider.DigestBase.implCompressMultiBlock(byte[] b, int ofs, int limit)
6601 //
6602 bool LibraryCallKit::inline_digestBase_implCompressMB(int predicate) {
6603   assert(UseSHA1Intrinsics || UseSHA256Intrinsics || UseSHA512Intrinsics,
6604          "need SHA1/SHA256/SHA512 instruction support");
6605   assert((uint)predicate < 3, "sanity");
6606   assert(callee()->signature()->size() == 3, "digestBase_implCompressMB has 3 parameters");
6607 
6608   Node* digestBase_obj = argument(0); // The receiver was checked for NULL already.
6609   Node* src            = argument(1); // byte[] array
6610   Node* ofs            = argument(2); // type int
6611   Node* limit          = argument(3); // type int
6612 
6613   const Type* src_type = src->Value(&_gvn);
6614   const TypeAryPtr* top_src = src_type->isa_aryptr();
6615   if (top_src  == NULL || top_src->klass()  == NULL) {
6616     // failed array check
6617     return false;
6618   }
6619   // Figure out the size and type of the elements we will be copying.
6620   BasicType src_elem = src_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
6621   if (src_elem != T_BYTE) {
6622     return false;
6623   }
6624   // 'src_start' points to src array + offset
6625   Node* src_start = array_element_address(src, ofs, src_elem);
6626 
6627   const char* klass_SHA_name = NULL;
6628   const char* stub_name = NULL;
6629   address     stub_addr = NULL;
6630   bool        long_state = false;
6631 
6632   switch (predicate) {
6633   case 0:
6634     if (UseSHA1Intrinsics) {
6635       klass_SHA_name = "sun/security/provider/SHA";
6636       stub_name = "sha1_implCompressMB";
6637       stub_addr = StubRoutines::sha1_implCompressMB();
6638     }
6639     break;
6640   case 1:
6641     if (UseSHA256Intrinsics) {
6642       klass_SHA_name = "sun/security/provider/SHA2";
6643       stub_name = "sha256_implCompressMB";
6644       stub_addr = StubRoutines::sha256_implCompressMB();
6645     }
6646     break;
6647   case 2:
6648     if (UseSHA512Intrinsics) {
6649       klass_SHA_name = "sun/security/provider/SHA5";
6650       stub_name = "sha512_implCompressMB";
6651       stub_addr = StubRoutines::sha512_implCompressMB();
6652       long_state = true;
6653     }
6654     break;
6655   default:
6656     fatal("unknown SHA intrinsic predicate: %d", predicate);
6657   }
6658   if (klass_SHA_name != NULL) {
6659     // get DigestBase klass to lookup for SHA klass
6660     const TypeInstPtr* tinst = _gvn.type(digestBase_obj)->isa_instptr();
6661     assert(tinst != NULL, "digestBase_obj is not instance???");
6662     assert(tinst->klass()->is_loaded(), "DigestBase is not loaded");
6663 
6664     ciKlass* klass_SHA = tinst->klass()->as_instance_klass()->find_klass(ciSymbol::make(klass_SHA_name));
6665     assert(klass_SHA->is_loaded(), "predicate checks that this class is loaded");
6666     ciInstanceKlass* instklass_SHA = klass_SHA->as_instance_klass();
6667     return inline_sha_implCompressMB(digestBase_obj, instklass_SHA, long_state, stub_addr, stub_name, src_start, ofs, limit);
6668   }
6669   return false;
6670 }
6671 //------------------------------inline_sha_implCompressMB-----------------------
6672 bool LibraryCallKit::inline_sha_implCompressMB(Node* digestBase_obj, ciInstanceKlass* instklass_SHA,
6673                                                bool long_state, address stubAddr, const char *stubName,
6674                                                Node* src_start, Node* ofs, Node* limit) {
6675   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_SHA);
6676   const TypeOopPtr* xtype = aklass->as_instance_type();
6677   Node* sha_obj = new CheckCastPPNode(control(), digestBase_obj, xtype);
6678   sha_obj = _gvn.transform(sha_obj);
6679 
6680   Node* state;
6681   if (long_state) {
6682     state = get_state_from_sha5_object(sha_obj);
6683   } else {
6684     state = get_state_from_sha_object(sha_obj);
6685   }
6686   if (state == NULL) return false;
6687 
6688   // Call the stub.
6689   Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
6690                                  OptoRuntime::digestBase_implCompressMB_Type(),
6691                                  stubAddr, stubName, TypePtr::BOTTOM,
6692                                  src_start, state, ofs, limit);
6693   // return ofs (int)
6694   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
6695   set_result(result);
6696 
6697   return true;
6698 }
6699 
6700 //------------------------------get_state_from_sha_object-----------------------
6701 Node * LibraryCallKit::get_state_from_sha_object(Node *sha_object) {
6702   Node* sha_state = load_field_from_object(sha_object, "state", "[I", /*is_exact*/ false);
6703   assert (sha_state != NULL, "wrong version of sun.security.provider.SHA/SHA2");
6704   if (sha_state == NULL) return (Node *) NULL;
6705 
6706   // now have the array, need to get the start address of the state array
6707   Node* state = array_element_address(sha_state, intcon(0), T_INT);
6708   return state;
6709 }
6710 
6711 //------------------------------get_state_from_sha5_object-----------------------
6712 Node * LibraryCallKit::get_state_from_sha5_object(Node *sha_object) {
6713   Node* sha_state = load_field_from_object(sha_object, "state", "[J", /*is_exact*/ false);
6714   assert (sha_state != NULL, "wrong version of sun.security.provider.SHA5");
6715   if (sha_state == NULL) return (Node *) NULL;
6716 
6717   // now have the array, need to get the start address of the state array
6718   Node* state = array_element_address(sha_state, intcon(0), T_LONG);
6719   return state;
6720 }
6721 
6722 //----------------------------inline_digestBase_implCompressMB_predicate----------------------------
6723 // Return node representing slow path of predicate check.
6724 // the pseudo code we want to emulate with this predicate is:
6725 //    if (digestBaseObj instanceof SHA/SHA2/SHA5) do_intrinsic, else do_javapath
6726 //
6727 Node* LibraryCallKit::inline_digestBase_implCompressMB_predicate(int predicate) {
6728   assert(UseSHA1Intrinsics || UseSHA256Intrinsics || UseSHA512Intrinsics,
6729          "need SHA1/SHA256/SHA512 instruction support");
6730   assert((uint)predicate < 3, "sanity");
6731 
6732   // The receiver was checked for NULL already.
6733   Node* digestBaseObj = argument(0);
6734 
6735   // get DigestBase klass for instanceOf check
6736   const TypeInstPtr* tinst = _gvn.type(digestBaseObj)->isa_instptr();
6737   assert(tinst != NULL, "digestBaseObj is null");
6738   assert(tinst->klass()->is_loaded(), "DigestBase is not loaded");
6739 
6740   const char* klass_SHA_name = NULL;
6741   switch (predicate) {
6742   case 0:
6743     if (UseSHA1Intrinsics) {
6744       // we want to do an instanceof comparison against the SHA class
6745       klass_SHA_name = "sun/security/provider/SHA";
6746     }
6747     break;
6748   case 1:
6749     if (UseSHA256Intrinsics) {
6750       // we want to do an instanceof comparison against the SHA2 class
6751       klass_SHA_name = "sun/security/provider/SHA2";
6752     }
6753     break;
6754   case 2:
6755     if (UseSHA512Intrinsics) {
6756       // we want to do an instanceof comparison against the SHA5 class
6757       klass_SHA_name = "sun/security/provider/SHA5";
6758     }
6759     break;
6760   default:
6761     fatal("unknown SHA intrinsic predicate: %d", predicate);
6762   }
6763 
6764   ciKlass* klass_SHA = NULL;
6765   if (klass_SHA_name != NULL) {
6766     klass_SHA = tinst->klass()->as_instance_klass()->find_klass(ciSymbol::make(klass_SHA_name));
6767   }
6768   if ((klass_SHA == NULL) || !klass_SHA->is_loaded()) {
6769     // if none of SHA/SHA2/SHA5 is loaded, we never take the intrinsic fast path
6770     Node* ctrl = control();
6771     set_control(top()); // no intrinsic path
6772     return ctrl;
6773   }
6774   ciInstanceKlass* instklass_SHA = klass_SHA->as_instance_klass();
6775 
6776   Node* instofSHA = gen_instanceof(digestBaseObj, makecon(TypeKlassPtr::make(instklass_SHA)));
6777   Node* cmp_instof = _gvn.transform(new CmpINode(instofSHA, intcon(1)));
6778   Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
6779   Node* instof_false = generate_guard(bool_instof, NULL, PROB_MIN);
6780 
6781   return instof_false;  // even if it is NULL
6782 }
6783 
6784 //-------------inline_fma-----------------------------------
6785 bool LibraryCallKit::inline_fma(vmIntrinsics::ID id) {
6786   Node *a = NULL;
6787   Node *b = NULL;
6788   Node *c = NULL;
6789   Node* result = NULL;
6790   switch (id) {
6791   case vmIntrinsics::_fmaD:
6792     assert(callee()->signature()->size() == 6, "fma has 3 parameters of size 2 each.");
6793     // no receiver since it is static method
6794     a = round_double_node(argument(0));
6795     b = round_double_node(argument(2));
6796     c = round_double_node(argument(4));
6797     result = _gvn.transform(new FmaDNode(control(), a, b, c));
6798     break;
6799   case vmIntrinsics::_fmaF:
6800     assert(callee()->signature()->size() == 3, "fma has 3 parameters of size 1 each.");
6801     a = argument(0);
6802     b = argument(1);
6803     c = argument(2);
6804     result = _gvn.transform(new FmaFNode(control(), a, b, c));
6805     break;
6806   default:
6807     fatal_unexpected_iid(id);  break;
6808   }
6809   set_result(result);
6810   return true;
6811 }
6812 
6813 bool LibraryCallKit::inline_profileBoolean() {
6814   Node* counts = argument(1);
6815   const TypeAryPtr* ary = NULL;
6816   ciArray* aobj = NULL;
6817   if (counts->is_Con()
6818       && (ary = counts->bottom_type()->isa_aryptr()) != NULL
6819       && (aobj = ary->const_oop()->as_array()) != NULL
6820       && (aobj->length() == 2)) {
6821     // Profile is int[2] where [0] and [1] correspond to false and true value occurrences respectively.
6822     jint false_cnt = aobj->element_value(0).as_int();
6823     jint  true_cnt = aobj->element_value(1).as_int();
6824 
6825     if (C->log() != NULL) {
6826       C->log()->elem("observe source='profileBoolean' false='%d' true='%d'",
6827                      false_cnt, true_cnt);
6828     }
6829 
6830     if (false_cnt + true_cnt == 0) {
6831       // According to profile, never executed.
6832       uncommon_trap_exact(Deoptimization::Reason_intrinsic,
6833                           Deoptimization::Action_reinterpret);
6834       return true;
6835     }
6836 
6837     // result is a boolean (0 or 1) and its profile (false_cnt & true_cnt)
6838     // is a number of each value occurrences.
6839     Node* result = argument(0);
6840     if (false_cnt == 0 || true_cnt == 0) {
6841       // According to profile, one value has been never seen.
6842       int expected_val = (false_cnt == 0) ? 1 : 0;
6843 
6844       Node* cmp  = _gvn.transform(new CmpINode(result, intcon(expected_val)));
6845       Node* test = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
6846 
6847       IfNode* check = create_and_map_if(control(), test, PROB_ALWAYS, COUNT_UNKNOWN);
6848       Node* fast_path = _gvn.transform(new IfTrueNode(check));
6849       Node* slow_path = _gvn.transform(new IfFalseNode(check));
6850 
6851       { // Slow path: uncommon trap for never seen value and then reexecute
6852         // MethodHandleImpl::profileBoolean() to bump the count, so JIT knows
6853         // the value has been seen at least once.
6854         PreserveJVMState pjvms(this);
6855         PreserveReexecuteState preexecs(this);
6856         jvms()->set_should_reexecute(true);
6857 
6858         set_control(slow_path);
6859         set_i_o(i_o());
6860 
6861         uncommon_trap_exact(Deoptimization::Reason_intrinsic,
6862                             Deoptimization::Action_reinterpret);
6863       }
6864       // The guard for never seen value enables sharpening of the result and
6865       // returning a constant. It allows to eliminate branches on the same value
6866       // later on.
6867       set_control(fast_path);
6868       result = intcon(expected_val);
6869     }
6870     // Stop profiling.
6871     // MethodHandleImpl::profileBoolean() has profiling logic in its bytecode.
6872     // By replacing method body with profile data (represented as ProfileBooleanNode
6873     // on IR level) we effectively disable profiling.
6874     // It enables full speed execution once optimized code is generated.
6875     Node* profile = _gvn.transform(new ProfileBooleanNode(result, false_cnt, true_cnt));
6876     C->record_for_igvn(profile);
6877     set_result(profile);
6878     return true;
6879   } else {
6880     // Continue profiling.
6881     // Profile data isn't available at the moment. So, execute method's bytecode version.
6882     // Usually, when GWT LambdaForms are profiled it means that a stand-alone nmethod
6883     // is compiled and counters aren't available since corresponding MethodHandle
6884     // isn't a compile-time constant.
6885     return false;
6886   }
6887 }
6888 
6889 bool LibraryCallKit::inline_isCompileConstant() {
6890   Node* n = argument(0);
6891   set_result(n->is_Con() ? intcon(1) : intcon(0));
6892   return true;
6893 }