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