Path: blob/aarch64-shenandoah-jdk8u272-b10/hotspot/src/share/vm/opto/library_call.cpp
32285 views
/*1* Copyright (c) 1999, 2019, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*22*/2324#include "precompiled.hpp"25#include "classfile/systemDictionary.hpp"26#include "classfile/vmSymbols.hpp"27#include "compiler/compileBroker.hpp"28#include "compiler/compileLog.hpp"29#include "jfr/support/jfrIntrinsics.hpp"30#include "oops/objArrayKlass.hpp"31#include "opto/addnode.hpp"32#include "opto/callGenerator.hpp"33#include "opto/cfgnode.hpp"34#include "opto/connode.hpp"35#include "opto/idealKit.hpp"36#include "opto/mathexactnode.hpp"37#include "opto/mulnode.hpp"38#include "opto/parse.hpp"39#include "opto/runtime.hpp"40#include "opto/subnode.hpp"41#include "prims/nativeLookup.hpp"42#include "runtime/sharedRuntime.hpp"43#include "utilities/macros.hpp"44#if INCLUDE_ALL_GCS45#include "gc_implementation/shenandoah/shenandoahRuntime.hpp"46#include "gc_implementation/shenandoah/c2/shenandoahBarrierSetC2.hpp"47#include "gc_implementation/shenandoah/c2/shenandoahSupport.hpp"48#endif4950class LibraryIntrinsic : public InlineCallGenerator {51// Extend the set of intrinsics known to the runtime:52public:53private:54bool _is_virtual;55bool _does_virtual_dispatch;56int8_t _predicates_count; // Intrinsic is predicated by several conditions57int8_t _last_predicate; // Last generated predicate58vmIntrinsics::ID _intrinsic_id;5960public:61LibraryIntrinsic(ciMethod* m, bool is_virtual, int predicates_count, bool does_virtual_dispatch, vmIntrinsics::ID id)62: InlineCallGenerator(m),63_is_virtual(is_virtual),64_does_virtual_dispatch(does_virtual_dispatch),65_predicates_count((int8_t)predicates_count),66_last_predicate((int8_t)-1),67_intrinsic_id(id)68{69}70virtual bool is_intrinsic() const { return true; }71virtual bool is_virtual() const { return _is_virtual; }72virtual bool is_predicated() const { return _predicates_count > 0; }73virtual int predicates_count() const { return _predicates_count; }74virtual bool does_virtual_dispatch() const { return _does_virtual_dispatch; }75virtual JVMState* generate(JVMState* jvms);76virtual Node* generate_predicate(JVMState* jvms, int predicate);77vmIntrinsics::ID intrinsic_id() const { return _intrinsic_id; }78};798081// Local helper class for LibraryIntrinsic:82class LibraryCallKit : public GraphKit {83private:84LibraryIntrinsic* _intrinsic; // the library intrinsic being called85Node* _result; // the result node, if any86int _reexecute_sp; // the stack pointer when bytecode needs to be reexecuted8788const TypeOopPtr* sharpen_unsafe_type(Compile::AliasType* alias_type, const TypePtr *adr_type, bool is_native_ptr = false);8990public:91LibraryCallKit(JVMState* jvms, LibraryIntrinsic* intrinsic)92: GraphKit(jvms),93_intrinsic(intrinsic),94_result(NULL)95{96// Check if this is a root compile. In that case we don't have a caller.97if (!jvms->has_method()) {98_reexecute_sp = sp();99} else {100// Find out how many arguments the interpreter needs when deoptimizing101// and save the stack pointer value so it can used by uncommon_trap.102// We find the argument count by looking at the declared signature.103bool ignored_will_link;104ciSignature* declared_signature = NULL;105ciMethod* ignored_callee = caller()->get_method_at_bci(bci(), ignored_will_link, &declared_signature);106const int nargs = declared_signature->arg_size_for_bc(caller()->java_code_at_bci(bci()));107_reexecute_sp = sp() + nargs; // "push" arguments back on stack108}109}110111virtual LibraryCallKit* is_LibraryCallKit() const { return (LibraryCallKit*)this; }112113ciMethod* caller() const { return jvms()->method(); }114int bci() const { return jvms()->bci(); }115LibraryIntrinsic* intrinsic() const { return _intrinsic; }116vmIntrinsics::ID intrinsic_id() const { return _intrinsic->intrinsic_id(); }117ciMethod* callee() const { return _intrinsic->method(); }118119bool try_to_inline(int predicate);120Node* try_to_predicate(int predicate);121122void push_result() {123// Push the result onto the stack.124if (!stopped() && result() != NULL) {125BasicType bt = result()->bottom_type()->basic_type();126push_node(bt, result());127}128}129130private:131void fatal_unexpected_iid(vmIntrinsics::ID iid) {132fatal(err_msg_res("unexpected intrinsic %d: %s", iid, vmIntrinsics::name_at(iid)));133}134135void set_result(Node* n) { assert(_result == NULL, "only set once"); _result = n; }136void set_result(RegionNode* region, PhiNode* value);137Node* result() { return _result; }138139virtual int reexecute_sp() { return _reexecute_sp; }140141// Helper functions to inline natives142Node* generate_guard(Node* test, RegionNode* region, float true_prob);143Node* generate_slow_guard(Node* test, RegionNode* region);144Node* generate_fair_guard(Node* test, RegionNode* region);145Node* generate_negative_guard(Node* index, RegionNode* region,146// resulting CastII of index:147Node* *pos_index = NULL);148Node* generate_nonpositive_guard(Node* index, bool never_negative,149// resulting CastII of index:150Node* *pos_index = NULL);151Node* generate_limit_guard(Node* offset, Node* subseq_length,152Node* array_length,153RegionNode* region);154Node* generate_current_thread(Node* &tls_output);155address basictype2arraycopy(BasicType t, Node *src_offset, Node *dest_offset,156bool disjoint_bases, const char* &name, bool dest_uninitialized);157Node* load_mirror_from_klass(Node* klass);158Node* load_klass_from_mirror_common(Node* mirror, bool never_see_null,159RegionNode* region, int null_path,160int offset);161Node* load_klass_from_mirror(Node* mirror, bool never_see_null,162RegionNode* region, int null_path) {163int offset = java_lang_Class::klass_offset_in_bytes();164return load_klass_from_mirror_common(mirror, never_see_null,165region, null_path,166offset);167}168Node* load_array_klass_from_mirror(Node* mirror, bool never_see_null,169RegionNode* region, int null_path) {170int offset = java_lang_Class::array_klass_offset_in_bytes();171return load_klass_from_mirror_common(mirror, never_see_null,172region, null_path,173offset);174}175Node* generate_access_flags_guard(Node* kls,176int modifier_mask, int modifier_bits,177RegionNode* region);178Node* generate_interface_guard(Node* kls, RegionNode* region);179Node* generate_array_guard(Node* kls, RegionNode* region) {180return generate_array_guard_common(kls, region, false, false);181}182Node* generate_non_array_guard(Node* kls, RegionNode* region) {183return generate_array_guard_common(kls, region, false, true);184}185Node* generate_objArray_guard(Node* kls, RegionNode* region) {186return generate_array_guard_common(kls, region, true, false);187}188Node* generate_non_objArray_guard(Node* kls, RegionNode* region) {189return generate_array_guard_common(kls, region, true, true);190}191Node* generate_array_guard_common(Node* kls, RegionNode* region,192bool obj_array, bool not_array);193Node* generate_virtual_guard(Node* obj_klass, RegionNode* slow_region);194CallJavaNode* generate_method_call(vmIntrinsics::ID method_id,195bool is_virtual = false, bool is_static = false);196CallJavaNode* generate_method_call_static(vmIntrinsics::ID method_id) {197return generate_method_call(method_id, false, true);198}199CallJavaNode* generate_method_call_virtual(vmIntrinsics::ID method_id) {200return generate_method_call(method_id, true, false);201}202Node * load_field_from_object(Node * fromObj, const char * fieldName, const char * fieldTypeString, bool is_exact, bool is_static);203204Node* make_string_method_node(int opcode, Node* str1_start, Node* cnt1, Node* str2_start, Node* cnt2);205Node* make_string_method_node(int opcode, Node* str1, Node* str2);206bool inline_string_compareTo();207bool inline_string_indexOf();208Node* string_indexOf(Node* string_object, ciTypeArray* target_array, jint offset, jint cache_i, jint md2_i);209bool inline_string_equals();210Node* round_double_node(Node* n);211bool runtime_math(const TypeFunc* call_type, address funcAddr, const char* funcName);212bool inline_math_native(vmIntrinsics::ID id);213bool inline_trig(vmIntrinsics::ID id);214bool inline_math(vmIntrinsics::ID id);215template <typename OverflowOp>216bool inline_math_overflow(Node* arg1, Node* arg2);217void inline_math_mathExact(Node* math, Node* test);218bool inline_math_addExactI(bool is_increment);219bool inline_math_addExactL(bool is_increment);220bool inline_math_multiplyExactI();221bool inline_math_multiplyExactL();222bool inline_math_negateExactI();223bool inline_math_negateExactL();224bool inline_math_subtractExactI(bool is_decrement);225bool inline_math_subtractExactL(bool is_decrement);226bool inline_exp();227bool inline_pow();228Node* finish_pow_exp(Node* result, Node* x, Node* y, const TypeFunc* call_type, address funcAddr, const char* funcName);229bool inline_min_max(vmIntrinsics::ID id);230Node* generate_min_max(vmIntrinsics::ID id, Node* x, Node* y);231// This returns Type::AnyPtr, RawPtr, or OopPtr.232int classify_unsafe_addr(Node* &base, Node* &offset);233Node* make_unsafe_address(Node* base, Node* offset);234// Helper for inline_unsafe_access.235// Generates the guards that check whether the result of236// Unsafe.getObject should be recorded in an SATB log buffer.237void insert_pre_barrier(Node* base_oop, Node* offset, Node* pre_val, bool need_mem_bar);238bool inline_unsafe_access(bool is_native_ptr, bool is_store, BasicType type, bool is_volatile, bool is_unaligned);239bool inline_unsafe_prefetch(bool is_native_ptr, bool is_store, bool is_static);240static bool klass_needs_init_guard(Node* kls);241bool inline_unsafe_allocate();242bool inline_unsafe_copyMemory();243bool inline_native_currentThread();244#ifdef JFR_HAVE_INTRINSICS245bool inline_native_classID();246bool inline_native_getEventWriter();247#endif248bool inline_native_time_funcs(address method, const char* funcName);249bool inline_native_isInterrupted();250bool inline_native_Class_query(vmIntrinsics::ID id);251bool inline_native_subtype_check();252253bool inline_native_newArray();254bool inline_native_getLength();255bool inline_array_copyOf(bool is_copyOfRange);256bool inline_array_equals();257void copy_to_clone(Node* obj, Node* alloc_obj, Node* obj_size, bool is_array, bool card_mark);258bool inline_native_clone(bool is_virtual);259bool inline_native_Reflection_getCallerClass();260// Helper function for inlining native object hash method261bool inline_native_hashcode(bool is_virtual, bool is_static);262bool inline_native_getClass();263264// Helper functions for inlining arraycopy265bool inline_arraycopy();266void generate_arraycopy(const TypePtr* adr_type,267BasicType basic_elem_type,268Node* src, Node* src_offset,269Node* dest, Node* dest_offset,270Node* copy_length,271bool disjoint_bases = false,272bool length_never_negative = false,273RegionNode* slow_region = NULL);274AllocateArrayNode* tightly_coupled_allocation(Node* ptr,275RegionNode* slow_region);276void generate_clear_array(const TypePtr* adr_type,277Node* dest,278BasicType basic_elem_type,279Node* slice_off,280Node* slice_len,281Node* slice_end);282bool generate_block_arraycopy(const TypePtr* adr_type,283BasicType basic_elem_type,284AllocateNode* alloc,285Node* src, Node* src_offset,286Node* dest, Node* dest_offset,287Node* dest_size, bool dest_uninitialized);288void generate_slow_arraycopy(const TypePtr* adr_type,289Node* src, Node* src_offset,290Node* dest, Node* dest_offset,291Node* copy_length, bool dest_uninitialized);292Node* generate_checkcast_arraycopy(const TypePtr* adr_type,293Node* dest_elem_klass,294Node* src, Node* src_offset,295Node* dest, Node* dest_offset,296Node* copy_length, bool dest_uninitialized);297Node* generate_generic_arraycopy(const TypePtr* adr_type,298Node* src, Node* src_offset,299Node* dest, Node* dest_offset,300Node* copy_length, bool dest_uninitialized);301void generate_unchecked_arraycopy(const TypePtr* adr_type,302BasicType basic_elem_type,303bool disjoint_bases,304Node* src, Node* src_offset,305Node* dest, Node* dest_offset,306Node* copy_length, bool dest_uninitialized);307typedef enum { LS_xadd, LS_xchg, LS_cmpxchg } LoadStoreKind;308bool inline_unsafe_load_store(BasicType type, LoadStoreKind kind);309bool inline_unsafe_ordered_store(BasicType type);310bool inline_unsafe_fence(vmIntrinsics::ID id);311bool inline_fp_conversions(vmIntrinsics::ID id);312bool inline_number_methods(vmIntrinsics::ID id);313bool inline_reference_get();314bool inline_aescrypt_Block(vmIntrinsics::ID id);315bool inline_cipherBlockChaining_AESCrypt(vmIntrinsics::ID id);316Node* inline_cipherBlockChaining_AESCrypt_predicate(bool decrypting);317Node* get_key_start_from_aescrypt_object(Node* aescrypt_object);318Node* get_original_key_start_from_aescrypt_object(Node* aescrypt_object);319bool inline_ghash_processBlocks();320bool inline_sha_implCompress(vmIntrinsics::ID id);321bool inline_digestBase_implCompressMB(int predicate);322bool inline_sha_implCompressMB(Node* digestBaseObj, ciInstanceKlass* instklass_SHA,323bool long_state, address stubAddr, const char *stubName,324Node* src_start, Node* ofs, Node* limit);325Node* get_state_from_sha_object(Node *sha_object);326Node* get_state_from_sha5_object(Node *sha_object);327Node* inline_digestBase_implCompressMB_predicate(int predicate);328bool inline_encodeISOArray();329bool inline_updateCRC32();330bool inline_updateBytesCRC32();331bool inline_updateByteBufferCRC32();332bool inline_multiplyToLen();333bool inline_squareToLen();334bool inline_mulAdd();335bool inline_montgomeryMultiply();336bool inline_montgomerySquare();337338bool inline_profileBoolean();339};340341342//---------------------------make_vm_intrinsic----------------------------343CallGenerator* Compile::make_vm_intrinsic(ciMethod* m, bool is_virtual) {344vmIntrinsics::ID id = m->intrinsic_id();345assert(id != vmIntrinsics::_none, "must be a VM intrinsic");346347ccstr disable_intr = NULL;348349if ((DisableIntrinsic[0] != '\0'350&& strstr(DisableIntrinsic, vmIntrinsics::name_at(id)) != NULL) ||351(method_has_option_value("DisableIntrinsic", disable_intr)352&& strstr(disable_intr, vmIntrinsics::name_at(id)) != NULL)) {353// disabled by a user request on the command line:354// example: -XX:DisableIntrinsic=_hashCode,_getClass355return NULL;356}357358if (!m->is_loaded()) {359// do not attempt to inline unloaded methods360return NULL;361}362363// Only a few intrinsics implement a virtual dispatch.364// They are expensive calls which are also frequently overridden.365if (is_virtual) {366switch (id) {367case vmIntrinsics::_hashCode:368case vmIntrinsics::_clone:369// OK, Object.hashCode and Object.clone intrinsics come in both flavors370break;371default:372return NULL;373}374}375376// -XX:-InlineNatives disables nearly all intrinsics:377if (!InlineNatives) {378switch (id) {379case vmIntrinsics::_indexOf:380case vmIntrinsics::_compareTo:381case vmIntrinsics::_equals:382case vmIntrinsics::_equalsC:383case vmIntrinsics::_getAndAddInt:384case vmIntrinsics::_getAndAddLong:385case vmIntrinsics::_getAndSetInt:386case vmIntrinsics::_getAndSetLong:387case vmIntrinsics::_getAndSetObject:388case vmIntrinsics::_loadFence:389case vmIntrinsics::_storeFence:390case vmIntrinsics::_fullFence:391break; // InlineNatives does not control String.compareTo392case vmIntrinsics::_Reference_get:393break; // InlineNatives does not control Reference.get394default:395return NULL;396}397}398399int predicates = 0;400bool does_virtual_dispatch = false;401402switch (id) {403case vmIntrinsics::_compareTo:404if (!SpecialStringCompareTo) return NULL;405if (!Matcher::match_rule_supported(Op_StrComp)) return NULL;406break;407case vmIntrinsics::_indexOf:408if (!SpecialStringIndexOf) return NULL;409break;410case vmIntrinsics::_equals:411if (!SpecialStringEquals) return NULL;412if (!Matcher::match_rule_supported(Op_StrEquals)) return NULL;413break;414case vmIntrinsics::_equalsC:415if (!SpecialArraysEquals) return NULL;416if (!Matcher::match_rule_supported(Op_AryEq)) return NULL;417break;418case vmIntrinsics::_arraycopy:419if (!InlineArrayCopy) return NULL;420break;421case vmIntrinsics::_copyMemory:422if (StubRoutines::unsafe_arraycopy() == NULL) return NULL;423if (!InlineArrayCopy) return NULL;424break;425case vmIntrinsics::_hashCode:426if (!InlineObjectHash) return NULL;427does_virtual_dispatch = true;428break;429case vmIntrinsics::_clone:430does_virtual_dispatch = true;431case vmIntrinsics::_copyOf:432case vmIntrinsics::_copyOfRange:433if (!InlineObjectCopy) return NULL;434// These also use the arraycopy intrinsic mechanism:435if (!InlineArrayCopy) return NULL;436break;437case vmIntrinsics::_encodeISOArray:438if (!SpecialEncodeISOArray) return NULL;439if (!Matcher::match_rule_supported(Op_EncodeISOArray)) return NULL;440break;441case vmIntrinsics::_checkIndex:442// We do not intrinsify this. The optimizer does fine with it.443return NULL;444445case vmIntrinsics::_getCallerClass:446if (!UseNewReflection) return NULL;447if (!InlineReflectionGetCallerClass) return NULL;448if (SystemDictionary::reflect_CallerSensitive_klass() == NULL) return NULL;449break;450451case vmIntrinsics::_bitCount_i:452if (!Matcher::match_rule_supported(Op_PopCountI)) return NULL;453break;454455case vmIntrinsics::_bitCount_l:456if (!Matcher::match_rule_supported(Op_PopCountL)) return NULL;457break;458459case vmIntrinsics::_numberOfLeadingZeros_i:460if (!Matcher::match_rule_supported(Op_CountLeadingZerosI)) return NULL;461break;462463case vmIntrinsics::_numberOfLeadingZeros_l:464if (!Matcher::match_rule_supported(Op_CountLeadingZerosL)) return NULL;465break;466467case vmIntrinsics::_numberOfTrailingZeros_i:468if (!Matcher::match_rule_supported(Op_CountTrailingZerosI)) return NULL;469break;470471case vmIntrinsics::_numberOfTrailingZeros_l:472if (!Matcher::match_rule_supported(Op_CountTrailingZerosL)) return NULL;473break;474475case vmIntrinsics::_reverseBytes_c:476if (!Matcher::match_rule_supported(Op_ReverseBytesUS)) return NULL;477break;478case vmIntrinsics::_reverseBytes_s:479if (!Matcher::match_rule_supported(Op_ReverseBytesS)) return NULL;480break;481case vmIntrinsics::_reverseBytes_i:482if (!Matcher::match_rule_supported(Op_ReverseBytesI)) return NULL;483break;484case vmIntrinsics::_reverseBytes_l:485if (!Matcher::match_rule_supported(Op_ReverseBytesL)) return NULL;486break;487488case vmIntrinsics::_Reference_get:489// Use the intrinsic version of Reference.get() so that the value in490// the referent field can be registered by the G1 pre-barrier code.491// Also add memory barrier to prevent commoning reads from this field492// across safepoint since GC can change it value.493break;494495case vmIntrinsics::_compareAndSwapObject:496#ifdef _LP64497if (!UseCompressedOops && !Matcher::match_rule_supported(Op_CompareAndSwapP)) return NULL;498#endif499break;500501case vmIntrinsics::_compareAndSwapLong:502if (!Matcher::match_rule_supported(Op_CompareAndSwapL)) return NULL;503break;504505case vmIntrinsics::_getAndAddInt:506if (!Matcher::match_rule_supported(Op_GetAndAddI)) return NULL;507break;508509case vmIntrinsics::_getAndAddLong:510if (!Matcher::match_rule_supported(Op_GetAndAddL)) return NULL;511break;512513case vmIntrinsics::_getAndSetInt:514if (!Matcher::match_rule_supported(Op_GetAndSetI)) return NULL;515break;516517case vmIntrinsics::_getAndSetLong:518if (!Matcher::match_rule_supported(Op_GetAndSetL)) return NULL;519break;520521case vmIntrinsics::_getAndSetObject:522#ifdef _LP64523if (!UseCompressedOops && !Matcher::match_rule_supported(Op_GetAndSetP)) return NULL;524if (UseCompressedOops && !Matcher::match_rule_supported(Op_GetAndSetN)) return NULL;525break;526#else527if (!Matcher::match_rule_supported(Op_GetAndSetP)) return NULL;528break;529#endif530531case vmIntrinsics::_aescrypt_encryptBlock:532case vmIntrinsics::_aescrypt_decryptBlock:533if (!UseAESIntrinsics) return NULL;534break;535536case vmIntrinsics::_multiplyToLen:537if (!UseMultiplyToLenIntrinsic) return NULL;538break;539540case vmIntrinsics::_squareToLen:541if (!UseSquareToLenIntrinsic) return NULL;542break;543544case vmIntrinsics::_mulAdd:545if (!UseMulAddIntrinsic) return NULL;546break;547548case vmIntrinsics::_montgomeryMultiply:549if (!UseMontgomeryMultiplyIntrinsic) return NULL;550break;551case vmIntrinsics::_montgomerySquare:552if (!UseMontgomerySquareIntrinsic) return NULL;553break;554555case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:556case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:557if (!UseAESIntrinsics) return NULL;558// these two require the predicated logic559predicates = 1;560break;561562case vmIntrinsics::_sha_implCompress:563if (!UseSHA1Intrinsics) return NULL;564break;565566case vmIntrinsics::_sha2_implCompress:567if (!UseSHA256Intrinsics) return NULL;568break;569570case vmIntrinsics::_sha5_implCompress:571if (!UseSHA512Intrinsics) return NULL;572break;573574case vmIntrinsics::_digestBase_implCompressMB:575if (!(UseSHA1Intrinsics || UseSHA256Intrinsics || UseSHA512Intrinsics)) return NULL;576predicates = 3;577break;578579case vmIntrinsics::_ghash_processBlocks:580if (!UseGHASHIntrinsics) return NULL;581break;582583case vmIntrinsics::_updateCRC32:584case vmIntrinsics::_updateBytesCRC32:585case vmIntrinsics::_updateByteBufferCRC32:586if (!UseCRC32Intrinsics) return NULL;587break;588589case vmIntrinsics::_incrementExactI:590case vmIntrinsics::_addExactI:591if (!Matcher::match_rule_supported(Op_OverflowAddI) || !UseMathExactIntrinsics) return NULL;592break;593case vmIntrinsics::_incrementExactL:594case vmIntrinsics::_addExactL:595if (!Matcher::match_rule_supported(Op_OverflowAddL) || !UseMathExactIntrinsics) return NULL;596break;597case vmIntrinsics::_decrementExactI:598case vmIntrinsics::_subtractExactI:599if (!Matcher::match_rule_supported(Op_OverflowSubI) || !UseMathExactIntrinsics) return NULL;600break;601case vmIntrinsics::_decrementExactL:602case vmIntrinsics::_subtractExactL:603if (!Matcher::match_rule_supported(Op_OverflowSubL) || !UseMathExactIntrinsics) return NULL;604break;605case vmIntrinsics::_negateExactI:606if (!Matcher::match_rule_supported(Op_OverflowSubI) || !UseMathExactIntrinsics) return NULL;607break;608case vmIntrinsics::_negateExactL:609if (!Matcher::match_rule_supported(Op_OverflowSubL) || !UseMathExactIntrinsics) return NULL;610break;611case vmIntrinsics::_multiplyExactI:612if (!Matcher::match_rule_supported(Op_OverflowMulI) || !UseMathExactIntrinsics) return NULL;613break;614case vmIntrinsics::_multiplyExactL:615if (!Matcher::match_rule_supported(Op_OverflowMulL) || !UseMathExactIntrinsics) return NULL;616break;617618default:619assert(id <= vmIntrinsics::LAST_COMPILER_INLINE, "caller responsibility");620assert(id != vmIntrinsics::_Object_init && id != vmIntrinsics::_invoke, "enum out of order?");621break;622}623624// -XX:-InlineClassNatives disables natives from the Class class.625// The flag applies to all reflective calls, notably Array.newArray626// (visible to Java programmers as Array.newInstance).627if (m->holder()->name() == ciSymbol::java_lang_Class() ||628m->holder()->name() == ciSymbol::java_lang_reflect_Array()) {629if (!InlineClassNatives) return NULL;630}631632// -XX:-InlineThreadNatives disables natives from the Thread class.633if (m->holder()->name() == ciSymbol::java_lang_Thread()) {634if (!InlineThreadNatives) return NULL;635}636637// -XX:-InlineMathNatives disables natives from the Math,Float and Double classes.638if (m->holder()->name() == ciSymbol::java_lang_Math() ||639m->holder()->name() == ciSymbol::java_lang_Float() ||640m->holder()->name() == ciSymbol::java_lang_Double()) {641if (!InlineMathNatives) return NULL;642}643644// -XX:-InlineUnsafeOps disables natives from the Unsafe class.645if (m->holder()->name() == ciSymbol::sun_misc_Unsafe()) {646if (!InlineUnsafeOps) return NULL;647}648649return new LibraryIntrinsic(m, is_virtual, predicates, does_virtual_dispatch, (vmIntrinsics::ID) id);650}651652//----------------------register_library_intrinsics-----------------------653// Initialize this file's data structures, for each Compile instance.654void Compile::register_library_intrinsics() {655// Nothing to do here.656}657658JVMState* LibraryIntrinsic::generate(JVMState* jvms) {659LibraryCallKit kit(jvms, this);660Compile* C = kit.C;661int nodes = C->unique();662#ifndef PRODUCT663if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {664char buf[1000];665const char* str = vmIntrinsics::short_name_as_C_string(intrinsic_id(), buf, sizeof(buf));666tty->print_cr("Intrinsic %s", str);667}668#endif669ciMethod* callee = kit.callee();670const int bci = kit.bci();671672// Try to inline the intrinsic.673if (kit.try_to_inline(_last_predicate)) {674if (C->print_intrinsics() || C->print_inlining()) {675C->print_inlining(callee, jvms->depth() - 1, bci, is_virtual() ? "(intrinsic, virtual)" : "(intrinsic)");676}677C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_worked);678if (C->log()) {679C->log()->elem("intrinsic id='%s'%s nodes='%d'",680vmIntrinsics::name_at(intrinsic_id()),681(is_virtual() ? " virtual='1'" : ""),682C->unique() - nodes);683}684// Push the result from the inlined method onto the stack.685kit.push_result();686return kit.transfer_exceptions_into_jvms();687}688689// The intrinsic bailed out690if (C->print_intrinsics() || C->print_inlining()) {691if (jvms->has_method()) {692// Not a root compile.693const char* msg = is_virtual() ? "failed to inline (intrinsic, virtual)" : "failed to inline (intrinsic)";694C->print_inlining(callee, jvms->depth() - 1, bci, msg);695} else {696// Root compile697tty->print("Did not generate intrinsic %s%s at bci:%d in",698vmIntrinsics::name_at(intrinsic_id()),699(is_virtual() ? " (virtual)" : ""), bci);700}701}702C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_failed);703return NULL;704}705706Node* LibraryIntrinsic::generate_predicate(JVMState* jvms, int predicate) {707LibraryCallKit kit(jvms, this);708Compile* C = kit.C;709int nodes = C->unique();710_last_predicate = predicate;711#ifndef PRODUCT712assert(is_predicated() && predicate < predicates_count(), "sanity");713if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {714char buf[1000];715const char* str = vmIntrinsics::short_name_as_C_string(intrinsic_id(), buf, sizeof(buf));716tty->print_cr("Predicate for intrinsic %s", str);717}718#endif719ciMethod* callee = kit.callee();720const int bci = kit.bci();721722Node* slow_ctl = kit.try_to_predicate(predicate);723if (!kit.failing()) {724if (C->print_intrinsics() || C->print_inlining()) {725C->print_inlining(callee, jvms->depth() - 1, bci, is_virtual() ? "(intrinsic, virtual, predicate)" : "(intrinsic, predicate)");726}727C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_worked);728if (C->log()) {729C->log()->elem("predicate_intrinsic id='%s'%s nodes='%d'",730vmIntrinsics::name_at(intrinsic_id()),731(is_virtual() ? " virtual='1'" : ""),732C->unique() - nodes);733}734return slow_ctl; // Could be NULL if the check folds.735}736737// The intrinsic bailed out738if (C->print_intrinsics() || C->print_inlining()) {739if (jvms->has_method()) {740// Not a root compile.741const char* msg = "failed to generate predicate for intrinsic";742C->print_inlining(kit.callee(), jvms->depth() - 1, bci, msg);743} else {744// Root compile745C->print_inlining_stream()->print("Did not generate predicate for intrinsic %s%s at bci:%d in",746vmIntrinsics::name_at(intrinsic_id()),747(is_virtual() ? " (virtual)" : ""), bci);748}749}750C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_failed);751return NULL;752}753754bool LibraryCallKit::try_to_inline(int predicate) {755// Handle symbolic names for otherwise undistinguished boolean switches:756const bool is_store = true;757const bool is_native_ptr = true;758const bool is_static = true;759const bool is_volatile = true;760761if (!jvms()->has_method()) {762// Root JVMState has a null method.763assert(map()->memory()->Opcode() == Op_Parm, "");764// Insert the memory aliasing node765set_all_memory(reset_memory());766}767assert(merged_memory(), "");768769770switch (intrinsic_id()) {771case vmIntrinsics::_hashCode: return inline_native_hashcode(intrinsic()->is_virtual(), !is_static);772case vmIntrinsics::_identityHashCode: return inline_native_hashcode(/*!virtual*/ false, is_static);773case vmIntrinsics::_getClass: return inline_native_getClass();774775case vmIntrinsics::_dsin:776case vmIntrinsics::_dcos:777case vmIntrinsics::_dtan:778case vmIntrinsics::_dabs:779case vmIntrinsics::_datan2:780case vmIntrinsics::_dsqrt:781case vmIntrinsics::_dexp:782case vmIntrinsics::_dlog:783case vmIntrinsics::_dlog10:784case vmIntrinsics::_dpow: return inline_math_native(intrinsic_id());785786case vmIntrinsics::_min:787case vmIntrinsics::_max: return inline_min_max(intrinsic_id());788789case vmIntrinsics::_addExactI: return inline_math_addExactI(false /* add */);790case vmIntrinsics::_addExactL: return inline_math_addExactL(false /* add */);791case vmIntrinsics::_decrementExactI: return inline_math_subtractExactI(true /* decrement */);792case vmIntrinsics::_decrementExactL: return inline_math_subtractExactL(true /* decrement */);793case vmIntrinsics::_incrementExactI: return inline_math_addExactI(true /* increment */);794case vmIntrinsics::_incrementExactL: return inline_math_addExactL(true /* increment */);795case vmIntrinsics::_multiplyExactI: return inline_math_multiplyExactI();796case vmIntrinsics::_multiplyExactL: return inline_math_multiplyExactL();797case vmIntrinsics::_negateExactI: return inline_math_negateExactI();798case vmIntrinsics::_negateExactL: return inline_math_negateExactL();799case vmIntrinsics::_subtractExactI: return inline_math_subtractExactI(false /* subtract */);800case vmIntrinsics::_subtractExactL: return inline_math_subtractExactL(false /* subtract */);801802case vmIntrinsics::_arraycopy: return inline_arraycopy();803804case vmIntrinsics::_compareTo: return inline_string_compareTo();805case vmIntrinsics::_indexOf: return inline_string_indexOf();806case vmIntrinsics::_equals: return inline_string_equals();807808case vmIntrinsics::_getObject: return inline_unsafe_access(!is_native_ptr, !is_store, T_OBJECT, !is_volatile, false);809case vmIntrinsics::_getBoolean: return inline_unsafe_access(!is_native_ptr, !is_store, T_BOOLEAN, !is_volatile, false);810case vmIntrinsics::_getByte: return inline_unsafe_access(!is_native_ptr, !is_store, T_BYTE, !is_volatile, false);811case vmIntrinsics::_getShort: return inline_unsafe_access(!is_native_ptr, !is_store, T_SHORT, !is_volatile, false);812case vmIntrinsics::_getChar: return inline_unsafe_access(!is_native_ptr, !is_store, T_CHAR, !is_volatile, false);813case vmIntrinsics::_getInt: return inline_unsafe_access(!is_native_ptr, !is_store, T_INT, !is_volatile, false);814case vmIntrinsics::_getLong: return inline_unsafe_access(!is_native_ptr, !is_store, T_LONG, !is_volatile, false);815case vmIntrinsics::_getFloat: return inline_unsafe_access(!is_native_ptr, !is_store, T_FLOAT, !is_volatile, false);816case vmIntrinsics::_getDouble: return inline_unsafe_access(!is_native_ptr, !is_store, T_DOUBLE, !is_volatile, false);817818case vmIntrinsics::_putObject: return inline_unsafe_access(!is_native_ptr, is_store, T_OBJECT, !is_volatile, false);819case vmIntrinsics::_putBoolean: return inline_unsafe_access(!is_native_ptr, is_store, T_BOOLEAN, !is_volatile, false);820case vmIntrinsics::_putByte: return inline_unsafe_access(!is_native_ptr, is_store, T_BYTE, !is_volatile, false);821case vmIntrinsics::_putShort: return inline_unsafe_access(!is_native_ptr, is_store, T_SHORT, !is_volatile, false);822case vmIntrinsics::_putChar: return inline_unsafe_access(!is_native_ptr, is_store, T_CHAR, !is_volatile, false);823case vmIntrinsics::_putInt: return inline_unsafe_access(!is_native_ptr, is_store, T_INT, !is_volatile, false);824case vmIntrinsics::_putLong: return inline_unsafe_access(!is_native_ptr, is_store, T_LONG, !is_volatile, false);825case vmIntrinsics::_putFloat: return inline_unsafe_access(!is_native_ptr, is_store, T_FLOAT, !is_volatile, false);826case vmIntrinsics::_putDouble: return inline_unsafe_access(!is_native_ptr, is_store, T_DOUBLE, !is_volatile, false);827828case vmIntrinsics::_getByte_raw: return inline_unsafe_access( is_native_ptr, !is_store, T_BYTE, !is_volatile, false);829case vmIntrinsics::_getShort_raw: return inline_unsafe_access( is_native_ptr, !is_store, T_SHORT, !is_volatile, false);830case vmIntrinsics::_getChar_raw: return inline_unsafe_access( is_native_ptr, !is_store, T_CHAR, !is_volatile, false);831case vmIntrinsics::_getInt_raw: return inline_unsafe_access( is_native_ptr, !is_store, T_INT, !is_volatile, false);832case vmIntrinsics::_getLong_raw: return inline_unsafe_access( is_native_ptr, !is_store, T_LONG, !is_volatile, false);833case vmIntrinsics::_getFloat_raw: return inline_unsafe_access( is_native_ptr, !is_store, T_FLOAT, !is_volatile, false);834case vmIntrinsics::_getDouble_raw: return inline_unsafe_access( is_native_ptr, !is_store, T_DOUBLE, !is_volatile, false);835case vmIntrinsics::_getAddress_raw: return inline_unsafe_access( is_native_ptr, !is_store, T_ADDRESS, !is_volatile, false);836837case vmIntrinsics::_putByte_raw: return inline_unsafe_access( is_native_ptr, is_store, T_BYTE, !is_volatile, false);838case vmIntrinsics::_putShort_raw: return inline_unsafe_access( is_native_ptr, is_store, T_SHORT, !is_volatile, false);839case vmIntrinsics::_putChar_raw: return inline_unsafe_access( is_native_ptr, is_store, T_CHAR, !is_volatile, false);840case vmIntrinsics::_putInt_raw: return inline_unsafe_access( is_native_ptr, is_store, T_INT, !is_volatile, false);841case vmIntrinsics::_putLong_raw: return inline_unsafe_access( is_native_ptr, is_store, T_LONG, !is_volatile, false);842case vmIntrinsics::_putFloat_raw: return inline_unsafe_access( is_native_ptr, is_store, T_FLOAT, !is_volatile, false);843case vmIntrinsics::_putDouble_raw: return inline_unsafe_access( is_native_ptr, is_store, T_DOUBLE, !is_volatile, false);844case vmIntrinsics::_putAddress_raw: return inline_unsafe_access( is_native_ptr, is_store, T_ADDRESS, !is_volatile, false);845846case vmIntrinsics::_getObjectVolatile: return inline_unsafe_access(!is_native_ptr, !is_store, T_OBJECT, is_volatile, false);847case vmIntrinsics::_getBooleanVolatile: return inline_unsafe_access(!is_native_ptr, !is_store, T_BOOLEAN, is_volatile, false);848case vmIntrinsics::_getByteVolatile: return inline_unsafe_access(!is_native_ptr, !is_store, T_BYTE, is_volatile, false);849case vmIntrinsics::_getShortVolatile: return inline_unsafe_access(!is_native_ptr, !is_store, T_SHORT, is_volatile, false);850case vmIntrinsics::_getCharVolatile: return inline_unsafe_access(!is_native_ptr, !is_store, T_CHAR, is_volatile, false);851case vmIntrinsics::_getIntVolatile: return inline_unsafe_access(!is_native_ptr, !is_store, T_INT, is_volatile, false);852case vmIntrinsics::_getLongVolatile: return inline_unsafe_access(!is_native_ptr, !is_store, T_LONG, is_volatile, false);853case vmIntrinsics::_getFloatVolatile: return inline_unsafe_access(!is_native_ptr, !is_store, T_FLOAT, is_volatile, false);854case vmIntrinsics::_getDoubleVolatile: return inline_unsafe_access(!is_native_ptr, !is_store, T_DOUBLE, is_volatile, false);855856case vmIntrinsics::_putObjectVolatile: return inline_unsafe_access(!is_native_ptr, is_store, T_OBJECT, is_volatile, false);857case vmIntrinsics::_putBooleanVolatile: return inline_unsafe_access(!is_native_ptr, is_store, T_BOOLEAN, is_volatile, false);858case vmIntrinsics::_putByteVolatile: return inline_unsafe_access(!is_native_ptr, is_store, T_BYTE, is_volatile, false);859case vmIntrinsics::_putShortVolatile: return inline_unsafe_access(!is_native_ptr, is_store, T_SHORT, is_volatile, false);860case vmIntrinsics::_putCharVolatile: return inline_unsafe_access(!is_native_ptr, is_store, T_CHAR, is_volatile, false);861case vmIntrinsics::_putIntVolatile: return inline_unsafe_access(!is_native_ptr, is_store, T_INT, is_volatile, false);862case vmIntrinsics::_putLongVolatile: return inline_unsafe_access(!is_native_ptr, is_store, T_LONG, is_volatile, false);863case vmIntrinsics::_putFloatVolatile: return inline_unsafe_access(!is_native_ptr, is_store, T_FLOAT, is_volatile, false);864case vmIntrinsics::_putDoubleVolatile: return inline_unsafe_access(!is_native_ptr, is_store, T_DOUBLE, is_volatile, false);865866case vmIntrinsics::_prefetchRead: return inline_unsafe_prefetch(!is_native_ptr, !is_store, !is_static);867case vmIntrinsics::_prefetchWrite: return inline_unsafe_prefetch(!is_native_ptr, is_store, !is_static);868case vmIntrinsics::_prefetchReadStatic: return inline_unsafe_prefetch(!is_native_ptr, !is_store, is_static);869case vmIntrinsics::_prefetchWriteStatic: return inline_unsafe_prefetch(!is_native_ptr, is_store, is_static);870871case vmIntrinsics::_compareAndSwapObject: return inline_unsafe_load_store(T_OBJECT, LS_cmpxchg);872case vmIntrinsics::_compareAndSwapInt: return inline_unsafe_load_store(T_INT, LS_cmpxchg);873case vmIntrinsics::_compareAndSwapLong: return inline_unsafe_load_store(T_LONG, LS_cmpxchg);874875case vmIntrinsics::_putOrderedObject: return inline_unsafe_ordered_store(T_OBJECT);876case vmIntrinsics::_putOrderedInt: return inline_unsafe_ordered_store(T_INT);877case vmIntrinsics::_putOrderedLong: return inline_unsafe_ordered_store(T_LONG);878879case vmIntrinsics::_getAndAddInt: return inline_unsafe_load_store(T_INT, LS_xadd);880case vmIntrinsics::_getAndAddLong: return inline_unsafe_load_store(T_LONG, LS_xadd);881case vmIntrinsics::_getAndSetInt: return inline_unsafe_load_store(T_INT, LS_xchg);882case vmIntrinsics::_getAndSetLong: return inline_unsafe_load_store(T_LONG, LS_xchg);883case vmIntrinsics::_getAndSetObject: return inline_unsafe_load_store(T_OBJECT, LS_xchg);884885case vmIntrinsics::_loadFence:886case vmIntrinsics::_storeFence:887case vmIntrinsics::_fullFence: return inline_unsafe_fence(intrinsic_id());888889case vmIntrinsics::_currentThread: return inline_native_currentThread();890case vmIntrinsics::_isInterrupted: return inline_native_isInterrupted();891892#ifdef JFR_HAVE_INTRINSICS893case vmIntrinsics::_counterTime: return inline_native_time_funcs(CAST_FROM_FN_PTR(address, JFR_TIME_FUNCTION), "counterTime");894case vmIntrinsics::_getClassId: return inline_native_classID();895case vmIntrinsics::_getEventWriter: return inline_native_getEventWriter();896#endif897case vmIntrinsics::_currentTimeMillis: return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeMillis), "currentTimeMillis");898case vmIntrinsics::_nanoTime: return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeNanos), "nanoTime");899case vmIntrinsics::_allocateInstance: return inline_unsafe_allocate();900case vmIntrinsics::_copyMemory: return inline_unsafe_copyMemory();901case vmIntrinsics::_newArray: return inline_native_newArray();902case vmIntrinsics::_getLength: return inline_native_getLength();903case vmIntrinsics::_copyOf: return inline_array_copyOf(false);904case vmIntrinsics::_copyOfRange: return inline_array_copyOf(true);905case vmIntrinsics::_equalsC: return inline_array_equals();906case vmIntrinsics::_clone: return inline_native_clone(intrinsic()->is_virtual());907908case vmIntrinsics::_isAssignableFrom: return inline_native_subtype_check();909910case vmIntrinsics::_isInstance:911case vmIntrinsics::_getModifiers:912case vmIntrinsics::_isInterface:913case vmIntrinsics::_isArray:914case vmIntrinsics::_isPrimitive:915case vmIntrinsics::_getSuperclass:916case vmIntrinsics::_getComponentType:917case vmIntrinsics::_getClassAccessFlags: return inline_native_Class_query(intrinsic_id());918919case vmIntrinsics::_floatToRawIntBits:920case vmIntrinsics::_floatToIntBits:921case vmIntrinsics::_intBitsToFloat:922case vmIntrinsics::_doubleToRawLongBits:923case vmIntrinsics::_doubleToLongBits:924case vmIntrinsics::_longBitsToDouble: return inline_fp_conversions(intrinsic_id());925926case vmIntrinsics::_numberOfLeadingZeros_i:927case vmIntrinsics::_numberOfLeadingZeros_l:928case vmIntrinsics::_numberOfTrailingZeros_i:929case vmIntrinsics::_numberOfTrailingZeros_l:930case vmIntrinsics::_bitCount_i:931case vmIntrinsics::_bitCount_l:932case vmIntrinsics::_reverseBytes_i:933case vmIntrinsics::_reverseBytes_l:934case vmIntrinsics::_reverseBytes_s:935case vmIntrinsics::_reverseBytes_c: return inline_number_methods(intrinsic_id());936937case vmIntrinsics::_getCallerClass: return inline_native_Reflection_getCallerClass();938939case vmIntrinsics::_Reference_get: return inline_reference_get();940941case vmIntrinsics::_aescrypt_encryptBlock:942case vmIntrinsics::_aescrypt_decryptBlock: return inline_aescrypt_Block(intrinsic_id());943944case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:945case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:946return inline_cipherBlockChaining_AESCrypt(intrinsic_id());947948case vmIntrinsics::_sha_implCompress:949case vmIntrinsics::_sha2_implCompress:950case vmIntrinsics::_sha5_implCompress:951return inline_sha_implCompress(intrinsic_id());952953case vmIntrinsics::_digestBase_implCompressMB:954return inline_digestBase_implCompressMB(predicate);955956case vmIntrinsics::_multiplyToLen:957return inline_multiplyToLen();958959case vmIntrinsics::_squareToLen:960return inline_squareToLen();961962case vmIntrinsics::_mulAdd:963return inline_mulAdd();964965case vmIntrinsics::_montgomeryMultiply:966return inline_montgomeryMultiply();967case vmIntrinsics::_montgomerySquare:968return inline_montgomerySquare();969970case vmIntrinsics::_ghash_processBlocks:971return inline_ghash_processBlocks();972973case vmIntrinsics::_encodeISOArray:974return inline_encodeISOArray();975976case vmIntrinsics::_updateCRC32:977return inline_updateCRC32();978case vmIntrinsics::_updateBytesCRC32:979return inline_updateBytesCRC32();980case vmIntrinsics::_updateByteBufferCRC32:981return inline_updateByteBufferCRC32();982983case vmIntrinsics::_profileBoolean:984return inline_profileBoolean();985986default:987// If you get here, it may be that someone has added a new intrinsic988// to the list in vmSymbols.hpp without implementing it here.989#ifndef PRODUCT990if ((PrintMiscellaneous && (Verbose || WizardMode)) || PrintOpto) {991tty->print_cr("*** Warning: Unimplemented intrinsic %s(%d)",992vmIntrinsics::name_at(intrinsic_id()), intrinsic_id());993}994#endif995return false;996}997}998999Node* LibraryCallKit::try_to_predicate(int predicate) {1000if (!jvms()->has_method()) {1001// Root JVMState has a null method.1002assert(map()->memory()->Opcode() == Op_Parm, "");1003// Insert the memory aliasing node1004set_all_memory(reset_memory());1005}1006assert(merged_memory(), "");10071008switch (intrinsic_id()) {1009case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:1010return inline_cipherBlockChaining_AESCrypt_predicate(false);1011case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:1012return inline_cipherBlockChaining_AESCrypt_predicate(true);1013case vmIntrinsics::_digestBase_implCompressMB:1014return inline_digestBase_implCompressMB_predicate(predicate);10151016default:1017// If you get here, it may be that someone has added a new intrinsic1018// to the list in vmSymbols.hpp without implementing it here.1019#ifndef PRODUCT1020if ((PrintMiscellaneous && (Verbose || WizardMode)) || PrintOpto) {1021tty->print_cr("*** Warning: Unimplemented predicate for intrinsic %s(%d)",1022vmIntrinsics::name_at(intrinsic_id()), intrinsic_id());1023}1024#endif1025Node* slow_ctl = control();1026set_control(top()); // No fast path instrinsic1027return slow_ctl;1028}1029}10301031//------------------------------set_result-------------------------------1032// Helper function for finishing intrinsics.1033void LibraryCallKit::set_result(RegionNode* region, PhiNode* value) {1034record_for_igvn(region);1035set_control(_gvn.transform(region));1036set_result( _gvn.transform(value));1037assert(value->type()->basic_type() == result()->bottom_type()->basic_type(), "sanity");1038}10391040//------------------------------generate_guard---------------------------1041// Helper function for generating guarded fast-slow graph structures.1042// The given 'test', if true, guards a slow path. If the test fails1043// then a fast path can be taken. (We generally hope it fails.)1044// In all cases, GraphKit::control() is updated to the fast path.1045// The returned value represents the control for the slow path.1046// The return value is never 'top'; it is either a valid control1047// or NULL if it is obvious that the slow path can never be taken.1048// Also, if region and the slow control are not NULL, the slow edge1049// is appended to the region.1050Node* LibraryCallKit::generate_guard(Node* test, RegionNode* region, float true_prob) {1051if (stopped()) {1052// Already short circuited.1053return NULL;1054}10551056// Build an if node and its projections.1057// If test is true we take the slow path, which we assume is uncommon.1058if (_gvn.type(test) == TypeInt::ZERO) {1059// The slow branch is never taken. No need to build this guard.1060return NULL;1061}10621063IfNode* iff = create_and_map_if(control(), test, true_prob, COUNT_UNKNOWN);10641065Node* if_slow = _gvn.transform(new (C) IfTrueNode(iff));1066if (if_slow == top()) {1067// The slow branch is never taken. No need to build this guard.1068return NULL;1069}10701071if (region != NULL)1072region->add_req(if_slow);10731074Node* if_fast = _gvn.transform(new (C) IfFalseNode(iff));1075set_control(if_fast);10761077return if_slow;1078}10791080inline Node* LibraryCallKit::generate_slow_guard(Node* test, RegionNode* region) {1081return generate_guard(test, region, PROB_UNLIKELY_MAG(3));1082}1083inline Node* LibraryCallKit::generate_fair_guard(Node* test, RegionNode* region) {1084return generate_guard(test, region, PROB_FAIR);1085}10861087inline Node* LibraryCallKit::generate_negative_guard(Node* index, RegionNode* region,1088Node* *pos_index) {1089if (stopped())1090return NULL; // already stopped1091if (_gvn.type(index)->higher_equal(TypeInt::POS)) // [0,maxint]1092return NULL; // index is already adequately typed1093Node* cmp_lt = _gvn.transform(new (C) CmpINode(index, intcon(0)));1094Node* bol_lt = _gvn.transform(new (C) BoolNode(cmp_lt, BoolTest::lt));1095Node* is_neg = generate_guard(bol_lt, region, PROB_MIN);1096if (is_neg != NULL && pos_index != NULL) {1097// Emulate effect of Parse::adjust_map_after_if.1098Node* ccast = new (C) CastIINode(index, TypeInt::POS);1099ccast->set_req(0, control());1100(*pos_index) = _gvn.transform(ccast);1101}1102return is_neg;1103}11041105inline Node* LibraryCallKit::generate_nonpositive_guard(Node* index, bool never_negative,1106Node* *pos_index) {1107if (stopped())1108return NULL; // already stopped1109if (_gvn.type(index)->higher_equal(TypeInt::POS1)) // [1,maxint]1110return NULL; // index is already adequately typed1111Node* cmp_le = _gvn.transform(new (C) CmpINode(index, intcon(0)));1112BoolTest::mask le_or_eq = (never_negative ? BoolTest::eq : BoolTest::le);1113Node* bol_le = _gvn.transform(new (C) BoolNode(cmp_le, le_or_eq));1114Node* is_notp = generate_guard(bol_le, NULL, PROB_MIN);1115if (is_notp != NULL && pos_index != NULL) {1116// Emulate effect of Parse::adjust_map_after_if.1117Node* ccast = new (C) CastIINode(index, TypeInt::POS1);1118ccast->set_req(0, control());1119(*pos_index) = _gvn.transform(ccast);1120}1121return is_notp;1122}11231124// Make sure that 'position' is a valid limit index, in [0..length].1125// There are two equivalent plans for checking this:1126// A. (offset + copyLength) unsigned<= arrayLength1127// B. offset <= (arrayLength - copyLength)1128// We require that all of the values above, except for the sum and1129// difference, are already known to be non-negative.1130// Plan A is robust in the face of overflow, if offset and copyLength1131// are both hugely positive.1132//1133// Plan B is less direct and intuitive, but it does not overflow at1134// all, since the difference of two non-negatives is always1135// representable. Whenever Java methods must perform the equivalent1136// check they generally use Plan B instead of Plan A.1137// For the moment we use Plan A.1138inline Node* LibraryCallKit::generate_limit_guard(Node* offset,1139Node* subseq_length,1140Node* array_length,1141RegionNode* region) {1142if (stopped())1143return NULL; // already stopped1144bool zero_offset = _gvn.type(offset) == TypeInt::ZERO;1145if (zero_offset && subseq_length->eqv_uncast(array_length))1146return NULL; // common case of whole-array copy1147Node* last = subseq_length;1148if (!zero_offset) // last += offset1149last = _gvn.transform(new (C) AddINode(last, offset));1150Node* cmp_lt = _gvn.transform(new (C) CmpUNode(array_length, last));1151Node* bol_lt = _gvn.transform(new (C) BoolNode(cmp_lt, BoolTest::lt));1152Node* is_over = generate_guard(bol_lt, region, PROB_MIN);1153return is_over;1154}115511561157//--------------------------generate_current_thread--------------------1158Node* LibraryCallKit::generate_current_thread(Node* &tls_output) {1159ciKlass* thread_klass = env()->Thread_klass();1160const Type* thread_type = TypeOopPtr::make_from_klass(thread_klass)->cast_to_ptr_type(TypePtr::NotNull);1161Node* thread = _gvn.transform(new (C) ThreadLocalNode());1162Node* p = basic_plus_adr(top()/*!oop*/, thread, in_bytes(JavaThread::threadObj_offset()));1163Node* threadObj = make_load(NULL, p, thread_type, T_OBJECT, MemNode::unordered);1164tls_output = thread;1165return threadObj;1166}116711681169//------------------------------make_string_method_node------------------------1170// Helper method for String intrinsic functions. This version is called1171// with str1 and str2 pointing to String object nodes.1172//1173Node* LibraryCallKit::make_string_method_node(int opcode, Node* str1, Node* str2) {1174Node* no_ctrl = NULL;11751176// Get start addr of string1177Node* str1_value = load_String_value(no_ctrl, str1);1178Node* str1_offset = load_String_offset(no_ctrl, str1);1179Node* str1_start = array_element_address(str1_value, str1_offset, T_CHAR);11801181// Get length of string 11182Node* str1_len = load_String_length(no_ctrl, str1);11831184Node* str2_value = load_String_value(no_ctrl, str2);1185Node* str2_offset = load_String_offset(no_ctrl, str2);1186Node* str2_start = array_element_address(str2_value, str2_offset, T_CHAR);11871188Node* str2_len = NULL;1189Node* result = NULL;11901191switch (opcode) {1192case Op_StrIndexOf:1193// Get length of string 21194str2_len = load_String_length(no_ctrl, str2);11951196result = new (C) StrIndexOfNode(control(), memory(TypeAryPtr::CHARS),1197str1_start, str1_len, str2_start, str2_len);1198break;1199case Op_StrComp:1200// Get length of string 21201str2_len = load_String_length(no_ctrl, str2);12021203result = new (C) StrCompNode(control(), memory(TypeAryPtr::CHARS),1204str1_start, str1_len, str2_start, str2_len);1205break;1206case Op_StrEquals:1207result = new (C) StrEqualsNode(control(), memory(TypeAryPtr::CHARS),1208str1_start, str2_start, str1_len);1209break;1210default:1211ShouldNotReachHere();1212return NULL;1213}12141215// All these intrinsics have checks.1216C->set_has_split_ifs(true); // Has chance for split-if optimization12171218return _gvn.transform(result);1219}12201221// Helper method for String intrinsic functions. This version is called1222// with str1 and str2 pointing to char[] nodes, with cnt1 and cnt2 pointing1223// to Int nodes containing the lenghts of str1 and str2.1224//1225Node* LibraryCallKit::make_string_method_node(int opcode, Node* str1_start, Node* cnt1, Node* str2_start, Node* cnt2) {1226Node* result = NULL;1227switch (opcode) {1228case Op_StrIndexOf:1229result = new (C) StrIndexOfNode(control(), memory(TypeAryPtr::CHARS),1230str1_start, cnt1, str2_start, cnt2);1231break;1232case Op_StrComp:1233result = new (C) StrCompNode(control(), memory(TypeAryPtr::CHARS),1234str1_start, cnt1, str2_start, cnt2);1235break;1236case Op_StrEquals:1237result = new (C) StrEqualsNode(control(), memory(TypeAryPtr::CHARS),1238str1_start, str2_start, cnt1);1239break;1240default:1241ShouldNotReachHere();1242return NULL;1243}12441245// All these intrinsics have checks.1246C->set_has_split_ifs(true); // Has chance for split-if optimization12471248return _gvn.transform(result);1249}12501251//------------------------------inline_string_compareTo------------------------1252// public int java.lang.String.compareTo(String anotherString);1253bool LibraryCallKit::inline_string_compareTo() {1254Node* receiver = null_check(argument(0));1255Node* arg = null_check(argument(1));1256if (stopped()) {1257return true;1258}1259set_result(make_string_method_node(Op_StrComp, receiver, arg));1260return true;1261}12621263//------------------------------inline_string_equals------------------------1264bool LibraryCallKit::inline_string_equals() {1265Node* receiver = null_check_receiver();1266// NOTE: Do not null check argument for String.equals() because spec1267// allows to specify NULL as argument.1268Node* argument = this->argument(1);1269if (stopped()) {1270return true;1271}12721273// paths (plus control) merge1274RegionNode* region = new (C) RegionNode(5);1275Node* phi = new (C) PhiNode(region, TypeInt::BOOL);12761277// does source == target string?1278Node* cmp = _gvn.transform(new (C) CmpPNode(receiver, argument));1279Node* bol = _gvn.transform(new (C) BoolNode(cmp, BoolTest::eq));12801281Node* if_eq = generate_slow_guard(bol, NULL);1282if (if_eq != NULL) {1283// receiver == argument1284phi->init_req(2, intcon(1));1285region->init_req(2, if_eq);1286}12871288// get String klass for instanceOf1289ciInstanceKlass* klass = env()->String_klass();12901291if (!stopped()) {1292Node* inst = gen_instanceof(argument, makecon(TypeKlassPtr::make(klass)));1293Node* cmp = _gvn.transform(new (C) CmpINode(inst, intcon(1)));1294Node* bol = _gvn.transform(new (C) BoolNode(cmp, BoolTest::ne));12951296Node* inst_false = generate_guard(bol, NULL, PROB_MIN);1297//instanceOf == true, fallthrough12981299if (inst_false != NULL) {1300phi->init_req(3, intcon(0));1301region->init_req(3, inst_false);1302}1303}13041305if (!stopped()) {1306const TypeOopPtr* string_type = TypeOopPtr::make_from_klass(klass);13071308// Properly cast the argument to String1309argument = _gvn.transform(new (C) CheckCastPPNode(control(), argument, string_type));1310// This path is taken only when argument's type is String:NotNull.1311argument = cast_not_null(argument, false);13121313Node* no_ctrl = NULL;13141315// Get start addr of receiver1316Node* receiver_val = load_String_value(no_ctrl, receiver);1317Node* receiver_offset = load_String_offset(no_ctrl, receiver);1318Node* receiver_start = array_element_address(receiver_val, receiver_offset, T_CHAR);13191320// Get length of receiver1321Node* receiver_cnt = load_String_length(no_ctrl, receiver);13221323// Get start addr of argument1324Node* argument_val = load_String_value(no_ctrl, argument);1325Node* argument_offset = load_String_offset(no_ctrl, argument);1326Node* argument_start = array_element_address(argument_val, argument_offset, T_CHAR);13271328// Get length of argument1329Node* argument_cnt = load_String_length(no_ctrl, argument);13301331// Check for receiver count != argument count1332Node* cmp = _gvn.transform(new(C) CmpINode(receiver_cnt, argument_cnt));1333Node* bol = _gvn.transform(new(C) BoolNode(cmp, BoolTest::ne));1334Node* if_ne = generate_slow_guard(bol, NULL);1335if (if_ne != NULL) {1336phi->init_req(4, intcon(0));1337region->init_req(4, if_ne);1338}13391340// Check for count == 0 is done by assembler code for StrEquals.13411342if (!stopped()) {1343Node* equals = make_string_method_node(Op_StrEquals, receiver_start, receiver_cnt, argument_start, argument_cnt);1344phi->init_req(1, equals);1345region->init_req(1, control());1346}1347}13481349// post merge1350set_control(_gvn.transform(region));1351record_for_igvn(region);13521353set_result(_gvn.transform(phi));1354return true;1355}13561357//------------------------------inline_array_equals----------------------------1358bool LibraryCallKit::inline_array_equals() {1359Node* arg1 = argument(0);1360Node* arg2 = argument(1);1361set_result(_gvn.transform(new (C) AryEqNode(control(), memory(TypeAryPtr::CHARS), arg1, arg2)));1362return true;1363}13641365// Java version of String.indexOf(constant string)1366// class StringDecl {1367// StringDecl(char[] ca) {1368// offset = 0;1369// count = ca.length;1370// value = ca;1371// }1372// int offset;1373// int count;1374// char[] value;1375// }1376//1377// static int string_indexOf_J(StringDecl string_object, char[] target_object,1378// int targetOffset, int cache_i, int md2) {1379// int cache = cache_i;1380// int sourceOffset = string_object.offset;1381// int sourceCount = string_object.count;1382// int targetCount = target_object.length;1383//1384// int targetCountLess1 = targetCount - 1;1385// int sourceEnd = sourceOffset + sourceCount - targetCountLess1;1386//1387// char[] source = string_object.value;1388// char[] target = target_object;1389// int lastChar = target[targetCountLess1];1390//1391// outer_loop:1392// for (int i = sourceOffset; i < sourceEnd; ) {1393// int src = source[i + targetCountLess1];1394// if (src == lastChar) {1395// // With random strings and a 4-character alphabet,1396// // reverse matching at this point sets up 0.8% fewer1397// // frames, but (paradoxically) makes 0.3% more probes.1398// // Since those probes are nearer the lastChar probe,1399// // there is may be a net D$ win with reverse matching.1400// // But, reversing loop inhibits unroll of inner loop1401// // for unknown reason. So, does running outer loop from1402// // (sourceOffset - targetCountLess1) to (sourceOffset + sourceCount)1403// for (int j = 0; j < targetCountLess1; j++) {1404// if (target[targetOffset + j] != source[i+j]) {1405// if ((cache & (1 << source[i+j])) == 0) {1406// if (md2 < j+1) {1407// i += j+1;1408// continue outer_loop;1409// }1410// }1411// i += md2;1412// continue outer_loop;1413// }1414// }1415// return i - sourceOffset;1416// }1417// if ((cache & (1 << src)) == 0) {1418// i += targetCountLess1;1419// } // using "i += targetCount;" and an "else i++;" causes a jump to jump.1420// i++;1421// }1422// return -1;1423// }14241425//------------------------------string_indexOf------------------------1426Node* LibraryCallKit::string_indexOf(Node* string_object, ciTypeArray* target_array, jint targetOffset_i,1427jint cache_i, jint md2_i) {14281429Node* no_ctrl = NULL;1430float likely = PROB_LIKELY(0.9);1431float unlikely = PROB_UNLIKELY(0.9);14321433const int nargs = 0; // no arguments to push back for uncommon trap in predicate14341435Node* source = load_String_value(no_ctrl, string_object);1436Node* sourceOffset = load_String_offset(no_ctrl, string_object);1437Node* sourceCount = load_String_length(no_ctrl, string_object);14381439Node* target = _gvn.transform( makecon(TypeOopPtr::make_from_constant(target_array, true)));1440jint target_length = target_array->length();1441const TypeAry* target_array_type = TypeAry::make(TypeInt::CHAR, TypeInt::make(0, target_length, Type::WidenMin));1442const TypeAryPtr* target_type = TypeAryPtr::make(TypePtr::BotPTR, target_array_type, target_array->klass(), true, Type::OffsetBot);14431444// String.value field is known to be @Stable.1445if (UseImplicitStableValues) {1446target = cast_array_to_stable(target, target_type);1447}14481449IdealKit kit(this, false, true);1450#define __ kit.1451Node* zero = __ ConI(0);1452Node* one = __ ConI(1);1453Node* cache = __ ConI(cache_i);1454Node* md2 = __ ConI(md2_i);1455Node* lastChar = __ ConI(target_array->char_at(target_length - 1));1456Node* targetCount = __ ConI(target_length);1457Node* targetCountLess1 = __ ConI(target_length - 1);1458Node* targetOffset = __ ConI(targetOffset_i);1459Node* sourceEnd = __ SubI(__ AddI(sourceOffset, sourceCount), targetCountLess1);14601461IdealVariable rtn(kit), i(kit), j(kit); __ declarations_done();1462Node* outer_loop = __ make_label(2 /* goto */);1463Node* return_ = __ make_label(1);14641465__ set(rtn,__ ConI(-1));1466__ loop(this, nargs, i, sourceOffset, BoolTest::lt, sourceEnd); {1467Node* i2 = __ AddI(__ value(i), targetCountLess1);1468// pin to prohibit loading of "next iteration" value which may SEGV (rare)1469Node* src = load_array_element(__ ctrl(), source, i2, TypeAryPtr::CHARS);1470__ if_then(src, BoolTest::eq, lastChar, unlikely); {1471__ loop(this, nargs, j, zero, BoolTest::lt, targetCountLess1); {1472Node* tpj = __ AddI(targetOffset, __ value(j));1473Node* targ = load_array_element(no_ctrl, target, tpj, target_type);1474Node* ipj = __ AddI(__ value(i), __ value(j));1475Node* src2 = load_array_element(no_ctrl, source, ipj, TypeAryPtr::CHARS);1476__ if_then(targ, BoolTest::ne, src2); {1477__ if_then(__ AndI(cache, __ LShiftI(one, src2)), BoolTest::eq, zero); {1478__ if_then(md2, BoolTest::lt, __ AddI(__ value(j), one)); {1479__ increment(i, __ AddI(__ value(j), one));1480__ goto_(outer_loop);1481} __ end_if(); __ dead(j);1482}__ end_if(); __ dead(j);1483__ increment(i, md2);1484__ goto_(outer_loop);1485}__ end_if();1486__ increment(j, one);1487}__ end_loop(); __ dead(j);1488__ set(rtn, __ SubI(__ value(i), sourceOffset)); __ dead(i);1489__ goto_(return_);1490}__ end_if();1491__ if_then(__ AndI(cache, __ LShiftI(one, src)), BoolTest::eq, zero, likely); {1492__ increment(i, targetCountLess1);1493}__ end_if();1494__ increment(i, one);1495__ bind(outer_loop);1496}__ end_loop(); __ dead(i);1497__ bind(return_);14981499// Final sync IdealKit and GraphKit.1500final_sync(kit);1501Node* result = __ value(rtn);1502#undef __1503C->set_has_loops(true);1504return result;1505}15061507//------------------------------inline_string_indexOf------------------------1508bool LibraryCallKit::inline_string_indexOf() {1509Node* receiver = argument(0);1510Node* arg = argument(1);15111512Node* result;1513// Disable the use of pcmpestri until it can be guaranteed that1514// the load doesn't cross into the uncommited space.1515if (Matcher::has_match_rule(Op_StrIndexOf) &&1516UseSSE42Intrinsics) {1517// Generate SSE4.2 version of indexOf1518// We currently only have match rules that use SSE4.215191520receiver = null_check(receiver);1521arg = null_check(arg);1522if (stopped()) {1523return true;1524}15251526ciInstanceKlass* str_klass = env()->String_klass();1527const TypeOopPtr* string_type = TypeOopPtr::make_from_klass(str_klass);15281529// Make the merge point1530RegionNode* result_rgn = new (C) RegionNode(4);1531Node* result_phi = new (C) PhiNode(result_rgn, TypeInt::INT);1532Node* no_ctrl = NULL;15331534// Get start addr of source string1535Node* source = load_String_value(no_ctrl, receiver);1536Node* source_offset = load_String_offset(no_ctrl, receiver);1537Node* source_start = array_element_address(source, source_offset, T_CHAR);15381539// Get length of source string1540Node* source_cnt = load_String_length(no_ctrl, receiver);15411542// Get start addr of substring1543Node* substr = load_String_value(no_ctrl, arg);1544Node* substr_offset = load_String_offset(no_ctrl, arg);1545Node* substr_start = array_element_address(substr, substr_offset, T_CHAR);15461547// Get length of source string1548Node* substr_cnt = load_String_length(no_ctrl, arg);15491550// Check for substr count > string count1551Node* cmp = _gvn.transform(new(C) CmpINode(substr_cnt, source_cnt));1552Node* bol = _gvn.transform(new(C) BoolNode(cmp, BoolTest::gt));1553Node* if_gt = generate_slow_guard(bol, NULL);1554if (if_gt != NULL) {1555result_phi->init_req(2, intcon(-1));1556result_rgn->init_req(2, if_gt);1557}15581559if (!stopped()) {1560// Check for substr count == 01561cmp = _gvn.transform(new(C) CmpINode(substr_cnt, intcon(0)));1562bol = _gvn.transform(new(C) BoolNode(cmp, BoolTest::eq));1563Node* if_zero = generate_slow_guard(bol, NULL);1564if (if_zero != NULL) {1565result_phi->init_req(3, intcon(0));1566result_rgn->init_req(3, if_zero);1567}1568}15691570if (!stopped()) {1571result = make_string_method_node(Op_StrIndexOf, source_start, source_cnt, substr_start, substr_cnt);1572result_phi->init_req(1, result);1573result_rgn->init_req(1, control());1574}1575set_control(_gvn.transform(result_rgn));1576record_for_igvn(result_rgn);1577result = _gvn.transform(result_phi);15781579} else { // Use LibraryCallKit::string_indexOf1580// don't intrinsify if argument isn't a constant string.1581if (!arg->is_Con()) {1582return false;1583}1584const TypeOopPtr* str_type = _gvn.type(arg)->isa_oopptr();1585if (str_type == NULL) {1586return false;1587}1588ciInstanceKlass* klass = env()->String_klass();1589ciObject* str_const = str_type->const_oop();1590if (str_const == NULL || str_const->klass() != klass) {1591return false;1592}1593ciInstance* str = str_const->as_instance();1594assert(str != NULL, "must be instance");15951596ciObject* v = str->field_value_by_offset(java_lang_String::value_offset_in_bytes()).as_object();1597ciTypeArray* pat = v->as_type_array(); // pattern (argument) character array15981599int o;1600int c;1601if (java_lang_String::has_offset_field()) {1602o = str->field_value_by_offset(java_lang_String::offset_offset_in_bytes()).as_int();1603c = str->field_value_by_offset(java_lang_String::count_offset_in_bytes()).as_int();1604} else {1605o = 0;1606c = pat->length();1607}16081609// constant strings have no offset and count == length which1610// simplifies the resulting code somewhat so lets optimize for that.1611if (o != 0 || c != pat->length()) {1612return false;1613}16141615receiver = null_check(receiver, T_OBJECT);1616// NOTE: No null check on the argument is needed since it's a constant String oop.1617if (stopped()) {1618return true;1619}16201621// The null string as a pattern always returns 0 (match at beginning of string)1622if (c == 0) {1623set_result(intcon(0));1624return true;1625}16261627// Generate default indexOf1628jchar lastChar = pat->char_at(o + (c - 1));1629int cache = 0;1630int i;1631for (i = 0; i < c - 1; i++) {1632assert(i < pat->length(), "out of range");1633cache |= (1 << (pat->char_at(o + i) & (sizeof(cache) * BitsPerByte - 1)));1634}16351636int md2 = c;1637for (i = 0; i < c - 1; i++) {1638assert(i < pat->length(), "out of range");1639if (pat->char_at(o + i) == lastChar) {1640md2 = (c - 1) - i;1641}1642}16431644result = string_indexOf(receiver, pat, o, cache, md2);1645}1646set_result(result);1647return true;1648}16491650//--------------------------round_double_node--------------------------------1651// Round a double node if necessary.1652Node* LibraryCallKit::round_double_node(Node* n) {1653if (Matcher::strict_fp_requires_explicit_rounding && UseSSE <= 1)1654n = _gvn.transform(new (C) RoundDoubleNode(0, n));1655return n;1656}16571658//------------------------------inline_math-----------------------------------1659// public static double Math.abs(double)1660// public static double Math.sqrt(double)1661// public static double Math.log(double)1662// public static double Math.log10(double)1663bool LibraryCallKit::inline_math(vmIntrinsics::ID id) {1664Node* arg = round_double_node(argument(0));1665Node* n = NULL;1666switch (id) {1667case vmIntrinsics::_dabs: n = new (C) AbsDNode( arg); break;1668case vmIntrinsics::_dsqrt: n = new (C) SqrtDNode(C, control(), arg); break;1669case vmIntrinsics::_dlog: n = new (C) LogDNode(C, control(), arg); break;1670case vmIntrinsics::_dlog10: n = new (C) Log10DNode(C, control(), arg); break;1671default: fatal_unexpected_iid(id); break;1672}1673set_result(_gvn.transform(n));1674return true;1675}16761677//------------------------------inline_trig----------------------------------1678// Inline sin/cos/tan instructions, if possible. If rounding is required, do1679// argument reduction which will turn into a fast/slow diamond.1680bool LibraryCallKit::inline_trig(vmIntrinsics::ID id) {1681Node* arg = round_double_node(argument(0));1682Node* n = NULL;16831684switch (id) {1685case vmIntrinsics::_dsin: n = new (C) SinDNode(C, control(), arg); break;1686case vmIntrinsics::_dcos: n = new (C) CosDNode(C, control(), arg); break;1687case vmIntrinsics::_dtan: n = new (C) TanDNode(C, control(), arg); break;1688default: fatal_unexpected_iid(id); break;1689}1690n = _gvn.transform(n);16911692// Rounding required? Check for argument reduction!1693if (Matcher::strict_fp_requires_explicit_rounding) {1694static const double pi_4 = 0.7853981633974483;1695static const double neg_pi_4 = -0.7853981633974483;1696// pi/2 in 80-bit extended precision1697// static const unsigned char pi_2_bits_x[] = {0x35,0xc2,0x68,0x21,0xa2,0xda,0x0f,0xc9,0xff,0x3f,0x00,0x00,0x00,0x00,0x00,0x00};1698// -pi/2 in 80-bit extended precision1699// 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};1700// Cutoff value for using this argument reduction technique1701//static const double pi_2_minus_epsilon = 1.564660403643354;1702//static const double neg_pi_2_plus_epsilon = -1.564660403643354;17031704// Pseudocode for sin:1705// if (x <= Math.PI / 4.0) {1706// if (x >= -Math.PI / 4.0) return fsin(x);1707// if (x >= -Math.PI / 2.0) return -fcos(x + Math.PI / 2.0);1708// } else {1709// if (x <= Math.PI / 2.0) return fcos(x - Math.PI / 2.0);1710// }1711// return StrictMath.sin(x);17121713// Pseudocode for cos:1714// if (x <= Math.PI / 4.0) {1715// if (x >= -Math.PI / 4.0) return fcos(x);1716// if (x >= -Math.PI / 2.0) return fsin(x + Math.PI / 2.0);1717// } else {1718// if (x <= Math.PI / 2.0) return -fsin(x - Math.PI / 2.0);1719// }1720// return StrictMath.cos(x);17211722// Actually, sticking in an 80-bit Intel value into C2 will be tough; it1723// requires a special machine instruction to load it. Instead we'll try1724// the 'easy' case. If we really need the extra range +/- PI/2 we'll1725// probably do the math inside the SIN encoding.17261727// Make the merge point1728RegionNode* r = new (C) RegionNode(3);1729Node* phi = new (C) PhiNode(r, Type::DOUBLE);17301731// Flatten arg so we need only 1 test1732Node *abs = _gvn.transform(new (C) AbsDNode(arg));1733// Node for PI/4 constant1734Node *pi4 = makecon(TypeD::make(pi_4));1735// Check PI/4 : abs(arg)1736Node *cmp = _gvn.transform(new (C) CmpDNode(pi4,abs));1737// Check: If PI/4 < abs(arg) then go slow1738Node *bol = _gvn.transform(new (C) BoolNode( cmp, BoolTest::lt ));1739// Branch either way1740IfNode *iff = create_and_xform_if(control(),bol, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);1741set_control(opt_iff(r,iff));17421743// Set fast path result1744phi->init_req(2, n);17451746// Slow path - non-blocking leaf call1747Node* call = NULL;1748switch (id) {1749case vmIntrinsics::_dsin:1750call = make_runtime_call(RC_LEAF, OptoRuntime::Math_D_D_Type(),1751CAST_FROM_FN_PTR(address, SharedRuntime::dsin),1752"Sin", NULL, arg, top());1753break;1754case vmIntrinsics::_dcos:1755call = make_runtime_call(RC_LEAF, OptoRuntime::Math_D_D_Type(),1756CAST_FROM_FN_PTR(address, SharedRuntime::dcos),1757"Cos", NULL, arg, top());1758break;1759case vmIntrinsics::_dtan:1760call = make_runtime_call(RC_LEAF, OptoRuntime::Math_D_D_Type(),1761CAST_FROM_FN_PTR(address, SharedRuntime::dtan),1762"Tan", NULL, arg, top());1763break;1764}1765assert(control()->in(0) == call, "");1766Node* slow_result = _gvn.transform(new (C) ProjNode(call, TypeFunc::Parms));1767r->init_req(1, control());1768phi->init_req(1, slow_result);17691770// Post-merge1771set_control(_gvn.transform(r));1772record_for_igvn(r);1773n = _gvn.transform(phi);17741775C->set_has_split_ifs(true); // Has chance for split-if optimization1776}1777set_result(n);1778return true;1779}17801781Node* LibraryCallKit::finish_pow_exp(Node* result, Node* x, Node* y, const TypeFunc* call_type, address funcAddr, const char* funcName) {1782//-------------------1783//result=(result.isNaN())? funcAddr():result;1784// Check: If isNaN() by checking result!=result? then either trap1785// or go to runtime1786Node* cmpisnan = _gvn.transform(new (C) CmpDNode(result, result));1787// Build the boolean node1788Node* bolisnum = _gvn.transform(new (C) BoolNode(cmpisnan, BoolTest::eq));17891790if (!too_many_traps(Deoptimization::Reason_intrinsic)) {1791{ BuildCutout unless(this, bolisnum, PROB_STATIC_FREQUENT);1792// The pow or exp intrinsic returned a NaN, which requires a call1793// to the runtime. Recompile with the runtime call.1794uncommon_trap(Deoptimization::Reason_intrinsic,1795Deoptimization::Action_make_not_entrant);1796}1797return result;1798} else {1799// If this inlining ever returned NaN in the past, we compile a call1800// to the runtime to properly handle corner cases18011802IfNode* iff = create_and_xform_if(control(), bolisnum, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);1803Node* if_slow = _gvn.transform(new (C) IfFalseNode(iff));1804Node* if_fast = _gvn.transform(new (C) IfTrueNode(iff));18051806if (!if_slow->is_top()) {1807RegionNode* result_region = new (C) RegionNode(3);1808PhiNode* result_val = new (C) PhiNode(result_region, Type::DOUBLE);18091810result_region->init_req(1, if_fast);1811result_val->init_req(1, result);18121813set_control(if_slow);18141815const TypePtr* no_memory_effects = NULL;1816Node* rt = make_runtime_call(RC_LEAF, call_type, funcAddr, funcName,1817no_memory_effects,1818x, top(), y, y ? top() : NULL);1819Node* value = _gvn.transform(new (C) ProjNode(rt, TypeFunc::Parms+0));1820#ifdef ASSERT1821Node* value_top = _gvn.transform(new (C) ProjNode(rt, TypeFunc::Parms+1));1822assert(value_top == top(), "second value must be top");1823#endif18241825result_region->init_req(2, control());1826result_val->init_req(2, value);1827set_control(_gvn.transform(result_region));1828return _gvn.transform(result_val);1829} else {1830return result;1831}1832}1833}18341835//------------------------------inline_exp-------------------------------------1836// Inline exp instructions, if possible. The Intel hardware only misses1837// really odd corner cases (+/- Infinity). Just uncommon-trap them.1838bool LibraryCallKit::inline_exp() {1839Node* arg = round_double_node(argument(0));1840Node* n = _gvn.transform(new (C) ExpDNode(C, control(), arg));18411842n = finish_pow_exp(n, arg, NULL, OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dexp), "EXP");1843set_result(n);18441845C->set_has_split_ifs(true); // Has chance for split-if optimization1846return true;1847}18481849//------------------------------inline_pow-------------------------------------1850// Inline power instructions, if possible.1851bool LibraryCallKit::inline_pow() {1852// Pseudocode for pow1853// if (y == 2) {1854// return x * x;1855// } else {1856// if (x <= 0.0) {1857// long longy = (long)y;1858// if ((double)longy == y) { // if y is long1859// if (y + 1 == y) longy = 0; // huge number: even1860// result = ((1&longy) == 0)?-DPow(abs(x), y):DPow(abs(x), y);1861// } else {1862// result = NaN;1863// }1864// } else {1865// result = DPow(x,y);1866// }1867// if (result != result)? {1868// result = uncommon_trap() or runtime_call();1869// }1870// return result;1871// }18721873Node* x = round_double_node(argument(0));1874Node* y = round_double_node(argument(2));18751876Node* result = NULL;18771878Node* const_two_node = makecon(TypeD::make(2.0));1879Node* cmp_node = _gvn.transform(new (C) CmpDNode(y, const_two_node));1880Node* bool_node = _gvn.transform(new (C) BoolNode(cmp_node, BoolTest::eq));1881IfNode* if_node = create_and_xform_if(control(), bool_node, PROB_STATIC_INFREQUENT, COUNT_UNKNOWN);1882Node* if_true = _gvn.transform(new (C) IfTrueNode(if_node));1883Node* if_false = _gvn.transform(new (C) IfFalseNode(if_node));18841885RegionNode* region_node = new (C) RegionNode(3);1886region_node->init_req(1, if_true);18871888Node* phi_node = new (C) PhiNode(region_node, Type::DOUBLE);1889// special case for x^y where y == 2, we can convert it to x * x1890phi_node->init_req(1, _gvn.transform(new (C) MulDNode(x, x)));18911892// set control to if_false since we will now process the false branch1893set_control(if_false);18941895if (!too_many_traps(Deoptimization::Reason_intrinsic)) {1896// Short form: skip the fancy tests and just check for NaN result.1897result = _gvn.transform(new (C) PowDNode(C, control(), x, y));1898} else {1899// If this inlining ever returned NaN in the past, include all1900// checks + call to the runtime.19011902// Set the merge point for If node with condition of (x <= 0.0)1903// There are four possible paths to region node and phi node1904RegionNode *r = new (C) RegionNode(4);1905Node *phi = new (C) PhiNode(r, Type::DOUBLE);19061907// Build the first if node: if (x <= 0.0)1908// Node for 0 constant1909Node *zeronode = makecon(TypeD::ZERO);1910// Check x:01911Node *cmp = _gvn.transform(new (C) CmpDNode(x, zeronode));1912// Check: If (x<=0) then go complex path1913Node *bol1 = _gvn.transform(new (C) BoolNode( cmp, BoolTest::le ));1914// Branch either way1915IfNode *if1 = create_and_xform_if(control(),bol1, PROB_STATIC_INFREQUENT, COUNT_UNKNOWN);1916// Fast path taken; set region slot 31917Node *fast_taken = _gvn.transform(new (C) IfFalseNode(if1));1918r->init_req(3,fast_taken); // Capture fast-control19191920// Fast path not-taken, i.e. slow path1921Node *complex_path = _gvn.transform(new (C) IfTrueNode(if1));19221923// Set fast path result1924Node *fast_result = _gvn.transform(new (C) PowDNode(C, control(), x, y));1925phi->init_req(3, fast_result);19261927// Complex path1928// Build the second if node (if y is long)1929// Node for (long)y1930Node *longy = _gvn.transform(new (C) ConvD2LNode(y));1931// Node for (double)((long) y)1932Node *doublelongy= _gvn.transform(new (C) ConvL2DNode(longy));1933// Check (double)((long) y) : y1934Node *cmplongy= _gvn.transform(new (C) CmpDNode(doublelongy, y));1935// Check if (y isn't long) then go to slow path19361937Node *bol2 = _gvn.transform(new (C) BoolNode( cmplongy, BoolTest::ne ));1938// Branch either way1939IfNode *if2 = create_and_xform_if(complex_path,bol2, PROB_STATIC_INFREQUENT, COUNT_UNKNOWN);1940Node* ylong_path = _gvn.transform(new (C) IfFalseNode(if2));19411942Node *slow_path = _gvn.transform(new (C) IfTrueNode(if2));19431944// Calculate DPow(abs(x), y)*(1 & (long)y)1945// Node for constant 11946Node *conone = longcon(1);1947// 1& (long)y1948Node *signnode= _gvn.transform(new (C) AndLNode(conone, longy));19491950// A huge number is always even. Detect a huge number by checking1951// if y + 1 == y and set integer to be tested for parity to 0.1952// Required for corner case:1953// (long)9.223372036854776E18 = max_jlong1954// (double)(long)9.223372036854776E18 = 9.223372036854776E181955// max_jlong is odd but 9.223372036854776E18 is even1956Node* yplus1 = _gvn.transform(new (C) AddDNode(y, makecon(TypeD::make(1))));1957Node *cmpyplus1= _gvn.transform(new (C) CmpDNode(yplus1, y));1958Node *bolyplus1 = _gvn.transform(new (C) BoolNode( cmpyplus1, BoolTest::eq ));1959Node* correctedsign = NULL;1960if (ConditionalMoveLimit != 0) {1961correctedsign = _gvn.transform( CMoveNode::make(C, NULL, bolyplus1, signnode, longcon(0), TypeLong::LONG));1962} else {1963IfNode *ifyplus1 = create_and_xform_if(ylong_path,bolyplus1, PROB_FAIR, COUNT_UNKNOWN);1964RegionNode *r = new (C) RegionNode(3);1965Node *phi = new (C) PhiNode(r, TypeLong::LONG);1966r->init_req(1, _gvn.transform(new (C) IfFalseNode(ifyplus1)));1967r->init_req(2, _gvn.transform(new (C) IfTrueNode(ifyplus1)));1968phi->init_req(1, signnode);1969phi->init_req(2, longcon(0));1970correctedsign = _gvn.transform(phi);1971ylong_path = _gvn.transform(r);1972record_for_igvn(r);1973}19741975// zero node1976Node *conzero = longcon(0);1977// Check (1&(long)y)==0?1978Node *cmpeq1 = _gvn.transform(new (C) CmpLNode(correctedsign, conzero));1979// Check if (1&(long)y)!=0?, if so the result is negative1980Node *bol3 = _gvn.transform(new (C) BoolNode( cmpeq1, BoolTest::ne ));1981// abs(x)1982Node *absx=_gvn.transform(new (C) AbsDNode(x));1983// abs(x)^y1984Node *absxpowy = _gvn.transform(new (C) PowDNode(C, control(), absx, y));1985// -abs(x)^y1986Node *negabsxpowy = _gvn.transform(new (C) NegDNode (absxpowy));1987// (1&(long)y)==1?-DPow(abs(x), y):DPow(abs(x), y)1988Node *signresult = NULL;1989if (ConditionalMoveLimit != 0) {1990signresult = _gvn.transform( CMoveNode::make(C, NULL, bol3, absxpowy, negabsxpowy, Type::DOUBLE));1991} else {1992IfNode *ifyeven = create_and_xform_if(ylong_path,bol3, PROB_FAIR, COUNT_UNKNOWN);1993RegionNode *r = new (C) RegionNode(3);1994Node *phi = new (C) PhiNode(r, Type::DOUBLE);1995r->init_req(1, _gvn.transform(new (C) IfFalseNode(ifyeven)));1996r->init_req(2, _gvn.transform(new (C) IfTrueNode(ifyeven)));1997phi->init_req(1, absxpowy);1998phi->init_req(2, negabsxpowy);1999signresult = _gvn.transform(phi);2000ylong_path = _gvn.transform(r);2001record_for_igvn(r);2002}2003// Set complex path fast result2004r->init_req(2, ylong_path);2005phi->init_req(2, signresult);20062007static const jlong nan_bits = CONST64(0x7ff8000000000000);2008Node *slow_result = makecon(TypeD::make(*(double*)&nan_bits)); // return NaN2009r->init_req(1,slow_path);2010phi->init_req(1,slow_result);20112012// Post merge2013set_control(_gvn.transform(r));2014record_for_igvn(r);2015result = _gvn.transform(phi);2016}20172018result = finish_pow_exp(result, x, y, OptoRuntime::Math_DD_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dpow), "POW");20192020// control from finish_pow_exp is now input to the region node2021region_node->set_req(2, control());2022// the result from finish_pow_exp is now input to the phi node2023phi_node->init_req(2, result);2024set_control(_gvn.transform(region_node));2025record_for_igvn(region_node);2026set_result(_gvn.transform(phi_node));20272028C->set_has_split_ifs(true); // Has chance for split-if optimization2029return true;2030}20312032//------------------------------runtime_math-----------------------------2033bool LibraryCallKit::runtime_math(const TypeFunc* call_type, address funcAddr, const char* funcName) {2034assert(call_type == OptoRuntime::Math_DD_D_Type() || call_type == OptoRuntime::Math_D_D_Type(),2035"must be (DD)D or (D)D type");20362037// Inputs2038Node* a = round_double_node(argument(0));2039Node* b = (call_type == OptoRuntime::Math_DD_D_Type()) ? round_double_node(argument(2)) : NULL;20402041const TypePtr* no_memory_effects = NULL;2042Node* trig = make_runtime_call(RC_LEAF, call_type, funcAddr, funcName,2043no_memory_effects,2044a, top(), b, b ? top() : NULL);2045Node* value = _gvn.transform(new (C) ProjNode(trig, TypeFunc::Parms+0));2046#ifdef ASSERT2047Node* value_top = _gvn.transform(new (C) ProjNode(trig, TypeFunc::Parms+1));2048assert(value_top == top(), "second value must be top");2049#endif20502051set_result(value);2052return true;2053}20542055//------------------------------inline_math_native-----------------------------2056bool LibraryCallKit::inline_math_native(vmIntrinsics::ID id) {2057#define FN_PTR(f) CAST_FROM_FN_PTR(address, f)2058switch (id) {2059// These intrinsics are not properly supported on all hardware2060case vmIntrinsics::_dcos: return Matcher::has_match_rule(Op_CosD) ? inline_trig(id) :2061runtime_math(OptoRuntime::Math_D_D_Type(), FN_PTR(SharedRuntime::dcos), "COS");2062case vmIntrinsics::_dsin: return Matcher::has_match_rule(Op_SinD) ? inline_trig(id) :2063runtime_math(OptoRuntime::Math_D_D_Type(), FN_PTR(SharedRuntime::dsin), "SIN");2064case vmIntrinsics::_dtan: return Matcher::has_match_rule(Op_TanD) ? inline_trig(id) :2065runtime_math(OptoRuntime::Math_D_D_Type(), FN_PTR(SharedRuntime::dtan), "TAN");20662067case vmIntrinsics::_dlog: return Matcher::has_match_rule(Op_LogD) ? inline_math(id) :2068runtime_math(OptoRuntime::Math_D_D_Type(), FN_PTR(SharedRuntime::dlog), "LOG");2069case vmIntrinsics::_dlog10: return Matcher::has_match_rule(Op_Log10D) ? inline_math(id) :2070runtime_math(OptoRuntime::Math_D_D_Type(), FN_PTR(SharedRuntime::dlog10), "LOG10");20712072// These intrinsics are supported on all hardware2073case vmIntrinsics::_dsqrt: return Matcher::match_rule_supported(Op_SqrtD) ? inline_math(id) : false;2074case vmIntrinsics::_dabs: return Matcher::has_match_rule(Op_AbsD) ? inline_math(id) : false;20752076case vmIntrinsics::_dexp: return Matcher::has_match_rule(Op_ExpD) ? inline_exp() :2077runtime_math(OptoRuntime::Math_D_D_Type(), FN_PTR(SharedRuntime::dexp), "EXP");2078case vmIntrinsics::_dpow: return Matcher::has_match_rule(Op_PowD) ? inline_pow() :2079runtime_math(OptoRuntime::Math_DD_D_Type(), FN_PTR(SharedRuntime::dpow), "POW");2080#undef FN_PTR20812082// These intrinsics are not yet correctly implemented2083case vmIntrinsics::_datan2:2084return false;20852086default:2087fatal_unexpected_iid(id);2088return false;2089}2090}20912092static bool is_simple_name(Node* n) {2093return (n->req() == 1 // constant2094|| (n->is_Type() && n->as_Type()->type()->singleton())2095|| n->is_Proj() // parameter or return value2096|| n->is_Phi() // local of some sort2097);2098}20992100//----------------------------inline_min_max-----------------------------------2101bool LibraryCallKit::inline_min_max(vmIntrinsics::ID id) {2102set_result(generate_min_max(id, argument(0), argument(1)));2103return true;2104}21052106void LibraryCallKit::inline_math_mathExact(Node* math, Node *test) {2107Node* bol = _gvn.transform( new (C) BoolNode(test, BoolTest::overflow) );2108IfNode* check = create_and_map_if(control(), bol, PROB_UNLIKELY_MAG(3), COUNT_UNKNOWN);2109Node* fast_path = _gvn.transform( new (C) IfFalseNode(check));2110Node* slow_path = _gvn.transform( new (C) IfTrueNode(check) );21112112{2113PreserveJVMState pjvms(this);2114PreserveReexecuteState preexecs(this);2115jvms()->set_should_reexecute(true);21162117set_control(slow_path);2118set_i_o(i_o());21192120uncommon_trap(Deoptimization::Reason_intrinsic,2121Deoptimization::Action_none);2122}21232124set_control(fast_path);2125set_result(math);2126}21272128template <typename OverflowOp>2129bool LibraryCallKit::inline_math_overflow(Node* arg1, Node* arg2) {2130typedef typename OverflowOp::MathOp MathOp;21312132MathOp* mathOp = new(C) MathOp(arg1, arg2);2133Node* operation = _gvn.transform( mathOp );2134Node* ofcheck = _gvn.transform( new(C) OverflowOp(arg1, arg2) );2135inline_math_mathExact(operation, ofcheck);2136return true;2137}21382139bool LibraryCallKit::inline_math_addExactI(bool is_increment) {2140return inline_math_overflow<OverflowAddINode>(argument(0), is_increment ? intcon(1) : argument(1));2141}21422143bool LibraryCallKit::inline_math_addExactL(bool is_increment) {2144return inline_math_overflow<OverflowAddLNode>(argument(0), is_increment ? longcon(1) : argument(2));2145}21462147bool LibraryCallKit::inline_math_subtractExactI(bool is_decrement) {2148return inline_math_overflow<OverflowSubINode>(argument(0), is_decrement ? intcon(1) : argument(1));2149}21502151bool LibraryCallKit::inline_math_subtractExactL(bool is_decrement) {2152return inline_math_overflow<OverflowSubLNode>(argument(0), is_decrement ? longcon(1) : argument(2));2153}21542155bool LibraryCallKit::inline_math_negateExactI() {2156return inline_math_overflow<OverflowSubINode>(intcon(0), argument(0));2157}21582159bool LibraryCallKit::inline_math_negateExactL() {2160return inline_math_overflow<OverflowSubLNode>(longcon(0), argument(0));2161}21622163bool LibraryCallKit::inline_math_multiplyExactI() {2164return inline_math_overflow<OverflowMulINode>(argument(0), argument(1));2165}21662167bool LibraryCallKit::inline_math_multiplyExactL() {2168return inline_math_overflow<OverflowMulLNode>(argument(0), argument(2));2169}21702171Node*2172LibraryCallKit::generate_min_max(vmIntrinsics::ID id, Node* x0, Node* y0) {2173// These are the candidate return value:2174Node* xvalue = x0;2175Node* yvalue = y0;21762177if (xvalue == yvalue) {2178return xvalue;2179}21802181bool want_max = (id == vmIntrinsics::_max);21822183const TypeInt* txvalue = _gvn.type(xvalue)->isa_int();2184const TypeInt* tyvalue = _gvn.type(yvalue)->isa_int();2185if (txvalue == NULL || tyvalue == NULL) return top();2186// This is not really necessary, but it is consistent with a2187// hypothetical MaxINode::Value method:2188int widen = MAX2(txvalue->_widen, tyvalue->_widen);21892190// %%% This folding logic should (ideally) be in a different place.2191// Some should be inside IfNode, and there to be a more reliable2192// transformation of ?: style patterns into cmoves. We also want2193// more powerful optimizations around cmove and min/max.21942195// Try to find a dominating comparison of these guys.2196// It can simplify the index computation for Arrays.copyOf2197// and similar uses of System.arraycopy.2198// First, compute the normalized version of CmpI(x, y).2199int cmp_op = Op_CmpI;2200Node* xkey = xvalue;2201Node* ykey = yvalue;2202Node* ideal_cmpxy = _gvn.transform(new(C) CmpINode(xkey, ykey));2203if (ideal_cmpxy->is_Cmp()) {2204// E.g., if we have CmpI(length - offset, count),2205// it might idealize to CmpI(length, count + offset)2206cmp_op = ideal_cmpxy->Opcode();2207xkey = ideal_cmpxy->in(1);2208ykey = ideal_cmpxy->in(2);2209}22102211// Start by locating any relevant comparisons.2212Node* start_from = (xkey->outcnt() < ykey->outcnt()) ? xkey : ykey;2213Node* cmpxy = NULL;2214Node* cmpyx = NULL;2215for (DUIterator_Fast kmax, k = start_from->fast_outs(kmax); k < kmax; k++) {2216Node* cmp = start_from->fast_out(k);2217if (cmp->outcnt() > 0 && // must have prior uses2218cmp->in(0) == NULL && // must be context-independent2219cmp->Opcode() == cmp_op) { // right kind of compare2220if (cmp->in(1) == xkey && cmp->in(2) == ykey) cmpxy = cmp;2221if (cmp->in(1) == ykey && cmp->in(2) == xkey) cmpyx = cmp;2222}2223}22242225const int NCMPS = 2;2226Node* cmps[NCMPS] = { cmpxy, cmpyx };2227int cmpn;2228for (cmpn = 0; cmpn < NCMPS; cmpn++) {2229if (cmps[cmpn] != NULL) break; // find a result2230}2231if (cmpn < NCMPS) {2232// Look for a dominating test that tells us the min and max.2233int depth = 0; // Limit search depth for speed2234Node* dom = control();2235for (; dom != NULL; dom = IfNode::up_one_dom(dom, true)) {2236if (++depth >= 100) break;2237Node* ifproj = dom;2238if (!ifproj->is_Proj()) continue;2239Node* iff = ifproj->in(0);2240if (!iff->is_If()) continue;2241Node* bol = iff->in(1);2242if (!bol->is_Bool()) continue;2243Node* cmp = bol->in(1);2244if (cmp == NULL) continue;2245for (cmpn = 0; cmpn < NCMPS; cmpn++)2246if (cmps[cmpn] == cmp) break;2247if (cmpn == NCMPS) continue;2248BoolTest::mask btest = bol->as_Bool()->_test._test;2249if (ifproj->is_IfFalse()) btest = BoolTest(btest).negate();2250if (cmp->in(1) == ykey) btest = BoolTest(btest).commute();2251// At this point, we know that 'x btest y' is true.2252switch (btest) {2253case BoolTest::eq:2254// They are proven equal, so we can collapse the min/max.2255// Either value is the answer. Choose the simpler.2256if (is_simple_name(yvalue) && !is_simple_name(xvalue))2257return yvalue;2258return xvalue;2259case BoolTest::lt: // x < y2260case BoolTest::le: // x <= y2261return (want_max ? yvalue : xvalue);2262case BoolTest::gt: // x > y2263case BoolTest::ge: // x >= y2264return (want_max ? xvalue : yvalue);2265}2266}2267}22682269// We failed to find a dominating test.2270// Let's pick a test that might GVN with prior tests.2271Node* best_bol = NULL;2272BoolTest::mask best_btest = BoolTest::illegal;2273for (cmpn = 0; cmpn < NCMPS; cmpn++) {2274Node* cmp = cmps[cmpn];2275if (cmp == NULL) continue;2276for (DUIterator_Fast jmax, j = cmp->fast_outs(jmax); j < jmax; j++) {2277Node* bol = cmp->fast_out(j);2278if (!bol->is_Bool()) continue;2279BoolTest::mask btest = bol->as_Bool()->_test._test;2280if (btest == BoolTest::eq || btest == BoolTest::ne) continue;2281if (cmp->in(1) == ykey) btest = BoolTest(btest).commute();2282if (bol->outcnt() > (best_bol == NULL ? 0 : best_bol->outcnt())) {2283best_bol = bol->as_Bool();2284best_btest = btest;2285}2286}2287}22882289Node* answer_if_true = NULL;2290Node* answer_if_false = NULL;2291switch (best_btest) {2292default:2293if (cmpxy == NULL)2294cmpxy = ideal_cmpxy;2295best_bol = _gvn.transform(new(C) BoolNode(cmpxy, BoolTest::lt));2296// and fall through:2297case BoolTest::lt: // x < y2298case BoolTest::le: // x <= y2299answer_if_true = (want_max ? yvalue : xvalue);2300answer_if_false = (want_max ? xvalue : yvalue);2301break;2302case BoolTest::gt: // x > y2303case BoolTest::ge: // x >= y2304answer_if_true = (want_max ? xvalue : yvalue);2305answer_if_false = (want_max ? yvalue : xvalue);2306break;2307}23082309jint hi, lo;2310if (want_max) {2311// We can sharpen the minimum.2312hi = MAX2(txvalue->_hi, tyvalue->_hi);2313lo = MAX2(txvalue->_lo, tyvalue->_lo);2314} else {2315// We can sharpen the maximum.2316hi = MIN2(txvalue->_hi, tyvalue->_hi);2317lo = MIN2(txvalue->_lo, tyvalue->_lo);2318}23192320// Use a flow-free graph structure, to avoid creating excess control edges2321// which could hinder other optimizations.2322// Since Math.min/max is often used with arraycopy, we want2323// tightly_coupled_allocation to be able to see beyond min/max expressions.2324Node* cmov = CMoveNode::make(C, NULL, best_bol,2325answer_if_false, answer_if_true,2326TypeInt::make(lo, hi, widen));23272328return _gvn.transform(cmov);23292330/*2331// This is not as desirable as it may seem, since Min and Max2332// nodes do not have a full set of optimizations.2333// And they would interfere, anyway, with 'if' optimizations2334// and with CMoveI canonical forms.2335switch (id) {2336case vmIntrinsics::_min:2337result_val = _gvn.transform(new (C, 3) MinINode(x,y)); break;2338case vmIntrinsics::_max:2339result_val = _gvn.transform(new (C, 3) MaxINode(x,y)); break;2340default:2341ShouldNotReachHere();2342}2343*/2344}23452346inline int2347LibraryCallKit::classify_unsafe_addr(Node* &base, Node* &offset) {2348const TypePtr* base_type = TypePtr::NULL_PTR;2349if (base != NULL) base_type = _gvn.type(base)->isa_ptr();2350if (base_type == NULL) {2351// Unknown type.2352return Type::AnyPtr;2353} else if (base_type == TypePtr::NULL_PTR) {2354// Since this is a NULL+long form, we have to switch to a rawptr.2355base = _gvn.transform(new (C) CastX2PNode(offset));2356offset = MakeConX(0);2357return Type::RawPtr;2358} else if (base_type->base() == Type::RawPtr) {2359return Type::RawPtr;2360} else if (base_type->isa_oopptr()) {2361// Base is never null => always a heap address.2362if (base_type->ptr() == TypePtr::NotNull) {2363return Type::OopPtr;2364}2365// Offset is small => always a heap address.2366const TypeX* offset_type = _gvn.type(offset)->isa_intptr_t();2367if (offset_type != NULL &&2368base_type->offset() == 0 && // (should always be?)2369offset_type->_lo >= 0 &&2370!MacroAssembler::needs_explicit_null_check(offset_type->_hi)) {2371return Type::OopPtr;2372}2373// Otherwise, it might either be oop+off or NULL+addr.2374return Type::AnyPtr;2375} else {2376// No information:2377return Type::AnyPtr;2378}2379}23802381inline Node* LibraryCallKit::make_unsafe_address(Node* base, Node* offset) {2382int kind = classify_unsafe_addr(base, offset);2383if (kind == Type::RawPtr) {2384return basic_plus_adr(top(), base, offset);2385} else {2386return basic_plus_adr(base, offset);2387}2388}23892390//--------------------------inline_number_methods-----------------------------2391// inline int Integer.numberOfLeadingZeros(int)2392// inline int Long.numberOfLeadingZeros(long)2393//2394// inline int Integer.numberOfTrailingZeros(int)2395// inline int Long.numberOfTrailingZeros(long)2396//2397// inline int Integer.bitCount(int)2398// inline int Long.bitCount(long)2399//2400// inline char Character.reverseBytes(char)2401// inline short Short.reverseBytes(short)2402// inline int Integer.reverseBytes(int)2403// inline long Long.reverseBytes(long)2404bool LibraryCallKit::inline_number_methods(vmIntrinsics::ID id) {2405Node* arg = argument(0);2406Node* n = NULL;2407switch (id) {2408case vmIntrinsics::_numberOfLeadingZeros_i: n = new (C) CountLeadingZerosINode( arg); break;2409case vmIntrinsics::_numberOfLeadingZeros_l: n = new (C) CountLeadingZerosLNode( arg); break;2410case vmIntrinsics::_numberOfTrailingZeros_i: n = new (C) CountTrailingZerosINode(arg); break;2411case vmIntrinsics::_numberOfTrailingZeros_l: n = new (C) CountTrailingZerosLNode(arg); break;2412case vmIntrinsics::_bitCount_i: n = new (C) PopCountINode( arg); break;2413case vmIntrinsics::_bitCount_l: n = new (C) PopCountLNode( arg); break;2414case vmIntrinsics::_reverseBytes_c: n = new (C) ReverseBytesUSNode(0, arg); break;2415case vmIntrinsics::_reverseBytes_s: n = new (C) ReverseBytesSNode( 0, arg); break;2416case vmIntrinsics::_reverseBytes_i: n = new (C) ReverseBytesINode( 0, arg); break;2417case vmIntrinsics::_reverseBytes_l: n = new (C) ReverseBytesLNode( 0, arg); break;2418default: fatal_unexpected_iid(id); break;2419}2420set_result(_gvn.transform(n));2421return true;2422}24232424//----------------------------inline_unsafe_access----------------------------24252426const static BasicType T_ADDRESS_HOLDER = T_LONG;24272428// Helper that guards and inserts a pre-barrier.2429void LibraryCallKit::insert_pre_barrier(Node* base_oop, Node* offset,2430Node* pre_val, bool need_mem_bar) {2431// We could be accessing the referent field of a reference object. If so, when G12432// is enabled, we need to log the value in the referent field in an SATB buffer.2433// This routine performs some compile time filters and generates suitable2434// runtime filters that guard the pre-barrier code.2435// Also add memory barrier for non volatile load from the referent field2436// to prevent commoning of loads across safepoint.2437if (!(UseG1GC || UseShenandoahGC) && !need_mem_bar)2438return;24392440// Some compile time checks.24412442// If offset is a constant, is it java_lang_ref_Reference::_reference_offset?2443const TypeX* otype = offset->find_intptr_t_type();2444if (otype != NULL && otype->is_con() &&2445otype->get_con() != java_lang_ref_Reference::referent_offset) {2446// Constant offset but not the reference_offset so just return2447return;2448}24492450// We only need to generate the runtime guards for instances.2451const TypeOopPtr* btype = base_oop->bottom_type()->isa_oopptr();2452if (btype != NULL) {2453if (btype->isa_aryptr()) {2454// Array type so nothing to do2455return;2456}24572458const TypeInstPtr* itype = btype->isa_instptr();2459if (itype != NULL) {2460// Can the klass of base_oop be statically determined to be2461// _not_ a sub-class of Reference and _not_ Object?2462ciKlass* klass = itype->klass();2463if ( klass->is_loaded() &&2464!klass->is_subtype_of(env()->Reference_klass()) &&2465!env()->Object_klass()->is_subtype_of(klass)) {2466return;2467}2468}2469}24702471// The compile time filters did not reject base_oop/offset so2472// we need to generate the following runtime filters2473//2474// if (offset == java_lang_ref_Reference::_reference_offset) {2475// if (instance_of(base, java.lang.ref.Reference)) {2476// pre_barrier(_, pre_val, ...);2477// }2478// }24792480float likely = PROB_LIKELY( 0.999);2481float unlikely = PROB_UNLIKELY(0.999);24822483IdealKit ideal(this);2484#define __ ideal.24852486Node* referent_off = __ ConX(java_lang_ref_Reference::referent_offset);24872488__ if_then(offset, BoolTest::eq, referent_off, unlikely); {2489// Update graphKit memory and control from IdealKit.2490sync_kit(ideal);24912492Node* ref_klass_con = makecon(TypeKlassPtr::make(env()->Reference_klass()));2493Node* is_instof = gen_instanceof(base_oop, ref_klass_con);24942495// Update IdealKit memory and control from graphKit.2496__ sync_kit(this);24972498Node* one = __ ConI(1);2499// is_instof == 0 if base_oop == NULL2500__ if_then(is_instof, BoolTest::eq, one, unlikely); {25012502// Update graphKit from IdeakKit.2503sync_kit(ideal);25042505// Use the pre-barrier to record the value in the referent field2506pre_barrier(false /* do_load */,2507__ ctrl(),2508NULL /* obj */, NULL /* adr */, max_juint /* alias_idx */, NULL /* val */, NULL /* val_type */,2509pre_val /* pre_val */,2510T_OBJECT);2511if (need_mem_bar) {2512// Add memory barrier to prevent commoning reads from this field2513// across safepoint since GC can change its value.2514insert_mem_bar(Op_MemBarCPUOrder);2515}2516// Update IdealKit from graphKit.2517__ sync_kit(this);25182519} __ end_if(); // _ref_type != ref_none2520} __ end_if(); // offset == referent_offset25212522// Final sync IdealKit and GraphKit.2523final_sync(ideal);2524#undef __2525}252625272528// Interpret Unsafe.fieldOffset cookies correctly:2529extern jlong Unsafe_field_offset_to_byte_offset(jlong field_offset);25302531const TypeOopPtr* LibraryCallKit::sharpen_unsafe_type(Compile::AliasType* alias_type, const TypePtr *adr_type, bool is_native_ptr) {2532// Attempt to infer a sharper value type from the offset and base type.2533ciKlass* sharpened_klass = NULL;25342535// See if it is an instance field, with an object type.2536if (alias_type->field() != NULL) {2537assert(!is_native_ptr, "native pointer op cannot use a java address");2538if (alias_type->field()->type()->is_klass()) {2539sharpened_klass = alias_type->field()->type()->as_klass();2540}2541}25422543// See if it is a narrow oop array.2544if (adr_type->isa_aryptr()) {2545if (adr_type->offset() >= objArrayOopDesc::base_offset_in_bytes()) {2546const TypeOopPtr *elem_type = adr_type->is_aryptr()->elem()->isa_oopptr();2547if (elem_type != NULL) {2548sharpened_klass = elem_type->klass();2549}2550}2551}25522553// The sharpened class might be unloaded if there is no class loader2554// contraint in place.2555if (sharpened_klass != NULL && sharpened_klass->is_loaded()) {2556const TypeOopPtr* tjp = TypeOopPtr::make_from_klass(sharpened_klass);25572558#ifndef PRODUCT2559if (C->print_intrinsics() || C->print_inlining()) {2560tty->print(" from base type: "); adr_type->dump(); tty->cr();2561tty->print(" sharpened value: "); tjp->dump(); tty->cr();2562}2563#endif2564// Sharpen the value type.2565return tjp;2566}2567return NULL;2568}25692570bool LibraryCallKit::inline_unsafe_access(bool is_native_ptr, bool is_store, BasicType type, bool is_volatile, bool unaligned) {2571if (callee()->is_static()) return false; // caller must have the capability!2572assert(type != T_OBJECT || !unaligned, "unaligned access not supported with object type");25732574#ifndef PRODUCT2575{2576ResourceMark rm;2577// Check the signatures.2578ciSignature* sig = callee()->signature();2579#ifdef ASSERT2580if (!is_store) {2581// Object getObject(Object base, int/long offset), etc.2582BasicType rtype = sig->return_type()->basic_type();2583if (rtype == T_ADDRESS_HOLDER && callee()->name() == ciSymbol::getAddress_name())2584rtype = T_ADDRESS; // it is really a C void*2585assert(rtype == type, "getter must return the expected value");2586if (!is_native_ptr) {2587assert(sig->count() == 2, "oop getter has 2 arguments");2588assert(sig->type_at(0)->basic_type() == T_OBJECT, "getter base is object");2589assert(sig->type_at(1)->basic_type() == T_LONG, "getter offset is correct");2590} else {2591assert(sig->count() == 1, "native getter has 1 argument");2592assert(sig->type_at(0)->basic_type() == T_LONG, "getter base is long");2593}2594} else {2595// void putObject(Object base, int/long offset, Object x), etc.2596assert(sig->return_type()->basic_type() == T_VOID, "putter must not return a value");2597if (!is_native_ptr) {2598assert(sig->count() == 3, "oop putter has 3 arguments");2599assert(sig->type_at(0)->basic_type() == T_OBJECT, "putter base is object");2600assert(sig->type_at(1)->basic_type() == T_LONG, "putter offset is correct");2601} else {2602assert(sig->count() == 2, "native putter has 2 arguments");2603assert(sig->type_at(0)->basic_type() == T_LONG, "putter base is long");2604}2605BasicType vtype = sig->type_at(sig->count()-1)->basic_type();2606if (vtype == T_ADDRESS_HOLDER && callee()->name() == ciSymbol::putAddress_name())2607vtype = T_ADDRESS; // it is really a C void*2608assert(vtype == type, "putter must accept the expected value");2609}2610#endif // ASSERT2611}2612#endif //PRODUCT26132614C->set_has_unsafe_access(true); // Mark eventual nmethod as "unsafe".26152616Node* receiver = argument(0); // type: oop26172618// Build address expression. See the code in inline_unsafe_prefetch.2619Node* adr;2620Node* heap_base_oop = top();2621Node* offset = top();2622Node* val;26232624// The base is either a Java object or a value produced by Unsafe.staticFieldBase2625Node* base = argument(1); // type: oop26262627if (!is_native_ptr) {2628// The offset is a value produced by Unsafe.staticFieldOffset or Unsafe.objectFieldOffset2629offset = argument(2); // type: long2630// We currently rely on the cookies produced by Unsafe.xxxFieldOffset2631// to be plain byte offsets, which are also the same as those accepted2632// by oopDesc::field_base.2633assert(Unsafe_field_offset_to_byte_offset(11) == 11,2634"fieldOffset must be byte-scaled");2635// 32-bit machines ignore the high half!2636offset = ConvL2X(offset);2637adr = make_unsafe_address(base, offset);2638heap_base_oop = base;2639val = is_store ? argument(4) : NULL;2640} else {2641Node* ptr = argument(1); // type: long2642ptr = ConvL2X(ptr); // adjust Java long to machine word2643adr = make_unsafe_address(NULL, ptr);2644val = is_store ? argument(3) : NULL;2645}26462647if ((_gvn.type(base)->isa_ptr() == TypePtr::NULL_PTR) && type == T_OBJECT) {2648return false; // off-heap oop accesses are not supported2649}26502651const TypePtr *adr_type = _gvn.type(adr)->isa_ptr();26522653// Try to categorize the address.2654Compile::AliasType* alias_type = C->alias_type(adr_type);2655assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");26562657if (alias_type->adr_type() == TypeInstPtr::KLASS ||2658alias_type->adr_type() == TypeAryPtr::RANGE) {2659return false; // not supported2660}26612662bool mismatched = false;2663BasicType bt = alias_type->basic_type();2664if (bt != T_ILLEGAL) {2665assert(alias_type->adr_type()->is_oopptr(), "should be on-heap access");2666if (bt == T_BYTE && adr_type->isa_aryptr()) {2667// Alias type doesn't differentiate between byte[] and boolean[]).2668// Use address type to get the element type.2669bt = adr_type->is_aryptr()->elem()->array_element_basic_type();2670}2671if (bt == T_ARRAY || bt == T_NARROWOOP) {2672// accessing an array field with getObject is not a mismatch2673bt = T_OBJECT;2674}2675if ((bt == T_OBJECT) != (type == T_OBJECT)) {2676// Don't intrinsify mismatched object accesses2677return false;2678}2679mismatched = (bt != type);2680}26812682assert(!mismatched || alias_type->adr_type()->is_oopptr(), "off-heap access can't be mismatched");26832684// First guess at the value type.2685const Type *value_type = Type::get_const_basic_type(type);26862687// We will need memory barriers unless we can determine a unique2688// alias category for this reference. (Note: If for some reason2689// the barriers get omitted and the unsafe reference begins to "pollute"2690// the alias analysis of the rest of the graph, either Compile::can_alias2691// or Compile::must_alias will throw a diagnostic assert.)2692bool need_mem_bar = (alias_type->adr_type() == TypeOopPtr::BOTTOM);26932694#if INCLUDE_ALL_GCS2695// Work around JDK-8220714 bug. This is done for Shenandoah only, until2696// the shared code fix is upstreamed and properly tested there.2697if (UseShenandoahGC) {2698need_mem_bar |= is_native_ptr;2699}2700#endif27012702// If we are reading the value of the referent field of a Reference2703// object (either by using Unsafe directly or through reflection)2704// then, if G1 is enabled, we need to record the referent in an2705// SATB log buffer using the pre-barrier mechanism.2706// Also we need to add memory barrier to prevent commoning reads2707// from this field across safepoint since GC can change its value.2708bool need_read_barrier = !is_native_ptr && !is_store &&2709offset != top() && heap_base_oop != top();27102711if (!is_store && type == T_OBJECT) {2712const TypeOopPtr* tjp = sharpen_unsafe_type(alias_type, adr_type, is_native_ptr);2713if (tjp != NULL) {2714value_type = tjp;2715}2716}27172718receiver = null_check(receiver);2719if (stopped()) {2720return true;2721}2722// Heap pointers get a null-check from the interpreter,2723// as a courtesy. However, this is not guaranteed by Unsafe,2724// and it is not possible to fully distinguish unintended nulls2725// from intended ones in this API.27262727Node* load = NULL;2728Node* store = NULL;2729Node* leading_membar = NULL;2730if (is_volatile) {2731// We need to emit leading and trailing CPU membars (see below) in2732// addition to memory membars when is_volatile. This is a little2733// too strong, but avoids the need to insert per-alias-type2734// volatile membars (for stores; compare Parse::do_put_xxx), which2735// we cannot do effectively here because we probably only have a2736// rough approximation of type.2737need_mem_bar = true;2738// For Stores, place a memory ordering barrier now.2739if (is_store) {2740leading_membar = insert_mem_bar(Op_MemBarRelease);2741} else {2742if (support_IRIW_for_not_multiple_copy_atomic_cpu) {2743leading_membar = insert_mem_bar(Op_MemBarVolatile);2744}2745}2746}27472748// Memory barrier to prevent normal and 'unsafe' accesses from2749// bypassing each other. Happens after null checks, so the2750// exception paths do not take memory state from the memory barrier,2751// so there's no problems making a strong assert about mixing users2752// of safe & unsafe memory. Otherwise fails in a CTW of rt.jar2753// around 5701, class sun/reflect/UnsafeBooleanFieldAccessorImpl.2754if (need_mem_bar) insert_mem_bar(Op_MemBarCPUOrder);27552756if (!is_store) {2757MemNode::MemOrd mo = is_volatile ? MemNode::acquire : MemNode::unordered;2758// To be valid, unsafe loads may depend on other conditions than2759// the one that guards them: pin the Load node2760load = make_load(control(), adr, value_type, type, adr_type, mo, LoadNode::Pinned, is_volatile, unaligned, mismatched);2761#if INCLUDE_ALL_GCS2762if (UseShenandoahGC && (type == T_OBJECT || type == T_ARRAY)) {2763load = ShenandoahBarrierSetC2::bsc2()->load_reference_barrier(this, load);2764}2765#endif2766// load value2767switch (type) {2768case T_BOOLEAN:2769case T_CHAR:2770case T_BYTE:2771case T_SHORT:2772case T_INT:2773case T_LONG:2774case T_FLOAT:2775case T_DOUBLE:2776break;2777case T_OBJECT:2778if (need_read_barrier) {2779insert_pre_barrier(heap_base_oop, offset, load, !(is_volatile || need_mem_bar));2780}2781break;2782case T_ADDRESS:2783// Cast to an int type.2784load = _gvn.transform(new (C) CastP2XNode(NULL, load));2785load = ConvX2UL(load);2786break;2787default:2788fatal(err_msg_res("unexpected type %d: %s", type, type2name(type)));2789break;2790}2791// The load node has the control of the preceding MemBarCPUOrder. All2792// following nodes will have the control of the MemBarCPUOrder inserted at2793// the end of this method. So, pushing the load onto the stack at a later2794// point is fine.2795set_result(load);2796} else {2797// place effect of store into memory2798switch (type) {2799case T_DOUBLE:2800val = dstore_rounding(val);2801break;2802case T_ADDRESS:2803// Repackage the long as a pointer.2804val = ConvL2X(val);2805val = _gvn.transform(new (C) CastX2PNode(val));2806break;2807}28082809MemNode::MemOrd mo = is_volatile ? MemNode::release : MemNode::unordered;2810if (type == T_OBJECT ) {2811store = store_oop_to_unknown(control(), heap_base_oop, adr, adr_type, val, type, mo, mismatched);2812} else {2813store = store_to_memory(control(), adr, val, type, adr_type, mo, is_volatile, unaligned, mismatched);2814}2815}28162817if (is_volatile) {2818if (!is_store) {2819#if INCLUDE_ALL_GCS2820if (UseShenandoahGC) {2821load = ShenandoahBarrierSetC2::bsc2()->step_over_gc_barrier(load);2822}2823#endif2824Node* mb = insert_mem_bar(Op_MemBarAcquire, load);2825mb->as_MemBar()->set_trailing_load();2826} else {2827if (!support_IRIW_for_not_multiple_copy_atomic_cpu) {2828Node* mb = insert_mem_bar(Op_MemBarVolatile, store);2829MemBarNode::set_store_pair(leading_membar->as_MemBar(), mb->as_MemBar());2830}2831}2832}28332834if (need_mem_bar) insert_mem_bar(Op_MemBarCPUOrder);28352836return true;2837}28382839//----------------------------inline_unsafe_prefetch----------------------------28402841bool LibraryCallKit::inline_unsafe_prefetch(bool is_native_ptr, bool is_store, bool is_static) {2842#ifndef PRODUCT2843{2844ResourceMark rm;2845// Check the signatures.2846ciSignature* sig = callee()->signature();2847#ifdef ASSERT2848// Object getObject(Object base, int/long offset), etc.2849BasicType rtype = sig->return_type()->basic_type();2850if (!is_native_ptr) {2851assert(sig->count() == 2, "oop prefetch has 2 arguments");2852assert(sig->type_at(0)->basic_type() == T_OBJECT, "prefetch base is object");2853assert(sig->type_at(1)->basic_type() == T_LONG, "prefetcha offset is correct");2854} else {2855assert(sig->count() == 1, "native prefetch has 1 argument");2856assert(sig->type_at(0)->basic_type() == T_LONG, "prefetch base is long");2857}2858#endif // ASSERT2859}2860#endif // !PRODUCT28612862C->set_has_unsafe_access(true); // Mark eventual nmethod as "unsafe".28632864const int idx = is_static ? 0 : 1;2865if (!is_static) {2866null_check_receiver();2867if (stopped()) {2868return true;2869}2870}28712872// Build address expression. See the code in inline_unsafe_access.2873Node *adr;2874if (!is_native_ptr) {2875// The base is either a Java object or a value produced by Unsafe.staticFieldBase2876Node* base = argument(idx + 0); // type: oop2877// The offset is a value produced by Unsafe.staticFieldOffset or Unsafe.objectFieldOffset2878Node* offset = argument(idx + 1); // type: long2879// We currently rely on the cookies produced by Unsafe.xxxFieldOffset2880// to be plain byte offsets, which are also the same as those accepted2881// by oopDesc::field_base.2882assert(Unsafe_field_offset_to_byte_offset(11) == 11,2883"fieldOffset must be byte-scaled");2884// 32-bit machines ignore the high half!2885offset = ConvL2X(offset);2886adr = make_unsafe_address(base, offset);2887} else {2888Node* ptr = argument(idx + 0); // type: long2889ptr = ConvL2X(ptr); // adjust Java long to machine word2890adr = make_unsafe_address(NULL, ptr);2891}28922893// Generate the read or write prefetch2894Node *prefetch;2895if (is_store) {2896prefetch = new (C) PrefetchWriteNode(i_o(), adr);2897} else {2898prefetch = new (C) PrefetchReadNode(i_o(), adr);2899}2900prefetch->init_req(0, control());2901set_i_o(_gvn.transform(prefetch));29022903return true;2904}29052906//----------------------------inline_unsafe_load_store----------------------------2907// This method serves a couple of different customers (depending on LoadStoreKind):2908//2909// LS_cmpxchg:2910// public final native boolean compareAndSwapObject(Object o, long offset, Object expected, Object x);2911// public final native boolean compareAndSwapInt( Object o, long offset, int expected, int x);2912// public final native boolean compareAndSwapLong( Object o, long offset, long expected, long x);2913//2914// LS_xadd:2915// public int getAndAddInt( Object o, long offset, int delta)2916// public long getAndAddLong(Object o, long offset, long delta)2917//2918// LS_xchg:2919// int getAndSet(Object o, long offset, int newValue)2920// long getAndSet(Object o, long offset, long newValue)2921// Object getAndSet(Object o, long offset, Object newValue)2922//2923bool LibraryCallKit::inline_unsafe_load_store(BasicType type, LoadStoreKind kind) {2924// This basic scheme here is the same as inline_unsafe_access, but2925// differs in enough details that combining them would make the code2926// overly confusing. (This is a true fact! I originally combined2927// them, but even I was confused by it!) As much code/comments as2928// possible are retained from inline_unsafe_access though to make2929// the correspondences clearer. - dl29302931if (callee()->is_static()) return false; // caller must have the capability!29322933#ifndef PRODUCT2934BasicType rtype;2935{2936ResourceMark rm;2937// Check the signatures.2938ciSignature* sig = callee()->signature();2939rtype = sig->return_type()->basic_type();2940if (kind == LS_xadd || kind == LS_xchg) {2941// Check the signatures.2942#ifdef ASSERT2943assert(rtype == type, "get and set must return the expected type");2944assert(sig->count() == 3, "get and set has 3 arguments");2945assert(sig->type_at(0)->basic_type() == T_OBJECT, "get and set base is object");2946assert(sig->type_at(1)->basic_type() == T_LONG, "get and set offset is long");2947assert(sig->type_at(2)->basic_type() == type, "get and set must take expected type as new value/delta");2948#endif // ASSERT2949} else if (kind == LS_cmpxchg) {2950// Check the signatures.2951#ifdef ASSERT2952assert(rtype == T_BOOLEAN, "CAS must return boolean");2953assert(sig->count() == 4, "CAS has 4 arguments");2954assert(sig->type_at(0)->basic_type() == T_OBJECT, "CAS base is object");2955assert(sig->type_at(1)->basic_type() == T_LONG, "CAS offset is long");2956#endif // ASSERT2957} else {2958ShouldNotReachHere();2959}2960}2961#endif //PRODUCT29622963C->set_has_unsafe_access(true); // Mark eventual nmethod as "unsafe".29642965// Get arguments:2966Node* receiver = NULL;2967Node* base = NULL;2968Node* offset = NULL;2969Node* oldval = NULL;2970Node* newval = NULL;2971if (kind == LS_cmpxchg) {2972const bool two_slot_type = type2size[type] == 2;2973receiver = argument(0); // type: oop2974base = argument(1); // type: oop2975offset = argument(2); // type: long2976oldval = argument(4); // type: oop, int, or long2977newval = argument(two_slot_type ? 6 : 5); // type: oop, int, or long2978} else if (kind == LS_xadd || kind == LS_xchg){2979receiver = argument(0); // type: oop2980base = argument(1); // type: oop2981offset = argument(2); // type: long2982oldval = NULL;2983newval = argument(4); // type: oop, int, or long2984}29852986// Build field offset expression.2987// We currently rely on the cookies produced by Unsafe.xxxFieldOffset2988// to be plain byte offsets, which are also the same as those accepted2989// by oopDesc::field_base.2990assert(Unsafe_field_offset_to_byte_offset(11) == 11, "fieldOffset must be byte-scaled");2991// 32-bit machines ignore the high half of long offsets2992offset = ConvL2X(offset);2993Node* adr = make_unsafe_address(base, offset);2994const TypePtr *adr_type = _gvn.type(adr)->isa_ptr();29952996Compile::AliasType* alias_type = C->alias_type(adr_type);2997BasicType bt = alias_type->basic_type();2998if (bt != T_ILLEGAL &&2999((bt == T_OBJECT || bt == T_ARRAY) != (type == T_OBJECT))) {3000// Don't intrinsify mismatched object accesses.3001return false;3002}30033004// For CAS, unlike inline_unsafe_access, there seems no point in3005// trying to refine types. Just use the coarse types here.3006assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");3007const Type *value_type = Type::get_const_basic_type(type);30083009if (kind == LS_xchg && type == T_OBJECT) {3010const TypeOopPtr* tjp = sharpen_unsafe_type(alias_type, adr_type);3011if (tjp != NULL) {3012value_type = tjp;3013}3014}30153016// Null check receiver.3017receiver = null_check(receiver);3018if (stopped()) {3019return true;3020}30213022int alias_idx = C->get_alias_index(adr_type);30233024// Memory-model-wise, a LoadStore acts like a little synchronized3025// block, so needs barriers on each side. These don't translate3026// into actual barriers on most machines, but we still need rest of3027// compiler to respect ordering.30283029Node* leading_membar = insert_mem_bar(Op_MemBarRelease);3030insert_mem_bar(Op_MemBarCPUOrder);30313032// 4984716: MemBars must be inserted before this3033// memory node in order to avoid a false3034// dependency which will confuse the scheduler.3035Node *mem = memory(alias_idx);30363037// For now, we handle only those cases that actually exist: ints,3038// longs, and Object. Adding others should be straightforward.3039Node* load_store = NULL;3040switch(type) {3041case T_INT:3042if (kind == LS_xadd) {3043load_store = _gvn.transform(new (C) GetAndAddINode(control(), mem, adr, newval, adr_type));3044} else if (kind == LS_xchg) {3045load_store = _gvn.transform(new (C) GetAndSetINode(control(), mem, adr, newval, adr_type));3046} else if (kind == LS_cmpxchg) {3047load_store = _gvn.transform(new (C) CompareAndSwapINode(control(), mem, adr, newval, oldval));3048} else {3049ShouldNotReachHere();3050}3051break;3052case T_LONG:3053if (kind == LS_xadd) {3054load_store = _gvn.transform(new (C) GetAndAddLNode(control(), mem, adr, newval, adr_type));3055} else if (kind == LS_xchg) {3056load_store = _gvn.transform(new (C) GetAndSetLNode(control(), mem, adr, newval, adr_type));3057} else if (kind == LS_cmpxchg) {3058load_store = _gvn.transform(new (C) CompareAndSwapLNode(control(), mem, adr, newval, oldval));3059} else {3060ShouldNotReachHere();3061}3062break;3063case T_OBJECT:3064// Transformation of a value which could be NULL pointer (CastPP #NULL)3065// could be delayed during Parse (for example, in adjust_map_after_if()).3066// Execute transformation here to avoid barrier generation in such case.3067if (_gvn.type(newval) == TypePtr::NULL_PTR)3068newval = _gvn.makecon(TypePtr::NULL_PTR);30693070// Reference stores need a store barrier.3071if (kind == LS_xchg) {3072// If pre-barrier must execute before the oop store, old value will require do_load here.3073if (!can_move_pre_barrier()) {3074pre_barrier(true /* do_load*/,3075control(), base, adr, alias_idx, newval, value_type->make_oopptr(),3076NULL /* pre_val*/,3077T_OBJECT);3078} // Else move pre_barrier to use load_store value, see below.3079} else if (kind == LS_cmpxchg) {3080// Same as for newval above:3081if (_gvn.type(oldval) == TypePtr::NULL_PTR) {3082oldval = _gvn.makecon(TypePtr::NULL_PTR);3083}3084// The only known value which might get overwritten is oldval.3085pre_barrier(false /* do_load */,3086control(), NULL, NULL, max_juint, NULL, NULL,3087oldval /* pre_val */,3088T_OBJECT);3089} else {3090ShouldNotReachHere();3091}30923093#ifdef _LP643094if (adr->bottom_type()->is_ptr_to_narrowoop()) {3095Node *newval_enc = _gvn.transform(new (C) EncodePNode(newval, newval->bottom_type()->make_narrowoop()));3096if (kind == LS_xchg) {3097load_store = _gvn.transform(new (C) GetAndSetNNode(control(), mem, adr,3098newval_enc, adr_type, value_type->make_narrowoop()));3099} else {3100assert(kind == LS_cmpxchg, "wrong LoadStore operation");3101Node *oldval_enc = _gvn.transform(new (C) EncodePNode(oldval, oldval->bottom_type()->make_narrowoop()));3102load_store = _gvn.transform(new (C) CompareAndSwapNNode(control(), mem, adr,3103newval_enc, oldval_enc));3104}3105} else3106#endif3107{3108if (kind == LS_xchg) {3109load_store = _gvn.transform(new (C) GetAndSetPNode(control(), mem, adr, newval, adr_type, value_type->is_oopptr()));3110} else {3111assert(kind == LS_cmpxchg, "wrong LoadStore operation");3112load_store = _gvn.transform(new (C) CompareAndSwapPNode(control(), mem, adr, newval, oldval));3113}3114}3115post_barrier(control(), load_store, base, adr, alias_idx, newval, T_OBJECT, true);3116break;3117default:3118fatal(err_msg_res("unexpected type %d: %s", type, type2name(type)));3119break;3120}31213122// SCMemProjNodes represent the memory state of a LoadStore. Their3123// main role is to prevent LoadStore nodes from being optimized away3124// when their results aren't used.3125Node* proj = _gvn.transform(new (C) SCMemProjNode(load_store));3126set_memory(proj, alias_idx);31273128Node* access = load_store;31293130if (type == T_OBJECT && kind == LS_xchg) {3131#ifdef _LP643132if (adr->bottom_type()->is_ptr_to_narrowoop()) {3133load_store = _gvn.transform(new (C) DecodeNNode(load_store, load_store->get_ptr_type()));3134}3135#endif3136#if INCLUDE_ALL_GCS3137if (UseShenandoahGC) {3138load_store = ShenandoahBarrierSetC2::bsc2()->load_reference_barrier(this, load_store);3139}3140#endif3141if (can_move_pre_barrier()) {3142// Don't need to load pre_val. The old value is returned by load_store.3143// The pre_barrier can execute after the xchg as long as no safepoint3144// gets inserted between them.3145pre_barrier(false /* do_load */,3146control(), NULL, NULL, max_juint, NULL, NULL,3147load_store /* pre_val */,3148T_OBJECT);3149}3150}31513152// Add the trailing membar surrounding the access3153insert_mem_bar(Op_MemBarCPUOrder);3154Node* mb = insert_mem_bar(Op_MemBarAcquire, access);3155MemBarNode::set_load_store_pair(leading_membar->as_MemBar(), mb->as_MemBar());31563157assert(type2size[load_store->bottom_type()->basic_type()] == type2size[rtype], "result type should match");3158set_result(load_store);3159return true;3160}31613162//----------------------------inline_unsafe_ordered_store----------------------3163// public native void sun.misc.Unsafe.putOrderedObject(Object o, long offset, Object x);3164// public native void sun.misc.Unsafe.putOrderedInt(Object o, long offset, int x);3165// public native void sun.misc.Unsafe.putOrderedLong(Object o, long offset, long x);3166bool LibraryCallKit::inline_unsafe_ordered_store(BasicType type) {3167// This is another variant of inline_unsafe_access, differing in3168// that it always issues store-store ("release") barrier and ensures3169// store-atomicity (which only matters for "long").31703171if (callee()->is_static()) return false; // caller must have the capability!31723173#ifndef PRODUCT3174{3175ResourceMark rm;3176// Check the signatures.3177ciSignature* sig = callee()->signature();3178#ifdef ASSERT3179BasicType rtype = sig->return_type()->basic_type();3180assert(rtype == T_VOID, "must return void");3181assert(sig->count() == 3, "has 3 arguments");3182assert(sig->type_at(0)->basic_type() == T_OBJECT, "base is object");3183assert(sig->type_at(1)->basic_type() == T_LONG, "offset is long");3184#endif // ASSERT3185}3186#endif //PRODUCT31873188C->set_has_unsafe_access(true); // Mark eventual nmethod as "unsafe".31893190// Get arguments:3191Node* receiver = argument(0); // type: oop3192Node* base = argument(1); // type: oop3193Node* offset = argument(2); // type: long3194Node* val = argument(4); // type: oop, int, or long31953196// Null check receiver.3197receiver = null_check(receiver);3198if (stopped()) {3199return true;3200}32013202// Build field offset expression.3203assert(Unsafe_field_offset_to_byte_offset(11) == 11, "fieldOffset must be byte-scaled");3204// 32-bit machines ignore the high half of long offsets3205offset = ConvL2X(offset);3206Node* adr = make_unsafe_address(base, offset);3207const TypePtr *adr_type = _gvn.type(adr)->isa_ptr();3208const Type *value_type = Type::get_const_basic_type(type);3209Compile::AliasType* alias_type = C->alias_type(adr_type);32103211insert_mem_bar(Op_MemBarRelease);3212insert_mem_bar(Op_MemBarCPUOrder);3213// Ensure that the store is atomic for longs:3214const bool require_atomic_access = true;3215Node* store;3216if (type == T_OBJECT) // reference stores need a store barrier.3217store = store_oop_to_unknown(control(), base, adr, adr_type, val, type, MemNode::release);3218else {3219store = store_to_memory(control(), adr, val, type, adr_type, MemNode::release, require_atomic_access);3220}3221insert_mem_bar(Op_MemBarCPUOrder);3222return true;3223}32243225bool LibraryCallKit::inline_unsafe_fence(vmIntrinsics::ID id) {3226// Regardless of form, don't allow previous ld/st to move down,3227// then issue acquire, release, or volatile mem_bar.3228insert_mem_bar(Op_MemBarCPUOrder);3229switch(id) {3230case vmIntrinsics::_loadFence:3231insert_mem_bar(Op_LoadFence);3232return true;3233case vmIntrinsics::_storeFence:3234insert_mem_bar(Op_StoreFence);3235return true;3236case vmIntrinsics::_fullFence:3237insert_mem_bar(Op_MemBarVolatile);3238return true;3239default:3240fatal_unexpected_iid(id);3241return false;3242}3243}32443245bool LibraryCallKit::klass_needs_init_guard(Node* kls) {3246if (!kls->is_Con()) {3247return true;3248}3249const TypeKlassPtr* klsptr = kls->bottom_type()->isa_klassptr();3250if (klsptr == NULL) {3251return true;3252}3253ciInstanceKlass* ik = klsptr->klass()->as_instance_klass();3254// don't need a guard for a klass that is already initialized3255return !ik->is_initialized();3256}32573258//----------------------------inline_unsafe_allocate---------------------------3259// public native Object sun.misc.Unsafe.allocateInstance(Class<?> cls);3260bool LibraryCallKit::inline_unsafe_allocate() {3261if (callee()->is_static()) return false; // caller must have the capability!32623263null_check_receiver(); // null-check, then ignore3264Node* cls = null_check(argument(1));3265if (stopped()) return true;32663267Node* kls = load_klass_from_mirror(cls, false, NULL, 0);3268kls = null_check(kls);3269if (stopped()) return true; // argument was like int.class32703271Node* test = NULL;3272if (LibraryCallKit::klass_needs_init_guard(kls)) {3273// Note: The argument might still be an illegal value like3274// Serializable.class or Object[].class. The runtime will handle it.3275// But we must make an explicit check for initialization.3276Node* insp = basic_plus_adr(kls, in_bytes(InstanceKlass::init_state_offset()));3277// Use T_BOOLEAN for InstanceKlass::_init_state so the compiler3278// can generate code to load it as unsigned byte.3279Node* inst = make_load(NULL, insp, TypeInt::UBYTE, T_BOOLEAN, MemNode::unordered);3280Node* bits = intcon(InstanceKlass::fully_initialized);3281test = _gvn.transform(new (C) SubINode(inst, bits));3282// The 'test' is non-zero if we need to take a slow path.3283}32843285Node* obj = new_instance(kls, test);3286set_result(obj);3287return true;3288}32893290#ifdef JFR_HAVE_INTRINSICS3291/*3292* oop -> myklass3293* myklass->trace_id |= USED3294* return myklass->trace_id & ~0x33295*/3296bool LibraryCallKit::inline_native_classID() {3297Node* cls = null_check(argument(0), T_OBJECT);3298Node* kls = load_klass_from_mirror(cls, false, NULL, 0);3299kls = null_check(kls, T_OBJECT);33003301ByteSize offset = KLASS_TRACE_ID_OFFSET;3302Node* insp = basic_plus_adr(kls, in_bytes(offset));3303Node* tvalue = make_load(NULL, insp, TypeLong::LONG, T_LONG, MemNode::unordered);33043305Node* clsused = longcon(0x01l); // set the class bit3306Node* orl = _gvn.transform(new (C) OrLNode(tvalue, clsused));3307const TypePtr *adr_type = _gvn.type(insp)->isa_ptr();3308store_to_memory(control(), insp, orl, T_LONG, adr_type, MemNode::unordered);33093310#ifdef TRACE_ID_META_BITS3311Node* mbits = longcon(~TRACE_ID_META_BITS);3312tvalue = _gvn.transform(new (C) AndLNode(tvalue, mbits));3313#endif3314#ifdef TRACE_ID_SHIFT3315Node* cbits = intcon(TRACE_ID_SHIFT);3316tvalue = _gvn.transform(new (C) URShiftLNode(tvalue, cbits));3317#endif33183319set_result(tvalue);3320return true;3321}33223323bool LibraryCallKit::inline_native_getEventWriter() {3324Node* tls_ptr = _gvn.transform(new (C) ThreadLocalNode());33253326Node* jobj_ptr = basic_plus_adr(top(), tls_ptr,3327in_bytes(THREAD_LOCAL_WRITER_OFFSET_JFR)3328);33293330Node* jobj = make_load(control(), jobj_ptr, TypeRawPtr::BOTTOM, T_ADDRESS, MemNode::unordered);33313332Node* jobj_cmp_null = _gvn.transform( new (C) CmpPNode(jobj, null()) );3333Node* test_jobj_eq_null = _gvn.transform( new (C) BoolNode(jobj_cmp_null, BoolTest::eq) );33343335IfNode* iff_jobj_null =3336create_and_map_if(control(), test_jobj_eq_null, PROB_MIN, COUNT_UNKNOWN);33373338enum { _normal_path = 1,3339_null_path = 2,3340PATH_LIMIT };33413342RegionNode* result_rgn = new (C) RegionNode(PATH_LIMIT);3343PhiNode* result_val = new (C) PhiNode(result_rgn, TypePtr::BOTTOM);33443345Node* jobj_is_null = _gvn.transform(new (C) IfTrueNode(iff_jobj_null));3346result_rgn->init_req(_null_path, jobj_is_null);3347result_val->init_req(_null_path, null());33483349Node* jobj_is_not_null = _gvn.transform(new (C) IfFalseNode(iff_jobj_null));3350result_rgn->init_req(_normal_path, jobj_is_not_null);33513352Node* res = make_load(jobj_is_not_null, jobj, TypeInstPtr::NOTNULL, T_OBJECT, MemNode::unordered);3353result_val->init_req(_normal_path, res);33543355set_result(result_rgn, result_val);33563357return true;3358}3359#endif // JFR_HAVE_INTRINSICS33603361//------------------------inline_native_time_funcs--------------3362// inline code for System.currentTimeMillis() and System.nanoTime()3363// these have the same type and signature3364bool LibraryCallKit::inline_native_time_funcs(address funcAddr, const char* funcName) {3365const TypeFunc* tf = OptoRuntime::void_long_Type();3366const TypePtr* no_memory_effects = NULL;3367Node* time = make_runtime_call(RC_LEAF, tf, funcAddr, funcName, no_memory_effects);3368Node* value = _gvn.transform(new (C) ProjNode(time, TypeFunc::Parms+0));3369#ifdef ASSERT3370Node* value_top = _gvn.transform(new (C) ProjNode(time, TypeFunc::Parms+1));3371assert(value_top == top(), "second value must be top");3372#endif3373set_result(value);3374return true;3375}33763377//------------------------inline_native_currentThread------------------3378bool LibraryCallKit::inline_native_currentThread() {3379Node* junk = NULL;3380set_result(generate_current_thread(junk));3381return true;3382}33833384//------------------------inline_native_isInterrupted------------------3385// private native boolean java.lang.Thread.isInterrupted(boolean ClearInterrupted);3386bool LibraryCallKit::inline_native_isInterrupted() {3387// Add a fast path to t.isInterrupted(clear_int):3388// (t == Thread.current() &&3389// (!TLS._osthread._interrupted || WINDOWS_ONLY(false) NOT_WINDOWS(!clear_int)))3390// ? TLS._osthread._interrupted : /*slow path:*/ t.isInterrupted(clear_int)3391// So, in the common case that the interrupt bit is false,3392// we avoid making a call into the VM. Even if the interrupt bit3393// is true, if the clear_int argument is false, we avoid the VM call.3394// However, if the receiver is not currentThread, we must call the VM,3395// because there must be some locking done around the operation.33963397// We only go to the fast case code if we pass two guards.3398// Paths which do not pass are accumulated in the slow_region.33993400enum {3401no_int_result_path = 1, // t == Thread.current() && !TLS._osthread._interrupted3402no_clear_result_path = 2, // t == Thread.current() && TLS._osthread._interrupted && !clear_int3403slow_result_path = 3, // slow path: t.isInterrupted(clear_int)3404PATH_LIMIT3405};34063407// Ensure that it's not possible to move the load of TLS._osthread._interrupted flag3408// out of the function.3409insert_mem_bar(Op_MemBarCPUOrder);34103411RegionNode* result_rgn = new (C) RegionNode(PATH_LIMIT);3412PhiNode* result_val = new (C) PhiNode(result_rgn, TypeInt::BOOL);34133414RegionNode* slow_region = new (C) RegionNode(1);3415record_for_igvn(slow_region);34163417// (a) Receiving thread must be the current thread.3418Node* rec_thr = argument(0);3419Node* tls_ptr = NULL;3420Node* cur_thr = generate_current_thread(tls_ptr);3421Node* cmp_thr = _gvn.transform(new (C) CmpPNode(cur_thr, rec_thr));3422Node* bol_thr = _gvn.transform(new (C) BoolNode(cmp_thr, BoolTest::ne));34233424generate_slow_guard(bol_thr, slow_region);34253426// (b) Interrupt bit on TLS must be false.3427Node* p = basic_plus_adr(top()/*!oop*/, tls_ptr, in_bytes(JavaThread::osthread_offset()));3428Node* osthread = make_load(NULL, p, TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered);3429p = basic_plus_adr(top()/*!oop*/, osthread, in_bytes(OSThread::interrupted_offset()));34303431// Set the control input on the field _interrupted read to prevent it floating up.3432Node* int_bit = make_load(control(), p, TypeInt::BOOL, T_INT, MemNode::unordered);3433Node* cmp_bit = _gvn.transform(new (C) CmpINode(int_bit, intcon(0)));3434Node* bol_bit = _gvn.transform(new (C) BoolNode(cmp_bit, BoolTest::ne));34353436IfNode* iff_bit = create_and_map_if(control(), bol_bit, PROB_UNLIKELY_MAG(3), COUNT_UNKNOWN);34373438// First fast path: if (!TLS._interrupted) return false;3439Node* false_bit = _gvn.transform(new (C) IfFalseNode(iff_bit));3440result_rgn->init_req(no_int_result_path, false_bit);3441result_val->init_req(no_int_result_path, intcon(0));34423443// drop through to next case3444set_control( _gvn.transform(new (C) IfTrueNode(iff_bit)));34453446#ifndef TARGET_OS_FAMILY_windows3447// (c) Or, if interrupt bit is set and clear_int is false, use 2nd fast path.3448Node* clr_arg = argument(1);3449Node* cmp_arg = _gvn.transform(new (C) CmpINode(clr_arg, intcon(0)));3450Node* bol_arg = _gvn.transform(new (C) BoolNode(cmp_arg, BoolTest::ne));3451IfNode* iff_arg = create_and_map_if(control(), bol_arg, PROB_FAIR, COUNT_UNKNOWN);34523453// Second fast path: ... else if (!clear_int) return true;3454Node* false_arg = _gvn.transform(new (C) IfFalseNode(iff_arg));3455result_rgn->init_req(no_clear_result_path, false_arg);3456result_val->init_req(no_clear_result_path, intcon(1));34573458// drop through to next case3459set_control( _gvn.transform(new (C) IfTrueNode(iff_arg)));3460#else3461// To return true on Windows you must read the _interrupted field3462// and check the the event state i.e. take the slow path.3463#endif // TARGET_OS_FAMILY_windows34643465// (d) Otherwise, go to the slow path.3466slow_region->add_req(control());3467set_control( _gvn.transform(slow_region));34683469if (stopped()) {3470// There is no slow path.3471result_rgn->init_req(slow_result_path, top());3472result_val->init_req(slow_result_path, top());3473} else {3474// non-virtual because it is a private non-static3475CallJavaNode* slow_call = generate_method_call(vmIntrinsics::_isInterrupted);34763477Node* slow_val = set_results_for_java_call(slow_call);3478// this->control() comes from set_results_for_java_call34793480Node* fast_io = slow_call->in(TypeFunc::I_O);3481Node* fast_mem = slow_call->in(TypeFunc::Memory);34823483// These two phis are pre-filled with copies of of the fast IO and Memory3484PhiNode* result_mem = PhiNode::make(result_rgn, fast_mem, Type::MEMORY, TypePtr::BOTTOM);3485PhiNode* result_io = PhiNode::make(result_rgn, fast_io, Type::ABIO);34863487result_rgn->init_req(slow_result_path, control());3488result_io ->init_req(slow_result_path, i_o());3489result_mem->init_req(slow_result_path, reset_memory());3490result_val->init_req(slow_result_path, slow_val);34913492set_all_memory(_gvn.transform(result_mem));3493set_i_o( _gvn.transform(result_io));3494}34953496C->set_has_split_ifs(true); // Has chance for split-if optimization3497set_result(result_rgn, result_val);3498return true;3499}35003501//---------------------------load_mirror_from_klass----------------------------3502// Given a klass oop, load its java mirror (a java.lang.Class oop).3503Node* LibraryCallKit::load_mirror_from_klass(Node* klass) {3504Node* p = basic_plus_adr(klass, in_bytes(Klass::java_mirror_offset()));3505return make_load(NULL, p, TypeInstPtr::MIRROR, T_OBJECT, MemNode::unordered);3506}35073508//-----------------------load_klass_from_mirror_common-------------------------3509// Given a java mirror (a java.lang.Class oop), load its corresponding klass oop.3510// Test the klass oop for null (signifying a primitive Class like Integer.TYPE),3511// and branch to the given path on the region.3512// If never_see_null, take an uncommon trap on null, so we can optimistically3513// compile for the non-null case.3514// If the region is NULL, force never_see_null = true.3515Node* LibraryCallKit::load_klass_from_mirror_common(Node* mirror,3516bool never_see_null,3517RegionNode* region,3518int null_path,3519int offset) {3520if (region == NULL) never_see_null = true;3521Node* p = basic_plus_adr(mirror, offset);3522const TypeKlassPtr* kls_type = TypeKlassPtr::OBJECT_OR_NULL;3523Node* kls = _gvn.transform(LoadKlassNode::make(_gvn, NULL, immutable_memory(), p, TypeRawPtr::BOTTOM, kls_type));3524Node* null_ctl = top();3525kls = null_check_oop(kls, &null_ctl, never_see_null);3526if (region != NULL) {3527// Set region->in(null_path) if the mirror is a primitive (e.g, int.class).3528region->init_req(null_path, null_ctl);3529} else {3530assert(null_ctl == top(), "no loose ends");3531}3532return kls;3533}35343535//--------------------(inline_native_Class_query helpers)---------------------3536// Use this for JVM_ACC_INTERFACE, JVM_ACC_IS_CLONEABLE, JVM_ACC_HAS_FINALIZER.3537// Fall through if (mods & mask) == bits, take the guard otherwise.3538Node* LibraryCallKit::generate_access_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region) {3539// Branch around if the given klass has the given modifier bit set.3540// Like generate_guard, adds a new path onto the region.3541Node* modp = basic_plus_adr(kls, in_bytes(Klass::access_flags_offset()));3542Node* mods = make_load(NULL, modp, TypeInt::INT, T_INT, MemNode::unordered);3543Node* mask = intcon(modifier_mask);3544Node* bits = intcon(modifier_bits);3545Node* mbit = _gvn.transform(new (C) AndINode(mods, mask));3546Node* cmp = _gvn.transform(new (C) CmpINode(mbit, bits));3547Node* bol = _gvn.transform(new (C) BoolNode(cmp, BoolTest::ne));3548return generate_fair_guard(bol, region);3549}3550Node* LibraryCallKit::generate_interface_guard(Node* kls, RegionNode* region) {3551return generate_access_flags_guard(kls, JVM_ACC_INTERFACE, 0, region);3552}35533554//-------------------------inline_native_Class_query-------------------3555bool LibraryCallKit::inline_native_Class_query(vmIntrinsics::ID id) {3556const Type* return_type = TypeInt::BOOL;3557Node* prim_return_value = top(); // what happens if it's a primitive class?3558bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);3559bool expect_prim = false; // most of these guys expect to work on refs35603561enum { _normal_path = 1, _prim_path = 2, PATH_LIMIT };35623563Node* mirror = argument(0);3564Node* obj = top();35653566switch (id) {3567case vmIntrinsics::_isInstance:3568// nothing is an instance of a primitive type3569prim_return_value = intcon(0);3570obj = argument(1);3571break;3572case vmIntrinsics::_getModifiers:3573prim_return_value = intcon(JVM_ACC_ABSTRACT | JVM_ACC_FINAL | JVM_ACC_PUBLIC);3574assert(is_power_of_2((int)JVM_ACC_WRITTEN_FLAGS+1), "change next line");3575return_type = TypeInt::make(0, JVM_ACC_WRITTEN_FLAGS, Type::WidenMin);3576break;3577case vmIntrinsics::_isInterface:3578prim_return_value = intcon(0);3579break;3580case vmIntrinsics::_isArray:3581prim_return_value = intcon(0);3582expect_prim = true; // cf. ObjectStreamClass.getClassSignature3583break;3584case vmIntrinsics::_isPrimitive:3585prim_return_value = intcon(1);3586expect_prim = true; // obviously3587break;3588case vmIntrinsics::_getSuperclass:3589prim_return_value = null();3590return_type = TypeInstPtr::MIRROR->cast_to_ptr_type(TypePtr::BotPTR);3591break;3592case vmIntrinsics::_getComponentType:3593prim_return_value = null();3594return_type = TypeInstPtr::MIRROR->cast_to_ptr_type(TypePtr::BotPTR);3595break;3596case vmIntrinsics::_getClassAccessFlags:3597prim_return_value = intcon(JVM_ACC_ABSTRACT | JVM_ACC_FINAL | JVM_ACC_PUBLIC);3598return_type = TypeInt::INT; // not bool! 62970943599break;3600default:3601fatal_unexpected_iid(id);3602break;3603}36043605const TypeInstPtr* mirror_con = _gvn.type(mirror)->isa_instptr();3606if (mirror_con == NULL) return false; // cannot happen?36073608#ifndef PRODUCT3609if (C->print_intrinsics() || C->print_inlining()) {3610ciType* k = mirror_con->java_mirror_type();3611if (k) {3612tty->print("Inlining %s on constant Class ", vmIntrinsics::name_at(intrinsic_id()));3613k->print_name();3614tty->cr();3615}3616}3617#endif36183619// Null-check the mirror, and the mirror's klass ptr (in case it is a primitive).3620RegionNode* region = new (C) RegionNode(PATH_LIMIT);3621record_for_igvn(region);3622PhiNode* phi = new (C) PhiNode(region, return_type);36233624// The mirror will never be null of Reflection.getClassAccessFlags, however3625// it may be null for Class.isInstance or Class.getModifiers. Throw a NPE3626// if it is. See bug 4774291.36273628// For Reflection.getClassAccessFlags(), the null check occurs in3629// the wrong place; see inline_unsafe_access(), above, for a similar3630// situation.3631mirror = null_check(mirror);3632// If mirror or obj is dead, only null-path is taken.3633if (stopped()) return true;36343635if (expect_prim) never_see_null = false; // expect nulls (meaning prims)36363637// Now load the mirror's klass metaobject, and null-check it.3638// Side-effects region with the control path if the klass is null.3639Node* kls = load_klass_from_mirror(mirror, never_see_null, region, _prim_path);3640// If kls is null, we have a primitive mirror.3641phi->init_req(_prim_path, prim_return_value);3642if (stopped()) { set_result(region, phi); return true; }3643bool safe_for_replace = (region->in(_prim_path) == top());36443645Node* p; // handy temp3646Node* null_ctl;36473648// Now that we have the non-null klass, we can perform the real query.3649// For constant classes, the query will constant-fold in LoadNode::Value.3650Node* query_value = top();3651switch (id) {3652case vmIntrinsics::_isInstance:3653// nothing is an instance of a primitive type3654query_value = gen_instanceof(obj, kls, safe_for_replace);3655break;36563657case vmIntrinsics::_getModifiers:3658p = basic_plus_adr(kls, in_bytes(Klass::modifier_flags_offset()));3659query_value = make_load(NULL, p, TypeInt::INT, T_INT, MemNode::unordered);3660break;36613662case vmIntrinsics::_isInterface:3663// (To verify this code sequence, check the asserts in JVM_IsInterface.)3664if (generate_interface_guard(kls, region) != NULL)3665// A guard was added. If the guard is taken, it was an interface.3666phi->add_req(intcon(1));3667// If we fall through, it's a plain class.3668query_value = intcon(0);3669break;36703671case vmIntrinsics::_isArray:3672// (To verify this code sequence, check the asserts in JVM_IsArrayClass.)3673if (generate_array_guard(kls, region) != NULL)3674// A guard was added. If the guard is taken, it was an array.3675phi->add_req(intcon(1));3676// If we fall through, it's a plain class.3677query_value = intcon(0);3678break;36793680case vmIntrinsics::_isPrimitive:3681query_value = intcon(0); // "normal" path produces false3682break;36833684case vmIntrinsics::_getSuperclass:3685// The rules here are somewhat unfortunate, but we can still do better3686// with random logic than with a JNI call.3687// Interfaces store null or Object as _super, but must report null.3688// Arrays store an intermediate super as _super, but must report Object.3689// Other types can report the actual _super.3690// (To verify this code sequence, check the asserts in JVM_IsInterface.)3691if (generate_interface_guard(kls, region) != NULL)3692// A guard was added. If the guard is taken, it was an interface.3693phi->add_req(null());3694if (generate_array_guard(kls, region) != NULL)3695// A guard was added. If the guard is taken, it was an array.3696phi->add_req(makecon(TypeInstPtr::make(env()->Object_klass()->java_mirror())));3697// If we fall through, it's a plain class. Get its _super.3698p = basic_plus_adr(kls, in_bytes(Klass::super_offset()));3699kls = _gvn.transform(LoadKlassNode::make(_gvn, NULL, immutable_memory(), p, TypeRawPtr::BOTTOM, TypeKlassPtr::OBJECT_OR_NULL));3700null_ctl = top();3701kls = null_check_oop(kls, &null_ctl);3702if (null_ctl != top()) {3703// If the guard is taken, Object.superClass is null (both klass and mirror).3704region->add_req(null_ctl);3705phi ->add_req(null());3706}3707if (!stopped()) {3708query_value = load_mirror_from_klass(kls);3709}3710break;37113712case vmIntrinsics::_getComponentType:3713if (generate_array_guard(kls, region) != NULL) {3714// Be sure to pin the oop load to the guard edge just created:3715Node* is_array_ctrl = region->in(region->req()-1);3716Node* cma = basic_plus_adr(kls, in_bytes(ArrayKlass::component_mirror_offset()));3717Node* cmo = make_load(is_array_ctrl, cma, TypeInstPtr::MIRROR, T_OBJECT, MemNode::unordered);3718phi->add_req(cmo);3719}3720query_value = null(); // non-array case is null3721break;37223723case vmIntrinsics::_getClassAccessFlags:3724p = basic_plus_adr(kls, in_bytes(Klass::access_flags_offset()));3725query_value = make_load(NULL, p, TypeInt::INT, T_INT, MemNode::unordered);3726break;37273728default:3729fatal_unexpected_iid(id);3730break;3731}37323733// Fall-through is the normal case of a query to a real class.3734phi->init_req(1, query_value);3735region->init_req(1, control());37363737C->set_has_split_ifs(true); // Has chance for split-if optimization3738set_result(region, phi);3739return true;3740}37413742//--------------------------inline_native_subtype_check------------------------3743// This intrinsic takes the JNI calls out of the heart of3744// UnsafeFieldAccessorImpl.set, which improves Field.set, readObject, etc.3745bool LibraryCallKit::inline_native_subtype_check() {3746// Pull both arguments off the stack.3747Node* args[2]; // two java.lang.Class mirrors: superc, subc3748args[0] = argument(0);3749args[1] = argument(1);3750Node* klasses[2]; // corresponding Klasses: superk, subk3751klasses[0] = klasses[1] = top();37523753enum {3754// A full decision tree on {superc is prim, subc is prim}:3755_prim_0_path = 1, // {P,N} => false3756// {P,P} & superc!=subc => false3757_prim_same_path, // {P,P} & superc==subc => true3758_prim_1_path, // {N,P} => false3759_ref_subtype_path, // {N,N} & subtype check wins => true3760_both_ref_path, // {N,N} & subtype check loses => false3761PATH_LIMIT3762};37633764RegionNode* region = new (C) RegionNode(PATH_LIMIT);3765Node* phi = new (C) PhiNode(region, TypeInt::BOOL);3766record_for_igvn(region);37673768const TypePtr* adr_type = TypeRawPtr::BOTTOM; // memory type of loads3769const TypeKlassPtr* kls_type = TypeKlassPtr::OBJECT_OR_NULL;3770int class_klass_offset = java_lang_Class::klass_offset_in_bytes();37713772// First null-check both mirrors and load each mirror's klass metaobject.3773int which_arg;3774for (which_arg = 0; which_arg <= 1; which_arg++) {3775Node* arg = args[which_arg];3776arg = null_check(arg);3777if (stopped()) break;3778args[which_arg] = arg;37793780Node* p = basic_plus_adr(arg, class_klass_offset);3781Node* kls = LoadKlassNode::make(_gvn, NULL, immutable_memory(), p, adr_type, kls_type);3782klasses[which_arg] = _gvn.transform(kls);3783}37843785// Having loaded both klasses, test each for null.3786bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);3787for (which_arg = 0; which_arg <= 1; which_arg++) {3788Node* kls = klasses[which_arg];3789Node* null_ctl = top();3790kls = null_check_oop(kls, &null_ctl, never_see_null);3791int prim_path = (which_arg == 0 ? _prim_0_path : _prim_1_path);3792region->init_req(prim_path, null_ctl);3793if (stopped()) break;3794klasses[which_arg] = kls;3795}37963797if (!stopped()) {3798// now we have two reference types, in klasses[0..1]3799Node* subk = klasses[1]; // the argument to isAssignableFrom3800Node* superk = klasses[0]; // the receiver3801region->set_req(_both_ref_path, gen_subtype_check(subk, superk));3802// now we have a successful reference subtype check3803region->set_req(_ref_subtype_path, control());3804}38053806// If both operands are primitive (both klasses null), then3807// we must return true when they are identical primitives.3808// It is convenient to test this after the first null klass check.3809set_control(region->in(_prim_0_path)); // go back to first null check3810if (!stopped()) {3811// Since superc is primitive, make a guard for the superc==subc case.3812Node* cmp_eq = _gvn.transform(new (C) CmpPNode(args[0], args[1]));3813Node* bol_eq = _gvn.transform(new (C) BoolNode(cmp_eq, BoolTest::eq));3814generate_guard(bol_eq, region, PROB_FAIR);3815if (region->req() == PATH_LIMIT+1) {3816// A guard was added. If the added guard is taken, superc==subc.3817region->swap_edges(PATH_LIMIT, _prim_same_path);3818region->del_req(PATH_LIMIT);3819}3820region->set_req(_prim_0_path, control()); // Not equal after all.3821}38223823// these are the only paths that produce 'true':3824phi->set_req(_prim_same_path, intcon(1));3825phi->set_req(_ref_subtype_path, intcon(1));38263827// pull together the cases:3828assert(region->req() == PATH_LIMIT, "sane region");3829for (uint i = 1; i < region->req(); i++) {3830Node* ctl = region->in(i);3831if (ctl == NULL || ctl == top()) {3832region->set_req(i, top());3833phi ->set_req(i, top());3834} else if (phi->in(i) == NULL) {3835phi->set_req(i, intcon(0)); // all other paths produce 'false'3836}3837}38383839set_control(_gvn.transform(region));3840set_result(_gvn.transform(phi));3841return true;3842}38433844//---------------------generate_array_guard_common------------------------3845Node* LibraryCallKit::generate_array_guard_common(Node* kls, RegionNode* region,3846bool obj_array, bool not_array) {3847// If obj_array/non_array==false/false:3848// Branch around if the given klass is in fact an array (either obj or prim).3849// If obj_array/non_array==false/true:3850// Branch around if the given klass is not an array klass of any kind.3851// If obj_array/non_array==true/true:3852// Branch around if the kls is not an oop array (kls is int[], String, etc.)3853// If obj_array/non_array==true/false:3854// Branch around if the kls is an oop array (Object[] or subtype)3855//3856// Like generate_guard, adds a new path onto the region.3857jint layout_con = 0;3858Node* layout_val = get_layout_helper(kls, layout_con);3859if (layout_val == NULL) {3860bool query = (obj_array3861? Klass::layout_helper_is_objArray(layout_con)3862: Klass::layout_helper_is_array(layout_con));3863if (query == not_array) {3864return NULL; // never a branch3865} else { // always a branch3866Node* always_branch = control();3867if (region != NULL)3868region->add_req(always_branch);3869set_control(top());3870return always_branch;3871}3872}3873// Now test the correct condition.3874jint nval = (obj_array3875? (jint)(Klass::_lh_array_tag_type_value3876<< Klass::_lh_array_tag_shift)3877: Klass::_lh_neutral_value);3878Node* cmp = _gvn.transform(new(C) CmpINode(layout_val, intcon(nval)));3879BoolTest::mask btest = BoolTest::lt; // correct for testing is_[obj]array3880// invert the test if we are looking for a non-array3881if (not_array) btest = BoolTest(btest).negate();3882Node* bol = _gvn.transform(new(C) BoolNode(cmp, btest));3883return generate_fair_guard(bol, region);3884}388538863887//-----------------------inline_native_newArray--------------------------3888// private static native Object java.lang.reflect.newArray(Class<?> componentType, int length);3889bool LibraryCallKit::inline_native_newArray() {3890Node* mirror = argument(0);3891Node* count_val = argument(1);38923893mirror = null_check(mirror);3894// If mirror or obj is dead, only null-path is taken.3895if (stopped()) return true;38963897enum { _normal_path = 1, _slow_path = 2, PATH_LIMIT };3898RegionNode* result_reg = new(C) RegionNode(PATH_LIMIT);3899PhiNode* result_val = new(C) PhiNode(result_reg,3900TypeInstPtr::NOTNULL);3901PhiNode* result_io = new(C) PhiNode(result_reg, Type::ABIO);3902PhiNode* result_mem = new(C) PhiNode(result_reg, Type::MEMORY,3903TypePtr::BOTTOM);39043905bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);3906Node* klass_node = load_array_klass_from_mirror(mirror, never_see_null,3907result_reg, _slow_path);3908Node* normal_ctl = control();3909Node* no_array_ctl = result_reg->in(_slow_path);39103911// Generate code for the slow case. We make a call to newArray().3912set_control(no_array_ctl);3913if (!stopped()) {3914// Either the input type is void.class, or else the3915// array klass has not yet been cached. Either the3916// ensuing call will throw an exception, or else it3917// will cache the array klass for next time.3918PreserveJVMState pjvms(this);3919CallJavaNode* slow_call = generate_method_call_static(vmIntrinsics::_newArray);3920Node* slow_result = set_results_for_java_call(slow_call);3921// this->control() comes from set_results_for_java_call3922result_reg->set_req(_slow_path, control());3923result_val->set_req(_slow_path, slow_result);3924result_io ->set_req(_slow_path, i_o());3925result_mem->set_req(_slow_path, reset_memory());3926}39273928set_control(normal_ctl);3929if (!stopped()) {3930// Normal case: The array type has been cached in the java.lang.Class.3931// The following call works fine even if the array type is polymorphic.3932// It could be a dynamic mix of int[], boolean[], Object[], etc.3933Node* obj = new_array(klass_node, count_val, 0); // no arguments to push3934result_reg->init_req(_normal_path, control());3935result_val->init_req(_normal_path, obj);3936result_io ->init_req(_normal_path, i_o());3937result_mem->init_req(_normal_path, reset_memory());3938}39393940// Return the combined state.3941set_i_o( _gvn.transform(result_io) );3942set_all_memory( _gvn.transform(result_mem));39433944C->set_has_split_ifs(true); // Has chance for split-if optimization3945set_result(result_reg, result_val);3946return true;3947}39483949//----------------------inline_native_getLength--------------------------3950// public static native int java.lang.reflect.Array.getLength(Object array);3951bool LibraryCallKit::inline_native_getLength() {3952if (too_many_traps(Deoptimization::Reason_intrinsic)) return false;39533954Node* array = null_check(argument(0));3955// If array is dead, only null-path is taken.3956if (stopped()) return true;39573958// Deoptimize if it is a non-array.3959Node* non_array = generate_non_array_guard(load_object_klass(array), NULL);39603961if (non_array != NULL) {3962PreserveJVMState pjvms(this);3963set_control(non_array);3964uncommon_trap(Deoptimization::Reason_intrinsic,3965Deoptimization::Action_maybe_recompile);3966}39673968// If control is dead, only non-array-path is taken.3969if (stopped()) return true;39703971// The works fine even if the array type is polymorphic.3972// It could be a dynamic mix of int[], boolean[], Object[], etc.3973Node* result = load_array_length(array);39743975C->set_has_split_ifs(true); // Has chance for split-if optimization3976set_result(result);3977return true;3978}39793980//------------------------inline_array_copyOf----------------------------3981// public static <T,U> T[] java.util.Arrays.copyOf( U[] original, int newLength, Class<? extends T[]> newType);3982// public static <T,U> T[] java.util.Arrays.copyOfRange(U[] original, int from, int to, Class<? extends T[]> newType);3983bool LibraryCallKit::inline_array_copyOf(bool is_copyOfRange) {3984if (too_many_traps(Deoptimization::Reason_intrinsic)) return false;39853986// Get the arguments.3987Node* original = argument(0);3988Node* start = is_copyOfRange? argument(1): intcon(0);3989Node* end = is_copyOfRange? argument(2): argument(1);3990Node* array_type_mirror = is_copyOfRange? argument(3): argument(2);39913992Node* newcopy = NULL;39933994// Set the original stack and the reexecute bit for the interpreter to reexecute3995// the bytecode that invokes Arrays.copyOf if deoptimization happens.3996{ PreserveReexecuteState preexecs(this);3997jvms()->set_should_reexecute(true);39983999array_type_mirror = null_check(array_type_mirror);4000original = null_check(original);40014002// Check if a null path was taken unconditionally.4003if (stopped()) return true;40044005Node* orig_length = load_array_length(original);40064007Node* klass_node = load_klass_from_mirror(array_type_mirror, false, NULL, 0);4008klass_node = null_check(klass_node);40094010RegionNode* bailout = new (C) RegionNode(1);4011record_for_igvn(bailout);40124013// Despite the generic type of Arrays.copyOf, the mirror might be int, int[], etc.4014// Bail out if that is so.4015Node* not_objArray = generate_non_objArray_guard(klass_node, bailout);4016if (not_objArray != NULL) {4017// Improve the klass node's type from the new optimistic assumption:4018ciKlass* ak = ciArrayKlass::make(env()->Object_klass());4019const Type* akls = TypeKlassPtr::make(TypePtr::NotNull, ak, 0/*offset*/);4020Node* cast = new (C) CastPPNode(klass_node, akls);4021cast->init_req(0, control());4022klass_node = _gvn.transform(cast);4023}40244025// Bail out if either start or end is negative.4026generate_negative_guard(start, bailout, &start);4027generate_negative_guard(end, bailout, &end);40284029Node* length = end;4030if (_gvn.type(start) != TypeInt::ZERO) {4031length = _gvn.transform(new (C) SubINode(end, start));4032}40334034// Bail out if length is negative.4035// Without this the new_array would throw4036// NegativeArraySizeException but IllegalArgumentException is what4037// should be thrown4038generate_negative_guard(length, bailout, &length);40394040if (bailout->req() > 1) {4041PreserveJVMState pjvms(this);4042set_control(_gvn.transform(bailout));4043uncommon_trap(Deoptimization::Reason_intrinsic,4044Deoptimization::Action_maybe_recompile);4045}40464047if (!stopped()) {4048// How many elements will we copy from the original?4049// The answer is MinI(orig_length - start, length).4050Node* orig_tail = _gvn.transform(new (C) SubINode(orig_length, start));4051Node* moved = generate_min_max(vmIntrinsics::_min, orig_tail, length);40524053newcopy = new_array(klass_node, length, 0); // no argments to push40544055// Generate a direct call to the right arraycopy function(s).4056// We know the copy is disjoint but we might not know if the4057// oop stores need checking.4058// Extreme case: Arrays.copyOf((Integer[])x, 10, String[].class).4059// This will fail a store-check if x contains any non-nulls.4060bool disjoint_bases = true;4061// if start > orig_length then the length of the copy may be4062// negative.4063bool length_never_negative = !is_copyOfRange;4064generate_arraycopy(TypeAryPtr::OOPS, T_OBJECT,4065original, start, newcopy, intcon(0), moved,4066disjoint_bases, length_never_negative);4067}4068} // original reexecute is set back here40694070C->set_has_split_ifs(true); // Has chance for split-if optimization4071if (!stopped()) {4072set_result(newcopy);4073}4074return true;4075}407640774078//----------------------generate_virtual_guard---------------------------4079// Helper for hashCode and clone. Peeks inside the vtable to avoid a call.4080Node* LibraryCallKit::generate_virtual_guard(Node* obj_klass,4081RegionNode* slow_region) {4082ciMethod* method = callee();4083int vtable_index = method->vtable_index();4084assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index,4085err_msg_res("bad index %d", vtable_index));4086// Get the Method* out of the appropriate vtable entry.4087int entry_offset = (InstanceKlass::vtable_start_offset() +4088vtable_index*vtableEntry::size()) * wordSize +4089vtableEntry::method_offset_in_bytes();4090Node* entry_addr = basic_plus_adr(obj_klass, entry_offset);4091Node* target_call = make_load(NULL, entry_addr, TypePtr::NOTNULL, T_ADDRESS, MemNode::unordered);40924093// Compare the target method with the expected method (e.g., Object.hashCode).4094const TypePtr* native_call_addr = TypeMetadataPtr::make(method);40954096Node* native_call = makecon(native_call_addr);4097Node* chk_native = _gvn.transform(new(C) CmpPNode(target_call, native_call));4098Node* test_native = _gvn.transform(new(C) BoolNode(chk_native, BoolTest::ne));40994100return generate_slow_guard(test_native, slow_region);4101}41024103//-----------------------generate_method_call----------------------------4104// Use generate_method_call to make a slow-call to the real4105// method if the fast path fails. An alternative would be to4106// use a stub like OptoRuntime::slow_arraycopy_Java.4107// This only works for expanding the current library call,4108// not another intrinsic. (E.g., don't use this for making an4109// arraycopy call inside of the copyOf intrinsic.)4110CallJavaNode*4111LibraryCallKit::generate_method_call(vmIntrinsics::ID method_id, bool is_virtual, bool is_static) {4112// When compiling the intrinsic method itself, do not use this technique.4113guarantee(callee() != C->method(), "cannot make slow-call to self");41144115ciMethod* method = callee();4116// ensure the JVMS we have will be correct for this call4117guarantee(method_id == method->intrinsic_id(), "must match");41184119const TypeFunc* tf = TypeFunc::make(method);4120CallJavaNode* slow_call;4121if (is_static) {4122assert(!is_virtual, "");4123slow_call = new(C) CallStaticJavaNode(C, tf,4124SharedRuntime::get_resolve_static_call_stub(),4125method, bci());4126} else if (is_virtual) {4127null_check_receiver();4128int vtable_index = Method::invalid_vtable_index;4129if (UseInlineCaches) {4130// Suppress the vtable call4131} else {4132// hashCode and clone are not a miranda methods,4133// so the vtable index is fixed.4134// No need to use the linkResolver to get it.4135vtable_index = method->vtable_index();4136assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index,4137err_msg_res("bad index %d", vtable_index));4138}4139slow_call = new(C) CallDynamicJavaNode(tf,4140SharedRuntime::get_resolve_virtual_call_stub(),4141method, vtable_index, bci());4142} else { // neither virtual nor static: opt_virtual4143null_check_receiver();4144slow_call = new(C) CallStaticJavaNode(C, tf,4145SharedRuntime::get_resolve_opt_virtual_call_stub(),4146method, bci());4147slow_call->set_optimized_virtual(true);4148}4149set_arguments_for_java_call(slow_call);4150set_edges_for_java_call(slow_call);4151return slow_call;4152}415341544155/**4156* Build special case code for calls to hashCode on an object. This call may4157* be virtual (invokevirtual) or bound (invokespecial). For each case we generate4158* slightly different code.4159*/4160bool LibraryCallKit::inline_native_hashcode(bool is_virtual, bool is_static) {4161assert(is_static == callee()->is_static(), "correct intrinsic selection");4162assert(!(is_virtual && is_static), "either virtual, special, or static");41634164enum { _slow_path = 1, _fast_path, _null_path, PATH_LIMIT };41654166RegionNode* result_reg = new(C) RegionNode(PATH_LIMIT);4167PhiNode* result_val = new(C) PhiNode(result_reg, TypeInt::INT);4168PhiNode* result_io = new(C) PhiNode(result_reg, Type::ABIO);4169PhiNode* result_mem = new(C) PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);4170Node* obj = NULL;4171if (!is_static) {4172// Check for hashing null object4173obj = null_check_receiver();4174if (stopped()) return true; // unconditionally null4175result_reg->init_req(_null_path, top());4176result_val->init_req(_null_path, top());4177} else {4178// Do a null check, and return zero if null.4179// System.identityHashCode(null) == 04180obj = argument(0);4181Node* null_ctl = top();4182obj = null_check_oop(obj, &null_ctl);4183result_reg->init_req(_null_path, null_ctl);4184result_val->init_req(_null_path, _gvn.intcon(0));4185}41864187// Unconditionally null? Then return right away.4188if (stopped()) {4189set_control( result_reg->in(_null_path));4190if (!stopped())4191set_result(result_val->in(_null_path));4192return true;4193}41944195// We only go to the fast case code if we pass a number of guards. The4196// paths which do not pass are accumulated in the slow_region.4197RegionNode* slow_region = new (C) RegionNode(1);4198record_for_igvn(slow_region);41994200// If this is a virtual call, we generate a funny guard. We pull out4201// the vtable entry corresponding to hashCode() from the target object.4202// If the target method which we are calling happens to be the native4203// Object hashCode() method, we pass the guard. We do not need this4204// guard for non-virtual calls -- the caller is known to be the native4205// Object hashCode().4206if (is_virtual) {4207// After null check, get the object's klass.4208Node* obj_klass = load_object_klass(obj);4209generate_virtual_guard(obj_klass, slow_region);4210}42114212// Get the header out of the object, use LoadMarkNode when available4213Node* header_addr = basic_plus_adr(obj, oopDesc::mark_offset_in_bytes());4214// The control of the load must be NULL. Otherwise, the load can move before4215// the null check after castPP removal.4216Node* no_ctrl = NULL;4217Node* header = make_load(no_ctrl, header_addr, TypeX_X, TypeX_X->basic_type(), MemNode::unordered);42184219// Test the header to see if it is unlocked.4220Node* lock_mask = _gvn.MakeConX(markOopDesc::biased_lock_mask_in_place);4221Node* lmasked_header = _gvn.transform(new (C) AndXNode(header, lock_mask));4222Node* unlocked_val = _gvn.MakeConX(markOopDesc::unlocked_value);4223Node* chk_unlocked = _gvn.transform(new (C) CmpXNode( lmasked_header, unlocked_val));4224Node* test_unlocked = _gvn.transform(new (C) BoolNode( chk_unlocked, BoolTest::ne));42254226generate_slow_guard(test_unlocked, slow_region);42274228// Get the hash value and check to see that it has been properly assigned.4229// We depend on hash_mask being at most 32 bits and avoid the use of4230// hash_mask_in_place because it could be larger than 32 bits in a 64-bit4231// vm: see markOop.hpp.4232Node* hash_mask = _gvn.intcon(markOopDesc::hash_mask);4233Node* hash_shift = _gvn.intcon(markOopDesc::hash_shift);4234Node* hshifted_header= _gvn.transform(new (C) URShiftXNode(header, hash_shift));4235// This hack lets the hash bits live anywhere in the mark object now, as long4236// as the shift drops the relevant bits into the low 32 bits. Note that4237// Java spec says that HashCode is an int so there's no point in capturing4238// an 'X'-sized hashcode (32 in 32-bit build or 64 in 64-bit build).4239hshifted_header = ConvX2I(hshifted_header);4240Node* hash_val = _gvn.transform(new (C) AndINode(hshifted_header, hash_mask));42414242Node* no_hash_val = _gvn.intcon(markOopDesc::no_hash);4243Node* chk_assigned = _gvn.transform(new (C) CmpINode( hash_val, no_hash_val));4244Node* test_assigned = _gvn.transform(new (C) BoolNode( chk_assigned, BoolTest::eq));42454246generate_slow_guard(test_assigned, slow_region);42474248Node* init_mem = reset_memory();4249// fill in the rest of the null path:4250result_io ->init_req(_null_path, i_o());4251result_mem->init_req(_null_path, init_mem);42524253result_val->init_req(_fast_path, hash_val);4254result_reg->init_req(_fast_path, control());4255result_io ->init_req(_fast_path, i_o());4256result_mem->init_req(_fast_path, init_mem);42574258// Generate code for the slow case. We make a call to hashCode().4259set_control(_gvn.transform(slow_region));4260if (!stopped()) {4261// No need for PreserveJVMState, because we're using up the present state.4262set_all_memory(init_mem);4263vmIntrinsics::ID hashCode_id = is_static ? vmIntrinsics::_identityHashCode : vmIntrinsics::_hashCode;4264CallJavaNode* slow_call = generate_method_call(hashCode_id, is_virtual, is_static);4265Node* slow_result = set_results_for_java_call(slow_call);4266// this->control() comes from set_results_for_java_call4267result_reg->init_req(_slow_path, control());4268result_val->init_req(_slow_path, slow_result);4269result_io ->set_req(_slow_path, i_o());4270result_mem ->set_req(_slow_path, reset_memory());4271}42724273// Return the combined state.4274set_i_o( _gvn.transform(result_io) );4275set_all_memory( _gvn.transform(result_mem));42764277set_result(result_reg, result_val);4278return true;4279}42804281//---------------------------inline_native_getClass----------------------------4282// public final native Class<?> java.lang.Object.getClass();4283//4284// Build special case code for calls to getClass on an object.4285bool LibraryCallKit::inline_native_getClass() {4286Node* obj = null_check_receiver();4287if (stopped()) return true;4288set_result(load_mirror_from_klass(load_object_klass(obj)));4289return true;4290}42914292//-----------------inline_native_Reflection_getCallerClass---------------------4293// public static native Class<?> sun.reflect.Reflection.getCallerClass();4294//4295// In the presence of deep enough inlining, getCallerClass() becomes a no-op.4296//4297// NOTE: This code must perform the same logic as JVM_GetCallerClass4298// in that it must skip particular security frames and checks for4299// caller sensitive methods.4300bool LibraryCallKit::inline_native_Reflection_getCallerClass() {4301#ifndef PRODUCT4302if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {4303tty->print_cr("Attempting to inline sun.reflect.Reflection.getCallerClass");4304}4305#endif43064307if (!jvms()->has_method()) {4308#ifndef PRODUCT4309if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {4310tty->print_cr(" Bailing out because intrinsic was inlined at top level");4311}4312#endif4313return false;4314}43154316// Walk back up the JVM state to find the caller at the required4317// depth.4318JVMState* caller_jvms = jvms();43194320// Cf. JVM_GetCallerClass4321// NOTE: Start the loop at depth 1 because the current JVM state does4322// not include the Reflection.getCallerClass() frame.4323for (int n = 1; caller_jvms != NULL; caller_jvms = caller_jvms->caller(), n++) {4324ciMethod* m = caller_jvms->method();4325switch (n) {4326case 0:4327fatal("current JVM state does not include the Reflection.getCallerClass frame");4328break;4329case 1:4330// Frame 0 and 1 must be caller sensitive (see JVM_GetCallerClass).4331if (!m->caller_sensitive()) {4332#ifndef PRODUCT4333if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {4334tty->print_cr(" Bailing out: CallerSensitive annotation expected at frame %d", n);4335}4336#endif4337return false; // bail-out; let JVM_GetCallerClass do the work4338}4339break;4340default:4341if (!m->is_ignored_by_security_stack_walk()) {4342// We have reached the desired frame; return the holder class.4343// Acquire method holder as java.lang.Class and push as constant.4344ciInstanceKlass* caller_klass = caller_jvms->method()->holder();4345ciInstance* caller_mirror = caller_klass->java_mirror();4346set_result(makecon(TypeInstPtr::make(caller_mirror)));43474348#ifndef PRODUCT4349if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {4350tty->print_cr(" Succeeded: caller = %d) %s.%s, JVMS depth = %d", n, caller_klass->name()->as_utf8(), caller_jvms->method()->name()->as_utf8(), jvms()->depth());4351tty->print_cr(" JVM state at this point:");4352for (int i = jvms()->depth(), n = 1; i >= 1; i--, n++) {4353ciMethod* m = jvms()->of_depth(i)->method();4354tty->print_cr(" %d) %s.%s", n, m->holder()->name()->as_utf8(), m->name()->as_utf8());4355}4356}4357#endif4358return true;4359}4360break;4361}4362}43634364#ifndef PRODUCT4365if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {4366tty->print_cr(" Bailing out because caller depth exceeded inlining depth = %d", jvms()->depth());4367tty->print_cr(" JVM state at this point:");4368for (int i = jvms()->depth(), n = 1; i >= 1; i--, n++) {4369ciMethod* m = jvms()->of_depth(i)->method();4370tty->print_cr(" %d) %s.%s", n, m->holder()->name()->as_utf8(), m->name()->as_utf8());4371}4372}4373#endif43744375return false; // bail-out; let JVM_GetCallerClass do the work4376}43774378bool LibraryCallKit::inline_fp_conversions(vmIntrinsics::ID id) {4379Node* arg = argument(0);4380Node* result = NULL;43814382switch (id) {4383case vmIntrinsics::_floatToRawIntBits: result = new (C) MoveF2INode(arg); break;4384case vmIntrinsics::_intBitsToFloat: result = new (C) MoveI2FNode(arg); break;4385case vmIntrinsics::_doubleToRawLongBits: result = new (C) MoveD2LNode(arg); break;4386case vmIntrinsics::_longBitsToDouble: result = new (C) MoveL2DNode(arg); break;43874388case vmIntrinsics::_doubleToLongBits: {4389// two paths (plus control) merge in a wood4390RegionNode *r = new (C) RegionNode(3);4391Node *phi = new (C) PhiNode(r, TypeLong::LONG);43924393Node *cmpisnan = _gvn.transform(new (C) CmpDNode(arg, arg));4394// Build the boolean node4395Node *bolisnan = _gvn.transform(new (C) BoolNode(cmpisnan, BoolTest::ne));43964397// Branch either way.4398// NaN case is less traveled, which makes all the difference.4399IfNode *ifisnan = create_and_xform_if(control(), bolisnan, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);4400Node *opt_isnan = _gvn.transform(ifisnan);4401assert( opt_isnan->is_If(), "Expect an IfNode");4402IfNode *opt_ifisnan = (IfNode*)opt_isnan;4403Node *iftrue = _gvn.transform(new (C) IfTrueNode(opt_ifisnan));44044405set_control(iftrue);44064407static const jlong nan_bits = CONST64(0x7ff8000000000000);4408Node *slow_result = longcon(nan_bits); // return NaN4409phi->init_req(1, _gvn.transform( slow_result ));4410r->init_req(1, iftrue);44114412// Else fall through4413Node *iffalse = _gvn.transform(new (C) IfFalseNode(opt_ifisnan));4414set_control(iffalse);44154416phi->init_req(2, _gvn.transform(new (C) MoveD2LNode(arg)));4417r->init_req(2, iffalse);44184419// Post merge4420set_control(_gvn.transform(r));4421record_for_igvn(r);44224423C->set_has_split_ifs(true); // Has chance for split-if optimization4424result = phi;4425assert(result->bottom_type()->isa_long(), "must be");4426break;4427}44284429case vmIntrinsics::_floatToIntBits: {4430// two paths (plus control) merge in a wood4431RegionNode *r = new (C) RegionNode(3);4432Node *phi = new (C) PhiNode(r, TypeInt::INT);44334434Node *cmpisnan = _gvn.transform(new (C) CmpFNode(arg, arg));4435// Build the boolean node4436Node *bolisnan = _gvn.transform(new (C) BoolNode(cmpisnan, BoolTest::ne));44374438// Branch either way.4439// NaN case is less traveled, which makes all the difference.4440IfNode *ifisnan = create_and_xform_if(control(), bolisnan, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);4441Node *opt_isnan = _gvn.transform(ifisnan);4442assert( opt_isnan->is_If(), "Expect an IfNode");4443IfNode *opt_ifisnan = (IfNode*)opt_isnan;4444Node *iftrue = _gvn.transform(new (C) IfTrueNode(opt_ifisnan));44454446set_control(iftrue);44474448static const jint nan_bits = 0x7fc00000;4449Node *slow_result = makecon(TypeInt::make(nan_bits)); // return NaN4450phi->init_req(1, _gvn.transform( slow_result ));4451r->init_req(1, iftrue);44524453// Else fall through4454Node *iffalse = _gvn.transform(new (C) IfFalseNode(opt_ifisnan));4455set_control(iffalse);44564457phi->init_req(2, _gvn.transform(new (C) MoveF2INode(arg)));4458r->init_req(2, iffalse);44594460// Post merge4461set_control(_gvn.transform(r));4462record_for_igvn(r);44634464C->set_has_split_ifs(true); // Has chance for split-if optimization4465result = phi;4466assert(result->bottom_type()->isa_int(), "must be");4467break;4468}44694470default:4471fatal_unexpected_iid(id);4472break;4473}4474set_result(_gvn.transform(result));4475return true;4476}44774478#ifdef _LP644479#define XTOP ,top() /*additional argument*/4480#else //_LP644481#define XTOP /*no additional argument*/4482#endif //_LP6444834484//----------------------inline_unsafe_copyMemory-------------------------4485// public native void sun.misc.Unsafe.copyMemory(Object srcBase, long srcOffset, Object destBase, long destOffset, long bytes);4486bool LibraryCallKit::inline_unsafe_copyMemory() {4487if (callee()->is_static()) return false; // caller must have the capability!4488null_check_receiver(); // null-check receiver4489if (stopped()) return true;44904491C->set_has_unsafe_access(true); // Mark eventual nmethod as "unsafe".44924493Node* src_ptr = argument(1); // type: oop4494Node* src_off = ConvL2X(argument(2)); // type: long4495Node* dst_ptr = argument(4); // type: oop4496Node* dst_off = ConvL2X(argument(5)); // type: long4497Node* size = ConvL2X(argument(7)); // type: long44984499assert(Unsafe_field_offset_to_byte_offset(11) == 11,4500"fieldOffset must be byte-scaled");45014502Node* src = make_unsafe_address(src_ptr, src_off);4503Node* dst = make_unsafe_address(dst_ptr, dst_off);45044505// Conservatively insert a memory barrier on all memory slices.4506// Do not let writes of the copy source or destination float below the copy.4507insert_mem_bar(Op_MemBarCPUOrder);45084509// Call it. Note that the length argument is not scaled.4510make_runtime_call(RC_LEAF|RC_NO_FP,4511OptoRuntime::fast_arraycopy_Type(),4512StubRoutines::unsafe_arraycopy(),4513"unsafe_arraycopy",4514TypeRawPtr::BOTTOM,4515src, dst, size XTOP);45164517// Do not let reads of the copy destination float above the copy.4518insert_mem_bar(Op_MemBarCPUOrder);45194520return true;4521}45224523//------------------------clone_coping-----------------------------------4524// Helper function for inline_native_clone.4525void LibraryCallKit::copy_to_clone(Node* obj, Node* alloc_obj, Node* obj_size, bool is_array, bool card_mark) {4526assert(obj_size != NULL, "");4527Node* raw_obj = alloc_obj->in(1);4528assert(alloc_obj->is_CheckCastPP() && raw_obj->is_Proj() && raw_obj->in(0)->is_Allocate(), "");45294530AllocateNode* alloc = NULL;4531if (ReduceBulkZeroing) {4532// We will be completely responsible for initializing this object -4533// mark Initialize node as complete.4534alloc = AllocateNode::Ideal_allocation(alloc_obj, &_gvn);4535// The object was just allocated - there should be no any stores!4536guarantee(alloc != NULL && alloc->maybe_set_complete(&_gvn), "");4537// Mark as complete_with_arraycopy so that on AllocateNode4538// expansion, we know this AllocateNode is initialized by an array4539// copy and a StoreStore barrier exists after the array copy.4540alloc->initialization()->set_complete_with_arraycopy();4541}45424543// Copy the fastest available way.4544// TODO: generate fields copies for small objects instead.4545Node* src = obj;4546Node* dest = alloc_obj;4547Node* size = _gvn.transform(obj_size);45484549// Exclude the header but include array length to copy by 8 bytes words.4550// Can't use base_offset_in_bytes(bt) since basic type is unknown.4551int base_off = is_array ? arrayOopDesc::length_offset_in_bytes() :4552instanceOopDesc::base_offset_in_bytes();4553// base_off:4554// 8 - 32-bit VM4555// 12 - 64-bit VM, compressed klass4556// 16 - 64-bit VM, normal klass4557if (base_off % BytesPerLong != 0) {4558assert(UseCompressedClassPointers, "");4559if (is_array) {4560// Exclude length to copy by 8 bytes words.4561base_off += sizeof(int);4562} else {4563// Include klass to copy by 8 bytes words.4564base_off = instanceOopDesc::klass_offset_in_bytes();4565}4566assert(base_off % BytesPerLong == 0, "expect 8 bytes alignment");4567}4568src = basic_plus_adr(src, base_off);4569dest = basic_plus_adr(dest, base_off);45704571// Compute the length also, if needed:4572Node* countx = size;4573countx = _gvn.transform(new (C) SubXNode(countx, MakeConX(base_off)));4574countx = _gvn.transform(new (C) URShiftXNode(countx, intcon(LogBytesPerLong) ));45754576#if INCLUDE_ALL_GCS4577if (UseShenandoahGC && ShenandoahCloneBarrier) {4578assert (src->is_AddP(), "for clone the src should be the interior ptr");4579assert (dest->is_AddP(), "for clone the dst should be the interior ptr");45804581// Make sure that references in the cloned object are updated for Shenandoah.4582make_runtime_call(RC_LEAF|RC_NO_FP,4583OptoRuntime::shenandoah_clone_barrier_Type(),4584CAST_FROM_FN_PTR(address, ShenandoahRuntime::shenandoah_clone_barrier),4585"shenandoah_clone_barrier", TypePtr::BOTTOM,4586src->in(AddPNode::Base));4587}4588#endif45894590const TypePtr* raw_adr_type = TypeRawPtr::BOTTOM;4591bool disjoint_bases = true;4592generate_unchecked_arraycopy(raw_adr_type, T_LONG, disjoint_bases,4593src, NULL, dest, NULL, countx,4594/*dest_uninitialized*/true);45954596// If necessary, emit some card marks afterwards. (Non-arrays only.)4597if (card_mark) {4598assert(!is_array, "");4599// Put in store barrier for any and all oops we are sticking4600// into this object. (We could avoid this if we could prove4601// that the object type contains no oop fields at all.)4602Node* no_particular_value = NULL;4603Node* no_particular_field = NULL;4604int raw_adr_idx = Compile::AliasIdxRaw;4605post_barrier(control(),4606memory(raw_adr_type),4607alloc_obj,4608no_particular_field,4609raw_adr_idx,4610no_particular_value,4611T_OBJECT,4612false);4613}46144615// Do not let reads from the cloned object float above the arraycopy.4616if (alloc != NULL) {4617// Do not let stores that initialize this object be reordered with4618// a subsequent store that would make this object accessible by4619// other threads.4620// Record what AllocateNode this StoreStore protects so that4621// escape analysis can go from the MemBarStoreStoreNode to the4622// AllocateNode and eliminate the MemBarStoreStoreNode if possible4623// based on the escape status of the AllocateNode.4624insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out(AllocateNode::RawAddress));4625} else {4626insert_mem_bar(Op_MemBarCPUOrder);4627}4628}46294630//------------------------inline_native_clone----------------------------4631// protected native Object java.lang.Object.clone();4632//4633// Here are the simple edge cases:4634// null receiver => normal trap4635// virtual and clone was overridden => slow path to out-of-line clone4636// not cloneable or finalizer => slow path to out-of-line Object.clone4637//4638// The general case has two steps, allocation and copying.4639// Allocation has two cases, and uses GraphKit::new_instance or new_array.4640//4641// Copying also has two cases, oop arrays and everything else.4642// Oop arrays use arrayof_oop_arraycopy (same as System.arraycopy).4643// Everything else uses the tight inline loop supplied by CopyArrayNode.4644//4645// These steps fold up nicely if and when the cloned object's klass4646// can be sharply typed as an object array, a type array, or an instance.4647//4648bool LibraryCallKit::inline_native_clone(bool is_virtual) {4649PhiNode* result_val;46504651// Set the reexecute bit for the interpreter to reexecute4652// the bytecode that invokes Object.clone if deoptimization happens.4653{ PreserveReexecuteState preexecs(this);4654jvms()->set_should_reexecute(true);46554656Node* obj = null_check_receiver();4657if (stopped()) return true;46584659Node* obj_klass = load_object_klass(obj);4660const TypeKlassPtr* tklass = _gvn.type(obj_klass)->isa_klassptr();4661const TypeOopPtr* toop = ((tklass != NULL)4662? tklass->as_instance_type()4663: TypeInstPtr::NOTNULL);46644665// Conservatively insert a memory barrier on all memory slices.4666// Do not let writes into the original float below the clone.4667insert_mem_bar(Op_MemBarCPUOrder);46684669// paths into result_reg:4670enum {4671_slow_path = 1, // out-of-line call to clone method (virtual or not)4672_objArray_path, // plain array allocation, plus arrayof_oop_arraycopy4673_array_path, // plain array allocation, plus arrayof_long_arraycopy4674_instance_path, // plain instance allocation, plus arrayof_long_arraycopy4675PATH_LIMIT4676};4677RegionNode* result_reg = new(C) RegionNode(PATH_LIMIT);4678result_val = new(C) PhiNode(result_reg,4679TypeInstPtr::NOTNULL);4680PhiNode* result_i_o = new(C) PhiNode(result_reg, Type::ABIO);4681PhiNode* result_mem = new(C) PhiNode(result_reg, Type::MEMORY,4682TypePtr::BOTTOM);4683record_for_igvn(result_reg);46844685const TypePtr* raw_adr_type = TypeRawPtr::BOTTOM;4686int raw_adr_idx = Compile::AliasIdxRaw;46874688Node* array_ctl = generate_array_guard(obj_klass, (RegionNode*)NULL);4689if (array_ctl != NULL) {4690// It's an array.4691PreserveJVMState pjvms(this);4692set_control(array_ctl);4693Node* obj_length = load_array_length(obj);4694Node* obj_size = NULL;4695Node* alloc_obj = new_array(obj_klass, obj_length, 0, &obj_size); // no arguments to push46964697if (!use_ReduceInitialCardMarks()) {4698// If it is an oop array, it requires very special treatment,4699// because card marking is required on each card of the array.4700Node* is_obja = generate_objArray_guard(obj_klass, (RegionNode*)NULL);4701if (is_obja != NULL) {4702PreserveJVMState pjvms2(this);4703set_control(is_obja);4704// Generate a direct call to the right arraycopy function(s).4705bool disjoint_bases = true;4706bool length_never_negative = true;4707generate_arraycopy(TypeAryPtr::OOPS, T_OBJECT,4708obj, intcon(0), alloc_obj, intcon(0),4709obj_length,4710disjoint_bases, length_never_negative);4711result_reg->init_req(_objArray_path, control());4712result_val->init_req(_objArray_path, alloc_obj);4713result_i_o ->set_req(_objArray_path, i_o());4714result_mem ->set_req(_objArray_path, reset_memory());4715}4716}4717// Otherwise, there are no card marks to worry about.4718// (We can dispense with card marks if we know the allocation4719// comes out of eden (TLAB)... In fact, ReduceInitialCardMarks4720// causes the non-eden paths to take compensating steps to4721// simulate a fresh allocation, so that no further4722// card marks are required in compiled code to initialize4723// the object.)47244725if (!stopped()) {4726copy_to_clone(obj, alloc_obj, obj_size, true, false);47274728// Present the results of the copy.4729result_reg->init_req(_array_path, control());4730result_val->init_req(_array_path, alloc_obj);4731result_i_o ->set_req(_array_path, i_o());4732result_mem ->set_req(_array_path, reset_memory());4733}4734}47354736// We only go to the instance fast case code if we pass a number of guards.4737// The paths which do not pass are accumulated in the slow_region.4738RegionNode* slow_region = new (C) RegionNode(1);4739record_for_igvn(slow_region);4740if (!stopped()) {4741// It's an instance (we did array above). Make the slow-path tests.4742// If this is a virtual call, we generate a funny guard. We grab4743// the vtable entry corresponding to clone() from the target object.4744// If the target method which we are calling happens to be the4745// Object clone() method, we pass the guard. We do not need this4746// guard for non-virtual calls; the caller is known to be the native4747// Object clone().4748if (is_virtual) {4749generate_virtual_guard(obj_klass, slow_region);4750}47514752// The object must be cloneable and must not have a finalizer.4753// Both of these conditions may be checked in a single test.4754// We could optimize the cloneable test further, but we don't care.4755generate_access_flags_guard(obj_klass,4756// Test both conditions:4757JVM_ACC_IS_CLONEABLE | JVM_ACC_HAS_FINALIZER,4758// Must be cloneable but not finalizer:4759JVM_ACC_IS_CLONEABLE,4760slow_region);4761}47624763if (!stopped()) {4764// It's an instance, and it passed the slow-path tests.4765PreserveJVMState pjvms(this);4766Node* obj_size = NULL;4767// Need to deoptimize on exception from allocation since Object.clone intrinsic4768// is reexecuted if deoptimization occurs and there could be problems when merging4769// exception state between multiple Object.clone versions (reexecute=true vs reexecute=false).4770Node* alloc_obj = new_instance(obj_klass, NULL, &obj_size, /*deoptimize_on_exception=*/true);47714772copy_to_clone(obj, alloc_obj, obj_size, false, !use_ReduceInitialCardMarks());47734774// Present the results of the slow call.4775result_reg->init_req(_instance_path, control());4776result_val->init_req(_instance_path, alloc_obj);4777result_i_o ->set_req(_instance_path, i_o());4778result_mem ->set_req(_instance_path, reset_memory());4779}47804781// Generate code for the slow case. We make a call to clone().4782set_control(_gvn.transform(slow_region));4783if (!stopped()) {4784PreserveJVMState pjvms(this);4785CallJavaNode* slow_call = generate_method_call(vmIntrinsics::_clone, is_virtual);4786Node* slow_result = set_results_for_java_call(slow_call);4787// this->control() comes from set_results_for_java_call4788result_reg->init_req(_slow_path, control());4789result_val->init_req(_slow_path, slow_result);4790result_i_o ->set_req(_slow_path, i_o());4791result_mem ->set_req(_slow_path, reset_memory());4792}47934794// Return the combined state.4795set_control( _gvn.transform(result_reg));4796set_i_o( _gvn.transform(result_i_o));4797set_all_memory( _gvn.transform(result_mem));4798} // original reexecute is set back here47994800set_result(_gvn.transform(result_val));4801return true;4802}48034804//------------------------------basictype2arraycopy----------------------------4805address LibraryCallKit::basictype2arraycopy(BasicType t,4806Node* src_offset,4807Node* dest_offset,4808bool disjoint_bases,4809const char* &name,4810bool dest_uninitialized) {4811const TypeInt* src_offset_inttype = gvn().find_int_type(src_offset);;4812const TypeInt* dest_offset_inttype = gvn().find_int_type(dest_offset);;48134814bool aligned = false;4815bool disjoint = disjoint_bases;48164817// if the offsets are the same, we can treat the memory regions as4818// disjoint, because either the memory regions are in different arrays,4819// or they are identical (which we can treat as disjoint.) We can also4820// treat a copy with a destination index less that the source index4821// as disjoint since a low->high copy will work correctly in this case.4822if (src_offset_inttype != NULL && src_offset_inttype->is_con() &&4823dest_offset_inttype != NULL && dest_offset_inttype->is_con()) {4824// both indices are constants4825int s_offs = src_offset_inttype->get_con();4826int d_offs = dest_offset_inttype->get_con();4827int element_size = type2aelembytes(t);4828aligned = ((arrayOopDesc::base_offset_in_bytes(t) + s_offs * element_size) % HeapWordSize == 0) &&4829((arrayOopDesc::base_offset_in_bytes(t) + d_offs * element_size) % HeapWordSize == 0);4830if (s_offs >= d_offs) disjoint = true;4831} else if (src_offset == dest_offset && src_offset != NULL) {4832// This can occur if the offsets are identical non-constants.4833disjoint = true;4834}48354836return StubRoutines::select_arraycopy_function(t, aligned, disjoint, name, dest_uninitialized);4837}483848394840//------------------------------inline_arraycopy-----------------------4841// public static native void java.lang.System.arraycopy(Object src, int srcPos,4842// Object dest, int destPos,4843// int length);4844bool LibraryCallKit::inline_arraycopy() {4845// Get the arguments.4846Node* src = argument(0); // type: oop4847Node* src_offset = argument(1); // type: int4848Node* dest = argument(2); // type: oop4849Node* dest_offset = argument(3); // type: int4850Node* length = argument(4); // type: int48514852// Compile time checks. If any of these checks cannot be verified at compile time,4853// we do not make a fast path for this call. Instead, we let the call remain as it4854// is. The checks we choose to mandate at compile time are:4855//4856// (1) src and dest are arrays.4857const Type* src_type = src->Value(&_gvn);4858const Type* dest_type = dest->Value(&_gvn);4859const TypeAryPtr* top_src = src_type->isa_aryptr();4860const TypeAryPtr* top_dest = dest_type->isa_aryptr();48614862// Do we have the type of src?4863bool has_src = (top_src != NULL && top_src->klass() != NULL);4864// Do we have the type of dest?4865bool has_dest = (top_dest != NULL && top_dest->klass() != NULL);4866// Is the type for src from speculation?4867bool src_spec = false;4868// Is the type for dest from speculation?4869bool dest_spec = false;48704871if (!has_src || !has_dest) {4872// We don't have sufficient type information, let's see if4873// speculative types can help. We need to have types for both src4874// and dest so that it pays off.48754876// Do we already have or could we have type information for src4877bool could_have_src = has_src;4878// Do we already have or could we have type information for dest4879bool could_have_dest = has_dest;48804881ciKlass* src_k = NULL;4882if (!has_src) {4883src_k = src_type->speculative_type();4884if (src_k != NULL && src_k->is_array_klass()) {4885could_have_src = true;4886}4887}48884889ciKlass* dest_k = NULL;4890if (!has_dest) {4891dest_k = dest_type->speculative_type();4892if (dest_k != NULL && dest_k->is_array_klass()) {4893could_have_dest = true;4894}4895}48964897if (could_have_src && could_have_dest) {4898// This is going to pay off so emit the required guards4899if (!has_src) {4900src = maybe_cast_profiled_obj(src, src_k);4901src_type = _gvn.type(src);4902top_src = src_type->isa_aryptr();4903has_src = (top_src != NULL && top_src->klass() != NULL);4904src_spec = true;4905}4906if (!has_dest) {4907dest = maybe_cast_profiled_obj(dest, dest_k);4908dest_type = _gvn.type(dest);4909top_dest = dest_type->isa_aryptr();4910has_dest = (top_dest != NULL && top_dest->klass() != NULL);4911dest_spec = true;4912}4913}4914}49154916if (!has_src || !has_dest) {4917// Conservatively insert a memory barrier on all memory slices.4918// Do not let writes into the source float below the arraycopy.4919insert_mem_bar(Op_MemBarCPUOrder);49204921// Call StubRoutines::generic_arraycopy stub.4922generate_arraycopy(TypeRawPtr::BOTTOM, T_CONFLICT,4923src, src_offset, dest, dest_offset, length);49244925// Do not let reads from the destination float above the arraycopy.4926// Since we cannot type the arrays, we don't know which slices4927// might be affected. We could restrict this barrier only to those4928// memory slices which pertain to array elements--but don't bother.4929if (!InsertMemBarAfterArraycopy)4930// (If InsertMemBarAfterArraycopy, there is already one in place.)4931insert_mem_bar(Op_MemBarCPUOrder);4932return true;4933}49344935// (2) src and dest arrays must have elements of the same BasicType4936// Figure out the size and type of the elements we will be copying.4937BasicType src_elem = top_src->klass()->as_array_klass()->element_type()->basic_type();4938BasicType dest_elem = top_dest->klass()->as_array_klass()->element_type()->basic_type();4939if (src_elem == T_ARRAY) src_elem = T_OBJECT;4940if (dest_elem == T_ARRAY) dest_elem = T_OBJECT;49414942if (src_elem != dest_elem || dest_elem == T_VOID) {4943// The component types are not the same or are not recognized. Punt.4944// (But, avoid the native method wrapper to JVM_ArrayCopy.)4945generate_slow_arraycopy(TypePtr::BOTTOM,4946src, src_offset, dest, dest_offset, length,4947/*dest_uninitialized*/false);4948return true;4949}49504951if (src_elem == T_OBJECT) {4952// If both arrays are object arrays then having the exact types4953// for both will remove the need for a subtype check at runtime4954// before the call and may make it possible to pick a faster copy4955// routine (without a subtype check on every element)4956// Do we have the exact type of src?4957bool could_have_src = src_spec;4958// Do we have the exact type of dest?4959bool could_have_dest = dest_spec;4960ciKlass* src_k = top_src->klass();4961ciKlass* dest_k = top_dest->klass();4962if (!src_spec) {4963src_k = src_type->speculative_type();4964if (src_k != NULL && src_k->is_array_klass()) {4965could_have_src = true;4966}4967}4968if (!dest_spec) {4969dest_k = dest_type->speculative_type();4970if (dest_k != NULL && dest_k->is_array_klass()) {4971could_have_dest = true;4972}4973}4974if (could_have_src && could_have_dest) {4975// If we can have both exact types, emit the missing guards4976if (could_have_src && !src_spec) {4977src = maybe_cast_profiled_obj(src, src_k);4978}4979if (could_have_dest && !dest_spec) {4980dest = maybe_cast_profiled_obj(dest, dest_k);4981}4982}4983}49844985//---------------------------------------------------------------------------4986// We will make a fast path for this call to arraycopy.49874988// We have the following tests left to perform:4989//4990// (3) src and dest must not be null.4991// (4) src_offset must not be negative.4992// (5) dest_offset must not be negative.4993// (6) length must not be negative.4994// (7) src_offset + length must not exceed length of src.4995// (8) dest_offset + length must not exceed length of dest.4996// (9) each element of an oop array must be assignable49974998RegionNode* slow_region = new (C) RegionNode(1);4999record_for_igvn(slow_region);50005001// (3) operands must not be null5002// We currently perform our null checks with the null_check routine.5003// This means that the null exceptions will be reported in the caller5004// rather than (correctly) reported inside of the native arraycopy call.5005// This should be corrected, given time. We do our null check with the5006// stack pointer restored.5007src = null_check(src, T_ARRAY);5008dest = null_check(dest, T_ARRAY);50095010// (4) src_offset must not be negative.5011generate_negative_guard(src_offset, slow_region);50125013// (5) dest_offset must not be negative.5014generate_negative_guard(dest_offset, slow_region);50155016// (6) length must not be negative (moved to generate_arraycopy()).5017// generate_negative_guard(length, slow_region);50185019// (7) src_offset + length must not exceed length of src.5020generate_limit_guard(src_offset, length,5021load_array_length(src),5022slow_region);50235024// (8) dest_offset + length must not exceed length of dest.5025generate_limit_guard(dest_offset, length,5026load_array_length(dest),5027slow_region);50285029// (9) each element of an oop array must be assignable5030// The generate_arraycopy subroutine checks this.50315032// This is where the memory effects are placed:5033const TypePtr* adr_type = TypeAryPtr::get_array_body_type(dest_elem);5034generate_arraycopy(adr_type, dest_elem,5035src, src_offset, dest, dest_offset, length,5036false, false, slow_region);50375038return true;5039}50405041//-----------------------------generate_arraycopy----------------------5042// Generate an optimized call to arraycopy.5043// Caller must guard against non-arrays.5044// Caller must determine a common array basic-type for both arrays.5045// Caller must validate offsets against array bounds.5046// The slow_region has already collected guard failure paths5047// (such as out of bounds length or non-conformable array types).5048// The generated code has this shape, in general:5049//5050// if (length == 0) return // via zero_path5051// slowval = -15052// if (types unknown) {5053// slowval = call generic copy loop5054// if (slowval == 0) return // via checked_path5055// } else if (indexes in bounds) {5056// if ((is object array) && !(array type check)) {5057// slowval = call checked copy loop5058// if (slowval == 0) return // via checked_path5059// } else {5060// call bulk copy loop5061// return // via fast_path5062// }5063// }5064// // adjust params for remaining work:5065// if (slowval != -1) {5066// n = -1^slowval; src_offset += n; dest_offset += n; length -= n5067// }5068// slow_region:5069// call slow arraycopy(src, src_offset, dest, dest_offset, length)5070// return // via slow_call_path5071//5072// This routine is used from several intrinsics: System.arraycopy,5073// Object.clone (the array subcase), and Arrays.copyOf[Range].5074//5075void5076LibraryCallKit::generate_arraycopy(const TypePtr* adr_type,5077BasicType basic_elem_type,5078Node* src, Node* src_offset,5079Node* dest, Node* dest_offset,5080Node* copy_length,5081bool disjoint_bases,5082bool length_never_negative,5083RegionNode* slow_region) {50845085if (slow_region == NULL) {5086slow_region = new(C) RegionNode(1);5087record_for_igvn(slow_region);5088}50895090Node* original_dest = dest;5091AllocateArrayNode* alloc = NULL; // used for zeroing, if needed5092bool dest_uninitialized = false;50935094// See if this is the initialization of a newly-allocated array.5095// If so, we will take responsibility here for initializing it to zero.5096// (Note: Because tightly_coupled_allocation performs checks on the5097// out-edges of the dest, we need to avoid making derived pointers5098// from it until we have checked its uses.)5099if (ReduceBulkZeroing5100&& !ZeroTLAB // pointless if already zeroed5101&& basic_elem_type != T_CONFLICT // avoid corner case5102&& !src->eqv_uncast(dest)5103&& ((alloc = tightly_coupled_allocation(dest, slow_region))5104!= NULL)5105&& _gvn.find_int_con(alloc->in(AllocateNode::ALength), 1) > 05106&& alloc->maybe_set_complete(&_gvn)) {5107// "You break it, you buy it."5108InitializeNode* init = alloc->initialization();5109assert(init->is_complete(), "we just did this");5110init->set_complete_with_arraycopy();5111assert(dest->is_CheckCastPP(), "sanity");5112assert(dest->in(0)->in(0) == init, "dest pinned");5113adr_type = TypeRawPtr::BOTTOM; // all initializations are into raw memory5114// From this point on, every exit path is responsible for5115// initializing any non-copied parts of the object to zero.5116// Also, if this flag is set we make sure that arraycopy interacts properly5117// with G1, eliding pre-barriers. See CR 6627983.5118dest_uninitialized = true;5119} else {5120// No zeroing elimination here.5121alloc = NULL;5122//original_dest = dest;5123//dest_uninitialized = false;5124}51255126// Results are placed here:5127enum { fast_path = 1, // normal void-returning assembly stub5128checked_path = 2, // special assembly stub with cleanup5129slow_call_path = 3, // something went wrong; call the VM5130zero_path = 4, // bypass when length of copy is zero5131bcopy_path = 5, // copy primitive array by 64-bit blocks5132PATH_LIMIT = 65133};5134RegionNode* result_region = new(C) RegionNode(PATH_LIMIT);5135PhiNode* result_i_o = new(C) PhiNode(result_region, Type::ABIO);5136PhiNode* result_memory = new(C) PhiNode(result_region, Type::MEMORY, adr_type);5137record_for_igvn(result_region);5138_gvn.set_type_bottom(result_i_o);5139_gvn.set_type_bottom(result_memory);5140assert(adr_type != TypePtr::BOTTOM, "must be RawMem or a T[] slice");51415142// The slow_control path:5143Node* slow_control;5144Node* slow_i_o = i_o();5145Node* slow_mem = memory(adr_type);5146debug_only(slow_control = (Node*) badAddress);51475148// Checked control path:5149Node* checked_control = top();5150Node* checked_mem = NULL;5151Node* checked_i_o = NULL;5152Node* checked_value = NULL;51535154if (basic_elem_type == T_CONFLICT) {5155assert(!dest_uninitialized, "");5156Node* cv = generate_generic_arraycopy(adr_type,5157src, src_offset, dest, dest_offset,5158copy_length, dest_uninitialized);5159if (cv == NULL) cv = intcon(-1); // failure (no stub available)5160checked_control = control();5161checked_i_o = i_o();5162checked_mem = memory(adr_type);5163checked_value = cv;5164set_control(top()); // no fast path5165}51665167Node* not_pos = generate_nonpositive_guard(copy_length, length_never_negative);5168if (not_pos != NULL) {5169PreserveJVMState pjvms(this);5170set_control(not_pos);51715172// (6) length must not be negative.5173if (!length_never_negative) {5174generate_negative_guard(copy_length, slow_region);5175}51765177// copy_length is 0.5178if (!stopped() && dest_uninitialized) {5179Node* dest_length = alloc->in(AllocateNode::ALength);5180if (copy_length->eqv_uncast(dest_length)5181|| _gvn.find_int_con(dest_length, 1) <= 0) {5182// There is no zeroing to do. No need for a secondary raw memory barrier.5183} else {5184// Clear the whole thing since there are no source elements to copy.5185generate_clear_array(adr_type, dest, basic_elem_type,5186intcon(0), NULL,5187alloc->in(AllocateNode::AllocSize));5188// Use a secondary InitializeNode as raw memory barrier.5189// Currently it is needed only on this path since other5190// paths have stub or runtime calls as raw memory barriers.5191InitializeNode* init = insert_mem_bar_volatile(Op_Initialize,5192Compile::AliasIdxRaw,5193top())->as_Initialize();5194init->set_complete(&_gvn); // (there is no corresponding AllocateNode)5195}5196}51975198// Present the results of the fast call.5199result_region->init_req(zero_path, control());5200result_i_o ->init_req(zero_path, i_o());5201result_memory->init_req(zero_path, memory(adr_type));5202}52035204if (!stopped() && dest_uninitialized) {5205// We have to initialize the *uncopied* part of the array to zero.5206// The copy destination is the slice dest[off..off+len]. The other slices5207// are dest_head = dest[0..off] and dest_tail = dest[off+len..dest.length].5208Node* dest_size = alloc->in(AllocateNode::AllocSize);5209Node* dest_length = alloc->in(AllocateNode::ALength);5210Node* dest_tail = _gvn.transform(new(C) AddINode(dest_offset,5211copy_length));52125213// If there is a head section that needs zeroing, do it now.5214if (find_int_con(dest_offset, -1) != 0) {5215generate_clear_array(adr_type, dest, basic_elem_type,5216intcon(0), dest_offset,5217NULL);5218}52195220// Next, perform a dynamic check on the tail length.5221// It is often zero, and we can win big if we prove this.5222// There are two wins: Avoid generating the ClearArray5223// with its attendant messy index arithmetic, and upgrade5224// the copy to a more hardware-friendly word size of 64 bits.5225Node* tail_ctl = NULL;5226if (!stopped() && !dest_tail->eqv_uncast(dest_length)) {5227Node* cmp_lt = _gvn.transform(new(C) CmpINode(dest_tail, dest_length));5228Node* bol_lt = _gvn.transform(new(C) BoolNode(cmp_lt, BoolTest::lt));5229tail_ctl = generate_slow_guard(bol_lt, NULL);5230assert(tail_ctl != NULL || !stopped(), "must be an outcome");5231}52325233// At this point, let's assume there is no tail.5234if (!stopped() && alloc != NULL && basic_elem_type != T_OBJECT) {5235// There is no tail. Try an upgrade to a 64-bit copy.5236bool didit = false;5237{ PreserveJVMState pjvms(this);5238didit = generate_block_arraycopy(adr_type, basic_elem_type, alloc,5239src, src_offset, dest, dest_offset,5240dest_size, dest_uninitialized);5241if (didit) {5242// Present the results of the block-copying fast call.5243result_region->init_req(bcopy_path, control());5244result_i_o ->init_req(bcopy_path, i_o());5245result_memory->init_req(bcopy_path, memory(adr_type));5246}5247}5248if (didit)5249set_control(top()); // no regular fast path5250}52515252// Clear the tail, if any.5253if (tail_ctl != NULL) {5254Node* notail_ctl = stopped() ? NULL : control();5255set_control(tail_ctl);5256if (notail_ctl == NULL) {5257generate_clear_array(adr_type, dest, basic_elem_type,5258dest_tail, NULL,5259dest_size);5260} else {5261// Make a local merge.5262Node* done_ctl = new(C) RegionNode(3);5263Node* done_mem = new(C) PhiNode(done_ctl, Type::MEMORY, adr_type);5264done_ctl->init_req(1, notail_ctl);5265done_mem->init_req(1, memory(adr_type));5266generate_clear_array(adr_type, dest, basic_elem_type,5267dest_tail, NULL,5268dest_size);5269done_ctl->init_req(2, control());5270done_mem->init_req(2, memory(adr_type));5271set_control( _gvn.transform(done_ctl));5272set_memory( _gvn.transform(done_mem), adr_type );5273}5274}5275}52765277BasicType copy_type = basic_elem_type;5278assert(basic_elem_type != T_ARRAY, "caller must fix this");5279if (!stopped() && copy_type == T_OBJECT) {5280// If src and dest have compatible element types, we can copy bits.5281// Types S[] and D[] are compatible if D is a supertype of S.5282//5283// If they are not, we will use checked_oop_disjoint_arraycopy,5284// which performs a fast optimistic per-oop check, and backs off5285// further to JVM_ArrayCopy on the first per-oop check that fails.5286// (Actually, we don't move raw bits only; the GC requires card marks.)52875288// Get the Klass* for both src and dest5289Node* src_klass = load_object_klass(src);5290Node* dest_klass = load_object_klass(dest);52915292// Generate the subtype check.5293// This might fold up statically, or then again it might not.5294//5295// Non-static example: Copying List<String>.elements to a new String[].5296// The backing store for a List<String> is always an Object[],5297// but its elements are always type String, if the generic types5298// are correct at the source level.5299//5300// Test S[] against D[], not S against D, because (probably)5301// the secondary supertype cache is less busy for S[] than S.5302// This usually only matters when D is an interface.5303Node* not_subtype_ctrl = gen_subtype_check(src_klass, dest_klass);5304// Plug failing path into checked_oop_disjoint_arraycopy5305if (not_subtype_ctrl != top()) {5306PreserveJVMState pjvms(this);5307set_control(not_subtype_ctrl);5308// (At this point we can assume disjoint_bases, since types differ.)5309int ek_offset = in_bytes(ObjArrayKlass::element_klass_offset());5310Node* p1 = basic_plus_adr(dest_klass, ek_offset);5311Node* n1 = LoadKlassNode::make(_gvn, NULL, immutable_memory(), p1, TypeRawPtr::BOTTOM);5312Node* dest_elem_klass = _gvn.transform(n1);5313Node* cv = generate_checkcast_arraycopy(adr_type,5314dest_elem_klass,5315src, src_offset, dest, dest_offset,5316ConvI2X(copy_length), dest_uninitialized);5317if (cv == NULL) cv = intcon(-1); // failure (no stub available)5318checked_control = control();5319checked_i_o = i_o();5320checked_mem = memory(adr_type);5321checked_value = cv;5322}5323// At this point we know we do not need type checks on oop stores.53245325// Let's see if we need card marks:5326if (alloc != NULL && use_ReduceInitialCardMarks() && ! UseShenandoahGC) {5327// If we do not need card marks, copy using the jint or jlong stub.5328copy_type = LP64_ONLY(UseCompressedOops ? T_INT : T_LONG) NOT_LP64(T_INT);5329assert(type2aelembytes(basic_elem_type) == type2aelembytes(copy_type),5330"sizes agree");5331}5332}53335334if (!stopped()) {5335// Generate the fast path, if possible.5336PreserveJVMState pjvms(this);5337generate_unchecked_arraycopy(adr_type, copy_type, disjoint_bases,5338src, src_offset, dest, dest_offset,5339ConvI2X(copy_length), dest_uninitialized);53405341// Present the results of the fast call.5342result_region->init_req(fast_path, control());5343result_i_o ->init_req(fast_path, i_o());5344result_memory->init_req(fast_path, memory(adr_type));5345}53465347// Here are all the slow paths up to this point, in one bundle:5348slow_control = top();5349if (slow_region != NULL)5350slow_control = _gvn.transform(slow_region);5351DEBUG_ONLY(slow_region = (RegionNode*)badAddress);53525353set_control(checked_control);5354if (!stopped()) {5355// Clean up after the checked call.5356// The returned value is either 0 or -1^K,5357// where K = number of partially transferred array elements.5358Node* cmp = _gvn.transform(new(C) CmpINode(checked_value, intcon(0)));5359Node* bol = _gvn.transform(new(C) BoolNode(cmp, BoolTest::eq));5360IfNode* iff = create_and_map_if(control(), bol, PROB_MAX, COUNT_UNKNOWN);53615362// If it is 0, we are done, so transfer to the end.5363Node* checks_done = _gvn.transform(new(C) IfTrueNode(iff));5364result_region->init_req(checked_path, checks_done);5365result_i_o ->init_req(checked_path, checked_i_o);5366result_memory->init_req(checked_path, checked_mem);53675368// If it is not zero, merge into the slow call.5369set_control( _gvn.transform(new(C) IfFalseNode(iff) ));5370RegionNode* slow_reg2 = new(C) RegionNode(3);5371PhiNode* slow_i_o2 = new(C) PhiNode(slow_reg2, Type::ABIO);5372PhiNode* slow_mem2 = new(C) PhiNode(slow_reg2, Type::MEMORY, adr_type);5373record_for_igvn(slow_reg2);5374slow_reg2 ->init_req(1, slow_control);5375slow_i_o2 ->init_req(1, slow_i_o);5376slow_mem2 ->init_req(1, slow_mem);5377slow_reg2 ->init_req(2, control());5378slow_i_o2 ->init_req(2, checked_i_o);5379slow_mem2 ->init_req(2, checked_mem);53805381slow_control = _gvn.transform(slow_reg2);5382slow_i_o = _gvn.transform(slow_i_o2);5383slow_mem = _gvn.transform(slow_mem2);53845385if (alloc != NULL) {5386// We'll restart from the very beginning, after zeroing the whole thing.5387// This can cause double writes, but that's OK since dest is brand new.5388// So we ignore the low 31 bits of the value returned from the stub.5389} else {5390// We must continue the copy exactly where it failed, or else5391// another thread might see the wrong number of writes to dest.5392Node* checked_offset = _gvn.transform(new(C) XorINode(checked_value, intcon(-1)));5393Node* slow_offset = new(C) PhiNode(slow_reg2, TypeInt::INT);5394slow_offset->init_req(1, intcon(0));5395slow_offset->init_req(2, checked_offset);5396slow_offset = _gvn.transform(slow_offset);53975398// Adjust the arguments by the conditionally incoming offset.5399Node* src_off_plus = _gvn.transform(new(C) AddINode(src_offset, slow_offset));5400Node* dest_off_plus = _gvn.transform(new(C) AddINode(dest_offset, slow_offset));5401Node* length_minus = _gvn.transform(new(C) SubINode(copy_length, slow_offset));54025403// Tweak the node variables to adjust the code produced below:5404src_offset = src_off_plus;5405dest_offset = dest_off_plus;5406copy_length = length_minus;5407}5408}54095410set_control(slow_control);5411if (!stopped()) {5412// Generate the slow path, if needed.5413PreserveJVMState pjvms(this); // replace_in_map may trash the map54145415set_memory(slow_mem, adr_type);5416set_i_o(slow_i_o);54175418if (dest_uninitialized) {5419generate_clear_array(adr_type, dest, basic_elem_type,5420intcon(0), NULL,5421alloc->in(AllocateNode::AllocSize));5422}54235424generate_slow_arraycopy(adr_type,5425src, src_offset, dest, dest_offset,5426copy_length, /*dest_uninitialized*/false);54275428result_region->init_req(slow_call_path, control());5429result_i_o ->init_req(slow_call_path, i_o());5430result_memory->init_req(slow_call_path, memory(adr_type));5431}54325433// Remove unused edges.5434for (uint i = 1; i < result_region->req(); i++) {5435if (result_region->in(i) == NULL)5436result_region->init_req(i, top());5437}54385439// Finished; return the combined state.5440set_control( _gvn.transform(result_region));5441set_i_o( _gvn.transform(result_i_o) );5442set_memory( _gvn.transform(result_memory), adr_type );54435444// The memory edges above are precise in order to model effects around5445// array copies accurately to allow value numbering of field loads around5446// arraycopy. Such field loads, both before and after, are common in Java5447// collections and similar classes involving header/array data structures.5448//5449// But with low number of register or when some registers are used or killed5450// by arraycopy calls it causes registers spilling on stack. See 6544710.5451// The next memory barrier is added to avoid it. If the arraycopy can be5452// optimized away (which it can, sometimes) then we can manually remove5453// the membar also.5454//5455// Do not let reads from the cloned object float above the arraycopy.5456if (alloc != NULL) {5457// Do not let stores that initialize this object be reordered with5458// a subsequent store that would make this object accessible by5459// other threads.5460// Record what AllocateNode this StoreStore protects so that5461// escape analysis can go from the MemBarStoreStoreNode to the5462// AllocateNode and eliminate the MemBarStoreStoreNode if possible5463// based on the escape status of the AllocateNode.5464insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out(AllocateNode::RawAddress));5465} else if (InsertMemBarAfterArraycopy)5466insert_mem_bar(Op_MemBarCPUOrder);5467}546854695470// Helper function which determines if an arraycopy immediately follows5471// an allocation, with no intervening tests or other escapes for the object.5472AllocateArrayNode*5473LibraryCallKit::tightly_coupled_allocation(Node* ptr,5474RegionNode* slow_region) {5475if (stopped()) return NULL; // no fast path5476if (C->AliasLevel() == 0) return NULL; // no MergeMems around54775478AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(ptr, &_gvn);5479if (alloc == NULL) return NULL;54805481Node* rawmem = memory(Compile::AliasIdxRaw);5482// Is the allocation's memory state untouched?5483if (!(rawmem->is_Proj() && rawmem->in(0)->is_Initialize())) {5484// Bail out if there have been raw-memory effects since the allocation.5485// (Example: There might have been a call or safepoint.)5486return NULL;5487}5488rawmem = rawmem->in(0)->as_Initialize()->memory(Compile::AliasIdxRaw);5489if (!(rawmem->is_Proj() && rawmem->in(0) == alloc)) {5490return NULL;5491}54925493// There must be no unexpected observers of this allocation.5494for (DUIterator_Fast imax, i = ptr->fast_outs(imax); i < imax; i++) {5495Node* obs = ptr->fast_out(i);5496if (obs != this->map()) {5497return NULL;5498}5499}55005501// This arraycopy must unconditionally follow the allocation of the ptr.5502Node* alloc_ctl = ptr->in(0);5503assert(just_allocated_object(alloc_ctl) == ptr, "most recent allo");55045505Node* ctl = control();5506while (ctl != alloc_ctl) {5507// There may be guards which feed into the slow_region.5508// Any other control flow means that we might not get a chance5509// to finish initializing the allocated object.5510if ((ctl->is_IfFalse() || ctl->is_IfTrue()) && ctl->in(0)->is_If()) {5511IfNode* iff = ctl->in(0)->as_If();5512Node* not_ctl = iff->proj_out(1 - ctl->as_Proj()->_con);5513assert(not_ctl != NULL && not_ctl != ctl, "found alternate");5514if (slow_region != NULL && slow_region->find_edge(not_ctl) >= 1) {5515ctl = iff->in(0); // This test feeds the known slow_region.5516continue;5517}5518// One more try: Various low-level checks bottom out in5519// uncommon traps. If the debug-info of the trap omits5520// any reference to the allocation, as we've already5521// observed, then there can be no objection to the trap.5522bool found_trap = false;5523for (DUIterator_Fast jmax, j = not_ctl->fast_outs(jmax); j < jmax; j++) {5524Node* obs = not_ctl->fast_out(j);5525if (obs->in(0) == not_ctl && obs->is_Call() &&5526(obs->as_Call()->entry_point() == SharedRuntime::uncommon_trap_blob()->entry_point())) {5527found_trap = true; break;5528}5529}5530if (found_trap) {5531ctl = iff->in(0); // This test feeds a harmless uncommon trap.5532continue;5533}5534}5535return NULL;5536}55375538// If we get this far, we have an allocation which immediately5539// precedes the arraycopy, and we can take over zeroing the new object.5540// The arraycopy will finish the initialization, and provide5541// a new control state to which we will anchor the destination pointer.55425543return alloc;5544}55455546// Helper for initialization of arrays, creating a ClearArray.5547// It writes zero bits in [start..end), within the body of an array object.5548// The memory effects are all chained onto the 'adr_type' alias category.5549//5550// Since the object is otherwise uninitialized, we are free5551// to put a little "slop" around the edges of the cleared area,5552// as long as it does not go back into the array's header,5553// or beyond the array end within the heap.5554//5555// The lower edge can be rounded down to the nearest jint and the5556// upper edge can be rounded up to the nearest MinObjAlignmentInBytes.5557//5558// Arguments:5559// adr_type memory slice where writes are generated5560// dest oop of the destination array5561// basic_elem_type element type of the destination5562// slice_idx array index of first element to store5563// slice_len number of elements to store (or NULL)5564// dest_size total size in bytes of the array object5565//5566// Exactly one of slice_len or dest_size must be non-NULL.5567// If dest_size is non-NULL, zeroing extends to the end of the object.5568// If slice_len is non-NULL, the slice_idx value must be a constant.5569void5570LibraryCallKit::generate_clear_array(const TypePtr* adr_type,5571Node* dest,5572BasicType basic_elem_type,5573Node* slice_idx,5574Node* slice_len,5575Node* dest_size) {5576// one or the other but not both of slice_len and dest_size:5577assert((slice_len != NULL? 1: 0) + (dest_size != NULL? 1: 0) == 1, "");5578if (slice_len == NULL) slice_len = top();5579if (dest_size == NULL) dest_size = top();55805581// operate on this memory slice:5582Node* mem = memory(adr_type); // memory slice to operate on55835584// scaling and rounding of indexes:5585int scale = exact_log2(type2aelembytes(basic_elem_type));5586int abase = arrayOopDesc::base_offset_in_bytes(basic_elem_type);5587int clear_low = (-1 << scale) & (BytesPerInt - 1);5588int bump_bit = (-1 << scale) & BytesPerInt;55895590// determine constant starts and ends5591const intptr_t BIG_NEG = -128;5592assert(BIG_NEG + 2*abase < 0, "neg enough");5593intptr_t slice_idx_con = (intptr_t) find_int_con(slice_idx, BIG_NEG);5594intptr_t slice_len_con = (intptr_t) find_int_con(slice_len, BIG_NEG);5595if (slice_len_con == 0) {5596return; // nothing to do here5597}5598intptr_t start_con = (abase + (slice_idx_con << scale)) & ~clear_low;5599intptr_t end_con = find_intptr_t_con(dest_size, -1);5600if (slice_idx_con >= 0 && slice_len_con >= 0) {5601assert(end_con < 0, "not two cons");5602end_con = round_to(abase + ((slice_idx_con + slice_len_con) << scale),5603BytesPerLong);5604}56055606if (start_con >= 0 && end_con >= 0) {5607// Constant start and end. Simple.5608mem = ClearArrayNode::clear_memory(control(), mem, dest,5609start_con, end_con, &_gvn);5610} else if (start_con >= 0 && dest_size != top()) {5611// Constant start, pre-rounded end after the tail of the array.5612Node* end = dest_size;5613mem = ClearArrayNode::clear_memory(control(), mem, dest,5614start_con, end, &_gvn);5615} else if (start_con >= 0 && slice_len != top()) {5616// Constant start, non-constant end. End needs rounding up.5617// End offset = round_up(abase + ((slice_idx_con + slice_len) << scale), 8)5618intptr_t end_base = abase + (slice_idx_con << scale);5619int end_round = (-1 << scale) & (BytesPerLong - 1);5620Node* end = ConvI2X(slice_len);5621if (scale != 0)5622end = _gvn.transform(new(C) LShiftXNode(end, intcon(scale) ));5623end_base += end_round;5624end = _gvn.transform(new(C) AddXNode(end, MakeConX(end_base)));5625end = _gvn.transform(new(C) AndXNode(end, MakeConX(~end_round)));5626mem = ClearArrayNode::clear_memory(control(), mem, dest,5627start_con, end, &_gvn);5628} else if (start_con < 0 && dest_size != top()) {5629// Non-constant start, pre-rounded end after the tail of the array.5630// This is almost certainly a "round-to-end" operation.5631Node* start = slice_idx;5632start = ConvI2X(start);5633if (scale != 0)5634start = _gvn.transform(new(C) LShiftXNode( start, intcon(scale) ));5635start = _gvn.transform(new(C) AddXNode(start, MakeConX(abase)));5636if ((bump_bit | clear_low) != 0) {5637int to_clear = (bump_bit | clear_low);5638// Align up mod 8, then store a jint zero unconditionally5639// just before the mod-8 boundary.5640if (((abase + bump_bit) & ~to_clear) - bump_bit5641< arrayOopDesc::length_offset_in_bytes() + BytesPerInt) {5642bump_bit = 0;5643assert((abase & to_clear) == 0, "array base must be long-aligned");5644} else {5645// Bump 'start' up to (or past) the next jint boundary:5646start = _gvn.transform(new(C) AddXNode(start, MakeConX(bump_bit)));5647assert((abase & clear_low) == 0, "array base must be int-aligned");5648}5649// Round bumped 'start' down to jlong boundary in body of array.5650start = _gvn.transform(new(C) AndXNode(start, MakeConX(~to_clear)));5651if (bump_bit != 0) {5652// Store a zero to the immediately preceding jint:5653Node* x1 = _gvn.transform(new(C) AddXNode(start, MakeConX(-bump_bit)));5654Node* p1 = basic_plus_adr(dest, x1);5655mem = StoreNode::make(_gvn, control(), mem, p1, adr_type, intcon(0), T_INT, MemNode::unordered);5656mem = _gvn.transform(mem);5657}5658}5659Node* end = dest_size; // pre-rounded5660mem = ClearArrayNode::clear_memory(control(), mem, dest,5661start, end, &_gvn);5662} else {5663// Non-constant start, unrounded non-constant end.5664// (Nobody zeroes a random midsection of an array using this routine.)5665ShouldNotReachHere(); // fix caller5666}56675668// Done.5669set_memory(mem, adr_type);5670}567156725673bool5674LibraryCallKit::generate_block_arraycopy(const TypePtr* adr_type,5675BasicType basic_elem_type,5676AllocateNode* alloc,5677Node* src, Node* src_offset,5678Node* dest, Node* dest_offset,5679Node* dest_size, bool dest_uninitialized) {5680// See if there is an advantage from block transfer.5681int scale = exact_log2(type2aelembytes(basic_elem_type));5682if (scale >= LogBytesPerLong)5683return false; // it is already a block transfer56845685// Look at the alignment of the starting offsets.5686int abase = arrayOopDesc::base_offset_in_bytes(basic_elem_type);56875688intptr_t src_off_con = (intptr_t) find_int_con(src_offset, -1);5689intptr_t dest_off_con = (intptr_t) find_int_con(dest_offset, -1);5690if (src_off_con < 0 || dest_off_con < 0)5691// At present, we can only understand constants.5692return false;56935694intptr_t src_off = abase + (src_off_con << scale);5695intptr_t dest_off = abase + (dest_off_con << scale);56965697if (((src_off | dest_off) & (BytesPerLong-1)) != 0) {5698// Non-aligned; too bad.5699// One more chance: Pick off an initial 32-bit word.5700// This is a common case, since abase can be odd mod 8.5701if (((src_off | dest_off) & (BytesPerLong-1)) == BytesPerInt &&5702((src_off ^ dest_off) & (BytesPerLong-1)) == 0) {5703Node* sptr = basic_plus_adr(src, src_off);5704Node* dptr = basic_plus_adr(dest, dest_off);5705Node* sval = make_load(control(), sptr, TypeInt::INT, T_INT, adr_type, MemNode::unordered);5706store_to_memory(control(), dptr, sval, T_INT, adr_type, MemNode::unordered);5707src_off += BytesPerInt;5708dest_off += BytesPerInt;5709} else {5710return false;5711}5712}5713assert(src_off % BytesPerLong == 0, "");5714assert(dest_off % BytesPerLong == 0, "");57155716// Do this copy by giant steps.5717Node* sptr = basic_plus_adr(src, src_off);5718Node* dptr = basic_plus_adr(dest, dest_off);5719Node* countx = dest_size;5720countx = _gvn.transform(new (C) SubXNode(countx, MakeConX(dest_off)));5721countx = _gvn.transform(new (C) URShiftXNode(countx, intcon(LogBytesPerLong)));57225723bool disjoint_bases = true; // since alloc != NULL5724generate_unchecked_arraycopy(adr_type, T_LONG, disjoint_bases,5725sptr, NULL, dptr, NULL, countx, dest_uninitialized);57265727return true;5728}572957305731// Helper function; generates code for the slow case.5732// We make a call to a runtime method which emulates the native method,5733// but without the native wrapper overhead.5734void5735LibraryCallKit::generate_slow_arraycopy(const TypePtr* adr_type,5736Node* src, Node* src_offset,5737Node* dest, Node* dest_offset,5738Node* copy_length, bool dest_uninitialized) {5739assert(!dest_uninitialized, "Invariant");5740Node* call = make_runtime_call(RC_NO_LEAF | RC_UNCOMMON,5741OptoRuntime::slow_arraycopy_Type(),5742OptoRuntime::slow_arraycopy_Java(),5743"slow_arraycopy", adr_type,5744src, src_offset, dest, dest_offset,5745copy_length);57465747// Handle exceptions thrown by this fellow:5748make_slow_call_ex(call, env()->Throwable_klass(), false);5749}57505751// Helper function; generates code for cases requiring runtime checks.5752Node*5753LibraryCallKit::generate_checkcast_arraycopy(const TypePtr* adr_type,5754Node* dest_elem_klass,5755Node* src, Node* src_offset,5756Node* dest, Node* dest_offset,5757Node* copy_length, bool dest_uninitialized) {5758if (stopped()) return NULL;57595760address copyfunc_addr = StubRoutines::checkcast_arraycopy(dest_uninitialized);5761if (copyfunc_addr == NULL) { // Stub was not generated, go slow path.5762return NULL;5763}57645765// Pick out the parameters required to perform a store-check5766// for the target array. This is an optimistic check. It will5767// look in each non-null element's class, at the desired klass's5768// super_check_offset, for the desired klass.5769int sco_offset = in_bytes(Klass::super_check_offset_offset());5770Node* p3 = basic_plus_adr(dest_elem_klass, sco_offset);5771Node* n3 = new(C) LoadINode(NULL, memory(p3), p3, _gvn.type(p3)->is_ptr(), TypeInt::INT, MemNode::unordered);5772Node* check_offset = ConvI2X(_gvn.transform(n3));5773Node* check_value = dest_elem_klass;57745775Node* src_start = array_element_address(src, src_offset, T_OBJECT);5776Node* dest_start = array_element_address(dest, dest_offset, T_OBJECT);57775778// (We know the arrays are never conjoint, because their types differ.)5779Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,5780OptoRuntime::checkcast_arraycopy_Type(),5781copyfunc_addr, "checkcast_arraycopy", adr_type,5782// five arguments, of which two are5783// intptr_t (jlong in LP64)5784src_start, dest_start,5785copy_length XTOP,5786check_offset XTOP,5787check_value);57885789return _gvn.transform(new (C) ProjNode(call, TypeFunc::Parms));5790}579157925793// Helper function; generates code for cases requiring runtime checks.5794Node*5795LibraryCallKit::generate_generic_arraycopy(const TypePtr* adr_type,5796Node* src, Node* src_offset,5797Node* dest, Node* dest_offset,5798Node* copy_length, bool dest_uninitialized) {5799assert(!dest_uninitialized, "Invariant");5800if (stopped()) return NULL;5801address copyfunc_addr = StubRoutines::generic_arraycopy();5802if (copyfunc_addr == NULL) { // Stub was not generated, go slow path.5803return NULL;5804}58055806Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,5807OptoRuntime::generic_arraycopy_Type(),5808copyfunc_addr, "generic_arraycopy", adr_type,5809src, src_offset, dest, dest_offset, copy_length);58105811return _gvn.transform(new (C) ProjNode(call, TypeFunc::Parms));5812}58135814// Helper function; generates the fast out-of-line call to an arraycopy stub.5815void5816LibraryCallKit::generate_unchecked_arraycopy(const TypePtr* adr_type,5817BasicType basic_elem_type,5818bool disjoint_bases,5819Node* src, Node* src_offset,5820Node* dest, Node* dest_offset,5821Node* copy_length, bool dest_uninitialized) {5822if (stopped()) return; // nothing to do58235824Node* src_start = src;5825Node* dest_start = dest;5826if (src_offset != NULL || dest_offset != NULL) {5827assert(src_offset != NULL && dest_offset != NULL, "");5828src_start = array_element_address(src, src_offset, basic_elem_type);5829dest_start = array_element_address(dest, dest_offset, basic_elem_type);5830}58315832// Figure out which arraycopy runtime method to call.5833const char* copyfunc_name = "arraycopy";5834address copyfunc_addr =5835basictype2arraycopy(basic_elem_type, src_offset, dest_offset,5836disjoint_bases, copyfunc_name, dest_uninitialized);58375838// Call it. Note that the count_ix value is not scaled to a byte-size.5839make_runtime_call(RC_LEAF|RC_NO_FP,5840OptoRuntime::fast_arraycopy_Type(),5841copyfunc_addr, copyfunc_name, adr_type,5842src_start, dest_start, copy_length XTOP);5843}58445845//-------------inline_encodeISOArray-----------------------------------5846// encode char[] to byte[] in ISO_8859_15847bool LibraryCallKit::inline_encodeISOArray() {5848assert(callee()->signature()->size() == 5, "encodeISOArray has 5 parameters");5849// no receiver since it is static method5850Node *src = argument(0);5851Node *src_offset = argument(1);5852Node *dst = argument(2);5853Node *dst_offset = argument(3);5854Node *length = argument(4);58555856const Type* src_type = src->Value(&_gvn);5857const Type* dst_type = dst->Value(&_gvn);5858const TypeAryPtr* top_src = src_type->isa_aryptr();5859const TypeAryPtr* top_dest = dst_type->isa_aryptr();5860if (top_src == NULL || top_src->klass() == NULL ||5861top_dest == NULL || top_dest->klass() == NULL) {5862// failed array check5863return false;5864}58655866// Figure out the size and type of the elements we will be copying.5867BasicType src_elem = src_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();5868BasicType dst_elem = dst_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();5869if (src_elem != T_CHAR || dst_elem != T_BYTE) {5870return false;5871}5872Node* src_start = array_element_address(src, src_offset, src_elem);5873Node* dst_start = array_element_address(dst, dst_offset, dst_elem);5874// 'src_start' points to src array + scaled offset5875// 'dst_start' points to dst array + scaled offset58765877const TypeAryPtr* mtype = TypeAryPtr::BYTES;5878Node* enc = new (C) EncodeISOArrayNode(control(), memory(mtype), src_start, dst_start, length);5879enc = _gvn.transform(enc);5880Node* res_mem = _gvn.transform(new (C) SCMemProjNode(enc));5881set_memory(res_mem, mtype);5882set_result(enc);5883return true;5884}58855886//-------------inline_multiplyToLen-----------------------------------5887bool LibraryCallKit::inline_multiplyToLen() {5888assert(UseMultiplyToLenIntrinsic, "not implementated on this platform");58895890address stubAddr = StubRoutines::multiplyToLen();5891if (stubAddr == NULL) {5892return false; // Intrinsic's stub is not implemented on this platform5893}5894const char* stubName = "multiplyToLen";58955896assert(callee()->signature()->size() == 5, "multiplyToLen has 5 parameters");58975898// no receiver because it is a static method5899Node* x = argument(0);5900Node* xlen = argument(1);5901Node* y = argument(2);5902Node* ylen = argument(3);5903Node* z = argument(4);59045905const Type* x_type = x->Value(&_gvn);5906const Type* y_type = y->Value(&_gvn);5907const TypeAryPtr* top_x = x_type->isa_aryptr();5908const TypeAryPtr* top_y = y_type->isa_aryptr();5909if (top_x == NULL || top_x->klass() == NULL ||5910top_y == NULL || top_y->klass() == NULL) {5911// failed array check5912return false;5913}59145915BasicType x_elem = x_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();5916BasicType y_elem = y_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();5917if (x_elem != T_INT || y_elem != T_INT) {5918return false;5919}59205921// Set the original stack and the reexecute bit for the interpreter to reexecute5922// the bytecode that invokes BigInteger.multiplyToLen() if deoptimization happens5923// on the return from z array allocation in runtime.5924{ PreserveReexecuteState preexecs(this);5925jvms()->set_should_reexecute(true);59265927Node* x_start = array_element_address(x, intcon(0), x_elem);5928Node* y_start = array_element_address(y, intcon(0), y_elem);5929// 'x_start' points to x array + scaled xlen5930// 'y_start' points to y array + scaled ylen59315932// Allocate the result array5933Node* zlen = _gvn.transform(new(C) AddINode(xlen, ylen));5934ciKlass* klass = ciTypeArrayKlass::make(T_INT);5935Node* klass_node = makecon(TypeKlassPtr::make(klass));59365937IdealKit ideal(this);59385939#define __ ideal.5940Node* one = __ ConI(1);5941Node* zero = __ ConI(0);5942IdealVariable need_alloc(ideal), z_alloc(ideal); __ declarations_done();5943__ set(need_alloc, zero);5944__ set(z_alloc, z);5945__ if_then(z, BoolTest::eq, null()); {5946__ increment (need_alloc, one);5947} __ else_(); {5948// Update graphKit memory and control from IdealKit.5949sync_kit(ideal);5950Node* zlen_arg = load_array_length(z);5951// Update IdealKit memory and control from graphKit.5952__ sync_kit(this);5953__ if_then(zlen_arg, BoolTest::lt, zlen); {5954__ increment (need_alloc, one);5955} __ end_if();5956} __ end_if();59575958__ if_then(__ value(need_alloc), BoolTest::ne, zero); {5959// Update graphKit memory and control from IdealKit.5960sync_kit(ideal);5961Node * narr = new_array(klass_node, zlen, 1);5962// Update IdealKit memory and control from graphKit.5963__ sync_kit(this);5964__ set(z_alloc, narr);5965} __ end_if();59665967sync_kit(ideal);5968z = __ value(z_alloc);5969// Can't use TypeAryPtr::INTS which uses Bottom offset.5970_gvn.set_type(z, TypeOopPtr::make_from_klass(klass));5971// Final sync IdealKit and GraphKit.5972final_sync(ideal);5973#undef __59745975Node* z_start = array_element_address(z, intcon(0), T_INT);59765977Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,5978OptoRuntime::multiplyToLen_Type(),5979stubAddr, stubName, TypePtr::BOTTOM,5980x_start, xlen, y_start, ylen, z_start, zlen);5981} // original reexecute is set back here59825983C->set_has_split_ifs(true); // Has chance for split-if optimization5984set_result(z);5985return true;5986}59875988//-------------inline_squareToLen------------------------------------5989bool LibraryCallKit::inline_squareToLen() {5990assert(UseSquareToLenIntrinsic, "not implementated on this platform");59915992address stubAddr = StubRoutines::squareToLen();5993if (stubAddr == NULL) {5994return false; // Intrinsic's stub is not implemented on this platform5995}5996const char* stubName = "squareToLen";59975998assert(callee()->signature()->size() == 4, "implSquareToLen has 4 parameters");59996000Node* x = argument(0);6001Node* len = argument(1);6002Node* z = argument(2);6003Node* zlen = argument(3);60046005const Type* x_type = x->Value(&_gvn);6006const Type* z_type = z->Value(&_gvn);6007const TypeAryPtr* top_x = x_type->isa_aryptr();6008const TypeAryPtr* top_z = z_type->isa_aryptr();6009if (top_x == NULL || top_x->klass() == NULL ||6010top_z == NULL || top_z->klass() == NULL) {6011// failed array check6012return false;6013}60146015BasicType x_elem = x_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();6016BasicType z_elem = z_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();6017if (x_elem != T_INT || z_elem != T_INT) {6018return false;6019}602060216022Node* x_start = array_element_address(x, intcon(0), x_elem);6023Node* z_start = array_element_address(z, intcon(0), z_elem);60246025Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,6026OptoRuntime::squareToLen_Type(),6027stubAddr, stubName, TypePtr::BOTTOM,6028x_start, len, z_start, zlen);60296030set_result(z);6031return true;6032}60336034//-------------inline_mulAdd------------------------------------------6035bool LibraryCallKit::inline_mulAdd() {6036assert(UseMulAddIntrinsic, "not implementated on this platform");60376038address stubAddr = StubRoutines::mulAdd();6039if (stubAddr == NULL) {6040return false; // Intrinsic's stub is not implemented on this platform6041}6042const char* stubName = "mulAdd";60436044assert(callee()->signature()->size() == 5, "mulAdd has 5 parameters");60456046Node* out = argument(0);6047Node* in = argument(1);6048Node* offset = argument(2);6049Node* len = argument(3);6050Node* k = argument(4);60516052const Type* out_type = out->Value(&_gvn);6053const Type* in_type = in->Value(&_gvn);6054const TypeAryPtr* top_out = out_type->isa_aryptr();6055const TypeAryPtr* top_in = in_type->isa_aryptr();6056if (top_out == NULL || top_out->klass() == NULL ||6057top_in == NULL || top_in->klass() == NULL) {6058// failed array check6059return false;6060}60616062BasicType out_elem = out_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();6063BasicType in_elem = in_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();6064if (out_elem != T_INT || in_elem != T_INT) {6065return false;6066}60676068Node* outlen = load_array_length(out);6069Node* new_offset = _gvn.transform(new (C) SubINode(outlen, offset));6070Node* out_start = array_element_address(out, intcon(0), out_elem);6071Node* in_start = array_element_address(in, intcon(0), in_elem);60726073Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,6074OptoRuntime::mulAdd_Type(),6075stubAddr, stubName, TypePtr::BOTTOM,6076out_start,in_start, new_offset, len, k);6077Node* result = _gvn.transform(new (C) ProjNode(call, TypeFunc::Parms));6078set_result(result);6079return true;6080}60816082//-------------inline_montgomeryMultiply-----------------------------------6083bool LibraryCallKit::inline_montgomeryMultiply() {6084address stubAddr = StubRoutines::montgomeryMultiply();6085if (stubAddr == NULL) {6086return false; // Intrinsic's stub is not implemented on this platform6087}60886089assert(UseMontgomeryMultiplyIntrinsic, "not implemented on this platform");6090const char* stubName = "montgomery_multiply";60916092assert(callee()->signature()->size() == 7, "montgomeryMultiply has 7 parameters");60936094Node* a = argument(0);6095Node* b = argument(1);6096Node* n = argument(2);6097Node* len = argument(3);6098Node* inv = argument(4);6099Node* m = argument(6);61006101const Type* a_type = a->Value(&_gvn);6102const TypeAryPtr* top_a = a_type->isa_aryptr();6103const Type* b_type = b->Value(&_gvn);6104const TypeAryPtr* top_b = b_type->isa_aryptr();6105const Type* n_type = a->Value(&_gvn);6106const TypeAryPtr* top_n = n_type->isa_aryptr();6107const Type* m_type = a->Value(&_gvn);6108const TypeAryPtr* top_m = m_type->isa_aryptr();6109if (top_a == NULL || top_a->klass() == NULL ||6110top_b == NULL || top_b->klass() == NULL ||6111top_n == NULL || top_n->klass() == NULL ||6112top_m == NULL || top_m->klass() == NULL) {6113// failed array check6114return false;6115}61166117BasicType a_elem = a_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();6118BasicType b_elem = b_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();6119BasicType n_elem = n_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();6120BasicType m_elem = m_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();6121if (a_elem != T_INT || b_elem != T_INT || n_elem != T_INT || m_elem != T_INT) {6122return false;6123}61246125// Make the call6126{6127Node* a_start = array_element_address(a, intcon(0), a_elem);6128Node* b_start = array_element_address(b, intcon(0), b_elem);6129Node* n_start = array_element_address(n, intcon(0), n_elem);6130Node* m_start = array_element_address(m, intcon(0), m_elem);61316132Node* call = NULL;6133if (CCallingConventionRequiresIntsAsLongs) {6134Node* len_I2L = ConvI2L(len);6135call = make_runtime_call(RC_LEAF,6136OptoRuntime::montgomeryMultiply_Type(),6137stubAddr, stubName, TypePtr::BOTTOM,6138a_start, b_start, n_start, len_I2L XTOP, inv,6139top(), m_start);6140} else {6141call = make_runtime_call(RC_LEAF,6142OptoRuntime::montgomeryMultiply_Type(),6143stubAddr, stubName, TypePtr::BOTTOM,6144a_start, b_start, n_start, len, inv, top(),6145m_start);6146}6147set_result(m);6148}61496150return true;6151}61526153bool LibraryCallKit::inline_montgomerySquare() {6154address stubAddr = StubRoutines::montgomerySquare();6155if (stubAddr == NULL) {6156return false; // Intrinsic's stub is not implemented on this platform6157}61586159assert(UseMontgomerySquareIntrinsic, "not implemented on this platform");6160const char* stubName = "montgomery_square";61616162assert(callee()->signature()->size() == 6, "montgomerySquare has 6 parameters");61636164Node* a = argument(0);6165Node* n = argument(1);6166Node* len = argument(2);6167Node* inv = argument(3);6168Node* m = argument(5);61696170const Type* a_type = a->Value(&_gvn);6171const TypeAryPtr* top_a = a_type->isa_aryptr();6172const Type* n_type = a->Value(&_gvn);6173const TypeAryPtr* top_n = n_type->isa_aryptr();6174const Type* m_type = a->Value(&_gvn);6175const TypeAryPtr* top_m = m_type->isa_aryptr();6176if (top_a == NULL || top_a->klass() == NULL ||6177top_n == NULL || top_n->klass() == NULL ||6178top_m == NULL || top_m->klass() == NULL) {6179// failed array check6180return false;6181}61826183BasicType a_elem = a_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();6184BasicType n_elem = n_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();6185BasicType m_elem = m_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();6186if (a_elem != T_INT || n_elem != T_INT || m_elem != T_INT) {6187return false;6188}61896190// Make the call6191{6192Node* a_start = array_element_address(a, intcon(0), a_elem);6193Node* n_start = array_element_address(n, intcon(0), n_elem);6194Node* m_start = array_element_address(m, intcon(0), m_elem);61956196Node* call = NULL;6197if (CCallingConventionRequiresIntsAsLongs) {6198Node* len_I2L = ConvI2L(len);6199call = make_runtime_call(RC_LEAF,6200OptoRuntime::montgomerySquare_Type(),6201stubAddr, stubName, TypePtr::BOTTOM,6202a_start, n_start, len_I2L XTOP, inv, top(),6203m_start);6204} else {6205call = make_runtime_call(RC_LEAF,6206OptoRuntime::montgomerySquare_Type(),6207stubAddr, stubName, TypePtr::BOTTOM,6208a_start, n_start, len, inv, top(),6209m_start);6210}62116212set_result(m);6213}62146215return true;6216}621762186219/**6220* Calculate CRC32 for byte.6221* int java.util.zip.CRC32.update(int crc, int b)6222*/6223bool LibraryCallKit::inline_updateCRC32() {6224assert(UseCRC32Intrinsics, "need AVX and LCMUL instructions support");6225assert(callee()->signature()->size() == 2, "update has 2 parameters");6226// no receiver since it is static method6227Node* crc = argument(0); // type: int6228Node* b = argument(1); // type: int62296230/*6231* int c = ~ crc;6232* b = timesXtoThe32[(b ^ c) & 0xFF];6233* b = b ^ (c >>> 8);6234* crc = ~b;6235*/62366237Node* M1 = intcon(-1);6238crc = _gvn.transform(new (C) XorINode(crc, M1));6239Node* result = _gvn.transform(new (C) XorINode(crc, b));6240result = _gvn.transform(new (C) AndINode(result, intcon(0xFF)));62416242Node* base = makecon(TypeRawPtr::make(StubRoutines::crc_table_addr()));6243Node* offset = _gvn.transform(new (C) LShiftINode(result, intcon(0x2)));6244Node* adr = basic_plus_adr(top(), base, ConvI2X(offset));6245result = make_load(control(), adr, TypeInt::INT, T_INT, MemNode::unordered);62466247crc = _gvn.transform(new (C) URShiftINode(crc, intcon(8)));6248result = _gvn.transform(new (C) XorINode(crc, result));6249result = _gvn.transform(new (C) XorINode(result, M1));6250set_result(result);6251return true;6252}62536254/**6255* Calculate CRC32 for byte[] array.6256* int java.util.zip.CRC32.updateBytes(int crc, byte[] buf, int off, int len)6257*/6258bool LibraryCallKit::inline_updateBytesCRC32() {6259assert(UseCRC32Intrinsics, "need AVX and LCMUL instructions support");6260assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");6261// no receiver since it is static method6262Node* crc = argument(0); // type: int6263Node* src = argument(1); // type: oop6264Node* offset = argument(2); // type: int6265Node* length = argument(3); // type: int62666267const Type* src_type = src->Value(&_gvn);6268const TypeAryPtr* top_src = src_type->isa_aryptr();6269if (top_src == NULL || top_src->klass() == NULL) {6270// failed array check6271return false;6272}62736274// Figure out the size and type of the elements we will be copying.6275BasicType src_elem = src_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();6276if (src_elem != T_BYTE) {6277return false;6278}62796280// 'src_start' points to src array + scaled offset6281Node* src_start = array_element_address(src, offset, src_elem);62826283// We assume that range check is done by caller.6284// TODO: generate range check (offset+length < src.length) in debug VM.62856286// Call the stub.6287address stubAddr = StubRoutines::updateBytesCRC32();6288const char *stubName = "updateBytesCRC32";6289Node* call;6290if (CCallingConventionRequiresIntsAsLongs) {6291call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::updateBytesCRC32_Type(),6292stubAddr, stubName, TypePtr::BOTTOM,6293crc XTOP, src_start, length XTOP);6294} else {6295call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::updateBytesCRC32_Type(),6296stubAddr, stubName, TypePtr::BOTTOM,6297crc, src_start, length);6298}6299Node* result = _gvn.transform(new (C) ProjNode(call, TypeFunc::Parms));6300set_result(result);6301return true;6302}63036304/**6305* Calculate CRC32 for ByteBuffer.6306* int java.util.zip.CRC32.updateByteBuffer(int crc, long buf, int off, int len)6307*/6308bool LibraryCallKit::inline_updateByteBufferCRC32() {6309assert(UseCRC32Intrinsics, "need AVX and LCMUL instructions support");6310assert(callee()->signature()->size() == 5, "updateByteBuffer has 4 parameters and one is long");6311// no receiver since it is static method6312Node* crc = argument(0); // type: int6313Node* src = argument(1); // type: long6314Node* offset = argument(3); // type: int6315Node* length = argument(4); // type: int63166317src = ConvL2X(src); // adjust Java long to machine word6318Node* base = _gvn.transform(new (C) CastX2PNode(src));6319offset = ConvI2X(offset);63206321// 'src_start' points to src array + scaled offset6322Node* src_start = basic_plus_adr(top(), base, offset);63236324// Call the stub.6325address stubAddr = StubRoutines::updateBytesCRC32();6326const char *stubName = "updateBytesCRC32";6327Node* call;6328if (CCallingConventionRequiresIntsAsLongs) {6329call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::updateBytesCRC32_Type(),6330stubAddr, stubName, TypePtr::BOTTOM,6331crc XTOP, src_start, length XTOP);6332} else {6333call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::updateBytesCRC32_Type(),6334stubAddr, stubName, TypePtr::BOTTOM,6335crc, src_start, length);6336}6337Node* result = _gvn.transform(new (C) ProjNode(call, TypeFunc::Parms));6338set_result(result);6339return true;6340}63416342//----------------------------inline_reference_get----------------------------6343// public T java.lang.ref.Reference.get();6344bool LibraryCallKit::inline_reference_get() {6345const int referent_offset = java_lang_ref_Reference::referent_offset;6346guarantee(referent_offset > 0, "should have already been set");63476348// Get the argument:6349Node* reference_obj = null_check_receiver();6350if (stopped()) return true;63516352Node* adr = basic_plus_adr(reference_obj, reference_obj, referent_offset);63536354ciInstanceKlass* klass = env()->Object_klass();6355const TypeOopPtr* object_type = TypeOopPtr::make_from_klass(klass);63566357Node* no_ctrl = NULL;6358Node* result = make_load(no_ctrl, adr, object_type, T_OBJECT, MemNode::unordered);63596360#if INCLUDE_ALL_GCS6361if (UseShenandoahGC) {6362result = ShenandoahBarrierSetC2::bsc2()->load_reference_barrier(this, result);6363}6364#endif63656366// Use the pre-barrier to record the value in the referent field6367pre_barrier(false /* do_load */,6368control(),6369NULL /* obj */, NULL /* adr */, max_juint /* alias_idx */, NULL /* val */, NULL /* val_type */,6370result /* pre_val */,6371T_OBJECT);63726373// Add memory barrier to prevent commoning reads from this field6374// across safepoint since GC can change its value.6375insert_mem_bar(Op_MemBarCPUOrder);63766377set_result(result);6378return true;6379}638063816382Node * LibraryCallKit::load_field_from_object(Node * fromObj, const char * fieldName, const char * fieldTypeString,6383bool is_exact=true, bool is_static=false) {63846385const TypeInstPtr* tinst = _gvn.type(fromObj)->isa_instptr();6386assert(tinst != NULL, "obj is null");6387assert(tinst->klass()->is_loaded(), "obj is not loaded");6388assert(!is_exact || tinst->klass_is_exact(), "klass not exact");63896390ciField* field = tinst->klass()->as_instance_klass()->get_field_by_name(ciSymbol::make(fieldName),6391ciSymbol::make(fieldTypeString),6392is_static);6393if (field == NULL) return (Node *) NULL;6394assert (field != NULL, "undefined field");63956396// Next code copied from Parse::do_get_xxx():63976398// Compute address and memory type.6399int offset = field->offset_in_bytes();6400bool is_vol = field->is_volatile();6401ciType* field_klass = field->type();6402assert(field_klass->is_loaded(), "should be loaded");6403const TypePtr* adr_type = C->alias_type(field)->adr_type();6404Node *adr = basic_plus_adr(fromObj, fromObj, offset);6405BasicType bt = field->layout_type();64066407// Build the resultant type of the load6408const Type *type;6409if (bt == T_OBJECT) {6410type = TypeOopPtr::make_from_klass(field_klass->as_klass());6411} else {6412type = Type::get_const_basic_type(bt);6413}64146415Node* leading_membar = NULL;6416if (support_IRIW_for_not_multiple_copy_atomic_cpu && is_vol) {6417leading_membar = insert_mem_bar(Op_MemBarVolatile); // StoreLoad barrier6418}6419// Build the load.6420MemNode::MemOrd mo = is_vol ? MemNode::acquire : MemNode::unordered;6421Node* loadedField = make_load(NULL, adr, type, bt, adr_type, mo, LoadNode::DependsOnlyOnTest, is_vol);6422#if INCLUDE_ALL_GCS6423if (UseShenandoahGC && (bt == T_OBJECT || bt == T_ARRAY)) {6424loadedField = ShenandoahBarrierSetC2::bsc2()->load_reference_barrier(this, loadedField);6425}6426#endif64276428// If reference is volatile, prevent following memory ops from6429// floating up past the volatile read. Also prevents commoning6430// another volatile read.6431if (is_vol) {6432// Memory barrier includes bogus read of value to force load BEFORE membar6433Node* mb = insert_mem_bar(Op_MemBarAcquire, loadedField);6434mb->as_MemBar()->set_trailing_load();6435}6436return loadedField;6437}643864396440//------------------------------inline_aescrypt_Block-----------------------6441bool LibraryCallKit::inline_aescrypt_Block(vmIntrinsics::ID id) {6442address stubAddr = NULL;6443const char *stubName;6444assert(UseAES, "need AES instruction support");64456446switch(id) {6447case vmIntrinsics::_aescrypt_encryptBlock:6448stubAddr = StubRoutines::aescrypt_encryptBlock();6449stubName = "aescrypt_encryptBlock";6450break;6451case vmIntrinsics::_aescrypt_decryptBlock:6452stubAddr = StubRoutines::aescrypt_decryptBlock();6453stubName = "aescrypt_decryptBlock";6454break;6455}6456if (stubAddr == NULL) return false;64576458Node* aescrypt_object = argument(0);6459Node* src = argument(1);6460Node* src_offset = argument(2);6461Node* dest = argument(3);6462Node* dest_offset = argument(4);64636464// (1) src and dest are arrays.6465const Type* src_type = src->Value(&_gvn);6466const Type* dest_type = dest->Value(&_gvn);6467const TypeAryPtr* top_src = src_type->isa_aryptr();6468const TypeAryPtr* top_dest = dest_type->isa_aryptr();6469assert (top_src != NULL && top_src->klass() != NULL && top_dest != NULL && top_dest->klass() != NULL, "args are strange");64706471// for the quick and dirty code we will skip all the checks.6472// we are just trying to get the call to be generated.6473Node* src_start = src;6474Node* dest_start = dest;6475if (src_offset != NULL || dest_offset != NULL) {6476assert(src_offset != NULL && dest_offset != NULL, "");6477src_start = array_element_address(src, src_offset, T_BYTE);6478dest_start = array_element_address(dest, dest_offset, T_BYTE);6479}64806481// now need to get the start of its expanded key array6482// this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java6483Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object);6484if (k_start == NULL) return false;64856486if (Matcher::pass_original_key_for_aes()) {6487// on SPARC we need to pass the original key since key expansion needs to happen in intrinsics due to6488// compatibility issues between Java key expansion and SPARC crypto instructions6489Node* original_k_start = get_original_key_start_from_aescrypt_object(aescrypt_object);6490if (original_k_start == NULL) return false;64916492// Call the stub.6493make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::aescrypt_block_Type(),6494stubAddr, stubName, TypePtr::BOTTOM,6495src_start, dest_start, k_start, original_k_start);6496} else {6497// Call the stub.6498make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::aescrypt_block_Type(),6499stubAddr, stubName, TypePtr::BOTTOM,6500src_start, dest_start, k_start);6501}65026503return true;6504}65056506//------------------------------inline_cipherBlockChaining_AESCrypt-----------------------6507bool LibraryCallKit::inline_cipherBlockChaining_AESCrypt(vmIntrinsics::ID id) {6508address stubAddr = NULL;6509const char *stubName = NULL;65106511assert(UseAES, "need AES instruction support");65126513switch(id) {6514case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:6515stubAddr = StubRoutines::cipherBlockChaining_encryptAESCrypt();6516stubName = "cipherBlockChaining_encryptAESCrypt";6517break;6518case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:6519stubAddr = StubRoutines::cipherBlockChaining_decryptAESCrypt();6520stubName = "cipherBlockChaining_decryptAESCrypt";6521break;6522}6523if (stubAddr == NULL) return false;65246525Node* cipherBlockChaining_object = argument(0);6526Node* src = argument(1);6527Node* src_offset = argument(2);6528Node* len = argument(3);6529Node* dest = argument(4);6530Node* dest_offset = argument(5);65316532// (1) src and dest are arrays.6533const Type* src_type = src->Value(&_gvn);6534const Type* dest_type = dest->Value(&_gvn);6535const TypeAryPtr* top_src = src_type->isa_aryptr();6536const TypeAryPtr* top_dest = dest_type->isa_aryptr();6537assert (top_src != NULL && top_src->klass() != NULL6538&& top_dest != NULL && top_dest->klass() != NULL, "args are strange");65396540// checks are the responsibility of the caller6541Node* src_start = src;6542Node* dest_start = dest;6543if (src_offset != NULL || dest_offset != NULL) {6544assert(src_offset != NULL && dest_offset != NULL, "");6545src_start = array_element_address(src, src_offset, T_BYTE);6546dest_start = array_element_address(dest, dest_offset, T_BYTE);6547}65486549// if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object6550// (because of the predicated logic executed earlier).6551// so we cast it here safely.6552// this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java65536554Node* embeddedCipherObj = load_field_from_object(cipherBlockChaining_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;", /*is_exact*/ false);6555if (embeddedCipherObj == NULL) return false;65566557// cast it to what we know it will be at runtime6558const TypeInstPtr* tinst = _gvn.type(cipherBlockChaining_object)->isa_instptr();6559assert(tinst != NULL, "CBC obj is null");6560assert(tinst->klass()->is_loaded(), "CBC obj is not loaded");6561ciKlass* klass_AESCrypt = tinst->klass()->as_instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AESCrypt"));6562assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");65636564ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();6565const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);6566const TypeOopPtr* xtype = aklass->as_instance_type();6567Node* aescrypt_object = new(C) CheckCastPPNode(control(), embeddedCipherObj, xtype);6568aescrypt_object = _gvn.transform(aescrypt_object);65696570// we need to get the start of the aescrypt_object's expanded key array6571Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object);6572if (k_start == NULL) return false;65736574// similarly, get the start address of the r vector6575Node* objRvec = load_field_from_object(cipherBlockChaining_object, "r", "[B", /*is_exact*/ false);6576if (objRvec == NULL) return false;6577Node* r_start = array_element_address(objRvec, intcon(0), T_BYTE);65786579Node* cbcCrypt;6580if (Matcher::pass_original_key_for_aes()) {6581// on SPARC we need to pass the original key since key expansion needs to happen in intrinsics due to6582// compatibility issues between Java key expansion and SPARC crypto instructions6583Node* original_k_start = get_original_key_start_from_aescrypt_object(aescrypt_object);6584if (original_k_start == NULL) return false;65856586// Call the stub, passing src_start, dest_start, k_start, r_start, src_len and original_k_start6587cbcCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,6588OptoRuntime::cipherBlockChaining_aescrypt_Type(),6589stubAddr, stubName, TypePtr::BOTTOM,6590src_start, dest_start, k_start, r_start, len, original_k_start);6591} else {6592// Call the stub, passing src_start, dest_start, k_start, r_start and src_len6593cbcCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,6594OptoRuntime::cipherBlockChaining_aescrypt_Type(),6595stubAddr, stubName, TypePtr::BOTTOM,6596src_start, dest_start, k_start, r_start, len);6597}65986599// return cipher length (int)6600Node* retvalue = _gvn.transform(new (C) ProjNode(cbcCrypt, TypeFunc::Parms));6601set_result(retvalue);6602return true;6603}66046605//------------------------------get_key_start_from_aescrypt_object-----------------------6606Node * LibraryCallKit::get_key_start_from_aescrypt_object(Node *aescrypt_object) {6607#ifdef PPC646608// MixColumns for decryption can be reduced by preprocessing MixColumns with round keys.6609// Intel's extention is based on this optimization and AESCrypt generates round keys by preprocessing MixColumns.6610// However, ppc64 vncipher processes MixColumns and requires the same round keys with encryption.6611// The ppc64 stubs of encryption and decryption use the same round keys (sessionK[0]).6612Node* objSessionK = load_field_from_object(aescrypt_object, "sessionK", "[[I", /*is_exact*/ false);6613assert (objSessionK != NULL, "wrong version of com.sun.crypto.provider.AESCrypt");6614if (objSessionK == NULL) {6615return (Node *) NULL;6616}6617Node* objAESCryptKey = load_array_element(control(), objSessionK, intcon(0), TypeAryPtr::OOPS);6618#else6619Node* objAESCryptKey = load_field_from_object(aescrypt_object, "K", "[I", /*is_exact*/ false);6620#endif // PPC646621assert (objAESCryptKey != NULL, "wrong version of com.sun.crypto.provider.AESCrypt");6622if (objAESCryptKey == NULL) return (Node *) NULL;66236624// now have the array, need to get the start address of the K array6625Node* k_start = array_element_address(objAESCryptKey, intcon(0), T_INT);6626return k_start;6627}66286629//------------------------------get_original_key_start_from_aescrypt_object-----------------------6630Node * LibraryCallKit::get_original_key_start_from_aescrypt_object(Node *aescrypt_object) {6631Node* objAESCryptKey = load_field_from_object(aescrypt_object, "lastKey", "[B", /*is_exact*/ false);6632assert (objAESCryptKey != NULL, "wrong version of com.sun.crypto.provider.AESCrypt");6633if (objAESCryptKey == NULL) return (Node *) NULL;66346635// now have the array, need to get the start address of the lastKey array6636Node* original_k_start = array_element_address(objAESCryptKey, intcon(0), T_BYTE);6637return original_k_start;6638}66396640//----------------------------inline_cipherBlockChaining_AESCrypt_predicate----------------------------6641// Return node representing slow path of predicate check.6642// the pseudo code we want to emulate with this predicate is:6643// for encryption:6644// if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath6645// for decryption:6646// if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath6647// note cipher==plain is more conservative than the original java code but that's OK6648//6649Node* LibraryCallKit::inline_cipherBlockChaining_AESCrypt_predicate(bool decrypting) {6650// The receiver was checked for NULL already.6651Node* objCBC = argument(0);66526653// Load embeddedCipher field of CipherBlockChaining object.6654Node* embeddedCipherObj = load_field_from_object(objCBC, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;", /*is_exact*/ false);66556656// get AESCrypt klass for instanceOf check6657// AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point6658// will have same classloader as CipherBlockChaining object6659const TypeInstPtr* tinst = _gvn.type(objCBC)->isa_instptr();6660assert(tinst != NULL, "CBCobj is null");6661assert(tinst->klass()->is_loaded(), "CBCobj is not loaded");66626663// we want to do an instanceof comparison against the AESCrypt class6664ciKlass* klass_AESCrypt = tinst->klass()->as_instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AESCrypt"));6665if (!klass_AESCrypt->is_loaded()) {6666// if AESCrypt is not even loaded, we never take the intrinsic fast path6667Node* ctrl = control();6668set_control(top()); // no regular fast path6669return ctrl;6670}6671ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();66726673Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));6674Node* cmp_instof = _gvn.transform(new (C) CmpINode(instof, intcon(1)));6675Node* bool_instof = _gvn.transform(new (C) BoolNode(cmp_instof, BoolTest::ne));66766677Node* instof_false = generate_guard(bool_instof, NULL, PROB_MIN);66786679// for encryption, we are done6680if (!decrypting)6681return instof_false; // even if it is NULL66826683// for decryption, we need to add a further check to avoid6684// taking the intrinsic path when cipher and plain are the same6685// see the original java code for why.6686RegionNode* region = new(C) RegionNode(3);6687region->init_req(1, instof_false);6688Node* src = argument(1);6689Node* dest = argument(4);6690Node* cmp_src_dest = _gvn.transform(new (C) CmpPNode(src, dest));6691Node* bool_src_dest = _gvn.transform(new (C) BoolNode(cmp_src_dest, BoolTest::eq));6692Node* src_dest_conjoint = generate_guard(bool_src_dest, NULL, PROB_MIN);6693region->init_req(2, src_dest_conjoint);66946695record_for_igvn(region);6696return _gvn.transform(region);6697}66986699//------------------------------inline_ghash_processBlocks6700bool LibraryCallKit::inline_ghash_processBlocks() {6701address stubAddr;6702const char *stubName;6703assert(UseGHASHIntrinsics, "need GHASH intrinsics support");67046705stubAddr = StubRoutines::ghash_processBlocks();6706stubName = "ghash_processBlocks";67076708Node* data = argument(0);6709Node* offset = argument(1);6710Node* len = argument(2);6711Node* state = argument(3);6712Node* subkeyH = argument(4);67136714Node* state_start = array_element_address(state, intcon(0), T_LONG);6715assert(state_start, "state is NULL");6716Node* subkeyH_start = array_element_address(subkeyH, intcon(0), T_LONG);6717assert(subkeyH_start, "subkeyH is NULL");6718Node* data_start = array_element_address(data, offset, T_BYTE);6719assert(data_start, "data is NULL");67206721Node* ghash = make_runtime_call(RC_LEAF|RC_NO_FP,6722OptoRuntime::ghash_processBlocks_Type(),6723stubAddr, stubName, TypePtr::BOTTOM,6724state_start, subkeyH_start, data_start, len);6725return true;6726}67276728//------------------------------inline_sha_implCompress-----------------------6729//6730// Calculate SHA (i.e., SHA-1) for single-block byte[] array.6731// void com.sun.security.provider.SHA.implCompress(byte[] buf, int ofs)6732//6733// Calculate SHA2 (i.e., SHA-244 or SHA-256) for single-block byte[] array.6734// void com.sun.security.provider.SHA2.implCompress(byte[] buf, int ofs)6735//6736// Calculate SHA5 (i.e., SHA-384 or SHA-512) for single-block byte[] array.6737// void com.sun.security.provider.SHA5.implCompress(byte[] buf, int ofs)6738//6739bool LibraryCallKit::inline_sha_implCompress(vmIntrinsics::ID id) {6740assert(callee()->signature()->size() == 2, "sha_implCompress has 2 parameters");67416742Node* sha_obj = argument(0);6743Node* src = argument(1); // type oop6744Node* ofs = argument(2); // type int67456746const Type* src_type = src->Value(&_gvn);6747const TypeAryPtr* top_src = src_type->isa_aryptr();6748if (top_src == NULL || top_src->klass() == NULL) {6749// failed array check6750return false;6751}6752// Figure out the size and type of the elements we will be copying.6753BasicType src_elem = src_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();6754if (src_elem != T_BYTE) {6755return false;6756}6757// 'src_start' points to src array + offset6758Node* src_start = array_element_address(src, ofs, src_elem);6759Node* state = NULL;6760address stubAddr;6761const char *stubName;67626763switch(id) {6764case vmIntrinsics::_sha_implCompress:6765assert(UseSHA1Intrinsics, "need SHA1 instruction support");6766state = get_state_from_sha_object(sha_obj);6767stubAddr = StubRoutines::sha1_implCompress();6768stubName = "sha1_implCompress";6769break;6770case vmIntrinsics::_sha2_implCompress:6771assert(UseSHA256Intrinsics, "need SHA256 instruction support");6772state = get_state_from_sha_object(sha_obj);6773stubAddr = StubRoutines::sha256_implCompress();6774stubName = "sha256_implCompress";6775break;6776case vmIntrinsics::_sha5_implCompress:6777assert(UseSHA512Intrinsics, "need SHA512 instruction support");6778state = get_state_from_sha5_object(sha_obj);6779stubAddr = StubRoutines::sha512_implCompress();6780stubName = "sha512_implCompress";6781break;6782default:6783fatal_unexpected_iid(id);6784return false;6785}6786if (state == NULL) return false;67876788// Call the stub.6789Node* call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::sha_implCompress_Type(),6790stubAddr, stubName, TypePtr::BOTTOM,6791src_start, state);67926793return true;6794}67956796//------------------------------inline_digestBase_implCompressMB-----------------------6797//6798// Calculate SHA/SHA2/SHA5 for multi-block byte[] array.6799// int com.sun.security.provider.DigestBase.implCompressMultiBlock(byte[] b, int ofs, int limit)6800//6801bool LibraryCallKit::inline_digestBase_implCompressMB(int predicate) {6802assert(UseSHA1Intrinsics || UseSHA256Intrinsics || UseSHA512Intrinsics,6803"need SHA1/SHA256/SHA512 instruction support");6804assert((uint)predicate < 3, "sanity");6805assert(callee()->signature()->size() == 3, "digestBase_implCompressMB has 3 parameters");68066807Node* digestBase_obj = argument(0); // The receiver was checked for NULL already.6808Node* src = argument(1); // byte[] array6809Node* ofs = argument(2); // type int6810Node* limit = argument(3); // type int68116812const Type* src_type = src->Value(&_gvn);6813const TypeAryPtr* top_src = src_type->isa_aryptr();6814if (top_src == NULL || top_src->klass() == NULL) {6815// failed array check6816return false;6817}6818// Figure out the size and type of the elements we will be copying.6819BasicType src_elem = src_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();6820if (src_elem != T_BYTE) {6821return false;6822}6823// 'src_start' points to src array + offset6824Node* src_start = array_element_address(src, ofs, src_elem);68256826const char* klass_SHA_name = NULL;6827const char* stub_name = NULL;6828address stub_addr = NULL;6829bool long_state = false;68306831switch (predicate) {6832case 0:6833if (UseSHA1Intrinsics) {6834klass_SHA_name = "sun/security/provider/SHA";6835stub_name = "sha1_implCompressMB";6836stub_addr = StubRoutines::sha1_implCompressMB();6837}6838break;6839case 1:6840if (UseSHA256Intrinsics) {6841klass_SHA_name = "sun/security/provider/SHA2";6842stub_name = "sha256_implCompressMB";6843stub_addr = StubRoutines::sha256_implCompressMB();6844}6845break;6846case 2:6847if (UseSHA512Intrinsics) {6848klass_SHA_name = "sun/security/provider/SHA5";6849stub_name = "sha512_implCompressMB";6850stub_addr = StubRoutines::sha512_implCompressMB();6851long_state = true;6852}6853break;6854default:6855fatal(err_msg_res("unknown SHA intrinsic predicate: %d", predicate));6856}6857if (klass_SHA_name != NULL) {6858// get DigestBase klass to lookup for SHA klass6859const TypeInstPtr* tinst = _gvn.type(digestBase_obj)->isa_instptr();6860assert(tinst != NULL, "digestBase_obj is not instance???");6861assert(tinst->klass()->is_loaded(), "DigestBase is not loaded");68626863ciKlass* klass_SHA = tinst->klass()->as_instance_klass()->find_klass(ciSymbol::make(klass_SHA_name));6864assert(klass_SHA->is_loaded(), "predicate checks that this class is loaded");6865ciInstanceKlass* instklass_SHA = klass_SHA->as_instance_klass();6866return inline_sha_implCompressMB(digestBase_obj, instklass_SHA, long_state, stub_addr, stub_name, src_start, ofs, limit);6867}6868return false;6869}6870//------------------------------inline_sha_implCompressMB-----------------------6871bool LibraryCallKit::inline_sha_implCompressMB(Node* digestBase_obj, ciInstanceKlass* instklass_SHA,6872bool long_state, address stubAddr, const char *stubName,6873Node* src_start, Node* ofs, Node* limit) {6874const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_SHA);6875const TypeOopPtr* xtype = aklass->as_instance_type();6876Node* sha_obj = new (C) CheckCastPPNode(control(), digestBase_obj, xtype);6877sha_obj = _gvn.transform(sha_obj);68786879Node* state;6880if (long_state) {6881state = get_state_from_sha5_object(sha_obj);6882} else {6883state = get_state_from_sha_object(sha_obj);6884}6885if (state == NULL) return false;68866887// Call the stub.6888Node *call;6889if (CCallingConventionRequiresIntsAsLongs) {6890call = make_runtime_call(RC_LEAF|RC_NO_FP,6891OptoRuntime::digestBase_implCompressMB_Type(),6892stubAddr, stubName, TypePtr::BOTTOM,6893src_start, state, ofs XTOP, limit XTOP);6894} else {6895call = make_runtime_call(RC_LEAF|RC_NO_FP,6896OptoRuntime::digestBase_implCompressMB_Type(),6897stubAddr, stubName, TypePtr::BOTTOM,6898src_start, state, ofs, limit);6899}6900// return ofs (int)6901Node* result = _gvn.transform(new (C) ProjNode(call, TypeFunc::Parms));6902set_result(result);69036904return true;6905}69066907//------------------------------get_state_from_sha_object-----------------------6908Node * LibraryCallKit::get_state_from_sha_object(Node *sha_object) {6909Node* sha_state = load_field_from_object(sha_object, "state", "[I", /*is_exact*/ false);6910assert (sha_state != NULL, "wrong version of sun.security.provider.SHA/SHA2");6911if (sha_state == NULL) return (Node *) NULL;69126913// now have the array, need to get the start address of the state array6914Node* state = array_element_address(sha_state, intcon(0), T_INT);6915return state;6916}69176918//------------------------------get_state_from_sha5_object-----------------------6919Node * LibraryCallKit::get_state_from_sha5_object(Node *sha_object) {6920Node* sha_state = load_field_from_object(sha_object, "state", "[J", /*is_exact*/ false);6921assert (sha_state != NULL, "wrong version of sun.security.provider.SHA5");6922if (sha_state == NULL) return (Node *) NULL;69236924// now have the array, need to get the start address of the state array6925Node* state = array_element_address(sha_state, intcon(0), T_LONG);6926return state;6927}69286929//----------------------------inline_digestBase_implCompressMB_predicate----------------------------6930// Return node representing slow path of predicate check.6931// the pseudo code we want to emulate with this predicate is:6932// if (digestBaseObj instanceof SHA/SHA2/SHA5) do_intrinsic, else do_javapath6933//6934Node* LibraryCallKit::inline_digestBase_implCompressMB_predicate(int predicate) {6935assert(UseSHA1Intrinsics || UseSHA256Intrinsics || UseSHA512Intrinsics,6936"need SHA1/SHA256/SHA512 instruction support");6937assert((uint)predicate < 3, "sanity");69386939// The receiver was checked for NULL already.6940Node* digestBaseObj = argument(0);69416942// get DigestBase klass for instanceOf check6943const TypeInstPtr* tinst = _gvn.type(digestBaseObj)->isa_instptr();6944assert(tinst != NULL, "digestBaseObj is null");6945assert(tinst->klass()->is_loaded(), "DigestBase is not loaded");69466947const char* klass_SHA_name = NULL;6948switch (predicate) {6949case 0:6950if (UseSHA1Intrinsics) {6951// we want to do an instanceof comparison against the SHA class6952klass_SHA_name = "sun/security/provider/SHA";6953}6954break;6955case 1:6956if (UseSHA256Intrinsics) {6957// we want to do an instanceof comparison against the SHA2 class6958klass_SHA_name = "sun/security/provider/SHA2";6959}6960break;6961case 2:6962if (UseSHA512Intrinsics) {6963// we want to do an instanceof comparison against the SHA5 class6964klass_SHA_name = "sun/security/provider/SHA5";6965}6966break;6967default:6968fatal(err_msg_res("unknown SHA intrinsic predicate: %d", predicate));6969}69706971ciKlass* klass_SHA = NULL;6972if (klass_SHA_name != NULL) {6973klass_SHA = tinst->klass()->as_instance_klass()->find_klass(ciSymbol::make(klass_SHA_name));6974}6975if ((klass_SHA == NULL) || !klass_SHA->is_loaded()) {6976// if none of SHA/SHA2/SHA5 is loaded, we never take the intrinsic fast path6977Node* ctrl = control();6978set_control(top()); // no intrinsic path6979return ctrl;6980}6981ciInstanceKlass* instklass_SHA = klass_SHA->as_instance_klass();69826983Node* instofSHA = gen_instanceof(digestBaseObj, makecon(TypeKlassPtr::make(instklass_SHA)));6984Node* cmp_instof = _gvn.transform(new (C) CmpINode(instofSHA, intcon(1)));6985Node* bool_instof = _gvn.transform(new (C) BoolNode(cmp_instof, BoolTest::ne));6986Node* instof_false = generate_guard(bool_instof, NULL, PROB_MIN);69876988return instof_false; // even if it is NULL6989}69906991bool LibraryCallKit::inline_profileBoolean() {6992Node* counts = argument(1);6993const TypeAryPtr* ary = NULL;6994ciArray* aobj = NULL;6995if (counts->is_Con()6996&& (ary = counts->bottom_type()->isa_aryptr()) != NULL6997&& (aobj = ary->const_oop()->as_array()) != NULL6998&& (aobj->length() == 2)) {6999// Profile is int[2] where [0] and [1] correspond to false and true value occurrences respectively.7000jint false_cnt = aobj->element_value(0).as_int();7001jint true_cnt = aobj->element_value(1).as_int();70027003if (C->log() != NULL) {7004C->log()->elem("observe source='profileBoolean' false='%d' true='%d'",7005false_cnt, true_cnt);7006}70077008if (false_cnt + true_cnt == 0) {7009// According to profile, never executed.7010uncommon_trap_exact(Deoptimization::Reason_intrinsic,7011Deoptimization::Action_reinterpret);7012return true;7013}70147015// result is a boolean (0 or 1) and its profile (false_cnt & true_cnt)7016// is a number of each value occurrences.7017Node* result = argument(0);7018if (false_cnt == 0 || true_cnt == 0) {7019// According to profile, one value has been never seen.7020int expected_val = (false_cnt == 0) ? 1 : 0;70217022Node* cmp = _gvn.transform(new (C) CmpINode(result, intcon(expected_val)));7023Node* test = _gvn.transform(new (C) BoolNode(cmp, BoolTest::eq));70247025IfNode* check = create_and_map_if(control(), test, PROB_ALWAYS, COUNT_UNKNOWN);7026Node* fast_path = _gvn.transform(new (C) IfTrueNode(check));7027Node* slow_path = _gvn.transform(new (C) IfFalseNode(check));70287029{ // Slow path: uncommon trap for never seen value and then reexecute7030// MethodHandleImpl::profileBoolean() to bump the count, so JIT knows7031// the value has been seen at least once.7032PreserveJVMState pjvms(this);7033PreserveReexecuteState preexecs(this);7034jvms()->set_should_reexecute(true);70357036set_control(slow_path);7037set_i_o(i_o());70387039uncommon_trap_exact(Deoptimization::Reason_intrinsic,7040Deoptimization::Action_reinterpret);7041}7042// The guard for never seen value enables sharpening of the result and7043// returning a constant. It allows to eliminate branches on the same value7044// later on.7045set_control(fast_path);7046result = intcon(expected_val);7047}7048// Stop profiling.7049// MethodHandleImpl::profileBoolean() has profiling logic in its bytecode.7050// By replacing method body with profile data (represented as ProfileBooleanNode7051// on IR level) we effectively disable profiling.7052// It enables full speed execution once optimized code is generated.7053Node* profile = _gvn.transform(new (C) ProfileBooleanNode(result, false_cnt, true_cnt));7054C->record_for_igvn(profile);7055set_result(profile);7056return true;7057} else {7058// Continue profiling.7059// Profile data isn't available at the moment. So, execute method's bytecode version.7060// Usually, when GWT LambdaForms are profiled it means that a stand-alone nmethod7061// is compiled and counters aren't available since corresponding MethodHandle7062// isn't a compile-time constant.7063return false;7064}7065}706670677068