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