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