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