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