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