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