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);
 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   bool inline_multiplyToLen();
 295   bool inline_squareToLen();
 296   bool inline_mulAdd();
 297 
 298   bool inline_profileBoolean();
 299   bool inline_isCompileConstant();
 300 };
 301 
 302 
 303 //---------------------------make_vm_intrinsic----------------------------
 304 CallGenerator* Compile::make_vm_intrinsic(ciMethod* m, bool is_virtual) {
 305   vmIntrinsics::ID id = m->intrinsic_id();
 306   assert(id != vmIntrinsics::_none, "must be a VM intrinsic");
 307 
 308   ccstr disable_intr = NULL;
 309 
 310   if ((DisableIntrinsic[0] != '\0'
 311        && strstr(DisableIntrinsic, vmIntrinsics::name_at(id)) != NULL) ||
 312       (method_has_option_value("DisableIntrinsic", disable_intr)
 313        && strstr(disable_intr, vmIntrinsics::name_at(id)) != NULL)) {
 314     // disabled by a user request on the command line:
 315     // example: -XX:DisableIntrinsic=_hashCode,_getClass
 316     return NULL;
 317   }
 318 
 319   if (!m->is_loaded()) {
 320     // do not attempt to inline unloaded methods
 321     return NULL;
 322   }
 323 
 324   // Only a few intrinsics implement a virtual dispatch.
 325   // They are expensive calls which are also frequently overridden.
 326   if (is_virtual) {
 327     switch (id) {
 328     case vmIntrinsics::_hashCode:
 329     case vmIntrinsics::_clone:
 330       // OK, Object.hashCode and Object.clone intrinsics come in both flavors
 331       break;
 332     default:
 333       return NULL;
 334     }
 335   }
 336 
 337   // -XX:-InlineNatives disables nearly all intrinsics:
 338   if (!InlineNatives) {
 339     switch (id) {
 340     case vmIntrinsics::_indexOf:
 341     case vmIntrinsics::_compareTo:
 342     case vmIntrinsics::_equals:
 343     case vmIntrinsics::_equalsC:
 344     case vmIntrinsics::_getAndAddInt:
 345     case vmIntrinsics::_getAndAddLong:
 346     case vmIntrinsics::_getAndSetInt:
 347     case vmIntrinsics::_getAndSetLong:
 348     case vmIntrinsics::_getAndSetObject:
 349     case vmIntrinsics::_loadFence:
 350     case vmIntrinsics::_storeFence:
 351     case vmIntrinsics::_fullFence:
 352       break;  // InlineNatives does not control String.compareTo
 353     case vmIntrinsics::_Reference_get:
 354       break;  // InlineNatives does not control Reference.get
 355     default:
 356       return NULL;
 357     }
 358   }
 359 
 360   int predicates = 0;
 361   bool does_virtual_dispatch = false;
 362 
 363   switch (id) {
 364   case vmIntrinsics::_compareTo:
 365     if (!SpecialStringCompareTo)  return NULL;
 366     if (!Matcher::match_rule_supported(Op_StrComp))  return NULL;
 367     break;
 368   case vmIntrinsics::_indexOf:
 369     if (!SpecialStringIndexOf)  return NULL;
 370     break;
 371   case vmIntrinsics::_equals:
 372     if (!SpecialStringEquals)  return NULL;
 373     if (!Matcher::match_rule_supported(Op_StrEquals))  return NULL;
 374     break;
 375   case vmIntrinsics::_equalsC:
 376     if (!SpecialArraysEquals)  return NULL;
 377     if (!Matcher::match_rule_supported(Op_AryEq))  return NULL;
 378     break;
 379   case vmIntrinsics::_arraycopy:
 380     if (!InlineArrayCopy)  return NULL;
 381     break;
 382   case vmIntrinsics::_copyMemory:
 383     if (StubRoutines::unsafe_arraycopy() == NULL)  return NULL;
 384     if (!InlineArrayCopy)  return NULL;
 385     break;
 386   case vmIntrinsics::_hashCode:
 387     if (!InlineObjectHash)  return NULL;
 388     does_virtual_dispatch = true;
 389     break;
 390   case vmIntrinsics::_clone:
 391     does_virtual_dispatch = true;
 392   case vmIntrinsics::_copyOf:
 393   case vmIntrinsics::_copyOfRange:
 394     if (!InlineObjectCopy)  return NULL;
 395     // These also use the arraycopy intrinsic mechanism:
 396     if (!InlineArrayCopy)  return NULL;
 397     break;
 398   case vmIntrinsics::_encodeISOArray:
 399     if (!SpecialEncodeISOArray)  return NULL;
 400     if (!Matcher::match_rule_supported(Op_EncodeISOArray))  return NULL;
 401     break;
 402   case vmIntrinsics::_checkIndex:
 403     // We do not intrinsify this.  The optimizer does fine with it.
 404     return NULL;
 405 
 406   case vmIntrinsics::_getCallerClass:
 407     if (!InlineReflectionGetCallerClass)  return NULL;
 408     if (SystemDictionary::reflect_CallerSensitive_klass() == NULL)  return NULL;
 409     break;
 410 
 411   case vmIntrinsics::_bitCount_i:
 412     if (!Matcher::match_rule_supported(Op_PopCountI)) return NULL;
 413     break;
 414 
 415   case vmIntrinsics::_bitCount_l:
 416     if (!Matcher::match_rule_supported(Op_PopCountL)) return NULL;
 417     break;
 418 
 419   case vmIntrinsics::_numberOfLeadingZeros_i:
 420     if (!Matcher::match_rule_supported(Op_CountLeadingZerosI)) return NULL;
 421     break;
 422 
 423   case vmIntrinsics::_numberOfLeadingZeros_l:
 424     if (!Matcher::match_rule_supported(Op_CountLeadingZerosL)) return NULL;
 425     break;
 426 
 427   case vmIntrinsics::_numberOfTrailingZeros_i:
 428     if (!Matcher::match_rule_supported(Op_CountTrailingZerosI)) return NULL;
 429     break;
 430 
 431   case vmIntrinsics::_numberOfTrailingZeros_l:
 432     if (!Matcher::match_rule_supported(Op_CountTrailingZerosL)) return NULL;
 433     break;
 434 
 435   case vmIntrinsics::_reverseBytes_c:
 436     if (!Matcher::match_rule_supported(Op_ReverseBytesUS)) return NULL;
 437     break;
 438   case vmIntrinsics::_reverseBytes_s:
 439     if (!Matcher::match_rule_supported(Op_ReverseBytesS))  return NULL;
 440     break;
 441   case vmIntrinsics::_reverseBytes_i:
 442     if (!Matcher::match_rule_supported(Op_ReverseBytesI))  return NULL;
 443     break;
 444   case vmIntrinsics::_reverseBytes_l:
 445     if (!Matcher::match_rule_supported(Op_ReverseBytesL))  return NULL;
 446     break;
 447 
 448   case vmIntrinsics::_Reference_get:
 449     // Use the intrinsic version of Reference.get() so that the value in
 450     // the referent field can be registered by the G1 pre-barrier code.
 451     // Also add memory barrier to prevent commoning reads from this field
 452     // across safepoint since GC can change it value.
 453     break;
 454 
 455   case vmIntrinsics::_compareAndSwapObject:
 456 #ifdef _LP64
 457     if (!UseCompressedOops && !Matcher::match_rule_supported(Op_CompareAndSwapP)) return NULL;
 458 #endif
 459     break;
 460 
 461   case vmIntrinsics::_compareAndSwapLong:
 462     if (!Matcher::match_rule_supported(Op_CompareAndSwapL)) return NULL;
 463     break;
 464 
 465   case vmIntrinsics::_getAndAddInt:
 466     if (!Matcher::match_rule_supported(Op_GetAndAddI)) return NULL;
 467     break;
 468 
 469   case vmIntrinsics::_getAndAddLong:
 470     if (!Matcher::match_rule_supported(Op_GetAndAddL)) return NULL;
 471     break;
 472 
 473   case vmIntrinsics::_getAndSetInt:
 474     if (!Matcher::match_rule_supported(Op_GetAndSetI)) return NULL;
 475     break;
 476 
 477   case vmIntrinsics::_getAndSetLong:
 478     if (!Matcher::match_rule_supported(Op_GetAndSetL)) return NULL;
 479     break;
 480 
 481   case vmIntrinsics::_getAndSetObject:
 482 #ifdef _LP64
 483     if (!UseCompressedOops && !Matcher::match_rule_supported(Op_GetAndSetP)) return NULL;
 484     if (UseCompressedOops && !Matcher::match_rule_supported(Op_GetAndSetN)) return NULL;
 485     break;
 486 #else
 487     if (!Matcher::match_rule_supported(Op_GetAndSetP)) return NULL;
 488     break;
 489 #endif
 490 
 491   case vmIntrinsics::_aescrypt_encryptBlock:
 492   case vmIntrinsics::_aescrypt_decryptBlock:
 493     if (!UseAESIntrinsics) return NULL;
 494     break;
 495 
 496   case vmIntrinsics::_multiplyToLen:
 497     if (!UseMultiplyToLenIntrinsic) return NULL;
 498     break;
 499 
 500   case vmIntrinsics::_squareToLen:
 501     if (!UseSquareToLenIntrinsic) return NULL;
 502     break;
 503 
 504   case vmIntrinsics::_mulAdd:
 505     if (!UseMulAddIntrinsic) return NULL;
 506     break;
 507 
 508   case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
 509   case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
 510     if (!UseAESIntrinsics) return NULL;
 511     // these two require the predicated logic
 512     predicates = 1;
 513     break;
 514 
 515   case vmIntrinsics::_sha_implCompress:
 516     if (!UseSHA1Intrinsics) return NULL;
 517     break;
 518 
 519   case vmIntrinsics::_sha2_implCompress:
 520     if (!UseSHA256Intrinsics) return NULL;
 521     break;
 522 
 523   case vmIntrinsics::_sha5_implCompress:
 524     if (!UseSHA512Intrinsics) return NULL;
 525     break;
 526 
 527   case vmIntrinsics::_digestBase_implCompressMB:
 528     if (!(UseSHA1Intrinsics || UseSHA256Intrinsics || UseSHA512Intrinsics)) return NULL;
 529     predicates = 3;
 530     break;
 531 
 532   case vmIntrinsics::_ghash_processBlocks:
 533     if (!UseGHASHIntrinsics) return NULL;
 534     break;
 535 
 536   case vmIntrinsics::_updateCRC32:
 537   case vmIntrinsics::_updateBytesCRC32:
 538   case vmIntrinsics::_updateByteBufferCRC32:
 539     if (!UseCRC32Intrinsics) return NULL;
 540     break;
 541 
 542   case vmIntrinsics::_incrementExactI:
 543   case vmIntrinsics::_addExactI:
 544     if (!Matcher::match_rule_supported(Op_OverflowAddI) || !UseMathExactIntrinsics) return NULL;
 545     break;
 546   case vmIntrinsics::_incrementExactL:
 547   case vmIntrinsics::_addExactL:
 548     if (!Matcher::match_rule_supported(Op_OverflowAddL) || !UseMathExactIntrinsics) return NULL;
 549     break;
 550   case vmIntrinsics::_decrementExactI:
 551   case vmIntrinsics::_subtractExactI:
 552     if (!Matcher::match_rule_supported(Op_OverflowSubI) || !UseMathExactIntrinsics) return NULL;
 553     break;
 554   case vmIntrinsics::_decrementExactL:
 555   case vmIntrinsics::_subtractExactL:
 556     if (!Matcher::match_rule_supported(Op_OverflowSubL) || !UseMathExactIntrinsics) return NULL;
 557     break;
 558   case vmIntrinsics::_negateExactI:
 559     if (!Matcher::match_rule_supported(Op_OverflowSubI) || !UseMathExactIntrinsics) return NULL;
 560     break;
 561   case vmIntrinsics::_negateExactL:
 562     if (!Matcher::match_rule_supported(Op_OverflowSubL) || !UseMathExactIntrinsics) return NULL;
 563     break;
 564   case vmIntrinsics::_multiplyExactI:
 565     if (!Matcher::match_rule_supported(Op_OverflowMulI) || !UseMathExactIntrinsics) return NULL;
 566     break;
 567   case vmIntrinsics::_multiplyExactL:
 568     if (!Matcher::match_rule_supported(Op_OverflowMulL) || !UseMathExactIntrinsics) return NULL;
 569     break;
 570 
 571   case vmIntrinsics::_getShortUnaligned:
 572   case vmIntrinsics::_getCharUnaligned:
 573   case vmIntrinsics::_getIntUnaligned:
 574   case vmIntrinsics::_getLongUnaligned:
 575   case vmIntrinsics::_putShortUnaligned:
 576   case vmIntrinsics::_putCharUnaligned:
 577   case vmIntrinsics::_putIntUnaligned:
 578   case vmIntrinsics::_putLongUnaligned:
 579     if (!UseUnalignedAccesses) return NULL;
 580     break;
 581 
 582  default:
 583     assert(id <= vmIntrinsics::LAST_COMPILER_INLINE, "caller responsibility");
 584     assert(id != vmIntrinsics::_Object_init && id != vmIntrinsics::_invoke, "enum out of order?");
 585     break;
 586   }
 587 
 588   // -XX:-InlineClassNatives disables natives from the Class class.
 589   // The flag applies to all reflective calls, notably Array.newArray
 590   // (visible to Java programmers as Array.newInstance).
 591   if (m->holder()->name() == ciSymbol::java_lang_Class() ||
 592       m->holder()->name() == ciSymbol::java_lang_reflect_Array()) {
 593     if (!InlineClassNatives)  return NULL;
 594   }
 595 
 596   // -XX:-InlineThreadNatives disables natives from the Thread class.
 597   if (m->holder()->name() == ciSymbol::java_lang_Thread()) {
 598     if (!InlineThreadNatives)  return NULL;
 599   }
 600 
 601   // -XX:-InlineMathNatives disables natives from the Math,Float and Double classes.
 602   if (m->holder()->name() == ciSymbol::java_lang_Math() ||
 603       m->holder()->name() == ciSymbol::java_lang_Float() ||
 604       m->holder()->name() == ciSymbol::java_lang_Double()) {
 605     if (!InlineMathNatives)  return NULL;
 606   }
 607 
 608   // -XX:-InlineUnsafeOps disables natives from the Unsafe class.
 609   if (m->holder()->name() == ciSymbol::sun_misc_Unsafe()) {
 610     if (!InlineUnsafeOps)  return NULL;
 611   }
 612 
 613   return new LibraryIntrinsic(m, is_virtual, predicates, does_virtual_dispatch, (vmIntrinsics::ID) id);
 614 }
 615 
 616 //----------------------register_library_intrinsics-----------------------
 617 // Initialize this file's data structures, for each Compile instance.
 618 void Compile::register_library_intrinsics() {
 619   // Nothing to do here.
 620 }
 621 
 622 JVMState* LibraryIntrinsic::generate(JVMState* jvms) {
 623   LibraryCallKit kit(jvms, this);
 624   Compile* C = kit.C;
 625   int nodes = C->unique();
 626 #ifndef PRODUCT
 627   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
 628     char buf[1000];
 629     const char* str = vmIntrinsics::short_name_as_C_string(intrinsic_id(), buf, sizeof(buf));
 630     tty->print_cr("Intrinsic %s", str);
 631   }
 632 #endif
 633   ciMethod* callee = kit.callee();
 634   const int bci    = kit.bci();
 635 
 636   // Try to inline the intrinsic.
 637   if (kit.try_to_inline(_last_predicate)) {

 638     if (C->print_intrinsics() || C->print_inlining()) {
 639       C->print_inlining(callee, jvms->depth() - 1, bci, is_virtual() ? "(intrinsic, virtual)" : "(intrinsic)");
 640     }
 641     C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_worked);
 642     if (C->log()) {
 643       C->log()->elem("intrinsic id='%s'%s nodes='%d'",
 644                      vmIntrinsics::name_at(intrinsic_id()),
 645                      (is_virtual() ? " virtual='1'" : ""),
 646                      C->unique() - nodes);
 647     }
 648     // Push the result from the inlined method onto the stack.
 649     kit.push_result();
 650     C->print_inlining_update(this);
 651     return kit.transfer_exceptions_into_jvms();
 652   }
 653 
 654   // The intrinsic bailed out
 655   if (C->print_intrinsics() || C->print_inlining()) {
 656     if (jvms->has_method()) {
 657       // Not a root compile.
 658       const char* msg = is_virtual() ? "failed to inline (intrinsic, virtual)" : "failed to inline (intrinsic)";






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