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