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