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