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