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