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