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