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