src/share/vm/opto/library_call.cpp

Thu, 16 Jul 2009 14:10:42 -0700

author
kvn
date
Thu, 16 Jul 2009 14:10:42 -0700
changeset 1286
fc4be448891f
parent 1271
4325cdaa78ad
child 1291
75596850f863
child 1330
94b6d06fd759
permissions
-rw-r--r--

6851742: (EA) allocation elimination doesn't work with UseG1GC
Summary: Fix eliminate_card_mark() to eliminate G1 pre/post barriers.
Reviewed-by: never

     1 /*
     2  * Copyright 1999-2009 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
    20  * CA 95054 USA or visit www.sun.com if you need additional information or
    21  * have any questions.
    22  *
    23  */
    25 #include "incls/_precompiled.incl"
    26 #include "incls/_library_call.cpp.incl"
    28 class LibraryIntrinsic : public InlineCallGenerator {
    29   // Extend the set of intrinsics known to the runtime:
    30  public:
    31  private:
    32   bool             _is_virtual;
    33   vmIntrinsics::ID _intrinsic_id;
    35  public:
    36   LibraryIntrinsic(ciMethod* m, bool is_virtual, vmIntrinsics::ID id)
    37     : InlineCallGenerator(m),
    38       _is_virtual(is_virtual),
    39       _intrinsic_id(id)
    40   {
    41   }
    42   virtual bool is_intrinsic() const { return true; }
    43   virtual bool is_virtual()   const { return _is_virtual; }
    44   virtual JVMState* generate(JVMState* jvms);
    45   vmIntrinsics::ID intrinsic_id() const { return _intrinsic_id; }
    46 };
    49 // Local helper class for LibraryIntrinsic:
    50 class LibraryCallKit : public GraphKit {
    51  private:
    52   LibraryIntrinsic* _intrinsic;   // the library intrinsic being called
    54  public:
    55   LibraryCallKit(JVMState* caller, LibraryIntrinsic* intrinsic)
    56     : GraphKit(caller),
    57       _intrinsic(intrinsic)
    58   {
    59   }
    61   ciMethod*         caller()    const    { return jvms()->method(); }
    62   int               bci()       const    { return jvms()->bci(); }
    63   LibraryIntrinsic* intrinsic() const    { return _intrinsic; }
    64   vmIntrinsics::ID  intrinsic_id() const { return _intrinsic->intrinsic_id(); }
    65   ciMethod*         callee()    const    { return _intrinsic->method(); }
    66   ciSignature*      signature() const    { return callee()->signature(); }
    67   int               arg_size()  const    { return callee()->arg_size(); }
    69   bool try_to_inline();
    71   // Helper functions to inline natives
    72   void push_result(RegionNode* region, PhiNode* value);
    73   Node* generate_guard(Node* test, RegionNode* region, float true_prob);
    74   Node* generate_slow_guard(Node* test, RegionNode* region);
    75   Node* generate_fair_guard(Node* test, RegionNode* region);
    76   Node* generate_negative_guard(Node* index, RegionNode* region,
    77                                 // resulting CastII of index:
    78                                 Node* *pos_index = NULL);
    79   Node* generate_nonpositive_guard(Node* index, bool never_negative,
    80                                    // resulting CastII of index:
    81                                    Node* *pos_index = NULL);
    82   Node* generate_limit_guard(Node* offset, Node* subseq_length,
    83                              Node* array_length,
    84                              RegionNode* region);
    85   Node* generate_current_thread(Node* &tls_output);
    86   address basictype2arraycopy(BasicType t, Node *src_offset, Node *dest_offset,
    87                               bool disjoint_bases, const char* &name);
    88   Node* load_mirror_from_klass(Node* klass);
    89   Node* load_klass_from_mirror_common(Node* mirror, bool never_see_null,
    90                                       int nargs,
    91                                       RegionNode* region, int null_path,
    92                                       int offset);
    93   Node* load_klass_from_mirror(Node* mirror, bool never_see_null, int nargs,
    94                                RegionNode* region, int null_path) {
    95     int offset = java_lang_Class::klass_offset_in_bytes();
    96     return load_klass_from_mirror_common(mirror, never_see_null, nargs,
    97                                          region, null_path,
    98                                          offset);
    99   }
   100   Node* load_array_klass_from_mirror(Node* mirror, bool never_see_null,
   101                                      int nargs,
   102                                      RegionNode* region, int null_path) {
   103     int offset = java_lang_Class::array_klass_offset_in_bytes();
   104     return load_klass_from_mirror_common(mirror, never_see_null, nargs,
   105                                          region, null_path,
   106                                          offset);
   107   }
   108   Node* generate_access_flags_guard(Node* kls,
   109                                     int modifier_mask, int modifier_bits,
   110                                     RegionNode* region);
   111   Node* generate_interface_guard(Node* kls, RegionNode* region);
   112   Node* generate_array_guard(Node* kls, RegionNode* region) {
   113     return generate_array_guard_common(kls, region, false, false);
   114   }
   115   Node* generate_non_array_guard(Node* kls, RegionNode* region) {
   116     return generate_array_guard_common(kls, region, false, true);
   117   }
   118   Node* generate_objArray_guard(Node* kls, RegionNode* region) {
   119     return generate_array_guard_common(kls, region, true, false);
   120   }
   121   Node* generate_non_objArray_guard(Node* kls, RegionNode* region) {
   122     return generate_array_guard_common(kls, region, true, true);
   123   }
   124   Node* generate_array_guard_common(Node* kls, RegionNode* region,
   125                                     bool obj_array, bool not_array);
   126   Node* generate_virtual_guard(Node* obj_klass, RegionNode* slow_region);
   127   CallJavaNode* generate_method_call(vmIntrinsics::ID method_id,
   128                                      bool is_virtual = false, bool is_static = false);
   129   CallJavaNode* generate_method_call_static(vmIntrinsics::ID method_id) {
   130     return generate_method_call(method_id, false, true);
   131   }
   132   CallJavaNode* generate_method_call_virtual(vmIntrinsics::ID method_id) {
   133     return generate_method_call(method_id, true, false);
   134   }
   136   bool inline_string_compareTo();
   137   bool inline_string_indexOf();
   138   Node* string_indexOf(Node* string_object, ciTypeArray* target_array, jint offset, jint cache_i, jint md2_i);
   139   bool inline_string_equals();
   140   Node* pop_math_arg();
   141   bool runtime_math(const TypeFunc* call_type, address funcAddr, const char* funcName);
   142   bool inline_math_native(vmIntrinsics::ID id);
   143   bool inline_trig(vmIntrinsics::ID id);
   144   bool inline_trans(vmIntrinsics::ID id);
   145   bool inline_abs(vmIntrinsics::ID id);
   146   bool inline_sqrt(vmIntrinsics::ID id);
   147   bool inline_pow(vmIntrinsics::ID id);
   148   bool inline_exp(vmIntrinsics::ID id);
   149   bool inline_min_max(vmIntrinsics::ID id);
   150   Node* generate_min_max(vmIntrinsics::ID id, Node* x, Node* y);
   151   // This returns Type::AnyPtr, RawPtr, or OopPtr.
   152   int classify_unsafe_addr(Node* &base, Node* &offset);
   153   Node* make_unsafe_address(Node* base, Node* offset);
   154   bool inline_unsafe_access(bool is_native_ptr, bool is_store, BasicType type, bool is_volatile);
   155   bool inline_unsafe_prefetch(bool is_native_ptr, bool is_store, bool is_static);
   156   bool inline_unsafe_allocate();
   157   bool inline_unsafe_copyMemory();
   158   bool inline_native_currentThread();
   159   bool inline_native_time_funcs(bool isNano);
   160   bool inline_native_isInterrupted();
   161   bool inline_native_Class_query(vmIntrinsics::ID id);
   162   bool inline_native_subtype_check();
   164   bool inline_native_newArray();
   165   bool inline_native_getLength();
   166   bool inline_array_copyOf(bool is_copyOfRange);
   167   bool inline_array_equals();
   168   void copy_to_clone(Node* obj, Node* alloc_obj, Node* obj_size, bool is_array, bool card_mark);
   169   bool inline_native_clone(bool is_virtual);
   170   bool inline_native_Reflection_getCallerClass();
   171   bool inline_native_AtomicLong_get();
   172   bool inline_native_AtomicLong_attemptUpdate();
   173   bool is_method_invoke_or_aux_frame(JVMState* jvms);
   174   // Helper function for inlining native object hash method
   175   bool inline_native_hashcode(bool is_virtual, bool is_static);
   176   bool inline_native_getClass();
   178   // Helper functions for inlining arraycopy
   179   bool inline_arraycopy();
   180   void generate_arraycopy(const TypePtr* adr_type,
   181                           BasicType basic_elem_type,
   182                           Node* src,  Node* src_offset,
   183                           Node* dest, Node* dest_offset,
   184                           Node* copy_length,
   185                           bool disjoint_bases = false,
   186                           bool length_never_negative = false,
   187                           RegionNode* slow_region = NULL);
   188   AllocateArrayNode* tightly_coupled_allocation(Node* ptr,
   189                                                 RegionNode* slow_region);
   190   void generate_clear_array(const TypePtr* adr_type,
   191                             Node* dest,
   192                             BasicType basic_elem_type,
   193                             Node* slice_off,
   194                             Node* slice_len,
   195                             Node* slice_end);
   196   bool generate_block_arraycopy(const TypePtr* adr_type,
   197                                 BasicType basic_elem_type,
   198                                 AllocateNode* alloc,
   199                                 Node* src,  Node* src_offset,
   200                                 Node* dest, Node* dest_offset,
   201                                 Node* dest_size);
   202   void generate_slow_arraycopy(const TypePtr* adr_type,
   203                                Node* src,  Node* src_offset,
   204                                Node* dest, Node* dest_offset,
   205                                Node* copy_length);
   206   Node* generate_checkcast_arraycopy(const TypePtr* adr_type,
   207                                      Node* dest_elem_klass,
   208                                      Node* src,  Node* src_offset,
   209                                      Node* dest, Node* dest_offset,
   210                                      Node* copy_length);
   211   Node* generate_generic_arraycopy(const TypePtr* adr_type,
   212                                    Node* src,  Node* src_offset,
   213                                    Node* dest, Node* dest_offset,
   214                                    Node* copy_length);
   215   void generate_unchecked_arraycopy(const TypePtr* adr_type,
   216                                     BasicType basic_elem_type,
   217                                     bool disjoint_bases,
   218                                     Node* src,  Node* src_offset,
   219                                     Node* dest, Node* dest_offset,
   220                                     Node* copy_length);
   221   bool inline_unsafe_CAS(BasicType type);
   222   bool inline_unsafe_ordered_store(BasicType type);
   223   bool inline_fp_conversions(vmIntrinsics::ID id);
   224   bool inline_numberOfLeadingZeros(vmIntrinsics::ID id);
   225   bool inline_numberOfTrailingZeros(vmIntrinsics::ID id);
   226   bool inline_bitCount(vmIntrinsics::ID id);
   227   bool inline_reverseBytes(vmIntrinsics::ID id);
   228 };
   231 //---------------------------make_vm_intrinsic----------------------------
   232 CallGenerator* Compile::make_vm_intrinsic(ciMethod* m, bool is_virtual) {
   233   vmIntrinsics::ID id = m->intrinsic_id();
   234   assert(id != vmIntrinsics::_none, "must be a VM intrinsic");
   236   if (DisableIntrinsic[0] != '\0'
   237       && strstr(DisableIntrinsic, vmIntrinsics::name_at(id)) != NULL) {
   238     // disabled by a user request on the command line:
   239     // example: -XX:DisableIntrinsic=_hashCode,_getClass
   240     return NULL;
   241   }
   243   if (!m->is_loaded()) {
   244     // do not attempt to inline unloaded methods
   245     return NULL;
   246   }
   248   // Only a few intrinsics implement a virtual dispatch.
   249   // They are expensive calls which are also frequently overridden.
   250   if (is_virtual) {
   251     switch (id) {
   252     case vmIntrinsics::_hashCode:
   253     case vmIntrinsics::_clone:
   254       // OK, Object.hashCode and Object.clone intrinsics come in both flavors
   255       break;
   256     default:
   257       return NULL;
   258     }
   259   }
   261   // -XX:-InlineNatives disables nearly all intrinsics:
   262   if (!InlineNatives) {
   263     switch (id) {
   264     case vmIntrinsics::_indexOf:
   265     case vmIntrinsics::_compareTo:
   266     case vmIntrinsics::_equals:
   267     case vmIntrinsics::_equalsC:
   268       break;  // InlineNatives does not control String.compareTo
   269     default:
   270       return NULL;
   271     }
   272   }
   274   switch (id) {
   275   case vmIntrinsics::_compareTo:
   276     if (!SpecialStringCompareTo)  return NULL;
   277     break;
   278   case vmIntrinsics::_indexOf:
   279     if (!SpecialStringIndexOf)  return NULL;
   280     break;
   281   case vmIntrinsics::_equals:
   282     if (!SpecialStringEquals)  return NULL;
   283     break;
   284   case vmIntrinsics::_equalsC:
   285     if (!SpecialArraysEquals)  return NULL;
   286     break;
   287   case vmIntrinsics::_arraycopy:
   288     if (!InlineArrayCopy)  return NULL;
   289     break;
   290   case vmIntrinsics::_copyMemory:
   291     if (StubRoutines::unsafe_arraycopy() == NULL)  return NULL;
   292     if (!InlineArrayCopy)  return NULL;
   293     break;
   294   case vmIntrinsics::_hashCode:
   295     if (!InlineObjectHash)  return NULL;
   296     break;
   297   case vmIntrinsics::_clone:
   298   case vmIntrinsics::_copyOf:
   299   case vmIntrinsics::_copyOfRange:
   300     if (!InlineObjectCopy)  return NULL;
   301     // These also use the arraycopy intrinsic mechanism:
   302     if (!InlineArrayCopy)  return NULL;
   303     break;
   304   case vmIntrinsics::_checkIndex:
   305     // We do not intrinsify this.  The optimizer does fine with it.
   306     return NULL;
   308   case vmIntrinsics::_get_AtomicLong:
   309   case vmIntrinsics::_attemptUpdate:
   310     if (!InlineAtomicLong)  return NULL;
   311     break;
   313   case vmIntrinsics::_Object_init:
   314   case vmIntrinsics::_invoke:
   315     // We do not intrinsify these; they are marked for other purposes.
   316     return NULL;
   318   case vmIntrinsics::_getCallerClass:
   319     if (!UseNewReflection)  return NULL;
   320     if (!InlineReflectionGetCallerClass)  return NULL;
   321     if (!JDK_Version::is_gte_jdk14x_version())  return NULL;
   322     break;
   324   case vmIntrinsics::_bitCount_i:
   325   case vmIntrinsics::_bitCount_l:
   326     if (!UsePopCountInstruction)  return NULL;
   327     break;
   329  default:
   330     break;
   331   }
   333   // -XX:-InlineClassNatives disables natives from the Class class.
   334   // The flag applies to all reflective calls, notably Array.newArray
   335   // (visible to Java programmers as Array.newInstance).
   336   if (m->holder()->name() == ciSymbol::java_lang_Class() ||
   337       m->holder()->name() == ciSymbol::java_lang_reflect_Array()) {
   338     if (!InlineClassNatives)  return NULL;
   339   }
   341   // -XX:-InlineThreadNatives disables natives from the Thread class.
   342   if (m->holder()->name() == ciSymbol::java_lang_Thread()) {
   343     if (!InlineThreadNatives)  return NULL;
   344   }
   346   // -XX:-InlineMathNatives disables natives from the Math,Float and Double classes.
   347   if (m->holder()->name() == ciSymbol::java_lang_Math() ||
   348       m->holder()->name() == ciSymbol::java_lang_Float() ||
   349       m->holder()->name() == ciSymbol::java_lang_Double()) {
   350     if (!InlineMathNatives)  return NULL;
   351   }
   353   // -XX:-InlineUnsafeOps disables natives from the Unsafe class.
   354   if (m->holder()->name() == ciSymbol::sun_misc_Unsafe()) {
   355     if (!InlineUnsafeOps)  return NULL;
   356   }
   358   return new LibraryIntrinsic(m, is_virtual, (vmIntrinsics::ID) id);
   359 }
   361 //----------------------register_library_intrinsics-----------------------
   362 // Initialize this file's data structures, for each Compile instance.
   363 void Compile::register_library_intrinsics() {
   364   // Nothing to do here.
   365 }
   367 JVMState* LibraryIntrinsic::generate(JVMState* jvms) {
   368   LibraryCallKit kit(jvms, this);
   369   Compile* C = kit.C;
   370   int nodes = C->unique();
   371 #ifndef PRODUCT
   372   if ((PrintIntrinsics || PrintInlining NOT_PRODUCT( || PrintOptoInlining) ) && Verbose) {
   373     char buf[1000];
   374     const char* str = vmIntrinsics::short_name_as_C_string(intrinsic_id(), buf, sizeof(buf));
   375     tty->print_cr("Intrinsic %s", str);
   376   }
   377 #endif
   378   if (kit.try_to_inline()) {
   379     if (PrintIntrinsics || PrintInlining NOT_PRODUCT( || PrintOptoInlining) ) {
   380       tty->print("Inlining intrinsic %s%s at bci:%d in",
   381                  vmIntrinsics::name_at(intrinsic_id()),
   382                  (is_virtual() ? " (virtual)" : ""), kit.bci());
   383       kit.caller()->print_short_name(tty);
   384       tty->print_cr(" (%d bytes)", kit.caller()->code_size());
   385     }
   386     C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_worked);
   387     if (C->log()) {
   388       C->log()->elem("intrinsic id='%s'%s nodes='%d'",
   389                      vmIntrinsics::name_at(intrinsic_id()),
   390                      (is_virtual() ? " virtual='1'" : ""),
   391                      C->unique() - nodes);
   392     }
   393     return kit.transfer_exceptions_into_jvms();
   394   }
   396   if (PrintIntrinsics) {
   397     switch (intrinsic_id()) {
   398     case vmIntrinsics::_invoke:
   399     case vmIntrinsics::_Object_init:
   400       // We do not expect to inline these, so do not produce any noise about them.
   401       break;
   402     default:
   403       tty->print("Did not inline intrinsic %s%s at bci:%d in",
   404                  vmIntrinsics::name_at(intrinsic_id()),
   405                  (is_virtual() ? " (virtual)" : ""), kit.bci());
   406       kit.caller()->print_short_name(tty);
   407       tty->print_cr(" (%d bytes)", kit.caller()->code_size());
   408     }
   409   }
   410   C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_failed);
   411   return NULL;
   412 }
   414 bool LibraryCallKit::try_to_inline() {
   415   // Handle symbolic names for otherwise undistinguished boolean switches:
   416   const bool is_store       = true;
   417   const bool is_native_ptr  = true;
   418   const bool is_static      = true;
   420   switch (intrinsic_id()) {
   421   case vmIntrinsics::_hashCode:
   422     return inline_native_hashcode(intrinsic()->is_virtual(), !is_static);
   423   case vmIntrinsics::_identityHashCode:
   424     return inline_native_hashcode(/*!virtual*/ false, is_static);
   425   case vmIntrinsics::_getClass:
   426     return inline_native_getClass();
   428   case vmIntrinsics::_dsin:
   429   case vmIntrinsics::_dcos:
   430   case vmIntrinsics::_dtan:
   431   case vmIntrinsics::_dabs:
   432   case vmIntrinsics::_datan2:
   433   case vmIntrinsics::_dsqrt:
   434   case vmIntrinsics::_dexp:
   435   case vmIntrinsics::_dlog:
   436   case vmIntrinsics::_dlog10:
   437   case vmIntrinsics::_dpow:
   438     return inline_math_native(intrinsic_id());
   440   case vmIntrinsics::_min:
   441   case vmIntrinsics::_max:
   442     return inline_min_max(intrinsic_id());
   444   case vmIntrinsics::_arraycopy:
   445     return inline_arraycopy();
   447   case vmIntrinsics::_compareTo:
   448     return inline_string_compareTo();
   449   case vmIntrinsics::_indexOf:
   450     return inline_string_indexOf();
   451   case vmIntrinsics::_equals:
   452     return inline_string_equals();
   454   case vmIntrinsics::_getObject:
   455     return inline_unsafe_access(!is_native_ptr, !is_store, T_OBJECT, false);
   456   case vmIntrinsics::_getBoolean:
   457     return inline_unsafe_access(!is_native_ptr, !is_store, T_BOOLEAN, false);
   458   case vmIntrinsics::_getByte:
   459     return inline_unsafe_access(!is_native_ptr, !is_store, T_BYTE, false);
   460   case vmIntrinsics::_getShort:
   461     return inline_unsafe_access(!is_native_ptr, !is_store, T_SHORT, false);
   462   case vmIntrinsics::_getChar:
   463     return inline_unsafe_access(!is_native_ptr, !is_store, T_CHAR, false);
   464   case vmIntrinsics::_getInt:
   465     return inline_unsafe_access(!is_native_ptr, !is_store, T_INT, false);
   466   case vmIntrinsics::_getLong:
   467     return inline_unsafe_access(!is_native_ptr, !is_store, T_LONG, false);
   468   case vmIntrinsics::_getFloat:
   469     return inline_unsafe_access(!is_native_ptr, !is_store, T_FLOAT, false);
   470   case vmIntrinsics::_getDouble:
   471     return inline_unsafe_access(!is_native_ptr, !is_store, T_DOUBLE, false);
   473   case vmIntrinsics::_putObject:
   474     return inline_unsafe_access(!is_native_ptr, is_store, T_OBJECT, false);
   475   case vmIntrinsics::_putBoolean:
   476     return inline_unsafe_access(!is_native_ptr, is_store, T_BOOLEAN, false);
   477   case vmIntrinsics::_putByte:
   478     return inline_unsafe_access(!is_native_ptr, is_store, T_BYTE, false);
   479   case vmIntrinsics::_putShort:
   480     return inline_unsafe_access(!is_native_ptr, is_store, T_SHORT, false);
   481   case vmIntrinsics::_putChar:
   482     return inline_unsafe_access(!is_native_ptr, is_store, T_CHAR, false);
   483   case vmIntrinsics::_putInt:
   484     return inline_unsafe_access(!is_native_ptr, is_store, T_INT, false);
   485   case vmIntrinsics::_putLong:
   486     return inline_unsafe_access(!is_native_ptr, is_store, T_LONG, false);
   487   case vmIntrinsics::_putFloat:
   488     return inline_unsafe_access(!is_native_ptr, is_store, T_FLOAT, false);
   489   case vmIntrinsics::_putDouble:
   490     return inline_unsafe_access(!is_native_ptr, is_store, T_DOUBLE, false);
   492   case vmIntrinsics::_getByte_raw:
   493     return inline_unsafe_access(is_native_ptr, !is_store, T_BYTE, false);
   494   case vmIntrinsics::_getShort_raw:
   495     return inline_unsafe_access(is_native_ptr, !is_store, T_SHORT, false);
   496   case vmIntrinsics::_getChar_raw:
   497     return inline_unsafe_access(is_native_ptr, !is_store, T_CHAR, false);
   498   case vmIntrinsics::_getInt_raw:
   499     return inline_unsafe_access(is_native_ptr, !is_store, T_INT, false);
   500   case vmIntrinsics::_getLong_raw:
   501     return inline_unsafe_access(is_native_ptr, !is_store, T_LONG, false);
   502   case vmIntrinsics::_getFloat_raw:
   503     return inline_unsafe_access(is_native_ptr, !is_store, T_FLOAT, false);
   504   case vmIntrinsics::_getDouble_raw:
   505     return inline_unsafe_access(is_native_ptr, !is_store, T_DOUBLE, false);
   506   case vmIntrinsics::_getAddress_raw:
   507     return inline_unsafe_access(is_native_ptr, !is_store, T_ADDRESS, false);
   509   case vmIntrinsics::_putByte_raw:
   510     return inline_unsafe_access(is_native_ptr, is_store, T_BYTE, false);
   511   case vmIntrinsics::_putShort_raw:
   512     return inline_unsafe_access(is_native_ptr, is_store, T_SHORT, false);
   513   case vmIntrinsics::_putChar_raw:
   514     return inline_unsafe_access(is_native_ptr, is_store, T_CHAR, false);
   515   case vmIntrinsics::_putInt_raw:
   516     return inline_unsafe_access(is_native_ptr, is_store, T_INT, false);
   517   case vmIntrinsics::_putLong_raw:
   518     return inline_unsafe_access(is_native_ptr, is_store, T_LONG, false);
   519   case vmIntrinsics::_putFloat_raw:
   520     return inline_unsafe_access(is_native_ptr, is_store, T_FLOAT, false);
   521   case vmIntrinsics::_putDouble_raw:
   522     return inline_unsafe_access(is_native_ptr, is_store, T_DOUBLE, false);
   523   case vmIntrinsics::_putAddress_raw:
   524     return inline_unsafe_access(is_native_ptr, is_store, T_ADDRESS, false);
   526   case vmIntrinsics::_getObjectVolatile:
   527     return inline_unsafe_access(!is_native_ptr, !is_store, T_OBJECT, true);
   528   case vmIntrinsics::_getBooleanVolatile:
   529     return inline_unsafe_access(!is_native_ptr, !is_store, T_BOOLEAN, true);
   530   case vmIntrinsics::_getByteVolatile:
   531     return inline_unsafe_access(!is_native_ptr, !is_store, T_BYTE, true);
   532   case vmIntrinsics::_getShortVolatile:
   533     return inline_unsafe_access(!is_native_ptr, !is_store, T_SHORT, true);
   534   case vmIntrinsics::_getCharVolatile:
   535     return inline_unsafe_access(!is_native_ptr, !is_store, T_CHAR, true);
   536   case vmIntrinsics::_getIntVolatile:
   537     return inline_unsafe_access(!is_native_ptr, !is_store, T_INT, true);
   538   case vmIntrinsics::_getLongVolatile:
   539     return inline_unsafe_access(!is_native_ptr, !is_store, T_LONG, true);
   540   case vmIntrinsics::_getFloatVolatile:
   541     return inline_unsafe_access(!is_native_ptr, !is_store, T_FLOAT, true);
   542   case vmIntrinsics::_getDoubleVolatile:
   543     return inline_unsafe_access(!is_native_ptr, !is_store, T_DOUBLE, true);
   545   case vmIntrinsics::_putObjectVolatile:
   546     return inline_unsafe_access(!is_native_ptr, is_store, T_OBJECT, true);
   547   case vmIntrinsics::_putBooleanVolatile:
   548     return inline_unsafe_access(!is_native_ptr, is_store, T_BOOLEAN, true);
   549   case vmIntrinsics::_putByteVolatile:
   550     return inline_unsafe_access(!is_native_ptr, is_store, T_BYTE, true);
   551   case vmIntrinsics::_putShortVolatile:
   552     return inline_unsafe_access(!is_native_ptr, is_store, T_SHORT, true);
   553   case vmIntrinsics::_putCharVolatile:
   554     return inline_unsafe_access(!is_native_ptr, is_store, T_CHAR, true);
   555   case vmIntrinsics::_putIntVolatile:
   556     return inline_unsafe_access(!is_native_ptr, is_store, T_INT, true);
   557   case vmIntrinsics::_putLongVolatile:
   558     return inline_unsafe_access(!is_native_ptr, is_store, T_LONG, true);
   559   case vmIntrinsics::_putFloatVolatile:
   560     return inline_unsafe_access(!is_native_ptr, is_store, T_FLOAT, true);
   561   case vmIntrinsics::_putDoubleVolatile:
   562     return inline_unsafe_access(!is_native_ptr, is_store, T_DOUBLE, true);
   564   case vmIntrinsics::_prefetchRead:
   565     return inline_unsafe_prefetch(!is_native_ptr, !is_store, !is_static);
   566   case vmIntrinsics::_prefetchWrite:
   567     return inline_unsafe_prefetch(!is_native_ptr, is_store, !is_static);
   568   case vmIntrinsics::_prefetchReadStatic:
   569     return inline_unsafe_prefetch(!is_native_ptr, !is_store, is_static);
   570   case vmIntrinsics::_prefetchWriteStatic:
   571     return inline_unsafe_prefetch(!is_native_ptr, is_store, is_static);
   573   case vmIntrinsics::_compareAndSwapObject:
   574     return inline_unsafe_CAS(T_OBJECT);
   575   case vmIntrinsics::_compareAndSwapInt:
   576     return inline_unsafe_CAS(T_INT);
   577   case vmIntrinsics::_compareAndSwapLong:
   578     return inline_unsafe_CAS(T_LONG);
   580   case vmIntrinsics::_putOrderedObject:
   581     return inline_unsafe_ordered_store(T_OBJECT);
   582   case vmIntrinsics::_putOrderedInt:
   583     return inline_unsafe_ordered_store(T_INT);
   584   case vmIntrinsics::_putOrderedLong:
   585     return inline_unsafe_ordered_store(T_LONG);
   587   case vmIntrinsics::_currentThread:
   588     return inline_native_currentThread();
   589   case vmIntrinsics::_isInterrupted:
   590     return inline_native_isInterrupted();
   592   case vmIntrinsics::_currentTimeMillis:
   593     return inline_native_time_funcs(false);
   594   case vmIntrinsics::_nanoTime:
   595     return inline_native_time_funcs(true);
   596   case vmIntrinsics::_allocateInstance:
   597     return inline_unsafe_allocate();
   598   case vmIntrinsics::_copyMemory:
   599     return inline_unsafe_copyMemory();
   600   case vmIntrinsics::_newArray:
   601     return inline_native_newArray();
   602   case vmIntrinsics::_getLength:
   603     return inline_native_getLength();
   604   case vmIntrinsics::_copyOf:
   605     return inline_array_copyOf(false);
   606   case vmIntrinsics::_copyOfRange:
   607     return inline_array_copyOf(true);
   608   case vmIntrinsics::_equalsC:
   609     return inline_array_equals();
   610   case vmIntrinsics::_clone:
   611     return inline_native_clone(intrinsic()->is_virtual());
   613   case vmIntrinsics::_isAssignableFrom:
   614     return inline_native_subtype_check();
   616   case vmIntrinsics::_isInstance:
   617   case vmIntrinsics::_getModifiers:
   618   case vmIntrinsics::_isInterface:
   619   case vmIntrinsics::_isArray:
   620   case vmIntrinsics::_isPrimitive:
   621   case vmIntrinsics::_getSuperclass:
   622   case vmIntrinsics::_getComponentType:
   623   case vmIntrinsics::_getClassAccessFlags:
   624     return inline_native_Class_query(intrinsic_id());
   626   case vmIntrinsics::_floatToRawIntBits:
   627   case vmIntrinsics::_floatToIntBits:
   628   case vmIntrinsics::_intBitsToFloat:
   629   case vmIntrinsics::_doubleToRawLongBits:
   630   case vmIntrinsics::_doubleToLongBits:
   631   case vmIntrinsics::_longBitsToDouble:
   632     return inline_fp_conversions(intrinsic_id());
   634   case vmIntrinsics::_numberOfLeadingZeros_i:
   635   case vmIntrinsics::_numberOfLeadingZeros_l:
   636     return inline_numberOfLeadingZeros(intrinsic_id());
   638   case vmIntrinsics::_numberOfTrailingZeros_i:
   639   case vmIntrinsics::_numberOfTrailingZeros_l:
   640     return inline_numberOfTrailingZeros(intrinsic_id());
   642   case vmIntrinsics::_bitCount_i:
   643   case vmIntrinsics::_bitCount_l:
   644     return inline_bitCount(intrinsic_id());
   646   case vmIntrinsics::_reverseBytes_i:
   647   case vmIntrinsics::_reverseBytes_l:
   648     return inline_reverseBytes((vmIntrinsics::ID) intrinsic_id());
   650   case vmIntrinsics::_get_AtomicLong:
   651     return inline_native_AtomicLong_get();
   652   case vmIntrinsics::_attemptUpdate:
   653     return inline_native_AtomicLong_attemptUpdate();
   655   case vmIntrinsics::_getCallerClass:
   656     return inline_native_Reflection_getCallerClass();
   658   default:
   659     // If you get here, it may be that someone has added a new intrinsic
   660     // to the list in vmSymbols.hpp without implementing it here.
   661 #ifndef PRODUCT
   662     if ((PrintMiscellaneous && (Verbose || WizardMode)) || PrintOpto) {
   663       tty->print_cr("*** Warning: Unimplemented intrinsic %s(%d)",
   664                     vmIntrinsics::name_at(intrinsic_id()), intrinsic_id());
   665     }
   666 #endif
   667     return false;
   668   }
   669 }
   671 //------------------------------push_result------------------------------
   672 // Helper function for finishing intrinsics.
   673 void LibraryCallKit::push_result(RegionNode* region, PhiNode* value) {
   674   record_for_igvn(region);
   675   set_control(_gvn.transform(region));
   676   BasicType value_type = value->type()->basic_type();
   677   push_node(value_type, _gvn.transform(value));
   678 }
   680 //------------------------------generate_guard---------------------------
   681 // Helper function for generating guarded fast-slow graph structures.
   682 // The given 'test', if true, guards a slow path.  If the test fails
   683 // then a fast path can be taken.  (We generally hope it fails.)
   684 // In all cases, GraphKit::control() is updated to the fast path.
   685 // The returned value represents the control for the slow path.
   686 // The return value is never 'top'; it is either a valid control
   687 // or NULL if it is obvious that the slow path can never be taken.
   688 // Also, if region and the slow control are not NULL, the slow edge
   689 // is appended to the region.
   690 Node* LibraryCallKit::generate_guard(Node* test, RegionNode* region, float true_prob) {
   691   if (stopped()) {
   692     // Already short circuited.
   693     return NULL;
   694   }
   696   // Build an if node and its projections.
   697   // If test is true we take the slow path, which we assume is uncommon.
   698   if (_gvn.type(test) == TypeInt::ZERO) {
   699     // The slow branch is never taken.  No need to build this guard.
   700     return NULL;
   701   }
   703   IfNode* iff = create_and_map_if(control(), test, true_prob, COUNT_UNKNOWN);
   705   Node* if_slow = _gvn.transform( new (C, 1) IfTrueNode(iff) );
   706   if (if_slow == top()) {
   707     // The slow branch is never taken.  No need to build this guard.
   708     return NULL;
   709   }
   711   if (region != NULL)
   712     region->add_req(if_slow);
   714   Node* if_fast = _gvn.transform( new (C, 1) IfFalseNode(iff) );
   715   set_control(if_fast);
   717   return if_slow;
   718 }
   720 inline Node* LibraryCallKit::generate_slow_guard(Node* test, RegionNode* region) {
   721   return generate_guard(test, region, PROB_UNLIKELY_MAG(3));
   722 }
   723 inline Node* LibraryCallKit::generate_fair_guard(Node* test, RegionNode* region) {
   724   return generate_guard(test, region, PROB_FAIR);
   725 }
   727 inline Node* LibraryCallKit::generate_negative_guard(Node* index, RegionNode* region,
   728                                                      Node* *pos_index) {
   729   if (stopped())
   730     return NULL;                // already stopped
   731   if (_gvn.type(index)->higher_equal(TypeInt::POS)) // [0,maxint]
   732     return NULL;                // index is already adequately typed
   733   Node* cmp_lt = _gvn.transform( new (C, 3) CmpINode(index, intcon(0)) );
   734   Node* bol_lt = _gvn.transform( new (C, 2) BoolNode(cmp_lt, BoolTest::lt) );
   735   Node* is_neg = generate_guard(bol_lt, region, PROB_MIN);
   736   if (is_neg != NULL && pos_index != NULL) {
   737     // Emulate effect of Parse::adjust_map_after_if.
   738     Node* ccast = new (C, 2) CastIINode(index, TypeInt::POS);
   739     ccast->set_req(0, control());
   740     (*pos_index) = _gvn.transform(ccast);
   741   }
   742   return is_neg;
   743 }
   745 inline Node* LibraryCallKit::generate_nonpositive_guard(Node* index, bool never_negative,
   746                                                         Node* *pos_index) {
   747   if (stopped())
   748     return NULL;                // already stopped
   749   if (_gvn.type(index)->higher_equal(TypeInt::POS1)) // [1,maxint]
   750     return NULL;                // index is already adequately typed
   751   Node* cmp_le = _gvn.transform( new (C, 3) CmpINode(index, intcon(0)) );
   752   BoolTest::mask le_or_eq = (never_negative ? BoolTest::eq : BoolTest::le);
   753   Node* bol_le = _gvn.transform( new (C, 2) BoolNode(cmp_le, le_or_eq) );
   754   Node* is_notp = generate_guard(bol_le, NULL, PROB_MIN);
   755   if (is_notp != NULL && pos_index != NULL) {
   756     // Emulate effect of Parse::adjust_map_after_if.
   757     Node* ccast = new (C, 2) CastIINode(index, TypeInt::POS1);
   758     ccast->set_req(0, control());
   759     (*pos_index) = _gvn.transform(ccast);
   760   }
   761   return is_notp;
   762 }
   764 // Make sure that 'position' is a valid limit index, in [0..length].
   765 // There are two equivalent plans for checking this:
   766 //   A. (offset + copyLength)  unsigned<=  arrayLength
   767 //   B. offset  <=  (arrayLength - copyLength)
   768 // We require that all of the values above, except for the sum and
   769 // difference, are already known to be non-negative.
   770 // Plan A is robust in the face of overflow, if offset and copyLength
   771 // are both hugely positive.
   772 //
   773 // Plan B is less direct and intuitive, but it does not overflow at
   774 // all, since the difference of two non-negatives is always
   775 // representable.  Whenever Java methods must perform the equivalent
   776 // check they generally use Plan B instead of Plan A.
   777 // For the moment we use Plan A.
   778 inline Node* LibraryCallKit::generate_limit_guard(Node* offset,
   779                                                   Node* subseq_length,
   780                                                   Node* array_length,
   781                                                   RegionNode* region) {
   782   if (stopped())
   783     return NULL;                // already stopped
   784   bool zero_offset = _gvn.type(offset) == TypeInt::ZERO;
   785   if (zero_offset && _gvn.eqv_uncast(subseq_length, array_length))
   786     return NULL;                // common case of whole-array copy
   787   Node* last = subseq_length;
   788   if (!zero_offset)             // last += offset
   789     last = _gvn.transform( new (C, 3) AddINode(last, offset));
   790   Node* cmp_lt = _gvn.transform( new (C, 3) CmpUNode(array_length, last) );
   791   Node* bol_lt = _gvn.transform( new (C, 2) BoolNode(cmp_lt, BoolTest::lt) );
   792   Node* is_over = generate_guard(bol_lt, region, PROB_MIN);
   793   return is_over;
   794 }
   797 //--------------------------generate_current_thread--------------------
   798 Node* LibraryCallKit::generate_current_thread(Node* &tls_output) {
   799   ciKlass*    thread_klass = env()->Thread_klass();
   800   const Type* thread_type  = TypeOopPtr::make_from_klass(thread_klass)->cast_to_ptr_type(TypePtr::NotNull);
   801   Node* thread = _gvn.transform(new (C, 1) ThreadLocalNode());
   802   Node* p = basic_plus_adr(top()/*!oop*/, thread, in_bytes(JavaThread::threadObj_offset()));
   803   Node* threadObj = make_load(NULL, p, thread_type, T_OBJECT);
   804   tls_output = thread;
   805   return threadObj;
   806 }
   809 //------------------------------inline_string_compareTo------------------------
   810 bool LibraryCallKit::inline_string_compareTo() {
   812   if (!Matcher::has_match_rule(Op_StrComp)) return false;
   814   const int value_offset = java_lang_String::value_offset_in_bytes();
   815   const int count_offset = java_lang_String::count_offset_in_bytes();
   816   const int offset_offset = java_lang_String::offset_offset_in_bytes();
   818   _sp += 2;
   819   Node *argument = pop();  // pop non-receiver first:  it was pushed second
   820   Node *receiver = pop();
   822   // Null check on self without removing any arguments.  The argument
   823   // null check technically happens in the wrong place, which can lead to
   824   // invalid stack traces when string compare is inlined into a method
   825   // which handles NullPointerExceptions.
   826   _sp += 2;
   827   receiver = do_null_check(receiver, T_OBJECT);
   828   argument = do_null_check(argument, T_OBJECT);
   829   _sp -= 2;
   830   if (stopped()) {
   831     return true;
   832   }
   834   ciInstanceKlass* klass = env()->String_klass();
   835   const TypeInstPtr* string_type =
   836     TypeInstPtr::make(TypePtr::BotPTR, klass, false, NULL, 0);
   838   Node* compare =
   839     _gvn.transform(new (C, 7) StrCompNode(
   840                         control(),
   841                         memory(TypeAryPtr::CHARS),
   842                         memory(string_type->add_offset(value_offset)),
   843                         memory(string_type->add_offset(count_offset)),
   844                         memory(string_type->add_offset(offset_offset)),
   845                         receiver,
   846                         argument));
   847   push(compare);
   848   return true;
   849 }
   851 //------------------------------inline_string_equals------------------------
   852 bool LibraryCallKit::inline_string_equals() {
   854   if (!Matcher::has_match_rule(Op_StrEquals)) return false;
   856   const int value_offset = java_lang_String::value_offset_in_bytes();
   857   const int count_offset = java_lang_String::count_offset_in_bytes();
   858   const int offset_offset = java_lang_String::offset_offset_in_bytes();
   860   _sp += 2;
   861   Node* argument = pop();  // pop non-receiver first:  it was pushed second
   862   Node* receiver = pop();
   864   // Null check on self without removing any arguments.  The argument
   865   // null check technically happens in the wrong place, which can lead to
   866   // invalid stack traces when string compare is inlined into a method
   867   // which handles NullPointerExceptions.
   868   _sp += 2;
   869   receiver = do_null_check(receiver, T_OBJECT);
   870   //should not do null check for argument for String.equals(), because spec
   871   //allows to specify NULL as argument.
   872   _sp -= 2;
   874   if (stopped()) {
   875     return true;
   876   }
   878   // get String klass for instanceOf
   879   ciInstanceKlass* klass = env()->String_klass();
   881   // two paths (plus control) merge
   882   RegionNode* region = new (C, 3) RegionNode(3);
   883   Node* phi = new (C, 3) PhiNode(region, TypeInt::BOOL);
   885   Node* inst = gen_instanceof(argument, makecon(TypeKlassPtr::make(klass)));
   886   Node* cmp  = _gvn.transform(new (C, 3) CmpINode(inst, intcon(1)));
   887   Node* bol  = _gvn.transform(new (C, 2) BoolNode(cmp, BoolTest::eq));
   889   IfNode* iff = create_and_map_if(control(), bol, PROB_MAX, COUNT_UNKNOWN);
   891   Node* if_true  = _gvn.transform(new (C, 1) IfTrueNode(iff));
   892   set_control(if_true);
   894   const TypeInstPtr* string_type =
   895     TypeInstPtr::make(TypePtr::BotPTR, klass, false, NULL, 0);
   897   // instanceOf == true
   898   Node* equals =
   899     _gvn.transform(new (C, 7) StrEqualsNode(
   900                         control(),
   901                         memory(TypeAryPtr::CHARS),
   902                         memory(string_type->add_offset(value_offset)),
   903                         memory(string_type->add_offset(count_offset)),
   904                         memory(string_type->add_offset(offset_offset)),
   905                         receiver,
   906                         argument));
   908   phi->init_req(1, _gvn.transform(equals));
   909   region->init_req(1, if_true);
   911   //instanceOf == false, fallthrough
   912   Node* if_false = _gvn.transform(new (C, 1) IfFalseNode(iff));
   913   set_control(if_false);
   915   phi->init_req(2, _gvn.transform(intcon(0)));
   916   region->init_req(2, if_false);
   918   // post merge
   919   set_control(_gvn.transform(region));
   920   record_for_igvn(region);
   922   push(_gvn.transform(phi));
   924   return true;
   925 }
   927 //------------------------------inline_array_equals----------------------------
   928 bool LibraryCallKit::inline_array_equals() {
   930   if (!Matcher::has_match_rule(Op_AryEq)) return false;
   932   _sp += 2;
   933   Node *argument2 = pop();
   934   Node *argument1 = pop();
   936   Node* equals =
   937     _gvn.transform(new (C, 3) AryEqNode(control(),
   938                                         argument1,
   939                                         argument2)
   940                    );
   941   push(equals);
   942   return true;
   943 }
   945 // Java version of String.indexOf(constant string)
   946 // class StringDecl {
   947 //   StringDecl(char[] ca) {
   948 //     offset = 0;
   949 //     count = ca.length;
   950 //     value = ca;
   951 //   }
   952 //   int offset;
   953 //   int count;
   954 //   char[] value;
   955 // }
   956 //
   957 // static int string_indexOf_J(StringDecl string_object, char[] target_object,
   958 //                             int targetOffset, int cache_i, int md2) {
   959 //   int cache = cache_i;
   960 //   int sourceOffset = string_object.offset;
   961 //   int sourceCount = string_object.count;
   962 //   int targetCount = target_object.length;
   963 //
   964 //   int targetCountLess1 = targetCount - 1;
   965 //   int sourceEnd = sourceOffset + sourceCount - targetCountLess1;
   966 //
   967 //   char[] source = string_object.value;
   968 //   char[] target = target_object;
   969 //   int lastChar = target[targetCountLess1];
   970 //
   971 //  outer_loop:
   972 //   for (int i = sourceOffset; i < sourceEnd; ) {
   973 //     int src = source[i + targetCountLess1];
   974 //     if (src == lastChar) {
   975 //       // With random strings and a 4-character alphabet,
   976 //       // reverse matching at this point sets up 0.8% fewer
   977 //       // frames, but (paradoxically) makes 0.3% more probes.
   978 //       // Since those probes are nearer the lastChar probe,
   979 //       // there is may be a net D$ win with reverse matching.
   980 //       // But, reversing loop inhibits unroll of inner loop
   981 //       // for unknown reason.  So, does running outer loop from
   982 //       // (sourceOffset - targetCountLess1) to (sourceOffset + sourceCount)
   983 //       for (int j = 0; j < targetCountLess1; j++) {
   984 //         if (target[targetOffset + j] != source[i+j]) {
   985 //           if ((cache & (1 << source[i+j])) == 0) {
   986 //             if (md2 < j+1) {
   987 //               i += j+1;
   988 //               continue outer_loop;
   989 //             }
   990 //           }
   991 //           i += md2;
   992 //           continue outer_loop;
   993 //         }
   994 //       }
   995 //       return i - sourceOffset;
   996 //     }
   997 //     if ((cache & (1 << src)) == 0) {
   998 //       i += targetCountLess1;
   999 //     } // using "i += targetCount;" and an "else i++;" causes a jump to jump.
  1000 //     i++;
  1001 //   }
  1002 //   return -1;
  1003 // }
  1005 //------------------------------string_indexOf------------------------
  1006 Node* LibraryCallKit::string_indexOf(Node* string_object, ciTypeArray* target_array, jint targetOffset_i,
  1007                                      jint cache_i, jint md2_i) {
  1009   Node* no_ctrl  = NULL;
  1010   float likely   = PROB_LIKELY(0.9);
  1011   float unlikely = PROB_UNLIKELY(0.9);
  1013   const int value_offset  = java_lang_String::value_offset_in_bytes();
  1014   const int count_offset  = java_lang_String::count_offset_in_bytes();
  1015   const int offset_offset = java_lang_String::offset_offset_in_bytes();
  1017   ciInstanceKlass* klass = env()->String_klass();
  1018   const TypeInstPtr* string_type = TypeInstPtr::make(TypePtr::BotPTR, klass, false, NULL, 0);
  1019   const TypeAryPtr*  source_type = TypeAryPtr::make(TypePtr::NotNull, TypeAry::make(TypeInt::CHAR,TypeInt::POS), ciTypeArrayKlass::make(T_CHAR), true, 0);
  1021   Node* sourceOffseta = basic_plus_adr(string_object, string_object, offset_offset);
  1022   Node* sourceOffset  = make_load(no_ctrl, sourceOffseta, TypeInt::INT, T_INT, string_type->add_offset(offset_offset));
  1023   Node* sourceCounta  = basic_plus_adr(string_object, string_object, count_offset);
  1024   Node* sourceCount   = make_load(no_ctrl, sourceCounta, TypeInt::INT, T_INT, string_type->add_offset(count_offset));
  1025   Node* sourcea       = basic_plus_adr(string_object, string_object, value_offset);
  1026   Node* source        = make_load(no_ctrl, sourcea, source_type, T_OBJECT, string_type->add_offset(value_offset));
  1028   Node* target = _gvn.transform( makecon(TypeOopPtr::make_from_constant(target_array)) );
  1029   jint target_length = target_array->length();
  1030   const TypeAry* target_array_type = TypeAry::make(TypeInt::CHAR, TypeInt::make(0, target_length, Type::WidenMin));
  1031   const TypeAryPtr* target_type = TypeAryPtr::make(TypePtr::BotPTR, target_array_type, target_array->klass(), true, Type::OffsetBot);
  1033   IdealKit kit(gvn(), control(), merged_memory(), false, true);
  1034 #define __ kit.
  1035   Node* zero             = __ ConI(0);
  1036   Node* one              = __ ConI(1);
  1037   Node* cache            = __ ConI(cache_i);
  1038   Node* md2              = __ ConI(md2_i);
  1039   Node* lastChar         = __ ConI(target_array->char_at(target_length - 1));
  1040   Node* targetCount      = __ ConI(target_length);
  1041   Node* targetCountLess1 = __ ConI(target_length - 1);
  1042   Node* targetOffset     = __ ConI(targetOffset_i);
  1043   Node* sourceEnd        = __ SubI(__ AddI(sourceOffset, sourceCount), targetCountLess1);
  1045   IdealVariable rtn(kit), i(kit), j(kit); __ declarations_done();
  1046   Node* outer_loop = __ make_label(2 /* goto */);
  1047   Node* return_    = __ make_label(1);
  1049   __ set(rtn,__ ConI(-1));
  1050   __ loop(i, sourceOffset, BoolTest::lt, sourceEnd); {
  1051        Node* i2  = __ AddI(__ value(i), targetCountLess1);
  1052        // pin to prohibit loading of "next iteration" value which may SEGV (rare)
  1053        Node* src = load_array_element(__ ctrl(), source, i2, TypeAryPtr::CHARS);
  1054        __ if_then(src, BoolTest::eq, lastChar, unlikely); {
  1055          __ loop(j, zero, BoolTest::lt, targetCountLess1); {
  1056               Node* tpj = __ AddI(targetOffset, __ value(j));
  1057               Node* targ = load_array_element(no_ctrl, target, tpj, target_type);
  1058               Node* ipj  = __ AddI(__ value(i), __ value(j));
  1059               Node* src2 = load_array_element(no_ctrl, source, ipj, TypeAryPtr::CHARS);
  1060               __ if_then(targ, BoolTest::ne, src2); {
  1061                 __ if_then(__ AndI(cache, __ LShiftI(one, src2)), BoolTest::eq, zero); {
  1062                   __ if_then(md2, BoolTest::lt, __ AddI(__ value(j), one)); {
  1063                     __ increment(i, __ AddI(__ value(j), one));
  1064                     __ goto_(outer_loop);
  1065                   } __ end_if(); __ dead(j);
  1066                 }__ end_if(); __ dead(j);
  1067                 __ increment(i, md2);
  1068                 __ goto_(outer_loop);
  1069               }__ end_if();
  1070               __ increment(j, one);
  1071          }__ end_loop(); __ dead(j);
  1072          __ set(rtn, __ SubI(__ value(i), sourceOffset)); __ dead(i);
  1073          __ goto_(return_);
  1074        }__ end_if();
  1075        __ if_then(__ AndI(cache, __ LShiftI(one, src)), BoolTest::eq, zero, likely); {
  1076          __ increment(i, targetCountLess1);
  1077        }__ end_if();
  1078        __ increment(i, one);
  1079        __ bind(outer_loop);
  1080   }__ end_loop(); __ dead(i);
  1081   __ bind(return_);
  1083   // Final sync IdealKit and GraphKit.
  1084   sync_kit(kit);
  1085   Node* result = __ value(rtn);
  1086 #undef __
  1087   C->set_has_loops(true);
  1088   return result;
  1091 //------------------------------inline_string_indexOf------------------------
  1092 bool LibraryCallKit::inline_string_indexOf() {
  1094   const int value_offset  = java_lang_String::value_offset_in_bytes();
  1095   const int count_offset  = java_lang_String::count_offset_in_bytes();
  1096   const int offset_offset = java_lang_String::offset_offset_in_bytes();
  1098   _sp += 2;
  1099   Node *argument = pop();  // pop non-receiver first:  it was pushed second
  1100   Node *receiver = pop();
  1102   Node* result;
  1103   if (Matcher::has_match_rule(Op_StrIndexOf) &&
  1104       UseSSE42Intrinsics) {
  1105     // Generate SSE4.2 version of indexOf
  1106     // We currently only have match rules that use SSE4.2
  1108     // Null check on self without removing any arguments.  The argument
  1109     // null check technically happens in the wrong place, which can lead to
  1110     // invalid stack traces when string compare is inlined into a method
  1111     // which handles NullPointerExceptions.
  1112     _sp += 2;
  1113     receiver = do_null_check(receiver, T_OBJECT);
  1114     argument = do_null_check(argument, T_OBJECT);
  1115     _sp -= 2;
  1117     if (stopped()) {
  1118       return true;
  1121     ciInstanceKlass* klass = env()->String_klass();
  1122     const TypeInstPtr* string_type =
  1123       TypeInstPtr::make(TypePtr::BotPTR, klass, false, NULL, 0);
  1125     result =
  1126       _gvn.transform(new (C, 7)
  1127                      StrIndexOfNode(control(),
  1128                                     memory(TypeAryPtr::CHARS),
  1129                                     memory(string_type->add_offset(value_offset)),
  1130                                     memory(string_type->add_offset(count_offset)),
  1131                                     memory(string_type->add_offset(offset_offset)),
  1132                                     receiver,
  1133                                     argument));
  1134   } else { //Use LibraryCallKit::string_indexOf
  1135     // don't intrinsify is argument isn't a constant string.
  1136     if (!argument->is_Con()) {
  1137      return false;
  1139     const TypeOopPtr* str_type = _gvn.type(argument)->isa_oopptr();
  1140     if (str_type == NULL) {
  1141       return false;
  1143     ciInstanceKlass* klass = env()->String_klass();
  1144     ciObject* str_const = str_type->const_oop();
  1145     if (str_const == NULL || str_const->klass() != klass) {
  1146       return false;
  1148     ciInstance* str = str_const->as_instance();
  1149     assert(str != NULL, "must be instance");
  1151     ciObject* v = str->field_value_by_offset(value_offset).as_object();
  1152     int       o = str->field_value_by_offset(offset_offset).as_int();
  1153     int       c = str->field_value_by_offset(count_offset).as_int();
  1154     ciTypeArray* pat = v->as_type_array(); // pattern (argument) character array
  1156     // constant strings have no offset and count == length which
  1157     // simplifies the resulting code somewhat so lets optimize for that.
  1158     if (o != 0 || c != pat->length()) {
  1159      return false;
  1162     // Null check on self without removing any arguments.  The argument
  1163     // null check technically happens in the wrong place, which can lead to
  1164     // invalid stack traces when string compare is inlined into a method
  1165     // which handles NullPointerExceptions.
  1166     _sp += 2;
  1167     receiver = do_null_check(receiver, T_OBJECT);
  1168     // No null check on the argument is needed since it's a constant String oop.
  1169     _sp -= 2;
  1170     if (stopped()) {
  1171      return true;
  1174     // The null string as a pattern always returns 0 (match at beginning of string)
  1175     if (c == 0) {
  1176       push(intcon(0));
  1177       return true;
  1180     // Generate default indexOf
  1181     jchar lastChar = pat->char_at(o + (c - 1));
  1182     int cache = 0;
  1183     int i;
  1184     for (i = 0; i < c - 1; i++) {
  1185       assert(i < pat->length(), "out of range");
  1186       cache |= (1 << (pat->char_at(o + i) & (sizeof(cache) * BitsPerByte - 1)));
  1189     int md2 = c;
  1190     for (i = 0; i < c - 1; i++) {
  1191       assert(i < pat->length(), "out of range");
  1192       if (pat->char_at(o + i) == lastChar) {
  1193         md2 = (c - 1) - i;
  1197     result = string_indexOf(receiver, pat, o, cache, md2);
  1200   push(result);
  1201   return true;
  1204 //--------------------------pop_math_arg--------------------------------
  1205 // Pop a double argument to a math function from the stack
  1206 // rounding it if necessary.
  1207 Node * LibraryCallKit::pop_math_arg() {
  1208   Node *arg = pop_pair();
  1209   if( Matcher::strict_fp_requires_explicit_rounding && UseSSE<=1 )
  1210     arg = _gvn.transform( new (C, 2) RoundDoubleNode(0, arg) );
  1211   return arg;
  1214 //------------------------------inline_trig----------------------------------
  1215 // Inline sin/cos/tan instructions, if possible.  If rounding is required, do
  1216 // argument reduction which will turn into a fast/slow diamond.
  1217 bool LibraryCallKit::inline_trig(vmIntrinsics::ID id) {
  1218   _sp += arg_size();            // restore stack pointer
  1219   Node* arg = pop_math_arg();
  1220   Node* trig = NULL;
  1222   switch (id) {
  1223   case vmIntrinsics::_dsin:
  1224     trig = _gvn.transform((Node*)new (C, 2) SinDNode(arg));
  1225     break;
  1226   case vmIntrinsics::_dcos:
  1227     trig = _gvn.transform((Node*)new (C, 2) CosDNode(arg));
  1228     break;
  1229   case vmIntrinsics::_dtan:
  1230     trig = _gvn.transform((Node*)new (C, 2) TanDNode(arg));
  1231     break;
  1232   default:
  1233     assert(false, "bad intrinsic was passed in");
  1234     return false;
  1237   // Rounding required?  Check for argument reduction!
  1238   if( Matcher::strict_fp_requires_explicit_rounding ) {
  1240     static const double     pi_4 =  0.7853981633974483;
  1241     static const double neg_pi_4 = -0.7853981633974483;
  1242     // pi/2 in 80-bit extended precision
  1243     // static const unsigned char pi_2_bits_x[] = {0x35,0xc2,0x68,0x21,0xa2,0xda,0x0f,0xc9,0xff,0x3f,0x00,0x00,0x00,0x00,0x00,0x00};
  1244     // -pi/2 in 80-bit extended precision
  1245     // 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};
  1246     // Cutoff value for using this argument reduction technique
  1247     //static const double    pi_2_minus_epsilon =  1.564660403643354;
  1248     //static const double neg_pi_2_plus_epsilon = -1.564660403643354;
  1250     // Pseudocode for sin:
  1251     // if (x <= Math.PI / 4.0) {
  1252     //   if (x >= -Math.PI / 4.0) return  fsin(x);
  1253     //   if (x >= -Math.PI / 2.0) return -fcos(x + Math.PI / 2.0);
  1254     // } else {
  1255     //   if (x <=  Math.PI / 2.0) return  fcos(x - Math.PI / 2.0);
  1256     // }
  1257     // return StrictMath.sin(x);
  1259     // Pseudocode for cos:
  1260     // if (x <= Math.PI / 4.0) {
  1261     //   if (x >= -Math.PI / 4.0) return  fcos(x);
  1262     //   if (x >= -Math.PI / 2.0) return  fsin(x + Math.PI / 2.0);
  1263     // } else {
  1264     //   if (x <=  Math.PI / 2.0) return -fsin(x - Math.PI / 2.0);
  1265     // }
  1266     // return StrictMath.cos(x);
  1268     // Actually, sticking in an 80-bit Intel value into C2 will be tough; it
  1269     // requires a special machine instruction to load it.  Instead we'll try
  1270     // the 'easy' case.  If we really need the extra range +/- PI/2 we'll
  1271     // probably do the math inside the SIN encoding.
  1273     // Make the merge point
  1274     RegionNode *r = new (C, 3) RegionNode(3);
  1275     Node *phi = new (C, 3) PhiNode(r,Type::DOUBLE);
  1277     // Flatten arg so we need only 1 test
  1278     Node *abs = _gvn.transform(new (C, 2) AbsDNode(arg));
  1279     // Node for PI/4 constant
  1280     Node *pi4 = makecon(TypeD::make(pi_4));
  1281     // Check PI/4 : abs(arg)
  1282     Node *cmp = _gvn.transform(new (C, 3) CmpDNode(pi4,abs));
  1283     // Check: If PI/4 < abs(arg) then go slow
  1284     Node *bol = _gvn.transform( new (C, 2) BoolNode( cmp, BoolTest::lt ) );
  1285     // Branch either way
  1286     IfNode *iff = create_and_xform_if(control(),bol, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
  1287     set_control(opt_iff(r,iff));
  1289     // Set fast path result
  1290     phi->init_req(2,trig);
  1292     // Slow path - non-blocking leaf call
  1293     Node* call = NULL;
  1294     switch (id) {
  1295     case vmIntrinsics::_dsin:
  1296       call = make_runtime_call(RC_LEAF, OptoRuntime::Math_D_D_Type(),
  1297                                CAST_FROM_FN_PTR(address, SharedRuntime::dsin),
  1298                                "Sin", NULL, arg, top());
  1299       break;
  1300     case vmIntrinsics::_dcos:
  1301       call = make_runtime_call(RC_LEAF, OptoRuntime::Math_D_D_Type(),
  1302                                CAST_FROM_FN_PTR(address, SharedRuntime::dcos),
  1303                                "Cos", NULL, arg, top());
  1304       break;
  1305     case vmIntrinsics::_dtan:
  1306       call = make_runtime_call(RC_LEAF, OptoRuntime::Math_D_D_Type(),
  1307                                CAST_FROM_FN_PTR(address, SharedRuntime::dtan),
  1308                                "Tan", NULL, arg, top());
  1309       break;
  1311     assert(control()->in(0) == call, "");
  1312     Node* slow_result = _gvn.transform(new (C, 1) ProjNode(call,TypeFunc::Parms));
  1313     r->init_req(1,control());
  1314     phi->init_req(1,slow_result);
  1316     // Post-merge
  1317     set_control(_gvn.transform(r));
  1318     record_for_igvn(r);
  1319     trig = _gvn.transform(phi);
  1321     C->set_has_split_ifs(true); // Has chance for split-if optimization
  1323   // Push result back on JVM stack
  1324   push_pair(trig);
  1325   return true;
  1328 //------------------------------inline_sqrt-------------------------------------
  1329 // Inline square root instruction, if possible.
  1330 bool LibraryCallKit::inline_sqrt(vmIntrinsics::ID id) {
  1331   assert(id == vmIntrinsics::_dsqrt, "Not square root");
  1332   _sp += arg_size();        // restore stack pointer
  1333   push_pair(_gvn.transform(new (C, 2) SqrtDNode(0, pop_math_arg())));
  1334   return true;
  1337 //------------------------------inline_abs-------------------------------------
  1338 // Inline absolute value instruction, if possible.
  1339 bool LibraryCallKit::inline_abs(vmIntrinsics::ID id) {
  1340   assert(id == vmIntrinsics::_dabs, "Not absolute value");
  1341   _sp += arg_size();        // restore stack pointer
  1342   push_pair(_gvn.transform(new (C, 2) AbsDNode(pop_math_arg())));
  1343   return true;
  1346 //------------------------------inline_exp-------------------------------------
  1347 // Inline exp instructions, if possible.  The Intel hardware only misses
  1348 // really odd corner cases (+/- Infinity).  Just uncommon-trap them.
  1349 bool LibraryCallKit::inline_exp(vmIntrinsics::ID id) {
  1350   assert(id == vmIntrinsics::_dexp, "Not exp");
  1352   // If this inlining ever returned NaN in the past, we do not intrinsify it
  1353   // every again.  NaN results requires StrictMath.exp handling.
  1354   if (too_many_traps(Deoptimization::Reason_intrinsic))  return false;
  1356   // Do not intrinsify on older platforms which lack cmove.
  1357   if (ConditionalMoveLimit == 0)  return false;
  1359   _sp += arg_size();        // restore stack pointer
  1360   Node *x = pop_math_arg();
  1361   Node *result = _gvn.transform(new (C, 2) ExpDNode(0,x));
  1363   //-------------------
  1364   //result=(result.isNaN())? StrictMath::exp():result;
  1365   // Check: If isNaN() by checking result!=result? then go to Strict Math
  1366   Node* cmpisnan = _gvn.transform(new (C, 3) CmpDNode(result,result));
  1367   // Build the boolean node
  1368   Node* bolisnum = _gvn.transform( new (C, 2) BoolNode(cmpisnan, BoolTest::eq) );
  1370   { BuildCutout unless(this, bolisnum, PROB_STATIC_FREQUENT);
  1371     // End the current control-flow path
  1372     push_pair(x);
  1373     // Math.exp intrinsic returned a NaN, which requires StrictMath.exp
  1374     // to handle.  Recompile without intrinsifying Math.exp
  1375     uncommon_trap(Deoptimization::Reason_intrinsic,
  1376                   Deoptimization::Action_make_not_entrant);
  1379   C->set_has_split_ifs(true); // Has chance for split-if optimization
  1381   push_pair(result);
  1383   return true;
  1386 //------------------------------inline_pow-------------------------------------
  1387 // Inline power instructions, if possible.
  1388 bool LibraryCallKit::inline_pow(vmIntrinsics::ID id) {
  1389   assert(id == vmIntrinsics::_dpow, "Not pow");
  1391   // If this inlining ever returned NaN in the past, we do not intrinsify it
  1392   // every again.  NaN results requires StrictMath.pow handling.
  1393   if (too_many_traps(Deoptimization::Reason_intrinsic))  return false;
  1395   // Do not intrinsify on older platforms which lack cmove.
  1396   if (ConditionalMoveLimit == 0)  return false;
  1398   // Pseudocode for pow
  1399   // if (x <= 0.0) {
  1400   //   if ((double)((int)y)==y) { // if y is int
  1401   //     result = ((1&(int)y)==0)?-DPow(abs(x), y):DPow(abs(x), y)
  1402   //   } else {
  1403   //     result = NaN;
  1404   //   }
  1405   // } else {
  1406   //   result = DPow(x,y);
  1407   // }
  1408   // if (result != result)?  {
  1409   //   uncommon_trap();
  1410   // }
  1411   // return result;
  1413   _sp += arg_size();        // restore stack pointer
  1414   Node* y = pop_math_arg();
  1415   Node* x = pop_math_arg();
  1417   Node *fast_result = _gvn.transform( new (C, 3) PowDNode(0, x, y) );
  1419   // Short form: if not top-level (i.e., Math.pow but inlining Math.pow
  1420   // inside of something) then skip the fancy tests and just check for
  1421   // NaN result.
  1422   Node *result = NULL;
  1423   if( jvms()->depth() >= 1 ) {
  1424     result = fast_result;
  1425   } else {
  1427     // Set the merge point for If node with condition of (x <= 0.0)
  1428     // There are four possible paths to region node and phi node
  1429     RegionNode *r = new (C, 4) RegionNode(4);
  1430     Node *phi = new (C, 4) PhiNode(r, Type::DOUBLE);
  1432     // Build the first if node: if (x <= 0.0)
  1433     // Node for 0 constant
  1434     Node *zeronode = makecon(TypeD::ZERO);
  1435     // Check x:0
  1436     Node *cmp = _gvn.transform(new (C, 3) CmpDNode(x, zeronode));
  1437     // Check: If (x<=0) then go complex path
  1438     Node *bol1 = _gvn.transform( new (C, 2) BoolNode( cmp, BoolTest::le ) );
  1439     // Branch either way
  1440     IfNode *if1 = create_and_xform_if(control(),bol1, PROB_STATIC_INFREQUENT, COUNT_UNKNOWN);
  1441     Node *opt_test = _gvn.transform(if1);
  1442     //assert( opt_test->is_If(), "Expect an IfNode");
  1443     IfNode *opt_if1 = (IfNode*)opt_test;
  1444     // Fast path taken; set region slot 3
  1445     Node *fast_taken = _gvn.transform( new (C, 1) IfFalseNode(opt_if1) );
  1446     r->init_req(3,fast_taken); // Capture fast-control
  1448     // Fast path not-taken, i.e. slow path
  1449     Node *complex_path = _gvn.transform( new (C, 1) IfTrueNode(opt_if1) );
  1451     // Set fast path result
  1452     Node *fast_result = _gvn.transform( new (C, 3) PowDNode(0, y, x) );
  1453     phi->init_req(3, fast_result);
  1455     // Complex path
  1456     // Build the second if node (if y is int)
  1457     // Node for (int)y
  1458     Node *inty = _gvn.transform( new (C, 2) ConvD2INode(y));
  1459     // Node for (double)((int) y)
  1460     Node *doubleinty= _gvn.transform( new (C, 2) ConvI2DNode(inty));
  1461     // Check (double)((int) y) : y
  1462     Node *cmpinty= _gvn.transform(new (C, 3) CmpDNode(doubleinty, y));
  1463     // Check if (y isn't int) then go to slow path
  1465     Node *bol2 = _gvn.transform( new (C, 2) BoolNode( cmpinty, BoolTest::ne ) );
  1466     // Branch either way
  1467     IfNode *if2 = create_and_xform_if(complex_path,bol2, PROB_STATIC_INFREQUENT, COUNT_UNKNOWN);
  1468     Node *slow_path = opt_iff(r,if2); // Set region path 2
  1470     // Calculate DPow(abs(x), y)*(1 & (int)y)
  1471     // Node for constant 1
  1472     Node *conone = intcon(1);
  1473     // 1& (int)y
  1474     Node *signnode= _gvn.transform( new (C, 3) AndINode(conone, inty) );
  1475     // zero node
  1476     Node *conzero = intcon(0);
  1477     // Check (1&(int)y)==0?
  1478     Node *cmpeq1 = _gvn.transform(new (C, 3) CmpINode(signnode, conzero));
  1479     // Check if (1&(int)y)!=0?, if so the result is negative
  1480     Node *bol3 = _gvn.transform( new (C, 2) BoolNode( cmpeq1, BoolTest::ne ) );
  1481     // abs(x)
  1482     Node *absx=_gvn.transform( new (C, 2) AbsDNode(x));
  1483     // abs(x)^y
  1484     Node *absxpowy = _gvn.transform( new (C, 3) PowDNode(0, y, absx) );
  1485     // -abs(x)^y
  1486     Node *negabsxpowy = _gvn.transform(new (C, 2) NegDNode (absxpowy));
  1487     // (1&(int)y)==1?-DPow(abs(x), y):DPow(abs(x), y)
  1488     Node *signresult = _gvn.transform( CMoveNode::make(C, NULL, bol3, absxpowy, negabsxpowy, Type::DOUBLE));
  1489     // Set complex path fast result
  1490     phi->init_req(2, signresult);
  1492     static const jlong nan_bits = CONST64(0x7ff8000000000000);
  1493     Node *slow_result = makecon(TypeD::make(*(double*)&nan_bits)); // return NaN
  1494     r->init_req(1,slow_path);
  1495     phi->init_req(1,slow_result);
  1497     // Post merge
  1498     set_control(_gvn.transform(r));
  1499     record_for_igvn(r);
  1500     result=_gvn.transform(phi);
  1503   //-------------------
  1504   //result=(result.isNaN())? uncommon_trap():result;
  1505   // Check: If isNaN() by checking result!=result? then go to Strict Math
  1506   Node* cmpisnan = _gvn.transform(new (C, 3) CmpDNode(result,result));
  1507   // Build the boolean node
  1508   Node* bolisnum = _gvn.transform( new (C, 2) BoolNode(cmpisnan, BoolTest::eq) );
  1510   { BuildCutout unless(this, bolisnum, PROB_STATIC_FREQUENT);
  1511     // End the current control-flow path
  1512     push_pair(x);
  1513     push_pair(y);
  1514     // Math.pow intrinsic returned a NaN, which requires StrictMath.pow
  1515     // to handle.  Recompile without intrinsifying Math.pow.
  1516     uncommon_trap(Deoptimization::Reason_intrinsic,
  1517                   Deoptimization::Action_make_not_entrant);
  1520   C->set_has_split_ifs(true); // Has chance for split-if optimization
  1522   push_pair(result);
  1524   return true;
  1527 //------------------------------inline_trans-------------------------------------
  1528 // Inline transcendental instructions, if possible.  The Intel hardware gets
  1529 // these right, no funny corner cases missed.
  1530 bool LibraryCallKit::inline_trans(vmIntrinsics::ID id) {
  1531   _sp += arg_size();        // restore stack pointer
  1532   Node* arg = pop_math_arg();
  1533   Node* trans = NULL;
  1535   switch (id) {
  1536   case vmIntrinsics::_dlog:
  1537     trans = _gvn.transform((Node*)new (C, 2) LogDNode(arg));
  1538     break;
  1539   case vmIntrinsics::_dlog10:
  1540     trans = _gvn.transform((Node*)new (C, 2) Log10DNode(arg));
  1541     break;
  1542   default:
  1543     assert(false, "bad intrinsic was passed in");
  1544     return false;
  1547   // Push result back on JVM stack
  1548   push_pair(trans);
  1549   return true;
  1552 //------------------------------runtime_math-----------------------------
  1553 bool LibraryCallKit::runtime_math(const TypeFunc* call_type, address funcAddr, const char* funcName) {
  1554   Node* a = NULL;
  1555   Node* b = NULL;
  1557   assert(call_type == OptoRuntime::Math_DD_D_Type() || call_type == OptoRuntime::Math_D_D_Type(),
  1558          "must be (DD)D or (D)D type");
  1560   // Inputs
  1561   _sp += arg_size();        // restore stack pointer
  1562   if (call_type == OptoRuntime::Math_DD_D_Type()) {
  1563     b = pop_math_arg();
  1565   a = pop_math_arg();
  1567   const TypePtr* no_memory_effects = NULL;
  1568   Node* trig = make_runtime_call(RC_LEAF, call_type, funcAddr, funcName,
  1569                                  no_memory_effects,
  1570                                  a, top(), b, b ? top() : NULL);
  1571   Node* value = _gvn.transform(new (C, 1) ProjNode(trig, TypeFunc::Parms+0));
  1572 #ifdef ASSERT
  1573   Node* value_top = _gvn.transform(new (C, 1) ProjNode(trig, TypeFunc::Parms+1));
  1574   assert(value_top == top(), "second value must be top");
  1575 #endif
  1577   push_pair(value);
  1578   return true;
  1581 //------------------------------inline_math_native-----------------------------
  1582 bool LibraryCallKit::inline_math_native(vmIntrinsics::ID id) {
  1583   switch (id) {
  1584     // These intrinsics are not properly supported on all hardware
  1585   case vmIntrinsics::_dcos: return Matcher::has_match_rule(Op_CosD) ? inline_trig(id) :
  1586     runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dcos), "COS");
  1587   case vmIntrinsics::_dsin: return Matcher::has_match_rule(Op_SinD) ? inline_trig(id) :
  1588     runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dsin), "SIN");
  1589   case vmIntrinsics::_dtan: return Matcher::has_match_rule(Op_TanD) ? inline_trig(id) :
  1590     runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dtan), "TAN");
  1592   case vmIntrinsics::_dlog:   return Matcher::has_match_rule(Op_LogD) ? inline_trans(id) :
  1593     runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dlog), "LOG");
  1594   case vmIntrinsics::_dlog10: return Matcher::has_match_rule(Op_Log10D) ? inline_trans(id) :
  1595     runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dlog10), "LOG10");
  1597     // These intrinsics are supported on all hardware
  1598   case vmIntrinsics::_dsqrt: return Matcher::has_match_rule(Op_SqrtD) ? inline_sqrt(id) : false;
  1599   case vmIntrinsics::_dabs:  return Matcher::has_match_rule(Op_AbsD)  ? inline_abs(id)  : false;
  1601     // These intrinsics don't work on X86.  The ad implementation doesn't
  1602     // handle NaN's properly.  Instead of returning infinity, the ad
  1603     // implementation returns a NaN on overflow. See bug: 6304089
  1604     // Once the ad implementations are fixed, change the code below
  1605     // to match the intrinsics above
  1607   case vmIntrinsics::_dexp:  return
  1608     runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dexp), "EXP");
  1609   case vmIntrinsics::_dpow:  return
  1610     runtime_math(OptoRuntime::Math_DD_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dpow), "POW");
  1612    // These intrinsics are not yet correctly implemented
  1613   case vmIntrinsics::_datan2:
  1614     return false;
  1616   default:
  1617     ShouldNotReachHere();
  1618     return false;
  1622 static bool is_simple_name(Node* n) {
  1623   return (n->req() == 1         // constant
  1624           || (n->is_Type() && n->as_Type()->type()->singleton())
  1625           || n->is_Proj()       // parameter or return value
  1626           || n->is_Phi()        // local of some sort
  1627           );
  1630 //----------------------------inline_min_max-----------------------------------
  1631 bool LibraryCallKit::inline_min_max(vmIntrinsics::ID id) {
  1632   push(generate_min_max(id, argument(0), argument(1)));
  1634   return true;
  1637 Node*
  1638 LibraryCallKit::generate_min_max(vmIntrinsics::ID id, Node* x0, Node* y0) {
  1639   // These are the candidate return value:
  1640   Node* xvalue = x0;
  1641   Node* yvalue = y0;
  1643   if (xvalue == yvalue) {
  1644     return xvalue;
  1647   bool want_max = (id == vmIntrinsics::_max);
  1649   const TypeInt* txvalue = _gvn.type(xvalue)->isa_int();
  1650   const TypeInt* tyvalue = _gvn.type(yvalue)->isa_int();
  1651   if (txvalue == NULL || tyvalue == NULL)  return top();
  1652   // This is not really necessary, but it is consistent with a
  1653   // hypothetical MaxINode::Value method:
  1654   int widen = MAX2(txvalue->_widen, tyvalue->_widen);
  1656   // %%% This folding logic should (ideally) be in a different place.
  1657   // Some should be inside IfNode, and there to be a more reliable
  1658   // transformation of ?: style patterns into cmoves.  We also want
  1659   // more powerful optimizations around cmove and min/max.
  1661   // Try to find a dominating comparison of these guys.
  1662   // It can simplify the index computation for Arrays.copyOf
  1663   // and similar uses of System.arraycopy.
  1664   // First, compute the normalized version of CmpI(x, y).
  1665   int   cmp_op = Op_CmpI;
  1666   Node* xkey = xvalue;
  1667   Node* ykey = yvalue;
  1668   Node* ideal_cmpxy = _gvn.transform( new(C, 3) CmpINode(xkey, ykey) );
  1669   if (ideal_cmpxy->is_Cmp()) {
  1670     // E.g., if we have CmpI(length - offset, count),
  1671     // it might idealize to CmpI(length, count + offset)
  1672     cmp_op = ideal_cmpxy->Opcode();
  1673     xkey = ideal_cmpxy->in(1);
  1674     ykey = ideal_cmpxy->in(2);
  1677   // Start by locating any relevant comparisons.
  1678   Node* start_from = (xkey->outcnt() < ykey->outcnt()) ? xkey : ykey;
  1679   Node* cmpxy = NULL;
  1680   Node* cmpyx = NULL;
  1681   for (DUIterator_Fast kmax, k = start_from->fast_outs(kmax); k < kmax; k++) {
  1682     Node* cmp = start_from->fast_out(k);
  1683     if (cmp->outcnt() > 0 &&            // must have prior uses
  1684         cmp->in(0) == NULL &&           // must be context-independent
  1685         cmp->Opcode() == cmp_op) {      // right kind of compare
  1686       if (cmp->in(1) == xkey && cmp->in(2) == ykey)  cmpxy = cmp;
  1687       if (cmp->in(1) == ykey && cmp->in(2) == xkey)  cmpyx = cmp;
  1691   const int NCMPS = 2;
  1692   Node* cmps[NCMPS] = { cmpxy, cmpyx };
  1693   int cmpn;
  1694   for (cmpn = 0; cmpn < NCMPS; cmpn++) {
  1695     if (cmps[cmpn] != NULL)  break;     // find a result
  1697   if (cmpn < NCMPS) {
  1698     // Look for a dominating test that tells us the min and max.
  1699     int depth = 0;                // Limit search depth for speed
  1700     Node* dom = control();
  1701     for (; dom != NULL; dom = IfNode::up_one_dom(dom, true)) {
  1702       if (++depth >= 100)  break;
  1703       Node* ifproj = dom;
  1704       if (!ifproj->is_Proj())  continue;
  1705       Node* iff = ifproj->in(0);
  1706       if (!iff->is_If())  continue;
  1707       Node* bol = iff->in(1);
  1708       if (!bol->is_Bool())  continue;
  1709       Node* cmp = bol->in(1);
  1710       if (cmp == NULL)  continue;
  1711       for (cmpn = 0; cmpn < NCMPS; cmpn++)
  1712         if (cmps[cmpn] == cmp)  break;
  1713       if (cmpn == NCMPS)  continue;
  1714       BoolTest::mask btest = bol->as_Bool()->_test._test;
  1715       if (ifproj->is_IfFalse())  btest = BoolTest(btest).negate();
  1716       if (cmp->in(1) == ykey)    btest = BoolTest(btest).commute();
  1717       // At this point, we know that 'x btest y' is true.
  1718       switch (btest) {
  1719       case BoolTest::eq:
  1720         // They are proven equal, so we can collapse the min/max.
  1721         // Either value is the answer.  Choose the simpler.
  1722         if (is_simple_name(yvalue) && !is_simple_name(xvalue))
  1723           return yvalue;
  1724         return xvalue;
  1725       case BoolTest::lt:          // x < y
  1726       case BoolTest::le:          // x <= y
  1727         return (want_max ? yvalue : xvalue);
  1728       case BoolTest::gt:          // x > y
  1729       case BoolTest::ge:          // x >= y
  1730         return (want_max ? xvalue : yvalue);
  1735   // We failed to find a dominating test.
  1736   // Let's pick a test that might GVN with prior tests.
  1737   Node*          best_bol   = NULL;
  1738   BoolTest::mask best_btest = BoolTest::illegal;
  1739   for (cmpn = 0; cmpn < NCMPS; cmpn++) {
  1740     Node* cmp = cmps[cmpn];
  1741     if (cmp == NULL)  continue;
  1742     for (DUIterator_Fast jmax, j = cmp->fast_outs(jmax); j < jmax; j++) {
  1743       Node* bol = cmp->fast_out(j);
  1744       if (!bol->is_Bool())  continue;
  1745       BoolTest::mask btest = bol->as_Bool()->_test._test;
  1746       if (btest == BoolTest::eq || btest == BoolTest::ne)  continue;
  1747       if (cmp->in(1) == ykey)   btest = BoolTest(btest).commute();
  1748       if (bol->outcnt() > (best_bol == NULL ? 0 : best_bol->outcnt())) {
  1749         best_bol   = bol->as_Bool();
  1750         best_btest = btest;
  1755   Node* answer_if_true  = NULL;
  1756   Node* answer_if_false = NULL;
  1757   switch (best_btest) {
  1758   default:
  1759     if (cmpxy == NULL)
  1760       cmpxy = ideal_cmpxy;
  1761     best_bol = _gvn.transform( new(C, 2) BoolNode(cmpxy, BoolTest::lt) );
  1762     // and fall through:
  1763   case BoolTest::lt:          // x < y
  1764   case BoolTest::le:          // x <= y
  1765     answer_if_true  = (want_max ? yvalue : xvalue);
  1766     answer_if_false = (want_max ? xvalue : yvalue);
  1767     break;
  1768   case BoolTest::gt:          // x > y
  1769   case BoolTest::ge:          // x >= y
  1770     answer_if_true  = (want_max ? xvalue : yvalue);
  1771     answer_if_false = (want_max ? yvalue : xvalue);
  1772     break;
  1775   jint hi, lo;
  1776   if (want_max) {
  1777     // We can sharpen the minimum.
  1778     hi = MAX2(txvalue->_hi, tyvalue->_hi);
  1779     lo = MAX2(txvalue->_lo, tyvalue->_lo);
  1780   } else {
  1781     // We can sharpen the maximum.
  1782     hi = MIN2(txvalue->_hi, tyvalue->_hi);
  1783     lo = MIN2(txvalue->_lo, tyvalue->_lo);
  1786   // Use a flow-free graph structure, to avoid creating excess control edges
  1787   // which could hinder other optimizations.
  1788   // Since Math.min/max is often used with arraycopy, we want
  1789   // tightly_coupled_allocation to be able to see beyond min/max expressions.
  1790   Node* cmov = CMoveNode::make(C, NULL, best_bol,
  1791                                answer_if_false, answer_if_true,
  1792                                TypeInt::make(lo, hi, widen));
  1794   return _gvn.transform(cmov);
  1796   /*
  1797   // This is not as desirable as it may seem, since Min and Max
  1798   // nodes do not have a full set of optimizations.
  1799   // And they would interfere, anyway, with 'if' optimizations
  1800   // and with CMoveI canonical forms.
  1801   switch (id) {
  1802   case vmIntrinsics::_min:
  1803     result_val = _gvn.transform(new (C, 3) MinINode(x,y)); break;
  1804   case vmIntrinsics::_max:
  1805     result_val = _gvn.transform(new (C, 3) MaxINode(x,y)); break;
  1806   default:
  1807     ShouldNotReachHere();
  1809   */
  1812 inline int
  1813 LibraryCallKit::classify_unsafe_addr(Node* &base, Node* &offset) {
  1814   const TypePtr* base_type = TypePtr::NULL_PTR;
  1815   if (base != NULL)  base_type = _gvn.type(base)->isa_ptr();
  1816   if (base_type == NULL) {
  1817     // Unknown type.
  1818     return Type::AnyPtr;
  1819   } else if (base_type == TypePtr::NULL_PTR) {
  1820     // Since this is a NULL+long form, we have to switch to a rawptr.
  1821     base   = _gvn.transform( new (C, 2) CastX2PNode(offset) );
  1822     offset = MakeConX(0);
  1823     return Type::RawPtr;
  1824   } else if (base_type->base() == Type::RawPtr) {
  1825     return Type::RawPtr;
  1826   } else if (base_type->isa_oopptr()) {
  1827     // Base is never null => always a heap address.
  1828     if (base_type->ptr() == TypePtr::NotNull) {
  1829       return Type::OopPtr;
  1831     // Offset is small => always a heap address.
  1832     const TypeX* offset_type = _gvn.type(offset)->isa_intptr_t();
  1833     if (offset_type != NULL &&
  1834         base_type->offset() == 0 &&     // (should always be?)
  1835         offset_type->_lo >= 0 &&
  1836         !MacroAssembler::needs_explicit_null_check(offset_type->_hi)) {
  1837       return Type::OopPtr;
  1839     // Otherwise, it might either be oop+off or NULL+addr.
  1840     return Type::AnyPtr;
  1841   } else {
  1842     // No information:
  1843     return Type::AnyPtr;
  1847 inline Node* LibraryCallKit::make_unsafe_address(Node* base, Node* offset) {
  1848   int kind = classify_unsafe_addr(base, offset);
  1849   if (kind == Type::RawPtr) {
  1850     return basic_plus_adr(top(), base, offset);
  1851   } else {
  1852     return basic_plus_adr(base, offset);
  1856 //-------------------inline_numberOfLeadingZeros_int/long-----------------------
  1857 // inline int Integer.numberOfLeadingZeros(int)
  1858 // inline int Long.numberOfLeadingZeros(long)
  1859 bool LibraryCallKit::inline_numberOfLeadingZeros(vmIntrinsics::ID id) {
  1860   assert(id == vmIntrinsics::_numberOfLeadingZeros_i || id == vmIntrinsics::_numberOfLeadingZeros_l, "not numberOfLeadingZeros");
  1861   if (id == vmIntrinsics::_numberOfLeadingZeros_i && !Matcher::match_rule_supported(Op_CountLeadingZerosI)) return false;
  1862   if (id == vmIntrinsics::_numberOfLeadingZeros_l && !Matcher::match_rule_supported(Op_CountLeadingZerosL)) return false;
  1863   _sp += arg_size();  // restore stack pointer
  1864   switch (id) {
  1865   case vmIntrinsics::_numberOfLeadingZeros_i:
  1866     push(_gvn.transform(new (C, 2) CountLeadingZerosINode(pop())));
  1867     break;
  1868   case vmIntrinsics::_numberOfLeadingZeros_l:
  1869     push(_gvn.transform(new (C, 2) CountLeadingZerosLNode(pop_pair())));
  1870     break;
  1871   default:
  1872     ShouldNotReachHere();
  1874   return true;
  1877 //-------------------inline_numberOfTrailingZeros_int/long----------------------
  1878 // inline int Integer.numberOfTrailingZeros(int)
  1879 // inline int Long.numberOfTrailingZeros(long)
  1880 bool LibraryCallKit::inline_numberOfTrailingZeros(vmIntrinsics::ID id) {
  1881   assert(id == vmIntrinsics::_numberOfTrailingZeros_i || id == vmIntrinsics::_numberOfTrailingZeros_l, "not numberOfTrailingZeros");
  1882   if (id == vmIntrinsics::_numberOfTrailingZeros_i && !Matcher::match_rule_supported(Op_CountTrailingZerosI)) return false;
  1883   if (id == vmIntrinsics::_numberOfTrailingZeros_l && !Matcher::match_rule_supported(Op_CountTrailingZerosL)) return false;
  1884   _sp += arg_size();  // restore stack pointer
  1885   switch (id) {
  1886   case vmIntrinsics::_numberOfTrailingZeros_i:
  1887     push(_gvn.transform(new (C, 2) CountTrailingZerosINode(pop())));
  1888     break;
  1889   case vmIntrinsics::_numberOfTrailingZeros_l:
  1890     push(_gvn.transform(new (C, 2) CountTrailingZerosLNode(pop_pair())));
  1891     break;
  1892   default:
  1893     ShouldNotReachHere();
  1895   return true;
  1898 //----------------------------inline_bitCount_int/long-----------------------
  1899 // inline int Integer.bitCount(int)
  1900 // inline int Long.bitCount(long)
  1901 bool LibraryCallKit::inline_bitCount(vmIntrinsics::ID id) {
  1902   assert(id == vmIntrinsics::_bitCount_i || id == vmIntrinsics::_bitCount_l, "not bitCount");
  1903   if (id == vmIntrinsics::_bitCount_i && !Matcher::has_match_rule(Op_PopCountI)) return false;
  1904   if (id == vmIntrinsics::_bitCount_l && !Matcher::has_match_rule(Op_PopCountL)) return false;
  1905   _sp += arg_size();  // restore stack pointer
  1906   switch (id) {
  1907   case vmIntrinsics::_bitCount_i:
  1908     push(_gvn.transform(new (C, 2) PopCountINode(pop())));
  1909     break;
  1910   case vmIntrinsics::_bitCount_l:
  1911     push(_gvn.transform(new (C, 2) PopCountLNode(pop_pair())));
  1912     break;
  1913   default:
  1914     ShouldNotReachHere();
  1916   return true;
  1919 //----------------------------inline_reverseBytes_int/long-------------------
  1920 // inline Integer.reverseBytes(int)
  1921 // inline Long.reverseBytes(long)
  1922 bool LibraryCallKit::inline_reverseBytes(vmIntrinsics::ID id) {
  1923   assert(id == vmIntrinsics::_reverseBytes_i || id == vmIntrinsics::_reverseBytes_l, "not reverse Bytes");
  1924   if (id == vmIntrinsics::_reverseBytes_i && !Matcher::has_match_rule(Op_ReverseBytesI)) return false;
  1925   if (id == vmIntrinsics::_reverseBytes_l && !Matcher::has_match_rule(Op_ReverseBytesL)) return false;
  1926   _sp += arg_size();        // restore stack pointer
  1927   switch (id) {
  1928   case vmIntrinsics::_reverseBytes_i:
  1929     push(_gvn.transform(new (C, 2) ReverseBytesINode(0, pop())));
  1930     break;
  1931   case vmIntrinsics::_reverseBytes_l:
  1932     push_pair(_gvn.transform(new (C, 2) ReverseBytesLNode(0, pop_pair())));
  1933     break;
  1934   default:
  1937   return true;
  1940 //----------------------------inline_unsafe_access----------------------------
  1942 const static BasicType T_ADDRESS_HOLDER = T_LONG;
  1944 // Interpret Unsafe.fieldOffset cookies correctly:
  1945 extern jlong Unsafe_field_offset_to_byte_offset(jlong field_offset);
  1947 bool LibraryCallKit::inline_unsafe_access(bool is_native_ptr, bool is_store, BasicType type, bool is_volatile) {
  1948   if (callee()->is_static())  return false;  // caller must have the capability!
  1950 #ifndef PRODUCT
  1952     ResourceMark rm;
  1953     // Check the signatures.
  1954     ciSignature* sig = signature();
  1955 #ifdef ASSERT
  1956     if (!is_store) {
  1957       // Object getObject(Object base, int/long offset), etc.
  1958       BasicType rtype = sig->return_type()->basic_type();
  1959       if (rtype == T_ADDRESS_HOLDER && callee()->name() == ciSymbol::getAddress_name())
  1960           rtype = T_ADDRESS;  // it is really a C void*
  1961       assert(rtype == type, "getter must return the expected value");
  1962       if (!is_native_ptr) {
  1963         assert(sig->count() == 2, "oop getter has 2 arguments");
  1964         assert(sig->type_at(0)->basic_type() == T_OBJECT, "getter base is object");
  1965         assert(sig->type_at(1)->basic_type() == T_LONG, "getter offset is correct");
  1966       } else {
  1967         assert(sig->count() == 1, "native getter has 1 argument");
  1968         assert(sig->type_at(0)->basic_type() == T_LONG, "getter base is long");
  1970     } else {
  1971       // void putObject(Object base, int/long offset, Object x), etc.
  1972       assert(sig->return_type()->basic_type() == T_VOID, "putter must not return a value");
  1973       if (!is_native_ptr) {
  1974         assert(sig->count() == 3, "oop putter has 3 arguments");
  1975         assert(sig->type_at(0)->basic_type() == T_OBJECT, "putter base is object");
  1976         assert(sig->type_at(1)->basic_type() == T_LONG, "putter offset is correct");
  1977       } else {
  1978         assert(sig->count() == 2, "native putter has 2 arguments");
  1979         assert(sig->type_at(0)->basic_type() == T_LONG, "putter base is long");
  1981       BasicType vtype = sig->type_at(sig->count()-1)->basic_type();
  1982       if (vtype == T_ADDRESS_HOLDER && callee()->name() == ciSymbol::putAddress_name())
  1983         vtype = T_ADDRESS;  // it is really a C void*
  1984       assert(vtype == type, "putter must accept the expected value");
  1986 #endif // ASSERT
  1988 #endif //PRODUCT
  1990   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
  1992   int type_words = type2size[ (type == T_ADDRESS) ? T_LONG : type ];
  1994   // Argument words:  "this" plus (oop/offset) or (lo/hi) args plus maybe 1 or 2 value words
  1995   int nargs = 1 + (is_native_ptr ? 2 : 3) + (is_store ? type_words : 0);
  1997   debug_only(int saved_sp = _sp);
  1998   _sp += nargs;
  2000   Node* val;
  2001   debug_only(val = (Node*)(uintptr_t)-1);
  2004   if (is_store) {
  2005     // Get the value being stored.  (Pop it first; it was pushed last.)
  2006     switch (type) {
  2007     case T_DOUBLE:
  2008     case T_LONG:
  2009     case T_ADDRESS:
  2010       val = pop_pair();
  2011       break;
  2012     default:
  2013       val = pop();
  2017   // Build address expression.  See the code in inline_unsafe_prefetch.
  2018   Node *adr;
  2019   Node *heap_base_oop = top();
  2020   if (!is_native_ptr) {
  2021     // The offset is a value produced by Unsafe.staticFieldOffset or Unsafe.objectFieldOffset
  2022     Node* offset = pop_pair();
  2023     // The base is either a Java object or a value produced by Unsafe.staticFieldBase
  2024     Node* base   = pop();
  2025     // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
  2026     // to be plain byte offsets, which are also the same as those accepted
  2027     // by oopDesc::field_base.
  2028     assert(Unsafe_field_offset_to_byte_offset(11) == 11,
  2029            "fieldOffset must be byte-scaled");
  2030     // 32-bit machines ignore the high half!
  2031     offset = ConvL2X(offset);
  2032     adr = make_unsafe_address(base, offset);
  2033     heap_base_oop = base;
  2034   } else {
  2035     Node* ptr = pop_pair();
  2036     // Adjust Java long to machine word:
  2037     ptr = ConvL2X(ptr);
  2038     adr = make_unsafe_address(NULL, ptr);
  2041   // Pop receiver last:  it was pushed first.
  2042   Node *receiver = pop();
  2044   assert(saved_sp == _sp, "must have correct argument count");
  2046   const TypePtr *adr_type = _gvn.type(adr)->isa_ptr();
  2048   // First guess at the value type.
  2049   const Type *value_type = Type::get_const_basic_type(type);
  2051   // Try to categorize the address.  If it comes up as TypeJavaPtr::BOTTOM,
  2052   // there was not enough information to nail it down.
  2053   Compile::AliasType* alias_type = C->alias_type(adr_type);
  2054   assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
  2056   // We will need memory barriers unless we can determine a unique
  2057   // alias category for this reference.  (Note:  If for some reason
  2058   // the barriers get omitted and the unsafe reference begins to "pollute"
  2059   // the alias analysis of the rest of the graph, either Compile::can_alias
  2060   // or Compile::must_alias will throw a diagnostic assert.)
  2061   bool need_mem_bar = (alias_type->adr_type() == TypeOopPtr::BOTTOM);
  2063   if (!is_store && type == T_OBJECT) {
  2064     // Attempt to infer a sharper value type from the offset and base type.
  2065     ciKlass* sharpened_klass = NULL;
  2067     // See if it is an instance field, with an object type.
  2068     if (alias_type->field() != NULL) {
  2069       assert(!is_native_ptr, "native pointer op cannot use a java address");
  2070       if (alias_type->field()->type()->is_klass()) {
  2071         sharpened_klass = alias_type->field()->type()->as_klass();
  2075     // See if it is a narrow oop array.
  2076     if (adr_type->isa_aryptr()) {
  2077       if (adr_type->offset() >= objArrayOopDesc::base_offset_in_bytes(type)) {
  2078         const TypeOopPtr *elem_type = adr_type->is_aryptr()->elem()->isa_oopptr();
  2079         if (elem_type != NULL) {
  2080           sharpened_klass = elem_type->klass();
  2085     if (sharpened_klass != NULL) {
  2086       const TypeOopPtr* tjp = TypeOopPtr::make_from_klass(sharpened_klass);
  2088       // Sharpen the value type.
  2089       value_type = tjp;
  2091 #ifndef PRODUCT
  2092       if (PrintIntrinsics || PrintInlining || PrintOptoInlining) {
  2093         tty->print("  from base type:  ");   adr_type->dump();
  2094         tty->print("  sharpened value: "); value_type->dump();
  2096 #endif
  2100   // Null check on self without removing any arguments.  The argument
  2101   // null check technically happens in the wrong place, which can lead to
  2102   // invalid stack traces when the primitive is inlined into a method
  2103   // which handles NullPointerExceptions.
  2104   _sp += nargs;
  2105   do_null_check(receiver, T_OBJECT);
  2106   _sp -= nargs;
  2107   if (stopped()) {
  2108     return true;
  2110   // Heap pointers get a null-check from the interpreter,
  2111   // as a courtesy.  However, this is not guaranteed by Unsafe,
  2112   // and it is not possible to fully distinguish unintended nulls
  2113   // from intended ones in this API.
  2115   if (is_volatile) {
  2116     // We need to emit leading and trailing CPU membars (see below) in
  2117     // addition to memory membars when is_volatile. This is a little
  2118     // too strong, but avoids the need to insert per-alias-type
  2119     // volatile membars (for stores; compare Parse::do_put_xxx), which
  2120     // we cannot do effectively here because we probably only have a
  2121     // rough approximation of type.
  2122     need_mem_bar = true;
  2123     // For Stores, place a memory ordering barrier now.
  2124     if (is_store)
  2125       insert_mem_bar(Op_MemBarRelease);
  2128   // Memory barrier to prevent normal and 'unsafe' accesses from
  2129   // bypassing each other.  Happens after null checks, so the
  2130   // exception paths do not take memory state from the memory barrier,
  2131   // so there's no problems making a strong assert about mixing users
  2132   // of safe & unsafe memory.  Otherwise fails in a CTW of rt.jar
  2133   // around 5701, class sun/reflect/UnsafeBooleanFieldAccessorImpl.
  2134   if (need_mem_bar) insert_mem_bar(Op_MemBarCPUOrder);
  2136   if (!is_store) {
  2137     Node* p = make_load(control(), adr, value_type, type, adr_type, is_volatile);
  2138     // load value and push onto stack
  2139     switch (type) {
  2140     case T_BOOLEAN:
  2141     case T_CHAR:
  2142     case T_BYTE:
  2143     case T_SHORT:
  2144     case T_INT:
  2145     case T_FLOAT:
  2146     case T_OBJECT:
  2147       push( p );
  2148       break;
  2149     case T_ADDRESS:
  2150       // Cast to an int type.
  2151       p = _gvn.transform( new (C, 2) CastP2XNode(NULL,p) );
  2152       p = ConvX2L(p);
  2153       push_pair(p);
  2154       break;
  2155     case T_DOUBLE:
  2156     case T_LONG:
  2157       push_pair( p );
  2158       break;
  2159     default: ShouldNotReachHere();
  2161   } else {
  2162     // place effect of store into memory
  2163     switch (type) {
  2164     case T_DOUBLE:
  2165       val = dstore_rounding(val);
  2166       break;
  2167     case T_ADDRESS:
  2168       // Repackage the long as a pointer.
  2169       val = ConvL2X(val);
  2170       val = _gvn.transform( new (C, 2) CastX2PNode(val) );
  2171       break;
  2174     if (type != T_OBJECT ) {
  2175       (void) store_to_memory(control(), adr, val, type, adr_type, is_volatile);
  2176     } else {
  2177       // Possibly an oop being stored to Java heap or native memory
  2178       if (!TypePtr::NULL_PTR->higher_equal(_gvn.type(heap_base_oop))) {
  2179         // oop to Java heap.
  2180         (void) store_oop_to_unknown(control(), heap_base_oop, adr, adr_type, val, type);
  2181       } else {
  2182         // We can't tell at compile time if we are storing in the Java heap or outside
  2183         // of it. So we need to emit code to conditionally do the proper type of
  2184         // store.
  2186         IdealKit ideal(gvn(), control(),  merged_memory());
  2187 #define __ ideal.
  2188         // QQQ who knows what probability is here??
  2189         __ if_then(heap_base_oop, BoolTest::ne, null(), PROB_UNLIKELY(0.999)); {
  2190           // Sync IdealKit and graphKit.
  2191           set_all_memory( __ merged_memory());
  2192           set_control(__ ctrl());
  2193           Node* st = store_oop_to_unknown(control(), heap_base_oop, adr, adr_type, val, type);
  2194           // Update IdealKit memory.
  2195           __ set_all_memory(merged_memory());
  2196           __ set_ctrl(control());
  2197         } __ else_(); {
  2198           __ store(__ ctrl(), adr, val, type, alias_type->index(), is_volatile);
  2199         } __ end_if();
  2200         // Final sync IdealKit and GraphKit.
  2201         sync_kit(ideal);
  2202 #undef __
  2207   if (is_volatile) {
  2208     if (!is_store)
  2209       insert_mem_bar(Op_MemBarAcquire);
  2210     else
  2211       insert_mem_bar(Op_MemBarVolatile);
  2214   if (need_mem_bar) insert_mem_bar(Op_MemBarCPUOrder);
  2216   return true;
  2219 //----------------------------inline_unsafe_prefetch----------------------------
  2221 bool LibraryCallKit::inline_unsafe_prefetch(bool is_native_ptr, bool is_store, bool is_static) {
  2222 #ifndef PRODUCT
  2224     ResourceMark rm;
  2225     // Check the signatures.
  2226     ciSignature* sig = signature();
  2227 #ifdef ASSERT
  2228     // Object getObject(Object base, int/long offset), etc.
  2229     BasicType rtype = sig->return_type()->basic_type();
  2230     if (!is_native_ptr) {
  2231       assert(sig->count() == 2, "oop prefetch has 2 arguments");
  2232       assert(sig->type_at(0)->basic_type() == T_OBJECT, "prefetch base is object");
  2233       assert(sig->type_at(1)->basic_type() == T_LONG, "prefetcha offset is correct");
  2234     } else {
  2235       assert(sig->count() == 1, "native prefetch has 1 argument");
  2236       assert(sig->type_at(0)->basic_type() == T_LONG, "prefetch base is long");
  2238 #endif // ASSERT
  2240 #endif // !PRODUCT
  2242   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
  2244   // Argument words:  "this" if not static, plus (oop/offset) or (lo/hi) args
  2245   int nargs = (is_static ? 0 : 1) + (is_native_ptr ? 2 : 3);
  2247   debug_only(int saved_sp = _sp);
  2248   _sp += nargs;
  2250   // Build address expression.  See the code in inline_unsafe_access.
  2251   Node *adr;
  2252   if (!is_native_ptr) {
  2253     // The offset is a value produced by Unsafe.staticFieldOffset or Unsafe.objectFieldOffset
  2254     Node* offset = pop_pair();
  2255     // The base is either a Java object or a value produced by Unsafe.staticFieldBase
  2256     Node* base   = pop();
  2257     // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
  2258     // to be plain byte offsets, which are also the same as those accepted
  2259     // by oopDesc::field_base.
  2260     assert(Unsafe_field_offset_to_byte_offset(11) == 11,
  2261            "fieldOffset must be byte-scaled");
  2262     // 32-bit machines ignore the high half!
  2263     offset = ConvL2X(offset);
  2264     adr = make_unsafe_address(base, offset);
  2265   } else {
  2266     Node* ptr = pop_pair();
  2267     // Adjust Java long to machine word:
  2268     ptr = ConvL2X(ptr);
  2269     adr = make_unsafe_address(NULL, ptr);
  2272   if (is_static) {
  2273     assert(saved_sp == _sp, "must have correct argument count");
  2274   } else {
  2275     // Pop receiver last:  it was pushed first.
  2276     Node *receiver = pop();
  2277     assert(saved_sp == _sp, "must have correct argument count");
  2279     // Null check on self without removing any arguments.  The argument
  2280     // null check technically happens in the wrong place, which can lead to
  2281     // invalid stack traces when the primitive is inlined into a method
  2282     // which handles NullPointerExceptions.
  2283     _sp += nargs;
  2284     do_null_check(receiver, T_OBJECT);
  2285     _sp -= nargs;
  2286     if (stopped()) {
  2287       return true;
  2291   // Generate the read or write prefetch
  2292   Node *prefetch;
  2293   if (is_store) {
  2294     prefetch = new (C, 3) PrefetchWriteNode(i_o(), adr);
  2295   } else {
  2296     prefetch = new (C, 3) PrefetchReadNode(i_o(), adr);
  2298   prefetch->init_req(0, control());
  2299   set_i_o(_gvn.transform(prefetch));
  2301   return true;
  2304 //----------------------------inline_unsafe_CAS----------------------------
  2306 bool LibraryCallKit::inline_unsafe_CAS(BasicType type) {
  2307   // This basic scheme here is the same as inline_unsafe_access, but
  2308   // differs in enough details that combining them would make the code
  2309   // overly confusing.  (This is a true fact! I originally combined
  2310   // them, but even I was confused by it!) As much code/comments as
  2311   // possible are retained from inline_unsafe_access though to make
  2312   // the correspondences clearer. - dl
  2314   if (callee()->is_static())  return false;  // caller must have the capability!
  2316 #ifndef PRODUCT
  2318     ResourceMark rm;
  2319     // Check the signatures.
  2320     ciSignature* sig = signature();
  2321 #ifdef ASSERT
  2322     BasicType rtype = sig->return_type()->basic_type();
  2323     assert(rtype == T_BOOLEAN, "CAS must return boolean");
  2324     assert(sig->count() == 4, "CAS has 4 arguments");
  2325     assert(sig->type_at(0)->basic_type() == T_OBJECT, "CAS base is object");
  2326     assert(sig->type_at(1)->basic_type() == T_LONG, "CAS offset is long");
  2327 #endif // ASSERT
  2329 #endif //PRODUCT
  2331   // number of stack slots per value argument (1 or 2)
  2332   int type_words = type2size[type];
  2334   // Cannot inline wide CAS on machines that don't support it natively
  2335   if (type2aelembytes(type) > BytesPerInt && !VM_Version::supports_cx8())
  2336     return false;
  2338   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
  2340   // Argument words:  "this" plus oop plus offset plus oldvalue plus newvalue;
  2341   int nargs = 1 + 1 + 2  + type_words + type_words;
  2343   // pop arguments: newval, oldval, offset, base, and receiver
  2344   debug_only(int saved_sp = _sp);
  2345   _sp += nargs;
  2346   Node* newval   = (type_words == 1) ? pop() : pop_pair();
  2347   Node* oldval   = (type_words == 1) ? pop() : pop_pair();
  2348   Node *offset   = pop_pair();
  2349   Node *base     = pop();
  2350   Node *receiver = pop();
  2351   assert(saved_sp == _sp, "must have correct argument count");
  2353   //  Null check receiver.
  2354   _sp += nargs;
  2355   do_null_check(receiver, T_OBJECT);
  2356   _sp -= nargs;
  2357   if (stopped()) {
  2358     return true;
  2361   // Build field offset expression.
  2362   // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
  2363   // to be plain byte offsets, which are also the same as those accepted
  2364   // by oopDesc::field_base.
  2365   assert(Unsafe_field_offset_to_byte_offset(11) == 11, "fieldOffset must be byte-scaled");
  2366   // 32-bit machines ignore the high half of long offsets
  2367   offset = ConvL2X(offset);
  2368   Node* adr = make_unsafe_address(base, offset);
  2369   const TypePtr *adr_type = _gvn.type(adr)->isa_ptr();
  2371   // (Unlike inline_unsafe_access, there seems no point in trying
  2372   // to refine types. Just use the coarse types here.
  2373   const Type *value_type = Type::get_const_basic_type(type);
  2374   Compile::AliasType* alias_type = C->alias_type(adr_type);
  2375   assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
  2376   int alias_idx = C->get_alias_index(adr_type);
  2378   // Memory-model-wise, a CAS acts like a little synchronized block,
  2379   // so needs barriers on each side.  These don't translate into
  2380   // actual barriers on most machines, but we still need rest of
  2381   // compiler to respect ordering.
  2383   insert_mem_bar(Op_MemBarRelease);
  2384   insert_mem_bar(Op_MemBarCPUOrder);
  2386   // 4984716: MemBars must be inserted before this
  2387   //          memory node in order to avoid a false
  2388   //          dependency which will confuse the scheduler.
  2389   Node *mem = memory(alias_idx);
  2391   // For now, we handle only those cases that actually exist: ints,
  2392   // longs, and Object. Adding others should be straightforward.
  2393   Node* cas;
  2394   switch(type) {
  2395   case T_INT:
  2396     cas = _gvn.transform(new (C, 5) CompareAndSwapINode(control(), mem, adr, newval, oldval));
  2397     break;
  2398   case T_LONG:
  2399     cas = _gvn.transform(new (C, 5) CompareAndSwapLNode(control(), mem, adr, newval, oldval));
  2400     break;
  2401   case T_OBJECT:
  2402      // reference stores need a store barrier.
  2403     // (They don't if CAS fails, but it isn't worth checking.)
  2404     pre_barrier(control(), base, adr, alias_idx, newval, value_type->make_oopptr(), T_OBJECT);
  2405 #ifdef _LP64
  2406     if (adr->bottom_type()->is_ptr_to_narrowoop()) {
  2407       Node *newval_enc = _gvn.transform(new (C, 2) EncodePNode(newval, newval->bottom_type()->make_narrowoop()));
  2408       Node *oldval_enc = _gvn.transform(new (C, 2) EncodePNode(oldval, oldval->bottom_type()->make_narrowoop()));
  2409       cas = _gvn.transform(new (C, 5) CompareAndSwapNNode(control(), mem, adr,
  2410                                                           newval_enc, oldval_enc));
  2411     } else
  2412 #endif
  2414       cas = _gvn.transform(new (C, 5) CompareAndSwapPNode(control(), mem, adr, newval, oldval));
  2416     post_barrier(control(), cas, base, adr, alias_idx, newval, T_OBJECT, true);
  2417     break;
  2418   default:
  2419     ShouldNotReachHere();
  2420     break;
  2423   // SCMemProjNodes represent the memory state of CAS. Their main
  2424   // role is to prevent CAS nodes from being optimized away when their
  2425   // results aren't used.
  2426   Node* proj = _gvn.transform( new (C, 1) SCMemProjNode(cas));
  2427   set_memory(proj, alias_idx);
  2429   // Add the trailing membar surrounding the access
  2430   insert_mem_bar(Op_MemBarCPUOrder);
  2431   insert_mem_bar(Op_MemBarAcquire);
  2433   push(cas);
  2434   return true;
  2437 bool LibraryCallKit::inline_unsafe_ordered_store(BasicType type) {
  2438   // This is another variant of inline_unsafe_access, differing in
  2439   // that it always issues store-store ("release") barrier and ensures
  2440   // store-atomicity (which only matters for "long").
  2442   if (callee()->is_static())  return false;  // caller must have the capability!
  2444 #ifndef PRODUCT
  2446     ResourceMark rm;
  2447     // Check the signatures.
  2448     ciSignature* sig = signature();
  2449 #ifdef ASSERT
  2450     BasicType rtype = sig->return_type()->basic_type();
  2451     assert(rtype == T_VOID, "must return void");
  2452     assert(sig->count() == 3, "has 3 arguments");
  2453     assert(sig->type_at(0)->basic_type() == T_OBJECT, "base is object");
  2454     assert(sig->type_at(1)->basic_type() == T_LONG, "offset is long");
  2455 #endif // ASSERT
  2457 #endif //PRODUCT
  2459   // number of stack slots per value argument (1 or 2)
  2460   int type_words = type2size[type];
  2462   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
  2464   // Argument words:  "this" plus oop plus offset plus value;
  2465   int nargs = 1 + 1 + 2 + type_words;
  2467   // pop arguments: val, offset, base, and receiver
  2468   debug_only(int saved_sp = _sp);
  2469   _sp += nargs;
  2470   Node* val      = (type_words == 1) ? pop() : pop_pair();
  2471   Node *offset   = pop_pair();
  2472   Node *base     = pop();
  2473   Node *receiver = pop();
  2474   assert(saved_sp == _sp, "must have correct argument count");
  2476   //  Null check receiver.
  2477   _sp += nargs;
  2478   do_null_check(receiver, T_OBJECT);
  2479   _sp -= nargs;
  2480   if (stopped()) {
  2481     return true;
  2484   // Build field offset expression.
  2485   assert(Unsafe_field_offset_to_byte_offset(11) == 11, "fieldOffset must be byte-scaled");
  2486   // 32-bit machines ignore the high half of long offsets
  2487   offset = ConvL2X(offset);
  2488   Node* adr = make_unsafe_address(base, offset);
  2489   const TypePtr *adr_type = _gvn.type(adr)->isa_ptr();
  2490   const Type *value_type = Type::get_const_basic_type(type);
  2491   Compile::AliasType* alias_type = C->alias_type(adr_type);
  2493   insert_mem_bar(Op_MemBarRelease);
  2494   insert_mem_bar(Op_MemBarCPUOrder);
  2495   // Ensure that the store is atomic for longs:
  2496   bool require_atomic_access = true;
  2497   Node* store;
  2498   if (type == T_OBJECT) // reference stores need a store barrier.
  2499     store = store_oop_to_unknown(control(), base, adr, adr_type, val, type);
  2500   else {
  2501     store = store_to_memory(control(), adr, val, type, adr_type, require_atomic_access);
  2503   insert_mem_bar(Op_MemBarCPUOrder);
  2504   return true;
  2507 bool LibraryCallKit::inline_unsafe_allocate() {
  2508   if (callee()->is_static())  return false;  // caller must have the capability!
  2509   int nargs = 1 + 1;
  2510   assert(signature()->size() == nargs-1, "alloc has 1 argument");
  2511   null_check_receiver(callee());  // check then ignore argument(0)
  2512   _sp += nargs;  // set original stack for use by uncommon_trap
  2513   Node* cls = do_null_check(argument(1), T_OBJECT);
  2514   _sp -= nargs;
  2515   if (stopped())  return true;
  2517   Node* kls = load_klass_from_mirror(cls, false, nargs, NULL, 0);
  2518   _sp += nargs;  // set original stack for use by uncommon_trap
  2519   kls = do_null_check(kls, T_OBJECT);
  2520   _sp -= nargs;
  2521   if (stopped())  return true;  // argument was like int.class
  2523   // Note:  The argument might still be an illegal value like
  2524   // Serializable.class or Object[].class.   The runtime will handle it.
  2525   // But we must make an explicit check for initialization.
  2526   Node* insp = basic_plus_adr(kls, instanceKlass::init_state_offset_in_bytes() + sizeof(oopDesc));
  2527   Node* inst = make_load(NULL, insp, TypeInt::INT, T_INT);
  2528   Node* bits = intcon(instanceKlass::fully_initialized);
  2529   Node* test = _gvn.transform( new (C, 3) SubINode(inst, bits) );
  2530   // The 'test' is non-zero if we need to take a slow path.
  2532   Node* obj = new_instance(kls, test);
  2533   push(obj);
  2535   return true;
  2538 //------------------------inline_native_time_funcs--------------
  2539 // inline code for System.currentTimeMillis() and System.nanoTime()
  2540 // these have the same type and signature
  2541 bool LibraryCallKit::inline_native_time_funcs(bool isNano) {
  2542   address funcAddr = isNano ? CAST_FROM_FN_PTR(address, os::javaTimeNanos) :
  2543                               CAST_FROM_FN_PTR(address, os::javaTimeMillis);
  2544   const char * funcName = isNano ? "nanoTime" : "currentTimeMillis";
  2545   const TypeFunc *tf = OptoRuntime::current_time_millis_Type();
  2546   const TypePtr* no_memory_effects = NULL;
  2547   Node* time = make_runtime_call(RC_LEAF, tf, funcAddr, funcName, no_memory_effects);
  2548   Node* value = _gvn.transform(new (C, 1) ProjNode(time, TypeFunc::Parms+0));
  2549 #ifdef ASSERT
  2550   Node* value_top = _gvn.transform(new (C, 1) ProjNode(time, TypeFunc::Parms + 1));
  2551   assert(value_top == top(), "second value must be top");
  2552 #endif
  2553   push_pair(value);
  2554   return true;
  2557 //------------------------inline_native_currentThread------------------
  2558 bool LibraryCallKit::inline_native_currentThread() {
  2559   Node* junk = NULL;
  2560   push(generate_current_thread(junk));
  2561   return true;
  2564 //------------------------inline_native_isInterrupted------------------
  2565 bool LibraryCallKit::inline_native_isInterrupted() {
  2566   const int nargs = 1+1;  // receiver + boolean
  2567   assert(nargs == arg_size(), "sanity");
  2568   // Add a fast path to t.isInterrupted(clear_int):
  2569   //   (t == Thread.current() && (!TLS._osthread._interrupted || !clear_int))
  2570   //   ? TLS._osthread._interrupted : /*slow path:*/ t.isInterrupted(clear_int)
  2571   // So, in the common case that the interrupt bit is false,
  2572   // we avoid making a call into the VM.  Even if the interrupt bit
  2573   // is true, if the clear_int argument is false, we avoid the VM call.
  2574   // However, if the receiver is not currentThread, we must call the VM,
  2575   // because there must be some locking done around the operation.
  2577   // We only go to the fast case code if we pass two guards.
  2578   // Paths which do not pass are accumulated in the slow_region.
  2579   RegionNode* slow_region = new (C, 1) RegionNode(1);
  2580   record_for_igvn(slow_region);
  2581   RegionNode* result_rgn = new (C, 4) RegionNode(1+3); // fast1, fast2, slow
  2582   PhiNode*    result_val = new (C, 4) PhiNode(result_rgn, TypeInt::BOOL);
  2583   enum { no_int_result_path   = 1,
  2584          no_clear_result_path = 2,
  2585          slow_result_path     = 3
  2586   };
  2588   // (a) Receiving thread must be the current thread.
  2589   Node* rec_thr = argument(0);
  2590   Node* tls_ptr = NULL;
  2591   Node* cur_thr = generate_current_thread(tls_ptr);
  2592   Node* cmp_thr = _gvn.transform( new (C, 3) CmpPNode(cur_thr, rec_thr) );
  2593   Node* bol_thr = _gvn.transform( new (C, 2) BoolNode(cmp_thr, BoolTest::ne) );
  2595   bool known_current_thread = (_gvn.type(bol_thr) == TypeInt::ZERO);
  2596   if (!known_current_thread)
  2597     generate_slow_guard(bol_thr, slow_region);
  2599   // (b) Interrupt bit on TLS must be false.
  2600   Node* p = basic_plus_adr(top()/*!oop*/, tls_ptr, in_bytes(JavaThread::osthread_offset()));
  2601   Node* osthread = make_load(NULL, p, TypeRawPtr::NOTNULL, T_ADDRESS);
  2602   p = basic_plus_adr(top()/*!oop*/, osthread, in_bytes(OSThread::interrupted_offset()));
  2603   // Set the control input on the field _interrupted read to prevent it floating up.
  2604   Node* int_bit = make_load(control(), p, TypeInt::BOOL, T_INT);
  2605   Node* cmp_bit = _gvn.transform( new (C, 3) CmpINode(int_bit, intcon(0)) );
  2606   Node* bol_bit = _gvn.transform( new (C, 2) BoolNode(cmp_bit, BoolTest::ne) );
  2608   IfNode* iff_bit = create_and_map_if(control(), bol_bit, PROB_UNLIKELY_MAG(3), COUNT_UNKNOWN);
  2610   // First fast path:  if (!TLS._interrupted) return false;
  2611   Node* false_bit = _gvn.transform( new (C, 1) IfFalseNode(iff_bit) );
  2612   result_rgn->init_req(no_int_result_path, false_bit);
  2613   result_val->init_req(no_int_result_path, intcon(0));
  2615   // drop through to next case
  2616   set_control( _gvn.transform(new (C, 1) IfTrueNode(iff_bit)) );
  2618   // (c) Or, if interrupt bit is set and clear_int is false, use 2nd fast path.
  2619   Node* clr_arg = argument(1);
  2620   Node* cmp_arg = _gvn.transform( new (C, 3) CmpINode(clr_arg, intcon(0)) );
  2621   Node* bol_arg = _gvn.transform( new (C, 2) BoolNode(cmp_arg, BoolTest::ne) );
  2622   IfNode* iff_arg = create_and_map_if(control(), bol_arg, PROB_FAIR, COUNT_UNKNOWN);
  2624   // Second fast path:  ... else if (!clear_int) return true;
  2625   Node* false_arg = _gvn.transform( new (C, 1) IfFalseNode(iff_arg) );
  2626   result_rgn->init_req(no_clear_result_path, false_arg);
  2627   result_val->init_req(no_clear_result_path, intcon(1));
  2629   // drop through to next case
  2630   set_control( _gvn.transform(new (C, 1) IfTrueNode(iff_arg)) );
  2632   // (d) Otherwise, go to the slow path.
  2633   slow_region->add_req(control());
  2634   set_control( _gvn.transform(slow_region) );
  2636   if (stopped()) {
  2637     // There is no slow path.
  2638     result_rgn->init_req(slow_result_path, top());
  2639     result_val->init_req(slow_result_path, top());
  2640   } else {
  2641     // non-virtual because it is a private non-static
  2642     CallJavaNode* slow_call = generate_method_call(vmIntrinsics::_isInterrupted);
  2644     Node* slow_val = set_results_for_java_call(slow_call);
  2645     // this->control() comes from set_results_for_java_call
  2647     // If we know that the result of the slow call will be true, tell the optimizer!
  2648     if (known_current_thread)  slow_val = intcon(1);
  2650     Node* fast_io  = slow_call->in(TypeFunc::I_O);
  2651     Node* fast_mem = slow_call->in(TypeFunc::Memory);
  2652     // These two phis are pre-filled with copies of of the fast IO and Memory
  2653     Node* io_phi   = PhiNode::make(result_rgn, fast_io,  Type::ABIO);
  2654     Node* mem_phi  = PhiNode::make(result_rgn, fast_mem, Type::MEMORY, TypePtr::BOTTOM);
  2656     result_rgn->init_req(slow_result_path, control());
  2657     io_phi    ->init_req(slow_result_path, i_o());
  2658     mem_phi   ->init_req(slow_result_path, reset_memory());
  2659     result_val->init_req(slow_result_path, slow_val);
  2661     set_all_memory( _gvn.transform(mem_phi) );
  2662     set_i_o(        _gvn.transform(io_phi) );
  2665   push_result(result_rgn, result_val);
  2666   C->set_has_split_ifs(true); // Has chance for split-if optimization
  2668   return true;
  2671 //---------------------------load_mirror_from_klass----------------------------
  2672 // Given a klass oop, load its java mirror (a java.lang.Class oop).
  2673 Node* LibraryCallKit::load_mirror_from_klass(Node* klass) {
  2674   Node* p = basic_plus_adr(klass, Klass::java_mirror_offset_in_bytes() + sizeof(oopDesc));
  2675   return make_load(NULL, p, TypeInstPtr::MIRROR, T_OBJECT);
  2678 //-----------------------load_klass_from_mirror_common-------------------------
  2679 // Given a java mirror (a java.lang.Class oop), load its corresponding klass oop.
  2680 // Test the klass oop for null (signifying a primitive Class like Integer.TYPE),
  2681 // and branch to the given path on the region.
  2682 // If never_see_null, take an uncommon trap on null, so we can optimistically
  2683 // compile for the non-null case.
  2684 // If the region is NULL, force never_see_null = true.
  2685 Node* LibraryCallKit::load_klass_from_mirror_common(Node* mirror,
  2686                                                     bool never_see_null,
  2687                                                     int nargs,
  2688                                                     RegionNode* region,
  2689                                                     int null_path,
  2690                                                     int offset) {
  2691   if (region == NULL)  never_see_null = true;
  2692   Node* p = basic_plus_adr(mirror, offset);
  2693   const TypeKlassPtr*  kls_type = TypeKlassPtr::OBJECT_OR_NULL;
  2694   Node* kls = _gvn.transform( LoadKlassNode::make(_gvn, immutable_memory(), p, TypeRawPtr::BOTTOM, kls_type) );
  2695   _sp += nargs; // any deopt will start just before call to enclosing method
  2696   Node* null_ctl = top();
  2697   kls = null_check_oop(kls, &null_ctl, never_see_null);
  2698   if (region != NULL) {
  2699     // Set region->in(null_path) if the mirror is a primitive (e.g, int.class).
  2700     region->init_req(null_path, null_ctl);
  2701   } else {
  2702     assert(null_ctl == top(), "no loose ends");
  2704   _sp -= nargs;
  2705   return kls;
  2708 //--------------------(inline_native_Class_query helpers)---------------------
  2709 // Use this for JVM_ACC_INTERFACE, JVM_ACC_IS_CLONEABLE, JVM_ACC_HAS_FINALIZER.
  2710 // Fall through if (mods & mask) == bits, take the guard otherwise.
  2711 Node* LibraryCallKit::generate_access_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region) {
  2712   // Branch around if the given klass has the given modifier bit set.
  2713   // Like generate_guard, adds a new path onto the region.
  2714   Node* modp = basic_plus_adr(kls, Klass::access_flags_offset_in_bytes() + sizeof(oopDesc));
  2715   Node* mods = make_load(NULL, modp, TypeInt::INT, T_INT);
  2716   Node* mask = intcon(modifier_mask);
  2717   Node* bits = intcon(modifier_bits);
  2718   Node* mbit = _gvn.transform( new (C, 3) AndINode(mods, mask) );
  2719   Node* cmp  = _gvn.transform( new (C, 3) CmpINode(mbit, bits) );
  2720   Node* bol  = _gvn.transform( new (C, 2) BoolNode(cmp, BoolTest::ne) );
  2721   return generate_fair_guard(bol, region);
  2723 Node* LibraryCallKit::generate_interface_guard(Node* kls, RegionNode* region) {
  2724   return generate_access_flags_guard(kls, JVM_ACC_INTERFACE, 0, region);
  2727 //-------------------------inline_native_Class_query-------------------
  2728 bool LibraryCallKit::inline_native_Class_query(vmIntrinsics::ID id) {
  2729   int nargs = 1+0;  // just the Class mirror, in most cases
  2730   const Type* return_type = TypeInt::BOOL;
  2731   Node* prim_return_value = top();  // what happens if it's a primitive class?
  2732   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
  2733   bool expect_prim = false;     // most of these guys expect to work on refs
  2735   enum { _normal_path = 1, _prim_path = 2, PATH_LIMIT };
  2737   switch (id) {
  2738   case vmIntrinsics::_isInstance:
  2739     nargs = 1+1;  // the Class mirror, plus the object getting queried about
  2740     // nothing is an instance of a primitive type
  2741     prim_return_value = intcon(0);
  2742     break;
  2743   case vmIntrinsics::_getModifiers:
  2744     prim_return_value = intcon(JVM_ACC_ABSTRACT | JVM_ACC_FINAL | JVM_ACC_PUBLIC);
  2745     assert(is_power_of_2((int)JVM_ACC_WRITTEN_FLAGS+1), "change next line");
  2746     return_type = TypeInt::make(0, JVM_ACC_WRITTEN_FLAGS, Type::WidenMin);
  2747     break;
  2748   case vmIntrinsics::_isInterface:
  2749     prim_return_value = intcon(0);
  2750     break;
  2751   case vmIntrinsics::_isArray:
  2752     prim_return_value = intcon(0);
  2753     expect_prim = true;  // cf. ObjectStreamClass.getClassSignature
  2754     break;
  2755   case vmIntrinsics::_isPrimitive:
  2756     prim_return_value = intcon(1);
  2757     expect_prim = true;  // obviously
  2758     break;
  2759   case vmIntrinsics::_getSuperclass:
  2760     prim_return_value = null();
  2761     return_type = TypeInstPtr::MIRROR->cast_to_ptr_type(TypePtr::BotPTR);
  2762     break;
  2763   case vmIntrinsics::_getComponentType:
  2764     prim_return_value = null();
  2765     return_type = TypeInstPtr::MIRROR->cast_to_ptr_type(TypePtr::BotPTR);
  2766     break;
  2767   case vmIntrinsics::_getClassAccessFlags:
  2768     prim_return_value = intcon(JVM_ACC_ABSTRACT | JVM_ACC_FINAL | JVM_ACC_PUBLIC);
  2769     return_type = TypeInt::INT;  // not bool!  6297094
  2770     break;
  2771   default:
  2772     ShouldNotReachHere();
  2775   Node* mirror =                      argument(0);
  2776   Node* obj    = (nargs <= 1)? top(): argument(1);
  2778   const TypeInstPtr* mirror_con = _gvn.type(mirror)->isa_instptr();
  2779   if (mirror_con == NULL)  return false;  // cannot happen?
  2781 #ifndef PRODUCT
  2782   if (PrintIntrinsics || PrintInlining || PrintOptoInlining) {
  2783     ciType* k = mirror_con->java_mirror_type();
  2784     if (k) {
  2785       tty->print("Inlining %s on constant Class ", vmIntrinsics::name_at(intrinsic_id()));
  2786       k->print_name();
  2787       tty->cr();
  2790 #endif
  2792   // Null-check the mirror, and the mirror's klass ptr (in case it is a primitive).
  2793   RegionNode* region = new (C, PATH_LIMIT) RegionNode(PATH_LIMIT);
  2794   record_for_igvn(region);
  2795   PhiNode* phi = new (C, PATH_LIMIT) PhiNode(region, return_type);
  2797   // The mirror will never be null of Reflection.getClassAccessFlags, however
  2798   // it may be null for Class.isInstance or Class.getModifiers. Throw a NPE
  2799   // if it is. See bug 4774291.
  2801   // For Reflection.getClassAccessFlags(), the null check occurs in
  2802   // the wrong place; see inline_unsafe_access(), above, for a similar
  2803   // situation.
  2804   _sp += nargs;  // set original stack for use by uncommon_trap
  2805   mirror = do_null_check(mirror, T_OBJECT);
  2806   _sp -= nargs;
  2807   // If mirror or obj is dead, only null-path is taken.
  2808   if (stopped())  return true;
  2810   if (expect_prim)  never_see_null = false;  // expect nulls (meaning prims)
  2812   // Now load the mirror's klass metaobject, and null-check it.
  2813   // Side-effects region with the control path if the klass is null.
  2814   Node* kls = load_klass_from_mirror(mirror, never_see_null, nargs,
  2815                                      region, _prim_path);
  2816   // If kls is null, we have a primitive mirror.
  2817   phi->init_req(_prim_path, prim_return_value);
  2818   if (stopped()) { push_result(region, phi); return true; }
  2820   Node* p;  // handy temp
  2821   Node* null_ctl;
  2823   // Now that we have the non-null klass, we can perform the real query.
  2824   // For constant classes, the query will constant-fold in LoadNode::Value.
  2825   Node* query_value = top();
  2826   switch (id) {
  2827   case vmIntrinsics::_isInstance:
  2828     // nothing is an instance of a primitive type
  2829     query_value = gen_instanceof(obj, kls);
  2830     break;
  2832   case vmIntrinsics::_getModifiers:
  2833     p = basic_plus_adr(kls, Klass::modifier_flags_offset_in_bytes() + sizeof(oopDesc));
  2834     query_value = make_load(NULL, p, TypeInt::INT, T_INT);
  2835     break;
  2837   case vmIntrinsics::_isInterface:
  2838     // (To verify this code sequence, check the asserts in JVM_IsInterface.)
  2839     if (generate_interface_guard(kls, region) != NULL)
  2840       // A guard was added.  If the guard is taken, it was an interface.
  2841       phi->add_req(intcon(1));
  2842     // If we fall through, it's a plain class.
  2843     query_value = intcon(0);
  2844     break;
  2846   case vmIntrinsics::_isArray:
  2847     // (To verify this code sequence, check the asserts in JVM_IsArrayClass.)
  2848     if (generate_array_guard(kls, region) != NULL)
  2849       // A guard was added.  If the guard is taken, it was an array.
  2850       phi->add_req(intcon(1));
  2851     // If we fall through, it's a plain class.
  2852     query_value = intcon(0);
  2853     break;
  2855   case vmIntrinsics::_isPrimitive:
  2856     query_value = intcon(0); // "normal" path produces false
  2857     break;
  2859   case vmIntrinsics::_getSuperclass:
  2860     // The rules here are somewhat unfortunate, but we can still do better
  2861     // with random logic than with a JNI call.
  2862     // Interfaces store null or Object as _super, but must report null.
  2863     // Arrays store an intermediate super as _super, but must report Object.
  2864     // Other types can report the actual _super.
  2865     // (To verify this code sequence, check the asserts in JVM_IsInterface.)
  2866     if (generate_interface_guard(kls, region) != NULL)
  2867       // A guard was added.  If the guard is taken, it was an interface.
  2868       phi->add_req(null());
  2869     if (generate_array_guard(kls, region) != NULL)
  2870       // A guard was added.  If the guard is taken, it was an array.
  2871       phi->add_req(makecon(TypeInstPtr::make(env()->Object_klass()->java_mirror())));
  2872     // If we fall through, it's a plain class.  Get its _super.
  2873     p = basic_plus_adr(kls, Klass::super_offset_in_bytes() + sizeof(oopDesc));
  2874     kls = _gvn.transform( LoadKlassNode::make(_gvn, immutable_memory(), p, TypeRawPtr::BOTTOM, TypeKlassPtr::OBJECT_OR_NULL) );
  2875     null_ctl = top();
  2876     kls = null_check_oop(kls, &null_ctl);
  2877     if (null_ctl != top()) {
  2878       // If the guard is taken, Object.superClass is null (both klass and mirror).
  2879       region->add_req(null_ctl);
  2880       phi   ->add_req(null());
  2882     if (!stopped()) {
  2883       query_value = load_mirror_from_klass(kls);
  2885     break;
  2887   case vmIntrinsics::_getComponentType:
  2888     if (generate_array_guard(kls, region) != NULL) {
  2889       // Be sure to pin the oop load to the guard edge just created:
  2890       Node* is_array_ctrl = region->in(region->req()-1);
  2891       Node* cma = basic_plus_adr(kls, in_bytes(arrayKlass::component_mirror_offset()) + sizeof(oopDesc));
  2892       Node* cmo = make_load(is_array_ctrl, cma, TypeInstPtr::MIRROR, T_OBJECT);
  2893       phi->add_req(cmo);
  2895     query_value = null();  // non-array case is null
  2896     break;
  2898   case vmIntrinsics::_getClassAccessFlags:
  2899     p = basic_plus_adr(kls, Klass::access_flags_offset_in_bytes() + sizeof(oopDesc));
  2900     query_value = make_load(NULL, p, TypeInt::INT, T_INT);
  2901     break;
  2903   default:
  2904     ShouldNotReachHere();
  2907   // Fall-through is the normal case of a query to a real class.
  2908   phi->init_req(1, query_value);
  2909   region->init_req(1, control());
  2911   push_result(region, phi);
  2912   C->set_has_split_ifs(true); // Has chance for split-if optimization
  2914   return true;
  2917 //--------------------------inline_native_subtype_check------------------------
  2918 // This intrinsic takes the JNI calls out of the heart of
  2919 // UnsafeFieldAccessorImpl.set, which improves Field.set, readObject, etc.
  2920 bool LibraryCallKit::inline_native_subtype_check() {
  2921   int nargs = 1+1;  // the Class mirror, plus the other class getting examined
  2923   // Pull both arguments off the stack.
  2924   Node* args[2];                // two java.lang.Class mirrors: superc, subc
  2925   args[0] = argument(0);
  2926   args[1] = argument(1);
  2927   Node* klasses[2];             // corresponding Klasses: superk, subk
  2928   klasses[0] = klasses[1] = top();
  2930   enum {
  2931     // A full decision tree on {superc is prim, subc is prim}:
  2932     _prim_0_path = 1,           // {P,N} => false
  2933                                 // {P,P} & superc!=subc => false
  2934     _prim_same_path,            // {P,P} & superc==subc => true
  2935     _prim_1_path,               // {N,P} => false
  2936     _ref_subtype_path,          // {N,N} & subtype check wins => true
  2937     _both_ref_path,             // {N,N} & subtype check loses => false
  2938     PATH_LIMIT
  2939   };
  2941   RegionNode* region = new (C, PATH_LIMIT) RegionNode(PATH_LIMIT);
  2942   Node*       phi    = new (C, PATH_LIMIT) PhiNode(region, TypeInt::BOOL);
  2943   record_for_igvn(region);
  2945   const TypePtr* adr_type = TypeRawPtr::BOTTOM;   // memory type of loads
  2946   const TypeKlassPtr* kls_type = TypeKlassPtr::OBJECT_OR_NULL;
  2947   int class_klass_offset = java_lang_Class::klass_offset_in_bytes();
  2949   // First null-check both mirrors and load each mirror's klass metaobject.
  2950   int which_arg;
  2951   for (which_arg = 0; which_arg <= 1; which_arg++) {
  2952     Node* arg = args[which_arg];
  2953     _sp += nargs;  // set original stack for use by uncommon_trap
  2954     arg = do_null_check(arg, T_OBJECT);
  2955     _sp -= nargs;
  2956     if (stopped())  break;
  2957     args[which_arg] = _gvn.transform(arg);
  2959     Node* p = basic_plus_adr(arg, class_klass_offset);
  2960     Node* kls = LoadKlassNode::make(_gvn, immutable_memory(), p, adr_type, kls_type);
  2961     klasses[which_arg] = _gvn.transform(kls);
  2964   // Having loaded both klasses, test each for null.
  2965   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
  2966   for (which_arg = 0; which_arg <= 1; which_arg++) {
  2967     Node* kls = klasses[which_arg];
  2968     Node* null_ctl = top();
  2969     _sp += nargs;  // set original stack for use by uncommon_trap
  2970     kls = null_check_oop(kls, &null_ctl, never_see_null);
  2971     _sp -= nargs;
  2972     int prim_path = (which_arg == 0 ? _prim_0_path : _prim_1_path);
  2973     region->init_req(prim_path, null_ctl);
  2974     if (stopped())  break;
  2975     klasses[which_arg] = kls;
  2978   if (!stopped()) {
  2979     // now we have two reference types, in klasses[0..1]
  2980     Node* subk   = klasses[1];  // the argument to isAssignableFrom
  2981     Node* superk = klasses[0];  // the receiver
  2982     region->set_req(_both_ref_path, gen_subtype_check(subk, superk));
  2983     // now we have a successful reference subtype check
  2984     region->set_req(_ref_subtype_path, control());
  2987   // If both operands are primitive (both klasses null), then
  2988   // we must return true when they are identical primitives.
  2989   // It is convenient to test this after the first null klass check.
  2990   set_control(region->in(_prim_0_path)); // go back to first null check
  2991   if (!stopped()) {
  2992     // Since superc is primitive, make a guard for the superc==subc case.
  2993     Node* cmp_eq = _gvn.transform( new (C, 3) CmpPNode(args[0], args[1]) );
  2994     Node* bol_eq = _gvn.transform( new (C, 2) BoolNode(cmp_eq, BoolTest::eq) );
  2995     generate_guard(bol_eq, region, PROB_FAIR);
  2996     if (region->req() == PATH_LIMIT+1) {
  2997       // A guard was added.  If the added guard is taken, superc==subc.
  2998       region->swap_edges(PATH_LIMIT, _prim_same_path);
  2999       region->del_req(PATH_LIMIT);
  3001     region->set_req(_prim_0_path, control()); // Not equal after all.
  3004   // these are the only paths that produce 'true':
  3005   phi->set_req(_prim_same_path,   intcon(1));
  3006   phi->set_req(_ref_subtype_path, intcon(1));
  3008   // pull together the cases:
  3009   assert(region->req() == PATH_LIMIT, "sane region");
  3010   for (uint i = 1; i < region->req(); i++) {
  3011     Node* ctl = region->in(i);
  3012     if (ctl == NULL || ctl == top()) {
  3013       region->set_req(i, top());
  3014       phi   ->set_req(i, top());
  3015     } else if (phi->in(i) == NULL) {
  3016       phi->set_req(i, intcon(0)); // all other paths produce 'false'
  3020   set_control(_gvn.transform(region));
  3021   push(_gvn.transform(phi));
  3023   return true;
  3026 //---------------------generate_array_guard_common------------------------
  3027 Node* LibraryCallKit::generate_array_guard_common(Node* kls, RegionNode* region,
  3028                                                   bool obj_array, bool not_array) {
  3029   // If obj_array/non_array==false/false:
  3030   // Branch around if the given klass is in fact an array (either obj or prim).
  3031   // If obj_array/non_array==false/true:
  3032   // Branch around if the given klass is not an array klass of any kind.
  3033   // If obj_array/non_array==true/true:
  3034   // Branch around if the kls is not an oop array (kls is int[], String, etc.)
  3035   // If obj_array/non_array==true/false:
  3036   // Branch around if the kls is an oop array (Object[] or subtype)
  3037   //
  3038   // Like generate_guard, adds a new path onto the region.
  3039   jint  layout_con = 0;
  3040   Node* layout_val = get_layout_helper(kls, layout_con);
  3041   if (layout_val == NULL) {
  3042     bool query = (obj_array
  3043                   ? Klass::layout_helper_is_objArray(layout_con)
  3044                   : Klass::layout_helper_is_javaArray(layout_con));
  3045     if (query == not_array) {
  3046       return NULL;                       // never a branch
  3047     } else {                             // always a branch
  3048       Node* always_branch = control();
  3049       if (region != NULL)
  3050         region->add_req(always_branch);
  3051       set_control(top());
  3052       return always_branch;
  3055   // Now test the correct condition.
  3056   jint  nval = (obj_array
  3057                 ? ((jint)Klass::_lh_array_tag_type_value
  3058                    <<    Klass::_lh_array_tag_shift)
  3059                 : Klass::_lh_neutral_value);
  3060   Node* cmp = _gvn.transform( new(C, 3) CmpINode(layout_val, intcon(nval)) );
  3061   BoolTest::mask btest = BoolTest::lt;  // correct for testing is_[obj]array
  3062   // invert the test if we are looking for a non-array
  3063   if (not_array)  btest = BoolTest(btest).negate();
  3064   Node* bol = _gvn.transform( new(C, 2) BoolNode(cmp, btest) );
  3065   return generate_fair_guard(bol, region);
  3069 //-----------------------inline_native_newArray--------------------------
  3070 bool LibraryCallKit::inline_native_newArray() {
  3071   int nargs = 2;
  3072   Node* mirror    = argument(0);
  3073   Node* count_val = argument(1);
  3075   _sp += nargs;  // set original stack for use by uncommon_trap
  3076   mirror = do_null_check(mirror, T_OBJECT);
  3077   _sp -= nargs;
  3078   // If mirror or obj is dead, only null-path is taken.
  3079   if (stopped())  return true;
  3081   enum { _normal_path = 1, _slow_path = 2, PATH_LIMIT };
  3082   RegionNode* result_reg = new(C, PATH_LIMIT) RegionNode(PATH_LIMIT);
  3083   PhiNode*    result_val = new(C, PATH_LIMIT) PhiNode(result_reg,
  3084                                                       TypeInstPtr::NOTNULL);
  3085   PhiNode*    result_io  = new(C, PATH_LIMIT) PhiNode(result_reg, Type::ABIO);
  3086   PhiNode*    result_mem = new(C, PATH_LIMIT) PhiNode(result_reg, Type::MEMORY,
  3087                                                       TypePtr::BOTTOM);
  3089   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
  3090   Node* klass_node = load_array_klass_from_mirror(mirror, never_see_null,
  3091                                                   nargs,
  3092                                                   result_reg, _slow_path);
  3093   Node* normal_ctl   = control();
  3094   Node* no_array_ctl = result_reg->in(_slow_path);
  3096   // Generate code for the slow case.  We make a call to newArray().
  3097   set_control(no_array_ctl);
  3098   if (!stopped()) {
  3099     // Either the input type is void.class, or else the
  3100     // array klass has not yet been cached.  Either the
  3101     // ensuing call will throw an exception, or else it
  3102     // will cache the array klass for next time.
  3103     PreserveJVMState pjvms(this);
  3104     CallJavaNode* slow_call = generate_method_call_static(vmIntrinsics::_newArray);
  3105     Node* slow_result = set_results_for_java_call(slow_call);
  3106     // this->control() comes from set_results_for_java_call
  3107     result_reg->set_req(_slow_path, control());
  3108     result_val->set_req(_slow_path, slow_result);
  3109     result_io ->set_req(_slow_path, i_o());
  3110     result_mem->set_req(_slow_path, reset_memory());
  3113   set_control(normal_ctl);
  3114   if (!stopped()) {
  3115     // Normal case:  The array type has been cached in the java.lang.Class.
  3116     // The following call works fine even if the array type is polymorphic.
  3117     // It could be a dynamic mix of int[], boolean[], Object[], etc.
  3118     Node* obj = new_array(klass_node, count_val, nargs);
  3119     result_reg->init_req(_normal_path, control());
  3120     result_val->init_req(_normal_path, obj);
  3121     result_io ->init_req(_normal_path, i_o());
  3122     result_mem->init_req(_normal_path, reset_memory());
  3125   // Return the combined state.
  3126   set_i_o(        _gvn.transform(result_io)  );
  3127   set_all_memory( _gvn.transform(result_mem) );
  3128   push_result(result_reg, result_val);
  3129   C->set_has_split_ifs(true); // Has chance for split-if optimization
  3131   return true;
  3134 //----------------------inline_native_getLength--------------------------
  3135 bool LibraryCallKit::inline_native_getLength() {
  3136   if (too_many_traps(Deoptimization::Reason_intrinsic))  return false;
  3138   int nargs = 1;
  3139   Node* array = argument(0);
  3141   _sp += nargs;  // set original stack for use by uncommon_trap
  3142   array = do_null_check(array, T_OBJECT);
  3143   _sp -= nargs;
  3145   // If array is dead, only null-path is taken.
  3146   if (stopped())  return true;
  3148   // Deoptimize if it is a non-array.
  3149   Node* non_array = generate_non_array_guard(load_object_klass(array), NULL);
  3151   if (non_array != NULL) {
  3152     PreserveJVMState pjvms(this);
  3153     set_control(non_array);
  3154     _sp += nargs;  // push the arguments back on the stack
  3155     uncommon_trap(Deoptimization::Reason_intrinsic,
  3156                   Deoptimization::Action_maybe_recompile);
  3159   // If control is dead, only non-array-path is taken.
  3160   if (stopped())  return true;
  3162   // The works fine even if the array type is polymorphic.
  3163   // It could be a dynamic mix of int[], boolean[], Object[], etc.
  3164   push( load_array_length(array) );
  3166   C->set_has_split_ifs(true); // Has chance for split-if optimization
  3168   return true;
  3171 //------------------------inline_array_copyOf----------------------------
  3172 bool LibraryCallKit::inline_array_copyOf(bool is_copyOfRange) {
  3173   if (too_many_traps(Deoptimization::Reason_intrinsic))  return false;
  3175   // Restore the stack and pop off the arguments.
  3176   int nargs = 3 + (is_copyOfRange? 1: 0);
  3177   Node* original          = argument(0);
  3178   Node* start             = is_copyOfRange? argument(1): intcon(0);
  3179   Node* end               = is_copyOfRange? argument(2): argument(1);
  3180   Node* array_type_mirror = is_copyOfRange? argument(3): argument(2);
  3182   _sp += nargs;  // set original stack for use by uncommon_trap
  3183   array_type_mirror = do_null_check(array_type_mirror, T_OBJECT);
  3184   original          = do_null_check(original, T_OBJECT);
  3185   _sp -= nargs;
  3187   // Check if a null path was taken unconditionally.
  3188   if (stopped())  return true;
  3190   Node* orig_length = load_array_length(original);
  3192   Node* klass_node = load_klass_from_mirror(array_type_mirror, false, nargs,
  3193                                             NULL, 0);
  3194   _sp += nargs;  // set original stack for use by uncommon_trap
  3195   klass_node = do_null_check(klass_node, T_OBJECT);
  3196   _sp -= nargs;
  3198   RegionNode* bailout = new (C, 1) RegionNode(1);
  3199   record_for_igvn(bailout);
  3201   // Despite the generic type of Arrays.copyOf, the mirror might be int, int[], etc.
  3202   // Bail out if that is so.
  3203   Node* not_objArray = generate_non_objArray_guard(klass_node, bailout);
  3204   if (not_objArray != NULL) {
  3205     // Improve the klass node's type from the new optimistic assumption:
  3206     ciKlass* ak = ciArrayKlass::make(env()->Object_klass());
  3207     const Type* akls = TypeKlassPtr::make(TypePtr::NotNull, ak, 0/*offset*/);
  3208     Node* cast = new (C, 2) CastPPNode(klass_node, akls);
  3209     cast->init_req(0, control());
  3210     klass_node = _gvn.transform(cast);
  3213   // Bail out if either start or end is negative.
  3214   generate_negative_guard(start, bailout, &start);
  3215   generate_negative_guard(end,   bailout, &end);
  3217   Node* length = end;
  3218   if (_gvn.type(start) != TypeInt::ZERO) {
  3219     length = _gvn.transform( new (C, 3) SubINode(end, start) );
  3222   // Bail out if length is negative.
  3223   // ...Not needed, since the new_array will throw the right exception.
  3224   //generate_negative_guard(length, bailout, &length);
  3226   if (bailout->req() > 1) {
  3227     PreserveJVMState pjvms(this);
  3228     set_control( _gvn.transform(bailout) );
  3229     _sp += nargs;  // push the arguments back on the stack
  3230     uncommon_trap(Deoptimization::Reason_intrinsic,
  3231                   Deoptimization::Action_maybe_recompile);
  3234   if (!stopped()) {
  3235     // How many elements will we copy from the original?
  3236     // The answer is MinI(orig_length - start, length).
  3237     Node* orig_tail = _gvn.transform( new(C, 3) SubINode(orig_length, start) );
  3238     Node* moved = generate_min_max(vmIntrinsics::_min, orig_tail, length);
  3240     const bool raw_mem_only = true;
  3241     Node* newcopy = new_array(klass_node, length, nargs, raw_mem_only);
  3243     // Generate a direct call to the right arraycopy function(s).
  3244     // We know the copy is disjoint but we might not know if the
  3245     // oop stores need checking.
  3246     // Extreme case:  Arrays.copyOf((Integer[])x, 10, String[].class).
  3247     // This will fail a store-check if x contains any non-nulls.
  3248     bool disjoint_bases = true;
  3249     bool length_never_negative = true;
  3250     generate_arraycopy(TypeAryPtr::OOPS, T_OBJECT,
  3251                        original, start, newcopy, intcon(0), moved,
  3252                        disjoint_bases, length_never_negative);
  3254     push(newcopy);
  3257   C->set_has_split_ifs(true); // Has chance for split-if optimization
  3259   return true;
  3263 //----------------------generate_virtual_guard---------------------------
  3264 // Helper for hashCode and clone.  Peeks inside the vtable to avoid a call.
  3265 Node* LibraryCallKit::generate_virtual_guard(Node* obj_klass,
  3266                                              RegionNode* slow_region) {
  3267   ciMethod* method = callee();
  3268   int vtable_index = method->vtable_index();
  3269   // Get the methodOop out of the appropriate vtable entry.
  3270   int entry_offset  = (instanceKlass::vtable_start_offset() +
  3271                      vtable_index*vtableEntry::size()) * wordSize +
  3272                      vtableEntry::method_offset_in_bytes();
  3273   Node* entry_addr  = basic_plus_adr(obj_klass, entry_offset);
  3274   Node* target_call = make_load(NULL, entry_addr, TypeInstPtr::NOTNULL, T_OBJECT);
  3276   // Compare the target method with the expected method (e.g., Object.hashCode).
  3277   const TypeInstPtr* native_call_addr = TypeInstPtr::make(method);
  3279   Node* native_call = makecon(native_call_addr);
  3280   Node* chk_native  = _gvn.transform( new(C, 3) CmpPNode(target_call, native_call) );
  3281   Node* test_native = _gvn.transform( new(C, 2) BoolNode(chk_native, BoolTest::ne) );
  3283   return generate_slow_guard(test_native, slow_region);
  3286 //-----------------------generate_method_call----------------------------
  3287 // Use generate_method_call to make a slow-call to the real
  3288 // method if the fast path fails.  An alternative would be to
  3289 // use a stub like OptoRuntime::slow_arraycopy_Java.
  3290 // This only works for expanding the current library call,
  3291 // not another intrinsic.  (E.g., don't use this for making an
  3292 // arraycopy call inside of the copyOf intrinsic.)
  3293 CallJavaNode*
  3294 LibraryCallKit::generate_method_call(vmIntrinsics::ID method_id, bool is_virtual, bool is_static) {
  3295   // When compiling the intrinsic method itself, do not use this technique.
  3296   guarantee(callee() != C->method(), "cannot make slow-call to self");
  3298   ciMethod* method = callee();
  3299   // ensure the JVMS we have will be correct for this call
  3300   guarantee(method_id == method->intrinsic_id(), "must match");
  3302   const TypeFunc* tf = TypeFunc::make(method);
  3303   int tfdc = tf->domain()->cnt();
  3304   CallJavaNode* slow_call;
  3305   if (is_static) {
  3306     assert(!is_virtual, "");
  3307     slow_call = new(C, tfdc) CallStaticJavaNode(tf,
  3308                                 SharedRuntime::get_resolve_static_call_stub(),
  3309                                 method, bci());
  3310   } else if (is_virtual) {
  3311     null_check_receiver(method);
  3312     int vtable_index = methodOopDesc::invalid_vtable_index;
  3313     if (UseInlineCaches) {
  3314       // Suppress the vtable call
  3315     } else {
  3316       // hashCode and clone are not a miranda methods,
  3317       // so the vtable index is fixed.
  3318       // No need to use the linkResolver to get it.
  3319        vtable_index = method->vtable_index();
  3321     slow_call = new(C, tfdc) CallDynamicJavaNode(tf,
  3322                                 SharedRuntime::get_resolve_virtual_call_stub(),
  3323                                 method, vtable_index, bci());
  3324   } else {  // neither virtual nor static:  opt_virtual
  3325     null_check_receiver(method);
  3326     slow_call = new(C, tfdc) CallStaticJavaNode(tf,
  3327                                 SharedRuntime::get_resolve_opt_virtual_call_stub(),
  3328                                 method, bci());
  3329     slow_call->set_optimized_virtual(true);
  3331   set_arguments_for_java_call(slow_call);
  3332   set_edges_for_java_call(slow_call);
  3333   return slow_call;
  3337 //------------------------------inline_native_hashcode--------------------
  3338 // Build special case code for calls to hashCode on an object.
  3339 bool LibraryCallKit::inline_native_hashcode(bool is_virtual, bool is_static) {
  3340   assert(is_static == callee()->is_static(), "correct intrinsic selection");
  3341   assert(!(is_virtual && is_static), "either virtual, special, or static");
  3343   enum { _slow_path = 1, _fast_path, _null_path, PATH_LIMIT };
  3345   RegionNode* result_reg = new(C, PATH_LIMIT) RegionNode(PATH_LIMIT);
  3346   PhiNode*    result_val = new(C, PATH_LIMIT) PhiNode(result_reg,
  3347                                                       TypeInt::INT);
  3348   PhiNode*    result_io  = new(C, PATH_LIMIT) PhiNode(result_reg, Type::ABIO);
  3349   PhiNode*    result_mem = new(C, PATH_LIMIT) PhiNode(result_reg, Type::MEMORY,
  3350                                                       TypePtr::BOTTOM);
  3351   Node* obj = NULL;
  3352   if (!is_static) {
  3353     // Check for hashing null object
  3354     obj = null_check_receiver(callee());
  3355     if (stopped())  return true;        // unconditionally null
  3356     result_reg->init_req(_null_path, top());
  3357     result_val->init_req(_null_path, top());
  3358   } else {
  3359     // Do a null check, and return zero if null.
  3360     // System.identityHashCode(null) == 0
  3361     obj = argument(0);
  3362     Node* null_ctl = top();
  3363     obj = null_check_oop(obj, &null_ctl);
  3364     result_reg->init_req(_null_path, null_ctl);
  3365     result_val->init_req(_null_path, _gvn.intcon(0));
  3368   // Unconditionally null?  Then return right away.
  3369   if (stopped()) {
  3370     set_control( result_reg->in(_null_path) );
  3371     if (!stopped())
  3372       push(      result_val ->in(_null_path) );
  3373     return true;
  3376   // After null check, get the object's klass.
  3377   Node* obj_klass = load_object_klass(obj);
  3379   // This call may be virtual (invokevirtual) or bound (invokespecial).
  3380   // For each case we generate slightly different code.
  3382   // We only go to the fast case code if we pass a number of guards.  The
  3383   // paths which do not pass are accumulated in the slow_region.
  3384   RegionNode* slow_region = new (C, 1) RegionNode(1);
  3385   record_for_igvn(slow_region);
  3387   // If this is a virtual call, we generate a funny guard.  We pull out
  3388   // the vtable entry corresponding to hashCode() from the target object.
  3389   // If the target method which we are calling happens to be the native
  3390   // Object hashCode() method, we pass the guard.  We do not need this
  3391   // guard for non-virtual calls -- the caller is known to be the native
  3392   // Object hashCode().
  3393   if (is_virtual) {
  3394     generate_virtual_guard(obj_klass, slow_region);
  3397   // Get the header out of the object, use LoadMarkNode when available
  3398   Node* header_addr = basic_plus_adr(obj, oopDesc::mark_offset_in_bytes());
  3399   Node* header = make_load(NULL, header_addr, TypeRawPtr::BOTTOM, T_ADDRESS);
  3400   header = _gvn.transform( new (C, 2) CastP2XNode(NULL, header) );
  3402   // Test the header to see if it is unlocked.
  3403   Node *lock_mask      = _gvn.MakeConX(markOopDesc::biased_lock_mask_in_place);
  3404   Node *lmasked_header = _gvn.transform( new (C, 3) AndXNode(header, lock_mask) );
  3405   Node *unlocked_val   = _gvn.MakeConX(markOopDesc::unlocked_value);
  3406   Node *chk_unlocked   = _gvn.transform( new (C, 3) CmpXNode( lmasked_header, unlocked_val));
  3407   Node *test_unlocked  = _gvn.transform( new (C, 2) BoolNode( chk_unlocked, BoolTest::ne) );
  3409   generate_slow_guard(test_unlocked, slow_region);
  3411   // Get the hash value and check to see that it has been properly assigned.
  3412   // We depend on hash_mask being at most 32 bits and avoid the use of
  3413   // hash_mask_in_place because it could be larger than 32 bits in a 64-bit
  3414   // vm: see markOop.hpp.
  3415   Node *hash_mask      = _gvn.intcon(markOopDesc::hash_mask);
  3416   Node *hash_shift     = _gvn.intcon(markOopDesc::hash_shift);
  3417   Node *hshifted_header= _gvn.transform( new (C, 3) URShiftXNode(header, hash_shift) );
  3418   // This hack lets the hash bits live anywhere in the mark object now, as long
  3419   // as the shift drops the relevant bits into the low 32 bits.  Note that
  3420   // Java spec says that HashCode is an int so there's no point in capturing
  3421   // an 'X'-sized hashcode (32 in 32-bit build or 64 in 64-bit build).
  3422   hshifted_header      = ConvX2I(hshifted_header);
  3423   Node *hash_val       = _gvn.transform( new (C, 3) AndINode(hshifted_header, hash_mask) );
  3425   Node *no_hash_val    = _gvn.intcon(markOopDesc::no_hash);
  3426   Node *chk_assigned   = _gvn.transform( new (C, 3) CmpINode( hash_val, no_hash_val));
  3427   Node *test_assigned  = _gvn.transform( new (C, 2) BoolNode( chk_assigned, BoolTest::eq) );
  3429   generate_slow_guard(test_assigned, slow_region);
  3431   Node* init_mem = reset_memory();
  3432   // fill in the rest of the null path:
  3433   result_io ->init_req(_null_path, i_o());
  3434   result_mem->init_req(_null_path, init_mem);
  3436   result_val->init_req(_fast_path, hash_val);
  3437   result_reg->init_req(_fast_path, control());
  3438   result_io ->init_req(_fast_path, i_o());
  3439   result_mem->init_req(_fast_path, init_mem);
  3441   // Generate code for the slow case.  We make a call to hashCode().
  3442   set_control(_gvn.transform(slow_region));
  3443   if (!stopped()) {
  3444     // No need for PreserveJVMState, because we're using up the present state.
  3445     set_all_memory(init_mem);
  3446     vmIntrinsics::ID hashCode_id = vmIntrinsics::_hashCode;
  3447     if (is_static)   hashCode_id = vmIntrinsics::_identityHashCode;
  3448     CallJavaNode* slow_call = generate_method_call(hashCode_id, is_virtual, is_static);
  3449     Node* slow_result = set_results_for_java_call(slow_call);
  3450     // this->control() comes from set_results_for_java_call
  3451     result_reg->init_req(_slow_path, control());
  3452     result_val->init_req(_slow_path, slow_result);
  3453     result_io  ->set_req(_slow_path, i_o());
  3454     result_mem ->set_req(_slow_path, reset_memory());
  3457   // Return the combined state.
  3458   set_i_o(        _gvn.transform(result_io)  );
  3459   set_all_memory( _gvn.transform(result_mem) );
  3460   push_result(result_reg, result_val);
  3462   return true;
  3465 //---------------------------inline_native_getClass----------------------------
  3466 // Build special case code for calls to getClass on an object.
  3467 bool LibraryCallKit::inline_native_getClass() {
  3468   Node* obj = null_check_receiver(callee());
  3469   if (stopped())  return true;
  3470   push( load_mirror_from_klass(load_object_klass(obj)) );
  3471   return true;
  3474 //-----------------inline_native_Reflection_getCallerClass---------------------
  3475 // In the presence of deep enough inlining, getCallerClass() becomes a no-op.
  3476 //
  3477 // NOTE that this code must perform the same logic as
  3478 // vframeStream::security_get_caller_frame in that it must skip
  3479 // Method.invoke() and auxiliary frames.
  3484 bool LibraryCallKit::inline_native_Reflection_getCallerClass() {
  3485   ciMethod*       method = callee();
  3487 #ifndef PRODUCT
  3488   if ((PrintIntrinsics || PrintInlining || PrintOptoInlining) && Verbose) {
  3489     tty->print_cr("Attempting to inline sun.reflect.Reflection.getCallerClass");
  3491 #endif
  3493   debug_only(int saved_sp = _sp);
  3495   // Argument words:  (int depth)
  3496   int nargs = 1;
  3498   _sp += nargs;
  3499   Node* caller_depth_node = pop();
  3501   assert(saved_sp == _sp, "must have correct argument count");
  3503   // The depth value must be a constant in order for the runtime call
  3504   // to be eliminated.
  3505   const TypeInt* caller_depth_type = _gvn.type(caller_depth_node)->isa_int();
  3506   if (caller_depth_type == NULL || !caller_depth_type->is_con()) {
  3507 #ifndef PRODUCT
  3508     if ((PrintIntrinsics || PrintInlining || PrintOptoInlining) && Verbose) {
  3509       tty->print_cr("  Bailing out because caller depth was not a constant");
  3511 #endif
  3512     return false;
  3514   // Note that the JVM state at this point does not include the
  3515   // getCallerClass() frame which we are trying to inline. The
  3516   // semantics of getCallerClass(), however, are that the "first"
  3517   // frame is the getCallerClass() frame, so we subtract one from the
  3518   // requested depth before continuing. We don't inline requests of
  3519   // getCallerClass(0).
  3520   int caller_depth = caller_depth_type->get_con() - 1;
  3521   if (caller_depth < 0) {
  3522 #ifndef PRODUCT
  3523     if ((PrintIntrinsics || PrintInlining || PrintOptoInlining) && Verbose) {
  3524       tty->print_cr("  Bailing out because caller depth was %d", caller_depth);
  3526 #endif
  3527     return false;
  3530   if (!jvms()->has_method()) {
  3531 #ifndef PRODUCT
  3532     if ((PrintIntrinsics || PrintInlining || PrintOptoInlining) && Verbose) {
  3533       tty->print_cr("  Bailing out because intrinsic was inlined at top level");
  3535 #endif
  3536     return false;
  3538   int _depth = jvms()->depth();  // cache call chain depth
  3540   // Walk back up the JVM state to find the caller at the required
  3541   // depth. NOTE that this code must perform the same logic as
  3542   // vframeStream::security_get_caller_frame in that it must skip
  3543   // Method.invoke() and auxiliary frames. Note also that depth is
  3544   // 1-based (1 is the bottom of the inlining).
  3545   int inlining_depth = _depth;
  3546   JVMState* caller_jvms = NULL;
  3548   if (inlining_depth > 0) {
  3549     caller_jvms = jvms();
  3550     assert(caller_jvms = jvms()->of_depth(inlining_depth), "inlining_depth == our depth");
  3551     do {
  3552       // The following if-tests should be performed in this order
  3553       if (is_method_invoke_or_aux_frame(caller_jvms)) {
  3554         // Skip a Method.invoke() or auxiliary frame
  3555       } else if (caller_depth > 0) {
  3556         // Skip real frame
  3557         --caller_depth;
  3558       } else {
  3559         // We're done: reached desired caller after skipping.
  3560         break;
  3562       caller_jvms = caller_jvms->caller();
  3563       --inlining_depth;
  3564     } while (inlining_depth > 0);
  3567   if (inlining_depth == 0) {
  3568 #ifndef PRODUCT
  3569     if ((PrintIntrinsics || PrintInlining || PrintOptoInlining) && Verbose) {
  3570       tty->print_cr("  Bailing out because caller depth (%d) exceeded inlining depth (%d)", caller_depth_type->get_con(), _depth);
  3571       tty->print_cr("  JVM state at this point:");
  3572       for (int i = _depth; i >= 1; i--) {
  3573         tty->print_cr("   %d) %s", i, jvms()->of_depth(i)->method()->name()->as_utf8());
  3576 #endif
  3577     return false; // Reached end of inlining
  3580   // Acquire method holder as java.lang.Class
  3581   ciInstanceKlass* caller_klass  = caller_jvms->method()->holder();
  3582   ciInstance*      caller_mirror = caller_klass->java_mirror();
  3583   // Push this as a constant
  3584   push(makecon(TypeInstPtr::make(caller_mirror)));
  3585 #ifndef PRODUCT
  3586   if ((PrintIntrinsics || PrintInlining || PrintOptoInlining) && Verbose) {
  3587     tty->print_cr("  Succeeded: caller = %s.%s, caller depth = %d, depth = %d", caller_klass->name()->as_utf8(), caller_jvms->method()->name()->as_utf8(), caller_depth_type->get_con(), _depth);
  3588     tty->print_cr("  JVM state at this point:");
  3589     for (int i = _depth; i >= 1; i--) {
  3590       tty->print_cr("   %d) %s", i, jvms()->of_depth(i)->method()->name()->as_utf8());
  3593 #endif
  3594   return true;
  3597 // Helper routine for above
  3598 bool LibraryCallKit::is_method_invoke_or_aux_frame(JVMState* jvms) {
  3599   // Is this the Method.invoke method itself?
  3600   if (jvms->method()->intrinsic_id() == vmIntrinsics::_invoke)
  3601     return true;
  3603   // Is this a helper, defined somewhere underneath MethodAccessorImpl.
  3604   ciKlass* k = jvms->method()->holder();
  3605   if (k->is_instance_klass()) {
  3606     ciInstanceKlass* ik = k->as_instance_klass();
  3607     for (; ik != NULL; ik = ik->super()) {
  3608       if (ik->name() == ciSymbol::sun_reflect_MethodAccessorImpl() &&
  3609           ik == env()->find_system_klass(ik->name())) {
  3610         return true;
  3615   return false;
  3618 static int value_field_offset = -1;  // offset of the "value" field of AtomicLongCSImpl.  This is needed by
  3619                                      // inline_native_AtomicLong_attemptUpdate() but it has no way of
  3620                                      // computing it since there is no lookup field by name function in the
  3621                                      // CI interface.  This is computed and set by inline_native_AtomicLong_get().
  3622                                      // Using a static variable here is safe even if we have multiple compilation
  3623                                      // threads because the offset is constant.  At worst the same offset will be
  3624                                      // computed and  stored multiple
  3626 bool LibraryCallKit::inline_native_AtomicLong_get() {
  3627   // Restore the stack and pop off the argument
  3628   _sp+=1;
  3629   Node *obj = pop();
  3631   // get the offset of the "value" field. Since the CI interfaces
  3632   // does not provide a way to look up a field by name, we scan the bytecodes
  3633   // to get the field index.  We expect the first 2 instructions of the method
  3634   // to be:
  3635   //    0 aload_0
  3636   //    1 getfield "value"
  3637   ciMethod* method = callee();
  3638   if (value_field_offset == -1)
  3640     ciField* value_field;
  3641     ciBytecodeStream iter(method);
  3642     Bytecodes::Code bc = iter.next();
  3644     if ((bc != Bytecodes::_aload_0) &&
  3645               ((bc != Bytecodes::_aload) || (iter.get_index() != 0)))
  3646       return false;
  3647     bc = iter.next();
  3648     if (bc != Bytecodes::_getfield)
  3649       return false;
  3650     bool ignore;
  3651     value_field = iter.get_field(ignore);
  3652     value_field_offset = value_field->offset_in_bytes();
  3655   // Null check without removing any arguments.
  3656   _sp++;
  3657   obj = do_null_check(obj, T_OBJECT);
  3658   _sp--;
  3659   // Check for locking null object
  3660   if (stopped()) return true;
  3662   Node *adr = basic_plus_adr(obj, obj, value_field_offset);
  3663   const TypePtr *adr_type = _gvn.type(adr)->is_ptr();
  3664   int alias_idx = C->get_alias_index(adr_type);
  3666   Node *result = _gvn.transform(new (C, 3) LoadLLockedNode(control(), memory(alias_idx), adr));
  3668   push_pair(result);
  3670   return true;
  3673 bool LibraryCallKit::inline_native_AtomicLong_attemptUpdate() {
  3674   // Restore the stack and pop off the arguments
  3675   _sp+=5;
  3676   Node *newVal = pop_pair();
  3677   Node *oldVal = pop_pair();
  3678   Node *obj = pop();
  3680   // we need the offset of the "value" field which was computed when
  3681   // inlining the get() method.  Give up if we don't have it.
  3682   if (value_field_offset == -1)
  3683     return false;
  3685   // Null check without removing any arguments.
  3686   _sp+=5;
  3687   obj = do_null_check(obj, T_OBJECT);
  3688   _sp-=5;
  3689   // Check for locking null object
  3690   if (stopped()) return true;
  3692   Node *adr = basic_plus_adr(obj, obj, value_field_offset);
  3693   const TypePtr *adr_type = _gvn.type(adr)->is_ptr();
  3694   int alias_idx = C->get_alias_index(adr_type);
  3696   Node *cas = _gvn.transform(new (C, 5) StoreLConditionalNode(control(), memory(alias_idx), adr, newVal, oldVal));
  3697   Node *store_proj = _gvn.transform( new (C, 1) SCMemProjNode(cas));
  3698   set_memory(store_proj, alias_idx);
  3699   Node *bol = _gvn.transform( new (C, 2) BoolNode( cas, BoolTest::eq ) );
  3701   Node *result;
  3702   // CMove node is not used to be able fold a possible check code
  3703   // after attemptUpdate() call. This code could be transformed
  3704   // into CMove node by loop optimizations.
  3706     RegionNode *r = new (C, 3) RegionNode(3);
  3707     result = new (C, 3) PhiNode(r, TypeInt::BOOL);
  3709     Node *iff = create_and_xform_if(control(), bol, PROB_FAIR, COUNT_UNKNOWN);
  3710     Node *iftrue = opt_iff(r, iff);
  3711     r->init_req(1, iftrue);
  3712     result->init_req(1, intcon(1));
  3713     result->init_req(2, intcon(0));
  3715     set_control(_gvn.transform(r));
  3716     record_for_igvn(r);
  3718     C->set_has_split_ifs(true); // Has chance for split-if optimization
  3721   push(_gvn.transform(result));
  3722   return true;
  3725 bool LibraryCallKit::inline_fp_conversions(vmIntrinsics::ID id) {
  3726   // restore the arguments
  3727   _sp += arg_size();
  3729   switch (id) {
  3730   case vmIntrinsics::_floatToRawIntBits:
  3731     push(_gvn.transform( new (C, 2) MoveF2INode(pop())));
  3732     break;
  3734   case vmIntrinsics::_intBitsToFloat:
  3735     push(_gvn.transform( new (C, 2) MoveI2FNode(pop())));
  3736     break;
  3738   case vmIntrinsics::_doubleToRawLongBits:
  3739     push_pair(_gvn.transform( new (C, 2) MoveD2LNode(pop_pair())));
  3740     break;
  3742   case vmIntrinsics::_longBitsToDouble:
  3743     push_pair(_gvn.transform( new (C, 2) MoveL2DNode(pop_pair())));
  3744     break;
  3746   case vmIntrinsics::_doubleToLongBits: {
  3747     Node* value = pop_pair();
  3749     // two paths (plus control) merge in a wood
  3750     RegionNode *r = new (C, 3) RegionNode(3);
  3751     Node *phi = new (C, 3) PhiNode(r, TypeLong::LONG);
  3753     Node *cmpisnan = _gvn.transform( new (C, 3) CmpDNode(value, value));
  3754     // Build the boolean node
  3755     Node *bolisnan = _gvn.transform( new (C, 2) BoolNode( cmpisnan, BoolTest::ne ) );
  3757     // Branch either way.
  3758     // NaN case is less traveled, which makes all the difference.
  3759     IfNode *ifisnan = create_and_xform_if(control(), bolisnan, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
  3760     Node *opt_isnan = _gvn.transform(ifisnan);
  3761     assert( opt_isnan->is_If(), "Expect an IfNode");
  3762     IfNode *opt_ifisnan = (IfNode*)opt_isnan;
  3763     Node *iftrue = _gvn.transform( new (C, 1) IfTrueNode(opt_ifisnan) );
  3765     set_control(iftrue);
  3767     static const jlong nan_bits = CONST64(0x7ff8000000000000);
  3768     Node *slow_result = longcon(nan_bits); // return NaN
  3769     phi->init_req(1, _gvn.transform( slow_result ));
  3770     r->init_req(1, iftrue);
  3772     // Else fall through
  3773     Node *iffalse = _gvn.transform( new (C, 1) IfFalseNode(opt_ifisnan) );
  3774     set_control(iffalse);
  3776     phi->init_req(2, _gvn.transform( new (C, 2) MoveD2LNode(value)));
  3777     r->init_req(2, iffalse);
  3779     // Post merge
  3780     set_control(_gvn.transform(r));
  3781     record_for_igvn(r);
  3783     Node* result = _gvn.transform(phi);
  3784     assert(result->bottom_type()->isa_long(), "must be");
  3785     push_pair(result);
  3787     C->set_has_split_ifs(true); // Has chance for split-if optimization
  3789     break;
  3792   case vmIntrinsics::_floatToIntBits: {
  3793     Node* value = pop();
  3795     // two paths (plus control) merge in a wood
  3796     RegionNode *r = new (C, 3) RegionNode(3);
  3797     Node *phi = new (C, 3) PhiNode(r, TypeInt::INT);
  3799     Node *cmpisnan = _gvn.transform( new (C, 3) CmpFNode(value, value));
  3800     // Build the boolean node
  3801     Node *bolisnan = _gvn.transform( new (C, 2) BoolNode( cmpisnan, BoolTest::ne ) );
  3803     // Branch either way.
  3804     // NaN case is less traveled, which makes all the difference.
  3805     IfNode *ifisnan = create_and_xform_if(control(), bolisnan, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
  3806     Node *opt_isnan = _gvn.transform(ifisnan);
  3807     assert( opt_isnan->is_If(), "Expect an IfNode");
  3808     IfNode *opt_ifisnan = (IfNode*)opt_isnan;
  3809     Node *iftrue = _gvn.transform( new (C, 1) IfTrueNode(opt_ifisnan) );
  3811     set_control(iftrue);
  3813     static const jint nan_bits = 0x7fc00000;
  3814     Node *slow_result = makecon(TypeInt::make(nan_bits)); // return NaN
  3815     phi->init_req(1, _gvn.transform( slow_result ));
  3816     r->init_req(1, iftrue);
  3818     // Else fall through
  3819     Node *iffalse = _gvn.transform( new (C, 1) IfFalseNode(opt_ifisnan) );
  3820     set_control(iffalse);
  3822     phi->init_req(2, _gvn.transform( new (C, 2) MoveF2INode(value)));
  3823     r->init_req(2, iffalse);
  3825     // Post merge
  3826     set_control(_gvn.transform(r));
  3827     record_for_igvn(r);
  3829     Node* result = _gvn.transform(phi);
  3830     assert(result->bottom_type()->isa_int(), "must be");
  3831     push(result);
  3833     C->set_has_split_ifs(true); // Has chance for split-if optimization
  3835     break;
  3838   default:
  3839     ShouldNotReachHere();
  3842   return true;
  3845 #ifdef _LP64
  3846 #define XTOP ,top() /*additional argument*/
  3847 #else  //_LP64
  3848 #define XTOP        /*no additional argument*/
  3849 #endif //_LP64
  3851 //----------------------inline_unsafe_copyMemory-------------------------
  3852 bool LibraryCallKit::inline_unsafe_copyMemory() {
  3853   if (callee()->is_static())  return false;  // caller must have the capability!
  3854   int nargs = 1 + 5 + 3;  // 5 args:  (src: ptr,off, dst: ptr,off, size)
  3855   assert(signature()->size() == nargs-1, "copy has 5 arguments");
  3856   null_check_receiver(callee());  // check then ignore argument(0)
  3857   if (stopped())  return true;
  3859   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
  3861   Node* src_ptr = argument(1);
  3862   Node* src_off = ConvL2X(argument(2));
  3863   assert(argument(3)->is_top(), "2nd half of long");
  3864   Node* dst_ptr = argument(4);
  3865   Node* dst_off = ConvL2X(argument(5));
  3866   assert(argument(6)->is_top(), "2nd half of long");
  3867   Node* size    = ConvL2X(argument(7));
  3868   assert(argument(8)->is_top(), "2nd half of long");
  3870   assert(Unsafe_field_offset_to_byte_offset(11) == 11,
  3871          "fieldOffset must be byte-scaled");
  3873   Node* src = make_unsafe_address(src_ptr, src_off);
  3874   Node* dst = make_unsafe_address(dst_ptr, dst_off);
  3876   // Conservatively insert a memory barrier on all memory slices.
  3877   // Do not let writes of the copy source or destination float below the copy.
  3878   insert_mem_bar(Op_MemBarCPUOrder);
  3880   // Call it.  Note that the length argument is not scaled.
  3881   make_runtime_call(RC_LEAF|RC_NO_FP,
  3882                     OptoRuntime::fast_arraycopy_Type(),
  3883                     StubRoutines::unsafe_arraycopy(),
  3884                     "unsafe_arraycopy",
  3885                     TypeRawPtr::BOTTOM,
  3886                     src, dst, size XTOP);
  3888   // Do not let reads of the copy destination float above the copy.
  3889   insert_mem_bar(Op_MemBarCPUOrder);
  3891   return true;
  3894 //------------------------clone_coping-----------------------------------
  3895 // Helper function for inline_native_clone.
  3896 void LibraryCallKit::copy_to_clone(Node* obj, Node* alloc_obj, Node* obj_size, bool is_array, bool card_mark) {
  3897   assert(obj_size != NULL, "");
  3898   Node* raw_obj = alloc_obj->in(1);
  3899   assert(alloc_obj->is_CheckCastPP() && raw_obj->is_Proj() && raw_obj->in(0)->is_Allocate(), "");
  3901   if (ReduceBulkZeroing) {
  3902     // We will be completely responsible for initializing this object -
  3903     // mark Initialize node as complete.
  3904     AllocateNode* alloc = AllocateNode::Ideal_allocation(alloc_obj, &_gvn);
  3905     // The object was just allocated - there should be no any stores!
  3906     guarantee(alloc != NULL && alloc->maybe_set_complete(&_gvn), "");
  3909   // Cast to Object for arraycopy.
  3910   // We can't use the original CheckCastPP since it should be moved
  3911   // after the arraycopy to prevent stores flowing above it.
  3912   Node* new_obj = new(C, 2) CheckCastPPNode(alloc_obj->in(0), raw_obj,
  3913                                             TypeInstPtr::NOTNULL);
  3914   new_obj = _gvn.transform(new_obj);
  3915   // Substitute in the locally valid dest_oop.
  3916   replace_in_map(alloc_obj, new_obj);
  3918   // Copy the fastest available way.
  3919   // TODO: generate fields copies for small objects instead.
  3920   Node* src  = obj;
  3921   Node* dest = new_obj;
  3922   Node* size = _gvn.transform(obj_size);
  3924   // Exclude the header but include array length to copy by 8 bytes words.
  3925   // Can't use base_offset_in_bytes(bt) since basic type is unknown.
  3926   int base_off = is_array ? arrayOopDesc::length_offset_in_bytes() :
  3927                             instanceOopDesc::base_offset_in_bytes();
  3928   // base_off:
  3929   // 8  - 32-bit VM
  3930   // 12 - 64-bit VM, compressed oops
  3931   // 16 - 64-bit VM, normal oops
  3932   if (base_off % BytesPerLong != 0) {
  3933     assert(UseCompressedOops, "");
  3934     if (is_array) {
  3935       // Exclude length to copy by 8 bytes words.
  3936       base_off += sizeof(int);
  3937     } else {
  3938       // Include klass to copy by 8 bytes words.
  3939       base_off = instanceOopDesc::klass_offset_in_bytes();
  3941     assert(base_off % BytesPerLong == 0, "expect 8 bytes alignment");
  3943   src  = basic_plus_adr(src,  base_off);
  3944   dest = basic_plus_adr(dest, base_off);
  3946   // Compute the length also, if needed:
  3947   Node* countx = size;
  3948   countx = _gvn.transform( new (C, 3) SubXNode(countx, MakeConX(base_off)) );
  3949   countx = _gvn.transform( new (C, 3) URShiftXNode(countx, intcon(LogBytesPerLong) ));
  3951   const TypePtr* raw_adr_type = TypeRawPtr::BOTTOM;
  3952   bool disjoint_bases = true;
  3953   generate_unchecked_arraycopy(raw_adr_type, T_LONG, disjoint_bases,
  3954                                src, NULL, dest, NULL, countx);
  3956   // If necessary, emit some card marks afterwards.  (Non-arrays only.)
  3957   if (card_mark) {
  3958     assert(!is_array, "");
  3959     // Put in store barrier for any and all oops we are sticking
  3960     // into this object.  (We could avoid this if we could prove
  3961     // that the object type contains no oop fields at all.)
  3962     Node* no_particular_value = NULL;
  3963     Node* no_particular_field = NULL;
  3964     int raw_adr_idx = Compile::AliasIdxRaw;
  3965     post_barrier(control(),
  3966                  memory(raw_adr_type),
  3967                  new_obj,
  3968                  no_particular_field,
  3969                  raw_adr_idx,
  3970                  no_particular_value,
  3971                  T_OBJECT,
  3972                  false);
  3975   // Move the original CheckCastPP after arraycopy.
  3976   _gvn.hash_delete(alloc_obj);
  3977   alloc_obj->set_req(0, control());
  3978   // Replace raw memory edge with new CheckCastPP to have a live oop
  3979   // at safepoints instead of raw value.
  3980   assert(new_obj->is_CheckCastPP() && new_obj->in(1) == alloc_obj->in(1), "sanity");
  3981   alloc_obj->set_req(1, new_obj);    // cast to the original type
  3982   _gvn.hash_find_insert(alloc_obj);  // put back into GVN table
  3983   // Restore in the locally valid dest_oop.
  3984   replace_in_map(new_obj, alloc_obj);
  3987 //------------------------inline_native_clone----------------------------
  3988 // Here are the simple edge cases:
  3989 //  null receiver => normal trap
  3990 //  virtual and clone was overridden => slow path to out-of-line clone
  3991 //  not cloneable or finalizer => slow path to out-of-line Object.clone
  3992 //
  3993 // The general case has two steps, allocation and copying.
  3994 // Allocation has two cases, and uses GraphKit::new_instance or new_array.
  3995 //
  3996 // Copying also has two cases, oop arrays and everything else.
  3997 // Oop arrays use arrayof_oop_arraycopy (same as System.arraycopy).
  3998 // Everything else uses the tight inline loop supplied by CopyArrayNode.
  3999 //
  4000 // These steps fold up nicely if and when the cloned object's klass
  4001 // can be sharply typed as an object array, a type array, or an instance.
  4002 //
  4003 bool LibraryCallKit::inline_native_clone(bool is_virtual) {
  4004   int nargs = 1;
  4005   Node* obj = null_check_receiver(callee());
  4006   if (stopped())  return true;
  4007   Node* obj_klass = load_object_klass(obj);
  4008   const TypeKlassPtr* tklass = _gvn.type(obj_klass)->isa_klassptr();
  4009   const TypeOopPtr*   toop   = ((tklass != NULL)
  4010                                 ? tklass->as_instance_type()
  4011                                 : TypeInstPtr::NOTNULL);
  4013   // Conservatively insert a memory barrier on all memory slices.
  4014   // Do not let writes into the original float below the clone.
  4015   insert_mem_bar(Op_MemBarCPUOrder);
  4017   // paths into result_reg:
  4018   enum {
  4019     _slow_path = 1,     // out-of-line call to clone method (virtual or not)
  4020     _objArray_path,     // plain array allocation, plus arrayof_oop_arraycopy
  4021     _array_path,        // plain array allocation, plus arrayof_long_arraycopy
  4022     _instance_path,     // plain instance allocation, plus arrayof_long_arraycopy
  4023     PATH_LIMIT
  4024   };
  4025   RegionNode* result_reg = new(C, PATH_LIMIT) RegionNode(PATH_LIMIT);
  4026   PhiNode*    result_val = new(C, PATH_LIMIT) PhiNode(result_reg,
  4027                                                       TypeInstPtr::NOTNULL);
  4028   PhiNode*    result_i_o = new(C, PATH_LIMIT) PhiNode(result_reg, Type::ABIO);
  4029   PhiNode*    result_mem = new(C, PATH_LIMIT) PhiNode(result_reg, Type::MEMORY,
  4030                                                       TypePtr::BOTTOM);
  4031   record_for_igvn(result_reg);
  4033   const TypePtr* raw_adr_type = TypeRawPtr::BOTTOM;
  4034   int raw_adr_idx = Compile::AliasIdxRaw;
  4035   const bool raw_mem_only = true;
  4037   Node* array_ctl = generate_array_guard(obj_klass, (RegionNode*)NULL);
  4038   if (array_ctl != NULL) {
  4039     // It's an array.
  4040     PreserveJVMState pjvms(this);
  4041     set_control(array_ctl);
  4042     Node* obj_length = load_array_length(obj);
  4043     Node* obj_size = NULL;
  4044     Node* alloc_obj = new_array(obj_klass, obj_length, nargs,
  4045                                 raw_mem_only, &obj_size);
  4047     if (!use_ReduceInitialCardMarks()) {
  4048       // If it is an oop array, it requires very special treatment,
  4049       // because card marking is required on each card of the array.
  4050       Node* is_obja = generate_objArray_guard(obj_klass, (RegionNode*)NULL);
  4051       if (is_obja != NULL) {
  4052         PreserveJVMState pjvms2(this);
  4053         set_control(is_obja);
  4054         // Generate a direct call to the right arraycopy function(s).
  4055         bool disjoint_bases = true;
  4056         bool length_never_negative = true;
  4057         generate_arraycopy(TypeAryPtr::OOPS, T_OBJECT,
  4058                            obj, intcon(0), alloc_obj, intcon(0),
  4059                            obj_length,
  4060                            disjoint_bases, length_never_negative);
  4061         result_reg->init_req(_objArray_path, control());
  4062         result_val->init_req(_objArray_path, alloc_obj);
  4063         result_i_o ->set_req(_objArray_path, i_o());
  4064         result_mem ->set_req(_objArray_path, reset_memory());
  4067     // We can dispense with card marks if we know the allocation
  4068     // comes out of eden (TLAB)...  In fact, ReduceInitialCardMarks
  4069     // causes the non-eden paths to simulate a fresh allocation,
  4070     // insofar that no further card marks are required to initialize
  4071     // the object.
  4073     // Otherwise, there are no card marks to worry about.
  4075     if (!stopped()) {
  4076       copy_to_clone(obj, alloc_obj, obj_size, true, false);
  4078       // Present the results of the copy.
  4079       result_reg->init_req(_array_path, control());
  4080       result_val->init_req(_array_path, alloc_obj);
  4081       result_i_o ->set_req(_array_path, i_o());
  4082       result_mem ->set_req(_array_path, reset_memory());
  4086   // We only go to the instance fast case code if we pass a number of guards.
  4087   // The paths which do not pass are accumulated in the slow_region.
  4088   RegionNode* slow_region = new (C, 1) RegionNode(1);
  4089   record_for_igvn(slow_region);
  4090   if (!stopped()) {
  4091     // It's an instance (we did array above).  Make the slow-path tests.
  4092     // If this is a virtual call, we generate a funny guard.  We grab
  4093     // the vtable entry corresponding to clone() from the target object.
  4094     // If the target method which we are calling happens to be the
  4095     // Object clone() method, we pass the guard.  We do not need this
  4096     // guard for non-virtual calls; the caller is known to be the native
  4097     // Object clone().
  4098     if (is_virtual) {
  4099       generate_virtual_guard(obj_klass, slow_region);
  4102     // The object must be cloneable and must not have a finalizer.
  4103     // Both of these conditions may be checked in a single test.
  4104     // We could optimize the cloneable test further, but we don't care.
  4105     generate_access_flags_guard(obj_klass,
  4106                                 // Test both conditions:
  4107                                 JVM_ACC_IS_CLONEABLE | JVM_ACC_HAS_FINALIZER,
  4108                                 // Must be cloneable but not finalizer:
  4109                                 JVM_ACC_IS_CLONEABLE,
  4110                                 slow_region);
  4113   if (!stopped()) {
  4114     // It's an instance, and it passed the slow-path tests.
  4115     PreserveJVMState pjvms(this);
  4116     Node* obj_size = NULL;
  4117     Node* alloc_obj = new_instance(obj_klass, NULL, raw_mem_only, &obj_size);
  4119     copy_to_clone(obj, alloc_obj, obj_size, false, !use_ReduceInitialCardMarks());
  4121     // Present the results of the slow call.
  4122     result_reg->init_req(_instance_path, control());
  4123     result_val->init_req(_instance_path, alloc_obj);
  4124     result_i_o ->set_req(_instance_path, i_o());
  4125     result_mem ->set_req(_instance_path, reset_memory());
  4128   // Generate code for the slow case.  We make a call to clone().
  4129   set_control(_gvn.transform(slow_region));
  4130   if (!stopped()) {
  4131     PreserveJVMState pjvms(this);
  4132     CallJavaNode* slow_call = generate_method_call(vmIntrinsics::_clone, is_virtual);
  4133     Node* slow_result = set_results_for_java_call(slow_call);
  4134     // this->control() comes from set_results_for_java_call
  4135     result_reg->init_req(_slow_path, control());
  4136     result_val->init_req(_slow_path, slow_result);
  4137     result_i_o ->set_req(_slow_path, i_o());
  4138     result_mem ->set_req(_slow_path, reset_memory());
  4141   // Return the combined state.
  4142   set_control(    _gvn.transform(result_reg) );
  4143   set_i_o(        _gvn.transform(result_i_o) );
  4144   set_all_memory( _gvn.transform(result_mem) );
  4146   push(_gvn.transform(result_val));
  4148   return true;
  4152 // constants for computing the copy function
  4153 enum {
  4154   COPYFUNC_UNALIGNED = 0,
  4155   COPYFUNC_ALIGNED = 1,                 // src, dest aligned to HeapWordSize
  4156   COPYFUNC_CONJOINT = 0,
  4157   COPYFUNC_DISJOINT = 2                 // src != dest, or transfer can descend
  4158 };
  4160 // Note:  The condition "disjoint" applies also for overlapping copies
  4161 // where an descending copy is permitted (i.e., dest_offset <= src_offset).
  4162 static address
  4163 select_arraycopy_function(BasicType t, bool aligned, bool disjoint, const char* &name) {
  4164   int selector =
  4165     (aligned  ? COPYFUNC_ALIGNED  : COPYFUNC_UNALIGNED) +
  4166     (disjoint ? COPYFUNC_DISJOINT : COPYFUNC_CONJOINT);
  4168 #define RETURN_STUB(xxx_arraycopy) { \
  4169   name = #xxx_arraycopy; \
  4170   return StubRoutines::xxx_arraycopy(); }
  4172   switch (t) {
  4173   case T_BYTE:
  4174   case T_BOOLEAN:
  4175     switch (selector) {
  4176     case COPYFUNC_CONJOINT | COPYFUNC_UNALIGNED:  RETURN_STUB(jbyte_arraycopy);
  4177     case COPYFUNC_CONJOINT | COPYFUNC_ALIGNED:    RETURN_STUB(arrayof_jbyte_arraycopy);
  4178     case COPYFUNC_DISJOINT | COPYFUNC_UNALIGNED:  RETURN_STUB(jbyte_disjoint_arraycopy);
  4179     case COPYFUNC_DISJOINT | COPYFUNC_ALIGNED:    RETURN_STUB(arrayof_jbyte_disjoint_arraycopy);
  4181   case T_CHAR:
  4182   case T_SHORT:
  4183     switch (selector) {
  4184     case COPYFUNC_CONJOINT | COPYFUNC_UNALIGNED:  RETURN_STUB(jshort_arraycopy);
  4185     case COPYFUNC_CONJOINT | COPYFUNC_ALIGNED:    RETURN_STUB(arrayof_jshort_arraycopy);
  4186     case COPYFUNC_DISJOINT | COPYFUNC_UNALIGNED:  RETURN_STUB(jshort_disjoint_arraycopy);
  4187     case COPYFUNC_DISJOINT | COPYFUNC_ALIGNED:    RETURN_STUB(arrayof_jshort_disjoint_arraycopy);
  4189   case T_INT:
  4190   case T_FLOAT:
  4191     switch (selector) {
  4192     case COPYFUNC_CONJOINT | COPYFUNC_UNALIGNED:  RETURN_STUB(jint_arraycopy);
  4193     case COPYFUNC_CONJOINT | COPYFUNC_ALIGNED:    RETURN_STUB(arrayof_jint_arraycopy);
  4194     case COPYFUNC_DISJOINT | COPYFUNC_UNALIGNED:  RETURN_STUB(jint_disjoint_arraycopy);
  4195     case COPYFUNC_DISJOINT | COPYFUNC_ALIGNED:    RETURN_STUB(arrayof_jint_disjoint_arraycopy);
  4197   case T_DOUBLE:
  4198   case T_LONG:
  4199     switch (selector) {
  4200     case COPYFUNC_CONJOINT | COPYFUNC_UNALIGNED:  RETURN_STUB(jlong_arraycopy);
  4201     case COPYFUNC_CONJOINT | COPYFUNC_ALIGNED:    RETURN_STUB(arrayof_jlong_arraycopy);
  4202     case COPYFUNC_DISJOINT | COPYFUNC_UNALIGNED:  RETURN_STUB(jlong_disjoint_arraycopy);
  4203     case COPYFUNC_DISJOINT | COPYFUNC_ALIGNED:    RETURN_STUB(arrayof_jlong_disjoint_arraycopy);
  4205   case T_ARRAY:
  4206   case T_OBJECT:
  4207     switch (selector) {
  4208     case COPYFUNC_CONJOINT | COPYFUNC_UNALIGNED:  RETURN_STUB(oop_arraycopy);
  4209     case COPYFUNC_CONJOINT | COPYFUNC_ALIGNED:    RETURN_STUB(arrayof_oop_arraycopy);
  4210     case COPYFUNC_DISJOINT | COPYFUNC_UNALIGNED:  RETURN_STUB(oop_disjoint_arraycopy);
  4211     case COPYFUNC_DISJOINT | COPYFUNC_ALIGNED:    RETURN_STUB(arrayof_oop_disjoint_arraycopy);
  4213   default:
  4214     ShouldNotReachHere();
  4215     return NULL;
  4218 #undef RETURN_STUB
  4221 //------------------------------basictype2arraycopy----------------------------
  4222 address LibraryCallKit::basictype2arraycopy(BasicType t,
  4223                                             Node* src_offset,
  4224                                             Node* dest_offset,
  4225                                             bool disjoint_bases,
  4226                                             const char* &name) {
  4227   const TypeInt* src_offset_inttype  = gvn().find_int_type(src_offset);;
  4228   const TypeInt* dest_offset_inttype = gvn().find_int_type(dest_offset);;
  4230   bool aligned = false;
  4231   bool disjoint = disjoint_bases;
  4233   // if the offsets are the same, we can treat the memory regions as
  4234   // disjoint, because either the memory regions are in different arrays,
  4235   // or they are identical (which we can treat as disjoint.)  We can also
  4236   // treat a copy with a destination index  less that the source index
  4237   // as disjoint since a low->high copy will work correctly in this case.
  4238   if (src_offset_inttype != NULL && src_offset_inttype->is_con() &&
  4239       dest_offset_inttype != NULL && dest_offset_inttype->is_con()) {
  4240     // both indices are constants
  4241     int s_offs = src_offset_inttype->get_con();
  4242     int d_offs = dest_offset_inttype->get_con();
  4243     int element_size = type2aelembytes(t);
  4244     aligned = ((arrayOopDesc::base_offset_in_bytes(t) + s_offs * element_size) % HeapWordSize == 0) &&
  4245               ((arrayOopDesc::base_offset_in_bytes(t) + d_offs * element_size) % HeapWordSize == 0);
  4246     if (s_offs >= d_offs)  disjoint = true;
  4247   } else if (src_offset == dest_offset && src_offset != NULL) {
  4248     // This can occur if the offsets are identical non-constants.
  4249     disjoint = true;
  4252   return select_arraycopy_function(t, aligned, disjoint, name);
  4256 //------------------------------inline_arraycopy-----------------------
  4257 bool LibraryCallKit::inline_arraycopy() {
  4258   // Restore the stack and pop off the arguments.
  4259   int nargs = 5;  // 2 oops, 3 ints, no size_t or long
  4260   assert(callee()->signature()->size() == nargs, "copy has 5 arguments");
  4262   Node *src         = argument(0);
  4263   Node *src_offset  = argument(1);
  4264   Node *dest        = argument(2);
  4265   Node *dest_offset = argument(3);
  4266   Node *length      = argument(4);
  4268   // Compile time checks.  If any of these checks cannot be verified at compile time,
  4269   // we do not make a fast path for this call.  Instead, we let the call remain as it
  4270   // is.  The checks we choose to mandate at compile time are:
  4271   //
  4272   // (1) src and dest are arrays.
  4273   const Type* src_type = src->Value(&_gvn);
  4274   const Type* dest_type = dest->Value(&_gvn);
  4275   const TypeAryPtr* top_src = src_type->isa_aryptr();
  4276   const TypeAryPtr* top_dest = dest_type->isa_aryptr();
  4277   if (top_src  == NULL || top_src->klass()  == NULL ||
  4278       top_dest == NULL || top_dest->klass() == NULL) {
  4279     // Conservatively insert a memory barrier on all memory slices.
  4280     // Do not let writes into the source float below the arraycopy.
  4281     insert_mem_bar(Op_MemBarCPUOrder);
  4283     // Call StubRoutines::generic_arraycopy stub.
  4284     generate_arraycopy(TypeRawPtr::BOTTOM, T_CONFLICT,
  4285                        src, src_offset, dest, dest_offset, length);
  4287     // Do not let reads from the destination float above the arraycopy.
  4288     // Since we cannot type the arrays, we don't know which slices
  4289     // might be affected.  We could restrict this barrier only to those
  4290     // memory slices which pertain to array elements--but don't bother.
  4291     if (!InsertMemBarAfterArraycopy)
  4292       // (If InsertMemBarAfterArraycopy, there is already one in place.)
  4293       insert_mem_bar(Op_MemBarCPUOrder);
  4294     return true;
  4297   // (2) src and dest arrays must have elements of the same BasicType
  4298   // Figure out the size and type of the elements we will be copying.
  4299   BasicType src_elem  =  top_src->klass()->as_array_klass()->element_type()->basic_type();
  4300   BasicType dest_elem = top_dest->klass()->as_array_klass()->element_type()->basic_type();
  4301   if (src_elem  == T_ARRAY)  src_elem  = T_OBJECT;
  4302   if (dest_elem == T_ARRAY)  dest_elem = T_OBJECT;
  4304   if (src_elem != dest_elem || dest_elem == T_VOID) {
  4305     // The component types are not the same or are not recognized.  Punt.
  4306     // (But, avoid the native method wrapper to JVM_ArrayCopy.)
  4307     generate_slow_arraycopy(TypePtr::BOTTOM,
  4308                             src, src_offset, dest, dest_offset, length);
  4309     return true;
  4312   //---------------------------------------------------------------------------
  4313   // We will make a fast path for this call to arraycopy.
  4315   // We have the following tests left to perform:
  4316   //
  4317   // (3) src and dest must not be null.
  4318   // (4) src_offset must not be negative.
  4319   // (5) dest_offset must not be negative.
  4320   // (6) length must not be negative.
  4321   // (7) src_offset + length must not exceed length of src.
  4322   // (8) dest_offset + length must not exceed length of dest.
  4323   // (9) each element of an oop array must be assignable
  4325   RegionNode* slow_region = new (C, 1) RegionNode(1);
  4326   record_for_igvn(slow_region);
  4328   // (3) operands must not be null
  4329   // We currently perform our null checks with the do_null_check routine.
  4330   // This means that the null exceptions will be reported in the caller
  4331   // rather than (correctly) reported inside of the native arraycopy call.
  4332   // This should be corrected, given time.  We do our null check with the
  4333   // stack pointer restored.
  4334   _sp += nargs;
  4335   src  = do_null_check(src,  T_ARRAY);
  4336   dest = do_null_check(dest, T_ARRAY);
  4337   _sp -= nargs;
  4339   // (4) src_offset must not be negative.
  4340   generate_negative_guard(src_offset, slow_region);
  4342   // (5) dest_offset must not be negative.
  4343   generate_negative_guard(dest_offset, slow_region);
  4345   // (6) length must not be negative (moved to generate_arraycopy()).
  4346   // generate_negative_guard(length, slow_region);
  4348   // (7) src_offset + length must not exceed length of src.
  4349   generate_limit_guard(src_offset, length,
  4350                        load_array_length(src),
  4351                        slow_region);
  4353   // (8) dest_offset + length must not exceed length of dest.
  4354   generate_limit_guard(dest_offset, length,
  4355                        load_array_length(dest),
  4356                        slow_region);
  4358   // (9) each element of an oop array must be assignable
  4359   // The generate_arraycopy subroutine checks this.
  4361   // This is where the memory effects are placed:
  4362   const TypePtr* adr_type = TypeAryPtr::get_array_body_type(dest_elem);
  4363   generate_arraycopy(adr_type, dest_elem,
  4364                      src, src_offset, dest, dest_offset, length,
  4365                      false, false, slow_region);
  4367   return true;
  4370 //-----------------------------generate_arraycopy----------------------
  4371 // Generate an optimized call to arraycopy.
  4372 // Caller must guard against non-arrays.
  4373 // Caller must determine a common array basic-type for both arrays.
  4374 // Caller must validate offsets against array bounds.
  4375 // The slow_region has already collected guard failure paths
  4376 // (such as out of bounds length or non-conformable array types).
  4377 // The generated code has this shape, in general:
  4378 //
  4379 //     if (length == 0)  return   // via zero_path
  4380 //     slowval = -1
  4381 //     if (types unknown) {
  4382 //       slowval = call generic copy loop
  4383 //       if (slowval == 0)  return  // via checked_path
  4384 //     } else if (indexes in bounds) {
  4385 //       if ((is object array) && !(array type check)) {
  4386 //         slowval = call checked copy loop
  4387 //         if (slowval == 0)  return  // via checked_path
  4388 //       } else {
  4389 //         call bulk copy loop
  4390 //         return  // via fast_path
  4391 //       }
  4392 //     }
  4393 //     // adjust params for remaining work:
  4394 //     if (slowval != -1) {
  4395 //       n = -1^slowval; src_offset += n; dest_offset += n; length -= n
  4396 //     }
  4397 //   slow_region:
  4398 //     call slow arraycopy(src, src_offset, dest, dest_offset, length)
  4399 //     return  // via slow_call_path
  4400 //
  4401 // This routine is used from several intrinsics:  System.arraycopy,
  4402 // Object.clone (the array subcase), and Arrays.copyOf[Range].
  4403 //
  4404 void
  4405 LibraryCallKit::generate_arraycopy(const TypePtr* adr_type,
  4406                                    BasicType basic_elem_type,
  4407                                    Node* src,  Node* src_offset,
  4408                                    Node* dest, Node* dest_offset,
  4409                                    Node* copy_length,
  4410                                    bool disjoint_bases,
  4411                                    bool length_never_negative,
  4412                                    RegionNode* slow_region) {
  4414   if (slow_region == NULL) {
  4415     slow_region = new(C,1) RegionNode(1);
  4416     record_for_igvn(slow_region);
  4419   Node* original_dest      = dest;
  4420   AllocateArrayNode* alloc = NULL;  // used for zeroing, if needed
  4421   bool  must_clear_dest    = false;
  4423   // See if this is the initialization of a newly-allocated array.
  4424   // If so, we will take responsibility here for initializing it to zero.
  4425   // (Note:  Because tightly_coupled_allocation performs checks on the
  4426   // out-edges of the dest, we need to avoid making derived pointers
  4427   // from it until we have checked its uses.)
  4428   if (ReduceBulkZeroing
  4429       && !ZeroTLAB              // pointless if already zeroed
  4430       && basic_elem_type != T_CONFLICT // avoid corner case
  4431       && !_gvn.eqv_uncast(src, dest)
  4432       && ((alloc = tightly_coupled_allocation(dest, slow_region))
  4433           != NULL)
  4434       && _gvn.find_int_con(alloc->in(AllocateNode::ALength), 1) > 0
  4435       && alloc->maybe_set_complete(&_gvn)) {
  4436     // "You break it, you buy it."
  4437     InitializeNode* init = alloc->initialization();
  4438     assert(init->is_complete(), "we just did this");
  4439     assert(dest->is_CheckCastPP(), "sanity");
  4440     assert(dest->in(0)->in(0) == init, "dest pinned");
  4442     // Cast to Object for arraycopy.
  4443     // We can't use the original CheckCastPP since it should be moved
  4444     // after the arraycopy to prevent stores flowing above it.
  4445     Node* new_obj = new(C, 2) CheckCastPPNode(dest->in(0), dest->in(1),
  4446                                               TypeInstPtr::NOTNULL);
  4447     dest = _gvn.transform(new_obj);
  4448     // Substitute in the locally valid dest_oop.
  4449     replace_in_map(original_dest, dest);
  4450     adr_type = TypeRawPtr::BOTTOM;  // all initializations are into raw memory
  4451     // From this point on, every exit path is responsible for
  4452     // initializing any non-copied parts of the object to zero.
  4453     must_clear_dest = true;
  4454   } else {
  4455     // No zeroing elimination here.
  4456     alloc             = NULL;
  4457     //original_dest   = dest;
  4458     //must_clear_dest = false;
  4461   // Results are placed here:
  4462   enum { fast_path        = 1,  // normal void-returning assembly stub
  4463          checked_path     = 2,  // special assembly stub with cleanup
  4464          slow_call_path   = 3,  // something went wrong; call the VM
  4465          zero_path        = 4,  // bypass when length of copy is zero
  4466          bcopy_path       = 5,  // copy primitive array by 64-bit blocks
  4467          PATH_LIMIT       = 6
  4468   };
  4469   RegionNode* result_region = new(C, PATH_LIMIT) RegionNode(PATH_LIMIT);
  4470   PhiNode*    result_i_o    = new(C, PATH_LIMIT) PhiNode(result_region, Type::ABIO);
  4471   PhiNode*    result_memory = new(C, PATH_LIMIT) PhiNode(result_region, Type::MEMORY, adr_type);
  4472   record_for_igvn(result_region);
  4473   _gvn.set_type_bottom(result_i_o);
  4474   _gvn.set_type_bottom(result_memory);
  4475   assert(adr_type != TypePtr::BOTTOM, "must be RawMem or a T[] slice");
  4477   // The slow_control path:
  4478   Node* slow_control;
  4479   Node* slow_i_o = i_o();
  4480   Node* slow_mem = memory(adr_type);
  4481   debug_only(slow_control = (Node*) badAddress);
  4483   // Checked control path:
  4484   Node* checked_control = top();
  4485   Node* checked_mem     = NULL;
  4486   Node* checked_i_o     = NULL;
  4487   Node* checked_value   = NULL;
  4489   if (basic_elem_type == T_CONFLICT) {
  4490     assert(!must_clear_dest, "");
  4491     Node* cv = generate_generic_arraycopy(adr_type,
  4492                                           src, src_offset, dest, dest_offset,
  4493                                           copy_length);
  4494     if (cv == NULL)  cv = intcon(-1);  // failure (no stub available)
  4495     checked_control = control();
  4496     checked_i_o     = i_o();
  4497     checked_mem     = memory(adr_type);
  4498     checked_value   = cv;
  4499     set_control(top());         // no fast path
  4502   Node* not_pos = generate_nonpositive_guard(copy_length, length_never_negative);
  4503   if (not_pos != NULL) {
  4504     PreserveJVMState pjvms(this);
  4505     set_control(not_pos);
  4507     // (6) length must not be negative.
  4508     if (!length_never_negative) {
  4509       generate_negative_guard(copy_length, slow_region);
  4512     // copy_length is 0.
  4513     if (!stopped() && must_clear_dest) {
  4514       Node* dest_length = alloc->in(AllocateNode::ALength);
  4515       if (_gvn.eqv_uncast(copy_length, dest_length)
  4516           || _gvn.find_int_con(dest_length, 1) <= 0) {
  4517         // There is no zeroing to do. No need for a secondary raw memory barrier.
  4518       } else {
  4519         // Clear the whole thing since there are no source elements to copy.
  4520         generate_clear_array(adr_type, dest, basic_elem_type,
  4521                              intcon(0), NULL,
  4522                              alloc->in(AllocateNode::AllocSize));
  4523         // Use a secondary InitializeNode as raw memory barrier.
  4524         // Currently it is needed only on this path since other
  4525         // paths have stub or runtime calls as raw memory barriers.
  4526         InitializeNode* init = insert_mem_bar_volatile(Op_Initialize,
  4527                                                        Compile::AliasIdxRaw,
  4528                                                        top())->as_Initialize();
  4529         init->set_complete(&_gvn);  // (there is no corresponding AllocateNode)
  4533     // Present the results of the fast call.
  4534     result_region->init_req(zero_path, control());
  4535     result_i_o   ->init_req(zero_path, i_o());
  4536     result_memory->init_req(zero_path, memory(adr_type));
  4539   if (!stopped() && must_clear_dest) {
  4540     // We have to initialize the *uncopied* part of the array to zero.
  4541     // The copy destination is the slice dest[off..off+len].  The other slices
  4542     // are dest_head = dest[0..off] and dest_tail = dest[off+len..dest.length].
  4543     Node* dest_size   = alloc->in(AllocateNode::AllocSize);
  4544     Node* dest_length = alloc->in(AllocateNode::ALength);
  4545     Node* dest_tail   = _gvn.transform( new(C,3) AddINode(dest_offset,
  4546                                                           copy_length) );
  4548     // If there is a head section that needs zeroing, do it now.
  4549     if (find_int_con(dest_offset, -1) != 0) {
  4550       generate_clear_array(adr_type, dest, basic_elem_type,
  4551                            intcon(0), dest_offset,
  4552                            NULL);
  4555     // Next, perform a dynamic check on the tail length.
  4556     // It is often zero, and we can win big if we prove this.
  4557     // There are two wins:  Avoid generating the ClearArray
  4558     // with its attendant messy index arithmetic, and upgrade
  4559     // the copy to a more hardware-friendly word size of 64 bits.
  4560     Node* tail_ctl = NULL;
  4561     if (!stopped() && !_gvn.eqv_uncast(dest_tail, dest_length)) {
  4562       Node* cmp_lt   = _gvn.transform( new(C,3) CmpINode(dest_tail, dest_length) );
  4563       Node* bol_lt   = _gvn.transform( new(C,2) BoolNode(cmp_lt, BoolTest::lt) );
  4564       tail_ctl = generate_slow_guard(bol_lt, NULL);
  4565       assert(tail_ctl != NULL || !stopped(), "must be an outcome");
  4568     // At this point, let's assume there is no tail.
  4569     if (!stopped() && alloc != NULL && basic_elem_type != T_OBJECT) {
  4570       // There is no tail.  Try an upgrade to a 64-bit copy.
  4571       bool didit = false;
  4572       { PreserveJVMState pjvms(this);
  4573         didit = generate_block_arraycopy(adr_type, basic_elem_type, alloc,
  4574                                          src, src_offset, dest, dest_offset,
  4575                                          dest_size);
  4576         if (didit) {
  4577           // Present the results of the block-copying fast call.
  4578           result_region->init_req(bcopy_path, control());
  4579           result_i_o   ->init_req(bcopy_path, i_o());
  4580           result_memory->init_req(bcopy_path, memory(adr_type));
  4583       if (didit)
  4584         set_control(top());     // no regular fast path
  4587     // Clear the tail, if any.
  4588     if (tail_ctl != NULL) {
  4589       Node* notail_ctl = stopped() ? NULL : control();
  4590       set_control(tail_ctl);
  4591       if (notail_ctl == NULL) {
  4592         generate_clear_array(adr_type, dest, basic_elem_type,
  4593                              dest_tail, NULL,
  4594                              dest_size);
  4595       } else {
  4596         // Make a local merge.
  4597         Node* done_ctl = new(C,3) RegionNode(3);
  4598         Node* done_mem = new(C,3) PhiNode(done_ctl, Type::MEMORY, adr_type);
  4599         done_ctl->init_req(1, notail_ctl);
  4600         done_mem->init_req(1, memory(adr_type));
  4601         generate_clear_array(adr_type, dest, basic_elem_type,
  4602                              dest_tail, NULL,
  4603                              dest_size);
  4604         done_ctl->init_req(2, control());
  4605         done_mem->init_req(2, memory(adr_type));
  4606         set_control( _gvn.transform(done_ctl) );
  4607         set_memory(  _gvn.transform(done_mem), adr_type );
  4612   BasicType copy_type = basic_elem_type;
  4613   assert(basic_elem_type != T_ARRAY, "caller must fix this");
  4614   if (!stopped() && copy_type == T_OBJECT) {
  4615     // If src and dest have compatible element types, we can copy bits.
  4616     // Types S[] and D[] are compatible if D is a supertype of S.
  4617     //
  4618     // If they are not, we will use checked_oop_disjoint_arraycopy,
  4619     // which performs a fast optimistic per-oop check, and backs off
  4620     // further to JVM_ArrayCopy on the first per-oop check that fails.
  4621     // (Actually, we don't move raw bits only; the GC requires card marks.)
  4623     // Get the klassOop for both src and dest
  4624     Node* src_klass  = load_object_klass(src);
  4625     Node* dest_klass = load_object_klass(dest);
  4627     // Generate the subtype check.
  4628     // This might fold up statically, or then again it might not.
  4629     //
  4630     // Non-static example:  Copying List<String>.elements to a new String[].
  4631     // The backing store for a List<String> is always an Object[],
  4632     // but its elements are always type String, if the generic types
  4633     // are correct at the source level.
  4634     //
  4635     // Test S[] against D[], not S against D, because (probably)
  4636     // the secondary supertype cache is less busy for S[] than S.
  4637     // This usually only matters when D is an interface.
  4638     Node* not_subtype_ctrl = gen_subtype_check(src_klass, dest_klass);
  4639     // Plug failing path into checked_oop_disjoint_arraycopy
  4640     if (not_subtype_ctrl != top()) {
  4641       PreserveJVMState pjvms(this);
  4642       set_control(not_subtype_ctrl);
  4643       // (At this point we can assume disjoint_bases, since types differ.)
  4644       int ek_offset = objArrayKlass::element_klass_offset_in_bytes() + sizeof(oopDesc);
  4645       Node* p1 = basic_plus_adr(dest_klass, ek_offset);
  4646       Node* n1 = LoadKlassNode::make(_gvn, immutable_memory(), p1, TypeRawPtr::BOTTOM);
  4647       Node* dest_elem_klass = _gvn.transform(n1);
  4648       Node* cv = generate_checkcast_arraycopy(adr_type,
  4649                                               dest_elem_klass,
  4650                                               src, src_offset, dest, dest_offset,
  4651                                               copy_length);
  4652       if (cv == NULL)  cv = intcon(-1);  // failure (no stub available)
  4653       checked_control = control();
  4654       checked_i_o     = i_o();
  4655       checked_mem     = memory(adr_type);
  4656       checked_value   = cv;
  4658     // At this point we know we do not need type checks on oop stores.
  4660     // Let's see if we need card marks:
  4661     if (alloc != NULL && use_ReduceInitialCardMarks()) {
  4662       // If we do not need card marks, copy using the jint or jlong stub.
  4663       copy_type = LP64_ONLY(UseCompressedOops ? T_INT : T_LONG) NOT_LP64(T_INT);
  4664       assert(type2aelembytes(basic_elem_type) == type2aelembytes(copy_type),
  4665              "sizes agree");
  4669   if (!stopped()) {
  4670     // Generate the fast path, if possible.
  4671     PreserveJVMState pjvms(this);
  4672     generate_unchecked_arraycopy(adr_type, copy_type, disjoint_bases,
  4673                                  src, src_offset, dest, dest_offset,
  4674                                  ConvI2X(copy_length));
  4676     // Present the results of the fast call.
  4677     result_region->init_req(fast_path, control());
  4678     result_i_o   ->init_req(fast_path, i_o());
  4679     result_memory->init_req(fast_path, memory(adr_type));
  4682   // Here are all the slow paths up to this point, in one bundle:
  4683   slow_control = top();
  4684   if (slow_region != NULL)
  4685     slow_control = _gvn.transform(slow_region);
  4686   debug_only(slow_region = (RegionNode*)badAddress);
  4688   set_control(checked_control);
  4689   if (!stopped()) {
  4690     // Clean up after the checked call.
  4691     // The returned value is either 0 or -1^K,
  4692     // where K = number of partially transferred array elements.
  4693     Node* cmp = _gvn.transform( new(C, 3) CmpINode(checked_value, intcon(0)) );
  4694     Node* bol = _gvn.transform( new(C, 2) BoolNode(cmp, BoolTest::eq) );
  4695     IfNode* iff = create_and_map_if(control(), bol, PROB_MAX, COUNT_UNKNOWN);
  4697     // If it is 0, we are done, so transfer to the end.
  4698     Node* checks_done = _gvn.transform( new(C, 1) IfTrueNode(iff) );
  4699     result_region->init_req(checked_path, checks_done);
  4700     result_i_o   ->init_req(checked_path, checked_i_o);
  4701     result_memory->init_req(checked_path, checked_mem);
  4703     // If it is not zero, merge into the slow call.
  4704     set_control( _gvn.transform( new(C, 1) IfFalseNode(iff) ));
  4705     RegionNode* slow_reg2 = new(C, 3) RegionNode(3);
  4706     PhiNode*    slow_i_o2 = new(C, 3) PhiNode(slow_reg2, Type::ABIO);
  4707     PhiNode*    slow_mem2 = new(C, 3) PhiNode(slow_reg2, Type::MEMORY, adr_type);
  4708     record_for_igvn(slow_reg2);
  4709     slow_reg2  ->init_req(1, slow_control);
  4710     slow_i_o2  ->init_req(1, slow_i_o);
  4711     slow_mem2  ->init_req(1, slow_mem);
  4712     slow_reg2  ->init_req(2, control());
  4713     slow_i_o2  ->init_req(2, checked_i_o);
  4714     slow_mem2  ->init_req(2, checked_mem);
  4716     slow_control = _gvn.transform(slow_reg2);
  4717     slow_i_o     = _gvn.transform(slow_i_o2);
  4718     slow_mem     = _gvn.transform(slow_mem2);
  4720     if (alloc != NULL) {
  4721       // We'll restart from the very beginning, after zeroing the whole thing.
  4722       // This can cause double writes, but that's OK since dest is brand new.
  4723       // So we ignore the low 31 bits of the value returned from the stub.
  4724     } else {
  4725       // We must continue the copy exactly where it failed, or else
  4726       // another thread might see the wrong number of writes to dest.
  4727       Node* checked_offset = _gvn.transform( new(C, 3) XorINode(checked_value, intcon(-1)) );
  4728       Node* slow_offset    = new(C, 3) PhiNode(slow_reg2, TypeInt::INT);
  4729       slow_offset->init_req(1, intcon(0));
  4730       slow_offset->init_req(2, checked_offset);
  4731       slow_offset  = _gvn.transform(slow_offset);
  4733       // Adjust the arguments by the conditionally incoming offset.
  4734       Node* src_off_plus  = _gvn.transform( new(C, 3) AddINode(src_offset,  slow_offset) );
  4735       Node* dest_off_plus = _gvn.transform( new(C, 3) AddINode(dest_offset, slow_offset) );
  4736       Node* length_minus  = _gvn.transform( new(C, 3) SubINode(copy_length, slow_offset) );
  4738       // Tweak the node variables to adjust the code produced below:
  4739       src_offset  = src_off_plus;
  4740       dest_offset = dest_off_plus;
  4741       copy_length = length_minus;
  4745   set_control(slow_control);
  4746   if (!stopped()) {
  4747     // Generate the slow path, if needed.
  4748     PreserveJVMState pjvms(this);   // replace_in_map may trash the map
  4750     set_memory(slow_mem, adr_type);
  4751     set_i_o(slow_i_o);
  4753     if (must_clear_dest) {
  4754       generate_clear_array(adr_type, dest, basic_elem_type,
  4755                            intcon(0), NULL,
  4756                            alloc->in(AllocateNode::AllocSize));
  4759     generate_slow_arraycopy(adr_type,
  4760                             src, src_offset, dest, dest_offset,
  4761                             copy_length);
  4763     result_region->init_req(slow_call_path, control());
  4764     result_i_o   ->init_req(slow_call_path, i_o());
  4765     result_memory->init_req(slow_call_path, memory(adr_type));
  4768   // Remove unused edges.
  4769   for (uint i = 1; i < result_region->req(); i++) {
  4770     if (result_region->in(i) == NULL)
  4771       result_region->init_req(i, top());
  4774   // Finished; return the combined state.
  4775   set_control( _gvn.transform(result_region) );
  4776   set_i_o(     _gvn.transform(result_i_o)    );
  4777   set_memory(  _gvn.transform(result_memory), adr_type );
  4779   if (dest != original_dest) {
  4780     // Pin the "finished" array node after the arraycopy/zeroing operations.
  4781     _gvn.hash_delete(original_dest);
  4782     original_dest->set_req(0, control());
  4783     // Replace raw memory edge with new CheckCastPP to have a live oop
  4784     // at safepoints instead of raw value.
  4785     assert(dest->is_CheckCastPP() && dest->in(1) == original_dest->in(1), "sanity");
  4786     original_dest->set_req(1, dest);       // cast to the original type
  4787     _gvn.hash_find_insert(original_dest);  // put back into GVN table
  4788     // Restore in the locally valid dest_oop.
  4789     replace_in_map(dest, original_dest);
  4791   // The memory edges above are precise in order to model effects around
  4792   // array copies accurately to allow value numbering of field loads around
  4793   // arraycopy.  Such field loads, both before and after, are common in Java
  4794   // collections and similar classes involving header/array data structures.
  4795   //
  4796   // But with low number of register or when some registers are used or killed
  4797   // by arraycopy calls it causes registers spilling on stack. See 6544710.
  4798   // The next memory barrier is added to avoid it. If the arraycopy can be
  4799   // optimized away (which it can, sometimes) then we can manually remove
  4800   // the membar also.
  4801   if (InsertMemBarAfterArraycopy)
  4802     insert_mem_bar(Op_MemBarCPUOrder);
  4806 // Helper function which determines if an arraycopy immediately follows
  4807 // an allocation, with no intervening tests or other escapes for the object.
  4808 AllocateArrayNode*
  4809 LibraryCallKit::tightly_coupled_allocation(Node* ptr,
  4810                                            RegionNode* slow_region) {
  4811   if (stopped())             return NULL;  // no fast path
  4812   if (C->AliasLevel() == 0)  return NULL;  // no MergeMems around
  4814   AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(ptr, &_gvn);
  4815   if (alloc == NULL)  return NULL;
  4817   Node* rawmem = memory(Compile::AliasIdxRaw);
  4818   // Is the allocation's memory state untouched?
  4819   if (!(rawmem->is_Proj() && rawmem->in(0)->is_Initialize())) {
  4820     // Bail out if there have been raw-memory effects since the allocation.
  4821     // (Example:  There might have been a call or safepoint.)
  4822     return NULL;
  4824   rawmem = rawmem->in(0)->as_Initialize()->memory(Compile::AliasIdxRaw);
  4825   if (!(rawmem->is_Proj() && rawmem->in(0) == alloc)) {
  4826     return NULL;
  4829   // There must be no unexpected observers of this allocation.
  4830   for (DUIterator_Fast imax, i = ptr->fast_outs(imax); i < imax; i++) {
  4831     Node* obs = ptr->fast_out(i);
  4832     if (obs != this->map()) {
  4833       return NULL;
  4837   // This arraycopy must unconditionally follow the allocation of the ptr.
  4838   Node* alloc_ctl = ptr->in(0);
  4839   assert(just_allocated_object(alloc_ctl) == ptr, "most recent allo");
  4841   Node* ctl = control();
  4842   while (ctl != alloc_ctl) {
  4843     // There may be guards which feed into the slow_region.
  4844     // Any other control flow means that we might not get a chance
  4845     // to finish initializing the allocated object.
  4846     if ((ctl->is_IfFalse() || ctl->is_IfTrue()) && ctl->in(0)->is_If()) {
  4847       IfNode* iff = ctl->in(0)->as_If();
  4848       Node* not_ctl = iff->proj_out(1 - ctl->as_Proj()->_con);
  4849       assert(not_ctl != NULL && not_ctl != ctl, "found alternate");
  4850       if (slow_region != NULL && slow_region->find_edge(not_ctl) >= 1) {
  4851         ctl = iff->in(0);       // This test feeds the known slow_region.
  4852         continue;
  4854       // One more try:  Various low-level checks bottom out in
  4855       // uncommon traps.  If the debug-info of the trap omits
  4856       // any reference to the allocation, as we've already
  4857       // observed, then there can be no objection to the trap.
  4858       bool found_trap = false;
  4859       for (DUIterator_Fast jmax, j = not_ctl->fast_outs(jmax); j < jmax; j++) {
  4860         Node* obs = not_ctl->fast_out(j);
  4861         if (obs->in(0) == not_ctl && obs->is_Call() &&
  4862             (obs->as_Call()->entry_point() ==
  4863              SharedRuntime::uncommon_trap_blob()->instructions_begin())) {
  4864           found_trap = true; break;
  4867       if (found_trap) {
  4868         ctl = iff->in(0);       // This test feeds a harmless uncommon trap.
  4869         continue;
  4872     return NULL;
  4875   // If we get this far, we have an allocation which immediately
  4876   // precedes the arraycopy, and we can take over zeroing the new object.
  4877   // The arraycopy will finish the initialization, and provide
  4878   // a new control state to which we will anchor the destination pointer.
  4880   return alloc;
  4883 // Helper for initialization of arrays, creating a ClearArray.
  4884 // It writes zero bits in [start..end), within the body of an array object.
  4885 // The memory effects are all chained onto the 'adr_type' alias category.
  4886 //
  4887 // Since the object is otherwise uninitialized, we are free
  4888 // to put a little "slop" around the edges of the cleared area,
  4889 // as long as it does not go back into the array's header,
  4890 // or beyond the array end within the heap.
  4891 //
  4892 // The lower edge can be rounded down to the nearest jint and the
  4893 // upper edge can be rounded up to the nearest MinObjAlignmentInBytes.
  4894 //
  4895 // Arguments:
  4896 //   adr_type           memory slice where writes are generated
  4897 //   dest               oop of the destination array
  4898 //   basic_elem_type    element type of the destination
  4899 //   slice_idx          array index of first element to store
  4900 //   slice_len          number of elements to store (or NULL)
  4901 //   dest_size          total size in bytes of the array object
  4902 //
  4903 // Exactly one of slice_len or dest_size must be non-NULL.
  4904 // If dest_size is non-NULL, zeroing extends to the end of the object.
  4905 // If slice_len is non-NULL, the slice_idx value must be a constant.
  4906 void
  4907 LibraryCallKit::generate_clear_array(const TypePtr* adr_type,
  4908                                      Node* dest,
  4909                                      BasicType basic_elem_type,
  4910                                      Node* slice_idx,
  4911                                      Node* slice_len,
  4912                                      Node* dest_size) {
  4913   // one or the other but not both of slice_len and dest_size:
  4914   assert((slice_len != NULL? 1: 0) + (dest_size != NULL? 1: 0) == 1, "");
  4915   if (slice_len == NULL)  slice_len = top();
  4916   if (dest_size == NULL)  dest_size = top();
  4918   // operate on this memory slice:
  4919   Node* mem = memory(adr_type); // memory slice to operate on
  4921   // scaling and rounding of indexes:
  4922   int scale = exact_log2(type2aelembytes(basic_elem_type));
  4923   int abase = arrayOopDesc::base_offset_in_bytes(basic_elem_type);
  4924   int clear_low = (-1 << scale) & (BytesPerInt  - 1);
  4925   int bump_bit  = (-1 << scale) & BytesPerInt;
  4927   // determine constant starts and ends
  4928   const intptr_t BIG_NEG = -128;
  4929   assert(BIG_NEG + 2*abase < 0, "neg enough");
  4930   intptr_t slice_idx_con = (intptr_t) find_int_con(slice_idx, BIG_NEG);
  4931   intptr_t slice_len_con = (intptr_t) find_int_con(slice_len, BIG_NEG);
  4932   if (slice_len_con == 0) {
  4933     return;                     // nothing to do here
  4935   intptr_t start_con = (abase + (slice_idx_con << scale)) & ~clear_low;
  4936   intptr_t end_con   = find_intptr_t_con(dest_size, -1);
  4937   if (slice_idx_con >= 0 && slice_len_con >= 0) {
  4938     assert(end_con < 0, "not two cons");
  4939     end_con = round_to(abase + ((slice_idx_con + slice_len_con) << scale),
  4940                        BytesPerLong);
  4943   if (start_con >= 0 && end_con >= 0) {
  4944     // Constant start and end.  Simple.
  4945     mem = ClearArrayNode::clear_memory(control(), mem, dest,
  4946                                        start_con, end_con, &_gvn);
  4947   } else if (start_con >= 0 && dest_size != top()) {
  4948     // Constant start, pre-rounded end after the tail of the array.
  4949     Node* end = dest_size;
  4950     mem = ClearArrayNode::clear_memory(control(), mem, dest,
  4951                                        start_con, end, &_gvn);
  4952   } else if (start_con >= 0 && slice_len != top()) {
  4953     // Constant start, non-constant end.  End needs rounding up.
  4954     // End offset = round_up(abase + ((slice_idx_con + slice_len) << scale), 8)
  4955     intptr_t end_base  = abase + (slice_idx_con << scale);
  4956     int      end_round = (-1 << scale) & (BytesPerLong  - 1);
  4957     Node*    end       = ConvI2X(slice_len);
  4958     if (scale != 0)
  4959       end = _gvn.transform( new(C,3) LShiftXNode(end, intcon(scale) ));
  4960     end_base += end_round;
  4961     end = _gvn.transform( new(C,3) AddXNode(end, MakeConX(end_base)) );
  4962     end = _gvn.transform( new(C,3) AndXNode(end, MakeConX(~end_round)) );
  4963     mem = ClearArrayNode::clear_memory(control(), mem, dest,
  4964                                        start_con, end, &_gvn);
  4965   } else if (start_con < 0 && dest_size != top()) {
  4966     // Non-constant start, pre-rounded end after the tail of the array.
  4967     // This is almost certainly a "round-to-end" operation.
  4968     Node* start = slice_idx;
  4969     start = ConvI2X(start);
  4970     if (scale != 0)
  4971       start = _gvn.transform( new(C,3) LShiftXNode( start, intcon(scale) ));
  4972     start = _gvn.transform( new(C,3) AddXNode(start, MakeConX(abase)) );
  4973     if ((bump_bit | clear_low) != 0) {
  4974       int to_clear = (bump_bit | clear_low);
  4975       // Align up mod 8, then store a jint zero unconditionally
  4976       // just before the mod-8 boundary.
  4977       if (((abase + bump_bit) & ~to_clear) - bump_bit
  4978           < arrayOopDesc::length_offset_in_bytes() + BytesPerInt) {
  4979         bump_bit = 0;
  4980         assert((abase & to_clear) == 0, "array base must be long-aligned");
  4981       } else {
  4982         // Bump 'start' up to (or past) the next jint boundary:
  4983         start = _gvn.transform( new(C,3) AddXNode(start, MakeConX(bump_bit)) );
  4984         assert((abase & clear_low) == 0, "array base must be int-aligned");
  4986       // Round bumped 'start' down to jlong boundary in body of array.
  4987       start = _gvn.transform( new(C,3) AndXNode(start, MakeConX(~to_clear)) );
  4988       if (bump_bit != 0) {
  4989         // Store a zero to the immediately preceding jint:
  4990         Node* x1 = _gvn.transform( new(C,3) AddXNode(start, MakeConX(-bump_bit)) );
  4991         Node* p1 = basic_plus_adr(dest, x1);
  4992         mem = StoreNode::make(_gvn, control(), mem, p1, adr_type, intcon(0), T_INT);
  4993         mem = _gvn.transform(mem);
  4996     Node* end = dest_size; // pre-rounded
  4997     mem = ClearArrayNode::clear_memory(control(), mem, dest,
  4998                                        start, end, &_gvn);
  4999   } else {
  5000     // Non-constant start, unrounded non-constant end.
  5001     // (Nobody zeroes a random midsection of an array using this routine.)
  5002     ShouldNotReachHere();       // fix caller
  5005   // Done.
  5006   set_memory(mem, adr_type);
  5010 bool
  5011 LibraryCallKit::generate_block_arraycopy(const TypePtr* adr_type,
  5012                                          BasicType basic_elem_type,
  5013                                          AllocateNode* alloc,
  5014                                          Node* src,  Node* src_offset,
  5015                                          Node* dest, Node* dest_offset,
  5016                                          Node* dest_size) {
  5017   // See if there is an advantage from block transfer.
  5018   int scale = exact_log2(type2aelembytes(basic_elem_type));
  5019   if (scale >= LogBytesPerLong)
  5020     return false;               // it is already a block transfer
  5022   // Look at the alignment of the starting offsets.
  5023   int abase = arrayOopDesc::base_offset_in_bytes(basic_elem_type);
  5024   const intptr_t BIG_NEG = -128;
  5025   assert(BIG_NEG + 2*abase < 0, "neg enough");
  5027   intptr_t src_off  = abase + ((intptr_t) find_int_con(src_offset, -1)  << scale);
  5028   intptr_t dest_off = abase + ((intptr_t) find_int_con(dest_offset, -1) << scale);
  5029   if (src_off < 0 || dest_off < 0)
  5030     // At present, we can only understand constants.
  5031     return false;
  5033   if (((src_off | dest_off) & (BytesPerLong-1)) != 0) {
  5034     // Non-aligned; too bad.
  5035     // One more chance:  Pick off an initial 32-bit word.
  5036     // This is a common case, since abase can be odd mod 8.
  5037     if (((src_off | dest_off) & (BytesPerLong-1)) == BytesPerInt &&
  5038         ((src_off ^ dest_off) & (BytesPerLong-1)) == 0) {
  5039       Node* sptr = basic_plus_adr(src,  src_off);
  5040       Node* dptr = basic_plus_adr(dest, dest_off);
  5041       Node* sval = make_load(control(), sptr, TypeInt::INT, T_INT, adr_type);
  5042       store_to_memory(control(), dptr, sval, T_INT, adr_type);
  5043       src_off += BytesPerInt;
  5044       dest_off += BytesPerInt;
  5045     } else {
  5046       return false;
  5049   assert(src_off % BytesPerLong == 0, "");
  5050   assert(dest_off % BytesPerLong == 0, "");
  5052   // Do this copy by giant steps.
  5053   Node* sptr  = basic_plus_adr(src,  src_off);
  5054   Node* dptr  = basic_plus_adr(dest, dest_off);
  5055   Node* countx = dest_size;
  5056   countx = _gvn.transform( new (C, 3) SubXNode(countx, MakeConX(dest_off)) );
  5057   countx = _gvn.transform( new (C, 3) URShiftXNode(countx, intcon(LogBytesPerLong)) );
  5059   bool disjoint_bases = true;   // since alloc != NULL
  5060   generate_unchecked_arraycopy(adr_type, T_LONG, disjoint_bases,
  5061                                sptr, NULL, dptr, NULL, countx);
  5063   return true;
  5067 // Helper function; generates code for the slow case.
  5068 // We make a call to a runtime method which emulates the native method,
  5069 // but without the native wrapper overhead.
  5070 void
  5071 LibraryCallKit::generate_slow_arraycopy(const TypePtr* adr_type,
  5072                                         Node* src,  Node* src_offset,
  5073                                         Node* dest, Node* dest_offset,
  5074                                         Node* copy_length) {
  5075   Node* call = make_runtime_call(RC_NO_LEAF | RC_UNCOMMON,
  5076                                  OptoRuntime::slow_arraycopy_Type(),
  5077                                  OptoRuntime::slow_arraycopy_Java(),
  5078                                  "slow_arraycopy", adr_type,
  5079                                  src, src_offset, dest, dest_offset,
  5080                                  copy_length);
  5082   // Handle exceptions thrown by this fellow:
  5083   make_slow_call_ex(call, env()->Throwable_klass(), false);
  5086 // Helper function; generates code for cases requiring runtime checks.
  5087 Node*
  5088 LibraryCallKit::generate_checkcast_arraycopy(const TypePtr* adr_type,
  5089                                              Node* dest_elem_klass,
  5090                                              Node* src,  Node* src_offset,
  5091                                              Node* dest, Node* dest_offset,
  5092                                              Node* copy_length) {
  5093   if (stopped())  return NULL;
  5095   address copyfunc_addr = StubRoutines::checkcast_arraycopy();
  5096   if (copyfunc_addr == NULL) { // Stub was not generated, go slow path.
  5097     return NULL;
  5100   // Pick out the parameters required to perform a store-check
  5101   // for the target array.  This is an optimistic check.  It will
  5102   // look in each non-null element's class, at the desired klass's
  5103   // super_check_offset, for the desired klass.
  5104   int sco_offset = Klass::super_check_offset_offset_in_bytes() + sizeof(oopDesc);
  5105   Node* p3 = basic_plus_adr(dest_elem_klass, sco_offset);
  5106   Node* n3 = new(C, 3) LoadINode(NULL, immutable_memory(), p3, TypeRawPtr::BOTTOM);
  5107   Node* check_offset = _gvn.transform(n3);
  5108   Node* check_value  = dest_elem_klass;
  5110   Node* src_start  = array_element_address(src,  src_offset,  T_OBJECT);
  5111   Node* dest_start = array_element_address(dest, dest_offset, T_OBJECT);
  5113   // (We know the arrays are never conjoint, because their types differ.)
  5114   Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
  5115                                  OptoRuntime::checkcast_arraycopy_Type(),
  5116                                  copyfunc_addr, "checkcast_arraycopy", adr_type,
  5117                                  // five arguments, of which two are
  5118                                  // intptr_t (jlong in LP64)
  5119                                  src_start, dest_start,
  5120                                  copy_length XTOP,
  5121                                  check_offset XTOP,
  5122                                  check_value);
  5124   return _gvn.transform(new (C, 1) ProjNode(call, TypeFunc::Parms));
  5128 // Helper function; generates code for cases requiring runtime checks.
  5129 Node*
  5130 LibraryCallKit::generate_generic_arraycopy(const TypePtr* adr_type,
  5131                                            Node* src,  Node* src_offset,
  5132                                            Node* dest, Node* dest_offset,
  5133                                            Node* copy_length) {
  5134   if (stopped())  return NULL;
  5136   address copyfunc_addr = StubRoutines::generic_arraycopy();
  5137   if (copyfunc_addr == NULL) { // Stub was not generated, go slow path.
  5138     return NULL;
  5141   Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
  5142                     OptoRuntime::generic_arraycopy_Type(),
  5143                     copyfunc_addr, "generic_arraycopy", adr_type,
  5144                     src, src_offset, dest, dest_offset, copy_length);
  5146   return _gvn.transform(new (C, 1) ProjNode(call, TypeFunc::Parms));
  5149 // Helper function; generates the fast out-of-line call to an arraycopy stub.
  5150 void
  5151 LibraryCallKit::generate_unchecked_arraycopy(const TypePtr* adr_type,
  5152                                              BasicType basic_elem_type,
  5153                                              bool disjoint_bases,
  5154                                              Node* src,  Node* src_offset,
  5155                                              Node* dest, Node* dest_offset,
  5156                                              Node* copy_length) {
  5157   if (stopped())  return;               // nothing to do
  5159   Node* src_start  = src;
  5160   Node* dest_start = dest;
  5161   if (src_offset != NULL || dest_offset != NULL) {
  5162     assert(src_offset != NULL && dest_offset != NULL, "");
  5163     src_start  = array_element_address(src,  src_offset,  basic_elem_type);
  5164     dest_start = array_element_address(dest, dest_offset, basic_elem_type);
  5167   // Figure out which arraycopy runtime method to call.
  5168   const char* copyfunc_name = "arraycopy";
  5169   address     copyfunc_addr =
  5170       basictype2arraycopy(basic_elem_type, src_offset, dest_offset,
  5171                           disjoint_bases, copyfunc_name);
  5173   // Call it.  Note that the count_ix value is not scaled to a byte-size.
  5174   make_runtime_call(RC_LEAF|RC_NO_FP,
  5175                     OptoRuntime::fast_arraycopy_Type(),
  5176                     copyfunc_addr, copyfunc_name, adr_type,
  5177                     src_start, dest_start, copy_length XTOP);

mercurial