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