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