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