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