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