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