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