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