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