Path: blob/jdk8u272-b10-aarch32-20201026/hotspot/src/share/vm/opto/library_call.cpp
83404 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"4445class LibraryIntrinsic : public InlineCallGenerator {46// Extend the set of intrinsics known to the runtime:47public:48private:49bool _is_virtual;50bool _does_virtual_dispatch;51int8_t _predicates_count; // Intrinsic is predicated by several conditions52int8_t _last_predicate; // Last generated predicate53vmIntrinsics::ID _intrinsic_id;5455public:56LibraryIntrinsic(ciMethod* m, bool is_virtual, int predicates_count, bool does_virtual_dispatch, vmIntrinsics::ID id)57: InlineCallGenerator(m),58_is_virtual(is_virtual),59_does_virtual_dispatch(does_virtual_dispatch),60_predicates_count((int8_t)predicates_count),61_last_predicate((int8_t)-1),62_intrinsic_id(id)63{64}65virtual bool is_intrinsic() const { return true; }66virtual bool is_virtual() const { return _is_virtual; }67virtual bool is_predicated() const { return _predicates_count > 0; }68virtual int predicates_count() const { return _predicates_count; }69virtual bool does_virtual_dispatch() const { return _does_virtual_dispatch; }70virtual JVMState* generate(JVMState* jvms);71virtual Node* generate_predicate(JVMState* jvms, int predicate);72vmIntrinsics::ID intrinsic_id() const { return _intrinsic_id; }73};747576// Local helper class for LibraryIntrinsic:77class LibraryCallKit : public GraphKit {78private:79LibraryIntrinsic* _intrinsic; // the library intrinsic being called80Node* _result; // the result node, if any81int _reexecute_sp; // the stack pointer when bytecode needs to be reexecuted8283const TypeOopPtr* sharpen_unsafe_type(Compile::AliasType* alias_type, const TypePtr *adr_type, bool is_native_ptr = false);8485public:86LibraryCallKit(JVMState* jvms, LibraryIntrinsic* intrinsic)87: GraphKit(jvms),88_intrinsic(intrinsic),89_result(NULL)90{91// Check if this is a root compile. In that case we don't have a caller.92if (!jvms->has_method()) {93_reexecute_sp = sp();94} else {95// Find out how many arguments the interpreter needs when deoptimizing96// and save the stack pointer value so it can used by uncommon_trap.97// We find the argument count by looking at the declared signature.98bool ignored_will_link;99ciSignature* declared_signature = NULL;100ciMethod* ignored_callee = caller()->get_method_at_bci(bci(), ignored_will_link, &declared_signature);101const int nargs = declared_signature->arg_size_for_bc(caller()->java_code_at_bci(bci()));102_reexecute_sp = sp() + nargs; // "push" arguments back on stack103}104}105106virtual LibraryCallKit* is_LibraryCallKit() const { return (LibraryCallKit*)this; }107108ciMethod* caller() const { return jvms()->method(); }109int bci() const { return jvms()->bci(); }110LibraryIntrinsic* intrinsic() const { return _intrinsic; }111vmIntrinsics::ID intrinsic_id() const { return _intrinsic->intrinsic_id(); }112ciMethod* callee() const { return _intrinsic->method(); }113114bool try_to_inline(int predicate);115Node* try_to_predicate(int predicate);116117void push_result() {118// Push the result onto the stack.119if (!stopped() && result() != NULL) {120BasicType bt = result()->bottom_type()->basic_type();121push_node(bt, result());122}123}124125private:126void fatal_unexpected_iid(vmIntrinsics::ID iid) {127fatal(err_msg_res("unexpected intrinsic %d: %s", iid, vmIntrinsics::name_at(iid)));128}129130void set_result(Node* n) { assert(_result == NULL, "only set once"); _result = n; }131void set_result(RegionNode* region, PhiNode* value);132Node* result() { return _result; }133134virtual int reexecute_sp() { return _reexecute_sp; }135136// Helper functions to inline natives137Node* generate_guard(Node* test, RegionNode* region, float true_prob);138Node* generate_slow_guard(Node* test, RegionNode* region);139Node* generate_fair_guard(Node* test, RegionNode* region);140Node* generate_negative_guard(Node* index, RegionNode* region,141// resulting CastII of index:142Node* *pos_index = NULL);143Node* generate_nonpositive_guard(Node* index, bool never_negative,144// resulting CastII of index:145Node* *pos_index = NULL);146Node* generate_limit_guard(Node* offset, Node* subseq_length,147Node* array_length,148RegionNode* region);149Node* generate_current_thread(Node* &tls_output);150address basictype2arraycopy(BasicType t, Node *src_offset, Node *dest_offset,151bool disjoint_bases, const char* &name, bool dest_uninitialized);152Node* load_mirror_from_klass(Node* klass);153Node* load_klass_from_mirror_common(Node* mirror, bool never_see_null,154RegionNode* region, int null_path,155int offset);156Node* load_klass_from_mirror(Node* mirror, bool never_see_null,157RegionNode* region, int null_path) {158int offset = java_lang_Class::klass_offset_in_bytes();159return load_klass_from_mirror_common(mirror, never_see_null,160region, null_path,161offset);162}163Node* load_array_klass_from_mirror(Node* mirror, bool never_see_null,164RegionNode* region, int null_path) {165int offset = java_lang_Class::array_klass_offset_in_bytes();166return load_klass_from_mirror_common(mirror, never_see_null,167region, null_path,168offset);169}170Node* generate_access_flags_guard(Node* kls,171int modifier_mask, int modifier_bits,172RegionNode* region);173Node* generate_interface_guard(Node* kls, RegionNode* region);174Node* generate_array_guard(Node* kls, RegionNode* region) {175return generate_array_guard_common(kls, region, false, false);176}177Node* generate_non_array_guard(Node* kls, RegionNode* region) {178return generate_array_guard_common(kls, region, false, true);179}180Node* generate_objArray_guard(Node* kls, RegionNode* region) {181return generate_array_guard_common(kls, region, true, false);182}183Node* generate_non_objArray_guard(Node* kls, RegionNode* region) {184return generate_array_guard_common(kls, region, true, true);185}186Node* generate_array_guard_common(Node* kls, RegionNode* region,187bool obj_array, bool not_array);188Node* generate_virtual_guard(Node* obj_klass, RegionNode* slow_region);189CallJavaNode* generate_method_call(vmIntrinsics::ID method_id,190bool is_virtual = false, bool is_static = false);191CallJavaNode* generate_method_call_static(vmIntrinsics::ID method_id) {192return generate_method_call(method_id, false, true);193}194CallJavaNode* generate_method_call_virtual(vmIntrinsics::ID method_id) {195return generate_method_call(method_id, true, false);196}197Node * load_field_from_object(Node * fromObj, const char * fieldName, const char * fieldTypeString, bool is_exact, bool is_static);198199Node* make_string_method_node(int opcode, Node* str1_start, Node* cnt1, Node* str2_start, Node* cnt2);200Node* make_string_method_node(int opcode, Node* str1, Node* str2);201bool inline_string_compareTo();202bool inline_string_indexOf();203Node* string_indexOf(Node* string_object, ciTypeArray* target_array, jint offset, jint cache_i, jint md2_i);204bool inline_string_equals();205Node* round_double_node(Node* n);206bool runtime_math(const TypeFunc* call_type, address funcAddr, const char* funcName);207bool inline_math_native(vmIntrinsics::ID id);208bool inline_trig(vmIntrinsics::ID id);209bool inline_math(vmIntrinsics::ID id);210template <typename OverflowOp>211bool inline_math_overflow(Node* arg1, Node* arg2);212void inline_math_mathExact(Node* math, Node* test);213bool inline_math_addExactI(bool is_increment);214bool inline_math_addExactL(bool is_increment);215bool inline_math_multiplyExactI();216bool inline_math_multiplyExactL();217bool inline_math_negateExactI();218bool inline_math_negateExactL();219bool inline_math_subtractExactI(bool is_decrement);220bool inline_math_subtractExactL(bool is_decrement);221bool inline_exp();222bool inline_pow();223Node* finish_pow_exp(Node* result, Node* x, Node* y, const TypeFunc* call_type, address funcAddr, const char* funcName);224bool inline_min_max(vmIntrinsics::ID id);225Node* generate_min_max(vmIntrinsics::ID id, Node* x, Node* y);226// This returns Type::AnyPtr, RawPtr, or OopPtr.227int classify_unsafe_addr(Node* &base, Node* &offset);228Node* make_unsafe_address(Node* base, Node* offset);229// Helper for inline_unsafe_access.230// Generates the guards that check whether the result of231// Unsafe.getObject should be recorded in an SATB log buffer.232void insert_pre_barrier(Node* base_oop, Node* offset, Node* pre_val, bool need_mem_bar);233bool inline_unsafe_access(bool is_native_ptr, bool is_store, BasicType type, bool is_volatile, bool is_unaligned);234bool inline_unsafe_prefetch(bool is_native_ptr, bool is_store, bool is_static);235static bool klass_needs_init_guard(Node* kls);236bool inline_unsafe_allocate();237bool inline_unsafe_copyMemory();238bool inline_native_currentThread();239#ifdef JFR_HAVE_INTRINSICS240bool inline_native_classID();241bool inline_native_getEventWriter();242#endif243bool inline_native_time_funcs(address method, const char* funcName);244bool inline_native_isInterrupted();245bool inline_native_Class_query(vmIntrinsics::ID id);246bool inline_native_subtype_check();247248bool inline_native_newArray();249bool inline_native_getLength();250bool inline_array_copyOf(bool is_copyOfRange);251bool inline_array_equals();252void copy_to_clone(Node* obj, Node* alloc_obj, Node* obj_size, bool is_array, bool card_mark);253bool inline_native_clone(bool is_virtual);254bool inline_native_Reflection_getCallerClass();255// Helper function for inlining native object hash method256bool inline_native_hashcode(bool is_virtual, bool is_static);257bool inline_native_getClass();258259// Helper functions for inlining arraycopy260bool inline_arraycopy();261void generate_arraycopy(const TypePtr* adr_type,262BasicType basic_elem_type,263Node* src, Node* src_offset,264Node* dest, Node* dest_offset,265Node* copy_length,266bool disjoint_bases = false,267bool length_never_negative = false,268RegionNode* slow_region = NULL);269AllocateArrayNode* tightly_coupled_allocation(Node* ptr,270RegionNode* slow_region);271void generate_clear_array(const TypePtr* adr_type,272Node* dest,273BasicType basic_elem_type,274Node* slice_off,275Node* slice_len,276Node* slice_end);277bool generate_block_arraycopy(const TypePtr* adr_type,278BasicType basic_elem_type,279AllocateNode* alloc,280Node* src, Node* src_offset,281Node* dest, Node* dest_offset,282Node* dest_size, bool dest_uninitialized);283void generate_slow_arraycopy(const TypePtr* adr_type,284Node* src, Node* src_offset,285Node* dest, Node* dest_offset,286Node* copy_length, bool dest_uninitialized);287Node* generate_checkcast_arraycopy(const TypePtr* adr_type,288Node* dest_elem_klass,289Node* src, Node* src_offset,290Node* dest, Node* dest_offset,291Node* copy_length, bool dest_uninitialized);292Node* generate_generic_arraycopy(const TypePtr* adr_type,293Node* src, Node* src_offset,294Node* dest, Node* dest_offset,295Node* copy_length, bool dest_uninitialized);296void generate_unchecked_arraycopy(const TypePtr* adr_type,297BasicType basic_elem_type,298bool disjoint_bases,299Node* src, Node* src_offset,300Node* dest, Node* dest_offset,301Node* copy_length, bool dest_uninitialized);302typedef enum { LS_xadd, LS_xchg, LS_cmpxchg } LoadStoreKind;303bool inline_unsafe_load_store(BasicType type, LoadStoreKind kind);304bool inline_unsafe_ordered_store(BasicType type);305bool inline_unsafe_fence(vmIntrinsics::ID id);306bool inline_fp_conversions(vmIntrinsics::ID id);307bool inline_number_methods(vmIntrinsics::ID id);308bool inline_reference_get();309bool inline_aescrypt_Block(vmIntrinsics::ID id);310bool inline_cipherBlockChaining_AESCrypt(vmIntrinsics::ID id);311Node* inline_cipherBlockChaining_AESCrypt_predicate(bool decrypting);312Node* get_key_start_from_aescrypt_object(Node* aescrypt_object);313Node* get_original_key_start_from_aescrypt_object(Node* aescrypt_object);314bool inline_ghash_processBlocks();315bool inline_sha_implCompress(vmIntrinsics::ID id);316bool inline_digestBase_implCompressMB(int predicate);317bool inline_sha_implCompressMB(Node* digestBaseObj, ciInstanceKlass* instklass_SHA,318bool long_state, address stubAddr, const char *stubName,319Node* src_start, Node* ofs, Node* limit);320Node* get_state_from_sha_object(Node *sha_object);321Node* get_state_from_sha5_object(Node *sha_object);322Node* inline_digestBase_implCompressMB_predicate(int predicate);323bool inline_encodeISOArray();324bool inline_updateCRC32();325bool inline_updateBytesCRC32();326bool inline_updateByteBufferCRC32();327bool inline_multiplyToLen();328bool inline_squareToLen();329bool inline_mulAdd();330bool inline_montgomeryMultiply();331bool inline_montgomerySquare();332333bool inline_profileBoolean();334};335336337//---------------------------make_vm_intrinsic----------------------------338CallGenerator* Compile::make_vm_intrinsic(ciMethod* m, bool is_virtual) {339vmIntrinsics::ID id = m->intrinsic_id();340assert(id != vmIntrinsics::_none, "must be a VM intrinsic");341342ccstr disable_intr = NULL;343344if ((DisableIntrinsic[0] != '\0'345&& strstr(DisableIntrinsic, vmIntrinsics::name_at(id)) != NULL) ||346(method_has_option_value("DisableIntrinsic", disable_intr)347&& strstr(disable_intr, vmIntrinsics::name_at(id)) != NULL)) {348// disabled by a user request on the command line:349// example: -XX:DisableIntrinsic=_hashCode,_getClass350return NULL;351}352353if (!m->is_loaded()) {354// do not attempt to inline unloaded methods355return NULL;356}357358// Only a few intrinsics implement a virtual dispatch.359// They are expensive calls which are also frequently overridden.360if (is_virtual) {361switch (id) {362case vmIntrinsics::_hashCode:363case vmIntrinsics::_clone:364// OK, Object.hashCode and Object.clone intrinsics come in both flavors365break;366default:367return NULL;368}369}370371// -XX:-InlineNatives disables nearly all intrinsics:372if (!InlineNatives) {373switch (id) {374case vmIntrinsics::_indexOf:375case vmIntrinsics::_compareTo:376case vmIntrinsics::_equals:377case vmIntrinsics::_equalsC:378case vmIntrinsics::_getAndAddInt:379case vmIntrinsics::_getAndAddLong:380case vmIntrinsics::_getAndSetInt:381case vmIntrinsics::_getAndSetLong:382case vmIntrinsics::_getAndSetObject:383case vmIntrinsics::_loadFence:384case vmIntrinsics::_storeFence:385case vmIntrinsics::_fullFence:386break; // InlineNatives does not control String.compareTo387case vmIntrinsics::_Reference_get:388break; // InlineNatives does not control Reference.get389default:390return NULL;391}392}393394int predicates = 0;395bool does_virtual_dispatch = false;396397switch (id) {398case vmIntrinsics::_compareTo:399if (!SpecialStringCompareTo) return NULL;400if (!Matcher::match_rule_supported(Op_StrComp)) return NULL;401break;402case vmIntrinsics::_indexOf:403if (!SpecialStringIndexOf) return NULL;404break;405case vmIntrinsics::_equals:406if (!SpecialStringEquals) return NULL;407if (!Matcher::match_rule_supported(Op_StrEquals)) return NULL;408break;409case vmIntrinsics::_equalsC:410if (!SpecialArraysEquals) return NULL;411if (!Matcher::match_rule_supported(Op_AryEq)) return NULL;412break;413case vmIntrinsics::_arraycopy:414if (!InlineArrayCopy) return NULL;415break;416case vmIntrinsics::_copyMemory:417if (StubRoutines::unsafe_arraycopy() == NULL) return NULL;418if (!InlineArrayCopy) return NULL;419break;420case vmIntrinsics::_hashCode:421if (!InlineObjectHash) return NULL;422does_virtual_dispatch = true;423break;424case vmIntrinsics::_clone:425does_virtual_dispatch = true;426case vmIntrinsics::_copyOf:427case vmIntrinsics::_copyOfRange:428if (!InlineObjectCopy) return NULL;429// These also use the arraycopy intrinsic mechanism:430if (!InlineArrayCopy) return NULL;431break;432case vmIntrinsics::_encodeISOArray:433if (!SpecialEncodeISOArray) return NULL;434if (!Matcher::match_rule_supported(Op_EncodeISOArray)) return NULL;435break;436case vmIntrinsics::_checkIndex:437// We do not intrinsify this. The optimizer does fine with it.438return NULL;439440case vmIntrinsics::_getCallerClass:441if (!UseNewReflection) return NULL;442if (!InlineReflectionGetCallerClass) return NULL;443if (SystemDictionary::reflect_CallerSensitive_klass() == NULL) return NULL;444break;445446case vmIntrinsics::_bitCount_i:447if (!Matcher::match_rule_supported(Op_PopCountI)) return NULL;448break;449450case vmIntrinsics::_bitCount_l:451if (!Matcher::match_rule_supported(Op_PopCountL)) return NULL;452break;453454case vmIntrinsics::_numberOfLeadingZeros_i:455if (!Matcher::match_rule_supported(Op_CountLeadingZerosI)) return NULL;456break;457458case vmIntrinsics::_numberOfLeadingZeros_l:459if (!Matcher::match_rule_supported(Op_CountLeadingZerosL)) return NULL;460break;461462case vmIntrinsics::_numberOfTrailingZeros_i:463if (!Matcher::match_rule_supported(Op_CountTrailingZerosI)) return NULL;464break;465466case vmIntrinsics::_numberOfTrailingZeros_l:467if (!Matcher::match_rule_supported(Op_CountTrailingZerosL)) return NULL;468break;469470case vmIntrinsics::_reverseBytes_c:471if (!Matcher::match_rule_supported(Op_ReverseBytesUS)) return NULL;472break;473case vmIntrinsics::_reverseBytes_s:474if (!Matcher::match_rule_supported(Op_ReverseBytesS)) return NULL;475break;476case vmIntrinsics::_reverseBytes_i:477if (!Matcher::match_rule_supported(Op_ReverseBytesI)) return NULL;478break;479case vmIntrinsics::_reverseBytes_l:480if (!Matcher::match_rule_supported(Op_ReverseBytesL)) return NULL;481break;482483case vmIntrinsics::_Reference_get:484// Use the intrinsic version of Reference.get() so that the value in485// the referent field can be registered by the G1 pre-barrier code.486// Also add memory barrier to prevent commoning reads from this field487// across safepoint since GC can change it value.488break;489490case vmIntrinsics::_compareAndSwapObject:491#ifdef _LP64492if (!UseCompressedOops && !Matcher::match_rule_supported(Op_CompareAndSwapP)) return NULL;493#endif494break;495496case vmIntrinsics::_compareAndSwapLong:497if (!Matcher::match_rule_supported(Op_CompareAndSwapL)) return NULL;498break;499500case vmIntrinsics::_getAndAddInt:501if (!Matcher::match_rule_supported(Op_GetAndAddI)) return NULL;502break;503504case vmIntrinsics::_getAndAddLong:505if (!Matcher::match_rule_supported(Op_GetAndAddL)) return NULL;506break;507508case vmIntrinsics::_getAndSetInt:509if (!Matcher::match_rule_supported(Op_GetAndSetI)) return NULL;510break;511512case vmIntrinsics::_getAndSetLong:513if (!Matcher::match_rule_supported(Op_GetAndSetL)) return NULL;514break;515516case vmIntrinsics::_getAndSetObject:517#ifdef _LP64518if (!UseCompressedOops && !Matcher::match_rule_supported(Op_GetAndSetP)) return NULL;519if (UseCompressedOops && !Matcher::match_rule_supported(Op_GetAndSetN)) return NULL;520break;521#else522if (!Matcher::match_rule_supported(Op_GetAndSetP)) return NULL;523break;524#endif525526case vmIntrinsics::_aescrypt_encryptBlock:527case vmIntrinsics::_aescrypt_decryptBlock:528if (!UseAESIntrinsics) return NULL;529break;530531case vmIntrinsics::_multiplyToLen:532if (!UseMultiplyToLenIntrinsic) return NULL;533break;534535case vmIntrinsics::_squareToLen:536if (!UseSquareToLenIntrinsic) return NULL;537break;538539case vmIntrinsics::_mulAdd:540if (!UseMulAddIntrinsic) return NULL;541break;542543case vmIntrinsics::_montgomeryMultiply:544if (!UseMontgomeryMultiplyIntrinsic) return NULL;545break;546case vmIntrinsics::_montgomerySquare:547if (!UseMontgomerySquareIntrinsic) return NULL;548break;549550case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:551case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:552if (!UseAESIntrinsics) return NULL;553// these two require the predicated logic554predicates = 1;555break;556557case vmIntrinsics::_sha_implCompress:558if (!UseSHA1Intrinsics) return NULL;559break;560561case vmIntrinsics::_sha2_implCompress:562if (!UseSHA256Intrinsics) return NULL;563break;564565case vmIntrinsics::_sha5_implCompress:566if (!UseSHA512Intrinsics) return NULL;567break;568569case vmIntrinsics::_digestBase_implCompressMB:570if (!(UseSHA1Intrinsics || UseSHA256Intrinsics || UseSHA512Intrinsics)) return NULL;571predicates = 3;572break;573574case vmIntrinsics::_ghash_processBlocks:575if (!UseGHASHIntrinsics) return NULL;576break;577578case vmIntrinsics::_updateCRC32:579case vmIntrinsics::_updateBytesCRC32:580case vmIntrinsics::_updateByteBufferCRC32:581if (!UseCRC32Intrinsics) return NULL;582break;583584case vmIntrinsics::_incrementExactI:585case vmIntrinsics::_addExactI:586if (!Matcher::match_rule_supported(Op_OverflowAddI) || !UseMathExactIntrinsics) return NULL;587break;588case vmIntrinsics::_incrementExactL:589case vmIntrinsics::_addExactL:590if (!Matcher::match_rule_supported(Op_OverflowAddL) || !UseMathExactIntrinsics) return NULL;591break;592case vmIntrinsics::_decrementExactI:593case vmIntrinsics::_subtractExactI:594if (!Matcher::match_rule_supported(Op_OverflowSubI) || !UseMathExactIntrinsics) return NULL;595break;596case vmIntrinsics::_decrementExactL:597case vmIntrinsics::_subtractExactL:598if (!Matcher::match_rule_supported(Op_OverflowSubL) || !UseMathExactIntrinsics) return NULL;599break;600case vmIntrinsics::_negateExactI:601if (!Matcher::match_rule_supported(Op_OverflowSubI) || !UseMathExactIntrinsics) return NULL;602break;603case vmIntrinsics::_negateExactL:604if (!Matcher::match_rule_supported(Op_OverflowSubL) || !UseMathExactIntrinsics) return NULL;605break;606case vmIntrinsics::_multiplyExactI:607if (!Matcher::match_rule_supported(Op_OverflowMulI) || !UseMathExactIntrinsics) return NULL;608break;609case vmIntrinsics::_multiplyExactL:610if (!Matcher::match_rule_supported(Op_OverflowMulL) || !UseMathExactIntrinsics) return NULL;611break;612613default:614assert(id <= vmIntrinsics::LAST_COMPILER_INLINE, "caller responsibility");615assert(id != vmIntrinsics::_Object_init && id != vmIntrinsics::_invoke, "enum out of order?");616break;617}618619// -XX:-InlineClassNatives disables natives from the Class class.620// The flag applies to all reflective calls, notably Array.newArray621// (visible to Java programmers as Array.newInstance).622if (m->holder()->name() == ciSymbol::java_lang_Class() ||623m->holder()->name() == ciSymbol::java_lang_reflect_Array()) {624if (!InlineClassNatives) return NULL;625}626627// -XX:-InlineThreadNatives disables natives from the Thread class.628if (m->holder()->name() == ciSymbol::java_lang_Thread()) {629if (!InlineThreadNatives) return NULL;630}631632// -XX:-InlineMathNatives disables natives from the Math,Float and Double classes.633if (m->holder()->name() == ciSymbol::java_lang_Math() ||634m->holder()->name() == ciSymbol::java_lang_Float() ||635m->holder()->name() == ciSymbol::java_lang_Double()) {636if (!InlineMathNatives) return NULL;637}638639// -XX:-InlineUnsafeOps disables natives from the Unsafe class.640if (m->holder()->name() == ciSymbol::sun_misc_Unsafe()) {641if (!InlineUnsafeOps) return NULL;642}643644return new LibraryIntrinsic(m, is_virtual, predicates, does_virtual_dispatch, (vmIntrinsics::ID) id);645}646647//----------------------register_library_intrinsics-----------------------648// Initialize this file's data structures, for each Compile instance.649void Compile::register_library_intrinsics() {650// Nothing to do here.651}652653JVMState* LibraryIntrinsic::generate(JVMState* jvms) {654LibraryCallKit kit(jvms, this);655Compile* C = kit.C;656int nodes = C->unique();657#ifndef PRODUCT658if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {659char buf[1000];660const char* str = vmIntrinsics::short_name_as_C_string(intrinsic_id(), buf, sizeof(buf));661tty->print_cr("Intrinsic %s", str);662}663#endif664ciMethod* callee = kit.callee();665const int bci = kit.bci();666667// Try to inline the intrinsic.668if (kit.try_to_inline(_last_predicate)) {669if (C->print_intrinsics() || C->print_inlining()) {670C->print_inlining(callee, jvms->depth() - 1, bci, is_virtual() ? "(intrinsic, virtual)" : "(intrinsic)");671}672C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_worked);673if (C->log()) {674C->log()->elem("intrinsic id='%s'%s nodes='%d'",675vmIntrinsics::name_at(intrinsic_id()),676(is_virtual() ? " virtual='1'" : ""),677C->unique() - nodes);678}679// Push the result from the inlined method onto the stack.680kit.push_result();681return kit.transfer_exceptions_into_jvms();682}683684// The intrinsic bailed out685if (C->print_intrinsics() || C->print_inlining()) {686if (jvms->has_method()) {687// Not a root compile.688const char* msg = is_virtual() ? "failed to inline (intrinsic, virtual)" : "failed to inline (intrinsic)";689C->print_inlining(callee, jvms->depth() - 1, bci, msg);690} else {691// Root compile692tty->print("Did not generate intrinsic %s%s at bci:%d in",693vmIntrinsics::name_at(intrinsic_id()),694(is_virtual() ? " (virtual)" : ""), bci);695}696}697C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_failed);698return NULL;699}700701Node* LibraryIntrinsic::generate_predicate(JVMState* jvms, int predicate) {702LibraryCallKit kit(jvms, this);703Compile* C = kit.C;704int nodes = C->unique();705_last_predicate = predicate;706#ifndef PRODUCT707assert(is_predicated() && predicate < predicates_count(), "sanity");708if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {709char buf[1000];710const char* str = vmIntrinsics::short_name_as_C_string(intrinsic_id(), buf, sizeof(buf));711tty->print_cr("Predicate for intrinsic %s", str);712}713#endif714ciMethod* callee = kit.callee();715const int bci = kit.bci();716717Node* slow_ctl = kit.try_to_predicate(predicate);718if (!kit.failing()) {719if (C->print_intrinsics() || C->print_inlining()) {720C->print_inlining(callee, jvms->depth() - 1, bci, is_virtual() ? "(intrinsic, virtual, predicate)" : "(intrinsic, predicate)");721}722C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_worked);723if (C->log()) {724C->log()->elem("predicate_intrinsic id='%s'%s nodes='%d'",725vmIntrinsics::name_at(intrinsic_id()),726(is_virtual() ? " virtual='1'" : ""),727C->unique() - nodes);728}729return slow_ctl; // Could be NULL if the check folds.730}731732// The intrinsic bailed out733if (C->print_intrinsics() || C->print_inlining()) {734if (jvms->has_method()) {735// Not a root compile.736const char* msg = "failed to generate predicate for intrinsic";737C->print_inlining(kit.callee(), jvms->depth() - 1, bci, msg);738} else {739// Root compile740C->print_inlining_stream()->print("Did not generate predicate for intrinsic %s%s at bci:%d in",741vmIntrinsics::name_at(intrinsic_id()),742(is_virtual() ? " (virtual)" : ""), bci);743}744}745C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_failed);746return NULL;747}748749bool LibraryCallKit::try_to_inline(int predicate) {750// Handle symbolic names for otherwise undistinguished boolean switches:751const bool is_store = true;752const bool is_native_ptr = true;753const bool is_static = true;754const bool is_volatile = true;755756if (!jvms()->has_method()) {757// Root JVMState has a null method.758assert(map()->memory()->Opcode() == Op_Parm, "");759// Insert the memory aliasing node760set_all_memory(reset_memory());761}762assert(merged_memory(), "");763764765switch (intrinsic_id()) {766case vmIntrinsics::_hashCode: return inline_native_hashcode(intrinsic()->is_virtual(), !is_static);767case vmIntrinsics::_identityHashCode: return inline_native_hashcode(/*!virtual*/ false, is_static);768case vmIntrinsics::_getClass: return inline_native_getClass();769770case vmIntrinsics::_dsin:771case vmIntrinsics::_dcos:772case vmIntrinsics::_dtan:773case vmIntrinsics::_dabs:774case vmIntrinsics::_datan2:775case vmIntrinsics::_dsqrt:776case vmIntrinsics::_dexp:777case vmIntrinsics::_dlog:778case vmIntrinsics::_dlog10:779case vmIntrinsics::_dpow: return inline_math_native(intrinsic_id());780781case vmIntrinsics::_min:782case vmIntrinsics::_max: return inline_min_max(intrinsic_id());783784case vmIntrinsics::_addExactI: return inline_math_addExactI(false /* add */);785case vmIntrinsics::_addExactL: return inline_math_addExactL(false /* add */);786case vmIntrinsics::_decrementExactI: return inline_math_subtractExactI(true /* decrement */);787case vmIntrinsics::_decrementExactL: return inline_math_subtractExactL(true /* decrement */);788case vmIntrinsics::_incrementExactI: return inline_math_addExactI(true /* increment */);789case vmIntrinsics::_incrementExactL: return inline_math_addExactL(true /* increment */);790case vmIntrinsics::_multiplyExactI: return inline_math_multiplyExactI();791case vmIntrinsics::_multiplyExactL: return inline_math_multiplyExactL();792case vmIntrinsics::_negateExactI: return inline_math_negateExactI();793case vmIntrinsics::_negateExactL: return inline_math_negateExactL();794case vmIntrinsics::_subtractExactI: return inline_math_subtractExactI(false /* subtract */);795case vmIntrinsics::_subtractExactL: return inline_math_subtractExactL(false /* subtract */);796797case vmIntrinsics::_arraycopy: return inline_arraycopy();798799case vmIntrinsics::_compareTo: return inline_string_compareTo();800case vmIntrinsics::_indexOf: return inline_string_indexOf();801case vmIntrinsics::_equals: return inline_string_equals();802803case vmIntrinsics::_getObject: return inline_unsafe_access(!is_native_ptr, !is_store, T_OBJECT, !is_volatile, false);804case vmIntrinsics::_getBoolean: return inline_unsafe_access(!is_native_ptr, !is_store, T_BOOLEAN, !is_volatile, false);805case vmIntrinsics::_getByte: return inline_unsafe_access(!is_native_ptr, !is_store, T_BYTE, !is_volatile, false);806case vmIntrinsics::_getShort: return inline_unsafe_access(!is_native_ptr, !is_store, T_SHORT, !is_volatile, false);807case vmIntrinsics::_getChar: return inline_unsafe_access(!is_native_ptr, !is_store, T_CHAR, !is_volatile, false);808case vmIntrinsics::_getInt: return inline_unsafe_access(!is_native_ptr, !is_store, T_INT, !is_volatile, false);809case vmIntrinsics::_getLong: return inline_unsafe_access(!is_native_ptr, !is_store, T_LONG, !is_volatile, false);810case vmIntrinsics::_getFloat: return inline_unsafe_access(!is_native_ptr, !is_store, T_FLOAT, !is_volatile, false);811case vmIntrinsics::_getDouble: return inline_unsafe_access(!is_native_ptr, !is_store, T_DOUBLE, !is_volatile, false);812813case vmIntrinsics::_putObject: return inline_unsafe_access(!is_native_ptr, is_store, T_OBJECT, !is_volatile, false);814case vmIntrinsics::_putBoolean: return inline_unsafe_access(!is_native_ptr, is_store, T_BOOLEAN, !is_volatile, false);815case vmIntrinsics::_putByte: return inline_unsafe_access(!is_native_ptr, is_store, T_BYTE, !is_volatile, false);816case vmIntrinsics::_putShort: return inline_unsafe_access(!is_native_ptr, is_store, T_SHORT, !is_volatile, false);817case vmIntrinsics::_putChar: return inline_unsafe_access(!is_native_ptr, is_store, T_CHAR, !is_volatile, false);818case vmIntrinsics::_putInt: return inline_unsafe_access(!is_native_ptr, is_store, T_INT, !is_volatile, false);819case vmIntrinsics::_putLong: return inline_unsafe_access(!is_native_ptr, is_store, T_LONG, !is_volatile, false);820case vmIntrinsics::_putFloat: return inline_unsafe_access(!is_native_ptr, is_store, T_FLOAT, !is_volatile, false);821case vmIntrinsics::_putDouble: return inline_unsafe_access(!is_native_ptr, is_store, T_DOUBLE, !is_volatile, false);822823case vmIntrinsics::_getByte_raw: return inline_unsafe_access( is_native_ptr, !is_store, T_BYTE, !is_volatile, false);824case vmIntrinsics::_getShort_raw: return inline_unsafe_access( is_native_ptr, !is_store, T_SHORT, !is_volatile, false);825case vmIntrinsics::_getChar_raw: return inline_unsafe_access( is_native_ptr, !is_store, T_CHAR, !is_volatile, false);826case vmIntrinsics::_getInt_raw: return inline_unsafe_access( is_native_ptr, !is_store, T_INT, !is_volatile, false);827case vmIntrinsics::_getLong_raw: return inline_unsafe_access( is_native_ptr, !is_store, T_LONG, !is_volatile, false);828case vmIntrinsics::_getFloat_raw: return inline_unsafe_access( is_native_ptr, !is_store, T_FLOAT, !is_volatile, false);829case vmIntrinsics::_getDouble_raw: return inline_unsafe_access( is_native_ptr, !is_store, T_DOUBLE, !is_volatile, false);830case vmIntrinsics::_getAddress_raw: return inline_unsafe_access( is_native_ptr, !is_store, T_ADDRESS, !is_volatile, false);831832case vmIntrinsics::_putByte_raw: return inline_unsafe_access( is_native_ptr, is_store, T_BYTE, !is_volatile, false);833case vmIntrinsics::_putShort_raw: return inline_unsafe_access( is_native_ptr, is_store, T_SHORT, !is_volatile, false);834case vmIntrinsics::_putChar_raw: return inline_unsafe_access( is_native_ptr, is_store, T_CHAR, !is_volatile, false);835case vmIntrinsics::_putInt_raw: return inline_unsafe_access( is_native_ptr, is_store, T_INT, !is_volatile, false);836case vmIntrinsics::_putLong_raw: return inline_unsafe_access( is_native_ptr, is_store, T_LONG, !is_volatile, false);837case vmIntrinsics::_putFloat_raw: return inline_unsafe_access( is_native_ptr, is_store, T_FLOAT, !is_volatile, false);838case vmIntrinsics::_putDouble_raw: return inline_unsafe_access( is_native_ptr, is_store, T_DOUBLE, !is_volatile, false);839case vmIntrinsics::_putAddress_raw: return inline_unsafe_access( is_native_ptr, is_store, T_ADDRESS, !is_volatile, false);840841case vmIntrinsics::_getObjectVolatile: return inline_unsafe_access(!is_native_ptr, !is_store, T_OBJECT, is_volatile, false);842case vmIntrinsics::_getBooleanVolatile: return inline_unsafe_access(!is_native_ptr, !is_store, T_BOOLEAN, is_volatile, false);843case vmIntrinsics::_getByteVolatile: return inline_unsafe_access(!is_native_ptr, !is_store, T_BYTE, is_volatile, false);844case vmIntrinsics::_getShortVolatile: return inline_unsafe_access(!is_native_ptr, !is_store, T_SHORT, is_volatile, false);845case vmIntrinsics::_getCharVolatile: return inline_unsafe_access(!is_native_ptr, !is_store, T_CHAR, is_volatile, false);846case vmIntrinsics::_getIntVolatile: return inline_unsafe_access(!is_native_ptr, !is_store, T_INT, is_volatile, false);847case vmIntrinsics::_getLongVolatile: return inline_unsafe_access(!is_native_ptr, !is_store, T_LONG, is_volatile, false);848case vmIntrinsics::_getFloatVolatile: return inline_unsafe_access(!is_native_ptr, !is_store, T_FLOAT, is_volatile, false);849case vmIntrinsics::_getDoubleVolatile: return inline_unsafe_access(!is_native_ptr, !is_store, T_DOUBLE, is_volatile, false);850851case vmIntrinsics::_putObjectVolatile: return inline_unsafe_access(!is_native_ptr, is_store, T_OBJECT, is_volatile, false);852case vmIntrinsics::_putBooleanVolatile: return inline_unsafe_access(!is_native_ptr, is_store, T_BOOLEAN, is_volatile, false);853case vmIntrinsics::_putByteVolatile: return inline_unsafe_access(!is_native_ptr, is_store, T_BYTE, is_volatile, false);854case vmIntrinsics::_putShortVolatile: return inline_unsafe_access(!is_native_ptr, is_store, T_SHORT, is_volatile, false);855case vmIntrinsics::_putCharVolatile: return inline_unsafe_access(!is_native_ptr, is_store, T_CHAR, is_volatile, false);856case vmIntrinsics::_putIntVolatile: return inline_unsafe_access(!is_native_ptr, is_store, T_INT, is_volatile, false);857case vmIntrinsics::_putLongVolatile: return inline_unsafe_access(!is_native_ptr, is_store, T_LONG, is_volatile, false);858case vmIntrinsics::_putFloatVolatile: return inline_unsafe_access(!is_native_ptr, is_store, T_FLOAT, is_volatile, false);859case vmIntrinsics::_putDoubleVolatile: return inline_unsafe_access(!is_native_ptr, is_store, T_DOUBLE, is_volatile, false);860861case vmIntrinsics::_prefetchRead: return inline_unsafe_prefetch(!is_native_ptr, !is_store, !is_static);862case vmIntrinsics::_prefetchWrite: return inline_unsafe_prefetch(!is_native_ptr, is_store, !is_static);863case vmIntrinsics::_prefetchReadStatic: return inline_unsafe_prefetch(!is_native_ptr, !is_store, is_static);864case vmIntrinsics::_prefetchWriteStatic: return inline_unsafe_prefetch(!is_native_ptr, is_store, is_static);865866case vmIntrinsics::_compareAndSwapObject: return inline_unsafe_load_store(T_OBJECT, LS_cmpxchg);867case vmIntrinsics::_compareAndSwapInt: return inline_unsafe_load_store(T_INT, LS_cmpxchg);868case vmIntrinsics::_compareAndSwapLong: return inline_unsafe_load_store(T_LONG, LS_cmpxchg);869870case vmIntrinsics::_putOrderedObject: return inline_unsafe_ordered_store(T_OBJECT);871case vmIntrinsics::_putOrderedInt: return inline_unsafe_ordered_store(T_INT);872case vmIntrinsics::_putOrderedLong: return inline_unsafe_ordered_store(T_LONG);873874case vmIntrinsics::_getAndAddInt: return inline_unsafe_load_store(T_INT, LS_xadd);875case vmIntrinsics::_getAndAddLong: return inline_unsafe_load_store(T_LONG, LS_xadd);876case vmIntrinsics::_getAndSetInt: return inline_unsafe_load_store(T_INT, LS_xchg);877case vmIntrinsics::_getAndSetLong: return inline_unsafe_load_store(T_LONG, LS_xchg);878case vmIntrinsics::_getAndSetObject: return inline_unsafe_load_store(T_OBJECT, LS_xchg);879880case vmIntrinsics::_loadFence:881case vmIntrinsics::_storeFence:882case vmIntrinsics::_fullFence: return inline_unsafe_fence(intrinsic_id());883884case vmIntrinsics::_currentThread: return inline_native_currentThread();885case vmIntrinsics::_isInterrupted: return inline_native_isInterrupted();886887#ifdef JFR_HAVE_INTRINSICS888case vmIntrinsics::_counterTime: return inline_native_time_funcs(CAST_FROM_FN_PTR(address, JFR_TIME_FUNCTION), "counterTime");889case vmIntrinsics::_getClassId: return inline_native_classID();890case vmIntrinsics::_getEventWriter: return inline_native_getEventWriter();891#endif892case vmIntrinsics::_currentTimeMillis: return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeMillis), "currentTimeMillis");893case vmIntrinsics::_nanoTime: return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeNanos), "nanoTime");894case vmIntrinsics::_allocateInstance: return inline_unsafe_allocate();895case vmIntrinsics::_copyMemory: return inline_unsafe_copyMemory();896case vmIntrinsics::_newArray: return inline_native_newArray();897case vmIntrinsics::_getLength: return inline_native_getLength();898case vmIntrinsics::_copyOf: return inline_array_copyOf(false);899case vmIntrinsics::_copyOfRange: return inline_array_copyOf(true);900case vmIntrinsics::_equalsC: return inline_array_equals();901case vmIntrinsics::_clone: return inline_native_clone(intrinsic()->is_virtual());902903case vmIntrinsics::_isAssignableFrom: return inline_native_subtype_check();904905case vmIntrinsics::_isInstance:906case vmIntrinsics::_getModifiers:907case vmIntrinsics::_isInterface:908case vmIntrinsics::_isArray:909case vmIntrinsics::_isPrimitive:910case vmIntrinsics::_getSuperclass:911case vmIntrinsics::_getComponentType:912case vmIntrinsics::_getClassAccessFlags: return inline_native_Class_query(intrinsic_id());913914case vmIntrinsics::_floatToRawIntBits:915case vmIntrinsics::_floatToIntBits:916case vmIntrinsics::_intBitsToFloat:917case vmIntrinsics::_doubleToRawLongBits:918case vmIntrinsics::_doubleToLongBits:919case vmIntrinsics::_longBitsToDouble: return inline_fp_conversions(intrinsic_id());920921case vmIntrinsics::_numberOfLeadingZeros_i:922case vmIntrinsics::_numberOfLeadingZeros_l:923case vmIntrinsics::_numberOfTrailingZeros_i:924case vmIntrinsics::_numberOfTrailingZeros_l:925case vmIntrinsics::_bitCount_i:926case vmIntrinsics::_bitCount_l:927case vmIntrinsics::_reverseBytes_i:928case vmIntrinsics::_reverseBytes_l:929case vmIntrinsics::_reverseBytes_s:930case vmIntrinsics::_reverseBytes_c: return inline_number_methods(intrinsic_id());931932case vmIntrinsics::_getCallerClass: return inline_native_Reflection_getCallerClass();933934case vmIntrinsics::_Reference_get: return inline_reference_get();935936case vmIntrinsics::_aescrypt_encryptBlock:937case vmIntrinsics::_aescrypt_decryptBlock: return inline_aescrypt_Block(intrinsic_id());938939case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:940case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:941return inline_cipherBlockChaining_AESCrypt(intrinsic_id());942943case vmIntrinsics::_sha_implCompress:944case vmIntrinsics::_sha2_implCompress:945case vmIntrinsics::_sha5_implCompress:946return inline_sha_implCompress(intrinsic_id());947948case vmIntrinsics::_digestBase_implCompressMB:949return inline_digestBase_implCompressMB(predicate);950951case vmIntrinsics::_multiplyToLen:952return inline_multiplyToLen();953954case vmIntrinsics::_squareToLen:955return inline_squareToLen();956957case vmIntrinsics::_mulAdd:958return inline_mulAdd();959960case vmIntrinsics::_montgomeryMultiply:961return inline_montgomeryMultiply();962case vmIntrinsics::_montgomerySquare:963return inline_montgomerySquare();964965case vmIntrinsics::_ghash_processBlocks:966return inline_ghash_processBlocks();967968case vmIntrinsics::_encodeISOArray:969return inline_encodeISOArray();970971case vmIntrinsics::_updateCRC32:972return inline_updateCRC32();973case vmIntrinsics::_updateBytesCRC32:974return inline_updateBytesCRC32();975case vmIntrinsics::_updateByteBufferCRC32:976return inline_updateByteBufferCRC32();977978case vmIntrinsics::_profileBoolean:979return inline_profileBoolean();980981default:982// If you get here, it may be that someone has added a new intrinsic983// to the list in vmSymbols.hpp without implementing it here.984#ifndef PRODUCT985if ((PrintMiscellaneous && (Verbose || WizardMode)) || PrintOpto) {986tty->print_cr("*** Warning: Unimplemented intrinsic %s(%d)",987vmIntrinsics::name_at(intrinsic_id()), intrinsic_id());988}989#endif990return false;991}992}993994Node* LibraryCallKit::try_to_predicate(int predicate) {995if (!jvms()->has_method()) {996// Root JVMState has a null method.997assert(map()->memory()->Opcode() == Op_Parm, "");998// Insert the memory aliasing node999set_all_memory(reset_memory());1000}1001assert(merged_memory(), "");10021003switch (intrinsic_id()) {1004case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:1005return inline_cipherBlockChaining_AESCrypt_predicate(false);1006case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:1007return inline_cipherBlockChaining_AESCrypt_predicate(true);1008case vmIntrinsics::_digestBase_implCompressMB:1009return inline_digestBase_implCompressMB_predicate(predicate);10101011default:1012// If you get here, it may be that someone has added a new intrinsic1013// to the list in vmSymbols.hpp without implementing it here.1014#ifndef PRODUCT1015if ((PrintMiscellaneous && (Verbose || WizardMode)) || PrintOpto) {1016tty->print_cr("*** Warning: Unimplemented predicate for intrinsic %s(%d)",1017vmIntrinsics::name_at(intrinsic_id()), intrinsic_id());1018}1019#endif1020Node* slow_ctl = control();1021set_control(top()); // No fast path instrinsic1022return slow_ctl;1023}1024}10251026//------------------------------set_result-------------------------------1027// Helper function for finishing intrinsics.1028void LibraryCallKit::set_result(RegionNode* region, PhiNode* value) {1029record_for_igvn(region);1030set_control(_gvn.transform(region));1031set_result( _gvn.transform(value));1032assert(value->type()->basic_type() == result()->bottom_type()->basic_type(), "sanity");1033}10341035//------------------------------generate_guard---------------------------1036// Helper function for generating guarded fast-slow graph structures.1037// The given 'test', if true, guards a slow path. If the test fails1038// then a fast path can be taken. (We generally hope it fails.)1039// In all cases, GraphKit::control() is updated to the fast path.1040// The returned value represents the control for the slow path.1041// The return value is never 'top'; it is either a valid control1042// or NULL if it is obvious that the slow path can never be taken.1043// Also, if region and the slow control are not NULL, the slow edge1044// is appended to the region.1045Node* LibraryCallKit::generate_guard(Node* test, RegionNode* region, float true_prob) {1046if (stopped()) {1047// Already short circuited.1048return NULL;1049}10501051// Build an if node and its projections.1052// If test is true we take the slow path, which we assume is uncommon.1053if (_gvn.type(test) == TypeInt::ZERO) {1054// The slow branch is never taken. No need to build this guard.1055return NULL;1056}10571058IfNode* iff = create_and_map_if(control(), test, true_prob, COUNT_UNKNOWN);10591060Node* if_slow = _gvn.transform(new (C) IfTrueNode(iff));1061if (if_slow == top()) {1062// The slow branch is never taken. No need to build this guard.1063return NULL;1064}10651066if (region != NULL)1067region->add_req(if_slow);10681069Node* if_fast = _gvn.transform(new (C) IfFalseNode(iff));1070set_control(if_fast);10711072return if_slow;1073}10741075inline Node* LibraryCallKit::generate_slow_guard(Node* test, RegionNode* region) {1076return generate_guard(test, region, PROB_UNLIKELY_MAG(3));1077}1078inline Node* LibraryCallKit::generate_fair_guard(Node* test, RegionNode* region) {1079return generate_guard(test, region, PROB_FAIR);1080}10811082inline Node* LibraryCallKit::generate_negative_guard(Node* index, RegionNode* region,1083Node* *pos_index) {1084if (stopped())1085return NULL; // already stopped1086if (_gvn.type(index)->higher_equal(TypeInt::POS)) // [0,maxint]1087return NULL; // index is already adequately typed1088Node* cmp_lt = _gvn.transform(new (C) CmpINode(index, intcon(0)));1089Node* bol_lt = _gvn.transform(new (C) BoolNode(cmp_lt, BoolTest::lt));1090Node* is_neg = generate_guard(bol_lt, region, PROB_MIN);1091if (is_neg != NULL && pos_index != NULL) {1092// Emulate effect of Parse::adjust_map_after_if.1093Node* ccast = new (C) CastIINode(index, TypeInt::POS);1094ccast->set_req(0, control());1095(*pos_index) = _gvn.transform(ccast);1096}1097return is_neg;1098}10991100inline Node* LibraryCallKit::generate_nonpositive_guard(Node* index, bool never_negative,1101Node* *pos_index) {1102if (stopped())1103return NULL; // already stopped1104if (_gvn.type(index)->higher_equal(TypeInt::POS1)) // [1,maxint]1105return NULL; // index is already adequately typed1106Node* cmp_le = _gvn.transform(new (C) CmpINode(index, intcon(0)));1107BoolTest::mask le_or_eq = (never_negative ? BoolTest::eq : BoolTest::le);1108Node* bol_le = _gvn.transform(new (C) BoolNode(cmp_le, le_or_eq));1109Node* is_notp = generate_guard(bol_le, NULL, PROB_MIN);1110if (is_notp != NULL && pos_index != NULL) {1111// Emulate effect of Parse::adjust_map_after_if.1112Node* ccast = new (C) CastIINode(index, TypeInt::POS1);1113ccast->set_req(0, control());1114(*pos_index) = _gvn.transform(ccast);1115}1116return is_notp;1117}11181119// Make sure that 'position' is a valid limit index, in [0..length].1120// There are two equivalent plans for checking this:1121// A. (offset + copyLength) unsigned<= arrayLength1122// B. offset <= (arrayLength - copyLength)1123// We require that all of the values above, except for the sum and1124// difference, are already known to be non-negative.1125// Plan A is robust in the face of overflow, if offset and copyLength1126// are both hugely positive.1127//1128// Plan B is less direct and intuitive, but it does not overflow at1129// all, since the difference of two non-negatives is always1130// representable. Whenever Java methods must perform the equivalent1131// check they generally use Plan B instead of Plan A.1132// For the moment we use Plan A.1133inline Node* LibraryCallKit::generate_limit_guard(Node* offset,1134Node* subseq_length,1135Node* array_length,1136RegionNode* region) {1137if (stopped())1138return NULL; // already stopped1139bool zero_offset = _gvn.type(offset) == TypeInt::ZERO;1140if (zero_offset && subseq_length->eqv_uncast(array_length))1141return NULL; // common case of whole-array copy1142Node* last = subseq_length;1143if (!zero_offset) // last += offset1144last = _gvn.transform(new (C) AddINode(last, offset));1145Node* cmp_lt = _gvn.transform(new (C) CmpUNode(array_length, last));1146Node* bol_lt = _gvn.transform(new (C) BoolNode(cmp_lt, BoolTest::lt));1147Node* is_over = generate_guard(bol_lt, region, PROB_MIN);1148return is_over;1149}115011511152//--------------------------generate_current_thread--------------------1153Node* LibraryCallKit::generate_current_thread(Node* &tls_output) {1154ciKlass* thread_klass = env()->Thread_klass();1155const Type* thread_type = TypeOopPtr::make_from_klass(thread_klass)->cast_to_ptr_type(TypePtr::NotNull);1156Node* thread = _gvn.transform(new (C) ThreadLocalNode());1157Node* p = basic_plus_adr(top()/*!oop*/, thread, in_bytes(JavaThread::threadObj_offset()));1158Node* threadObj = make_load(NULL, p, thread_type, T_OBJECT, MemNode::unordered);1159tls_output = thread;1160return threadObj;1161}116211631164//------------------------------make_string_method_node------------------------1165// Helper method for String intrinsic functions. This version is called1166// with str1 and str2 pointing to String object nodes.1167//1168Node* LibraryCallKit::make_string_method_node(int opcode, Node* str1, Node* str2) {1169Node* no_ctrl = NULL;11701171// Get start addr of string1172Node* str1_value = load_String_value(no_ctrl, str1);1173Node* str1_offset = load_String_offset(no_ctrl, str1);1174Node* str1_start = array_element_address(str1_value, str1_offset, T_CHAR);11751176// Get length of string 11177Node* str1_len = load_String_length(no_ctrl, str1);11781179Node* str2_value = load_String_value(no_ctrl, str2);1180Node* str2_offset = load_String_offset(no_ctrl, str2);1181Node* str2_start = array_element_address(str2_value, str2_offset, T_CHAR);11821183Node* str2_len = NULL;1184Node* result = NULL;11851186switch (opcode) {1187case Op_StrIndexOf:1188// Get length of string 21189str2_len = load_String_length(no_ctrl, str2);11901191result = new (C) StrIndexOfNode(control(), memory(TypeAryPtr::CHARS),1192str1_start, str1_len, str2_start, str2_len);1193break;1194case Op_StrComp:1195// Get length of string 21196str2_len = load_String_length(no_ctrl, str2);11971198result = new (C) StrCompNode(control(), memory(TypeAryPtr::CHARS),1199str1_start, str1_len, str2_start, str2_len);1200break;1201case Op_StrEquals:1202result = new (C) StrEqualsNode(control(), memory(TypeAryPtr::CHARS),1203str1_start, str2_start, str1_len);1204break;1205default:1206ShouldNotReachHere();1207return NULL;1208}12091210// All these intrinsics have checks.1211C->set_has_split_ifs(true); // Has chance for split-if optimization12121213return _gvn.transform(result);1214}12151216// Helper method for String intrinsic functions. This version is called1217// with str1 and str2 pointing to char[] nodes, with cnt1 and cnt2 pointing1218// to Int nodes containing the lenghts of str1 and str2.1219//1220Node* LibraryCallKit::make_string_method_node(int opcode, Node* str1_start, Node* cnt1, Node* str2_start, Node* cnt2) {1221Node* result = NULL;1222switch (opcode) {1223case Op_StrIndexOf:1224result = new (C) StrIndexOfNode(control(), memory(TypeAryPtr::CHARS),1225str1_start, cnt1, str2_start, cnt2);1226break;1227case Op_StrComp:1228result = new (C) StrCompNode(control(), memory(TypeAryPtr::CHARS),1229str1_start, cnt1, str2_start, cnt2);1230break;1231case Op_StrEquals:1232result = new (C) StrEqualsNode(control(), memory(TypeAryPtr::CHARS),1233str1_start, str2_start, cnt1);1234break;1235default:1236ShouldNotReachHere();1237return NULL;1238}12391240// All these intrinsics have checks.1241C->set_has_split_ifs(true); // Has chance for split-if optimization12421243return _gvn.transform(result);1244}12451246//------------------------------inline_string_compareTo------------------------1247// public int java.lang.String.compareTo(String anotherString);1248bool LibraryCallKit::inline_string_compareTo() {1249Node* receiver = null_check(argument(0));1250Node* arg = null_check(argument(1));1251if (stopped()) {1252return true;1253}1254set_result(make_string_method_node(Op_StrComp, receiver, arg));1255return true;1256}12571258//------------------------------inline_string_equals------------------------1259bool LibraryCallKit::inline_string_equals() {1260Node* receiver = null_check_receiver();1261// NOTE: Do not null check argument for String.equals() because spec1262// allows to specify NULL as argument.1263Node* argument = this->argument(1);1264if (stopped()) {1265return true;1266}12671268// paths (plus control) merge1269RegionNode* region = new (C) RegionNode(5);1270Node* phi = new (C) PhiNode(region, TypeInt::BOOL);12711272// does source == target string?1273Node* cmp = _gvn.transform(new (C) CmpPNode(receiver, argument));1274Node* bol = _gvn.transform(new (C) BoolNode(cmp, BoolTest::eq));12751276Node* if_eq = generate_slow_guard(bol, NULL);1277if (if_eq != NULL) {1278// receiver == argument1279phi->init_req(2, intcon(1));1280region->init_req(2, if_eq);1281}12821283// get String klass for instanceOf1284ciInstanceKlass* klass = env()->String_klass();12851286if (!stopped()) {1287Node* inst = gen_instanceof(argument, makecon(TypeKlassPtr::make(klass)));1288Node* cmp = _gvn.transform(new (C) CmpINode(inst, intcon(1)));1289Node* bol = _gvn.transform(new (C) BoolNode(cmp, BoolTest::ne));12901291Node* inst_false = generate_guard(bol, NULL, PROB_MIN);1292//instanceOf == true, fallthrough12931294if (inst_false != NULL) {1295phi->init_req(3, intcon(0));1296region->init_req(3, inst_false);1297}1298}12991300if (!stopped()) {1301const TypeOopPtr* string_type = TypeOopPtr::make_from_klass(klass);13021303// Properly cast the argument to String1304argument = _gvn.transform(new (C) CheckCastPPNode(control(), argument, string_type));1305// This path is taken only when argument's type is String:NotNull.1306argument = cast_not_null(argument, false);13071308Node* no_ctrl = NULL;13091310// Get start addr of receiver1311Node* receiver_val = load_String_value(no_ctrl, receiver);1312Node* receiver_offset = load_String_offset(no_ctrl, receiver);1313Node* receiver_start = array_element_address(receiver_val, receiver_offset, T_CHAR);13141315// Get length of receiver1316Node* receiver_cnt = load_String_length(no_ctrl, receiver);13171318// Get start addr of argument1319Node* argument_val = load_String_value(no_ctrl, argument);1320Node* argument_offset = load_String_offset(no_ctrl, argument);1321Node* argument_start = array_element_address(argument_val, argument_offset, T_CHAR);13221323// Get length of argument1324Node* argument_cnt = load_String_length(no_ctrl, argument);13251326// Check for receiver count != argument count1327Node* cmp = _gvn.transform(new(C) CmpINode(receiver_cnt, argument_cnt));1328Node* bol = _gvn.transform(new(C) BoolNode(cmp, BoolTest::ne));1329Node* if_ne = generate_slow_guard(bol, NULL);1330if (if_ne != NULL) {1331phi->init_req(4, intcon(0));1332region->init_req(4, if_ne);1333}13341335// Check for count == 0 is done by assembler code for StrEquals.13361337if (!stopped()) {1338Node* equals = make_string_method_node(Op_StrEquals, receiver_start, receiver_cnt, argument_start, argument_cnt);1339phi->init_req(1, equals);1340region->init_req(1, control());1341}1342}13431344// post merge1345set_control(_gvn.transform(region));1346record_for_igvn(region);13471348set_result(_gvn.transform(phi));1349return true;1350}13511352//------------------------------inline_array_equals----------------------------1353bool LibraryCallKit::inline_array_equals() {1354Node* arg1 = argument(0);1355Node* arg2 = argument(1);1356set_result(_gvn.transform(new (C) AryEqNode(control(), memory(TypeAryPtr::CHARS), arg1, arg2)));1357return true;1358}13591360// Java version of String.indexOf(constant string)1361// class StringDecl {1362// StringDecl(char[] ca) {1363// offset = 0;1364// count = ca.length;1365// value = ca;1366// }1367// int offset;1368// int count;1369// char[] value;1370// }1371//1372// static int string_indexOf_J(StringDecl string_object, char[] target_object,1373// int targetOffset, int cache_i, int md2) {1374// int cache = cache_i;1375// int sourceOffset = string_object.offset;1376// int sourceCount = string_object.count;1377// int targetCount = target_object.length;1378//1379// int targetCountLess1 = targetCount - 1;1380// int sourceEnd = sourceOffset + sourceCount - targetCountLess1;1381//1382// char[] source = string_object.value;1383// char[] target = target_object;1384// int lastChar = target[targetCountLess1];1385//1386// outer_loop:1387// for (int i = sourceOffset; i < sourceEnd; ) {1388// int src = source[i + targetCountLess1];1389// if (src == lastChar) {1390// // With random strings and a 4-character alphabet,1391// // reverse matching at this point sets up 0.8% fewer1392// // frames, but (paradoxically) makes 0.3% more probes.1393// // Since those probes are nearer the lastChar probe,1394// // there is may be a net D$ win with reverse matching.1395// // But, reversing loop inhibits unroll of inner loop1396// // for unknown reason. So, does running outer loop from1397// // (sourceOffset - targetCountLess1) to (sourceOffset + sourceCount)1398// for (int j = 0; j < targetCountLess1; j++) {1399// if (target[targetOffset + j] != source[i+j]) {1400// if ((cache & (1 << source[i+j])) == 0) {1401// if (md2 < j+1) {1402// i += j+1;1403// continue outer_loop;1404// }1405// }1406// i += md2;1407// continue outer_loop;1408// }1409// }1410// return i - sourceOffset;1411// }1412// if ((cache & (1 << src)) == 0) {1413// i += targetCountLess1;1414// } // using "i += targetCount;" and an "else i++;" causes a jump to jump.1415// i++;1416// }1417// return -1;1418// }14191420//------------------------------string_indexOf------------------------1421Node* LibraryCallKit::string_indexOf(Node* string_object, ciTypeArray* target_array, jint targetOffset_i,1422jint cache_i, jint md2_i) {14231424Node* no_ctrl = NULL;1425float likely = PROB_LIKELY(0.9);1426float unlikely = PROB_UNLIKELY(0.9);14271428const int nargs = 0; // no arguments to push back for uncommon trap in predicate14291430Node* source = load_String_value(no_ctrl, string_object);1431Node* sourceOffset = load_String_offset(no_ctrl, string_object);1432Node* sourceCount = load_String_length(no_ctrl, string_object);14331434Node* target = _gvn.transform( makecon(TypeOopPtr::make_from_constant(target_array, true)));1435jint target_length = target_array->length();1436const TypeAry* target_array_type = TypeAry::make(TypeInt::CHAR, TypeInt::make(0, target_length, Type::WidenMin));1437const TypeAryPtr* target_type = TypeAryPtr::make(TypePtr::BotPTR, target_array_type, target_array->klass(), true, Type::OffsetBot);14381439// String.value field is known to be @Stable.1440if (UseImplicitStableValues) {1441target = cast_array_to_stable(target, target_type);1442}14431444IdealKit kit(this, false, true);1445#define __ kit.1446Node* zero = __ ConI(0);1447Node* one = __ ConI(1);1448Node* cache = __ ConI(cache_i);1449Node* md2 = __ ConI(md2_i);1450Node* lastChar = __ ConI(target_array->char_at(target_length - 1));1451Node* targetCount = __ ConI(target_length);1452Node* targetCountLess1 = __ ConI(target_length - 1);1453Node* targetOffset = __ ConI(targetOffset_i);1454Node* sourceEnd = __ SubI(__ AddI(sourceOffset, sourceCount), targetCountLess1);14551456IdealVariable rtn(kit), i(kit), j(kit); __ declarations_done();1457Node* outer_loop = __ make_label(2 /* goto */);1458Node* return_ = __ make_label(1);14591460__ set(rtn,__ ConI(-1));1461__ loop(this, nargs, i, sourceOffset, BoolTest::lt, sourceEnd); {1462Node* i2 = __ AddI(__ value(i), targetCountLess1);1463// pin to prohibit loading of "next iteration" value which may SEGV (rare)1464Node* src = load_array_element(__ ctrl(), source, i2, TypeAryPtr::CHARS);1465__ if_then(src, BoolTest::eq, lastChar, unlikely); {1466__ loop(this, nargs, j, zero, BoolTest::lt, targetCountLess1); {1467Node* tpj = __ AddI(targetOffset, __ value(j));1468Node* targ = load_array_element(no_ctrl, target, tpj, target_type);1469Node* ipj = __ AddI(__ value(i), __ value(j));1470Node* src2 = load_array_element(no_ctrl, source, ipj, TypeAryPtr::CHARS);1471__ if_then(targ, BoolTest::ne, src2); {1472__ if_then(__ AndI(cache, __ LShiftI(one, src2)), BoolTest::eq, zero); {1473__ if_then(md2, BoolTest::lt, __ AddI(__ value(j), one)); {1474__ increment(i, __ AddI(__ value(j), one));1475__ goto_(outer_loop);1476} __ end_if(); __ dead(j);1477}__ end_if(); __ dead(j);1478__ increment(i, md2);1479__ goto_(outer_loop);1480}__ end_if();1481__ increment(j, one);1482}__ end_loop(); __ dead(j);1483__ set(rtn, __ SubI(__ value(i), sourceOffset)); __ dead(i);1484__ goto_(return_);1485}__ end_if();1486__ if_then(__ AndI(cache, __ LShiftI(one, src)), BoolTest::eq, zero, likely); {1487__ increment(i, targetCountLess1);1488}__ end_if();1489__ increment(i, one);1490__ bind(outer_loop);1491}__ end_loop(); __ dead(i);1492__ bind(return_);14931494// Final sync IdealKit and GraphKit.1495final_sync(kit);1496Node* result = __ value(rtn);1497#undef __1498C->set_has_loops(true);1499return result;1500}15011502//------------------------------inline_string_indexOf------------------------1503bool LibraryCallKit::inline_string_indexOf() {1504Node* receiver = argument(0);1505Node* arg = argument(1);15061507Node* result;1508// Disable the use of pcmpestri until it can be guaranteed that1509// the load doesn't cross into the uncommited space.1510if (Matcher::has_match_rule(Op_StrIndexOf) &&1511UseSSE42Intrinsics) {1512// Generate SSE4.2 version of indexOf1513// We currently only have match rules that use SSE4.215141515receiver = null_check(receiver);1516arg = null_check(arg);1517if (stopped()) {1518return true;1519}15201521ciInstanceKlass* str_klass = env()->String_klass();1522const TypeOopPtr* string_type = TypeOopPtr::make_from_klass(str_klass);15231524// Make the merge point1525RegionNode* result_rgn = new (C) RegionNode(4);1526Node* result_phi = new (C) PhiNode(result_rgn, TypeInt::INT);1527Node* no_ctrl = NULL;15281529// Get start addr of source string1530Node* source = load_String_value(no_ctrl, receiver);1531Node* source_offset = load_String_offset(no_ctrl, receiver);1532Node* source_start = array_element_address(source, source_offset, T_CHAR);15331534// Get length of source string1535Node* source_cnt = load_String_length(no_ctrl, receiver);15361537// Get start addr of substring1538Node* substr = load_String_value(no_ctrl, arg);1539Node* substr_offset = load_String_offset(no_ctrl, arg);1540Node* substr_start = array_element_address(substr, substr_offset, T_CHAR);15411542// Get length of source string1543Node* substr_cnt = load_String_length(no_ctrl, arg);15441545// Check for substr count > string count1546Node* cmp = _gvn.transform(new(C) CmpINode(substr_cnt, source_cnt));1547Node* bol = _gvn.transform(new(C) BoolNode(cmp, BoolTest::gt));1548Node* if_gt = generate_slow_guard(bol, NULL);1549if (if_gt != NULL) {1550result_phi->init_req(2, intcon(-1));1551result_rgn->init_req(2, if_gt);1552}15531554if (!stopped()) {1555// Check for substr count == 01556cmp = _gvn.transform(new(C) CmpINode(substr_cnt, intcon(0)));1557bol = _gvn.transform(new(C) BoolNode(cmp, BoolTest::eq));1558Node* if_zero = generate_slow_guard(bol, NULL);1559if (if_zero != NULL) {1560result_phi->init_req(3, intcon(0));1561result_rgn->init_req(3, if_zero);1562}1563}15641565if (!stopped()) {1566result = make_string_method_node(Op_StrIndexOf, source_start, source_cnt, substr_start, substr_cnt);1567result_phi->init_req(1, result);1568result_rgn->init_req(1, control());1569}1570set_control(_gvn.transform(result_rgn));1571record_for_igvn(result_rgn);1572result = _gvn.transform(result_phi);15731574} else { // Use LibraryCallKit::string_indexOf1575// don't intrinsify if argument isn't a constant string.1576if (!arg->is_Con()) {1577return false;1578}1579const TypeOopPtr* str_type = _gvn.type(arg)->isa_oopptr();1580if (str_type == NULL) {1581return false;1582}1583ciInstanceKlass* klass = env()->String_klass();1584ciObject* str_const = str_type->const_oop();1585if (str_const == NULL || str_const->klass() != klass) {1586return false;1587}1588ciInstance* str = str_const->as_instance();1589assert(str != NULL, "must be instance");15901591ciObject* v = str->field_value_by_offset(java_lang_String::value_offset_in_bytes()).as_object();1592ciTypeArray* pat = v->as_type_array(); // pattern (argument) character array15931594int o;1595int c;1596if (java_lang_String::has_offset_field()) {1597o = str->field_value_by_offset(java_lang_String::offset_offset_in_bytes()).as_int();1598c = str->field_value_by_offset(java_lang_String::count_offset_in_bytes()).as_int();1599} else {1600o = 0;1601c = pat->length();1602}16031604// constant strings have no offset and count == length which1605// simplifies the resulting code somewhat so lets optimize for that.1606if (o != 0 || c != pat->length()) {1607return false;1608}16091610receiver = null_check(receiver, T_OBJECT);1611// NOTE: No null check on the argument is needed since it's a constant String oop.1612if (stopped()) {1613return true;1614}16151616// The null string as a pattern always returns 0 (match at beginning of string)1617if (c == 0) {1618set_result(intcon(0));1619return true;1620}16211622// Generate default indexOf1623jchar lastChar = pat->char_at(o + (c - 1));1624int cache = 0;1625int i;1626for (i = 0; i < c - 1; i++) {1627assert(i < pat->length(), "out of range");1628cache |= (1 << (pat->char_at(o + i) & (sizeof(cache) * BitsPerByte - 1)));1629}16301631int md2 = c;1632for (i = 0; i < c - 1; i++) {1633assert(i < pat->length(), "out of range");1634if (pat->char_at(o + i) == lastChar) {1635md2 = (c - 1) - i;1636}1637}16381639result = string_indexOf(receiver, pat, o, cache, md2);1640}1641set_result(result);1642return true;1643}16441645//--------------------------round_double_node--------------------------------1646// Round a double node if necessary.1647Node* LibraryCallKit::round_double_node(Node* n) {1648if (Matcher::strict_fp_requires_explicit_rounding && UseSSE <= 1)1649n = _gvn.transform(new (C) RoundDoubleNode(0, n));1650return n;1651}16521653//------------------------------inline_math-----------------------------------1654// public static double Math.abs(double)1655// public static double Math.sqrt(double)1656// public static double Math.log(double)1657// public static double Math.log10(double)1658bool LibraryCallKit::inline_math(vmIntrinsics::ID id) {1659Node* arg = round_double_node(argument(0));1660Node* n = NULL;1661switch (id) {1662case vmIntrinsics::_dabs: n = new (C) AbsDNode( arg); break;1663case vmIntrinsics::_dsqrt: n = new (C) SqrtDNode(C, control(), arg); break;1664case vmIntrinsics::_dlog: n = new (C) LogDNode(C, control(), arg); break;1665case vmIntrinsics::_dlog10: n = new (C) Log10DNode(C, control(), arg); break;1666default: fatal_unexpected_iid(id); break;1667}1668set_result(_gvn.transform(n));1669return true;1670}16711672//------------------------------inline_trig----------------------------------1673// Inline sin/cos/tan instructions, if possible. If rounding is required, do1674// argument reduction which will turn into a fast/slow diamond.1675bool LibraryCallKit::inline_trig(vmIntrinsics::ID id) {1676Node* arg = round_double_node(argument(0));1677Node* n = NULL;16781679switch (id) {1680case vmIntrinsics::_dsin: n = new (C) SinDNode(C, control(), arg); break;1681case vmIntrinsics::_dcos: n = new (C) CosDNode(C, control(), arg); break;1682case vmIntrinsics::_dtan: n = new (C) TanDNode(C, control(), arg); break;1683default: fatal_unexpected_iid(id); break;1684}1685n = _gvn.transform(n);16861687// Rounding required? Check for argument reduction!1688if (Matcher::strict_fp_requires_explicit_rounding) {1689static const double pi_4 = 0.7853981633974483;1690static const double neg_pi_4 = -0.7853981633974483;1691// pi/2 in 80-bit extended precision1692// static const unsigned char pi_2_bits_x[] = {0x35,0xc2,0x68,0x21,0xa2,0xda,0x0f,0xc9,0xff,0x3f,0x00,0x00,0x00,0x00,0x00,0x00};1693// -pi/2 in 80-bit extended precision1694// 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};1695// Cutoff value for using this argument reduction technique1696//static const double pi_2_minus_epsilon = 1.564660403643354;1697//static const double neg_pi_2_plus_epsilon = -1.564660403643354;16981699// Pseudocode for sin:1700// if (x <= Math.PI / 4.0) {1701// if (x >= -Math.PI / 4.0) return fsin(x);1702// if (x >= -Math.PI / 2.0) return -fcos(x + Math.PI / 2.0);1703// } else {1704// if (x <= Math.PI / 2.0) return fcos(x - Math.PI / 2.0);1705// }1706// return StrictMath.sin(x);17071708// Pseudocode for cos:1709// if (x <= Math.PI / 4.0) {1710// if (x >= -Math.PI / 4.0) return fcos(x);1711// if (x >= -Math.PI / 2.0) return fsin(x + Math.PI / 2.0);1712// } else {1713// if (x <= Math.PI / 2.0) return -fsin(x - Math.PI / 2.0);1714// }1715// return StrictMath.cos(x);17161717// Actually, sticking in an 80-bit Intel value into C2 will be tough; it1718// requires a special machine instruction to load it. Instead we'll try1719// the 'easy' case. If we really need the extra range +/- PI/2 we'll1720// probably do the math inside the SIN encoding.17211722// Make the merge point1723RegionNode* r = new (C) RegionNode(3);1724Node* phi = new (C) PhiNode(r, Type::DOUBLE);17251726// Flatten arg so we need only 1 test1727Node *abs = _gvn.transform(new (C) AbsDNode(arg));1728// Node for PI/4 constant1729Node *pi4 = makecon(TypeD::make(pi_4));1730// Check PI/4 : abs(arg)1731Node *cmp = _gvn.transform(new (C) CmpDNode(pi4,abs));1732// Check: If PI/4 < abs(arg) then go slow1733Node *bol = _gvn.transform(new (C) BoolNode( cmp, BoolTest::lt ));1734// Branch either way1735IfNode *iff = create_and_xform_if(control(),bol, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);1736set_control(opt_iff(r,iff));17371738// Set fast path result1739phi->init_req(2, n);17401741// Slow path - non-blocking leaf call1742Node* call = NULL;1743switch (id) {1744case vmIntrinsics::_dsin:1745call = make_runtime_call(RC_LEAF, OptoRuntime::Math_D_D_Type(),1746CAST_FROM_FN_PTR(address, SharedRuntime::dsin),1747"Sin", NULL, arg, top());1748break;1749case vmIntrinsics::_dcos:1750call = make_runtime_call(RC_LEAF, OptoRuntime::Math_D_D_Type(),1751CAST_FROM_FN_PTR(address, SharedRuntime::dcos),1752"Cos", NULL, arg, top());1753break;1754case vmIntrinsics::_dtan:1755call = make_runtime_call(RC_LEAF, OptoRuntime::Math_D_D_Type(),1756CAST_FROM_FN_PTR(address, SharedRuntime::dtan),1757"Tan", NULL, arg, top());1758break;1759}1760assert(control()->in(0) == call, "");1761Node* slow_result = _gvn.transform(new (C) ProjNode(call, TypeFunc::Parms));1762r->init_req(1, control());1763phi->init_req(1, slow_result);17641765// Post-merge1766set_control(_gvn.transform(r));1767record_for_igvn(r);1768n = _gvn.transform(phi);17691770C->set_has_split_ifs(true); // Has chance for split-if optimization1771}1772set_result(n);1773return true;1774}17751776Node* LibraryCallKit::finish_pow_exp(Node* result, Node* x, Node* y, const TypeFunc* call_type, address funcAddr, const char* funcName) {1777//-------------------1778//result=(result.isNaN())? funcAddr():result;1779// Check: If isNaN() by checking result!=result? then either trap1780// or go to runtime1781Node* cmpisnan = _gvn.transform(new (C) CmpDNode(result, result));1782// Build the boolean node1783Node* bolisnum = _gvn.transform(new (C) BoolNode(cmpisnan, BoolTest::eq));17841785if (!too_many_traps(Deoptimization::Reason_intrinsic)) {1786{ BuildCutout unless(this, bolisnum, PROB_STATIC_FREQUENT);1787// The pow or exp intrinsic returned a NaN, which requires a call1788// to the runtime. Recompile with the runtime call.1789uncommon_trap(Deoptimization::Reason_intrinsic,1790Deoptimization::Action_make_not_entrant);1791}1792return result;1793} else {1794// If this inlining ever returned NaN in the past, we compile a call1795// to the runtime to properly handle corner cases17961797IfNode* iff = create_and_xform_if(control(), bolisnum, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);1798Node* if_slow = _gvn.transform(new (C) IfFalseNode(iff));1799Node* if_fast = _gvn.transform(new (C) IfTrueNode(iff));18001801if (!if_slow->is_top()) {1802RegionNode* result_region = new (C) RegionNode(3);1803PhiNode* result_val = new (C) PhiNode(result_region, Type::DOUBLE);18041805result_region->init_req(1, if_fast);1806result_val->init_req(1, result);18071808set_control(if_slow);18091810const TypePtr* no_memory_effects = NULL;1811Node* rt = make_runtime_call(RC_LEAF, call_type, funcAddr, funcName,1812no_memory_effects,1813x, top(), y, y ? top() : NULL);1814Node* value = _gvn.transform(new (C) ProjNode(rt, TypeFunc::Parms+0));1815#ifdef ASSERT1816Node* value_top = _gvn.transform(new (C) ProjNode(rt, TypeFunc::Parms+1));1817assert(value_top == top(), "second value must be top");1818#endif18191820result_region->init_req(2, control());1821result_val->init_req(2, value);1822set_control(_gvn.transform(result_region));1823return _gvn.transform(result_val);1824} else {1825return result;1826}1827}1828}18291830//------------------------------inline_exp-------------------------------------1831// Inline exp instructions, if possible. The Intel hardware only misses1832// really odd corner cases (+/- Infinity). Just uncommon-trap them.1833bool LibraryCallKit::inline_exp() {1834Node* arg = round_double_node(argument(0));1835Node* n = _gvn.transform(new (C) ExpDNode(C, control(), arg));18361837n = finish_pow_exp(n, arg, NULL, OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dexp), "EXP");1838set_result(n);18391840C->set_has_split_ifs(true); // Has chance for split-if optimization1841return true;1842}18431844//------------------------------inline_pow-------------------------------------1845// Inline power instructions, if possible.1846bool LibraryCallKit::inline_pow() {1847// Pseudocode for pow1848// if (y == 2) {1849// return x * x;1850// } else {1851// if (x <= 0.0) {1852// long longy = (long)y;1853// if ((double)longy == y) { // if y is long1854// if (y + 1 == y) longy = 0; // huge number: even1855// result = ((1&longy) == 0)?-DPow(abs(x), y):DPow(abs(x), y);1856// } else {1857// result = NaN;1858// }1859// } else {1860// result = DPow(x,y);1861// }1862// if (result != result)? {1863// result = uncommon_trap() or runtime_call();1864// }1865// return result;1866// }18671868Node* x = round_double_node(argument(0));1869Node* y = round_double_node(argument(2));18701871Node* result = NULL;18721873Node* const_two_node = makecon(TypeD::make(2.0));1874Node* cmp_node = _gvn.transform(new (C) CmpDNode(y, const_two_node));1875Node* bool_node = _gvn.transform(new (C) BoolNode(cmp_node, BoolTest::eq));1876IfNode* if_node = create_and_xform_if(control(), bool_node, PROB_STATIC_INFREQUENT, COUNT_UNKNOWN);1877Node* if_true = _gvn.transform(new (C) IfTrueNode(if_node));1878Node* if_false = _gvn.transform(new (C) IfFalseNode(if_node));18791880RegionNode* region_node = new (C) RegionNode(3);1881region_node->init_req(1, if_true);18821883Node* phi_node = new (C) PhiNode(region_node, Type::DOUBLE);1884// special case for x^y where y == 2, we can convert it to x * x1885phi_node->init_req(1, _gvn.transform(new (C) MulDNode(x, x)));18861887// set control to if_false since we will now process the false branch1888set_control(if_false);18891890if (!too_many_traps(Deoptimization::Reason_intrinsic)) {1891// Short form: skip the fancy tests and just check for NaN result.1892result = _gvn.transform(new (C) PowDNode(C, control(), x, y));1893} else {1894// If this inlining ever returned NaN in the past, include all1895// checks + call to the runtime.18961897// Set the merge point for If node with condition of (x <= 0.0)1898// There are four possible paths to region node and phi node1899RegionNode *r = new (C) RegionNode(4);1900Node *phi = new (C) PhiNode(r, Type::DOUBLE);19011902// Build the first if node: if (x <= 0.0)1903// Node for 0 constant1904Node *zeronode = makecon(TypeD::ZERO);1905// Check x:01906Node *cmp = _gvn.transform(new (C) CmpDNode(x, zeronode));1907// Check: If (x<=0) then go complex path1908Node *bol1 = _gvn.transform(new (C) BoolNode( cmp, BoolTest::le ));1909// Branch either way1910IfNode *if1 = create_and_xform_if(control(),bol1, PROB_STATIC_INFREQUENT, COUNT_UNKNOWN);1911// Fast path taken; set region slot 31912Node *fast_taken = _gvn.transform(new (C) IfFalseNode(if1));1913r->init_req(3,fast_taken); // Capture fast-control19141915// Fast path not-taken, i.e. slow path1916Node *complex_path = _gvn.transform(new (C) IfTrueNode(if1));19171918// Set fast path result1919Node *fast_result = _gvn.transform(new (C) PowDNode(C, control(), x, y));1920phi->init_req(3, fast_result);19211922// Complex path1923// Build the second if node (if y is long)1924// Node for (long)y1925Node *longy = _gvn.transform(new (C) ConvD2LNode(y));1926// Node for (double)((long) y)1927Node *doublelongy= _gvn.transform(new (C) ConvL2DNode(longy));1928// Check (double)((long) y) : y1929Node *cmplongy= _gvn.transform(new (C) CmpDNode(doublelongy, y));1930// Check if (y isn't long) then go to slow path19311932Node *bol2 = _gvn.transform(new (C) BoolNode( cmplongy, BoolTest::ne ));1933// Branch either way1934IfNode *if2 = create_and_xform_if(complex_path,bol2, PROB_STATIC_INFREQUENT, COUNT_UNKNOWN);1935Node* ylong_path = _gvn.transform(new (C) IfFalseNode(if2));19361937Node *slow_path = _gvn.transform(new (C) IfTrueNode(if2));19381939// Calculate DPow(abs(x), y)*(1 & (long)y)1940// Node for constant 11941Node *conone = longcon(1);1942// 1& (long)y1943Node *signnode= _gvn.transform(new (C) AndLNode(conone, longy));19441945// A huge number is always even. Detect a huge number by checking1946// if y + 1 == y and set integer to be tested for parity to 0.1947// Required for corner case:1948// (long)9.223372036854776E18 = max_jlong1949// (double)(long)9.223372036854776E18 = 9.223372036854776E181950// max_jlong is odd but 9.223372036854776E18 is even1951Node* yplus1 = _gvn.transform(new (C) AddDNode(y, makecon(TypeD::make(1))));1952Node *cmpyplus1= _gvn.transform(new (C) CmpDNode(yplus1, y));1953Node *bolyplus1 = _gvn.transform(new (C) BoolNode( cmpyplus1, BoolTest::eq ));1954Node* correctedsign = NULL;1955if (ConditionalMoveLimit != 0) {1956correctedsign = _gvn.transform( CMoveNode::make(C, NULL, bolyplus1, signnode, longcon(0), TypeLong::LONG));1957} else {1958IfNode *ifyplus1 = create_and_xform_if(ylong_path,bolyplus1, PROB_FAIR, COUNT_UNKNOWN);1959RegionNode *r = new (C) RegionNode(3);1960Node *phi = new (C) PhiNode(r, TypeLong::LONG);1961r->init_req(1, _gvn.transform(new (C) IfFalseNode(ifyplus1)));1962r->init_req(2, _gvn.transform(new (C) IfTrueNode(ifyplus1)));1963phi->init_req(1, signnode);1964phi->init_req(2, longcon(0));1965correctedsign = _gvn.transform(phi);1966ylong_path = _gvn.transform(r);1967record_for_igvn(r);1968}19691970// zero node1971Node *conzero = longcon(0);1972// Check (1&(long)y)==0?1973Node *cmpeq1 = _gvn.transform(new (C) CmpLNode(correctedsign, conzero));1974// Check if (1&(long)y)!=0?, if so the result is negative1975Node *bol3 = _gvn.transform(new (C) BoolNode( cmpeq1, BoolTest::ne ));1976// abs(x)1977Node *absx=_gvn.transform(new (C) AbsDNode(x));1978// abs(x)^y1979Node *absxpowy = _gvn.transform(new (C) PowDNode(C, control(), absx, y));1980// -abs(x)^y1981Node *negabsxpowy = _gvn.transform(new (C) NegDNode (absxpowy));1982// (1&(long)y)==1?-DPow(abs(x), y):DPow(abs(x), y)1983Node *signresult = NULL;1984if (ConditionalMoveLimit != 0) {1985signresult = _gvn.transform( CMoveNode::make(C, NULL, bol3, absxpowy, negabsxpowy, Type::DOUBLE));1986} else {1987IfNode *ifyeven = create_and_xform_if(ylong_path,bol3, PROB_FAIR, COUNT_UNKNOWN);1988RegionNode *r = new (C) RegionNode(3);1989Node *phi = new (C) PhiNode(r, Type::DOUBLE);1990r->init_req(1, _gvn.transform(new (C) IfFalseNode(ifyeven)));1991r->init_req(2, _gvn.transform(new (C) IfTrueNode(ifyeven)));1992phi->init_req(1, absxpowy);1993phi->init_req(2, negabsxpowy);1994signresult = _gvn.transform(phi);1995ylong_path = _gvn.transform(r);1996record_for_igvn(r);1997}1998// Set complex path fast result1999r->init_req(2, ylong_path);2000phi->init_req(2, signresult);20012002static const jlong nan_bits = CONST64(0x7ff8000000000000);2003Node *slow_result = makecon(TypeD::make(*(double*)&nan_bits)); // return NaN2004r->init_req(1,slow_path);2005phi->init_req(1,slow_result);20062007// Post merge2008set_control(_gvn.transform(r));2009record_for_igvn(r);2010result = _gvn.transform(phi);2011}20122013result = finish_pow_exp(result, x, y, OptoRuntime::Math_DD_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dpow), "POW");20142015// control from finish_pow_exp is now input to the region node2016region_node->set_req(2, control());2017// the result from finish_pow_exp is now input to the phi node2018phi_node->init_req(2, result);2019set_control(_gvn.transform(region_node));2020record_for_igvn(region_node);2021set_result(_gvn.transform(phi_node));20222023C->set_has_split_ifs(true); // Has chance for split-if optimization2024return true;2025}20262027//------------------------------runtime_math-----------------------------2028bool LibraryCallKit::runtime_math(const TypeFunc* call_type, address funcAddr, const char* funcName) {2029assert(call_type == OptoRuntime::Math_DD_D_Type() || call_type == OptoRuntime::Math_D_D_Type(),2030"must be (DD)D or (D)D type");20312032// Inputs2033Node* a = round_double_node(argument(0));2034Node* b = (call_type == OptoRuntime::Math_DD_D_Type()) ? round_double_node(argument(2)) : NULL;20352036const TypePtr* no_memory_effects = NULL;2037Node* trig = make_runtime_call(RC_LEAF, call_type, funcAddr, funcName,2038no_memory_effects,2039a, top(), b, b ? top() : NULL);2040Node* value = _gvn.transform(new (C) ProjNode(trig, TypeFunc::Parms+0));2041#ifdef ASSERT2042Node* value_top = _gvn.transform(new (C) ProjNode(trig, TypeFunc::Parms+1));2043assert(value_top == top(), "second value must be top");2044#endif20452046set_result(value);2047return true;2048}20492050//------------------------------inline_math_native-----------------------------2051bool LibraryCallKit::inline_math_native(vmIntrinsics::ID id) {2052#define FN_PTR(f) CAST_FROM_FN_PTR(address, f)2053switch (id) {2054// These intrinsics are not properly supported on all hardware2055case vmIntrinsics::_dcos: return Matcher::has_match_rule(Op_CosD) ? inline_trig(id) :2056runtime_math(OptoRuntime::Math_D_D_Type(), FN_PTR(SharedRuntime::dcos), "COS");2057case vmIntrinsics::_dsin: return Matcher::has_match_rule(Op_SinD) ? inline_trig(id) :2058runtime_math(OptoRuntime::Math_D_D_Type(), FN_PTR(SharedRuntime::dsin), "SIN");2059case vmIntrinsics::_dtan: return Matcher::has_match_rule(Op_TanD) ? inline_trig(id) :2060runtime_math(OptoRuntime::Math_D_D_Type(), FN_PTR(SharedRuntime::dtan), "TAN");20612062case vmIntrinsics::_dlog: return Matcher::has_match_rule(Op_LogD) ? inline_math(id) :2063runtime_math(OptoRuntime::Math_D_D_Type(), FN_PTR(SharedRuntime::dlog), "LOG");2064case vmIntrinsics::_dlog10: return Matcher::has_match_rule(Op_Log10D) ? inline_math(id) :2065runtime_math(OptoRuntime::Math_D_D_Type(), FN_PTR(SharedRuntime::dlog10), "LOG10");20662067// These intrinsics are supported on all hardware2068case vmIntrinsics::_dsqrt: return Matcher::match_rule_supported(Op_SqrtD) ? inline_math(id) : false;2069case vmIntrinsics::_dabs: return Matcher::has_match_rule(Op_AbsD) ? inline_math(id) : false;20702071case vmIntrinsics::_dexp: return Matcher::has_match_rule(Op_ExpD) ? inline_exp() :2072runtime_math(OptoRuntime::Math_D_D_Type(), FN_PTR(SharedRuntime::dexp), "EXP");2073case vmIntrinsics::_dpow: return Matcher::has_match_rule(Op_PowD) ? inline_pow() :2074runtime_math(OptoRuntime::Math_DD_D_Type(), FN_PTR(SharedRuntime::dpow), "POW");2075#undef FN_PTR20762077// These intrinsics are not yet correctly implemented2078case vmIntrinsics::_datan2:2079return false;20802081default:2082fatal_unexpected_iid(id);2083return false;2084}2085}20862087static bool is_simple_name(Node* n) {2088return (n->req() == 1 // constant2089|| (n->is_Type() && n->as_Type()->type()->singleton())2090|| n->is_Proj() // parameter or return value2091|| n->is_Phi() // local of some sort2092);2093}20942095//----------------------------inline_min_max-----------------------------------2096bool LibraryCallKit::inline_min_max(vmIntrinsics::ID id) {2097set_result(generate_min_max(id, argument(0), argument(1)));2098return true;2099}21002101void LibraryCallKit::inline_math_mathExact(Node* math, Node *test) {2102Node* bol = _gvn.transform( new (C) BoolNode(test, BoolTest::overflow) );2103IfNode* check = create_and_map_if(control(), bol, PROB_UNLIKELY_MAG(3), COUNT_UNKNOWN);2104Node* fast_path = _gvn.transform( new (C) IfFalseNode(check));2105Node* slow_path = _gvn.transform( new (C) IfTrueNode(check) );21062107{2108PreserveJVMState pjvms(this);2109PreserveReexecuteState preexecs(this);2110jvms()->set_should_reexecute(true);21112112set_control(slow_path);2113set_i_o(i_o());21142115uncommon_trap(Deoptimization::Reason_intrinsic,2116Deoptimization::Action_none);2117}21182119set_control(fast_path);2120set_result(math);2121}21222123template <typename OverflowOp>2124bool LibraryCallKit::inline_math_overflow(Node* arg1, Node* arg2) {2125typedef typename OverflowOp::MathOp MathOp;21262127MathOp* mathOp = new(C) MathOp(arg1, arg2);2128Node* operation = _gvn.transform( mathOp );2129Node* ofcheck = _gvn.transform( new(C) OverflowOp(arg1, arg2) );2130inline_math_mathExact(operation, ofcheck);2131return true;2132}21332134bool LibraryCallKit::inline_math_addExactI(bool is_increment) {2135return inline_math_overflow<OverflowAddINode>(argument(0), is_increment ? intcon(1) : argument(1));2136}21372138bool LibraryCallKit::inline_math_addExactL(bool is_increment) {2139return inline_math_overflow<OverflowAddLNode>(argument(0), is_increment ? longcon(1) : argument(2));2140}21412142bool LibraryCallKit::inline_math_subtractExactI(bool is_decrement) {2143return inline_math_overflow<OverflowSubINode>(argument(0), is_decrement ? intcon(1) : argument(1));2144}21452146bool LibraryCallKit::inline_math_subtractExactL(bool is_decrement) {2147return inline_math_overflow<OverflowSubLNode>(argument(0), is_decrement ? longcon(1) : argument(2));2148}21492150bool LibraryCallKit::inline_math_negateExactI() {2151return inline_math_overflow<OverflowSubINode>(intcon(0), argument(0));2152}21532154bool LibraryCallKit::inline_math_negateExactL() {2155return inline_math_overflow<OverflowSubLNode>(longcon(0), argument(0));2156}21572158bool LibraryCallKit::inline_math_multiplyExactI() {2159return inline_math_overflow<OverflowMulINode>(argument(0), argument(1));2160}21612162bool LibraryCallKit::inline_math_multiplyExactL() {2163return inline_math_overflow<OverflowMulLNode>(argument(0), argument(2));2164}21652166Node*2167LibraryCallKit::generate_min_max(vmIntrinsics::ID id, Node* x0, Node* y0) {2168// These are the candidate return value:2169Node* xvalue = x0;2170Node* yvalue = y0;21712172if (xvalue == yvalue) {2173return xvalue;2174}21752176bool want_max = (id == vmIntrinsics::_max);21772178const TypeInt* txvalue = _gvn.type(xvalue)->isa_int();2179const TypeInt* tyvalue = _gvn.type(yvalue)->isa_int();2180if (txvalue == NULL || tyvalue == NULL) return top();2181// This is not really necessary, but it is consistent with a2182// hypothetical MaxINode::Value method:2183int widen = MAX2(txvalue->_widen, tyvalue->_widen);21842185// %%% This folding logic should (ideally) be in a different place.2186// Some should be inside IfNode, and there to be a more reliable2187// transformation of ?: style patterns into cmoves. We also want2188// more powerful optimizations around cmove and min/max.21892190// Try to find a dominating comparison of these guys.2191// It can simplify the index computation for Arrays.copyOf2192// and similar uses of System.arraycopy.2193// First, compute the normalized version of CmpI(x, y).2194int cmp_op = Op_CmpI;2195Node* xkey = xvalue;2196Node* ykey = yvalue;2197Node* ideal_cmpxy = _gvn.transform(new(C) CmpINode(xkey, ykey));2198if (ideal_cmpxy->is_Cmp()) {2199// E.g., if we have CmpI(length - offset, count),2200// it might idealize to CmpI(length, count + offset)2201cmp_op = ideal_cmpxy->Opcode();2202xkey = ideal_cmpxy->in(1);2203ykey = ideal_cmpxy->in(2);2204}22052206// Start by locating any relevant comparisons.2207Node* start_from = (xkey->outcnt() < ykey->outcnt()) ? xkey : ykey;2208Node* cmpxy = NULL;2209Node* cmpyx = NULL;2210for (DUIterator_Fast kmax, k = start_from->fast_outs(kmax); k < kmax; k++) {2211Node* cmp = start_from->fast_out(k);2212if (cmp->outcnt() > 0 && // must have prior uses2213cmp->in(0) == NULL && // must be context-independent2214cmp->Opcode() == cmp_op) { // right kind of compare2215if (cmp->in(1) == xkey && cmp->in(2) == ykey) cmpxy = cmp;2216if (cmp->in(1) == ykey && cmp->in(2) == xkey) cmpyx = cmp;2217}2218}22192220const int NCMPS = 2;2221Node* cmps[NCMPS] = { cmpxy, cmpyx };2222int cmpn;2223for (cmpn = 0; cmpn < NCMPS; cmpn++) {2224if (cmps[cmpn] != NULL) break; // find a result2225}2226if (cmpn < NCMPS) {2227// Look for a dominating test that tells us the min and max.2228int depth = 0; // Limit search depth for speed2229Node* dom = control();2230for (; dom != NULL; dom = IfNode::up_one_dom(dom, true)) {2231if (++depth >= 100) break;2232Node* ifproj = dom;2233if (!ifproj->is_Proj()) continue;2234Node* iff = ifproj->in(0);2235if (!iff->is_If()) continue;2236Node* bol = iff->in(1);2237if (!bol->is_Bool()) continue;2238Node* cmp = bol->in(1);2239if (cmp == NULL) continue;2240for (cmpn = 0; cmpn < NCMPS; cmpn++)2241if (cmps[cmpn] == cmp) break;2242if (cmpn == NCMPS) continue;2243BoolTest::mask btest = bol->as_Bool()->_test._test;2244if (ifproj->is_IfFalse()) btest = BoolTest(btest).negate();2245if (cmp->in(1) == ykey) btest = BoolTest(btest).commute();2246// At this point, we know that 'x btest y' is true.2247switch (btest) {2248case BoolTest::eq:2249// They are proven equal, so we can collapse the min/max.2250// Either value is the answer. Choose the simpler.2251if (is_simple_name(yvalue) && !is_simple_name(xvalue))2252return yvalue;2253return xvalue;2254case BoolTest::lt: // x < y2255case BoolTest::le: // x <= y2256return (want_max ? yvalue : xvalue);2257case BoolTest::gt: // x > y2258case BoolTest::ge: // x >= y2259return (want_max ? xvalue : yvalue);2260}2261}2262}22632264// We failed to find a dominating test.2265// Let's pick a test that might GVN with prior tests.2266Node* best_bol = NULL;2267BoolTest::mask best_btest = BoolTest::illegal;2268for (cmpn = 0; cmpn < NCMPS; cmpn++) {2269Node* cmp = cmps[cmpn];2270if (cmp == NULL) continue;2271for (DUIterator_Fast jmax, j = cmp->fast_outs(jmax); j < jmax; j++) {2272Node* bol = cmp->fast_out(j);2273if (!bol->is_Bool()) continue;2274BoolTest::mask btest = bol->as_Bool()->_test._test;2275if (btest == BoolTest::eq || btest == BoolTest::ne) continue;2276if (cmp->in(1) == ykey) btest = BoolTest(btest).commute();2277if (bol->outcnt() > (best_bol == NULL ? 0 : best_bol->outcnt())) {2278best_bol = bol->as_Bool();2279best_btest = btest;2280}2281}2282}22832284Node* answer_if_true = NULL;2285Node* answer_if_false = NULL;2286switch (best_btest) {2287default:2288if (cmpxy == NULL)2289cmpxy = ideal_cmpxy;2290best_bol = _gvn.transform(new(C) BoolNode(cmpxy, BoolTest::lt));2291// and fall through:2292case BoolTest::lt: // x < y2293case BoolTest::le: // x <= y2294answer_if_true = (want_max ? yvalue : xvalue);2295answer_if_false = (want_max ? xvalue : yvalue);2296break;2297case BoolTest::gt: // x > y2298case BoolTest::ge: // x >= y2299answer_if_true = (want_max ? xvalue : yvalue);2300answer_if_false = (want_max ? yvalue : xvalue);2301break;2302}23032304jint hi, lo;2305if (want_max) {2306// We can sharpen the minimum.2307hi = MAX2(txvalue->_hi, tyvalue->_hi);2308lo = MAX2(txvalue->_lo, tyvalue->_lo);2309} else {2310// We can sharpen the maximum.2311hi = MIN2(txvalue->_hi, tyvalue->_hi);2312lo = MIN2(txvalue->_lo, tyvalue->_lo);2313}23142315// Use a flow-free graph structure, to avoid creating excess control edges2316// which could hinder other optimizations.2317// Since Math.min/max is often used with arraycopy, we want2318// tightly_coupled_allocation to be able to see beyond min/max expressions.2319Node* cmov = CMoveNode::make(C, NULL, best_bol,2320answer_if_false, answer_if_true,2321TypeInt::make(lo, hi, widen));23222323return _gvn.transform(cmov);23242325/*2326// This is not as desirable as it may seem, since Min and Max2327// nodes do not have a full set of optimizations.2328// And they would interfere, anyway, with 'if' optimizations2329// and with CMoveI canonical forms.2330switch (id) {2331case vmIntrinsics::_min:2332result_val = _gvn.transform(new (C, 3) MinINode(x,y)); break;2333case vmIntrinsics::_max:2334result_val = _gvn.transform(new (C, 3) MaxINode(x,y)); break;2335default:2336ShouldNotReachHere();2337}2338*/2339}23402341inline int2342LibraryCallKit::classify_unsafe_addr(Node* &base, Node* &offset) {2343const TypePtr* base_type = TypePtr::NULL_PTR;2344if (base != NULL) base_type = _gvn.type(base)->isa_ptr();2345if (base_type == NULL) {2346// Unknown type.2347return Type::AnyPtr;2348} else if (base_type == TypePtr::NULL_PTR) {2349// Since this is a NULL+long form, we have to switch to a rawptr.2350base = _gvn.transform(new (C) CastX2PNode(offset));2351offset = MakeConX(0);2352return Type::RawPtr;2353} else if (base_type->base() == Type::RawPtr) {2354return Type::RawPtr;2355} else if (base_type->isa_oopptr()) {2356// Base is never null => always a heap address.2357if (base_type->ptr() == TypePtr::NotNull) {2358return Type::OopPtr;2359}2360// Offset is small => always a heap address.2361const TypeX* offset_type = _gvn.type(offset)->isa_intptr_t();2362if (offset_type != NULL &&2363base_type->offset() == 0 && // (should always be?)2364offset_type->_lo >= 0 &&2365!MacroAssembler::needs_explicit_null_check(offset_type->_hi)) {2366return Type::OopPtr;2367}2368// Otherwise, it might either be oop+off or NULL+addr.2369return Type::AnyPtr;2370} else {2371// No information:2372return Type::AnyPtr;2373}2374}23752376inline Node* LibraryCallKit::make_unsafe_address(Node* base, Node* offset) {2377int kind = classify_unsafe_addr(base, offset);2378if (kind == Type::RawPtr) {2379return basic_plus_adr(top(), base, offset);2380} else {2381return basic_plus_adr(base, offset);2382}2383}23842385//--------------------------inline_number_methods-----------------------------2386// inline int Integer.numberOfLeadingZeros(int)2387// inline int Long.numberOfLeadingZeros(long)2388//2389// inline int Integer.numberOfTrailingZeros(int)2390// inline int Long.numberOfTrailingZeros(long)2391//2392// inline int Integer.bitCount(int)2393// inline int Long.bitCount(long)2394//2395// inline char Character.reverseBytes(char)2396// inline short Short.reverseBytes(short)2397// inline int Integer.reverseBytes(int)2398// inline long Long.reverseBytes(long)2399bool LibraryCallKit::inline_number_methods(vmIntrinsics::ID id) {2400Node* arg = argument(0);2401Node* n = NULL;2402switch (id) {2403case vmIntrinsics::_numberOfLeadingZeros_i: n = new (C) CountLeadingZerosINode( arg); break;2404case vmIntrinsics::_numberOfLeadingZeros_l: n = new (C) CountLeadingZerosLNode( arg); break;2405case vmIntrinsics::_numberOfTrailingZeros_i: n = new (C) CountTrailingZerosINode(arg); break;2406case vmIntrinsics::_numberOfTrailingZeros_l: n = new (C) CountTrailingZerosLNode(arg); break;2407case vmIntrinsics::_bitCount_i: n = new (C) PopCountINode( arg); break;2408case vmIntrinsics::_bitCount_l: n = new (C) PopCountLNode( arg); break;2409case vmIntrinsics::_reverseBytes_c: n = new (C) ReverseBytesUSNode(0, arg); break;2410case vmIntrinsics::_reverseBytes_s: n = new (C) ReverseBytesSNode( 0, arg); break;2411case vmIntrinsics::_reverseBytes_i: n = new (C) ReverseBytesINode( 0, arg); break;2412case vmIntrinsics::_reverseBytes_l: n = new (C) ReverseBytesLNode( 0, arg); break;2413default: fatal_unexpected_iid(id); break;2414}2415set_result(_gvn.transform(n));2416return true;2417}24182419//----------------------------inline_unsafe_access----------------------------24202421const static BasicType T_ADDRESS_HOLDER = T_LONG;24222423// Helper that guards and inserts a pre-barrier.2424void LibraryCallKit::insert_pre_barrier(Node* base_oop, Node* offset,2425Node* pre_val, bool need_mem_bar) {2426// We could be accessing the referent field of a reference object. If so, when G12427// is enabled, we need to log the value in the referent field in an SATB buffer.2428// This routine performs some compile time filters and generates suitable2429// runtime filters that guard the pre-barrier code.2430// Also add memory barrier for non volatile load from the referent field2431// to prevent commoning of loads across safepoint.2432if (!UseG1GC && !need_mem_bar)2433return;24342435// Some compile time checks.24362437// If offset is a constant, is it java_lang_ref_Reference::_reference_offset?2438const TypeX* otype = offset->find_intptr_t_type();2439if (otype != NULL && otype->is_con() &&2440otype->get_con() != java_lang_ref_Reference::referent_offset) {2441// Constant offset but not the reference_offset so just return2442return;2443}24442445// We only need to generate the runtime guards for instances.2446const TypeOopPtr* btype = base_oop->bottom_type()->isa_oopptr();2447if (btype != NULL) {2448if (btype->isa_aryptr()) {2449// Array type so nothing to do2450return;2451}24522453const TypeInstPtr* itype = btype->isa_instptr();2454if (itype != NULL) {2455// Can the klass of base_oop be statically determined to be2456// _not_ a sub-class of Reference and _not_ Object?2457ciKlass* klass = itype->klass();2458if ( klass->is_loaded() &&2459!klass->is_subtype_of(env()->Reference_klass()) &&2460!env()->Object_klass()->is_subtype_of(klass)) {2461return;2462}2463}2464}24652466// The compile time filters did not reject base_oop/offset so2467// we need to generate the following runtime filters2468//2469// if (offset == java_lang_ref_Reference::_reference_offset) {2470// if (instance_of(base, java.lang.ref.Reference)) {2471// pre_barrier(_, pre_val, ...);2472// }2473// }24742475float likely = PROB_LIKELY( 0.999);2476float unlikely = PROB_UNLIKELY(0.999);24772478IdealKit ideal(this);2479#define __ ideal.24802481Node* referent_off = __ ConX(java_lang_ref_Reference::referent_offset);24822483__ if_then(offset, BoolTest::eq, referent_off, unlikely); {2484// Update graphKit memory and control from IdealKit.2485sync_kit(ideal);24862487Node* ref_klass_con = makecon(TypeKlassPtr::make(env()->Reference_klass()));2488Node* is_instof = gen_instanceof(base_oop, ref_klass_con);24892490// Update IdealKit memory and control from graphKit.2491__ sync_kit(this);24922493Node* one = __ ConI(1);2494// is_instof == 0 if base_oop == NULL2495__ if_then(is_instof, BoolTest::eq, one, unlikely); {24962497// Update graphKit from IdeakKit.2498sync_kit(ideal);24992500// Use the pre-barrier to record the value in the referent field2501pre_barrier(false /* do_load */,2502__ ctrl(),2503NULL /* obj */, NULL /* adr */, max_juint /* alias_idx */, NULL /* val */, NULL /* val_type */,2504pre_val /* pre_val */,2505T_OBJECT);2506if (need_mem_bar) {2507// Add memory barrier to prevent commoning reads from this field2508// across safepoint since GC can change its value.2509insert_mem_bar(Op_MemBarCPUOrder);2510}2511// Update IdealKit from graphKit.2512__ sync_kit(this);25132514} __ end_if(); // _ref_type != ref_none2515} __ end_if(); // offset == referent_offset25162517// Final sync IdealKit and GraphKit.2518final_sync(ideal);2519#undef __2520}252125222523// Interpret Unsafe.fieldOffset cookies correctly:2524extern jlong Unsafe_field_offset_to_byte_offset(jlong field_offset);25252526const TypeOopPtr* LibraryCallKit::sharpen_unsafe_type(Compile::AliasType* alias_type, const TypePtr *adr_type, bool is_native_ptr) {2527// Attempt to infer a sharper value type from the offset and base type.2528ciKlass* sharpened_klass = NULL;25292530// See if it is an instance field, with an object type.2531if (alias_type->field() != NULL) {2532assert(!is_native_ptr, "native pointer op cannot use a java address");2533if (alias_type->field()->type()->is_klass()) {2534sharpened_klass = alias_type->field()->type()->as_klass();2535}2536}25372538// See if it is a narrow oop array.2539if (adr_type->isa_aryptr()) {2540if (adr_type->offset() >= objArrayOopDesc::base_offset_in_bytes()) {2541const TypeOopPtr *elem_type = adr_type->is_aryptr()->elem()->isa_oopptr();2542if (elem_type != NULL) {2543sharpened_klass = elem_type->klass();2544}2545}2546}25472548// The sharpened class might be unloaded if there is no class loader2549// contraint in place.2550if (sharpened_klass != NULL && sharpened_klass->is_loaded()) {2551const TypeOopPtr* tjp = TypeOopPtr::make_from_klass(sharpened_klass);25522553#ifndef PRODUCT2554if (C->print_intrinsics() || C->print_inlining()) {2555tty->print(" from base type: "); adr_type->dump(); tty->cr();2556tty->print(" sharpened value: "); tjp->dump(); tty->cr();2557}2558#endif2559// Sharpen the value type.2560return tjp;2561}2562return NULL;2563}25642565bool LibraryCallKit::inline_unsafe_access(bool is_native_ptr, bool is_store, BasicType type, bool is_volatile, bool unaligned) {2566if (callee()->is_static()) return false; // caller must have the capability!2567assert(type != T_OBJECT || !unaligned, "unaligned access not supported with object type");25682569#ifndef PRODUCT2570{2571ResourceMark rm;2572// Check the signatures.2573ciSignature* sig = callee()->signature();2574#ifdef ASSERT2575if (!is_store) {2576// Object getObject(Object base, int/long offset), etc.2577BasicType rtype = sig->return_type()->basic_type();2578if (rtype == T_ADDRESS_HOLDER && callee()->name() == ciSymbol::getAddress_name())2579rtype = T_ADDRESS; // it is really a C void*2580assert(rtype == type, "getter must return the expected value");2581if (!is_native_ptr) {2582assert(sig->count() == 2, "oop getter has 2 arguments");2583assert(sig->type_at(0)->basic_type() == T_OBJECT, "getter base is object");2584assert(sig->type_at(1)->basic_type() == T_LONG, "getter offset is correct");2585} else {2586assert(sig->count() == 1, "native getter has 1 argument");2587assert(sig->type_at(0)->basic_type() == T_LONG, "getter base is long");2588}2589} else {2590// void putObject(Object base, int/long offset, Object x), etc.2591assert(sig->return_type()->basic_type() == T_VOID, "putter must not return a value");2592if (!is_native_ptr) {2593assert(sig->count() == 3, "oop putter has 3 arguments");2594assert(sig->type_at(0)->basic_type() == T_OBJECT, "putter base is object");2595assert(sig->type_at(1)->basic_type() == T_LONG, "putter offset is correct");2596} else {2597assert(sig->count() == 2, "native putter has 2 arguments");2598assert(sig->type_at(0)->basic_type() == T_LONG, "putter base is long");2599}2600BasicType vtype = sig->type_at(sig->count()-1)->basic_type();2601if (vtype == T_ADDRESS_HOLDER && callee()->name() == ciSymbol::putAddress_name())2602vtype = T_ADDRESS; // it is really a C void*2603assert(vtype == type, "putter must accept the expected value");2604}2605#endif // ASSERT2606}2607#endif //PRODUCT26082609C->set_has_unsafe_access(true); // Mark eventual nmethod as "unsafe".26102611Node* receiver = argument(0); // type: oop26122613// Build address expression. See the code in inline_unsafe_prefetch.2614Node* adr;2615Node* heap_base_oop = top();2616Node* offset = top();2617Node* val;26182619// The base is either a Java object or a value produced by Unsafe.staticFieldBase2620Node* base = argument(1); // type: oop26212622if (!is_native_ptr) {2623// The offset is a value produced by Unsafe.staticFieldOffset or Unsafe.objectFieldOffset2624offset = argument(2); // type: long2625// We currently rely on the cookies produced by Unsafe.xxxFieldOffset2626// to be plain byte offsets, which are also the same as those accepted2627// by oopDesc::field_base.2628assert(Unsafe_field_offset_to_byte_offset(11) == 11,2629"fieldOffset must be byte-scaled");2630// 32-bit machines ignore the high half!2631offset = ConvL2X(offset);2632adr = make_unsafe_address(base, offset);2633heap_base_oop = base;2634val = is_store ? argument(4) : NULL;2635} else {2636Node* ptr = argument(1); // type: long2637ptr = ConvL2X(ptr); // adjust Java long to machine word2638adr = make_unsafe_address(NULL, ptr);2639val = is_store ? argument(3) : NULL;2640}26412642if ((_gvn.type(base)->isa_ptr() == TypePtr::NULL_PTR) && type == T_OBJECT) {2643return false; // off-heap oop accesses are not supported2644}26452646const TypePtr *adr_type = _gvn.type(adr)->isa_ptr();26472648// Try to categorize the address.2649Compile::AliasType* alias_type = C->alias_type(adr_type);2650assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");26512652if (alias_type->adr_type() == TypeInstPtr::KLASS ||2653alias_type->adr_type() == TypeAryPtr::RANGE) {2654return false; // not supported2655}26562657bool mismatched = false;2658BasicType bt = alias_type->basic_type();2659if (bt != T_ILLEGAL) {2660assert(alias_type->adr_type()->is_oopptr(), "should be on-heap access");2661if (bt == T_BYTE && adr_type->isa_aryptr()) {2662// Alias type doesn't differentiate between byte[] and boolean[]).2663// Use address type to get the element type.2664bt = adr_type->is_aryptr()->elem()->array_element_basic_type();2665}2666if (bt == T_ARRAY || bt == T_NARROWOOP) {2667// accessing an array field with getObject is not a mismatch2668bt = T_OBJECT;2669}2670if ((bt == T_OBJECT) != (type == T_OBJECT)) {2671// Don't intrinsify mismatched object accesses2672return false;2673}2674mismatched = (bt != type);2675}26762677assert(!mismatched || alias_type->adr_type()->is_oopptr(), "off-heap access can't be mismatched");26782679// First guess at the value type.2680const Type *value_type = Type::get_const_basic_type(type);26812682// We will need memory barriers unless we can determine a unique2683// alias category for this reference. (Note: If for some reason2684// the barriers get omitted and the unsafe reference begins to "pollute"2685// the alias analysis of the rest of the graph, either Compile::can_alias2686// or Compile::must_alias will throw a diagnostic assert.)2687bool need_mem_bar = (alias_type->adr_type() == TypeOopPtr::BOTTOM);26882689// If we are reading the value of the referent field of a Reference2690// object (either by using Unsafe directly or through reflection)2691// then, if G1 is enabled, we need to record the referent in an2692// SATB log buffer using the pre-barrier mechanism.2693// Also we need to add memory barrier to prevent commoning reads2694// from this field across safepoint since GC can change its value.2695bool need_read_barrier = !is_native_ptr && !is_store &&2696offset != top() && heap_base_oop != top();26972698if (!is_store && type == T_OBJECT) {2699const TypeOopPtr* tjp = sharpen_unsafe_type(alias_type, adr_type, is_native_ptr);2700if (tjp != NULL) {2701value_type = tjp;2702}2703}27042705receiver = null_check(receiver);2706if (stopped()) {2707return true;2708}2709// Heap pointers get a null-check from the interpreter,2710// as a courtesy. However, this is not guaranteed by Unsafe,2711// and it is not possible to fully distinguish unintended nulls2712// from intended ones in this API.27132714Node* load = NULL;2715Node* store = NULL;2716Node* leading_membar = NULL;2717if (is_volatile) {2718// We need to emit leading and trailing CPU membars (see below) in2719// addition to memory membars when is_volatile. This is a little2720// too strong, but avoids the need to insert per-alias-type2721// volatile membars (for stores; compare Parse::do_put_xxx), which2722// we cannot do effectively here because we probably only have a2723// rough approximation of type.2724need_mem_bar = true;2725// For Stores, place a memory ordering barrier now.2726if (is_store) {2727leading_membar = insert_mem_bar(Op_MemBarRelease);2728} else {2729if (support_IRIW_for_not_multiple_copy_atomic_cpu) {2730leading_membar = insert_mem_bar(Op_MemBarVolatile);2731}2732}2733}27342735// Memory barrier to prevent normal and 'unsafe' accesses from2736// bypassing each other. Happens after null checks, so the2737// exception paths do not take memory state from the memory barrier,2738// so there's no problems making a strong assert about mixing users2739// of safe & unsafe memory. Otherwise fails in a CTW of rt.jar2740// around 5701, class sun/reflect/UnsafeBooleanFieldAccessorImpl.2741if (need_mem_bar) insert_mem_bar(Op_MemBarCPUOrder);27422743if (!is_store) {2744MemNode::MemOrd mo = is_volatile ? MemNode::acquire : MemNode::unordered;2745// To be valid, unsafe loads may depend on other conditions than2746// the one that guards them: pin the Load node2747load = make_load(control(), adr, value_type, type, adr_type, mo, LoadNode::Pinned, is_volatile, unaligned, mismatched);2748// load value2749switch (type) {2750case T_BOOLEAN:2751case T_CHAR:2752case T_BYTE:2753case T_SHORT:2754case T_INT:2755case T_LONG:2756case T_FLOAT:2757case T_DOUBLE:2758break;2759case T_OBJECT:2760if (need_read_barrier) {2761insert_pre_barrier(heap_base_oop, offset, load, !(is_volatile || need_mem_bar));2762}2763break;2764case T_ADDRESS:2765// Cast to an int type.2766load = _gvn.transform(new (C) CastP2XNode(NULL, load));2767load = ConvX2UL(load);2768break;2769default:2770fatal(err_msg_res("unexpected type %d: %s", type, type2name(type)));2771break;2772}2773// The load node has the control of the preceding MemBarCPUOrder. All2774// following nodes will have the control of the MemBarCPUOrder inserted at2775// the end of this method. So, pushing the load onto the stack at a later2776// point is fine.2777set_result(load);2778} else {2779// place effect of store into memory2780switch (type) {2781case T_DOUBLE:2782val = dstore_rounding(val);2783break;2784case T_ADDRESS:2785// Repackage the long as a pointer.2786val = ConvL2X(val);2787val = _gvn.transform(new (C) CastX2PNode(val));2788break;2789}27902791MemNode::MemOrd mo = is_volatile ? MemNode::release : MemNode::unordered;2792if (type == T_OBJECT ) {2793store = store_oop_to_unknown(control(), heap_base_oop, adr, adr_type, val, type, mo, mismatched);2794} else {2795store = store_to_memory(control(), adr, val, type, adr_type, mo, is_volatile, unaligned, mismatched);2796}2797}27982799if (is_volatile) {2800if (!is_store) {2801Node* mb = insert_mem_bar(Op_MemBarAcquire, load);2802mb->as_MemBar()->set_trailing_load();2803} else {2804if (!support_IRIW_for_not_multiple_copy_atomic_cpu) {2805Node* mb = insert_mem_bar(Op_MemBarVolatile, store);2806MemBarNode::set_store_pair(leading_membar->as_MemBar(), mb->as_MemBar());2807}2808}2809}28102811if (need_mem_bar) insert_mem_bar(Op_MemBarCPUOrder);28122813return true;2814}28152816//----------------------------inline_unsafe_prefetch----------------------------28172818bool LibraryCallKit::inline_unsafe_prefetch(bool is_native_ptr, bool is_store, bool is_static) {2819#ifndef PRODUCT2820{2821ResourceMark rm;2822// Check the signatures.2823ciSignature* sig = callee()->signature();2824#ifdef ASSERT2825// Object getObject(Object base, int/long offset), etc.2826BasicType rtype = sig->return_type()->basic_type();2827if (!is_native_ptr) {2828assert(sig->count() == 2, "oop prefetch has 2 arguments");2829assert(sig->type_at(0)->basic_type() == T_OBJECT, "prefetch base is object");2830assert(sig->type_at(1)->basic_type() == T_LONG, "prefetcha offset is correct");2831} else {2832assert(sig->count() == 1, "native prefetch has 1 argument");2833assert(sig->type_at(0)->basic_type() == T_LONG, "prefetch base is long");2834}2835#endif // ASSERT2836}2837#endif // !PRODUCT28382839C->set_has_unsafe_access(true); // Mark eventual nmethod as "unsafe".28402841const int idx = is_static ? 0 : 1;2842if (!is_static) {2843null_check_receiver();2844if (stopped()) {2845return true;2846}2847}28482849// Build address expression. See the code in inline_unsafe_access.2850Node *adr;2851if (!is_native_ptr) {2852// The base is either a Java object or a value produced by Unsafe.staticFieldBase2853Node* base = argument(idx + 0); // type: oop2854// The offset is a value produced by Unsafe.staticFieldOffset or Unsafe.objectFieldOffset2855Node* offset = argument(idx + 1); // type: long2856// We currently rely on the cookies produced by Unsafe.xxxFieldOffset2857// to be plain byte offsets, which are also the same as those accepted2858// by oopDesc::field_base.2859assert(Unsafe_field_offset_to_byte_offset(11) == 11,2860"fieldOffset must be byte-scaled");2861// 32-bit machines ignore the high half!2862offset = ConvL2X(offset);2863adr = make_unsafe_address(base, offset);2864} else {2865Node* ptr = argument(idx + 0); // type: long2866ptr = ConvL2X(ptr); // adjust Java long to machine word2867adr = make_unsafe_address(NULL, ptr);2868}28692870// Generate the read or write prefetch2871Node *prefetch;2872if (is_store) {2873prefetch = new (C) PrefetchWriteNode(i_o(), adr);2874} else {2875prefetch = new (C) PrefetchReadNode(i_o(), adr);2876}2877prefetch->init_req(0, control());2878set_i_o(_gvn.transform(prefetch));28792880return true;2881}28822883//----------------------------inline_unsafe_load_store----------------------------2884// This method serves a couple of different customers (depending on LoadStoreKind):2885//2886// LS_cmpxchg:2887// public final native boolean compareAndSwapObject(Object o, long offset, Object expected, Object x);2888// public final native boolean compareAndSwapInt( Object o, long offset, int expected, int x);2889// public final native boolean compareAndSwapLong( Object o, long offset, long expected, long x);2890//2891// LS_xadd:2892// public int getAndAddInt( Object o, long offset, int delta)2893// public long getAndAddLong(Object o, long offset, long delta)2894//2895// LS_xchg:2896// int getAndSet(Object o, long offset, int newValue)2897// long getAndSet(Object o, long offset, long newValue)2898// Object getAndSet(Object o, long offset, Object newValue)2899//2900bool LibraryCallKit::inline_unsafe_load_store(BasicType type, LoadStoreKind kind) {2901// This basic scheme here is the same as inline_unsafe_access, but2902// differs in enough details that combining them would make the code2903// overly confusing. (This is a true fact! I originally combined2904// them, but even I was confused by it!) As much code/comments as2905// possible are retained from inline_unsafe_access though to make2906// the correspondences clearer. - dl29072908if (callee()->is_static()) return false; // caller must have the capability!29092910#ifndef PRODUCT2911BasicType rtype;2912{2913ResourceMark rm;2914// Check the signatures.2915ciSignature* sig = callee()->signature();2916rtype = sig->return_type()->basic_type();2917if (kind == LS_xadd || kind == LS_xchg) {2918// Check the signatures.2919#ifdef ASSERT2920assert(rtype == type, "get and set must return the expected type");2921assert(sig->count() == 3, "get and set has 3 arguments");2922assert(sig->type_at(0)->basic_type() == T_OBJECT, "get and set base is object");2923assert(sig->type_at(1)->basic_type() == T_LONG, "get and set offset is long");2924assert(sig->type_at(2)->basic_type() == type, "get and set must take expected type as new value/delta");2925#endif // ASSERT2926} else if (kind == LS_cmpxchg) {2927// Check the signatures.2928#ifdef ASSERT2929assert(rtype == T_BOOLEAN, "CAS must return boolean");2930assert(sig->count() == 4, "CAS has 4 arguments");2931assert(sig->type_at(0)->basic_type() == T_OBJECT, "CAS base is object");2932assert(sig->type_at(1)->basic_type() == T_LONG, "CAS offset is long");2933#endif // ASSERT2934} else {2935ShouldNotReachHere();2936}2937}2938#endif //PRODUCT29392940C->set_has_unsafe_access(true); // Mark eventual nmethod as "unsafe".29412942// Get arguments:2943Node* receiver = NULL;2944Node* base = NULL;2945Node* offset = NULL;2946Node* oldval = NULL;2947Node* newval = NULL;2948if (kind == LS_cmpxchg) {2949const bool two_slot_type = type2size[type] == 2;2950receiver = argument(0); // type: oop2951base = argument(1); // type: oop2952offset = argument(2); // type: long2953oldval = argument(4); // type: oop, int, or long2954newval = argument(two_slot_type ? 6 : 5); // type: oop, int, or long2955} else if (kind == LS_xadd || kind == LS_xchg){2956receiver = argument(0); // type: oop2957base = argument(1); // type: oop2958offset = argument(2); // type: long2959oldval = NULL;2960newval = argument(4); // type: oop, int, or long2961}29622963// Build field offset expression.2964// We currently rely on the cookies produced by Unsafe.xxxFieldOffset2965// to be plain byte offsets, which are also the same as those accepted2966// by oopDesc::field_base.2967assert(Unsafe_field_offset_to_byte_offset(11) == 11, "fieldOffset must be byte-scaled");2968// 32-bit machines ignore the high half of long offsets2969offset = ConvL2X(offset);2970Node* adr = make_unsafe_address(base, offset);2971const TypePtr *adr_type = _gvn.type(adr)->isa_ptr();29722973Compile::AliasType* alias_type = C->alias_type(adr_type);2974BasicType bt = alias_type->basic_type();2975if (bt != T_ILLEGAL &&2976((bt == T_OBJECT || bt == T_ARRAY) != (type == T_OBJECT))) {2977// Don't intrinsify mismatched object accesses.2978return false;2979}29802981// For CAS, unlike inline_unsafe_access, there seems no point in2982// trying to refine types. Just use the coarse types here.2983assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");2984const Type *value_type = Type::get_const_basic_type(type);29852986if (kind == LS_xchg && type == T_OBJECT) {2987const TypeOopPtr* tjp = sharpen_unsafe_type(alias_type, adr_type);2988if (tjp != NULL) {2989value_type = tjp;2990}2991}29922993// Null check receiver.2994receiver = null_check(receiver);2995if (stopped()) {2996return true;2997}29982999int alias_idx = C->get_alias_index(adr_type);30003001// Memory-model-wise, a LoadStore acts like a little synchronized3002// block, so needs barriers on each side. These don't translate3003// into actual barriers on most machines, but we still need rest of3004// compiler to respect ordering.30053006Node* leading_membar = insert_mem_bar(Op_MemBarRelease);3007insert_mem_bar(Op_MemBarCPUOrder);30083009// 4984716: MemBars must be inserted before this3010// memory node in order to avoid a false3011// dependency which will confuse the scheduler.3012Node *mem = memory(alias_idx);30133014// For now, we handle only those cases that actually exist: ints,3015// longs, and Object. Adding others should be straightforward.3016Node* load_store = NULL;3017switch(type) {3018case T_INT:3019if (kind == LS_xadd) {3020load_store = _gvn.transform(new (C) GetAndAddINode(control(), mem, adr, newval, adr_type));3021} else if (kind == LS_xchg) {3022load_store = _gvn.transform(new (C) GetAndSetINode(control(), mem, adr, newval, adr_type));3023} else if (kind == LS_cmpxchg) {3024load_store = _gvn.transform(new (C) CompareAndSwapINode(control(), mem, adr, newval, oldval));3025} else {3026ShouldNotReachHere();3027}3028break;3029case T_LONG:3030if (kind == LS_xadd) {3031load_store = _gvn.transform(new (C) GetAndAddLNode(control(), mem, adr, newval, adr_type));3032} else if (kind == LS_xchg) {3033load_store = _gvn.transform(new (C) GetAndSetLNode(control(), mem, adr, newval, adr_type));3034} else if (kind == LS_cmpxchg) {3035load_store = _gvn.transform(new (C) CompareAndSwapLNode(control(), mem, adr, newval, oldval));3036} else {3037ShouldNotReachHere();3038}3039break;3040case T_OBJECT:3041// Transformation of a value which could be NULL pointer (CastPP #NULL)3042// could be delayed during Parse (for example, in adjust_map_after_if()).3043// Execute transformation here to avoid barrier generation in such case.3044if (_gvn.type(newval) == TypePtr::NULL_PTR)3045newval = _gvn.makecon(TypePtr::NULL_PTR);30463047// Reference stores need a store barrier.3048if (kind == LS_xchg) {3049// If pre-barrier must execute before the oop store, old value will require do_load here.3050if (!can_move_pre_barrier()) {3051pre_barrier(true /* do_load*/,3052control(), base, adr, alias_idx, newval, value_type->make_oopptr(),3053NULL /* pre_val*/,3054T_OBJECT);3055} // Else move pre_barrier to use load_store value, see below.3056} else if (kind == LS_cmpxchg) {3057// Same as for newval above:3058if (_gvn.type(oldval) == TypePtr::NULL_PTR) {3059oldval = _gvn.makecon(TypePtr::NULL_PTR);3060}3061// The only known value which might get overwritten is oldval.3062pre_barrier(false /* do_load */,3063control(), NULL, NULL, max_juint, NULL, NULL,3064oldval /* pre_val */,3065T_OBJECT);3066} else {3067ShouldNotReachHere();3068}30693070#ifdef _LP643071if (adr->bottom_type()->is_ptr_to_narrowoop()) {3072Node *newval_enc = _gvn.transform(new (C) EncodePNode(newval, newval->bottom_type()->make_narrowoop()));3073if (kind == LS_xchg) {3074load_store = _gvn.transform(new (C) GetAndSetNNode(control(), mem, adr,3075newval_enc, adr_type, value_type->make_narrowoop()));3076} else {3077assert(kind == LS_cmpxchg, "wrong LoadStore operation");3078Node *oldval_enc = _gvn.transform(new (C) EncodePNode(oldval, oldval->bottom_type()->make_narrowoop()));3079load_store = _gvn.transform(new (C) CompareAndSwapNNode(control(), mem, adr,3080newval_enc, oldval_enc));3081}3082} else3083#endif3084{3085if (kind == LS_xchg) {3086load_store = _gvn.transform(new (C) GetAndSetPNode(control(), mem, adr, newval, adr_type, value_type->is_oopptr()));3087} else {3088assert(kind == LS_cmpxchg, "wrong LoadStore operation");3089load_store = _gvn.transform(new (C) CompareAndSwapPNode(control(), mem, adr, newval, oldval));3090}3091}3092post_barrier(control(), load_store, base, adr, alias_idx, newval, T_OBJECT, true);3093break;3094default:3095fatal(err_msg_res("unexpected type %d: %s", type, type2name(type)));3096break;3097}30983099// SCMemProjNodes represent the memory state of a LoadStore. Their3100// main role is to prevent LoadStore nodes from being optimized away3101// when their results aren't used.3102Node* proj = _gvn.transform(new (C) SCMemProjNode(load_store));3103set_memory(proj, alias_idx);31043105Node* access = load_store;31063107if (type == T_OBJECT && kind == LS_xchg) {3108#ifdef _LP643109if (adr->bottom_type()->is_ptr_to_narrowoop()) {3110load_store = _gvn.transform(new (C) DecodeNNode(load_store, load_store->get_ptr_type()));3111}3112#endif3113if (can_move_pre_barrier()) {3114// Don't need to load pre_val. The old value is returned by load_store.3115// The pre_barrier can execute after the xchg as long as no safepoint3116// gets inserted between them.3117pre_barrier(false /* do_load */,3118control(), NULL, NULL, max_juint, NULL, NULL,3119load_store /* pre_val */,3120T_OBJECT);3121}3122}31233124// Add the trailing membar surrounding the access3125insert_mem_bar(Op_MemBarCPUOrder);3126Node* mb = insert_mem_bar(Op_MemBarAcquire, access);3127MemBarNode::set_load_store_pair(leading_membar->as_MemBar(), mb->as_MemBar());31283129assert(type2size[load_store->bottom_type()->basic_type()] == type2size[rtype], "result type should match");3130set_result(load_store);3131return true;3132}31333134//----------------------------inline_unsafe_ordered_store----------------------3135// public native void sun.misc.Unsafe.putOrderedObject(Object o, long offset, Object x);3136// public native void sun.misc.Unsafe.putOrderedInt(Object o, long offset, int x);3137// public native void sun.misc.Unsafe.putOrderedLong(Object o, long offset, long x);3138bool LibraryCallKit::inline_unsafe_ordered_store(BasicType type) {3139// This is another variant of inline_unsafe_access, differing in3140// that it always issues store-store ("release") barrier and ensures3141// store-atomicity (which only matters for "long").31423143if (callee()->is_static()) return false; // caller must have the capability!31443145#ifndef PRODUCT3146{3147ResourceMark rm;3148// Check the signatures.3149ciSignature* sig = callee()->signature();3150#ifdef ASSERT3151BasicType rtype = sig->return_type()->basic_type();3152assert(rtype == T_VOID, "must return void");3153assert(sig->count() == 3, "has 3 arguments");3154assert(sig->type_at(0)->basic_type() == T_OBJECT, "base is object");3155assert(sig->type_at(1)->basic_type() == T_LONG, "offset is long");3156#endif // ASSERT3157}3158#endif //PRODUCT31593160C->set_has_unsafe_access(true); // Mark eventual nmethod as "unsafe".31613162// Get arguments:3163Node* receiver = argument(0); // type: oop3164Node* base = argument(1); // type: oop3165Node* offset = argument(2); // type: long3166Node* val = argument(4); // type: oop, int, or long31673168// Null check receiver.3169receiver = null_check(receiver);3170if (stopped()) {3171return true;3172}31733174// Build field offset expression.3175assert(Unsafe_field_offset_to_byte_offset(11) == 11, "fieldOffset must be byte-scaled");3176// 32-bit machines ignore the high half of long offsets3177offset = ConvL2X(offset);3178Node* adr = make_unsafe_address(base, offset);3179const TypePtr *adr_type = _gvn.type(adr)->isa_ptr();3180const Type *value_type = Type::get_const_basic_type(type);3181Compile::AliasType* alias_type = C->alias_type(adr_type);31823183insert_mem_bar(Op_MemBarRelease);3184insert_mem_bar(Op_MemBarCPUOrder);3185// Ensure that the store is atomic for longs:3186const bool require_atomic_access = true;3187Node* store;3188if (type == T_OBJECT) // reference stores need a store barrier.3189store = store_oop_to_unknown(control(), base, adr, adr_type, val, type, MemNode::release);3190else {3191store = store_to_memory(control(), adr, val, type, adr_type, MemNode::release, require_atomic_access);3192}3193insert_mem_bar(Op_MemBarCPUOrder);3194return true;3195}31963197bool LibraryCallKit::inline_unsafe_fence(vmIntrinsics::ID id) {3198// Regardless of form, don't allow previous ld/st to move down,3199// then issue acquire, release, or volatile mem_bar.3200insert_mem_bar(Op_MemBarCPUOrder);3201switch(id) {3202case vmIntrinsics::_loadFence:3203insert_mem_bar(Op_LoadFence);3204return true;3205case vmIntrinsics::_storeFence:3206insert_mem_bar(Op_StoreFence);3207return true;3208case vmIntrinsics::_fullFence:3209insert_mem_bar(Op_MemBarVolatile);3210return true;3211default:3212fatal_unexpected_iid(id);3213return false;3214}3215}32163217bool LibraryCallKit::klass_needs_init_guard(Node* kls) {3218if (!kls->is_Con()) {3219return true;3220}3221const TypeKlassPtr* klsptr = kls->bottom_type()->isa_klassptr();3222if (klsptr == NULL) {3223return true;3224}3225ciInstanceKlass* ik = klsptr->klass()->as_instance_klass();3226// don't need a guard for a klass that is already initialized3227return !ik->is_initialized();3228}32293230//----------------------------inline_unsafe_allocate---------------------------3231// public native Object sun.misc.Unsafe.allocateInstance(Class<?> cls);3232bool LibraryCallKit::inline_unsafe_allocate() {3233if (callee()->is_static()) return false; // caller must have the capability!32343235null_check_receiver(); // null-check, then ignore3236Node* cls = null_check(argument(1));3237if (stopped()) return true;32383239Node* kls = load_klass_from_mirror(cls, false, NULL, 0);3240kls = null_check(kls);3241if (stopped()) return true; // argument was like int.class32423243Node* test = NULL;3244if (LibraryCallKit::klass_needs_init_guard(kls)) {3245// Note: The argument might still be an illegal value like3246// Serializable.class or Object[].class. The runtime will handle it.3247// But we must make an explicit check for initialization.3248Node* insp = basic_plus_adr(kls, in_bytes(InstanceKlass::init_state_offset()));3249// Use T_BOOLEAN for InstanceKlass::_init_state so the compiler3250// can generate code to load it as unsigned byte.3251Node* inst = make_load(NULL, insp, TypeInt::UBYTE, T_BOOLEAN, MemNode::unordered);3252Node* bits = intcon(InstanceKlass::fully_initialized);3253test = _gvn.transform(new (C) SubINode(inst, bits));3254// The 'test' is non-zero if we need to take a slow path.3255}32563257Node* obj = new_instance(kls, test);3258set_result(obj);3259return true;3260}32613262#ifdef JFR_HAVE_INTRINSICS3263/*3264* oop -> myklass3265* myklass->trace_id |= USED3266* return myklass->trace_id & ~0x33267*/3268bool LibraryCallKit::inline_native_classID() {3269Node* cls = null_check(argument(0), T_OBJECT);3270Node* kls = load_klass_from_mirror(cls, false, NULL, 0);3271kls = null_check(kls, T_OBJECT);32723273ByteSize offset = KLASS_TRACE_ID_OFFSET;3274Node* insp = basic_plus_adr(kls, in_bytes(offset));3275Node* tvalue = make_load(NULL, insp, TypeLong::LONG, T_LONG, MemNode::unordered);32763277Node* clsused = longcon(0x01l); // set the class bit3278Node* orl = _gvn.transform(new (C) OrLNode(tvalue, clsused));3279const TypePtr *adr_type = _gvn.type(insp)->isa_ptr();3280store_to_memory(control(), insp, orl, T_LONG, adr_type, MemNode::unordered);32813282#ifdef TRACE_ID_META_BITS3283Node* mbits = longcon(~TRACE_ID_META_BITS);3284tvalue = _gvn.transform(new (C) AndLNode(tvalue, mbits));3285#endif3286#ifdef TRACE_ID_SHIFT3287Node* cbits = intcon(TRACE_ID_SHIFT);3288tvalue = _gvn.transform(new (C) URShiftLNode(tvalue, cbits));3289#endif32903291set_result(tvalue);3292return true;3293}32943295bool LibraryCallKit::inline_native_getEventWriter() {3296Node* tls_ptr = _gvn.transform(new (C) ThreadLocalNode());32973298Node* jobj_ptr = basic_plus_adr(top(), tls_ptr,3299in_bytes(THREAD_LOCAL_WRITER_OFFSET_JFR)3300);33013302Node* jobj = make_load(control(), jobj_ptr, TypeRawPtr::BOTTOM, T_ADDRESS, MemNode::unordered);33033304Node* jobj_cmp_null = _gvn.transform( new (C) CmpPNode(jobj, null()) );3305Node* test_jobj_eq_null = _gvn.transform( new (C) BoolNode(jobj_cmp_null, BoolTest::eq) );33063307IfNode* iff_jobj_null =3308create_and_map_if(control(), test_jobj_eq_null, PROB_MIN, COUNT_UNKNOWN);33093310enum { _normal_path = 1,3311_null_path = 2,3312PATH_LIMIT };33133314RegionNode* result_rgn = new (C) RegionNode(PATH_LIMIT);3315PhiNode* result_val = new (C) PhiNode(result_rgn, TypePtr::BOTTOM);33163317Node* jobj_is_null = _gvn.transform(new (C) IfTrueNode(iff_jobj_null));3318result_rgn->init_req(_null_path, jobj_is_null);3319result_val->init_req(_null_path, null());33203321Node* jobj_is_not_null = _gvn.transform(new (C) IfFalseNode(iff_jobj_null));3322result_rgn->init_req(_normal_path, jobj_is_not_null);33233324Node* res = make_load(jobj_is_not_null, jobj, TypeInstPtr::NOTNULL, T_OBJECT, MemNode::unordered);3325result_val->init_req(_normal_path, res);33263327set_result(result_rgn, result_val);33283329return true;3330}3331#endif // JFR_HAVE_INTRINSICS33323333//------------------------inline_native_time_funcs--------------3334// inline code for System.currentTimeMillis() and System.nanoTime()3335// these have the same type and signature3336bool LibraryCallKit::inline_native_time_funcs(address funcAddr, const char* funcName) {3337const TypeFunc* tf = OptoRuntime::void_long_Type();3338const TypePtr* no_memory_effects = NULL;3339Node* time = make_runtime_call(RC_LEAF, tf, funcAddr, funcName, no_memory_effects);3340Node* value = _gvn.transform(new (C) ProjNode(time, TypeFunc::Parms+0));3341#ifdef ASSERT3342Node* value_top = _gvn.transform(new (C) ProjNode(time, TypeFunc::Parms+1));3343assert(value_top == top(), "second value must be top");3344#endif3345set_result(value);3346return true;3347}33483349//------------------------inline_native_currentThread------------------3350bool LibraryCallKit::inline_native_currentThread() {3351Node* junk = NULL;3352set_result(generate_current_thread(junk));3353return true;3354}33553356//------------------------inline_native_isInterrupted------------------3357// private native boolean java.lang.Thread.isInterrupted(boolean ClearInterrupted);3358bool LibraryCallKit::inline_native_isInterrupted() {3359// Add a fast path to t.isInterrupted(clear_int):3360// (t == Thread.current() &&3361// (!TLS._osthread._interrupted || WINDOWS_ONLY(false) NOT_WINDOWS(!clear_int)))3362// ? TLS._osthread._interrupted : /*slow path:*/ t.isInterrupted(clear_int)3363// So, in the common case that the interrupt bit is false,3364// we avoid making a call into the VM. Even if the interrupt bit3365// is true, if the clear_int argument is false, we avoid the VM call.3366// However, if the receiver is not currentThread, we must call the VM,3367// because there must be some locking done around the operation.33683369// We only go to the fast case code if we pass two guards.3370// Paths which do not pass are accumulated in the slow_region.33713372enum {3373no_int_result_path = 1, // t == Thread.current() && !TLS._osthread._interrupted3374no_clear_result_path = 2, // t == Thread.current() && TLS._osthread._interrupted && !clear_int3375slow_result_path = 3, // slow path: t.isInterrupted(clear_int)3376PATH_LIMIT3377};33783379// Ensure that it's not possible to move the load of TLS._osthread._interrupted flag3380// out of the function.3381insert_mem_bar(Op_MemBarCPUOrder);33823383RegionNode* result_rgn = new (C) RegionNode(PATH_LIMIT);3384PhiNode* result_val = new (C) PhiNode(result_rgn, TypeInt::BOOL);33853386RegionNode* slow_region = new (C) RegionNode(1);3387record_for_igvn(slow_region);33883389// (a) Receiving thread must be the current thread.3390Node* rec_thr = argument(0);3391Node* tls_ptr = NULL;3392Node* cur_thr = generate_current_thread(tls_ptr);3393Node* cmp_thr = _gvn.transform(new (C) CmpPNode(cur_thr, rec_thr));3394Node* bol_thr = _gvn.transform(new (C) BoolNode(cmp_thr, BoolTest::ne));33953396generate_slow_guard(bol_thr, slow_region);33973398// (b) Interrupt bit on TLS must be false.3399Node* p = basic_plus_adr(top()/*!oop*/, tls_ptr, in_bytes(JavaThread::osthread_offset()));3400Node* osthread = make_load(NULL, p, TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered);3401p = basic_plus_adr(top()/*!oop*/, osthread, in_bytes(OSThread::interrupted_offset()));34023403// Set the control input on the field _interrupted read to prevent it floating up.3404Node* int_bit = make_load(control(), p, TypeInt::BOOL, T_INT, MemNode::unordered);3405Node* cmp_bit = _gvn.transform(new (C) CmpINode(int_bit, intcon(0)));3406Node* bol_bit = _gvn.transform(new (C) BoolNode(cmp_bit, BoolTest::ne));34073408IfNode* iff_bit = create_and_map_if(control(), bol_bit, PROB_UNLIKELY_MAG(3), COUNT_UNKNOWN);34093410// First fast path: if (!TLS._interrupted) return false;3411Node* false_bit = _gvn.transform(new (C) IfFalseNode(iff_bit));3412result_rgn->init_req(no_int_result_path, false_bit);3413result_val->init_req(no_int_result_path, intcon(0));34143415// drop through to next case3416set_control( _gvn.transform(new (C) IfTrueNode(iff_bit)));34173418#ifndef TARGET_OS_FAMILY_windows3419// (c) Or, if interrupt bit is set and clear_int is false, use 2nd fast path.3420Node* clr_arg = argument(1);3421Node* cmp_arg = _gvn.transform(new (C) CmpINode(clr_arg, intcon(0)));3422Node* bol_arg = _gvn.transform(new (C) BoolNode(cmp_arg, BoolTest::ne));3423IfNode* iff_arg = create_and_map_if(control(), bol_arg, PROB_FAIR, COUNT_UNKNOWN);34243425// Second fast path: ... else if (!clear_int) return true;3426Node* false_arg = _gvn.transform(new (C) IfFalseNode(iff_arg));3427result_rgn->init_req(no_clear_result_path, false_arg);3428result_val->init_req(no_clear_result_path, intcon(1));34293430// drop through to next case3431set_control( _gvn.transform(new (C) IfTrueNode(iff_arg)));3432#else3433// To return true on Windows you must read the _interrupted field3434// and check the the event state i.e. take the slow path.3435#endif // TARGET_OS_FAMILY_windows34363437// (d) Otherwise, go to the slow path.3438slow_region->add_req(control());3439set_control( _gvn.transform(slow_region));34403441if (stopped()) {3442// There is no slow path.3443result_rgn->init_req(slow_result_path, top());3444result_val->init_req(slow_result_path, top());3445} else {3446// non-virtual because it is a private non-static3447CallJavaNode* slow_call = generate_method_call(vmIntrinsics::_isInterrupted);34483449Node* slow_val = set_results_for_java_call(slow_call);3450// this->control() comes from set_results_for_java_call34513452Node* fast_io = slow_call->in(TypeFunc::I_O);3453Node* fast_mem = slow_call->in(TypeFunc::Memory);34543455// These two phis are pre-filled with copies of of the fast IO and Memory3456PhiNode* result_mem = PhiNode::make(result_rgn, fast_mem, Type::MEMORY, TypePtr::BOTTOM);3457PhiNode* result_io = PhiNode::make(result_rgn, fast_io, Type::ABIO);34583459result_rgn->init_req(slow_result_path, control());3460result_io ->init_req(slow_result_path, i_o());3461result_mem->init_req(slow_result_path, reset_memory());3462result_val->init_req(slow_result_path, slow_val);34633464set_all_memory(_gvn.transform(result_mem));3465set_i_o( _gvn.transform(result_io));3466}34673468C->set_has_split_ifs(true); // Has chance for split-if optimization3469set_result(result_rgn, result_val);3470return true;3471}34723473//---------------------------load_mirror_from_klass----------------------------3474// Given a klass oop, load its java mirror (a java.lang.Class oop).3475Node* LibraryCallKit::load_mirror_from_klass(Node* klass) {3476Node* p = basic_plus_adr(klass, in_bytes(Klass::java_mirror_offset()));3477return make_load(NULL, p, TypeInstPtr::MIRROR, T_OBJECT, MemNode::unordered);3478}34793480//-----------------------load_klass_from_mirror_common-------------------------3481// Given a java mirror (a java.lang.Class oop), load its corresponding klass oop.3482// Test the klass oop for null (signifying a primitive Class like Integer.TYPE),3483// and branch to the given path on the region.3484// If never_see_null, take an uncommon trap on null, so we can optimistically3485// compile for the non-null case.3486// If the region is NULL, force never_see_null = true.3487Node* LibraryCallKit::load_klass_from_mirror_common(Node* mirror,3488bool never_see_null,3489RegionNode* region,3490int null_path,3491int offset) {3492if (region == NULL) never_see_null = true;3493Node* p = basic_plus_adr(mirror, offset);3494const TypeKlassPtr* kls_type = TypeKlassPtr::OBJECT_OR_NULL;3495Node* kls = _gvn.transform(LoadKlassNode::make(_gvn, NULL, immutable_memory(), p, TypeRawPtr::BOTTOM, kls_type));3496Node* null_ctl = top();3497kls = null_check_oop(kls, &null_ctl, never_see_null);3498if (region != NULL) {3499// Set region->in(null_path) if the mirror is a primitive (e.g, int.class).3500region->init_req(null_path, null_ctl);3501} else {3502assert(null_ctl == top(), "no loose ends");3503}3504return kls;3505}35063507//--------------------(inline_native_Class_query helpers)---------------------3508// Use this for JVM_ACC_INTERFACE, JVM_ACC_IS_CLONEABLE, JVM_ACC_HAS_FINALIZER.3509// Fall through if (mods & mask) == bits, take the guard otherwise.3510Node* LibraryCallKit::generate_access_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region) {3511// Branch around if the given klass has the given modifier bit set.3512// Like generate_guard, adds a new path onto the region.3513Node* modp = basic_plus_adr(kls, in_bytes(Klass::access_flags_offset()));3514Node* mods = make_load(NULL, modp, TypeInt::INT, T_INT, MemNode::unordered);3515Node* mask = intcon(modifier_mask);3516Node* bits = intcon(modifier_bits);3517Node* mbit = _gvn.transform(new (C) AndINode(mods, mask));3518Node* cmp = _gvn.transform(new (C) CmpINode(mbit, bits));3519Node* bol = _gvn.transform(new (C) BoolNode(cmp, BoolTest::ne));3520return generate_fair_guard(bol, region);3521}3522Node* LibraryCallKit::generate_interface_guard(Node* kls, RegionNode* region) {3523return generate_access_flags_guard(kls, JVM_ACC_INTERFACE, 0, region);3524}35253526//-------------------------inline_native_Class_query-------------------3527bool LibraryCallKit::inline_native_Class_query(vmIntrinsics::ID id) {3528const Type* return_type = TypeInt::BOOL;3529Node* prim_return_value = top(); // what happens if it's a primitive class?3530bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);3531bool expect_prim = false; // most of these guys expect to work on refs35323533enum { _normal_path = 1, _prim_path = 2, PATH_LIMIT };35343535Node* mirror = argument(0);3536Node* obj = top();35373538switch (id) {3539case vmIntrinsics::_isInstance:3540// nothing is an instance of a primitive type3541prim_return_value = intcon(0);3542obj = argument(1);3543break;3544case vmIntrinsics::_getModifiers:3545prim_return_value = intcon(JVM_ACC_ABSTRACT | JVM_ACC_FINAL | JVM_ACC_PUBLIC);3546assert(is_power_of_2((int)JVM_ACC_WRITTEN_FLAGS+1), "change next line");3547return_type = TypeInt::make(0, JVM_ACC_WRITTEN_FLAGS, Type::WidenMin);3548break;3549case vmIntrinsics::_isInterface:3550prim_return_value = intcon(0);3551break;3552case vmIntrinsics::_isArray:3553prim_return_value = intcon(0);3554expect_prim = true; // cf. ObjectStreamClass.getClassSignature3555break;3556case vmIntrinsics::_isPrimitive:3557prim_return_value = intcon(1);3558expect_prim = true; // obviously3559break;3560case vmIntrinsics::_getSuperclass:3561prim_return_value = null();3562return_type = TypeInstPtr::MIRROR->cast_to_ptr_type(TypePtr::BotPTR);3563break;3564case vmIntrinsics::_getComponentType:3565prim_return_value = null();3566return_type = TypeInstPtr::MIRROR->cast_to_ptr_type(TypePtr::BotPTR);3567break;3568case vmIntrinsics::_getClassAccessFlags:3569prim_return_value = intcon(JVM_ACC_ABSTRACT | JVM_ACC_FINAL | JVM_ACC_PUBLIC);3570return_type = TypeInt::INT; // not bool! 62970943571break;3572default:3573fatal_unexpected_iid(id);3574break;3575}35763577const TypeInstPtr* mirror_con = _gvn.type(mirror)->isa_instptr();3578if (mirror_con == NULL) return false; // cannot happen?35793580#ifndef PRODUCT3581if (C->print_intrinsics() || C->print_inlining()) {3582ciType* k = mirror_con->java_mirror_type();3583if (k) {3584tty->print("Inlining %s on constant Class ", vmIntrinsics::name_at(intrinsic_id()));3585k->print_name();3586tty->cr();3587}3588}3589#endif35903591// Null-check the mirror, and the mirror's klass ptr (in case it is a primitive).3592RegionNode* region = new (C) RegionNode(PATH_LIMIT);3593record_for_igvn(region);3594PhiNode* phi = new (C) PhiNode(region, return_type);35953596// The mirror will never be null of Reflection.getClassAccessFlags, however3597// it may be null for Class.isInstance or Class.getModifiers. Throw a NPE3598// if it is. See bug 4774291.35993600// For Reflection.getClassAccessFlags(), the null check occurs in3601// the wrong place; see inline_unsafe_access(), above, for a similar3602// situation.3603mirror = null_check(mirror);3604// If mirror or obj is dead, only null-path is taken.3605if (stopped()) return true;36063607if (expect_prim) never_see_null = false; // expect nulls (meaning prims)36083609// Now load the mirror's klass metaobject, and null-check it.3610// Side-effects region with the control path if the klass is null.3611Node* kls = load_klass_from_mirror(mirror, never_see_null, region, _prim_path);3612// If kls is null, we have a primitive mirror.3613phi->init_req(_prim_path, prim_return_value);3614if (stopped()) { set_result(region, phi); return true; }3615bool safe_for_replace = (region->in(_prim_path) == top());36163617Node* p; // handy temp3618Node* null_ctl;36193620// Now that we have the non-null klass, we can perform the real query.3621// For constant classes, the query will constant-fold in LoadNode::Value.3622Node* query_value = top();3623switch (id) {3624case vmIntrinsics::_isInstance:3625// nothing is an instance of a primitive type3626query_value = gen_instanceof(obj, kls, safe_for_replace);3627break;36283629case vmIntrinsics::_getModifiers:3630p = basic_plus_adr(kls, in_bytes(Klass::modifier_flags_offset()));3631query_value = make_load(NULL, p, TypeInt::INT, T_INT, MemNode::unordered);3632break;36333634case vmIntrinsics::_isInterface:3635// (To verify this code sequence, check the asserts in JVM_IsInterface.)3636if (generate_interface_guard(kls, region) != NULL)3637// A guard was added. If the guard is taken, it was an interface.3638phi->add_req(intcon(1));3639// If we fall through, it's a plain class.3640query_value = intcon(0);3641break;36423643case vmIntrinsics::_isArray:3644// (To verify this code sequence, check the asserts in JVM_IsArrayClass.)3645if (generate_array_guard(kls, region) != NULL)3646// A guard was added. If the guard is taken, it was an array.3647phi->add_req(intcon(1));3648// If we fall through, it's a plain class.3649query_value = intcon(0);3650break;36513652case vmIntrinsics::_isPrimitive:3653query_value = intcon(0); // "normal" path produces false3654break;36553656case vmIntrinsics::_getSuperclass:3657// The rules here are somewhat unfortunate, but we can still do better3658// with random logic than with a JNI call.3659// Interfaces store null or Object as _super, but must report null.3660// Arrays store an intermediate super as _super, but must report Object.3661// Other types can report the actual _super.3662// (To verify this code sequence, check the asserts in JVM_IsInterface.)3663if (generate_interface_guard(kls, region) != NULL)3664// A guard was added. If the guard is taken, it was an interface.3665phi->add_req(null());3666if (generate_array_guard(kls, region) != NULL)3667// A guard was added. If the guard is taken, it was an array.3668phi->add_req(makecon(TypeInstPtr::make(env()->Object_klass()->java_mirror())));3669// If we fall through, it's a plain class. Get its _super.3670p = basic_plus_adr(kls, in_bytes(Klass::super_offset()));3671kls = _gvn.transform(LoadKlassNode::make(_gvn, NULL, immutable_memory(), p, TypeRawPtr::BOTTOM, TypeKlassPtr::OBJECT_OR_NULL));3672null_ctl = top();3673kls = null_check_oop(kls, &null_ctl);3674if (null_ctl != top()) {3675// If the guard is taken, Object.superClass is null (both klass and mirror).3676region->add_req(null_ctl);3677phi ->add_req(null());3678}3679if (!stopped()) {3680query_value = load_mirror_from_klass(kls);3681}3682break;36833684case vmIntrinsics::_getComponentType:3685if (generate_array_guard(kls, region) != NULL) {3686// Be sure to pin the oop load to the guard edge just created:3687Node* is_array_ctrl = region->in(region->req()-1);3688Node* cma = basic_plus_adr(kls, in_bytes(ArrayKlass::component_mirror_offset()));3689Node* cmo = make_load(is_array_ctrl, cma, TypeInstPtr::MIRROR, T_OBJECT, MemNode::unordered);3690phi->add_req(cmo);3691}3692query_value = null(); // non-array case is null3693break;36943695case vmIntrinsics::_getClassAccessFlags:3696p = basic_plus_adr(kls, in_bytes(Klass::access_flags_offset()));3697query_value = make_load(NULL, p, TypeInt::INT, T_INT, MemNode::unordered);3698break;36993700default:3701fatal_unexpected_iid(id);3702break;3703}37043705// Fall-through is the normal case of a query to a real class.3706phi->init_req(1, query_value);3707region->init_req(1, control());37083709C->set_has_split_ifs(true); // Has chance for split-if optimization3710set_result(region, phi);3711return true;3712}37133714//--------------------------inline_native_subtype_check------------------------3715// This intrinsic takes the JNI calls out of the heart of3716// UnsafeFieldAccessorImpl.set, which improves Field.set, readObject, etc.3717bool LibraryCallKit::inline_native_subtype_check() {3718// Pull both arguments off the stack.3719Node* args[2]; // two java.lang.Class mirrors: superc, subc3720args[0] = argument(0);3721args[1] = argument(1);3722Node* klasses[2]; // corresponding Klasses: superk, subk3723klasses[0] = klasses[1] = top();37243725enum {3726// A full decision tree on {superc is prim, subc is prim}:3727_prim_0_path = 1, // {P,N} => false3728// {P,P} & superc!=subc => false3729_prim_same_path, // {P,P} & superc==subc => true3730_prim_1_path, // {N,P} => false3731_ref_subtype_path, // {N,N} & subtype check wins => true3732_both_ref_path, // {N,N} & subtype check loses => false3733PATH_LIMIT3734};37353736RegionNode* region = new (C) RegionNode(PATH_LIMIT);3737Node* phi = new (C) PhiNode(region, TypeInt::BOOL);3738record_for_igvn(region);37393740const TypePtr* adr_type = TypeRawPtr::BOTTOM; // memory type of loads3741const TypeKlassPtr* kls_type = TypeKlassPtr::OBJECT_OR_NULL;3742int class_klass_offset = java_lang_Class::klass_offset_in_bytes();37433744// First null-check both mirrors and load each mirror's klass metaobject.3745int which_arg;3746for (which_arg = 0; which_arg <= 1; which_arg++) {3747Node* arg = args[which_arg];3748arg = null_check(arg);3749if (stopped()) break;3750args[which_arg] = arg;37513752Node* p = basic_plus_adr(arg, class_klass_offset);3753Node* kls = LoadKlassNode::make(_gvn, NULL, immutable_memory(), p, adr_type, kls_type);3754klasses[which_arg] = _gvn.transform(kls);3755}37563757// Having loaded both klasses, test each for null.3758bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);3759for (which_arg = 0; which_arg <= 1; which_arg++) {3760Node* kls = klasses[which_arg];3761Node* null_ctl = top();3762kls = null_check_oop(kls, &null_ctl, never_see_null);3763int prim_path = (which_arg == 0 ? _prim_0_path : _prim_1_path);3764region->init_req(prim_path, null_ctl);3765if (stopped()) break;3766klasses[which_arg] = kls;3767}37683769if (!stopped()) {3770// now we have two reference types, in klasses[0..1]3771Node* subk = klasses[1]; // the argument to isAssignableFrom3772Node* superk = klasses[0]; // the receiver3773region->set_req(_both_ref_path, gen_subtype_check(subk, superk));3774// now we have a successful reference subtype check3775region->set_req(_ref_subtype_path, control());3776}37773778// If both operands are primitive (both klasses null), then3779// we must return true when they are identical primitives.3780// It is convenient to test this after the first null klass check.3781set_control(region->in(_prim_0_path)); // go back to first null check3782if (!stopped()) {3783// Since superc is primitive, make a guard for the superc==subc case.3784Node* cmp_eq = _gvn.transform(new (C) CmpPNode(args[0], args[1]));3785Node* bol_eq = _gvn.transform(new (C) BoolNode(cmp_eq, BoolTest::eq));3786generate_guard(bol_eq, region, PROB_FAIR);3787if (region->req() == PATH_LIMIT+1) {3788// A guard was added. If the added guard is taken, superc==subc.3789region->swap_edges(PATH_LIMIT, _prim_same_path);3790region->del_req(PATH_LIMIT);3791}3792region->set_req(_prim_0_path, control()); // Not equal after all.3793}37943795// these are the only paths that produce 'true':3796phi->set_req(_prim_same_path, intcon(1));3797phi->set_req(_ref_subtype_path, intcon(1));37983799// pull together the cases:3800assert(region->req() == PATH_LIMIT, "sane region");3801for (uint i = 1; i < region->req(); i++) {3802Node* ctl = region->in(i);3803if (ctl == NULL || ctl == top()) {3804region->set_req(i, top());3805phi ->set_req(i, top());3806} else if (phi->in(i) == NULL) {3807phi->set_req(i, intcon(0)); // all other paths produce 'false'3808}3809}38103811set_control(_gvn.transform(region));3812set_result(_gvn.transform(phi));3813return true;3814}38153816//---------------------generate_array_guard_common------------------------3817Node* LibraryCallKit::generate_array_guard_common(Node* kls, RegionNode* region,3818bool obj_array, bool not_array) {3819// If obj_array/non_array==false/false:3820// Branch around if the given klass is in fact an array (either obj or prim).3821// If obj_array/non_array==false/true:3822// Branch around if the given klass is not an array klass of any kind.3823// If obj_array/non_array==true/true:3824// Branch around if the kls is not an oop array (kls is int[], String, etc.)3825// If obj_array/non_array==true/false:3826// Branch around if the kls is an oop array (Object[] or subtype)3827//3828// Like generate_guard, adds a new path onto the region.3829jint layout_con = 0;3830Node* layout_val = get_layout_helper(kls, layout_con);3831if (layout_val == NULL) {3832bool query = (obj_array3833? Klass::layout_helper_is_objArray(layout_con)3834: Klass::layout_helper_is_array(layout_con));3835if (query == not_array) {3836return NULL; // never a branch3837} else { // always a branch3838Node* always_branch = control();3839if (region != NULL)3840region->add_req(always_branch);3841set_control(top());3842return always_branch;3843}3844}3845// Now test the correct condition.3846jint nval = (obj_array3847? (jint)(Klass::_lh_array_tag_type_value3848<< Klass::_lh_array_tag_shift)3849: Klass::_lh_neutral_value);3850Node* cmp = _gvn.transform(new(C) CmpINode(layout_val, intcon(nval)));3851BoolTest::mask btest = BoolTest::lt; // correct for testing is_[obj]array3852// invert the test if we are looking for a non-array3853if (not_array) btest = BoolTest(btest).negate();3854Node* bol = _gvn.transform(new(C) BoolNode(cmp, btest));3855return generate_fair_guard(bol, region);3856}385738583859//-----------------------inline_native_newArray--------------------------3860// private static native Object java.lang.reflect.newArray(Class<?> componentType, int length);3861bool LibraryCallKit::inline_native_newArray() {3862Node* mirror = argument(0);3863Node* count_val = argument(1);38643865mirror = null_check(mirror);3866// If mirror or obj is dead, only null-path is taken.3867if (stopped()) return true;38683869enum { _normal_path = 1, _slow_path = 2, PATH_LIMIT };3870RegionNode* result_reg = new(C) RegionNode(PATH_LIMIT);3871PhiNode* result_val = new(C) PhiNode(result_reg,3872TypeInstPtr::NOTNULL);3873PhiNode* result_io = new(C) PhiNode(result_reg, Type::ABIO);3874PhiNode* result_mem = new(C) PhiNode(result_reg, Type::MEMORY,3875TypePtr::BOTTOM);38763877bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);3878Node* klass_node = load_array_klass_from_mirror(mirror, never_see_null,3879result_reg, _slow_path);3880Node* normal_ctl = control();3881Node* no_array_ctl = result_reg->in(_slow_path);38823883// Generate code for the slow case. We make a call to newArray().3884set_control(no_array_ctl);3885if (!stopped()) {3886// Either the input type is void.class, or else the3887// array klass has not yet been cached. Either the3888// ensuing call will throw an exception, or else it3889// will cache the array klass for next time.3890PreserveJVMState pjvms(this);3891CallJavaNode* slow_call = generate_method_call_static(vmIntrinsics::_newArray);3892Node* slow_result = set_results_for_java_call(slow_call);3893// this->control() comes from set_results_for_java_call3894result_reg->set_req(_slow_path, control());3895result_val->set_req(_slow_path, slow_result);3896result_io ->set_req(_slow_path, i_o());3897result_mem->set_req(_slow_path, reset_memory());3898}38993900set_control(normal_ctl);3901if (!stopped()) {3902// Normal case: The array type has been cached in the java.lang.Class.3903// The following call works fine even if the array type is polymorphic.3904// It could be a dynamic mix of int[], boolean[], Object[], etc.3905Node* obj = new_array(klass_node, count_val, 0); // no arguments to push3906result_reg->init_req(_normal_path, control());3907result_val->init_req(_normal_path, obj);3908result_io ->init_req(_normal_path, i_o());3909result_mem->init_req(_normal_path, reset_memory());3910}39113912// Return the combined state.3913set_i_o( _gvn.transform(result_io) );3914set_all_memory( _gvn.transform(result_mem));39153916C->set_has_split_ifs(true); // Has chance for split-if optimization3917set_result(result_reg, result_val);3918return true;3919}39203921//----------------------inline_native_getLength--------------------------3922// public static native int java.lang.reflect.Array.getLength(Object array);3923bool LibraryCallKit::inline_native_getLength() {3924if (too_many_traps(Deoptimization::Reason_intrinsic)) return false;39253926Node* array = null_check(argument(0));3927// If array is dead, only null-path is taken.3928if (stopped()) return true;39293930// Deoptimize if it is a non-array.3931Node* non_array = generate_non_array_guard(load_object_klass(array), NULL);39323933if (non_array != NULL) {3934PreserveJVMState pjvms(this);3935set_control(non_array);3936uncommon_trap(Deoptimization::Reason_intrinsic,3937Deoptimization::Action_maybe_recompile);3938}39393940// If control is dead, only non-array-path is taken.3941if (stopped()) return true;39423943// The works fine even if the array type is polymorphic.3944// It could be a dynamic mix of int[], boolean[], Object[], etc.3945Node* result = load_array_length(array);39463947C->set_has_split_ifs(true); // Has chance for split-if optimization3948set_result(result);3949return true;3950}39513952//------------------------inline_array_copyOf----------------------------3953// public static <T,U> T[] java.util.Arrays.copyOf( U[] original, int newLength, Class<? extends T[]> newType);3954// public static <T,U> T[] java.util.Arrays.copyOfRange(U[] original, int from, int to, Class<? extends T[]> newType);3955bool LibraryCallKit::inline_array_copyOf(bool is_copyOfRange) {3956if (too_many_traps(Deoptimization::Reason_intrinsic)) return false;39573958// Get the arguments.3959Node* original = argument(0);3960Node* start = is_copyOfRange? argument(1): intcon(0);3961Node* end = is_copyOfRange? argument(2): argument(1);3962Node* array_type_mirror = is_copyOfRange? argument(3): argument(2);39633964Node* newcopy = NULL;39653966// Set the original stack and the reexecute bit for the interpreter to reexecute3967// the bytecode that invokes Arrays.copyOf if deoptimization happens.3968{ PreserveReexecuteState preexecs(this);3969jvms()->set_should_reexecute(true);39703971array_type_mirror = null_check(array_type_mirror);3972original = null_check(original);39733974// Check if a null path was taken unconditionally.3975if (stopped()) return true;39763977Node* orig_length = load_array_length(original);39783979Node* klass_node = load_klass_from_mirror(array_type_mirror, false, NULL, 0);3980klass_node = null_check(klass_node);39813982RegionNode* bailout = new (C) RegionNode(1);3983record_for_igvn(bailout);39843985// Despite the generic type of Arrays.copyOf, the mirror might be int, int[], etc.3986// Bail out if that is so.3987Node* not_objArray = generate_non_objArray_guard(klass_node, bailout);3988if (not_objArray != NULL) {3989// Improve the klass node's type from the new optimistic assumption:3990ciKlass* ak = ciArrayKlass::make(env()->Object_klass());3991const Type* akls = TypeKlassPtr::make(TypePtr::NotNull, ak, 0/*offset*/);3992Node* cast = new (C) CastPPNode(klass_node, akls);3993cast->init_req(0, control());3994klass_node = _gvn.transform(cast);3995}39963997// Bail out if either start or end is negative.3998generate_negative_guard(start, bailout, &start);3999generate_negative_guard(end, bailout, &end);40004001Node* length = end;4002if (_gvn.type(start) != TypeInt::ZERO) {4003length = _gvn.transform(new (C) SubINode(end, start));4004}40054006// Bail out if length is negative.4007// Without this the new_array would throw4008// NegativeArraySizeException but IllegalArgumentException is what4009// should be thrown4010generate_negative_guard(length, bailout, &length);40114012if (bailout->req() > 1) {4013PreserveJVMState pjvms(this);4014set_control(_gvn.transform(bailout));4015uncommon_trap(Deoptimization::Reason_intrinsic,4016Deoptimization::Action_maybe_recompile);4017}40184019if (!stopped()) {4020// How many elements will we copy from the original?4021// The answer is MinI(orig_length - start, length).4022Node* orig_tail = _gvn.transform(new (C) SubINode(orig_length, start));4023Node* moved = generate_min_max(vmIntrinsics::_min, orig_tail, length);40244025newcopy = new_array(klass_node, length, 0); // no argments to push40264027// Generate a direct call to the right arraycopy function(s).4028// We know the copy is disjoint but we might not know if the4029// oop stores need checking.4030// Extreme case: Arrays.copyOf((Integer[])x, 10, String[].class).4031// This will fail a store-check if x contains any non-nulls.4032bool disjoint_bases = true;4033// if start > orig_length then the length of the copy may be4034// negative.4035bool length_never_negative = !is_copyOfRange;4036generate_arraycopy(TypeAryPtr::OOPS, T_OBJECT,4037original, start, newcopy, intcon(0), moved,4038disjoint_bases, length_never_negative);4039}4040} // original reexecute is set back here40414042C->set_has_split_ifs(true); // Has chance for split-if optimization4043if (!stopped()) {4044set_result(newcopy);4045}4046return true;4047}404840494050//----------------------generate_virtual_guard---------------------------4051// Helper for hashCode and clone. Peeks inside the vtable to avoid a call.4052Node* LibraryCallKit::generate_virtual_guard(Node* obj_klass,4053RegionNode* slow_region) {4054ciMethod* method = callee();4055int vtable_index = method->vtable_index();4056assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index,4057err_msg_res("bad index %d", vtable_index));4058// Get the Method* out of the appropriate vtable entry.4059int entry_offset = (InstanceKlass::vtable_start_offset() +4060vtable_index*vtableEntry::size()) * wordSize +4061vtableEntry::method_offset_in_bytes();4062Node* entry_addr = basic_plus_adr(obj_klass, entry_offset);4063Node* target_call = make_load(NULL, entry_addr, TypePtr::NOTNULL, T_ADDRESS, MemNode::unordered);40644065// Compare the target method with the expected method (e.g., Object.hashCode).4066const TypePtr* native_call_addr = TypeMetadataPtr::make(method);40674068Node* native_call = makecon(native_call_addr);4069Node* chk_native = _gvn.transform(new(C) CmpPNode(target_call, native_call));4070Node* test_native = _gvn.transform(new(C) BoolNode(chk_native, BoolTest::ne));40714072return generate_slow_guard(test_native, slow_region);4073}40744075//-----------------------generate_method_call----------------------------4076// Use generate_method_call to make a slow-call to the real4077// method if the fast path fails. An alternative would be to4078// use a stub like OptoRuntime::slow_arraycopy_Java.4079// This only works for expanding the current library call,4080// not another intrinsic. (E.g., don't use this for making an4081// arraycopy call inside of the copyOf intrinsic.)4082CallJavaNode*4083LibraryCallKit::generate_method_call(vmIntrinsics::ID method_id, bool is_virtual, bool is_static) {4084// When compiling the intrinsic method itself, do not use this technique.4085guarantee(callee() != C->method(), "cannot make slow-call to self");40864087ciMethod* method = callee();4088// ensure the JVMS we have will be correct for this call4089guarantee(method_id == method->intrinsic_id(), "must match");40904091const TypeFunc* tf = TypeFunc::make(method);4092CallJavaNode* slow_call;4093if (is_static) {4094assert(!is_virtual, "");4095slow_call = new(C) CallStaticJavaNode(C, tf,4096SharedRuntime::get_resolve_static_call_stub(),4097method, bci());4098} else if (is_virtual) {4099null_check_receiver();4100int vtable_index = Method::invalid_vtable_index;4101if (UseInlineCaches) {4102// Suppress the vtable call4103} else {4104// hashCode and clone are not a miranda methods,4105// so the vtable index is fixed.4106// No need to use the linkResolver to get it.4107vtable_index = method->vtable_index();4108assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index,4109err_msg_res("bad index %d", vtable_index));4110}4111slow_call = new(C) CallDynamicJavaNode(tf,4112SharedRuntime::get_resolve_virtual_call_stub(),4113method, vtable_index, bci());4114} else { // neither virtual nor static: opt_virtual4115null_check_receiver();4116slow_call = new(C) CallStaticJavaNode(C, tf,4117SharedRuntime::get_resolve_opt_virtual_call_stub(),4118method, bci());4119slow_call->set_optimized_virtual(true);4120}4121set_arguments_for_java_call(slow_call);4122set_edges_for_java_call(slow_call);4123return slow_call;4124}412541264127/**4128* Build special case code for calls to hashCode on an object. This call may4129* be virtual (invokevirtual) or bound (invokespecial). For each case we generate4130* slightly different code.4131*/4132bool LibraryCallKit::inline_native_hashcode(bool is_virtual, bool is_static) {4133assert(is_static == callee()->is_static(), "correct intrinsic selection");4134assert(!(is_virtual && is_static), "either virtual, special, or static");41354136enum { _slow_path = 1, _fast_path, _null_path, PATH_LIMIT };41374138RegionNode* result_reg = new(C) RegionNode(PATH_LIMIT);4139PhiNode* result_val = new(C) PhiNode(result_reg, TypeInt::INT);4140PhiNode* result_io = new(C) PhiNode(result_reg, Type::ABIO);4141PhiNode* result_mem = new(C) PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);4142Node* obj = NULL;4143if (!is_static) {4144// Check for hashing null object4145obj = null_check_receiver();4146if (stopped()) return true; // unconditionally null4147result_reg->init_req(_null_path, top());4148result_val->init_req(_null_path, top());4149} else {4150// Do a null check, and return zero if null.4151// System.identityHashCode(null) == 04152obj = argument(0);4153Node* null_ctl = top();4154obj = null_check_oop(obj, &null_ctl);4155result_reg->init_req(_null_path, null_ctl);4156result_val->init_req(_null_path, _gvn.intcon(0));4157}41584159// Unconditionally null? Then return right away.4160if (stopped()) {4161set_control( result_reg->in(_null_path));4162if (!stopped())4163set_result(result_val->in(_null_path));4164return true;4165}41664167// We only go to the fast case code if we pass a number of guards. The4168// paths which do not pass are accumulated in the slow_region.4169RegionNode* slow_region = new (C) RegionNode(1);4170record_for_igvn(slow_region);41714172// If this is a virtual call, we generate a funny guard. We pull out4173// the vtable entry corresponding to hashCode() from the target object.4174// If the target method which we are calling happens to be the native4175// Object hashCode() method, we pass the guard. We do not need this4176// guard for non-virtual calls -- the caller is known to be the native4177// Object hashCode().4178if (is_virtual) {4179// After null check, get the object's klass.4180Node* obj_klass = load_object_klass(obj);4181generate_virtual_guard(obj_klass, slow_region);4182}41834184// Get the header out of the object, use LoadMarkNode when available4185Node* header_addr = basic_plus_adr(obj, oopDesc::mark_offset_in_bytes());4186// The control of the load must be NULL. Otherwise, the load can move before4187// the null check after castPP removal.4188Node* no_ctrl = NULL;4189Node* header = make_load(no_ctrl, header_addr, TypeX_X, TypeX_X->basic_type(), MemNode::unordered);41904191// Test the header to see if it is unlocked.4192Node* lock_mask = _gvn.MakeConX(markOopDesc::biased_lock_mask_in_place);4193Node* lmasked_header = _gvn.transform(new (C) AndXNode(header, lock_mask));4194Node* unlocked_val = _gvn.MakeConX(markOopDesc::unlocked_value);4195Node* chk_unlocked = _gvn.transform(new (C) CmpXNode( lmasked_header, unlocked_val));4196Node* test_unlocked = _gvn.transform(new (C) BoolNode( chk_unlocked, BoolTest::ne));41974198generate_slow_guard(test_unlocked, slow_region);41994200// Get the hash value and check to see that it has been properly assigned.4201// We depend on hash_mask being at most 32 bits and avoid the use of4202// hash_mask_in_place because it could be larger than 32 bits in a 64-bit4203// vm: see markOop.hpp.4204Node* hash_mask = _gvn.intcon(markOopDesc::hash_mask);4205Node* hash_shift = _gvn.intcon(markOopDesc::hash_shift);4206Node* hshifted_header= _gvn.transform(new (C) URShiftXNode(header, hash_shift));4207// This hack lets the hash bits live anywhere in the mark object now, as long4208// as the shift drops the relevant bits into the low 32 bits. Note that4209// Java spec says that HashCode is an int so there's no point in capturing4210// an 'X'-sized hashcode (32 in 32-bit build or 64 in 64-bit build).4211hshifted_header = ConvX2I(hshifted_header);4212Node* hash_val = _gvn.transform(new (C) AndINode(hshifted_header, hash_mask));42134214Node* no_hash_val = _gvn.intcon(markOopDesc::no_hash);4215Node* chk_assigned = _gvn.transform(new (C) CmpINode( hash_val, no_hash_val));4216Node* test_assigned = _gvn.transform(new (C) BoolNode( chk_assigned, BoolTest::eq));42174218generate_slow_guard(test_assigned, slow_region);42194220Node* init_mem = reset_memory();4221// fill in the rest of the null path:4222result_io ->init_req(_null_path, i_o());4223result_mem->init_req(_null_path, init_mem);42244225result_val->init_req(_fast_path, hash_val);4226result_reg->init_req(_fast_path, control());4227result_io ->init_req(_fast_path, i_o());4228result_mem->init_req(_fast_path, init_mem);42294230// Generate code for the slow case. We make a call to hashCode().4231set_control(_gvn.transform(slow_region));4232if (!stopped()) {4233// No need for PreserveJVMState, because we're using up the present state.4234set_all_memory(init_mem);4235vmIntrinsics::ID hashCode_id = is_static ? vmIntrinsics::_identityHashCode : vmIntrinsics::_hashCode;4236CallJavaNode* slow_call = generate_method_call(hashCode_id, is_virtual, is_static);4237Node* slow_result = set_results_for_java_call(slow_call);4238// this->control() comes from set_results_for_java_call4239result_reg->init_req(_slow_path, control());4240result_val->init_req(_slow_path, slow_result);4241result_io ->set_req(_slow_path, i_o());4242result_mem ->set_req(_slow_path, reset_memory());4243}42444245// Return the combined state.4246set_i_o( _gvn.transform(result_io) );4247set_all_memory( _gvn.transform(result_mem));42484249set_result(result_reg, result_val);4250return true;4251}42524253//---------------------------inline_native_getClass----------------------------4254// public final native Class<?> java.lang.Object.getClass();4255//4256// Build special case code for calls to getClass on an object.4257bool LibraryCallKit::inline_native_getClass() {4258Node* obj = null_check_receiver();4259if (stopped()) return true;4260set_result(load_mirror_from_klass(load_object_klass(obj)));4261return true;4262}42634264//-----------------inline_native_Reflection_getCallerClass---------------------4265// public static native Class<?> sun.reflect.Reflection.getCallerClass();4266//4267// In the presence of deep enough inlining, getCallerClass() becomes a no-op.4268//4269// NOTE: This code must perform the same logic as JVM_GetCallerClass4270// in that it must skip particular security frames and checks for4271// caller sensitive methods.4272bool LibraryCallKit::inline_native_Reflection_getCallerClass() {4273#ifndef PRODUCT4274if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {4275tty->print_cr("Attempting to inline sun.reflect.Reflection.getCallerClass");4276}4277#endif42784279if (!jvms()->has_method()) {4280#ifndef PRODUCT4281if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {4282tty->print_cr(" Bailing out because intrinsic was inlined at top level");4283}4284#endif4285return false;4286}42874288// Walk back up the JVM state to find the caller at the required4289// depth.4290JVMState* caller_jvms = jvms();42914292// Cf. JVM_GetCallerClass4293// NOTE: Start the loop at depth 1 because the current JVM state does4294// not include the Reflection.getCallerClass() frame.4295for (int n = 1; caller_jvms != NULL; caller_jvms = caller_jvms->caller(), n++) {4296ciMethod* m = caller_jvms->method();4297switch (n) {4298case 0:4299fatal("current JVM state does not include the Reflection.getCallerClass frame");4300break;4301case 1:4302// Frame 0 and 1 must be caller sensitive (see JVM_GetCallerClass).4303if (!m->caller_sensitive()) {4304#ifndef PRODUCT4305if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {4306tty->print_cr(" Bailing out: CallerSensitive annotation expected at frame %d", n);4307}4308#endif4309return false; // bail-out; let JVM_GetCallerClass do the work4310}4311break;4312default:4313if (!m->is_ignored_by_security_stack_walk()) {4314// We have reached the desired frame; return the holder class.4315// Acquire method holder as java.lang.Class and push as constant.4316ciInstanceKlass* caller_klass = caller_jvms->method()->holder();4317ciInstance* caller_mirror = caller_klass->java_mirror();4318set_result(makecon(TypeInstPtr::make(caller_mirror)));43194320#ifndef PRODUCT4321if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {4322tty->print_cr(" Succeeded: caller = %d) %s.%s, JVMS depth = %d", n, caller_klass->name()->as_utf8(), caller_jvms->method()->name()->as_utf8(), jvms()->depth());4323tty->print_cr(" JVM state at this point:");4324for (int i = jvms()->depth(), n = 1; i >= 1; i--, n++) {4325ciMethod* m = jvms()->of_depth(i)->method();4326tty->print_cr(" %d) %s.%s", n, m->holder()->name()->as_utf8(), m->name()->as_utf8());4327}4328}4329#endif4330return true;4331}4332break;4333}4334}43354336#ifndef PRODUCT4337if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {4338tty->print_cr(" Bailing out because caller depth exceeded inlining depth = %d", jvms()->depth());4339tty->print_cr(" JVM state at this point:");4340for (int i = jvms()->depth(), n = 1; i >= 1; i--, n++) {4341ciMethod* m = jvms()->of_depth(i)->method();4342tty->print_cr(" %d) %s.%s", n, m->holder()->name()->as_utf8(), m->name()->as_utf8());4343}4344}4345#endif43464347return false; // bail-out; let JVM_GetCallerClass do the work4348}43494350bool LibraryCallKit::inline_fp_conversions(vmIntrinsics::ID id) {4351Node* arg = argument(0);4352Node* result = NULL;43534354switch (id) {4355case vmIntrinsics::_floatToRawIntBits: result = new (C) MoveF2INode(arg); break;4356case vmIntrinsics::_intBitsToFloat: result = new (C) MoveI2FNode(arg); break;4357case vmIntrinsics::_doubleToRawLongBits: result = new (C) MoveD2LNode(arg); break;4358case vmIntrinsics::_longBitsToDouble: result = new (C) MoveL2DNode(arg); break;43594360case vmIntrinsics::_doubleToLongBits: {4361// two paths (plus control) merge in a wood4362RegionNode *r = new (C) RegionNode(3);4363Node *phi = new (C) PhiNode(r, TypeLong::LONG);43644365Node *cmpisnan = _gvn.transform(new (C) CmpDNode(arg, arg));4366// Build the boolean node4367Node *bolisnan = _gvn.transform(new (C) BoolNode(cmpisnan, BoolTest::ne));43684369// Branch either way.4370// NaN case is less traveled, which makes all the difference.4371IfNode *ifisnan = create_and_xform_if(control(), bolisnan, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);4372Node *opt_isnan = _gvn.transform(ifisnan);4373assert( opt_isnan->is_If(), "Expect an IfNode");4374IfNode *opt_ifisnan = (IfNode*)opt_isnan;4375Node *iftrue = _gvn.transform(new (C) IfTrueNode(opt_ifisnan));43764377set_control(iftrue);43784379static const jlong nan_bits = CONST64(0x7ff8000000000000);4380Node *slow_result = longcon(nan_bits); // return NaN4381phi->init_req(1, _gvn.transform( slow_result ));4382r->init_req(1, iftrue);43834384// Else fall through4385Node *iffalse = _gvn.transform(new (C) IfFalseNode(opt_ifisnan));4386set_control(iffalse);43874388phi->init_req(2, _gvn.transform(new (C) MoveD2LNode(arg)));4389r->init_req(2, iffalse);43904391// Post merge4392set_control(_gvn.transform(r));4393record_for_igvn(r);43944395C->set_has_split_ifs(true); // Has chance for split-if optimization4396result = phi;4397assert(result->bottom_type()->isa_long(), "must be");4398break;4399}44004401case vmIntrinsics::_floatToIntBits: {4402// two paths (plus control) merge in a wood4403RegionNode *r = new (C) RegionNode(3);4404Node *phi = new (C) PhiNode(r, TypeInt::INT);44054406Node *cmpisnan = _gvn.transform(new (C) CmpFNode(arg, arg));4407// Build the boolean node4408Node *bolisnan = _gvn.transform(new (C) BoolNode(cmpisnan, BoolTest::ne));44094410// Branch either way.4411// NaN case is less traveled, which makes all the difference.4412IfNode *ifisnan = create_and_xform_if(control(), bolisnan, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);4413Node *opt_isnan = _gvn.transform(ifisnan);4414assert( opt_isnan->is_If(), "Expect an IfNode");4415IfNode *opt_ifisnan = (IfNode*)opt_isnan;4416Node *iftrue = _gvn.transform(new (C) IfTrueNode(opt_ifisnan));44174418set_control(iftrue);44194420static const jint nan_bits = 0x7fc00000;4421Node *slow_result = makecon(TypeInt::make(nan_bits)); // return NaN4422phi->init_req(1, _gvn.transform( slow_result ));4423r->init_req(1, iftrue);44244425// Else fall through4426Node *iffalse = _gvn.transform(new (C) IfFalseNode(opt_ifisnan));4427set_control(iffalse);44284429phi->init_req(2, _gvn.transform(new (C) MoveF2INode(arg)));4430r->init_req(2, iffalse);44314432// Post merge4433set_control(_gvn.transform(r));4434record_for_igvn(r);44354436C->set_has_split_ifs(true); // Has chance for split-if optimization4437result = phi;4438assert(result->bottom_type()->isa_int(), "must be");4439break;4440}44414442default:4443fatal_unexpected_iid(id);4444break;4445}4446set_result(_gvn.transform(result));4447return true;4448}44494450#ifdef _LP644451#define XTOP ,top() /*additional argument*/4452#else //_LP644453#define XTOP /*no additional argument*/4454#endif //_LP6444554456//----------------------inline_unsafe_copyMemory-------------------------4457// public native void sun.misc.Unsafe.copyMemory(Object srcBase, long srcOffset, Object destBase, long destOffset, long bytes);4458bool LibraryCallKit::inline_unsafe_copyMemory() {4459if (callee()->is_static()) return false; // caller must have the capability!4460null_check_receiver(); // null-check receiver4461if (stopped()) return true;44624463C->set_has_unsafe_access(true); // Mark eventual nmethod as "unsafe".44644465Node* src_ptr = argument(1); // type: oop4466Node* src_off = ConvL2X(argument(2)); // type: long4467Node* dst_ptr = argument(4); // type: oop4468Node* dst_off = ConvL2X(argument(5)); // type: long4469Node* size = ConvL2X(argument(7)); // type: long44704471assert(Unsafe_field_offset_to_byte_offset(11) == 11,4472"fieldOffset must be byte-scaled");44734474Node* src = make_unsafe_address(src_ptr, src_off);4475Node* dst = make_unsafe_address(dst_ptr, dst_off);44764477// Conservatively insert a memory barrier on all memory slices.4478// Do not let writes of the copy source or destination float below the copy.4479insert_mem_bar(Op_MemBarCPUOrder);44804481// Call it. Note that the length argument is not scaled.4482make_runtime_call(RC_LEAF|RC_NO_FP,4483OptoRuntime::fast_arraycopy_Type(),4484StubRoutines::unsafe_arraycopy(),4485"unsafe_arraycopy",4486TypeRawPtr::BOTTOM,4487src, dst, size XTOP);44884489// Do not let reads of the copy destination float above the copy.4490insert_mem_bar(Op_MemBarCPUOrder);44914492return true;4493}44944495//------------------------clone_coping-----------------------------------4496// Helper function for inline_native_clone.4497void LibraryCallKit::copy_to_clone(Node* obj, Node* alloc_obj, Node* obj_size, bool is_array, bool card_mark) {4498assert(obj_size != NULL, "");4499Node* raw_obj = alloc_obj->in(1);4500assert(alloc_obj->is_CheckCastPP() && raw_obj->is_Proj() && raw_obj->in(0)->is_Allocate(), "");45014502AllocateNode* alloc = NULL;4503if (ReduceBulkZeroing) {4504// We will be completely responsible for initializing this object -4505// mark Initialize node as complete.4506alloc = AllocateNode::Ideal_allocation(alloc_obj, &_gvn);4507// The object was just allocated - there should be no any stores!4508guarantee(alloc != NULL && alloc->maybe_set_complete(&_gvn), "");4509// Mark as complete_with_arraycopy so that on AllocateNode4510// expansion, we know this AllocateNode is initialized by an array4511// copy and a StoreStore barrier exists after the array copy.4512alloc->initialization()->set_complete_with_arraycopy();4513}45144515// Copy the fastest available way.4516// TODO: generate fields copies for small objects instead.4517Node* src = obj;4518Node* dest = alloc_obj;4519Node* size = _gvn.transform(obj_size);45204521// Exclude the header but include array length to copy by 8 bytes words.4522// Can't use base_offset_in_bytes(bt) since basic type is unknown.4523int base_off = is_array ? arrayOopDesc::length_offset_in_bytes() :4524instanceOopDesc::base_offset_in_bytes();4525// base_off:4526// 8 - 32-bit VM4527// 12 - 64-bit VM, compressed klass4528// 16 - 64-bit VM, normal klass4529if (base_off % BytesPerLong != 0) {4530assert(UseCompressedClassPointers, "");4531if (is_array) {4532// Exclude length to copy by 8 bytes words.4533base_off += sizeof(int);4534} else {4535// Include klass to copy by 8 bytes words.4536base_off = instanceOopDesc::klass_offset_in_bytes();4537}4538assert(base_off % BytesPerLong == 0, "expect 8 bytes alignment");4539}4540src = basic_plus_adr(src, base_off);4541dest = basic_plus_adr(dest, base_off);45424543// Compute the length also, if needed:4544Node* countx = size;4545countx = _gvn.transform(new (C) SubXNode(countx, MakeConX(base_off)));4546countx = _gvn.transform(new (C) URShiftXNode(countx, intcon(LogBytesPerLong) ));45474548const TypePtr* raw_adr_type = TypeRawPtr::BOTTOM;4549bool disjoint_bases = true;4550generate_unchecked_arraycopy(raw_adr_type, T_LONG, disjoint_bases,4551src, NULL, dest, NULL, countx,4552/*dest_uninitialized*/true);45534554// If necessary, emit some card marks afterwards. (Non-arrays only.)4555if (card_mark) {4556assert(!is_array, "");4557// Put in store barrier for any and all oops we are sticking4558// into this object. (We could avoid this if we could prove4559// that the object type contains no oop fields at all.)4560Node* no_particular_value = NULL;4561Node* no_particular_field = NULL;4562int raw_adr_idx = Compile::AliasIdxRaw;4563post_barrier(control(),4564memory(raw_adr_type),4565alloc_obj,4566no_particular_field,4567raw_adr_idx,4568no_particular_value,4569T_OBJECT,4570false);4571}45724573// Do not let reads from the cloned object float above the arraycopy.4574if (alloc != NULL) {4575// Do not let stores that initialize this object be reordered with4576// a subsequent store that would make this object accessible by4577// other threads.4578// Record what AllocateNode this StoreStore protects so that4579// escape analysis can go from the MemBarStoreStoreNode to the4580// AllocateNode and eliminate the MemBarStoreStoreNode if possible4581// based on the escape status of the AllocateNode.4582insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out(AllocateNode::RawAddress));4583} else {4584insert_mem_bar(Op_MemBarCPUOrder);4585}4586}45874588//------------------------inline_native_clone----------------------------4589// protected native Object java.lang.Object.clone();4590//4591// Here are the simple edge cases:4592// null receiver => normal trap4593// virtual and clone was overridden => slow path to out-of-line clone4594// not cloneable or finalizer => slow path to out-of-line Object.clone4595//4596// The general case has two steps, allocation and copying.4597// Allocation has two cases, and uses GraphKit::new_instance or new_array.4598//4599// Copying also has two cases, oop arrays and everything else.4600// Oop arrays use arrayof_oop_arraycopy (same as System.arraycopy).4601// Everything else uses the tight inline loop supplied by CopyArrayNode.4602//4603// These steps fold up nicely if and when the cloned object's klass4604// can be sharply typed as an object array, a type array, or an instance.4605//4606bool LibraryCallKit::inline_native_clone(bool is_virtual) {4607PhiNode* result_val;46084609// Set the reexecute bit for the interpreter to reexecute4610// the bytecode that invokes Object.clone if deoptimization happens.4611{ PreserveReexecuteState preexecs(this);4612jvms()->set_should_reexecute(true);46134614Node* obj = null_check_receiver();4615if (stopped()) return true;46164617Node* obj_klass = load_object_klass(obj);4618const TypeKlassPtr* tklass = _gvn.type(obj_klass)->isa_klassptr();4619const TypeOopPtr* toop = ((tklass != NULL)4620? tklass->as_instance_type()4621: TypeInstPtr::NOTNULL);46224623// Conservatively insert a memory barrier on all memory slices.4624// Do not let writes into the original float below the clone.4625insert_mem_bar(Op_MemBarCPUOrder);46264627// paths into result_reg:4628enum {4629_slow_path = 1, // out-of-line call to clone method (virtual or not)4630_objArray_path, // plain array allocation, plus arrayof_oop_arraycopy4631_array_path, // plain array allocation, plus arrayof_long_arraycopy4632_instance_path, // plain instance allocation, plus arrayof_long_arraycopy4633PATH_LIMIT4634};4635RegionNode* result_reg = new(C) RegionNode(PATH_LIMIT);4636result_val = new(C) PhiNode(result_reg,4637TypeInstPtr::NOTNULL);4638PhiNode* result_i_o = new(C) PhiNode(result_reg, Type::ABIO);4639PhiNode* result_mem = new(C) PhiNode(result_reg, Type::MEMORY,4640TypePtr::BOTTOM);4641record_for_igvn(result_reg);46424643const TypePtr* raw_adr_type = TypeRawPtr::BOTTOM;4644int raw_adr_idx = Compile::AliasIdxRaw;46454646Node* array_ctl = generate_array_guard(obj_klass, (RegionNode*)NULL);4647if (array_ctl != NULL) {4648// It's an array.4649PreserveJVMState pjvms(this);4650set_control(array_ctl);4651Node* obj_length = load_array_length(obj);4652Node* obj_size = NULL;4653Node* alloc_obj = new_array(obj_klass, obj_length, 0, &obj_size); // no arguments to push46544655if (!use_ReduceInitialCardMarks()) {4656// If it is an oop array, it requires very special treatment,4657// because card marking is required on each card of the array.4658Node* is_obja = generate_objArray_guard(obj_klass, (RegionNode*)NULL);4659if (is_obja != NULL) {4660PreserveJVMState pjvms2(this);4661set_control(is_obja);4662// Generate a direct call to the right arraycopy function(s).4663bool disjoint_bases = true;4664bool length_never_negative = true;4665generate_arraycopy(TypeAryPtr::OOPS, T_OBJECT,4666obj, intcon(0), alloc_obj, intcon(0),4667obj_length,4668disjoint_bases, length_never_negative);4669result_reg->init_req(_objArray_path, control());4670result_val->init_req(_objArray_path, alloc_obj);4671result_i_o ->set_req(_objArray_path, i_o());4672result_mem ->set_req(_objArray_path, reset_memory());4673}4674}4675// Otherwise, there are no card marks to worry about.4676// (We can dispense with card marks if we know the allocation4677// comes out of eden (TLAB)... In fact, ReduceInitialCardMarks4678// causes the non-eden paths to take compensating steps to4679// simulate a fresh allocation, so that no further4680// card marks are required in compiled code to initialize4681// the object.)46824683if (!stopped()) {4684copy_to_clone(obj, alloc_obj, obj_size, true, false);46854686// Present the results of the copy.4687result_reg->init_req(_array_path, control());4688result_val->init_req(_array_path, alloc_obj);4689result_i_o ->set_req(_array_path, i_o());4690result_mem ->set_req(_array_path, reset_memory());4691}4692}46934694// We only go to the instance fast case code if we pass a number of guards.4695// The paths which do not pass are accumulated in the slow_region.4696RegionNode* slow_region = new (C) RegionNode(1);4697record_for_igvn(slow_region);4698if (!stopped()) {4699// It's an instance (we did array above). Make the slow-path tests.4700// If this is a virtual call, we generate a funny guard. We grab4701// the vtable entry corresponding to clone() from the target object.4702// If the target method which we are calling happens to be the4703// Object clone() method, we pass the guard. We do not need this4704// guard for non-virtual calls; the caller is known to be the native4705// Object clone().4706if (is_virtual) {4707generate_virtual_guard(obj_klass, slow_region);4708}47094710// The object must be cloneable and must not have a finalizer.4711// Both of these conditions may be checked in a single test.4712// We could optimize the cloneable test further, but we don't care.4713generate_access_flags_guard(obj_klass,4714// Test both conditions:4715JVM_ACC_IS_CLONEABLE | JVM_ACC_HAS_FINALIZER,4716// Must be cloneable but not finalizer:4717JVM_ACC_IS_CLONEABLE,4718slow_region);4719}47204721if (!stopped()) {4722// It's an instance, and it passed the slow-path tests.4723PreserveJVMState pjvms(this);4724Node* obj_size = NULL;4725// Need to deoptimize on exception from allocation since Object.clone intrinsic4726// is reexecuted if deoptimization occurs and there could be problems when merging4727// exception state between multiple Object.clone versions (reexecute=true vs reexecute=false).4728Node* alloc_obj = new_instance(obj_klass, NULL, &obj_size, /*deoptimize_on_exception=*/true);47294730copy_to_clone(obj, alloc_obj, obj_size, false, !use_ReduceInitialCardMarks());47314732// Present the results of the slow call.4733result_reg->init_req(_instance_path, control());4734result_val->init_req(_instance_path, alloc_obj);4735result_i_o ->set_req(_instance_path, i_o());4736result_mem ->set_req(_instance_path, reset_memory());4737}47384739// Generate code for the slow case. We make a call to clone().4740set_control(_gvn.transform(slow_region));4741if (!stopped()) {4742PreserveJVMState pjvms(this);4743CallJavaNode* slow_call = generate_method_call(vmIntrinsics::_clone, is_virtual);4744Node* slow_result = set_results_for_java_call(slow_call);4745// this->control() comes from set_results_for_java_call4746result_reg->init_req(_slow_path, control());4747result_val->init_req(_slow_path, slow_result);4748result_i_o ->set_req(_slow_path, i_o());4749result_mem ->set_req(_slow_path, reset_memory());4750}47514752// Return the combined state.4753set_control( _gvn.transform(result_reg));4754set_i_o( _gvn.transform(result_i_o));4755set_all_memory( _gvn.transform(result_mem));4756} // original reexecute is set back here47574758set_result(_gvn.transform(result_val));4759return true;4760}47614762//------------------------------basictype2arraycopy----------------------------4763address LibraryCallKit::basictype2arraycopy(BasicType t,4764Node* src_offset,4765Node* dest_offset,4766bool disjoint_bases,4767const char* &name,4768bool dest_uninitialized) {4769const TypeInt* src_offset_inttype = gvn().find_int_type(src_offset);;4770const TypeInt* dest_offset_inttype = gvn().find_int_type(dest_offset);;47714772bool aligned = false;4773bool disjoint = disjoint_bases;47744775// if the offsets are the same, we can treat the memory regions as4776// disjoint, because either the memory regions are in different arrays,4777// or they are identical (which we can treat as disjoint.) We can also4778// treat a copy with a destination index less that the source index4779// as disjoint since a low->high copy will work correctly in this case.4780if (src_offset_inttype != NULL && src_offset_inttype->is_con() &&4781dest_offset_inttype != NULL && dest_offset_inttype->is_con()) {4782// both indices are constants4783int s_offs = src_offset_inttype->get_con();4784int d_offs = dest_offset_inttype->get_con();4785int element_size = type2aelembytes(t);4786aligned = ((arrayOopDesc::base_offset_in_bytes(t) + s_offs * element_size) % HeapWordSize == 0) &&4787((arrayOopDesc::base_offset_in_bytes(t) + d_offs * element_size) % HeapWordSize == 0);4788if (s_offs >= d_offs) disjoint = true;4789} else if (src_offset == dest_offset && src_offset != NULL) {4790// This can occur if the offsets are identical non-constants.4791disjoint = true;4792}47934794return StubRoutines::select_arraycopy_function(t, aligned, disjoint, name, dest_uninitialized);4795}479647974798//------------------------------inline_arraycopy-----------------------4799// public static native void java.lang.System.arraycopy(Object src, int srcPos,4800// Object dest, int destPos,4801// int length);4802bool LibraryCallKit::inline_arraycopy() {4803// Get the arguments.4804Node* src = argument(0); // type: oop4805Node* src_offset = argument(1); // type: int4806Node* dest = argument(2); // type: oop4807Node* dest_offset = argument(3); // type: int4808Node* length = argument(4); // type: int48094810// Compile time checks. If any of these checks cannot be verified at compile time,4811// we do not make a fast path for this call. Instead, we let the call remain as it4812// is. The checks we choose to mandate at compile time are:4813//4814// (1) src and dest are arrays.4815const Type* src_type = src->Value(&_gvn);4816const Type* dest_type = dest->Value(&_gvn);4817const TypeAryPtr* top_src = src_type->isa_aryptr();4818const TypeAryPtr* top_dest = dest_type->isa_aryptr();48194820// Do we have the type of src?4821bool has_src = (top_src != NULL && top_src->klass() != NULL);4822// Do we have the type of dest?4823bool has_dest = (top_dest != NULL && top_dest->klass() != NULL);4824// Is the type for src from speculation?4825bool src_spec = false;4826// Is the type for dest from speculation?4827bool dest_spec = false;48284829if (!has_src || !has_dest) {4830// We don't have sufficient type information, let's see if4831// speculative types can help. We need to have types for both src4832// and dest so that it pays off.48334834// Do we already have or could we have type information for src4835bool could_have_src = has_src;4836// Do we already have or could we have type information for dest4837bool could_have_dest = has_dest;48384839ciKlass* src_k = NULL;4840if (!has_src) {4841src_k = src_type->speculative_type();4842if (src_k != NULL && src_k->is_array_klass()) {4843could_have_src = true;4844}4845}48464847ciKlass* dest_k = NULL;4848if (!has_dest) {4849dest_k = dest_type->speculative_type();4850if (dest_k != NULL && dest_k->is_array_klass()) {4851could_have_dest = true;4852}4853}48544855if (could_have_src && could_have_dest) {4856// This is going to pay off so emit the required guards4857if (!has_src) {4858src = maybe_cast_profiled_obj(src, src_k);4859src_type = _gvn.type(src);4860top_src = src_type->isa_aryptr();4861has_src = (top_src != NULL && top_src->klass() != NULL);4862src_spec = true;4863}4864if (!has_dest) {4865dest = maybe_cast_profiled_obj(dest, dest_k);4866dest_type = _gvn.type(dest);4867top_dest = dest_type->isa_aryptr();4868has_dest = (top_dest != NULL && top_dest->klass() != NULL);4869dest_spec = true;4870}4871}4872}48734874if (!has_src || !has_dest) {4875// Conservatively insert a memory barrier on all memory slices.4876// Do not let writes into the source float below the arraycopy.4877insert_mem_bar(Op_MemBarCPUOrder);48784879// Call StubRoutines::generic_arraycopy stub.4880generate_arraycopy(TypeRawPtr::BOTTOM, T_CONFLICT,4881src, src_offset, dest, dest_offset, length);48824883// Do not let reads from the destination float above the arraycopy.4884// Since we cannot type the arrays, we don't know which slices4885// might be affected. We could restrict this barrier only to those4886// memory slices which pertain to array elements--but don't bother.4887if (!InsertMemBarAfterArraycopy)4888// (If InsertMemBarAfterArraycopy, there is already one in place.)4889insert_mem_bar(Op_MemBarCPUOrder);4890return true;4891}48924893// (2) src and dest arrays must have elements of the same BasicType4894// Figure out the size and type of the elements we will be copying.4895BasicType src_elem = top_src->klass()->as_array_klass()->element_type()->basic_type();4896BasicType dest_elem = top_dest->klass()->as_array_klass()->element_type()->basic_type();4897if (src_elem == T_ARRAY) src_elem = T_OBJECT;4898if (dest_elem == T_ARRAY) dest_elem = T_OBJECT;48994900if (src_elem != dest_elem || dest_elem == T_VOID) {4901// The component types are not the same or are not recognized. Punt.4902// (But, avoid the native method wrapper to JVM_ArrayCopy.)4903generate_slow_arraycopy(TypePtr::BOTTOM,4904src, src_offset, dest, dest_offset, length,4905/*dest_uninitialized*/false);4906return true;4907}49084909if (src_elem == T_OBJECT) {4910// If both arrays are object arrays then having the exact types4911// for both will remove the need for a subtype check at runtime4912// before the call and may make it possible to pick a faster copy4913// routine (without a subtype check on every element)4914// Do we have the exact type of src?4915bool could_have_src = src_spec;4916// Do we have the exact type of dest?4917bool could_have_dest = dest_spec;4918ciKlass* src_k = top_src->klass();4919ciKlass* dest_k = top_dest->klass();4920if (!src_spec) {4921src_k = src_type->speculative_type();4922if (src_k != NULL && src_k->is_array_klass()) {4923could_have_src = true;4924}4925}4926if (!dest_spec) {4927dest_k = dest_type->speculative_type();4928if (dest_k != NULL && dest_k->is_array_klass()) {4929could_have_dest = true;4930}4931}4932if (could_have_src && could_have_dest) {4933// If we can have both exact types, emit the missing guards4934if (could_have_src && !src_spec) {4935src = maybe_cast_profiled_obj(src, src_k);4936}4937if (could_have_dest && !dest_spec) {4938dest = maybe_cast_profiled_obj(dest, dest_k);4939}4940}4941}49424943//---------------------------------------------------------------------------4944// We will make a fast path for this call to arraycopy.49454946// We have the following tests left to perform:4947//4948// (3) src and dest must not be null.4949// (4) src_offset must not be negative.4950// (5) dest_offset must not be negative.4951// (6) length must not be negative.4952// (7) src_offset + length must not exceed length of src.4953// (8) dest_offset + length must not exceed length of dest.4954// (9) each element of an oop array must be assignable49554956RegionNode* slow_region = new (C) RegionNode(1);4957record_for_igvn(slow_region);49584959// (3) operands must not be null4960// We currently perform our null checks with the null_check routine.4961// This means that the null exceptions will be reported in the caller4962// rather than (correctly) reported inside of the native arraycopy call.4963// This should be corrected, given time. We do our null check with the4964// stack pointer restored.4965src = null_check(src, T_ARRAY);4966dest = null_check(dest, T_ARRAY);49674968// (4) src_offset must not be negative.4969generate_negative_guard(src_offset, slow_region);49704971// (5) dest_offset must not be negative.4972generate_negative_guard(dest_offset, slow_region);49734974// (6) length must not be negative (moved to generate_arraycopy()).4975// generate_negative_guard(length, slow_region);49764977// (7) src_offset + length must not exceed length of src.4978generate_limit_guard(src_offset, length,4979load_array_length(src),4980slow_region);49814982// (8) dest_offset + length must not exceed length of dest.4983generate_limit_guard(dest_offset, length,4984load_array_length(dest),4985slow_region);49864987// (9) each element of an oop array must be assignable4988// The generate_arraycopy subroutine checks this.49894990// This is where the memory effects are placed:4991const TypePtr* adr_type = TypeAryPtr::get_array_body_type(dest_elem);4992generate_arraycopy(adr_type, dest_elem,4993src, src_offset, dest, dest_offset, length,4994false, false, slow_region);49954996return true;4997}49984999//-----------------------------generate_arraycopy----------------------5000// Generate an optimized call to arraycopy.5001// Caller must guard against non-arrays.5002// Caller must determine a common array basic-type for both arrays.5003// Caller must validate offsets against array bounds.5004// The slow_region has already collected guard failure paths5005// (such as out of bounds length or non-conformable array types).5006// The generated code has this shape, in general:5007//5008// if (length == 0) return // via zero_path5009// slowval = -15010// if (types unknown) {5011// slowval = call generic copy loop5012// if (slowval == 0) return // via checked_path5013// } else if (indexes in bounds) {5014// if ((is object array) && !(array type check)) {5015// slowval = call checked copy loop5016// if (slowval == 0) return // via checked_path5017// } else {5018// call bulk copy loop5019// return // via fast_path5020// }5021// }5022// // adjust params for remaining work:5023// if (slowval != -1) {5024// n = -1^slowval; src_offset += n; dest_offset += n; length -= n5025// }5026// slow_region:5027// call slow arraycopy(src, src_offset, dest, dest_offset, length)5028// return // via slow_call_path5029//5030// This routine is used from several intrinsics: System.arraycopy,5031// Object.clone (the array subcase), and Arrays.copyOf[Range].5032//5033void5034LibraryCallKit::generate_arraycopy(const TypePtr* adr_type,5035BasicType basic_elem_type,5036Node* src, Node* src_offset,5037Node* dest, Node* dest_offset,5038Node* copy_length,5039bool disjoint_bases,5040bool length_never_negative,5041RegionNode* slow_region) {50425043if (slow_region == NULL) {5044slow_region = new(C) RegionNode(1);5045record_for_igvn(slow_region);5046}50475048Node* original_dest = dest;5049AllocateArrayNode* alloc = NULL; // used for zeroing, if needed5050bool dest_uninitialized = false;50515052// See if this is the initialization of a newly-allocated array.5053// If so, we will take responsibility here for initializing it to zero.5054// (Note: Because tightly_coupled_allocation performs checks on the5055// out-edges of the dest, we need to avoid making derived pointers5056// from it until we have checked its uses.)5057if (ReduceBulkZeroing5058&& !ZeroTLAB // pointless if already zeroed5059&& basic_elem_type != T_CONFLICT // avoid corner case5060&& !src->eqv_uncast(dest)5061&& ((alloc = tightly_coupled_allocation(dest, slow_region))5062!= NULL)5063&& _gvn.find_int_con(alloc->in(AllocateNode::ALength), 1) > 05064&& alloc->maybe_set_complete(&_gvn)) {5065// "You break it, you buy it."5066InitializeNode* init = alloc->initialization();5067assert(init->is_complete(), "we just did this");5068init->set_complete_with_arraycopy();5069assert(dest->is_CheckCastPP(), "sanity");5070assert(dest->in(0)->in(0) == init, "dest pinned");5071adr_type = TypeRawPtr::BOTTOM; // all initializations are into raw memory5072// From this point on, every exit path is responsible for5073// initializing any non-copied parts of the object to zero.5074// Also, if this flag is set we make sure that arraycopy interacts properly5075// with G1, eliding pre-barriers. See CR 6627983.5076dest_uninitialized = true;5077} else {5078// No zeroing elimination here.5079alloc = NULL;5080//original_dest = dest;5081//dest_uninitialized = false;5082}50835084// Results are placed here:5085enum { fast_path = 1, // normal void-returning assembly stub5086checked_path = 2, // special assembly stub with cleanup5087slow_call_path = 3, // something went wrong; call the VM5088zero_path = 4, // bypass when length of copy is zero5089bcopy_path = 5, // copy primitive array by 64-bit blocks5090PATH_LIMIT = 65091};5092RegionNode* result_region = new(C) RegionNode(PATH_LIMIT);5093PhiNode* result_i_o = new(C) PhiNode(result_region, Type::ABIO);5094PhiNode* result_memory = new(C) PhiNode(result_region, Type::MEMORY, adr_type);5095record_for_igvn(result_region);5096_gvn.set_type_bottom(result_i_o);5097_gvn.set_type_bottom(result_memory);5098assert(adr_type != TypePtr::BOTTOM, "must be RawMem or a T[] slice");50995100// The slow_control path:5101Node* slow_control;5102Node* slow_i_o = i_o();5103Node* slow_mem = memory(adr_type);5104debug_only(slow_control = (Node*) badAddress);51055106// Checked control path:5107Node* checked_control = top();5108Node* checked_mem = NULL;5109Node* checked_i_o = NULL;5110Node* checked_value = NULL;51115112if (basic_elem_type == T_CONFLICT) {5113assert(!dest_uninitialized, "");5114Node* cv = generate_generic_arraycopy(adr_type,5115src, src_offset, dest, dest_offset,5116copy_length, dest_uninitialized);5117if (cv == NULL) cv = intcon(-1); // failure (no stub available)5118checked_control = control();5119checked_i_o = i_o();5120checked_mem = memory(adr_type);5121checked_value = cv;5122set_control(top()); // no fast path5123}51245125Node* not_pos = generate_nonpositive_guard(copy_length, length_never_negative);5126if (not_pos != NULL) {5127PreserveJVMState pjvms(this);5128set_control(not_pos);51295130// (6) length must not be negative.5131if (!length_never_negative) {5132generate_negative_guard(copy_length, slow_region);5133}51345135// copy_length is 0.5136if (!stopped() && dest_uninitialized) {5137Node* dest_length = alloc->in(AllocateNode::ALength);5138if (copy_length->eqv_uncast(dest_length)5139|| _gvn.find_int_con(dest_length, 1) <= 0) {5140// There is no zeroing to do. No need for a secondary raw memory barrier.5141} else {5142// Clear the whole thing since there are no source elements to copy.5143generate_clear_array(adr_type, dest, basic_elem_type,5144intcon(0), NULL,5145alloc->in(AllocateNode::AllocSize));5146// Use a secondary InitializeNode as raw memory barrier.5147// Currently it is needed only on this path since other5148// paths have stub or runtime calls as raw memory barriers.5149InitializeNode* init = insert_mem_bar_volatile(Op_Initialize,5150Compile::AliasIdxRaw,5151top())->as_Initialize();5152init->set_complete(&_gvn); // (there is no corresponding AllocateNode)5153}5154}51555156// Present the results of the fast call.5157result_region->init_req(zero_path, control());5158result_i_o ->init_req(zero_path, i_o());5159result_memory->init_req(zero_path, memory(adr_type));5160}51615162if (!stopped() && dest_uninitialized) {5163// We have to initialize the *uncopied* part of the array to zero.5164// The copy destination is the slice dest[off..off+len]. The other slices5165// are dest_head = dest[0..off] and dest_tail = dest[off+len..dest.length].5166Node* dest_size = alloc->in(AllocateNode::AllocSize);5167Node* dest_length = alloc->in(AllocateNode::ALength);5168Node* dest_tail = _gvn.transform(new(C) AddINode(dest_offset,5169copy_length));51705171// If there is a head section that needs zeroing, do it now.5172if (find_int_con(dest_offset, -1) != 0) {5173generate_clear_array(adr_type, dest, basic_elem_type,5174intcon(0), dest_offset,5175NULL);5176}51775178// Next, perform a dynamic check on the tail length.5179// It is often zero, and we can win big if we prove this.5180// There are two wins: Avoid generating the ClearArray5181// with its attendant messy index arithmetic, and upgrade5182// the copy to a more hardware-friendly word size of 64 bits.5183Node* tail_ctl = NULL;5184if (!stopped() && !dest_tail->eqv_uncast(dest_length)) {5185Node* cmp_lt = _gvn.transform(new(C) CmpINode(dest_tail, dest_length));5186Node* bol_lt = _gvn.transform(new(C) BoolNode(cmp_lt, BoolTest::lt));5187tail_ctl = generate_slow_guard(bol_lt, NULL);5188assert(tail_ctl != NULL || !stopped(), "must be an outcome");5189}51905191// At this point, let's assume there is no tail.5192if (!stopped() && alloc != NULL && basic_elem_type != T_OBJECT) {5193// There is no tail. Try an upgrade to a 64-bit copy.5194bool didit = false;5195{ PreserveJVMState pjvms(this);5196didit = generate_block_arraycopy(adr_type, basic_elem_type, alloc,5197src, src_offset, dest, dest_offset,5198dest_size, dest_uninitialized);5199if (didit) {5200// Present the results of the block-copying fast call.5201result_region->init_req(bcopy_path, control());5202result_i_o ->init_req(bcopy_path, i_o());5203result_memory->init_req(bcopy_path, memory(adr_type));5204}5205}5206if (didit)5207set_control(top()); // no regular fast path5208}52095210// Clear the tail, if any.5211if (tail_ctl != NULL) {5212Node* notail_ctl = stopped() ? NULL : control();5213set_control(tail_ctl);5214if (notail_ctl == NULL) {5215generate_clear_array(adr_type, dest, basic_elem_type,5216dest_tail, NULL,5217dest_size);5218} else {5219// Make a local merge.5220Node* done_ctl = new(C) RegionNode(3);5221Node* done_mem = new(C) PhiNode(done_ctl, Type::MEMORY, adr_type);5222done_ctl->init_req(1, notail_ctl);5223done_mem->init_req(1, memory(adr_type));5224generate_clear_array(adr_type, dest, basic_elem_type,5225dest_tail, NULL,5226dest_size);5227done_ctl->init_req(2, control());5228done_mem->init_req(2, memory(adr_type));5229set_control( _gvn.transform(done_ctl));5230set_memory( _gvn.transform(done_mem), adr_type );5231}5232}5233}52345235BasicType copy_type = basic_elem_type;5236assert(basic_elem_type != T_ARRAY, "caller must fix this");5237if (!stopped() && copy_type == T_OBJECT) {5238// If src and dest have compatible element types, we can copy bits.5239// Types S[] and D[] are compatible if D is a supertype of S.5240//5241// If they are not, we will use checked_oop_disjoint_arraycopy,5242// which performs a fast optimistic per-oop check, and backs off5243// further to JVM_ArrayCopy on the first per-oop check that fails.5244// (Actually, we don't move raw bits only; the GC requires card marks.)52455246// Get the Klass* for both src and dest5247Node* src_klass = load_object_klass(src);5248Node* dest_klass = load_object_klass(dest);52495250// Generate the subtype check.5251// This might fold up statically, or then again it might not.5252//5253// Non-static example: Copying List<String>.elements to a new String[].5254// The backing store for a List<String> is always an Object[],5255// but its elements are always type String, if the generic types5256// are correct at the source level.5257//5258// Test S[] against D[], not S against D, because (probably)5259// the secondary supertype cache is less busy for S[] than S.5260// This usually only matters when D is an interface.5261Node* not_subtype_ctrl = gen_subtype_check(src_klass, dest_klass);5262// Plug failing path into checked_oop_disjoint_arraycopy5263if (not_subtype_ctrl != top()) {5264PreserveJVMState pjvms(this);5265set_control(not_subtype_ctrl);5266// (At this point we can assume disjoint_bases, since types differ.)5267int ek_offset = in_bytes(ObjArrayKlass::element_klass_offset());5268Node* p1 = basic_plus_adr(dest_klass, ek_offset);5269Node* n1 = LoadKlassNode::make(_gvn, NULL, immutable_memory(), p1, TypeRawPtr::BOTTOM);5270Node* dest_elem_klass = _gvn.transform(n1);5271Node* cv = generate_checkcast_arraycopy(adr_type,5272dest_elem_klass,5273src, src_offset, dest, dest_offset,5274ConvI2X(copy_length), dest_uninitialized);5275if (cv == NULL) cv = intcon(-1); // failure (no stub available)5276checked_control = control();5277checked_i_o = i_o();5278checked_mem = memory(adr_type);5279checked_value = cv;5280}5281// At this point we know we do not need type checks on oop stores.52825283// Let's see if we need card marks:5284if (alloc != NULL && use_ReduceInitialCardMarks()) {5285// If we do not need card marks, copy using the jint or jlong stub.5286copy_type = LP64_ONLY(UseCompressedOops ? T_INT : T_LONG) NOT_LP64(T_INT);5287assert(type2aelembytes(basic_elem_type) == type2aelembytes(copy_type),5288"sizes agree");5289}5290}52915292if (!stopped()) {5293// Generate the fast path, if possible.5294PreserveJVMState pjvms(this);5295generate_unchecked_arraycopy(adr_type, copy_type, disjoint_bases,5296src, src_offset, dest, dest_offset,5297ConvI2X(copy_length), dest_uninitialized);52985299// Present the results of the fast call.5300result_region->init_req(fast_path, control());5301result_i_o ->init_req(fast_path, i_o());5302result_memory->init_req(fast_path, memory(adr_type));5303}53045305// Here are all the slow paths up to this point, in one bundle:5306slow_control = top();5307if (slow_region != NULL)5308slow_control = _gvn.transform(slow_region);5309DEBUG_ONLY(slow_region = (RegionNode*)badAddress);53105311set_control(checked_control);5312if (!stopped()) {5313// Clean up after the checked call.5314// The returned value is either 0 or -1^K,5315// where K = number of partially transferred array elements.5316Node* cmp = _gvn.transform(new(C) CmpINode(checked_value, intcon(0)));5317Node* bol = _gvn.transform(new(C) BoolNode(cmp, BoolTest::eq));5318IfNode* iff = create_and_map_if(control(), bol, PROB_MAX, COUNT_UNKNOWN);53195320// If it is 0, we are done, so transfer to the end.5321Node* checks_done = _gvn.transform(new(C) IfTrueNode(iff));5322result_region->init_req(checked_path, checks_done);5323result_i_o ->init_req(checked_path, checked_i_o);5324result_memory->init_req(checked_path, checked_mem);53255326// If it is not zero, merge into the slow call.5327set_control( _gvn.transform(new(C) IfFalseNode(iff) ));5328RegionNode* slow_reg2 = new(C) RegionNode(3);5329PhiNode* slow_i_o2 = new(C) PhiNode(slow_reg2, Type::ABIO);5330PhiNode* slow_mem2 = new(C) PhiNode(slow_reg2, Type::MEMORY, adr_type);5331record_for_igvn(slow_reg2);5332slow_reg2 ->init_req(1, slow_control);5333slow_i_o2 ->init_req(1, slow_i_o);5334slow_mem2 ->init_req(1, slow_mem);5335slow_reg2 ->init_req(2, control());5336slow_i_o2 ->init_req(2, checked_i_o);5337slow_mem2 ->init_req(2, checked_mem);53385339slow_control = _gvn.transform(slow_reg2);5340slow_i_o = _gvn.transform(slow_i_o2);5341slow_mem = _gvn.transform(slow_mem2);53425343if (alloc != NULL) {5344// We'll restart from the very beginning, after zeroing the whole thing.5345// This can cause double writes, but that's OK since dest is brand new.5346// So we ignore the low 31 bits of the value returned from the stub.5347} else {5348// We must continue the copy exactly where it failed, or else5349// another thread might see the wrong number of writes to dest.5350Node* checked_offset = _gvn.transform(new(C) XorINode(checked_value, intcon(-1)));5351Node* slow_offset = new(C) PhiNode(slow_reg2, TypeInt::INT);5352slow_offset->init_req(1, intcon(0));5353slow_offset->init_req(2, checked_offset);5354slow_offset = _gvn.transform(slow_offset);53555356// Adjust the arguments by the conditionally incoming offset.5357Node* src_off_plus = _gvn.transform(new(C) AddINode(src_offset, slow_offset));5358Node* dest_off_plus = _gvn.transform(new(C) AddINode(dest_offset, slow_offset));5359Node* length_minus = _gvn.transform(new(C) SubINode(copy_length, slow_offset));53605361// Tweak the node variables to adjust the code produced below:5362src_offset = src_off_plus;5363dest_offset = dest_off_plus;5364copy_length = length_minus;5365}5366}53675368set_control(slow_control);5369if (!stopped()) {5370// Generate the slow path, if needed.5371PreserveJVMState pjvms(this); // replace_in_map may trash the map53725373set_memory(slow_mem, adr_type);5374set_i_o(slow_i_o);53755376if (dest_uninitialized) {5377generate_clear_array(adr_type, dest, basic_elem_type,5378intcon(0), NULL,5379alloc->in(AllocateNode::AllocSize));5380}53815382generate_slow_arraycopy(adr_type,5383src, src_offset, dest, dest_offset,5384copy_length, /*dest_uninitialized*/false);53855386result_region->init_req(slow_call_path, control());5387result_i_o ->init_req(slow_call_path, i_o());5388result_memory->init_req(slow_call_path, memory(adr_type));5389}53905391// Remove unused edges.5392for (uint i = 1; i < result_region->req(); i++) {5393if (result_region->in(i) == NULL)5394result_region->init_req(i, top());5395}53965397// Finished; return the combined state.5398set_control( _gvn.transform(result_region));5399set_i_o( _gvn.transform(result_i_o) );5400set_memory( _gvn.transform(result_memory), adr_type );54015402// The memory edges above are precise in order to model effects around5403// array copies accurately to allow value numbering of field loads around5404// arraycopy. Such field loads, both before and after, are common in Java5405// collections and similar classes involving header/array data structures.5406//5407// But with low number of register or when some registers are used or killed5408// by arraycopy calls it causes registers spilling on stack. See 6544710.5409// The next memory barrier is added to avoid it. If the arraycopy can be5410// optimized away (which it can, sometimes) then we can manually remove5411// the membar also.5412//5413// Do not let reads from the cloned object float above the arraycopy.5414if (alloc != NULL) {5415// Do not let stores that initialize this object be reordered with5416// a subsequent store that would make this object accessible by5417// other threads.5418// Record what AllocateNode this StoreStore protects so that5419// escape analysis can go from the MemBarStoreStoreNode to the5420// AllocateNode and eliminate the MemBarStoreStoreNode if possible5421// based on the escape status of the AllocateNode.5422insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out(AllocateNode::RawAddress));5423} else if (InsertMemBarAfterArraycopy)5424insert_mem_bar(Op_MemBarCPUOrder);5425}542654275428// Helper function which determines if an arraycopy immediately follows5429// an allocation, with no intervening tests or other escapes for the object.5430AllocateArrayNode*5431LibraryCallKit::tightly_coupled_allocation(Node* ptr,5432RegionNode* slow_region) {5433if (stopped()) return NULL; // no fast path5434if (C->AliasLevel() == 0) return NULL; // no MergeMems around54355436AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(ptr, &_gvn);5437if (alloc == NULL) return NULL;54385439Node* rawmem = memory(Compile::AliasIdxRaw);5440// Is the allocation's memory state untouched?5441if (!(rawmem->is_Proj() && rawmem->in(0)->is_Initialize())) {5442// Bail out if there have been raw-memory effects since the allocation.5443// (Example: There might have been a call or safepoint.)5444return NULL;5445}5446rawmem = rawmem->in(0)->as_Initialize()->memory(Compile::AliasIdxRaw);5447if (!(rawmem->is_Proj() && rawmem->in(0) == alloc)) {5448return NULL;5449}54505451// There must be no unexpected observers of this allocation.5452for (DUIterator_Fast imax, i = ptr->fast_outs(imax); i < imax; i++) {5453Node* obs = ptr->fast_out(i);5454if (obs != this->map()) {5455return NULL;5456}5457}54585459// This arraycopy must unconditionally follow the allocation of the ptr.5460Node* alloc_ctl = ptr->in(0);5461assert(just_allocated_object(alloc_ctl) == ptr, "most recent allo");54625463Node* ctl = control();5464while (ctl != alloc_ctl) {5465// There may be guards which feed into the slow_region.5466// Any other control flow means that we might not get a chance5467// to finish initializing the allocated object.5468if ((ctl->is_IfFalse() || ctl->is_IfTrue()) && ctl->in(0)->is_If()) {5469IfNode* iff = ctl->in(0)->as_If();5470Node* not_ctl = iff->proj_out(1 - ctl->as_Proj()->_con);5471assert(not_ctl != NULL && not_ctl != ctl, "found alternate");5472if (slow_region != NULL && slow_region->find_edge(not_ctl) >= 1) {5473ctl = iff->in(0); // This test feeds the known slow_region.5474continue;5475}5476// One more try: Various low-level checks bottom out in5477// uncommon traps. If the debug-info of the trap omits5478// any reference to the allocation, as we've already5479// observed, then there can be no objection to the trap.5480bool found_trap = false;5481for (DUIterator_Fast jmax, j = not_ctl->fast_outs(jmax); j < jmax; j++) {5482Node* obs = not_ctl->fast_out(j);5483if (obs->in(0) == not_ctl && obs->is_Call() &&5484(obs->as_Call()->entry_point() == SharedRuntime::uncommon_trap_blob()->entry_point())) {5485found_trap = true; break;5486}5487}5488if (found_trap) {5489ctl = iff->in(0); // This test feeds a harmless uncommon trap.5490continue;5491}5492}5493return NULL;5494}54955496// If we get this far, we have an allocation which immediately5497// precedes the arraycopy, and we can take over zeroing the new object.5498// The arraycopy will finish the initialization, and provide5499// a new control state to which we will anchor the destination pointer.55005501return alloc;5502}55035504// Helper for initialization of arrays, creating a ClearArray.5505// It writes zero bits in [start..end), within the body of an array object.5506// The memory effects are all chained onto the 'adr_type' alias category.5507//5508// Since the object is otherwise uninitialized, we are free5509// to put a little "slop" around the edges of the cleared area,5510// as long as it does not go back into the array's header,5511// or beyond the array end within the heap.5512//5513// The lower edge can be rounded down to the nearest jint and the5514// upper edge can be rounded up to the nearest MinObjAlignmentInBytes.5515//5516// Arguments:5517// adr_type memory slice where writes are generated5518// dest oop of the destination array5519// basic_elem_type element type of the destination5520// slice_idx array index of first element to store5521// slice_len number of elements to store (or NULL)5522// dest_size total size in bytes of the array object5523//5524// Exactly one of slice_len or dest_size must be non-NULL.5525// If dest_size is non-NULL, zeroing extends to the end of the object.5526// If slice_len is non-NULL, the slice_idx value must be a constant.5527void5528LibraryCallKit::generate_clear_array(const TypePtr* adr_type,5529Node* dest,5530BasicType basic_elem_type,5531Node* slice_idx,5532Node* slice_len,5533Node* dest_size) {5534// one or the other but not both of slice_len and dest_size:5535assert((slice_len != NULL? 1: 0) + (dest_size != NULL? 1: 0) == 1, "");5536if (slice_len == NULL) slice_len = top();5537if (dest_size == NULL) dest_size = top();55385539// operate on this memory slice:5540Node* mem = memory(adr_type); // memory slice to operate on55415542// scaling and rounding of indexes:5543int scale = exact_log2(type2aelembytes(basic_elem_type));5544int abase = arrayOopDesc::base_offset_in_bytes(basic_elem_type);5545int clear_low = (-1 << scale) & (BytesPerInt - 1);5546int bump_bit = (-1 << scale) & BytesPerInt;55475548// determine constant starts and ends5549const intptr_t BIG_NEG = -128;5550assert(BIG_NEG + 2*abase < 0, "neg enough");5551intptr_t slice_idx_con = (intptr_t) find_int_con(slice_idx, BIG_NEG);5552intptr_t slice_len_con = (intptr_t) find_int_con(slice_len, BIG_NEG);5553if (slice_len_con == 0) {5554return; // nothing to do here5555}5556intptr_t start_con = (abase + (slice_idx_con << scale)) & ~clear_low;5557intptr_t end_con = find_intptr_t_con(dest_size, -1);5558if (slice_idx_con >= 0 && slice_len_con >= 0) {5559assert(end_con < 0, "not two cons");5560end_con = round_to(abase + ((slice_idx_con + slice_len_con) << scale),5561BytesPerLong);5562}55635564if (start_con >= 0 && end_con >= 0) {5565// Constant start and end. Simple.5566mem = ClearArrayNode::clear_memory(control(), mem, dest,5567start_con, end_con, &_gvn);5568} else if (start_con >= 0 && dest_size != top()) {5569// Constant start, pre-rounded end after the tail of the array.5570Node* end = dest_size;5571mem = ClearArrayNode::clear_memory(control(), mem, dest,5572start_con, end, &_gvn);5573} else if (start_con >= 0 && slice_len != top()) {5574// Constant start, non-constant end. End needs rounding up.5575// End offset = round_up(abase + ((slice_idx_con + slice_len) << scale), 8)5576intptr_t end_base = abase + (slice_idx_con << scale);5577int end_round = (-1 << scale) & (BytesPerLong - 1);5578Node* end = ConvI2X(slice_len);5579if (scale != 0)5580end = _gvn.transform(new(C) LShiftXNode(end, intcon(scale) ));5581end_base += end_round;5582end = _gvn.transform(new(C) AddXNode(end, MakeConX(end_base)));5583end = _gvn.transform(new(C) AndXNode(end, MakeConX(~end_round)));5584mem = ClearArrayNode::clear_memory(control(), mem, dest,5585start_con, end, &_gvn);5586} else if (start_con < 0 && dest_size != top()) {5587// Non-constant start, pre-rounded end after the tail of the array.5588// This is almost certainly a "round-to-end" operation.5589Node* start = slice_idx;5590start = ConvI2X(start);5591if (scale != 0)5592start = _gvn.transform(new(C) LShiftXNode( start, intcon(scale) ));5593start = _gvn.transform(new(C) AddXNode(start, MakeConX(abase)));5594if ((bump_bit | clear_low) != 0) {5595int to_clear = (bump_bit | clear_low);5596// Align up mod 8, then store a jint zero unconditionally5597// just before the mod-8 boundary.5598if (((abase + bump_bit) & ~to_clear) - bump_bit5599< arrayOopDesc::length_offset_in_bytes() + BytesPerInt) {5600bump_bit = 0;5601assert((abase & to_clear) == 0, "array base must be long-aligned");5602} else {5603// Bump 'start' up to (or past) the next jint boundary:5604start = _gvn.transform(new(C) AddXNode(start, MakeConX(bump_bit)));5605assert((abase & clear_low) == 0, "array base must be int-aligned");5606}5607// Round bumped 'start' down to jlong boundary in body of array.5608start = _gvn.transform(new(C) AndXNode(start, MakeConX(~to_clear)));5609if (bump_bit != 0) {5610// Store a zero to the immediately preceding jint:5611Node* x1 = _gvn.transform(new(C) AddXNode(start, MakeConX(-bump_bit)));5612Node* p1 = basic_plus_adr(dest, x1);5613mem = StoreNode::make(_gvn, control(), mem, p1, adr_type, intcon(0), T_INT, MemNode::unordered);5614mem = _gvn.transform(mem);5615}5616}5617Node* end = dest_size; // pre-rounded5618mem = ClearArrayNode::clear_memory(control(), mem, dest,5619start, end, &_gvn);5620} else {5621// Non-constant start, unrounded non-constant end.5622// (Nobody zeroes a random midsection of an array using this routine.)5623ShouldNotReachHere(); // fix caller5624}56255626// Done.5627set_memory(mem, adr_type);5628}562956305631bool5632LibraryCallKit::generate_block_arraycopy(const TypePtr* adr_type,5633BasicType basic_elem_type,5634AllocateNode* alloc,5635Node* src, Node* src_offset,5636Node* dest, Node* dest_offset,5637Node* dest_size, bool dest_uninitialized) {5638// See if there is an advantage from block transfer.5639int scale = exact_log2(type2aelembytes(basic_elem_type));5640if (scale >= LogBytesPerLong)5641return false; // it is already a block transfer56425643// Look at the alignment of the starting offsets.5644int abase = arrayOopDesc::base_offset_in_bytes(basic_elem_type);56455646intptr_t src_off_con = (intptr_t) find_int_con(src_offset, -1);5647intptr_t dest_off_con = (intptr_t) find_int_con(dest_offset, -1);5648if (src_off_con < 0 || dest_off_con < 0)5649// At present, we can only understand constants.5650return false;56515652intptr_t src_off = abase + (src_off_con << scale);5653intptr_t dest_off = abase + (dest_off_con << scale);56545655if (((src_off | dest_off) & (BytesPerLong-1)) != 0) {5656// Non-aligned; too bad.5657// One more chance: Pick off an initial 32-bit word.5658// This is a common case, since abase can be odd mod 8.5659if (((src_off | dest_off) & (BytesPerLong-1)) == BytesPerInt &&5660((src_off ^ dest_off) & (BytesPerLong-1)) == 0) {5661Node* sptr = basic_plus_adr(src, src_off);5662Node* dptr = basic_plus_adr(dest, dest_off);5663Node* sval = make_load(control(), sptr, TypeInt::INT, T_INT, adr_type, MemNode::unordered);5664store_to_memory(control(), dptr, sval, T_INT, adr_type, MemNode::unordered);5665src_off += BytesPerInt;5666dest_off += BytesPerInt;5667} else {5668return false;5669}5670}5671assert(src_off % BytesPerLong == 0, "");5672assert(dest_off % BytesPerLong == 0, "");56735674// Do this copy by giant steps.5675Node* sptr = basic_plus_adr(src, src_off);5676Node* dptr = basic_plus_adr(dest, dest_off);5677Node* countx = dest_size;5678countx = _gvn.transform(new (C) SubXNode(countx, MakeConX(dest_off)));5679countx = _gvn.transform(new (C) URShiftXNode(countx, intcon(LogBytesPerLong)));56805681bool disjoint_bases = true; // since alloc != NULL5682generate_unchecked_arraycopy(adr_type, T_LONG, disjoint_bases,5683sptr, NULL, dptr, NULL, countx, dest_uninitialized);56845685return true;5686}568756885689// Helper function; generates code for the slow case.5690// We make a call to a runtime method which emulates the native method,5691// but without the native wrapper overhead.5692void5693LibraryCallKit::generate_slow_arraycopy(const TypePtr* adr_type,5694Node* src, Node* src_offset,5695Node* dest, Node* dest_offset,5696Node* copy_length, bool dest_uninitialized) {5697assert(!dest_uninitialized, "Invariant");5698Node* call = make_runtime_call(RC_NO_LEAF | RC_UNCOMMON,5699OptoRuntime::slow_arraycopy_Type(),5700OptoRuntime::slow_arraycopy_Java(),5701"slow_arraycopy", adr_type,5702src, src_offset, dest, dest_offset,5703copy_length);57045705// Handle exceptions thrown by this fellow:5706make_slow_call_ex(call, env()->Throwable_klass(), false);5707}57085709// Helper function; generates code for cases requiring runtime checks.5710Node*5711LibraryCallKit::generate_checkcast_arraycopy(const TypePtr* adr_type,5712Node* dest_elem_klass,5713Node* src, Node* src_offset,5714Node* dest, Node* dest_offset,5715Node* copy_length, bool dest_uninitialized) {5716if (stopped()) return NULL;57175718address copyfunc_addr = StubRoutines::checkcast_arraycopy(dest_uninitialized);5719if (copyfunc_addr == NULL) { // Stub was not generated, go slow path.5720return NULL;5721}57225723// Pick out the parameters required to perform a store-check5724// for the target array. This is an optimistic check. It will5725// look in each non-null element's class, at the desired klass's5726// super_check_offset, for the desired klass.5727int sco_offset = in_bytes(Klass::super_check_offset_offset());5728Node* p3 = basic_plus_adr(dest_elem_klass, sco_offset);5729Node* n3 = new(C) LoadINode(NULL, memory(p3), p3, _gvn.type(p3)->is_ptr(), TypeInt::INT, MemNode::unordered);5730Node* check_offset = ConvI2X(_gvn.transform(n3));5731Node* check_value = dest_elem_klass;57325733Node* src_start = array_element_address(src, src_offset, T_OBJECT);5734Node* dest_start = array_element_address(dest, dest_offset, T_OBJECT);57355736// (We know the arrays are never conjoint, because their types differ.)5737Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,5738OptoRuntime::checkcast_arraycopy_Type(),5739copyfunc_addr, "checkcast_arraycopy", adr_type,5740// five arguments, of which two are5741// intptr_t (jlong in LP64)5742src_start, dest_start,5743copy_length XTOP,5744check_offset XTOP,5745check_value);57465747return _gvn.transform(new (C) ProjNode(call, TypeFunc::Parms));5748}574957505751// Helper function; generates code for cases requiring runtime checks.5752Node*5753LibraryCallKit::generate_generic_arraycopy(const TypePtr* adr_type,5754Node* src, Node* src_offset,5755Node* dest, Node* dest_offset,5756Node* copy_length, bool dest_uninitialized) {5757assert(!dest_uninitialized, "Invariant");5758if (stopped()) return NULL;5759address copyfunc_addr = StubRoutines::generic_arraycopy();5760if (copyfunc_addr == NULL) { // Stub was not generated, go slow path.5761return NULL;5762}57635764Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,5765OptoRuntime::generic_arraycopy_Type(),5766copyfunc_addr, "generic_arraycopy", adr_type,5767src, src_offset, dest, dest_offset, copy_length);57685769return _gvn.transform(new (C) ProjNode(call, TypeFunc::Parms));5770}57715772// Helper function; generates the fast out-of-line call to an arraycopy stub.5773void5774LibraryCallKit::generate_unchecked_arraycopy(const TypePtr* adr_type,5775BasicType basic_elem_type,5776bool disjoint_bases,5777Node* src, Node* src_offset,5778Node* dest, Node* dest_offset,5779Node* copy_length, bool dest_uninitialized) {5780if (stopped()) return; // nothing to do57815782Node* src_start = src;5783Node* dest_start = dest;5784if (src_offset != NULL || dest_offset != NULL) {5785assert(src_offset != NULL && dest_offset != NULL, "");5786src_start = array_element_address(src, src_offset, basic_elem_type);5787dest_start = array_element_address(dest, dest_offset, basic_elem_type);5788}57895790// Figure out which arraycopy runtime method to call.5791const char* copyfunc_name = "arraycopy";5792address copyfunc_addr =5793basictype2arraycopy(basic_elem_type, src_offset, dest_offset,5794disjoint_bases, copyfunc_name, dest_uninitialized);57955796// Call it. Note that the count_ix value is not scaled to a byte-size.5797make_runtime_call(RC_LEAF|RC_NO_FP,5798OptoRuntime::fast_arraycopy_Type(),5799copyfunc_addr, copyfunc_name, adr_type,5800src_start, dest_start, copy_length XTOP);5801}58025803//-------------inline_encodeISOArray-----------------------------------5804// encode char[] to byte[] in ISO_8859_15805bool LibraryCallKit::inline_encodeISOArray() {5806assert(callee()->signature()->size() == 5, "encodeISOArray has 5 parameters");5807// no receiver since it is static method5808Node *src = argument(0);5809Node *src_offset = argument(1);5810Node *dst = argument(2);5811Node *dst_offset = argument(3);5812Node *length = argument(4);58135814const Type* src_type = src->Value(&_gvn);5815const Type* dst_type = dst->Value(&_gvn);5816const TypeAryPtr* top_src = src_type->isa_aryptr();5817const TypeAryPtr* top_dest = dst_type->isa_aryptr();5818if (top_src == NULL || top_src->klass() == NULL ||5819top_dest == NULL || top_dest->klass() == NULL) {5820// failed array check5821return false;5822}58235824// Figure out the size and type of the elements we will be copying.5825BasicType src_elem = src_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();5826BasicType dst_elem = dst_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();5827if (src_elem != T_CHAR || dst_elem != T_BYTE) {5828return false;5829}5830Node* src_start = array_element_address(src, src_offset, src_elem);5831Node* dst_start = array_element_address(dst, dst_offset, dst_elem);5832// 'src_start' points to src array + scaled offset5833// 'dst_start' points to dst array + scaled offset58345835const TypeAryPtr* mtype = TypeAryPtr::BYTES;5836Node* enc = new (C) EncodeISOArrayNode(control(), memory(mtype), src_start, dst_start, length);5837enc = _gvn.transform(enc);5838Node* res_mem = _gvn.transform(new (C) SCMemProjNode(enc));5839set_memory(res_mem, mtype);5840set_result(enc);5841return true;5842}58435844//-------------inline_multiplyToLen-----------------------------------5845bool LibraryCallKit::inline_multiplyToLen() {5846assert(UseMultiplyToLenIntrinsic, "not implementated on this platform");58475848address stubAddr = StubRoutines::multiplyToLen();5849if (stubAddr == NULL) {5850return false; // Intrinsic's stub is not implemented on this platform5851}5852const char* stubName = "multiplyToLen";58535854assert(callee()->signature()->size() == 5, "multiplyToLen has 5 parameters");58555856// no receiver because it is a static method5857Node* x = argument(0);5858Node* xlen = argument(1);5859Node* y = argument(2);5860Node* ylen = argument(3);5861Node* z = argument(4);58625863const Type* x_type = x->Value(&_gvn);5864const Type* y_type = y->Value(&_gvn);5865const TypeAryPtr* top_x = x_type->isa_aryptr();5866const TypeAryPtr* top_y = y_type->isa_aryptr();5867if (top_x == NULL || top_x->klass() == NULL ||5868top_y == NULL || top_y->klass() == NULL) {5869// failed array check5870return false;5871}58725873BasicType x_elem = x_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();5874BasicType y_elem = y_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();5875if (x_elem != T_INT || y_elem != T_INT) {5876return false;5877}58785879// Set the original stack and the reexecute bit for the interpreter to reexecute5880// the bytecode that invokes BigInteger.multiplyToLen() if deoptimization happens5881// on the return from z array allocation in runtime.5882{ PreserveReexecuteState preexecs(this);5883jvms()->set_should_reexecute(true);58845885Node* x_start = array_element_address(x, intcon(0), x_elem);5886Node* y_start = array_element_address(y, intcon(0), y_elem);5887// 'x_start' points to x array + scaled xlen5888// 'y_start' points to y array + scaled ylen58895890// Allocate the result array5891Node* zlen = _gvn.transform(new(C) AddINode(xlen, ylen));5892ciKlass* klass = ciTypeArrayKlass::make(T_INT);5893Node* klass_node = makecon(TypeKlassPtr::make(klass));58945895IdealKit ideal(this);58965897#define __ ideal.5898Node* one = __ ConI(1);5899Node* zero = __ ConI(0);5900IdealVariable need_alloc(ideal), z_alloc(ideal); __ declarations_done();5901__ set(need_alloc, zero);5902__ set(z_alloc, z);5903__ if_then(z, BoolTest::eq, null()); {5904__ increment (need_alloc, one);5905} __ else_(); {5906// Update graphKit memory and control from IdealKit.5907sync_kit(ideal);5908Node* zlen_arg = load_array_length(z);5909// Update IdealKit memory and control from graphKit.5910__ sync_kit(this);5911__ if_then(zlen_arg, BoolTest::lt, zlen); {5912__ increment (need_alloc, one);5913} __ end_if();5914} __ end_if();59155916__ if_then(__ value(need_alloc), BoolTest::ne, zero); {5917// Update graphKit memory and control from IdealKit.5918sync_kit(ideal);5919Node * narr = new_array(klass_node, zlen, 1);5920// Update IdealKit memory and control from graphKit.5921__ sync_kit(this);5922__ set(z_alloc, narr);5923} __ end_if();59245925sync_kit(ideal);5926z = __ value(z_alloc);5927// Can't use TypeAryPtr::INTS which uses Bottom offset.5928_gvn.set_type(z, TypeOopPtr::make_from_klass(klass));5929// Final sync IdealKit and GraphKit.5930final_sync(ideal);5931#undef __59325933Node* z_start = array_element_address(z, intcon(0), T_INT);59345935Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,5936OptoRuntime::multiplyToLen_Type(),5937stubAddr, stubName, TypePtr::BOTTOM,5938x_start, xlen, y_start, ylen, z_start, zlen);5939} // original reexecute is set back here59405941C->set_has_split_ifs(true); // Has chance for split-if optimization5942set_result(z);5943return true;5944}59455946//-------------inline_squareToLen------------------------------------5947bool LibraryCallKit::inline_squareToLen() {5948assert(UseSquareToLenIntrinsic, "not implementated on this platform");59495950address stubAddr = StubRoutines::squareToLen();5951if (stubAddr == NULL) {5952return false; // Intrinsic's stub is not implemented on this platform5953}5954const char* stubName = "squareToLen";59555956assert(callee()->signature()->size() == 4, "implSquareToLen has 4 parameters");59575958Node* x = argument(0);5959Node* len = argument(1);5960Node* z = argument(2);5961Node* zlen = argument(3);59625963const Type* x_type = x->Value(&_gvn);5964const Type* z_type = z->Value(&_gvn);5965const TypeAryPtr* top_x = x_type->isa_aryptr();5966const TypeAryPtr* top_z = z_type->isa_aryptr();5967if (top_x == NULL || top_x->klass() == NULL ||5968top_z == NULL || top_z->klass() == NULL) {5969// failed array check5970return false;5971}59725973BasicType x_elem = x_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();5974BasicType z_elem = z_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();5975if (x_elem != T_INT || z_elem != T_INT) {5976return false;5977}597859795980Node* x_start = array_element_address(x, intcon(0), x_elem);5981Node* z_start = array_element_address(z, intcon(0), z_elem);59825983Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,5984OptoRuntime::squareToLen_Type(),5985stubAddr, stubName, TypePtr::BOTTOM,5986x_start, len, z_start, zlen);59875988set_result(z);5989return true;5990}59915992//-------------inline_mulAdd------------------------------------------5993bool LibraryCallKit::inline_mulAdd() {5994assert(UseMulAddIntrinsic, "not implementated on this platform");59955996address stubAddr = StubRoutines::mulAdd();5997if (stubAddr == NULL) {5998return false; // Intrinsic's stub is not implemented on this platform5999}6000const char* stubName = "mulAdd";60016002assert(callee()->signature()->size() == 5, "mulAdd has 5 parameters");60036004Node* out = argument(0);6005Node* in = argument(1);6006Node* offset = argument(2);6007Node* len = argument(3);6008Node* k = argument(4);60096010const Type* out_type = out->Value(&_gvn);6011const Type* in_type = in->Value(&_gvn);6012const TypeAryPtr* top_out = out_type->isa_aryptr();6013const TypeAryPtr* top_in = in_type->isa_aryptr();6014if (top_out == NULL || top_out->klass() == NULL ||6015top_in == NULL || top_in->klass() == NULL) {6016// failed array check6017return false;6018}60196020BasicType out_elem = out_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();6021BasicType in_elem = in_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();6022if (out_elem != T_INT || in_elem != T_INT) {6023return false;6024}60256026Node* outlen = load_array_length(out);6027Node* new_offset = _gvn.transform(new (C) SubINode(outlen, offset));6028Node* out_start = array_element_address(out, intcon(0), out_elem);6029Node* in_start = array_element_address(in, intcon(0), in_elem);60306031Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,6032OptoRuntime::mulAdd_Type(),6033stubAddr, stubName, TypePtr::BOTTOM,6034out_start,in_start, new_offset, len, k);6035Node* result = _gvn.transform(new (C) ProjNode(call, TypeFunc::Parms));6036set_result(result);6037return true;6038}60396040//-------------inline_montgomeryMultiply-----------------------------------6041bool LibraryCallKit::inline_montgomeryMultiply() {6042address stubAddr = StubRoutines::montgomeryMultiply();6043if (stubAddr == NULL) {6044return false; // Intrinsic's stub is not implemented on this platform6045}60466047assert(UseMontgomeryMultiplyIntrinsic, "not implemented on this platform");6048const char* stubName = "montgomery_multiply";60496050assert(callee()->signature()->size() == 7, "montgomeryMultiply has 7 parameters");60516052Node* a = argument(0);6053Node* b = argument(1);6054Node* n = argument(2);6055Node* len = argument(3);6056Node* inv = argument(4);6057Node* m = argument(6);60586059const Type* a_type = a->Value(&_gvn);6060const TypeAryPtr* top_a = a_type->isa_aryptr();6061const Type* b_type = b->Value(&_gvn);6062const TypeAryPtr* top_b = b_type->isa_aryptr();6063const Type* n_type = a->Value(&_gvn);6064const TypeAryPtr* top_n = n_type->isa_aryptr();6065const Type* m_type = a->Value(&_gvn);6066const TypeAryPtr* top_m = m_type->isa_aryptr();6067if (top_a == NULL || top_a->klass() == NULL ||6068top_b == NULL || top_b->klass() == NULL ||6069top_n == NULL || top_n->klass() == NULL ||6070top_m == NULL || top_m->klass() == NULL) {6071// failed array check6072return false;6073}60746075BasicType a_elem = a_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();6076BasicType b_elem = b_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();6077BasicType n_elem = n_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();6078BasicType m_elem = m_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();6079if (a_elem != T_INT || b_elem != T_INT || n_elem != T_INT || m_elem != T_INT) {6080return false;6081}60826083// Make the call6084{6085Node* a_start = array_element_address(a, intcon(0), a_elem);6086Node* b_start = array_element_address(b, intcon(0), b_elem);6087Node* n_start = array_element_address(n, intcon(0), n_elem);6088Node* m_start = array_element_address(m, intcon(0), m_elem);60896090Node* call = NULL;6091if (CCallingConventionRequiresIntsAsLongs) {6092Node* len_I2L = ConvI2L(len);6093call = make_runtime_call(RC_LEAF,6094OptoRuntime::montgomeryMultiply_Type(),6095stubAddr, stubName, TypePtr::BOTTOM,6096a_start, b_start, n_start, len_I2L XTOP, inv,6097top(), m_start);6098} else {6099call = make_runtime_call(RC_LEAF,6100OptoRuntime::montgomeryMultiply_Type(),6101stubAddr, stubName, TypePtr::BOTTOM,6102a_start, b_start, n_start, len, inv, top(),6103m_start);6104}6105set_result(m);6106}61076108return true;6109}61106111bool LibraryCallKit::inline_montgomerySquare() {6112address stubAddr = StubRoutines::montgomerySquare();6113if (stubAddr == NULL) {6114return false; // Intrinsic's stub is not implemented on this platform6115}61166117assert(UseMontgomerySquareIntrinsic, "not implemented on this platform");6118const char* stubName = "montgomery_square";61196120assert(callee()->signature()->size() == 6, "montgomerySquare has 6 parameters");61216122Node* a = argument(0);6123Node* n = argument(1);6124Node* len = argument(2);6125Node* inv = argument(3);6126Node* m = argument(5);61276128const Type* a_type = a->Value(&_gvn);6129const TypeAryPtr* top_a = a_type->isa_aryptr();6130const Type* n_type = a->Value(&_gvn);6131const TypeAryPtr* top_n = n_type->isa_aryptr();6132const Type* m_type = a->Value(&_gvn);6133const TypeAryPtr* top_m = m_type->isa_aryptr();6134if (top_a == NULL || top_a->klass() == NULL ||6135top_n == NULL || top_n->klass() == NULL ||6136top_m == NULL || top_m->klass() == NULL) {6137// failed array check6138return false;6139}61406141BasicType a_elem = a_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();6142BasicType n_elem = n_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();6143BasicType m_elem = m_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();6144if (a_elem != T_INT || n_elem != T_INT || m_elem != T_INT) {6145return false;6146}61476148// Make the call6149{6150Node* a_start = array_element_address(a, intcon(0), a_elem);6151Node* n_start = array_element_address(n, intcon(0), n_elem);6152Node* m_start = array_element_address(m, intcon(0), m_elem);61536154Node* call = NULL;6155if (CCallingConventionRequiresIntsAsLongs) {6156Node* len_I2L = ConvI2L(len);6157call = make_runtime_call(RC_LEAF,6158OptoRuntime::montgomerySquare_Type(),6159stubAddr, stubName, TypePtr::BOTTOM,6160a_start, n_start, len_I2L XTOP, inv, top(),6161m_start);6162} else {6163call = make_runtime_call(RC_LEAF,6164OptoRuntime::montgomerySquare_Type(),6165stubAddr, stubName, TypePtr::BOTTOM,6166a_start, n_start, len, inv, top(),6167m_start);6168}61696170set_result(m);6171}61726173return true;6174}617561766177/**6178* Calculate CRC32 for byte.6179* int java.util.zip.CRC32.update(int crc, int b)6180*/6181bool LibraryCallKit::inline_updateCRC32() {6182assert(UseCRC32Intrinsics, "need AVX and LCMUL instructions support");6183assert(callee()->signature()->size() == 2, "update has 2 parameters");6184// no receiver since it is static method6185Node* crc = argument(0); // type: int6186Node* b = argument(1); // type: int61876188/*6189* int c = ~ crc;6190* b = timesXtoThe32[(b ^ c) & 0xFF];6191* b = b ^ (c >>> 8);6192* crc = ~b;6193*/61946195Node* M1 = intcon(-1);6196crc = _gvn.transform(new (C) XorINode(crc, M1));6197Node* result = _gvn.transform(new (C) XorINode(crc, b));6198result = _gvn.transform(new (C) AndINode(result, intcon(0xFF)));61996200Node* base = makecon(TypeRawPtr::make(StubRoutines::crc_table_addr()));6201Node* offset = _gvn.transform(new (C) LShiftINode(result, intcon(0x2)));6202Node* adr = basic_plus_adr(top(), base, ConvI2X(offset));6203result = make_load(control(), adr, TypeInt::INT, T_INT, MemNode::unordered);62046205crc = _gvn.transform(new (C) URShiftINode(crc, intcon(8)));6206result = _gvn.transform(new (C) XorINode(crc, result));6207result = _gvn.transform(new (C) XorINode(result, M1));6208set_result(result);6209return true;6210}62116212/**6213* Calculate CRC32 for byte[] array.6214* int java.util.zip.CRC32.updateBytes(int crc, byte[] buf, int off, int len)6215*/6216bool LibraryCallKit::inline_updateBytesCRC32() {6217assert(UseCRC32Intrinsics, "need AVX and LCMUL instructions support");6218assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");6219// no receiver since it is static method6220Node* crc = argument(0); // type: int6221Node* src = argument(1); // type: oop6222Node* offset = argument(2); // type: int6223Node* length = argument(3); // type: int62246225const Type* src_type = src->Value(&_gvn);6226const TypeAryPtr* top_src = src_type->isa_aryptr();6227if (top_src == NULL || top_src->klass() == NULL) {6228// failed array check6229return false;6230}62316232// Figure out the size and type of the elements we will be copying.6233BasicType src_elem = src_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();6234if (src_elem != T_BYTE) {6235return false;6236}62376238// 'src_start' points to src array + scaled offset6239Node* src_start = array_element_address(src, offset, src_elem);62406241// We assume that range check is done by caller.6242// TODO: generate range check (offset+length < src.length) in debug VM.62436244// Call the stub.6245address stubAddr = StubRoutines::updateBytesCRC32();6246const char *stubName = "updateBytesCRC32";6247Node* call;6248if (CCallingConventionRequiresIntsAsLongs) {6249call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::updateBytesCRC32_Type(),6250stubAddr, stubName, TypePtr::BOTTOM,6251crc XTOP, src_start, length XTOP);6252} else {6253call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::updateBytesCRC32_Type(),6254stubAddr, stubName, TypePtr::BOTTOM,6255crc, src_start, length);6256}6257Node* result = _gvn.transform(new (C) ProjNode(call, TypeFunc::Parms));6258set_result(result);6259return true;6260}62616262/**6263* Calculate CRC32 for ByteBuffer.6264* int java.util.zip.CRC32.updateByteBuffer(int crc, long buf, int off, int len)6265*/6266bool LibraryCallKit::inline_updateByteBufferCRC32() {6267assert(UseCRC32Intrinsics, "need AVX and LCMUL instructions support");6268assert(callee()->signature()->size() == 5, "updateByteBuffer has 4 parameters and one is long");6269// no receiver since it is static method6270Node* crc = argument(0); // type: int6271Node* src = argument(1); // type: long6272Node* offset = argument(3); // type: int6273Node* length = argument(4); // type: int62746275src = ConvL2X(src); // adjust Java long to machine word6276Node* base = _gvn.transform(new (C) CastX2PNode(src));6277offset = ConvI2X(offset);62786279// 'src_start' points to src array + scaled offset6280Node* src_start = basic_plus_adr(top(), base, offset);62816282// Call the stub.6283address stubAddr = StubRoutines::updateBytesCRC32();6284const char *stubName = "updateBytesCRC32";6285Node* call;6286if (CCallingConventionRequiresIntsAsLongs) {6287call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::updateBytesCRC32_Type(),6288stubAddr, stubName, TypePtr::BOTTOM,6289crc XTOP, src_start, length XTOP);6290} else {6291call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::updateBytesCRC32_Type(),6292stubAddr, stubName, TypePtr::BOTTOM,6293crc, src_start, length);6294}6295Node* result = _gvn.transform(new (C) ProjNode(call, TypeFunc::Parms));6296set_result(result);6297return true;6298}62996300//----------------------------inline_reference_get----------------------------6301// public T java.lang.ref.Reference.get();6302bool LibraryCallKit::inline_reference_get() {6303const int referent_offset = java_lang_ref_Reference::referent_offset;6304guarantee(referent_offset > 0, "should have already been set");63056306// Get the argument:6307Node* reference_obj = null_check_receiver();6308if (stopped()) return true;63096310Node* adr = basic_plus_adr(reference_obj, reference_obj, referent_offset);63116312ciInstanceKlass* klass = env()->Object_klass();6313const TypeOopPtr* object_type = TypeOopPtr::make_from_klass(klass);63146315Node* no_ctrl = NULL;6316Node* result = make_load(no_ctrl, adr, object_type, T_OBJECT, MemNode::unordered);63176318// Use the pre-barrier to record the value in the referent field6319pre_barrier(false /* do_load */,6320control(),6321NULL /* obj */, NULL /* adr */, max_juint /* alias_idx */, NULL /* val */, NULL /* val_type */,6322result /* pre_val */,6323T_OBJECT);63246325// Add memory barrier to prevent commoning reads from this field6326// across safepoint since GC can change its value.6327insert_mem_bar(Op_MemBarCPUOrder);63286329set_result(result);6330return true;6331}633263336334Node * LibraryCallKit::load_field_from_object(Node * fromObj, const char * fieldName, const char * fieldTypeString,6335bool is_exact=true, bool is_static=false) {63366337const TypeInstPtr* tinst = _gvn.type(fromObj)->isa_instptr();6338assert(tinst != NULL, "obj is null");6339assert(tinst->klass()->is_loaded(), "obj is not loaded");6340assert(!is_exact || tinst->klass_is_exact(), "klass not exact");63416342ciField* field = tinst->klass()->as_instance_klass()->get_field_by_name(ciSymbol::make(fieldName),6343ciSymbol::make(fieldTypeString),6344is_static);6345if (field == NULL) return (Node *) NULL;6346assert (field != NULL, "undefined field");63476348// Next code copied from Parse::do_get_xxx():63496350// Compute address and memory type.6351int offset = field->offset_in_bytes();6352bool is_vol = field->is_volatile();6353ciType* field_klass = field->type();6354assert(field_klass->is_loaded(), "should be loaded");6355const TypePtr* adr_type = C->alias_type(field)->adr_type();6356Node *adr = basic_plus_adr(fromObj, fromObj, offset);6357BasicType bt = field->layout_type();63586359// Build the resultant type of the load6360const Type *type;6361if (bt == T_OBJECT) {6362type = TypeOopPtr::make_from_klass(field_klass->as_klass());6363} else {6364type = Type::get_const_basic_type(bt);6365}63666367Node* leading_membar = NULL;6368if (support_IRIW_for_not_multiple_copy_atomic_cpu && is_vol) {6369leading_membar = insert_mem_bar(Op_MemBarVolatile); // StoreLoad barrier6370}6371// Build the load.6372MemNode::MemOrd mo = is_vol ? MemNode::acquire : MemNode::unordered;6373Node* loadedField = make_load(NULL, adr, type, bt, adr_type, mo, LoadNode::DependsOnlyOnTest, is_vol);6374// If reference is volatile, prevent following memory ops from6375// floating up past the volatile read. Also prevents commoning6376// another volatile read.6377if (is_vol) {6378// Memory barrier includes bogus read of value to force load BEFORE membar6379Node* mb = insert_mem_bar(Op_MemBarAcquire, loadedField);6380mb->as_MemBar()->set_trailing_load();6381}6382return loadedField;6383}638463856386//------------------------------inline_aescrypt_Block-----------------------6387bool LibraryCallKit::inline_aescrypt_Block(vmIntrinsics::ID id) {6388address stubAddr = NULL;6389const char *stubName;6390assert(UseAES, "need AES instruction support");63916392switch(id) {6393case vmIntrinsics::_aescrypt_encryptBlock:6394stubAddr = StubRoutines::aescrypt_encryptBlock();6395stubName = "aescrypt_encryptBlock";6396break;6397case vmIntrinsics::_aescrypt_decryptBlock:6398stubAddr = StubRoutines::aescrypt_decryptBlock();6399stubName = "aescrypt_decryptBlock";6400break;6401}6402if (stubAddr == NULL) return false;64036404Node* aescrypt_object = argument(0);6405Node* src = argument(1);6406Node* src_offset = argument(2);6407Node* dest = argument(3);6408Node* dest_offset = argument(4);64096410// (1) src and dest are arrays.6411const Type* src_type = src->Value(&_gvn);6412const Type* dest_type = dest->Value(&_gvn);6413const TypeAryPtr* top_src = src_type->isa_aryptr();6414const TypeAryPtr* top_dest = dest_type->isa_aryptr();6415assert (top_src != NULL && top_src->klass() != NULL && top_dest != NULL && top_dest->klass() != NULL, "args are strange");64166417// for the quick and dirty code we will skip all the checks.6418// we are just trying to get the call to be generated.6419Node* src_start = src;6420Node* dest_start = dest;6421if (src_offset != NULL || dest_offset != NULL) {6422assert(src_offset != NULL && dest_offset != NULL, "");6423src_start = array_element_address(src, src_offset, T_BYTE);6424dest_start = array_element_address(dest, dest_offset, T_BYTE);6425}64266427// now need to get the start of its expanded key array6428// this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java6429Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object);6430if (k_start == NULL) return false;64316432if (Matcher::pass_original_key_for_aes()) {6433// on SPARC we need to pass the original key since key expansion needs to happen in intrinsics due to6434// compatibility issues between Java key expansion and SPARC crypto instructions6435Node* original_k_start = get_original_key_start_from_aescrypt_object(aescrypt_object);6436if (original_k_start == NULL) return false;64376438// Call the stub.6439make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::aescrypt_block_Type(),6440stubAddr, stubName, TypePtr::BOTTOM,6441src_start, dest_start, k_start, original_k_start);6442} else {6443// Call the stub.6444make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::aescrypt_block_Type(),6445stubAddr, stubName, TypePtr::BOTTOM,6446src_start, dest_start, k_start);6447}64486449return true;6450}64516452//------------------------------inline_cipherBlockChaining_AESCrypt-----------------------6453bool LibraryCallKit::inline_cipherBlockChaining_AESCrypt(vmIntrinsics::ID id) {6454address stubAddr = NULL;6455const char *stubName = NULL;64566457assert(UseAES, "need AES instruction support");64586459switch(id) {6460case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:6461stubAddr = StubRoutines::cipherBlockChaining_encryptAESCrypt();6462stubName = "cipherBlockChaining_encryptAESCrypt";6463break;6464case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:6465stubAddr = StubRoutines::cipherBlockChaining_decryptAESCrypt();6466stubName = "cipherBlockChaining_decryptAESCrypt";6467break;6468}6469if (stubAddr == NULL) return false;64706471Node* cipherBlockChaining_object = argument(0);6472Node* src = argument(1);6473Node* src_offset = argument(2);6474Node* len = argument(3);6475Node* dest = argument(4);6476Node* dest_offset = argument(5);64776478// (1) src and dest are arrays.6479const Type* src_type = src->Value(&_gvn);6480const Type* dest_type = dest->Value(&_gvn);6481const TypeAryPtr* top_src = src_type->isa_aryptr();6482const TypeAryPtr* top_dest = dest_type->isa_aryptr();6483assert (top_src != NULL && top_src->klass() != NULL6484&& top_dest != NULL && top_dest->klass() != NULL, "args are strange");64856486// checks are the responsibility of the caller6487Node* src_start = src;6488Node* dest_start = dest;6489if (src_offset != NULL || dest_offset != NULL) {6490assert(src_offset != NULL && dest_offset != NULL, "");6491src_start = array_element_address(src, src_offset, T_BYTE);6492dest_start = array_element_address(dest, dest_offset, T_BYTE);6493}64946495// if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object6496// (because of the predicated logic executed earlier).6497// so we cast it here safely.6498// this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java64996500Node* embeddedCipherObj = load_field_from_object(cipherBlockChaining_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;", /*is_exact*/ false);6501if (embeddedCipherObj == NULL) return false;65026503// cast it to what we know it will be at runtime6504const TypeInstPtr* tinst = _gvn.type(cipherBlockChaining_object)->isa_instptr();6505assert(tinst != NULL, "CBC obj is null");6506assert(tinst->klass()->is_loaded(), "CBC obj is not loaded");6507ciKlass* klass_AESCrypt = tinst->klass()->as_instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AESCrypt"));6508assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");65096510ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();6511const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);6512const TypeOopPtr* xtype = aklass->as_instance_type();6513Node* aescrypt_object = new(C) CheckCastPPNode(control(), embeddedCipherObj, xtype);6514aescrypt_object = _gvn.transform(aescrypt_object);65156516// we need to get the start of the aescrypt_object's expanded key array6517Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object);6518if (k_start == NULL) return false;65196520// similarly, get the start address of the r vector6521Node* objRvec = load_field_from_object(cipherBlockChaining_object, "r", "[B", /*is_exact*/ false);6522if (objRvec == NULL) return false;6523Node* r_start = array_element_address(objRvec, intcon(0), T_BYTE);65246525Node* cbcCrypt;6526if (Matcher::pass_original_key_for_aes()) {6527// on SPARC we need to pass the original key since key expansion needs to happen in intrinsics due to6528// compatibility issues between Java key expansion and SPARC crypto instructions6529Node* original_k_start = get_original_key_start_from_aescrypt_object(aescrypt_object);6530if (original_k_start == NULL) return false;65316532// Call the stub, passing src_start, dest_start, k_start, r_start, src_len and original_k_start6533cbcCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,6534OptoRuntime::cipherBlockChaining_aescrypt_Type(),6535stubAddr, stubName, TypePtr::BOTTOM,6536src_start, dest_start, k_start, r_start, len, original_k_start);6537} else {6538// Call the stub, passing src_start, dest_start, k_start, r_start and src_len6539cbcCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,6540OptoRuntime::cipherBlockChaining_aescrypt_Type(),6541stubAddr, stubName, TypePtr::BOTTOM,6542src_start, dest_start, k_start, r_start, len);6543}65446545// return cipher length (int)6546Node* retvalue = _gvn.transform(new (C) ProjNode(cbcCrypt, TypeFunc::Parms));6547set_result(retvalue);6548return true;6549}65506551//------------------------------get_key_start_from_aescrypt_object-----------------------6552Node * LibraryCallKit::get_key_start_from_aescrypt_object(Node *aescrypt_object) {6553#ifdef PPC646554// MixColumns for decryption can be reduced by preprocessing MixColumns with round keys.6555// Intel's extention is based on this optimization and AESCrypt generates round keys by preprocessing MixColumns.6556// However, ppc64 vncipher processes MixColumns and requires the same round keys with encryption.6557// The ppc64 stubs of encryption and decryption use the same round keys (sessionK[0]).6558Node* objSessionK = load_field_from_object(aescrypt_object, "sessionK", "[[I", /*is_exact*/ false);6559assert (objSessionK != NULL, "wrong version of com.sun.crypto.provider.AESCrypt");6560if (objSessionK == NULL) {6561return (Node *) NULL;6562}6563Node* objAESCryptKey = load_array_element(control(), objSessionK, intcon(0), TypeAryPtr::OOPS);6564#else6565Node* objAESCryptKey = load_field_from_object(aescrypt_object, "K", "[I", /*is_exact*/ false);6566#endif // PPC646567assert (objAESCryptKey != NULL, "wrong version of com.sun.crypto.provider.AESCrypt");6568if (objAESCryptKey == NULL) return (Node *) NULL;65696570// now have the array, need to get the start address of the K array6571Node* k_start = array_element_address(objAESCryptKey, intcon(0), T_INT);6572return k_start;6573}65746575//------------------------------get_original_key_start_from_aescrypt_object-----------------------6576Node * LibraryCallKit::get_original_key_start_from_aescrypt_object(Node *aescrypt_object) {6577Node* objAESCryptKey = load_field_from_object(aescrypt_object, "lastKey", "[B", /*is_exact*/ false);6578assert (objAESCryptKey != NULL, "wrong version of com.sun.crypto.provider.AESCrypt");6579if (objAESCryptKey == NULL) return (Node *) NULL;65806581// now have the array, need to get the start address of the lastKey array6582Node* original_k_start = array_element_address(objAESCryptKey, intcon(0), T_BYTE);6583return original_k_start;6584}65856586//----------------------------inline_cipherBlockChaining_AESCrypt_predicate----------------------------6587// Return node representing slow path of predicate check.6588// the pseudo code we want to emulate with this predicate is:6589// for encryption:6590// if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath6591// for decryption:6592// if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath6593// note cipher==plain is more conservative than the original java code but that's OK6594//6595Node* LibraryCallKit::inline_cipherBlockChaining_AESCrypt_predicate(bool decrypting) {6596// The receiver was checked for NULL already.6597Node* objCBC = argument(0);65986599// Load embeddedCipher field of CipherBlockChaining object.6600Node* embeddedCipherObj = load_field_from_object(objCBC, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;", /*is_exact*/ false);66016602// get AESCrypt klass for instanceOf check6603// AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point6604// will have same classloader as CipherBlockChaining object6605const TypeInstPtr* tinst = _gvn.type(objCBC)->isa_instptr();6606assert(tinst != NULL, "CBCobj is null");6607assert(tinst->klass()->is_loaded(), "CBCobj is not loaded");66086609// we want to do an instanceof comparison against the AESCrypt class6610ciKlass* klass_AESCrypt = tinst->klass()->as_instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AESCrypt"));6611if (!klass_AESCrypt->is_loaded()) {6612// if AESCrypt is not even loaded, we never take the intrinsic fast path6613Node* ctrl = control();6614set_control(top()); // no regular fast path6615return ctrl;6616}6617ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();66186619Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));6620Node* cmp_instof = _gvn.transform(new (C) CmpINode(instof, intcon(1)));6621Node* bool_instof = _gvn.transform(new (C) BoolNode(cmp_instof, BoolTest::ne));66226623Node* instof_false = generate_guard(bool_instof, NULL, PROB_MIN);66246625// for encryption, we are done6626if (!decrypting)6627return instof_false; // even if it is NULL66286629// for decryption, we need to add a further check to avoid6630// taking the intrinsic path when cipher and plain are the same6631// see the original java code for why.6632RegionNode* region = new(C) RegionNode(3);6633region->init_req(1, instof_false);6634Node* src = argument(1);6635Node* dest = argument(4);6636Node* cmp_src_dest = _gvn.transform(new (C) CmpPNode(src, dest));6637Node* bool_src_dest = _gvn.transform(new (C) BoolNode(cmp_src_dest, BoolTest::eq));6638Node* src_dest_conjoint = generate_guard(bool_src_dest, NULL, PROB_MIN);6639region->init_req(2, src_dest_conjoint);66406641record_for_igvn(region);6642return _gvn.transform(region);6643}66446645//------------------------------inline_ghash_processBlocks6646bool LibraryCallKit::inline_ghash_processBlocks() {6647address stubAddr;6648const char *stubName;6649assert(UseGHASHIntrinsics, "need GHASH intrinsics support");66506651stubAddr = StubRoutines::ghash_processBlocks();6652stubName = "ghash_processBlocks";66536654Node* data = argument(0);6655Node* offset = argument(1);6656Node* len = argument(2);6657Node* state = argument(3);6658Node* subkeyH = argument(4);66596660Node* state_start = array_element_address(state, intcon(0), T_LONG);6661assert(state_start, "state is NULL");6662Node* subkeyH_start = array_element_address(subkeyH, intcon(0), T_LONG);6663assert(subkeyH_start, "subkeyH is NULL");6664Node* data_start = array_element_address(data, offset, T_BYTE);6665assert(data_start, "data is NULL");66666667Node* ghash = make_runtime_call(RC_LEAF|RC_NO_FP,6668OptoRuntime::ghash_processBlocks_Type(),6669stubAddr, stubName, TypePtr::BOTTOM,6670state_start, subkeyH_start, data_start, len);6671return true;6672}66736674//------------------------------inline_sha_implCompress-----------------------6675//6676// Calculate SHA (i.e., SHA-1) for single-block byte[] array.6677// void com.sun.security.provider.SHA.implCompress(byte[] buf, int ofs)6678//6679// Calculate SHA2 (i.e., SHA-244 or SHA-256) for single-block byte[] array.6680// void com.sun.security.provider.SHA2.implCompress(byte[] buf, int ofs)6681//6682// Calculate SHA5 (i.e., SHA-384 or SHA-512) for single-block byte[] array.6683// void com.sun.security.provider.SHA5.implCompress(byte[] buf, int ofs)6684//6685bool LibraryCallKit::inline_sha_implCompress(vmIntrinsics::ID id) {6686assert(callee()->signature()->size() == 2, "sha_implCompress has 2 parameters");66876688Node* sha_obj = argument(0);6689Node* src = argument(1); // type oop6690Node* ofs = argument(2); // type int66916692const Type* src_type = src->Value(&_gvn);6693const TypeAryPtr* top_src = src_type->isa_aryptr();6694if (top_src == NULL || top_src->klass() == NULL) {6695// failed array check6696return false;6697}6698// Figure out the size and type of the elements we will be copying.6699BasicType src_elem = src_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();6700if (src_elem != T_BYTE) {6701return false;6702}6703// 'src_start' points to src array + offset6704Node* src_start = array_element_address(src, ofs, src_elem);6705Node* state = NULL;6706address stubAddr;6707const char *stubName;67086709switch(id) {6710case vmIntrinsics::_sha_implCompress:6711assert(UseSHA1Intrinsics, "need SHA1 instruction support");6712state = get_state_from_sha_object(sha_obj);6713stubAddr = StubRoutines::sha1_implCompress();6714stubName = "sha1_implCompress";6715break;6716case vmIntrinsics::_sha2_implCompress:6717assert(UseSHA256Intrinsics, "need SHA256 instruction support");6718state = get_state_from_sha_object(sha_obj);6719stubAddr = StubRoutines::sha256_implCompress();6720stubName = "sha256_implCompress";6721break;6722case vmIntrinsics::_sha5_implCompress:6723assert(UseSHA512Intrinsics, "need SHA512 instruction support");6724state = get_state_from_sha5_object(sha_obj);6725stubAddr = StubRoutines::sha512_implCompress();6726stubName = "sha512_implCompress";6727break;6728default:6729fatal_unexpected_iid(id);6730return false;6731}6732if (state == NULL) return false;67336734// Call the stub.6735Node* call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::sha_implCompress_Type(),6736stubAddr, stubName, TypePtr::BOTTOM,6737src_start, state);67386739return true;6740}67416742//------------------------------inline_digestBase_implCompressMB-----------------------6743//6744// Calculate SHA/SHA2/SHA5 for multi-block byte[] array.6745// int com.sun.security.provider.DigestBase.implCompressMultiBlock(byte[] b, int ofs, int limit)6746//6747bool LibraryCallKit::inline_digestBase_implCompressMB(int predicate) {6748assert(UseSHA1Intrinsics || UseSHA256Intrinsics || UseSHA512Intrinsics,6749"need SHA1/SHA256/SHA512 instruction support");6750assert((uint)predicate < 3, "sanity");6751assert(callee()->signature()->size() == 3, "digestBase_implCompressMB has 3 parameters");67526753Node* digestBase_obj = argument(0); // The receiver was checked for NULL already.6754Node* src = argument(1); // byte[] array6755Node* ofs = argument(2); // type int6756Node* limit = argument(3); // type int67576758const Type* src_type = src->Value(&_gvn);6759const TypeAryPtr* top_src = src_type->isa_aryptr();6760if (top_src == NULL || top_src->klass() == NULL) {6761// failed array check6762return false;6763}6764// Figure out the size and type of the elements we will be copying.6765BasicType src_elem = src_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();6766if (src_elem != T_BYTE) {6767return false;6768}6769// 'src_start' points to src array + offset6770Node* src_start = array_element_address(src, ofs, src_elem);67716772const char* klass_SHA_name = NULL;6773const char* stub_name = NULL;6774address stub_addr = NULL;6775bool long_state = false;67766777switch (predicate) {6778case 0:6779if (UseSHA1Intrinsics) {6780klass_SHA_name = "sun/security/provider/SHA";6781stub_name = "sha1_implCompressMB";6782stub_addr = StubRoutines::sha1_implCompressMB();6783}6784break;6785case 1:6786if (UseSHA256Intrinsics) {6787klass_SHA_name = "sun/security/provider/SHA2";6788stub_name = "sha256_implCompressMB";6789stub_addr = StubRoutines::sha256_implCompressMB();6790}6791break;6792case 2:6793if (UseSHA512Intrinsics) {6794klass_SHA_name = "sun/security/provider/SHA5";6795stub_name = "sha512_implCompressMB";6796stub_addr = StubRoutines::sha512_implCompressMB();6797long_state = true;6798}6799break;6800default:6801fatal(err_msg_res("unknown SHA intrinsic predicate: %d", predicate));6802}6803if (klass_SHA_name != NULL) {6804// get DigestBase klass to lookup for SHA klass6805const TypeInstPtr* tinst = _gvn.type(digestBase_obj)->isa_instptr();6806assert(tinst != NULL, "digestBase_obj is not instance???");6807assert(tinst->klass()->is_loaded(), "DigestBase is not loaded");68086809ciKlass* klass_SHA = tinst->klass()->as_instance_klass()->find_klass(ciSymbol::make(klass_SHA_name));6810assert(klass_SHA->is_loaded(), "predicate checks that this class is loaded");6811ciInstanceKlass* instklass_SHA = klass_SHA->as_instance_klass();6812return inline_sha_implCompressMB(digestBase_obj, instklass_SHA, long_state, stub_addr, stub_name, src_start, ofs, limit);6813}6814return false;6815}6816//------------------------------inline_sha_implCompressMB-----------------------6817bool LibraryCallKit::inline_sha_implCompressMB(Node* digestBase_obj, ciInstanceKlass* instklass_SHA,6818bool long_state, address stubAddr, const char *stubName,6819Node* src_start, Node* ofs, Node* limit) {6820const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_SHA);6821const TypeOopPtr* xtype = aklass->as_instance_type();6822Node* sha_obj = new (C) CheckCastPPNode(control(), digestBase_obj, xtype);6823sha_obj = _gvn.transform(sha_obj);68246825Node* state;6826if (long_state) {6827state = get_state_from_sha5_object(sha_obj);6828} else {6829state = get_state_from_sha_object(sha_obj);6830}6831if (state == NULL) return false;68326833// Call the stub.6834Node *call;6835if (CCallingConventionRequiresIntsAsLongs) {6836call = make_runtime_call(RC_LEAF|RC_NO_FP,6837OptoRuntime::digestBase_implCompressMB_Type(),6838stubAddr, stubName, TypePtr::BOTTOM,6839src_start, state, ofs XTOP, limit XTOP);6840} else {6841call = make_runtime_call(RC_LEAF|RC_NO_FP,6842OptoRuntime::digestBase_implCompressMB_Type(),6843stubAddr, stubName, TypePtr::BOTTOM,6844src_start, state, ofs, limit);6845}6846// return ofs (int)6847Node* result = _gvn.transform(new (C) ProjNode(call, TypeFunc::Parms));6848set_result(result);68496850return true;6851}68526853//------------------------------get_state_from_sha_object-----------------------6854Node * LibraryCallKit::get_state_from_sha_object(Node *sha_object) {6855Node* sha_state = load_field_from_object(sha_object, "state", "[I", /*is_exact*/ false);6856assert (sha_state != NULL, "wrong version of sun.security.provider.SHA/SHA2");6857if (sha_state == NULL) return (Node *) NULL;68586859// now have the array, need to get the start address of the state array6860Node* state = array_element_address(sha_state, intcon(0), T_INT);6861return state;6862}68636864//------------------------------get_state_from_sha5_object-----------------------6865Node * LibraryCallKit::get_state_from_sha5_object(Node *sha_object) {6866Node* sha_state = load_field_from_object(sha_object, "state", "[J", /*is_exact*/ false);6867assert (sha_state != NULL, "wrong version of sun.security.provider.SHA5");6868if (sha_state == NULL) return (Node *) NULL;68696870// now have the array, need to get the start address of the state array6871Node* state = array_element_address(sha_state, intcon(0), T_LONG);6872return state;6873}68746875//----------------------------inline_digestBase_implCompressMB_predicate----------------------------6876// Return node representing slow path of predicate check.6877// the pseudo code we want to emulate with this predicate is:6878// if (digestBaseObj instanceof SHA/SHA2/SHA5) do_intrinsic, else do_javapath6879//6880Node* LibraryCallKit::inline_digestBase_implCompressMB_predicate(int predicate) {6881assert(UseSHA1Intrinsics || UseSHA256Intrinsics || UseSHA512Intrinsics,6882"need SHA1/SHA256/SHA512 instruction support");6883assert((uint)predicate < 3, "sanity");68846885// The receiver was checked for NULL already.6886Node* digestBaseObj = argument(0);68876888// get DigestBase klass for instanceOf check6889const TypeInstPtr* tinst = _gvn.type(digestBaseObj)->isa_instptr();6890assert(tinst != NULL, "digestBaseObj is null");6891assert(tinst->klass()->is_loaded(), "DigestBase is not loaded");68926893const char* klass_SHA_name = NULL;6894switch (predicate) {6895case 0:6896if (UseSHA1Intrinsics) {6897// we want to do an instanceof comparison against the SHA class6898klass_SHA_name = "sun/security/provider/SHA";6899}6900break;6901case 1:6902if (UseSHA256Intrinsics) {6903// we want to do an instanceof comparison against the SHA2 class6904klass_SHA_name = "sun/security/provider/SHA2";6905}6906break;6907case 2:6908if (UseSHA512Intrinsics) {6909// we want to do an instanceof comparison against the SHA5 class6910klass_SHA_name = "sun/security/provider/SHA5";6911}6912break;6913default:6914fatal(err_msg_res("unknown SHA intrinsic predicate: %d", predicate));6915}69166917ciKlass* klass_SHA = NULL;6918if (klass_SHA_name != NULL) {6919klass_SHA = tinst->klass()->as_instance_klass()->find_klass(ciSymbol::make(klass_SHA_name));6920}6921if ((klass_SHA == NULL) || !klass_SHA->is_loaded()) {6922// if none of SHA/SHA2/SHA5 is loaded, we never take the intrinsic fast path6923Node* ctrl = control();6924set_control(top()); // no intrinsic path6925return ctrl;6926}6927ciInstanceKlass* instklass_SHA = klass_SHA->as_instance_klass();69286929Node* instofSHA = gen_instanceof(digestBaseObj, makecon(TypeKlassPtr::make(instklass_SHA)));6930Node* cmp_instof = _gvn.transform(new (C) CmpINode(instofSHA, intcon(1)));6931Node* bool_instof = _gvn.transform(new (C) BoolNode(cmp_instof, BoolTest::ne));6932Node* instof_false = generate_guard(bool_instof, NULL, PROB_MIN);69336934return instof_false; // even if it is NULL6935}69366937bool LibraryCallKit::inline_profileBoolean() {6938Node* counts = argument(1);6939const TypeAryPtr* ary = NULL;6940ciArray* aobj = NULL;6941if (counts->is_Con()6942&& (ary = counts->bottom_type()->isa_aryptr()) != NULL6943&& (aobj = ary->const_oop()->as_array()) != NULL6944&& (aobj->length() == 2)) {6945// Profile is int[2] where [0] and [1] correspond to false and true value occurrences respectively.6946jint false_cnt = aobj->element_value(0).as_int();6947jint true_cnt = aobj->element_value(1).as_int();69486949if (C->log() != NULL) {6950C->log()->elem("observe source='profileBoolean' false='%d' true='%d'",6951false_cnt, true_cnt);6952}69536954if (false_cnt + true_cnt == 0) {6955// According to profile, never executed.6956uncommon_trap_exact(Deoptimization::Reason_intrinsic,6957Deoptimization::Action_reinterpret);6958return true;6959}69606961// result is a boolean (0 or 1) and its profile (false_cnt & true_cnt)6962// is a number of each value occurrences.6963Node* result = argument(0);6964if (false_cnt == 0 || true_cnt == 0) {6965// According to profile, one value has been never seen.6966int expected_val = (false_cnt == 0) ? 1 : 0;69676968Node* cmp = _gvn.transform(new (C) CmpINode(result, intcon(expected_val)));6969Node* test = _gvn.transform(new (C) BoolNode(cmp, BoolTest::eq));69706971IfNode* check = create_and_map_if(control(), test, PROB_ALWAYS, COUNT_UNKNOWN);6972Node* fast_path = _gvn.transform(new (C) IfTrueNode(check));6973Node* slow_path = _gvn.transform(new (C) IfFalseNode(check));69746975{ // Slow path: uncommon trap for never seen value and then reexecute6976// MethodHandleImpl::profileBoolean() to bump the count, so JIT knows6977// the value has been seen at least once.6978PreserveJVMState pjvms(this);6979PreserveReexecuteState preexecs(this);6980jvms()->set_should_reexecute(true);69816982set_control(slow_path);6983set_i_o(i_o());69846985uncommon_trap_exact(Deoptimization::Reason_intrinsic,6986Deoptimization::Action_reinterpret);6987}6988// The guard for never seen value enables sharpening of the result and6989// returning a constant. It allows to eliminate branches on the same value6990// later on.6991set_control(fast_path);6992result = intcon(expected_val);6993}6994// Stop profiling.6995// MethodHandleImpl::profileBoolean() has profiling logic in its bytecode.6996// By replacing method body with profile data (represented as ProfileBooleanNode6997// on IR level) we effectively disable profiling.6998// It enables full speed execution once optimized code is generated.6999Node* profile = _gvn.transform(new (C) ProfileBooleanNode(result, false_cnt, true_cnt));7000C->record_for_igvn(profile);7001set_result(profile);7002return true;7003} else {7004// Continue profiling.7005// Profile data isn't available at the moment. So, execute method's bytecode version.7006// Usually, when GWT LambdaForms are profiled it means that a stand-alone nmethod7007// is compiled and counters aren't available since corresponding MethodHandle7008// isn't a compile-time constant.7009return false;7010}7011}701270137014