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