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