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