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