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