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