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