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