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