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