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