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