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