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