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