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