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