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