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