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_sha_implCompress(vmIntrinsics::ID id);
 282   bool inline_digestBase_implCompressMB(int predicate);
 283   bool inline_sha_implCompressMB(Node* digestBaseObj, ciInstanceKlass* instklass_SHA,
 284                                  bool long_state, address stubAddr, const char *stubName,
 285                                  Node* src_start, Node* ofs, Node* limit);
 286   Node* get_state_from_sha_object(Node *sha_object);
 287   Node* get_state_from_sha5_object(Node *sha_object);
 288   Node* inline_digestBase_implCompressMB_predicate(int predicate);
 289   bool inline_encodeISOArray();
 290   bool inline_updateCRC32();
 291   bool inline_updateBytesCRC32();
 292   bool inline_updateByteBufferCRC32();
 293   bool inline_multiplyToLen();
 294 
 295   bool inline_profileBoolean();
 296   bool inline_isCompileConstant();
 297 };
 298 
 299 
 300 //---------------------------make_vm_intrinsic----------------------------
 301 CallGenerator* Compile::make_vm_intrinsic(ciMethod* m, bool is_virtual) {
 302   vmIntrinsics::ID id = m->intrinsic_id();
 303   assert(id != vmIntrinsics::_none, "must be a VM intrinsic");
 304 
 305   ccstr disable_intr = NULL;
 306 
 307   if ((DisableIntrinsic[0] != '\0'
 308        && strstr(DisableIntrinsic, vmIntrinsics::name_at(id)) != NULL) ||
 309       (method_has_option_value("DisableIntrinsic", disable_intr)
 310        && strstr(disable_intr, vmIntrinsics::name_at(id)) != NULL)) {
 311     // disabled by a user request on the command line:
 312     // example: -XX:DisableIntrinsic=_hashCode,_getClass
 313     return NULL;
 314   }
 315 
 316   if (!m->is_loaded()) {
 317     // do not attempt to inline unloaded methods
 318     return NULL;
 319   }
 320 
 321   // Only a few intrinsics implement a virtual dispatch.
 322   // They are expensive calls which are also frequently overridden.
 323   if (is_virtual) {
 324     switch (id) {
 325     case vmIntrinsics::_hashCode:
 326     case vmIntrinsics::_clone:
 327       // OK, Object.hashCode and Object.clone intrinsics come in both flavors
 328       break;
 329     default:
 330       return NULL;
 331     }
 332   }
 333 
 334   // -XX:-InlineNatives disables nearly all intrinsics:
 335   if (!InlineNatives) {
 336     switch (id) {
 337     case vmIntrinsics::_indexOf:
 338     case vmIntrinsics::_compareTo:
 339     case vmIntrinsics::_equals:
 340     case vmIntrinsics::_equalsC:
 341     case vmIntrinsics::_getAndAddInt:
 342     case vmIntrinsics::_getAndAddLong:
 343     case vmIntrinsics::_getAndSetInt:
 344     case vmIntrinsics::_getAndSetLong:
 345     case vmIntrinsics::_getAndSetObject:
 346     case vmIntrinsics::_loadFence:
 347     case vmIntrinsics::_storeFence:
 348     case vmIntrinsics::_fullFence:
 349       break;  // InlineNatives does not control String.compareTo
 350     case vmIntrinsics::_Reference_get:
 351       break;  // InlineNatives does not control Reference.get
 352     default:
 353       return NULL;
 354     }
 355   }
 356 
 357   int predicates = 0;
 358   bool does_virtual_dispatch = false;
 359 
 360   switch (id) {
 361   case vmIntrinsics::_compareTo:
 362     if (!SpecialStringCompareTo)  return NULL;
 363     if (!Matcher::match_rule_supported(Op_StrComp))  return NULL;
 364     break;
 365   case vmIntrinsics::_indexOf:
 366     if (!SpecialStringIndexOf)  return NULL;
 367     break;
 368   case vmIntrinsics::_equals:
 369     if (!SpecialStringEquals)  return NULL;
 370     if (!Matcher::match_rule_supported(Op_StrEquals))  return NULL;
 371     break;
 372   case vmIntrinsics::_equalsC:
 373     if (!SpecialArraysEquals)  return NULL;
 374     if (!Matcher::match_rule_supported(Op_AryEq))  return NULL;
 375     break;
 376   case vmIntrinsics::_arraycopy:
 377     if (!InlineArrayCopy)  return NULL;
 378     break;
 379   case vmIntrinsics::_copyMemory:
 380     if (StubRoutines::unsafe_arraycopy() == NULL)  return NULL;
 381     if (!InlineArrayCopy)  return NULL;
 382     break;
 383   case vmIntrinsics::_hashCode:
 384     if (!InlineObjectHash)  return NULL;
 385     does_virtual_dispatch = true;
 386     break;
 387   case vmIntrinsics::_clone:
 388     does_virtual_dispatch = true;
 389   case vmIntrinsics::_copyOf:
 390   case vmIntrinsics::_copyOfRange:
 391     if (!InlineObjectCopy)  return NULL;
 392     // These also use the arraycopy intrinsic mechanism:
 393     if (!InlineArrayCopy)  return NULL;
 394     break;
 395   case vmIntrinsics::_encodeISOArray:
 396     if (!SpecialEncodeISOArray)  return NULL;
 397     if (!Matcher::match_rule_supported(Op_EncodeISOArray))  return NULL;
 398     break;
 399   case vmIntrinsics::_checkIndex:
 400     // We do not intrinsify this.  The optimizer does fine with it.
 401     return NULL;
 402 
 403   case vmIntrinsics::_getCallerClass:
 404     if (!InlineReflectionGetCallerClass)  return NULL;
 405     if (SystemDictionary::reflect_CallerSensitive_klass() == NULL)  return NULL;
 406     break;
 407 
 408   case vmIntrinsics::_bitCount_i:
 409     if (!Matcher::match_rule_supported(Op_PopCountI)) return NULL;
 410     break;
 411 
 412   case vmIntrinsics::_bitCount_l:
 413     if (!Matcher::match_rule_supported(Op_PopCountL)) return NULL;
 414     break;
 415 
 416   case vmIntrinsics::_numberOfLeadingZeros_i:
 417     if (!Matcher::match_rule_supported(Op_CountLeadingZerosI)) return NULL;
 418     break;
 419 
 420   case vmIntrinsics::_numberOfLeadingZeros_l:
 421     if (!Matcher::match_rule_supported(Op_CountLeadingZerosL)) return NULL;
 422     break;
 423 
 424   case vmIntrinsics::_numberOfTrailingZeros_i:
 425     if (!Matcher::match_rule_supported(Op_CountTrailingZerosI)) return NULL;
 426     break;
 427 
 428   case vmIntrinsics::_numberOfTrailingZeros_l:
 429     if (!Matcher::match_rule_supported(Op_CountTrailingZerosL)) return NULL;
 430     break;
 431 
 432   case vmIntrinsics::_reverseBytes_c:
 433     if (!Matcher::match_rule_supported(Op_ReverseBytesUS)) return NULL;
 434     break;
 435   case vmIntrinsics::_reverseBytes_s:
 436     if (!Matcher::match_rule_supported(Op_ReverseBytesS))  return NULL;
 437     break;
 438   case vmIntrinsics::_reverseBytes_i:
 439     if (!Matcher::match_rule_supported(Op_ReverseBytesI))  return NULL;
 440     break;
 441   case vmIntrinsics::_reverseBytes_l:
 442     if (!Matcher::match_rule_supported(Op_ReverseBytesL))  return NULL;
 443     break;
 444 
 445   case vmIntrinsics::_Reference_get:
 446     // Use the intrinsic version of Reference.get() so that the value in
 447     // the referent field can be registered by the G1 pre-barrier code.
 448     // Also add memory barrier to prevent commoning reads from this field
 449     // across safepoint since GC can change it value.
 450     break;
 451 
 452   case vmIntrinsics::_compareAndSwapObject:
 453 #ifdef _LP64
 454     if (!UseCompressedOops && !Matcher::match_rule_supported(Op_CompareAndSwapP)) return NULL;
 455 #endif
 456     break;
 457 
 458   case vmIntrinsics::_compareAndSwapLong:
 459     if (!Matcher::match_rule_supported(Op_CompareAndSwapL)) return NULL;
 460     break;
 461 
 462   case vmIntrinsics::_getAndAddInt:
 463     if (!Matcher::match_rule_supported(Op_GetAndAddI)) return NULL;
 464     break;
 465 
 466   case vmIntrinsics::_getAndAddLong:
 467     if (!Matcher::match_rule_supported(Op_GetAndAddL)) return NULL;
 468     break;
 469 
 470   case vmIntrinsics::_getAndSetInt:
 471     if (!Matcher::match_rule_supported(Op_GetAndSetI)) return NULL;
 472     break;
 473 
 474   case vmIntrinsics::_getAndSetLong:
 475     if (!Matcher::match_rule_supported(Op_GetAndSetL)) return NULL;
 476     break;
 477 
 478   case vmIntrinsics::_getAndSetObject:
 479 #ifdef _LP64
 480     if (!UseCompressedOops && !Matcher::match_rule_supported(Op_GetAndSetP)) return NULL;
 481     if (UseCompressedOops && !Matcher::match_rule_supported(Op_GetAndSetN)) return NULL;
 482     break;
 483 #else
 484     if (!Matcher::match_rule_supported(Op_GetAndSetP)) return NULL;
 485     break;
 486 #endif
 487 
 488   case vmIntrinsics::_aescrypt_encryptBlock:
 489   case vmIntrinsics::_aescrypt_decryptBlock:
 490     if (!UseAESIntrinsics) return NULL;
 491     break;
 492 
 493   case vmIntrinsics::_multiplyToLen:
 494     if (!UseMultiplyToLenIntrinsic) return NULL;
 495     break;
 496 
 497   case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
 498   case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
 499     if (!UseAESIntrinsics) return NULL;
 500     // these two require the predicated logic
 501     predicates = 1;
 502     break;
 503 
 504   case vmIntrinsics::_sha_implCompress:
 505     if (!UseSHA1Intrinsics) return NULL;
 506     break;
 507 
 508   case vmIntrinsics::_sha2_implCompress:
 509     if (!UseSHA256Intrinsics) return NULL;
 510     break;
 511 
 512   case vmIntrinsics::_sha5_implCompress:
 513     if (!UseSHA512Intrinsics) return NULL;
 514     break;
 515 
 516   case vmIntrinsics::_digestBase_implCompressMB:
 517     if (!(UseSHA1Intrinsics || UseSHA256Intrinsics || UseSHA512Intrinsics)) return NULL;
 518     predicates = 3;
 519     break;
 520 
 521   case vmIntrinsics::_updateCRC32:
 522   case vmIntrinsics::_updateBytesCRC32:
 523   case vmIntrinsics::_updateByteBufferCRC32:
 524     if (!UseCRC32Intrinsics) return NULL;
 525     break;
 526 
 527   case vmIntrinsics::_incrementExactI:
 528   case vmIntrinsics::_addExactI:
 529     if (!Matcher::match_rule_supported(Op_OverflowAddI) || !UseMathExactIntrinsics) return NULL;
 530     break;
 531   case vmIntrinsics::_incrementExactL:
 532   case vmIntrinsics::_addExactL:
 533     if (!Matcher::match_rule_supported(Op_OverflowAddL) || !UseMathExactIntrinsics) return NULL;
 534     break;
 535   case vmIntrinsics::_decrementExactI:
 536   case vmIntrinsics::_subtractExactI:
 537     if (!Matcher::match_rule_supported(Op_OverflowSubI) || !UseMathExactIntrinsics) return NULL;
 538     break;
 539   case vmIntrinsics::_decrementExactL:
 540   case vmIntrinsics::_subtractExactL:
 541     if (!Matcher::match_rule_supported(Op_OverflowSubL) || !UseMathExactIntrinsics) return NULL;
 542     break;
 543   case vmIntrinsics::_negateExactI:
 544     if (!Matcher::match_rule_supported(Op_OverflowSubI) || !UseMathExactIntrinsics) return NULL;
 545     break;
 546   case vmIntrinsics::_negateExactL:
 547     if (!Matcher::match_rule_supported(Op_OverflowSubL) || !UseMathExactIntrinsics) return NULL;
 548     break;
 549   case vmIntrinsics::_multiplyExactI:
 550     if (!Matcher::match_rule_supported(Op_OverflowMulI) || !UseMathExactIntrinsics) return NULL;
 551     break;
 552   case vmIntrinsics::_multiplyExactL:
 553     if (!Matcher::match_rule_supported(Op_OverflowMulL) || !UseMathExactIntrinsics) return NULL;
 554     break;
 555 
 556   case vmIntrinsics::_getShortUnaligned:
 557   case vmIntrinsics::_getCharUnaligned:
 558   case vmIntrinsics::_getIntUnaligned:
 559   case vmIntrinsics::_getLongUnaligned:
 560   case vmIntrinsics::_putShortUnaligned:
 561   case vmIntrinsics::_putCharUnaligned:
 562   case vmIntrinsics::_putIntUnaligned:
 563   case vmIntrinsics::_putLongUnaligned:
 564     if (!UseUnalignedAccesses) return NULL;
 565     break;
 566 
 567  default:
 568     assert(id <= vmIntrinsics::LAST_COMPILER_INLINE, "caller responsibility");
 569     assert(id != vmIntrinsics::_Object_init && id != vmIntrinsics::_invoke, "enum out of order?");
 570     break;
 571   }
 572 
 573   // -XX:-InlineClassNatives disables natives from the Class class.
 574   // The flag applies to all reflective calls, notably Array.newArray
 575   // (visible to Java programmers as Array.newInstance).
 576   if (m->holder()->name() == ciSymbol::java_lang_Class() ||
 577       m->holder()->name() == ciSymbol::java_lang_reflect_Array()) {
 578     if (!InlineClassNatives)  return NULL;
 579   }
 580 
 581   // -XX:-InlineThreadNatives disables natives from the Thread class.
 582   if (m->holder()->name() == ciSymbol::java_lang_Thread()) {
 583     if (!InlineThreadNatives)  return NULL;
 584   }
 585 
 586   // -XX:-InlineMathNatives disables natives from the Math,Float and Double classes.
 587   if (m->holder()->name() == ciSymbol::java_lang_Math() ||
 588       m->holder()->name() == ciSymbol::java_lang_Float() ||
 589       m->holder()->name() == ciSymbol::java_lang_Double()) {
 590     if (!InlineMathNatives)  return NULL;
 591   }
 592 
 593   // -XX:-InlineUnsafeOps disables natives from the Unsafe class.
 594   if (m->holder()->name() == ciSymbol::sun_misc_Unsafe()) {
 595     if (!InlineUnsafeOps)  return NULL;
 596   }
 597 
 598   return new LibraryIntrinsic(m, is_virtual, predicates, does_virtual_dispatch, (vmIntrinsics::ID) id);
 599 }
 600 
 601 //----------------------register_library_intrinsics-----------------------
 602 // Initialize this file's data structures, for each Compile instance.
 603 void Compile::register_library_intrinsics() {
 604   // Nothing to do here.
 605 }
 606 
 607 JVMState* LibraryIntrinsic::generate(JVMState* jvms) {
 608   LibraryCallKit kit(jvms, this);
 609   Compile* C = kit.C;
 610   int nodes = C->unique();
 611 #ifndef PRODUCT
 612   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
 613     char buf[1000];
 614     const char* str = vmIntrinsics::short_name_as_C_string(intrinsic_id(), buf, sizeof(buf));
 615     tty->print_cr("Intrinsic %s", str);
 616   }
 617 #endif
 618   ciMethod* callee = kit.callee();
 619   const int bci    = kit.bci();
 620 
 621   // Try to inline the intrinsic.
 622   if (kit.try_to_inline(_last_predicate)) {
 623     if (C->print_intrinsics() || C->print_inlining()) {
 624       C->print_inlining(callee, jvms->depth() - 1, bci, is_virtual() ? "(intrinsic, virtual)" : "(intrinsic)");
 625     }
 626     C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_worked);
 627     if (C->log()) {
 628       C->log()->elem("intrinsic id='%s'%s nodes='%d'",
 629                      vmIntrinsics::name_at(intrinsic_id()),
 630                      (is_virtual() ? " virtual='1'" : ""),
 631                      C->unique() - nodes);
 632     }
 633     // Push the result from the inlined method onto the stack.
 634     kit.push_result();
 635     C->print_inlining_update(this);
 636     return kit.transfer_exceptions_into_jvms();
 637   }
 638 
 639   // The intrinsic bailed out
 640   if (C->print_intrinsics() || C->print_inlining()) {
 641     if (jvms->has_method()) {
 642       // Not a root compile.
 643       const char* msg = is_virtual() ? "failed to inline (intrinsic, virtual)" : "failed to inline (intrinsic)";
 644       C->print_inlining(callee, jvms->depth() - 1, bci, msg);
 645     } else {
 646       // Root compile
 647       tty->print("Did not generate intrinsic %s%s at bci:%d in",
 648                vmIntrinsics::name_at(intrinsic_id()),
 649                (is_virtual() ? " (virtual)" : ""), bci);
 650     }
 651   }
 652   C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_failed);
 653   C->print_inlining_update(this);
 654   return NULL;
 655 }
 656 
 657 Node* LibraryIntrinsic::generate_predicate(JVMState* jvms, int predicate) {
 658   LibraryCallKit kit(jvms, this);
 659   Compile* C = kit.C;
 660   int nodes = C->unique();
 661   _last_predicate = predicate;
 662 #ifndef PRODUCT
 663   assert(is_predicated() && predicate < predicates_count(), "sanity");
 664   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
 665     char buf[1000];
 666     const char* str = vmIntrinsics::short_name_as_C_string(intrinsic_id(), buf, sizeof(buf));
 667     tty->print_cr("Predicate for intrinsic %s", str);
 668   }
 669 #endif
 670   ciMethod* callee = kit.callee();
 671   const int bci    = kit.bci();
 672 
 673   Node* slow_ctl = kit.try_to_predicate(predicate);
 674   if (!kit.failing()) {
 675     if (C->print_intrinsics() || C->print_inlining()) {
 676       C->print_inlining(callee, jvms->depth() - 1, bci, is_virtual() ? "(intrinsic, virtual, predicate)" : "(intrinsic, predicate)");
 677     }
 678     C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_worked);
 679     if (C->log()) {
 680       C->log()->elem("predicate_intrinsic id='%s'%s nodes='%d'",
 681                      vmIntrinsics::name_at(intrinsic_id()),
 682                      (is_virtual() ? " virtual='1'" : ""),
 683                      C->unique() - nodes);
 684     }
 685     return slow_ctl; // Could be NULL if the check folds.
 686   }
 687 
 688   // The intrinsic bailed out
 689   if (C->print_intrinsics() || C->print_inlining()) {
 690     if (jvms->has_method()) {
 691       // Not a root compile.
 692       const char* msg = "failed to generate predicate for intrinsic";
 693       C->print_inlining(kit.callee(), jvms->depth() - 1, bci, msg);
 694     } else {
 695       // Root compile
 696       C->print_inlining_stream()->print("Did not generate predicate for intrinsic %s%s at bci:%d in",
 697                                         vmIntrinsics::name_at(intrinsic_id()),
 698                                         (is_virtual() ? " (virtual)" : ""), bci);
 699     }
 700   }
 701   C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_failed);
 702   return NULL;
 703 }
 704 
 705 bool LibraryCallKit::try_to_inline(int predicate) {
 706   // Handle symbolic names for otherwise undistinguished boolean switches:
 707   const bool is_store       = true;
 708   const bool is_native_ptr  = true;
 709   const bool is_static      = true;
 710   const bool is_volatile    = true;
 711 
 712   if (!jvms()->has_method()) {
 713     // Root JVMState has a null method.
 714     assert(map()->memory()->Opcode() == Op_Parm, "");
 715     // Insert the memory aliasing node
 716     set_all_memory(reset_memory());
 717   }
 718   assert(merged_memory(), "");
 719 
 720 
 721   switch (intrinsic_id()) {
 722   case vmIntrinsics::_hashCode:                 return inline_native_hashcode(intrinsic()->is_virtual(), !is_static);
 723   case vmIntrinsics::_identityHashCode:         return inline_native_hashcode(/*!virtual*/ false,         is_static);
 724   case vmIntrinsics::_getClass:                 return inline_native_getClass();
 725 
 726   case vmIntrinsics::_dsin:
 727   case vmIntrinsics::_dcos:
 728   case vmIntrinsics::_dtan:
 729   case vmIntrinsics::_dabs:
 730   case vmIntrinsics::_datan2:
 731   case vmIntrinsics::_dsqrt:
 732   case vmIntrinsics::_dexp:
 733   case vmIntrinsics::_dlog:
 734   case vmIntrinsics::_dlog10:
 735   case vmIntrinsics::_dpow:                     return inline_math_native(intrinsic_id());
 736 
 737   case vmIntrinsics::_min:
 738   case vmIntrinsics::_max:                      return inline_min_max(intrinsic_id());
 739 







 740   case vmIntrinsics::_addExactI:                return inline_math_addExactI(false /* add */);
 741   case vmIntrinsics::_addExactL:                return inline_math_addExactL(false /* add */);
 742   case vmIntrinsics::_decrementExactI:          return inline_math_subtractExactI(true /* decrement */);
 743   case vmIntrinsics::_decrementExactL:          return inline_math_subtractExactL(true /* decrement */);
 744   case vmIntrinsics::_incrementExactI:          return inline_math_addExactI(true /* increment */);
 745   case vmIntrinsics::_incrementExactL:          return inline_math_addExactL(true /* increment */);
 746   case vmIntrinsics::_multiplyExactI:           return inline_math_multiplyExactI();
 747   case vmIntrinsics::_multiplyExactL:           return inline_math_multiplyExactL();
 748   case vmIntrinsics::_negateExactI:             return inline_math_negateExactI();
 749   case vmIntrinsics::_negateExactL:             return inline_math_negateExactL();
 750   case vmIntrinsics::_subtractExactI:           return inline_math_subtractExactI(false /* subtract */);
 751   case vmIntrinsics::_subtractExactL:           return inline_math_subtractExactL(false /* subtract */);
 752 
 753   case vmIntrinsics::_arraycopy:                return inline_arraycopy();
 754 
 755   case vmIntrinsics::_compareTo:                return inline_string_compareTo();
 756   case vmIntrinsics::_indexOf:                  return inline_string_indexOf();
 757   case vmIntrinsics::_equals:                   return inline_string_equals();
 758 
 759   case vmIntrinsics::_getObject:                return inline_unsafe_access(!is_native_ptr, !is_store, T_OBJECT,  !is_volatile);
 760   case vmIntrinsics::_getBoolean:               return inline_unsafe_access(!is_native_ptr, !is_store, T_BOOLEAN, !is_volatile);
 761   case vmIntrinsics::_getByte:                  return inline_unsafe_access(!is_native_ptr, !is_store, T_BYTE,    !is_volatile);
 762   case vmIntrinsics::_getShort:                 return inline_unsafe_access(!is_native_ptr, !is_store, T_SHORT,   !is_volatile);
 763   case vmIntrinsics::_getChar:                  return inline_unsafe_access(!is_native_ptr, !is_store, T_CHAR,    !is_volatile);
 764   case vmIntrinsics::_getInt:                   return inline_unsafe_access(!is_native_ptr, !is_store, T_INT,     !is_volatile);
 765   case vmIntrinsics::_getLong:                  return inline_unsafe_access(!is_native_ptr, !is_store, T_LONG,    !is_volatile);
 766   case vmIntrinsics::_getFloat:                 return inline_unsafe_access(!is_native_ptr, !is_store, T_FLOAT,   !is_volatile);
 767   case vmIntrinsics::_getDouble:                return inline_unsafe_access(!is_native_ptr, !is_store, T_DOUBLE,  !is_volatile);
 768 
 769   case vmIntrinsics::_putObject:                return inline_unsafe_access(!is_native_ptr,  is_store, T_OBJECT,  !is_volatile);
 770   case vmIntrinsics::_putBoolean:               return inline_unsafe_access(!is_native_ptr,  is_store, T_BOOLEAN, !is_volatile);
 771   case vmIntrinsics::_putByte:                  return inline_unsafe_access(!is_native_ptr,  is_store, T_BYTE,    !is_volatile);
 772   case vmIntrinsics::_putShort:                 return inline_unsafe_access(!is_native_ptr,  is_store, T_SHORT,   !is_volatile);
 773   case vmIntrinsics::_putChar:                  return inline_unsafe_access(!is_native_ptr,  is_store, T_CHAR,    !is_volatile);
 774   case vmIntrinsics::_putInt:                   return inline_unsafe_access(!is_native_ptr,  is_store, T_INT,     !is_volatile);
 775   case vmIntrinsics::_putLong:                  return inline_unsafe_access(!is_native_ptr,  is_store, T_LONG,    !is_volatile);
 776   case vmIntrinsics::_putFloat:                 return inline_unsafe_access(!is_native_ptr,  is_store, T_FLOAT,   !is_volatile);
 777   case vmIntrinsics::_putDouble:                return inline_unsafe_access(!is_native_ptr,  is_store, T_DOUBLE,  !is_volatile);
 778 
 779   case vmIntrinsics::_getByte_raw:              return inline_unsafe_access( is_native_ptr, !is_store, T_BYTE,    !is_volatile);
 780   case vmIntrinsics::_getShort_raw:             return inline_unsafe_access( is_native_ptr, !is_store, T_SHORT,   !is_volatile);
 781   case vmIntrinsics::_getChar_raw:              return inline_unsafe_access( is_native_ptr, !is_store, T_CHAR,    !is_volatile);
 782   case vmIntrinsics::_getInt_raw:               return inline_unsafe_access( is_native_ptr, !is_store, T_INT,     !is_volatile);
 783   case vmIntrinsics::_getLong_raw:              return inline_unsafe_access( is_native_ptr, !is_store, T_LONG,    !is_volatile);
 784   case vmIntrinsics::_getFloat_raw:             return inline_unsafe_access( is_native_ptr, !is_store, T_FLOAT,   !is_volatile);
 785   case vmIntrinsics::_getDouble_raw:            return inline_unsafe_access( is_native_ptr, !is_store, T_DOUBLE,  !is_volatile);
 786   case vmIntrinsics::_getAddress_raw:           return inline_unsafe_access( is_native_ptr, !is_store, T_ADDRESS, !is_volatile);
 787 
 788   case vmIntrinsics::_putByte_raw:              return inline_unsafe_access( is_native_ptr,  is_store, T_BYTE,    !is_volatile);
 789   case vmIntrinsics::_putShort_raw:             return inline_unsafe_access( is_native_ptr,  is_store, T_SHORT,   !is_volatile);
 790   case vmIntrinsics::_putChar_raw:              return inline_unsafe_access( is_native_ptr,  is_store, T_CHAR,    !is_volatile);
 791   case vmIntrinsics::_putInt_raw:               return inline_unsafe_access( is_native_ptr,  is_store, T_INT,     !is_volatile);
 792   case vmIntrinsics::_putLong_raw:              return inline_unsafe_access( is_native_ptr,  is_store, T_LONG,    !is_volatile);
 793   case vmIntrinsics::_putFloat_raw:             return inline_unsafe_access( is_native_ptr,  is_store, T_FLOAT,   !is_volatile);
 794   case vmIntrinsics::_putDouble_raw:            return inline_unsafe_access( is_native_ptr,  is_store, T_DOUBLE,  !is_volatile);
 795   case vmIntrinsics::_putAddress_raw:           return inline_unsafe_access( is_native_ptr,  is_store, T_ADDRESS, !is_volatile);
 796 
 797   case vmIntrinsics::_getObjectVolatile:        return inline_unsafe_access(!is_native_ptr, !is_store, T_OBJECT,   is_volatile);
 798   case vmIntrinsics::_getBooleanVolatile:       return inline_unsafe_access(!is_native_ptr, !is_store, T_BOOLEAN,  is_volatile);
 799   case vmIntrinsics::_getByteVolatile:          return inline_unsafe_access(!is_native_ptr, !is_store, T_BYTE,     is_volatile);
 800   case vmIntrinsics::_getShortVolatile:         return inline_unsafe_access(!is_native_ptr, !is_store, T_SHORT,    is_volatile);
 801   case vmIntrinsics::_getCharVolatile:          return inline_unsafe_access(!is_native_ptr, !is_store, T_CHAR,     is_volatile);
 802   case vmIntrinsics::_getIntVolatile:           return inline_unsafe_access(!is_native_ptr, !is_store, T_INT,      is_volatile);
 803   case vmIntrinsics::_getLongVolatile:          return inline_unsafe_access(!is_native_ptr, !is_store, T_LONG,     is_volatile);
 804   case vmIntrinsics::_getFloatVolatile:         return inline_unsafe_access(!is_native_ptr, !is_store, T_FLOAT,    is_volatile);
 805   case vmIntrinsics::_getDoubleVolatile:        return inline_unsafe_access(!is_native_ptr, !is_store, T_DOUBLE,   is_volatile);
 806 
 807   case vmIntrinsics::_putObjectVolatile:        return inline_unsafe_access(!is_native_ptr,  is_store, T_OBJECT,   is_volatile);
 808   case vmIntrinsics::_putBooleanVolatile:       return inline_unsafe_access(!is_native_ptr,  is_store, T_BOOLEAN,  is_volatile);
 809   case vmIntrinsics::_putByteVolatile:          return inline_unsafe_access(!is_native_ptr,  is_store, T_BYTE,     is_volatile);
 810   case vmIntrinsics::_putShortVolatile:         return inline_unsafe_access(!is_native_ptr,  is_store, T_SHORT,    is_volatile);
 811   case vmIntrinsics::_putCharVolatile:          return inline_unsafe_access(!is_native_ptr,  is_store, T_CHAR,     is_volatile);
 812   case vmIntrinsics::_putIntVolatile:           return inline_unsafe_access(!is_native_ptr,  is_store, T_INT,      is_volatile);
 813   case vmIntrinsics::_putLongVolatile:          return inline_unsafe_access(!is_native_ptr,  is_store, T_LONG,     is_volatile);
 814   case vmIntrinsics::_putFloatVolatile:         return inline_unsafe_access(!is_native_ptr,  is_store, T_FLOAT,    is_volatile);
 815   case vmIntrinsics::_putDoubleVolatile:        return inline_unsafe_access(!is_native_ptr,  is_store, T_DOUBLE,   is_volatile);
 816 
 817   case vmIntrinsics::_getShortUnaligned:        return inline_unsafe_access(!is_native_ptr, !is_store, T_SHORT,   !is_volatile);
 818   case vmIntrinsics::_getCharUnaligned:         return inline_unsafe_access(!is_native_ptr, !is_store, T_CHAR,    !is_volatile);
 819   case vmIntrinsics::_getIntUnaligned:          return inline_unsafe_access(!is_native_ptr, !is_store, T_INT,     !is_volatile);
 820   case vmIntrinsics::_getLongUnaligned:         return inline_unsafe_access(!is_native_ptr, !is_store, T_LONG,    !is_volatile);
 821 
 822   case vmIntrinsics::_putShortUnaligned:        return inline_unsafe_access(!is_native_ptr,  is_store, T_SHORT,   !is_volatile);
 823   case vmIntrinsics::_putCharUnaligned:         return inline_unsafe_access(!is_native_ptr,  is_store, T_CHAR,    !is_volatile);
 824   case vmIntrinsics::_putIntUnaligned:          return inline_unsafe_access(!is_native_ptr,  is_store, T_INT,     !is_volatile);
 825   case vmIntrinsics::_putLongUnaligned:         return inline_unsafe_access(!is_native_ptr,  is_store, T_LONG,    !is_volatile);
 826 
 827   case vmIntrinsics::_compareAndSwapObject:     return inline_unsafe_load_store(T_OBJECT, LS_cmpxchg);
 828   case vmIntrinsics::_compareAndSwapInt:        return inline_unsafe_load_store(T_INT,    LS_cmpxchg);
 829   case vmIntrinsics::_compareAndSwapLong:       return inline_unsafe_load_store(T_LONG,   LS_cmpxchg);
 830 
 831   case vmIntrinsics::_putOrderedObject:         return inline_unsafe_ordered_store(T_OBJECT);
 832   case vmIntrinsics::_putOrderedInt:            return inline_unsafe_ordered_store(T_INT);
 833   case vmIntrinsics::_putOrderedLong:           return inline_unsafe_ordered_store(T_LONG);
 834 
 835   case vmIntrinsics::_getAndAddInt:             return inline_unsafe_load_store(T_INT,    LS_xadd);
 836   case vmIntrinsics::_getAndAddLong:            return inline_unsafe_load_store(T_LONG,   LS_xadd);
 837   case vmIntrinsics::_getAndSetInt:             return inline_unsafe_load_store(T_INT,    LS_xchg);
 838   case vmIntrinsics::_getAndSetLong:            return inline_unsafe_load_store(T_LONG,   LS_xchg);
 839   case vmIntrinsics::_getAndSetObject:          return inline_unsafe_load_store(T_OBJECT, LS_xchg);
 840 
 841   case vmIntrinsics::_loadFence:
 842   case vmIntrinsics::_storeFence:
 843   case vmIntrinsics::_fullFence:                return inline_unsafe_fence(intrinsic_id());
 844 
 845   case vmIntrinsics::_currentThread:            return inline_native_currentThread();
 846   case vmIntrinsics::_isInterrupted:            return inline_native_isInterrupted();
 847 
 848 #ifdef TRACE_HAVE_INTRINSICS
 849   case vmIntrinsics::_classID:                  return inline_native_classID();
 850   case vmIntrinsics::_threadID:                 return inline_native_threadID();
 851   case vmIntrinsics::_counterTime:              return inline_native_time_funcs(CAST_FROM_FN_PTR(address, TRACE_TIME_METHOD), "counterTime");
 852 #endif
 853   case vmIntrinsics::_currentTimeMillis:        return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeMillis), "currentTimeMillis");
 854   case vmIntrinsics::_nanoTime:                 return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeNanos), "nanoTime");
 855   case vmIntrinsics::_allocateInstance:         return inline_unsafe_allocate();
 856   case vmIntrinsics::_copyMemory:               return inline_unsafe_copyMemory();
 857   case vmIntrinsics::_newArray:                 return inline_native_newArray();
 858   case vmIntrinsics::_getLength:                return inline_native_getLength();
 859   case vmIntrinsics::_copyOf:                   return inline_array_copyOf(false);
 860   case vmIntrinsics::_copyOfRange:              return inline_array_copyOf(true);
 861   case vmIntrinsics::_equalsC:                  return inline_array_equals();
 862   case vmIntrinsics::_clone:                    return inline_native_clone(intrinsic()->is_virtual());
 863 
 864   case vmIntrinsics::_isAssignableFrom:         return inline_native_subtype_check();
 865 
 866   case vmIntrinsics::_isInstance:
 867   case vmIntrinsics::_getModifiers:
 868   case vmIntrinsics::_isInterface:
 869   case vmIntrinsics::_isArray:
 870   case vmIntrinsics::_isPrimitive:
 871   case vmIntrinsics::_getSuperclass:
 872   case vmIntrinsics::_getClassAccessFlags:      return inline_native_Class_query(intrinsic_id());
 873 
 874   case vmIntrinsics::_floatToRawIntBits:
 875   case vmIntrinsics::_floatToIntBits:
 876   case vmIntrinsics::_intBitsToFloat:
 877   case vmIntrinsics::_doubleToRawLongBits:
 878   case vmIntrinsics::_doubleToLongBits:
 879   case vmIntrinsics::_longBitsToDouble:         return inline_fp_conversions(intrinsic_id());
 880 
 881   case vmIntrinsics::_numberOfLeadingZeros_i:
 882   case vmIntrinsics::_numberOfLeadingZeros_l:
 883   case vmIntrinsics::_numberOfTrailingZeros_i:
 884   case vmIntrinsics::_numberOfTrailingZeros_l:
 885   case vmIntrinsics::_bitCount_i:
 886   case vmIntrinsics::_bitCount_l:
 887   case vmIntrinsics::_reverseBytes_i:
 888   case vmIntrinsics::_reverseBytes_l:
 889   case vmIntrinsics::_reverseBytes_s:
 890   case vmIntrinsics::_reverseBytes_c:           return inline_number_methods(intrinsic_id());
 891 
 892   case vmIntrinsics::_getCallerClass:           return inline_native_Reflection_getCallerClass();
 893 
 894   case vmIntrinsics::_Reference_get:            return inline_reference_get();
 895 
 896   case vmIntrinsics::_Class_cast:               return inline_Class_cast();
 897 
 898   case vmIntrinsics::_aescrypt_encryptBlock:
 899   case vmIntrinsics::_aescrypt_decryptBlock:    return inline_aescrypt_Block(intrinsic_id());
 900 
 901   case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
 902   case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
 903     return inline_cipherBlockChaining_AESCrypt(intrinsic_id());
 904 
 905   case vmIntrinsics::_sha_implCompress:
 906   case vmIntrinsics::_sha2_implCompress:
 907   case vmIntrinsics::_sha5_implCompress:
 908     return inline_sha_implCompress(intrinsic_id());
 909 
 910   case vmIntrinsics::_digestBase_implCompressMB:
 911     return inline_digestBase_implCompressMB(predicate);
 912 
 913   case vmIntrinsics::_multiplyToLen:
 914     return inline_multiplyToLen();
 915 
 916   case vmIntrinsics::_encodeISOArray:
 917     return inline_encodeISOArray();
 918 
 919   case vmIntrinsics::_updateCRC32:
 920     return inline_updateCRC32();
 921   case vmIntrinsics::_updateBytesCRC32:
 922     return inline_updateBytesCRC32();
 923   case vmIntrinsics::_updateByteBufferCRC32:
 924     return inline_updateByteBufferCRC32();
 925 
 926   case vmIntrinsics::_profileBoolean:
 927     return inline_profileBoolean();
 928   case vmIntrinsics::_isCompileConstant:
 929     return inline_isCompileConstant();
 930 
 931   default:
 932     // If you get here, it may be that someone has added a new intrinsic
 933     // to the list in vmSymbols.hpp without implementing it here.
 934 #ifndef PRODUCT
 935     if ((PrintMiscellaneous && (Verbose || WizardMode)) || PrintOpto) {
 936       tty->print_cr("*** Warning: Unimplemented intrinsic %s(%d)",
 937                     vmIntrinsics::name_at(intrinsic_id()), intrinsic_id());
 938     }
 939 #endif
 940     return false;
 941   }
 942 }
 943 
 944 Node* LibraryCallKit::try_to_predicate(int predicate) {
 945   if (!jvms()->has_method()) {
 946     // Root JVMState has a null method.
 947     assert(map()->memory()->Opcode() == Op_Parm, "");
 948     // Insert the memory aliasing node
 949     set_all_memory(reset_memory());
 950   }
 951   assert(merged_memory(), "");
 952 
 953   switch (intrinsic_id()) {
 954   case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
 955     return inline_cipherBlockChaining_AESCrypt_predicate(false);
 956   case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
 957     return inline_cipherBlockChaining_AESCrypt_predicate(true);
 958   case vmIntrinsics::_digestBase_implCompressMB:
 959     return inline_digestBase_implCompressMB_predicate(predicate);
 960 
 961   default:
 962     // If you get here, it may be that someone has added a new intrinsic
 963     // to the list in vmSymbols.hpp without implementing it here.
 964 #ifndef PRODUCT
 965     if ((PrintMiscellaneous && (Verbose || WizardMode)) || PrintOpto) {
 966       tty->print_cr("*** Warning: Unimplemented predicate for intrinsic %s(%d)",
 967                     vmIntrinsics::name_at(intrinsic_id()), intrinsic_id());
 968     }
 969 #endif
 970     Node* slow_ctl = control();
 971     set_control(top()); // No fast path instrinsic
 972     return slow_ctl;
 973   }
 974 }
 975 
 976 //------------------------------set_result-------------------------------
 977 // Helper function for finishing intrinsics.
 978 void LibraryCallKit::set_result(RegionNode* region, PhiNode* value) {
 979   record_for_igvn(region);
 980   set_control(_gvn.transform(region));
 981   set_result( _gvn.transform(value));
 982   assert(value->type()->basic_type() == result()->bottom_type()->basic_type(), "sanity");
 983 }
 984 
 985 //------------------------------generate_guard---------------------------
 986 // Helper function for generating guarded fast-slow graph structures.
 987 // The given 'test', if true, guards a slow path.  If the test fails
 988 // then a fast path can be taken.  (We generally hope it fails.)
 989 // In all cases, GraphKit::control() is updated to the fast path.
 990 // The returned value represents the control for the slow path.
 991 // The return value is never 'top'; it is either a valid control
 992 // or NULL if it is obvious that the slow path can never be taken.
 993 // Also, if region and the slow control are not NULL, the slow edge
 994 // is appended to the region.
 995 Node* LibraryCallKit::generate_guard(Node* test, RegionNode* region, float true_prob) {
 996   if (stopped()) {
 997     // Already short circuited.
 998     return NULL;
 999   }
1000 
1001   // Build an if node and its projections.
1002   // If test is true we take the slow path, which we assume is uncommon.
1003   if (_gvn.type(test) == TypeInt::ZERO) {
1004     // The slow branch is never taken.  No need to build this guard.
1005     return NULL;
1006   }
1007 
1008   IfNode* iff = create_and_map_if(control(), test, true_prob, COUNT_UNKNOWN);
1009 
1010   Node* if_slow = _gvn.transform(new IfTrueNode(iff));
1011   if (if_slow == top()) {
1012     // The slow branch is never taken.  No need to build this guard.
1013     return NULL;
1014   }
1015 
1016   if (region != NULL)
1017     region->add_req(if_slow);
1018 
1019   Node* if_fast = _gvn.transform(new IfFalseNode(iff));
1020   set_control(if_fast);
1021 
1022   return if_slow;
1023 }
1024 
1025 inline Node* LibraryCallKit::generate_slow_guard(Node* test, RegionNode* region) {
1026   return generate_guard(test, region, PROB_UNLIKELY_MAG(3));
1027 }
1028 inline Node* LibraryCallKit::generate_fair_guard(Node* test, RegionNode* region) {
1029   return generate_guard(test, region, PROB_FAIR);
1030 }
1031 
1032 inline Node* LibraryCallKit::generate_negative_guard(Node* index, RegionNode* region,
1033                                                      Node* *pos_index) {
1034   if (stopped())
1035     return NULL;                // already stopped
1036   if (_gvn.type(index)->higher_equal(TypeInt::POS)) // [0,maxint]
1037     return NULL;                // index is already adequately typed
1038   Node* cmp_lt = _gvn.transform(new CmpINode(index, intcon(0)));
1039   Node* bol_lt = _gvn.transform(new BoolNode(cmp_lt, BoolTest::lt));
1040   Node* is_neg = generate_guard(bol_lt, region, PROB_MIN);
1041   if (is_neg != NULL && pos_index != NULL) {
1042     // Emulate effect of Parse::adjust_map_after_if.
1043     Node* ccast = new CastIINode(index, TypeInt::POS);
1044     ccast->set_req(0, control());
1045     (*pos_index) = _gvn.transform(ccast);
1046   }
1047   return is_neg;
1048 }
1049 
1050 // Make sure that 'position' is a valid limit index, in [0..length].
1051 // There are two equivalent plans for checking this:
1052 //   A. (offset + copyLength)  unsigned<=  arrayLength
1053 //   B. offset  <=  (arrayLength - copyLength)
1054 // We require that all of the values above, except for the sum and
1055 // difference, are already known to be non-negative.
1056 // Plan A is robust in the face of overflow, if offset and copyLength
1057 // are both hugely positive.
1058 //
1059 // Plan B is less direct and intuitive, but it does not overflow at
1060 // all, since the difference of two non-negatives is always
1061 // representable.  Whenever Java methods must perform the equivalent
1062 // check they generally use Plan B instead of Plan A.
1063 // For the moment we use Plan A.
1064 inline Node* LibraryCallKit::generate_limit_guard(Node* offset,
1065                                                   Node* subseq_length,
1066                                                   Node* array_length,
1067                                                   RegionNode* region) {
1068   if (stopped())
1069     return NULL;                // already stopped
1070   bool zero_offset = _gvn.type(offset) == TypeInt::ZERO;
1071   if (zero_offset && subseq_length->eqv_uncast(array_length))
1072     return NULL;                // common case of whole-array copy
1073   Node* last = subseq_length;
1074   if (!zero_offset)             // last += offset
1075     last = _gvn.transform(new AddINode(last, offset));
1076   Node* cmp_lt = _gvn.transform(new CmpUNode(array_length, last));
1077   Node* bol_lt = _gvn.transform(new BoolNode(cmp_lt, BoolTest::lt));
1078   Node* is_over = generate_guard(bol_lt, region, PROB_MIN);
1079   return is_over;
1080 }
1081 
1082 
1083 //--------------------------generate_current_thread--------------------
1084 Node* LibraryCallKit::generate_current_thread(Node* &tls_output) {
1085   ciKlass*    thread_klass = env()->Thread_klass();
1086   const Type* thread_type  = TypeOopPtr::make_from_klass(thread_klass)->cast_to_ptr_type(TypePtr::NotNull);
1087   Node* thread = _gvn.transform(new ThreadLocalNode());
1088   Node* p = basic_plus_adr(top()/*!oop*/, thread, in_bytes(JavaThread::threadObj_offset()));
1089   Node* threadObj = make_load(NULL, p, thread_type, T_OBJECT, MemNode::unordered);
1090   tls_output = thread;
1091   return threadObj;
1092 }
1093 
1094 
1095 //------------------------------make_string_method_node------------------------
1096 // Helper method for String intrinsic functions. This version is called
1097 // with str1 and str2 pointing to String object nodes.
1098 //
1099 Node* LibraryCallKit::make_string_method_node(int opcode, Node* str1, Node* str2) {
1100   Node* no_ctrl = NULL;
1101 
1102   // Get start addr of string
1103   Node* str1_value   = load_String_value(no_ctrl, str1);
1104   Node* str1_offset  = load_String_offset(no_ctrl, str1);
1105   Node* str1_start   = array_element_address(str1_value, str1_offset, T_CHAR);
1106 
1107   // Get length of string 1
1108   Node* str1_len  = load_String_length(no_ctrl, str1);
1109 
1110   Node* str2_value   = load_String_value(no_ctrl, str2);
1111   Node* str2_offset  = load_String_offset(no_ctrl, str2);
1112   Node* str2_start   = array_element_address(str2_value, str2_offset, T_CHAR);
1113 
1114   Node* str2_len = NULL;
1115   Node* result = NULL;
1116 
1117   switch (opcode) {
1118   case Op_StrIndexOf:
1119     // Get length of string 2
1120     str2_len = load_String_length(no_ctrl, str2);
1121 
1122     result = new StrIndexOfNode(control(), memory(TypeAryPtr::CHARS),
1123                                 str1_start, str1_len, str2_start, str2_len);
1124     break;
1125   case Op_StrComp:
1126     // Get length of string 2
1127     str2_len = load_String_length(no_ctrl, str2);
1128 
1129     result = new StrCompNode(control(), memory(TypeAryPtr::CHARS),
1130                              str1_start, str1_len, str2_start, str2_len);
1131     break;
1132   case Op_StrEquals:
1133     result = new StrEqualsNode(control(), memory(TypeAryPtr::CHARS),
1134                                str1_start, str2_start, str1_len);
1135     break;
1136   default:
1137     ShouldNotReachHere();
1138     return NULL;
1139   }
1140 
1141   // All these intrinsics have checks.
1142   C->set_has_split_ifs(true); // Has chance for split-if optimization
1143 
1144   return _gvn.transform(result);
1145 }
1146 
1147 // Helper method for String intrinsic functions. This version is called
1148 // with str1 and str2 pointing to char[] nodes, with cnt1 and cnt2 pointing
1149 // to Int nodes containing the lenghts of str1 and str2.
1150 //
1151 Node* LibraryCallKit::make_string_method_node(int opcode, Node* str1_start, Node* cnt1, Node* str2_start, Node* cnt2) {
1152   Node* result = NULL;
1153   switch (opcode) {
1154   case Op_StrIndexOf:
1155     result = new StrIndexOfNode(control(), memory(TypeAryPtr::CHARS),
1156                                 str1_start, cnt1, str2_start, cnt2);
1157     break;
1158   case Op_StrComp:
1159     result = new StrCompNode(control(), memory(TypeAryPtr::CHARS),
1160                              str1_start, cnt1, str2_start, cnt2);
1161     break;
1162   case Op_StrEquals:
1163     result = new StrEqualsNode(control(), memory(TypeAryPtr::CHARS),
1164                                str1_start, str2_start, cnt1);
1165     break;
1166   default:
1167     ShouldNotReachHere();
1168     return NULL;
1169   }
1170 
1171   // All these intrinsics have checks.
1172   C->set_has_split_ifs(true); // Has chance for split-if optimization
1173 
1174   return _gvn.transform(result);
1175 }
1176 
1177 //------------------------------inline_string_compareTo------------------------
1178 // public int java.lang.String.compareTo(String anotherString);
1179 bool LibraryCallKit::inline_string_compareTo() {
1180   Node* receiver = null_check(argument(0));
1181   Node* arg      = null_check(argument(1));
1182   if (stopped()) {
1183     return true;
1184   }
1185   set_result(make_string_method_node(Op_StrComp, receiver, arg));
1186   return true;
1187 }
1188 
1189 //------------------------------inline_string_equals------------------------
1190 bool LibraryCallKit::inline_string_equals() {
1191   Node* receiver = null_check_receiver();
1192   // NOTE: Do not null check argument for String.equals() because spec
1193   // allows to specify NULL as argument.
1194   Node* argument = this->argument(1);
1195   if (stopped()) {
1196     return true;
1197   }
1198 
1199   // paths (plus control) merge
1200   RegionNode* region = new RegionNode(5);
1201   Node* phi = new PhiNode(region, TypeInt::BOOL);
1202 
1203   // does source == target string?
1204   Node* cmp = _gvn.transform(new CmpPNode(receiver, argument));
1205   Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
1206 
1207   Node* if_eq = generate_slow_guard(bol, NULL);
1208   if (if_eq != NULL) {
1209     // receiver == argument
1210     phi->init_req(2, intcon(1));
1211     region->init_req(2, if_eq);
1212   }
1213 
1214   // get String klass for instanceOf
1215   ciInstanceKlass* klass = env()->String_klass();
1216 
1217   if (!stopped()) {
1218     Node* inst = gen_instanceof(argument, makecon(TypeKlassPtr::make(klass)));
1219     Node* cmp  = _gvn.transform(new CmpINode(inst, intcon(1)));
1220     Node* bol  = _gvn.transform(new BoolNode(cmp, BoolTest::ne));
1221 
1222     Node* inst_false = generate_guard(bol, NULL, PROB_MIN);
1223     //instanceOf == true, fallthrough
1224 
1225     if (inst_false != NULL) {
1226       phi->init_req(3, intcon(0));
1227       region->init_req(3, inst_false);
1228     }
1229   }
1230 
1231   if (!stopped()) {
1232     const TypeOopPtr* string_type = TypeOopPtr::make_from_klass(klass);
1233 
1234     // Properly cast the argument to String
1235     argument = _gvn.transform(new CheckCastPPNode(control(), argument, string_type));
1236     // This path is taken only when argument's type is String:NotNull.
1237     argument = cast_not_null(argument, false);
1238 
1239     Node* no_ctrl = NULL;
1240 
1241     // Get start addr of receiver
1242     Node* receiver_val    = load_String_value(no_ctrl, receiver);
1243     Node* receiver_offset = load_String_offset(no_ctrl, receiver);
1244     Node* receiver_start = array_element_address(receiver_val, receiver_offset, T_CHAR);
1245 
1246     // Get length of receiver
1247     Node* receiver_cnt  = load_String_length(no_ctrl, receiver);
1248 
1249     // Get start addr of argument
1250     Node* argument_val    = load_String_value(no_ctrl, argument);
1251     Node* argument_offset = load_String_offset(no_ctrl, argument);
1252     Node* argument_start = array_element_address(argument_val, argument_offset, T_CHAR);
1253 
1254     // Get length of argument
1255     Node* argument_cnt  = load_String_length(no_ctrl, argument);
1256 
1257     // Check for receiver count != argument count
1258     Node* cmp = _gvn.transform(new CmpINode(receiver_cnt, argument_cnt));
1259     Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::ne));
1260     Node* if_ne = generate_slow_guard(bol, NULL);
1261     if (if_ne != NULL) {
1262       phi->init_req(4, intcon(0));
1263       region->init_req(4, if_ne);
1264     }
1265 
1266     // Check for count == 0 is done by assembler code for StrEquals.
1267 
1268     if (!stopped()) {
1269       Node* equals = make_string_method_node(Op_StrEquals, receiver_start, receiver_cnt, argument_start, argument_cnt);
1270       phi->init_req(1, equals);
1271       region->init_req(1, control());
1272     }
1273   }
1274 
1275   // post merge
1276   set_control(_gvn.transform(region));
1277   record_for_igvn(region);
1278 
1279   set_result(_gvn.transform(phi));
1280   return true;
1281 }
1282 
1283 //------------------------------inline_array_equals----------------------------
1284 bool LibraryCallKit::inline_array_equals() {
1285   Node* arg1 = argument(0);
1286   Node* arg2 = argument(1);
1287   set_result(_gvn.transform(new AryEqNode(control(), memory(TypeAryPtr::CHARS), arg1, arg2)));
1288   return true;
1289 }
1290 
1291 // Java version of String.indexOf(constant string)
1292 // class StringDecl {
1293 //   StringDecl(char[] ca) {
1294 //     offset = 0;
1295 //     count = ca.length;
1296 //     value = ca;
1297 //   }
1298 //   int offset;
1299 //   int count;
1300 //   char[] value;
1301 // }
1302 //
1303 // static int string_indexOf_J(StringDecl string_object, char[] target_object,
1304 //                             int targetOffset, int cache_i, int md2) {
1305 //   int cache = cache_i;
1306 //   int sourceOffset = string_object.offset;
1307 //   int sourceCount = string_object.count;
1308 //   int targetCount = target_object.length;
1309 //
1310 //   int targetCountLess1 = targetCount - 1;
1311 //   int sourceEnd = sourceOffset + sourceCount - targetCountLess1;
1312 //
1313 //   char[] source = string_object.value;
1314 //   char[] target = target_object;
1315 //   int lastChar = target[targetCountLess1];
1316 //
1317 //  outer_loop:
1318 //   for (int i = sourceOffset; i < sourceEnd; ) {
1319 //     int src = source[i + targetCountLess1];
1320 //     if (src == lastChar) {
1321 //       // With random strings and a 4-character alphabet,
1322 //       // reverse matching at this point sets up 0.8% fewer
1323 //       // frames, but (paradoxically) makes 0.3% more probes.
1324 //       // Since those probes are nearer the lastChar probe,
1325 //       // there is may be a net D$ win with reverse matching.
1326 //       // But, reversing loop inhibits unroll of inner loop
1327 //       // for unknown reason.  So, does running outer loop from
1328 //       // (sourceOffset - targetCountLess1) to (sourceOffset + sourceCount)
1329 //       for (int j = 0; j < targetCountLess1; j++) {
1330 //         if (target[targetOffset + j] != source[i+j]) {
1331 //           if ((cache & (1 << source[i+j])) == 0) {
1332 //             if (md2 < j+1) {
1333 //               i += j+1;
1334 //               continue outer_loop;
1335 //             }
1336 //           }
1337 //           i += md2;
1338 //           continue outer_loop;
1339 //         }
1340 //       }
1341 //       return i - sourceOffset;
1342 //     }
1343 //     if ((cache & (1 << src)) == 0) {
1344 //       i += targetCountLess1;
1345 //     } // using "i += targetCount;" and an "else i++;" causes a jump to jump.
1346 //     i++;
1347 //   }
1348 //   return -1;
1349 // }
1350 
1351 //------------------------------string_indexOf------------------------
1352 Node* LibraryCallKit::string_indexOf(Node* string_object, ciTypeArray* target_array, jint targetOffset_i,
1353                                      jint cache_i, jint md2_i) {
1354 
1355   Node* no_ctrl  = NULL;
1356   float likely   = PROB_LIKELY(0.9);
1357   float unlikely = PROB_UNLIKELY(0.9);
1358 
1359   const int nargs = 0; // no arguments to push back for uncommon trap in predicate
1360 
1361   Node* source        = load_String_value(no_ctrl, string_object);
1362   Node* sourceOffset  = load_String_offset(no_ctrl, string_object);
1363   Node* sourceCount   = load_String_length(no_ctrl, string_object);
1364 
1365   Node* target = _gvn.transform( makecon(TypeOopPtr::make_from_constant(target_array, true)));
1366   jint target_length = target_array->length();
1367   const TypeAry* target_array_type = TypeAry::make(TypeInt::CHAR, TypeInt::make(0, target_length, Type::WidenMin));
1368   const TypeAryPtr* target_type = TypeAryPtr::make(TypePtr::BotPTR, target_array_type, target_array->klass(), true, Type::OffsetBot);
1369 
1370   // String.value field is known to be @Stable.
1371   if (UseImplicitStableValues) {
1372     target = cast_array_to_stable(target, target_type);
1373   }
1374 
1375   IdealKit kit(this, false, true);
1376 #define __ kit.
1377   Node* zero             = __ ConI(0);
1378   Node* one              = __ ConI(1);
1379   Node* cache            = __ ConI(cache_i);
1380   Node* md2              = __ ConI(md2_i);
1381   Node* lastChar         = __ ConI(target_array->char_at(target_length - 1));
1382   Node* targetCountLess1 = __ ConI(target_length - 1);
1383   Node* targetOffset     = __ ConI(targetOffset_i);
1384   Node* sourceEnd        = __ SubI(__ AddI(sourceOffset, sourceCount), targetCountLess1);
1385 
1386   IdealVariable rtn(kit), i(kit), j(kit); __ declarations_done();
1387   Node* outer_loop = __ make_label(2 /* goto */);
1388   Node* return_    = __ make_label(1);
1389 
1390   __ set(rtn,__ ConI(-1));
1391   __ loop(this, nargs, i, sourceOffset, BoolTest::lt, sourceEnd); {
1392        Node* i2  = __ AddI(__ value(i), targetCountLess1);
1393        // pin to prohibit loading of "next iteration" value which may SEGV (rare)
1394        Node* src = load_array_element(__ ctrl(), source, i2, TypeAryPtr::CHARS);
1395        __ if_then(src, BoolTest::eq, lastChar, unlikely); {
1396          __ loop(this, nargs, j, zero, BoolTest::lt, targetCountLess1); {
1397               Node* tpj = __ AddI(targetOffset, __ value(j));
1398               Node* targ = load_array_element(no_ctrl, target, tpj, target_type);
1399               Node* ipj  = __ AddI(__ value(i), __ value(j));
1400               Node* src2 = load_array_element(no_ctrl, source, ipj, TypeAryPtr::CHARS);
1401               __ if_then(targ, BoolTest::ne, src2); {
1402                 __ if_then(__ AndI(cache, __ LShiftI(one, src2)), BoolTest::eq, zero); {
1403                   __ if_then(md2, BoolTest::lt, __ AddI(__ value(j), one)); {
1404                     __ increment(i, __ AddI(__ value(j), one));
1405                     __ goto_(outer_loop);
1406                   } __ end_if(); __ dead(j);
1407                 }__ end_if(); __ dead(j);
1408                 __ increment(i, md2);
1409                 __ goto_(outer_loop);
1410               }__ end_if();
1411               __ increment(j, one);
1412          }__ end_loop(); __ dead(j);
1413          __ set(rtn, __ SubI(__ value(i), sourceOffset)); __ dead(i);
1414          __ goto_(return_);
1415        }__ end_if();
1416        __ if_then(__ AndI(cache, __ LShiftI(one, src)), BoolTest::eq, zero, likely); {
1417          __ increment(i, targetCountLess1);
1418        }__ end_if();
1419        __ increment(i, one);
1420        __ bind(outer_loop);
1421   }__ end_loop(); __ dead(i);
1422   __ bind(return_);
1423 
1424   // Final sync IdealKit and GraphKit.
1425   final_sync(kit);
1426   Node* result = __ value(rtn);
1427 #undef __
1428   C->set_has_loops(true);
1429   return result;
1430 }
1431 
1432 //------------------------------inline_string_indexOf------------------------
1433 bool LibraryCallKit::inline_string_indexOf() {
1434   Node* receiver = argument(0);
1435   Node* arg      = argument(1);
1436 
1437   Node* result;
1438   if (Matcher::has_match_rule(Op_StrIndexOf) &&
1439       UseSSE42Intrinsics) {
1440     // Generate SSE4.2 version of indexOf
1441     // We currently only have match rules that use SSE4.2
1442 
1443     receiver = null_check(receiver);
1444     arg      = null_check(arg);
1445     if (stopped()) {
1446       return true;
1447     }
1448 
1449     // Make the merge point
1450     RegionNode* result_rgn = new RegionNode(4);
1451     Node*       result_phi = new PhiNode(result_rgn, TypeInt::INT);
1452     Node* no_ctrl  = NULL;
1453 
1454     // Get start addr of source string
1455     Node* source = load_String_value(no_ctrl, receiver);
1456     Node* source_offset = load_String_offset(no_ctrl, receiver);
1457     Node* source_start = array_element_address(source, source_offset, T_CHAR);
1458 
1459     // Get length of source string
1460     Node* source_cnt  = load_String_length(no_ctrl, receiver);
1461 
1462     // Get start addr of substring
1463     Node* substr = load_String_value(no_ctrl, arg);
1464     Node* substr_offset = load_String_offset(no_ctrl, arg);
1465     Node* substr_start = array_element_address(substr, substr_offset, T_CHAR);
1466 
1467     // Get length of source string
1468     Node* substr_cnt  = load_String_length(no_ctrl, arg);
1469 
1470     // Check for substr count > string count
1471     Node* cmp = _gvn.transform(new CmpINode(substr_cnt, source_cnt));
1472     Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::gt));
1473     Node* if_gt = generate_slow_guard(bol, NULL);
1474     if (if_gt != NULL) {
1475       result_phi->init_req(2, intcon(-1));
1476       result_rgn->init_req(2, if_gt);
1477     }
1478 
1479     if (!stopped()) {
1480       // Check for substr count == 0
1481       cmp = _gvn.transform(new CmpINode(substr_cnt, intcon(0)));
1482       bol = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
1483       Node* if_zero = generate_slow_guard(bol, NULL);
1484       if (if_zero != NULL) {
1485         result_phi->init_req(3, intcon(0));
1486         result_rgn->init_req(3, if_zero);
1487       }
1488     }
1489 
1490     if (!stopped()) {
1491       result = make_string_method_node(Op_StrIndexOf, source_start, source_cnt, substr_start, substr_cnt);
1492       result_phi->init_req(1, result);
1493       result_rgn->init_req(1, control());
1494     }
1495     set_control(_gvn.transform(result_rgn));
1496     record_for_igvn(result_rgn);
1497     result = _gvn.transform(result_phi);
1498 
1499   } else { // Use LibraryCallKit::string_indexOf
1500     // don't intrinsify if argument isn't a constant string.
1501     if (!arg->is_Con()) {
1502      return false;
1503     }
1504     const TypeOopPtr* str_type = _gvn.type(arg)->isa_oopptr();
1505     if (str_type == NULL) {
1506       return false;
1507     }
1508     ciInstanceKlass* klass = env()->String_klass();
1509     ciObject* str_const = str_type->const_oop();
1510     if (str_const == NULL || str_const->klass() != klass) {
1511       return false;
1512     }
1513     ciInstance* str = str_const->as_instance();
1514     assert(str != NULL, "must be instance");
1515 
1516     ciObject* v = str->field_value_by_offset(java_lang_String::value_offset_in_bytes()).as_object();
1517     ciTypeArray* pat = v->as_type_array(); // pattern (argument) character array
1518 
1519     int o;
1520     int c;
1521     if (java_lang_String::has_offset_field()) {
1522       o = str->field_value_by_offset(java_lang_String::offset_offset_in_bytes()).as_int();
1523       c = str->field_value_by_offset(java_lang_String::count_offset_in_bytes()).as_int();
1524     } else {
1525       o = 0;
1526       c = pat->length();
1527     }
1528 
1529     // constant strings have no offset and count == length which
1530     // simplifies the resulting code somewhat so lets optimize for that.
1531     if (o != 0 || c != pat->length()) {
1532      return false;
1533     }
1534 
1535     receiver = null_check(receiver, T_OBJECT);
1536     // NOTE: No null check on the argument is needed since it's a constant String oop.
1537     if (stopped()) {
1538       return true;
1539     }
1540 
1541     // The null string as a pattern always returns 0 (match at beginning of string)
1542     if (c == 0) {
1543       set_result(intcon(0));
1544       return true;
1545     }
1546 
1547     // Generate default indexOf
1548     jchar lastChar = pat->char_at(o + (c - 1));
1549     int cache = 0;
1550     int i;
1551     for (i = 0; i < c - 1; i++) {
1552       assert(i < pat->length(), "out of range");
1553       cache |= (1 << (pat->char_at(o + i) & (sizeof(cache) * BitsPerByte - 1)));
1554     }
1555 
1556     int md2 = c;
1557     for (i = 0; i < c - 1; i++) {
1558       assert(i < pat->length(), "out of range");
1559       if (pat->char_at(o + i) == lastChar) {
1560         md2 = (c - 1) - i;
1561       }
1562     }
1563 
1564     result = string_indexOf(receiver, pat, o, cache, md2);
1565   }
1566   set_result(result);
1567   return true;
1568 }
1569 
1570 //--------------------------round_double_node--------------------------------
1571 // Round a double node if necessary.
1572 Node* LibraryCallKit::round_double_node(Node* n) {
1573   if (Matcher::strict_fp_requires_explicit_rounding && UseSSE <= 1)
1574     n = _gvn.transform(new RoundDoubleNode(0, n));
1575   return n;
1576 }
1577 
1578 //------------------------------inline_math-----------------------------------
1579 // public static double Math.abs(double)
1580 // public static double Math.sqrt(double)
1581 // public static double Math.log(double)
1582 // public static double Math.log10(double)
1583 bool LibraryCallKit::inline_math(vmIntrinsics::ID id) {
1584   Node* arg = round_double_node(argument(0));
1585   Node* n;
1586   switch (id) {
1587   case vmIntrinsics::_dabs:   n = new AbsDNode(                arg);  break;
1588   case vmIntrinsics::_dsqrt:  n = new SqrtDNode(C, control(),  arg);  break;
1589   case vmIntrinsics::_dlog:   n = new LogDNode(C, control(),   arg);  break;
1590   case vmIntrinsics::_dlog10: n = new Log10DNode(C, control(), arg);  break;
1591   default:  fatal_unexpected_iid(id);  break;
1592   }
1593   set_result(_gvn.transform(n));
1594   return true;
1595 }
1596 
1597 //------------------------------inline_trig----------------------------------
1598 // Inline sin/cos/tan instructions, if possible.  If rounding is required, do
1599 // argument reduction which will turn into a fast/slow diamond.
1600 bool LibraryCallKit::inline_trig(vmIntrinsics::ID id) {
1601   Node* arg = round_double_node(argument(0));
1602   Node* n = NULL;
1603 
1604   switch (id) {
1605   case vmIntrinsics::_dsin:  n = new SinDNode(C, control(), arg);  break;
1606   case vmIntrinsics::_dcos:  n = new CosDNode(C, control(), arg);  break;
1607   case vmIntrinsics::_dtan:  n = new TanDNode(C, control(), arg);  break;
1608   default:  fatal_unexpected_iid(id);  break;
1609   }
1610   n = _gvn.transform(n);
1611 
1612   // Rounding required?  Check for argument reduction!
1613   if (Matcher::strict_fp_requires_explicit_rounding) {
1614     static const double     pi_4 =  0.7853981633974483;
1615     static const double neg_pi_4 = -0.7853981633974483;
1616     // pi/2 in 80-bit extended precision
1617     // static const unsigned char pi_2_bits_x[] = {0x35,0xc2,0x68,0x21,0xa2,0xda,0x0f,0xc9,0xff,0x3f,0x00,0x00,0x00,0x00,0x00,0x00};
1618     // -pi/2 in 80-bit extended precision
1619     // 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};
1620     // Cutoff value for using this argument reduction technique
1621     //static const double    pi_2_minus_epsilon =  1.564660403643354;
1622     //static const double neg_pi_2_plus_epsilon = -1.564660403643354;
1623 
1624     // Pseudocode for sin:
1625     // if (x <= Math.PI / 4.0) {
1626     //   if (x >= -Math.PI / 4.0) return  fsin(x);
1627     //   if (x >= -Math.PI / 2.0) return -fcos(x + Math.PI / 2.0);
1628     // } else {
1629     //   if (x <=  Math.PI / 2.0) return  fcos(x - Math.PI / 2.0);
1630     // }
1631     // return StrictMath.sin(x);
1632 
1633     // Pseudocode for cos:
1634     // if (x <= Math.PI / 4.0) {
1635     //   if (x >= -Math.PI / 4.0) return  fcos(x);
1636     //   if (x >= -Math.PI / 2.0) return  fsin(x + Math.PI / 2.0);
1637     // } else {
1638     //   if (x <=  Math.PI / 2.0) return -fsin(x - Math.PI / 2.0);
1639     // }
1640     // return StrictMath.cos(x);
1641 
1642     // Actually, sticking in an 80-bit Intel value into C2 will be tough; it
1643     // requires a special machine instruction to load it.  Instead we'll try
1644     // the 'easy' case.  If we really need the extra range +/- PI/2 we'll
1645     // probably do the math inside the SIN encoding.
1646 
1647     // Make the merge point
1648     RegionNode* r = new RegionNode(3);
1649     Node* phi = new PhiNode(r, Type::DOUBLE);
1650 
1651     // Flatten arg so we need only 1 test
1652     Node *abs = _gvn.transform(new AbsDNode(arg));
1653     // Node for PI/4 constant
1654     Node *pi4 = makecon(TypeD::make(pi_4));
1655     // Check PI/4 : abs(arg)
1656     Node *cmp = _gvn.transform(new CmpDNode(pi4,abs));
1657     // Check: If PI/4 < abs(arg) then go slow
1658     Node *bol = _gvn.transform(new BoolNode( cmp, BoolTest::lt ));
1659     // Branch either way
1660     IfNode *iff = create_and_xform_if(control(),bol, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
1661     set_control(opt_iff(r,iff));
1662 
1663     // Set fast path result
1664     phi->init_req(2, n);
1665 
1666     // Slow path - non-blocking leaf call
1667     Node* call = NULL;
1668     switch (id) {
1669     case vmIntrinsics::_dsin:
1670       call = make_runtime_call(RC_LEAF, OptoRuntime::Math_D_D_Type(),
1671                                CAST_FROM_FN_PTR(address, SharedRuntime::dsin),
1672                                "Sin", NULL, arg, top());
1673       break;
1674     case vmIntrinsics::_dcos:
1675       call = make_runtime_call(RC_LEAF, OptoRuntime::Math_D_D_Type(),
1676                                CAST_FROM_FN_PTR(address, SharedRuntime::dcos),
1677                                "Cos", NULL, arg, top());
1678       break;
1679     case vmIntrinsics::_dtan:
1680       call = make_runtime_call(RC_LEAF, OptoRuntime::Math_D_D_Type(),
1681                                CAST_FROM_FN_PTR(address, SharedRuntime::dtan),
1682                                "Tan", NULL, arg, top());
1683       break;
1684     }
1685     assert(control()->in(0) == call, "");
1686     Node* slow_result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
1687     r->init_req(1, control());
1688     phi->init_req(1, slow_result);
1689 
1690     // Post-merge
1691     set_control(_gvn.transform(r));
1692     record_for_igvn(r);
1693     n = _gvn.transform(phi);
1694 
1695     C->set_has_split_ifs(true); // Has chance for split-if optimization
1696   }
1697   set_result(n);
1698   return true;
1699 }
1700 
1701 Node* LibraryCallKit::finish_pow_exp(Node* result, Node* x, Node* y, const TypeFunc* call_type, address funcAddr, const char* funcName) {
1702   //-------------------
1703   //result=(result.isNaN())? funcAddr():result;
1704   // Check: If isNaN() by checking result!=result? then either trap
1705   // or go to runtime
1706   Node* cmpisnan = _gvn.transform(new CmpDNode(result, result));
1707   // Build the boolean node
1708   Node* bolisnum = _gvn.transform(new BoolNode(cmpisnan, BoolTest::eq));
1709 
1710   if (!too_many_traps(Deoptimization::Reason_intrinsic)) {
1711     { BuildCutout unless(this, bolisnum, PROB_STATIC_FREQUENT);
1712       // The pow or exp intrinsic returned a NaN, which requires a call
1713       // to the runtime.  Recompile with the runtime call.
1714       uncommon_trap(Deoptimization::Reason_intrinsic,
1715                     Deoptimization::Action_make_not_entrant);
1716     }
1717     return result;
1718   } else {
1719     // If this inlining ever returned NaN in the past, we compile a call
1720     // to the runtime to properly handle corner cases
1721 
1722     IfNode* iff = create_and_xform_if(control(), bolisnum, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
1723     Node* if_slow = _gvn.transform(new IfFalseNode(iff));
1724     Node* if_fast = _gvn.transform(new IfTrueNode(iff));
1725 
1726     if (!if_slow->is_top()) {
1727       RegionNode* result_region = new RegionNode(3);
1728       PhiNode*    result_val = new PhiNode(result_region, Type::DOUBLE);
1729 
1730       result_region->init_req(1, if_fast);
1731       result_val->init_req(1, result);
1732 
1733       set_control(if_slow);
1734 
1735       const TypePtr* no_memory_effects = NULL;
1736       Node* rt = make_runtime_call(RC_LEAF, call_type, funcAddr, funcName,
1737                                    no_memory_effects,
1738                                    x, top(), y, y ? top() : NULL);
1739       Node* value = _gvn.transform(new ProjNode(rt, TypeFunc::Parms+0));
1740 #ifdef ASSERT
1741       Node* value_top = _gvn.transform(new ProjNode(rt, TypeFunc::Parms+1));
1742       assert(value_top == top(), "second value must be top");
1743 #endif
1744 
1745       result_region->init_req(2, control());
1746       result_val->init_req(2, value);
1747       set_control(_gvn.transform(result_region));
1748       return _gvn.transform(result_val);
1749     } else {
1750       return result;
1751     }
1752   }
1753 }
1754 
1755 //------------------------------inline_exp-------------------------------------
1756 // Inline exp instructions, if possible.  The Intel hardware only misses
1757 // really odd corner cases (+/- Infinity).  Just uncommon-trap them.
1758 bool LibraryCallKit::inline_exp() {
1759   Node* arg = round_double_node(argument(0));
1760   Node* n   = _gvn.transform(new ExpDNode(C, control(), arg));
1761 
1762   n = finish_pow_exp(n, arg, NULL, OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dexp), "EXP");
1763   set_result(n);
1764 
1765   C->set_has_split_ifs(true); // Has chance for split-if optimization
1766   return true;
1767 }
1768 
1769 //------------------------------inline_pow-------------------------------------
1770 // Inline power instructions, if possible.
1771 bool LibraryCallKit::inline_pow() {
1772   // Pseudocode for pow
1773   // if (y == 2) {
1774   //   return x * x;
1775   // } else {
1776   //   if (x <= 0.0) {
1777   //     long longy = (long)y;
1778   //     if ((double)longy == y) { // if y is long
1779   //       if (y + 1 == y) longy = 0; // huge number: even
1780   //       result = ((1&longy) == 0)?-DPow(abs(x), y):DPow(abs(x), y);
1781   //     } else {
1782   //       result = NaN;
1783   //     }
1784   //   } else {
1785   //     result = DPow(x,y);
1786   //   }
1787   //   if (result != result)?  {
1788   //     result = uncommon_trap() or runtime_call();
1789   //   }
1790   //   return result;
1791   // }
1792 
1793   Node* x = round_double_node(argument(0));
1794   Node* y = round_double_node(argument(2));
1795 
1796   Node* result = NULL;
1797 
1798   Node*   const_two_node = makecon(TypeD::make(2.0));
1799   Node*   cmp_node       = _gvn.transform(new CmpDNode(y, const_two_node));
1800   Node*   bool_node      = _gvn.transform(new BoolNode(cmp_node, BoolTest::eq));
1801   IfNode* if_node        = create_and_xform_if(control(), bool_node, PROB_STATIC_INFREQUENT, COUNT_UNKNOWN);
1802   Node*   if_true        = _gvn.transform(new IfTrueNode(if_node));
1803   Node*   if_false       = _gvn.transform(new IfFalseNode(if_node));
1804 
1805   RegionNode* region_node = new RegionNode(3);
1806   region_node->init_req(1, if_true);
1807 
1808   Node* phi_node = new PhiNode(region_node, Type::DOUBLE);
1809   // special case for x^y where y == 2, we can convert it to x * x
1810   phi_node->init_req(1, _gvn.transform(new MulDNode(x, x)));
1811 
1812   // set control to if_false since we will now process the false branch
1813   set_control(if_false);
1814 
1815   if (!too_many_traps(Deoptimization::Reason_intrinsic)) {
1816     // Short form: skip the fancy tests and just check for NaN result.
1817     result = _gvn.transform(new PowDNode(C, control(), x, y));
1818   } else {
1819     // If this inlining ever returned NaN in the past, include all
1820     // checks + call to the runtime.
1821 
1822     // Set the merge point for If node with condition of (x <= 0.0)
1823     // There are four possible paths to region node and phi node
1824     RegionNode *r = new RegionNode(4);
1825     Node *phi = new PhiNode(r, Type::DOUBLE);
1826 
1827     // Build the first if node: if (x <= 0.0)
1828     // Node for 0 constant
1829     Node *zeronode = makecon(TypeD::ZERO);
1830     // Check x:0
1831     Node *cmp = _gvn.transform(new CmpDNode(x, zeronode));
1832     // Check: If (x<=0) then go complex path
1833     Node *bol1 = _gvn.transform(new BoolNode( cmp, BoolTest::le ));
1834     // Branch either way
1835     IfNode *if1 = create_and_xform_if(control(),bol1, PROB_STATIC_INFREQUENT, COUNT_UNKNOWN);
1836     // Fast path taken; set region slot 3
1837     Node *fast_taken = _gvn.transform(new IfFalseNode(if1));
1838     r->init_req(3,fast_taken); // Capture fast-control
1839 
1840     // Fast path not-taken, i.e. slow path
1841     Node *complex_path = _gvn.transform(new IfTrueNode(if1));
1842 
1843     // Set fast path result
1844     Node *fast_result = _gvn.transform(new PowDNode(C, control(), x, y));
1845     phi->init_req(3, fast_result);
1846 
1847     // Complex path
1848     // Build the second if node (if y is long)
1849     // Node for (long)y
1850     Node *longy = _gvn.transform(new ConvD2LNode(y));
1851     // Node for (double)((long) y)
1852     Node *doublelongy= _gvn.transform(new ConvL2DNode(longy));
1853     // Check (double)((long) y) : y
1854     Node *cmplongy= _gvn.transform(new CmpDNode(doublelongy, y));
1855     // Check if (y isn't long) then go to slow path
1856 
1857     Node *bol2 = _gvn.transform(new BoolNode( cmplongy, BoolTest::ne ));
1858     // Branch either way
1859     IfNode *if2 = create_and_xform_if(complex_path,bol2, PROB_STATIC_INFREQUENT, COUNT_UNKNOWN);
1860     Node* ylong_path = _gvn.transform(new IfFalseNode(if2));
1861 
1862     Node *slow_path = _gvn.transform(new IfTrueNode(if2));
1863 
1864     // Calculate DPow(abs(x), y)*(1 & (long)y)
1865     // Node for constant 1
1866     Node *conone = longcon(1);
1867     // 1& (long)y
1868     Node *signnode= _gvn.transform(new AndLNode(conone, longy));
1869 
1870     // A huge number is always even. Detect a huge number by checking
1871     // if y + 1 == y and set integer to be tested for parity to 0.
1872     // Required for corner case:
1873     // (long)9.223372036854776E18 = max_jlong
1874     // (double)(long)9.223372036854776E18 = 9.223372036854776E18
1875     // max_jlong is odd but 9.223372036854776E18 is even
1876     Node* yplus1 = _gvn.transform(new AddDNode(y, makecon(TypeD::make(1))));
1877     Node *cmpyplus1= _gvn.transform(new CmpDNode(yplus1, y));
1878     Node *bolyplus1 = _gvn.transform(new BoolNode( cmpyplus1, BoolTest::eq ));
1879     Node* correctedsign = NULL;
1880     if (ConditionalMoveLimit != 0) {
1881       correctedsign = _gvn.transform(CMoveNode::make(NULL, bolyplus1, signnode, longcon(0), TypeLong::LONG));
1882     } else {
1883       IfNode *ifyplus1 = create_and_xform_if(ylong_path,bolyplus1, PROB_FAIR, COUNT_UNKNOWN);
1884       RegionNode *r = new RegionNode(3);
1885       Node *phi = new PhiNode(r, TypeLong::LONG);
1886       r->init_req(1, _gvn.transform(new IfFalseNode(ifyplus1)));
1887       r->init_req(2, _gvn.transform(new IfTrueNode(ifyplus1)));
1888       phi->init_req(1, signnode);
1889       phi->init_req(2, longcon(0));
1890       correctedsign = _gvn.transform(phi);
1891       ylong_path = _gvn.transform(r);
1892       record_for_igvn(r);
1893     }
1894 
1895     // zero node
1896     Node *conzero = longcon(0);
1897     // Check (1&(long)y)==0?
1898     Node *cmpeq1 = _gvn.transform(new CmpLNode(correctedsign, conzero));
1899     // Check if (1&(long)y)!=0?, if so the result is negative
1900     Node *bol3 = _gvn.transform(new BoolNode( cmpeq1, BoolTest::ne ));
1901     // abs(x)
1902     Node *absx=_gvn.transform(new AbsDNode(x));
1903     // abs(x)^y
1904     Node *absxpowy = _gvn.transform(new PowDNode(C, control(), absx, y));
1905     // -abs(x)^y
1906     Node *negabsxpowy = _gvn.transform(new NegDNode (absxpowy));
1907     // (1&(long)y)==1?-DPow(abs(x), y):DPow(abs(x), y)
1908     Node *signresult = NULL;
1909     if (ConditionalMoveLimit != 0) {
1910       signresult = _gvn.transform(CMoveNode::make(NULL, bol3, absxpowy, negabsxpowy, Type::DOUBLE));
1911     } else {
1912       IfNode *ifyeven = create_and_xform_if(ylong_path,bol3, PROB_FAIR, COUNT_UNKNOWN);
1913       RegionNode *r = new RegionNode(3);
1914       Node *phi = new PhiNode(r, Type::DOUBLE);
1915       r->init_req(1, _gvn.transform(new IfFalseNode(ifyeven)));
1916       r->init_req(2, _gvn.transform(new IfTrueNode(ifyeven)));
1917       phi->init_req(1, absxpowy);
1918       phi->init_req(2, negabsxpowy);
1919       signresult = _gvn.transform(phi);
1920       ylong_path = _gvn.transform(r);
1921       record_for_igvn(r);
1922     }
1923     // Set complex path fast result
1924     r->init_req(2, ylong_path);
1925     phi->init_req(2, signresult);
1926 
1927     static const jlong nan_bits = CONST64(0x7ff8000000000000);
1928     Node *slow_result = makecon(TypeD::make(*(double*)&nan_bits)); // return NaN
1929     r->init_req(1,slow_path);
1930     phi->init_req(1,slow_result);
1931 
1932     // Post merge
1933     set_control(_gvn.transform(r));
1934     record_for_igvn(r);
1935     result = _gvn.transform(phi);
1936   }
1937 
1938   result = finish_pow_exp(result, x, y, OptoRuntime::Math_DD_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dpow), "POW");
1939 
1940   // control from finish_pow_exp is now input to the region node
1941   region_node->set_req(2, control());
1942   // the result from finish_pow_exp is now input to the phi node
1943   phi_node->init_req(2, result);
1944   set_control(_gvn.transform(region_node));
1945   record_for_igvn(region_node);
1946   set_result(_gvn.transform(phi_node));
1947 
1948   C->set_has_split_ifs(true); // Has chance for split-if optimization
1949   return true;
1950 }
1951 
1952 //------------------------------runtime_math-----------------------------
1953 bool LibraryCallKit::runtime_math(const TypeFunc* call_type, address funcAddr, const char* funcName) {
1954   assert(call_type == OptoRuntime::Math_DD_D_Type() || call_type == OptoRuntime::Math_D_D_Type(),
1955          "must be (DD)D or (D)D type");
1956 
1957   // Inputs
1958   Node* a = round_double_node(argument(0));
1959   Node* b = (call_type == OptoRuntime::Math_DD_D_Type()) ? round_double_node(argument(2)) : NULL;
1960 
1961   const TypePtr* no_memory_effects = NULL;
1962   Node* trig = make_runtime_call(RC_LEAF, call_type, funcAddr, funcName,
1963                                  no_memory_effects,
1964                                  a, top(), b, b ? top() : NULL);
1965   Node* value = _gvn.transform(new ProjNode(trig, TypeFunc::Parms+0));
1966 #ifdef ASSERT
1967   Node* value_top = _gvn.transform(new ProjNode(trig, TypeFunc::Parms+1));
1968   assert(value_top == top(), "second value must be top");
1969 #endif
1970 
1971   set_result(value);
1972   return true;
1973 }
1974 
1975 //------------------------------inline_math_native-----------------------------
1976 bool LibraryCallKit::inline_math_native(vmIntrinsics::ID id) {
1977 #define FN_PTR(f) CAST_FROM_FN_PTR(address, f)
1978   switch (id) {
1979     // These intrinsics are not properly supported on all hardware
1980   case vmIntrinsics::_dcos:   return Matcher::has_match_rule(Op_CosD)   ? inline_trig(id) :
1981     runtime_math(OptoRuntime::Math_D_D_Type(), FN_PTR(SharedRuntime::dcos),   "COS");
1982   case vmIntrinsics::_dsin:   return Matcher::has_match_rule(Op_SinD)   ? inline_trig(id) :
1983     runtime_math(OptoRuntime::Math_D_D_Type(), FN_PTR(SharedRuntime::dsin),   "SIN");
1984   case vmIntrinsics::_dtan:   return Matcher::has_match_rule(Op_TanD)   ? inline_trig(id) :
1985     runtime_math(OptoRuntime::Math_D_D_Type(), FN_PTR(SharedRuntime::dtan),   "TAN");
1986 
1987   case vmIntrinsics::_dlog:   return Matcher::has_match_rule(Op_LogD)   ? inline_math(id) :
1988     runtime_math(OptoRuntime::Math_D_D_Type(), FN_PTR(SharedRuntime::dlog),   "LOG");
1989   case vmIntrinsics::_dlog10: return Matcher::has_match_rule(Op_Log10D) ? inline_math(id) :
1990     runtime_math(OptoRuntime::Math_D_D_Type(), FN_PTR(SharedRuntime::dlog10), "LOG10");
1991 
1992     // These intrinsics are supported on all hardware
1993   case vmIntrinsics::_dsqrt:  return Matcher::match_rule_supported(Op_SqrtD) ? inline_math(id) : false;
1994   case vmIntrinsics::_dabs:   return Matcher::has_match_rule(Op_AbsD)   ? inline_math(id) : false;
1995 
1996   case vmIntrinsics::_dexp:   return Matcher::has_match_rule(Op_ExpD)   ? inline_exp()    :
1997     runtime_math(OptoRuntime::Math_D_D_Type(),  FN_PTR(SharedRuntime::dexp),  "EXP");
1998   case vmIntrinsics::_dpow:   return Matcher::has_match_rule(Op_PowD)   ? inline_pow()    :
1999     runtime_math(OptoRuntime::Math_DD_D_Type(), FN_PTR(SharedRuntime::dpow),  "POW");
2000 #undef FN_PTR
2001 
2002    // These intrinsics are not yet correctly implemented
2003   case vmIntrinsics::_datan2:
2004     return false;
2005 
2006   default:
2007     fatal_unexpected_iid(id);
2008     return false;
2009   }
2010 }
2011 
2012 static bool is_simple_name(Node* n) {
2013   return (n->req() == 1         // constant
2014           || (n->is_Type() && n->as_Type()->type()->singleton())
2015           || n->is_Proj()       // parameter or return value
2016           || n->is_Phi()        // local of some sort
2017           );
2018 }
2019 















