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