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