1 /*
   2  * Copyright (c) 1999, 2015, 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 "asm/macroAssembler.hpp"
  27 #include "classfile/systemDictionary.hpp"
  28 #include "classfile/vmSymbols.hpp"
  29 #include "compiler/compileBroker.hpp"
  30 #include "compiler/compileLog.hpp"
  31 #include "oops/objArrayKlass.hpp"
  32 #include "opto/addnode.hpp"
  33 #include "opto/arraycopynode.hpp"
  34 #include "opto/callGenerator.hpp"
  35 #include "opto/castnode.hpp"
  36 #include "opto/cfgnode.hpp"
  37 #include "opto/convertnode.hpp"
  38 #include "opto/countbitsnode.hpp"
  39 #include "opto/intrinsicnode.hpp"
  40 #include "opto/idealKit.hpp"
  41 #include "opto/mathexactnode.hpp"
  42 #include "opto/movenode.hpp"
  43 #include "opto/mulnode.hpp"
  44 #include "opto/narrowptrnode.hpp"
  45 #include "opto/opaquenode.hpp"
  46 #include "opto/parse.hpp"
  47 #include "opto/runtime.hpp"
  48 #include "opto/subnode.hpp"
  49 #include "prims/nativeLookup.hpp"
  50 #include "runtime/sharedRuntime.hpp"
  51 #include "trace/traceMacros.hpp"
  52 
  53 class LibraryIntrinsic : public InlineCallGenerator {
  54   // Extend the set of intrinsics known to the runtime:
  55  public:
  56  private:
  57   bool             _is_virtual;
  58   bool             _does_virtual_dispatch;
  59   int8_t           _predicates_count;  // Intrinsic is predicated by several conditions
  60   int8_t           _last_predicate; // Last generated predicate
  61   vmIntrinsics::ID _intrinsic_id;
  62 
  63  public:
  64   LibraryIntrinsic(ciMethod* m, bool is_virtual, int predicates_count, bool does_virtual_dispatch, vmIntrinsics::ID id)
  65     : InlineCallGenerator(m),
  66       _is_virtual(is_virtual),
  67       _does_virtual_dispatch(does_virtual_dispatch),
  68       _predicates_count((int8_t)predicates_count),
  69       _last_predicate((int8_t)-1),
  70       _intrinsic_id(id)
  71   {
  72   }
  73   virtual bool is_intrinsic() const { return true; }
  74   virtual bool is_virtual()   const { return _is_virtual; }
  75   virtual bool is_predicated() const { return _predicates_count > 0; }
  76   virtual int  predicates_count() const { return _predicates_count; }
  77   virtual bool does_virtual_dispatch()   const { return _does_virtual_dispatch; }
  78   virtual JVMState* generate(JVMState* jvms);
  79   virtual Node* generate_predicate(JVMState* jvms, int predicate);
  80   vmIntrinsics::ID intrinsic_id() const { return _intrinsic_id; }
  81 };
  82 
  83 
  84 // Local helper class for LibraryIntrinsic:
  85 class LibraryCallKit : public GraphKit {
  86  private:
  87   LibraryIntrinsic* _intrinsic;     // the library intrinsic being called
  88   Node*             _result;        // the result node, if any
  89   int               _reexecute_sp;  // the stack pointer when bytecode needs to be reexecuted
  90 
  91   const TypeOopPtr* sharpen_unsafe_type(Compile::AliasType* alias_type, const TypePtr *adr_type, bool is_native_ptr = false);
  92 
  93  public:
  94   LibraryCallKit(JVMState* jvms, LibraryIntrinsic* intrinsic)
  95     : GraphKit(jvms),
  96       _intrinsic(intrinsic),
  97       _result(NULL)
  98   {
  99     // Check if this is a root compile.  In that case we don't have a caller.
 100     if (!jvms->has_method()) {
 101       _reexecute_sp = sp();
 102     } else {
 103       // Find out how many arguments the interpreter needs when deoptimizing
 104       // and save the stack pointer value so it can used by uncommon_trap.
 105       // We find the argument count by looking at the declared signature.
 106       bool ignored_will_link;
 107       ciSignature* declared_signature = NULL;
 108       ciMethod* ignored_callee = caller()->get_method_at_bci(bci(), ignored_will_link, &declared_signature);
 109       const int nargs = declared_signature->arg_size_for_bc(caller()->java_code_at_bci(bci()));
 110       _reexecute_sp = sp() + nargs;  // "push" arguments back on stack
 111     }
 112   }
 113 
 114   virtual LibraryCallKit* is_LibraryCallKit() const { return (LibraryCallKit*)this; }
 115 
 116   ciMethod*         caller()    const    { return jvms()->method(); }
 117   int               bci()       const    { return jvms()->bci(); }
 118   LibraryIntrinsic* intrinsic() const    { return _intrinsic; }
 119   vmIntrinsics::ID  intrinsic_id() const { return _intrinsic->intrinsic_id(); }
 120   ciMethod*         callee()    const    { return _intrinsic->method(); }
 121 
 122   bool  try_to_inline(int predicate);
 123   Node* try_to_predicate(int predicate);
 124 
 125   void push_result() {
 126     // Push the result onto the stack.
 127     if (!stopped() && result() != NULL) {
 128       BasicType bt = result()->bottom_type()->basic_type();
 129       push_node(bt, result());
 130     }
 131   }
 132 
 133  private:
 134   void fatal_unexpected_iid(vmIntrinsics::ID iid) {
 135     fatal(err_msg_res("unexpected intrinsic %d: %s", iid, vmIntrinsics::name_at(iid)));
 136   }
 137 
 138   void  set_result(Node* n) { assert(_result == NULL, "only set once"); _result = n; }
 139   void  set_result(RegionNode* region, PhiNode* value);
 140   Node*     result() { return _result; }
 141 
 142   virtual int reexecute_sp() { return _reexecute_sp; }
 143 
 144   // Helper functions to inline natives
 145   Node* generate_guard(Node* test, RegionNode* region, float true_prob);
 146   Node* generate_slow_guard(Node* test, RegionNode* region);
 147   Node* generate_fair_guard(Node* test, RegionNode* region);
 148   Node* generate_negative_guard(Node* index, RegionNode* region,
 149                                 // resulting CastII of index:
 150                                 Node* *pos_index = NULL);
 151   Node* generate_limit_guard(Node* offset, Node* subseq_length,
 152                              Node* array_length,
 153                              RegionNode* region);
 154   Node* generate_current_thread(Node* &tls_output);
 155   Node* load_mirror_from_klass(Node* klass);
 156   Node* load_klass_from_mirror_common(Node* mirror, bool never_see_null,
 157                                       RegionNode* region, int null_path,
 158                                       int offset);
 159   Node* load_klass_from_mirror(Node* mirror, bool never_see_null,
 160                                RegionNode* region, int null_path) {
 161     int offset = java_lang_Class::klass_offset_in_bytes();
 162     return load_klass_from_mirror_common(mirror, never_see_null,
 163                                          region, null_path,
 164                                          offset);
 165   }
 166   Node* load_array_klass_from_mirror(Node* mirror, bool never_see_null,
 167                                      RegionNode* region, int null_path) {
 168     int offset = java_lang_Class::array_klass_offset_in_bytes();
 169     return load_klass_from_mirror_common(mirror, never_see_null,
 170                                          region, null_path,
 171                                          offset);
 172   }
 173   Node* generate_access_flags_guard(Node* kls,
 174                                     int modifier_mask, int modifier_bits,
 175                                     RegionNode* region);
 176   Node* generate_interface_guard(Node* kls, RegionNode* region);
 177   Node* generate_array_guard(Node* kls, RegionNode* region) {
 178     return generate_array_guard_common(kls, region, false, false);
 179   }
 180   Node* generate_non_array_guard(Node* kls, RegionNode* region) {
 181     return generate_array_guard_common(kls, region, false, true);
 182   }
 183   Node* generate_objArray_guard(Node* kls, RegionNode* region) {
 184     return generate_array_guard_common(kls, region, true, false);
 185   }
 186   Node* generate_non_objArray_guard(Node* kls, RegionNode* region) {
 187     return generate_array_guard_common(kls, region, true, true);
 188   }
 189   Node* generate_array_guard_common(Node* kls, RegionNode* region,
 190                                     bool obj_array, bool not_array);
 191   Node* generate_virtual_guard(Node* obj_klass, RegionNode* slow_region);
 192   CallJavaNode* generate_method_call(vmIntrinsics::ID method_id,
 193                                      bool is_virtual = false, bool is_static = false);
 194   CallJavaNode* generate_method_call_static(vmIntrinsics::ID method_id) {
 195     return generate_method_call(method_id, false, true);
 196   }
 197   CallJavaNode* generate_method_call_virtual(vmIntrinsics::ID method_id) {
 198     return generate_method_call(method_id, true, false);
 199   }
 200   Node * load_field_from_object(Node * fromObj, const char * fieldName, const char * fieldTypeString, bool is_exact, bool is_static, ciInstanceKlass * fromKls);
 201 
 202   Node* make_string_method_node(int opcode, Node* str1_start, Node* cnt1, Node* str2_start, Node* cnt2);
 203   Node* make_string_method_node(int opcode, Node* str1, Node* str2);
 204   bool inline_string_compareTo();
 205   bool inline_string_indexOf();
 206   Node* string_indexOf(Node* string_object, ciTypeArray* target_array, jint offset, jint cache_i, jint md2_i);
 207   bool inline_string_equals();
 208   Node* round_double_node(Node* n);
 209   bool runtime_math(const TypeFunc* call_type, address funcAddr, const char* funcName);
 210   bool inline_math_native(vmIntrinsics::ID id);
 211   bool inline_trig(vmIntrinsics::ID id);
 212   bool inline_math(vmIntrinsics::ID id);
 213   template <typename OverflowOp>
 214   bool inline_math_overflow(Node* arg1, Node* arg2);
 215   void inline_math_mathExact(Node* math, Node* test);
 216   bool inline_math_addExactI(bool is_increment);
 217   bool inline_math_addExactL(bool is_increment);
 218   bool inline_math_multiplyExactI();
 219   bool inline_math_multiplyExactL();
 220   bool inline_math_negateExactI();
 221   bool inline_math_negateExactL();
 222   bool inline_math_subtractExactI(bool is_decrement);
 223   bool inline_math_subtractExactL(bool is_decrement);
 224   bool inline_exp();
 225   bool inline_pow();
 226   Node* finish_pow_exp(Node* result, Node* x, Node* y, const TypeFunc* call_type, address funcAddr, const char* funcName);
 227   bool inline_min_max(vmIntrinsics::ID id);
 228   Node* generate_min_max(vmIntrinsics::ID id, Node* x, Node* y);
 229   // This returns Type::AnyPtr, RawPtr, or OopPtr.
 230   int classify_unsafe_addr(Node* &base, Node* &offset);
 231   Node* make_unsafe_address(Node* base, Node* offset);
 232   // Helper for inline_unsafe_access.
 233   // Generates the guards that check whether the result of
 234   // Unsafe.getObject should be recorded in an SATB log buffer.
 235   void insert_pre_barrier(Node* base_oop, Node* offset, Node* pre_val, bool need_mem_bar);
 236   bool inline_unsafe_access(bool is_native_ptr, bool is_store, BasicType type, bool is_volatile);
 237   static bool klass_needs_init_guard(Node* kls);
 238   bool inline_unsafe_allocate();
 239   bool inline_unsafe_copyMemory();
 240   bool inline_native_currentThread();
 241 #ifdef TRACE_HAVE_INTRINSICS
 242   bool inline_native_classID();
 243   bool inline_native_threadID();
 244 #endif
 245   bool inline_native_time_funcs(address method, const char* funcName);
 246   bool inline_native_isInterrupted();
 247   bool inline_native_Class_query(vmIntrinsics::ID id);
 248   bool inline_native_subtype_check();
 249 
 250   bool inline_native_newArray();
 251   bool inline_native_getLength();
 252   bool inline_array_copyOf(bool is_copyOfRange);
 253   bool inline_array_equals();
 254   void copy_to_clone(Node* obj, Node* alloc_obj, Node* obj_size, bool is_array, bool card_mark);
 255   bool inline_native_clone(bool is_virtual);
 256   bool inline_native_Reflection_getCallerClass();
 257   // Helper function for inlining native object hash method
 258   bool inline_native_hashcode(bool is_virtual, bool is_static);
 259   bool inline_native_getClass();
 260 
 261   // Helper functions for inlining arraycopy
 262   bool inline_arraycopy();
 263   AllocateArrayNode* tightly_coupled_allocation(Node* ptr,
 264                                                 RegionNode* slow_region);
 265   JVMState* arraycopy_restore_alloc_state(AllocateArrayNode* alloc, int& saved_reexecute_sp);
 266   void arraycopy_move_allocation_here(AllocateArrayNode* alloc, Node* dest, JVMState* saved_jvms, int saved_reexecute_sp);
 267 
 268   typedef enum { LS_xadd, LS_xchg, LS_cmpxchg } LoadStoreKind;
 269   bool inline_unsafe_load_store(BasicType type,  LoadStoreKind kind);
 270   bool inline_unsafe_ordered_store(BasicType type);
 271   bool inline_unsafe_fence(vmIntrinsics::ID id);
 272   bool inline_fp_conversions(vmIntrinsics::ID id);
 273   bool inline_number_methods(vmIntrinsics::ID id);
 274   bool inline_reference_get();
 275   bool inline_Class_cast();
 276   bool inline_aescrypt_Block(vmIntrinsics::ID id);
 277   bool inline_cipherBlockChaining_AESCrypt(vmIntrinsics::ID id);
 278   Node* inline_cipherBlockChaining_AESCrypt_predicate(bool decrypting);
 279   Node* get_key_start_from_aescrypt_object(Node* aescrypt_object);
 280   Node* get_original_key_start_from_aescrypt_object(Node* aescrypt_object);
 281   bool inline_ghash_processBlocks();
 282   bool inline_sha_implCompress(vmIntrinsics::ID id);
 283   bool inline_digestBase_implCompressMB(int predicate);
 284   bool inline_sha_implCompressMB(Node* digestBaseObj, ciInstanceKlass* instklass_SHA,
 285                                  bool long_state, address stubAddr, const char *stubName,
 286                                  Node* src_start, Node* ofs, Node* limit);
 287   Node* get_state_from_sha_object(Node *sha_object);
 288   Node* get_state_from_sha5_object(Node *sha_object);
 289   Node* inline_digestBase_implCompressMB_predicate(int predicate);
 290   bool inline_encodeISOArray();
 291   bool inline_updateCRC32();
 292   bool inline_updateBytesCRC32();
 293   bool inline_updateByteBufferCRC32();
 294   Node* get_table_from_crc32c_class(ciInstanceKlass *crc32c_class);
 295   bool inline_updateBytesCRC32C();
 296   bool inline_updateDirectByteBufferCRC32C();
 297   bool inline_multiplyToLen();
 298   bool inline_squareToLen();
 299   bool inline_mulAdd();
 300   bool inline_montgomeryMultiply();
 301   bool inline_montgomerySquare();
 302 
 303   bool inline_profileBoolean();
 304   bool inline_isCompileConstant();
 305 };
 306 
 307 bool Compile::intrinsic_does_virtual_dispatch_for(vmIntrinsics::ID id) {
 308   assert(id != vmIntrinsics::_none, "must be a VM intrinsic");
 309   switch(id) {
 310   case vmIntrinsics::_hashCode:
 311   case vmIntrinsics::_clone:
 312     return true;
 313     break;
 314   default:
 315     return false;
 316   }
 317 }
 318 int Compile::intrinsic_predicates_needed_for(vmIntrinsics::ID id) {
 319   assert(id != vmIntrinsics::_none, "must be a VM intrinsic");
 320   switch (id) {
 321   case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
 322   case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
 323     return 1;
 324   case vmIntrinsics::_digestBase_implCompressMB:
 325     return 3;
 326   default:
 327     return 0;
 328   }
 329 }
 330 
 331 bool Compile::is_intrinsic_available_for(Method* method, Method* compilation_context, bool is_virtual) {
 332   vmIntrinsics::ID id = method->intrinsic_id();
 333   if (id < vmIntrinsics::FIRST_ID || id >= vmIntrinsics::LAST_COMPILER_INLINE) {
 334     return false;
 335   }
 336 
 337   // Check if the intrinsic corresponding to 'method' has been disabled on
 338   // the command line by using the DisableIntrinsic flag (either globally
 339   // or on a per-method level, see src/share/vm/compiler/abstractCompiler.hpp
 340   // for details).
 341   // Usually, the compilation context is the caller of the method 'method'.
 342   // The only case when for a non-recursive method 'method' the compilation context
 343   // is not the caller of the 'method' (but it is the method itself) is
 344   // java.lang.ref.Referene::get.
 345   // For java.lang.ref.Reference::get, the intrinsic version is used
 346   // instead of the C2-compiled version so that the value in the referent
 347   // field can be registered by the G1 pre-barrier code. The intrinsified
 348   // version of Reference::get also adds a memory barrier to prevent
 349   // commoning reads from the referent field across safepoint since GC
 350   // can change the referent field's value. See Compile::Compile()
 351   // in src/share/vm/opto/compile.cpp for more details.
 352   ccstr disable_intr = NULL;
 353   if ((DisableIntrinsic[0] != '\0' && strstr(DisableIntrinsic, vmIntrinsics::name_at(id)) != NULL) ||
 354       (compilation_context != NULL &&
 355           CompilerOracle::has_option_value(compilation_context, "DisableIntrinsic", disable_intr) &&
 356           strstr(disable_intr, vmIntrinsics::name_at(id)) != NULL)
 357   ) {
 358     return false;
 359   }
 360 
 361   // Only Object.hashCode and Object.clone intrinsics implement also a virtual
 362   // dispatch because calling both methods is expensive but both methods are
 363   // frequently overridden. All other intrinsics implement only a non-virtual
 364   // dispatch.
 365   if (is_virtual) {
 366     switch (id) {
 367     case vmIntrinsics::_hashCode:
 368     case vmIntrinsics::_clone:
 369       break;
 370     default:
 371       return false;
 372     }
 373   }
 374 
 375   // -XX:-InlineNatives disables nearly all intrinsics except the ones listed in
 376   // the following switch statement.
 377   if (!InlineNatives) {
 378     switch (id) {
 379     case vmIntrinsics::_indexOf:
 380     case vmIntrinsics::_compareTo:
 381     case vmIntrinsics::_equals:
 382     case vmIntrinsics::_equalsC:
 383     case vmIntrinsics::_getAndAddInt:
 384     case vmIntrinsics::_getAndAddLong:
 385     case vmIntrinsics::_getAndSetInt:
 386     case vmIntrinsics::_getAndSetLong:
 387     case vmIntrinsics::_getAndSetObject:
 388     case vmIntrinsics::_loadFence:
 389     case vmIntrinsics::_storeFence:
 390     case vmIntrinsics::_fullFence:
 391     case vmIntrinsics::_Reference_get:
 392       break;
 393     default:
 394       return false;
 395     }
 396   }
 397 
 398   switch (id) {
 399   case vmIntrinsics::_compareTo:
 400     if (!SpecialStringCompareTo) return false;
 401     if (!Matcher::match_rule_supported(Op_StrComp)) return false;
 402     break;
 403   case vmIntrinsics::_indexOf:
 404     if (!SpecialStringIndexOf) return false;
 405     break;
 406   case vmIntrinsics::_equals:
 407     if (!SpecialStringEquals) return false;
 408     if (!Matcher::match_rule_supported(Op_StrEquals)) return false;
 409     break;
 410   case vmIntrinsics::_equalsC:
 411     if (!SpecialArraysEquals) return false;
 412     if (!Matcher::match_rule_supported(Op_AryEq)) return false;
 413     break;
 414   case vmIntrinsics::_arraycopy:
 415     if (!InlineArrayCopy) return false;
 416     break;
 417   case vmIntrinsics::_copyMemory:
 418     if (!InlineArrayCopy) return false;
 419     if (StubRoutines::unsafe_arraycopy() == NULL) return false;
 420     break;
 421   case vmIntrinsics::_hashCode:
 422     if (!InlineObjectHash) return false;
 423     break;
 424   case vmIntrinsics::_clone:
 425   case vmIntrinsics::_copyOf:
 426   case vmIntrinsics::_copyOfRange:
 427     // These intrinsics use both the objectcopy and the arraycopy
 428     // intrinsic mechanism.
 429     if (!InlineObjectCopy || !InlineArrayCopy) return false;
 430     break;
 431   case vmIntrinsics::_encodeISOArray:
 432     if (!SpecialEncodeISOArray) return false;
 433     if (!Matcher::match_rule_supported(Op_EncodeISOArray)) return false;
 434     break;
 435   case vmIntrinsics::_checkIndex:
 436     // We do not intrinsify this.  The optimizer does fine with it.
 437     return false;
 438   case vmIntrinsics::_getCallerClass:
 439     if (!InlineReflectionGetCallerClass ||
 440         SystemDictionary::reflect_CallerSensitive_klass() == NULL) {
 441       return false;
 442     }
 443     break;
 444   case vmIntrinsics::_bitCount_i:
 445     if (!Matcher::match_rule_supported(Op_PopCountI)) return false;
 446     break;
 447   case vmIntrinsics::_bitCount_l:
 448     if (!Matcher::match_rule_supported(Op_PopCountL)) return false;
 449     break;
 450   case vmIntrinsics::_numberOfLeadingZeros_i:
 451     if (!Matcher::match_rule_supported(Op_CountLeadingZerosI)) return false;
 452     break;
 453   case vmIntrinsics::_numberOfLeadingZeros_l:
 454     if (!Matcher::match_rule_supported(Op_CountLeadingZerosL)) return false;
 455     break;
 456   case vmIntrinsics::_numberOfTrailingZeros_i:
 457     if (!Matcher::match_rule_supported(Op_CountTrailingZerosI)) return false;
 458     break;
 459   case vmIntrinsics::_numberOfTrailingZeros_l:
 460     if (!Matcher::match_rule_supported(Op_CountTrailingZerosL)) return false;
 461     break;
 462   case vmIntrinsics::_reverseBytes_c:
 463     if (!Matcher::match_rule_supported(Op_ReverseBytesUS)) return false;
 464     break;
 465   case vmIntrinsics::_reverseBytes_s:
 466     if (!Matcher::match_rule_supported(Op_ReverseBytesS)) return false;
 467     break;
 468   case vmIntrinsics::_reverseBytes_i:
 469     if (!Matcher::match_rule_supported(Op_ReverseBytesI)) return false;
 470     break;
 471   case vmIntrinsics::_reverseBytes_l:
 472     if (!Matcher::match_rule_supported(Op_ReverseBytesL)) return false;
 473     break;
 474   case vmIntrinsics::_compareAndSwapObject:
 475 #ifdef _LP64
 476 if (!UseCompressedOops && !Matcher::match_rule_supported(Op_CompareAndSwapP)) return false;
 477 #endif
 478 break;
 479   case vmIntrinsics::_compareAndSwapLong:
 480     if (!Matcher::match_rule_supported(Op_CompareAndSwapL)) return false;
 481     break;
 482   case vmIntrinsics::_getAndAddInt:
 483     if (!Matcher::match_rule_supported(Op_GetAndAddI)) return false;
 484     break;
 485   case vmIntrinsics::_getAndAddLong:
 486     if (!Matcher::match_rule_supported(Op_GetAndAddL)) return false;
 487     break;
 488   case vmIntrinsics::_getAndSetInt:
 489     if (!Matcher::match_rule_supported(Op_GetAndSetI)) return false;
 490     break;
 491   case vmIntrinsics::_getAndSetLong:
 492     if (!Matcher::match_rule_supported(Op_GetAndSetL)) return false;
 493     break;
 494   case vmIntrinsics::_getAndSetObject:
 495 #ifdef _LP64
 496     if (!UseCompressedOops && !Matcher::match_rule_supported(Op_GetAndSetP)) return false;
 497     if (UseCompressedOops && !Matcher::match_rule_supported(Op_GetAndSetN)) return false;
 498     break;
 499 #else
 500     if (!Matcher::match_rule_supported(Op_GetAndSetP)) return false;
 501     break;
 502 #endif
 503   case vmIntrinsics::_aescrypt_encryptBlock:
 504   case vmIntrinsics::_aescrypt_decryptBlock:
 505     if (!UseAESIntrinsics) return false;
 506     break;
 507   case vmIntrinsics::_multiplyToLen:
 508     if (!UseMultiplyToLenIntrinsic) return false;
 509     break;
 510   case vmIntrinsics::_squareToLen:
 511     if (!UseSquareToLenIntrinsic) return false;
 512     break;
 513   case vmIntrinsics::_mulAdd:
 514     if (!UseMulAddIntrinsic) return false;
 515     break;
 516   case vmIntrinsics::_montgomeryMultiply:
 517     if (!UseMontgomeryMultiplyIntrinsic) return false;
 518     break;
 519   case vmIntrinsics::_montgomerySquare:
 520     if (!UseMontgomerySquareIntrinsic) return false;
 521     break;
 522   case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
 523   case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
 524     if (!UseAESIntrinsics) return false;
 525     break;
 526   case vmIntrinsics::_sha_implCompress:
 527     if (!UseSHA1Intrinsics) return false;
 528     break;
 529   case vmIntrinsics::_sha2_implCompress:
 530     if (!UseSHA256Intrinsics) return false;
 531     break;
 532   case vmIntrinsics::_sha5_implCompress:
 533     if (!UseSHA512Intrinsics) return false;
 534     break;
 535   case vmIntrinsics::_digestBase_implCompressMB:
 536     if (!(UseSHA1Intrinsics || UseSHA256Intrinsics || UseSHA512Intrinsics)) return false;
 537     break;
 538   case vmIntrinsics::_ghash_processBlocks:
 539     if (!UseGHASHIntrinsics) return false;
 540     break;
 541   case vmIntrinsics::_updateCRC32:
 542   case vmIntrinsics::_updateBytesCRC32:
 543   case vmIntrinsics::_updateByteBufferCRC32:
 544     if (!UseCRC32Intrinsics) return false;
 545     break;
 546   case vmIntrinsics::_updateBytesCRC32C:
 547   case vmIntrinsics::_updateDirectByteBufferCRC32C:
 548     if (!UseCRC32CIntrinsics) return false;
 549     break;
 550   case vmIntrinsics::_incrementExactI:
 551   case vmIntrinsics::_addExactI:
 552     if (!UseMathExactIntrinsics || !Matcher::match_rule_supported(Op_OverflowAddI)) return false;
 553     break;
 554   case vmIntrinsics::_incrementExactL:
 555   case vmIntrinsics::_addExactL:
 556     if (!UseMathExactIntrinsics || !Matcher::match_rule_supported(Op_OverflowAddL)) return false;
 557     break;
 558   case vmIntrinsics::_decrementExactI:
 559   case vmIntrinsics::_subtractExactI:
 560   case vmIntrinsics::_negateExactI:
 561     if (!UseMathExactIntrinsics || !Matcher::match_rule_supported(Op_OverflowSubI)) return false;
 562     break;
 563   case vmIntrinsics::_decrementExactL:
 564   case vmIntrinsics::_subtractExactL:
 565   case vmIntrinsics::_negateExactL:
 566     if (!UseMathExactIntrinsics || !Matcher::match_rule_supported(Op_OverflowSubL)) return false;
 567     break;
 568   case vmIntrinsics::_multiplyExactI:
 569     if (!UseMathExactIntrinsics || !Matcher::match_rule_supported(Op_OverflowMulI)) return false;
 570     break;
 571   case vmIntrinsics::_multiplyExactL:
 572     if (!Matcher::match_rule_supported(Op_OverflowMulL) || !UseMathExactIntrinsics) return false;
 573     break;
 574   case vmIntrinsics::_getShortUnaligned:
 575   case vmIntrinsics::_getCharUnaligned:
 576   case vmIntrinsics::_getIntUnaligned:
 577   case vmIntrinsics::_getLongUnaligned:
 578   case vmIntrinsics::_putShortUnaligned:
 579   case vmIntrinsics::_putCharUnaligned:
 580   case vmIntrinsics::_putIntUnaligned:
 581   case vmIntrinsics::_putLongUnaligned:
 582     if (!UseUnalignedAccesses) return false;
 583     break;
 584   default:
 585     break;
 586   }
 587 
 588   Symbol* method_holder = method->method_holder()->name();
 589   // -XX:-InlineClassNatives disables natives from the Class class.
 590   // The flag applies to all reflective calls, notably Array.newArray
 591   // (visible to Java programmers as Array.newInstance).
 592   if (method_holder == vmSymbols::java_lang_Class() ||
 593       method_holder == vmSymbols::java_lang_reflect_Array()) {
 594     if (!InlineClassNatives) return false;
 595   }
 596 
 597   // -XX:-InlineThreadNatives disables natives from the Thread class.
 598   if (method_holder == vmSymbols::java_lang_Thread()) {
 599     if (!InlineThreadNatives) return false;
 600   }
 601 
 602   // -XX:-InlineMathNatives disables natives from the Math,Float and Double classes.
 603   if (method_holder == vmSymbols::java_lang_Math() ||
 604       method_holder == vmSymbols::java_lang_Float() ||
 605       method_holder == vmSymbols::java_lang_Double()) {
 606     if (!InlineMathNatives) return false;
 607   }
 608 
 609   // -XX:-InlineUnsafeOps disables natives from the Unsafe class.
 610   if (method_holder == vmSymbols::sun_misc_Unsafe()) {
 611     if (!InlineUnsafeOps) return false;
 612   }
 613 
 614   return true;
 615 }
 616 
 617 //---------------------------make_vm_intrinsic----------------------------
 618 CallGenerator* Compile::make_vm_intrinsic(ciMethod* m, bool is_virtual) {
 619   vmIntrinsics::ID id = m->intrinsic_id();
 620   assert(id != vmIntrinsics::_none, "must be a VM intrinsic");
 621 
 622   if (!m->is_loaded()) {
 623     // Do not attempt to inline unloaded methods.
 624     return NULL;
 625   }
 626 
 627   bool is_available = false;
 628   {
 629     // For calling is_intrinsic_available we need to transition to
 630     // the '_thread_in_vm' stat because is_intrinsic_available_for()
 631     // accesses VM-internal data.
 632     VM_ENTRY_MARK;
 633     methodHandle mh(THREAD, m->get_Method());
 634     methodHandle ct(THREAD, method()->get_Method());
 635     is_available = is_intrinsic_available_for(mh(), ct(), is_virtual);
 636   }
 637 
 638   if (is_available) {
 639     assert(id <= vmIntrinsics::LAST_COMPILER_INLINE, "caller responsibility");
 640     assert(id != vmIntrinsics::_Object_init && id != vmIntrinsics::_invoke, "enum out of order?");
 641     return new LibraryIntrinsic(m, is_virtual,
 642                                 intrinsic_predicates_needed_for(id),
 643                                 intrinsic_does_virtual_dispatch_for(id),
 644                                 (vmIntrinsics::ID) id);
 645   } else {
 646     return NULL;
 647   }
 648 }
 649 
 650 //----------------------register_library_intrinsics-----------------------
 651 // Initialize this file's data structures, for each Compile instance.
 652 void Compile::register_library_intrinsics() {
 653   // Nothing to do here.
 654 }
 655 
 656 JVMState* LibraryIntrinsic::generate(JVMState* jvms) {
 657   LibraryCallKit kit(jvms, this);
 658   Compile* C = kit.C;
 659   int nodes = C->unique();
 660 #ifndef PRODUCT
 661   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
 662     char buf[1000];
 663     const char* str = vmIntrinsics::short_name_as_C_string(intrinsic_id(), buf, sizeof(buf));
 664     tty->print_cr("Intrinsic %s", str);
 665   }
 666 #endif
 667   ciMethod* callee = kit.callee();
 668   const int bci    = kit.bci();
 669 
 670   // Try to inline the intrinsic.
 671   if ((CheckIntrinsics ? callee->intrinsic_candidate() : true) &&
 672       kit.try_to_inline(_last_predicate)) {
 673     if (C->print_intrinsics() || C->print_inlining()) {
 674       C->print_inlining(callee, jvms->depth() - 1, bci, is_virtual() ? "(intrinsic, virtual)" : "(intrinsic)");
 675     }
 676     C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_worked);
 677     if (C->log()) {
 678       C->log()->elem("intrinsic id='%s'%s nodes='%d'",
 679                      vmIntrinsics::name_at(intrinsic_id()),
 680                      (is_virtual() ? " virtual='1'" : ""),
 681                      C->unique() - nodes);
 682     }
 683     // Push the result from the inlined method onto the stack.
 684     kit.push_result();
 685     C->print_inlining_update(this);
 686     return kit.transfer_exceptions_into_jvms();
 687   }
 688 
 689   // The intrinsic bailed out
 690   if (C->print_intrinsics() || C->print_inlining()) {
 691     if (jvms->has_method()) {
 692       // Not a root compile.
 693       const char* msg;
 694       if (callee->intrinsic_candidate()) {
 695         msg = is_virtual() ? "failed to inline (intrinsic, virtual)" : "failed to inline (intrinsic)";
 696       } else {
 697         msg = is_virtual() ? "failed to inline (intrinsic, virtual), method not annotated"
 698                            : "failed to inline (intrinsic), method not annotated";
 699       }
 700       C->print_inlining(callee, jvms->depth() - 1, bci, msg);
 701     } else {
 702       // Root compile
 703       tty->print("Did not generate intrinsic %s%s at bci:%d in",
 704                vmIntrinsics::name_at(intrinsic_id()),
 705                (is_virtual() ? " (virtual)" : ""), bci);
 706     }
 707   }
 708   C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_failed);
 709   C->print_inlining_update(this);
 710   return NULL;
 711 }
 712 
 713 Node* LibraryIntrinsic::generate_predicate(JVMState* jvms, int predicate) {
 714   LibraryCallKit kit(jvms, this);
 715   Compile* C = kit.C;
 716   int nodes = C->unique();
 717   _last_predicate = predicate;
 718 #ifndef PRODUCT
 719   assert(is_predicated() && predicate < predicates_count(), "sanity");
 720   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
 721     char buf[1000];
 722     const char* str = vmIntrinsics::short_name_as_C_string(intrinsic_id(), buf, sizeof(buf));
 723     tty->print_cr("Predicate for intrinsic %s", str);
 724   }
 725 #endif
 726   ciMethod* callee = kit.callee();
 727   const int bci    = kit.bci();
 728 
 729   Node* slow_ctl = kit.try_to_predicate(predicate);
 730   if (!kit.failing()) {
 731     if (C->print_intrinsics() || C->print_inlining()) {
 732       C->print_inlining(callee, jvms->depth() - 1, bci, is_virtual() ? "(intrinsic, virtual, predicate)" : "(intrinsic, predicate)");
 733     }
 734     C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_worked);
 735     if (C->log()) {
 736       C->log()->elem("predicate_intrinsic id='%s'%s nodes='%d'",
 737                      vmIntrinsics::name_at(intrinsic_id()),
 738                      (is_virtual() ? " virtual='1'" : ""),
 739                      C->unique() - nodes);
 740     }
 741     return slow_ctl; // Could be NULL if the check folds.
 742   }
 743 
 744   // The intrinsic bailed out
 745   if (C->print_intrinsics() || C->print_inlining()) {
 746     if (jvms->has_method()) {
 747       // Not a root compile.
 748       const char* msg = "failed to generate predicate for intrinsic";
 749       C->print_inlining(kit.callee(), jvms->depth() - 1, bci, msg);
 750     } else {
 751       // Root compile
 752       C->print_inlining_stream()->print("Did not generate predicate for intrinsic %s%s at bci:%d in",
 753                                         vmIntrinsics::name_at(intrinsic_id()),
 754                                         (is_virtual() ? " (virtual)" : ""), bci);
 755     }
 756   }
 757   C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_failed);
 758   return NULL;
 759 }
 760 
 761 bool LibraryCallKit::try_to_inline(int predicate) {
 762   // Handle symbolic names for otherwise undistinguished boolean switches:
 763   const bool is_store       = true;
 764   const bool is_native_ptr  = true;
 765   const bool is_static      = true;
 766   const bool is_volatile    = true;
 767 
 768   if (!jvms()->has_method()) {
 769     // Root JVMState has a null method.
 770     assert(map()->memory()->Opcode() == Op_Parm, "");
 771     // Insert the memory aliasing node
 772     set_all_memory(reset_memory());
 773   }
 774   assert(merged_memory(), "");
 775 
 776 
 777   switch (intrinsic_id()) {
 778   case vmIntrinsics::_hashCode:                 return inline_native_hashcode(intrinsic()->is_virtual(), !is_static);
 779   case vmIntrinsics::_identityHashCode:         return inline_native_hashcode(/*!virtual*/ false,         is_static);
 780   case vmIntrinsics::_getClass:                 return inline_native_getClass();
 781 
 782   case vmIntrinsics::_dsin:
 783   case vmIntrinsics::_dcos:
 784   case vmIntrinsics::_dtan:
 785   case vmIntrinsics::_dabs:
 786   case vmIntrinsics::_datan2:
 787   case vmIntrinsics::_dsqrt:
 788   case vmIntrinsics::_dexp:
 789   case vmIntrinsics::_dlog:
 790   case vmIntrinsics::_dlog10:
 791   case vmIntrinsics::_dpow:                     return inline_math_native(intrinsic_id());
 792 
 793   case vmIntrinsics::_min:
 794   case vmIntrinsics::_max:                      return inline_min_max(intrinsic_id());
 795 
 796   case vmIntrinsics::_addExactI:                return inline_math_addExactI(false /* add */);
 797   case vmIntrinsics::_addExactL:                return inline_math_addExactL(false /* add */);
 798   case vmIntrinsics::_decrementExactI:          return inline_math_subtractExactI(true /* decrement */);
 799   case vmIntrinsics::_decrementExactL:          return inline_math_subtractExactL(true /* decrement */);
 800   case vmIntrinsics::_incrementExactI:          return inline_math_addExactI(true /* increment */);
 801   case vmIntrinsics::_incrementExactL:          return inline_math_addExactL(true /* increment */);
 802   case vmIntrinsics::_multiplyExactI:           return inline_math_multiplyExactI();
 803   case vmIntrinsics::_multiplyExactL:           return inline_math_multiplyExactL();
 804   case vmIntrinsics::_negateExactI:             return inline_math_negateExactI();
 805   case vmIntrinsics::_negateExactL:             return inline_math_negateExactL();
 806   case vmIntrinsics::_subtractExactI:           return inline_math_subtractExactI(false /* subtract */);
 807   case vmIntrinsics::_subtractExactL:           return inline_math_subtractExactL(false /* subtract */);
 808 
 809   case vmIntrinsics::_arraycopy:                return inline_arraycopy();
 810 
 811   case vmIntrinsics::_compareTo:                return inline_string_compareTo();
 812   case vmIntrinsics::_indexOf:                  return inline_string_indexOf();
 813   case vmIntrinsics::_equals:                   return inline_string_equals();
 814 
 815   case vmIntrinsics::_getObject:                return inline_unsafe_access(!is_native_ptr, !is_store, T_OBJECT,  !is_volatile);
 816   case vmIntrinsics::_getBoolean:               return inline_unsafe_access(!is_native_ptr, !is_store, T_BOOLEAN, !is_volatile);
 817   case vmIntrinsics::_getByte:                  return inline_unsafe_access(!is_native_ptr, !is_store, T_BYTE,    !is_volatile);
 818   case vmIntrinsics::_getShort:                 return inline_unsafe_access(!is_native_ptr, !is_store, T_SHORT,   !is_volatile);
 819   case vmIntrinsics::_getChar:                  return inline_unsafe_access(!is_native_ptr, !is_store, T_CHAR,    !is_volatile);
 820   case vmIntrinsics::_getInt:                   return inline_unsafe_access(!is_native_ptr, !is_store, T_INT,     !is_volatile);
 821   case vmIntrinsics::_getLong:                  return inline_unsafe_access(!is_native_ptr, !is_store, T_LONG,    !is_volatile);
 822   case vmIntrinsics::_getFloat:                 return inline_unsafe_access(!is_native_ptr, !is_store, T_FLOAT,   !is_volatile);
 823   case vmIntrinsics::_getDouble:                return inline_unsafe_access(!is_native_ptr, !is_store, T_DOUBLE,  !is_volatile);
 824 
 825   case vmIntrinsics::_putObject:                return inline_unsafe_access(!is_native_ptr,  is_store, T_OBJECT,  !is_volatile);
 826   case vmIntrinsics::_putBoolean:               return inline_unsafe_access(!is_native_ptr,  is_store, T_BOOLEAN, !is_volatile);
 827   case vmIntrinsics::_putByte:                  return inline_unsafe_access(!is_native_ptr,  is_store, T_BYTE,    !is_volatile);
 828   case vmIntrinsics::_putShort:                 return inline_unsafe_access(!is_native_ptr,  is_store, T_SHORT,   !is_volatile);
 829   case vmIntrinsics::_putChar:                  return inline_unsafe_access(!is_native_ptr,  is_store, T_CHAR,    !is_volatile);
 830   case vmIntrinsics::_putInt:                   return inline_unsafe_access(!is_native_ptr,  is_store, T_INT,     !is_volatile);
 831   case vmIntrinsics::_putLong:                  return inline_unsafe_access(!is_native_ptr,  is_store, T_LONG,    !is_volatile);
 832   case vmIntrinsics::_putFloat:                 return inline_unsafe_access(!is_native_ptr,  is_store, T_FLOAT,   !is_volatile);
 833   case vmIntrinsics::_putDouble:                return inline_unsafe_access(!is_native_ptr,  is_store, T_DOUBLE,  !is_volatile);
 834 
 835   case vmIntrinsics::_getByte_raw:              return inline_unsafe_access( is_native_ptr, !is_store, T_BYTE,    !is_volatile);
 836   case vmIntrinsics::_getShort_raw:             return inline_unsafe_access( is_native_ptr, !is_store, T_SHORT,   !is_volatile);
 837   case vmIntrinsics::_getChar_raw:              return inline_unsafe_access( is_native_ptr, !is_store, T_CHAR,    !is_volatile);
 838   case vmIntrinsics::_getInt_raw:               return inline_unsafe_access( is_native_ptr, !is_store, T_INT,     !is_volatile);
 839   case vmIntrinsics::_getLong_raw:              return inline_unsafe_access( is_native_ptr, !is_store, T_LONG,    !is_volatile);
 840   case vmIntrinsics::_getFloat_raw:             return inline_unsafe_access( is_native_ptr, !is_store, T_FLOAT,   !is_volatile);
 841   case vmIntrinsics::_getDouble_raw:            return inline_unsafe_access( is_native_ptr, !is_store, T_DOUBLE,  !is_volatile);
 842   case vmIntrinsics::_getAddress_raw:           return inline_unsafe_access( is_native_ptr, !is_store, T_ADDRESS, !is_volatile);
 843 
 844   case vmIntrinsics::_putByte_raw:              return inline_unsafe_access( is_native_ptr,  is_store, T_BYTE,    !is_volatile);
 845   case vmIntrinsics::_putShort_raw:             return inline_unsafe_access( is_native_ptr,  is_store, T_SHORT,   !is_volatile);
 846   case vmIntrinsics::_putChar_raw:              return inline_unsafe_access( is_native_ptr,  is_store, T_CHAR,    !is_volatile);
 847   case vmIntrinsics::_putInt_raw:               return inline_unsafe_access( is_native_ptr,  is_store, T_INT,     !is_volatile);
 848   case vmIntrinsics::_putLong_raw:              return inline_unsafe_access( is_native_ptr,  is_store, T_LONG,    !is_volatile);
 849   case vmIntrinsics::_putFloat_raw:             return inline_unsafe_access( is_native_ptr,  is_store, T_FLOAT,   !is_volatile);
 850   case vmIntrinsics::_putDouble_raw:            return inline_unsafe_access( is_native_ptr,  is_store, T_DOUBLE,  !is_volatile);
 851   case vmIntrinsics::_putAddress_raw:           return inline_unsafe_access( is_native_ptr,  is_store, T_ADDRESS, !is_volatile);
 852 
 853   case vmIntrinsics::_getObjectVolatile:        return inline_unsafe_access(!is_native_ptr, !is_store, T_OBJECT,   is_volatile);
 854   case vmIntrinsics::_getBooleanVolatile:       return inline_unsafe_access(!is_native_ptr, !is_store, T_BOOLEAN,  is_volatile);
 855   case vmIntrinsics::_getByteVolatile:          return inline_unsafe_access(!is_native_ptr, !is_store, T_BYTE,     is_volatile);
 856   case vmIntrinsics::_getShortVolatile:         return inline_unsafe_access(!is_native_ptr, !is_store, T_SHORT,    is_volatile);
 857   case vmIntrinsics::_getCharVolatile:          return inline_unsafe_access(!is_native_ptr, !is_store, T_CHAR,     is_volatile);
 858   case vmIntrinsics::_getIntVolatile:           return inline_unsafe_access(!is_native_ptr, !is_store, T_INT,      is_volatile);
 859   case vmIntrinsics::_getLongVolatile:          return inline_unsafe_access(!is_native_ptr, !is_store, T_LONG,     is_volatile);
 860   case vmIntrinsics::_getFloatVolatile:         return inline_unsafe_access(!is_native_ptr, !is_store, T_FLOAT,    is_volatile);
 861   case vmIntrinsics::_getDoubleVolatile:        return inline_unsafe_access(!is_native_ptr, !is_store, T_DOUBLE,   is_volatile);
 862 
 863   case vmIntrinsics::_putObjectVolatile:        return inline_unsafe_access(!is_native_ptr,  is_store, T_OBJECT,   is_volatile);
 864   case vmIntrinsics::_putBooleanVolatile:       return inline_unsafe_access(!is_native_ptr,  is_store, T_BOOLEAN,  is_volatile);
 865   case vmIntrinsics::_putByteVolatile:          return inline_unsafe_access(!is_native_ptr,  is_store, T_BYTE,     is_volatile);
 866   case vmIntrinsics::_putShortVolatile:         return inline_unsafe_access(!is_native_ptr,  is_store, T_SHORT,    is_volatile);
 867   case vmIntrinsics::_putCharVolatile:          return inline_unsafe_access(!is_native_ptr,  is_store, T_CHAR,     is_volatile);
 868   case vmIntrinsics::_putIntVolatile:           return inline_unsafe_access(!is_native_ptr,  is_store, T_INT,      is_volatile);
 869   case vmIntrinsics::_putLongVolatile:          return inline_unsafe_access(!is_native_ptr,  is_store, T_LONG,     is_volatile);
 870   case vmIntrinsics::_putFloatVolatile:         return inline_unsafe_access(!is_native_ptr,  is_store, T_FLOAT,    is_volatile);
 871   case vmIntrinsics::_putDoubleVolatile:        return inline_unsafe_access(!is_native_ptr,  is_store, T_DOUBLE,   is_volatile);
 872 
 873   case vmIntrinsics::_getShortUnaligned:        return inline_unsafe_access(!is_native_ptr, !is_store, T_SHORT,   !is_volatile);
 874   case vmIntrinsics::_getCharUnaligned:         return inline_unsafe_access(!is_native_ptr, !is_store, T_CHAR,    !is_volatile);
 875   case vmIntrinsics::_getIntUnaligned:          return inline_unsafe_access(!is_native_ptr, !is_store, T_INT,     !is_volatile);
 876   case vmIntrinsics::_getLongUnaligned:         return inline_unsafe_access(!is_native_ptr, !is_store, T_LONG,    !is_volatile);
 877 
 878   case vmIntrinsics::_putShortUnaligned:        return inline_unsafe_access(!is_native_ptr,  is_store, T_SHORT,   !is_volatile);
 879   case vmIntrinsics::_putCharUnaligned:         return inline_unsafe_access(!is_native_ptr,  is_store, T_CHAR,    !is_volatile);
 880   case vmIntrinsics::_putIntUnaligned:          return inline_unsafe_access(!is_native_ptr,  is_store, T_INT,     !is_volatile);
 881   case vmIntrinsics::_putLongUnaligned:         return inline_unsafe_access(!is_native_ptr,  is_store, T_LONG,    !is_volatile);
 882 
 883   case vmIntrinsics::_compareAndSwapObject:     return inline_unsafe_load_store(T_OBJECT, LS_cmpxchg);
 884   case vmIntrinsics::_compareAndSwapInt:        return inline_unsafe_load_store(T_INT,    LS_cmpxchg);
 885   case vmIntrinsics::_compareAndSwapLong:       return inline_unsafe_load_store(T_LONG,   LS_cmpxchg);
 886 
 887   case vmIntrinsics::_putOrderedObject:         return inline_unsafe_ordered_store(T_OBJECT);
 888   case vmIntrinsics::_putOrderedInt:            return inline_unsafe_ordered_store(T_INT);
 889   case vmIntrinsics::_putOrderedLong:           return inline_unsafe_ordered_store(T_LONG);
 890 
 891   case vmIntrinsics::_getAndAddInt:             return inline_unsafe_load_store(T_INT,    LS_xadd);
 892   case vmIntrinsics::_getAndAddLong:            return inline_unsafe_load_store(T_LONG,   LS_xadd);
 893   case vmIntrinsics::_getAndSetInt:             return inline_unsafe_load_store(T_INT,    LS_xchg);
 894   case vmIntrinsics::_getAndSetLong:            return inline_unsafe_load_store(T_LONG,   LS_xchg);
 895   case vmIntrinsics::_getAndSetObject:          return inline_unsafe_load_store(T_OBJECT, LS_xchg);
 896 
 897   case vmIntrinsics::_loadFence:
 898   case vmIntrinsics::_storeFence:
 899   case vmIntrinsics::_fullFence:                return inline_unsafe_fence(intrinsic_id());
 900 
 901   case vmIntrinsics::_currentThread:            return inline_native_currentThread();
 902   case vmIntrinsics::_isInterrupted:            return inline_native_isInterrupted();
 903 
 904 #ifdef TRACE_HAVE_INTRINSICS
 905   case vmIntrinsics::_classID:                  return inline_native_classID();
 906   case vmIntrinsics::_threadID:                 return inline_native_threadID();
 907   case vmIntrinsics::_counterTime:              return inline_native_time_funcs(CAST_FROM_FN_PTR(address, TRACE_TIME_METHOD), "counterTime");
 908 #endif
 909   case vmIntrinsics::_currentTimeMillis:        return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeMillis), "currentTimeMillis");
 910   case vmIntrinsics::_nanoTime:                 return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeNanos), "nanoTime");
 911   case vmIntrinsics::_allocateInstance:         return inline_unsafe_allocate();
 912   case vmIntrinsics::_copyMemory:               return inline_unsafe_copyMemory();
 913   case vmIntrinsics::_newArray:                 return inline_native_newArray();
 914   case vmIntrinsics::_getLength:                return inline_native_getLength();
 915   case vmIntrinsics::_copyOf:                   return inline_array_copyOf(false);
 916   case vmIntrinsics::_copyOfRange:              return inline_array_copyOf(true);
 917   case vmIntrinsics::_equalsC:                  return inline_array_equals();
 918   case vmIntrinsics::_clone:                    return inline_native_clone(intrinsic()->is_virtual());
 919 
 920   case vmIntrinsics::_isAssignableFrom:         return inline_native_subtype_check();
 921 
 922   case vmIntrinsics::_isInstance:
 923   case vmIntrinsics::_getModifiers:
 924   case vmIntrinsics::_isInterface:
 925   case vmIntrinsics::_isArray:
 926   case vmIntrinsics::_isPrimitive:
 927   case vmIntrinsics::_getSuperclass:
 928   case vmIntrinsics::_getClassAccessFlags:      return inline_native_Class_query(intrinsic_id());
 929 
 930   case vmIntrinsics::_floatToRawIntBits:
 931   case vmIntrinsics::_floatToIntBits:
 932   case vmIntrinsics::_intBitsToFloat:
 933   case vmIntrinsics::_doubleToRawLongBits:
 934   case vmIntrinsics::_doubleToLongBits:
 935   case vmIntrinsics::_longBitsToDouble:         return inline_fp_conversions(intrinsic_id());
 936 
 937   case vmIntrinsics::_numberOfLeadingZeros_i:
 938   case vmIntrinsics::_numberOfLeadingZeros_l:
 939   case vmIntrinsics::_numberOfTrailingZeros_i:
 940   case vmIntrinsics::_numberOfTrailingZeros_l:
 941   case vmIntrinsics::_bitCount_i:
 942   case vmIntrinsics::_bitCount_l:
 943   case vmIntrinsics::_reverseBytes_i:
 944   case vmIntrinsics::_reverseBytes_l:
 945   case vmIntrinsics::_reverseBytes_s:
 946   case vmIntrinsics::_reverseBytes_c:           return inline_number_methods(intrinsic_id());
 947 
 948   case vmIntrinsics::_getCallerClass:           return inline_native_Reflection_getCallerClass();
 949 
 950   case vmIntrinsics::_Reference_get:            return inline_reference_get();
 951 
 952   case vmIntrinsics::_Class_cast:               return inline_Class_cast();
 953 
 954   case vmIntrinsics::_aescrypt_encryptBlock:
 955   case vmIntrinsics::_aescrypt_decryptBlock:    return inline_aescrypt_Block(intrinsic_id());
 956 
 957   case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
 958   case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
 959     return inline_cipherBlockChaining_AESCrypt(intrinsic_id());
 960 
 961   case vmIntrinsics::_sha_implCompress:
 962   case vmIntrinsics::_sha2_implCompress:
 963   case vmIntrinsics::_sha5_implCompress:
 964     return inline_sha_implCompress(intrinsic_id());
 965 
 966   case vmIntrinsics::_digestBase_implCompressMB:
 967     return inline_digestBase_implCompressMB(predicate);
 968 
 969   case vmIntrinsics::_multiplyToLen:
 970     return inline_multiplyToLen();
 971 
 972   case vmIntrinsics::_squareToLen:
 973     return inline_squareToLen();
 974 
 975   case vmIntrinsics::_mulAdd:
 976     return inline_mulAdd();
 977 
 978   case vmIntrinsics::_montgomeryMultiply:
 979     return inline_montgomeryMultiply();
 980   case vmIntrinsics::_montgomerySquare:
 981     return inline_montgomerySquare();
 982 
 983   case vmIntrinsics::_ghash_processBlocks:
 984     return inline_ghash_processBlocks();
 985 
 986   case vmIntrinsics::_encodeISOArray:
 987     return inline_encodeISOArray();
 988 
 989   case vmIntrinsics::_updateCRC32:
 990     return inline_updateCRC32();
 991   case vmIntrinsics::_updateBytesCRC32:
 992     return inline_updateBytesCRC32();
 993   case vmIntrinsics::_updateByteBufferCRC32:
 994     return inline_updateByteBufferCRC32();
 995 
 996   case vmIntrinsics::_updateBytesCRC32C:
 997     return inline_updateBytesCRC32C();
 998   case vmIntrinsics::_updateDirectByteBufferCRC32C:
 999     return inline_updateDirectByteBufferCRC32C();
