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