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