1000 
1001   case vmIntrinsics::_profileBoolean:
1002     return inline_profileBoolean();
1003   case vmIntrinsics::_isCompileConstant:
1004     return inline_isCompileConstant();
1005 
1006   default:
1007     // If you get here, it may be that someone has added a new intrinsic
1008     // to the list in vmSymbols.hpp without implementing it here.
1009 #ifndef PRODUCT
1010     if ((PrintMiscellaneous && (Verbose || WizardMode)) || PrintOpto) {
1011       tty->print_cr("*** Warning: Unimplemented intrinsic %s(%d)",
1012                     vmIntrinsics::name_at(intrinsic_id()), intrinsic_id());
1013     }
1014 #endif
1015     return false;
1016   }
1017 }
1018 
1019 Node* LibraryCallKit::try_to_predicate(int predicate) {
1020   if (!jvms()->has_method()) {
1021     // Root JVMState has a null method.
1022     assert(map()->memory()->Opcode() == Op_Parm, "");
1023     // Insert the memory aliasing node
1024     set_all_memory(reset_memory());
1025   }
1026   assert(merged_memory(), "");
1027 
1028   switch (intrinsic_id()) {
1029   case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
1030     return inline_cipherBlockChaining_AESCrypt_predicate(false);
1031   case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
1032     return inline_cipherBlockChaining_AESCrypt_predicate(true);
1033   case vmIntrinsics::_digestBase_implCompressMB:
1034     return inline_digestBase_implCompressMB_predicate(predicate);
1035 
1036   default:
1037     // If you get here, it may be that someone has added a new intrinsic
1038     // to the list in vmSymbols.hpp without implementing it here.
1039 #ifndef PRODUCT
1040     if ((PrintMiscellaneous && (Verbose || WizardMode)) || PrintOpto) {
1041       tty->print_cr("*** Warning: Unimplemented predicate for intrinsic %s(%d)",
1042                     vmIntrinsics::name_at(intrinsic_id()), intrinsic_id());
1043     }
1044 #endif
1045     Node* slow_ctl = control();
1046     set_control(top()); // No fast path instrinsic
1047     return slow_ctl;
1048   }
1049 }
1050 
1051 //------------------------------set_result-------------------------------
1052 // Helper function for finishing intrinsics.
1053 void LibraryCallKit::set_result(RegionNode* region, PhiNode* value) {
1054   record_for_igvn(region);
1055   set_control(_gvn.transform(region));
1056   set_result( _gvn.transform(value));
1057   assert(value->type()->basic_type() == result()->bottom_type()->basic_type(), "sanity");
1058 }
1059 
1060 //------------------------------generate_guard---------------------------
1061 // Helper function for generating guarded fast-slow graph structures.
1062 // The given 'test', if true, guards a slow path.  If the test fails
1063 // then a fast path can be taken.  (We generally hope it fails.)
1064 // In all cases, GraphKit::control() is updated to the fast path.
1065 // The returned value represents the control for the slow path.
1066 // The return value is never 'top'; it is either a valid control
1067 // or NULL if it is obvious that the slow path can never be taken.
1068 // Also, if region and the slow control are not NULL, the slow edge
1069 // is appended to the region.
1070 Node* LibraryCallKit::generate_guard(Node* test, RegionNode* region, float true_prob) {
1071   if (stopped()) {
1072     // Already short circuited.
1073     return NULL;
1074   }
1075 
1076   // Build an if node and its projections.
1077   // If test is true we take the slow path, which we assume is uncommon.
1078   if (_gvn.type(test) == TypeInt::ZERO) {
1079     // The slow branch is never taken.  No need to build this guard.
1080     return NULL;
1081   }
1082 
1083   IfNode* iff = create_and_map_if(control(), test, true_prob, COUNT_UNKNOWN);
1084 
1085   Node* if_slow = _gvn.transform(new IfTrueNode(iff));
1086   if (if_slow == top()) {
1087     // The slow branch is never taken.  No need to build this guard.
1088     return NULL;
1089   }
1090 
1091   if (region != NULL)
1092     region->add_req(if_slow);
1093 
1094   Node* if_fast = _gvn.transform(new IfFalseNode(iff));
1095   set_control(if_fast);
1096 
1097   return if_slow;
1098 }
1099 
1100 inline Node* LibraryCallKit::generate_slow_guard(Node* test, RegionNode* region) {
1101   return generate_guard(test, region, PROB_UNLIKELY_MAG(3));
1102 }
1103 inline Node* LibraryCallKit::generate_fair_guard(Node* test, RegionNode* region) {
1104   return generate_guard(test, region, PROB_FAIR);
1105 }
1106 
1107 inline Node* LibraryCallKit::generate_negative_guard(Node* index, RegionNode* region,
1108                                                      Node* *pos_index) {
1109   if (stopped())
1110     return NULL;                // already stopped
1111   if (_gvn.type(index)->higher_equal(TypeInt::POS)) // [0,maxint]
1112     return NULL;                // index is already adequately typed
1113   Node* cmp_lt = _gvn.transform(new CmpINode(index, intcon(0)));
1114   Node* bol_lt = _gvn.transform(new BoolNode(cmp_lt, BoolTest::lt));
1115   Node* is_neg = generate_guard(bol_lt, region, PROB_MIN);
1116   if (is_neg != NULL && pos_index != NULL) {
1117     // Emulate effect of Parse::adjust_map_after_if.
1118     Node* ccast = new CastIINode(index, TypeInt::POS);
1119     ccast->set_req(0, control());
1120     (*pos_index) = _gvn.transform(ccast);
1121   }
1122   return is_neg;
1123 }
1124 
1125 // Make sure that 'position' is a valid limit index, in [0..length].
1126 // There are two equivalent plans for checking this:
1127 //   A. (offset + copyLength)  unsigned<=  arrayLength
1128 //   B. offset  <=  (arrayLength - copyLength)
1129 // We require that all of the values above, except for the sum and
1130 // difference, are already known to be non-negative.
1131 // Plan A is robust in the face of overflow, if offset and copyLength
1132 // are both hugely positive.
1133 //
1134 // Plan B is less direct and intuitive, but it does not overflow at
1135 // all, since the difference of two non-negatives is always
1136 // representable.  Whenever Java methods must perform the equivalent
1137 // check they generally use Plan B instead of Plan A.
1138 // For the moment we use Plan A.
1139 inline Node* LibraryCallKit::generate_limit_guard(Node* offset,
1140                                                   Node* subseq_length,
1141                                                   Node* array_length,
1142                                                   RegionNode* region) {
1143   if (stopped())
1144     return NULL;                // already stopped
1145   bool zero_offset = _gvn.type(offset) == TypeInt::ZERO;
1146   if (zero_offset && subseq_length->eqv_uncast(array_length))
1147     return NULL;                // common case of whole-array copy
1148   Node* last = subseq_length;
1149   if (!zero_offset)             // last += offset
1150     last = _gvn.transform(new AddINode(last, offset));
1151   Node* cmp_lt = _gvn.transform(new CmpUNode(array_length, last));
1152   Node* bol_lt = _gvn.transform(new BoolNode(cmp_lt, BoolTest::lt));
1153   Node* is_over = generate_guard(bol_lt, region, PROB_MIN);
1154   return is_over;
1155 }
1156 
1157 
1158 //--------------------------generate_current_thread--------------------
1159 Node* LibraryCallKit::generate_current_thread(Node* &tls_output) {
1160   ciKlass*    thread_klass = env()->Thread_klass();
1161   const Type* thread_type  = TypeOopPtr::make_from_klass(thread_klass)->cast_to_ptr_type(TypePtr::NotNull);
1162   Node* thread = _gvn.transform(new ThreadLocalNode());
1163   Node* p = basic_plus_adr(top()/*!oop*/, thread, in_bytes(JavaThread::threadObj_offset()));
1164   Node* threadObj = make_load(NULL, p, thread_type, T_OBJECT, MemNode::unordered);
1165   tls_output = thread;
1166   return threadObj;
1167 }
1168 
1169 
1170 //------------------------------make_string_method_node------------------------
1171 // Helper method for String intrinsic functions. This version is called
1172 // with str1 and str2 pointing to String object nodes.
1173 //
1174 Node* LibraryCallKit::make_string_method_node(int opcode, Node* str1, Node* str2) {
1175   Node* no_ctrl = NULL;
1176 
1177   // Get start addr of string
1178   Node* str1_value   = load_String_value(no_ctrl, str1);
1179   Node* str1_offset  = load_String_offset(no_ctrl, str1);
1180   Node* str1_start   = array_element_address(str1_value, str1_offset, T_CHAR);
1181 
1182   // Get length of string 1
1183   Node* str1_len  = load_String_length(no_ctrl, str1);
1184 
1185   Node* str2_value   = load_String_value(no_ctrl, str2);
1186   Node* str2_offset  = load_String_offset(no_ctrl, str2);
1187   Node* str2_start   = array_element_address(str2_value, str2_offset, T_CHAR);
1188 
1189   Node* str2_len = NULL;
1190   Node* result = NULL;
1191 
1192   switch (opcode) {
1193   case Op_StrIndexOf:
1194     // Get length of string 2
1195     str2_len = load_String_length(no_ctrl, str2);
1196 
1197     result = new StrIndexOfNode(control(), memory(TypeAryPtr::CHARS),
1198                                 str1_start, str1_len, str2_start, str2_len);
1199     break;
1200   case Op_StrComp:
1201     // Get length of string 2
1202     str2_len = load_String_length(no_ctrl, str2);
1203 
1204     result = new StrCompNode(control(), memory(TypeAryPtr::CHARS),
1205                              str1_start, str1_len, str2_start, str2_len);
1206     break;
1207   case Op_StrEquals:
1208     result = new StrEqualsNode(control(), memory(TypeAryPtr::CHARS),
1209                                str1_start, str2_start, str1_len);
1210     break;
1211   default:
1212     ShouldNotReachHere();
1213     return NULL;
1214   }
1215 
1216   // All these intrinsics have checks.
1217   C->set_has_split_ifs(true); // Has chance for split-if optimization
1218 
1219   return _gvn.transform(result);
1220 }
1221 
1222 // Helper method for String intrinsic functions. This version is called
1223 // with str1 and str2 pointing to char[] nodes, with cnt1 and cnt2 pointing
1224 // to Int nodes containing the lenghts of str1 and str2.
1225 //
1226 Node* LibraryCallKit::make_string_method_node(int opcode, Node* str1_start, Node* cnt1, Node* str2_start, Node* cnt2) {
1227   Node* result = NULL;
1228   switch (opcode) {
1229   case Op_StrIndexOf:
1230     result = new StrIndexOfNode(control(), memory(TypeAryPtr::CHARS),
1231                                 str1_start, cnt1, str2_start, cnt2);
1232     break;
1233   case Op_StrComp:
1234     result = new StrCompNode(control(), memory(TypeAryPtr::CHARS),
1235                              str1_start, cnt1, str2_start, cnt2);
1236     break;
1237   case Op_StrEquals:
1238     result = new StrEqualsNode(control(), memory(TypeAryPtr::CHARS),
1239                                str1_start, str2_start, cnt1);
1240     break;
1241   default:
1242     ShouldNotReachHere();
1243     return NULL;
1244   }
1245 
1246   // All these intrinsics have checks.
1247   C->set_has_split_ifs(true); // Has chance for split-if optimization
1248 
1249   return _gvn.transform(result);
1250 }
1251 
1252 //------------------------------inline_string_compareTo------------------------
1253 // public int java.lang.String.compareTo(String anotherString);
1254 bool LibraryCallKit::inline_string_compareTo() {
1255   Node* receiver = null_check(argument(0));
1256   Node* arg      = null_check(argument(1));
1257   if (stopped()) {
1258     return true;
1259   }
1260   set_result(make_string_method_node(Op_StrComp, receiver, arg));
1261   return true;
1262 }
1263 
1264 //------------------------------inline_string_equals------------------------
1265 bool LibraryCallKit::inline_string_equals() {
1266   Node* receiver = null_check_receiver();
1267   // NOTE: Do not null check argument for String.equals() because spec
1268   // allows to specify NULL as argument.
1269   Node* argument = this->argument(1);
1270   if (stopped()) {
1271     return true;
1272   }
1273 
1274   // paths (plus control) merge
1275   RegionNode* region = new RegionNode(5);
1276   Node* phi = new PhiNode(region, TypeInt::BOOL);
1277 
1278   // does source == target string?
1279   Node* cmp = _gvn.transform(new CmpPNode(receiver, argument));
1280   Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
1281 
1282   Node* if_eq = generate_slow_guard(bol, NULL);
1283   if (if_eq != NULL) {
1284     // receiver == argument
1285     phi->init_req(2, intcon(1));
1286     region->init_req(2, if_eq);
1287   }
1288 
1289   // get String klass for instanceOf
1290   ciInstanceKlass* klass = env()->String_klass();
1291 
1292   if (!stopped()) {
1293     Node* inst = gen_instanceof(argument, makecon(TypeKlassPtr::make(klass)));
1294     Node* cmp  = _gvn.transform(new CmpINode(inst, intcon(1)));
1295     Node* bol  = _gvn.transform(new BoolNode(cmp, BoolTest::ne));
1296 
1297     Node* inst_false = generate_guard(bol, NULL, PROB_MIN);
1298     //instanceOf == true, fallthrough
1299 
1300     if (inst_false != NULL) {
1301       phi->init_req(3, intcon(0));
1302       region->init_req(3, inst_false);
1303     }
1304   }
1305 
1306   if (!stopped()) {
1307     const TypeOopPtr* string_type = TypeOopPtr::make_from_klass(klass);
1308 
1309     // Properly cast the argument to String
1310     argument = _gvn.transform(new CheckCastPPNode(control(), argument, string_type));
1311     // This path is taken only when argument's type is String:NotNull.
1312     argument = cast_not_null(argument, false);
1313 
1314     Node* no_ctrl = NULL;
1315 
1316     // Get start addr of receiver
1317     Node* receiver_val    = load_String_value(no_ctrl, receiver);
1318     Node* receiver_offset = load_String_offset(no_ctrl, receiver);
1319     Node* receiver_start = array_element_address(receiver_val, receiver_offset, T_CHAR);
1320 
1321     // Get length of receiver
1322     Node* receiver_cnt  = load_String_length(no_ctrl, receiver);
1323 
1324     // Get start addr of argument
1325     Node* argument_val    = load_String_value(no_ctrl, argument);
1326     Node* argument_offset = load_String_offset(no_ctrl, argument);
1327     Node* argument_start = array_element_address(argument_val, argument_offset, T_CHAR);
1328 
1329     // Get length of argument
1330     Node* argument_cnt  = load_String_length(no_ctrl, argument);
1331 
1332     // Check for receiver count != argument count
1333     Node* cmp = _gvn.transform(new CmpINode(receiver_cnt, argument_cnt));
1334     Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::ne));
1335     Node* if_ne = generate_slow_guard(bol, NULL);
1336     if (if_ne != NULL) {
1337       phi->init_req(4, intcon(0));
1338       region->init_req(4, if_ne);
1339     }
1340 
1341     // Check for count == 0 is done by assembler code for StrEquals.
1342 
1343     if (!stopped()) {
1344       Node* equals = make_string_method_node(Op_StrEquals, receiver_start, receiver_cnt, argument_start, argument_cnt);
1345       phi->init_req(1, equals);
1346       region->init_req(1, control());
1347     }
1348   }
1349 
1350   // post merge
1351   set_control(_gvn.transform(region));
1352   record_for_igvn(region);
1353 
1354   set_result(_gvn.transform(phi));
1355   return true;
1356 }
1357 
1358 //------------------------------inline_array_equals----------------------------
1359 bool LibraryCallKit::inline_array_equals() {
1360   Node* arg1 = argument(0);
1361   Node* arg2 = argument(1);
1362   set_result(_gvn.transform(new AryEqNode(control(), memory(TypeAryPtr::CHARS), arg1, arg2)));
1363   return true;
1364 }
1365 
1366 // Java version of String.indexOf(constant string)
1367 // class StringDecl {
1368 //   StringDecl(char[] ca) {
1369 //     offset = 0;
1370 //     count = ca.length;
1371 //     value = ca;
1372 //   }
1373 //   int offset;
1374 //   int count;
1375 //   char[] value;
1376 // }
1377 //
1378 // static int string_indexOf_J(StringDecl string_object, char[] target_object,
1379 //                             int targetOffset, int cache_i, int md2) {
1380 //   int cache = cache_i;
1381 //   int sourceOffset = string_object.offset;
1382 //   int sourceCount = string_object.count;
1383 //   int targetCount = target_object.length;
1384 //
1385 //   int targetCountLess1 = targetCount - 1;
1386 //   int sourceEnd = sourceOffset + sourceCount - targetCountLess1;
1387 //
1388 //   char[] source = string_object.value;
1389 //   char[] target = target_object;
1390 //   int lastChar = target[targetCountLess1];
1391 //
1392 //  outer_loop:
1393 //   for (int i = sourceOffset; i < sourceEnd; ) {
1394 //     int src = source[i + targetCountLess1];
1395 //     if (src == lastChar) {
1396 //       // With random strings and a 4-character alphabet,
1397 //       // reverse matching at this point sets up 0.8% fewer
1398 //       // frames, but (paradoxically) makes 0.3% more probes.
1399 //       // Since those probes are nearer the lastChar probe,
1400 //       // there is may be a net D$ win with reverse matching.
1401 //       // But, reversing loop inhibits unroll of inner loop
1402 //       // for unknown reason.  So, does running outer loop from
1403 //       // (sourceOffset - targetCountLess1) to (sourceOffset + sourceCount)
1404 //       for (int j = 0; j < targetCountLess1; j++) {
1405 //         if (target[targetOffset + j] != source[i+j]) {
1406 //           if ((cache & (1 << source[i+j])) == 0) {
1407 //             if (md2 < j+1) {
1408 //               i += j+1;
1409 //               continue outer_loop;
1410 //             }
1411 //           }
1412 //           i += md2;
1413 //           continue outer_loop;
1414 //         }
1415 //       }
1416 //       return i - sourceOffset;
1417 //     }
1418 //     if ((cache & (1 << src)) == 0) {
1419 //       i += targetCountLess1;
1420 //     } // using "i += targetCount;" and an "else i++;" causes a jump to jump.
1421 //     i++;
1422 //   }
1423 //   return -1;
1424 // }
1425 
1426 //------------------------------string_indexOf------------------------
1427 Node* LibraryCallKit::string_indexOf(Node* string_object, ciTypeArray* target_array, jint targetOffset_i,
1428                                      jint cache_i, jint md2_i) {
1429 
1430   Node* no_ctrl  = NULL;
1431   float likely   = PROB_LIKELY(0.9);
1432   float unlikely = PROB_UNLIKELY(0.9);
1433 
1434   const int nargs = 0; // no arguments to push back for uncommon trap in predicate
1435 
1436   Node* source        = load_String_value(no_ctrl, string_object);
1437   Node* sourceOffset  = load_String_offset(no_ctrl, string_object);
1438   Node* sourceCount   = load_String_length(no_ctrl, string_object);
1439 
1440   Node* target = _gvn.transform( makecon(TypeOopPtr::make_from_constant(target_array, true)));
1441   jint target_length = target_array->length();
1442   const TypeAry* target_array_type = TypeAry::make(TypeInt::CHAR, TypeInt::make(0, target_length, Type::WidenMin));
1443   const TypeAryPtr* target_type = TypeAryPtr::make(TypePtr::BotPTR, target_array_type, target_array->klass(), true, Type::OffsetBot);
1444 
1445   // String.value field is known to be @Stable.
1446   if (UseImplicitStableValues) {
1447     target = cast_array_to_stable(target, target_type);
1448   }
1449 
1450   IdealKit kit(this, false, true);
1451 #define __ kit.
1452   Node* zero             = __ ConI(0);
1453   Node* one              = __ ConI(1);
1454   Node* cache            = __ ConI(cache_i);
1455   Node* md2              = __ ConI(md2_i);
1456   Node* lastChar         = __ ConI(target_array->char_at(target_length - 1));
1457   Node* targetCountLess1 = __ ConI(target_length - 1);
1458   Node* targetOffset     = __ ConI(targetOffset_i);
1459   Node* sourceEnd        = __ SubI(__ AddI(sourceOffset, sourceCount), targetCountLess1);
1460 
1461   IdealVariable rtn(kit), i(kit), j(kit); __ declarations_done();
1462   Node* outer_loop = __ make_label(2 /* goto */);
1463   Node* return_    = __ make_label(1);
1464 
1465   __ set(rtn,__ ConI(-1));
1466   __ loop(this, nargs, i, sourceOffset, BoolTest::lt, sourceEnd); {
1467        Node* i2  = __ AddI(__ value(i), targetCountLess1);
1468        // pin to prohibit loading of "next iteration" value which may SEGV (rare)
1469        Node* src = load_array_element(__ ctrl(), source, i2, TypeAryPtr::CHARS);
1470        __ if_then(src, BoolTest::eq, lastChar, unlikely); {
1471          __ loop(this, nargs, j, zero, BoolTest::lt, targetCountLess1); {
1472               Node* tpj = __ AddI(targetOffset, __ value(j));
1473               Node* targ = load_array_element(no_ctrl, target, tpj, target_type);
1474               Node* ipj  = __ AddI(__ value(i), __ value(j));
1475               Node* src2 = load_array_element(no_ctrl, source, ipj, TypeAryPtr::CHARS);
1476               __ if_then(targ, BoolTest::ne, src2); {
1477                 __ if_then(__ AndI(cache, __ LShiftI(one, src2)), BoolTest::eq, zero); {
1478                   __ if_then(md2, BoolTest::lt, __ AddI(__ value(j), one)); {
1479                     __ increment(i, __ AddI(__ value(j), one));
1480                     __ goto_(outer_loop);
1481                   } __ end_if(); __ dead(j);
1482                 }__ end_if(); __ dead(j);
1483                 __ increment(i, md2);
1484                 __ goto_(outer_loop);
1485               }__ end_if();
1486               __ increment(j, one);
1487          }__ end_loop(); __ dead(j);
1488          __ set(rtn, __ SubI(__ value(i), sourceOffset)); __ dead(i);
1489          __ goto_(return_);
1490        }__ end_if();
1491        __ if_then(__ AndI(cache, __ LShiftI(one, src)), BoolTest::eq, zero, likely); {
1492          __ increment(i, targetCountLess1);
1493        }__ end_if();
1494        __ increment(i, one);
1495        __ bind(outer_loop);
1496   }__ end_loop(); __ dead(i);
1497   __ bind(return_);
1498 
1499   // Final sync IdealKit and GraphKit.
1500   final_sync(kit);
1501   Node* result = __ value(rtn);
1502 #undef __
1503   C->set_has_loops(true);
1504   return result;
1505 }
1506 
1507 //------------------------------inline_string_indexOf------------------------
1508 bool LibraryCallKit::inline_string_indexOf() {
1509   Node* receiver = argument(0);
1510   Node* arg      = argument(1);
1511 
1512   Node* result;
1513   if (Matcher::has_match_rule(Op_StrIndexOf) &&
1514       UseSSE42Intrinsics) {
1515     // Generate SSE4.2 version of indexOf
1516     // We currently only have match rules that use SSE4.2
1517 
1518     receiver = null_check(receiver);
1519     arg      = null_check(arg);
1520     if (stopped()) {
1521       return true;
1522     }
1523 
1524     // Make the merge point
1525     RegionNode* result_rgn = new RegionNode(4);
1526     Node*       result_phi = new PhiNode(result_rgn, TypeInt::INT);
1527     Node* no_ctrl  = NULL;
1528 
1529     // Get start addr of source string
1530     Node* source = load_String_value(no_ctrl, receiver);
1531     Node* source_offset = load_String_offset(no_ctrl, receiver);
1532     Node* source_start = array_element_address(source, source_offset, T_CHAR);
1533 
1534     // Get length of source string
1535     Node* source_cnt  = load_String_length(no_ctrl, receiver);
1536 
1537     // Get start addr of substring
1538     Node* substr = load_String_value(no_ctrl, arg);
1539     Node* substr_offset = load_String_offset(no_ctrl, arg);
1540     Node* substr_start = array_element_address(substr, substr_offset, T_CHAR);
1541 
1542     // Get length of source string
1543     Node* substr_cnt  = load_String_length(no_ctrl, arg);
1544 
1545     // Check for substr count > string count
1546     Node* cmp = _gvn.transform(new CmpINode(substr_cnt, source_cnt));
1547     Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::gt));
1548     Node* if_gt = generate_slow_guard(bol, NULL);
1549     if (if_gt != NULL) {
1550       result_phi->init_req(2, intcon(-1));
1551       result_rgn->init_req(2, if_gt);
1552     }
1553 
1554     if (!stopped()) {
1555       // Check for substr count == 0
1556       cmp = _gvn.transform(new CmpINode(substr_cnt, intcon(0)));
1557       bol = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
1558       Node* if_zero = generate_slow_guard(bol, NULL);
1559       if (if_zero != NULL) {
1560         result_phi->init_req(3, intcon(0));
1561         result_rgn->init_req(3, if_zero);
1562       }
1563     }
1564 
1565     if (!stopped()) {
1566       result = make_string_method_node(Op_StrIndexOf, source_start, source_cnt, substr_start, substr_cnt);
1567       result_phi->init_req(1, result);
1568       result_rgn->init_req(1, control());
1569     }
1570     set_control(_gvn.transform(result_rgn));
1571     record_for_igvn(result_rgn);
1572     result = _gvn.transform(result_phi);
1573 
1574   } else { // Use LibraryCallKit::string_indexOf
1575     // don't intrinsify if argument isn't a constant string.
1576     if (!arg->is_Con()) {
1577      return false;
1578     }
1579     const TypeOopPtr* str_type = _gvn.type(arg)->isa_oopptr();
1580     if (str_type == NULL) {
1581       return false;
1582     }
1583     ciInstanceKlass* klass = env()->String_klass();
1584     ciObject* str_const = str_type->const_oop();
1585     if (str_const == NULL || str_const->klass() != klass) {
1586       return false;
1587     }
1588     ciInstance* str = str_const->as_instance();
1589     assert(str != NULL, "must be instance");
1590 
1591     ciObject* v = str->field_value_by_offset(java_lang_String::value_offset_in_bytes()).as_object();
1592     ciTypeArray* pat = v->as_type_array(); // pattern (argument) character array
1593 
1594     int o;
1595     int c;
1596     if (java_lang_String::has_offset_field()) {
1597       o = str->field_value_by_offset(java_lang_String::offset_offset_in_bytes()).as_int();
1598       c = str->field_value_by_offset(java_lang_String::count_offset_in_bytes()).as_int();
1599     } else {
1600       o = 0;
1601       c = pat->length();
1602     }
1603 
1604     // constant strings have no offset and count == length which
1605     // simplifies the resulting code somewhat so lets optimize for that.
1606     if (o != 0 || c != pat->length()) {
1607      return false;
1608     }
1609 
1610     receiver = null_check(receiver, T_OBJECT);
1611     // NOTE: No null check on the argument is needed since it's a constant String oop.
1612     if (stopped()) {
1613       return true;
1614     }
1615 
1616     // The null string as a pattern always returns 0 (match at beginning of string)
1617     if (c == 0) {
1618       set_result(intcon(0));
1619       return true;
1620     }
1621 
1622     // Generate default indexOf
1623     jchar lastChar = pat->char_at(o + (c - 1));
1624     int cache = 0;
1625     int i;
1626     for (i = 0; i < c - 1; i++) {
1627       assert(i < pat->length(), "out of range");
1628       cache |= (1 << (pat->char_at(o + i) & (sizeof(cache) * BitsPerByte - 1)));
1629     }
1630 
1631     int md2 = c;
1632     for (i = 0; i < c - 1; i++) {
1633       assert(i < pat->length(), "out of range");
1634       if (pat->char_at(o + i) == lastChar) {
1635         md2 = (c - 1) - i;
1636       }
1637     }
1638 
1639     result = string_indexOf(receiver, pat, o, cache, md2);
1640   }
1641   set_result(result);
1642   return true;
1643 }
1644 
1645 //--------------------------round_double_node--------------------------------
1646 // Round a double node if necessary.
1647 Node* LibraryCallKit::round_double_node(Node* n) {
1648   if (Matcher::strict_fp_requires_explicit_rounding && UseSSE <= 1)
1649     n = _gvn.transform(new RoundDoubleNode(0, n));
1650   return n;
1651 }
1652 
1653 //------------------------------inline_math-----------------------------------
1654 // public static double Math.abs(double)
1655 // public static double Math.sqrt(double)
1656 // public static double Math.log(double)
1657 // public static double Math.log10(double)
1658 bool LibraryCallKit::inline_math(vmIntrinsics::ID id) {
1659   Node* arg = round_double_node(argument(0));
1660   Node* n;
1661   switch (id) {
1662   case vmIntrinsics::_dabs:   n = new AbsDNode(                arg);  break;
1663   case vmIntrinsics::_dsqrt:  n = new SqrtDNode(C, control(),  arg);  break;
1664   case vmIntrinsics::_dlog:   n = new LogDNode(C, control(),   arg);  break;
1665   case vmIntrinsics::_dlog10: n = new Log10DNode(C, control(), arg);  break;
1666   default:  fatal_unexpected_iid(id);  break;
1667   }
1668   set_result(_gvn.transform(n));
1669   return true;
1670 }
1671 
1672 //------------------------------inline_trig----------------------------------
1673 // Inline sin/cos/tan instructions, if possible.  If rounding is required, do
1674 // argument reduction which will turn into a fast/slow diamond.
1675 bool LibraryCallKit::inline_trig(vmIntrinsics::ID id) {
1676   Node* arg = round_double_node(argument(0));
1677   Node* n = NULL;
1678 
1679   switch (id) {
1680   case vmIntrinsics::_dsin:  n = new SinDNode(C, control(), arg);  break;
1681   case vmIntrinsics::_dcos:  n = new CosDNode(C, control(), arg);  break;
1682   case vmIntrinsics::_dtan:  n = new TanDNode(C, control(), arg);  break;
1683   default:  fatal_unexpected_iid(id);  break;
1684   }
1685   n = _gvn.transform(n);
1686 
1687   // Rounding required?  Check for argument reduction!
1688   if (Matcher::strict_fp_requires_explicit_rounding) {
1689     static const double     pi_4 =  0.7853981633974483;
1690     static const double neg_pi_4 = -0.7853981633974483;
1691     // pi/2 in 80-bit extended precision
1692     // static const unsigned char pi_2_bits_x[] = {0x35,0xc2,0x68,0x21,0xa2,0xda,0x0f,0xc9,0xff,0x3f,0x00,0x00,0x00,0x00,0x00,0x00};
1693     // -pi/2 in 80-bit extended precision
1694     // 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};
1695     // Cutoff value for using this argument reduction technique
1696     //static const double    pi_2_minus_epsilon =  1.564660403643354;
1697     //static const double neg_pi_2_plus_epsilon = -1.564660403643354;
1698 
1699     // Pseudocode for sin:
1700     // if (x <= Math.PI / 4.0) {
1701     //   if (x >= -Math.PI / 4.0) return  fsin(x);
1702     //   if (x >= -Math.PI / 2.0) return -fcos(x + Math.PI / 2.0);
1703     // } else {
1704     //   if (x <=  Math.PI / 2.0) return  fcos(x - Math.PI / 2.0);
1705     // }
1706     // return StrictMath.sin(x);
1707 
1708     // Pseudocode for cos:
1709     // if (x <= Math.PI / 4.0) {
1710     //   if (x >= -Math.PI / 4.0) return  fcos(x);
1711     //   if (x >= -Math.PI / 2.0) return  fsin(x + Math.PI / 2.0);
1712     // } else {
1713     //   if (x <=  Math.PI / 2.0) return -fsin(x - Math.PI / 2.0);
1714     // }
1715     // return StrictMath.cos(x);
1716 
1717     // Actually, sticking in an 80-bit Intel value into C2 will be tough; it
1718     // requires a special machine instruction to load it.  Instead we'll try
1719     // the 'easy' case.  If we really need the extra range +/- PI/2 we'll
1720     // probably do the math inside the SIN encoding.
1721 
1722     // Make the merge point
1723     RegionNode* r = new RegionNode(3);
1724     Node* phi = new PhiNode(r, Type::DOUBLE);
1725 
1726     // Flatten arg so we need only 1 test
1727     Node *abs = _gvn.transform(new AbsDNode(arg));
1728     // Node for PI/4 constant
1729     Node *pi4 = makecon(TypeD::make(pi_4));
1730     // Check PI/4 : abs(arg)
1731     Node *cmp = _gvn.transform(new CmpDNode(pi4,abs));
1732     // Check: If PI/4 < abs(arg) then go slow
1733     Node *bol = _gvn.transform(new BoolNode( cmp, BoolTest::lt ));
1734     // Branch either way
1735     IfNode *iff = create_and_xform_if(control(),bol, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
1736     set_control(opt_iff(r,iff));
1737 
1738     // Set fast path result
1739     phi->init_req(2, n);
1740 
1741     // Slow path - non-blocking leaf call
1742     Node* call = NULL;
1743     switch (id) {
1744     case vmIntrinsics::_dsin:
1745       call = make_runtime_call(RC_LEAF, OptoRuntime::Math_D_D_Type(),
1746                                CAST_FROM_FN_PTR(address, SharedRuntime::dsin),
1747                                "Sin", NULL, arg, top());
1748       break;
1749     case vmIntrinsics::_dcos:
1750       call = make_runtime_call(RC_LEAF, OptoRuntime::Math_D_D_Type(),
1751                                CAST_FROM_FN_PTR(address, SharedRuntime::dcos),
1752                                "Cos", NULL, arg, top());
1753       break;
1754     case vmIntrinsics::_dtan:
1755       call = make_runtime_call(RC_LEAF, OptoRuntime::Math_D_D_Type(),
1756                                CAST_FROM_FN_PTR(address, SharedRuntime::dtan),
1757                                "Tan", NULL, arg, top());
1758       break;
1759     }
1760     assert(control()->in(0) == call, "");
1761     Node* slow_result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
1762     r->init_req(1, control());
1763     phi->init_req(1, slow_result);
1764 
1765     // Post-merge
1766     set_control(_gvn.transform(r));
1767     record_for_igvn(r);
1768     n = _gvn.transform(phi);
1769 
1770     C->set_has_split_ifs(true); // Has chance for split-if optimization
1771   }
1772   set_result(n);
1773   return true;
1774 }
1775 
1776 Node* LibraryCallKit::finish_pow_exp(Node* result, Node* x, Node* y, const TypeFunc* call_type, address funcAddr, const char* funcName) {
1777   //-------------------
1778   //result=(result.isNaN())? funcAddr():result;
1779   // Check: If isNaN() by checking result!=result? then either trap
1780   // or go to runtime
1781   Node* cmpisnan = _gvn.transform(new CmpDNode(result, result));
1782   // Build the boolean node
1783   Node* bolisnum = _gvn.transform(new BoolNode(cmpisnan, BoolTest::eq));
1784 
1785   if (!too_many_traps(Deoptimization::Reason_intrinsic)) {
1786     { BuildCutout unless(this, bolisnum, PROB_STATIC_FREQUENT);
1787       // The pow or exp intrinsic returned a NaN, which requires a call
1788       // to the runtime.  Recompile with the runtime call.
1789       uncommon_trap(Deoptimization::Reason_intrinsic,
1790                     Deoptimization::Action_make_not_entrant);
1791     }
1792     return result;
1793   } else {
1794     // If this inlining ever returned NaN in the past, we compile a call
1795     // to the runtime to properly handle corner cases
1796 
1797     IfNode* iff = create_and_xform_if(control(), bolisnum, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
1798     Node* if_slow = _gvn.transform(new IfFalseNode(iff));
1799     Node* if_fast = _gvn.transform(new IfTrueNode(iff));
1800 
1801     if (!if_slow->is_top()) {
1802       RegionNode* result_region = new RegionNode(3);
1803       PhiNode*    result_val = new PhiNode(result_region, Type::DOUBLE);
1804 
1805       result_region->init_req(1, if_fast);
1806       result_val->init_req(1, result);
1807 
1808       set_control(if_slow);
1809 
1810       const TypePtr* no_memory_effects = NULL;
1811       Node* rt = make_runtime_call(RC_LEAF, call_type, funcAddr, funcName,
1812                                    no_memory_effects,
1813                                    x, top(), y, y ? top() : NULL);
1814       Node* value = _gvn.transform(new ProjNode(rt, TypeFunc::Parms+0));
1815 #ifdef ASSERT
1816       Node* value_top = _gvn.transform(new ProjNode(rt, TypeFunc::Parms+1));
1817       assert(value_top == top(), "second value must be top");
1818 #endif
1819 
1820       result_region->init_req(2, control());
1821       result_val->init_req(2, value);
1822       set_control(_gvn.transform(result_region));
1823       return _gvn.transform(result_val);
1824     } else {
1825       return result;
1826     }
1827   }
1828 }
1829 
1830 //------------------------------inline_exp-------------------------------------
1831 // Inline exp instructions, if possible.  The Intel hardware only misses
1832 // really odd corner cases (+/- Infinity).  Just uncommon-trap them.
1833 bool LibraryCallKit::inline_exp() {
1834   Node* arg = round_double_node(argument(0));
1835   Node* n   = _gvn.transform(new ExpDNode(C, control(), arg));
1836 
1837   n = finish_pow_exp(n, arg, NULL, OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dexp), "EXP");
1838   set_result(n);
1839 
1840   C->set_has_split_ifs(true); // Has chance for split-if optimization
1841   return true;
1842 }
1843 
1844 //------------------------------inline_pow-------------------------------------
1845 // Inline power instructions, if possible.
1846 bool LibraryCallKit::inline_pow() {
1847   // Pseudocode for pow
1848   // if (y == 2) {
1849   //   return x * x;
1850   // } else {
1851   //   if (x <= 0.0) {
1852   //     long longy = (long)y;
1853   //     if ((double)longy == y) { // if y is long
1854   //       if (y + 1 == y) longy = 0; // huge number: even
1855   //       result = ((1&longy) == 0)?-DPow(abs(x), y):DPow(abs(x), y);
1856   //     } else {
1857   //       result = NaN;
1858   //     }
1859   //   } else {
1860   //     result = DPow(x,y);
1861   //   }
1862   //   if (result != result)?  {
1863   //     result = uncommon_trap() or runtime_call();
1864   //   }
1865   //   return result;
1866   // }
1867 
1868   Node* x = round_double_node(argument(0));
1869   Node* y = round_double_node(argument(2));
1870 
1871   Node* result = NULL;
1872 
1873   Node*   const_two_node = makecon(TypeD::make(2.0));
1874   Node*   cmp_node       = _gvn.transform(new CmpDNode(y, const_two_node));
1875   Node*   bool_node      = _gvn.transform(new BoolNode(cmp_node, BoolTest::eq));
1876   IfNode* if_node        = create_and_xform_if(control(), bool_node, PROB_STATIC_INFREQUENT, COUNT_UNKNOWN);
1877   Node*   if_true        = _gvn.transform(new IfTrueNode(if_node));
1878   Node*   if_false       = _gvn.transform(new IfFalseNode(if_node));
1879 
1880   RegionNode* region_node = new RegionNode(3);
1881   region_node->init_req(1, if_true);
1882 
1883   Node* phi_node = new PhiNode(region_node, Type::DOUBLE);
1884   // special case for x^y where y == 2, we can convert it to x * x
1885   phi_node->init_req(1, _gvn.transform(new MulDNode(x, x)));
1886 
1887   // set control to if_false since we will now process the false branch
1888   set_control(if_false);
1889 
1890   if (!too_many_traps(Deoptimization::Reason_intrinsic)) {
1891     // Short form: skip the fancy tests and just check for NaN result.
1892     result = _gvn.transform(new PowDNode(C, control(), x, y));
1893   } else {
1894     // If this inlining ever returned NaN in the past, include all
1895     // checks + call to the runtime.
1896 
1897     // Set the merge point for If node with condition of (x <= 0.0)
1898     // There are four possible paths to region node and phi node
1899     RegionNode *r = new RegionNode(4);
1900     Node *phi = new PhiNode(r, Type::DOUBLE);
1901 
1902     // Build the first if node: if (x <= 0.0)
1903     // Node for 0 constant
1904     Node *zeronode = makecon(TypeD::ZERO);
1905     // Check x:0
1906     Node *cmp = _gvn.transform(new CmpDNode(x, zeronode));
1907     // Check: If (x<=0) then go complex path
1908     Node *bol1 = _gvn.transform(new BoolNode( cmp, BoolTest::le ));
1909     // Branch either way
1910     IfNode *if1 = create_and_xform_if(control(),bol1, PROB_STATIC_INFREQUENT, COUNT_UNKNOWN);
1911     // Fast path taken; set region slot 3
1912     Node *fast_taken = _gvn.transform(new IfFalseNode(if1));
1913     r->init_req(3,fast_taken); // Capture fast-control
1914 
1915     // Fast path not-taken, i.e. slow path
1916     Node *complex_path = _gvn.transform(new IfTrueNode(if1));
1917 
1918     // Set fast path result
1919     Node *fast_result = _gvn.transform(new PowDNode(C, control(), x, y));
1920     phi->init_req(3, fast_result);
1921 
1922     // Complex path
1923     // Build the second if node (if y is long)
1924     // Node for (long)y
1925     Node *longy = _gvn.transform(new ConvD2LNode(y));
1926     // Node for (double)((long) y)
1927     Node *doublelongy= _gvn.transform(new ConvL2DNode(longy));
1928     // Check (double)((long) y) : y
1929     Node *cmplongy= _gvn.transform(new CmpDNode(doublelongy, y));
1930     // Check if (y isn't long) then go to slow path
1931 
1932     Node *bol2 = _gvn.transform(new BoolNode( cmplongy, BoolTest::ne ));
1933     // Branch either way
1934     IfNode *if2 = create_and_xform_if(complex_path,bol2, PROB_STATIC_INFREQUENT, COUNT_UNKNOWN);
1935     Node* ylong_path = _gvn.transform(new IfFalseNode(if2));
1936 
1937     Node *slow_path = _gvn.transform(new IfTrueNode(if2));
1938 
1939     // Calculate DPow(abs(x), y)*(1 & (long)y)
1940     // Node for constant 1
1941     Node *conone = longcon(1);
1942     // 1& (long)y
1943     Node *signnode= _gvn.transform(new AndLNode(conone, longy));
1944 
1945     // A huge number is always even. Detect a huge number by checking
1946     // if y + 1 == y and set integer to be tested for parity to 0.
1947     // Required for corner case:
1948     // (long)9.223372036854776E18 = max_jlong
1949     // (double)(long)9.223372036854776E18 = 9.223372036854776E18
1950     // max_jlong is odd but 9.223372036854776E18 is even
1951     Node* yplus1 = _gvn.transform(new AddDNode(y, makecon(TypeD::make(1))));
1952     Node *cmpyplus1= _gvn.transform(new CmpDNode(yplus1, y));
1953     Node *bolyplus1 = _gvn.transform(new BoolNode( cmpyplus1, BoolTest::eq ));
1954     Node* correctedsign = NULL;
1955     if (ConditionalMoveLimit != 0) {
1956       correctedsign = _gvn.transform(CMoveNode::make(NULL, bolyplus1, signnode, longcon(0), TypeLong::LONG));
1957     } else {
1958       IfNode *ifyplus1 = create_and_xform_if(ylong_path,bolyplus1, PROB_FAIR, COUNT_UNKNOWN);
1959       RegionNode *r = new RegionNode(3);
1960       Node *phi = new PhiNode(r, TypeLong::LONG);
1961       r->init_req(1, _gvn.transform(new IfFalseNode(ifyplus1)));
1962       r->init_req(2, _gvn.transform(new IfTrueNode(ifyplus1)));
1963       phi->init_req(1, signnode);
1964       phi->init_req(2, longcon(0));
1965       correctedsign = _gvn.transform(phi);
1966       ylong_path = _gvn.transform(r);
1967       record_for_igvn(r);
1968     }
1969 
1970     // zero node
1971     Node *conzero = longcon(0);
1972     // Check (1&(long)y)==0?
1973     Node *cmpeq1 = _gvn.transform(new CmpLNode(correctedsign, conzero));
1974     // Check if (1&(long)y)!=0?, if so the result is negative
1975     Node *bol3 = _gvn.transform(new BoolNode( cmpeq1, BoolTest::ne ));
1976     // abs(x)
1977     Node *absx=_gvn.transform(new AbsDNode(x));
1978     // abs(x)^y
1979     Node *absxpowy = _gvn.transform(new PowDNode(C, control(), absx, y));
1980     // -abs(x)^y
1981     Node *negabsxpowy = _gvn.transform(new NegDNode (absxpowy));
1982     // (1&(long)y)==1?-DPow(abs(x), y):DPow(abs(x), y)
1983     Node *signresult = NULL;
1984     if (ConditionalMoveLimit != 0) {
1985       signresult = _gvn.transform(CMoveNode::make(NULL, bol3, absxpowy, negabsxpowy, Type::DOUBLE));
1986     } else {
1987       IfNode *ifyeven = create_and_xform_if(ylong_path,bol3, PROB_FAIR, COUNT_UNKNOWN);
1988       RegionNode *r = new RegionNode(3);
1989       Node *phi = new PhiNode(r, Type::DOUBLE);
1990       r->init_req(1, _gvn.transform(new IfFalseNode(ifyeven)));
1991       r->init_req(2, _gvn.transform(new IfTrueNode(ifyeven)));
1992       phi->init_req(1, absxpowy);
1993       phi->init_req(2, negabsxpowy);
1994       signresult = _gvn.transform(phi);
1995       ylong_path = _gvn.transform(r);
1996       record_for_igvn(r);
1997     }
1998     // Set complex path fast result
1999     r->init_req(2, ylong_path);
2000     phi->init_req(2, signresult);
2001 
2002     static const jlong nan_bits = CONST64(0x7ff8000000000000);
2003     Node *slow_result = makecon(TypeD::make(*(double*)&nan_bits)); // return NaN
2004     r->init_req(1,slow_path);
2005     phi->init_req(1,slow_result);
2006 
2007     // Post merge
2008     set_control(_gvn.transform(r));
2009     record_for_igvn(r);
2010     result = _gvn.transform(phi);
2011   }
2012 
2013   result = finish_pow_exp(result, x, y, OptoRuntime::Math_DD_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dpow), "POW");
2014 
2015   // control from finish_pow_exp is now input to the region node
2016   region_node->set_req(2, control());
2017   // the result from finish_pow_exp is now input to the phi node
2018   phi_node->init_req(2, result);
2019   set_control(_gvn.transform(region_node));
2020   record_for_igvn(region_node);
2021   set_result(_gvn.transform(phi_node));
2022 
2023   C->set_has_split_ifs(true); // Has chance for split-if optimization
2024   return true;
2025 }
2026 
2027 //------------------------------runtime_math-----------------------------
2028 bool LibraryCallKit::runtime_math(const TypeFunc* call_type, address funcAddr, const char* funcName) {
2029   assert(call_type == OptoRuntime::Math_DD_D_Type() || call_type == OptoRuntime::Math_D_D_Type(),
2030          "must be (DD)D or (D)D type");
2031 
2032   // Inputs
2033   Node* a = round_double_node(argument(0));
2034   Node* b = (call_type == OptoRuntime::Math_DD_D_Type()) ? round_double_node(argument(2)) : NULL;
2035 
2036   const TypePtr* no_memory_effects = NULL;
2037   Node* trig = make_runtime_call(RC_LEAF, call_type, funcAddr, funcName,
2038                                  no_memory_effects,
2039                                  a, top(), b, b ? top() : NULL);
2040   Node* value = _gvn.transform(new ProjNode(trig, TypeFunc::Parms+0));
2041 #ifdef ASSERT
2042   Node* value_top = _gvn.transform(new ProjNode(trig, TypeFunc::Parms+1));
2043   assert(value_top == top(), "second value must be top");
2044 #endif
2045 
2046   set_result(value);
2047   return true;
2048 }
2049 
2050 //------------------------------inline_math_native-----------------------------
2051 bool LibraryCallKit::inline_math_native(vmIntrinsics::ID id) {
2052 #define FN_PTR(f) CAST_FROM_FN_PTR(address, f)
2053   switch (id) {
2054     // These intrinsics are not properly supported on all hardware
2055   case vmIntrinsics::_dcos:   return Matcher::has_match_rule(Op_CosD)   ? inline_trig(id) :
2056     runtime_math(OptoRuntime::Math_D_D_Type(), FN_PTR(SharedRuntime::dcos),   "COS");
2057   case vmIntrinsics::_dsin:   return Matcher::has_match_rule(Op_SinD)   ? inline_trig(id) :
2058     runtime_math(OptoRuntime::Math_D_D_Type(), FN_PTR(SharedRuntime::dsin),   "SIN");
2059   case vmIntrinsics::_dtan:   return Matcher::has_match_rule(Op_TanD)   ? inline_trig(id) :
2060     runtime_math(OptoRuntime::Math_D_D_Type(), FN_PTR(SharedRuntime::dtan),   "TAN");
2061 
2062   case vmIntrinsics::_dlog:   return Matcher::has_match_rule(Op_LogD)   ? inline_math(id) :
2063     runtime_math(OptoRuntime::Math_D_D_Type(), FN_PTR(SharedRuntime::dlog),   "LOG");
2064   case vmIntrinsics::_dlog10: return Matcher::has_match_rule(Op_Log10D) ? inline_math(id) :
2065     runtime_math(OptoRuntime::Math_D_D_Type(), FN_PTR(SharedRuntime::dlog10), "LOG10");
2066 
2067     // These intrinsics are supported on all hardware
2068   case vmIntrinsics::_dsqrt:  return Matcher::match_rule_supported(Op_SqrtD) ? inline_math(id) : false;
2069   case vmIntrinsics::_dabs:   return Matcher::has_match_rule(Op_AbsD)   ? inline_math(id) : false;
2070 
2071   case vmIntrinsics::_dexp:   return Matcher::has_match_rule(Op_ExpD)   ? inline_exp()    :
2072     runtime_math(OptoRuntime::Math_D_D_Type(),  FN_PTR(SharedRuntime::dexp),  "EXP");
2073   case vmIntrinsics::_dpow:   return Matcher::has_match_rule(Op_PowD)   ? inline_pow()    :
2074     runtime_math(OptoRuntime::Math_DD_D_Type(), FN_PTR(SharedRuntime::dpow),  "POW");
2075 #undef FN_PTR
2076 
2077    // These intrinsics are not yet correctly implemented
2078   case vmIntrinsics::_datan2:
2079     return false;
2080 
2081   default:
2082     fatal_unexpected_iid(id);
2083     return false;
2084   }
2085 }
2086 
2087 static bool is_simple_name(Node* n) {
2088   return (n->req() == 1         // constant
2089           || (n->is_Type() && n->as_Type()->type()->singleton())
2090           || n->is_Proj()       // parameter or return value
2091           || n->is_Phi()        // local of some sort
2092           );
2093 }
2094 
2095 //----------------------------inline_min_max-----------------------------------
2096 bool LibraryCallKit::inline_min_max(vmIntrinsics::ID id) {
2097   set_result(generate_min_max(id, argument(0), argument(1)));
2098   return true;
2099 }
2100 
2101 void LibraryCallKit::inline_math_mathExact(Node* math, Node *test) {
2102   Node* bol = _gvn.transform( new BoolNode(test, BoolTest::overflow) );
2103   IfNode* check = create_and_map_if(control(), bol, PROB_UNLIKELY_MAG(3), COUNT_UNKNOWN);
2104   Node* fast_path = _gvn.transform( new IfFalseNode(check));
2105   Node* slow_path = _gvn.transform( new IfTrueNode(check) );
2106 
2107   {
2108     PreserveJVMState pjvms(this);
2109     PreserveReexecuteState preexecs(this);
2110     jvms()->set_should_reexecute(true);
2111 
2112     set_control(slow_path);
2113     set_i_o(i_o());
2114 
2115     uncommon_trap(Deoptimization::Reason_intrinsic,
2116                   Deoptimization::Action_none);
2117   }
2118 
2119   set_control(fast_path);
2120   set_result(math);
2121 }
2122 
2123 template <typename OverflowOp>
2124 bool LibraryCallKit::inline_math_overflow(Node* arg1, Node* arg2) {
2125   typedef typename OverflowOp::MathOp MathOp;
2126 
2127   MathOp* mathOp = new MathOp(arg1, arg2);
2128   Node* operation = _gvn.transform( mathOp );
2129   Node* ofcheck = _gvn.transform( new OverflowOp(arg1, arg2) );
2130   inline_math_mathExact(operation, ofcheck);
2131   return true;
2132 }
2133 
2134 bool LibraryCallKit::inline_math_addExactI(bool is_increment) {
2135   return inline_math_overflow<OverflowAddINode>(argument(0), is_increment ? intcon(1) : argument(1));
2136 }
2137 
2138 bool LibraryCallKit::inline_math_addExactL(bool is_increment) {
2139   return inline_math_overflow<OverflowAddLNode>(argument(0), is_increment ? longcon(1) : argument(2));
2140 }
2141 
2142 bool LibraryCallKit::inline_math_subtractExactI(bool is_decrement) {
2143   return inline_math_overflow<OverflowSubINode>(argument(0), is_decrement ? intcon(1) : argument(1));
2144 }
2145 
2146 bool LibraryCallKit::inline_math_subtractExactL(bool is_decrement) {
2147   return inline_math_overflow<OverflowSubLNode>(argument(0), is_decrement ? longcon(1) : argument(2));
2148 }
2149 
2150 bool LibraryCallKit::inline_math_negateExactI() {
2151   return inline_math_overflow<OverflowSubINode>(intcon(0), argument(0));
2152 }
2153 
2154 bool LibraryCallKit::inline_math_negateExactL() {
2155   return inline_math_overflow<OverflowSubLNode>(longcon(0), argument(0));
2156 }
2157 
2158 bool LibraryCallKit::inline_math_multiplyExactI() {
2159   return inline_math_overflow<OverflowMulINode>(argument(0), argument(1));
2160 }
2161 
2162 bool LibraryCallKit::inline_math_multiplyExactL() {
2163   return inline_math_overflow<OverflowMulLNode>(argument(0), argument(2));
2164 }
2165 
2166 Node*
2167 LibraryCallKit::generate_min_max(vmIntrinsics::ID id, Node* x0, Node* y0) {
2168   // These are the candidate return value:
2169   Node* xvalue = x0;
2170   Node* yvalue = y0;
2171 
2172   if (xvalue == yvalue) {
2173     return xvalue;
2174   }
2175 
2176   bool want_max = (id == vmIntrinsics::_max);
2177 
2178   const TypeInt* txvalue = _gvn.type(xvalue)->isa_int();
2179   const TypeInt* tyvalue = _gvn.type(yvalue)->isa_int();
2180   if (txvalue == NULL || tyvalue == NULL)  return top();
2181   // This is not really necessary, but it is consistent with a
2182   // hypothetical MaxINode::Value method:
2183   int widen = MAX2(txvalue->_widen, tyvalue->_widen);
2184 
2185   // %%% This folding logic should (ideally) be in a different place.
2186   // Some should be inside IfNode, and there to be a more reliable
2187   // transformation of ?: style patterns into cmoves.  We also want
2188   // more powerful optimizations around cmove and min/max.
2189 
2190   // Try to find a dominating comparison of these guys.
2191   // It can simplify the index computation for Arrays.copyOf
2192   // and similar uses of System.arraycopy.
2193   // First, compute the normalized version of CmpI(x, y).
2194   int   cmp_op = Op_CmpI;
2195   Node* xkey = xvalue;
2196   Node* ykey = yvalue;
2197   Node* ideal_cmpxy = _gvn.transform(new CmpINode(xkey, ykey));
2198   if (ideal_cmpxy->is_Cmp()) {
2199     // E.g., if we have CmpI(length - offset, count),
2200     // it might idealize to CmpI(length, count + offset)
2201     cmp_op = ideal_cmpxy->Opcode();
2202     xkey = ideal_cmpxy->in(1);
2203     ykey = ideal_cmpxy->in(2);
2204   }
2205 
2206   // Start by locating any relevant comparisons.
2207   Node* start_from = (xkey->outcnt() < ykey->outcnt()) ? xkey : ykey;
2208   Node* cmpxy = NULL;
2209   Node* cmpyx = NULL;
2210   for (DUIterator_Fast kmax, k = start_from->fast_outs(kmax); k < kmax; k++) {
2211     Node* cmp = start_from->fast_out(k);
2212     if (cmp->outcnt() > 0 &&            // must have prior uses
2213         cmp->in(0) == NULL &&           // must be context-independent
2214         cmp->Opcode() == cmp_op) {      // right kind of compare
2215       if (cmp->in(1) == xkey && cmp->in(2) == ykey)  cmpxy = cmp;
2216       if (cmp->in(1) == ykey && cmp->in(2) == xkey)  cmpyx = cmp;
2217     }
2218   }
2219 
2220   const int NCMPS = 2;
2221   Node* cmps[NCMPS] = { cmpxy, cmpyx };
2222   int cmpn;
2223   for (cmpn = 0; cmpn < NCMPS; cmpn++) {
2224     if (cmps[cmpn] != NULL)  break;     // find a result
2225   }
2226   if (cmpn < NCMPS) {
2227     // Look for a dominating test that tells us the min and max.
2228     int depth = 0;                // Limit search depth for speed
2229     Node* dom = control();
2230     for (; dom != NULL; dom = IfNode::up_one_dom(dom, true)) {
2231       if (++depth >= 100)  break;
2232       Node* ifproj = dom;
2233       if (!ifproj->is_Proj())  continue;
2234       Node* iff = ifproj->in(0);
2235       if (!iff->is_If())  continue;
2236       Node* bol = iff->in(1);
2237       if (!bol->is_Bool())  continue;
2238       Node* cmp = bol->in(1);
2239       if (cmp == NULL)  continue;
2240       for (cmpn = 0; cmpn < NCMPS; cmpn++)
2241         if (cmps[cmpn] == cmp)  break;
2242       if (cmpn == NCMPS)  continue;
2243       BoolTest::mask btest = bol->as_Bool()->_test._test;
2244       if (ifproj->is_IfFalse())  btest = BoolTest(btest).negate();
2245       if (cmp->in(1) == ykey)    btest = BoolTest(btest).commute();
2246       // At this point, we know that 'x btest y' is true.
2247       switch (btest) {
2248       case BoolTest::eq:
2249         // They are proven equal, so we can collapse the min/max.
2250         // Either value is the answer.  Choose the simpler.
2251         if (is_simple_name(yvalue) && !is_simple_name(xvalue))
2252           return yvalue;
2253         return xvalue;
2254       case BoolTest::lt:          // x < y
2255       case BoolTest::le:          // x <= y
2256         return (want_max ? yvalue : xvalue);
2257       case BoolTest::gt:          // x > y
2258       case BoolTest::ge:          // x >= y
2259         return (want_max ? xvalue : yvalue);
2260       }
2261     }
2262   }
2263 
2264   // We failed to find a dominating test.
2265   // Let's pick a test that might GVN with prior tests.
2266   Node*          best_bol   = NULL;
2267   BoolTest::mask best_btest = BoolTest::illegal;
2268   for (cmpn = 0; cmpn < NCMPS; cmpn++) {
2269     Node* cmp = cmps[cmpn];
2270     if (cmp == NULL)  continue;
2271     for (DUIterator_Fast jmax, j = cmp->fast_outs(jmax); j < jmax; j++) {
2272       Node* bol = cmp->fast_out(j);
2273       if (!bol->is_Bool())  continue;
2274       BoolTest::mask btest = bol->as_Bool()->_test._test;
2275       if (btest == BoolTest::eq || btest == BoolTest::ne)  continue;
2276       if (cmp->in(1) == ykey)   btest = BoolTest(btest).commute();
2277       if (bol->outcnt() > (best_bol == NULL ? 0 : best_bol->outcnt())) {
2278         best_bol   = bol->as_Bool();
2279         best_btest = btest;
2280       }
2281     }
2282   }
2283 
2284   Node* answer_if_true  = NULL;
2285   Node* answer_if_false = NULL;
2286   switch (best_btest) {
2287   default:
2288     if (cmpxy == NULL)
2289       cmpxy = ideal_cmpxy;
2290     best_bol = _gvn.transform(new BoolNode(cmpxy, BoolTest::lt));
2291     // and fall through:
2292   case BoolTest::lt:          // x < y
2293   case BoolTest::le:          // x <= y
2294     answer_if_true  = (want_max ? yvalue : xvalue);
2295     answer_if_false = (want_max ? xvalue : yvalue);
2296     break;
2297   case BoolTest::gt:          // x > y
2298   case BoolTest::ge:          // x >= y
2299     answer_if_true  = (want_max ? xvalue : yvalue);
2300     answer_if_false = (want_max ? yvalue : xvalue);
2301     break;
2302   }
2303 
2304   jint hi, lo;
2305   if (want_max) {
2306     // We can sharpen the minimum.
2307     hi = MAX2(txvalue->_hi, tyvalue->_hi);
2308     lo = MAX2(txvalue->_lo, tyvalue->_lo);
2309   } else {
2310     // We can sharpen the maximum.
2311     hi = MIN2(txvalue->_hi, tyvalue->_hi);
2312     lo = MIN2(txvalue->_lo, tyvalue->_lo);
2313   }
2314 
2315   // Use a flow-free graph structure, to avoid creating excess control edges
2316   // which could hinder other optimizations.
2317   // Since Math.min/max is often used with arraycopy, we want
2318   // tightly_coupled_allocation to be able to see beyond min/max expressions.
2319   Node* cmov = CMoveNode::make(NULL, best_bol,
2320                                answer_if_false, answer_if_true,
2321                                TypeInt::make(lo, hi, widen));
2322 
2323   return _gvn.transform(cmov);
2324 
2325   /*
2326   // This is not as desirable as it may seem, since Min and Max
2327   // nodes do not have a full set of optimizations.
2328   // And they would interfere, anyway, with 'if' optimizations
2329   // and with CMoveI canonical forms.
2330   switch (id) {
2331   case vmIntrinsics::_min:
2332     result_val = _gvn.transform(new (C, 3) MinINode(x,y)); break;
2333   case vmIntrinsics::_max:
2334     result_val = _gvn.transform(new (C, 3) MaxINode(x,y)); break;
2335   default:
2336     ShouldNotReachHere();
2337   }
2338   */
2339 }
2340 
2341 inline int
2342 LibraryCallKit::classify_unsafe_addr(Node* &base, Node* &offset) {
2343   const TypePtr* base_type = TypePtr::NULL_PTR;
2344   if (base != NULL)  base_type = _gvn.type(base)->isa_ptr();
2345   if (base_type == NULL) {
2346     // Unknown type.
2347     return Type::AnyPtr;
2348   } else if (base_type == TypePtr::NULL_PTR) {
2349     // Since this is a NULL+long form, we have to switch to a rawptr.
2350     base   = _gvn.transform(new CastX2PNode(offset));
2351     offset = MakeConX(0);
2352     return Type::RawPtr;
2353   } else if (base_type->base() == Type::RawPtr) {
2354     return Type::RawPtr;
2355   } else if (base_type->isa_oopptr()) {
2356     // Base is never null => always a heap address.
2357     if (base_type->ptr() == TypePtr::NotNull) {
2358       return Type::OopPtr;
2359     }
2360     // Offset is small => always a heap address.
2361     const TypeX* offset_type = _gvn.type(offset)->isa_intptr_t();
2362     if (offset_type != NULL &&
2363         base_type->offset() == 0 &&     // (should always be?)
2364         offset_type->_lo >= 0 &&
2365         !MacroAssembler::needs_explicit_null_check(offset_type->_hi)) {
2366       return Type::OopPtr;
2367     }
2368     // Otherwise, it might either be oop+off or NULL+addr.
2369     return Type::AnyPtr;
2370   } else {
2371     // No information:
2372     return Type::AnyPtr;
2373   }
2374 }
2375 
2376 inline Node* LibraryCallKit::make_unsafe_address(Node* base, Node* offset) {
2377   int kind = classify_unsafe_addr(base, offset);
2378   if (kind == Type::RawPtr) {
2379     return basic_plus_adr(top(), base, offset);
2380   } else {
2381     return basic_plus_adr(base, offset);
2382   }
2383 }
2384 
2385 //--------------------------inline_number_methods-----------------------------
2386 // inline int     Integer.numberOfLeadingZeros(int)
2387 // inline int        Long.numberOfLeadingZeros(long)
2388 //
2389 // inline int     Integer.numberOfTrailingZeros(int)
2390 // inline int        Long.numberOfTrailingZeros(long)
2391 //
2392 // inline int     Integer.bitCount(int)
2393 // inline int        Long.bitCount(long)
2394 //
2395 // inline char  Character.reverseBytes(char)
2396 // inline short     Short.reverseBytes(short)
2397 // inline int     Integer.reverseBytes(int)
2398 // inline long       Long.reverseBytes(long)
2399 bool LibraryCallKit::inline_number_methods(vmIntrinsics::ID id) {
2400   Node* arg = argument(0);
2401   Node* n;
2402   switch (id) {
2403   case vmIntrinsics::_numberOfLeadingZeros_i:   n = new CountLeadingZerosINode( arg);  break;
2404   case vmIntrinsics::_numberOfLeadingZeros_l:   n = new CountLeadingZerosLNode( arg);  break;
2405   case vmIntrinsics::_numberOfTrailingZeros_i:  n = new CountTrailingZerosINode(arg);  break;
2406   case vmIntrinsics::_numberOfTrailingZeros_l:  n = new CountTrailingZerosLNode(arg);  break;
2407   case vmIntrinsics::_bitCount_i:               n = new PopCountINode(          arg);  break;
2408   case vmIntrinsics::_bitCount_l:               n = new PopCountLNode(          arg);  break;
2409   case vmIntrinsics::_reverseBytes_c:           n = new ReverseBytesUSNode(0,   arg);  break;
2410   case vmIntrinsics::_reverseBytes_s:           n = new ReverseBytesSNode( 0,   arg);  break;
2411   case vmIntrinsics::_reverseBytes_i:           n = new ReverseBytesINode( 0,   arg);  break;
2412   case vmIntrinsics::_reverseBytes_l:           n = new ReverseBytesLNode( 0,   arg);  break;
2413   default:  fatal_unexpected_iid(id);  break;
2414   }
2415   set_result(_gvn.transform(n));
2416   return true;
2417 }
2418 
2419 //----------------------------inline_unsafe_access----------------------------
2420 
2421 const static BasicType T_ADDRESS_HOLDER = T_LONG;
2422 
2423 // Helper that guards and inserts a pre-barrier.
2424 void LibraryCallKit::insert_pre_barrier(Node* base_oop, Node* offset,
2425                                         Node* pre_val, bool need_mem_bar) {
2426   // We could be accessing the referent field of a reference object. If so, when G1
2427   // is enabled, we need to log the value in the referent field in an SATB buffer.
2428   // This routine performs some compile time filters and generates suitable
2429   // runtime filters that guard the pre-barrier code.
2430   // Also add memory barrier for non volatile load from the referent field
2431   // to prevent commoning of loads across safepoint.
2432   if (!UseG1GC && !need_mem_bar)
2433     return;
2434 
2435   // Some compile time checks.
2436 
2437   // If offset is a constant, is it java_lang_ref_Reference::_reference_offset?
2438   const TypeX* otype = offset->find_intptr_t_type();
2439   if (otype != NULL && otype->is_con() &&
2440       otype->get_con() != java_lang_ref_Reference::referent_offset) {
2441     // Constant offset but not the reference_offset so just return
2442     return;
2443   }
2444 
2445   // We only need to generate the runtime guards for instances.
2446   const TypeOopPtr* btype = base_oop->bottom_type()->isa_oopptr();
2447   if (btype != NULL) {
2448     if (btype->isa_aryptr()) {
2449       // Array type so nothing to do
2450       return;
2451     }
2452 
2453     const TypeInstPtr* itype = btype->isa_instptr();
2454     if (itype != NULL) {
2455       // Can the klass of base_oop be statically determined to be
2456       // _not_ a sub-class of Reference and _not_ Object?
2457       ciKlass* klass = itype->klass();
2458       if ( klass->is_loaded() &&
2459           !klass->is_subtype_of(env()->Reference_klass()) &&
2460           !env()->Object_klass()->is_subtype_of(klass)) {
2461         return;
2462       }
2463     }
2464   }
2465 
2466   // The compile time filters did not reject base_oop/offset so
2467   // we need to generate the following runtime filters
2468   //
2469   // if (offset == java_lang_ref_Reference::_reference_offset) {
2470   //   if (instance_of(base, java.lang.ref.Reference)) {
2471   //     pre_barrier(_, pre_val, ...);
2472   //   }
2473   // }
2474 
2475   float likely   = PROB_LIKELY(  0.999);
2476   float unlikely = PROB_UNLIKELY(0.999);
2477 
2478   IdealKit ideal(this);
2479 #define __ ideal.
2480 
2481   Node* referent_off = __ ConX(java_lang_ref_Reference::referent_offset);
2482 
2483   __ if_then(offset, BoolTest::eq, referent_off, unlikely); {
2484       // Update graphKit memory and control from IdealKit.
2485       sync_kit(ideal);
2486 
2487       Node* ref_klass_con = makecon(TypeKlassPtr::make(env()->Reference_klass()));
2488       Node* is_instof = gen_instanceof(base_oop, ref_klass_con);
2489 
2490       // Update IdealKit memory and control from graphKit.
2491       __ sync_kit(this);
2492 
2493       Node* one = __ ConI(1);
2494       // is_instof == 0 if base_oop == NULL
2495       __ if_then(is_instof, BoolTest::eq, one, unlikely); {
2496 
2497         // Update graphKit from IdeakKit.
2498         sync_kit(ideal);
2499 
2500         // Use the pre-barrier to record the value in the referent field
2501         pre_barrier(false /* do_load */,
2502                     __ ctrl(),
2503                     NULL /* obj */, NULL /* adr */, max_juint /* alias_idx */, NULL /* val */, NULL /* val_type */,
2504                     pre_val /* pre_val */,
2505                     T_OBJECT);
2506         if (need_mem_bar) {
2507           // Add memory barrier to prevent commoning reads from this field
2508           // across safepoint since GC can change its value.
2509           insert_mem_bar(Op_MemBarCPUOrder);
2510         }
2511         // Update IdealKit from graphKit.
2512         __ sync_kit(this);
2513 
2514       } __ end_if(); // _ref_type != ref_none
2515   } __ end_if(); // offset == referent_offset
2516 
2517   // Final sync IdealKit and GraphKit.
2518   final_sync(ideal);
2519 #undef __
2520 }
2521 
2522 
2523 // Interpret Unsafe.fieldOffset cookies correctly:
2524 extern jlong Unsafe_field_offset_to_byte_offset(jlong field_offset);
2525 
2526 const TypeOopPtr* LibraryCallKit::sharpen_unsafe_type(Compile::AliasType* alias_type, const TypePtr *adr_type, bool is_native_ptr) {
2527   // Attempt to infer a sharper value type from the offset and base type.
2528   ciKlass* sharpened_klass = NULL;
2529 
2530   // See if it is an instance field, with an object type.
2531   if (alias_type->field() != NULL) {
2532     assert(!is_native_ptr, "native pointer op cannot use a java address");
2533     if (alias_type->field()->type()->is_klass()) {
2534       sharpened_klass = alias_type->field()->type()->as_klass();
2535     }
2536   }
2537 
2538   // See if it is a narrow oop array.
2539   if (adr_type->isa_aryptr()) {
2540     if (adr_type->offset() >= objArrayOopDesc::base_offset_in_bytes()) {
2541       const TypeOopPtr *elem_type = adr_type->is_aryptr()->elem()->isa_oopptr();
2542       if (elem_type != NULL) {
2543         sharpened_klass = elem_type->klass();
2544       }
2545     }
2546   }
2547 
2548   // The sharpened class might be unloaded if there is no class loader
2549   // contraint in place.
2550   if (sharpened_klass != NULL && sharpened_klass->is_loaded()) {
2551     const TypeOopPtr* tjp = TypeOopPtr::make_from_klass(sharpened_klass);
2552 
2553 #ifndef PRODUCT
2554     if (C->print_intrinsics() || C->print_inlining()) {
2555       tty->print("  from base type: ");  adr_type->dump();
2556       tty->print("  sharpened value: ");  tjp->dump();
2557     }
2558 #endif
2559     // Sharpen the value type.
2560     return tjp;
2561   }
2562   return NULL;
2563 }
2564 
2565 bool LibraryCallKit::inline_unsafe_access(bool is_native_ptr, bool is_store, BasicType type, bool is_volatile) {
2566   if (callee()->is_static())  return false;  // caller must have the capability!
2567 
2568 #ifndef PRODUCT
2569   {
2570     ResourceMark rm;
2571     // Check the signatures.
2572     ciSignature* sig = callee()->signature();
2573 #ifdef ASSERT
2574     if (!is_store) {
2575       // Object getObject(Object base, int/long offset), etc.
2576       BasicType rtype = sig->return_type()->basic_type();
2577       if (rtype == T_ADDRESS_HOLDER && callee()->name() == ciSymbol::getAddress_name())
2578           rtype = T_ADDRESS;  // it is really a C void*
2579       assert(rtype == type, "getter must return the expected value");
2580       if (!is_native_ptr) {
2581         assert(sig->count() == 2, "oop getter has 2 arguments");
2582         assert(sig->type_at(0)->basic_type() == T_OBJECT, "getter base is object");
2583         assert(sig->type_at(1)->basic_type() == T_LONG, "getter offset is correct");
2584       } else {
2585         assert(sig->count() == 1, "native getter has 1 argument");
2586         assert(sig->type_at(0)->basic_type() == T_LONG, "getter base is long");
2587       }
2588     } else {
2589       // void putObject(Object base, int/long offset, Object x), etc.
2590       assert(sig->return_type()->basic_type() == T_VOID, "putter must not return a value");
2591       if (!is_native_ptr) {
2592         assert(sig->count() == 3, "oop putter has 3 arguments");
2593         assert(sig->type_at(0)->basic_type() == T_OBJECT, "putter base is object");
2594         assert(sig->type_at(1)->basic_type() == T_LONG, "putter offset is correct");
2595       } else {
2596         assert(sig->count() == 2, "native putter has 2 arguments");
2597         assert(sig->type_at(0)->basic_type() == T_LONG, "putter base is long");
2598       }
2599       BasicType vtype = sig->type_at(sig->count()-1)->basic_type();
2600       if (vtype == T_ADDRESS_HOLDER && callee()->name() == ciSymbol::putAddress_name())
2601         vtype = T_ADDRESS;  // it is really a C void*
2602       assert(vtype == type, "putter must accept the expected value");
2603     }
2604 #endif // ASSERT
2605  }
2606 #endif //PRODUCT
2607 
2608   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
2609 
2610   Node* receiver = argument(0);  // type: oop
2611 
2612   // Build address expression.
2613   Node* adr;
2614   Node* heap_base_oop = top();
2615   Node* offset = top();
2616   Node* val;
2617 
2618   if (!is_native_ptr) {
2619     // The base is either a Java object or a value produced by Unsafe.staticFieldBase
2620     Node* base = argument(1);  // type: oop
2621     // The offset is a value produced by Unsafe.staticFieldOffset or Unsafe.objectFieldOffset
2622     offset = argument(2);  // type: long
2623     // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
2624     // to be plain byte offsets, which are also the same as those accepted
2625     // by oopDesc::field_base.
2626     assert(Unsafe_field_offset_to_byte_offset(11) == 11,
2627            "fieldOffset must be byte-scaled");
2628     // 32-bit machines ignore the high half!
2629     offset = ConvL2X(offset);
2630     adr = make_unsafe_address(base, offset);
2631     heap_base_oop = base;
2632     val = is_store ? argument(4) : NULL;
2633   } else {
2634     Node* ptr = argument(1);  // type: long
2635     ptr = ConvL2X(ptr);  // adjust Java long to machine word
2636     adr = make_unsafe_address(NULL, ptr);
2637     val = is_store ? argument(3) : NULL;
2638   }
2639 
2640   const TypePtr *adr_type = _gvn.type(adr)->isa_ptr();
2641 
2642   // First guess at the value type.
2643   const Type *value_type = Type::get_const_basic_type(type);
2644 
2645   // Try to categorize the address.  If it comes up as TypeJavaPtr::BOTTOM,
2646   // there was not enough information to nail it down.
2647   Compile::AliasType* alias_type = C->alias_type(adr_type);
2648   assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
2649 
2650   // We will need memory barriers unless we can determine a unique
2651   // alias category for this reference.  (Note:  If for some reason
2652   // the barriers get omitted and the unsafe reference begins to "pollute"
2653   // the alias analysis of the rest of the graph, either Compile::can_alias
2654   // or Compile::must_alias will throw a diagnostic assert.)
2655   bool need_mem_bar = (alias_type->adr_type() == TypeOopPtr::BOTTOM);
2656 
2657   // If we are reading the value of the referent field of a Reference
2658   // object (either by using Unsafe directly or through reflection)
2659   // then, if G1 is enabled, we need to record the referent in an
2660   // SATB log buffer using the pre-barrier mechanism.
2661   // Also we need to add memory barrier to prevent commoning reads
2662   // from this field across safepoint since GC can change its value.
2663   bool need_read_barrier = !is_native_ptr && !is_store &&
2664                            offset != top() && heap_base_oop != top();
2665 
2666   if (!is_store && type == T_OBJECT) {
2667     const TypeOopPtr* tjp = sharpen_unsafe_type(alias_type, adr_type, is_native_ptr);
2668     if (tjp != NULL) {
2669       value_type = tjp;
2670     }
2671   }
2672 
2673   receiver = null_check(receiver);
2674   if (stopped()) {
2675     return true;
2676   }
2677   // Heap pointers get a null-check from the interpreter,
2678   // as a courtesy.  However, this is not guaranteed by Unsafe,
2679   // and it is not possible to fully distinguish unintended nulls
2680   // from intended ones in this API.
2681 
2682   if (is_volatile) {
2683     // We need to emit leading and trailing CPU membars (see below) in
2684     // addition to memory membars when is_volatile. This is a little
2685     // too strong, but avoids the need to insert per-alias-type
2686     // volatile membars (for stores; compare Parse::do_put_xxx), which
2687     // we cannot do effectively here because we probably only have a
2688     // rough approximation of type.
2689     need_mem_bar = true;
2690     // For Stores, place a memory ordering barrier now.
2691     if (is_store) {
2692       insert_mem_bar(Op_MemBarRelease);
2693     } else {
2694       if (support_IRIW_for_not_multiple_copy_atomic_cpu) {
2695         insert_mem_bar(Op_MemBarVolatile);
2696       }
2697     }
2698   }
2699 
2700   // Memory barrier to prevent normal and 'unsafe' accesses from
2701   // bypassing each other.  Happens after null checks, so the
2702   // exception paths do not take memory state from the memory barrier,
2703   // so there's no problems making a strong assert about mixing users
2704   // of safe & unsafe memory.
2705   if (need_mem_bar) insert_mem_bar(Op_MemBarCPUOrder);
2706 
2707    if (!is_store) {
2708     Node* p = NULL;
2709     // Try to constant fold a load from a constant field
2710     ciField* field = alias_type->field();
2711     if (heap_base_oop != top() &&
2712         field != NULL && field->is_constant() && field->layout_type() == type) {
2713       // final or stable field
2714       const Type* con_type = Type::make_constant(alias_type->field(), heap_base_oop);
2715       if (con_type != NULL) {
2716         p = makecon(con_type);
2717       }
2718     }
2719     if (p == NULL) {
2720       MemNode::MemOrd mo = is_volatile ? MemNode::acquire : MemNode::unordered;
2721       // To be valid, unsafe loads may depend on other conditions than
2722       // the one that guards them: pin the Load node
2723       p = make_load(control(), adr, value_type, type, adr_type, mo, LoadNode::Pinned, is_volatile);
2724       // load value
2725       switch (type) {
2726       case T_BOOLEAN:
2727       case T_CHAR:
2728       case T_BYTE:
2729       case T_SHORT:
2730       case T_INT:
2731       case T_LONG:
2732       case T_FLOAT:
2733       case T_DOUBLE:
2734         break;
2735       case T_OBJECT:
2736         if (need_read_barrier) {
2737           insert_pre_barrier(heap_base_oop, offset, p, !(is_volatile || need_mem_bar));
2738         }
2739         break;
2740       case T_ADDRESS:
2741         // Cast to an int type.
2742         p = _gvn.transform(new CastP2XNode(NULL, p));
2743         p = ConvX2UL(p);
2744         break;
2745       default:
2746         fatal(err_msg_res("unexpected type %d: %s", type, type2name(type)));
2747         break;
2748       }
2749     }
2750     // The load node has the control of the preceding MemBarCPUOrder.  All
2751     // following nodes will have the control of the MemBarCPUOrder inserted at
2752     // the end of this method.  So, pushing the load onto the stack at a later
2753     // point is fine.
2754     set_result(p);
2755   } else {
2756     // place effect of store into memory
2757     switch (type) {
2758     case T_DOUBLE:
2759       val = dstore_rounding(val);
2760       break;
2761     case T_ADDRESS:
2762       // Repackage the long as a pointer.
2763       val = ConvL2X(val);
2764       val = _gvn.transform(new CastX2PNode(val));
2765       break;
2766     }
2767 
2768     MemNode::MemOrd mo = is_volatile ? MemNode::release : MemNode::unordered;
2769     if (type != T_OBJECT ) {
2770       (void) store_to_memory(control(), adr, val, type, adr_type, mo, is_volatile);
2771     } else {
2772       // Possibly an oop being stored to Java heap or native memory
2773       if (!TypePtr::NULL_PTR->higher_equal(_gvn.type(heap_base_oop))) {
2774         // oop to Java heap.
2775         (void) store_oop_to_unknown(control(), heap_base_oop, adr, adr_type, val, type, mo);
2776       } else {
2777         // We can't tell at compile time if we are storing in the Java heap or outside
2778         // of it. So we need to emit code to conditionally do the proper type of
2779         // store.
2780 
2781         IdealKit ideal(this);
2782 #define __ ideal.
2783         // QQQ who knows what probability is here??
2784         __ if_then(heap_base_oop, BoolTest::ne, null(), PROB_UNLIKELY(0.999)); {
2785           // Sync IdealKit and graphKit.
2786           sync_kit(ideal);
2787           Node* st = store_oop_to_unknown(control(), heap_base_oop, adr, adr_type, val, type, mo);
2788           // Update IdealKit memory.
2789           __ sync_kit(this);
2790         } __ else_(); {
2791           __ store(__ ctrl(), adr, val, type, alias_type->index(), mo, is_volatile);
2792         } __ end_if();
2793         // Final sync IdealKit and GraphKit.
2794         final_sync(ideal);
2795 #undef __
2796       }
2797     }
2798   }
2799 
2800   if (is_volatile) {
2801     if (!is_store) {
2802       insert_mem_bar(Op_MemBarAcquire);
2803     } else {
2804       if (!support_IRIW_for_not_multiple_copy_atomic_cpu) {
2805         insert_mem_bar(Op_MemBarVolatile);
2806       }
2807     }
2808   }
2809 
2810   if (need_mem_bar) insert_mem_bar(Op_MemBarCPUOrder);
2811 
2812   return true;
2813 }
2814 
2815 //----------------------------inline_unsafe_load_store----------------------------
2816 // This method serves a couple of different customers (depending on LoadStoreKind):
2817 //
2818 // LS_cmpxchg:
2819 //   public final native boolean compareAndSwapObject(Object o, long offset, Object expected, Object x);
2820 //   public final native boolean compareAndSwapInt(   Object o, long offset, int    expected, int    x);
2821 //   public final native boolean compareAndSwapLong(  Object o, long offset, long   expected, long   x);
2822 //
2823 // LS_xadd:
2824 //   public int  getAndAddInt( Object o, long offset, int  delta)
2825 //   public long getAndAddLong(Object o, long offset, long delta)
2826 //
2827 // LS_xchg:
2828 //   int    getAndSet(Object o, long offset, int    newValue)
2829 //   long   getAndSet(Object o, long offset, long   newValue)
2830 //   Object getAndSet(Object o, long offset, Object newValue)
2831 //
2832 bool LibraryCallKit::inline_unsafe_load_store(BasicType type, LoadStoreKind kind) {
2833   // This basic scheme here is the same as inline_unsafe_access, but
2834   // differs in enough details that combining them would make the code
2835   // overly confusing.  (This is a true fact! I originally combined
2836   // them, but even I was confused by it!) As much code/comments as
2837   // possible are retained from inline_unsafe_access though to make
2838   // the correspondences clearer. - dl
2839 
2840   if (callee()->is_static())  return false;  // caller must have the capability!
2841 
2842 #ifndef PRODUCT
2843   BasicType rtype;
2844   {
2845     ResourceMark rm;
2846     // Check the signatures.
2847     ciSignature* sig = callee()->signature();
2848     rtype = sig->return_type()->basic_type();
2849     if (kind == LS_xadd || kind == LS_xchg) {
2850       // Check the signatures.
2851 #ifdef ASSERT
2852       assert(rtype == type, "get and set must return the expected type");
2853       assert(sig->count() == 3, "get and set has 3 arguments");
2854       assert(sig->type_at(0)->basic_type() == T_OBJECT, "get and set base is object");
2855       assert(sig->type_at(1)->basic_type() == T_LONG, "get and set offset is long");
2856       assert(sig->type_at(2)->basic_type() == type, "get and set must take expected type as new value/delta");
2857 #endif // ASSERT
2858     } else if (kind == LS_cmpxchg) {
2859       // Check the signatures.
2860 #ifdef ASSERT
2861       assert(rtype == T_BOOLEAN, "CAS must return boolean");
2862       assert(sig->count() == 4, "CAS has 4 arguments");
2863       assert(sig->type_at(0)->basic_type() == T_OBJECT, "CAS base is object");
2864       assert(sig->type_at(1)->basic_type() == T_LONG, "CAS offset is long");
2865 #endif // ASSERT
2866     } else {
2867       ShouldNotReachHere();
2868     }
2869   }
2870 #endif //PRODUCT
2871 
2872   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
2873 
2874   // Get arguments:
2875   Node* receiver = NULL;
2876   Node* base     = NULL;
2877   Node* offset   = NULL;
2878   Node* oldval   = NULL;
2879   Node* newval   = NULL;
2880   if (kind == LS_cmpxchg) {
2881     const bool two_slot_type = type2size[type] == 2;
2882     receiver = argument(0);  // type: oop
2883     base     = argument(1);  // type: oop
2884     offset   = argument(2);  // type: long
2885     oldval   = argument(4);  // type: oop, int, or long
2886     newval   = argument(two_slot_type ? 6 : 5);  // type: oop, int, or long
2887   } else if (kind == LS_xadd || kind == LS_xchg){
2888     receiver = argument(0);  // type: oop
2889     base     = argument(1);  // type: oop
2890     offset   = argument(2);  // type: long
2891     oldval   = NULL;
2892     newval   = argument(4);  // type: oop, int, or long
2893   }
2894 
2895   // Null check receiver.
2896   receiver = null_check(receiver);
2897   if (stopped()) {
2898     return true;
2899   }
2900 
2901   // Build field offset expression.
2902   // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
2903   // to be plain byte offsets, which are also the same as those accepted
2904   // by oopDesc::field_base.
2905   assert(Unsafe_field_offset_to_byte_offset(11) == 11, "fieldOffset must be byte-scaled");
2906   // 32-bit machines ignore the high half of long offsets
2907   offset = ConvL2X(offset);
2908   Node* adr = make_unsafe_address(base, offset);
2909   const TypePtr *adr_type = _gvn.type(adr)->isa_ptr();
2910 
2911   // For CAS, unlike inline_unsafe_access, there seems no point in
2912   // trying to refine types. Just use the coarse types here.
2913   const Type *value_type = Type::get_const_basic_type(type);
2914   Compile::AliasType* alias_type = C->alias_type(adr_type);
2915   assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
2916 
2917   if (kind == LS_xchg && type == T_OBJECT) {
2918     const TypeOopPtr* tjp = sharpen_unsafe_type(alias_type, adr_type);
2919     if (tjp != NULL) {
2920       value_type = tjp;
2921     }
2922   }
2923 
2924   int alias_idx = C->get_alias_index(adr_type);
2925 
2926   // Memory-model-wise, a LoadStore acts like a little synchronized
2927   // block, so needs barriers on each side.  These don't translate
2928   // into actual barriers on most machines, but we still need rest of
2929   // compiler to respect ordering.
2930 
2931   insert_mem_bar(Op_MemBarRelease);
2932   insert_mem_bar(Op_MemBarCPUOrder);
2933 
2934   // 4984716: MemBars must be inserted before this
2935   //          memory node in order to avoid a false
2936   //          dependency which will confuse the scheduler.
2937   Node *mem = memory(alias_idx);
2938 
2939   // For now, we handle only those cases that actually exist: ints,
2940   // longs, and Object. Adding others should be straightforward.
2941   Node* load_store;
2942   switch(type) {
2943   case T_INT:
2944     if (kind == LS_xadd) {
2945       load_store = _gvn.transform(new GetAndAddINode(control(), mem, adr, newval, adr_type));
2946     } else if (kind == LS_xchg) {
2947       load_store = _gvn.transform(new GetAndSetINode(control(), mem, adr, newval, adr_type));
2948     } else if (kind == LS_cmpxchg) {
2949       load_store = _gvn.transform(new CompareAndSwapINode(control(), mem, adr, newval, oldval));
2950     } else {
2951       ShouldNotReachHere();
2952     }
2953     break;
2954   case T_LONG:
2955     if (kind == LS_xadd) {
2956       load_store = _gvn.transform(new GetAndAddLNode(control(), mem, adr, newval, adr_type));
2957     } else if (kind == LS_xchg) {
2958       load_store = _gvn.transform(new GetAndSetLNode(control(), mem, adr, newval, adr_type));
2959     } else if (kind == LS_cmpxchg) {
2960       load_store = _gvn.transform(new CompareAndSwapLNode(control(), mem, adr, newval, oldval));
2961     } else {
2962       ShouldNotReachHere();
2963     }
2964     break;
2965   case T_OBJECT:
2966     // Transformation of a value which could be NULL pointer (CastPP #NULL)
2967     // could be delayed during Parse (for example, in adjust_map_after_if()).
2968     // Execute transformation here to avoid barrier generation in such case.
2969     if (_gvn.type(newval) == TypePtr::NULL_PTR)
2970       newval = _gvn.makecon(TypePtr::NULL_PTR);
2971 
2972     // Reference stores need a store barrier.
2973     if (kind == LS_xchg) {
2974       // If pre-barrier must execute before the oop store, old value will require do_load here.
2975       if (!can_move_pre_barrier()) {
2976         pre_barrier(true /* do_load*/,
2977                     control(), base, adr, alias_idx, newval, value_type->make_oopptr(),
2978                     NULL /* pre_val*/,
2979                     T_OBJECT);
2980       } // Else move pre_barrier to use load_store value, see below.
2981     } else if (kind == LS_cmpxchg) {
2982       // Same as for newval above:
2983       if (_gvn.type(oldval) == TypePtr::NULL_PTR) {
2984         oldval = _gvn.makecon(TypePtr::NULL_PTR);
2985       }
2986       // The only known value which might get overwritten is oldval.
2987       pre_barrier(false /* do_load */,
2988                   control(), NULL, NULL, max_juint, NULL, NULL,
2989                   oldval /* pre_val */,
2990                   T_OBJECT);
2991     } else {
2992       ShouldNotReachHere();
2993     }
2994 
2995 #ifdef _LP64
2996     if (adr->bottom_type()->is_ptr_to_narrowoop()) {
2997       Node *newval_enc = _gvn.transform(new EncodePNode(newval, newval->bottom_type()->make_narrowoop()));
2998       if (kind == LS_xchg) {
2999         load_store = _gvn.transform(new GetAndSetNNode(control(), mem, adr,
3000                                                        newval_enc, adr_type, value_type->make_narrowoop()));
3001       } else {
3002         assert(kind == LS_cmpxchg, "wrong LoadStore operation");
3003         Node *oldval_enc = _gvn.transform(new EncodePNode(oldval, oldval->bottom_type()->make_narrowoop()));
3004         load_store = _gvn.transform(new CompareAndSwapNNode(control(), mem, adr,
3005                                                                 newval_enc, oldval_enc));
3006       }
3007     } else
3008 #endif
3009     {
3010       if (kind == LS_xchg) {
3011         load_store = _gvn.transform(new GetAndSetPNode(control(), mem, adr, newval, adr_type, value_type->is_oopptr()));
3012       } else {
3013         assert(kind == LS_cmpxchg, "wrong LoadStore operation");
3014         load_store = _gvn.transform(new CompareAndSwapPNode(control(), mem, adr, newval, oldval));
3015       }
3016     }
3017     post_barrier(control(), load_store, base, adr, alias_idx, newval, T_OBJECT, true);
3018     break;
3019   default:
3020     fatal(err_msg_res("unexpected type %d: %s", type, type2name(type)));
3021     break;
3022   }
3023 
3024   // SCMemProjNodes represent the memory state of a LoadStore. Their
3025   // main role is to prevent LoadStore nodes from being optimized away
3026   // when their results aren't used.
3027   Node* proj = _gvn.transform(new SCMemProjNode(load_store));
3028   set_memory(proj, alias_idx);
3029 
3030   if (type == T_OBJECT && kind == LS_xchg) {
3031 #ifdef _LP64
3032     if (adr->bottom_type()->is_ptr_to_narrowoop()) {
3033       load_store = _gvn.transform(new DecodeNNode(load_store, load_store->get_ptr_type()));
3034     }
3035 #endif
3036     if (can_move_pre_barrier()) {
3037       // Don't need to load pre_val. The old value is returned by load_store.
3038       // The pre_barrier can execute after the xchg as long as no safepoint
3039       // gets inserted between them.
3040       pre_barrier(false /* do_load */,
3041                   control(), NULL, NULL, max_juint, NULL, NULL,
3042                   load_store /* pre_val */,
3043                   T_OBJECT);
3044     }
3045   }
3046 
3047   // Add the trailing membar surrounding the access
3048   insert_mem_bar(Op_MemBarCPUOrder);
3049   insert_mem_bar(Op_MemBarAcquire);
3050 
3051   assert(type2size[load_store->bottom_type()->basic_type()] == type2size[rtype], "result type should match");
3052   set_result(load_store);
3053   return true;
3054 }
3055 
3056 //----------------------------inline_unsafe_ordered_store----------------------
3057 // public native void sun.misc.Unsafe.putOrderedObject(Object o, long offset, Object x);
3058 // public native void sun.misc.Unsafe.putOrderedInt(Object o, long offset, int x);
3059 // public native void sun.misc.Unsafe.putOrderedLong(Object o, long offset, long x);
3060 bool LibraryCallKit::inline_unsafe_ordered_store(BasicType type) {
3061   // This is another variant of inline_unsafe_access, differing in
3062   // that it always issues store-store ("release") barrier and ensures
3063   // store-atomicity (which only matters for "long").
3064 
3065   if (callee()->is_static())  return false;  // caller must have the capability!
3066 
3067 #ifndef PRODUCT
3068   {
3069     ResourceMark rm;
3070     // Check the signatures.
3071     ciSignature* sig = callee()->signature();
3072 #ifdef ASSERT
3073     BasicType rtype = sig->return_type()->basic_type();
3074     assert(rtype == T_VOID, "must return void");
3075     assert(sig->count() == 3, "has 3 arguments");
3076     assert(sig->type_at(0)->basic_type() == T_OBJECT, "base is object");
3077     assert(sig->type_at(1)->basic_type() == T_LONG, "offset is long");
3078 #endif // ASSERT
3079   }
3080 #endif //PRODUCT
3081 
3082   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
3083 
3084   // Get arguments:
3085   Node* receiver = argument(0);  // type: oop
3086   Node* base     = argument(1);  // type: oop
3087   Node* offset   = argument(2);  // type: long
3088   Node* val      = argument(4);  // type: oop, int, or long
3089 
3090   // Null check receiver.
3091   receiver = null_check(receiver);
3092   if (stopped()) {
3093     return true;
3094   }
3095 
3096   // Build field offset expression.
3097   assert(Unsafe_field_offset_to_byte_offset(11) == 11, "fieldOffset must be byte-scaled");
3098   // 32-bit machines ignore the high half of long offsets
3099   offset = ConvL2X(offset);
3100   Node* adr = make_unsafe_address(base, offset);
3101   const TypePtr *adr_type = _gvn.type(adr)->isa_ptr();
3102   const Type *value_type = Type::get_const_basic_type(type);
3103   Compile::AliasType* alias_type = C->alias_type(adr_type);
3104 
3105   insert_mem_bar(Op_MemBarRelease);
3106   insert_mem_bar(Op_MemBarCPUOrder);
3107   // Ensure that the store is atomic for longs:
3108   const bool require_atomic_access = true;
3109   Node* store;
3110   if (type == T_OBJECT) // reference stores need a store barrier.
3111     store = store_oop_to_unknown(control(), base, adr, adr_type, val, type, MemNode::release);
3112   else {
3113     store = store_to_memory(control(), adr, val, type, adr_type, MemNode::release, require_atomic_access);
3114   }
3115   insert_mem_bar(Op_MemBarCPUOrder);
3116   return true;
3117 }
3118 
3119 bool LibraryCallKit::inline_unsafe_fence(vmIntrinsics::ID id) {
3120   // Regardless of form, don't allow previous ld/st to move down,
3121   // then issue acquire, release, or volatile mem_bar.
3122   insert_mem_bar(Op_MemBarCPUOrder);
3123   switch(id) {
3124     case vmIntrinsics::_loadFence:
3125       insert_mem_bar(Op_LoadFence);
3126       return true;
3127     case vmIntrinsics::_storeFence:
3128       insert_mem_bar(Op_StoreFence);
3129       return true;
3130     case vmIntrinsics::_fullFence:
3131       insert_mem_bar(Op_MemBarVolatile);
3132       return true;
3133     default:
3134       fatal_unexpected_iid(id);
3135       return false;
3136   }
3137 }
3138 
3139 bool LibraryCallKit::klass_needs_init_guard(Node* kls) {
3140   if (!kls->is_Con()) {
3141     return true;
3142   }
3143   const TypeKlassPtr* klsptr = kls->bottom_type()->isa_klassptr();
3144   if (klsptr == NULL) {
3145     return true;
3146   }
3147   ciInstanceKlass* ik = klsptr->klass()->as_instance_klass();
3148   // don't need a guard for a klass that is already initialized
3149   return !ik->is_initialized();
3150 }
3151 
3152 //----------------------------inline_unsafe_allocate---------------------------
3153 // public native Object sun.misc.Unsafe.allocateInstance(Class<?> cls);
3154 bool LibraryCallKit::inline_unsafe_allocate() {
3155   if (callee()->is_static())  return false;  // caller must have the capability!
3156 
3157   null_check_receiver();  // null-check, then ignore
3158   Node* cls = null_check(argument(1));
3159   if (stopped())  return true;
3160 
3161   Node* kls = load_klass_from_mirror(cls, false, NULL, 0);
3162   kls = null_check(kls);
3163   if (stopped())  return true;  // argument was like int.class
3164 
3165   Node* test = NULL;
3166   if (LibraryCallKit::klass_needs_init_guard(kls)) {
3167     // Note:  The argument might still be an illegal value like
3168     // Serializable.class or Object[].class.   The runtime will handle it.
3169     // But we must make an explicit check for initialization.
3170     Node* insp = basic_plus_adr(kls, in_bytes(InstanceKlass::init_state_offset()));
3171     // Use T_BOOLEAN for InstanceKlass::_init_state so the compiler
3172     // can generate code to load it as unsigned byte.
3173     Node* inst = make_load(NULL, insp, TypeInt::UBYTE, T_BOOLEAN, MemNode::unordered);
3174     Node* bits = intcon(InstanceKlass::fully_initialized);
3175     test = _gvn.transform(new SubINode(inst, bits));
3176     // The 'test' is non-zero if we need to take a slow path.
3177   }
3178 
3179   Node* obj = new_instance(kls, test);
3180   set_result(obj);
3181   return true;
3182 }
3183 
3184 #ifdef TRACE_HAVE_INTRINSICS
3185 /*
3186  * oop -> myklass
3187  * myklass->trace_id |= USED
3188  * return myklass->trace_id & ~0x3
3189  */
3190 bool LibraryCallKit::inline_native_classID() {
3191   null_check_receiver();  // null-check, then ignore
3192   Node* cls = null_check(argument(1), T_OBJECT);
3193   Node* kls = load_klass_from_mirror(cls, false, NULL, 0);
3194   kls = null_check(kls, T_OBJECT);
3195   ByteSize offset = TRACE_ID_OFFSET;
3196   Node* insp = basic_plus_adr(kls, in_bytes(offset));
3197   Node* tvalue = make_load(NULL, insp, TypeLong::LONG, T_LONG, MemNode::unordered);
3198   Node* bits = longcon(~0x03l); // ignore bit 0 & 1
3199   Node* andl = _gvn.transform(new AndLNode(tvalue, bits));
3200   Node* clsused = longcon(0x01l); // set the class bit
3201   Node* orl = _gvn.transform(new OrLNode(tvalue, clsused));
3202 
3203   const TypePtr *adr_type = _gvn.type(insp)->isa_ptr();
3204   store_to_memory(control(), insp, orl, T_LONG, adr_type, MemNode::unordered);
3205   set_result(andl);
3206   return true;
3207 }
3208 
3209 bool LibraryCallKit::inline_native_threadID() {
3210   Node* tls_ptr = NULL;
3211   Node* cur_thr = generate_current_thread(tls_ptr);
3212   Node* p = basic_plus_adr(top()/*!oop*/, tls_ptr, in_bytes(JavaThread::osthread_offset()));
3213   Node* osthread = make_load(NULL, p, TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered);
3214   p = basic_plus_adr(top()/*!oop*/, osthread, in_bytes(OSThread::thread_id_offset()));
3215 
3216   Node* threadid = NULL;
3217   size_t thread_id_size = OSThread::thread_id_size();
3218   if (thread_id_size == (size_t) BytesPerLong) {
3219     threadid = ConvL2I(make_load(control(), p, TypeLong::LONG, T_LONG, MemNode::unordered));
3220   } else if (thread_id_size == (size_t) BytesPerInt) {
3221     threadid = make_load(control(), p, TypeInt::INT, T_INT, MemNode::unordered);
3222   } else {
3223     ShouldNotReachHere();
3224   }
3225   set_result(threadid);
3226   return true;
3227 }
3228 #endif
3229 
3230 //------------------------inline_native_time_funcs--------------
3231 // inline code for System.currentTimeMillis() and System.nanoTime()
3232 // these have the same type and signature
3233 bool LibraryCallKit::inline_native_time_funcs(address funcAddr, const char* funcName) {
3234   const TypeFunc* tf = OptoRuntime::void_long_Type();
3235   const TypePtr* no_memory_effects = NULL;
3236   Node* time = make_runtime_call(RC_LEAF, tf, funcAddr, funcName, no_memory_effects);
3237   Node* value = _gvn.transform(new ProjNode(time, TypeFunc::Parms+0));
3238 #ifdef ASSERT
3239   Node* value_top = _gvn.transform(new ProjNode(time, TypeFunc::Parms+1));
3240   assert(value_top == top(), "second value must be top");
3241 #endif
3242   set_result(value);
3243   return true;
3244 }
3245 
3246 //------------------------inline_native_currentThread------------------
3247 bool LibraryCallKit::inline_native_currentThread() {
3248   Node* junk = NULL;
3249   set_result(generate_current_thread(junk));
3250   return true;
3251 }
3252 
3253 //------------------------inline_native_isInterrupted------------------
3254 // private native boolean java.lang.Thread.isInterrupted(boolean ClearInterrupted);
3255 bool LibraryCallKit::inline_native_isInterrupted() {
3256   // Add a fast path to t.isInterrupted(clear_int):
3257   //   (t == Thread.current() &&
3258   //    (!TLS._osthread._interrupted || WINDOWS_ONLY(false) NOT_WINDOWS(!clear_int)))
3259   //   ? TLS._osthread._interrupted : /*slow path:*/ t.isInterrupted(clear_int)
3260   // So, in the common case that the interrupt bit is false,
3261   // we avoid making a call into the VM.  Even if the interrupt bit
3262   // is true, if the clear_int argument is false, we avoid the VM call.
3263   // However, if the receiver is not currentThread, we must call the VM,
3264   // because there must be some locking done around the operation.
3265 
3266   // We only go to the fast case code if we pass two guards.
3267   // Paths which do not pass are accumulated in the slow_region.
3268 
3269   enum {
3270     no_int_result_path   = 1, // t == Thread.current() && !TLS._osthread._interrupted
3271     no_clear_result_path = 2, // t == Thread.current() &&  TLS._osthread._interrupted && !clear_int
3272     slow_result_path     = 3, // slow path: t.isInterrupted(clear_int)
3273     PATH_LIMIT
3274   };
3275 
3276   // Ensure that it's not possible to move the load of TLS._osthread._interrupted flag
3277   // out of the function.
3278   insert_mem_bar(Op_MemBarCPUOrder);
3279 
3280   RegionNode* result_rgn = new RegionNode(PATH_LIMIT);
3281   PhiNode*    result_val = new PhiNode(result_rgn, TypeInt::BOOL);
3282 
3283   RegionNode* slow_region = new RegionNode(1);
3284   record_for_igvn(slow_region);
3285 
3286   // (a) Receiving thread must be the current thread.
3287   Node* rec_thr = argument(0);
3288   Node* tls_ptr = NULL;
3289   Node* cur_thr = generate_current_thread(tls_ptr);
3290   Node* cmp_thr = _gvn.transform(new CmpPNode(cur_thr, rec_thr));
3291   Node* bol_thr = _gvn.transform(new BoolNode(cmp_thr, BoolTest::ne));
3292 
3293   generate_slow_guard(bol_thr, slow_region);
3294 
3295   // (b) Interrupt bit on TLS must be false.
3296   Node* p = basic_plus_adr(top()/*!oop*/, tls_ptr, in_bytes(JavaThread::osthread_offset()));
3297   Node* osthread = make_load(NULL, p, TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered);
3298   p = basic_plus_adr(top()/*!oop*/, osthread, in_bytes(OSThread::interrupted_offset()));
3299 
3300   // Set the control input on the field _interrupted read to prevent it floating up.
3301   Node* int_bit = make_load(control(), p, TypeInt::BOOL, T_INT, MemNode::unordered);
3302   Node* cmp_bit = _gvn.transform(new CmpINode(int_bit, intcon(0)));
3303   Node* bol_bit = _gvn.transform(new BoolNode(cmp_bit, BoolTest::ne));
3304 
3305   IfNode* iff_bit = create_and_map_if(control(), bol_bit, PROB_UNLIKELY_MAG(3), COUNT_UNKNOWN);
3306 
3307   // First fast path:  if (!TLS._interrupted) return false;
3308   Node* false_bit = _gvn.transform(new IfFalseNode(iff_bit));
3309   result_rgn->init_req(no_int_result_path, false_bit);
3310   result_val->init_req(no_int_result_path, intcon(0));
3311 
3312   // drop through to next case
3313   set_control( _gvn.transform(new IfTrueNode(iff_bit)));
3314 
3315 #ifndef TARGET_OS_FAMILY_windows
3316   // (c) Or, if interrupt bit is set and clear_int is false, use 2nd fast path.
3317   Node* clr_arg = argument(1);
3318   Node* cmp_arg = _gvn.transform(new CmpINode(clr_arg, intcon(0)));
3319   Node* bol_arg = _gvn.transform(new BoolNode(cmp_arg, BoolTest::ne));
3320   IfNode* iff_arg = create_and_map_if(control(), bol_arg, PROB_FAIR, COUNT_UNKNOWN);
3321 
3322   // Second fast path:  ... else if (!clear_int) return true;
3323   Node* false_arg = _gvn.transform(new IfFalseNode(iff_arg));
3324   result_rgn->init_req(no_clear_result_path, false_arg);
3325   result_val->init_req(no_clear_result_path, intcon(1));
3326 
3327   // drop through to next case
3328   set_control( _gvn.transform(new IfTrueNode(iff_arg)));
3329 #else
3330   // To return true on Windows you must read the _interrupted field
3331   // and check the the event state i.e. take the slow path.
3332 #endif // TARGET_OS_FAMILY_windows
3333 
3334   // (d) Otherwise, go to the slow path.
3335   slow_region->add_req(control());
3336   set_control( _gvn.transform(slow_region));
3337 
3338   if (stopped()) {
3339     // There is no slow path.
3340     result_rgn->init_req(slow_result_path, top());
3341     result_val->init_req(slow_result_path, top());
3342   } else {
3343     // non-virtual because it is a private non-static
3344     CallJavaNode* slow_call = generate_method_call(vmIntrinsics::_isInterrupted);
3345 
3346     Node* slow_val = set_results_for_java_call(slow_call);
3347     // this->control() comes from set_results_for_java_call
3348 
3349     Node* fast_io  = slow_call->in(TypeFunc::I_O);
3350     Node* fast_mem = slow_call->in(TypeFunc::Memory);
3351 
3352     // These two phis are pre-filled with copies of of the fast IO and Memory
3353     PhiNode* result_mem  = PhiNode::make(result_rgn, fast_mem, Type::MEMORY, TypePtr::BOTTOM);
3354     PhiNode* result_io   = PhiNode::make(result_rgn, fast_io,  Type::ABIO);
3355 
3356     result_rgn->init_req(slow_result_path, control());
3357     result_io ->init_req(slow_result_path, i_o());
3358     result_mem->init_req(slow_result_path, reset_memory());
3359     result_val->init_req(slow_result_path, slow_val);
3360 
3361     set_all_memory(_gvn.transform(result_mem));
3362     set_i_o(       _gvn.transform(result_io));
3363   }
3364 
3365   C->set_has_split_ifs(true); // Has chance for split-if optimization
3366   set_result(result_rgn, result_val);
3367   return true;
3368 }
3369 
3370 //---------------------------load_mirror_from_klass----------------------------
3371 // Given a klass oop, load its java mirror (a java.lang.Class oop).
3372 Node* LibraryCallKit::load_mirror_from_klass(Node* klass) {
3373   Node* p = basic_plus_adr(klass, in_bytes(Klass::java_mirror_offset()));
3374   return make_load(NULL, p, TypeInstPtr::MIRROR, T_OBJECT, MemNode::unordered);
3375 }
3376 
3377 //-----------------------load_klass_from_mirror_common-------------------------
3378 // Given a java mirror (a java.lang.Class oop), load its corresponding klass oop.
3379 // Test the klass oop for null (signifying a primitive Class like Integer.TYPE),
3380 // and branch to the given path on the region.
3381 // If never_see_null, take an uncommon trap on null, so we can optimistically
3382 // compile for the non-null case.
3383 // If the region is NULL, force never_see_null = true.
3384 Node* LibraryCallKit::load_klass_from_mirror_common(Node* mirror,
3385                                                     bool never_see_null,
3386                                                     RegionNode* region,
3387                                                     int null_path,
3388                                                     int offset) {
3389   if (region == NULL)  never_see_null = true;
3390   Node* p = basic_plus_adr(mirror, offset);
3391   const TypeKlassPtr*  kls_type = TypeKlassPtr::OBJECT_OR_NULL;
3392   Node* kls = _gvn.transform(LoadKlassNode::make(_gvn, NULL, immutable_memory(), p, TypeRawPtr::BOTTOM, kls_type));
3393   Node* null_ctl = top();
3394   kls = null_check_oop(kls, &null_ctl, never_see_null);
3395   if (region != NULL) {
3396     // Set region->in(null_path) if the mirror is a primitive (e.g, int.class).
3397     region->init_req(null_path, null_ctl);
3398   } else {
3399     assert(null_ctl == top(), "no loose ends");
3400   }
3401   return kls;
3402 }
3403 
3404 //--------------------(inline_native_Class_query helpers)---------------------
3405 // Use this for JVM_ACC_INTERFACE, JVM_ACC_IS_CLONEABLE, JVM_ACC_HAS_FINALIZER.
3406 // Fall through if (mods & mask) == bits, take the guard otherwise.
3407 Node* LibraryCallKit::generate_access_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region) {
3408   // Branch around if the given klass has the given modifier bit set.
3409   // Like generate_guard, adds a new path onto the region.
3410   Node* modp = basic_plus_adr(kls, in_bytes(Klass::access_flags_offset()));
3411   Node* mods = make_load(NULL, modp, TypeInt::INT, T_INT, MemNode::unordered);
3412   Node* mask = intcon(modifier_mask);
3413   Node* bits = intcon(modifier_bits);
3414   Node* mbit = _gvn.transform(new AndINode(mods, mask));
3415   Node* cmp  = _gvn.transform(new CmpINode(mbit, bits));
3416   Node* bol  = _gvn.transform(new BoolNode(cmp, BoolTest::ne));
3417   return generate_fair_guard(bol, region);
3418 }
3419 Node* LibraryCallKit::generate_interface_guard(Node* kls, RegionNode* region) {
3420   return generate_access_flags_guard(kls, JVM_ACC_INTERFACE, 0, region);
3421 }
3422 
3423 //-------------------------inline_native_Class_query-------------------
3424 bool LibraryCallKit::inline_native_Class_query(vmIntrinsics::ID id) {
3425   const Type* return_type = TypeInt::BOOL;
3426   Node* prim_return_value = top();  // what happens if it's a primitive class?
3427   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
3428   bool expect_prim = false;     // most of these guys expect to work on refs
3429 
3430   enum { _normal_path = 1, _prim_path = 2, PATH_LIMIT };
3431 
3432   Node* mirror = argument(0);
3433   Node* obj    = top();
3434 
3435   switch (id) {
3436   case vmIntrinsics::_isInstance:
3437     // nothing is an instance of a primitive type
3438     prim_return_value = intcon(0);
3439     obj = argument(1);
3440     break;
3441   case vmIntrinsics::_getModifiers:
3442     prim_return_value = intcon(JVM_ACC_ABSTRACT | JVM_ACC_FINAL | JVM_ACC_PUBLIC);
3443     assert(is_power_of_2((int)JVM_ACC_WRITTEN_FLAGS+1), "change next line");
3444     return_type = TypeInt::make(0, JVM_ACC_WRITTEN_FLAGS, Type::WidenMin);
3445     break;
3446   case vmIntrinsics::_isInterface:
3447     prim_return_value = intcon(0);
3448     break;
3449   case vmIntrinsics::_isArray:
3450     prim_return_value = intcon(0);
3451     expect_prim = true;  // cf. ObjectStreamClass.getClassSignature
3452     break;
3453   case vmIntrinsics::_isPrimitive:
3454     prim_return_value = intcon(1);
3455     expect_prim = true;  // obviously
3456     break;
3457   case vmIntrinsics::_getSuperclass:
3458     prim_return_value = null();
3459     return_type = TypeInstPtr::MIRROR->cast_to_ptr_type(TypePtr::BotPTR);
3460     break;
3461   case vmIntrinsics::_getClassAccessFlags:
3462     prim_return_value = intcon(JVM_ACC_ABSTRACT | JVM_ACC_FINAL | JVM_ACC_PUBLIC);
3463     return_type = TypeInt::INT;  // not bool!  6297094
3464     break;
3465   default:
3466     fatal_unexpected_iid(id);
3467     break;
3468   }
3469 
3470   const TypeInstPtr* mirror_con = _gvn.type(mirror)->isa_instptr();
3471   if (mirror_con == NULL)  return false;  // cannot happen?
3472 
3473 #ifndef PRODUCT
3474   if (C->print_intrinsics() || C->print_inlining()) {
3475     ciType* k = mirror_con->java_mirror_type();
3476     if (k) {
3477       tty->print("Inlining %s on constant Class ", vmIntrinsics::name_at(intrinsic_id()));
3478       k->print_name();
3479       tty->cr();
3480     }
3481   }
3482 #endif
3483 
3484   // Null-check the mirror, and the mirror's klass ptr (in case it is a primitive).
3485   RegionNode* region = new RegionNode(PATH_LIMIT);
3486   record_for_igvn(region);
3487   PhiNode* phi = new PhiNode(region, return_type);
3488 
3489   // The mirror will never be null of Reflection.getClassAccessFlags, however
3490   // it may be null for Class.isInstance or Class.getModifiers. Throw a NPE
3491   // if it is. See bug 4774291.
3492 
3493   // For Reflection.getClassAccessFlags(), the null check occurs in
3494   // the wrong place; see inline_unsafe_access(), above, for a similar
3495   // situation.
3496   mirror = null_check(mirror);
3497   // If mirror or obj is dead, only null-path is taken.
3498   if (stopped())  return true;
3499 
3500   if (expect_prim)  never_see_null = false;  // expect nulls (meaning prims)
3501 
3502   // Now load the mirror's klass metaobject, and null-check it.
3503   // Side-effects region with the control path if the klass is null.
3504   Node* kls = load_klass_from_mirror(mirror, never_see_null, region, _prim_path);
3505   // If kls is null, we have a primitive mirror.
3506   phi->init_req(_prim_path, prim_return_value);
3507   if (stopped()) { set_result(region, phi); return true; }
3508   bool safe_for_replace = (region->in(_prim_path) == top());
3509 
3510   Node* p;  // handy temp
3511   Node* null_ctl;
3512 
3513   // Now that we have the non-null klass, we can perform the real query.
3514   // For constant classes, the query will constant-fold in LoadNode::Value.
3515   Node* query_value = top();
3516   switch (id) {
3517   case vmIntrinsics::_isInstance:
3518     // nothing is an instance of a primitive type
3519     query_value = gen_instanceof(obj, kls, safe_for_replace);
3520     break;
3521 
3522   case vmIntrinsics::_getModifiers:
3523     p = basic_plus_adr(kls, in_bytes(Klass::modifier_flags_offset()));
3524     query_value = make_load(NULL, p, TypeInt::INT, T_INT, MemNode::unordered);
3525     break;
3526 
3527   case vmIntrinsics::_isInterface:
3528     // (To verify this code sequence, check the asserts in JVM_IsInterface.)
3529     if (generate_interface_guard(kls, region) != NULL)
3530       // A guard was added.  If the guard is taken, it was an interface.
3531       phi->add_req(intcon(1));
3532     // If we fall through, it's a plain class.
3533     query_value = intcon(0);
3534     break;
3535 
3536   case vmIntrinsics::_isArray:
3537     // (To verify this code sequence, check the asserts in JVM_IsArrayClass.)
3538     if (generate_array_guard(kls, region) != NULL)
3539       // A guard was added.  If the guard is taken, it was an array.
3540       phi->add_req(intcon(1));
3541     // If we fall through, it's a plain class.
3542     query_value = intcon(0);
3543     break;
3544 
3545   case vmIntrinsics::_isPrimitive:
3546     query_value = intcon(0); // "normal" path produces false
3547     break;
3548 
3549   case vmIntrinsics::_getSuperclass:
3550     // The rules here are somewhat unfortunate, but we can still do better
3551     // with random logic than with a JNI call.
3552     // Interfaces store null or Object as _super, but must report null.
3553     // Arrays store an intermediate super as _super, but must report Object.
3554     // Other types can report the actual _super.
3555     // (To verify this code sequence, check the asserts in JVM_IsInterface.)
3556     if (generate_interface_guard(kls, region) != NULL)
3557       // A guard was added.  If the guard is taken, it was an interface.
3558       phi->add_req(null());
3559     if (generate_array_guard(kls, region) != NULL)
3560       // A guard was added.  If the guard is taken, it was an array.
3561       phi->add_req(makecon(TypeInstPtr::make(env()->Object_klass()->java_mirror())));
3562     // If we fall through, it's a plain class.  Get its _super.
3563     p = basic_plus_adr(kls, in_bytes(Klass::super_offset()));
3564     kls = _gvn.transform(LoadKlassNode::make(_gvn, NULL, immutable_memory(), p, TypeRawPtr::BOTTOM, TypeKlassPtr::OBJECT_OR_NULL));
3565     null_ctl = top();
3566     kls = null_check_oop(kls, &null_ctl);
3567     if (null_ctl != top()) {
3568       // If the guard is taken, Object.superClass is null (both klass and mirror).
3569       region->add_req(null_ctl);
3570       phi   ->add_req(null());
3571     }
3572     if (!stopped()) {
3573       query_value = load_mirror_from_klass(kls);
3574     }
3575     break;
3576 
3577   case vmIntrinsics::_getClassAccessFlags:
3578     p = basic_plus_adr(kls, in_bytes(Klass::access_flags_offset()));
3579     query_value = make_load(NULL, p, TypeInt::INT, T_INT, MemNode::unordered);
3580     break;
3581 
3582   default:
3583     fatal_unexpected_iid(id);
3584     break;
3585   }
3586 
3587   // Fall-through is the normal case of a query to a real class.
3588   phi->init_req(1, query_value);
3589   region->init_req(1, control());
3590 
3591   C->set_has_split_ifs(true); // Has chance for split-if optimization
3592   set_result(region, phi);
3593   return true;
3594 }
3595 
3596 //-------------------------inline_Class_cast-------------------
3597 bool LibraryCallKit::inline_Class_cast() {
3598   Node* mirror = argument(0); // Class
3599   Node* obj    = argument(1);
3600   const TypeInstPtr* mirror_con = _gvn.type(mirror)->isa_instptr();
3601   if (mirror_con == NULL) {
3602     return false;  // dead path (mirror->is_top()).
3603   }
3604   if (obj == NULL || obj->is_top()) {
3605     return false;  // dead path
3606   }
3607   const TypeOopPtr* tp = _gvn.type(obj)->isa_oopptr();
3608 
3609   // First, see if Class.cast() can be folded statically.
3610   // java_mirror_type() returns non-null for compile-time Class constants.
3611   ciType* tm = mirror_con->java_mirror_type();
3612   if (tm != NULL && tm->is_klass() &&
3613       tp != NULL && tp->klass() != NULL) {
3614     if (!tp->klass()->is_loaded()) {
3615       // Don't use intrinsic when class is not loaded.
3616       return false;
3617     } else {
3618       int static_res = C->static_subtype_check(tm->as_klass(), tp->klass());
3619       if (static_res == Compile::SSC_always_true) {
3620         // isInstance() is true - fold the code.
3621         set_result(obj);
3622         return true;
3623       } else if (static_res == Compile::SSC_always_false) {
3624         // Don't use intrinsic, have to throw ClassCastException.
3625         // If the reference is null, the non-intrinsic bytecode will
3626         // be optimized appropriately.
3627         return false;
3628       }
3629     }
3630   }
3631 
3632   // Bailout intrinsic and do normal inlining if exception path is frequent.
3633   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
3634     return false;
3635   }
3636 
3637   // Generate dynamic checks.
3638   // Class.cast() is java implementation of _checkcast bytecode.
3639   // Do checkcast (Parse::do_checkcast()) optimizations here.
3640 
3641   mirror = null_check(mirror);
3642   // If mirror is dead, only null-path is taken.
3643   if (stopped()) {
3644     return true;
3645   }
3646 
3647   // Not-subtype or the mirror's klass ptr is NULL (in case it is a primitive).
3648   enum { _bad_type_path = 1, _prim_path = 2, PATH_LIMIT };
3649   RegionNode* region = new RegionNode(PATH_LIMIT);
3650   record_for_igvn(region);
3651 
3652   // Now load the mirror's klass metaobject, and null-check it.
3653   // If kls is null, we have a primitive mirror and
3654   // nothing is an instance of a primitive type.
3655   Node* kls = load_klass_from_mirror(mirror, false, region, _prim_path);
3656 
3657   Node* res = top();
3658   if (!stopped()) {
3659     Node* bad_type_ctrl = top();
3660     // Do checkcast optimizations.
3661     res = gen_checkcast(obj, kls, &bad_type_ctrl);
3662     region->init_req(_bad_type_path, bad_type_ctrl);
3663   }
3664   if (region->in(_prim_path) != top() ||
3665       region->in(_bad_type_path) != top()) {
3666     // Let Interpreter throw ClassCastException.
3667     PreserveJVMState pjvms(this);
3668     set_control(_gvn.transform(region));
3669     uncommon_trap(Deoptimization::Reason_intrinsic,
3670                   Deoptimization::Action_maybe_recompile);
3671   }
3672   if (!stopped()) {
3673     set_result(res);
3674   }
3675   return true;
3676 }
3677 
3678 
3679 //--------------------------inline_native_subtype_check------------------------
3680 // This intrinsic takes the JNI calls out of the heart of
3681 // UnsafeFieldAccessorImpl.set, which improves Field.set, readObject, etc.
3682 bool LibraryCallKit::inline_native_subtype_check() {
3683   // Pull both arguments off the stack.
3684   Node* args[2];                // two java.lang.Class mirrors: superc, subc
3685   args[0] = argument(0);
3686   args[1] = argument(1);
3687   Node* klasses[2];             // corresponding Klasses: superk, subk
3688   klasses[0] = klasses[1] = top();
3689 
3690   enum {
3691     // A full decision tree on {superc is prim, subc is prim}:
3692     _prim_0_path = 1,           // {P,N} => false
3693                                 // {P,P} & superc!=subc => false
3694     _prim_same_path,            // {P,P} & superc==subc => true
3695     _prim_1_path,               // {N,P} => false
3696     _ref_subtype_path,          // {N,N} & subtype check wins => true
3697     _both_ref_path,             // {N,N} & subtype check loses => false
3698     PATH_LIMIT
3699   };
3700 
3701   RegionNode* region = new RegionNode(PATH_LIMIT);
3702   Node*       phi    = new PhiNode(region, TypeInt::BOOL);
3703   record_for_igvn(region);
3704 
3705   const TypePtr* adr_type = TypeRawPtr::BOTTOM;   // memory type of loads
3706   const TypeKlassPtr* kls_type = TypeKlassPtr::OBJECT_OR_NULL;
3707   int class_klass_offset = java_lang_Class::klass_offset_in_bytes();
3708 
3709   // First null-check both mirrors and load each mirror's klass metaobject.
3710   int which_arg;
3711   for (which_arg = 0; which_arg <= 1; which_arg++) {
3712     Node* arg = args[which_arg];
3713     arg = null_check(arg);
3714     if (stopped())  break;
3715     args[which_arg] = arg;
3716 
3717     Node* p = basic_plus_adr(arg, class_klass_offset);
3718     Node* kls = LoadKlassNode::make(_gvn, NULL, immutable_memory(), p, adr_type, kls_type);
3719     klasses[which_arg] = _gvn.transform(kls);
3720   }
3721 
3722   // Having loaded both klasses, test each for null.
3723   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
3724   for (which_arg = 0; which_arg <= 1; which_arg++) {
3725     Node* kls = klasses[which_arg];
3726     Node* null_ctl = top();
3727     kls = null_check_oop(kls, &null_ctl, never_see_null);
3728     int prim_path = (which_arg == 0 ? _prim_0_path : _prim_1_path);
3729     region->init_req(prim_path, null_ctl);
3730     if (stopped())  break;
3731     klasses[which_arg] = kls;
3732   }
3733 
3734   if (!stopped()) {
3735     // now we have two reference types, in klasses[0..1]
3736     Node* subk   = klasses[1];  // the argument to isAssignableFrom
3737     Node* superk = klasses[0];  // the receiver
3738     region->set_req(_both_ref_path, gen_subtype_check(subk, superk));
3739     // now we have a successful reference subtype check
3740     region->set_req(_ref_subtype_path, control());
3741   }
3742 
3743   // If both operands are primitive (both klasses null), then
3744   // we must return true when they are identical primitives.
3745   // It is convenient to test this after the first null klass check.
3746   set_control(region->in(_prim_0_path)); // go back to first null check
3747   if (!stopped()) {
3748     // Since superc is primitive, make a guard for the superc==subc case.
3749     Node* cmp_eq = _gvn.transform(new CmpPNode(args[0], args[1]));
3750     Node* bol_eq = _gvn.transform(new BoolNode(cmp_eq, BoolTest::eq));
3751     generate_guard(bol_eq, region, PROB_FAIR);
3752     if (region->req() == PATH_LIMIT+1) {
3753       // A guard was added.  If the added guard is taken, superc==subc.
3754       region->swap_edges(PATH_LIMIT, _prim_same_path);
3755       region->del_req(PATH_LIMIT);
3756     }
3757     region->set_req(_prim_0_path, control()); // Not equal after all.
3758   }
3759 
3760   // these are the only paths that produce 'true':
3761   phi->set_req(_prim_same_path,   intcon(1));
3762   phi->set_req(_ref_subtype_path, intcon(1));
3763 
3764   // pull together the cases:
3765   assert(region->req() == PATH_LIMIT, "sane region");
3766   for (uint i = 1; i < region->req(); i++) {
3767     Node* ctl = region->in(i);
3768     if (ctl == NULL || ctl == top()) {
3769       region->set_req(i, top());
3770       phi   ->set_req(i, top());
3771     } else if (phi->in(i) == NULL) {
3772       phi->set_req(i, intcon(0)); // all other paths produce 'false'
3773     }
3774   }
3775 
3776   set_control(_gvn.transform(region));
3777   set_result(_gvn.transform(phi));
3778   return true;
3779 }
3780 
3781 //---------------------generate_array_guard_common------------------------
3782 Node* LibraryCallKit::generate_array_guard_common(Node* kls, RegionNode* region,
3783                                                   bool obj_array, bool not_array) {
3784 
3785   if (stopped()) {
3786     return NULL;
3787   }
3788 
3789   // If obj_array/non_array==false/false:
3790   // Branch around if the given klass is in fact an array (either obj or prim).
3791   // If obj_array/non_array==false/true:
3792   // Branch around if the given klass is not an array klass of any kind.
3793   // If obj_array/non_array==true/true:
3794   // Branch around if the kls is not an oop array (kls is int[], String, etc.)
3795   // If obj_array/non_array==true/false:
3796   // Branch around if the kls is an oop array (Object[] or subtype)
3797   //
3798   // Like generate_guard, adds a new path onto the region.
3799   jint  layout_con = 0;
3800   Node* layout_val = get_layout_helper(kls, layout_con);
3801   if (layout_val == NULL) {
3802     bool query = (obj_array
3803                   ? Klass::layout_helper_is_objArray(layout_con)
3804                   : Klass::layout_helper_is_array(layout_con));
3805     if (query == not_array) {
3806       return NULL;                       // never a branch
3807     } else {                             // always a branch
3808       Node* always_branch = control();
3809       if (region != NULL)
3810         region->add_req(always_branch);
3811       set_control(top());
3812       return always_branch;
3813     }
3814   }
3815   // Now test the correct condition.
3816   jint  nval = (obj_array
3817                 ? ((jint)Klass::_lh_array_tag_type_value
3818                    <<    Klass::_lh_array_tag_shift)
3819                 : Klass::_lh_neutral_value);
3820   Node* cmp = _gvn.transform(new CmpINode(layout_val, intcon(nval)));
3821   BoolTest::mask btest = BoolTest::lt;  // correct for testing is_[obj]array
3822   // invert the test if we are looking for a non-array
3823   if (not_array)  btest = BoolTest(btest).negate();
3824   Node* bol = _gvn.transform(new BoolNode(cmp, btest));
3825   return generate_fair_guard(bol, region);
3826 }
3827 
3828 
3829 //-----------------------inline_native_newArray--------------------------
3830 // private static native Object java.lang.reflect.newArray(Class<?> componentType, int length);
3831 bool LibraryCallKit::inline_native_newArray() {
3832   Node* mirror    = argument(0);
3833   Node* count_val = argument(1);
3834 
3835   mirror = null_check(mirror);
3836   // If mirror or obj is dead, only null-path is taken.
3837   if (stopped())  return true;
3838 
3839   enum { _normal_path = 1, _slow_path = 2, PATH_LIMIT };
3840   RegionNode* result_reg = new RegionNode(PATH_LIMIT);
3841   PhiNode*    result_val = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
3842   PhiNode*    result_io  = new PhiNode(result_reg, Type::ABIO);
3843   PhiNode*    result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
3844 
3845   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
3846   Node* klass_node = load_array_klass_from_mirror(mirror, never_see_null,
3847                                                   result_reg, _slow_path);
3848   Node* normal_ctl   = control();
3849   Node* no_array_ctl = result_reg->in(_slow_path);
3850 
3851   // Generate code for the slow case.  We make a call to newArray().
3852   set_control(no_array_ctl);
3853   if (!stopped()) {
3854     // Either the input type is void.class, or else the
3855     // array klass has not yet been cached.  Either the
3856     // ensuing call will throw an exception, or else it
3857     // will cache the array klass for next time.
3858     PreserveJVMState pjvms(this);
3859     CallJavaNode* slow_call = generate_method_call_static(vmIntrinsics::_newArray);
3860     Node* slow_result = set_results_for_java_call(slow_call);
3861     // this->control() comes from set_results_for_java_call
3862     result_reg->set_req(_slow_path, control());
3863     result_val->set_req(_slow_path, slow_result);
3864     result_io ->set_req(_slow_path, i_o());
3865     result_mem->set_req(_slow_path, reset_memory());
3866   }
3867 
3868   set_control(normal_ctl);
3869   if (!stopped()) {
3870     // Normal case:  The array type has been cached in the java.lang.Class.
3871     // The following call works fine even if the array type is polymorphic.
3872     // It could be a dynamic mix of int[], boolean[], Object[], etc.
3873     Node* obj = new_array(klass_node, count_val, 0);  // no arguments to push
3874     result_reg->init_req(_normal_path, control());
3875     result_val->init_req(_normal_path, obj);
3876     result_io ->init_req(_normal_path, i_o());
3877     result_mem->init_req(_normal_path, reset_memory());
3878   }
3879 
3880   // Return the combined state.
3881   set_i_o(        _gvn.transform(result_io)  );
3882   set_all_memory( _gvn.transform(result_mem));
3883 
3884   C->set_has_split_ifs(true); // Has chance for split-if optimization
3885   set_result(result_reg, result_val);
3886   return true;
3887 }
3888 
3889 //----------------------inline_native_getLength--------------------------
3890 // public static native int java.lang.reflect.Array.getLength(Object array);
3891 bool LibraryCallKit::inline_native_getLength() {
3892   if (too_many_traps(Deoptimization::Reason_intrinsic))  return false;
3893 
3894   Node* array = null_check(argument(0));
3895   // If array is dead, only null-path is taken.
3896   if (stopped())  return true;
3897 
3898   // Deoptimize if it is a non-array.
3899   Node* non_array = generate_non_array_guard(load_object_klass(array), NULL);
3900 
3901   if (non_array != NULL) {
3902     PreserveJVMState pjvms(this);
3903     set_control(non_array);
3904     uncommon_trap(Deoptimization::Reason_intrinsic,
3905                   Deoptimization::Action_maybe_recompile);
3906   }
3907 
3908   // If control is dead, only non-array-path is taken.
3909   if (stopped())  return true;
3910 
3911   // The works fine even if the array type is polymorphic.
3912   // It could be a dynamic mix of int[], boolean[], Object[], etc.
3913   Node* result = load_array_length(array);
3914 
3915   C->set_has_split_ifs(true);  // Has chance for split-if optimization
3916   set_result(result);
3917   return true;
3918 }
3919 
3920 //------------------------inline_array_copyOf----------------------------
3921 // public static <T,U> T[] java.util.Arrays.copyOf(     U[] original, int newLength,         Class<? extends T[]> newType);
3922 // public static <T,U> T[] java.util.Arrays.copyOfRange(U[] original, int from,      int to, Class<? extends T[]> newType);
3923 bool LibraryCallKit::inline_array_copyOf(bool is_copyOfRange) {
3924   if (too_many_traps(Deoptimization::Reason_intrinsic))  return false;
3925 
3926   // Get the arguments.
3927   Node* original          = argument(0);
3928   Node* start             = is_copyOfRange? argument(1): intcon(0);
3929   Node* end               = is_copyOfRange? argument(2): argument(1);
3930   Node* array_type_mirror = is_copyOfRange? argument(3): argument(2);
3931 
3932   Node* newcopy;
3933 
3934   // Set the original stack and the reexecute bit for the interpreter to reexecute
3935   // the bytecode that invokes Arrays.copyOf if deoptimization happens.
3936   { PreserveReexecuteState preexecs(this);
3937     jvms()->set_should_reexecute(true);
3938 
3939     array_type_mirror = null_check(array_type_mirror);
3940     original          = null_check(original);
3941 
3942     // Check if a null path was taken unconditionally.
3943     if (stopped())  return true;
3944 
3945     Node* orig_length = load_array_length(original);
3946 
3947     Node* klass_node = load_klass_from_mirror(array_type_mirror, false, NULL, 0);
3948     klass_node = null_check(klass_node);
3949 
3950     RegionNode* bailout = new RegionNode(1);
3951     record_for_igvn(bailout);
3952 
3953     // Despite the generic type of Arrays.copyOf, the mirror might be int, int[], etc.
3954     // Bail out if that is so.
3955     Node* not_objArray = generate_non_objArray_guard(klass_node, bailout);
3956     if (not_objArray != NULL) {
3957       // Improve the klass node's type from the new optimistic assumption:
3958       ciKlass* ak = ciArrayKlass::make(env()->Object_klass());
3959       const Type* akls = TypeKlassPtr::make(TypePtr::NotNull, ak, 0/*offset*/);
3960       Node* cast = new CastPPNode(klass_node, akls);
3961       cast->init_req(0, control());
3962       klass_node = _gvn.transform(cast);
3963     }
3964 
3965     // Bail out if either start or end is negative.
3966     generate_negative_guard(start, bailout, &start);
3967     generate_negative_guard(end,   bailout, &end);
3968 
3969     Node* length = end;
3970     if (_gvn.type(start) != TypeInt::ZERO) {
3971       length = _gvn.transform(new SubINode(end, start));
3972     }
3973 
3974     // Bail out if length is negative.
3975     // Without this the new_array would throw
3976     // NegativeArraySizeException but IllegalArgumentException is what
3977     // should be thrown
3978     generate_negative_guard(length, bailout, &length);
3979 
3980     if (bailout->req() > 1) {
3981       PreserveJVMState pjvms(this);
3982       set_control(_gvn.transform(bailout));
3983       uncommon_trap(Deoptimization::Reason_intrinsic,
3984                     Deoptimization::Action_maybe_recompile);
3985     }
3986 
3987     if (!stopped()) {
3988       // How many elements will we copy from the original?
3989       // The answer is MinI(orig_length - start, length).
3990       Node* orig_tail = _gvn.transform(new SubINode(orig_length, start));
3991       Node* moved = generate_min_max(vmIntrinsics::_min, orig_tail, length);
3992 
3993       // Generate a direct call to the right arraycopy function(s).
3994       // We know the copy is disjoint but we might not know if the
3995       // oop stores need checking.
3996       // Extreme case:  Arrays.copyOf((Integer[])x, 10, String[].class).
3997       // This will fail a store-check if x contains any non-nulls.
3998 
3999       // ArrayCopyNode:Ideal may transform the ArrayCopyNode to
4000       // loads/stores but it is legal only if we're sure the
4001       // Arrays.copyOf would succeed. So we need all input arguments
4002       // to the copyOf to be validated, including that the copy to the
4003       // new array won't trigger an ArrayStoreException. That subtype
4004       // check can be optimized if we know something on the type of
4005       // the input array from type speculation.
4006       if (_gvn.type(klass_node)->singleton()) {
4007         ciKlass* subk   = _gvn.type(load_object_klass(original))->is_klassptr()->klass();
4008         ciKlass* superk = _gvn.type(klass_node)->is_klassptr()->klass();
4009 
4010         int test = C->static_subtype_check(superk, subk);
4011         if (test != Compile::SSC_always_true && test != Compile::SSC_always_false) {
4012           const TypeOopPtr* t_original = _gvn.type(original)->is_oopptr();
4013           if (t_original->speculative_type() != NULL) {
4014             original = maybe_cast_profiled_obj(original, t_original->speculative_type(), true);
4015           }
4016         }
4017       }
4018 
4019       bool validated = false;
4020       // Reason_class_check rather than Reason_intrinsic because we
4021       // want to intrinsify even if this traps.
4022       if (!too_many_traps(Deoptimization::Reason_class_check)) {
4023         Node* not_subtype_ctrl = gen_subtype_check(load_object_klass(original),
4024                                                    klass_node);
4025 
4026         if (not_subtype_ctrl != top()) {
4027           PreserveJVMState pjvms(this);
4028           set_control(not_subtype_ctrl);
4029           uncommon_trap(Deoptimization::Reason_class_check,
4030                         Deoptimization::Action_make_not_entrant);
4031           assert(stopped(), "Should be stopped");
4032         }
4033         validated = true;
4034       }
4035 
4036       if (!stopped()) {
4037         newcopy = new_array(klass_node, length, 0);  // no arguments to push
4038 
4039         ArrayCopyNode* ac = ArrayCopyNode::make(this, true, original, start, newcopy, intcon(0), moved, true,
4040                                                 load_object_klass(original), klass_node);
4041         if (!is_copyOfRange) {
4042           ac->set_copyof(validated);
4043         } else {
4044           ac->set_copyofrange(validated);
4045         }
4046         Node* n = _gvn.transform(ac);
4047         if (n == ac) {
4048           ac->connect_outputs(this);
4049         } else {
4050           assert(validated, "shouldn't transform if all arguments not validated");
4051           set_all_memory(n);
4052         }
4053       }
4054     }
4055   } // original reexecute is set back here
4056 
4057   C->set_has_split_ifs(true); // Has chance for split-if optimization
4058   if (!stopped()) {
4059     set_result(newcopy);
4060   }
4061   return true;
4062 }
4063 
4064 
4065 //----------------------generate_virtual_guard---------------------------
4066 // Helper for hashCode and clone.  Peeks inside the vtable to avoid a call.
4067 Node* LibraryCallKit::generate_virtual_guard(Node* obj_klass,
4068                                              RegionNode* slow_region) {
4069   ciMethod* method = callee();
4070   int vtable_index = method->vtable_index();
4071   assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index,
4072          err_msg_res("bad index %d", vtable_index));
4073   // Get the Method* out of the appropriate vtable entry.
4074   int entry_offset  = (InstanceKlass::vtable_start_offset() +
4075                      vtable_index*vtableEntry::size()) * wordSize +
4076                      vtableEntry::method_offset_in_bytes();
4077   Node* entry_addr  = basic_plus_adr(obj_klass, entry_offset);
4078   Node* target_call = make_load(NULL, entry_addr, TypePtr::NOTNULL, T_ADDRESS, MemNode::unordered);
4079 
4080   // Compare the target method with the expected method (e.g., Object.hashCode).
4081   const TypePtr* native_call_addr = TypeMetadataPtr::make(method);
4082 
4083   Node* native_call = makecon(native_call_addr);
4084   Node* chk_native  = _gvn.transform(new CmpPNode(target_call, native_call));
4085   Node* test_native = _gvn.transform(new BoolNode(chk_native, BoolTest::ne));
4086 
4087   return generate_slow_guard(test_native, slow_region);
4088 }
4089 
4090 //-----------------------generate_method_call----------------------------
4091 // Use generate_method_call to make a slow-call to the real
4092 // method if the fast path fails.  An alternative would be to
4093 // use a stub like OptoRuntime::slow_arraycopy_Java.
4094 // This only works for expanding the current library call,
4095 // not another intrinsic.  (E.g., don't use this for making an
4096 // arraycopy call inside of the copyOf intrinsic.)
4097 CallJavaNode*
4098 LibraryCallKit::generate_method_call(vmIntrinsics::ID method_id, bool is_virtual, bool is_static) {
4099   // When compiling the intrinsic method itself, do not use this technique.
4100   guarantee(callee() != C->method(), "cannot make slow-call to self");
4101 
4102   ciMethod* method = callee();
4103   // ensure the JVMS we have will be correct for this call
4104   guarantee(method_id == method->intrinsic_id(), "must match");
4105 
4106   const TypeFunc* tf = TypeFunc::make(method);
4107   CallJavaNode* slow_call;
4108   if (is_static) {
4109     assert(!is_virtual, "");
4110     slow_call = new CallStaticJavaNode(C, tf,
4111                            SharedRuntime::get_resolve_static_call_stub(),
4112                            method, bci());
4113   } else if (is_virtual) {
4114     null_check_receiver();
4115     int vtable_index = Method::invalid_vtable_index;
4116     if (UseInlineCaches) {
4117       // Suppress the vtable call
4118     } else {
4119       // hashCode and clone are not a miranda methods,
4120       // so the vtable index is fixed.
4121       // No need to use the linkResolver to get it.
4122        vtable_index = method->vtable_index();
4123        assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index,
4124               err_msg_res("bad index %d", vtable_index));
4125     }
4126     slow_call = new CallDynamicJavaNode(tf,
4127                           SharedRuntime::get_resolve_virtual_call_stub(),
4128                           method, vtable_index, bci());
4129   } else {  // neither virtual nor static:  opt_virtual
4130     null_check_receiver();
4131     slow_call = new CallStaticJavaNode(C, tf,
4132                                 SharedRuntime::get_resolve_opt_virtual_call_stub(),
4133                                 method, bci());
4134     slow_call->set_optimized_virtual(true);
4135   }
4136   set_arguments_for_java_call(slow_call);
4137   set_edges_for_java_call(slow_call);
4138   return slow_call;
4139 }
4140 
4141 
4142 /**
4143  * Build special case code for calls to hashCode on an object. This call may
4144  * be virtual (invokevirtual) or bound (invokespecial). For each case we generate
4145  * slightly different code.
4146  */
4147 bool LibraryCallKit::inline_native_hashcode(bool is_virtual, bool is_static) {
4148   assert(is_static == callee()->is_static(), "correct intrinsic selection");
4149   assert(!(is_virtual && is_static), "either virtual, special, or static");
4150 
4151   enum { _slow_path = 1, _fast_path, _null_path, PATH_LIMIT };
4152 
4153   RegionNode* result_reg = new RegionNode(PATH_LIMIT);
4154   PhiNode*    result_val = new PhiNode(result_reg, TypeInt::INT);
4155   PhiNode*    result_io  = new PhiNode(result_reg, Type::ABIO);
4156   PhiNode*    result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
4157   Node* obj = NULL;
4158   if (!is_static) {
4159     // Check for hashing null object
4160     obj = null_check_receiver();
4161     if (stopped())  return true;        // unconditionally null
4162     result_reg->init_req(_null_path, top());
4163     result_val->init_req(_null_path, top());
4164   } else {
4165     // Do a null check, and return zero if null.
4166     // System.identityHashCode(null) == 0
4167     obj = argument(0);
4168     Node* null_ctl = top();
4169     obj = null_check_oop(obj, &null_ctl);
4170     result_reg->init_req(_null_path, null_ctl);
4171     result_val->init_req(_null_path, _gvn.intcon(0));
4172   }
4173 
4174   // Unconditionally null?  Then return right away.
4175   if (stopped()) {
4176     set_control( result_reg->in(_null_path));
4177     if (!stopped())
4178       set_result(result_val->in(_null_path));
4179     return true;
4180   }
4181 
4182   // We only go to the fast case code if we pass a number of guards.  The
4183   // paths which do not pass are accumulated in the slow_region.
4184   RegionNode* slow_region = new RegionNode(1);
4185   record_for_igvn(slow_region);
4186 
4187   // If this is a virtual call, we generate a funny guard.  We pull out
4188   // the vtable entry corresponding to hashCode() from the target object.
4189   // If the target method which we are calling happens to be the native
4190   // Object hashCode() method, we pass the guard.  We do not need this
4191   // guard for non-virtual calls -- the caller is known to be the native
4192   // Object hashCode().
4193   if (is_virtual) {
4194     // After null check, get the object's klass.
4195     Node* obj_klass = load_object_klass(obj);
4196     generate_virtual_guard(obj_klass, slow_region);
4197   }
4198 
4199   // Get the header out of the object, use LoadMarkNode when available
4200   Node* header_addr = basic_plus_adr(obj, oopDesc::mark_offset_in_bytes());
4201   // The control of the load must be NULL. Otherwise, the load can move before
4202   // the null check after castPP removal.
4203   Node* no_ctrl = NULL;
4204   Node* header = make_load(no_ctrl, header_addr, TypeX_X, TypeX_X->basic_type(), MemNode::unordered);
4205 
4206   // Test the header to see if it is unlocked.
4207   Node *lock_mask      = _gvn.MakeConX(markOopDesc::biased_lock_mask_in_place);
4208   Node *lmasked_header = _gvn.transform(new AndXNode(header, lock_mask));
4209   Node *unlocked_val   = _gvn.MakeConX(markOopDesc::unlocked_value);
4210   Node *chk_unlocked   = _gvn.transform(new CmpXNode( lmasked_header, unlocked_val));
4211   Node *test_unlocked  = _gvn.transform(new BoolNode( chk_unlocked, BoolTest::ne));
4212 
4213   generate_slow_guard(test_unlocked, slow_region);
4214 
4215   // Get the hash value and check to see that it has been properly assigned.
4216   // We depend on hash_mask being at most 32 bits and avoid the use of
4217   // hash_mask_in_place because it could be larger than 32 bits in a 64-bit
4218   // vm: see markOop.hpp.
4219   Node *hash_mask      = _gvn.intcon(markOopDesc::hash_mask);
4220   Node *hash_shift     = _gvn.intcon(markOopDesc::hash_shift);
4221   Node *hshifted_header= _gvn.transform(new URShiftXNode(header, hash_shift));
4222   // This hack lets the hash bits live anywhere in the mark object now, as long
4223   // as the shift drops the relevant bits into the low 32 bits.  Note that
4224   // Java spec says that HashCode is an int so there's no point in capturing
4225   // an 'X'-sized hashcode (32 in 32-bit build or 64 in 64-bit build).
4226   hshifted_header      = ConvX2I(hshifted_header);
4227   Node *hash_val       = _gvn.transform(new AndINode(hshifted_header, hash_mask));
4228 
4229   Node *no_hash_val    = _gvn.intcon(markOopDesc::no_hash);
4230   Node *chk_assigned   = _gvn.transform(new CmpINode( hash_val, no_hash_val));
4231   Node *test_assigned  = _gvn.transform(new BoolNode( chk_assigned, BoolTest::eq));
4232 
4233   generate_slow_guard(test_assigned, slow_region);
4234 
4235   Node* init_mem = reset_memory();
4236   // fill in the rest of the null path:
4237   result_io ->init_req(_null_path, i_o());
4238   result_mem->init_req(_null_path, init_mem);
4239 
4240   result_val->init_req(_fast_path, hash_val);
4241   result_reg->init_req(_fast_path, control());
4242   result_io ->init_req(_fast_path, i_o());
4243   result_mem->init_req(_fast_path, init_mem);
4244 
4245   // Generate code for the slow case.  We make a call to hashCode().
4246   set_control(_gvn.transform(slow_region));
4247   if (!stopped()) {
4248     // No need for PreserveJVMState, because we're using up the present state.
4249     set_all_memory(init_mem);
4250     vmIntrinsics::ID hashCode_id = is_static ? vmIntrinsics::_identityHashCode : vmIntrinsics::_hashCode;
4251     CallJavaNode* slow_call = generate_method_call(hashCode_id, is_virtual, is_static);
4252     Node* slow_result = set_results_for_java_call(slow_call);
4253     // this->control() comes from set_results_for_java_call
4254     result_reg->init_req(_slow_path, control());
4255     result_val->init_req(_slow_path, slow_result);
4256     result_io  ->set_req(_slow_path, i_o());
4257     result_mem ->set_req(_slow_path, reset_memory());
4258   }
4259 
4260   // Return the combined state.
4261   set_i_o(        _gvn.transform(result_io)  );
4262   set_all_memory( _gvn.transform(result_mem));
4263 
4264   set_result(result_reg, result_val);
4265   return true;
4266 }
4267 
4268 //---------------------------inline_native_getClass----------------------------
4269 // public final native Class<?> java.lang.Object.getClass();
4270 //
4271 // Build special case code for calls to getClass on an object.
4272 bool LibraryCallKit::inline_native_getClass() {
4273   Node* obj = null_check_receiver();
4274   if (stopped())  return true;
4275   set_result(load_mirror_from_klass(load_object_klass(obj)));
4276   return true;
4277 }
4278 
4279 //-----------------inline_native_Reflection_getCallerClass---------------------
4280 // public static native Class<?> sun.reflect.Reflection.getCallerClass();
4281 //
4282 // In the presence of deep enough inlining, getCallerClass() becomes a no-op.
4283 //
4284 // NOTE: This code must perform the same logic as JVM_GetCallerClass
4285 // in that it must skip particular security frames and checks for
4286 // caller sensitive methods.
4287 bool LibraryCallKit::inline_native_Reflection_getCallerClass() {
4288 #ifndef PRODUCT
4289   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
4290     tty->print_cr("Attempting to inline sun.reflect.Reflection.getCallerClass");
4291   }
4292 #endif
4293 
4294   if (!jvms()->has_method()) {
4295 #ifndef PRODUCT
4296     if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
4297       tty->print_cr("  Bailing out because intrinsic was inlined at top level");
4298     }
4299 #endif
4300     return false;
4301   }
4302 
4303   // Walk back up the JVM state to find the caller at the required
4304   // depth.
4305   JVMState* caller_jvms = jvms();
4306 
4307   // Cf. JVM_GetCallerClass
4308   // NOTE: Start the loop at depth 1 because the current JVM state does
4309   // not include the Reflection.getCallerClass() frame.
4310   for (int n = 1; caller_jvms != NULL; caller_jvms = caller_jvms->caller(), n++) {
4311     ciMethod* m = caller_jvms->method();
4312     switch (n) {
4313     case 0:
4314       fatal("current JVM state does not include the Reflection.getCallerClass frame");
4315       break;
4316     case 1:
4317       // Frame 0 and 1 must be caller sensitive (see JVM_GetCallerClass).
4318       if (!m->caller_sensitive()) {
4319 #ifndef PRODUCT
4320         if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
4321           tty->print_cr("  Bailing out: CallerSensitive annotation expected at frame %d", n);
4322         }
4323 #endif
4324         return false;  // bail-out; let JVM_GetCallerClass do the work
4325       }
4326       break;
4327     default:
4328       if (!m->is_ignored_by_security_stack_walk()) {
4329         // We have reached the desired frame; return the holder class.
4330         // Acquire method holder as java.lang.Class and push as constant.
4331         ciInstanceKlass* caller_klass = caller_jvms->method()->holder();
4332         ciInstance* caller_mirror = caller_klass->java_mirror();
4333         set_result(makecon(TypeInstPtr::make(caller_mirror)));
4334 
4335 #ifndef PRODUCT
4336         if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
4337           tty->print_cr("  Succeeded: caller = %d) %s.%s, JVMS depth = %d", n, caller_klass->name()->as_utf8(), caller_jvms->method()->name()->as_utf8(), jvms()->depth());
4338           tty->print_cr("  JVM state at this point:");
4339           for (int i = jvms()->depth(), n = 1; i >= 1; i--, n++) {
4340             ciMethod* m = jvms()->of_depth(i)->method();
4341             tty->print_cr("   %d) %s.%s", n, m->holder()->name()->as_utf8(), m->name()->as_utf8());
4342           }
4343         }
4344 #endif
4345         return true;
4346       }
4347       break;
4348     }
4349   }
4350 
4351 #ifndef PRODUCT
4352   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
4353     tty->print_cr("  Bailing out because caller depth exceeded inlining depth = %d", jvms()->depth());
4354     tty->print_cr("  JVM state at this point:");
4355     for (int i = jvms()->depth(), n = 1; i >= 1; i--, n++) {
4356       ciMethod* m = jvms()->of_depth(i)->method();
4357       tty->print_cr("   %d) %s.%s", n, m->holder()->name()->as_utf8(), m->name()->as_utf8());
4358     }
4359   }
4360 #endif
4361 
4362   return false;  // bail-out; let JVM_GetCallerClass do the work
4363 }
4364 
4365 bool LibraryCallKit::inline_fp_conversions(vmIntrinsics::ID id) {
4366   Node* arg = argument(0);
4367   Node* result;
4368 
4369   switch (id) {
4370   case vmIntrinsics::_floatToRawIntBits:    result = new MoveF2INode(arg);  break;
4371   case vmIntrinsics::_intBitsToFloat:       result = new MoveI2FNode(arg);  break;
4372   case vmIntrinsics::_doubleToRawLongBits:  result = new MoveD2LNode(arg);  break;
4373   case vmIntrinsics::_longBitsToDouble:     result = new MoveL2DNode(arg);  break;
4374 
4375   case vmIntrinsics::_doubleToLongBits: {
4376     // two paths (plus control) merge in a wood
4377     RegionNode *r = new RegionNode(3);
4378     Node *phi = new PhiNode(r, TypeLong::LONG);
4379 
4380     Node *cmpisnan = _gvn.transform(new CmpDNode(arg, arg));
4381     // Build the boolean node
4382     Node *bolisnan = _gvn.transform(new BoolNode(cmpisnan, BoolTest::ne));
4383 
4384     // Branch either way.
4385     // NaN case is less traveled, which makes all the difference.
4386     IfNode *ifisnan = create_and_xform_if(control(), bolisnan, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
4387     Node *opt_isnan = _gvn.transform(ifisnan);
4388     assert( opt_isnan->is_If(), "Expect an IfNode");
4389     IfNode *opt_ifisnan = (IfNode*)opt_isnan;
4390     Node *iftrue = _gvn.transform(new IfTrueNode(opt_ifisnan));
4391 
4392     set_control(iftrue);
4393 
4394     static const jlong nan_bits = CONST64(0x7ff8000000000000);
4395     Node *slow_result = longcon(nan_bits); // return NaN
4396     phi->init_req(1, _gvn.transform( slow_result ));
4397     r->init_req(1, iftrue);
4398 
4399     // Else fall through
4400     Node *iffalse = _gvn.transform(new IfFalseNode(opt_ifisnan));
4401     set_control(iffalse);
4402 
4403     phi->init_req(2, _gvn.transform(new MoveD2LNode(arg)));
4404     r->init_req(2, iffalse);
4405 
4406     // Post merge
4407     set_control(_gvn.transform(r));
4408     record_for_igvn(r);
4409 
4410     C->set_has_split_ifs(true); // Has chance for split-if optimization
4411     result = phi;
4412     assert(result->bottom_type()->isa_long(), "must be");
4413     break;
4414   }
4415 
4416   case vmIntrinsics::_floatToIntBits: {
4417     // two paths (plus control) merge in a wood
4418     RegionNode *r = new RegionNode(3);
4419     Node *phi = new PhiNode(r, TypeInt::INT);
4420 
4421     Node *cmpisnan = _gvn.transform(new CmpFNode(arg, arg));
4422     // Build the boolean node
4423     Node *bolisnan = _gvn.transform(new BoolNode(cmpisnan, BoolTest::ne));
4424 
4425     // Branch either way.
4426     // NaN case is less traveled, which makes all the difference.
4427     IfNode *ifisnan = create_and_xform_if(control(), bolisnan, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
4428     Node *opt_isnan = _gvn.transform(ifisnan);
4429     assert( opt_isnan->is_If(), "Expect an IfNode");
4430     IfNode *opt_ifisnan = (IfNode*)opt_isnan;
4431     Node *iftrue = _gvn.transform(new IfTrueNode(opt_ifisnan));
4432 
4433     set_control(iftrue);
4434 
4435     static const jint nan_bits = 0x7fc00000;
4436     Node *slow_result = makecon(TypeInt::make(nan_bits)); // return NaN
4437     phi->init_req(1, _gvn.transform( slow_result ));
4438     r->init_req(1, iftrue);
4439 
4440     // Else fall through
4441     Node *iffalse = _gvn.transform(new IfFalseNode(opt_ifisnan));
4442     set_control(iffalse);
4443 
4444     phi->init_req(2, _gvn.transform(new MoveF2INode(arg)));
4445     r->init_req(2, iffalse);
4446 
4447     // Post merge
4448     set_control(_gvn.transform(r));
4449     record_for_igvn(r);
4450 
4451     C->set_has_split_ifs(true); // Has chance for split-if optimization
4452     result = phi;
4453     assert(result->bottom_type()->isa_int(), "must be");
4454     break;
4455   }
4456 
4457   default:
4458     fatal_unexpected_iid(id);
4459     break;
4460   }
4461   set_result(_gvn.transform(result));
4462   return true;
4463 }
4464 
4465 #ifdef _LP64
4466 #define XTOP ,top() /*additional argument*/
4467 #else  //_LP64
4468 #define XTOP        /*no additional argument*/
4469 #endif //_LP64
4470 
4471 //----------------------inline_unsafe_copyMemory-------------------------
4472 // public native void sun.misc.Unsafe.copyMemory(Object srcBase, long srcOffset, Object destBase, long destOffset, long bytes);
4473 bool LibraryCallKit::inline_unsafe_copyMemory() {
4474   if (callee()->is_static())  return false;  // caller must have the capability!
4475   null_check_receiver();  // null-check receiver
4476   if (stopped())  return true;
4477 
4478   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
4479 
4480   Node* src_ptr =         argument(1);   // type: oop
4481   Node* src_off = ConvL2X(argument(2));  // type: long
4482   Node* dst_ptr =         argument(4);   // type: oop
4483   Node* dst_off = ConvL2X(argument(5));  // type: long
4484   Node* size    = ConvL2X(argument(7));  // type: long
4485 
4486   assert(Unsafe_field_offset_to_byte_offset(11) == 11,
4487          "fieldOffset must be byte-scaled");
4488 
4489   Node* src = make_unsafe_address(src_ptr, src_off);
4490   Node* dst = make_unsafe_address(dst_ptr, dst_off);
4491 
4492   // Conservatively insert a memory barrier on all memory slices.
4493   // Do not let writes of the copy source or destination float below the copy.
4494   insert_mem_bar(Op_MemBarCPUOrder);
4495 
4496   // Call it.  Note that the length argument is not scaled.
4497   make_runtime_call(RC_LEAF|RC_NO_FP,
4498                     OptoRuntime::fast_arraycopy_Type(),
4499                     StubRoutines::unsafe_arraycopy(),
4500                     "unsafe_arraycopy",
4501                     TypeRawPtr::BOTTOM,
4502                     src, dst, size XTOP);
4503 
4504   // Do not let reads of the copy destination float above the copy.
4505   insert_mem_bar(Op_MemBarCPUOrder);
4506 
4507   return true;
4508 }
4509 
4510 //------------------------clone_coping-----------------------------------
4511 // Helper function for inline_native_clone.
4512 void LibraryCallKit::copy_to_clone(Node* obj, Node* alloc_obj, Node* obj_size, bool is_array, bool card_mark) {
4513   assert(obj_size != NULL, "");
4514   Node* raw_obj = alloc_obj->in(1);
4515   assert(alloc_obj->is_CheckCastPP() && raw_obj->is_Proj() && raw_obj->in(0)->is_Allocate(), "");
4516 
4517   AllocateNode* alloc = NULL;
4518   if (ReduceBulkZeroing) {
4519     // We will be completely responsible for initializing this object -
4520     // mark Initialize node as complete.
4521     alloc = AllocateNode::Ideal_allocation(alloc_obj, &_gvn);
4522     // The object was just allocated - there should be no any stores!
4523     guarantee(alloc != NULL && alloc->maybe_set_complete(&_gvn), "");
4524     // Mark as complete_with_arraycopy so that on AllocateNode
4525     // expansion, we know this AllocateNode is initialized by an array
4526     // copy and a StoreStore barrier exists after the array copy.
4527     alloc->initialization()->set_complete_with_arraycopy();
4528   }
4529 
4530   // Copy the fastest available way.
4531   // TODO: generate fields copies for small objects instead.
4532   Node* src  = obj;
4533   Node* dest = alloc_obj;
4534   Node* size = _gvn.transform(obj_size);
4535 
4536   // Exclude the header but include array length to copy by 8 bytes words.
4537   // Can't use base_offset_in_bytes(bt) since basic type is unknown.
4538   int base_off = is_array ? arrayOopDesc::length_offset_in_bytes() :
4539                             instanceOopDesc::base_offset_in_bytes();
4540   // base_off:
4541   // 8  - 32-bit VM
4542   // 12 - 64-bit VM, compressed klass
4543   // 16 - 64-bit VM, normal klass
4544   if (base_off % BytesPerLong != 0) {
4545     assert(UseCompressedClassPointers, "");
4546     if (is_array) {
4547       // Exclude length to copy by 8 bytes words.
4548       base_off += sizeof(int);
4549     } else {
4550       // Include klass to copy by 8 bytes words.
4551       base_off = instanceOopDesc::klass_offset_in_bytes();
4552     }
4553     assert(base_off % BytesPerLong == 0, "expect 8 bytes alignment");
4554   }
4555   src  = basic_plus_adr(src,  base_off);
4556   dest = basic_plus_adr(dest, base_off);
4557 
4558   // Compute the length also, if needed:
4559   Node* countx = size;
4560   countx = _gvn.transform(new SubXNode(countx, MakeConX(base_off)));
4561   countx = _gvn.transform(new URShiftXNode(countx, intcon(LogBytesPerLong) ));
4562 
4563   const TypePtr* raw_adr_type = TypeRawPtr::BOTTOM;
4564 
4565   ArrayCopyNode* ac = ArrayCopyNode::make(this, false, src, NULL, dest, NULL, countx, false);
4566   ac->set_clonebasic();
4567   Node* n = _gvn.transform(ac);
4568   if (n == ac) {
4569     set_predefined_output_for_runtime_call(ac, ac->in(TypeFunc::Memory), raw_adr_type);
4570   } else {
4571     set_all_memory(n);
4572   }
4573 
4574   // If necessary, emit some card marks afterwards.  (Non-arrays only.)
4575   if (card_mark) {
4576     assert(!is_array, "");
4577     // Put in store barrier for any and all oops we are sticking
4578     // into this object.  (We could avoid this if we could prove
4579     // that the object type contains no oop fields at all.)
4580     Node* no_particular_value = NULL;
4581     Node* no_particular_field = NULL;
4582     int raw_adr_idx = Compile::AliasIdxRaw;
4583     post_barrier(control(),
4584                  memory(raw_adr_type),
4585                  alloc_obj,
4586                  no_particular_field,
4587                  raw_adr_idx,
4588                  no_particular_value,
4589                  T_OBJECT,
4590                  false);
4591   }
4592 
4593   // Do not let reads from the cloned object float above the arraycopy.
4594   if (alloc != NULL) {
4595     // Do not let stores that initialize this object be reordered with
4596     // a subsequent store that would make this object accessible by
4597     // other threads.
4598     // Record what AllocateNode this StoreStore protects so that
4599     // escape analysis can go from the MemBarStoreStoreNode to the
4600     // AllocateNode and eliminate the MemBarStoreStoreNode if possible
4601     // based on the escape status of the AllocateNode.
4602     insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out(AllocateNode::RawAddress));
4603   } else {
4604     insert_mem_bar(Op_MemBarCPUOrder);
4605   }
4606 }
4607 
4608 //------------------------inline_native_clone----------------------------
4609 // protected native Object java.lang.Object.clone();
4610 //
4611 // Here are the simple edge cases:
4612 //  null receiver => normal trap
4613 //  virtual and clone was overridden => slow path to out-of-line clone
4614 //  not cloneable or finalizer => slow path to out-of-line Object.clone
4615 //
4616 // The general case has two steps, allocation and copying.
4617 // Allocation has two cases, and uses GraphKit::new_instance or new_array.
4618 //
4619 // Copying also has two cases, oop arrays and everything else.
4620 // Oop arrays use arrayof_oop_arraycopy (same as System.arraycopy).
4621 // Everything else uses the tight inline loop supplied by CopyArrayNode.
4622 //
4623 // These steps fold up nicely if and when the cloned object's klass
4624 // can be sharply typed as an object array, a type array, or an instance.
4625 //
4626 bool LibraryCallKit::inline_native_clone(bool is_virtual) {
4627   PhiNode* result_val;
4628 
4629   // Set the reexecute bit for the interpreter to reexecute
4630   // the bytecode that invokes Object.clone if deoptimization happens.
4631   { PreserveReexecuteState preexecs(this);
4632     jvms()->set_should_reexecute(true);
4633 
4634     Node* obj = null_check_receiver();
4635     if (stopped())  return true;
4636 
4637     const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
4638 
4639     // If we are going to clone an instance, we need its exact type to
4640     // know the number and types of fields to convert the clone to
4641     // loads/stores. Maybe a speculative type can help us.
4642     if (!obj_type->klass_is_exact() &&
4643         obj_type->speculative_type() != NULL &&
4644         obj_type->speculative_type()->is_instance_klass()) {
4645       ciInstanceKlass* spec_ik = obj_type->speculative_type()->as_instance_klass();
4646       if (spec_ik->nof_nonstatic_fields() <= ArrayCopyLoadStoreMaxElem &&
4647           !spec_ik->has_injected_fields()) {
4648         ciKlass* k = obj_type->klass();
4649         if (!k->is_instance_klass() ||
4650             k->as_instance_klass()->is_interface() ||
4651             k->as_instance_klass()->has_subklass()) {
4652           obj = maybe_cast_profiled_obj(obj, obj_type->speculative_type(), false);
4653         }
4654       }
4655     }
4656 
4657     Node* obj_klass = load_object_klass(obj);
4658     const TypeKlassPtr* tklass = _gvn.type(obj_klass)->isa_klassptr();
4659     const TypeOopPtr*   toop   = ((tklass != NULL)
4660                                 ? tklass->as_instance_type()
4661                                 : TypeInstPtr::NOTNULL);
4662 
4663     // Conservatively insert a memory barrier on all memory slices.
4664     // Do not let writes into the original float below the clone.
4665     insert_mem_bar(Op_MemBarCPUOrder);
4666 
4667     // paths into result_reg:
4668     enum {
4669       _slow_path = 1,     // out-of-line call to clone method (virtual or not)
4670       _objArray_path,     // plain array allocation, plus arrayof_oop_arraycopy
4671       _array_path,        // plain array allocation, plus arrayof_long_arraycopy
4672       _instance_path,     // plain instance allocation, plus arrayof_long_arraycopy
4673       PATH_LIMIT
4674     };
4675     RegionNode* result_reg = new RegionNode(PATH_LIMIT);
4676     result_val             = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
4677     PhiNode*    result_i_o = new PhiNode(result_reg, Type::ABIO);
4678     PhiNode*    result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
4679     record_for_igvn(result_reg);
4680 
4681     const TypePtr* raw_adr_type = TypeRawPtr::BOTTOM;
4682     int raw_adr_idx = Compile::AliasIdxRaw;
4683 
4684     Node* array_ctl = generate_array_guard(obj_klass, (RegionNode*)NULL);
4685     if (array_ctl != NULL) {
4686       // It's an array.
4687       PreserveJVMState pjvms(this);
4688       set_control(array_ctl);
4689       Node* obj_length = load_array_length(obj);
4690       Node* obj_size  = NULL;
4691       Node* alloc_obj = new_array(obj_klass, obj_length, 0, &obj_size);  // no arguments to push
4692 
4693       if (!use_ReduceInitialCardMarks()) {
4694         // If it is an oop array, it requires very special treatment,
4695         // because card marking is required on each card of the array.
4696         Node* is_obja = generate_objArray_guard(obj_klass, (RegionNode*)NULL);
4697         if (is_obja != NULL) {
4698           PreserveJVMState pjvms2(this);
4699           set_control(is_obja);
4700           // Generate a direct call to the right arraycopy function(s).
4701           Node* alloc = tightly_coupled_allocation(alloc_obj, NULL);
4702           ArrayCopyNode* ac = ArrayCopyNode::make(this, true, obj, intcon(0), alloc_obj, intcon(0), obj_length, alloc != NULL);
4703           ac->set_cloneoop();
4704           Node* n = _gvn.transform(ac);
4705           assert(n == ac, "cannot disappear");
4706           ac->connect_outputs(this);
4707 
4708           result_reg->init_req(_objArray_path, control());
4709           result_val->init_req(_objArray_path, alloc_obj);
4710           result_i_o ->set_req(_objArray_path, i_o());
4711           result_mem ->set_req(_objArray_path, reset_memory());
4712         }
4713       }
4714       // Otherwise, there are no card marks to worry about.
4715       // (We can dispense with card marks if we know the allocation
4716       //  comes out of eden (TLAB)...  In fact, ReduceInitialCardMarks
4717       //  causes the non-eden paths to take compensating steps to
4718       //  simulate a fresh allocation, so that no further
4719       //  card marks are required in compiled code to initialize
4720       //  the object.)
4721 
4722       if (!stopped()) {
4723         copy_to_clone(obj, alloc_obj, obj_size, true, false);
4724 
4725         // Present the results of the copy.
4726         result_reg->init_req(_array_path, control());
4727         result_val->init_req(_array_path, alloc_obj);
4728         result_i_o ->set_req(_array_path, i_o());
4729         result_mem ->set_req(_array_path, reset_memory());
4730       }
4731     }
4732 
4733     // We only go to the instance fast case code if we pass a number of guards.
4734     // The paths which do not pass are accumulated in the slow_region.
4735     RegionNode* slow_region = new RegionNode(1);
4736     record_for_igvn(slow_region);
4737     if (!stopped()) {
4738       // It's an instance (we did array above).  Make the slow-path tests.
4739       // If this is a virtual call, we generate a funny guard.  We grab
4740       // the vtable entry corresponding to clone() from the target object.
4741       // If the target method which we are calling happens to be the
4742       // Object clone() method, we pass the guard.  We do not need this
4743       // guard for non-virtual calls; the caller is known to be the native
4744       // Object clone().
4745       if (is_virtual) {
4746         generate_virtual_guard(obj_klass, slow_region);
4747       }
4748 
4749       // The object must be cloneable and must not have a finalizer.
4750       // Both of these conditions may be checked in a single test.
4751       // We could optimize the cloneable test further, but we don't care.
4752       generate_access_flags_guard(obj_klass,
4753                                   // Test both conditions:
4754                                   JVM_ACC_IS_CLONEABLE | JVM_ACC_HAS_FINALIZER,
4755                                   // Must be cloneable but not finalizer:
4756                                   JVM_ACC_IS_CLONEABLE,
4757                                   slow_region);
4758     }
4759 
4760     if (!stopped()) {
4761       // It's an instance, and it passed the slow-path tests.
4762       PreserveJVMState pjvms(this);
4763       Node* obj_size  = NULL;
4764       // Need to deoptimize on exception from allocation since Object.clone intrinsic
4765       // is reexecuted if deoptimization occurs and there could be problems when merging
4766       // exception state between multiple Object.clone versions (reexecute=true vs reexecute=false).
4767       Node* alloc_obj = new_instance(obj_klass, NULL, &obj_size, /*deoptimize_on_exception=*/true);
4768 
4769       copy_to_clone(obj, alloc_obj, obj_size, false, !use_ReduceInitialCardMarks());
4770 
4771       // Present the results of the slow call.
4772       result_reg->init_req(_instance_path, control());
4773       result_val->init_req(_instance_path, alloc_obj);
4774       result_i_o ->set_req(_instance_path, i_o());
4775       result_mem ->set_req(_instance_path, reset_memory());
4776     }
4777 
4778     // Generate code for the slow case.  We make a call to clone().
4779     set_control(_gvn.transform(slow_region));
4780     if (!stopped()) {
4781       PreserveJVMState pjvms(this);
4782       CallJavaNode* slow_call = generate_method_call(vmIntrinsics::_clone, is_virtual);
4783       Node* slow_result = set_results_for_java_call(slow_call);
4784       // this->control() comes from set_results_for_java_call
4785       result_reg->init_req(_slow_path, control());
4786       result_val->init_req(_slow_path, slow_result);
4787       result_i_o ->set_req(_slow_path, i_o());
4788       result_mem ->set_req(_slow_path, reset_memory());
4789     }
4790 
4791     // Return the combined state.
4792     set_control(    _gvn.transform(result_reg));
4793     set_i_o(        _gvn.transform(result_i_o));
4794     set_all_memory( _gvn.transform(result_mem));
4795   } // original reexecute is set back here
4796 
4797   set_result(_gvn.transform(result_val));
4798   return true;
4799 }
4800 
4801 // If we have a tighly coupled allocation, the arraycopy may take care
4802 // of the array initialization. If one of the guards we insert between
4803 // the allocation and the arraycopy causes a deoptimization, an
4804 // unitialized array will escape the compiled method. To prevent that
4805 // we set the JVM state for uncommon traps between the allocation and
4806 // the arraycopy to the state before the allocation so, in case of
4807 // deoptimization, we'll reexecute the allocation and the
4808 // initialization.
4809 JVMState* LibraryCallKit::arraycopy_restore_alloc_state(AllocateArrayNode* alloc, int& saved_reexecute_sp) {
4810   if (alloc != NULL) {
4811     ciMethod* trap_method = alloc->jvms()->method();
4812     int trap_bci = alloc->jvms()->bci();
4813 
4814     if (!C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_intrinsic) &
4815           !C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_null_check)) {
4816       // Make sure there's no store between the allocation and the
4817       // arraycopy otherwise visible side effects could be rexecuted
4818       // in case of deoptimization and cause incorrect execution.
4819       bool no_interfering_store = true;
4820       Node* mem = alloc->in(TypeFunc::Memory);
4821       if (mem->is_MergeMem()) {
4822         for (MergeMemStream mms(merged_memory(), mem->as_MergeMem()); mms.next_non_empty2(); ) {
4823           Node* n = mms.memory();
4824           if (n != mms.memory2() && !(n->is_Proj() && n->in(0) == alloc->initialization())) {
4825             assert(n->is_Store(), "what else?");
4826             no_interfering_store = false;
4827             break;
4828           }
4829         }
4830       } else {
4831         for (MergeMemStream mms(merged_memory()); mms.next_non_empty(); ) {
4832           Node* n = mms.memory();
4833           if (n != mem && !(n->is_Proj() && n->in(0) == alloc->initialization())) {
4834             assert(n->is_Store(), "what else?");
4835             no_interfering_store = false;
4836             break;
4837           }
4838         }
4839       }
4840 
4841       if (no_interfering_store) {
4842         JVMState* old_jvms = alloc->jvms()->clone_shallow(C);
4843         uint size = alloc->req();
4844         SafePointNode* sfpt = new SafePointNode(size, old_jvms);
4845         old_jvms->set_map(sfpt);
4846         for (uint i = 0; i < size; i++) {
4847           sfpt->init_req(i, alloc->in(i));
4848         }
4849         // re-push array length for deoptimization
4850         sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp(), alloc->in(AllocateNode::ALength));
4851         old_jvms->set_sp(old_jvms->sp()+1);
4852         old_jvms->set_monoff(old_jvms->monoff()+1);
4853         old_jvms->set_scloff(old_jvms->scloff()+1);
4854         old_jvms->set_endoff(old_jvms->endoff()+1);
4855         old_jvms->set_should_reexecute(true);
4856 
4857         sfpt->set_i_o(map()->i_o());
4858         sfpt->set_memory(map()->memory());
4859         sfpt->set_control(map()->control());
4860 
4861         JVMState* saved_jvms = jvms();
4862         saved_reexecute_sp = _reexecute_sp;
4863 
4864         set_jvms(sfpt->jvms());
4865         _reexecute_sp = jvms()->sp();
4866 
4867         return saved_jvms;
4868       }
4869     }
4870   }
4871   return NULL;
4872 }
4873 
4874 // In case of a deoptimization, we restart execution at the
4875 // allocation, allocating a new array. We would leave an uninitialized
4876 // array in the heap that GCs wouldn't expect. Move the allocation
4877 // after the traps so we don't allocate the array if we
4878 // deoptimize. This is possible because tightly_coupled_allocation()
4879 // guarantees there's no observer of the allocated array at this point
4880 // and the control flow is simple enough.
4881 void LibraryCallKit::arraycopy_move_allocation_here(AllocateArrayNode* alloc, Node* dest, JVMState* saved_jvms, int saved_reexecute_sp) {
4882   if (saved_jvms != NULL && !stopped()) {
4883     assert(alloc != NULL, "only with a tightly coupled allocation");
4884     // restore JVM state to the state at the arraycopy
4885     saved_jvms->map()->set_control(map()->control());
4886     assert(saved_jvms->map()->memory() == map()->memory(), "memory state changed?");
4887     assert(saved_jvms->map()->i_o() == map()->i_o(), "IO state changed?");
4888     // If we've improved the types of some nodes (null check) while
4889     // emitting the guards, propagate them to the current state
4890     map()->replaced_nodes().apply(saved_jvms->map());
4891     set_jvms(saved_jvms);
4892     _reexecute_sp = saved_reexecute_sp;
4893 
4894     // Remove the allocation from above the guards
4895     CallProjections callprojs;
4896     alloc->extract_projections(&callprojs, true);
4897     InitializeNode* init = alloc->initialization();
4898     Node* alloc_mem = alloc->in(TypeFunc::Memory);
4899     C->gvn_replace_by(callprojs.fallthrough_ioproj, alloc->in(TypeFunc::I_O));
4900     C->gvn_replace_by(init->proj_out(TypeFunc::Memory), alloc_mem);
4901     C->gvn_replace_by(init->proj_out(TypeFunc::Control), alloc->in(0));
4902 
4903     // move the allocation here (after the guards)
4904     _gvn.hash_delete(alloc);
4905     alloc->set_req(TypeFunc::Control, control());
4906     alloc->set_req(TypeFunc::I_O, i_o());
4907     Node *mem = reset_memory();
4908     set_all_memory(mem);
4909     alloc->set_req(TypeFunc::Memory, mem);
4910     set_control(init->proj_out(TypeFunc::Control));
4911     set_i_o(callprojs.fallthrough_ioproj);
4912 
4913     // Update memory as done in GraphKit::set_output_for_allocation()
4914     const TypeInt* length_type = _gvn.find_int_type(alloc->in(AllocateNode::ALength));
4915     const TypeOopPtr* ary_type = _gvn.type(alloc->in(AllocateNode::KlassNode))->is_klassptr()->as_instance_type();
4916     if (ary_type->isa_aryptr() && length_type != NULL) {
4917       ary_type = ary_type->is_aryptr()->cast_to_size(length_type);
4918     }
4919     const TypePtr* telemref = ary_type->add_offset(Type::OffsetBot);
4920     int            elemidx  = C->get_alias_index(telemref);
4921     set_memory(init->proj_out(TypeFunc::Memory), Compile::AliasIdxRaw);
4922     set_memory(init->proj_out(TypeFunc::Memory), elemidx);
4923 
4924     Node* allocx = _gvn.transform(alloc);
4925     assert(allocx == alloc, "where has the allocation gone?");
4926     assert(dest->is_CheckCastPP(), "not an allocation result?");
4927 
4928     _gvn.hash_delete(dest);
4929     dest->set_req(0, control());
4930     Node* destx = _gvn.transform(dest);
4931     assert(destx == dest, "where has the allocation result gone?");
4932   }
4933 }
4934 
4935 
4936 //------------------------------inline_arraycopy-----------------------
4937 // public static native void java.lang.System.arraycopy(Object src,  int  srcPos,
4938 //                                                      Object dest, int destPos,
4939 //                                                      int length);
4940 bool LibraryCallKit::inline_arraycopy() {
4941   // Get the arguments.
4942   Node* src         = argument(0);  // type: oop
4943   Node* src_offset  = argument(1);  // type: int
4944   Node* dest        = argument(2);  // type: oop
4945   Node* dest_offset = argument(3);  // type: int
4946   Node* length      = argument(4);  // type: int
4947 
4948 
4949   // Check for allocation before we add nodes that would confuse
4950   // tightly_coupled_allocation()
4951   AllocateArrayNode* alloc = tightly_coupled_allocation(dest, NULL);
4952 
4953   int saved_reexecute_sp = -1;
4954   JVMState* saved_jvms = arraycopy_restore_alloc_state(alloc, saved_reexecute_sp);
4955   // See arraycopy_restore_alloc_state() comment
4956   // if alloc == NULL we don't have to worry about a tightly coupled allocation so we can emit all needed guards
4957   // if saved_jvms != NULL (then alloc != NULL) then we can handle guards and a tightly coupled allocation
4958   // if saved_jvms == NULL and alloc != NULL, we can’t emit any guards
4959   bool can_emit_guards = (alloc == NULL || saved_jvms != NULL);
4960 
4961   // The following tests must be performed
4962   // (1) src and dest are arrays.
4963   // (2) src and dest arrays must have elements of the same BasicType
4964   // (3) src and dest must not be null.
4965   // (4) src_offset must not be negative.
4966   // (5) dest_offset must not be negative.
4967   // (6) length must not be negative.
4968   // (7) src_offset + length must not exceed length of src.
4969   // (8) dest_offset + length must not exceed length of dest.
4970   // (9) each element of an oop array must be assignable
4971 
4972   // (3) src and dest must not be null.
4973   // always do this here because we need the JVM state for uncommon traps
4974   Node* null_ctl = top();
4975   src  = saved_jvms != NULL ? null_check_oop(src, &null_ctl, true, true) : null_check(src,  T_ARRAY);
4976   assert(null_ctl->is_top(), "no null control here");
4977   dest = null_check(dest, T_ARRAY);
4978 
4979   if (!can_emit_guards) {
4980     // if saved_jvms == NULL and alloc != NULL, we don't emit any
4981     // guards but the arraycopy node could still take advantage of a
4982     // tightly allocated allocation. tightly_coupled_allocation() is
4983     // called again to make sure it takes the null check above into
4984     // account: the null check is mandatory and if it caused an
4985     // uncommon trap to be emitted then the allocation can't be
4986     // considered tightly coupled in this context.
4987     alloc = tightly_coupled_allocation(dest, NULL);
4988   }
4989 
4990   bool validated = false;
4991 
4992   const Type* src_type  = _gvn.type(src);
4993   const Type* dest_type = _gvn.type(dest);
4994   const TypeAryPtr* top_src  = src_type->isa_aryptr();
4995   const TypeAryPtr* top_dest = dest_type->isa_aryptr();
4996 
4997   // Do we have the type of src?
4998   bool has_src = (top_src != NULL && top_src->klass() != NULL);
4999   // Do we have the type of dest?
5000   bool has_dest = (top_dest != NULL && top_dest->klass() != NULL);
5001   // Is the type for src from speculation?
5002   bool src_spec = false;
5003   // Is the type for dest from speculation?
5004   bool dest_spec = false;
5005 
5006   if ((!has_src || !has_dest) && can_emit_guards) {
5007     // We don't have sufficient type information, let's see if
5008     // speculative types can help. We need to have types for both src
5009     // and dest so that it pays off.
5010 
5011     // Do we already have or could we have type information for src
5012     bool could_have_src = has_src;
5013     // Do we already have or could we have type information for dest
5014     bool could_have_dest = has_dest;
5015 
5016     ciKlass* src_k = NULL;
5017     if (!has_src) {
5018       src_k = src_type->speculative_type_not_null();
5019       if (src_k != NULL && src_k->is_array_klass()) {
5020         could_have_src = true;
5021       }
5022     }
5023 
5024     ciKlass* dest_k = NULL;
5025     if (!has_dest) {
5026       dest_k = dest_type->speculative_type_not_null();
5027       if (dest_k != NULL && dest_k->is_array_klass()) {
5028         could_have_dest = true;
5029       }
5030     }
5031 
5032     if (could_have_src && could_have_dest) {
5033       // This is going to pay off so emit the required guards
5034       if (!has_src) {
5035         src = maybe_cast_profiled_obj(src, src_k, true);
5036         src_type  = _gvn.type(src);
5037         top_src  = src_type->isa_aryptr();
5038         has_src = (top_src != NULL && top_src->klass() != NULL);
5039         src_spec = true;
5040       }
5041       if (!has_dest) {
5042         dest = maybe_cast_profiled_obj(dest, dest_k, true);
5043         dest_type  = _gvn.type(dest);
5044         top_dest  = dest_type->isa_aryptr();
5045         has_dest = (top_dest != NULL && top_dest->klass() != NULL);
5046         dest_spec = true;
5047       }
5048     }
5049   }
5050 
5051   if (has_src && has_dest && can_emit_guards) {
5052     BasicType src_elem  = top_src->klass()->as_array_klass()->element_type()->basic_type();
5053     BasicType dest_elem = top_dest->klass()->as_array_klass()->element_type()->basic_type();
5054     if (src_elem  == T_ARRAY)  src_elem  = T_OBJECT;
5055     if (dest_elem == T_ARRAY)  dest_elem = T_OBJECT;
5056 
5057     if (src_elem == dest_elem && src_elem == T_OBJECT) {
5058       // If both arrays are object arrays then having the exact types
5059       // for both will remove the need for a subtype check at runtime
5060       // before the call and may make it possible to pick a faster copy
5061       // routine (without a subtype check on every element)
5062       // Do we have the exact type of src?
5063       bool could_have_src = src_spec;
5064       // Do we have the exact type of dest?
5065       bool could_have_dest = dest_spec;
5066       ciKlass* src_k = top_src->klass();
5067       ciKlass* dest_k = top_dest->klass();
5068       if (!src_spec) {
5069         src_k = src_type->speculative_type_not_null();
5070         if (src_k != NULL && src_k->is_array_klass()) {
5071           could_have_src = true;
5072         }
5073       }
5074       if (!dest_spec) {
5075         dest_k = dest_type->speculative_type_not_null();
5076         if (dest_k != NULL && dest_k->is_array_klass()) {
5077           could_have_dest = true;
5078         }
5079       }
5080       if (could_have_src && could_have_dest) {
5081         // If we can have both exact types, emit the missing guards
5082         if (could_have_src && !src_spec) {
5083           src = maybe_cast_profiled_obj(src, src_k, true);
5084         }
5085         if (could_have_dest && !dest_spec) {
5086           dest = maybe_cast_profiled_obj(dest, dest_k, true);
5087         }
5088       }
5089     }
5090   }
5091 
5092   ciMethod* trap_method = method();
5093   int trap_bci = bci();
5094   if (saved_jvms != NULL) {
5095     trap_method = alloc->jvms()->method();
5096     trap_bci = alloc->jvms()->bci();
5097   }
5098 
5099   if (!C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_intrinsic) &&
5100       can_emit_guards &&
5101       !src->is_top() && !dest->is_top()) {
5102     // validate arguments: enables transformation the ArrayCopyNode
5103     validated = true;
5104 
5105     RegionNode* slow_region = new RegionNode(1);
5106     record_for_igvn(slow_region);
5107 
5108     // (1) src and dest are arrays.
5109     generate_non_array_guard(load_object_klass(src), slow_region);
5110     generate_non_array_guard(load_object_klass(dest), slow_region);
5111 
5112     // (2) src and dest arrays must have elements of the same BasicType
5113     // done at macro expansion or at Ideal transformation time
5114 
5115     // (4) src_offset must not be negative.
5116     generate_negative_guard(src_offset, slow_region);
5117 
5118     // (5) dest_offset must not be negative.
5119     generate_negative_guard(dest_offset, slow_region);
5120 
5121     // (7) src_offset + length must not exceed length of src.
5122     generate_limit_guard(src_offset, length,
5123                          load_array_length(src),
5124                          slow_region);
5125 
5126     // (8) dest_offset + length must not exceed length of dest.
5127     generate_limit_guard(dest_offset, length,
5128                          load_array_length(dest),
5129                          slow_region);
5130 
5131     // (9) each element of an oop array must be assignable
5132     Node* src_klass  = load_object_klass(src);
5133     Node* dest_klass = load_object_klass(dest);
5134     Node* not_subtype_ctrl = gen_subtype_check(src_klass, dest_klass);
5135 
5136     if (not_subtype_ctrl != top()) {
5137       PreserveJVMState pjvms(this);
5138       set_control(not_subtype_ctrl);
5139       uncommon_trap(Deoptimization::Reason_intrinsic,
5140                     Deoptimization::Action_make_not_entrant);
5141       assert(stopped(), "Should be stopped");
5142     }
5143     {
5144       PreserveJVMState pjvms(this);
5145       set_control(_gvn.transform(slow_region));
5146       uncommon_trap(Deoptimization::Reason_intrinsic,
5147                     Deoptimization::Action_make_not_entrant);
5148       assert(stopped(), "Should be stopped");
5149     }
5150   }
5151 
5152   arraycopy_move_allocation_here(alloc, dest, saved_jvms, saved_reexecute_sp);
5153 
5154   if (stopped()) {
5155     return true;
5156   }
5157 
5158   ArrayCopyNode* ac = ArrayCopyNode::make(this, true, src, src_offset, dest, dest_offset, length, alloc != NULL,
5159                                           // Create LoadRange and LoadKlass nodes for use during macro expansion here
5160                                           // so the compiler has a chance to eliminate them: during macro expansion,
5161                                           // we have to set their control (CastPP nodes are eliminated).
5162                                           load_object_klass(src), load_object_klass(dest),
5163                                           load_array_length(src), load_array_length(dest));
5164 
5165   ac->set_arraycopy(validated);
5166 
5167   Node* n = _gvn.transform(ac);
5168   if (n == ac) {
5169     ac->connect_outputs(this);
5170   } else {
5171     assert(validated, "shouldn't transform if all arguments not validated");
5172     set_all_memory(n);
5173   }
5174 
5175   return true;
5176 }
5177 
5178 
5179 // Helper function which determines if an arraycopy immediately follows
5180 // an allocation, with no intervening tests or other escapes for the object.
5181 AllocateArrayNode*
5182 LibraryCallKit::tightly_coupled_allocation(Node* ptr,
5183                                            RegionNode* slow_region) {
5184   if (stopped())             return NULL;  // no fast path
5185   if (C->AliasLevel() == 0)  return NULL;  // no MergeMems around
5186 
5187   AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(ptr, &_gvn);
5188   if (alloc == NULL)  return NULL;
5189 
5190   Node* rawmem = memory(Compile::AliasIdxRaw);
5191   // Is the allocation's memory state untouched?
5192   if (!(rawmem->is_Proj() && rawmem->in(0)->is_Initialize())) {
5193     // Bail out if there have been raw-memory effects since the allocation.
5194     // (Example:  There might have been a call or safepoint.)
5195     return NULL;
5196   }
5197   rawmem = rawmem->in(0)->as_Initialize()->memory(Compile::AliasIdxRaw);
5198   if (!(rawmem->is_Proj() && rawmem->in(0) == alloc)) {
5199     return NULL;
5200   }
5201 
5202   // There must be no unexpected observers of this allocation.
5203   for (DUIterator_Fast imax, i = ptr->fast_outs(imax); i < imax; i++) {
5204     Node* obs = ptr->fast_out(i);
5205     if (obs != this->map()) {
5206       return NULL;
5207     }
5208   }
5209 
5210   // This arraycopy must unconditionally follow the allocation of the ptr.
5211   Node* alloc_ctl = ptr->in(0);
5212   assert(just_allocated_object(alloc_ctl) == ptr, "most recent allo");
5213 
5214   Node* ctl = control();
5215   while (ctl != alloc_ctl) {
5216     // There may be guards which feed into the slow_region.
5217     // Any other control flow means that we might not get a chance
5218     // to finish initializing the allocated object.
5219     if ((ctl->is_IfFalse() || ctl->is_IfTrue()) && ctl->in(0)->is_If()) {
5220       IfNode* iff = ctl->in(0)->as_If();
5221       Node* not_ctl = iff->proj_out(1 - ctl->as_Proj()->_con);
5222       assert(not_ctl != NULL && not_ctl != ctl, "found alternate");
5223       if (slow_region != NULL && slow_region->find_edge(not_ctl) >= 1) {
5224         ctl = iff->in(0);       // This test feeds the known slow_region.
5225         continue;
5226       }
5227       // One more try:  Various low-level checks bottom out in
5228       // uncommon traps.  If the debug-info of the trap omits
5229       // any reference to the allocation, as we've already
5230       // observed, then there can be no objection to the trap.
5231       bool found_trap = false;
5232       for (DUIterator_Fast jmax, j = not_ctl->fast_outs(jmax); j < jmax; j++) {
5233         Node* obs = not_ctl->fast_out(j);
5234         if (obs->in(0) == not_ctl && obs->is_Call() &&
5235             (obs->as_Call()->entry_point() == SharedRuntime::uncommon_trap_blob()->entry_point())) {
5236           found_trap = true; break;
5237         }
5238       }
5239       if (found_trap) {
5240         ctl = iff->in(0);       // This test feeds a harmless uncommon trap.
5241         continue;
5242       }
5243     }
5244     return NULL;
5245   }
5246 
5247   // If we get this far, we have an allocation which immediately
5248   // precedes the arraycopy, and we can take over zeroing the new object.
5249   // The arraycopy will finish the initialization, and provide
5250   // a new control state to which we will anchor the destination pointer.
5251 
5252   return alloc;
5253 }
5254 
5255 //-------------inline_encodeISOArray-----------------------------------
5256 // encode char[] to byte[] in ISO_8859_1
5257 bool LibraryCallKit::inline_encodeISOArray() {
5258   assert(callee()->signature()->size() == 5, "encodeISOArray has 5 parameters");
5259   // no receiver since it is static method
5260   Node *src         = argument(0);
5261   Node *src_offset  = argument(1);
5262   Node *dst         = argument(2);
5263   Node *dst_offset  = argument(3);
5264   Node *length      = argument(4);
5265 
5266   const Type* src_type = src->Value(&_gvn);
5267   const Type* dst_type = dst->Value(&_gvn);
5268   const TypeAryPtr* top_src = src_type->isa_aryptr();
5269   const TypeAryPtr* top_dest = dst_type->isa_aryptr();
5270   if (top_src  == NULL || top_src->klass()  == NULL ||
5271       top_dest == NULL || top_dest->klass() == NULL) {
5272     // failed array check
5273     return false;
5274   }
5275 
5276   // Figure out the size and type of the elements we will be copying.
5277   BasicType src_elem = src_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5278   BasicType dst_elem = dst_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5279   if (src_elem != T_CHAR || dst_elem != T_BYTE) {
5280     return false;
5281   }
5282   Node* src_start = array_element_address(src, src_offset, src_elem);
5283   Node* dst_start = array_element_address(dst, dst_offset, dst_elem);
5284   // 'src_start' points to src array + scaled offset
5285   // 'dst_start' points to dst array + scaled offset
5286 
5287   const TypeAryPtr* mtype = TypeAryPtr::BYTES;
5288   Node* enc = new EncodeISOArrayNode(control(), memory(mtype), src_start, dst_start, length);
5289   enc = _gvn.transform(enc);
5290   Node* res_mem = _gvn.transform(new SCMemProjNode(enc));
5291   set_memory(res_mem, mtype);
5292   set_result(enc);
5293   return true;
5294 }
5295 
5296 //-------------inline_multiplyToLen-----------------------------------
5297 bool LibraryCallKit::inline_multiplyToLen() {
5298   assert(UseMultiplyToLenIntrinsic, "not implemented on this platform");
5299 
5300   address stubAddr = StubRoutines::multiplyToLen();
5301   if (stubAddr == NULL) {
5302     return false; // Intrinsic's stub is not implemented on this platform
5303   }
5304   const char* stubName = "multiplyToLen";
5305 
5306   assert(callee()->signature()->size() == 5, "multiplyToLen has 5 parameters");
5307 
5308   // no receiver because it is a static method
5309   Node* x    = argument(0);
5310   Node* xlen = argument(1);
5311   Node* y    = argument(2);
5312   Node* ylen = argument(3);
5313   Node* z    = argument(4);
5314 
5315   const Type* x_type = x->Value(&_gvn);
5316   const Type* y_type = y->Value(&_gvn);
5317   const TypeAryPtr* top_x = x_type->isa_aryptr();
5318   const TypeAryPtr* top_y = y_type->isa_aryptr();
5319   if (top_x  == NULL || top_x->klass()  == NULL ||
5320       top_y == NULL || top_y->klass() == NULL) {
5321     // failed array check
5322     return false;
5323   }
5324 
5325   BasicType x_elem = x_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5326   BasicType y_elem = y_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5327   if (x_elem != T_INT || y_elem != T_INT) {
5328     return false;
5329   }
5330 
5331   // Set the original stack and the reexecute bit for the interpreter to reexecute
5332   // the bytecode that invokes BigInteger.multiplyToLen() if deoptimization happens
5333   // on the return from z array allocation in runtime.
5334   { PreserveReexecuteState preexecs(this);
5335     jvms()->set_should_reexecute(true);
5336 
5337     Node* x_start = array_element_address(x, intcon(0), x_elem);
5338     Node* y_start = array_element_address(y, intcon(0), y_elem);
5339     // 'x_start' points to x array + scaled xlen
5340     // 'y_start' points to y array + scaled ylen
5341 
5342     // Allocate the result array
5343     Node* zlen = _gvn.transform(new AddINode(xlen, ylen));
5344     ciKlass* klass = ciTypeArrayKlass::make(T_INT);
5345     Node* klass_node = makecon(TypeKlassPtr::make(klass));
5346 
5347     IdealKit ideal(this);
5348 
5349 #define __ ideal.
5350      Node* one = __ ConI(1);
5351      Node* zero = __ ConI(0);
5352      IdealVariable need_alloc(ideal), z_alloc(ideal);  __ declarations_done();
5353      __ set(need_alloc, zero);
5354      __ set(z_alloc, z);
5355      __ if_then(z, BoolTest::eq, null()); {
5356        __ increment (need_alloc, one);
5357      } __ else_(); {
5358        // Update graphKit memory and control from IdealKit.
5359        sync_kit(ideal);
5360        Node* zlen_arg = load_array_length(z);
5361        // Update IdealKit memory and control from graphKit.
5362        __ sync_kit(this);
5363        __ if_then(zlen_arg, BoolTest::lt, zlen); {
5364          __ increment (need_alloc, one);
5365        } __ end_if();
5366      } __ end_if();
5367 
5368      __ if_then(__ value(need_alloc), BoolTest::ne, zero); {
5369        // Update graphKit memory and control from IdealKit.
5370        sync_kit(ideal);
5371        Node * narr = new_array(klass_node, zlen, 1);
5372        // Update IdealKit memory and control from graphKit.
5373        __ sync_kit(this);
5374        __ set(z_alloc, narr);
5375      } __ end_if();
5376 
5377      sync_kit(ideal);
5378      z = __ value(z_alloc);
5379      // Can't use TypeAryPtr::INTS which uses Bottom offset.
5380      _gvn.set_type(z, TypeOopPtr::make_from_klass(klass));
5381      // Final sync IdealKit and GraphKit.
5382      final_sync(ideal);
5383 #undef __
5384 
5385     Node* z_start = array_element_address(z, intcon(0), T_INT);
5386 
5387     Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
5388                                    OptoRuntime::multiplyToLen_Type(),
5389                                    stubAddr, stubName, TypePtr::BOTTOM,
5390                                    x_start, xlen, y_start, ylen, z_start, zlen);
5391   } // original reexecute is set back here
5392 
5393   C->set_has_split_ifs(true); // Has chance for split-if optimization
5394   set_result(z);
5395   return true;
5396 }
5397 
5398 //-------------inline_squareToLen------------------------------------
5399 bool LibraryCallKit::inline_squareToLen() {
5400   assert(UseSquareToLenIntrinsic, "not implementated on this platform");
5401 
5402   address stubAddr = StubRoutines::squareToLen();
5403   if (stubAddr == NULL) {
5404     return false; // Intrinsic's stub is not implemented on this platform
5405   }
5406   const char* stubName = "squareToLen";
5407 
5408   assert(callee()->signature()->size() == 4, "implSquareToLen has 4 parameters");
5409 
5410   Node* x    = argument(0);
5411   Node* len  = argument(1);
5412   Node* z    = argument(2);
5413   Node* zlen = argument(3);
5414 
5415   const Type* x_type = x->Value(&_gvn);
5416   const Type* z_type = z->Value(&_gvn);
5417   const TypeAryPtr* top_x = x_type->isa_aryptr();
5418   const TypeAryPtr* top_z = z_type->isa_aryptr();
5419   if (top_x  == NULL || top_x->klass()  == NULL ||
5420       top_z  == NULL || top_z->klass()  == NULL) {
5421     // failed array check
5422     return false;
5423   }
5424 
5425   BasicType x_elem = x_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5426   BasicType z_elem = z_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5427   if (x_elem != T_INT || z_elem != T_INT) {
5428     return false;
5429   }
5430 
5431 
5432   Node* x_start = array_element_address(x, intcon(0), x_elem);
5433   Node* z_start = array_element_address(z, intcon(0), z_elem);
5434 
5435   Node*  call = make_runtime_call(RC_LEAF|RC_NO_FP,
5436                                   OptoRuntime::squareToLen_Type(),
5437                                   stubAddr, stubName, TypePtr::BOTTOM,
5438                                   x_start, len, z_start, zlen);
5439 
5440   set_result(z);
5441   return true;
5442 }
5443 
5444 //-------------inline_mulAdd------------------------------------------
5445 bool LibraryCallKit::inline_mulAdd() {
5446   assert(UseMulAddIntrinsic, "not implementated on this platform");
5447 
5448   address stubAddr = StubRoutines::mulAdd();
5449   if (stubAddr == NULL) {
5450     return false; // Intrinsic's stub is not implemented on this platform
5451   }
5452   const char* stubName = "mulAdd";
5453 
5454   assert(callee()->signature()->size() == 5, "mulAdd has 5 parameters");
5455 
5456   Node* out      = argument(0);
5457   Node* in       = argument(1);
5458   Node* offset   = argument(2);
5459   Node* len      = argument(3);
5460   Node* k        = argument(4);
5461 
5462   const Type* out_type = out->Value(&_gvn);
5463   const Type* in_type = in->Value(&_gvn);
5464   const TypeAryPtr* top_out = out_type->isa_aryptr();
5465   const TypeAryPtr* top_in = in_type->isa_aryptr();
5466   if (top_out  == NULL || top_out->klass()  == NULL ||
5467       top_in == NULL || top_in->klass() == NULL) {
5468     // failed array check
5469     return false;
5470   }
5471 
5472   BasicType out_elem = out_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5473   BasicType in_elem = in_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5474   if (out_elem != T_INT || in_elem != T_INT) {
5475     return false;
5476   }
5477 
5478   Node* outlen = load_array_length(out);
5479   Node* new_offset = _gvn.transform(new SubINode(outlen, offset));
5480   Node* out_start = array_element_address(out, intcon(0), out_elem);
5481   Node* in_start = array_element_address(in, intcon(0), in_elem);
5482 
5483   Node*  call = make_runtime_call(RC_LEAF|RC_NO_FP,
5484                                   OptoRuntime::mulAdd_Type(),
5485                                   stubAddr, stubName, TypePtr::BOTTOM,
5486                                   out_start,in_start, new_offset, len, k);
5487   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
5488   set_result(result);
5489   return true;
5490 }
5491 
5492 //-------------inline_montgomeryMultiply-----------------------------------
5493 bool LibraryCallKit::inline_montgomeryMultiply() {
5494   address stubAddr = StubRoutines::montgomeryMultiply();
5495   if (stubAddr == NULL) {
5496     return false; // Intrinsic's stub is not implemented on this platform
5497   }
5498 
5499   assert(UseMontgomeryMultiplyIntrinsic, "not implemented on this platform");
5500   const char* stubName = "montgomery_square";
5501 
5502   assert(callee()->signature()->size() == 7, "montgomeryMultiply has 7 parameters");
5503 
5504   Node* a    = argument(0);
5505   Node* b    = argument(1);
5506   Node* n    = argument(2);
5507   Node* len  = argument(3);
5508   Node* inv  = argument(4);
5509   Node* m    = argument(6);
5510 
5511   const Type* a_type = a->Value(&_gvn);
5512   const TypeAryPtr* top_a = a_type->isa_aryptr();
5513   const Type* b_type = b->Value(&_gvn);
5514   const TypeAryPtr* top_b = b_type->isa_aryptr();
5515   const Type* n_type = a->Value(&_gvn);
5516   const TypeAryPtr* top_n = n_type->isa_aryptr();
5517   const Type* m_type = a->Value(&_gvn);
5518   const TypeAryPtr* top_m = m_type->isa_aryptr();
5519   if (top_a  == NULL || top_a->klass()  == NULL ||
5520       top_b == NULL || top_b->klass()  == NULL ||
5521       top_n == NULL || top_n->klass()  == NULL ||
5522       top_m == NULL || top_m->klass()  == NULL) {
5523     // failed array check
5524     return false;
5525   }
5526 
5527   BasicType a_elem = a_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5528   BasicType b_elem = b_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5529   BasicType n_elem = n_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5530   BasicType m_elem = m_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5531   if (a_elem != T_INT || b_elem != T_INT || n_elem != T_INT || m_elem != T_INT) {
5532     return false;
5533   }
5534 
5535   // Make the call
5536   {
5537     Node* a_start = array_element_address(a, intcon(0), a_elem);
5538     Node* b_start = array_element_address(b, intcon(0), b_elem);
5539     Node* n_start = array_element_address(n, intcon(0), n_elem);
5540     Node* m_start = array_element_address(m, intcon(0), m_elem);
5541 
5542     Node* call = make_runtime_call(RC_LEAF,
5543                                    OptoRuntime::montgomeryMultiply_Type(),
5544                                    stubAddr, stubName, TypePtr::BOTTOM,
5545                                    a_start, b_start, n_start, len, inv, top(),
5546                                    m_start);
5547     set_result(m);
5548   }
5549 
5550   return true;
5551 }
5552 
5553 bool LibraryCallKit::inline_montgomerySquare() {
5554   address stubAddr = StubRoutines::montgomerySquare();
5555   if (stubAddr == NULL) {
5556     return false; // Intrinsic's stub is not implemented on this platform
5557   }
5558 
5559   assert(UseMontgomerySquareIntrinsic, "not implemented on this platform");
5560   const char* stubName = "montgomery_square";
5561 
5562   assert(callee()->signature()->size() == 6, "montgomerySquare has 6 parameters");
5563 
5564   Node* a    = argument(0);
5565   Node* n    = argument(1);
5566   Node* len  = argument(2);
5567   Node* inv  = argument(3);
5568   Node* m    = argument(5);
5569 
5570   const Type* a_type = a->Value(&_gvn);
5571   const TypeAryPtr* top_a = a_type->isa_aryptr();
5572   const Type* n_type = a->Value(&_gvn);
5573   const TypeAryPtr* top_n = n_type->isa_aryptr();
5574   const Type* m_type = a->Value(&_gvn);
5575   const TypeAryPtr* top_m = m_type->isa_aryptr();
5576   if (top_a  == NULL || top_a->klass()  == NULL ||
5577       top_n == NULL || top_n->klass()  == NULL ||
5578       top_m == NULL || top_m->klass()  == NULL) {
5579     // failed array check
5580     return false;
5581   }
5582 
5583   BasicType a_elem = a_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5584   BasicType n_elem = n_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5585   BasicType m_elem = m_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5586   if (a_elem != T_INT || n_elem != T_INT || m_elem != T_INT) {
5587     return false;
5588   }
5589 
5590   // Make the call
5591   {
5592     Node* a_start = array_element_address(a, intcon(0), a_elem);
5593     Node* n_start = array_element_address(n, intcon(0), n_elem);
5594     Node* m_start = array_element_address(m, intcon(0), m_elem);
5595 
5596     Node* call = make_runtime_call(RC_LEAF,
5597                                    OptoRuntime::montgomerySquare_Type(),
5598                                    stubAddr, stubName, TypePtr::BOTTOM,
5599                                    a_start, n_start, len, inv, top(),
5600                                    m_start);
5601     set_result(m);
5602   }
5603 
5604   return true;
5605 }
5606 
5607 
5608 /**
5609  * Calculate CRC32 for byte.
5610  * int java.util.zip.CRC32.update(int crc, int b)
5611  */
5612 bool LibraryCallKit::inline_updateCRC32() {
5613   assert(UseCRC32Intrinsics, "need AVX and LCMUL instructions support");
5614   assert(callee()->signature()->size() == 2, "update has 2 parameters");
5615   // no receiver since it is static method
5616   Node* crc  = argument(0); // type: int
5617   Node* b    = argument(1); // type: int
5618 
5619   /*
5620    *    int c = ~ crc;
5621    *    b = timesXtoThe32[(b ^ c) & 0xFF];
5622    *    b = b ^ (c >>> 8);
5623    *    crc = ~b;
5624    */
5625 
5626   Node* M1 = intcon(-1);
5627   crc = _gvn.transform(new XorINode(crc, M1));
5628   Node* result = _gvn.transform(new XorINode(crc, b));
5629   result = _gvn.transform(new AndINode(result, intcon(0xFF)));
5630 
5631   Node* base = makecon(TypeRawPtr::make(StubRoutines::crc_table_addr()));
5632   Node* offset = _gvn.transform(new LShiftINode(result, intcon(0x2)));
5633   Node* adr = basic_plus_adr(top(), base, ConvI2X(offset));
5634   result = make_load(control(), adr, TypeInt::INT, T_INT, MemNode::unordered);
5635 
5636   crc = _gvn.transform(new URShiftINode(crc, intcon(8)));
5637   result = _gvn.transform(new XorINode(crc, result));
5638   result = _gvn.transform(new XorINode(result, M1));
5639   set_result(result);
5640   return true;
5641 }
5642 
5643 /**
5644  * Calculate CRC32 for byte[] array.
5645  * int java.util.zip.CRC32.updateBytes(int crc, byte[] buf, int off, int len)
5646  */
5647 bool LibraryCallKit::inline_updateBytesCRC32() {
5648   assert(UseCRC32Intrinsics, "need AVX and LCMUL instructions support");
5649   assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
5650   // no receiver since it is static method
5651   Node* crc     = argument(0); // type: int
5652   Node* src     = argument(1); // type: oop
5653   Node* offset  = argument(2); // type: int
5654   Node* length  = argument(3); // type: int
5655 
5656   const Type* src_type = src->Value(&_gvn);
5657   const TypeAryPtr* top_src = src_type->isa_aryptr();
5658   if (top_src  == NULL || top_src->klass()  == NULL) {
5659     // failed array check
5660     return false;
5661   }
5662 
5663   // Figure out the size and type of the elements we will be copying.
5664   BasicType src_elem = src_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5665   if (src_elem != T_BYTE) {
5666     return false;
5667   }
5668 
5669   // 'src_start' points to src array + scaled offset
5670   Node* src_start = array_element_address(src, offset, src_elem);
5671 
5672   // We assume that range check is done by caller.
5673   // TODO: generate range check (offset+length < src.length) in debug VM.
5674 
5675   // Call the stub.
5676   address stubAddr = StubRoutines::updateBytesCRC32();
5677   const char *stubName = "updateBytesCRC32";
5678 
5679   Node* call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::updateBytesCRC32_Type(),
5680                                  stubAddr, stubName, TypePtr::BOTTOM,
5681                                  crc, src_start, length);
5682   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
5683   set_result(result);
5684   return true;
5685 }
5686 
5687 /**
5688  * Calculate CRC32 for ByteBuffer.
5689  * int java.util.zip.CRC32.updateByteBuffer(int crc, long buf, int off, int len)
5690  */
5691 bool LibraryCallKit::inline_updateByteBufferCRC32() {
5692   assert(UseCRC32Intrinsics, "need AVX and LCMUL instructions support");
5693   assert(callee()->signature()->size() == 5, "updateByteBuffer has 4 parameters and one is long");
5694   // no receiver since it is static method
5695   Node* crc     = argument(0); // type: int
5696   Node* src     = argument(1); // type: long
5697   Node* offset  = argument(3); // type: int
5698   Node* length  = argument(4); // type: int
5699 
5700   src = ConvL2X(src);  // adjust Java long to machine word
5701   Node* base = _gvn.transform(new CastX2PNode(src));
5702   offset = ConvI2X(offset);
5703 
5704   // 'src_start' points to src array + scaled offset
5705   Node* src_start = basic_plus_adr(top(), base, offset);
5706 
5707   // Call the stub.
5708   address stubAddr = StubRoutines::updateBytesCRC32();
5709   const char *stubName = "updateBytesCRC32";
5710 
5711   Node* call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::updateBytesCRC32_Type(),
5712                                  stubAddr, stubName, TypePtr::BOTTOM,
5713                                  crc, src_start, length);
5714   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
5715   set_result(result);
5716   return true;
5717 }
5718 
5719 //------------------------------get_table_from_crc32c_class-----------------------
5720 Node * LibraryCallKit::get_table_from_crc32c_class(ciInstanceKlass *crc32c_class) {
5721   Node* table = load_field_from_object(NULL, "byteTable", "[I", /*is_exact*/ false, /*is_static*/ true, crc32c_class);
5722   assert (table != NULL, "wrong version of java.util.zip.CRC32C");
5723 
5724   return table;
5725 }
5726 
5727 //------------------------------inline_updateBytesCRC32C-----------------------
5728 //
5729 // Calculate CRC32C for byte[] array.
5730 // int java.util.zip.CRC32C.updateBytes(int crc, byte[] buf, int off, int end)
5731 //
5732 bool LibraryCallKit::inline_updateBytesCRC32C() {
5733   assert(UseCRC32CIntrinsics, "need CRC32C instruction support");
5734   assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
5735   assert(callee()->holder()->is_loaded(), "CRC32C class must be loaded");
5736   // no receiver since it is a static method
5737   Node* crc     = argument(0); // type: int
5738   Node* src     = argument(1); // type: oop
5739   Node* offset  = argument(2); // type: int
5740   Node* end     = argument(3); // type: int
5741 
5742   Node* length = _gvn.transform(new SubINode(end, offset));
5743 
5744   const Type* src_type = src->Value(&_gvn);
5745   const TypeAryPtr* top_src = src_type->isa_aryptr();
5746   if (top_src  == NULL || top_src->klass()  == NULL) {
5747     // failed array check
5748     return false;
5749   }
5750 
5751   // Figure out the size and type of the elements we will be copying.
5752   BasicType src_elem = src_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5753   if (src_elem != T_BYTE) {
5754     return false;
5755   }
5756 
5757   // 'src_start' points to src array + scaled offset
5758   Node* src_start = array_element_address(src, offset, src_elem);
5759 
5760   // static final int[] byteTable in class CRC32C
5761   Node* table = get_table_from_crc32c_class(callee()->holder());
5762   Node* table_start = array_element_address(table, intcon(0), T_INT);
5763 
5764   // We assume that range check is done by caller.
5765   // TODO: generate range check (offset+length < src.length) in debug VM.
5766 
5767   // Call the stub.
5768   address stubAddr = StubRoutines::updateBytesCRC32C();
5769   const char *stubName = "updateBytesCRC32C";
5770 
5771   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesCRC32C_Type(),
5772                                  stubAddr, stubName, TypePtr::BOTTOM,
5773                                  crc, src_start, length, table_start);
5774   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
5775   set_result(result);
5776   return true;
5777 }
5778 
5779 //------------------------------inline_updateDirectByteBufferCRC32C-----------------------
5780 //
5781 // Calculate CRC32C for DirectByteBuffer.
5782 // int java.util.zip.CRC32C.updateDirectByteBuffer(int crc, long buf, int off, int end)
5783 //
5784 bool LibraryCallKit::inline_updateDirectByteBufferCRC32C() {
5785   assert(UseCRC32CIntrinsics, "need CRC32C instruction support");
5786   assert(callee()->signature()->size() == 5, "updateDirectByteBuffer has 4 parameters and one is long");
5787   assert(callee()->holder()->is_loaded(), "CRC32C class must be loaded");
5788   // no receiver since it is a static method
5789   Node* crc     = argument(0); // type: int
5790   Node* src     = argument(1); // type: long
5791   Node* offset  = argument(3); // type: int
5792   Node* end     = argument(4); // type: int
5793 
5794   Node* length = _gvn.transform(new SubINode(end, offset));
5795 
5796   src = ConvL2X(src);  // adjust Java long to machine word
5797   Node* base = _gvn.transform(new CastX2PNode(src));
5798   offset = ConvI2X(offset);
5799 
5800   // 'src_start' points to src array + scaled offset
5801   Node* src_start = basic_plus_adr(top(), base, offset);
5802 
5803   // static final int[] byteTable in class CRC32C
5804   Node* table = get_table_from_crc32c_class(callee()->holder());
5805   Node* table_start = array_element_address(table, intcon(0), T_INT);
5806 
5807   // Call the stub.
5808   address stubAddr = StubRoutines::updateBytesCRC32C();
5809   const char *stubName = "updateBytesCRC32C";
5810 
5811   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesCRC32C_Type(),
5812                                  stubAddr, stubName, TypePtr::BOTTOM,
5813                                  crc, src_start, length, table_start);
5814   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
5815   set_result(result);
5816   return true;
5817 }
5818 
5819 //----------------------------inline_reference_get----------------------------
5820 // public T java.lang.ref.Reference.get();
5821 bool LibraryCallKit::inline_reference_get() {
5822   const int referent_offset = java_lang_ref_Reference::referent_offset;
5823   guarantee(referent_offset > 0, "should have already been set");
5824 
5825   // Get the argument:
5826   Node* reference_obj = null_check_receiver();
5827   if (stopped()) return true;
5828 
5829   Node* adr = basic_plus_adr(reference_obj, reference_obj, referent_offset);
5830 
5831   ciInstanceKlass* klass = env()->Object_klass();
5832   const TypeOopPtr* object_type = TypeOopPtr::make_from_klass(klass);
5833 
5834   Node* no_ctrl = NULL;
5835   Node* result = make_load(no_ctrl, adr, object_type, T_OBJECT, MemNode::unordered);
5836 
5837   // Use the pre-barrier to record the value in the referent field
5838   pre_barrier(false /* do_load */,
5839               control(),
5840               NULL /* obj */, NULL /* adr */, max_juint /* alias_idx */, NULL /* val */, NULL /* val_type */,
5841               result /* pre_val */,
5842               T_OBJECT);
5843 
5844   // Add memory barrier to prevent commoning reads from this field
5845   // across safepoint since GC can change its value.
5846   insert_mem_bar(Op_MemBarCPUOrder);
5847 
5848   set_result(result);
5849   return true;
5850 }
5851 
5852 
5853 Node * LibraryCallKit::load_field_from_object(Node * fromObj, const char * fieldName, const char * fieldTypeString,
5854                                               bool is_exact=true, bool is_static=false,
5855                                               ciInstanceKlass * fromKls=NULL) {
5856   if (fromKls == NULL) {
5857     const TypeInstPtr* tinst = _gvn.type(fromObj)->isa_instptr();
5858     assert(tinst != NULL, "obj is null");
5859     assert(tinst->klass()->is_loaded(), "obj is not loaded");
5860     assert(!is_exact || tinst->klass_is_exact(), "klass not exact");
5861     fromKls = tinst->klass()->as_instance_klass();
5862   } else {
5863     assert(is_static, "only for static field access");
5864   }
5865   ciField* field = fromKls->get_field_by_name(ciSymbol::make(fieldName),
5866                                               ciSymbol::make(fieldTypeString),
5867                                               is_static);
5868 
5869   assert (field != NULL, "undefined field");
5870   if (field == NULL) return (Node *) NULL;
5871 
5872   if (is_static) {
5873     const TypeInstPtr* tip = TypeInstPtr::make(fromKls->java_mirror());
5874     fromObj = makecon(tip);
5875   }
5876 
5877   // Next code  copied from Parse::do_get_xxx():
5878 
5879   // Compute address and memory type.
5880   int offset  = field->offset_in_bytes();
5881   bool is_vol = field->is_volatile();
5882   ciType* field_klass = field->type();
5883   assert(field_klass->is_loaded(), "should be loaded");
5884   const TypePtr* adr_type = C->alias_type(field)->adr_type();
5885   Node *adr = basic_plus_adr(fromObj, fromObj, offset);
5886   BasicType bt = field->layout_type();
5887 
5888   // Build the resultant type of the load
5889   const Type *type;
5890   if (bt == T_OBJECT) {
5891     type = TypeOopPtr::make_from_klass(field_klass->as_klass());
5892   } else {
5893     type = Type::get_const_basic_type(bt);
5894   }
5895 
5896   if (support_IRIW_for_not_multiple_copy_atomic_cpu && is_vol) {
5897     insert_mem_bar(Op_MemBarVolatile);   // StoreLoad barrier
5898   }
5899   // Build the load.
5900   MemNode::MemOrd mo = is_vol ? MemNode::acquire : MemNode::unordered;
5901   Node* loadedField = make_load(NULL, adr, type, bt, adr_type, mo, LoadNode::DependsOnlyOnTest, is_vol);
5902   // If reference is volatile, prevent following memory ops from
5903   // floating up past the volatile read.  Also prevents commoning
5904   // another volatile read.
5905   if (is_vol) {
5906     // Memory barrier includes bogus read of value to force load BEFORE membar
5907     insert_mem_bar(Op_MemBarAcquire, loadedField);
5908   }
5909   return loadedField;
5910 }
5911 
5912 
5913 //------------------------------inline_aescrypt_Block-----------------------
5914 bool LibraryCallKit::inline_aescrypt_Block(vmIntrinsics::ID id) {
5915   address stubAddr;
5916   const char *stubName;
5917   assert(UseAES, "need AES instruction support");
5918 
5919   switch(id) {
5920   case vmIntrinsics::_aescrypt_encryptBlock:
5921     stubAddr = StubRoutines::aescrypt_encryptBlock();
5922     stubName = "aescrypt_encryptBlock";
5923     break;
5924   case vmIntrinsics::_aescrypt_decryptBlock:
5925     stubAddr = StubRoutines::aescrypt_decryptBlock();
5926     stubName = "aescrypt_decryptBlock";
5927     break;
5928   }
5929   if (stubAddr == NULL) return false;
5930 
5931   Node* aescrypt_object = argument(0);
5932   Node* src             = argument(1);
5933   Node* src_offset      = argument(2);
5934   Node* dest            = argument(3);
5935   Node* dest_offset     = argument(4);
5936 
5937   // (1) src and dest are arrays.
5938   const Type* src_type = src->Value(&_gvn);
5939   const Type* dest_type = dest->Value(&_gvn);
5940   const TypeAryPtr* top_src = src_type->isa_aryptr();
5941   const TypeAryPtr* top_dest = dest_type->isa_aryptr();
5942   assert (top_src  != NULL && top_src->klass()  != NULL &&  top_dest != NULL && top_dest->klass() != NULL, "args are strange");
5943 
5944   // for the quick and dirty code we will skip all the checks.
5945   // we are just trying to get the call to be generated.
5946   Node* src_start  = src;
5947   Node* dest_start = dest;
5948   if (src_offset != NULL || dest_offset != NULL) {
5949     assert(src_offset != NULL && dest_offset != NULL, "");
5950     src_start  = array_element_address(src,  src_offset,  T_BYTE);
5951     dest_start = array_element_address(dest, dest_offset, T_BYTE);
5952   }
5953 
5954   // now need to get the start of its expanded key array
5955   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
5956   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object);
5957   if (k_start == NULL) return false;
5958 
5959   if (Matcher::pass_original_key_for_aes()) {
5960     // on SPARC we need to pass the original key since key expansion needs to happen in intrinsics due to
5961     // compatibility issues between Java key expansion and SPARC crypto instructions
5962     Node* original_k_start = get_original_key_start_from_aescrypt_object(aescrypt_object);
5963     if (original_k_start == NULL) return false;
5964 
5965     // Call the stub.
5966     make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::aescrypt_block_Type(),
5967                       stubAddr, stubName, TypePtr::BOTTOM,
5968                       src_start, dest_start, k_start, original_k_start);
5969   } else {
5970     // Call the stub.
5971     make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::aescrypt_block_Type(),
5972                       stubAddr, stubName, TypePtr::BOTTOM,
5973                       src_start, dest_start, k_start);
5974   }
5975 
5976   return true;
5977 }
5978 
5979 //------------------------------inline_cipherBlockChaining_AESCrypt-----------------------
5980 bool LibraryCallKit::inline_cipherBlockChaining_AESCrypt(vmIntrinsics::ID id) {
5981   address stubAddr;
5982   const char *stubName;
5983 
5984   assert(UseAES, "need AES instruction support");
5985 
5986   switch(id) {
5987   case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
5988     stubAddr = StubRoutines::cipherBlockChaining_encryptAESCrypt();
5989     stubName = "cipherBlockChaining_encryptAESCrypt";
5990     break;
5991   case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
5992     stubAddr = StubRoutines::cipherBlockChaining_decryptAESCrypt();
5993     stubName = "cipherBlockChaining_decryptAESCrypt";
5994     break;
5995   }
5996   if (stubAddr == NULL) return false;
5997 
5998   Node* cipherBlockChaining_object = argument(0);
5999   Node* src                        = argument(1);
6000   Node* src_offset                 = argument(2);
6001   Node* len                        = argument(3);
6002   Node* dest                       = argument(4);
6003   Node* dest_offset                = argument(5);
6004 
6005   // (1) src and dest are arrays.
6006   const Type* src_type = src->Value(&_gvn);
6007   const Type* dest_type = dest->Value(&_gvn);
6008   const TypeAryPtr* top_src = src_type->isa_aryptr();
6009   const TypeAryPtr* top_dest = dest_type->isa_aryptr();
6010   assert (top_src  != NULL && top_src->klass()  != NULL
6011           &&  top_dest != NULL && top_dest->klass() != NULL, "args are strange");
6012 
6013   // checks are the responsibility of the caller
6014   Node* src_start  = src;
6015   Node* dest_start = dest;
6016   if (src_offset != NULL || dest_offset != NULL) {
6017     assert(src_offset != NULL && dest_offset != NULL, "");
6018     src_start  = array_element_address(src,  src_offset,  T_BYTE);
6019     dest_start = array_element_address(dest, dest_offset, T_BYTE);
6020   }
6021 
6022   // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
6023   // (because of the predicated logic executed earlier).
6024   // so we cast it here safely.
6025   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
6026 
6027   Node* embeddedCipherObj = load_field_from_object(cipherBlockChaining_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;", /*is_exact*/ false);
6028   if (embeddedCipherObj == NULL) return false;
6029 
6030   // cast it to what we know it will be at runtime
6031   const TypeInstPtr* tinst = _gvn.type(cipherBlockChaining_object)->isa_instptr();
6032   assert(tinst != NULL, "CBC obj is null");
6033   assert(tinst->klass()->is_loaded(), "CBC obj is not loaded");
6034   ciKlass* klass_AESCrypt = tinst->klass()->as_instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AESCrypt"));
6035   assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
6036 
6037   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
6038   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
6039   const TypeOopPtr* xtype = aklass->as_instance_type();
6040   Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
6041   aescrypt_object = _gvn.transform(aescrypt_object);
6042 
6043   // we need to get the start of the aescrypt_object's expanded key array
6044   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object);
6045   if (k_start == NULL) return false;
6046 
6047   // similarly, get the start address of the r vector
6048   Node* objRvec = load_field_from_object(cipherBlockChaining_object, "r", "[B", /*is_exact*/ false);
6049   if (objRvec == NULL) return false;
6050   Node* r_start = array_element_address(objRvec, intcon(0), T_BYTE);
6051 
6052   Node* cbcCrypt;
6053   if (Matcher::pass_original_key_for_aes()) {
6054     // on SPARC we need to pass the original key since key expansion needs to happen in intrinsics due to
6055     // compatibility issues between Java key expansion and SPARC crypto instructions
6056     Node* original_k_start = get_original_key_start_from_aescrypt_object(aescrypt_object);
6057     if (original_k_start == NULL) return false;
6058 
6059     // Call the stub, passing src_start, dest_start, k_start, r_start, src_len and original_k_start
6060     cbcCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
6061                                  OptoRuntime::cipherBlockChaining_aescrypt_Type(),
6062                                  stubAddr, stubName, TypePtr::BOTTOM,
6063                                  src_start, dest_start, k_start, r_start, len, original_k_start);
6064   } else {
6065     // Call the stub, passing src_start, dest_start, k_start, r_start and src_len
6066     cbcCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
6067                                  OptoRuntime::cipherBlockChaining_aescrypt_Type(),
6068                                  stubAddr, stubName, TypePtr::BOTTOM,
6069                                  src_start, dest_start, k_start, r_start, len);
6070   }
6071 
6072   // return cipher length (int)
6073   Node* retvalue = _gvn.transform(new ProjNode(cbcCrypt, TypeFunc::Parms));
6074   set_result(retvalue);
6075   return true;
6076 }
6077 
6078 //------------------------------get_key_start_from_aescrypt_object-----------------------
6079 Node * LibraryCallKit::get_key_start_from_aescrypt_object(Node *aescrypt_object) {
6080   Node* objAESCryptKey = load_field_from_object(aescrypt_object, "K", "[I", /*is_exact*/ false);
6081   assert (objAESCryptKey != NULL, "wrong version of com.sun.crypto.provider.AESCrypt");
6082   if (objAESCryptKey == NULL) return (Node *) NULL;
6083 
6084   // now have the array, need to get the start address of the K array
6085   Node* k_start = array_element_address(objAESCryptKey, intcon(0), T_INT);
6086   return k_start;
6087 }
6088 
6089 //------------------------------get_original_key_start_from_aescrypt_object-----------------------
6090 Node * LibraryCallKit::get_original_key_start_from_aescrypt_object(Node *aescrypt_object) {
6091   Node* objAESCryptKey = load_field_from_object(aescrypt_object, "lastKey", "[B", /*is_exact*/ false);
6092   assert (objAESCryptKey != NULL, "wrong version of com.sun.crypto.provider.AESCrypt");
6093   if (objAESCryptKey == NULL) return (Node *) NULL;
6094 
6095   // now have the array, need to get the start address of the lastKey array
6096   Node* original_k_start = array_element_address(objAESCryptKey, intcon(0), T_BYTE);
6097   return original_k_start;
6098 }
6099 
6100 //----------------------------inline_cipherBlockChaining_AESCrypt_predicate----------------------------
6101 // Return node representing slow path of predicate check.
6102 // the pseudo code we want to emulate with this predicate is:
6103 // for encryption:
6104 //    if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
6105 // for decryption:
6106 //    if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
6107 //    note cipher==plain is more conservative than the original java code but that's OK
6108 //
6109 Node* LibraryCallKit::inline_cipherBlockChaining_AESCrypt_predicate(bool decrypting) {
6110   // The receiver was checked for NULL already.
6111   Node* objCBC = argument(0);
6112 
6113   // Load embeddedCipher field of CipherBlockChaining object.
6114   Node* embeddedCipherObj = load_field_from_object(objCBC, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;", /*is_exact*/ false);
6115 
6116   // get AESCrypt klass for instanceOf check
6117   // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
6118   // will have same classloader as CipherBlockChaining object
6119   const TypeInstPtr* tinst = _gvn.type(objCBC)->isa_instptr();
6120   assert(tinst != NULL, "CBCobj is null");
6121   assert(tinst->klass()->is_loaded(), "CBCobj is not loaded");
6122 
6123   // we want to do an instanceof comparison against the AESCrypt class
6124   ciKlass* klass_AESCrypt = tinst->klass()->as_instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AESCrypt"));
6125   if (!klass_AESCrypt->is_loaded()) {
6126     // if AESCrypt is not even loaded, we never take the intrinsic fast path
6127     Node* ctrl = control();
6128     set_control(top()); // no regular fast path
6129     return ctrl;
6130   }
6131   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
6132 
6133   Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
6134   Node* cmp_instof  = _gvn.transform(new CmpINode(instof, intcon(1)));
6135   Node* bool_instof  = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
6136 
6137   Node* instof_false = generate_guard(bool_instof, NULL, PROB_MIN);
6138 
6139   // for encryption, we are done
6140   if (!decrypting)
6141     return instof_false;  // even if it is NULL
6142 
6143   // for decryption, we need to add a further check to avoid
6144   // taking the intrinsic path when cipher and plain are the same
6145   // see the original java code for why.
6146   RegionNode* region = new RegionNode(3);
6147   region->init_req(1, instof_false);
6148   Node* src = argument(1);
6149   Node* dest = argument(4);
6150   Node* cmp_src_dest = _gvn.transform(new CmpPNode(src, dest));
6151   Node* bool_src_dest = _gvn.transform(new BoolNode(cmp_src_dest, BoolTest::eq));
6152   Node* src_dest_conjoint = generate_guard(bool_src_dest, NULL, PROB_MIN);
6153   region->init_req(2, src_dest_conjoint);
6154 
6155   record_for_igvn(region);
6156   return _gvn.transform(region);
6157 }
6158 
6159 //------------------------------inline_ghash_processBlocks
6160 bool LibraryCallKit::inline_ghash_processBlocks() {
6161   address stubAddr;
6162   const char *stubName;
6163   assert(UseGHASHIntrinsics, "need GHASH intrinsics support");
6164 
6165   stubAddr = StubRoutines::ghash_processBlocks();
6166   stubName = "ghash_processBlocks";
6167 
6168   Node* data           = argument(0);
6169   Node* offset         = argument(1);
6170   Node* len            = argument(2);
6171   Node* state          = argument(3);
6172   Node* subkeyH        = argument(4);
6173 
6174   Node* state_start  = array_element_address(state, intcon(0), T_LONG);
6175   assert(state_start, "state is NULL");
6176   Node* subkeyH_start  = array_element_address(subkeyH, intcon(0), T_LONG);
6177   assert(subkeyH_start, "subkeyH is NULL");
6178   Node* data_start  = array_element_address(data, offset, T_BYTE);
6179   assert(data_start, "data is NULL");
6180 
6181   Node* ghash = make_runtime_call(RC_LEAF|RC_NO_FP,
6182                                   OptoRuntime::ghash_processBlocks_Type(),
6183                                   stubAddr, stubName, TypePtr::BOTTOM,
6184                                   state_start, subkeyH_start, data_start, len);
6185   return true;
6186 }
6187 
6188 //------------------------------inline_sha_implCompress-----------------------
6189 //
6190 // Calculate SHA (i.e., SHA-1) for single-block byte[] array.
6191 // void com.sun.security.provider.SHA.implCompress(byte[] buf, int ofs)
6192 //
6193 // Calculate SHA2 (i.e., SHA-244 or SHA-256) for single-block byte[] array.
6194 // void com.sun.security.provider.SHA2.implCompress(byte[] buf, int ofs)
6195 //
6196 // Calculate SHA5 (i.e., SHA-384 or SHA-512) for single-block byte[] array.
6197 // void com.sun.security.provider.SHA5.implCompress(byte[] buf, int ofs)
6198 //
6199 bool LibraryCallKit::inline_sha_implCompress(vmIntrinsics::ID id) {
6200   assert(callee()->signature()->size() == 2, "sha_implCompress has 2 parameters");
6201 
6202   Node* sha_obj = argument(0);
6203   Node* src     = argument(1); // type oop
6204   Node* ofs     = argument(2); // type int
6205 
6206   const Type* src_type = src->Value(&_gvn);
6207   const TypeAryPtr* top_src = src_type->isa_aryptr();
6208   if (top_src  == NULL || top_src->klass()  == NULL) {
6209     // failed array check
6210     return false;
6211   }
6212   // Figure out the size and type of the elements we will be copying.
6213   BasicType src_elem = src_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
6214   if (src_elem != T_BYTE) {
6215     return false;
6216   }
6217   // 'src_start' points to src array + offset
6218   Node* src_start = array_element_address(src, ofs, src_elem);
6219   Node* state = NULL;
6220   address stubAddr;
6221   const char *stubName;
6222 
6223   switch(id) {
6224   case vmIntrinsics::_sha_implCompress:
6225     assert(UseSHA1Intrinsics, "need SHA1 instruction support");
6226     state = get_state_from_sha_object(sha_obj);
6227     stubAddr = StubRoutines::sha1_implCompress();
6228     stubName = "sha1_implCompress";
6229     break;
6230   case vmIntrinsics::_sha2_implCompress:
6231     assert(UseSHA256Intrinsics, "need SHA256 instruction support");
6232     state = get_state_from_sha_object(sha_obj);
6233     stubAddr = StubRoutines::sha256_implCompress();
6234     stubName = "sha256_implCompress";
6235     break;
6236   case vmIntrinsics::_sha5_implCompress:
6237     assert(UseSHA512Intrinsics, "need SHA512 instruction support");
6238     state = get_state_from_sha5_object(sha_obj);
6239     stubAddr = StubRoutines::sha512_implCompress();
6240     stubName = "sha512_implCompress";
6241     break;
6242   default:
6243     fatal_unexpected_iid(id);
6244     return false;
6245   }
6246   if (state == NULL) return false;
6247 
6248   // Call the stub.
6249   Node* call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::sha_implCompress_Type(),
6250                                  stubAddr, stubName, TypePtr::BOTTOM,
6251                                  src_start, state);
6252 
6253   return true;
6254 }
6255 
6256 //------------------------------inline_digestBase_implCompressMB-----------------------
6257 //
6258 // Calculate SHA/SHA2/SHA5 for multi-block byte[] array.
6259 // int com.sun.security.provider.DigestBase.implCompressMultiBlock(byte[] b, int ofs, int limit)
6260 //
6261 bool LibraryCallKit::inline_digestBase_implCompressMB(int predicate) {
6262   assert(UseSHA1Intrinsics || UseSHA256Intrinsics || UseSHA512Intrinsics,
6263          "need SHA1/SHA256/SHA512 instruction support");
6264   assert((uint)predicate < 3, "sanity");
6265   assert(callee()->signature()->size() == 3, "digestBase_implCompressMB has 3 parameters");
6266 
6267   Node* digestBase_obj = argument(0); // The receiver was checked for NULL already.
6268   Node* src            = argument(1); // byte[] array
6269   Node* ofs            = argument(2); // type int
6270   Node* limit          = argument(3); // type int
6271 
6272   const Type* src_type = src->Value(&_gvn);
6273   const TypeAryPtr* top_src = src_type->isa_aryptr();
6274   if (top_src  == NULL || top_src->klass()  == NULL) {
6275     // failed array check
6276     return false;
6277   }
6278   // Figure out the size and type of the elements we will be copying.
6279   BasicType src_elem = src_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
6280   if (src_elem != T_BYTE) {
6281     return false;
6282   }
6283   // 'src_start' points to src array + offset
6284   Node* src_start = array_element_address(src, ofs, src_elem);
6285 
6286   const char* klass_SHA_name = NULL;
6287   const char* stub_name = NULL;
6288   address     stub_addr = NULL;
6289   bool        long_state = false;
6290 
6291   switch (predicate) {
6292   case 0:
6293     if (UseSHA1Intrinsics) {
6294       klass_SHA_name = "sun/security/provider/SHA";
6295       stub_name = "sha1_implCompressMB";
6296       stub_addr = StubRoutines::sha1_implCompressMB();
6297     }
6298     break;
6299   case 1:
6300     if (UseSHA256Intrinsics) {
6301       klass_SHA_name = "sun/security/provider/SHA2";
6302       stub_name = "sha256_implCompressMB";
6303       stub_addr = StubRoutines::sha256_implCompressMB();
6304     }
6305     break;
6306   case 2:
6307     if (UseSHA512Intrinsics) {
6308       klass_SHA_name = "sun/security/provider/SHA5";
6309       stub_name = "sha512_implCompressMB";
6310       stub_addr = StubRoutines::sha512_implCompressMB();
6311       long_state = true;
6312     }
6313     break;
6314   default:
6315     fatal(err_msg_res("unknown SHA intrinsic predicate: %d", predicate));
6316   }
6317   if (klass_SHA_name != NULL) {
6318     // get DigestBase klass to lookup for SHA klass
6319     const TypeInstPtr* tinst = _gvn.type(digestBase_obj)->isa_instptr();
6320     assert(tinst != NULL, "digestBase_obj is not instance???");
6321     assert(tinst->klass()->is_loaded(), "DigestBase is not loaded");
6322 
6323     ciKlass* klass_SHA = tinst->klass()->as_instance_klass()->find_klass(ciSymbol::make(klass_SHA_name));
6324     assert(klass_SHA->is_loaded(), "predicate checks that this class is loaded");
6325     ciInstanceKlass* instklass_SHA = klass_SHA->as_instance_klass();
6326     return inline_sha_implCompressMB(digestBase_obj, instklass_SHA, long_state, stub_addr, stub_name, src_start, ofs, limit);
6327   }
6328   return false;
6329 }
6330 //------------------------------inline_sha_implCompressMB-----------------------
6331 bool LibraryCallKit::inline_sha_implCompressMB(Node* digestBase_obj, ciInstanceKlass* instklass_SHA,
6332                                                bool long_state, address stubAddr, const char *stubName,
6333                                                Node* src_start, Node* ofs, Node* limit) {
6334   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_SHA);
6335   const TypeOopPtr* xtype = aklass->as_instance_type();
6336   Node* sha_obj = new CheckCastPPNode(control(), digestBase_obj, xtype);
6337   sha_obj = _gvn.transform(sha_obj);
6338 
6339   Node* state;
6340   if (long_state) {
6341     state = get_state_from_sha5_object(sha_obj);
6342   } else {
6343     state = get_state_from_sha_object(sha_obj);
6344   }
6345   if (state == NULL) return false;
6346 
6347   // Call the stub.
6348   Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
6349                                  OptoRuntime::digestBase_implCompressMB_Type(),
6350                                  stubAddr, stubName, TypePtr::BOTTOM,
6351                                  src_start, state, ofs, limit);
6352   // return ofs (int)
6353   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
6354   set_result(result);
6355 
6356   return true;
6357 }
6358 
6359 //------------------------------get_state_from_sha_object-----------------------
6360 Node * LibraryCallKit::get_state_from_sha_object(Node *sha_object) {
6361   Node* sha_state = load_field_from_object(sha_object, "state", "[I", /*is_exact*/ false);
6362   assert (sha_state != NULL, "wrong version of sun.security.provider.SHA/SHA2");
6363   if (sha_state == NULL) return (Node *) NULL;
6364 
6365   // now have the array, need to get the start address of the state array
6366   Node* state = array_element_address(sha_state, intcon(0), T_INT);
6367   return state;
6368 }
6369 
6370 //------------------------------get_state_from_sha5_object-----------------------
6371 Node * LibraryCallKit::get_state_from_sha5_object(Node *sha_object) {
6372   Node* sha_state = load_field_from_object(sha_object, "state", "[J", /*is_exact*/ false);
6373   assert (sha_state != NULL, "wrong version of sun.security.provider.SHA5");
6374   if (sha_state == NULL) return (Node *) NULL;
6375 
6376   // now have the array, need to get the start address of the state array
6377   Node* state = array_element_address(sha_state, intcon(0), T_LONG);
6378   return state;
6379 }
6380 
6381 //----------------------------inline_digestBase_implCompressMB_predicate----------------------------
6382 // Return node representing slow path of predicate check.
6383 // the pseudo code we want to emulate with this predicate is:
6384 //    if (digestBaseObj instanceof SHA/SHA2/SHA5) do_intrinsic, else do_javapath
6385 //
6386 Node* LibraryCallKit::inline_digestBase_implCompressMB_predicate(int predicate) {
6387   assert(UseSHA1Intrinsics || UseSHA256Intrinsics || UseSHA512Intrinsics,
6388          "need SHA1/SHA256/SHA512 instruction support");
6389   assert((uint)predicate < 3, "sanity");
6390 
6391   // The receiver was checked for NULL already.
6392   Node* digestBaseObj = argument(0);
6393 
6394   // get DigestBase klass for instanceOf check
6395   const TypeInstPtr* tinst = _gvn.type(digestBaseObj)->isa_instptr();
6396   assert(tinst != NULL, "digestBaseObj is null");
6397   assert(tinst->klass()->is_loaded(), "DigestBase is not loaded");
6398 
6399   const char* klass_SHA_name = NULL;
6400   switch (predicate) {
6401   case 0:
6402     if (UseSHA1Intrinsics) {
6403       // we want to do an instanceof comparison against the SHA class
6404       klass_SHA_name = "sun/security/provider/SHA";
6405     }
6406     break;
6407   case 1:
6408     if (UseSHA256Intrinsics) {
6409       // we want to do an instanceof comparison against the SHA2 class
6410       klass_SHA_name = "sun/security/provider/SHA2";
6411     }
6412     break;
6413   case 2:
6414     if (UseSHA512Intrinsics) {
6415       // we want to do an instanceof comparison against the SHA5 class
6416       klass_SHA_name = "sun/security/provider/SHA5";
6417     }
6418     break;
6419   default:
6420     fatal(err_msg_res("unknown SHA intrinsic predicate: %d", predicate));
6421   }
6422 
6423   ciKlass* klass_SHA = NULL;
6424   if (klass_SHA_name != NULL) {
6425     klass_SHA = tinst->klass()->as_instance_klass()->find_klass(ciSymbol::make(klass_SHA_name));
6426   }
6427   if ((klass_SHA == NULL) || !klass_SHA->is_loaded()) {
6428     // if none of SHA/SHA2/SHA5 is loaded, we never take the intrinsic fast path
6429     Node* ctrl = control();
6430     set_control(top()); // no intrinsic path
6431     return ctrl;
6432   }
6433   ciInstanceKlass* instklass_SHA = klass_SHA->as_instance_klass();
6434 
6435   Node* instofSHA = gen_instanceof(digestBaseObj, makecon(TypeKlassPtr::make(instklass_SHA)));
6436   Node* cmp_instof = _gvn.transform(new CmpINode(instofSHA, intcon(1)));
6437   Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
6438   Node* instof_false = generate_guard(bool_instof, NULL, PROB_MIN);
6439 
6440   return instof_false;  // even if it is NULL
6441 }
6442 
6443 bool LibraryCallKit::inline_profileBoolean() {
6444   Node* counts = argument(1);
6445   const TypeAryPtr* ary = NULL;
6446   ciArray* aobj = NULL;
6447   if (counts->is_Con()
6448       && (ary = counts->bottom_type()->isa_aryptr()) != NULL
6449       && (aobj = ary->const_oop()->as_array()) != NULL
6450       && (aobj->length() == 2)) {
6451     // Profile is int[2] where [0] and [1] correspond to false and true value occurrences respectively.
6452     jint false_cnt = aobj->element_value(0).as_int();
6453     jint  true_cnt = aobj->element_value(1).as_int();
6454 
6455     if (C->log() != NULL) {
6456       C->log()->elem("observe source='profileBoolean' false='%d' true='%d'",
6457                      false_cnt, true_cnt);
6458     }
6459 
6460     if (false_cnt + true_cnt == 0) {
6461       // According to profile, never executed.
6462       uncommon_trap_exact(Deoptimization::Reason_intrinsic,
6463                           Deoptimization::Action_reinterpret);
6464       return true;
6465     }
6466 
6467     // result is a boolean (0 or 1) and its profile (false_cnt & true_cnt)
6468     // is a number of each value occurrences.
6469     Node* result = argument(0);
6470     if (false_cnt == 0 || true_cnt == 0) {
6471       // According to profile, one value has been never seen.
6472       int expected_val = (false_cnt == 0) ? 1 : 0;
6473 
6474       Node* cmp  = _gvn.transform(new CmpINode(result, intcon(expected_val)));
6475       Node* test = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
6476 
6477       IfNode* check = create_and_map_if(control(), test, PROB_ALWAYS, COUNT_UNKNOWN);
6478       Node* fast_path = _gvn.transform(new IfTrueNode(check));
6479       Node* slow_path = _gvn.transform(new IfFalseNode(check));
6480 
6481       { // Slow path: uncommon trap for never seen value and then reexecute
6482         // MethodHandleImpl::profileBoolean() to bump the count, so JIT knows
6483         // the value has been seen at least once.
6484         PreserveJVMState pjvms(this);
6485         PreserveReexecuteState preexecs(this);
6486         jvms()->set_should_reexecute(true);
6487 
6488         set_control(slow_path);
6489         set_i_o(i_o());
6490 
6491         uncommon_trap_exact(Deoptimization::Reason_intrinsic,
6492                             Deoptimization::Action_reinterpret);
6493       }
6494       // The guard for never seen value enables sharpening of the result and
6495       // returning a constant. It allows to eliminate branches on the same value
6496       // later on.
6497       set_control(fast_path);
6498       result = intcon(expected_val);
6499     }
6500     // Stop profiling.
6501     // MethodHandleImpl::profileBoolean() has profiling logic in its bytecode.
6502     // By replacing method body with profile data (represented as ProfileBooleanNode
6503     // on IR level) we effectively disable profiling.
6504     // It enables full speed execution once optimized code is generated.
6505     Node* profile = _gvn.transform(new ProfileBooleanNode(result, false_cnt, true_cnt));
6506     C->record_for_igvn(profile);
6507     set_result(profile);
6508     return true;
6509   } else {
6510     // Continue profiling.
6511     // Profile data isn't available at the moment. So, execute method's bytecode version.
6512     // Usually, when GWT LambdaForms are profiled it means that a stand-alone nmethod
6513     // is compiled and counters aren't available since corresponding MethodHandle
6514     // isn't a compile-time constant.
6515     return false;
6516   }
6517 }
6518 
6519 bool LibraryCallKit::inline_isCompileConstant() {
6520   Node* n = argument(0);
6521   set_result(n->is_Con() ? intcon(1) : intcon(0));
6522   return true;
6523 }