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