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