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