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