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