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