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