src/share/vm/opto/library_call.cpp

Tue, 06 Mar 2012 12:36:59 +0100

author
rbackman
date
Tue, 06 Mar 2012 12:36:59 +0100
changeset 3709
0105f367a14c
parent 3637
61b82be3b1ff
child 3760
8f972594effc
permissions
-rw-r--r--

7160570: Intrinsification support for tracing framework
Reviewed-by: sla, never

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

mercurial