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