2020 //----------------------------inline_min_max-----------------------------------
2021 bool LibraryCallKit::inline_min_max(vmIntrinsics::ID id) {
2022   set_result(generate_min_max(id, argument(0), argument(1)));
2023   return true;
2024 }
2025 
2026 void LibraryCallKit::inline_math_mathExact(Node* math, Node *test) {
2027   Node* bol = _gvn.transform( new BoolNode(test, BoolTest::overflow) );
2028   IfNode* check = create_and_map_if(control(), bol, PROB_UNLIKELY_MAG(3), COUNT_UNKNOWN);
2029   Node* fast_path = _gvn.transform( new IfFalseNode(check));
2030   Node* slow_path = _gvn.transform( new IfTrueNode(check) );
2031 
2032   {
2033     PreserveJVMState pjvms(this);
2034     PreserveReexecuteState preexecs(this);
2035     jvms()->set_should_reexecute(true);
2036 
2037     set_control(slow_path);
2038     set_i_o(i_o());
2039 
2040     uncommon_trap(Deoptimization::Reason_intrinsic,
2041                   Deoptimization::Action_none);
2042   }
2043 
2044   set_control(fast_path);
2045   set_result(math);
2046 }
2047 
2048 template <typename OverflowOp>
2049 bool LibraryCallKit::inline_math_overflow(Node* arg1, Node* arg2) {
2050   typedef typename OverflowOp::MathOp MathOp;
2051 
2052   MathOp* mathOp = new MathOp(arg1, arg2);
2053   Node* operation = _gvn.transform( mathOp );
2054   Node* ofcheck = _gvn.transform( new OverflowOp(arg1, arg2) );
2055   inline_math_mathExact(operation, ofcheck);
2056   return true;
2057 }
2058 
2059 bool LibraryCallKit::inline_math_addExactI(bool is_increment) {
2060   return inline_math_overflow<OverflowAddINode>(argument(0), is_increment ? intcon(1) : argument(1));
2061 }
2062 
2063 bool LibraryCallKit::inline_math_addExactL(bool is_increment) {
2064   return inline_math_overflow<OverflowAddLNode>(argument(0), is_increment ? longcon(1) : argument(2));
2065 }
2066 
2067 bool LibraryCallKit::inline_math_subtractExactI(bool is_decrement) {
2068   return inline_math_overflow<OverflowSubINode>(argument(0), is_decrement ? intcon(1) : argument(1));
2069 }
2070 
2071 bool LibraryCallKit::inline_math_subtractExactL(bool is_decrement) {
2072   return inline_math_overflow<OverflowSubLNode>(argument(0), is_decrement ? longcon(1) : argument(2));
2073 }
2074 
2075 bool LibraryCallKit::inline_math_negateExactI() {
2076   return inline_math_overflow<OverflowSubINode>(intcon(0), argument(0));
2077 }
2078 
2079 bool LibraryCallKit::inline_math_negateExactL() {
2080   return inline_math_overflow<OverflowSubLNode>(longcon(0), argument(0));
2081 }
2082 
2083 bool LibraryCallKit::inline_math_multiplyExactI() {
2084   return inline_math_overflow<OverflowMulINode>(argument(0), argument(1));
2085 }
2086 
2087 bool LibraryCallKit::inline_math_multiplyExactL() {
2088   return inline_math_overflow<OverflowMulLNode>(argument(0), argument(2));
2089 }
2090 
2091 Node*
2092 LibraryCallKit::generate_min_max(vmIntrinsics::ID id, Node* x0, Node* y0) {
2093   // These are the candidate return value:
2094   Node* xvalue = x0;
2095   Node* yvalue = y0;
2096 
2097   if (xvalue == yvalue) {
2098     return xvalue;
2099   }
2100 
2101   bool want_max = (id == vmIntrinsics::_max);
2102 
2103   const TypeInt* txvalue = _gvn.type(xvalue)->isa_int();
2104   const TypeInt* tyvalue = _gvn.type(yvalue)->isa_int();
2105   if (txvalue == NULL || tyvalue == NULL)  return top();
2106   // This is not really necessary, but it is consistent with a
2107   // hypothetical MaxINode::Value method:
2108   int widen = MAX2(txvalue->_widen, tyvalue->_widen);
2109 
2110   // %%% This folding logic should (ideally) be in a different place.
2111   // Some should be inside IfNode, and there to be a more reliable
2112   // transformation of ?: style patterns into cmoves.  We also want
2113   // more powerful optimizations around cmove and min/max.
2114 
2115   // Try to find a dominating comparison of these guys.
2116   // It can simplify the index computation for Arrays.copyOf
2117   // and similar uses of System.arraycopy.
2118   // First, compute the normalized version of CmpI(x, y).
2119   int   cmp_op = Op_CmpI;
2120   Node* xkey = xvalue;
2121   Node* ykey = yvalue;
2122   Node* ideal_cmpxy = _gvn.transform(new CmpINode(xkey, ykey));
2123   if (ideal_cmpxy->is_Cmp()) {
2124     // E.g., if we have CmpI(length - offset, count),
2125     // it might idealize to CmpI(length, count + offset)
2126     cmp_op = ideal_cmpxy->Opcode();
2127     xkey = ideal_cmpxy->in(1);
2128     ykey = ideal_cmpxy->in(2);
2129   }
2130 
2131   // Start by locating any relevant comparisons.
2132   Node* start_from = (xkey->outcnt() < ykey->outcnt()) ? xkey : ykey;
2133   Node* cmpxy = NULL;
2134   Node* cmpyx = NULL;
2135   for (DUIterator_Fast kmax, k = start_from->fast_outs(kmax); k < kmax; k++) {
2136     Node* cmp = start_from->fast_out(k);
2137     if (cmp->outcnt() > 0 &&            // must have prior uses
2138         cmp->in(0) == NULL &&           // must be context-independent
2139         cmp->Opcode() == cmp_op) {      // right kind of compare
2140       if (cmp->in(1) == xkey && cmp->in(2) == ykey)  cmpxy = cmp;
2141       if (cmp->in(1) == ykey && cmp->in(2) == xkey)  cmpyx = cmp;
2142     }
2143   }
2144 
2145   const int NCMPS = 2;
2146   Node* cmps[NCMPS] = { cmpxy, cmpyx };
2147   int cmpn;
2148   for (cmpn = 0; cmpn < NCMPS; cmpn++) {
2149     if (cmps[cmpn] != NULL)  break;     // find a result
2150   }
2151   if (cmpn < NCMPS) {
2152     // Look for a dominating test that tells us the min and max.
2153     int depth = 0;                // Limit search depth for speed
2154     Node* dom = control();
2155     for (; dom != NULL; dom = IfNode::up_one_dom(dom, true)) {
2156       if (++depth >= 100)  break;
2157       Node* ifproj = dom;
2158       if (!ifproj->is_Proj())  continue;
2159       Node* iff = ifproj->in(0);
2160       if (!iff->is_If())  continue;
2161       Node* bol = iff->in(1);
2162       if (!bol->is_Bool())  continue;
2163       Node* cmp = bol->in(1);
2164       if (cmp == NULL)  continue;
2165       for (cmpn = 0; cmpn < NCMPS; cmpn++)
2166         if (cmps[cmpn] == cmp)  break;
2167       if (cmpn == NCMPS)  continue;
2168       BoolTest::mask btest = bol->as_Bool()->_test._test;
2169       if (ifproj->is_IfFalse())  btest = BoolTest(btest).negate();
2170       if (cmp->in(1) == ykey)    btest = BoolTest(btest).commute();
2171       // At this point, we know that 'x btest y' is true.
2172       switch (btest) {
2173       case BoolTest::eq:
2174         // They are proven equal, so we can collapse the min/max.
2175         // Either value is the answer.  Choose the simpler.
2176         if (is_simple_name(yvalue) && !is_simple_name(xvalue))
2177           return yvalue;
2178         return xvalue;
2179       case BoolTest::lt:          // x < y
2180       case BoolTest::le:          // x <= y
2181         return (want_max ? yvalue : xvalue);
2182       case BoolTest::gt:          // x > y
2183       case BoolTest::ge:          // x >= y
2184         return (want_max ? xvalue : yvalue);
2185       }
2186     }
2187   }
2188 
2189   // We failed to find a dominating test.
2190   // Let's pick a test that might GVN with prior tests.
2191   Node*          best_bol   = NULL;
2192   BoolTest::mask best_btest = BoolTest::illegal;
2193   for (cmpn = 0; cmpn < NCMPS; cmpn++) {
2194     Node* cmp = cmps[cmpn];
2195     if (cmp == NULL)  continue;
2196     for (DUIterator_Fast jmax, j = cmp->fast_outs(jmax); j < jmax; j++) {
2197       Node* bol = cmp->fast_out(j);
2198       if (!bol->is_Bool())  continue;
2199       BoolTest::mask btest = bol->as_Bool()->_test._test;
2200       if (btest == BoolTest::eq || btest == BoolTest::ne)  continue;
2201       if (cmp->in(1) == ykey)   btest = BoolTest(btest).commute();
2202       if (bol->outcnt() > (best_bol == NULL ? 0 : best_bol->outcnt())) {
2203         best_bol   = bol->as_Bool();
2204         best_btest = btest;
2205       }
2206     }
2207   }
2208 
2209   Node* answer_if_true  = NULL;
2210   Node* answer_if_false = NULL;
2211   switch (best_btest) {
2212   default:
2213     if (cmpxy == NULL)
2214       cmpxy = ideal_cmpxy;
2215     best_bol = _gvn.transform(new BoolNode(cmpxy, BoolTest::lt));
2216     // and fall through:
2217   case BoolTest::lt:          // x < y
2218   case BoolTest::le:          // x <= y
2219     answer_if_true  = (want_max ? yvalue : xvalue);
2220     answer_if_false = (want_max ? xvalue : yvalue);
2221     break;
2222   case BoolTest::gt:          // x > y
2223   case BoolTest::ge:          // x >= y
2224     answer_if_true  = (want_max ? xvalue : yvalue);
2225     answer_if_false = (want_max ? yvalue : xvalue);
2226     break;
2227   }
2228 
2229   jint hi, lo;
2230   if (want_max) {
2231     // We can sharpen the minimum.
2232     hi = MAX2(txvalue->_hi, tyvalue->_hi);
2233     lo = MAX2(txvalue->_lo, tyvalue->_lo);
2234   } else {
2235     // We can sharpen the maximum.
2236     hi = MIN2(txvalue->_hi, tyvalue->_hi);
2237     lo = MIN2(txvalue->_lo, tyvalue->_lo);
2238   }
2239 
2240   // Use a flow-free graph structure, to avoid creating excess control edges
2241   // which could hinder other optimizations.
2242   // Since Math.min/max is often used with arraycopy, we want
2243   // tightly_coupled_allocation to be able to see beyond min/max expressions.
2244   Node* cmov = CMoveNode::make(NULL, best_bol,
2245                                answer_if_false, answer_if_true,
2246                                TypeInt::make(lo, hi, widen));
2247 
2248   return _gvn.transform(cmov);
2249 
2250   /*
2251   // This is not as desirable as it may seem, since Min and Max
2252   // nodes do not have a full set of optimizations.
2253   // And they would interfere, anyway, with 'if' optimizations
2254   // and with CMoveI canonical forms.
2255   switch (id) {
2256   case vmIntrinsics::_min:
2257     result_val = _gvn.transform(new (C, 3) MinINode(x,y)); break;
2258   case vmIntrinsics::_max:
2259     result_val = _gvn.transform(new (C, 3) MaxINode(x,y)); break;
2260   default:
2261     ShouldNotReachHere();
2262   }
2263   */
2264 }
2265 
2266 inline int
2267 LibraryCallKit::classify_unsafe_addr(Node* &base, Node* &offset) {
2268   const TypePtr* base_type = TypePtr::NULL_PTR;
2269   if (base != NULL)  base_type = _gvn.type(base)->isa_ptr();
2270   if (base_type == NULL) {
2271     // Unknown type.
2272     return Type::AnyPtr;
2273   } else if (base_type == TypePtr::NULL_PTR) {
2274     // Since this is a NULL+long form, we have to switch to a rawptr.
2275     base   = _gvn.transform(new CastX2PNode(offset));
2276     offset = MakeConX(0);
2277     return Type::RawPtr;
2278   } else if (base_type->base() == Type::RawPtr) {
2279     return Type::RawPtr;
2280   } else if (base_type->isa_oopptr()) {
2281     // Base is never null => always a heap address.
2282     if (base_type->ptr() == TypePtr::NotNull) {
2283       return Type::OopPtr;
2284     }
2285     // Offset is small => always a heap address.
2286     const TypeX* offset_type = _gvn.type(offset)->isa_intptr_t();
2287     if (offset_type != NULL &&
2288         base_type->offset() == 0 &&     // (should always be?)
2289         offset_type->_lo >= 0 &&
2290         !MacroAssembler::needs_explicit_null_check(offset_type->_hi)) {
2291       return Type::OopPtr;
2292     }
2293     // Otherwise, it might either be oop+off or NULL+addr.
2294     return Type::AnyPtr;
2295   } else {
2296     // No information:
2297     return Type::AnyPtr;
2298   }
2299 }
2300 
2301 inline Node* LibraryCallKit::make_unsafe_address(Node* base, Node* offset) {
2302   int kind = classify_unsafe_addr(base, offset);
2303   if (kind == Type::RawPtr) {
2304     return basic_plus_adr(top(), base, offset);
2305   } else {
2306     return basic_plus_adr(base, offset);
2307   }
2308 }
2309 
2310 //--------------------------inline_number_methods-----------------------------
2311 // inline int     Integer.numberOfLeadingZeros(int)
2312 // inline int        Long.numberOfLeadingZeros(long)
2313 //
2314 // inline int     Integer.numberOfTrailingZeros(int)
2315 // inline int        Long.numberOfTrailingZeros(long)
2316 //
2317 // inline int     Integer.bitCount(int)
2318 // inline int        Long.bitCount(long)
2319 //
2320 // inline char  Character.reverseBytes(char)
2321 // inline short     Short.reverseBytes(short)
2322 // inline int     Integer.reverseBytes(int)
2323 // inline long       Long.reverseBytes(long)
2324 bool LibraryCallKit::inline_number_methods(vmIntrinsics::ID id) {
2325   Node* arg = argument(0);
2326   Node* n;
2327   switch (id) {
2328   case vmIntrinsics::_numberOfLeadingZeros_i:   n = new CountLeadingZerosINode( arg);  break;
2329   case vmIntrinsics::_numberOfLeadingZeros_l:   n = new CountLeadingZerosLNode( arg);  break;
2330   case vmIntrinsics::_numberOfTrailingZeros_i:  n = new CountTrailingZerosINode(arg);  break;
2331   case vmIntrinsics::_numberOfTrailingZeros_l:  n = new CountTrailingZerosLNode(arg);  break;
2332   case vmIntrinsics::_bitCount_i:               n = new PopCountINode(          arg);  break;
2333   case vmIntrinsics::_bitCount_l:               n = new PopCountLNode(          arg);  break;
2334   case vmIntrinsics::_reverseBytes_c:           n = new ReverseBytesUSNode(0,   arg);  break;
2335   case vmIntrinsics::_reverseBytes_s:           n = new ReverseBytesSNode( 0,   arg);  break;
2336   case vmIntrinsics::_reverseBytes_i:           n = new ReverseBytesINode( 0,   arg);  break;
2337   case vmIntrinsics::_reverseBytes_l:           n = new ReverseBytesLNode( 0,   arg);  break;
2338   default:  fatal_unexpected_iid(id);  break;
2339   }
2340   set_result(_gvn.transform(n));
2341   return true;
2342 }
2343 
2344 //----------------------------inline_unsafe_access----------------------------
2345 
2346 const static BasicType T_ADDRESS_HOLDER = T_LONG;
2347 
2348 // Helper that guards and inserts a pre-barrier.
2349 void LibraryCallKit::insert_pre_barrier(Node* base_oop, Node* offset,
2350                                         Node* pre_val, bool need_mem_bar) {
2351   // We could be accessing the referent field of a reference object. If so, when G1
2352   // is enabled, we need to log the value in the referent field in an SATB buffer.
2353   // This routine performs some compile time filters and generates suitable
2354   // runtime filters that guard the pre-barrier code.
2355   // Also add memory barrier for non volatile load from the referent field
2356   // to prevent commoning of loads across safepoint.
2357   if (!UseG1GC && !need_mem_bar)
2358     return;
2359 
2360   // Some compile time checks.
2361 
2362   // If offset is a constant, is it java_lang_ref_Reference::_reference_offset?
2363   const TypeX* otype = offset->find_intptr_t_type();
2364   if (otype != NULL && otype->is_con() &&
2365       otype->get_con() != java_lang_ref_Reference::referent_offset) {
2366     // Constant offset but not the reference_offset so just return
2367     return;
2368   }
2369 
2370   // We only need to generate the runtime guards for instances.
2371   const TypeOopPtr* btype = base_oop->bottom_type()->isa_oopptr();
2372   if (btype != NULL) {
2373     if (btype->isa_aryptr()) {
2374       // Array type so nothing to do
2375       return;
2376     }
2377 
2378     const TypeInstPtr* itype = btype->isa_instptr();
2379     if (itype != NULL) {
2380       // Can the klass of base_oop be statically determined to be
2381       // _not_ a sub-class of Reference and _not_ Object?
2382       ciKlass* klass = itype->klass();
2383       if ( klass->is_loaded() &&
2384           !klass->is_subtype_of(env()->Reference_klass()) &&
2385           !env()->Object_klass()->is_subtype_of(klass)) {
2386         return;
2387       }
2388     }
2389   }
2390 
2391   // The compile time filters did not reject base_oop/offset so
2392   // we need to generate the following runtime filters
2393   //
2394   // if (offset == java_lang_ref_Reference::_reference_offset) {
2395   //   if (instance_of(base, java.lang.ref.Reference)) {
2396   //     pre_barrier(_, pre_val, ...);
2397   //   }
2398   // }
2399 
2400   float likely   = PROB_LIKELY(  0.999);
2401   float unlikely = PROB_UNLIKELY(0.999);
2402 
2403   IdealKit ideal(this);
2404 #define __ ideal.
2405 
2406   Node* referent_off = __ ConX(java_lang_ref_Reference::referent_offset);
2407 
2408   __ if_then(offset, BoolTest::eq, referent_off, unlikely); {
2409       // Update graphKit memory and control from IdealKit.
2410       sync_kit(ideal);
2411 
2412       Node* ref_klass_con = makecon(TypeKlassPtr::make(env()->Reference_klass()));
2413       Node* is_instof = gen_instanceof(base_oop, ref_klass_con);
2414 
2415       // Update IdealKit memory and control from graphKit.
2416       __ sync_kit(this);
2417 
2418       Node* one = __ ConI(1);
2419       // is_instof == 0 if base_oop == NULL
2420       __ if_then(is_instof, BoolTest::eq, one, unlikely); {
2421 
2422         // Update graphKit from IdeakKit.
2423         sync_kit(ideal);
2424 
2425         // Use the pre-barrier to record the value in the referent field
2426         pre_barrier(false /* do_load */,
2427                     __ ctrl(),
2428                     NULL /* obj */, NULL /* adr */, max_juint /* alias_idx */, NULL /* val */, NULL /* val_type */,
2429                     pre_val /* pre_val */,
2430                     T_OBJECT);
2431         if (need_mem_bar) {
2432           // Add memory barrier to prevent commoning reads from this field
2433           // across safepoint since GC can change its value.
2434           insert_mem_bar(Op_MemBarCPUOrder);
2435         }
2436         // Update IdealKit from graphKit.
2437         __ sync_kit(this);
2438 
2439       } __ end_if(); // _ref_type != ref_none
2440   } __ end_if(); // offset == referent_offset
2441 
2442   // Final sync IdealKit and GraphKit.
2443   final_sync(ideal);
2444 #undef __
2445 }
2446 
2447 
2448 // Interpret Unsafe.fieldOffset cookies correctly:
2449 extern jlong Unsafe_field_offset_to_byte_offset(jlong field_offset);
2450 
2451 const TypeOopPtr* LibraryCallKit::sharpen_unsafe_type(Compile::AliasType* alias_type, const TypePtr *adr_type, bool is_native_ptr) {
2452   // Attempt to infer a sharper value type from the offset and base type.
2453   ciKlass* sharpened_klass = NULL;
2454 
2455   // See if it is an instance field, with an object type.
2456   if (alias_type->field() != NULL) {
2457     assert(!is_native_ptr, "native pointer op cannot use a java address");
2458     if (alias_type->field()->type()->is_klass()) {
2459       sharpened_klass = alias_type->field()->type()->as_klass();
2460     }
2461   }
2462 
2463   // See if it is a narrow oop array.
2464   if (adr_type->isa_aryptr()) {
2465     if (adr_type->offset() >= objArrayOopDesc::base_offset_in_bytes()) {
2466       const TypeOopPtr *elem_type = adr_type->is_aryptr()->elem()->isa_oopptr();
2467       if (elem_type != NULL) {
2468         sharpened_klass = elem_type->klass();
2469       }
2470     }
2471   }
2472 
2473   // The sharpened class might be unloaded if there is no class loader
2474   // contraint in place.
2475   if (sharpened_klass != NULL && sharpened_klass->is_loaded()) {
2476     const TypeOopPtr* tjp = TypeOopPtr::make_from_klass(sharpened_klass);
2477 
2478 #ifndef PRODUCT
2479     if (C->print_intrinsics() || C->print_inlining()) {
2480       tty->print("  from base type: ");  adr_type->dump();
2481       tty->print("  sharpened value: ");  tjp->dump();
2482     }
2483 #endif
2484     // Sharpen the value type.
2485     return tjp;
2486   }
2487   return NULL;
2488 }
2489 
2490 bool LibraryCallKit::inline_unsafe_access(bool is_native_ptr, bool is_store, BasicType type, bool is_volatile) {
2491   if (callee()->is_static())  return false;  // caller must have the capability!
2492 
2493 #ifndef PRODUCT
2494   {
2495     ResourceMark rm;
2496     // Check the signatures.
2497     ciSignature* sig = callee()->signature();
2498 #ifdef ASSERT
2499     if (!is_store) {
2500       // Object getObject(Object base, int/long offset), etc.
2501       BasicType rtype = sig->return_type()->basic_type();
2502       if (rtype == T_ADDRESS_HOLDER && callee()->name() == ciSymbol::getAddress_name())
2503           rtype = T_ADDRESS;  // it is really a C void*
2504       assert(rtype == type, "getter must return the expected value");
2505       if (!is_native_ptr) {
2506         assert(sig->count() == 2, "oop getter has 2 arguments");
2507         assert(sig->type_at(0)->basic_type() == T_OBJECT, "getter base is object");
2508         assert(sig->type_at(1)->basic_type() == T_LONG, "getter offset is correct");
2509       } else {
2510         assert(sig->count() == 1, "native getter has 1 argument");
2511         assert(sig->type_at(0)->basic_type() == T_LONG, "getter base is long");
2512       }
2513     } else {
2514       // void putObject(Object base, int/long offset, Object x), etc.
2515       assert(sig->return_type()->basic_type() == T_VOID, "putter must not return a value");
2516       if (!is_native_ptr) {
2517         assert(sig->count() == 3, "oop putter has 3 arguments");
2518         assert(sig->type_at(0)->basic_type() == T_OBJECT, "putter base is object");
2519         assert(sig->type_at(1)->basic_type() == T_LONG, "putter offset is correct");
2520       } else {
2521         assert(sig->count() == 2, "native putter has 2 arguments");
2522         assert(sig->type_at(0)->basic_type() == T_LONG, "putter base is long");
2523       }
2524       BasicType vtype = sig->type_at(sig->count()-1)->basic_type();
2525       if (vtype == T_ADDRESS_HOLDER && callee()->name() == ciSymbol::putAddress_name())
2526         vtype = T_ADDRESS;  // it is really a C void*
2527       assert(vtype == type, "putter must accept the expected value");
2528     }
2529 #endif // ASSERT
2530  }
2531 #endif //PRODUCT
2532 
2533   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
2534 
2535   Node* receiver = argument(0);  // type: oop
2536 
2537   // Build address expression.
2538   Node* adr;
2539   Node* heap_base_oop = top();
2540   Node* offset = top();
2541   Node* val;
2542 
2543   if (!is_native_ptr) {
2544     // The base is either a Java object or a value produced by Unsafe.staticFieldBase
2545     Node* base = argument(1);  // type: oop
2546     // The offset is a value produced by Unsafe.staticFieldOffset or Unsafe.objectFieldOffset
2547     offset = argument(2);  // type: long
2548     // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
2549     // to be plain byte offsets, which are also the same as those accepted
2550     // by oopDesc::field_base.
2551     assert(Unsafe_field_offset_to_byte_offset(11) == 11,
2552            "fieldOffset must be byte-scaled");
2553     // 32-bit machines ignore the high half!
2554     offset = ConvL2X(offset);
2555     adr = make_unsafe_address(base, offset);
2556     heap_base_oop = base;
2557     val = is_store ? argument(4) : NULL;
2558   } else {
2559     Node* ptr = argument(1);  // type: long
2560     ptr = ConvL2X(ptr);  // adjust Java long to machine word
2561     adr = make_unsafe_address(NULL, ptr);
2562     val = is_store ? argument(3) : NULL;
2563   }
2564 
2565   const TypePtr *adr_type = _gvn.type(adr)->isa_ptr();
2566 
2567   // First guess at the value type.
2568   const Type *value_type = Type::get_const_basic_type(type);
2569 
2570   // Try to categorize the address.  If it comes up as TypeJavaPtr::BOTTOM,
2571   // there was not enough information to nail it down.
2572   Compile::AliasType* alias_type = C->alias_type(adr_type);
2573   assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
2574 
2575   // We will need memory barriers unless we can determine a unique
2576   // alias category for this reference.  (Note:  If for some reason
2577   // the barriers get omitted and the unsafe reference begins to "pollute"
2578   // the alias analysis of the rest of the graph, either Compile::can_alias
2579   // or Compile::must_alias will throw a diagnostic assert.)
2580   bool need_mem_bar = (alias_type->adr_type() == TypeOopPtr::BOTTOM);
2581 
2582   // If we are reading the value of the referent field of a Reference
2583   // object (either by using Unsafe directly or through reflection)
2584   // then, if G1 is enabled, we need to record the referent in an
2585   // SATB log buffer using the pre-barrier mechanism.
2586   // Also we need to add memory barrier to prevent commoning reads
2587   // from this field across safepoint since GC can change its value.
2588   bool need_read_barrier = !is_native_ptr && !is_store &&
2589                            offset != top() && heap_base_oop != top();
2590 
2591   if (!is_store && type == T_OBJECT) {
2592     const TypeOopPtr* tjp = sharpen_unsafe_type(alias_type, adr_type, is_native_ptr);
2593     if (tjp != NULL) {
2594       value_type = tjp;
2595     }
2596   }
2597 
2598   receiver = null_check(receiver);
2599   if (stopped()) {
2600     return true;
2601   }
2602   // Heap pointers get a null-check from the interpreter,
2603   // as a courtesy.  However, this is not guaranteed by Unsafe,
2604   // and it is not possible to fully distinguish unintended nulls
2605   // from intended ones in this API.
2606 
2607   if (is_volatile) {
2608     // We need to emit leading and trailing CPU membars (see below) in
2609     // addition to memory membars when is_volatile. This is a little
2610     // too strong, but avoids the need to insert per-alias-type
2611     // volatile membars (for stores; compare Parse::do_put_xxx), which
2612     // we cannot do effectively here because we probably only have a
2613     // rough approximation of type.
2614     need_mem_bar = true;
2615     // For Stores, place a memory ordering barrier now.
2616     if (is_store) {
2617       insert_mem_bar(Op_MemBarRelease);
2618     } else {
2619       if (support_IRIW_for_not_multiple_copy_atomic_cpu) {
2620         insert_mem_bar(Op_MemBarVolatile);
2621       }
2622     }
2623   }
2624 
2625   // Memory barrier to prevent normal and 'unsafe' accesses from
2626   // bypassing each other.  Happens after null checks, so the
2627   // exception paths do not take memory state from the memory barrier,
2628   // so there's no problems making a strong assert about mixing users
2629   // of safe & unsafe memory.
2630   if (need_mem_bar) insert_mem_bar(Op_MemBarCPUOrder);
2631 
2632   if (!is_store) {
2633     MemNode::MemOrd mo = is_volatile ? MemNode::acquire : MemNode::unordered;
2634     Node* p = make_load(control(), adr, value_type, type, adr_type, mo, is_volatile);
2635     // load value
2636     switch (type) {
2637     case T_BOOLEAN:
2638     case T_CHAR:
2639     case T_BYTE:
2640     case T_SHORT:
2641     case T_INT:
2642     case T_LONG:
2643     case T_FLOAT:
2644     case T_DOUBLE:
2645       break;
2646     case T_OBJECT:
2647       if (need_read_barrier) {
2648         insert_pre_barrier(heap_base_oop, offset, p, !(is_volatile || need_mem_bar));
2649       }
2650       break;
2651     case T_ADDRESS:
2652       // Cast to an int type.
2653       p = _gvn.transform(new CastP2XNode(NULL, p));
2654       p = ConvX2UL(p);
2655       break;
2656     default:
2657       fatal(err_msg_res("unexpected type %d: %s", type, type2name(type)));
2658       break;
2659     }
2660     // The load node has the control of the preceding MemBarCPUOrder.  All
2661     // following nodes will have the control of the MemBarCPUOrder inserted at
2662     // the end of this method.  So, pushing the load onto the stack at a later
2663     // point is fine.
2664     set_result(p);
2665   } else {
2666     // place effect of store into memory
2667     switch (type) {
2668     case T_DOUBLE:
2669       val = dstore_rounding(val);
2670       break;
2671     case T_ADDRESS:
2672       // Repackage the long as a pointer.
2673       val = ConvL2X(val);
2674       val = _gvn.transform(new CastX2PNode(val));
2675       break;
2676     }
2677 
2678     MemNode::MemOrd mo = is_volatile ? MemNode::release : MemNode::unordered;
2679     if (type != T_OBJECT ) {
2680       (void) store_to_memory(control(), adr, val, type, adr_type, mo, is_volatile);
2681     } else {
2682       // Possibly an oop being stored to Java heap or native memory
2683       if (!TypePtr::NULL_PTR->higher_equal(_gvn.type(heap_base_oop))) {
2684         // oop to Java heap.
2685         (void) store_oop_to_unknown(control(), heap_base_oop, adr, adr_type, val, type, mo);
2686       } else {
2687         // We can't tell at compile time if we are storing in the Java heap or outside
2688         // of it. So we need to emit code to conditionally do the proper type of
2689         // store.
2690 
2691         IdealKit ideal(this);
2692 #define __ ideal.
2693         // QQQ who knows what probability is here??
2694         __ if_then(heap_base_oop, BoolTest::ne, null(), PROB_UNLIKELY(0.999)); {
2695           // Sync IdealKit and graphKit.
2696           sync_kit(ideal);
2697           Node* st = store_oop_to_unknown(control(), heap_base_oop, adr, adr_type, val, type, mo);
2698           // Update IdealKit memory.
2699           __ sync_kit(this);
2700         } __ else_(); {
2701           __ store(__ ctrl(), adr, val, type, alias_type->index(), mo, is_volatile);
2702         } __ end_if();
2703         // Final sync IdealKit and GraphKit.
2704         final_sync(ideal);
2705 #undef __
2706       }
2707     }
2708   }
2709 
2710   if (is_volatile) {
2711     if (!is_store) {
2712       insert_mem_bar(Op_MemBarAcquire);
2713     } else {
2714       if (!support_IRIW_for_not_multiple_copy_atomic_cpu) {
2715         insert_mem_bar(Op_MemBarVolatile);
2716       }
2717     }
2718   }
2719 
2720   if (need_mem_bar) insert_mem_bar(Op_MemBarCPUOrder);
2721 
2722   return true;
2723 }
2724 
2725 //----------------------------inline_unsafe_load_store----------------------------
2726 // This method serves a couple of different customers (depending on LoadStoreKind):
2727 //
2728 // LS_cmpxchg:
2729 //   public final native boolean compareAndSwapObject(Object o, long offset, Object expected, Object x);
2730 //   public final native boolean compareAndSwapInt(   Object o, long offset, int    expected, int    x);
2731 //   public final native boolean compareAndSwapLong(  Object o, long offset, long   expected, long   x);
2732 //
2733 // LS_xadd:
2734 //   public int  getAndAddInt( Object o, long offset, int  delta)
2735 //   public long getAndAddLong(Object o, long offset, long delta)
2736 //
2737 // LS_xchg:
2738 //   int    getAndSet(Object o, long offset, int    newValue)
2739 //   long   getAndSet(Object o, long offset, long   newValue)
2740 //   Object getAndSet(Object o, long offset, Object newValue)
2741 //
2742 bool LibraryCallKit::inline_unsafe_load_store(BasicType type, LoadStoreKind kind) {
2743   // This basic scheme here is the same as inline_unsafe_access, but
2744   // differs in enough details that combining them would make the code
2745   // overly confusing.  (This is a true fact! I originally combined
2746   // them, but even I was confused by it!) As much code/comments as
2747   // possible are retained from inline_unsafe_access though to make
2748   // the correspondences clearer. - dl
2749 
2750   if (callee()->is_static())  return false;  // caller must have the capability!
2751 
2752 #ifndef PRODUCT
2753   BasicType rtype;
2754   {
2755     ResourceMark rm;
2756     // Check the signatures.
2757     ciSignature* sig = callee()->signature();
2758     rtype = sig->return_type()->basic_type();
2759     if (kind == LS_xadd || kind == LS_xchg) {
2760       // Check the signatures.
2761 #ifdef ASSERT
2762       assert(rtype == type, "get and set must return the expected type");
2763       assert(sig->count() == 3, "get and set has 3 arguments");
2764       assert(sig->type_at(0)->basic_type() == T_OBJECT, "get and set base is object");
2765       assert(sig->type_at(1)->basic_type() == T_LONG, "get and set offset is long");
2766       assert(sig->type_at(2)->basic_type() == type, "get and set must take expected type as new value/delta");
2767 #endif // ASSERT
2768     } else if (kind == LS_cmpxchg) {
2769       // Check the signatures.
2770 #ifdef ASSERT
2771       assert(rtype == T_BOOLEAN, "CAS must return boolean");
2772       assert(sig->count() == 4, "CAS has 4 arguments");
2773       assert(sig->type_at(0)->basic_type() == T_OBJECT, "CAS base is object");
2774       assert(sig->type_at(1)->basic_type() == T_LONG, "CAS offset is long");
2775 #endif // ASSERT
2776     } else {
2777       ShouldNotReachHere();
2778     }
2779   }
2780 #endif //PRODUCT
2781 
2782   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
2783 
2784   // Get arguments:
2785   Node* receiver = NULL;
2786   Node* base     = NULL;
2787   Node* offset   = NULL;
2788   Node* oldval   = NULL;
2789   Node* newval   = NULL;
2790   if (kind == LS_cmpxchg) {
2791     const bool two_slot_type = type2size[type] == 2;
2792     receiver = argument(0);  // type: oop
2793     base     = argument(1);  // type: oop
2794     offset   = argument(2);  // type: long
2795     oldval   = argument(4);  // type: oop, int, or long
2796     newval   = argument(two_slot_type ? 6 : 5);  // type: oop, int, or long
2797   } else if (kind == LS_xadd || kind == LS_xchg){
2798     receiver = argument(0);  // type: oop
2799     base     = argument(1);  // type: oop
2800     offset   = argument(2);  // type: long
2801     oldval   = NULL;
2802     newval   = argument(4);  // type: oop, int, or long
2803   }
2804 
2805   // Null check receiver.
2806   receiver = null_check(receiver);
2807   if (stopped()) {
2808     return true;
2809   }
2810 
2811   // Build field offset expression.
2812   // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
2813   // to be plain byte offsets, which are also the same as those accepted
2814   // by oopDesc::field_base.
2815   assert(Unsafe_field_offset_to_byte_offset(11) == 11, "fieldOffset must be byte-scaled");
2816   // 32-bit machines ignore the high half of long offsets
2817   offset = ConvL2X(offset);
2818   Node* adr = make_unsafe_address(base, offset);
2819   const TypePtr *adr_type = _gvn.type(adr)->isa_ptr();
2820 
2821   // For CAS, unlike inline_unsafe_access, there seems no point in
2822   // trying to refine types. Just use the coarse types here.
2823   const Type *value_type = Type::get_const_basic_type(type);
2824   Compile::AliasType* alias_type = C->alias_type(adr_type);
2825   assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
2826 
2827   if (kind == LS_xchg && type == T_OBJECT) {
2828     const TypeOopPtr* tjp = sharpen_unsafe_type(alias_type, adr_type);
2829     if (tjp != NULL) {
2830       value_type = tjp;
2831     }
2832   }
2833 
2834   int alias_idx = C->get_alias_index(adr_type);
2835 
2836   // Memory-model-wise, a LoadStore acts like a little synchronized
2837   // block, so needs barriers on each side.  These don't translate
2838   // into actual barriers on most machines, but we still need rest of
2839   // compiler to respect ordering.
2840 
2841   insert_mem_bar(Op_MemBarRelease);
2842   insert_mem_bar(Op_MemBarCPUOrder);
2843 
2844   // 4984716: MemBars must be inserted before this
2845   //          memory node in order to avoid a false
2846   //          dependency which will confuse the scheduler.
2847   Node *mem = memory(alias_idx);
2848 
2849   // For now, we handle only those cases that actually exist: ints,
2850   // longs, and Object. Adding others should be straightforward.
2851   Node* load_store;
2852   switch(type) {
2853   case T_INT:
2854     if (kind == LS_xadd) {
2855       load_store = _gvn.transform(new GetAndAddINode(control(), mem, adr, newval, adr_type));
2856     } else if (kind == LS_xchg) {
2857       load_store = _gvn.transform(new GetAndSetINode(control(), mem, adr, newval, adr_type));
2858     } else if (kind == LS_cmpxchg) {
2859       load_store = _gvn.transform(new CompareAndSwapINode(control(), mem, adr, newval, oldval));
2860     } else {
2861       ShouldNotReachHere();
2862     }
2863     break;
2864   case T_LONG:
2865     if (kind == LS_xadd) {
2866       load_store = _gvn.transform(new GetAndAddLNode(control(), mem, adr, newval, adr_type));
2867     } else if (kind == LS_xchg) {
2868       load_store = _gvn.transform(new GetAndSetLNode(control(), mem, adr, newval, adr_type));
2869     } else if (kind == LS_cmpxchg) {
2870       load_store = _gvn.transform(new CompareAndSwapLNode(control(), mem, adr, newval, oldval));
2871     } else {
2872       ShouldNotReachHere();
2873     }
2874     break;
2875   case T_OBJECT:
2876     // Transformation of a value which could be NULL pointer (CastPP #NULL)
2877     // could be delayed during Parse (for example, in adjust_map_after_if()).
2878     // Execute transformation here to avoid barrier generation in such case.
2879     if (_gvn.type(newval) == TypePtr::NULL_PTR)
2880       newval = _gvn.makecon(TypePtr::NULL_PTR);
2881 
2882     // Reference stores need a store barrier.
2883     if (kind == LS_xchg) {
2884       // If pre-barrier must execute before the oop store, old value will require do_load here.
2885       if (!can_move_pre_barrier()) {
2886         pre_barrier(true /* do_load*/,
2887                     control(), base, adr, alias_idx, newval, value_type->make_oopptr(),
2888                     NULL /* pre_val*/,
2889                     T_OBJECT);
2890       } // Else move pre_barrier to use load_store value, see below.
2891     } else if (kind == LS_cmpxchg) {
2892       // Same as for newval above:
2893       if (_gvn.type(oldval) == TypePtr::NULL_PTR) {
2894         oldval = _gvn.makecon(TypePtr::NULL_PTR);
2895       }
2896       // The only known value which might get overwritten is oldval.
2897       pre_barrier(false /* do_load */,
2898                   control(), NULL, NULL, max_juint, NULL, NULL,
2899                   oldval /* pre_val */,
2900                   T_OBJECT);
2901     } else {
2902       ShouldNotReachHere();
2903     }
2904 
2905 #ifdef _LP64
2906     if (adr->bottom_type()->is_ptr_to_narrowoop()) {
2907       Node *newval_enc = _gvn.transform(new EncodePNode(newval, newval->bottom_type()->make_narrowoop()));
2908       if (kind == LS_xchg) {
2909         load_store = _gvn.transform(new GetAndSetNNode(control(), mem, adr,
2910                                                        newval_enc, adr_type, value_type->make_narrowoop()));
2911       } else {
2912         assert(kind == LS_cmpxchg, "wrong LoadStore operation");
2913         Node *oldval_enc = _gvn.transform(new EncodePNode(oldval, oldval->bottom_type()->make_narrowoop()));
2914         load_store = _gvn.transform(new CompareAndSwapNNode(control(), mem, adr,
2915                                                                 newval_enc, oldval_enc));
2916       }
2917     } else
2918 #endif
2919     {
2920       if (kind == LS_xchg) {
2921         load_store = _gvn.transform(new GetAndSetPNode(control(), mem, adr, newval, adr_type, value_type->is_oopptr()));
2922       } else {
2923         assert(kind == LS_cmpxchg, "wrong LoadStore operation");
2924         load_store = _gvn.transform(new CompareAndSwapPNode(control(), mem, adr, newval, oldval));
2925       }
2926     }
2927     post_barrier(control(), load_store, base, adr, alias_idx, newval, T_OBJECT, true);
2928     break;
2929   default:
2930     fatal(err_msg_res("unexpected type %d: %s", type, type2name(type)));
2931     break;
2932   }
2933 
2934   // SCMemProjNodes represent the memory state of a LoadStore. Their
2935   // main role is to prevent LoadStore nodes from being optimized away
2936   // when their results aren't used.
2937   Node* proj = _gvn.transform(new SCMemProjNode(load_store));
2938   set_memory(proj, alias_idx);
2939 
2940   if (type == T_OBJECT && kind == LS_xchg) {
2941 #ifdef _LP64
2942     if (adr->bottom_type()->is_ptr_to_narrowoop()) {
2943       load_store = _gvn.transform(new DecodeNNode(load_store, load_store->get_ptr_type()));
2944     }
2945 #endif
2946     if (can_move_pre_barrier()) {
2947       // Don't need to load pre_val. The old value is returned by load_store.
2948       // The pre_barrier can execute after the xchg as long as no safepoint
2949       // gets inserted between them.
2950       pre_barrier(false /* do_load */,
2951                   control(), NULL, NULL, max_juint, NULL, NULL,
2952                   load_store /* pre_val */,
2953                   T_OBJECT);
2954     }
2955   }
2956 
2957   // Add the trailing membar surrounding the access
2958   insert_mem_bar(Op_MemBarCPUOrder);
2959   insert_mem_bar(Op_MemBarAcquire);
2960 
2961   assert(type2size[load_store->bottom_type()->basic_type()] == type2size[rtype], "result type should match");
2962   set_result(load_store);
2963   return true;
2964 }
2965 
2966 //----------------------------inline_unsafe_ordered_store----------------------
2967 // public native void sun.misc.Unsafe.putOrderedObject(Object o, long offset, Object x);
2968 // public native void sun.misc.Unsafe.putOrderedInt(Object o, long offset, int x);
2969 // public native void sun.misc.Unsafe.putOrderedLong(Object o, long offset, long x);
2970 bool LibraryCallKit::inline_unsafe_ordered_store(BasicType type) {
2971   // This is another variant of inline_unsafe_access, differing in
2972   // that it always issues store-store ("release") barrier and ensures
2973   // store-atomicity (which only matters for "long").
2974 
2975   if (callee()->is_static())  return false;  // caller must have the capability!
2976 
2977 #ifndef PRODUCT
2978   {
2979     ResourceMark rm;
2980     // Check the signatures.
2981     ciSignature* sig = callee()->signature();
2982 #ifdef ASSERT
2983     BasicType rtype = sig->return_type()->basic_type();
2984     assert(rtype == T_VOID, "must return void");
2985     assert(sig->count() == 3, "has 3 arguments");
2986     assert(sig->type_at(0)->basic_type() == T_OBJECT, "base is object");
2987     assert(sig->type_at(1)->basic_type() == T_LONG, "offset is long");
2988 #endif // ASSERT
2989   }
2990 #endif //PRODUCT
2991 
2992   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
2993 
2994   // Get arguments:
2995   Node* receiver = argument(0);  // type: oop
2996   Node* base     = argument(1);  // type: oop
2997   Node* offset   = argument(2);  // type: long
2998   Node* val      = argument(4);  // type: oop, int, or long
2999 
3000   // Null check receiver.
3001   receiver = null_check(receiver);
3002   if (stopped()) {
3003     return true;
3004   }
3005 
3006   // Build field offset expression.
3007   assert(Unsafe_field_offset_to_byte_offset(11) == 11, "fieldOffset must be byte-scaled");
3008   // 32-bit machines ignore the high half of long offsets
3009   offset = ConvL2X(offset);
3010   Node* adr = make_unsafe_address(base, offset);
3011   const TypePtr *adr_type = _gvn.type(adr)->isa_ptr();
3012   const Type *value_type = Type::get_const_basic_type(type);
3013   Compile::AliasType* alias_type = C->alias_type(adr_type);
3014 
3015   insert_mem_bar(Op_MemBarRelease);
3016   insert_mem_bar(Op_MemBarCPUOrder);
3017   // Ensure that the store is atomic for longs:
3018   const bool require_atomic_access = true;
3019   Node* store;
3020   if (type == T_OBJECT) // reference stores need a store barrier.
3021     store = store_oop_to_unknown(control(), base, adr, adr_type, val, type, MemNode::release);
3022   else {
3023     store = store_to_memory(control(), adr, val, type, adr_type, MemNode::release, require_atomic_access);
3024   }
3025   insert_mem_bar(Op_MemBarCPUOrder);
3026   return true;
3027 }
3028 
3029 bool LibraryCallKit::inline_unsafe_fence(vmIntrinsics::ID id) {
3030   // Regardless of form, don't allow previous ld/st to move down,
3031   // then issue acquire, release, or volatile mem_bar.
3032   insert_mem_bar(Op_MemBarCPUOrder);
3033   switch(id) {
3034     case vmIntrinsics::_loadFence:
3035       insert_mem_bar(Op_LoadFence);
3036       return true;
3037     case vmIntrinsics::_storeFence:
3038       insert_mem_bar(Op_StoreFence);
3039       return true;
3040     case vmIntrinsics::_fullFence:
3041       insert_mem_bar(Op_MemBarVolatile);
3042       return true;
3043     default:
3044       fatal_unexpected_iid(id);
3045       return false;
3046   }
3047 }
3048 
3049 bool LibraryCallKit::klass_needs_init_guard(Node* kls) {
3050   if (!kls->is_Con()) {
3051     return true;
3052   }
3053   const TypeKlassPtr* klsptr = kls->bottom_type()->isa_klassptr();
3054   if (klsptr == NULL) {
3055     return true;
3056   }
3057   ciInstanceKlass* ik = klsptr->klass()->as_instance_klass();
3058   // don't need a guard for a klass that is already initialized
3059   return !ik->is_initialized();
3060 }
3061 
3062 //----------------------------inline_unsafe_allocate---------------------------
3063 // public native Object sun.misc.Unsafe.allocateInstance(Class<?> cls);
3064 bool LibraryCallKit::inline_unsafe_allocate() {
3065   if (callee()->is_static())  return false;  // caller must have the capability!
3066 
3067   null_check_receiver();  // null-check, then ignore
3068   Node* cls = null_check(argument(1));
3069   if (stopped())  return true;
3070 
3071   Node* kls = load_klass_from_mirror(cls, false, NULL, 0);
3072   kls = null_check(kls);
3073   if (stopped())  return true;  // argument was like int.class
3074 
3075   Node* test = NULL;
3076   if (LibraryCallKit::klass_needs_init_guard(kls)) {
3077     // Note:  The argument might still be an illegal value like
3078     // Serializable.class or Object[].class.   The runtime will handle it.
3079     // But we must make an explicit check for initialization.
3080     Node* insp = basic_plus_adr(kls, in_bytes(InstanceKlass::init_state_offset()));
3081     // Use T_BOOLEAN for InstanceKlass::_init_state so the compiler
3082     // can generate code to load it as unsigned byte.
3083     Node* inst = make_load(NULL, insp, TypeInt::UBYTE, T_BOOLEAN, MemNode::unordered);
3084     Node* bits = intcon(InstanceKlass::fully_initialized);
3085     test = _gvn.transform(new SubINode(inst, bits));
3086     // The 'test' is non-zero if we need to take a slow path.
3087   }
3088 
3089   Node* obj = new_instance(kls, test);
3090   set_result(obj);
3091   return true;
3092 }
3093 
3094 #ifdef TRACE_HAVE_INTRINSICS
3095 /*
3096  * oop -> myklass
3097  * myklass->trace_id |= USED
3098  * return myklass->trace_id & ~0x3
3099  */
3100 bool LibraryCallKit::inline_native_classID() {
3101   null_check_receiver();  // null-check, then ignore
3102   Node* cls = null_check(argument(1), T_OBJECT);
3103   Node* kls = load_klass_from_mirror(cls, false, NULL, 0);
3104   kls = null_check(kls, T_OBJECT);
3105   ByteSize offset = TRACE_ID_OFFSET;
3106   Node* insp = basic_plus_adr(kls, in_bytes(offset));
3107   Node* tvalue = make_load(NULL, insp, TypeLong::LONG, T_LONG, MemNode::unordered);
3108   Node* bits = longcon(~0x03l); // ignore bit 0 & 1
3109   Node* andl = _gvn.transform(new AndLNode(tvalue, bits));
3110   Node* clsused = longcon(0x01l); // set the class bit
3111   Node* orl = _gvn.transform(new OrLNode(tvalue, clsused));
3112 
3113   const TypePtr *adr_type = _gvn.type(insp)->isa_ptr();
3114   store_to_memory(control(), insp, orl, T_LONG, adr_type, MemNode::unordered);
3115   set_result(andl);
3116   return true;
3117 }
3118 
3119 bool LibraryCallKit::inline_native_threadID() {
3120   Node* tls_ptr = NULL;
3121   Node* cur_thr = generate_current_thread(tls_ptr);
3122   Node* p = basic_plus_adr(top()/*!oop*/, tls_ptr, in_bytes(JavaThread::osthread_offset()));
3123   Node* osthread = make_load(NULL, p, TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered);
3124   p = basic_plus_adr(top()/*!oop*/, osthread, in_bytes(OSThread::thread_id_offset()));
3125 
3126   Node* threadid = NULL;
3127   size_t thread_id_size = OSThread::thread_id_size();
3128   if (thread_id_size == (size_t) BytesPerLong) {
3129     threadid = ConvL2I(make_load(control(), p, TypeLong::LONG, T_LONG, MemNode::unordered));
3130   } else if (thread_id_size == (size_t) BytesPerInt) {
3131     threadid = make_load(control(), p, TypeInt::INT, T_INT, MemNode::unordered);
3132   } else {
3133     ShouldNotReachHere();
3134   }
3135   set_result(threadid);
3136   return true;
3137 }
3138 #endif
3139 
3140 //------------------------inline_native_time_funcs--------------
3141 // inline code for System.currentTimeMillis() and System.nanoTime()
3142 // these have the same type and signature
3143 bool LibraryCallKit::inline_native_time_funcs(address funcAddr, const char* funcName) {
3144   const TypeFunc* tf = OptoRuntime::void_long_Type();
3145   const TypePtr* no_memory_effects = NULL;
3146   Node* time = make_runtime_call(RC_LEAF, tf, funcAddr, funcName, no_memory_effects);
3147   Node* value = _gvn.transform(new ProjNode(time, TypeFunc::Parms+0));
3148 #ifdef ASSERT
3149   Node* value_top = _gvn.transform(new ProjNode(time, TypeFunc::Parms+1));
3150   assert(value_top == top(), "second value must be top");
3151 #endif
3152   set_result(value);
3153   return true;
3154 }
3155 
3156 //------------------------inline_native_currentThread------------------
3157 bool LibraryCallKit::inline_native_currentThread() {
3158   Node* junk = NULL;
3159   set_result(generate_current_thread(junk));
3160   return true;
3161 }
3162 
3163 //------------------------inline_native_isInterrupted------------------
3164 // private native boolean java.lang.Thread.isInterrupted(boolean ClearInterrupted);
3165 bool LibraryCallKit::inline_native_isInterrupted() {
3166   // Add a fast path to t.isInterrupted(clear_int):
3167   //   (t == Thread.current() &&
3168   //    (!TLS._osthread._interrupted || WINDOWS_ONLY(false) NOT_WINDOWS(!clear_int)))
3169   //   ? TLS._osthread._interrupted : /*slow path:*/ t.isInterrupted(clear_int)
3170   // So, in the common case that the interrupt bit is false,
3171   // we avoid making a call into the VM.  Even if the interrupt bit
3172   // is true, if the clear_int argument is false, we avoid the VM call.
3173   // However, if the receiver is not currentThread, we must call the VM,
3174   // because there must be some locking done around the operation.
3175 
3176   // We only go to the fast case code if we pass two guards.
3177   // Paths which do not pass are accumulated in the slow_region.
3178 
3179   enum {
3180     no_int_result_path   = 1, // t == Thread.current() && !TLS._osthread._interrupted
3181     no_clear_result_path = 2, // t == Thread.current() &&  TLS._osthread._interrupted && !clear_int
3182     slow_result_path     = 3, // slow path: t.isInterrupted(clear_int)
3183     PATH_LIMIT
3184   };
3185 
3186   // Ensure that it's not possible to move the load of TLS._osthread._interrupted flag
3187   // out of the function.
3188   insert_mem_bar(Op_MemBarCPUOrder);
3189 
3190   RegionNode* result_rgn = new RegionNode(PATH_LIMIT);
3191   PhiNode*    result_val = new PhiNode(result_rgn, TypeInt::BOOL);
3192 
3193   RegionNode* slow_region = new RegionNode(1);
3194   record_for_igvn(slow_region);
3195 
3196   // (a) Receiving thread must be the current thread.
3197   Node* rec_thr = argument(0);
3198   Node* tls_ptr = NULL;
3199   Node* cur_thr = generate_current_thread(tls_ptr);
3200   Node* cmp_thr = _gvn.transform(new CmpPNode(cur_thr, rec_thr));
3201   Node* bol_thr = _gvn.transform(new BoolNode(cmp_thr, BoolTest::ne));
3202 
3203   generate_slow_guard(bol_thr, slow_region);
3204 
3205   // (b) Interrupt bit on TLS must be false.
3206   Node* p = basic_plus_adr(top()/*!oop*/, tls_ptr, in_bytes(JavaThread::osthread_offset()));
3207   Node* osthread = make_load(NULL, p, TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered);
3208   p = basic_plus_adr(top()/*!oop*/, osthread, in_bytes(OSThread::interrupted_offset()));
3209 
3210   // Set the control input on the field _interrupted read to prevent it floating up.
3211   Node* int_bit = make_load(control(), p, TypeInt::BOOL, T_INT, MemNode::unordered);
3212   Node* cmp_bit = _gvn.transform(new CmpINode(int_bit, intcon(0)));
3213   Node* bol_bit = _gvn.transform(new BoolNode(cmp_bit, BoolTest::ne));
3214 
3215   IfNode* iff_bit = create_and_map_if(control(), bol_bit, PROB_UNLIKELY_MAG(3), COUNT_UNKNOWN);
3216 
3217   // First fast path:  if (!TLS._interrupted) return false;
3218   Node* false_bit = _gvn.transform(new IfFalseNode(iff_bit));
3219   result_rgn->init_req(no_int_result_path, false_bit);
3220   result_val->init_req(no_int_result_path, intcon(0));
3221 
3222   // drop through to next case
3223   set_control( _gvn.transform(new IfTrueNode(iff_bit)));
3224 
3225 #ifndef TARGET_OS_FAMILY_windows
3226   // (c) Or, if interrupt bit is set and clear_int is false, use 2nd fast path.
3227   Node* clr_arg = argument(1);
3228   Node* cmp_arg = _gvn.transform(new CmpINode(clr_arg, intcon(0)));
3229   Node* bol_arg = _gvn.transform(new BoolNode(cmp_arg, BoolTest::ne));
3230   IfNode* iff_arg = create_and_map_if(control(), bol_arg, PROB_FAIR, COUNT_UNKNOWN);
3231 
3232   // Second fast path:  ... else if (!clear_int) return true;
3233   Node* false_arg = _gvn.transform(new IfFalseNode(iff_arg));
3234   result_rgn->init_req(no_clear_result_path, false_arg);
3235   result_val->init_req(no_clear_result_path, intcon(1));
3236 
3237   // drop through to next case
3238   set_control( _gvn.transform(new IfTrueNode(iff_arg)));
3239 #else
3240   // To return true on Windows you must read the _interrupted field
3241   // and check the the event state i.e. take the slow path.
3242 #endif // TARGET_OS_FAMILY_windows
3243 
3244   // (d) Otherwise, go to the slow path.
3245   slow_region->add_req(control());
3246   set_control( _gvn.transform(slow_region));
3247 
3248   if (stopped()) {
3249     // There is no slow path.
3250     result_rgn->init_req(slow_result_path, top());
3251     result_val->init_req(slow_result_path, top());
3252   } else {
3253     // non-virtual because it is a private non-static
3254     CallJavaNode* slow_call = generate_method_call(vmIntrinsics::_isInterrupted);
3255 
3256     Node* slow_val = set_results_for_java_call(slow_call);
3257     // this->control() comes from set_results_for_java_call
3258 
3259     Node* fast_io  = slow_call->in(TypeFunc::I_O);
3260     Node* fast_mem = slow_call->in(TypeFunc::Memory);
3261 
3262     // These two phis are pre-filled with copies of of the fast IO and Memory
3263     PhiNode* result_mem  = PhiNode::make(result_rgn, fast_mem, Type::MEMORY, TypePtr::BOTTOM);
3264     PhiNode* result_io   = PhiNode::make(result_rgn, fast_io,  Type::ABIO);
3265 
3266     result_rgn->init_req(slow_result_path, control());
3267     result_io ->init_req(slow_result_path, i_o());
3268     result_mem->init_req(slow_result_path, reset_memory());
3269     result_val->init_req(slow_result_path, slow_val);
3270 
3271     set_all_memory(_gvn.transform(result_mem));
3272     set_i_o(       _gvn.transform(result_io));
3273   }
3274 
3275   C->set_has_split_ifs(true); // Has chance for split-if optimization
3276   set_result(result_rgn, result_val);
3277   return true;
3278 }
3279 
3280 //---------------------------load_mirror_from_klass----------------------------
3281 // Given a klass oop, load its java mirror (a java.lang.Class oop).
3282 Node* LibraryCallKit::load_mirror_from_klass(Node* klass) {
3283   Node* p = basic_plus_adr(klass, in_bytes(Klass::java_mirror_offset()));
3284   return make_load(NULL, p, TypeInstPtr::MIRROR, T_OBJECT, MemNode::unordered);
3285 }
3286 
3287 //-----------------------load_klass_from_mirror_common-------------------------
3288 // Given a java mirror (a java.lang.Class oop), load its corresponding klass oop.
3289 // Test the klass oop for null (signifying a primitive Class like Integer.TYPE),
3290 // and branch to the given path on the region.
3291 // If never_see_null, take an uncommon trap on null, so we can optimistically
3292 // compile for the non-null case.
3293 // If the region is NULL, force never_see_null = true.
3294 Node* LibraryCallKit::load_klass_from_mirror_common(Node* mirror,
3295                                                     bool never_see_null,
3296                                                     RegionNode* region,
3297                                                     int null_path,
3298                                                     int offset) {
3299   if (region == NULL)  never_see_null = true;
3300   Node* p = basic_plus_adr(mirror, offset);
3301   const TypeKlassPtr*  kls_type = TypeKlassPtr::OBJECT_OR_NULL;
3302   Node* kls = _gvn.transform(LoadKlassNode::make(_gvn, NULL, immutable_memory(), p, TypeRawPtr::BOTTOM, kls_type));
3303   Node* null_ctl = top();
3304   kls = null_check_oop(kls, &null_ctl, never_see_null);
3305   if (region != NULL) {
3306     // Set region->in(null_path) if the mirror is a primitive (e.g, int.class).
3307     region->init_req(null_path, null_ctl);
3308   } else {
3309     assert(null_ctl == top(), "no loose ends");
3310   }
3311   return kls;
3312 }
3313 
3314 //--------------------(inline_native_Class_query helpers)---------------------
3315 // Use this for JVM_ACC_INTERFACE, JVM_ACC_IS_CLONEABLE, JVM_ACC_HAS_FINALIZER.
3316 // Fall through if (mods & mask) == bits, take the guard otherwise.
3317 Node* LibraryCallKit::generate_access_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region) {
3318   // Branch around if the given klass has the given modifier bit set.
3319   // Like generate_guard, adds a new path onto the region.
3320   Node* modp = basic_plus_adr(kls, in_bytes(Klass::access_flags_offset()));
3321   Node* mods = make_load(NULL, modp, TypeInt::INT, T_INT, MemNode::unordered);
3322   Node* mask = intcon(modifier_mask);
3323   Node* bits = intcon(modifier_bits);
3324   Node* mbit = _gvn.transform(new AndINode(mods, mask));
3325   Node* cmp  = _gvn.transform(new CmpINode(mbit, bits));
3326   Node* bol  = _gvn.transform(new BoolNode(cmp, BoolTest::ne));
3327   return generate_fair_guard(bol, region);
3328 }
3329 Node* LibraryCallKit::generate_interface_guard(Node* kls, RegionNode* region) {
3330   return generate_access_flags_guard(kls, JVM_ACC_INTERFACE, 0, region);
3331 }
3332 
3333 //-------------------------inline_native_Class_query-------------------
3334 bool LibraryCallKit::inline_native_Class_query(vmIntrinsics::ID id) {
3335   const Type* return_type = TypeInt::BOOL;
3336   Node* prim_return_value = top();  // what happens if it's a primitive class?
3337   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
3338   bool expect_prim = false;     // most of these guys expect to work on refs
3339 
3340   enum { _normal_path = 1, _prim_path = 2, PATH_LIMIT };
3341 
3342   Node* mirror = argument(0);
3343   Node* obj    = top();
3344 
3345   switch (id) {
3346   case vmIntrinsics::_isInstance:
3347     // nothing is an instance of a primitive type
3348     prim_return_value = intcon(0);
3349     obj = argument(1);
3350     break;
3351   case vmIntrinsics::_getModifiers:
3352     prim_return_value = intcon(JVM_ACC_ABSTRACT | JVM_ACC_FINAL | JVM_ACC_PUBLIC);
3353     assert(is_power_of_2((int)JVM_ACC_WRITTEN_FLAGS+1), "change next line");
3354     return_type = TypeInt::make(0, JVM_ACC_WRITTEN_FLAGS, Type::WidenMin);
3355     break;
3356   case vmIntrinsics::_isInterface:
3357     prim_return_value = intcon(0);
3358     break;
3359   case vmIntrinsics::_isArray:
3360     prim_return_value = intcon(0);
3361     expect_prim = true;  // cf. ObjectStreamClass.getClassSignature
3362     break;
3363   case vmIntrinsics::_isPrimitive:
3364     prim_return_value = intcon(1);
3365     expect_prim = true;  // obviously
3366     break;
3367   case vmIntrinsics::_getSuperclass:
3368     prim_return_value = null();
3369     return_type = TypeInstPtr::MIRROR->cast_to_ptr_type(TypePtr::BotPTR);
3370     break;
3371   case vmIntrinsics::_getClassAccessFlags:
3372     prim_return_value = intcon(JVM_ACC_ABSTRACT | JVM_ACC_FINAL | JVM_ACC_PUBLIC);
3373     return_type = TypeInt::INT;  // not bool!  6297094
3374     break;
3375   default:
3376     fatal_unexpected_iid(id);
3377     break;
3378   }
3379 
3380   const TypeInstPtr* mirror_con = _gvn.type(mirror)->isa_instptr();
3381   if (mirror_con == NULL)  return false;  // cannot happen?
3382 
3383 #ifndef PRODUCT
3384   if (C->print_intrinsics() || C->print_inlining()) {
3385     ciType* k = mirror_con->java_mirror_type();
3386     if (k) {
3387       tty->print("Inlining %s on constant Class ", vmIntrinsics::name_at(intrinsic_id()));
3388       k->print_name();
3389       tty->cr();
3390     }
3391   }
3392 #endif
3393 
3394   // Null-check the mirror, and the mirror's klass ptr (in case it is a primitive).
3395   RegionNode* region = new RegionNode(PATH_LIMIT);
3396   record_for_igvn(region);
3397   PhiNode* phi = new PhiNode(region, return_type);
3398 
3399   // The mirror will never be null of Reflection.getClassAccessFlags, however
3400   // it may be null for Class.isInstance or Class.getModifiers. Throw a NPE
3401   // if it is. See bug 4774291.
3402 
3403   // For Reflection.getClassAccessFlags(), the null check occurs in
3404   // the wrong place; see inline_unsafe_access(), above, for a similar
3405   // situation.
3406   mirror = null_check(mirror);
3407   // If mirror or obj is dead, only null-path is taken.
3408   if (stopped())  return true;
3409 
3410   if (expect_prim)  never_see_null = false;  // expect nulls (meaning prims)
3411 
3412   // Now load the mirror's klass metaobject, and null-check it.
3413   // Side-effects region with the control path if the klass is null.
3414   Node* kls = load_klass_from_mirror(mirror, never_see_null, region, _prim_path);
3415   // If kls is null, we have a primitive mirror.
3416   phi->init_req(_prim_path, prim_return_value);
3417   if (stopped()) { set_result(region, phi); return true; }
3418   bool safe_for_replace = (region->in(_prim_path) == top());
3419 
3420   Node* p;  // handy temp
3421   Node* null_ctl;
3422 
3423   // Now that we have the non-null klass, we can perform the real query.
3424   // For constant classes, the query will constant-fold in LoadNode::Value.
3425   Node* query_value = top();
3426   switch (id) {
3427   case vmIntrinsics::_isInstance:
3428     // nothing is an instance of a primitive type
3429     query_value = gen_instanceof(obj, kls, safe_for_replace);
3430     break;
3431 
3432   case vmIntrinsics::_getModifiers:
3433     p = basic_plus_adr(kls, in_bytes(Klass::modifier_flags_offset()));
3434     query_value = make_load(NULL, p, TypeInt::INT, T_INT, MemNode::unordered);
3435     break;
3436 
3437   case vmIntrinsics::_isInterface:
3438     // (To verify this code sequence, check the asserts in JVM_IsInterface.)
3439     if (generate_interface_guard(kls, region) != NULL)
3440       // A guard was added.  If the guard is taken, it was an interface.
3441       phi->add_req(intcon(1));
3442     // If we fall through, it's a plain class.
3443     query_value = intcon(0);
3444     break;
3445 
3446   case vmIntrinsics::_isArray:
3447     // (To verify this code sequence, check the asserts in JVM_IsArrayClass.)
3448     if (generate_array_guard(kls, region) != NULL)
3449       // A guard was added.  If the guard is taken, it was an array.
3450       phi->add_req(intcon(1));
3451     // If we fall through, it's a plain class.
3452     query_value = intcon(0);
3453     break;
3454 
3455   case vmIntrinsics::_isPrimitive:
3456     query_value = intcon(0); // "normal" path produces false
3457     break;
3458 
3459   case vmIntrinsics::_getSuperclass:
3460     // The rules here are somewhat unfortunate, but we can still do better
3461     // with random logic than with a JNI call.
3462     // Interfaces store null or Object as _super, but must report null.
3463     // Arrays store an intermediate super as _super, but must report Object.
3464     // Other types can report the actual _super.
3465     // (To verify this code sequence, check the asserts in JVM_IsInterface.)
3466     if (generate_interface_guard(kls, region) != NULL)
3467       // A guard was added.  If the guard is taken, it was an interface.
3468       phi->add_req(null());
3469     if (generate_array_guard(kls, region) != NULL)
3470       // A guard was added.  If the guard is taken, it was an array.
3471       phi->add_req(makecon(TypeInstPtr::make(env()->Object_klass()->java_mirror())));
3472     // If we fall through, it's a plain class.  Get its _super.
3473     p = basic_plus_adr(kls, in_bytes(Klass::super_offset()));
3474     kls = _gvn.transform(LoadKlassNode::make(_gvn, NULL, immutable_memory(), p, TypeRawPtr::BOTTOM, TypeKlassPtr::OBJECT_OR_NULL));
3475     null_ctl = top();
3476     kls = null_check_oop(kls, &null_ctl);
3477     if (null_ctl != top()) {
3478       // If the guard is taken, Object.superClass is null (both klass and mirror).
3479       region->add_req(null_ctl);
3480       phi   ->add_req(null());
3481     }
3482     if (!stopped()) {
3483       query_value = load_mirror_from_klass(kls);
3484     }
3485     break;
3486 
3487   case vmIntrinsics::_getClassAccessFlags:
3488     p = basic_plus_adr(kls, in_bytes(Klass::access_flags_offset()));
3489     query_value = make_load(NULL, p, TypeInt::INT, T_INT, MemNode::unordered);
3490     break;
3491 
3492   default:
3493     fatal_unexpected_iid(id);
3494     break;
3495   }
3496 
3497   // Fall-through is the normal case of a query to a real class.
3498   phi->init_req(1, query_value);
3499   region->init_req(1, control());
3500 
3501   C->set_has_split_ifs(true); // Has chance for split-if optimization
3502   set_result(region, phi);
3503   return true;
3504 }
3505 
3506 //-------------------------inline_Class_cast-------------------
3507 bool LibraryCallKit::inline_Class_cast() {
3508   Node* mirror = argument(0); // Class
3509   Node* obj    = argument(1);
3510   const TypeInstPtr* mirror_con = _gvn.type(mirror)->isa_instptr();
3511   if (mirror_con == NULL) {
3512     return false;  // dead path (mirror->is_top()).
3513   }
3514   if (obj == NULL || obj->is_top()) {
3515     return false;  // dead path
3516   }
3517   const TypeOopPtr* tp = _gvn.type(obj)->isa_oopptr();
3518 
3519   // First, see if Class.cast() can be folded statically.
3520   // java_mirror_type() returns non-null for compile-time Class constants.
3521   ciType* tm = mirror_con->java_mirror_type();
3522   if (tm != NULL && tm->is_klass() &&
3523       tp != NULL && tp->klass() != NULL) {
3524     if (!tp->klass()->is_loaded()) {
3525       // Don't use intrinsic when class is not loaded.
3526       return false;
3527     } else {
3528       int static_res = C->static_subtype_check(tm->as_klass(), tp->klass());
3529       if (static_res == Compile::SSC_always_true) {
3530         // isInstance() is true - fold the code.
3531         set_result(obj);
3532         return true;
3533       } else if (static_res == Compile::SSC_always_false) {
3534         // Don't use intrinsic, have to throw ClassCastException.
3535         // If the reference is null, the non-intrinsic bytecode will
3536         // be optimized appropriately.
3537         return false;
3538       }
3539     }
3540   }
3541 
3542   // Bailout intrinsic and do normal inlining if exception path is frequent.
3543   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
3544     return false;
3545   }
3546 
3547   // Generate dynamic checks.
3548   // Class.cast() is java implementation of _checkcast bytecode.
3549   // Do checkcast (Parse::do_checkcast()) optimizations here.
3550 
3551   mirror = null_check(mirror);
3552   // If mirror is dead, only null-path is taken.
3553   if (stopped()) {
3554     return true;
3555   }
3556 
3557   // Not-subtype or the mirror's klass ptr is NULL (in case it is a primitive).
3558   enum { _bad_type_path = 1, _prim_path = 2, PATH_LIMIT };
3559   RegionNode* region = new RegionNode(PATH_LIMIT);
3560   record_for_igvn(region);
3561 
3562   // Now load the mirror's klass metaobject, and null-check it.
3563   // If kls is null, we have a primitive mirror and
3564   // nothing is an instance of a primitive type.
3565   Node* kls = load_klass_from_mirror(mirror, false, region, _prim_path);
3566 
3567   Node* res = top();
3568   if (!stopped()) {
3569     Node* bad_type_ctrl = top();
3570     // Do checkcast optimizations.
3571     res = gen_checkcast(obj, kls, &bad_type_ctrl);
3572     region->init_req(_bad_type_path, bad_type_ctrl);
3573   }
3574   if (region->in(_prim_path) != top() ||
3575       region->in(_bad_type_path) != top()) {
3576     // Let Interpreter throw ClassCastException.
3577     PreserveJVMState pjvms(this);
3578     set_control(_gvn.transform(region));
3579     uncommon_trap(Deoptimization::Reason_intrinsic,
3580                   Deoptimization::Action_maybe_recompile);
3581   }
3582   if (!stopped()) {
3583     set_result(res);
3584   }
3585   return true;
3586 }
3587 
3588 
3589 //--------------------------inline_native_subtype_check------------------------
3590 // This intrinsic takes the JNI calls out of the heart of
3591 // UnsafeFieldAccessorImpl.set, which improves Field.set, readObject, etc.
3592 bool LibraryCallKit::inline_native_subtype_check() {
3593   // Pull both arguments off the stack.
3594   Node* args[2];                // two java.lang.Class mirrors: superc, subc
3595   args[0] = argument(0);
3596   args[1] = argument(1);
3597   Node* klasses[2];             // corresponding Klasses: superk, subk
3598   klasses[0] = klasses[1] = top();
3599 
3600   enum {
3601     // A full decision tree on {superc is prim, subc is prim}:
3602     _prim_0_path = 1,           // {P,N} => false
3603                                 // {P,P} & superc!=subc => false
3604     _prim_same_path,            // {P,P} & superc==subc => true
3605     _prim_1_path,               // {N,P} => false
3606     _ref_subtype_path,          // {N,N} & subtype check wins => true
3607     _both_ref_path,             // {N,N} & subtype check loses => false
3608     PATH_LIMIT
3609   };
3610 
3611   RegionNode* region = new RegionNode(PATH_LIMIT);
3612   Node*       phi    = new PhiNode(region, TypeInt::BOOL);
3613   record_for_igvn(region);
3614 
3615   const TypePtr* adr_type = TypeRawPtr::BOTTOM;   // memory type of loads
3616   const TypeKlassPtr* kls_type = TypeKlassPtr::OBJECT_OR_NULL;
3617   int class_klass_offset = java_lang_Class::klass_offset_in_bytes();
3618 
3619   // First null-check both mirrors and load each mirror's klass metaobject.
3620   int which_arg;
3621   for (which_arg = 0; which_arg <= 1; which_arg++) {
3622     Node* arg = args[which_arg];
3623     arg = null_check(arg);
3624     if (stopped())  break;
3625     args[which_arg] = arg;
3626 
3627     Node* p = basic_plus_adr(arg, class_klass_offset);
3628     Node* kls = LoadKlassNode::make(_gvn, NULL, immutable_memory(), p, adr_type, kls_type);
3629     klasses[which_arg] = _gvn.transform(kls);
3630   }
3631 
3632   // Having loaded both klasses, test each for null.
3633   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
3634   for (which_arg = 0; which_arg <= 1; which_arg++) {
3635     Node* kls = klasses[which_arg];
3636     Node* null_ctl = top();
3637     kls = null_check_oop(kls, &null_ctl, never_see_null);
3638     int prim_path = (which_arg == 0 ? _prim_0_path : _prim_1_path);
3639     region->init_req(prim_path, null_ctl);
3640     if (stopped())  break;
3641     klasses[which_arg] = kls;
3642   }
3643 
3644   if (!stopped()) {
3645     // now we have two reference types, in klasses[0..1]
3646     Node* subk   = klasses[1];  // the argument to isAssignableFrom
3647     Node* superk = klasses[0];  // the receiver
3648     region->set_req(_both_ref_path, gen_subtype_check(subk, superk));
3649     // now we have a successful reference subtype check
3650     region->set_req(_ref_subtype_path, control());
3651   }
3652 
3653   // If both operands are primitive (both klasses null), then
3654   // we must return true when they are identical primitives.
3655   // It is convenient to test this after the first null klass check.
3656   set_control(region->in(_prim_0_path)); // go back to first null check
3657   if (!stopped()) {
3658     // Since superc is primitive, make a guard for the superc==subc case.
3659     Node* cmp_eq = _gvn.transform(new CmpPNode(args[0], args[1]));
3660     Node* bol_eq = _gvn.transform(new BoolNode(cmp_eq, BoolTest::eq));
3661     generate_guard(bol_eq, region, PROB_FAIR);
3662     if (region->req() == PATH_LIMIT+1) {
3663       // A guard was added.  If the added guard is taken, superc==subc.
3664       region->swap_edges(PATH_LIMIT, _prim_same_path);
3665       region->del_req(PATH_LIMIT);
3666     }
3667     region->set_req(_prim_0_path, control()); // Not equal after all.
3668   }
3669 
3670   // these are the only paths that produce 'true':
3671   phi->set_req(_prim_same_path,   intcon(1));
3672   phi->set_req(_ref_subtype_path, intcon(1));
3673 
3674   // pull together the cases:
3675   assert(region->req() == PATH_LIMIT, "sane region");
3676   for (uint i = 1; i < region->req(); i++) {
3677     Node* ctl = region->in(i);
3678     if (ctl == NULL || ctl == top()) {
3679       region->set_req(i, top());
3680       phi   ->set_req(i, top());
3681     } else if (phi->in(i) == NULL) {
3682       phi->set_req(i, intcon(0)); // all other paths produce 'false'
3683     }
3684   }
3685 
3686   set_control(_gvn.transform(region));
3687   set_result(_gvn.transform(phi));
3688   return true;
3689 }
3690 
3691 //---------------------generate_array_guard_common------------------------
3692 Node* LibraryCallKit::generate_array_guard_common(Node* kls, RegionNode* region,
3693                                                   bool obj_array, bool not_array) {
3694 
3695   if (stopped()) {
3696     return NULL;
3697   }
3698 
3699   // If obj_array/non_array==false/false:
3700   // Branch around if the given klass is in fact an array (either obj or prim).
3701   // If obj_array/non_array==false/true:
3702   // Branch around if the given klass is not an array klass of any kind.
3703   // If obj_array/non_array==true/true:
3704   // Branch around if the kls is not an oop array (kls is int[], String, etc.)
3705   // If obj_array/non_array==true/false:
3706   // Branch around if the kls is an oop array (Object[] or subtype)
3707   //
3708   // Like generate_guard, adds a new path onto the region.
3709   jint  layout_con = 0;
3710   Node* layout_val = get_layout_helper(kls, layout_con);
3711   if (layout_val == NULL) {
3712     bool query = (obj_array
3713                   ? Klass::layout_helper_is_objArray(layout_con)
3714                   : Klass::layout_helper_is_array(layout_con));
3715     if (query == not_array) {
3716       return NULL;                       // never a branch
3717     } else {                             // always a branch
3718       Node* always_branch = control();
3719       if (region != NULL)
3720         region->add_req(always_branch);
3721       set_control(top());
3722       return always_branch;
3723     }
3724   }
3725   // Now test the correct condition.
3726   jint  nval = (obj_array
3727                 ? ((jint)Klass::_lh_array_tag_type_value
3728                    <<    Klass::_lh_array_tag_shift)
3729                 : Klass::_lh_neutral_value);
3730   Node* cmp = _gvn.transform(new CmpINode(layout_val, intcon(nval)));
3731   BoolTest::mask btest = BoolTest::lt;  // correct for testing is_[obj]array
3732   // invert the test if we are looking for a non-array
3733   if (not_array)  btest = BoolTest(btest).negate();
3734   Node* bol = _gvn.transform(new BoolNode(cmp, btest));
3735   return generate_fair_guard(bol, region);
3736 }
3737 
3738 
3739 //-----------------------inline_native_newArray--------------------------
3740 // private static native Object java.lang.reflect.newArray(Class<?> componentType, int length);
3741 bool LibraryCallKit::inline_native_newArray() {
3742   Node* mirror    = argument(0);
3743   Node* count_val = argument(1);
3744 
3745   mirror = null_check(mirror);
3746   // If mirror or obj is dead, only null-path is taken.
3747   if (stopped())  return true;
3748 
3749   enum { _normal_path = 1, _slow_path = 2, PATH_LIMIT };
3750   RegionNode* result_reg = new RegionNode(PATH_LIMIT);
3751   PhiNode*    result_val = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
3752   PhiNode*    result_io  = new PhiNode(result_reg, Type::ABIO);
3753   PhiNode*    result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
3754 
3755   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
3756   Node* klass_node = load_array_klass_from_mirror(mirror, never_see_null,
3757                                                   result_reg, _slow_path);
3758   Node* normal_ctl   = control();
3759   Node* no_array_ctl = result_reg->in(_slow_path);
3760 
3761   // Generate code for the slow case.  We make a call to newArray().
3762   set_control(no_array_ctl);
3763   if (!stopped()) {
3764     // Either the input type is void.class, or else the
3765     // array klass has not yet been cached.  Either the
3766     // ensuing call will throw an exception, or else it
3767     // will cache the array klass for next time.
3768     PreserveJVMState pjvms(this);
3769     CallJavaNode* slow_call = generate_method_call_static(vmIntrinsics::_newArray);
3770     Node* slow_result = set_results_for_java_call(slow_call);
3771     // this->control() comes from set_results_for_java_call
3772     result_reg->set_req(_slow_path, control());
3773     result_val->set_req(_slow_path, slow_result);
3774     result_io ->set_req(_slow_path, i_o());
3775     result_mem->set_req(_slow_path, reset_memory());
3776   }
3777 
3778   set_control(normal_ctl);
3779   if (!stopped()) {
3780     // Normal case:  The array type has been cached in the java.lang.Class.
3781     // The following call works fine even if the array type is polymorphic.
3782     // It could be a dynamic mix of int[], boolean[], Object[], etc.
3783     Node* obj = new_array(klass_node, count_val, 0);  // no arguments to push
3784     result_reg->init_req(_normal_path, control());
3785     result_val->init_req(_normal_path, obj);
3786     result_io ->init_req(_normal_path, i_o());
3787     result_mem->init_req(_normal_path, reset_memory());
3788   }
3789 
3790   // Return the combined state.
3791   set_i_o(        _gvn.transform(result_io)  );
3792   set_all_memory( _gvn.transform(result_mem));
3793 
3794   C->set_has_split_ifs(true); // Has chance for split-if optimization
3795   set_result(result_reg, result_val);
3796   return true;
3797 }
3798 
3799 //----------------------inline_native_getLength--------------------------
3800 // public static native int java.lang.reflect.Array.getLength(Object array);
3801 bool LibraryCallKit::inline_native_getLength() {
3802   if (too_many_traps(Deoptimization::Reason_intrinsic))  return false;
3803 
3804   Node* array = null_check(argument(0));
3805   // If array is dead, only null-path is taken.
3806   if (stopped())  return true;
3807 
3808   // Deoptimize if it is a non-array.
3809   Node* non_array = generate_non_array_guard(load_object_klass(array), NULL);
3810 
3811   if (non_array != NULL) {
3812     PreserveJVMState pjvms(this);
3813     set_control(non_array);
3814     uncommon_trap(Deoptimization::Reason_intrinsic,
3815                   Deoptimization::Action_maybe_recompile);
3816   }
3817 
3818   // If control is dead, only non-array-path is taken.
3819   if (stopped())  return true;
3820 
3821   // The works fine even if the array type is polymorphic.
3822   // It could be a dynamic mix of int[], boolean[], Object[], etc.
3823   Node* result = load_array_length(array);
3824 
3825   C->set_has_split_ifs(true);  // Has chance for split-if optimization
3826   set_result(result);
3827   return true;
3828 }
3829 
3830 //------------------------inline_array_copyOf----------------------------
3831 // public static <T,U> T[] java.util.Arrays.copyOf(     U[] original, int newLength,         Class<? extends T[]> newType);
3832 // public static <T,U> T[] java.util.Arrays.copyOfRange(U[] original, int from,      int to, Class<? extends T[]> newType);
3833 bool LibraryCallKit::inline_array_copyOf(bool is_copyOfRange) {
3834   if (too_many_traps(Deoptimization::Reason_intrinsic))  return false;
3835 
3836   // Get the arguments.
3837   Node* original          = argument(0);
3838   Node* start             = is_copyOfRange? argument(1): intcon(0);
3839   Node* end               = is_copyOfRange? argument(2): argument(1);
3840   Node* array_type_mirror = is_copyOfRange? argument(3): argument(2);
3841 
3842   Node* newcopy;
3843 
3844   // Set the original stack and the reexecute bit for the interpreter to reexecute
3845   // the bytecode that invokes Arrays.copyOf if deoptimization happens.
3846   { PreserveReexecuteState preexecs(this);
3847     jvms()->set_should_reexecute(true);
3848 
3849     array_type_mirror = null_check(array_type_mirror);
3850     original          = null_check(original);
3851 
3852     // Check if a null path was taken unconditionally.
3853     if (stopped())  return true;
3854 
3855     Node* orig_length = load_array_length(original);
3856 
3857     Node* klass_node = load_klass_from_mirror(array_type_mirror, false, NULL, 0);
3858     klass_node = null_check(klass_node);
3859 
3860     RegionNode* bailout = new RegionNode(1);
3861     record_for_igvn(bailout);
3862 
3863     // Despite the generic type of Arrays.copyOf, the mirror might be int, int[], etc.
3864     // Bail out if that is so.
3865     Node* not_objArray = generate_non_objArray_guard(klass_node, bailout);
3866     if (not_objArray != NULL) {
3867       // Improve the klass node's type from the new optimistic assumption:
3868       ciKlass* ak = ciArrayKlass::make(env()->Object_klass());
3869       const Type* akls = TypeKlassPtr::make(TypePtr::NotNull, ak, 0/*offset*/);
3870       Node* cast = new CastPPNode(klass_node, akls);
3871       cast->init_req(0, control());
3872       klass_node = _gvn.transform(cast);
3873     }
3874 
3875     // Bail out if either start or end is negative.
3876     generate_negative_guard(start, bailout, &start);
3877     generate_negative_guard(end,   bailout, &end);
3878 
3879     Node* length = end;
3880     if (_gvn.type(start) != TypeInt::ZERO) {
3881       length = _gvn.transform(new SubINode(end, start));
3882     }
3883 
3884     // Bail out if length is negative.
3885     // Without this the new_array would throw
3886     // NegativeArraySizeException but IllegalArgumentException is what
3887     // should be thrown
3888     generate_negative_guard(length, bailout, &length);
3889 
3890     if (bailout->req() > 1) {
3891       PreserveJVMState pjvms(this);
3892       set_control(_gvn.transform(bailout));
3893       uncommon_trap(Deoptimization::Reason_intrinsic,
3894                     Deoptimization::Action_maybe_recompile);
3895     }
3896 
3897     if (!stopped()) {
3898       // How many elements will we copy from the original?
3899       // The answer is MinI(orig_length - start, length).
3900       Node* orig_tail = _gvn.transform(new SubINode(orig_length, start));
3901       Node* moved = generate_min_max(vmIntrinsics::_min, orig_tail, length);
3902 
3903       // Generate a direct call to the right arraycopy function(s).
3904       // We know the copy is disjoint but we might not know if the
3905       // oop stores need checking.
3906       // Extreme case:  Arrays.copyOf((Integer[])x, 10, String[].class).
3907       // This will fail a store-check if x contains any non-nulls.
3908 
3909       // ArrayCopyNode:Ideal may transform the ArrayCopyNode to
3910       // loads/stores but it is legal only if we're sure the
3911       // Arrays.copyOf would succeed. So we need all input arguments
3912       // to the copyOf to be validated, including that the copy to the
3913       // new array won't trigger an ArrayStoreException. That subtype
3914       // check can be optimized if we know something on the type of
3915       // the input array from type speculation.
3916       if (_gvn.type(klass_node)->singleton()) {
3917         ciKlass* subk   = _gvn.type(load_object_klass(original))->is_klassptr()->klass();
3918         ciKlass* superk = _gvn.type(klass_node)->is_klassptr()->klass();
3919 
3920         int test = C->static_subtype_check(superk, subk);
3921         if (test != Compile::SSC_always_true && test != Compile::SSC_always_false) {
3922           const TypeOopPtr* t_original = _gvn.type(original)->is_oopptr();
3923           if (t_original->speculative_type() != NULL) {
3924             original = maybe_cast_profiled_obj(original, t_original->speculative_type(), true);
3925           }
3926         }
3927       }
3928 
3929       bool validated = false;
3930       // Reason_class_check rather than Reason_intrinsic because we
3931       // want to intrinsify even if this traps.
3932       if (!too_many_traps(Deoptimization::Reason_class_check)) {
3933         Node* not_subtype_ctrl = gen_subtype_check(load_object_klass(original),
3934                                                    klass_node);
3935 
3936         if (not_subtype_ctrl != top()) {
3937           PreserveJVMState pjvms(this);
3938           set_control(not_subtype_ctrl);
3939           uncommon_trap(Deoptimization::Reason_class_check,
3940                         Deoptimization::Action_make_not_entrant);
3941           assert(stopped(), "Should be stopped");
3942         }
3943         validated = true;
3944       }
3945 
3946       if (!stopped()) {
3947         newcopy = new_array(klass_node, length, 0);  // no arguments to push
3948 
3949         ArrayCopyNode* ac = ArrayCopyNode::make(this, true, original, start, newcopy, intcon(0), moved, true,
3950                                                 load_object_klass(original), klass_node);
3951         if (!is_copyOfRange) {
3952           ac->set_copyof(validated);
3953         } else {
3954           ac->set_copyofrange(validated);
3955         }
3956         Node* n = _gvn.transform(ac);
3957         if (n == ac) {
3958           ac->connect_outputs(this);
3959         } else {
3960           assert(validated, "shouldn't transform if all arguments not validated");
3961           set_all_memory(n);
3962         }
3963       }
3964     }
3965   } // original reexecute is set back here
3966 
3967   C->set_has_split_ifs(true); // Has chance for split-if optimization
3968   if (!stopped()) {
3969     set_result(newcopy);
3970   }
3971   return true;
3972 }
3973 
3974 
3975 //----------------------generate_virtual_guard---------------------------
3976 // Helper for hashCode and clone.  Peeks inside the vtable to avoid a call.
3977 Node* LibraryCallKit::generate_virtual_guard(Node* obj_klass,
3978                                              RegionNode* slow_region) {
3979   ciMethod* method = callee();
3980   int vtable_index = method->vtable_index();
3981   assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index,
3982          err_msg_res("bad index %d", vtable_index));
3983   // Get the Method* out of the appropriate vtable entry.
3984   int entry_offset  = (InstanceKlass::vtable_start_offset() +
3985                      vtable_index*vtableEntry::size()) * wordSize +
3986                      vtableEntry::method_offset_in_bytes();
3987   Node* entry_addr  = basic_plus_adr(obj_klass, entry_offset);
3988   Node* target_call = make_load(NULL, entry_addr, TypePtr::NOTNULL, T_ADDRESS, MemNode::unordered);
3989 
3990   // Compare the target method with the expected method (e.g., Object.hashCode).
3991   const TypePtr* native_call_addr = TypeMetadataPtr::make(method);
3992 
3993   Node* native_call = makecon(native_call_addr);
3994   Node* chk_native  = _gvn.transform(new CmpPNode(target_call, native_call));
3995   Node* test_native = _gvn.transform(new BoolNode(chk_native, BoolTest::ne));
3996 
3997   return generate_slow_guard(test_native, slow_region);
3998 }
3999 
4000 //-----------------------generate_method_call----------------------------
4001 // Use generate_method_call to make a slow-call to the real
4002 // method if the fast path fails.  An alternative would be to
4003 // use a stub like OptoRuntime::slow_arraycopy_Java.
4004 // This only works for expanding the current library call,
4005 // not another intrinsic.  (E.g., don't use this for making an
4006 // arraycopy call inside of the copyOf intrinsic.)
4007 CallJavaNode*
4008 LibraryCallKit::generate_method_call(vmIntrinsics::ID method_id, bool is_virtual, bool is_static) {
4009   // When compiling the intrinsic method itself, do not use this technique.
4010   guarantee(callee() != C->method(), "cannot make slow-call to self");
4011 
4012   ciMethod* method = callee();
4013   // ensure the JVMS we have will be correct for this call
4014   guarantee(method_id == method->intrinsic_id(), "must match");
4015 
4016   const TypeFunc* tf = TypeFunc::make(method);
4017   CallJavaNode* slow_call;
4018   if (is_static) {
4019     assert(!is_virtual, "");
4020     slow_call = new CallStaticJavaNode(C, tf,
4021                            SharedRuntime::get_resolve_static_call_stub(),
4022                            method, bci());
4023   } else if (is_virtual) {
4024     null_check_receiver();
4025     int vtable_index = Method::invalid_vtable_index;
4026     if (UseInlineCaches) {
4027       // Suppress the vtable call
4028     } else {
4029       // hashCode and clone are not a miranda methods,
4030       // so the vtable index is fixed.
4031       // No need to use the linkResolver to get it.
4032        vtable_index = method->vtable_index();
4033        assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index,
4034               err_msg_res("bad index %d", vtable_index));
4035     }
4036     slow_call = new CallDynamicJavaNode(tf,
4037                           SharedRuntime::get_resolve_virtual_call_stub(),
4038                           method, vtable_index, bci());
4039   } else {  // neither virtual nor static:  opt_virtual
4040     null_check_receiver();
4041     slow_call = new CallStaticJavaNode(C, tf,
4042                                 SharedRuntime::get_resolve_opt_virtual_call_stub(),
4043                                 method, bci());
4044     slow_call->set_optimized_virtual(true);
4045   }
4046   set_arguments_for_java_call(slow_call);
4047   set_edges_for_java_call(slow_call);
4048   return slow_call;
4049 }
4050 
4051 
4052 /**
4053  * Build special case code for calls to hashCode on an object. This call may
4054  * be virtual (invokevirtual) or bound (invokespecial). For each case we generate
4055  * slightly different code.
4056  */
4057 bool LibraryCallKit::inline_native_hashcode(bool is_virtual, bool is_static) {
4058   assert(is_static == callee()->is_static(), "correct intrinsic selection");
4059   assert(!(is_virtual && is_static), "either virtual, special, or static");
4060 
4061   enum { _slow_path = 1, _fast_path, _null_path, PATH_LIMIT };
4062 
4063   RegionNode* result_reg = new RegionNode(PATH_LIMIT);
4064   PhiNode*    result_val = new PhiNode(result_reg, TypeInt::INT);
4065   PhiNode*    result_io  = new PhiNode(result_reg, Type::ABIO);
4066   PhiNode*    result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
4067   Node* obj = NULL;
4068   if (!is_static) {
4069     // Check for hashing null object
4070     obj = null_check_receiver();
4071     if (stopped())  return true;        // unconditionally null
4072     result_reg->init_req(_null_path, top());
4073     result_val->init_req(_null_path, top());
4074   } else {
4075     // Do a null check, and return zero if null.
4076     // System.identityHashCode(null) == 0
4077     obj = argument(0);
4078     Node* null_ctl = top();
4079     obj = null_check_oop(obj, &null_ctl);
4080     result_reg->init_req(_null_path, null_ctl);
4081     result_val->init_req(_null_path, _gvn.intcon(0));
4082   }
4083 
4084   // Unconditionally null?  Then return right away.
4085   if (stopped()) {
4086     set_control( result_reg->in(_null_path));
4087     if (!stopped())
4088       set_result(result_val->in(_null_path));
4089     return true;
4090   }
4091 
4092   // We only go to the fast case code if we pass a number of guards.  The
4093   // paths which do not pass are accumulated in the slow_region.
4094   RegionNode* slow_region = new RegionNode(1);
4095   record_for_igvn(slow_region);
4096 
4097   // If this is a virtual call, we generate a funny guard.  We pull out
4098   // the vtable entry corresponding to hashCode() from the target object.
4099   // If the target method which we are calling happens to be the native
4100   // Object hashCode() method, we pass the guard.  We do not need this
4101   // guard for non-virtual calls -- the caller is known to be the native
4102   // Object hashCode().
4103   if (is_virtual) {
4104     // After null check, get the object's klass.
4105     Node* obj_klass = load_object_klass(obj);
4106     generate_virtual_guard(obj_klass, slow_region);
4107   }
4108 
4109   // Get the header out of the object, use LoadMarkNode when available
4110   Node* header_addr = basic_plus_adr(obj, oopDesc::mark_offset_in_bytes());
4111   // The control of the load must be NULL. Otherwise, the load can move before
4112   // the null check after castPP removal.
4113   Node* no_ctrl = NULL;
4114   Node* header = make_load(no_ctrl, header_addr, TypeX_X, TypeX_X->basic_type(), MemNode::unordered);
4115 
4116   // Test the header to see if it is unlocked.
4117   Node *lock_mask      = _gvn.MakeConX(markOopDesc::biased_lock_mask_in_place);
4118   Node *lmasked_header = _gvn.transform(new AndXNode(header, lock_mask));
4119   Node *unlocked_val   = _gvn.MakeConX(markOopDesc::unlocked_value);
4120   Node *chk_unlocked   = _gvn.transform(new CmpXNode( lmasked_header, unlocked_val));
4121   Node *test_unlocked  = _gvn.transform(new BoolNode( chk_unlocked, BoolTest::ne));
4122 
4123   generate_slow_guard(test_unlocked, slow_region);
4124 
4125   // Get the hash value and check to see that it has been properly assigned.
4126   // We depend on hash_mask being at most 32 bits and avoid the use of
4127   // hash_mask_in_place because it could be larger than 32 bits in a 64-bit
4128   // vm: see markOop.hpp.
4129   Node *hash_mask      = _gvn.intcon(markOopDesc::hash_mask);
4130   Node *hash_shift     = _gvn.intcon(markOopDesc::hash_shift);
4131   Node *hshifted_header= _gvn.transform(new URShiftXNode(header, hash_shift));
4132   // This hack lets the hash bits live anywhere in the mark object now, as long
4133   // as the shift drops the relevant bits into the low 32 bits.  Note that
4134   // Java spec says that HashCode is an int so there's no point in capturing
4135   // an 'X'-sized hashcode (32 in 32-bit build or 64 in 64-bit build).
4136   hshifted_header      = ConvX2I(hshifted_header);
4137   Node *hash_val       = _gvn.transform(new AndINode(hshifted_header, hash_mask));
4138 
4139   Node *no_hash_val    = _gvn.intcon(markOopDesc::no_hash);
4140   Node *chk_assigned   = _gvn.transform(new CmpINode( hash_val, no_hash_val));
4141   Node *test_assigned  = _gvn.transform(new BoolNode( chk_assigned, BoolTest::eq));
4142 
4143   generate_slow_guard(test_assigned, slow_region);
4144 
4145   Node* init_mem = reset_memory();
4146   // fill in the rest of the null path:
4147   result_io ->init_req(_null_path, i_o());
4148   result_mem->init_req(_null_path, init_mem);
4149 
4150   result_val->init_req(_fast_path, hash_val);
4151   result_reg->init_req(_fast_path, control());
4152   result_io ->init_req(_fast_path, i_o());
4153   result_mem->init_req(_fast_path, init_mem);
4154 
4155   // Generate code for the slow case.  We make a call to hashCode().
4156   set_control(_gvn.transform(slow_region));
4157   if (!stopped()) {
4158     // No need for PreserveJVMState, because we're using up the present state.
4159     set_all_memory(init_mem);
4160     vmIntrinsics::ID hashCode_id = is_static ? vmIntrinsics::_identityHashCode : vmIntrinsics::_hashCode;
4161     CallJavaNode* slow_call = generate_method_call(hashCode_id, is_virtual, is_static);
4162     Node* slow_result = set_results_for_java_call(slow_call);
4163     // this->control() comes from set_results_for_java_call
4164     result_reg->init_req(_slow_path, control());
4165     result_val->init_req(_slow_path, slow_result);
4166     result_io  ->set_req(_slow_path, i_o());
4167     result_mem ->set_req(_slow_path, reset_memory());
4168   }
4169 
4170   // Return the combined state.
4171   set_i_o(        _gvn.transform(result_io)  );
4172   set_all_memory( _gvn.transform(result_mem));
4173 
4174   set_result(result_reg, result_val);
4175   return true;
4176 }
4177 
4178 //---------------------------inline_native_getClass----------------------------
4179 // public final native Class<?> java.lang.Object.getClass();
4180 //
4181 // Build special case code for calls to getClass on an object.
4182 bool LibraryCallKit::inline_native_getClass() {
4183   Node* obj = null_check_receiver();
4184   if (stopped())  return true;
4185   set_result(load_mirror_from_klass(load_object_klass(obj)));
4186   return true;
4187 }
4188 
4189 //-----------------inline_native_Reflection_getCallerClass---------------------
4190 // public static native Class<?> sun.reflect.Reflection.getCallerClass();
4191 //
4192 // In the presence of deep enough inlining, getCallerClass() becomes a no-op.
4193 //
4194 // NOTE: This code must perform the same logic as JVM_GetCallerClass
4195 // in that it must skip particular security frames and checks for
4196 // caller sensitive methods.
4197 bool LibraryCallKit::inline_native_Reflection_getCallerClass() {
4198 #ifndef PRODUCT
4199   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
4200     tty->print_cr("Attempting to inline sun.reflect.Reflection.getCallerClass");
4201   }
4202 #endif
4203 
4204   if (!jvms()->has_method()) {
4205 #ifndef PRODUCT
4206     if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
4207       tty->print_cr("  Bailing out because intrinsic was inlined at top level");
4208     }
4209 #endif
4210     return false;
4211   }
4212 
4213   // Walk back up the JVM state to find the caller at the required
4214   // depth.
4215   JVMState* caller_jvms = jvms();
4216 
4217   // Cf. JVM_GetCallerClass
4218   // NOTE: Start the loop at depth 1 because the current JVM state does
4219   // not include the Reflection.getCallerClass() frame.
4220   for (int n = 1; caller_jvms != NULL; caller_jvms = caller_jvms->caller(), n++) {
4221     ciMethod* m = caller_jvms->method();
4222     switch (n) {
4223     case 0:
4224       fatal("current JVM state does not include the Reflection.getCallerClass frame");
4225       break;
4226     case 1:
4227       // Frame 0 and 1 must be caller sensitive (see JVM_GetCallerClass).
4228       if (!m->caller_sensitive()) {
4229 #ifndef PRODUCT
4230         if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
4231           tty->print_cr("  Bailing out: CallerSensitive annotation expected at frame %d", n);
4232         }
4233 #endif
4234         return false;  // bail-out; let JVM_GetCallerClass do the work
4235       }
4236       break;
4237     default:
4238       if (!m->is_ignored_by_security_stack_walk()) {
4239         // We have reached the desired frame; return the holder class.
4240         // Acquire method holder as java.lang.Class and push as constant.
4241         ciInstanceKlass* caller_klass = caller_jvms->method()->holder();
4242         ciInstance* caller_mirror = caller_klass->java_mirror();
4243         set_result(makecon(TypeInstPtr::make(caller_mirror)));
4244 
4245 #ifndef PRODUCT
4246         if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
4247           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());
4248           tty->print_cr("  JVM state at this point:");
4249           for (int i = jvms()->depth(), n = 1; i >= 1; i--, n++) {
4250             ciMethod* m = jvms()->of_depth(i)->method();
4251             tty->print_cr("   %d) %s.%s", n, m->holder()->name()->as_utf8(), m->name()->as_utf8());
4252           }
4253         }
4254 #endif
4255         return true;
4256       }
4257       break;
4258     }
4259   }
4260 
4261 #ifndef PRODUCT
4262   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
4263     tty->print_cr("  Bailing out because caller depth exceeded inlining depth = %d", jvms()->depth());
4264     tty->print_cr("  JVM state at this point:");
4265     for (int i = jvms()->depth(), n = 1; i >= 1; i--, n++) {
4266       ciMethod* m = jvms()->of_depth(i)->method();
4267       tty->print_cr("   %d) %s.%s", n, m->holder()->name()->as_utf8(), m->name()->as_utf8());
4268     }
4269   }
4270 #endif
4271 
4272   return false;  // bail-out; let JVM_GetCallerClass do the work
4273 }
4274 
4275 bool LibraryCallKit::inline_fp_conversions(vmIntrinsics::ID id) {
4276   Node* arg = argument(0);
4277   Node* result;
4278 
4279   switch (id) {
4280   case vmIntrinsics::_floatToRawIntBits:    result = new MoveF2INode(arg);  break;
4281   case vmIntrinsics::_intBitsToFloat:       result = new MoveI2FNode(arg);  break;
4282   case vmIntrinsics::_doubleToRawLongBits:  result = new MoveD2LNode(arg);  break;
4283   case vmIntrinsics::_longBitsToDouble:     result = new MoveL2DNode(arg);  break;
4284 
4285   case vmIntrinsics::_doubleToLongBits: {
4286     // two paths (plus control) merge in a wood
4287     RegionNode *r = new RegionNode(3);
4288     Node *phi = new PhiNode(r, TypeLong::LONG);
4289 
4290     Node *cmpisnan = _gvn.transform(new CmpDNode(arg, arg));
4291     // Build the boolean node
4292     Node *bolisnan = _gvn.transform(new BoolNode(cmpisnan, BoolTest::ne));
4293 
4294     // Branch either way.
4295     // NaN case is less traveled, which makes all the difference.
4296     IfNode *ifisnan = create_and_xform_if(control(), bolisnan, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
4297     Node *opt_isnan = _gvn.transform(ifisnan);
4298     assert( opt_isnan->is_If(), "Expect an IfNode");
4299     IfNode *opt_ifisnan = (IfNode*)opt_isnan;
4300     Node *iftrue = _gvn.transform(new IfTrueNode(opt_ifisnan));
4301 
4302     set_control(iftrue);
4303 
4304     static const jlong nan_bits = CONST64(0x7ff8000000000000);
4305     Node *slow_result = longcon(nan_bits); // return NaN
4306     phi->init_req(1, _gvn.transform( slow_result ));
4307     r->init_req(1, iftrue);
4308 
4309     // Else fall through
4310     Node *iffalse = _gvn.transform(new IfFalseNode(opt_ifisnan));
4311     set_control(iffalse);
4312 
4313     phi->init_req(2, _gvn.transform(new MoveD2LNode(arg)));
4314     r->init_req(2, iffalse);
4315 
4316     // Post merge
4317     set_control(_gvn.transform(r));
4318     record_for_igvn(r);
4319 
4320     C->set_has_split_ifs(true); // Has chance for split-if optimization
4321     result = phi;
4322     assert(result->bottom_type()->isa_long(), "must be");
4323     break;
4324   }
4325 
4326   case vmIntrinsics::_floatToIntBits: {
4327     // two paths (plus control) merge in a wood
4328     RegionNode *r = new RegionNode(3);
4329     Node *phi = new PhiNode(r, TypeInt::INT);
4330 
4331     Node *cmpisnan = _gvn.transform(new CmpFNode(arg, arg));
4332     // Build the boolean node
4333     Node *bolisnan = _gvn.transform(new BoolNode(cmpisnan, BoolTest::ne));
4334 
4335     // Branch either way.
4336     // NaN case is less traveled, which makes all the difference.
4337     IfNode *ifisnan = create_and_xform_if(control(), bolisnan, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
4338     Node *opt_isnan = _gvn.transform(ifisnan);
4339     assert( opt_isnan->is_If(), "Expect an IfNode");
4340     IfNode *opt_ifisnan = (IfNode*)opt_isnan;
4341     Node *iftrue = _gvn.transform(new IfTrueNode(opt_ifisnan));
4342 
4343     set_control(iftrue);
4344 
4345     static const jint nan_bits = 0x7fc00000;
4346     Node *slow_result = makecon(TypeInt::make(nan_bits)); // return NaN
4347     phi->init_req(1, _gvn.transform( slow_result ));
4348     r->init_req(1, iftrue);
4349 
4350     // Else fall through
4351     Node *iffalse = _gvn.transform(new IfFalseNode(opt_ifisnan));
4352     set_control(iffalse);
4353 
4354     phi->init_req(2, _gvn.transform(new MoveF2INode(arg)));
4355     r->init_req(2, iffalse);
4356 
4357     // Post merge
4358     set_control(_gvn.transform(r));
4359     record_for_igvn(r);
4360 
4361     C->set_has_split_ifs(true); // Has chance for split-if optimization
4362     result = phi;
4363     assert(result->bottom_type()->isa_int(), "must be");
4364     break;
4365   }
4366 
4367   default:
4368     fatal_unexpected_iid(id);
4369     break;
4370   }
4371   set_result(_gvn.transform(result));
4372   return true;
4373 }
4374 
4375 #ifdef _LP64
4376 #define XTOP ,top() /*additional argument*/
4377 #else  //_LP64
4378 #define XTOP        /*no additional argument*/
4379 #endif //_LP64
4380 
4381 //----------------------inline_unsafe_copyMemory-------------------------
4382 // public native void sun.misc.Unsafe.copyMemory(Object srcBase, long srcOffset, Object destBase, long destOffset, long bytes);
4383 bool LibraryCallKit::inline_unsafe_copyMemory() {
4384   if (callee()->is_static())  return false;  // caller must have the capability!
4385   null_check_receiver();  // null-check receiver
4386   if (stopped())  return true;
4387 
4388   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
4389 
4390   Node* src_ptr =         argument(1);   // type: oop
4391   Node* src_off = ConvL2X(argument(2));  // type: long
4392   Node* dst_ptr =         argument(4);   // type: oop
4393   Node* dst_off = ConvL2X(argument(5));  // type: long
4394   Node* size    = ConvL2X(argument(7));  // type: long
4395 
4396   assert(Unsafe_field_offset_to_byte_offset(11) == 11,
4397          "fieldOffset must be byte-scaled");
4398 
4399   Node* src = make_unsafe_address(src_ptr, src_off);
4400   Node* dst = make_unsafe_address(dst_ptr, dst_off);
4401 
4402   // Conservatively insert a memory barrier on all memory slices.
4403   // Do not let writes of the copy source or destination float below the copy.
4404   insert_mem_bar(Op_MemBarCPUOrder);
4405 
4406   // Call it.  Note that the length argument is not scaled.
4407   make_runtime_call(RC_LEAF|RC_NO_FP,
4408                     OptoRuntime::fast_arraycopy_Type(),
4409                     StubRoutines::unsafe_arraycopy(),
4410                     "unsafe_arraycopy",
4411                     TypeRawPtr::BOTTOM,
4412                     src, dst, size XTOP);
4413 
4414   // Do not let reads of the copy destination float above the copy.
4415   insert_mem_bar(Op_MemBarCPUOrder);
4416 
4417   return true;
4418 }
4419 
4420 //------------------------clone_coping-----------------------------------
4421 // Helper function for inline_native_clone.
4422 void LibraryCallKit::copy_to_clone(Node* obj, Node* alloc_obj, Node* obj_size, bool is_array, bool card_mark) {
4423   assert(obj_size != NULL, "");
4424   Node* raw_obj = alloc_obj->in(1);
4425   assert(alloc_obj->is_CheckCastPP() && raw_obj->is_Proj() && raw_obj->in(0)->is_Allocate(), "");
4426 
4427   AllocateNode* alloc = NULL;
4428   if (ReduceBulkZeroing) {
4429     // We will be completely responsible for initializing this object -
4430     // mark Initialize node as complete.
4431     alloc = AllocateNode::Ideal_allocation(alloc_obj, &_gvn);
4432     // The object was just allocated - there should be no any stores!
4433     guarantee(alloc != NULL && alloc->maybe_set_complete(&_gvn), "");
4434     // Mark as complete_with_arraycopy so that on AllocateNode
4435     // expansion, we know this AllocateNode is initialized by an array
4436     // copy and a StoreStore barrier exists after the array copy.
4437     alloc->initialization()->set_complete_with_arraycopy();
4438   }
4439 
4440   // Copy the fastest available way.
4441   // TODO: generate fields copies for small objects instead.
4442   Node* src  = obj;
4443   Node* dest = alloc_obj;
4444   Node* size = _gvn.transform(obj_size);
4445 
4446   // Exclude the header but include array length to copy by 8 bytes words.
4447   // Can't use base_offset_in_bytes(bt) since basic type is unknown.
4448   int base_off = is_array ? arrayOopDesc::length_offset_in_bytes() :
4449                             instanceOopDesc::base_offset_in_bytes();
4450   // base_off:
4451   // 8  - 32-bit VM
4452   // 12 - 64-bit VM, compressed klass
4453   // 16 - 64-bit VM, normal klass
4454   if (base_off % BytesPerLong != 0) {
4455     assert(UseCompressedClassPointers, "");
4456     if (is_array) {
4457       // Exclude length to copy by 8 bytes words.
4458       base_off += sizeof(int);
4459     } else {
4460       // Include klass to copy by 8 bytes words.
4461       base_off = instanceOopDesc::klass_offset_in_bytes();
4462     }
4463     assert(base_off % BytesPerLong == 0, "expect 8 bytes alignment");
4464   }
4465   src  = basic_plus_adr(src,  base_off);
4466   dest = basic_plus_adr(dest, base_off);
4467 
4468   // Compute the length also, if needed:
4469   Node* countx = size;
4470   countx = _gvn.transform(new SubXNode(countx, MakeConX(base_off)));
4471   countx = _gvn.transform(new URShiftXNode(countx, intcon(LogBytesPerLong) ));
4472 
4473   const TypePtr* raw_adr_type = TypeRawPtr::BOTTOM;
4474 
4475   ArrayCopyNode* ac = ArrayCopyNode::make(this, false, src, NULL, dest, NULL, countx, false);
4476   ac->set_clonebasic();
4477   Node* n = _gvn.transform(ac);
4478   if (n == ac) {
4479     set_predefined_output_for_runtime_call(ac, ac->in(TypeFunc::Memory), raw_adr_type);
4480   } else {
4481     set_all_memory(n);
4482   }
4483 
4484   // If necessary, emit some card marks afterwards.  (Non-arrays only.)
4485   if (card_mark) {
4486     assert(!is_array, "");
4487     // Put in store barrier for any and all oops we are sticking
4488     // into this object.  (We could avoid this if we could prove
4489     // that the object type contains no oop fields at all.)
4490     Node* no_particular_value = NULL;
4491     Node* no_particular_field = NULL;
4492     int raw_adr_idx = Compile::AliasIdxRaw;
4493     post_barrier(control(),
4494                  memory(raw_adr_type),
4495                  alloc_obj,
4496                  no_particular_field,
4497                  raw_adr_idx,
4498                  no_particular_value,
4499                  T_OBJECT,
4500                  false);
4501   }
4502 
4503   // Do not let reads from the cloned object float above the arraycopy.
4504   if (alloc != NULL) {
4505     // Do not let stores that initialize this object be reordered with
4506     // a subsequent store that would make this object accessible by
4507     // other threads.
4508     // Record what AllocateNode this StoreStore protects so that
4509     // escape analysis can go from the MemBarStoreStoreNode to the
4510     // AllocateNode and eliminate the MemBarStoreStoreNode if possible
4511     // based on the escape status of the AllocateNode.
4512     insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out(AllocateNode::RawAddress));
4513   } else {
4514     insert_mem_bar(Op_MemBarCPUOrder);
4515   }
4516 }
4517 
4518 //------------------------inline_native_clone----------------------------
4519 // protected native Object java.lang.Object.clone();
4520 //
4521 // Here are the simple edge cases:
4522 //  null receiver => normal trap
4523 //  virtual and clone was overridden => slow path to out-of-line clone
4524 //  not cloneable or finalizer => slow path to out-of-line Object.clone
4525 //
4526 // The general case has two steps, allocation and copying.
4527 // Allocation has two cases, and uses GraphKit::new_instance or new_array.
4528 //
4529 // Copying also has two cases, oop arrays and everything else.
4530 // Oop arrays use arrayof_oop_arraycopy (same as System.arraycopy).
4531 // Everything else uses the tight inline loop supplied by CopyArrayNode.
4532 //
4533 // These steps fold up nicely if and when the cloned object's klass
4534 // can be sharply typed as an object array, a type array, or an instance.
4535 //
4536 bool LibraryCallKit::inline_native_clone(bool is_virtual) {
4537   PhiNode* result_val;
4538 
4539   // Set the reexecute bit for the interpreter to reexecute
4540   // the bytecode that invokes Object.clone if deoptimization happens.
4541   { PreserveReexecuteState preexecs(this);
4542     jvms()->set_should_reexecute(true);
4543 
4544     Node* obj = null_check_receiver();
4545     if (stopped())  return true;
4546 
4547     const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
4548 
4549     // If we are going to clone an instance, we need its exact type to
4550     // know the number and types of fields to convert the clone to
4551     // loads/stores. Maybe a speculative type can help us.
4552     if (!obj_type->klass_is_exact() &&
4553         obj_type->speculative_type() != NULL &&
4554         obj_type->speculative_type()->is_instance_klass()) {
4555       ciInstanceKlass* spec_ik = obj_type->speculative_type()->as_instance_klass();
4556       if (spec_ik->nof_nonstatic_fields() <= ArrayCopyLoadStoreMaxElem &&
4557           !spec_ik->has_injected_fields()) {
4558         ciKlass* k = obj_type->klass();
4559         if (!k->is_instance_klass() ||
4560             k->as_instance_klass()->is_interface() ||
4561             k->as_instance_klass()->has_subklass()) {
4562           obj = maybe_cast_profiled_obj(obj, obj_type->speculative_type(), false);
4563         }
4564       }
4565     }
4566 
4567     Node* obj_klass = load_object_klass(obj);
4568     const TypeKlassPtr* tklass = _gvn.type(obj_klass)->isa_klassptr();
4569     const TypeOopPtr*   toop   = ((tklass != NULL)
4570                                 ? tklass->as_instance_type()
4571                                 : TypeInstPtr::NOTNULL);
4572 
4573     // Conservatively insert a memory barrier on all memory slices.
4574     // Do not let writes into the original float below the clone.
4575     insert_mem_bar(Op_MemBarCPUOrder);
4576 
4577     // paths into result_reg:
4578     enum {
4579       _slow_path = 1,     // out-of-line call to clone method (virtual or not)
4580       _objArray_path,     // plain array allocation, plus arrayof_oop_arraycopy
4581       _array_path,        // plain array allocation, plus arrayof_long_arraycopy
4582       _instance_path,     // plain instance allocation, plus arrayof_long_arraycopy
4583       PATH_LIMIT
4584     };
4585     RegionNode* result_reg = new RegionNode(PATH_LIMIT);
4586     result_val             = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
4587     PhiNode*    result_i_o = new PhiNode(result_reg, Type::ABIO);
4588     PhiNode*    result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
4589     record_for_igvn(result_reg);
4590 
4591     const TypePtr* raw_adr_type = TypeRawPtr::BOTTOM;
4592     int raw_adr_idx = Compile::AliasIdxRaw;
4593 
4594     Node* array_ctl = generate_array_guard(obj_klass, (RegionNode*)NULL);
4595     if (array_ctl != NULL) {
4596       // It's an array.
4597       PreserveJVMState pjvms(this);
4598       set_control(array_ctl);
4599       Node* obj_length = load_array_length(obj);
4600       Node* obj_size  = NULL;
4601       Node* alloc_obj = new_array(obj_klass, obj_length, 0, &obj_size);  // no arguments to push
4602 
4603       if (!use_ReduceInitialCardMarks()) {
4604         // If it is an oop array, it requires very special treatment,
4605         // because card marking is required on each card of the array.
4606         Node* is_obja = generate_objArray_guard(obj_klass, (RegionNode*)NULL);
4607         if (is_obja != NULL) {
4608           PreserveJVMState pjvms2(this);
4609           set_control(is_obja);
4610           // Generate a direct call to the right arraycopy function(s).
4611           Node* alloc = tightly_coupled_allocation(alloc_obj, NULL);
4612           ArrayCopyNode* ac = ArrayCopyNode::make(this, true, obj, intcon(0), alloc_obj, intcon(0), obj_length, alloc != NULL);
4613           ac->set_cloneoop();
4614           Node* n = _gvn.transform(ac);
4615           assert(n == ac, "cannot disappear");
4616           ac->connect_outputs(this);
4617 
4618           result_reg->init_req(_objArray_path, control());
4619           result_val->init_req(_objArray_path, alloc_obj);
4620           result_i_o ->set_req(_objArray_path, i_o());
4621           result_mem ->set_req(_objArray_path, reset_memory());
4622         }
4623       }
4624       // Otherwise, there are no card marks to worry about.
4625       // (We can dispense with card marks if we know the allocation
4626       //  comes out of eden (TLAB)...  In fact, ReduceInitialCardMarks
4627       //  causes the non-eden paths to take compensating steps to
4628       //  simulate a fresh allocation, so that no further
4629       //  card marks are required in compiled code to initialize
4630       //  the object.)
4631 
4632       if (!stopped()) {
4633         copy_to_clone(obj, alloc_obj, obj_size, true, false);
4634 
4635         // Present the results of the copy.
4636         result_reg->init_req(_array_path, control());
4637         result_val->init_req(_array_path, alloc_obj);
4638         result_i_o ->set_req(_array_path, i_o());
4639         result_mem ->set_req(_array_path, reset_memory());
4640       }
4641     }
4642 
4643     // We only go to the instance fast case code if we pass a number of guards.
4644     // The paths which do not pass are accumulated in the slow_region.
4645     RegionNode* slow_region = new RegionNode(1);
4646     record_for_igvn(slow_region);
4647     if (!stopped()) {
4648       // It's an instance (we did array above).  Make the slow-path tests.
4649       // If this is a virtual call, we generate a funny guard.  We grab
4650       // the vtable entry corresponding to clone() from the target object.
4651       // If the target method which we are calling happens to be the
4652       // Object clone() method, we pass the guard.  We do not need this
4653       // guard for non-virtual calls; the caller is known to be the native
4654       // Object clone().
4655       if (is_virtual) {
4656         generate_virtual_guard(obj_klass, slow_region);
4657       }
4658 
4659       // The object must be cloneable and must not have a finalizer.
4660       // Both of these conditions may be checked in a single test.
4661       // We could optimize the cloneable test further, but we don't care.
4662       generate_access_flags_guard(obj_klass,
4663                                   // Test both conditions:
4664                                   JVM_ACC_IS_CLONEABLE | JVM_ACC_HAS_FINALIZER,
4665                                   // Must be cloneable but not finalizer:
4666                                   JVM_ACC_IS_CLONEABLE,
4667                                   slow_region);
4668     }
4669 
4670     if (!stopped()) {
4671       // It's an instance, and it passed the slow-path tests.
4672       PreserveJVMState pjvms(this);
4673       Node* obj_size  = NULL;
4674       // Need to deoptimize on exception from allocation since Object.clone intrinsic
4675       // is reexecuted if deoptimization occurs and there could be problems when merging
4676       // exception state between multiple Object.clone versions (reexecute=true vs reexecute=false).
4677       Node* alloc_obj = new_instance(obj_klass, NULL, &obj_size, /*deoptimize_on_exception=*/true);
4678 
4679       copy_to_clone(obj, alloc_obj, obj_size, false, !use_ReduceInitialCardMarks());
4680 
4681       // Present the results of the slow call.
4682       result_reg->init_req(_instance_path, control());
4683       result_val->init_req(_instance_path, alloc_obj);
4684       result_i_o ->set_req(_instance_path, i_o());
4685       result_mem ->set_req(_instance_path, reset_memory());
4686     }
4687 
4688     // Generate code for the slow case.  We make a call to clone().
4689     set_control(_gvn.transform(slow_region));
4690     if (!stopped()) {
4691       PreserveJVMState pjvms(this);
4692       CallJavaNode* slow_call = generate_method_call(vmIntrinsics::_clone, is_virtual);
4693       Node* slow_result = set_results_for_java_call(slow_call);
4694       // this->control() comes from set_results_for_java_call
4695       result_reg->init_req(_slow_path, control());
4696       result_val->init_req(_slow_path, slow_result);
4697       result_i_o ->set_req(_slow_path, i_o());
4698       result_mem ->set_req(_slow_path, reset_memory());
4699     }
4700 
4701     // Return the combined state.
4702     set_control(    _gvn.transform(result_reg));
4703     set_i_o(        _gvn.transform(result_i_o));
4704     set_all_memory( _gvn.transform(result_mem));
4705   } // original reexecute is set back here
4706 
4707   set_result(_gvn.transform(result_val));
4708   return true;
4709 }
4710 
4711 // If we have a tighly coupled allocation, the arraycopy may take care
4712 // of the array initialization. If one of the guards we insert between
4713 // the allocation and the arraycopy causes a deoptimization, an
4714 // unitialized array will escape the compiled method. To prevent that
4715 // we set the JVM state for uncommon traps between the allocation and
4716 // the arraycopy to the state before the allocation so, in case of
4717 // deoptimization, we'll reexecute the allocation and the
4718 // initialization.
4719 JVMState* LibraryCallKit::arraycopy_restore_alloc_state(AllocateArrayNode* alloc, int& saved_reexecute_sp) {
4720   if (alloc != NULL) {
4721     ciMethod* trap_method = alloc->jvms()->method();
4722     int trap_bci = alloc->jvms()->bci();
4723 
4724     if (!C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_intrinsic) &
4725           !C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_null_check)) {
4726       // Make sure there's no store between the allocation and the
4727       // arraycopy otherwise visible side effects could be rexecuted
4728       // in case of deoptimization and cause incorrect execution.
4729       bool no_interfering_store = true;
4730       Node* mem = alloc->in(TypeFunc::Memory);
4731       if (mem->is_MergeMem()) {
4732         for (MergeMemStream mms(merged_memory(), mem->as_MergeMem()); mms.next_non_empty2(); ) {
4733           Node* n = mms.memory();
4734           if (n != mms.memory2() && !(n->is_Proj() && n->in(0) == alloc->initialization())) {
4735             assert(n->is_Store(), "what else?");
4736             no_interfering_store = false;
4737             break;
4738           }
4739         }
4740       } else {
4741         for (MergeMemStream mms(merged_memory()); mms.next_non_empty(); ) {
4742           Node* n = mms.memory();
4743           if (n != mem && !(n->is_Proj() && n->in(0) == alloc->initialization())) {
4744             assert(n->is_Store(), "what else?");
4745             no_interfering_store = false;
4746             break;
4747           }
4748         }
4749       }
4750 
4751       if (no_interfering_store) {
4752         JVMState* old_jvms = alloc->jvms()->clone_shallow(C);
4753         uint size = alloc->req();
4754         SafePointNode* sfpt = new SafePointNode(size, old_jvms);
4755         old_jvms->set_map(sfpt);
4756         for (uint i = 0; i < size; i++) {
4757           sfpt->init_req(i, alloc->in(i));
4758         }
4759         // re-push array length for deoptimization
4760         sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp(), alloc->in(AllocateNode::ALength));
4761         old_jvms->set_sp(old_jvms->sp()+1);
4762         old_jvms->set_monoff(old_jvms->monoff()+1);
4763         old_jvms->set_scloff(old_jvms->scloff()+1);
4764         old_jvms->set_endoff(old_jvms->endoff()+1);
4765         old_jvms->set_should_reexecute(true);
4766 
4767         sfpt->set_i_o(map()->i_o());
4768         sfpt->set_memory(map()->memory());
4769         sfpt->set_control(map()->control());
4770 
4771         JVMState* saved_jvms = jvms();
4772         saved_reexecute_sp = _reexecute_sp;
4773 
4774         set_jvms(sfpt->jvms());
4775         _reexecute_sp = jvms()->sp();
4776 
4777         return saved_jvms;
4778       }
4779     }
4780   }
4781   return NULL;
4782 }
4783 
4784 // In case of a deoptimization, we restart execution at the
4785 // allocation, allocating a new array. We would leave an uninitialized
4786 // array in the heap that GCs wouldn't expect. Move the allocation
4787 // after the traps so we don't allocate the array if we
4788 // deoptimize. This is possible because tightly_coupled_allocation()
4789 // guarantees there's no observer of the allocated array at this point
4790 // and the control flow is simple enough.
4791 void LibraryCallKit::arraycopy_move_allocation_here(AllocateArrayNode* alloc, Node* dest, JVMState* saved_jvms, int saved_reexecute_sp) {
4792   if (saved_jvms != NULL && !stopped()) {
4793     assert(alloc != NULL, "only with a tightly coupled allocation");
4794     // restore JVM state to the state at the arraycopy
4795     saved_jvms->map()->set_control(map()->control());
4796     assert(saved_jvms->map()->memory() == map()->memory(), "memory state changed?");
4797     assert(saved_jvms->map()->i_o() == map()->i_o(), "IO state changed?");
4798     // If we've improved the types of some nodes (null check) while
4799     // emitting the guards, propagate them to the current state
4800     map()->replaced_nodes().apply(saved_jvms->map());
4801     set_jvms(saved_jvms);
4802     _reexecute_sp = saved_reexecute_sp;
4803 
4804     // Remove the allocation from above the guards
4805     CallProjections callprojs;
4806     alloc->extract_projections(&callprojs, true);
4807     InitializeNode* init = alloc->initialization();
4808     Node* alloc_mem = alloc->in(TypeFunc::Memory);
4809     C->gvn_replace_by(callprojs.fallthrough_ioproj, alloc->in(TypeFunc::I_O));
4810     C->gvn_replace_by(init->proj_out(TypeFunc::Memory), alloc_mem);
4811     C->gvn_replace_by(init->proj_out(TypeFunc::Control), alloc->in(0));
4812 
4813     // move the allocation here (after the guards)
4814     _gvn.hash_delete(alloc);
4815     alloc->set_req(TypeFunc::Control, control());
4816     alloc->set_req(TypeFunc::I_O, i_o());
4817     Node *mem = reset_memory();
4818     set_all_memory(mem);
4819     alloc->set_req(TypeFunc::Memory, mem);
4820     set_control(init->proj_out(TypeFunc::Control));
4821     set_i_o(callprojs.fallthrough_ioproj);
4822 
4823     // Update memory as done in GraphKit::set_output_for_allocation()
4824     const TypeInt* length_type = _gvn.find_int_type(alloc->in(AllocateNode::ALength));
4825     const TypeOopPtr* ary_type = _gvn.type(alloc->in(AllocateNode::KlassNode))->is_klassptr()->as_instance_type();
4826     if (ary_type->isa_aryptr() && length_type != NULL) {
4827       ary_type = ary_type->is_aryptr()->cast_to_size(length_type);
4828     }
4829     const TypePtr* telemref = ary_type->add_offset(Type::OffsetBot);
4830     int            elemidx  = C->get_alias_index(telemref);
4831     set_memory(init->proj_out(TypeFunc::Memory), Compile::AliasIdxRaw);
4832     set_memory(init->proj_out(TypeFunc::Memory), elemidx);
4833 
4834     Node* allocx = _gvn.transform(alloc);
4835     assert(allocx == alloc, "where has the allocation gone?");
4836     assert(dest->is_CheckCastPP(), "not an allocation result?");
4837 
4838     _gvn.hash_delete(dest);
4839     dest->set_req(0, control());
4840     Node* destx = _gvn.transform(dest);
4841     assert(destx == dest, "where has the allocation result gone?");
4842   }
4843 }
4844 
4845 
4846 //------------------------------inline_arraycopy-----------------------
4847 // public static native void java.lang.System.arraycopy(Object src,  int  srcPos,
4848 //                                                      Object dest, int destPos,
4849 //                                                      int length);
4850 bool LibraryCallKit::inline_arraycopy() {
4851   // Get the arguments.
4852   Node* src         = argument(0);  // type: oop
4853   Node* src_offset  = argument(1);  // type: int
4854   Node* dest        = argument(2);  // type: oop
4855   Node* dest_offset = argument(3);  // type: int
4856   Node* length      = argument(4);  // type: int
4857 
4858 
4859   // Check for allocation before we add nodes that would confuse
4860   // tightly_coupled_allocation()
4861   AllocateArrayNode* alloc = tightly_coupled_allocation(dest, NULL);
4862 
4863   int saved_reexecute_sp = -1;
4864   JVMState* saved_jvms = arraycopy_restore_alloc_state(alloc, saved_reexecute_sp);
4865   // See arraycopy_restore_alloc_state() comment
4866   // if alloc == NULL we don't have to worry about a tightly coupled allocation so we can emit all needed guards
4867   // if saved_jvms != NULL (then alloc != NULL) then we can handle guards and a tightly coupled allocation
4868   // if saved_jvms == NULL and alloc != NULL, we can’t emit any guards
4869   bool can_emit_guards = (alloc == NULL || saved_jvms != NULL);
4870 
4871   // The following tests must be performed
4872   // (1) src and dest are arrays.
4873   // (2) src and dest arrays must have elements of the same BasicType
4874   // (3) src and dest must not be null.
4875   // (4) src_offset must not be negative.
4876   // (5) dest_offset must not be negative.
4877   // (6) length must not be negative.
4878   // (7) src_offset + length must not exceed length of src.
4879   // (8) dest_offset + length must not exceed length of dest.
4880   // (9) each element of an oop array must be assignable
4881 
4882   // (3) src and dest must not be null.
4883   // always do this here because we need the JVM state for uncommon traps
4884   Node* null_ctl = top();
4885   src  = saved_jvms != NULL ? null_check_oop(src, &null_ctl, true, true) : null_check(src,  T_ARRAY);
4886   assert(null_ctl->is_top(), "no null control here");
4887   dest = null_check(dest, T_ARRAY);
4888 
4889   if (!can_emit_guards) {
4890     // if saved_jvms == NULL and alloc != NULL, we don't emit any
4891     // guards but the arraycopy node could still take advantage of a
4892     // tightly allocated allocation. tightly_coupled_allocation() is
4893     // called again to make sure it takes the null check above into
4894     // account: the null check is mandatory and if it caused an
4895     // uncommon trap to be emitted then the allocation can't be
4896     // considered tightly coupled in this context.
4897     alloc = tightly_coupled_allocation(dest, NULL);
4898   }
4899 
4900   bool validated = false;
4901 
4902   const Type* src_type  = _gvn.type(src);
4903   const Type* dest_type = _gvn.type(dest);
4904   const TypeAryPtr* top_src  = src_type->isa_aryptr();
4905   const TypeAryPtr* top_dest = dest_type->isa_aryptr();
4906 
4907   // Do we have the type of src?
4908   bool has_src = (top_src != NULL && top_src->klass() != NULL);
4909   // Do we have the type of dest?
4910   bool has_dest = (top_dest != NULL && top_dest->klass() != NULL);
4911   // Is the type for src from speculation?
4912   bool src_spec = false;
4913   // Is the type for dest from speculation?
4914   bool dest_spec = false;
4915 
4916   if ((!has_src || !has_dest) && can_emit_guards) {
4917     // We don't have sufficient type information, let's see if
4918     // speculative types can help. We need to have types for both src
4919     // and dest so that it pays off.
4920 
4921     // Do we already have or could we have type information for src
4922     bool could_have_src = has_src;
4923     // Do we already have or could we have type information for dest
4924     bool could_have_dest = has_dest;
4925 
4926     ciKlass* src_k = NULL;
4927     if (!has_src) {
4928       src_k = src_type->speculative_type_not_null();
4929       if (src_k != NULL && src_k->is_array_klass()) {
4930         could_have_src = true;
4931       }
4932     }
4933 
4934     ciKlass* dest_k = NULL;
4935     if (!has_dest) {
4936       dest_k = dest_type->speculative_type_not_null();
4937       if (dest_k != NULL && dest_k->is_array_klass()) {
4938         could_have_dest = true;
4939       }
4940     }
4941 
4942     if (could_have_src && could_have_dest) {
4943       // This is going to pay off so emit the required guards
4944       if (!has_src) {
4945         src = maybe_cast_profiled_obj(src, src_k, true);
4946         src_type  = _gvn.type(src);
4947         top_src  = src_type->isa_aryptr();
4948         has_src = (top_src != NULL && top_src->klass() != NULL);
4949         src_spec = true;
4950       }
4951       if (!has_dest) {
4952         dest = maybe_cast_profiled_obj(dest, dest_k, true);
4953         dest_type  = _gvn.type(dest);
4954         top_dest  = dest_type->isa_aryptr();
4955         has_dest = (top_dest != NULL && top_dest->klass() != NULL);
4956         dest_spec = true;
4957       }
4958     }
4959   }
4960 
4961   if (has_src && has_dest && can_emit_guards) {
4962     BasicType src_elem  = top_src->klass()->as_array_klass()->element_type()->basic_type();
4963     BasicType dest_elem = top_dest->klass()->as_array_klass()->element_type()->basic_type();
4964     if (src_elem  == T_ARRAY)  src_elem  = T_OBJECT;
4965     if (dest_elem == T_ARRAY)  dest_elem = T_OBJECT;
4966 
4967     if (src_elem == dest_elem && src_elem == T_OBJECT) {
4968       // If both arrays are object arrays then having the exact types
4969       // for both will remove the need for a subtype check at runtime
4970       // before the call and may make it possible to pick a faster copy
4971       // routine (without a subtype check on every element)
4972       // Do we have the exact type of src?
4973       bool could_have_src = src_spec;
4974       // Do we have the exact type of dest?
4975       bool could_have_dest = dest_spec;
4976       ciKlass* src_k = top_src->klass();
4977       ciKlass* dest_k = top_dest->klass();
4978       if (!src_spec) {
4979         src_k = src_type->speculative_type_not_null();
4980         if (src_k != NULL && src_k->is_array_klass()) {
4981           could_have_src = true;
4982         }
4983       }
4984       if (!dest_spec) {
4985         dest_k = dest_type->speculative_type_not_null();
4986         if (dest_k != NULL && dest_k->is_array_klass()) {
4987           could_have_dest = true;
4988         }
4989       }
4990       if (could_have_src && could_have_dest) {
4991         // If we can have both exact types, emit the missing guards
4992         if (could_have_src && !src_spec) {
4993           src = maybe_cast_profiled_obj(src, src_k, true);
4994         }
4995         if (could_have_dest && !dest_spec) {
4996           dest = maybe_cast_profiled_obj(dest, dest_k, true);
4997         }
4998       }
4999     }
5000   }
5001 
5002   ciMethod* trap_method = method();
5003   int trap_bci = bci();
5004   if (saved_jvms != NULL) {
5005     trap_method = alloc->jvms()->method();
5006     trap_bci = alloc->jvms()->bci();
5007   }
5008 
5009   if (!C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_intrinsic) &&
5010       can_emit_guards &&
5011       !src->is_top() && !dest->is_top()) {
5012     // validate arguments: enables transformation the ArrayCopyNode
5013     validated = true;
5014 
5015     RegionNode* slow_region = new RegionNode(1);
5016     record_for_igvn(slow_region);
5017 
5018     // (1) src and dest are arrays.
5019     generate_non_array_guard(load_object_klass(src), slow_region);
5020     generate_non_array_guard(load_object_klass(dest), slow_region);
5021 
5022     // (2) src and dest arrays must have elements of the same BasicType
5023     // done at macro expansion or at Ideal transformation time
5024 
5025     // (4) src_offset must not be negative.
5026     generate_negative_guard(src_offset, slow_region);
5027 
5028     // (5) dest_offset must not be negative.
5029     generate_negative_guard(dest_offset, slow_region);
5030 
5031     // (7) src_offset + length must not exceed length of src.
5032     generate_limit_guard(src_offset, length,
5033                          load_array_length(src),
5034                          slow_region);
5035 
5036     // (8) dest_offset + length must not exceed length of dest.
5037     generate_limit_guard(dest_offset, length,
5038                          load_array_length(dest),
5039                          slow_region);
5040 
5041     // (9) each element of an oop array must be assignable
5042     Node* src_klass  = load_object_klass(src);
5043     Node* dest_klass = load_object_klass(dest);
5044     Node* not_subtype_ctrl = gen_subtype_check(src_klass, dest_klass);
5045 
5046     if (not_subtype_ctrl != top()) {
5047       PreserveJVMState pjvms(this);
5048       set_control(not_subtype_ctrl);
5049       uncommon_trap(Deoptimization::Reason_intrinsic,
5050                     Deoptimization::Action_make_not_entrant);
5051       assert(stopped(), "Should be stopped");
5052     }
5053     {
5054       PreserveJVMState pjvms(this);
5055       set_control(_gvn.transform(slow_region));
5056       uncommon_trap(Deoptimization::Reason_intrinsic,
5057                     Deoptimization::Action_make_not_entrant);
5058       assert(stopped(), "Should be stopped");
5059     }
5060   }
5061 
5062   arraycopy_move_allocation_here(alloc, dest, saved_jvms, saved_reexecute_sp);
5063 
5064   if (stopped()) {
5065     return true;
5066   }
5067 
5068   ArrayCopyNode* ac = ArrayCopyNode::make(this, true, src, src_offset, dest, dest_offset, length, alloc != NULL,
5069                                           // Create LoadRange and LoadKlass nodes for use during macro expansion here
5070                                           // so the compiler has a chance to eliminate them: during macro expansion,
5071                                           // we have to set their control (CastPP nodes are eliminated).
5072                                           load_object_klass(src), load_object_klass(dest),
5073                                           load_array_length(src), load_array_length(dest));
5074 
5075   ac->set_arraycopy(validated);
5076 
5077   Node* n = _gvn.transform(ac);
5078   if (n == ac) {
5079     ac->connect_outputs(this);
5080   } else {
5081     assert(validated, "shouldn't transform if all arguments not validated");
5082     set_all_memory(n);
5083   }
5084 
5085   return true;
5086 }
5087 
5088 
5089 // Helper function which determines if an arraycopy immediately follows
5090 // an allocation, with no intervening tests or other escapes for the object.
5091 AllocateArrayNode*
5092 LibraryCallKit::tightly_coupled_allocation(Node* ptr,
5093                                            RegionNode* slow_region) {
5094   if (stopped())             return NULL;  // no fast path
5095   if (C->AliasLevel() == 0)  return NULL;  // no MergeMems around
5096 
5097   AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(ptr, &_gvn);
5098   if (alloc == NULL)  return NULL;
5099 
5100   Node* rawmem = memory(Compile::AliasIdxRaw);
5101   // Is the allocation's memory state untouched?
5102   if (!(rawmem->is_Proj() && rawmem->in(0)->is_Initialize())) {
5103     // Bail out if there have been raw-memory effects since the allocation.
5104     // (Example:  There might have been a call or safepoint.)
5105     return NULL;
5106   }
5107   rawmem = rawmem->in(0)->as_Initialize()->memory(Compile::AliasIdxRaw);
5108   if (!(rawmem->is_Proj() && rawmem->in(0) == alloc)) {
5109     return NULL;
5110   }
5111 
5112   // There must be no unexpected observers of this allocation.
5113   for (DUIterator_Fast imax, i = ptr->fast_outs(imax); i < imax; i++) {
5114     Node* obs = ptr->fast_out(i);
5115     if (obs != this->map()) {
5116       return NULL;
5117     }
5118   }
5119 
5120   // This arraycopy must unconditionally follow the allocation of the ptr.
5121   Node* alloc_ctl = ptr->in(0);
5122   assert(just_allocated_object(alloc_ctl) == ptr, "most recent allo");
5123 
5124   Node* ctl = control();
5125   while (ctl != alloc_ctl) {
5126     // There may be guards which feed into the slow_region.
5127     // Any other control flow means that we might not get a chance
5128     // to finish initializing the allocated object.
5129     if ((ctl->is_IfFalse() || ctl->is_IfTrue()) && ctl->in(0)->is_If()) {
5130       IfNode* iff = ctl->in(0)->as_If();
5131       Node* not_ctl = iff->proj_out(1 - ctl->as_Proj()->_con);
5132       assert(not_ctl != NULL && not_ctl != ctl, "found alternate");
5133       if (slow_region != NULL && slow_region->find_edge(not_ctl) >= 1) {
5134         ctl = iff->in(0);       // This test feeds the known slow_region.
5135         continue;
5136       }
5137       // One more try:  Various low-level checks bottom out in
5138       // uncommon traps.  If the debug-info of the trap omits
5139       // any reference to the allocation, as we've already
5140       // observed, then there can be no objection to the trap.
5141       bool found_trap = false;
5142       for (DUIterator_Fast jmax, j = not_ctl->fast_outs(jmax); j < jmax; j++) {
5143         Node* obs = not_ctl->fast_out(j);
5144         if (obs->in(0) == not_ctl && obs->is_Call() &&
5145             (obs->as_Call()->entry_point() == SharedRuntime::uncommon_trap_blob()->entry_point())) {
5146           found_trap = true; break;
5147         }
5148       }
5149       if (found_trap) {
5150         ctl = iff->in(0);       // This test feeds a harmless uncommon trap.
5151         continue;
5152       }
5153     }
5154     return NULL;
5155   }
5156 
5157   // If we get this far, we have an allocation which immediately
5158   // precedes the arraycopy, and we can take over zeroing the new object.
5159   // The arraycopy will finish the initialization, and provide
5160   // a new control state to which we will anchor the destination pointer.
5161 
5162   return alloc;
5163 }
5164 
5165 //-------------inline_encodeISOArray-----------------------------------
5166 // encode char[] to byte[] in ISO_8859_1
5167 bool LibraryCallKit::inline_encodeISOArray() {
5168   assert(callee()->signature()->size() == 5, "encodeISOArray has 5 parameters");
5169   // no receiver since it is static method
5170   Node *src         = argument(0);
5171   Node *src_offset  = argument(1);
5172   Node *dst         = argument(2);
5173   Node *dst_offset  = argument(3);
5174   Node *length      = argument(4);
5175 
5176   const Type* src_type = src->Value(&_gvn);
5177   const Type* dst_type = dst->Value(&_gvn);
5178   const TypeAryPtr* top_src = src_type->isa_aryptr();
5179   const TypeAryPtr* top_dest = dst_type->isa_aryptr();
5180   if (top_src  == NULL || top_src->klass()  == NULL ||
5181       top_dest == NULL || top_dest->klass() == NULL) {
5182     // failed array check
5183     return false;
5184   }
5185 
5186   // Figure out the size and type of the elements we will be copying.
5187   BasicType src_elem = src_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5188   BasicType dst_elem = dst_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5189   if (src_elem != T_CHAR || dst_elem != T_BYTE) {
5190     return false;
5191   }
5192   Node* src_start = array_element_address(src, src_offset, src_elem);
5193   Node* dst_start = array_element_address(dst, dst_offset, dst_elem);
5194   // 'src_start' points to src array + scaled offset
5195   // 'dst_start' points to dst array + scaled offset
5196 
5197   const TypeAryPtr* mtype = TypeAryPtr::BYTES;
5198   Node* enc = new EncodeISOArrayNode(control(), memory(mtype), src_start, dst_start, length);
5199   enc = _gvn.transform(enc);
5200   Node* res_mem = _gvn.transform(new SCMemProjNode(enc));
5201   set_memory(res_mem, mtype);
5202   set_result(enc);
5203   return true;
5204 }
5205 
5206 //-------------inline_multiplyToLen-----------------------------------
5207 bool LibraryCallKit::inline_multiplyToLen() {
5208   assert(UseMultiplyToLenIntrinsic, "not implementated on this platform");
5209 
5210   address stubAddr = StubRoutines::multiplyToLen();
5211   if (stubAddr == NULL) {
5212     return false; // Intrinsic's stub is not implemented on this platform
5213   }
5214   const char* stubName = "multiplyToLen";
5215 
5216   assert(callee()->signature()->size() == 5, "multiplyToLen has 5 parameters");
5217 
5218   Node* x    = argument(1);
5219   Node* xlen = argument(2);
5220   Node* y    = argument(3);
5221   Node* ylen = argument(4);
5222   Node* z    = argument(5);
5223 
5224   const Type* x_type = x->Value(&_gvn);
5225   const Type* y_type = y->Value(&_gvn);
5226   const TypeAryPtr* top_x = x_type->isa_aryptr();
5227   const TypeAryPtr* top_y = y_type->isa_aryptr();
5228   if (top_x  == NULL || top_x->klass()  == NULL ||
5229       top_y == NULL || top_y->klass() == NULL) {
5230     // failed array check
5231     return false;
5232   }
5233 
5234   BasicType x_elem = x_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5235   BasicType y_elem = y_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5236   if (x_elem != T_INT || y_elem != T_INT) {
5237     return false;
5238   }
5239 
5240   // Set the original stack and the reexecute bit for the interpreter to reexecute
5241   // the bytecode that invokes BigInteger.multiplyToLen() if deoptimization happens
5242   // on the return from z array allocation in runtime.
5243   { PreserveReexecuteState preexecs(this);
5244     jvms()->set_should_reexecute(true);
5245 
5246     Node* x_start = array_element_address(x, intcon(0), x_elem);
5247     Node* y_start = array_element_address(y, intcon(0), y_elem);
5248     // 'x_start' points to x array + scaled xlen
5249     // 'y_start' points to y array + scaled ylen
5250 
5251     // Allocate the result array
5252     Node* zlen = _gvn.transform(new AddINode(xlen, ylen));
5253     ciKlass* klass = ciTypeArrayKlass::make(T_INT);
5254     Node* klass_node = makecon(TypeKlassPtr::make(klass));
5255 
5256     IdealKit ideal(this);
5257 
5258 #define __ ideal.
5259      Node* one = __ ConI(1);
5260      Node* zero = __ ConI(0);
5261      IdealVariable need_alloc(ideal), z_alloc(ideal);  __ declarations_done();
5262      __ set(need_alloc, zero);
5263      __ set(z_alloc, z);
5264      __ if_then(z, BoolTest::eq, null()); {
5265        __ increment (need_alloc, one);
5266      } __ else_(); {
5267        // Update graphKit memory and control from IdealKit.
5268        sync_kit(ideal);
5269        Node* zlen_arg = load_array_length(z);
5270        // Update IdealKit memory and control from graphKit.
5271        __ sync_kit(this);
5272        __ if_then(zlen_arg, BoolTest::lt, zlen); {
5273          __ increment (need_alloc, one);
5274        } __ end_if();
5275      } __ end_if();
5276 
5277      __ if_then(__ value(need_alloc), BoolTest::ne, zero); {
5278        // Update graphKit memory and control from IdealKit.
5279        sync_kit(ideal);
5280        Node * narr = new_array(klass_node, zlen, 1);
5281        // Update IdealKit memory and control from graphKit.
5282        __ sync_kit(this);
5283        __ set(z_alloc, narr);
5284      } __ end_if();
5285 
5286      sync_kit(ideal);
5287      z = __ value(z_alloc);
5288      // Can't use TypeAryPtr::INTS which uses Bottom offset.
5289      _gvn.set_type(z, TypeOopPtr::make_from_klass(klass));
5290      // Final sync IdealKit and GraphKit.
5291      final_sync(ideal);
5292 #undef __
5293 
5294     Node* z_start = array_element_address(z, intcon(0), T_INT);
5295 
5296     Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
5297                                    OptoRuntime::multiplyToLen_Type(),
5298                                    stubAddr, stubName, TypePtr::BOTTOM,
5299                                    x_start, xlen, y_start, ylen, z_start, zlen);
5300   } // original reexecute is set back here
5301 
5302   C->set_has_split_ifs(true); // Has chance for split-if optimization
5303   set_result(z);
5304   return true;
5305 }
5306 
5307 
5308 /**
5309  * Calculate CRC32 for byte.
5310  * int java.util.zip.CRC32.update(int crc, int b)
5311  */
5312 bool LibraryCallKit::inline_updateCRC32() {
5313   assert(UseCRC32Intrinsics, "need AVX and LCMUL instructions support");
5314   assert(callee()->signature()->size() == 2, "update has 2 parameters");
5315   // no receiver since it is static method
5316   Node* crc  = argument(0); // type: int
5317   Node* b    = argument(1); // type: int
5318 
5319   /*
5320    *    int c = ~ crc;
5321    *    b = timesXtoThe32[(b ^ c) & 0xFF];
5322    *    b = b ^ (c >>> 8);
5323    *    crc = ~b;
5324    */
5325 
5326   Node* M1 = intcon(-1);
5327   crc = _gvn.transform(new XorINode(crc, M1));
5328   Node* result = _gvn.transform(new XorINode(crc, b));
5329   result = _gvn.transform(new AndINode(result, intcon(0xFF)));
5330 
5331   Node* base = makecon(TypeRawPtr::make(StubRoutines::crc_table_addr()));
5332   Node* offset = _gvn.transform(new LShiftINode(result, intcon(0x2)));
5333   Node* adr = basic_plus_adr(top(), base, ConvI2X(offset));
5334   result = make_load(control(), adr, TypeInt::INT, T_INT, MemNode::unordered);
5335 
5336   crc = _gvn.transform(new URShiftINode(crc, intcon(8)));
5337   result = _gvn.transform(new XorINode(crc, result));
5338   result = _gvn.transform(new XorINode(result, M1));
5339   set_result(result);
5340   return true;
5341 }
5342 
5343 /**
5344  * Calculate CRC32 for byte[] array.
5345  * int java.util.zip.CRC32.updateBytes(int crc, byte[] buf, int off, int len)
5346  */
5347 bool LibraryCallKit::inline_updateBytesCRC32() {
5348   assert(UseCRC32Intrinsics, "need AVX and LCMUL instructions support");
5349   assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
5350   // no receiver since it is static method
5351   Node* crc     = argument(0); // type: int
5352   Node* src     = argument(1); // type: oop
5353   Node* offset  = argument(2); // type: int
5354   Node* length  = argument(3); // type: int
5355 
5356   const Type* src_type = src->Value(&_gvn);
5357   const TypeAryPtr* top_src = src_type->isa_aryptr();
5358   if (top_src  == NULL || top_src->klass()  == NULL) {
5359     // failed array check
5360     return false;
5361   }
5362 
5363   // Figure out the size and type of the elements we will be copying.
5364   BasicType src_elem = src_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5365   if (src_elem != T_BYTE) {
5366     return false;
5367   }
5368 
5369   // 'src_start' points to src array + scaled offset
5370   Node* src_start = array_element_address(src, offset, src_elem);
5371 
5372   // We assume that range check is done by caller.
5373   // TODO: generate range check (offset+length < src.length) in debug VM.
5374 
5375   // Call the stub.
5376   address stubAddr = StubRoutines::updateBytesCRC32();
5377   const char *stubName = "updateBytesCRC32";
5378 
5379   Node* call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::updateBytesCRC32_Type(),
5380                                  stubAddr, stubName, TypePtr::BOTTOM,
5381                                  crc, src_start, length);
5382   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
5383   set_result(result);
5384   return true;
5385 }
5386 
5387 /**
5388  * Calculate CRC32 for ByteBuffer.
5389  * int java.util.zip.CRC32.updateByteBuffer(int crc, long buf, int off, int len)
5390  */
5391 bool LibraryCallKit::inline_updateByteBufferCRC32() {
5392   assert(UseCRC32Intrinsics, "need AVX and LCMUL instructions support");
5393   assert(callee()->signature()->size() == 5, "updateByteBuffer has 4 parameters and one is long");
5394   // no receiver since it is static method
5395   Node* crc     = argument(0); // type: int
5396   Node* src     = argument(1); // type: long
5397   Node* offset  = argument(3); // type: int
5398   Node* length  = argument(4); // type: int
5399 
5400   src = ConvL2X(src);  // adjust Java long to machine word
5401   Node* base = _gvn.transform(new CastX2PNode(src));
5402   offset = ConvI2X(offset);
5403 
5404   // 'src_start' points to src array + scaled offset
5405   Node* src_start = basic_plus_adr(top(), base, offset);
5406 
5407   // Call the stub.
5408   address stubAddr = StubRoutines::updateBytesCRC32();
5409   const char *stubName = "updateBytesCRC32";
5410 
5411   Node* call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::updateBytesCRC32_Type(),
5412                                  stubAddr, stubName, TypePtr::BOTTOM,
5413                                  crc, src_start, length);
5414   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
5415   set_result(result);
5416   return true;
5417 }
5418 
5419 //----------------------------inline_reference_get----------------------------
5420 // public T java.lang.ref.Reference.get();
5421 bool LibraryCallKit::inline_reference_get() {
5422   const int referent_offset = java_lang_ref_Reference::referent_offset;
5423   guarantee(referent_offset > 0, "should have already been set");
5424 
5425   // Get the argument:
5426   Node* reference_obj = null_check_receiver();
5427   if (stopped()) return true;
5428 
5429   Node* adr = basic_plus_adr(reference_obj, reference_obj, referent_offset);
5430 
5431   ciInstanceKlass* klass = env()->Object_klass();
5432   const TypeOopPtr* object_type = TypeOopPtr::make_from_klass(klass);
5433 
5434   Node* no_ctrl = NULL;
5435   Node* result = make_load(no_ctrl, adr, object_type, T_OBJECT, MemNode::unordered);
5436 
5437   // Use the pre-barrier to record the value in the referent field
5438   pre_barrier(false /* do_load */,
5439               control(),
5440               NULL /* obj */, NULL /* adr */, max_juint /* alias_idx */, NULL /* val */, NULL /* val_type */,
5441               result /* pre_val */,
5442               T_OBJECT);
5443 
5444   // Add memory barrier to prevent commoning reads from this field
5445   // across safepoint since GC can change its value.
5446   insert_mem_bar(Op_MemBarCPUOrder);
5447 
5448   set_result(result);
5449   return true;
5450 }
5451 
5452 
5453 Node * LibraryCallKit::load_field_from_object(Node * fromObj, const char * fieldName, const char * fieldTypeString,
5454                                               bool is_exact=true, bool is_static=false) {
5455 
5456   const TypeInstPtr* tinst = _gvn.type(fromObj)->isa_instptr();
5457   assert(tinst != NULL, "obj is null");
5458   assert(tinst->klass()->is_loaded(), "obj is not loaded");
5459   assert(!is_exact || tinst->klass_is_exact(), "klass not exact");
5460 
5461   ciField* field = tinst->klass()->as_instance_klass()->get_field_by_name(ciSymbol::make(fieldName),
5462                                                                           ciSymbol::make(fieldTypeString),
5463                                                                           is_static);
5464   if (field == NULL) return (Node *) NULL;
5465   assert (field != NULL, "undefined field");
5466 
5467   // Next code  copied from Parse::do_get_xxx():
5468 
5469   // Compute address and memory type.
5470   int offset  = field->offset_in_bytes();
5471   bool is_vol = field->is_volatile();
5472   ciType* field_klass = field->type();
5473   assert(field_klass->is_loaded(), "should be loaded");
5474   const TypePtr* adr_type = C->alias_type(field)->adr_type();
5475   Node *adr = basic_plus_adr(fromObj, fromObj, offset);
5476   BasicType bt = field->layout_type();
5477 
5478   // Build the resultant type of the load
5479   const Type *type;
5480   if (bt == T_OBJECT) {
5481     type = TypeOopPtr::make_from_klass(field_klass->as_klass());
5482   } else {
5483     type = Type::get_const_basic_type(bt);
5484   }
5485 
5486   if (support_IRIW_for_not_multiple_copy_atomic_cpu && is_vol) {
5487     insert_mem_bar(Op_MemBarVolatile);   // StoreLoad barrier
5488   }
5489   // Build the load.
5490   MemNode::MemOrd mo = is_vol ? MemNode::acquire : MemNode::unordered;
5491   Node* loadedField = make_load(NULL, adr, type, bt, adr_type, mo, is_vol);
5492   // If reference is volatile, prevent following memory ops from
5493   // floating up past the volatile read.  Also prevents commoning
5494   // another volatile read.
5495   if (is_vol) {
5496     // Memory barrier includes bogus read of value to force load BEFORE membar
5497     insert_mem_bar(Op_MemBarAcquire, loadedField);
5498   }
5499   return loadedField;
5500 }
5501 
5502 
5503 //------------------------------inline_aescrypt_Block-----------------------
5504 bool LibraryCallKit::inline_aescrypt_Block(vmIntrinsics::ID id) {
5505   address stubAddr;
5506   const char *stubName;
5507   assert(UseAES, "need AES instruction support");
5508 
5509   switch(id) {
5510   case vmIntrinsics::_aescrypt_encryptBlock:
5511     stubAddr = StubRoutines::aescrypt_encryptBlock();
5512     stubName = "aescrypt_encryptBlock";
5513     break;
5514   case vmIntrinsics::_aescrypt_decryptBlock:
5515     stubAddr = StubRoutines::aescrypt_decryptBlock();
5516     stubName = "aescrypt_decryptBlock";
5517     break;
5518   }
5519   if (stubAddr == NULL) return false;
5520 
5521   Node* aescrypt_object = argument(0);
5522   Node* src             = argument(1);
5523   Node* src_offset      = argument(2);
5524   Node* dest            = argument(3);
5525   Node* dest_offset     = argument(4);
5526 
5527   // (1) src and dest are arrays.
5528   const Type* src_type = src->Value(&_gvn);
5529   const Type* dest_type = dest->Value(&_gvn);
5530   const TypeAryPtr* top_src = src_type->isa_aryptr();
5531   const TypeAryPtr* top_dest = dest_type->isa_aryptr();
5532   assert (top_src  != NULL && top_src->klass()  != NULL &&  top_dest != NULL && top_dest->klass() != NULL, "args are strange");
5533 
5534   // for the quick and dirty code we will skip all the checks.
5535   // we are just trying to get the call to be generated.
5536   Node* src_start  = src;
5537   Node* dest_start = dest;
5538   if (src_offset != NULL || dest_offset != NULL) {
5539     assert(src_offset != NULL && dest_offset != NULL, "");
5540     src_start  = array_element_address(src,  src_offset,  T_BYTE);
5541     dest_start = array_element_address(dest, dest_offset, T_BYTE);
5542   }
5543 
5544   // now need to get the start of its expanded key array
5545   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
5546   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object);
5547   if (k_start == NULL) return false;
5548 
5549   if (Matcher::pass_original_key_for_aes()) {
5550     // on SPARC we need to pass the original key since key expansion needs to happen in intrinsics due to
5551     // compatibility issues between Java key expansion and SPARC crypto instructions
5552     Node* original_k_start = get_original_key_start_from_aescrypt_object(aescrypt_object);
5553     if (original_k_start == NULL) return false;
5554 
5555     // Call the stub.
5556     make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::aescrypt_block_Type(),
5557                       stubAddr, stubName, TypePtr::BOTTOM,
5558                       src_start, dest_start, k_start, original_k_start);
5559   } else {
5560     // Call the stub.
5561     make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::aescrypt_block_Type(),
5562                       stubAddr, stubName, TypePtr::BOTTOM,
5563                       src_start, dest_start, k_start);
5564   }
5565 
5566   return true;
5567 }
5568 
5569 //------------------------------inline_cipherBlockChaining_AESCrypt-----------------------
5570 bool LibraryCallKit::inline_cipherBlockChaining_AESCrypt(vmIntrinsics::ID id) {
5571   address stubAddr;
5572   const char *stubName;
5573 
5574   assert(UseAES, "need AES instruction support");
5575 
5576   switch(id) {
5577   case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
5578     stubAddr = StubRoutines::cipherBlockChaining_encryptAESCrypt();
5579     stubName = "cipherBlockChaining_encryptAESCrypt";
5580     break;
5581   case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
5582     stubAddr = StubRoutines::cipherBlockChaining_decryptAESCrypt();
5583     stubName = "cipherBlockChaining_decryptAESCrypt";
5584     break;
5585   }
5586   if (stubAddr == NULL) return false;
5587 
5588   Node* cipherBlockChaining_object = argument(0);
5589   Node* src                        = argument(1);
5590   Node* src_offset                 = argument(2);
5591   Node* len                        = argument(3);
5592   Node* dest                       = argument(4);
5593   Node* dest_offset                = argument(5);
5594 
5595   // (1) src and dest are arrays.
5596   const Type* src_type = src->Value(&_gvn);
5597   const Type* dest_type = dest->Value(&_gvn);
5598   const TypeAryPtr* top_src = src_type->isa_aryptr();
5599   const TypeAryPtr* top_dest = dest_type->isa_aryptr();
5600   assert (top_src  != NULL && top_src->klass()  != NULL
5601           &&  top_dest != NULL && top_dest->klass() != NULL, "args are strange");
5602 
5603   // checks are the responsibility of the caller
5604   Node* src_start  = src;
5605   Node* dest_start = dest;
5606   if (src_offset != NULL || dest_offset != NULL) {
5607     assert(src_offset != NULL && dest_offset != NULL, "");
5608     src_start  = array_element_address(src,  src_offset,  T_BYTE);
5609     dest_start = array_element_address(dest, dest_offset, T_BYTE);
5610   }
5611 
5612   // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
5613   // (because of the predicated logic executed earlier).
5614   // so we cast it here safely.
5615   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
5616 
5617   Node* embeddedCipherObj = load_field_from_object(cipherBlockChaining_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;", /*is_exact*/ false);
5618   if (embeddedCipherObj == NULL) return false;
5619 
5620   // cast it to what we know it will be at runtime
5621   const TypeInstPtr* tinst = _gvn.type(cipherBlockChaining_object)->isa_instptr();
5622   assert(tinst != NULL, "CBC obj is null");
5623   assert(tinst->klass()->is_loaded(), "CBC obj is not loaded");
5624   ciKlass* klass_AESCrypt = tinst->klass()->as_instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AESCrypt"));
5625   assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
5626 
5627   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
5628   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
5629   const TypeOopPtr* xtype = aklass->as_instance_type();
5630   Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
5631   aescrypt_object = _gvn.transform(aescrypt_object);
5632 
5633   // we need to get the start of the aescrypt_object's expanded key array
5634   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object);
5635   if (k_start == NULL) return false;
5636 
5637   // similarly, get the start address of the r vector
5638   Node* objRvec = load_field_from_object(cipherBlockChaining_object, "r", "[B", /*is_exact*/ false);
5639   if (objRvec == NULL) return false;
5640   Node* r_start = array_element_address(objRvec, intcon(0), T_BYTE);
5641 
5642   Node* cbcCrypt;
5643   if (Matcher::pass_original_key_for_aes()) {
5644     // on SPARC we need to pass the original key since key expansion needs to happen in intrinsics due to
5645     // compatibility issues between Java key expansion and SPARC crypto instructions
5646     Node* original_k_start = get_original_key_start_from_aescrypt_object(aescrypt_object);
5647     if (original_k_start == NULL) return false;
5648 
5649     // Call the stub, passing src_start, dest_start, k_start, r_start, src_len and original_k_start
5650     cbcCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
5651                                  OptoRuntime::cipherBlockChaining_aescrypt_Type(),
5652                                  stubAddr, stubName, TypePtr::BOTTOM,
5653                                  src_start, dest_start, k_start, r_start, len, original_k_start);
5654   } else {
5655     // Call the stub, passing src_start, dest_start, k_start, r_start and src_len
5656     cbcCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
5657                                  OptoRuntime::cipherBlockChaining_aescrypt_Type(),
5658                                  stubAddr, stubName, TypePtr::BOTTOM,
5659                                  src_start, dest_start, k_start, r_start, len);
5660   }
5661 
5662   // return cipher length (int)
5663   Node* retvalue = _gvn.transform(new ProjNode(cbcCrypt, TypeFunc::Parms));
5664   set_result(retvalue);
5665   return true;
5666 }
5667 
5668 //------------------------------get_key_start_from_aescrypt_object-----------------------
5669 Node * LibraryCallKit::get_key_start_from_aescrypt_object(Node *aescrypt_object) {
5670   Node* objAESCryptKey = load_field_from_object(aescrypt_object, "K", "[I", /*is_exact*/ false);
5671   assert (objAESCryptKey != NULL, "wrong version of com.sun.crypto.provider.AESCrypt");
5672   if (objAESCryptKey == NULL) return (Node *) NULL;
5673 
5674   // now have the array, need to get the start address of the K array
5675   Node* k_start = array_element_address(objAESCryptKey, intcon(0), T_INT);
5676   return k_start;
5677 }
5678 
5679 //------------------------------get_original_key_start_from_aescrypt_object-----------------------
5680 Node * LibraryCallKit::get_original_key_start_from_aescrypt_object(Node *aescrypt_object) {
5681   Node* objAESCryptKey = load_field_from_object(aescrypt_object, "lastKey", "[B", /*is_exact*/ false);
5682   assert (objAESCryptKey != NULL, "wrong version of com.sun.crypto.provider.AESCrypt");
5683   if (objAESCryptKey == NULL) return (Node *) NULL;
5684 
5685   // now have the array, need to get the start address of the lastKey array
5686   Node* original_k_start = array_element_address(objAESCryptKey, intcon(0), T_BYTE);
5687   return original_k_start;
5688 }
5689 
5690 //----------------------------inline_cipherBlockChaining_AESCrypt_predicate----------------------------
5691 // Return node representing slow path of predicate check.
5692 // the pseudo code we want to emulate with this predicate is:
5693 // for encryption:
5694 //    if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
5695 // for decryption:
5696 //    if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
5697 //    note cipher==plain is more conservative than the original java code but that's OK
5698 //
5699 Node* LibraryCallKit::inline_cipherBlockChaining_AESCrypt_predicate(bool decrypting) {
5700   // The receiver was checked for NULL already.
5701   Node* objCBC = argument(0);
5702 
5703   // Load embeddedCipher field of CipherBlockChaining object.
5704   Node* embeddedCipherObj = load_field_from_object(objCBC, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;", /*is_exact*/ false);
5705 
5706   // get AESCrypt klass for instanceOf check
5707   // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
5708   // will have same classloader as CipherBlockChaining object
5709   const TypeInstPtr* tinst = _gvn.type(objCBC)->isa_instptr();
5710   assert(tinst != NULL, "CBCobj is null");
5711   assert(tinst->klass()->is_loaded(), "CBCobj is not loaded");
5712 
5713   // we want to do an instanceof comparison against the AESCrypt class
5714   ciKlass* klass_AESCrypt = tinst->klass()->as_instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AESCrypt"));
5715   if (!klass_AESCrypt->is_loaded()) {
5716     // if AESCrypt is not even loaded, we never take the intrinsic fast path
5717     Node* ctrl = control();
5718     set_control(top()); // no regular fast path
5719     return ctrl;
5720   }
5721   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
5722 
5723   Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
5724   Node* cmp_instof  = _gvn.transform(new CmpINode(instof, intcon(1)));
5725   Node* bool_instof  = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
5726 
5727   Node* instof_false = generate_guard(bool_instof, NULL, PROB_MIN);
5728 
5729   // for encryption, we are done
5730   if (!decrypting)
5731     return instof_false;  // even if it is NULL
5732 
5733   // for decryption, we need to add a further check to avoid
5734   // taking the intrinsic path when cipher and plain are the same
5735   // see the original java code for why.
5736   RegionNode* region = new RegionNode(3);
5737   region->init_req(1, instof_false);
5738   Node* src = argument(1);
5739   Node* dest = argument(4);
5740   Node* cmp_src_dest = _gvn.transform(new CmpPNode(src, dest));
5741   Node* bool_src_dest = _gvn.transform(new BoolNode(cmp_src_dest, BoolTest::eq));
5742   Node* src_dest_conjoint = generate_guard(bool_src_dest, NULL, PROB_MIN);
5743   region->init_req(2, src_dest_conjoint);
5744 
5745   record_for_igvn(region);
5746   return _gvn.transform(region);
5747 }
5748 
5749 //------------------------------inline_sha_implCompress-----------------------
5750 //
5751 // Calculate SHA (i.e., SHA-1) for single-block byte[] array.
5752 // void com.sun.security.provider.SHA.implCompress(byte[] buf, int ofs)
5753 //
5754 // Calculate SHA2 (i.e., SHA-244 or SHA-256) for single-block byte[] array.
5755 // void com.sun.security.provider.SHA2.implCompress(byte[] buf, int ofs)
5756 //
5757 // Calculate SHA5 (i.e., SHA-384 or SHA-512) for single-block byte[] array.
5758 // void com.sun.security.provider.SHA5.implCompress(byte[] buf, int ofs)
5759 //
5760 bool LibraryCallKit::inline_sha_implCompress(vmIntrinsics::ID id) {
5761   assert(callee()->signature()->size() == 2, "sha_implCompress has 2 parameters");
5762 
5763   Node* sha_obj = argument(0);
5764   Node* src     = argument(1); // type oop
5765   Node* ofs     = argument(2); // type int
5766 
5767   const Type* src_type = src->Value(&_gvn);
5768   const TypeAryPtr* top_src = src_type->isa_aryptr();
5769   if (top_src  == NULL || top_src->klass()  == NULL) {
5770     // failed array check
5771     return false;
5772   }
5773   // Figure out the size and type of the elements we will be copying.
5774   BasicType src_elem = src_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5775   if (src_elem != T_BYTE) {
5776     return false;
5777   }
5778   // 'src_start' points to src array + offset
5779   Node* src_start = array_element_address(src, ofs, src_elem);
5780   Node* state = NULL;
5781   address stubAddr;
5782   const char *stubName;
5783 
5784   switch(id) {
5785   case vmIntrinsics::_sha_implCompress:
5786     assert(UseSHA1Intrinsics, "need SHA1 instruction support");
5787     state = get_state_from_sha_object(sha_obj);
5788     stubAddr = StubRoutines::sha1_implCompress();
5789     stubName = "sha1_implCompress";
5790     break;
5791   case vmIntrinsics::_sha2_implCompress:
5792     assert(UseSHA256Intrinsics, "need SHA256 instruction support");
5793     state = get_state_from_sha_object(sha_obj);
5794     stubAddr = StubRoutines::sha256_implCompress();
5795     stubName = "sha256_implCompress";
5796     break;
5797   case vmIntrinsics::_sha5_implCompress:
5798     assert(UseSHA512Intrinsics, "need SHA512 instruction support");
5799     state = get_state_from_sha5_object(sha_obj);
5800     stubAddr = StubRoutines::sha512_implCompress();
5801     stubName = "sha512_implCompress";
5802     break;
5803   default:
5804     fatal_unexpected_iid(id);
5805     return false;
5806   }
5807   if (state == NULL) return false;
5808 
5809   // Call the stub.
5810   Node* call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::sha_implCompress_Type(),
5811                                  stubAddr, stubName, TypePtr::BOTTOM,
5812                                  src_start, state);
5813 
5814   return true;
5815 }
5816 
5817 //------------------------------inline_digestBase_implCompressMB-----------------------
5818 //
5819 // Calculate SHA/SHA2/SHA5 for multi-block byte[] array.
5820 // int com.sun.security.provider.DigestBase.implCompressMultiBlock(byte[] b, int ofs, int limit)
5821 //
5822 bool LibraryCallKit::inline_digestBase_implCompressMB(int predicate) {
5823   assert(UseSHA1Intrinsics || UseSHA256Intrinsics || UseSHA512Intrinsics,
5824          "need SHA1/SHA256/SHA512 instruction support");
5825   assert((uint)predicate < 3, "sanity");
5826   assert(callee()->signature()->size() == 3, "digestBase_implCompressMB has 3 parameters");
5827 
5828   Node* digestBase_obj = argument(0); // The receiver was checked for NULL already.
5829   Node* src            = argument(1); // byte[] array
5830   Node* ofs            = argument(2); // type int
5831   Node* limit          = argument(3); // type int
5832 
5833   const Type* src_type = src->Value(&_gvn);
5834   const TypeAryPtr* top_src = src_type->isa_aryptr();
5835   if (top_src  == NULL || top_src->klass()  == NULL) {
5836     // failed array check
5837     return false;
5838   }
5839   // Figure out the size and type of the elements we will be copying.
5840   BasicType src_elem = src_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5841   if (src_elem != T_BYTE) {
5842     return false;
5843   }
5844   // 'src_start' points to src array + offset
5845   Node* src_start = array_element_address(src, ofs, src_elem);
5846 
5847   const char* klass_SHA_name = NULL;
5848   const char* stub_name = NULL;
5849   address     stub_addr = NULL;
5850   bool        long_state = false;
5851 
5852   switch (predicate) {
5853   case 0:
5854     if (UseSHA1Intrinsics) {
5855       klass_SHA_name = "sun/security/provider/SHA";
5856       stub_name = "sha1_implCompressMB";
5857       stub_addr = StubRoutines::sha1_implCompressMB();
5858     }
5859     break;
5860   case 1:
5861     if (UseSHA256Intrinsics) {
5862       klass_SHA_name = "sun/security/provider/SHA2";
5863       stub_name = "sha256_implCompressMB";
5864       stub_addr = StubRoutines::sha256_implCompressMB();
5865     }
5866     break;
5867   case 2:
5868     if (UseSHA512Intrinsics) {
5869       klass_SHA_name = "sun/security/provider/SHA5";
5870       stub_name = "sha512_implCompressMB";
5871       stub_addr = StubRoutines::sha512_implCompressMB();
5872       long_state = true;
5873     }
5874     break;
5875   default:
5876     fatal(err_msg_res("unknown SHA intrinsic predicate: %d", predicate));
5877   }
5878   if (klass_SHA_name != NULL) {
5879     // get DigestBase klass to lookup for SHA klass
5880     const TypeInstPtr* tinst = _gvn.type(digestBase_obj)->isa_instptr();
5881     assert(tinst != NULL, "digestBase_obj is not instance???");
5882     assert(tinst->klass()->is_loaded(), "DigestBase is not loaded");
5883 
5884     ciKlass* klass_SHA = tinst->klass()->as_instance_klass()->find_klass(ciSymbol::make(klass_SHA_name));
5885     assert(klass_SHA->is_loaded(), "predicate checks that this class is loaded");
5886     ciInstanceKlass* instklass_SHA = klass_SHA->as_instance_klass();
5887     return inline_sha_implCompressMB(digestBase_obj, instklass_SHA, long_state, stub_addr, stub_name, src_start, ofs, limit);
5888   }
5889   return false;
5890 }
5891 //------------------------------inline_sha_implCompressMB-----------------------
5892 bool LibraryCallKit::inline_sha_implCompressMB(Node* digestBase_obj, ciInstanceKlass* instklass_SHA,
5893                                                bool long_state, address stubAddr, const char *stubName,
5894                                                Node* src_start, Node* ofs, Node* limit) {
5895   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_SHA);
5896   const TypeOopPtr* xtype = aklass->as_instance_type();
5897   Node* sha_obj = new CheckCastPPNode(control(), digestBase_obj, xtype);
5898   sha_obj = _gvn.transform(sha_obj);
5899 
5900   Node* state;
5901   if (long_state) {
5902     state = get_state_from_sha5_object(sha_obj);
5903   } else {
5904     state = get_state_from_sha_object(sha_obj);
5905   }
5906   if (state == NULL) return false;
5907 
5908   // Call the stub.
5909   Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
5910                                  OptoRuntime::digestBase_implCompressMB_Type(),
5911                                  stubAddr, stubName, TypePtr::BOTTOM,
5912                                  src_start, state, ofs, limit);
5913   // return ofs (int)
5914   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
5915   set_result(result);
5916 
5917   return true;
5918 }
5919 
5920 //------------------------------get_state_from_sha_object-----------------------
5921 Node * LibraryCallKit::get_state_from_sha_object(Node *sha_object) {
5922   Node* sha_state = load_field_from_object(sha_object, "state", "[I", /*is_exact*/ false);
5923   assert (sha_state != NULL, "wrong version of sun.security.provider.SHA/SHA2");
5924   if (sha_state == NULL) return (Node *) NULL;
5925 
5926   // now have the array, need to get the start address of the state array
5927   Node* state = array_element_address(sha_state, intcon(0), T_INT);
5928   return state;
5929 }
5930 
5931 //------------------------------get_state_from_sha5_object-----------------------
5932 Node * LibraryCallKit::get_state_from_sha5_object(Node *sha_object) {
5933   Node* sha_state = load_field_from_object(sha_object, "state", "[J", /*is_exact*/ false);
5934   assert (sha_state != NULL, "wrong version of sun.security.provider.SHA5");
5935   if (sha_state == NULL) return (Node *) NULL;
5936 
5937   // now have the array, need to get the start address of the state array
5938   Node* state = array_element_address(sha_state, intcon(0), T_LONG);
5939   return state;
5940 }
5941 
5942 //----------------------------inline_digestBase_implCompressMB_predicate----------------------------
5943 // Return node representing slow path of predicate check.
5944 // the pseudo code we want to emulate with this predicate is:
5945 //    if (digestBaseObj instanceof SHA/SHA2/SHA5) do_intrinsic, else do_javapath
5946 //
5947 Node* LibraryCallKit::inline_digestBase_implCompressMB_predicate(int predicate) {
5948   assert(UseSHA1Intrinsics || UseSHA256Intrinsics || UseSHA512Intrinsics,
5949          "need SHA1/SHA256/SHA512 instruction support");
5950   assert((uint)predicate < 3, "sanity");
5951 
5952   // The receiver was checked for NULL already.
5953   Node* digestBaseObj = argument(0);
5954 
5955   // get DigestBase klass for instanceOf check
5956   const TypeInstPtr* tinst = _gvn.type(digestBaseObj)->isa_instptr();
5957   assert(tinst != NULL, "digestBaseObj is null");
5958   assert(tinst->klass()->is_loaded(), "DigestBase is not loaded");
5959 
5960   const char* klass_SHA_name = NULL;
5961   switch (predicate) {
5962   case 0:
5963     if (UseSHA1Intrinsics) {
5964       // we want to do an instanceof comparison against the SHA class
5965       klass_SHA_name = "sun/security/provider/SHA";
5966     }
5967     break;
5968   case 1:
5969     if (UseSHA256Intrinsics) {
5970       // we want to do an instanceof comparison against the SHA2 class
5971       klass_SHA_name = "sun/security/provider/SHA2";
5972     }
5973     break;
5974   case 2:
5975     if (UseSHA512Intrinsics) {
5976       // we want to do an instanceof comparison against the SHA5 class
5977       klass_SHA_name = "sun/security/provider/SHA5";
5978     }
5979     break;
5980   default:
5981     fatal(err_msg_res("unknown SHA intrinsic predicate: %d", predicate));
5982   }
5983 
5984   ciKlass* klass_SHA = NULL;
5985   if (klass_SHA_name != NULL) {
5986     klass_SHA = tinst->klass()->as_instance_klass()->find_klass(ciSymbol::make(klass_SHA_name));
5987   }
5988   if ((klass_SHA == NULL) || !klass_SHA->is_loaded()) {
5989     // if none of SHA/SHA2/SHA5 is loaded, we never take the intrinsic fast path
5990     Node* ctrl = control();
5991     set_control(top()); // no intrinsic path
5992     return ctrl;
5993   }
5994   ciInstanceKlass* instklass_SHA = klass_SHA->as_instance_klass();
5995 
5996   Node* instofSHA = gen_instanceof(digestBaseObj, makecon(TypeKlassPtr::make(instklass_SHA)));
5997   Node* cmp_instof = _gvn.transform(new CmpINode(instofSHA, intcon(1)));
5998   Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
5999   Node* instof_false = generate_guard(bool_instof, NULL, PROB_MIN);
6000 
6001   return instof_false;  // even if it is NULL
6002 }
6003 
6004 bool LibraryCallKit::inline_profileBoolean() {
6005   Node* counts = argument(1);
6006   const TypeAryPtr* ary = NULL;
6007   ciArray* aobj = NULL;
6008   if (counts->is_Con()
6009       && (ary = counts->bottom_type()->isa_aryptr()) != NULL
6010       && (aobj = ary->const_oop()->as_array()) != NULL
6011       && (aobj->length() == 2)) {
6012     // Profile is int[2] where [0] and [1] correspond to false and true value occurrences respectively.
6013     jint false_cnt = aobj->element_value(0).as_int();
6014     jint  true_cnt = aobj->element_value(1).as_int();
6015 
6016     method()->set_injected_profile(true);
6017 
6018     if (C->log() != NULL) {
6019       C->log()->elem("observe source='profileBoolean' false='%d' true='%d'",
6020                      false_cnt, true_cnt);
6021     }
6022 
6023     if (false_cnt + true_cnt == 0) {
6024       // According to profile, never executed.
6025       uncommon_trap_exact(Deoptimization::Reason_intrinsic,
6026                           Deoptimization::Action_reinterpret);
6027       return true;
6028     }
6029 
6030     // result is a boolean (0 or 1) and its profile (false_cnt & true_cnt)
6031     // is a number of each value occurrences.
6032     Node* result = argument(0);
6033     if (false_cnt == 0 || true_cnt == 0) {
6034       // According to profile, one value has been never seen.
6035       int expected_val = (false_cnt == 0) ? 1 : 0;
6036 
6037       Node* cmp  = _gvn.transform(new CmpINode(result, intcon(expected_val)));
6038       Node* test = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
6039 
6040       IfNode* check = create_and_map_if(control(), test, PROB_ALWAYS, COUNT_UNKNOWN);
6041       Node* fast_path = _gvn.transform(new IfTrueNode(check));
6042       Node* slow_path = _gvn.transform(new IfFalseNode(check));
6043 
6044       { // Slow path: uncommon trap for never seen value and then reexecute
6045         // MethodHandleImpl::profileBoolean() to bump the count, so JIT knows
6046         // the value has been seen at least once.
6047         PreserveJVMState pjvms(this);
6048         PreserveReexecuteState preexecs(this);
6049         jvms()->set_should_reexecute(true);
6050 
6051         set_control(slow_path);
6052         set_i_o(i_o());
6053 
6054         uncommon_trap_exact(Deoptimization::Reason_intrinsic,
6055                             Deoptimization::Action_reinterpret);
6056       }
6057       // The guard for never seen value enables sharpening of the result and
6058       // returning a constant. It allows to eliminate branches on the same value
6059       // later on.
6060       set_control(fast_path);
6061       result = intcon(expected_val);
6062     }
6063     // Stop profiling.
6064     // MethodHandleImpl::profileBoolean() has profiling logic in its bytecode.
6065     // By replacing method body with profile data (represented as ProfileBooleanNode
6066     // on IR level) we effectively disable profiling.
6067     // It enables full speed execution once optimized code is generated.
6068     Node* profile = _gvn.transform(new ProfileBooleanNode(result, false_cnt, true_cnt));
6069     C->record_for_igvn(profile);
6070     set_result(profile);
6071     return true;
6072   } else {
6073     // Continue profiling.
6074     // Profile data isn't available at the moment. So, execute method's bytecode version.
6075     // Usually, when GWT LambdaForms are profiled it means that a stand-alone nmethod
6076     // is compiled and counters aren't available since corresponding MethodHandle
6077     // isn't a compile-time constant.
6078     return false;
6079   }
6080 }
6081 
6082 bool LibraryCallKit::inline_isCompileConstant() {
6083   Node* n = argument(0);
6084   set_result(n->is_Con() ? intcon(1) : intcon(0));
6085   return true;
6086 }
--- EOF ---