Path: blob/jdk8u272-b10-aarch32-20201026/hotspot/src/share/vm/opto/graphKit.cpp
83404 views
/*1* Copyright (c) 2001, 2015, 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 "compiler/compileLog.hpp"26#include "gc_implementation/g1/g1SATBCardTableModRefBS.hpp"27#include "gc_implementation/g1/heapRegion.hpp"28#include "gc_interface/collectedHeap.hpp"29#include "memory/barrierSet.hpp"30#include "memory/cardTableModRefBS.hpp"31#include "opto/addnode.hpp"32#include "opto/graphKit.hpp"33#include "opto/idealKit.hpp"34#include "opto/locknode.hpp"35#include "opto/machnode.hpp"36#include "opto/parse.hpp"37#include "opto/rootnode.hpp"38#include "opto/runtime.hpp"39#include "runtime/deoptimization.hpp"40#include "runtime/sharedRuntime.hpp"4142//----------------------------GraphKit-----------------------------------------43// Main utility constructor.44GraphKit::GraphKit(JVMState* jvms)45: Phase(Phase::Parser),46_env(C->env()),47_gvn(*C->initial_gvn())48{49_exceptions = jvms->map()->next_exception();50if (_exceptions != NULL) jvms->map()->set_next_exception(NULL);51set_jvms(jvms);52}5354// Private constructor for parser.55GraphKit::GraphKit()56: Phase(Phase::Parser),57_env(C->env()),58_gvn(*C->initial_gvn())59{60_exceptions = NULL;61set_map(NULL);62debug_only(_sp = -99);63debug_only(set_bci(-99));64}65666768//---------------------------clean_stack---------------------------------------69// Clear away rubbish from the stack area of the JVM state.70// This destroys any arguments that may be waiting on the stack.71void GraphKit::clean_stack(int from_sp) {72SafePointNode* map = this->map();73JVMState* jvms = this->jvms();74int stk_size = jvms->stk_size();75int stkoff = jvms->stkoff();76Node* top = this->top();77for (int i = from_sp; i < stk_size; i++) {78if (map->in(stkoff + i) != top) {79map->set_req(stkoff + i, top);80}81}82}838485//--------------------------------sync_jvms-----------------------------------86// Make sure our current jvms agrees with our parse state.87JVMState* GraphKit::sync_jvms() const {88JVMState* jvms = this->jvms();89jvms->set_bci(bci()); // Record the new bci in the JVMState90jvms->set_sp(sp()); // Record the new sp in the JVMState91assert(jvms_in_sync(), "jvms is now in sync");92return jvms;93}9495//--------------------------------sync_jvms_for_reexecute---------------------96// Make sure our current jvms agrees with our parse state. This version97// uses the reexecute_sp for reexecuting bytecodes.98JVMState* GraphKit::sync_jvms_for_reexecute() {99JVMState* jvms = this->jvms();100jvms->set_bci(bci()); // Record the new bci in the JVMState101jvms->set_sp(reexecute_sp()); // Record the new sp in the JVMState102return jvms;103}104105#ifdef ASSERT106bool GraphKit::jvms_in_sync() const {107Parse* parse = is_Parse();108if (parse == NULL) {109if (bci() != jvms()->bci()) return false;110if (sp() != (int)jvms()->sp()) return false;111return true;112}113if (jvms()->method() != parse->method()) return false;114if (jvms()->bci() != parse->bci()) return false;115int jvms_sp = jvms()->sp();116if (jvms_sp != parse->sp()) return false;117int jvms_depth = jvms()->depth();118if (jvms_depth != parse->depth()) return false;119return true;120}121122// Local helper checks for special internal merge points123// used to accumulate and merge exception states.124// They are marked by the region's in(0) edge being the map itself.125// Such merge points must never "escape" into the parser at large,126// until they have been handed to gvn.transform.127static bool is_hidden_merge(Node* reg) {128if (reg == NULL) return false;129if (reg->is_Phi()) {130reg = reg->in(0);131if (reg == NULL) return false;132}133return reg->is_Region() && reg->in(0) != NULL && reg->in(0)->is_Root();134}135136void GraphKit::verify_map() const {137if (map() == NULL) return; // null map is OK138assert(map()->req() <= jvms()->endoff(), "no extra garbage on map");139assert(!map()->has_exceptions(), "call add_exception_states_from 1st");140assert(!is_hidden_merge(control()), "call use_exception_state, not set_map");141}142143void GraphKit::verify_exception_state(SafePointNode* ex_map) {144assert(ex_map->next_exception() == NULL, "not already part of a chain");145assert(has_saved_ex_oop(ex_map), "every exception state has an ex_oop");146}147#endif148149//---------------------------stop_and_kill_map---------------------------------150// Set _map to NULL, signalling a stop to further bytecode execution.151// First smash the current map's control to a constant, to mark it dead.152void GraphKit::stop_and_kill_map() {153SafePointNode* dead_map = stop();154if (dead_map != NULL) {155dead_map->disconnect_inputs(NULL, C); // Mark the map as killed.156assert(dead_map->is_killed(), "must be so marked");157}158}159160161//--------------------------------stopped--------------------------------------162// Tell if _map is NULL, or control is top.163bool GraphKit::stopped() {164if (map() == NULL) return true;165else if (control() == top()) return true;166else return false;167}168169170//-----------------------------has_ex_handler----------------------------------171// Tell if this method or any caller method has exception handlers.172bool GraphKit::has_ex_handler() {173for (JVMState* jvmsp = jvms(); jvmsp != NULL; jvmsp = jvmsp->caller()) {174if (jvmsp->has_method() && jvmsp->method()->has_exception_handlers()) {175return true;176}177}178return false;179}180181//------------------------------save_ex_oop------------------------------------182// Save an exception without blowing stack contents or other JVM state.183void GraphKit::set_saved_ex_oop(SafePointNode* ex_map, Node* ex_oop) {184assert(!has_saved_ex_oop(ex_map), "clear ex-oop before setting again");185ex_map->add_req(ex_oop);186debug_only(verify_exception_state(ex_map));187}188189inline static Node* common_saved_ex_oop(SafePointNode* ex_map, bool clear_it) {190assert(GraphKit::has_saved_ex_oop(ex_map), "ex_oop must be there");191Node* ex_oop = ex_map->in(ex_map->req()-1);192if (clear_it) ex_map->del_req(ex_map->req()-1);193return ex_oop;194}195196//-----------------------------saved_ex_oop------------------------------------197// Recover a saved exception from its map.198Node* GraphKit::saved_ex_oop(SafePointNode* ex_map) {199return common_saved_ex_oop(ex_map, false);200}201202//--------------------------clear_saved_ex_oop---------------------------------203// Erase a previously saved exception from its map.204Node* GraphKit::clear_saved_ex_oop(SafePointNode* ex_map) {205return common_saved_ex_oop(ex_map, true);206}207208#ifdef ASSERT209//---------------------------has_saved_ex_oop----------------------------------210// Erase a previously saved exception from its map.211bool GraphKit::has_saved_ex_oop(SafePointNode* ex_map) {212return ex_map->req() == ex_map->jvms()->endoff()+1;213}214#endif215216//-------------------------make_exception_state--------------------------------217// Turn the current JVM state into an exception state, appending the ex_oop.218SafePointNode* GraphKit::make_exception_state(Node* ex_oop) {219sync_jvms();220SafePointNode* ex_map = stop(); // do not manipulate this map any more221set_saved_ex_oop(ex_map, ex_oop);222return ex_map;223}224225226//--------------------------add_exception_state--------------------------------227// Add an exception to my list of exceptions.228void GraphKit::add_exception_state(SafePointNode* ex_map) {229if (ex_map == NULL || ex_map->control() == top()) {230return;231}232#ifdef ASSERT233verify_exception_state(ex_map);234if (has_exceptions()) {235assert(ex_map->jvms()->same_calls_as(_exceptions->jvms()), "all collected exceptions must come from the same place");236}237#endif238239// If there is already an exception of exactly this type, merge with it.240// In particular, null-checks and other low-level exceptions common up here.241Node* ex_oop = saved_ex_oop(ex_map);242const Type* ex_type = _gvn.type(ex_oop);243if (ex_oop == top()) {244// No action needed.245return;246}247assert(ex_type->isa_instptr(), "exception must be an instance");248for (SafePointNode* e2 = _exceptions; e2 != NULL; e2 = e2->next_exception()) {249const Type* ex_type2 = _gvn.type(saved_ex_oop(e2));250// We check sp also because call bytecodes can generate exceptions251// both before and after arguments are popped!252if (ex_type2 == ex_type253&& e2->_jvms->sp() == ex_map->_jvms->sp()) {254combine_exception_states(ex_map, e2);255return;256}257}258259// No pre-existing exception of the same type. Chain it on the list.260push_exception_state(ex_map);261}262263//-----------------------add_exception_states_from-----------------------------264void GraphKit::add_exception_states_from(JVMState* jvms) {265SafePointNode* ex_map = jvms->map()->next_exception();266if (ex_map != NULL) {267jvms->map()->set_next_exception(NULL);268for (SafePointNode* next_map; ex_map != NULL; ex_map = next_map) {269next_map = ex_map->next_exception();270ex_map->set_next_exception(NULL);271add_exception_state(ex_map);272}273}274}275276//-----------------------transfer_exceptions_into_jvms-------------------------277JVMState* GraphKit::transfer_exceptions_into_jvms() {278if (map() == NULL) {279// We need a JVMS to carry the exceptions, but the map has gone away.280// Create a scratch JVMS, cloned from any of the exception states...281if (has_exceptions()) {282_map = _exceptions;283_map = clone_map();284_map->set_next_exception(NULL);285clear_saved_ex_oop(_map);286debug_only(verify_map());287} else {288// ...or created from scratch289JVMState* jvms = new (C) JVMState(_method, NULL);290jvms->set_bci(_bci);291jvms->set_sp(_sp);292jvms->set_map(new (C) SafePointNode(TypeFunc::Parms, jvms));293set_jvms(jvms);294for (uint i = 0; i < map()->req(); i++) map()->init_req(i, top());295set_all_memory(top());296while (map()->req() < jvms->endoff()) map()->add_req(top());297}298// (This is a kludge, in case you didn't notice.)299set_control(top());300}301JVMState* jvms = sync_jvms();302assert(!jvms->map()->has_exceptions(), "no exceptions on this map yet");303jvms->map()->set_next_exception(_exceptions);304_exceptions = NULL; // done with this set of exceptions305return jvms;306}307308static inline void add_n_reqs(Node* dstphi, Node* srcphi) {309assert(is_hidden_merge(dstphi), "must be a special merge node");310assert(is_hidden_merge(srcphi), "must be a special merge node");311uint limit = srcphi->req();312for (uint i = PhiNode::Input; i < limit; i++) {313dstphi->add_req(srcphi->in(i));314}315}316static inline void add_one_req(Node* dstphi, Node* src) {317assert(is_hidden_merge(dstphi), "must be a special merge node");318assert(!is_hidden_merge(src), "must not be a special merge node");319dstphi->add_req(src);320}321322//-----------------------combine_exception_states------------------------------323// This helper function combines exception states by building phis on a324// specially marked state-merging region. These regions and phis are325// untransformed, and can build up gradually. The region is marked by326// having a control input of its exception map, rather than NULL. Such327// regions do not appear except in this function, and in use_exception_state.328void GraphKit::combine_exception_states(SafePointNode* ex_map, SafePointNode* phi_map) {329if (failing()) return; // dying anyway...330JVMState* ex_jvms = ex_map->_jvms;331assert(ex_jvms->same_calls_as(phi_map->_jvms), "consistent call chains");332assert(ex_jvms->stkoff() == phi_map->_jvms->stkoff(), "matching locals");333assert(ex_jvms->sp() == phi_map->_jvms->sp(), "matching stack sizes");334assert(ex_jvms->monoff() == phi_map->_jvms->monoff(), "matching JVMS");335assert(ex_jvms->scloff() == phi_map->_jvms->scloff(), "matching scalar replaced objects");336assert(ex_map->req() == phi_map->req(), "matching maps");337uint tos = ex_jvms->stkoff() + ex_jvms->sp();338Node* hidden_merge_mark = root();339Node* region = phi_map->control();340MergeMemNode* phi_mem = phi_map->merged_memory();341MergeMemNode* ex_mem = ex_map->merged_memory();342if (region->in(0) != hidden_merge_mark) {343// The control input is not (yet) a specially-marked region in phi_map.344// Make it so, and build some phis.345region = new (C) RegionNode(2);346_gvn.set_type(region, Type::CONTROL);347region->set_req(0, hidden_merge_mark); // marks an internal ex-state348region->init_req(1, phi_map->control());349phi_map->set_control(region);350Node* io_phi = PhiNode::make(region, phi_map->i_o(), Type::ABIO);351record_for_igvn(io_phi);352_gvn.set_type(io_phi, Type::ABIO);353phi_map->set_i_o(io_phi);354for (MergeMemStream mms(phi_mem); mms.next_non_empty(); ) {355Node* m = mms.memory();356Node* m_phi = PhiNode::make(region, m, Type::MEMORY, mms.adr_type(C));357record_for_igvn(m_phi);358_gvn.set_type(m_phi, Type::MEMORY);359mms.set_memory(m_phi);360}361}362363// Either or both of phi_map and ex_map might already be converted into phis.364Node* ex_control = ex_map->control();365// if there is special marking on ex_map also, we add multiple edges from src366bool add_multiple = (ex_control->in(0) == hidden_merge_mark);367// how wide was the destination phi_map, originally?368uint orig_width = region->req();369370if (add_multiple) {371add_n_reqs(region, ex_control);372add_n_reqs(phi_map->i_o(), ex_map->i_o());373} else {374// ex_map has no merges, so we just add single edges everywhere375add_one_req(region, ex_control);376add_one_req(phi_map->i_o(), ex_map->i_o());377}378for (MergeMemStream mms(phi_mem, ex_mem); mms.next_non_empty2(); ) {379if (mms.is_empty()) {380// get a copy of the base memory, and patch some inputs into it381const TypePtr* adr_type = mms.adr_type(C);382Node* phi = mms.force_memory()->as_Phi()->slice_memory(adr_type);383assert(phi->as_Phi()->region() == mms.base_memory()->in(0), "");384mms.set_memory(phi);385// Prepare to append interesting stuff onto the newly sliced phi:386while (phi->req() > orig_width) phi->del_req(phi->req()-1);387}388// Append stuff from ex_map:389if (add_multiple) {390add_n_reqs(mms.memory(), mms.memory2());391} else {392add_one_req(mms.memory(), mms.memory2());393}394}395uint limit = ex_map->req();396for (uint i = TypeFunc::Parms; i < limit; i++) {397// Skip everything in the JVMS after tos. (The ex_oop follows.)398if (i == tos) i = ex_jvms->monoff();399Node* src = ex_map->in(i);400Node* dst = phi_map->in(i);401if (src != dst) {402PhiNode* phi;403if (dst->in(0) != region) {404dst = phi = PhiNode::make(region, dst, _gvn.type(dst));405record_for_igvn(phi);406_gvn.set_type(phi, phi->type());407phi_map->set_req(i, dst);408// Prepare to append interesting stuff onto the new phi:409while (dst->req() > orig_width) dst->del_req(dst->req()-1);410} else {411assert(dst->is_Phi(), "nobody else uses a hidden region");412phi = dst->as_Phi();413}414if (add_multiple && src->in(0) == ex_control) {415// Both are phis.416add_n_reqs(dst, src);417} else {418while (dst->req() < region->req()) add_one_req(dst, src);419}420const Type* srctype = _gvn.type(src);421if (phi->type() != srctype) {422const Type* dsttype = phi->type()->meet_speculative(srctype);423if (phi->type() != dsttype) {424phi->set_type(dsttype);425_gvn.set_type(phi, dsttype);426}427}428}429}430phi_map->merge_replaced_nodes_with(ex_map);431}432433//--------------------------use_exception_state--------------------------------434Node* GraphKit::use_exception_state(SafePointNode* phi_map) {435if (failing()) { stop(); return top(); }436Node* region = phi_map->control();437Node* hidden_merge_mark = root();438assert(phi_map->jvms()->map() == phi_map, "sanity: 1-1 relation");439Node* ex_oop = clear_saved_ex_oop(phi_map);440if (region->in(0) == hidden_merge_mark) {441// Special marking for internal ex-states. Process the phis now.442region->set_req(0, region); // now it's an ordinary region443set_jvms(phi_map->jvms()); // ...so now we can use it as a map444// Note: Setting the jvms also sets the bci and sp.445set_control(_gvn.transform(region));446uint tos = jvms()->stkoff() + sp();447for (uint i = 1; i < tos; i++) {448Node* x = phi_map->in(i);449if (x->in(0) == region) {450assert(x->is_Phi(), "expected a special phi");451phi_map->set_req(i, _gvn.transform(x));452}453}454for (MergeMemStream mms(merged_memory()); mms.next_non_empty(); ) {455Node* x = mms.memory();456if (x->in(0) == region) {457assert(x->is_Phi(), "nobody else uses a hidden region");458mms.set_memory(_gvn.transform(x));459}460}461if (ex_oop->in(0) == region) {462assert(ex_oop->is_Phi(), "expected a special phi");463ex_oop = _gvn.transform(ex_oop);464}465} else {466set_jvms(phi_map->jvms());467}468469assert(!is_hidden_merge(phi_map->control()), "hidden ex. states cleared");470assert(!is_hidden_merge(phi_map->i_o()), "hidden ex. states cleared");471return ex_oop;472}473474//---------------------------------java_bc-------------------------------------475Bytecodes::Code GraphKit::java_bc() const {476ciMethod* method = this->method();477int bci = this->bci();478if (method != NULL && bci != InvocationEntryBci)479return method->java_code_at_bci(bci);480else481return Bytecodes::_illegal;482}483484void GraphKit::uncommon_trap_if_should_post_on_exceptions(Deoptimization::DeoptReason reason,485bool must_throw) {486// if the exception capability is set, then we will generate code487// to check the JavaThread.should_post_on_exceptions flag to see488// if we actually need to report exception events (for this489// thread). If we don't need to report exception events, we will490// take the normal fast path provided by add_exception_events. If491// exception event reporting is enabled for this thread, we will492// take the uncommon_trap in the BuildCutout below.493494// first must access the should_post_on_exceptions_flag in this thread's JavaThread495Node* jthread = _gvn.transform(new (C) ThreadLocalNode());496Node* adr = basic_plus_adr(top(), jthread, in_bytes(JavaThread::should_post_on_exceptions_flag_offset()));497Node* should_post_flag = make_load(control(), adr, TypeInt::INT, T_INT, Compile::AliasIdxRaw, MemNode::unordered);498499// Test the should_post_on_exceptions_flag vs. 0500Node* chk = _gvn.transform( new (C) CmpINode(should_post_flag, intcon(0)) );501Node* tst = _gvn.transform( new (C) BoolNode(chk, BoolTest::eq) );502503// Branch to slow_path if should_post_on_exceptions_flag was true504{ BuildCutout unless(this, tst, PROB_MAX);505// Do not try anything fancy if we're notifying the VM on every throw.506// Cf. case Bytecodes::_athrow in parse2.cpp.507uncommon_trap(reason, Deoptimization::Action_none,508(ciKlass*)NULL, (char*)NULL, must_throw);509}510511}512513//------------------------------builtin_throw----------------------------------514void GraphKit::builtin_throw(Deoptimization::DeoptReason reason, Node* arg) {515bool must_throw = true;516517if (env()->jvmti_can_post_on_exceptions()) {518// check if we must post exception events, take uncommon trap if so519uncommon_trap_if_should_post_on_exceptions(reason, must_throw);520// here if should_post_on_exceptions is false521// continue on with the normal codegen522}523524// If this particular condition has not yet happened at this525// bytecode, then use the uncommon trap mechanism, and allow for526// a future recompilation if several traps occur here.527// If the throw is hot, try to use a more complicated inline mechanism528// which keeps execution inside the compiled code.529bool treat_throw_as_hot = false;530ciMethodData* md = method()->method_data();531532if (ProfileTraps) {533if (too_many_traps(reason)) {534treat_throw_as_hot = true;535}536// (If there is no MDO at all, assume it is early in537// execution, and that any deopts are part of the538// startup transient, and don't need to be remembered.)539540// Also, if there is a local exception handler, treat all throws541// as hot if there has been at least one in this method.542if (C->trap_count(reason) != 0543&& method()->method_data()->trap_count(reason) != 0544&& has_ex_handler()) {545treat_throw_as_hot = true;546}547}548549// If this throw happens frequently, an uncommon trap might cause550// a performance pothole. If there is a local exception handler,551// and if this particular bytecode appears to be deoptimizing often,552// let us handle the throw inline, with a preconstructed instance.553// Note: If the deopt count has blown up, the uncommon trap554// runtime is going to flush this nmethod, not matter what.555if (treat_throw_as_hot556&& (!StackTraceInThrowable || OmitStackTraceInFastThrow)) {557// If the throw is local, we use a pre-existing instance and558// punt on the backtrace. This would lead to a missing backtrace559// (a repeat of 4292742) if the backtrace object is ever asked560// for its backtrace.561// Fixing this remaining case of 4292742 requires some flavor of562// escape analysis. Leave that for the future.563ciInstance* ex_obj = NULL;564switch (reason) {565case Deoptimization::Reason_null_check:566ex_obj = env()->NullPointerException_instance();567break;568case Deoptimization::Reason_div0_check:569ex_obj = env()->ArithmeticException_instance();570break;571case Deoptimization::Reason_range_check:572ex_obj = env()->ArrayIndexOutOfBoundsException_instance();573break;574case Deoptimization::Reason_class_check:575if (java_bc() == Bytecodes::_aastore) {576ex_obj = env()->ArrayStoreException_instance();577} else {578ex_obj = env()->ClassCastException_instance();579}580break;581}582if (failing()) { stop(); return; } // exception allocation might fail583if (ex_obj != NULL) {584// Cheat with a preallocated exception object.585if (C->log() != NULL)586C->log()->elem("hot_throw preallocated='1' reason='%s'",587Deoptimization::trap_reason_name(reason));588const TypeInstPtr* ex_con = TypeInstPtr::make(ex_obj);589Node* ex_node = _gvn.transform( ConNode::make(C, ex_con) );590591// Clear the detail message of the preallocated exception object.592// Weblogic sometimes mutates the detail message of exceptions593// using reflection.594int offset = java_lang_Throwable::get_detailMessage_offset();595const TypePtr* adr_typ = ex_con->add_offset(offset);596597Node *adr = basic_plus_adr(ex_node, ex_node, offset);598const TypeOopPtr* val_type = TypeOopPtr::make_from_klass(env()->String_klass());599// Conservatively release stores of object references.600Node *store = store_oop_to_object(control(), ex_node, adr, adr_typ, null(), val_type, T_OBJECT, MemNode::release);601602add_exception_state(make_exception_state(ex_node));603return;604}605}606607// %%% Maybe add entry to OptoRuntime which directly throws the exc.?608// It won't be much cheaper than bailing to the interp., since we'll609// have to pass up all the debug-info, and the runtime will have to610// create the stack trace.611612// Usual case: Bail to interpreter.613// Reserve the right to recompile if we haven't seen anything yet.614615assert(!Deoptimization::reason_is_speculate(reason), "unsupported");616Deoptimization::DeoptAction action = Deoptimization::Action_maybe_recompile;617if (treat_throw_as_hot618&& (method()->method_data()->trap_recompiled_at(bci(), NULL)619|| C->too_many_traps(reason))) {620// We cannot afford to take more traps here. Suffer in the interpreter.621if (C->log() != NULL)622C->log()->elem("hot_throw preallocated='0' reason='%s' mcount='%d'",623Deoptimization::trap_reason_name(reason),624C->trap_count(reason));625action = Deoptimization::Action_none;626}627628// "must_throw" prunes the JVM state to include only the stack, if there629// are no local exception handlers. This should cut down on register630// allocation time and code size, by drastically reducing the number631// of in-edges on the call to the uncommon trap.632633uncommon_trap(reason, action, (ciKlass*)NULL, (char*)NULL, must_throw);634}635636637//----------------------------PreserveJVMState---------------------------------638PreserveJVMState::PreserveJVMState(GraphKit* kit, bool clone_map) {639debug_only(kit->verify_map());640_kit = kit;641_map = kit->map(); // preserve the map642_sp = kit->sp();643kit->set_map(clone_map ? kit->clone_map() : NULL);644#ifdef ASSERT645_bci = kit->bci();646Parse* parser = kit->is_Parse();647int block = (parser == NULL || parser->block() == NULL) ? -1 : parser->block()->rpo();648_block = block;649#endif650}651PreserveJVMState::~PreserveJVMState() {652GraphKit* kit = _kit;653#ifdef ASSERT654assert(kit->bci() == _bci, "bci must not shift");655Parse* parser = kit->is_Parse();656int block = (parser == NULL || parser->block() == NULL) ? -1 : parser->block()->rpo();657assert(block == _block, "block must not shift");658#endif659kit->set_map(_map);660kit->set_sp(_sp);661}662663664//-----------------------------BuildCutout-------------------------------------665BuildCutout::BuildCutout(GraphKit* kit, Node* p, float prob, float cnt)666: PreserveJVMState(kit)667{668assert(p->is_Con() || p->is_Bool(), "test must be a bool");669SafePointNode* outer_map = _map; // preserved map is caller's670SafePointNode* inner_map = kit->map();671IfNode* iff = kit->create_and_map_if(outer_map->control(), p, prob, cnt);672outer_map->set_control(kit->gvn().transform( new (kit->C) IfTrueNode(iff) ));673inner_map->set_control(kit->gvn().transform( new (kit->C) IfFalseNode(iff) ));674}675BuildCutout::~BuildCutout() {676GraphKit* kit = _kit;677assert(kit->stopped(), "cutout code must stop, throw, return, etc.");678}679680//---------------------------PreserveReexecuteState----------------------------681PreserveReexecuteState::PreserveReexecuteState(GraphKit* kit) {682assert(!kit->stopped(), "must call stopped() before");683_kit = kit;684_sp = kit->sp();685_reexecute = kit->jvms()->_reexecute;686}687PreserveReexecuteState::~PreserveReexecuteState() {688if (_kit->stopped()) return;689_kit->jvms()->_reexecute = _reexecute;690_kit->set_sp(_sp);691}692693//------------------------------clone_map--------------------------------------694// Implementation of PreserveJVMState695//696// Only clone_map(...) here. If this function is only used in the697// PreserveJVMState class we may want to get rid of this extra698// function eventually and do it all there.699700SafePointNode* GraphKit::clone_map() {701if (map() == NULL) return NULL;702703// Clone the memory edge first704Node* mem = MergeMemNode::make(C, map()->memory());705gvn().set_type_bottom(mem);706707SafePointNode *clonemap = (SafePointNode*)map()->clone();708JVMState* jvms = this->jvms();709JVMState* clonejvms = jvms->clone_shallow(C);710clonemap->set_memory(mem);711clonemap->set_jvms(clonejvms);712clonejvms->set_map(clonemap);713record_for_igvn(clonemap);714gvn().set_type_bottom(clonemap);715return clonemap;716}717718719//-----------------------------set_map_clone-----------------------------------720void GraphKit::set_map_clone(SafePointNode* m) {721_map = m;722_map = clone_map();723_map->set_next_exception(NULL);724debug_only(verify_map());725}726727728//----------------------------kill_dead_locals---------------------------------729// Detect any locals which are known to be dead, and force them to top.730void GraphKit::kill_dead_locals() {731// Consult the liveness information for the locals. If any732// of them are unused, then they can be replaced by top(). This733// should help register allocation time and cut down on the size734// of the deoptimization information.735736// This call is made from many of the bytecode handling737// subroutines called from the Big Switch in do_one_bytecode.738// Every bytecode which might include a slow path is responsible739// for killing its dead locals. The more consistent we740// are about killing deads, the fewer useless phis will be741// constructed for them at various merge points.742743// bci can be -1 (InvocationEntryBci). We return the entry744// liveness for the method.745746if (method() == NULL || method()->code_size() == 0) {747// We are building a graph for a call to a native method.748// All locals are live.749return;750}751752ResourceMark rm;753754// Consult the liveness information for the locals. If any755// of them are unused, then they can be replaced by top(). This756// should help register allocation time and cut down on the size757// of the deoptimization information.758MethodLivenessResult live_locals = method()->liveness_at_bci(bci());759760int len = (int)live_locals.size();761assert(len <= jvms()->loc_size(), "too many live locals");762for (int local = 0; local < len; local++) {763if (!live_locals.at(local)) {764set_local(local, top());765}766}767}768769#ifdef ASSERT770//-------------------------dead_locals_are_killed------------------------------771// Return true if all dead locals are set to top in the map.772// Used to assert "clean" debug info at various points.773bool GraphKit::dead_locals_are_killed() {774if (method() == NULL || method()->code_size() == 0) {775// No locals need to be dead, so all is as it should be.776return true;777}778779// Make sure somebody called kill_dead_locals upstream.780ResourceMark rm;781for (JVMState* jvms = this->jvms(); jvms != NULL; jvms = jvms->caller()) {782if (jvms->loc_size() == 0) continue; // no locals to consult783SafePointNode* map = jvms->map();784ciMethod* method = jvms->method();785int bci = jvms->bci();786if (jvms == this->jvms()) {787bci = this->bci(); // it might not yet be synched788}789MethodLivenessResult live_locals = method->liveness_at_bci(bci);790int len = (int)live_locals.size();791if (!live_locals.is_valid() || len == 0)792// This method is trivial, or is poisoned by a breakpoint.793return true;794assert(len == jvms->loc_size(), "live map consistent with locals map");795for (int local = 0; local < len; local++) {796if (!live_locals.at(local) && map->local(jvms, local) != top()) {797if (PrintMiscellaneous && (Verbose || WizardMode)) {798tty->print_cr("Zombie local %d: ", local);799jvms->dump();800}801return false;802}803}804}805return true;806}807808#endif //ASSERT809810// Helper function for enforcing certain bytecodes to reexecute if811// deoptimization happens812static bool should_reexecute_implied_by_bytecode(JVMState *jvms, bool is_anewarray) {813ciMethod* cur_method = jvms->method();814int cur_bci = jvms->bci();815if (cur_method != NULL && cur_bci != InvocationEntryBci) {816Bytecodes::Code code = cur_method->java_code_at_bci(cur_bci);817return Interpreter::bytecode_should_reexecute(code) ||818is_anewarray && code == Bytecodes::_multianewarray;819// Reexecute _multianewarray bytecode which was replaced with820// sequence of [a]newarray. See Parse::do_multianewarray().821//822// Note: interpreter should not have it set since this optimization823// is limited by dimensions and guarded by flag so in some cases824// multianewarray() runtime calls will be generated and825// the bytecode should not be reexecutes (stack will not be reset).826} else827return false;828}829830// Helper function for adding JVMState and debug information to node831void GraphKit::add_safepoint_edges(SafePointNode* call, bool must_throw) {832// Add the safepoint edges to the call (or other safepoint).833834// Make sure dead locals are set to top. This835// should help register allocation time and cut down on the size836// of the deoptimization information.837assert(dead_locals_are_killed(), "garbage in debug info before safepoint");838839// Walk the inline list to fill in the correct set of JVMState's840// Also fill in the associated edges for each JVMState.841842// If the bytecode needs to be reexecuted we need to put843// the arguments back on the stack.844const bool should_reexecute = jvms()->should_reexecute();845JVMState* youngest_jvms = should_reexecute ? sync_jvms_for_reexecute() : sync_jvms();846847// NOTE: set_bci (called from sync_jvms) might reset the reexecute bit to848// undefined if the bci is different. This is normal for Parse but it849// should not happen for LibraryCallKit because only one bci is processed.850assert(!is_LibraryCallKit() || (jvms()->should_reexecute() == should_reexecute),851"in LibraryCallKit the reexecute bit should not change");852853// If we are guaranteed to throw, we can prune everything but the854// input to the current bytecode.855bool can_prune_locals = false;856uint stack_slots_not_pruned = 0;857int inputs = 0, depth = 0;858if (must_throw) {859assert(method() == youngest_jvms->method(), "sanity");860if (compute_stack_effects(inputs, depth)) {861can_prune_locals = true;862stack_slots_not_pruned = inputs;863}864}865866if (env()->should_retain_local_variables()) {867// At any safepoint, this method can get breakpointed, which would868// then require an immediate deoptimization.869can_prune_locals = false; // do not prune locals870stack_slots_not_pruned = 0;871}872873// do not scribble on the input jvms874JVMState* out_jvms = youngest_jvms->clone_deep(C);875call->set_jvms(out_jvms); // Start jvms list for call node876877// For a known set of bytecodes, the interpreter should reexecute them if878// deoptimization happens. We set the reexecute state for them here879if (out_jvms->is_reexecute_undefined() && //don't change if already specified880should_reexecute_implied_by_bytecode(out_jvms, call->is_AllocateArray())) {881out_jvms->set_should_reexecute(true); //NOTE: youngest_jvms not changed882}883884// Presize the call:885DEBUG_ONLY(uint non_debug_edges = call->req());886call->add_req_batch(top(), youngest_jvms->debug_depth());887assert(call->req() == non_debug_edges + youngest_jvms->debug_depth(), "");888889// Set up edges so that the call looks like this:890// Call [state:] ctl io mem fptr retadr891// [parms:] parm0 ... parmN892// [root:] loc0 ... locN stk0 ... stkSP mon0 obj0 ... monN objN893// [...mid:] loc0 ... locN stk0 ... stkSP mon0 obj0 ... monN objN [...]894// [young:] loc0 ... locN stk0 ... stkSP mon0 obj0 ... monN objN895// Note that caller debug info precedes callee debug info.896897// Fill pointer walks backwards from "young:" to "root:" in the diagram above:898uint debug_ptr = call->req();899900// Loop over the map input edges associated with jvms, add them901// to the call node, & reset all offsets to match call node array.902for (JVMState* in_jvms = youngest_jvms; in_jvms != NULL; ) {903uint debug_end = debug_ptr;904uint debug_start = debug_ptr - in_jvms->debug_size();905debug_ptr = debug_start; // back up the ptr906907uint p = debug_start; // walks forward in [debug_start, debug_end)908uint j, k, l;909SafePointNode* in_map = in_jvms->map();910out_jvms->set_map(call);911912if (can_prune_locals) {913assert(in_jvms->method() == out_jvms->method(), "sanity");914// If the current throw can reach an exception handler in this JVMS,915// then we must keep everything live that can reach that handler.916// As a quick and dirty approximation, we look for any handlers at all.917if (in_jvms->method()->has_exception_handlers()) {918can_prune_locals = false;919}920}921922// Add the Locals923k = in_jvms->locoff();924l = in_jvms->loc_size();925out_jvms->set_locoff(p);926if (!can_prune_locals) {927for (j = 0; j < l; j++)928call->set_req(p++, in_map->in(k+j));929} else {930p += l; // already set to top above by add_req_batch931}932933// Add the Expression Stack934k = in_jvms->stkoff();935l = in_jvms->sp();936out_jvms->set_stkoff(p);937if (!can_prune_locals) {938for (j = 0; j < l; j++)939call->set_req(p++, in_map->in(k+j));940} else if (can_prune_locals && stack_slots_not_pruned != 0) {941// Divide stack into {S0,...,S1}, where S0 is set to top.942uint s1 = stack_slots_not_pruned;943stack_slots_not_pruned = 0; // for next iteration944if (s1 > l) s1 = l;945uint s0 = l - s1;946p += s0; // skip the tops preinstalled by add_req_batch947for (j = s0; j < l; j++)948call->set_req(p++, in_map->in(k+j));949} else {950p += l; // already set to top above by add_req_batch951}952953// Add the Monitors954k = in_jvms->monoff();955l = in_jvms->mon_size();956out_jvms->set_monoff(p);957for (j = 0; j < l; j++)958call->set_req(p++, in_map->in(k+j));959960// Copy any scalar object fields.961k = in_jvms->scloff();962l = in_jvms->scl_size();963out_jvms->set_scloff(p);964for (j = 0; j < l; j++)965call->set_req(p++, in_map->in(k+j));966967// Finish the new jvms.968out_jvms->set_endoff(p);969970assert(out_jvms->endoff() == debug_end, "fill ptr must match");971assert(out_jvms->depth() == in_jvms->depth(), "depth must match");972assert(out_jvms->loc_size() == in_jvms->loc_size(), "size must match");973assert(out_jvms->mon_size() == in_jvms->mon_size(), "size must match");974assert(out_jvms->scl_size() == in_jvms->scl_size(), "size must match");975assert(out_jvms->debug_size() == in_jvms->debug_size(), "size must match");976977// Update the two tail pointers in parallel.978out_jvms = out_jvms->caller();979in_jvms = in_jvms->caller();980}981982assert(debug_ptr == non_debug_edges, "debug info must fit exactly");983984// Test the correctness of JVMState::debug_xxx accessors:985assert(call->jvms()->debug_start() == non_debug_edges, "");986assert(call->jvms()->debug_end() == call->req(), "");987assert(call->jvms()->debug_depth() == call->req() - non_debug_edges, "");988}989990bool GraphKit::compute_stack_effects(int& inputs, int& depth) {991Bytecodes::Code code = java_bc();992if (code == Bytecodes::_wide) {993code = method()->java_code_at_bci(bci() + 1);994}995996BasicType rtype = T_ILLEGAL;997int rsize = 0;998999if (code != Bytecodes::_illegal) {1000depth = Bytecodes::depth(code); // checkcast=0, athrow=-11001rtype = Bytecodes::result_type(code); // checkcast=P, athrow=V1002if (rtype < T_CONFLICT)1003rsize = type2size[rtype];1004}10051006switch (code) {1007case Bytecodes::_illegal:1008return false;10091010case Bytecodes::_ldc:1011case Bytecodes::_ldc_w:1012case Bytecodes::_ldc2_w:1013inputs = 0;1014break;10151016case Bytecodes::_dup: inputs = 1; break;1017case Bytecodes::_dup_x1: inputs = 2; break;1018case Bytecodes::_dup_x2: inputs = 3; break;1019case Bytecodes::_dup2: inputs = 2; break;1020case Bytecodes::_dup2_x1: inputs = 3; break;1021case Bytecodes::_dup2_x2: inputs = 4; break;1022case Bytecodes::_swap: inputs = 2; break;1023case Bytecodes::_arraylength: inputs = 1; break;10241025case Bytecodes::_getstatic:1026case Bytecodes::_putstatic:1027case Bytecodes::_getfield:1028case Bytecodes::_putfield:1029{1030bool ignored_will_link;1031ciField* field = method()->get_field_at_bci(bci(), ignored_will_link);1032int size = field->type()->size();1033bool is_get = (depth >= 0), is_static = (depth & 1);1034inputs = (is_static ? 0 : 1);1035if (is_get) {1036depth = size - inputs;1037} else {1038inputs += size; // putxxx pops the value from the stack1039depth = - inputs;1040}1041}1042break;10431044case Bytecodes::_invokevirtual:1045case Bytecodes::_invokespecial:1046case Bytecodes::_invokestatic:1047case Bytecodes::_invokedynamic:1048case Bytecodes::_invokeinterface:1049{1050bool ignored_will_link;1051ciSignature* declared_signature = NULL;1052ciMethod* ignored_callee = method()->get_method_at_bci(bci(), ignored_will_link, &declared_signature);1053assert(declared_signature != NULL, "cannot be null");1054inputs = declared_signature->arg_size_for_bc(code);1055int size = declared_signature->return_type()->size();1056depth = size - inputs;1057}1058break;10591060case Bytecodes::_multianewarray:1061{1062ciBytecodeStream iter(method());1063iter.reset_to_bci(bci());1064iter.next();1065inputs = iter.get_dimensions();1066assert(rsize == 1, "");1067depth = rsize - inputs;1068}1069break;10701071case Bytecodes::_ireturn:1072case Bytecodes::_lreturn:1073case Bytecodes::_freturn:1074case Bytecodes::_dreturn:1075case Bytecodes::_areturn:1076assert(rsize = -depth, "");1077inputs = rsize;1078break;10791080case Bytecodes::_jsr:1081case Bytecodes::_jsr_w:1082inputs = 0;1083depth = 1; // S.B. depth=1, not zero1084break;10851086default:1087// bytecode produces a typed result1088inputs = rsize - depth;1089assert(inputs >= 0, "");1090break;1091}10921093#ifdef ASSERT1094// spot check1095int outputs = depth + inputs;1096assert(outputs >= 0, "sanity");1097switch (code) {1098case Bytecodes::_checkcast: assert(inputs == 1 && outputs == 1, ""); break;1099case Bytecodes::_athrow: assert(inputs == 1 && outputs == 0, ""); break;1100case Bytecodes::_aload_0: assert(inputs == 0 && outputs == 1, ""); break;1101case Bytecodes::_return: assert(inputs == 0 && outputs == 0, ""); break;1102case Bytecodes::_drem: assert(inputs == 4 && outputs == 2, ""); break;1103}1104#endif //ASSERT11051106return true;1107}1108110911101111//------------------------------basic_plus_adr---------------------------------1112Node* GraphKit::basic_plus_adr(Node* base, Node* ptr, Node* offset) {1113// short-circuit a common case1114if (offset == intcon(0)) return ptr;1115return _gvn.transform( new (C) AddPNode(base, ptr, offset) );1116}11171118Node* GraphKit::ConvI2L(Node* offset) {1119// short-circuit a common case1120jint offset_con = find_int_con(offset, Type::OffsetBot);1121if (offset_con != Type::OffsetBot) {1122return longcon((jlong) offset_con);1123}1124return _gvn.transform( new (C) ConvI2LNode(offset));1125}11261127Node* GraphKit::ConvI2UL(Node* offset) {1128juint offset_con = (juint) find_int_con(offset, Type::OffsetBot);1129if (offset_con != (juint) Type::OffsetBot) {1130return longcon((julong) offset_con);1131}1132Node* conv = _gvn.transform( new (C) ConvI2LNode(offset));1133Node* mask = _gvn.transform( ConLNode::make(C, (julong) max_juint) );1134return _gvn.transform( new (C) AndLNode(conv, mask) );1135}11361137Node* GraphKit::ConvL2I(Node* offset) {1138// short-circuit a common case1139jlong offset_con = find_long_con(offset, (jlong)Type::OffsetBot);1140if (offset_con != (jlong)Type::OffsetBot) {1141return intcon((int) offset_con);1142}1143return _gvn.transform( new (C) ConvL2INode(offset));1144}11451146//-------------------------load_object_klass-----------------------------------1147Node* GraphKit::load_object_klass(Node* obj) {1148// Special-case a fresh allocation to avoid building nodes:1149Node* akls = AllocateNode::Ideal_klass(obj, &_gvn);1150if (akls != NULL) return akls;1151Node* k_adr = basic_plus_adr(obj, oopDesc::klass_offset_in_bytes());1152return _gvn.transform(LoadKlassNode::make(_gvn, NULL, immutable_memory(), k_adr, TypeInstPtr::KLASS));1153}11541155//-------------------------load_array_length-----------------------------------1156Node* GraphKit::load_array_length(Node* array) {1157// Special-case a fresh allocation to avoid building nodes:1158AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(array, &_gvn);1159Node *alen;1160if (alloc == NULL) {1161Node *r_adr = basic_plus_adr(array, arrayOopDesc::length_offset_in_bytes());1162alen = _gvn.transform( new (C) LoadRangeNode(0, immutable_memory(), r_adr, TypeInt::POS));1163} else {1164alen = alloc->Ideal_length();1165Node* ccast = alloc->make_ideal_length(_gvn.type(array)->is_oopptr(), &_gvn);1166if (ccast != alen) {1167alen = _gvn.transform(ccast);1168}1169}1170return alen;1171}11721173//------------------------------do_null_check----------------------------------1174// Helper function to do a NULL pointer check. Returned value is1175// the incoming address with NULL casted away. You are allowed to use the1176// not-null value only if you are control dependent on the test.1177extern int explicit_null_checks_inserted,1178explicit_null_checks_elided;1179Node* GraphKit::null_check_common(Node* value, BasicType type,1180// optional arguments for variations:1181bool assert_null,1182Node* *null_control) {1183assert(!assert_null || null_control == NULL, "not both at once");1184if (stopped()) return top();1185if (!GenerateCompilerNullChecks && !assert_null && null_control == NULL) {1186// For some performance testing, we may wish to suppress null checking.1187value = cast_not_null(value); // Make it appear to be non-null (4962416).1188return value;1189}1190explicit_null_checks_inserted++;11911192// Construct NULL check1193Node *chk = NULL;1194switch(type) {1195case T_LONG : chk = new (C) CmpLNode(value, _gvn.zerocon(T_LONG)); break;1196case T_INT : chk = new (C) CmpINode(value, _gvn.intcon(0)); break;1197case T_ARRAY : // fall through1198type = T_OBJECT; // simplify further tests1199case T_OBJECT : {1200const Type *t = _gvn.type( value );12011202const TypeOopPtr* tp = t->isa_oopptr();1203if (tp != NULL && tp->klass() != NULL && !tp->klass()->is_loaded()1204// Only for do_null_check, not any of its siblings:1205&& !assert_null && null_control == NULL) {1206// Usually, any field access or invocation on an unloaded oop type1207// will simply fail to link, since the statically linked class is1208// likely also to be unloaded. However, in -Xcomp mode, sometimes1209// the static class is loaded but the sharper oop type is not.1210// Rather than checking for this obscure case in lots of places,1211// we simply observe that a null check on an unloaded class1212// will always be followed by a nonsense operation, so we1213// can just issue the uncommon trap here.1214// Our access to the unloaded class will only be correct1215// after it has been loaded and initialized, which requires1216// a trip through the interpreter.1217#ifndef PRODUCT1218if (WizardMode) { tty->print("Null check of unloaded "); tp->klass()->print(); tty->cr(); }1219#endif1220uncommon_trap(Deoptimization::Reason_unloaded,1221Deoptimization::Action_reinterpret,1222tp->klass(), "!loaded");1223return top();1224}12251226if (assert_null) {1227// See if the type is contained in NULL_PTR.1228// If so, then the value is already null.1229if (t->higher_equal(TypePtr::NULL_PTR)) {1230explicit_null_checks_elided++;1231return value; // Elided null assert quickly!1232}1233} else {1234// See if mixing in the NULL pointer changes type.1235// If so, then the NULL pointer was not allowed in the original1236// type. In other words, "value" was not-null.1237if (t->meet(TypePtr::NULL_PTR) != t->remove_speculative()) {1238// same as: if (!TypePtr::NULL_PTR->higher_equal(t)) ...1239explicit_null_checks_elided++;1240return value; // Elided null check quickly!1241}1242}1243chk = new (C) CmpPNode( value, null() );1244break;1245}12461247default:1248fatal(err_msg_res("unexpected type: %s", type2name(type)));1249}1250assert(chk != NULL, "sanity check");1251chk = _gvn.transform(chk);12521253BoolTest::mask btest = assert_null ? BoolTest::eq : BoolTest::ne;1254BoolNode *btst = new (C) BoolNode( chk, btest);1255Node *tst = _gvn.transform( btst );12561257//-----------1258// if peephole optimizations occurred, a prior test existed.1259// If a prior test existed, maybe it dominates as we can avoid this test.1260if (tst != btst && type == T_OBJECT) {1261// At this point we want to scan up the CFG to see if we can1262// find an identical test (and so avoid this test altogether).1263Node *cfg = control();1264int depth = 0;1265while( depth < 16 ) { // Limit search depth for speed1266if( cfg->Opcode() == Op_IfTrue &&1267cfg->in(0)->in(1) == tst ) {1268// Found prior test. Use "cast_not_null" to construct an identical1269// CastPP (and hence hash to) as already exists for the prior test.1270// Return that casted value.1271if (assert_null) {1272replace_in_map(value, null());1273return null(); // do not issue the redundant test1274}1275Node *oldcontrol = control();1276set_control(cfg);1277Node *res = cast_not_null(value);1278set_control(oldcontrol);1279explicit_null_checks_elided++;1280return res;1281}1282cfg = IfNode::up_one_dom(cfg, /*linear_only=*/ true);1283if (cfg == NULL) break; // Quit at region nodes1284depth++;1285}1286}12871288//-----------1289// Branch to failure if null1290float ok_prob = PROB_MAX; // a priori estimate: nulls never happen1291Deoptimization::DeoptReason reason;1292if (assert_null)1293reason = Deoptimization::Reason_null_assert;1294else if (type == T_OBJECT)1295reason = Deoptimization::Reason_null_check;1296else1297reason = Deoptimization::Reason_div0_check;12981299// %%% Since Reason_unhandled is not recorded on a per-bytecode basis,1300// ciMethodData::has_trap_at will return a conservative -1 if any1301// must-be-null assertion has failed. This could cause performance1302// problems for a method after its first do_null_assert failure.1303// Consider using 'Reason_class_check' instead?13041305// To cause an implicit null check, we set the not-null probability1306// to the maximum (PROB_MAX). For an explicit check the probability1307// is set to a smaller value.1308if (null_control != NULL || too_many_traps(reason)) {1309// probability is less likely1310ok_prob = PROB_LIKELY_MAG(3);1311} else if (!assert_null &&1312(ImplicitNullCheckThreshold > 0) &&1313method() != NULL &&1314(method()->method_data()->trap_count(reason)1315>= (uint)ImplicitNullCheckThreshold)) {1316ok_prob = PROB_LIKELY_MAG(3);1317}13181319if (null_control != NULL) {1320IfNode* iff = create_and_map_if(control(), tst, ok_prob, COUNT_UNKNOWN);1321Node* null_true = _gvn.transform( new (C) IfFalseNode(iff));1322set_control( _gvn.transform( new (C) IfTrueNode(iff)));1323if (null_true == top())1324explicit_null_checks_elided++;1325(*null_control) = null_true;1326} else {1327BuildCutout unless(this, tst, ok_prob);1328// Check for optimizer eliding test at parse time1329if (stopped()) {1330// Failure not possible; do not bother making uncommon trap.1331explicit_null_checks_elided++;1332} else if (assert_null) {1333uncommon_trap(reason,1334Deoptimization::Action_make_not_entrant,1335NULL, "assert_null");1336} else {1337replace_in_map(value, zerocon(type));1338builtin_throw(reason);1339}1340}13411342// Must throw exception, fall-thru not possible?1343if (stopped()) {1344return top(); // No result1345}13461347if (assert_null) {1348// Cast obj to null on this path.1349replace_in_map(value, zerocon(type));1350return zerocon(type);1351}13521353// Cast obj to not-null on this path, if there is no null_control.1354// (If there is a null_control, a non-null value may come back to haunt us.)1355if (type == T_OBJECT) {1356Node* cast = cast_not_null(value, false);1357if (null_control == NULL || (*null_control) == top())1358replace_in_map(value, cast);1359value = cast;1360}13611362return value;1363}136413651366//------------------------------cast_not_null----------------------------------1367// Cast obj to not-null on this path1368Node* GraphKit::cast_not_null(Node* obj, bool do_replace_in_map) {1369const Type *t = _gvn.type(obj);1370const Type *t_not_null = t->join_speculative(TypePtr::NOTNULL);1371// Object is already not-null?1372if( t == t_not_null ) return obj;13731374Node *cast = new (C) CastPPNode(obj,t_not_null);1375cast->init_req(0, control());1376cast = _gvn.transform( cast );13771378// Scan for instances of 'obj' in the current JVM mapping.1379// These instances are known to be not-null after the test.1380if (do_replace_in_map)1381replace_in_map(obj, cast);13821383return cast; // Return casted value1384}138513861387//--------------------------replace_in_map-------------------------------------1388void GraphKit::replace_in_map(Node* old, Node* neww) {1389if (old == neww) {1390return;1391}13921393map()->replace_edge(old, neww);13941395// Note: This operation potentially replaces any edge1396// on the map. This includes locals, stack, and monitors1397// of the current (innermost) JVM state.13981399// don't let inconsistent types from profiling escape this1400// method14011402const Type* told = _gvn.type(old);1403const Type* tnew = _gvn.type(neww);14041405if (!tnew->higher_equal(told)) {1406return;1407}14081409map()->record_replaced_node(old, neww);1410}141114121413//=============================================================================1414//--------------------------------memory---------------------------------------1415Node* GraphKit::memory(uint alias_idx) {1416MergeMemNode* mem = merged_memory();1417Node* p = mem->memory_at(alias_idx);1418_gvn.set_type(p, Type::MEMORY); // must be mapped1419return p;1420}14211422//-----------------------------reset_memory------------------------------------1423Node* GraphKit::reset_memory() {1424Node* mem = map()->memory();1425// do not use this node for any more parsing!1426debug_only( map()->set_memory((Node*)NULL) );1427return _gvn.transform( mem );1428}14291430//------------------------------set_all_memory---------------------------------1431void GraphKit::set_all_memory(Node* newmem) {1432Node* mergemem = MergeMemNode::make(C, newmem);1433gvn().set_type_bottom(mergemem);1434map()->set_memory(mergemem);1435}14361437//------------------------------set_all_memory_call----------------------------1438void GraphKit::set_all_memory_call(Node* call, bool separate_io_proj) {1439Node* newmem = _gvn.transform( new (C) ProjNode(call, TypeFunc::Memory, separate_io_proj) );1440set_all_memory(newmem);1441}14421443//=============================================================================1444//1445// parser factory methods for MemNodes1446//1447// These are layered on top of the factory methods in LoadNode and StoreNode,1448// and integrate with the parser's memory state and _gvn engine.1449//14501451// factory methods in "int adr_idx"1452Node* GraphKit::make_load(Node* ctl, Node* adr, const Type* t, BasicType bt,1453int adr_idx,1454MemNode::MemOrd mo,1455LoadNode::ControlDependency control_dependency,1456bool require_atomic_access,1457bool unaligned,1458bool mismatched) {1459assert(adr_idx != Compile::AliasIdxTop, "use other make_load factory" );1460const TypePtr* adr_type = NULL; // debug-mode-only argument1461debug_only(adr_type = C->get_adr_type(adr_idx));1462Node* mem = memory(adr_idx);1463Node* ld;1464if (require_atomic_access && bt == T_LONG) {1465ld = LoadLNode::make_atomic(C, ctl, mem, adr, adr_type, t, mo, control_dependency);1466} else if (require_atomic_access && bt == T_DOUBLE) {1467ld = LoadDNode::make_atomic(C, ctl, mem, adr, adr_type, t, mo, control_dependency);1468} else {1469ld = LoadNode::make(_gvn, ctl, mem, adr, adr_type, t, bt, mo, control_dependency);1470}1471if (unaligned) {1472ld->as_Load()->set_unaligned_access();1473}1474if (mismatched) {1475ld->as_Load()->set_mismatched_access();1476}1477ld = _gvn.transform(ld);1478if ((bt == T_OBJECT) && C->do_escape_analysis() || C->eliminate_boxing()) {1479// Improve graph before escape analysis and boxing elimination.1480record_for_igvn(ld);1481}1482return ld;1483}14841485Node* GraphKit::store_to_memory(Node* ctl, Node* adr, Node *val, BasicType bt,1486int adr_idx,1487MemNode::MemOrd mo,1488bool require_atomic_access,1489bool unaligned,1490bool mismatched) {1491assert(adr_idx != Compile::AliasIdxTop, "use other store_to_memory factory" );1492const TypePtr* adr_type = NULL;1493debug_only(adr_type = C->get_adr_type(adr_idx));1494Node *mem = memory(adr_idx);1495Node* st;1496if (require_atomic_access && bt == T_LONG) {1497st = StoreLNode::make_atomic(C, ctl, mem, adr, adr_type, val, mo);1498} else if (require_atomic_access && bt == T_DOUBLE) {1499st = StoreDNode::make_atomic(C, ctl, mem, adr, adr_type, val, mo);1500} else {1501st = StoreNode::make(_gvn, ctl, mem, adr, adr_type, val, bt, mo);1502}1503if (unaligned) {1504st->as_Store()->set_unaligned_access();1505}1506if (mismatched) {1507st->as_Store()->set_mismatched_access();1508}1509st = _gvn.transform(st);1510set_memory(st, adr_idx);1511// Back-to-back stores can only remove intermediate store with DU info1512// so push on worklist for optimizer.1513if (mem->req() > MemNode::Address && adr == mem->in(MemNode::Address))1514record_for_igvn(st);15151516return st;1517}151815191520void GraphKit::pre_barrier(bool do_load,1521Node* ctl,1522Node* obj,1523Node* adr,1524uint adr_idx,1525Node* val,1526const TypeOopPtr* val_type,1527Node* pre_val,1528BasicType bt) {15291530BarrierSet* bs = Universe::heap()->barrier_set();1531set_control(ctl);1532switch (bs->kind()) {1533case BarrierSet::G1SATBCT:1534case BarrierSet::G1SATBCTLogging:1535g1_write_barrier_pre(do_load, obj, adr, adr_idx, val, val_type, pre_val, bt);1536break;15371538case BarrierSet::CardTableModRef:1539case BarrierSet::CardTableExtension:1540case BarrierSet::ModRef:1541break;15421543case BarrierSet::Other:1544default :1545ShouldNotReachHere();15461547}1548}15491550bool GraphKit::can_move_pre_barrier() const {1551BarrierSet* bs = Universe::heap()->barrier_set();1552switch (bs->kind()) {1553case BarrierSet::G1SATBCT:1554case BarrierSet::G1SATBCTLogging:1555return true; // Can move it if no safepoint15561557case BarrierSet::CardTableModRef:1558case BarrierSet::CardTableExtension:1559case BarrierSet::ModRef:1560return true; // There is no pre-barrier15611562case BarrierSet::Other:1563default :1564ShouldNotReachHere();1565}1566return false;1567}15681569void GraphKit::post_barrier(Node* ctl,1570Node* store,1571Node* obj,1572Node* adr,1573uint adr_idx,1574Node* val,1575BasicType bt,1576bool use_precise) {1577BarrierSet* bs = Universe::heap()->barrier_set();1578set_control(ctl);1579switch (bs->kind()) {1580case BarrierSet::G1SATBCT:1581case BarrierSet::G1SATBCTLogging:1582g1_write_barrier_post(store, obj, adr, adr_idx, val, bt, use_precise);1583break;15841585case BarrierSet::CardTableModRef:1586case BarrierSet::CardTableExtension:1587write_barrier_post(store, obj, adr, adr_idx, val, use_precise);1588break;15891590case BarrierSet::ModRef:1591break;15921593case BarrierSet::Other:1594default :1595ShouldNotReachHere();15961597}1598}15991600Node* GraphKit::store_oop(Node* ctl,1601Node* obj,1602Node* adr,1603const TypePtr* adr_type,1604Node* val,1605const TypeOopPtr* val_type,1606BasicType bt,1607bool use_precise,1608MemNode::MemOrd mo,1609bool mismatched) {1610// Transformation of a value which could be NULL pointer (CastPP #NULL)1611// could be delayed during Parse (for example, in adjust_map_after_if()).1612// Execute transformation here to avoid barrier generation in such case.1613if (_gvn.type(val) == TypePtr::NULL_PTR)1614val = _gvn.makecon(TypePtr::NULL_PTR);16151616set_control(ctl);1617if (stopped()) return top(); // Dead path ?16181619assert(bt == T_OBJECT, "sanity");1620assert(val != NULL, "not dead path");1621uint adr_idx = C->get_alias_index(adr_type);1622assert(adr_idx != Compile::AliasIdxTop, "use other store_to_memory factory" );16231624pre_barrier(true /* do_load */,1625control(), obj, adr, adr_idx, val, val_type,1626NULL /* pre_val */,1627bt);16281629Node* store = store_to_memory(control(), adr, val, bt, adr_idx, mo, mismatched);1630post_barrier(control(), store, obj, adr, adr_idx, val, bt, use_precise);1631return store;1632}16331634// Could be an array or object we don't know at compile time (unsafe ref.)1635Node* GraphKit::store_oop_to_unknown(Node* ctl,1636Node* obj, // containing obj1637Node* adr, // actual adress to store val at1638const TypePtr* adr_type,1639Node* val,1640BasicType bt,1641MemNode::MemOrd mo,1642bool mismatched) {1643Compile::AliasType* at = C->alias_type(adr_type);1644const TypeOopPtr* val_type = NULL;1645if (adr_type->isa_instptr()) {1646if (at->field() != NULL) {1647// known field. This code is a copy of the do_put_xxx logic.1648ciField* field = at->field();1649if (!field->type()->is_loaded()) {1650val_type = TypeInstPtr::BOTTOM;1651} else {1652val_type = TypeOopPtr::make_from_klass(field->type()->as_klass());1653}1654}1655} else if (adr_type->isa_aryptr()) {1656val_type = adr_type->is_aryptr()->elem()->make_oopptr();1657}1658if (val_type == NULL) {1659val_type = TypeInstPtr::BOTTOM;1660}1661return store_oop(ctl, obj, adr, adr_type, val, val_type, bt, true, mo, mismatched);1662}166316641665//-------------------------array_element_address-------------------------1666Node* GraphKit::array_element_address(Node* ary, Node* idx, BasicType elembt,1667const TypeInt* sizetype, Node* ctrl) {1668uint shift = exact_log2(type2aelembytes(elembt));1669uint header = arrayOopDesc::base_offset_in_bytes(elembt);16701671// short-circuit a common case (saves lots of confusing waste motion)1672jint idx_con = find_int_con(idx, -1);1673if (idx_con >= 0) {1674intptr_t offset = header + ((intptr_t)idx_con << shift);1675return basic_plus_adr(ary, offset);1676}16771678// must be correct type for alignment purposes1679Node* base = basic_plus_adr(ary, header);1680#ifdef _LP641681// The scaled index operand to AddP must be a clean 64-bit value.1682// Java allows a 32-bit int to be incremented to a negative1683// value, which appears in a 64-bit register as a large1684// positive number. Using that large positive number as an1685// operand in pointer arithmetic has bad consequences.1686// On the other hand, 32-bit overflow is rare, and the possibility1687// can often be excluded, if we annotate the ConvI2L node with1688// a type assertion that its value is known to be a small positive1689// number. (The prior range check has ensured this.)1690// This assertion is used by ConvI2LNode::Ideal.1691int index_max = max_jint - 1; // array size is max_jint, index is one less1692if (sizetype != NULL) index_max = sizetype->_hi - 1;1693const TypeInt* iidxtype = TypeInt::make(0, index_max, Type::WidenMax);1694idx = C->constrained_convI2L(&_gvn, idx, iidxtype, ctrl);1695#endif1696Node* scale = _gvn.transform( new (C) LShiftXNode(idx, intcon(shift)) );1697return basic_plus_adr(ary, base, scale);1698}16991700//-------------------------load_array_element-------------------------1701Node* GraphKit::load_array_element(Node* ctl, Node* ary, Node* idx, const TypeAryPtr* arytype) {1702const Type* elemtype = arytype->elem();1703BasicType elembt = elemtype->array_element_basic_type();1704Node* adr = array_element_address(ary, idx, elembt, arytype->size());1705if (elembt == T_NARROWOOP) {1706elembt = T_OBJECT; // To satisfy switch in LoadNode::make()1707}1708Node* ld = make_load(ctl, adr, elemtype, elembt, arytype, MemNode::unordered);1709return ld;1710}17111712//-------------------------set_arguments_for_java_call-------------------------1713// Arguments (pre-popped from the stack) are taken from the JVMS.1714void GraphKit::set_arguments_for_java_call(CallJavaNode* call) {1715// Add the call arguments:1716uint nargs = call->method()->arg_size();1717for (uint i = 0; i < nargs; i++) {1718Node* arg = argument(i);1719call->init_req(i + TypeFunc::Parms, arg);1720}1721}17221723//---------------------------set_edges_for_java_call---------------------------1724// Connect a newly created call into the current JVMS.1725// A return value node (if any) is returned from set_edges_for_java_call.1726void GraphKit::set_edges_for_java_call(CallJavaNode* call, bool must_throw, bool separate_io_proj) {17271728// Add the predefined inputs:1729call->init_req( TypeFunc::Control, control() );1730call->init_req( TypeFunc::I_O , i_o() );1731call->init_req( TypeFunc::Memory , reset_memory() );1732call->init_req( TypeFunc::FramePtr, frameptr() );1733call->init_req( TypeFunc::ReturnAdr, top() );17341735add_safepoint_edges(call, must_throw);17361737Node* xcall = _gvn.transform(call);17381739if (xcall == top()) {1740set_control(top());1741return;1742}1743assert(xcall == call, "call identity is stable");17441745// Re-use the current map to produce the result.17461747set_control(_gvn.transform(new (C) ProjNode(call, TypeFunc::Control)));1748set_i_o( _gvn.transform(new (C) ProjNode(call, TypeFunc::I_O , separate_io_proj)));1749set_all_memory_call(xcall, separate_io_proj);17501751//return xcall; // no need, caller already has it1752}17531754Node* GraphKit::set_results_for_java_call(CallJavaNode* call, bool separate_io_proj) {1755if (stopped()) return top(); // maybe the call folded up?17561757// Capture the return value, if any.1758Node* ret;1759if (call->method() == NULL ||1760call->method()->return_type()->basic_type() == T_VOID)1761ret = top();1762else ret = _gvn.transform(new (C) ProjNode(call, TypeFunc::Parms));17631764// Note: Since any out-of-line call can produce an exception,1765// we always insert an I_O projection from the call into the result.17661767make_slow_call_ex(call, env()->Throwable_klass(), separate_io_proj);17681769if (separate_io_proj) {1770// The caller requested separate projections be used by the fall1771// through and exceptional paths, so replace the projections for1772// the fall through path.1773set_i_o(_gvn.transform( new (C) ProjNode(call, TypeFunc::I_O) ));1774set_all_memory(_gvn.transform( new (C) ProjNode(call, TypeFunc::Memory) ));1775}1776return ret;1777}17781779//--------------------set_predefined_input_for_runtime_call--------------------1780// Reading and setting the memory state is way conservative here.1781// The real problem is that I am not doing real Type analysis on memory,1782// so I cannot distinguish card mark stores from other stores. Across a GC1783// point the Store Barrier and the card mark memory has to agree. I cannot1784// have a card mark store and its barrier split across the GC point from1785// either above or below. Here I get that to happen by reading ALL of memory.1786// A better answer would be to separate out card marks from other memory.1787// For now, return the input memory state, so that it can be reused1788// after the call, if this call has restricted memory effects.1789Node* GraphKit::set_predefined_input_for_runtime_call(SafePointNode* call, Node* narrow_mem) {1790// Set fixed predefined input arguments1791Node* memory = reset_memory();1792Node* m = narrow_mem == NULL ? memory : narrow_mem;1793call->init_req( TypeFunc::Control, control() );1794call->init_req( TypeFunc::I_O, top() ); // does no i/o1795call->init_req( TypeFunc::Memory, m ); // may gc ptrs1796call->init_req( TypeFunc::FramePtr, frameptr() );1797call->init_req( TypeFunc::ReturnAdr, top() );1798return memory;1799}18001801//-------------------set_predefined_output_for_runtime_call--------------------1802// Set control and memory (not i_o) from the call.1803// If keep_mem is not NULL, use it for the output state,1804// except for the RawPtr output of the call, if hook_mem is TypeRawPtr::BOTTOM.1805// If hook_mem is NULL, this call produces no memory effects at all.1806// If hook_mem is a Java-visible memory slice (such as arraycopy operands),1807// then only that memory slice is taken from the call.1808// In the last case, we must put an appropriate memory barrier before1809// the call, so as to create the correct anti-dependencies on loads1810// preceding the call.1811void GraphKit::set_predefined_output_for_runtime_call(Node* call,1812Node* keep_mem,1813const TypePtr* hook_mem) {1814// no i/o1815set_control(_gvn.transform( new (C) ProjNode(call,TypeFunc::Control) ));1816if (keep_mem) {1817// First clone the existing memory state1818set_all_memory(keep_mem);1819if (hook_mem != NULL) {1820// Make memory for the call1821Node* mem = _gvn.transform( new (C) ProjNode(call, TypeFunc::Memory) );1822// Set the RawPtr memory state only. This covers all the heap top/GC stuff1823// We also use hook_mem to extract specific effects from arraycopy stubs.1824set_memory(mem, hook_mem);1825}1826// ...else the call has NO memory effects.18271828// Make sure the call advertises its memory effects precisely.1829// This lets us build accurate anti-dependences in gcm.cpp.1830assert(C->alias_type(call->adr_type()) == C->alias_type(hook_mem),1831"call node must be constructed correctly");1832} else {1833assert(hook_mem == NULL, "");1834// This is not a "slow path" call; all memory comes from the call.1835set_all_memory_call(call);1836}1837}183818391840// Replace the call with the current state of the kit.1841void GraphKit::replace_call(CallNode* call, Node* result, bool do_replaced_nodes) {1842JVMState* ejvms = NULL;1843if (has_exceptions()) {1844ejvms = transfer_exceptions_into_jvms();1845}18461847ReplacedNodes replaced_nodes = map()->replaced_nodes();1848ReplacedNodes replaced_nodes_exception;1849Node* ex_ctl = top();18501851SafePointNode* final_state = stop();18521853// Find all the needed outputs of this call1854CallProjections callprojs;1855call->extract_projections(&callprojs, true);18561857Node* init_mem = call->in(TypeFunc::Memory);1858Node* final_mem = final_state->in(TypeFunc::Memory);1859Node* final_ctl = final_state->in(TypeFunc::Control);1860Node* final_io = final_state->in(TypeFunc::I_O);18611862// Replace all the old call edges with the edges from the inlining result1863if (callprojs.fallthrough_catchproj != NULL) {1864C->gvn_replace_by(callprojs.fallthrough_catchproj, final_ctl);1865}1866if (callprojs.fallthrough_memproj != NULL) {1867if (final_mem->is_MergeMem()) {1868// Parser's exits MergeMem was not transformed but may be optimized1869final_mem = _gvn.transform(final_mem);1870}1871C->gvn_replace_by(callprojs.fallthrough_memproj, final_mem);1872}1873if (callprojs.fallthrough_ioproj != NULL) {1874C->gvn_replace_by(callprojs.fallthrough_ioproj, final_io);1875}18761877// Replace the result with the new result if it exists and is used1878if (callprojs.resproj != NULL && result != NULL) {1879C->gvn_replace_by(callprojs.resproj, result);1880}18811882if (ejvms == NULL) {1883// No exception edges to simply kill off those paths1884if (callprojs.catchall_catchproj != NULL) {1885C->gvn_replace_by(callprojs.catchall_catchproj, C->top());1886}1887if (callprojs.catchall_memproj != NULL) {1888C->gvn_replace_by(callprojs.catchall_memproj, C->top());1889}1890if (callprojs.catchall_ioproj != NULL) {1891C->gvn_replace_by(callprojs.catchall_ioproj, C->top());1892}1893// Replace the old exception object with top1894if (callprojs.exobj != NULL) {1895C->gvn_replace_by(callprojs.exobj, C->top());1896}1897} else {1898GraphKit ekit(ejvms);18991900// Load my combined exception state into the kit, with all phis transformed:1901SafePointNode* ex_map = ekit.combine_and_pop_all_exception_states();1902replaced_nodes_exception = ex_map->replaced_nodes();19031904Node* ex_oop = ekit.use_exception_state(ex_map);19051906if (callprojs.catchall_catchproj != NULL) {1907C->gvn_replace_by(callprojs.catchall_catchproj, ekit.control());1908ex_ctl = ekit.control();1909}1910if (callprojs.catchall_memproj != NULL) {1911C->gvn_replace_by(callprojs.catchall_memproj, ekit.reset_memory());1912}1913if (callprojs.catchall_ioproj != NULL) {1914C->gvn_replace_by(callprojs.catchall_ioproj, ekit.i_o());1915}19161917// Replace the old exception object with the newly created one1918if (callprojs.exobj != NULL) {1919C->gvn_replace_by(callprojs.exobj, ex_oop);1920}1921}19221923// Disconnect the call from the graph1924call->disconnect_inputs(NULL, C);1925C->gvn_replace_by(call, C->top());19261927// Clean up any MergeMems that feed other MergeMems since the1928// optimizer doesn't like that.1929if (final_mem->is_MergeMem()) {1930Node_List wl;1931for (SimpleDUIterator i(final_mem); i.has_next(); i.next()) {1932Node* m = i.get();1933if (m->is_MergeMem() && !wl.contains(m)) {1934wl.push(m);1935}1936}1937while (wl.size() > 0) {1938_gvn.transform(wl.pop());1939}1940}19411942if (callprojs.fallthrough_catchproj != NULL && !final_ctl->is_top() && do_replaced_nodes) {1943replaced_nodes.apply(C, final_ctl);1944}1945if (!ex_ctl->is_top() && do_replaced_nodes) {1946replaced_nodes_exception.apply(C, ex_ctl);1947}1948}194919501951//------------------------------increment_counter------------------------------1952// for statistics: increment a VM counter by 119531954void GraphKit::increment_counter(address counter_addr) {1955Node* adr1 = makecon(TypeRawPtr::make(counter_addr));1956increment_counter(adr1);1957}19581959void GraphKit::increment_counter(Node* counter_addr) {1960int adr_type = Compile::AliasIdxRaw;1961Node* ctrl = control();1962Node* cnt = make_load(ctrl, counter_addr, TypeInt::INT, T_INT, adr_type, MemNode::unordered);1963Node* incr = _gvn.transform(new (C) AddINode(cnt, _gvn.intcon(1)));1964store_to_memory(ctrl, counter_addr, incr, T_INT, adr_type, MemNode::unordered);1965}196619671968//------------------------------uncommon_trap----------------------------------1969// Bail out to the interpreter in mid-method. Implemented by calling the1970// uncommon_trap blob. This helper function inserts a runtime call with the1971// right debug info.1972void GraphKit::uncommon_trap(int trap_request,1973ciKlass* klass, const char* comment,1974bool must_throw,1975bool keep_exact_action) {1976if (failing()) stop();1977if (stopped()) return; // trap reachable?19781979// Note: If ProfileTraps is true, and if a deopt. actually1980// occurs here, the runtime will make sure an MDO exists. There is1981// no need to call method()->ensure_method_data() at this point.19821983// Set the stack pointer to the right value for reexecution:1984set_sp(reexecute_sp());19851986#ifdef ASSERT1987if (!must_throw) {1988// Make sure the stack has at least enough depth to execute1989// the current bytecode.1990int inputs, ignored_depth;1991if (compute_stack_effects(inputs, ignored_depth)) {1992assert(sp() >= inputs, err_msg_res("must have enough JVMS stack to execute %s: sp=%d, inputs=%d",1993Bytecodes::name(java_bc()), sp(), inputs));1994}1995}1996#endif19971998Deoptimization::DeoptReason reason = Deoptimization::trap_request_reason(trap_request);1999Deoptimization::DeoptAction action = Deoptimization::trap_request_action(trap_request);20002001switch (action) {2002case Deoptimization::Action_maybe_recompile:2003case Deoptimization::Action_reinterpret:2004// Temporary fix for 6529811 to allow virtual calls to be sure they2005// get the chance to go from mono->bi->mega2006if (!keep_exact_action &&2007Deoptimization::trap_request_index(trap_request) < 0 &&2008too_many_recompiles(reason)) {2009// This BCI is causing too many recompilations.2010if (C->log() != NULL) {2011C->log()->elem("observe that='trap_action_change' reason='%s' from='%s' to='none'",2012Deoptimization::trap_reason_name(reason),2013Deoptimization::trap_action_name(action));2014}2015action = Deoptimization::Action_none;2016trap_request = Deoptimization::make_trap_request(reason, action);2017} else {2018C->set_trap_can_recompile(true);2019}2020break;2021case Deoptimization::Action_make_not_entrant:2022C->set_trap_can_recompile(true);2023break;2024#ifdef ASSERT2025case Deoptimization::Action_none:2026case Deoptimization::Action_make_not_compilable:2027break;2028default:2029fatal(err_msg_res("unknown action %d: %s", action, Deoptimization::trap_action_name(action)));2030break;2031#endif2032}20332034if (TraceOptoParse) {2035char buf[100];2036tty->print_cr("Uncommon trap %s at bci:%d",2037Deoptimization::format_trap_request(buf, sizeof(buf),2038trap_request), bci());2039}20402041CompileLog* log = C->log();2042if (log != NULL) {2043int kid = (klass == NULL)? -1: log->identify(klass);2044log->begin_elem("uncommon_trap bci='%d'", bci());2045char buf[100];2046log->print(" %s", Deoptimization::format_trap_request(buf, sizeof(buf),2047trap_request));2048if (kid >= 0) log->print(" klass='%d'", kid);2049if (comment != NULL) log->print(" comment='%s'", comment);2050log->end_elem();2051}20522053// Make sure any guarding test views this path as very unlikely2054Node *i0 = control()->in(0);2055if (i0 != NULL && i0->is_If()) { // Found a guarding if test?2056IfNode *iff = i0->as_If();2057float f = iff->_prob; // Get prob2058if (control()->Opcode() == Op_IfTrue) {2059if (f > PROB_UNLIKELY_MAG(4))2060iff->_prob = PROB_MIN;2061} else {2062if (f < PROB_LIKELY_MAG(4))2063iff->_prob = PROB_MAX;2064}2065}20662067// Clear out dead values from the debug info.2068kill_dead_locals();20692070// Now insert the uncommon trap subroutine call2071address call_addr = SharedRuntime::uncommon_trap_blob()->entry_point();2072const TypePtr* no_memory_effects = NULL;2073// Pass the index of the class to be loaded2074Node* call = make_runtime_call(RC_NO_LEAF | RC_UNCOMMON |2075(must_throw ? RC_MUST_THROW : 0),2076OptoRuntime::uncommon_trap_Type(),2077call_addr, "uncommon_trap", no_memory_effects,2078intcon(trap_request));2079assert(call->as_CallStaticJava()->uncommon_trap_request() == trap_request,2080"must extract request correctly from the graph");2081assert(trap_request != 0, "zero value reserved by uncommon_trap_request");20822083call->set_req(TypeFunc::ReturnAdr, returnadr());2084// The debug info is the only real input to this call.20852086// Halt-and-catch fire here. The above call should never return!2087HaltNode* halt = new(C) HaltNode(control(), frameptr());2088_gvn.set_type_bottom(halt);2089root()->add_req(halt);20902091stop_and_kill_map();2092}209320942095//--------------------------just_allocated_object------------------------------2096// Report the object that was just allocated.2097// It must be the case that there are no intervening safepoints.2098// We use this to determine if an object is so "fresh" that2099// it does not require card marks.2100Node* GraphKit::just_allocated_object(Node* current_control) {2101if (C->recent_alloc_ctl() == current_control)2102return C->recent_alloc_obj();2103return NULL;2104}210521062107void GraphKit::round_double_arguments(ciMethod* dest_method) {2108// (Note: TypeFunc::make has a cache that makes this fast.)2109const TypeFunc* tf = TypeFunc::make(dest_method);2110int nargs = tf->_domain->_cnt - TypeFunc::Parms;2111for (int j = 0; j < nargs; j++) {2112const Type *targ = tf->_domain->field_at(j + TypeFunc::Parms);2113if( targ->basic_type() == T_DOUBLE ) {2114// If any parameters are doubles, they must be rounded before2115// the call, dstore_rounding does gvn.transform2116Node *arg = argument(j);2117arg = dstore_rounding(arg);2118set_argument(j, arg);2119}2120}2121}21222123/**2124* Record profiling data exact_kls for Node n with the type system so2125* that it can propagate it (speculation)2126*2127* @param n node that the type applies to2128* @param exact_kls type from profiling2129*2130* @return node with improved type2131*/2132Node* GraphKit::record_profile_for_speculation(Node* n, ciKlass* exact_kls) {2133const Type* current_type = _gvn.type(n);2134assert(UseTypeSpeculation, "type speculation must be on");21352136const TypeOopPtr* speculative = current_type->speculative();21372138if (current_type->would_improve_type(exact_kls, jvms()->depth())) {2139const TypeKlassPtr* tklass = TypeKlassPtr::make(exact_kls);2140const TypeOopPtr* xtype = tklass->as_instance_type();2141assert(xtype->klass_is_exact(), "Should be exact");2142// record the new speculative type's depth2143speculative = xtype->with_inline_depth(jvms()->depth());2144}21452146if (speculative != current_type->speculative()) {2147// Build a type with a speculative type (what we think we know2148// about the type but will need a guard when we use it)2149const TypeOopPtr* spec_type = TypeOopPtr::make(TypePtr::BotPTR, Type::OffsetBot, TypeOopPtr::InstanceBot, speculative);2150// We're changing the type, we need a new CheckCast node to carry2151// the new type. The new type depends on the control: what2152// profiling tells us is only valid from here as far as we can2153// tell.2154Node* cast = new(C) CheckCastPPNode(control(), n, current_type->remove_speculative()->join_speculative(spec_type));2155cast = _gvn.transform(cast);2156replace_in_map(n, cast);2157n = cast;2158}21592160return n;2161}21622163/**2164* Record profiling data from receiver profiling at an invoke with the2165* type system so that it can propagate it (speculation)2166*2167* @param n receiver node2168*2169* @return node with improved type2170*/2171Node* GraphKit::record_profiled_receiver_for_speculation(Node* n) {2172if (!UseTypeSpeculation) {2173return n;2174}2175ciKlass* exact_kls = profile_has_unique_klass();2176return record_profile_for_speculation(n, exact_kls);2177}21782179/**2180* Record profiling data from argument profiling at an invoke with the2181* type system so that it can propagate it (speculation)2182*2183* @param dest_method target method for the call2184* @param bc what invoke bytecode is this?2185*/2186void GraphKit::record_profiled_arguments_for_speculation(ciMethod* dest_method, Bytecodes::Code bc) {2187if (!UseTypeSpeculation) {2188return;2189}2190const TypeFunc* tf = TypeFunc::make(dest_method);2191int nargs = tf->_domain->_cnt - TypeFunc::Parms;2192int skip = Bytecodes::has_receiver(bc) ? 1 : 0;2193for (int j = skip, i = 0; j < nargs && i < TypeProfileArgsLimit; j++) {2194const Type *targ = tf->_domain->field_at(j + TypeFunc::Parms);2195if (targ->basic_type() == T_OBJECT || targ->basic_type() == T_ARRAY) {2196ciKlass* better_type = method()->argument_profiled_type(bci(), i);2197if (better_type != NULL) {2198record_profile_for_speculation(argument(j), better_type);2199}2200i++;2201}2202}2203}22042205/**2206* Record profiling data from parameter profiling at an invoke with2207* the type system so that it can propagate it (speculation)2208*/2209void GraphKit::record_profiled_parameters_for_speculation() {2210if (!UseTypeSpeculation) {2211return;2212}2213for (int i = 0, j = 0; i < method()->arg_size() ; i++) {2214if (_gvn.type(local(i))->isa_oopptr()) {2215ciKlass* better_type = method()->parameter_profiled_type(j);2216if (better_type != NULL) {2217record_profile_for_speculation(local(i), better_type);2218}2219j++;2220}2221}2222}22232224void GraphKit::round_double_result(ciMethod* dest_method) {2225// A non-strict method may return a double value which has an extended2226// exponent, but this must not be visible in a caller which is 'strict'2227// If a strict caller invokes a non-strict callee, round a double result22282229BasicType result_type = dest_method->return_type()->basic_type();2230assert( method() != NULL, "must have caller context");2231if( result_type == T_DOUBLE && method()->is_strict() && !dest_method->is_strict() ) {2232// Destination method's return value is on top of stack2233// dstore_rounding() does gvn.transform2234Node *result = pop_pair();2235result = dstore_rounding(result);2236push_pair(result);2237}2238}22392240// rounding for strict float precision conformance2241Node* GraphKit::precision_rounding(Node* n) {2242return UseStrictFP && _method->flags().is_strict()2243&& UseSSE == 0 && Matcher::strict_fp_requires_explicit_rounding2244? _gvn.transform( new (C) RoundFloatNode(0, n) )2245: n;2246}22472248// rounding for strict double precision conformance2249Node* GraphKit::dprecision_rounding(Node *n) {2250return UseStrictFP && _method->flags().is_strict()2251&& UseSSE <= 1 && Matcher::strict_fp_requires_explicit_rounding2252? _gvn.transform( new (C) RoundDoubleNode(0, n) )2253: n;2254}22552256// rounding for non-strict double stores2257Node* GraphKit::dstore_rounding(Node* n) {2258return Matcher::strict_fp_requires_explicit_rounding2259&& UseSSE <= 12260? _gvn.transform( new (C) RoundDoubleNode(0, n) )2261: n;2262}22632264//=============================================================================2265// Generate a fast path/slow path idiom. Graph looks like:2266// [foo] indicates that 'foo' is a parameter2267//2268// [in] NULL2269// \ /2270// CmpP2271// Bool ne2272// If2273// / \2274// True False-<2>2275// / |2276// / cast_not_null2277// Load | | ^2278// [fast_test] | |2279// gvn to opt_test | |2280// / \ | <1>2281// True False |2282// | \\ |2283// [slow_call] \[fast_result]2284// Ctl Val \ \2285// | \ \2286// Catch <1> \ \2287// / \ ^ \ \2288// Ex No_Ex | \ \2289// | \ \ | \ <2> \2290// ... \ [slow_res] | | \ [null_result]2291// \ \--+--+--- | |2292// \ | / \ | /2293// --------Region Phi2294//2295//=============================================================================2296// Code is structured as a series of driver functions all called 'do_XXX' that2297// call a set of helper functions. Helper functions first, then drivers.22982299//------------------------------null_check_oop---------------------------------2300// Null check oop. Set null-path control into Region in slot 3.2301// Make a cast-not-nullness use the other not-null control. Return cast.2302Node* GraphKit::null_check_oop(Node* value, Node* *null_control,2303bool never_see_null, bool safe_for_replace) {2304// Initial NULL check taken path2305(*null_control) = top();2306Node* cast = null_check_common(value, T_OBJECT, false, null_control);23072308// Generate uncommon_trap:2309if (never_see_null && (*null_control) != top()) {2310// If we see an unexpected null at a check-cast we record it and force a2311// recompile; the offending check-cast will be compiled to handle NULLs.2312// If we see more than one offending BCI, then all checkcasts in the2313// method will be compiled to handle NULLs.2314PreserveJVMState pjvms(this);2315set_control(*null_control);2316replace_in_map(value, null());2317uncommon_trap(Deoptimization::Reason_null_check,2318Deoptimization::Action_make_not_entrant);2319(*null_control) = top(); // NULL path is dead2320}2321if ((*null_control) == top() && safe_for_replace) {2322replace_in_map(value, cast);2323}23242325// Cast away null-ness on the result2326return cast;2327}23282329//------------------------------opt_iff----------------------------------------2330// Optimize the fast-check IfNode. Set the fast-path region slot 2.2331// Return slow-path control.2332Node* GraphKit::opt_iff(Node* region, Node* iff) {2333IfNode *opt_iff = _gvn.transform(iff)->as_If();23342335// Fast path taken; set region slot 22336Node *fast_taken = _gvn.transform( new (C) IfFalseNode(opt_iff) );2337region->init_req(2,fast_taken); // Capture fast-control23382339// Fast path not-taken, i.e. slow path2340Node *slow_taken = _gvn.transform( new (C) IfTrueNode(opt_iff) );2341return slow_taken;2342}23432344//-----------------------------make_runtime_call-------------------------------2345Node* GraphKit::make_runtime_call(int flags,2346const TypeFunc* call_type, address call_addr,2347const char* call_name,2348const TypePtr* adr_type,2349// The following parms are all optional.2350// The first NULL ends the list.2351Node* parm0, Node* parm1,2352Node* parm2, Node* parm3,2353Node* parm4, Node* parm5,2354Node* parm6, Node* parm7) {2355// Slow-path call2356bool is_leaf = !(flags & RC_NO_LEAF);2357bool has_io = (!is_leaf && !(flags & RC_NO_IO));2358if (call_name == NULL) {2359assert(!is_leaf, "must supply name for leaf");2360call_name = OptoRuntime::stub_name(call_addr);2361}2362CallNode* call;2363if (!is_leaf) {2364call = new(C) CallStaticJavaNode(call_type, call_addr, call_name,2365bci(), adr_type);2366} else if (flags & RC_NO_FP) {2367call = new(C) CallLeafNoFPNode(call_type, call_addr, call_name, adr_type);2368} else {2369call = new(C) CallLeafNode(call_type, call_addr, call_name, adr_type);2370}23712372// The following is similar to set_edges_for_java_call,2373// except that the memory effects of the call are restricted to AliasIdxRaw.23742375// Slow path call has no side-effects, uses few values2376bool wide_in = !(flags & RC_NARROW_MEM);2377bool wide_out = (C->get_alias_index(adr_type) == Compile::AliasIdxBot);23782379Node* prev_mem = NULL;2380if (wide_in) {2381prev_mem = set_predefined_input_for_runtime_call(call);2382} else {2383assert(!wide_out, "narrow in => narrow out");2384Node* narrow_mem = memory(adr_type);2385prev_mem = set_predefined_input_for_runtime_call(call, narrow_mem);2386}23872388// Hook each parm in order. Stop looking at the first NULL.2389if (parm0 != NULL) { call->init_req(TypeFunc::Parms+0, parm0);2390if (parm1 != NULL) { call->init_req(TypeFunc::Parms+1, parm1);2391if (parm2 != NULL) { call->init_req(TypeFunc::Parms+2, parm2);2392if (parm3 != NULL) { call->init_req(TypeFunc::Parms+3, parm3);2393if (parm4 != NULL) { call->init_req(TypeFunc::Parms+4, parm4);2394if (parm5 != NULL) { call->init_req(TypeFunc::Parms+5, parm5);2395if (parm6 != NULL) { call->init_req(TypeFunc::Parms+6, parm6);2396if (parm7 != NULL) { call->init_req(TypeFunc::Parms+7, parm7);2397/* close each nested if ===> */ } } } } } } } }2398assert(call->in(call->req()-1) != NULL, "must initialize all parms");23992400if (!is_leaf) {2401// Non-leaves can block and take safepoints:2402add_safepoint_edges(call, ((flags & RC_MUST_THROW) != 0));2403}2404// Non-leaves can throw exceptions:2405if (has_io) {2406call->set_req(TypeFunc::I_O, i_o());2407}24082409if (flags & RC_UNCOMMON) {2410// Set the count to a tiny probability. Cf. Estimate_Block_Frequency.2411// (An "if" probability corresponds roughly to an unconditional count.2412// Sort of.)2413call->set_cnt(PROB_UNLIKELY_MAG(4));2414}24152416Node* c = _gvn.transform(call);2417assert(c == call, "cannot disappear");24182419if (wide_out) {2420// Slow path call has full side-effects.2421set_predefined_output_for_runtime_call(call);2422} else {2423// Slow path call has few side-effects, and/or sets few values.2424set_predefined_output_for_runtime_call(call, prev_mem, adr_type);2425}24262427if (has_io) {2428set_i_o(_gvn.transform(new (C) ProjNode(call, TypeFunc::I_O)));2429}2430return call;24312432}24332434//------------------------------merge_memory-----------------------------------2435// Merge memory from one path into the current memory state.2436void GraphKit::merge_memory(Node* new_mem, Node* region, int new_path) {2437for (MergeMemStream mms(merged_memory(), new_mem->as_MergeMem()); mms.next_non_empty2(); ) {2438Node* old_slice = mms.force_memory();2439Node* new_slice = mms.memory2();2440if (old_slice != new_slice) {2441PhiNode* phi;2442if (old_slice->is_Phi() && old_slice->as_Phi()->region() == region) {2443if (mms.is_empty()) {2444// clone base memory Phi's inputs for this memory slice2445assert(old_slice == mms.base_memory(), "sanity");2446phi = PhiNode::make(region, NULL, Type::MEMORY, mms.adr_type(C));2447_gvn.set_type(phi, Type::MEMORY);2448for (uint i = 1; i < phi->req(); i++) {2449phi->init_req(i, old_slice->in(i));2450}2451} else {2452phi = old_slice->as_Phi(); // Phi was generated already2453}2454} else {2455phi = PhiNode::make(region, old_slice, Type::MEMORY, mms.adr_type(C));2456_gvn.set_type(phi, Type::MEMORY);2457}2458phi->set_req(new_path, new_slice);2459mms.set_memory(phi);2460}2461}2462}24632464//------------------------------make_slow_call_ex------------------------------2465// Make the exception handler hookups for the slow call2466void GraphKit::make_slow_call_ex(Node* call, ciInstanceKlass* ex_klass, bool separate_io_proj, bool deoptimize) {2467if (stopped()) return;24682469// Make a catch node with just two handlers: fall-through and catch-all2470Node* i_o = _gvn.transform( new (C) ProjNode(call, TypeFunc::I_O, separate_io_proj) );2471Node* catc = _gvn.transform( new (C) CatchNode(control(), i_o, 2) );2472Node* norm = _gvn.transform( new (C) CatchProjNode(catc, CatchProjNode::fall_through_index, CatchProjNode::no_handler_bci) );2473Node* excp = _gvn.transform( new (C) CatchProjNode(catc, CatchProjNode::catch_all_index, CatchProjNode::no_handler_bci) );24742475{ PreserveJVMState pjvms(this);2476set_control(excp);2477set_i_o(i_o);24782479if (excp != top()) {2480if (deoptimize) {2481// Deoptimize if an exception is caught. Don't construct exception state in this case.2482uncommon_trap(Deoptimization::Reason_unhandled,2483Deoptimization::Action_none);2484} else {2485// Create an exception state also.2486// Use an exact type if the caller has specified a specific exception.2487const Type* ex_type = TypeOopPtr::make_from_klass_unique(ex_klass)->cast_to_ptr_type(TypePtr::NotNull);2488Node* ex_oop = new (C) CreateExNode(ex_type, control(), i_o);2489add_exception_state(make_exception_state(_gvn.transform(ex_oop)));2490}2491}2492}24932494// Get the no-exception control from the CatchNode.2495set_control(norm);2496}249724982499//-------------------------------gen_subtype_check-----------------------------2500// Generate a subtyping check. Takes as input the subtype and supertype.2501// Returns 2 values: sets the default control() to the true path and returns2502// the false path. Only reads invariant memory; sets no (visible) memory.2503// The PartialSubtypeCheckNode sets the hidden 1-word cache in the encoding2504// but that's not exposed to the optimizer. This call also doesn't take in an2505// Object; if you wish to check an Object you need to load the Object's class2506// prior to coming here.2507Node* GraphKit::gen_subtype_check(Node* subklass, Node* superklass) {2508// Fast check for identical types, perhaps identical constants.2509// The types can even be identical non-constants, in cases2510// involving Array.newInstance, Object.clone, etc.2511if (subklass == superklass)2512return top(); // false path is dead; no test needed.25132514if (_gvn.type(superklass)->singleton()) {2515ciKlass* superk = _gvn.type(superklass)->is_klassptr()->klass();2516ciKlass* subk = _gvn.type(subklass)->is_klassptr()->klass();25172518// In the common case of an exact superklass, try to fold up the2519// test before generating code. You may ask, why not just generate2520// the code and then let it fold up? The answer is that the generated2521// code will necessarily include null checks, which do not always2522// completely fold away. If they are also needless, then they turn2523// into a performance loss. Example:2524// Foo[] fa = blah(); Foo x = fa[0]; fa[1] = x;2525// Here, the type of 'fa' is often exact, so the store check2526// of fa[1]=x will fold up, without testing the nullness of x.2527switch (static_subtype_check(superk, subk)) {2528case SSC_always_false:2529{2530Node* always_fail = control();2531set_control(top());2532return always_fail;2533}2534case SSC_always_true:2535return top();2536case SSC_easy_test:2537{2538// Just do a direct pointer compare and be done.2539Node* cmp = _gvn.transform( new(C) CmpPNode(subklass, superklass) );2540Node* bol = _gvn.transform( new(C) BoolNode(cmp, BoolTest::eq) );2541IfNode* iff = create_and_xform_if(control(), bol, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);2542set_control( _gvn.transform( new(C) IfTrueNode (iff) ) );2543return _gvn.transform( new(C) IfFalseNode(iff) );2544}2545case SSC_full_test:2546break;2547default:2548ShouldNotReachHere();2549}2550}25512552// %%% Possible further optimization: Even if the superklass is not exact,2553// if the subklass is the unique subtype of the superklass, the check2554// will always succeed. We could leave a dependency behind to ensure this.25552556// First load the super-klass's check-offset2557Node *p1 = basic_plus_adr( superklass, superklass, in_bytes(Klass::super_check_offset_offset()) );2558Node *chk_off = _gvn.transform(new (C) LoadINode(NULL, memory(p1), p1, _gvn.type(p1)->is_ptr(),2559TypeInt::INT, MemNode::unordered));2560int cacheoff_con = in_bytes(Klass::secondary_super_cache_offset());2561bool might_be_cache = (find_int_con(chk_off, cacheoff_con) == cacheoff_con);25622563// Load from the sub-klass's super-class display list, or a 1-word cache of2564// the secondary superclass list, or a failing value with a sentinel offset2565// if the super-klass is an interface or exceptionally deep in the Java2566// hierarchy and we have to scan the secondary superclass list the hard way.2567// Worst-case type is a little odd: NULL is allowed as a result (usually2568// klass loads can never produce a NULL).2569Node *chk_off_X = ConvI2X(chk_off);2570Node *p2 = _gvn.transform( new (C) AddPNode(subklass,subklass,chk_off_X) );2571// For some types like interfaces the following loadKlass is from a 1-word2572// cache which is mutable so can't use immutable memory. Other2573// types load from the super-class display table which is immutable.2574Node *kmem = might_be_cache ? memory(p2) : immutable_memory();2575Node* nkls = _gvn.transform(LoadKlassNode::make(_gvn, NULL, kmem, p2, _gvn.type(p2)->is_ptr(), TypeKlassPtr::OBJECT_OR_NULL));25762577// Compile speed common case: ARE a subtype and we canNOT fail2578if( superklass == nkls )2579return top(); // false path is dead; no test needed.25802581// See if we get an immediate positive hit. Happens roughly 83% of the2582// time. Test to see if the value loaded just previously from the subklass2583// is exactly the superklass.2584Node *cmp1 = _gvn.transform( new (C) CmpPNode( superklass, nkls ) );2585Node *bol1 = _gvn.transform( new (C) BoolNode( cmp1, BoolTest::eq ) );2586IfNode *iff1 = create_and_xform_if( control(), bol1, PROB_LIKELY(0.83f), COUNT_UNKNOWN );2587Node *iftrue1 = _gvn.transform( new (C) IfTrueNode ( iff1 ) );2588set_control( _gvn.transform( new (C) IfFalseNode( iff1 ) ) );25892590// Compile speed common case: Check for being deterministic right now. If2591// chk_off is a constant and not equal to cacheoff then we are NOT a2592// subklass. In this case we need exactly the 1 test above and we can2593// return those results immediately.2594if (!might_be_cache) {2595Node* not_subtype_ctrl = control();2596set_control(iftrue1); // We need exactly the 1 test above2597return not_subtype_ctrl;2598}25992600// Gather the various success & failures here2601RegionNode *r_ok_subtype = new (C) RegionNode(4);2602record_for_igvn(r_ok_subtype);2603RegionNode *r_not_subtype = new (C) RegionNode(3);2604record_for_igvn(r_not_subtype);26052606r_ok_subtype->init_req(1, iftrue1);26072608// Check for immediate negative hit. Happens roughly 11% of the time (which2609// is roughly 63% of the remaining cases). Test to see if the loaded2610// check-offset points into the subklass display list or the 1-element2611// cache. If it points to the display (and NOT the cache) and the display2612// missed then it's not a subtype.2613Node *cacheoff = _gvn.intcon(cacheoff_con);2614Node *cmp2 = _gvn.transform( new (C) CmpINode( chk_off, cacheoff ) );2615Node *bol2 = _gvn.transform( new (C) BoolNode( cmp2, BoolTest::ne ) );2616IfNode *iff2 = create_and_xform_if( control(), bol2, PROB_LIKELY(0.63f), COUNT_UNKNOWN );2617r_not_subtype->init_req(1, _gvn.transform( new (C) IfTrueNode (iff2) ) );2618set_control( _gvn.transform( new (C) IfFalseNode(iff2) ) );26192620// Check for self. Very rare to get here, but it is taken 1/3 the time.2621// No performance impact (too rare) but allows sharing of secondary arrays2622// which has some footprint reduction.2623Node *cmp3 = _gvn.transform( new (C) CmpPNode( subklass, superklass ) );2624Node *bol3 = _gvn.transform( new (C) BoolNode( cmp3, BoolTest::eq ) );2625IfNode *iff3 = create_and_xform_if( control(), bol3, PROB_LIKELY(0.36f), COUNT_UNKNOWN );2626r_ok_subtype->init_req(2, _gvn.transform( new (C) IfTrueNode ( iff3 ) ) );2627set_control( _gvn.transform( new (C) IfFalseNode( iff3 ) ) );26282629// -- Roads not taken here: --2630// We could also have chosen to perform the self-check at the beginning2631// of this code sequence, as the assembler does. This would not pay off2632// the same way, since the optimizer, unlike the assembler, can perform2633// static type analysis to fold away many successful self-checks.2634// Non-foldable self checks work better here in second position, because2635// the initial primary superclass check subsumes a self-check for most2636// types. An exception would be a secondary type like array-of-interface,2637// which does not appear in its own primary supertype display.2638// Finally, we could have chosen to move the self-check into the2639// PartialSubtypeCheckNode, and from there out-of-line in a platform2640// dependent manner. But it is worthwhile to have the check here,2641// where it can be perhaps be optimized. The cost in code space is2642// small (register compare, branch).26432644// Now do a linear scan of the secondary super-klass array. Again, no real2645// performance impact (too rare) but it's gotta be done.2646// Since the code is rarely used, there is no penalty for moving it2647// out of line, and it can only improve I-cache density.2648// The decision to inline or out-of-line this final check is platform2649// dependent, and is found in the AD file definition of PartialSubtypeCheck.2650Node* psc = _gvn.transform(2651new (C) PartialSubtypeCheckNode(control(), subklass, superklass) );26522653Node *cmp4 = _gvn.transform( new (C) CmpPNode( psc, null() ) );2654Node *bol4 = _gvn.transform( new (C) BoolNode( cmp4, BoolTest::ne ) );2655IfNode *iff4 = create_and_xform_if( control(), bol4, PROB_FAIR, COUNT_UNKNOWN );2656r_not_subtype->init_req(2, _gvn.transform( new (C) IfTrueNode (iff4) ) );2657r_ok_subtype ->init_req(3, _gvn.transform( new (C) IfFalseNode(iff4) ) );26582659// Return false path; set default control to true path.2660set_control( _gvn.transform(r_ok_subtype) );2661return _gvn.transform(r_not_subtype);2662}26632664//----------------------------static_subtype_check-----------------------------2665// Shortcut important common cases when superklass is exact:2666// (0) superklass is java.lang.Object (can occur in reflective code)2667// (1) subklass is already limited to a subtype of superklass => always ok2668// (2) subklass does not overlap with superklass => always fail2669// (3) superklass has NO subtypes and we can check with a simple compare.2670int GraphKit::static_subtype_check(ciKlass* superk, ciKlass* subk) {2671if (StressReflectiveCode) {2672return SSC_full_test; // Let caller generate the general case.2673}26742675if (superk == env()->Object_klass()) {2676return SSC_always_true; // (0) this test cannot fail2677}26782679ciType* superelem = superk;2680if (superelem->is_array_klass())2681superelem = superelem->as_array_klass()->base_element_type();26822683if (!subk->is_interface()) { // cannot trust static interface types yet2684if (subk->is_subtype_of(superk)) {2685return SSC_always_true; // (1) false path dead; no dynamic test needed2686}2687if (!(superelem->is_klass() && superelem->as_klass()->is_interface()) &&2688!superk->is_subtype_of(subk)) {2689return SSC_always_false;2690}2691}26922693// If casting to an instance klass, it must have no subtypes2694if (superk->is_interface()) {2695// Cannot trust interfaces yet.2696// %%% S.B. superk->nof_implementors() == 12697} else if (superelem->is_instance_klass()) {2698ciInstanceKlass* ik = superelem->as_instance_klass();2699if (!ik->has_subklass() && !ik->is_interface()) {2700if (!ik->is_final()) {2701// Add a dependency if there is a chance of a later subclass.2702C->dependencies()->assert_leaf_type(ik);2703}2704return SSC_easy_test; // (3) caller can do a simple ptr comparison2705}2706} else {2707// A primitive array type has no subtypes.2708return SSC_easy_test; // (3) caller can do a simple ptr comparison2709}27102711return SSC_full_test;2712}27132714// Profile-driven exact type check:2715Node* GraphKit::type_check_receiver(Node* receiver, ciKlass* klass,2716float prob,2717Node* *casted_receiver) {2718const TypeKlassPtr* tklass = TypeKlassPtr::make(klass);2719Node* recv_klass = load_object_klass(receiver);2720Node* want_klass = makecon(tklass);2721Node* cmp = _gvn.transform( new(C) CmpPNode(recv_klass, want_klass) );2722Node* bol = _gvn.transform( new(C) BoolNode(cmp, BoolTest::eq) );2723IfNode* iff = create_and_xform_if(control(), bol, prob, COUNT_UNKNOWN);2724set_control( _gvn.transform( new(C) IfTrueNode (iff) ));2725Node* fail = _gvn.transform( new(C) IfFalseNode(iff) );27262727const TypeOopPtr* recv_xtype = tklass->as_instance_type();2728assert(recv_xtype->klass_is_exact(), "");27292730// Subsume downstream occurrences of receiver with a cast to2731// recv_xtype, since now we know what the type will be.2732Node* cast = new(C) CheckCastPPNode(control(), receiver, recv_xtype);2733(*casted_receiver) = _gvn.transform(cast);2734// (User must make the replace_in_map call.)27352736return fail;2737}273827392740//------------------------------seems_never_null-------------------------------2741// Use null_seen information if it is available from the profile.2742// If we see an unexpected null at a type check we record it and force a2743// recompile; the offending check will be recompiled to handle NULLs.2744// If we see several offending BCIs, then all checks in the2745// method will be recompiled.2746bool GraphKit::seems_never_null(Node* obj, ciProfileData* data) {2747if (UncommonNullCast // Cutout for this technique2748&& obj != null() // And not the -Xcomp stupid case?2749&& !too_many_traps(Deoptimization::Reason_null_check)2750) {2751if (data == NULL)2752// Edge case: no mature data. Be optimistic here.2753return true;2754// If the profile has not seen a null, assume it won't happen.2755assert(java_bc() == Bytecodes::_checkcast ||2756java_bc() == Bytecodes::_instanceof ||2757java_bc() == Bytecodes::_aastore, "MDO must collect null_seen bit here");2758return !data->as_BitData()->null_seen();2759}2760return false;2761}27622763//------------------------maybe_cast_profiled_receiver-------------------------2764// If the profile has seen exactly one type, narrow to exactly that type.2765// Subsequent type checks will always fold up.2766Node* GraphKit::maybe_cast_profiled_receiver(Node* not_null_obj,2767ciKlass* require_klass,2768ciKlass* spec_klass,2769bool safe_for_replace) {2770if (!UseTypeProfile || !TypeProfileCasts) return NULL;27712772Deoptimization::DeoptReason reason = spec_klass == NULL ? Deoptimization::Reason_class_check : Deoptimization::Reason_speculate_class_check;27732774// Make sure we haven't already deoptimized from this tactic.2775if (too_many_traps(reason) || too_many_recompiles(reason))2776return NULL;27772778// (No, this isn't a call, but it's enough like a virtual call2779// to use the same ciMethod accessor to get the profile info...)2780// If we have a speculative type use it instead of profiling (which2781// may not help us)2782ciKlass* exact_kls = spec_klass == NULL ? profile_has_unique_klass() : spec_klass;2783if (exact_kls != NULL) {// no cast failures here2784if (require_klass == NULL ||2785static_subtype_check(require_klass, exact_kls) == SSC_always_true) {2786// If we narrow the type to match what the type profile sees or2787// the speculative type, we can then remove the rest of the2788// cast.2789// This is a win, even if the exact_kls is very specific,2790// because downstream operations, such as method calls,2791// will often benefit from the sharper type.2792Node* exact_obj = not_null_obj; // will get updated in place...2793Node* slow_ctl = type_check_receiver(exact_obj, exact_kls, 1.0,2794&exact_obj);2795{ PreserveJVMState pjvms(this);2796set_control(slow_ctl);2797uncommon_trap_exact(reason, Deoptimization::Action_maybe_recompile);2798}2799if (safe_for_replace) {2800replace_in_map(not_null_obj, exact_obj);2801}2802return exact_obj;2803}2804// assert(ssc == SSC_always_true)... except maybe the profile lied to us.2805}28062807return NULL;2808}28092810/**2811* Cast obj to type and emit guard unless we had too many traps here2812* already2813*2814* @param obj node being casted2815* @param type type to cast the node to2816* @param not_null true if we know node cannot be null2817*/2818Node* GraphKit::maybe_cast_profiled_obj(Node* obj,2819ciKlass* type,2820bool not_null) {2821// type == NULL if profiling tells us this object is always null2822if (type != NULL) {2823Deoptimization::DeoptReason class_reason = Deoptimization::Reason_speculate_class_check;2824Deoptimization::DeoptReason null_reason = Deoptimization::Reason_null_check;2825if (!too_many_traps(null_reason) && !too_many_recompiles(null_reason) &&2826!too_many_traps(class_reason) && !too_many_recompiles(class_reason)) {2827Node* not_null_obj = NULL;2828// not_null is true if we know the object is not null and2829// there's no need for a null check2830if (!not_null) {2831Node* null_ctl = top();2832not_null_obj = null_check_oop(obj, &null_ctl, true, true);2833assert(null_ctl->is_top(), "no null control here");2834} else {2835not_null_obj = obj;2836}28372838Node* exact_obj = not_null_obj;2839ciKlass* exact_kls = type;2840Node* slow_ctl = type_check_receiver(exact_obj, exact_kls, 1.0,2841&exact_obj);2842{2843PreserveJVMState pjvms(this);2844set_control(slow_ctl);2845uncommon_trap_exact(class_reason, Deoptimization::Action_maybe_recompile);2846}2847replace_in_map(not_null_obj, exact_obj);2848obj = exact_obj;2849}2850} else {2851if (!too_many_traps(Deoptimization::Reason_null_assert) &&2852!too_many_recompiles(Deoptimization::Reason_null_assert)) {2853Node* exact_obj = null_assert(obj);2854replace_in_map(obj, exact_obj);2855obj = exact_obj;2856}2857}2858return obj;2859}28602861//-------------------------------gen_instanceof--------------------------------2862// Generate an instance-of idiom. Used by both the instance-of bytecode2863// and the reflective instance-of call.2864Node* GraphKit::gen_instanceof(Node* obj, Node* superklass, bool safe_for_replace) {2865kill_dead_locals(); // Benefit all the uncommon traps2866assert( !stopped(), "dead parse path should be checked in callers" );2867assert(!TypePtr::NULL_PTR->higher_equal(_gvn.type(superklass)->is_klassptr()),2868"must check for not-null not-dead klass in callers");28692870// Make the merge point2871enum { _obj_path = 1, _fail_path, _null_path, PATH_LIMIT };2872RegionNode* region = new(C) RegionNode(PATH_LIMIT);2873Node* phi = new(C) PhiNode(region, TypeInt::BOOL);2874C->set_has_split_ifs(true); // Has chance for split-if optimization28752876ciProfileData* data = NULL;2877if (java_bc() == Bytecodes::_instanceof) { // Only for the bytecode2878data = method()->method_data()->bci_to_data(bci());2879}2880bool never_see_null = (ProfileDynamicTypes // aggressive use of profile2881&& seems_never_null(obj, data));28822883// Null check; get casted pointer; set region slot 32884Node* null_ctl = top();2885Node* not_null_obj = null_check_oop(obj, &null_ctl, never_see_null, safe_for_replace);28862887// If not_null_obj is dead, only null-path is taken2888if (stopped()) { // Doing instance-of on a NULL?2889set_control(null_ctl);2890return intcon(0);2891}2892region->init_req(_null_path, null_ctl);2893phi ->init_req(_null_path, intcon(0)); // Set null path value2894if (null_ctl == top()) {2895// Do this eagerly, so that pattern matches like is_diamond_phi2896// will work even during parsing.2897assert(_null_path == PATH_LIMIT-1, "delete last");2898region->del_req(_null_path);2899phi ->del_req(_null_path);2900}29012902// Do we know the type check always succeed?2903bool known_statically = false;2904if (_gvn.type(superklass)->singleton()) {2905ciKlass* superk = _gvn.type(superklass)->is_klassptr()->klass();2906ciKlass* subk = _gvn.type(obj)->is_oopptr()->klass();2907if (subk != NULL && subk->is_loaded()) {2908int static_res = static_subtype_check(superk, subk);2909known_statically = (static_res == SSC_always_true || static_res == SSC_always_false);2910}2911}29122913if (known_statically && UseTypeSpeculation) {2914// If we know the type check always succeeds then we don't use the2915// profiling data at this bytecode. Don't lose it, feed it to the2916// type system as a speculative type.2917not_null_obj = record_profiled_receiver_for_speculation(not_null_obj);2918} else {2919const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();2920// We may not have profiling here or it may not help us. If we2921// have a speculative type use it to perform an exact cast.2922ciKlass* spec_obj_type = obj_type->speculative_type();2923if (spec_obj_type != NULL || (ProfileDynamicTypes && data != NULL)) {2924Node* cast_obj = maybe_cast_profiled_receiver(not_null_obj, NULL, spec_obj_type, safe_for_replace);2925if (stopped()) { // Profile disagrees with this path.2926set_control(null_ctl); // Null is the only remaining possibility.2927return intcon(0);2928}2929if (cast_obj != NULL) {2930not_null_obj = cast_obj;2931}2932}2933}29342935// Load the object's klass2936Node* obj_klass = load_object_klass(not_null_obj);29372938// Generate the subtype check2939Node* not_subtype_ctrl = gen_subtype_check(obj_klass, superklass);29402941// Plug in the success path to the general merge in slot 1.2942region->init_req(_obj_path, control());2943phi ->init_req(_obj_path, intcon(1));29442945// Plug in the failing path to the general merge in slot 2.2946region->init_req(_fail_path, not_subtype_ctrl);2947phi ->init_req(_fail_path, intcon(0));29482949// Return final merged results2950set_control( _gvn.transform(region) );2951record_for_igvn(region);2952return _gvn.transform(phi);2953}29542955//-------------------------------gen_checkcast---------------------------------2956// Generate a checkcast idiom. Used by both the checkcast bytecode and the2957// array store bytecode. Stack must be as-if BEFORE doing the bytecode so the2958// uncommon-trap paths work. Adjust stack after this call.2959// If failure_control is supplied and not null, it is filled in with2960// the control edge for the cast failure. Otherwise, an appropriate2961// uncommon trap or exception is thrown.2962Node* GraphKit::gen_checkcast(Node *obj, Node* superklass,2963Node* *failure_control) {2964kill_dead_locals(); // Benefit all the uncommon traps2965const TypeKlassPtr *tk = _gvn.type(superklass)->is_klassptr();2966const Type *toop = TypeOopPtr::make_from_klass(tk->klass());29672968// Fast cutout: Check the case that the cast is vacuously true.2969// This detects the common cases where the test will short-circuit2970// away completely. We do this before we perform the null check,2971// because if the test is going to turn into zero code, we don't2972// want a residual null check left around. (Causes a slowdown,2973// for example, in some objArray manipulations, such as a[i]=a[j].)2974if (tk->singleton()) {2975const TypeOopPtr* objtp = _gvn.type(obj)->isa_oopptr();2976if (objtp != NULL && objtp->klass() != NULL) {2977switch (static_subtype_check(tk->klass(), objtp->klass())) {2978case SSC_always_true:2979// If we know the type check always succeed then we don't use2980// the profiling data at this bytecode. Don't lose it, feed it2981// to the type system as a speculative type.2982return record_profiled_receiver_for_speculation(obj);2983case SSC_always_false:2984// It needs a null check because a null will *pass* the cast check.2985// A non-null value will always produce an exception.2986return null_assert(obj);2987}2988}2989}29902991ciProfileData* data = NULL;2992bool safe_for_replace = false;2993if (failure_control == NULL) { // use MDO in regular case only2994assert(java_bc() == Bytecodes::_aastore ||2995java_bc() == Bytecodes::_checkcast,2996"interpreter profiles type checks only for these BCs");2997data = method()->method_data()->bci_to_data(bci());2998safe_for_replace = true;2999}30003001// Make the merge point3002enum { _obj_path = 1, _null_path, PATH_LIMIT };3003RegionNode* region = new (C) RegionNode(PATH_LIMIT);3004Node* phi = new (C) PhiNode(region, toop);3005C->set_has_split_ifs(true); // Has chance for split-if optimization30063007// Use null-cast information if it is available3008bool never_see_null = ((failure_control == NULL) // regular case only3009&& seems_never_null(obj, data));30103011// Null check; get casted pointer; set region slot 33012Node* null_ctl = top();3013Node* not_null_obj = null_check_oop(obj, &null_ctl, never_see_null, safe_for_replace);30143015// If not_null_obj is dead, only null-path is taken3016if (stopped()) { // Doing instance-of on a NULL?3017set_control(null_ctl);3018return null();3019}3020region->init_req(_null_path, null_ctl);3021phi ->init_req(_null_path, null()); // Set null path value3022if (null_ctl == top()) {3023// Do this eagerly, so that pattern matches like is_diamond_phi3024// will work even during parsing.3025assert(_null_path == PATH_LIMIT-1, "delete last");3026region->del_req(_null_path);3027phi ->del_req(_null_path);3028}30293030Node* cast_obj = NULL;3031if (tk->klass_is_exact()) {3032// The following optimization tries to statically cast the speculative type of the object3033// (for example obtained during profiling) to the type of the superklass and then do a3034// dynamic check that the type of the object is what we expect. To work correctly3035// for checkcast and aastore the type of superklass should be exact.3036const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();3037// We may not have profiling here or it may not help us. If we have3038// a speculative type use it to perform an exact cast.3039ciKlass* spec_obj_type = obj_type->speculative_type();3040if (spec_obj_type != NULL ||3041(data != NULL &&3042// Counter has never been decremented (due to cast failure).3043// ...This is a reasonable thing to expect. It is true of3044// all casts inserted by javac to implement generic types.3045data->as_CounterData()->count() >= 0)) {3046cast_obj = maybe_cast_profiled_receiver(not_null_obj, tk->klass(), spec_obj_type, safe_for_replace);3047if (cast_obj != NULL) {3048if (failure_control != NULL) // failure is now impossible3049(*failure_control) = top();3050// adjust the type of the phi to the exact klass:3051phi->raise_bottom_type(_gvn.type(cast_obj)->meet_speculative(TypePtr::NULL_PTR));3052}3053}3054}30553056if (cast_obj == NULL) {3057// Load the object's klass3058Node* obj_klass = load_object_klass(not_null_obj);30593060// Generate the subtype check3061Node* not_subtype_ctrl = gen_subtype_check( obj_klass, superklass );30623063// Plug in success path into the merge3064cast_obj = _gvn.transform(new (C) CheckCastPPNode(control(),3065not_null_obj, toop));3066// Failure path ends in uncommon trap (or may be dead - failure impossible)3067if (failure_control == NULL) {3068if (not_subtype_ctrl != top()) { // If failure is possible3069PreserveJVMState pjvms(this);3070set_control(not_subtype_ctrl);3071builtin_throw(Deoptimization::Reason_class_check, obj_klass);3072}3073} else {3074(*failure_control) = not_subtype_ctrl;3075}3076}30773078region->init_req(_obj_path, control());3079phi ->init_req(_obj_path, cast_obj);30803081// A merge of NULL or Casted-NotNull obj3082Node* res = _gvn.transform(phi);30833084// Note I do NOT always 'replace_in_map(obj,result)' here.3085// if( tk->klass()->can_be_primary_super() )3086// This means that if I successfully store an Object into an array-of-String3087// I 'forget' that the Object is really now known to be a String. I have to3088// do this because we don't have true union types for interfaces - if I store3089// a Baz into an array-of-Interface and then tell the optimizer it's an3090// Interface, I forget that it's also a Baz and cannot do Baz-like field3091// references to it. FIX THIS WHEN UNION TYPES APPEAR!3092// replace_in_map( obj, res );30933094// Return final merged results3095set_control( _gvn.transform(region) );3096record_for_igvn(region);3097return res;3098}30993100//------------------------------next_monitor-----------------------------------3101// What number should be given to the next monitor?3102int GraphKit::next_monitor() {3103int current = jvms()->monitor_depth()* C->sync_stack_slots();3104int next = current + C->sync_stack_slots();3105// Keep the toplevel high water mark current:3106if (C->fixed_slots() < next) C->set_fixed_slots(next);3107return current;3108}31093110//------------------------------insert_mem_bar---------------------------------3111// Memory barrier to avoid floating things around3112// The membar serves as a pinch point between both control and all memory slices.3113Node* GraphKit::insert_mem_bar(int opcode, Node* precedent) {3114MemBarNode* mb = MemBarNode::make(C, opcode, Compile::AliasIdxBot, precedent);3115mb->init_req(TypeFunc::Control, control());3116mb->init_req(TypeFunc::Memory, reset_memory());3117Node* membar = _gvn.transform(mb);3118set_control(_gvn.transform(new (C) ProjNode(membar, TypeFunc::Control)));3119set_all_memory_call(membar);3120return membar;3121}31223123//-------------------------insert_mem_bar_volatile----------------------------3124// Memory barrier to avoid floating things around3125// The membar serves as a pinch point between both control and memory(alias_idx).3126// If you want to make a pinch point on all memory slices, do not use this3127// function (even with AliasIdxBot); use insert_mem_bar() instead.3128Node* GraphKit::insert_mem_bar_volatile(int opcode, int alias_idx, Node* precedent) {3129// When Parse::do_put_xxx updates a volatile field, it appends a series3130// of MemBarVolatile nodes, one for *each* volatile field alias category.3131// The first membar is on the same memory slice as the field store opcode.3132// This forces the membar to follow the store. (Bug 6500685 broke this.)3133// All the other membars (for other volatile slices, including AliasIdxBot,3134// which stands for all unknown volatile slices) are control-dependent3135// on the first membar. This prevents later volatile loads or stores3136// from sliding up past the just-emitted store.31373138MemBarNode* mb = MemBarNode::make(C, opcode, alias_idx, precedent);3139mb->set_req(TypeFunc::Control,control());3140if (alias_idx == Compile::AliasIdxBot) {3141mb->set_req(TypeFunc::Memory, merged_memory()->base_memory());3142} else {3143assert(!(opcode == Op_Initialize && alias_idx != Compile::AliasIdxRaw), "fix caller");3144mb->set_req(TypeFunc::Memory, memory(alias_idx));3145}3146Node* membar = _gvn.transform(mb);3147set_control(_gvn.transform(new (C) ProjNode(membar, TypeFunc::Control)));3148if (alias_idx == Compile::AliasIdxBot) {3149merged_memory()->set_base_memory(_gvn.transform(new (C) ProjNode(membar, TypeFunc::Memory)));3150} else {3151set_memory(_gvn.transform(new (C) ProjNode(membar, TypeFunc::Memory)),alias_idx);3152}3153return membar;3154}31553156//------------------------------shared_lock------------------------------------3157// Emit locking code.3158FastLockNode* GraphKit::shared_lock(Node* obj) {3159// bci is either a monitorenter bc or InvocationEntryBci3160// %%% SynchronizationEntryBCI is redundant; use InvocationEntryBci in interfaces3161assert(SynchronizationEntryBCI == InvocationEntryBci, "");31623163if( !GenerateSynchronizationCode )3164return NULL; // Not locking things?3165if (stopped()) // Dead monitor?3166return NULL;31673168assert(dead_locals_are_killed(), "should kill locals before sync. point");31693170// Box the stack location3171Node* box = _gvn.transform(new (C) BoxLockNode(next_monitor()));3172Node* mem = reset_memory();31733174FastLockNode * flock = _gvn.transform(new (C) FastLockNode(0, obj, box) )->as_FastLock();3175if (UseBiasedLocking && PrintPreciseBiasedLockingStatistics) {3176// Create the counters for this fast lock.3177flock->create_lock_counter(sync_jvms()); // sync_jvms used to get current bci3178}31793180// Create the rtm counters for this fast lock if needed.3181flock->create_rtm_lock_counter(sync_jvms()); // sync_jvms used to get current bci31823183// Add monitor to debug info for the slow path. If we block inside the3184// slow path and de-opt, we need the monitor hanging around3185map()->push_monitor( flock );31863187const TypeFunc *tf = LockNode::lock_type();3188LockNode *lock = new (C) LockNode(C, tf);31893190lock->init_req( TypeFunc::Control, control() );3191lock->init_req( TypeFunc::Memory , mem );3192lock->init_req( TypeFunc::I_O , top() ) ; // does no i/o3193lock->init_req( TypeFunc::FramePtr, frameptr() );3194lock->init_req( TypeFunc::ReturnAdr, top() );31953196lock->init_req(TypeFunc::Parms + 0, obj);3197lock->init_req(TypeFunc::Parms + 1, box);3198lock->init_req(TypeFunc::Parms + 2, flock);3199add_safepoint_edges(lock);32003201lock = _gvn.transform( lock )->as_Lock();32023203// lock has no side-effects, sets few values3204set_predefined_output_for_runtime_call(lock, mem, TypeRawPtr::BOTTOM);32053206insert_mem_bar(Op_MemBarAcquireLock);32073208// Add this to the worklist so that the lock can be eliminated3209record_for_igvn(lock);32103211#ifndef PRODUCT3212if (PrintLockStatistics) {3213// Update the counter for this lock. Don't bother using an atomic3214// operation since we don't require absolute accuracy.3215lock->create_lock_counter(map()->jvms());3216increment_counter(lock->counter()->addr());3217}3218#endif32193220return flock;3221}322232233224//------------------------------shared_unlock----------------------------------3225// Emit unlocking code.3226void GraphKit::shared_unlock(Node* box, Node* obj) {3227// bci is either a monitorenter bc or InvocationEntryBci3228// %%% SynchronizationEntryBCI is redundant; use InvocationEntryBci in interfaces3229assert(SynchronizationEntryBCI == InvocationEntryBci, "");32303231if( !GenerateSynchronizationCode )3232return;3233if (stopped()) { // Dead monitor?3234map()->pop_monitor(); // Kill monitor from debug info3235return;3236}32373238// Memory barrier to avoid floating things down past the locked region3239insert_mem_bar(Op_MemBarReleaseLock);32403241const TypeFunc *tf = OptoRuntime::complete_monitor_exit_Type();3242UnlockNode *unlock = new (C) UnlockNode(C, tf);3243#ifdef ASSERT3244unlock->set_dbg_jvms(sync_jvms());3245#endif3246uint raw_idx = Compile::AliasIdxRaw;3247unlock->init_req( TypeFunc::Control, control() );3248unlock->init_req( TypeFunc::Memory , memory(raw_idx) );3249unlock->init_req( TypeFunc::I_O , top() ) ; // does no i/o3250unlock->init_req( TypeFunc::FramePtr, frameptr() );3251unlock->init_req( TypeFunc::ReturnAdr, top() );32523253unlock->init_req(TypeFunc::Parms + 0, obj);3254unlock->init_req(TypeFunc::Parms + 1, box);3255unlock = _gvn.transform(unlock)->as_Unlock();32563257Node* mem = reset_memory();32583259// unlock has no side-effects, sets few values3260set_predefined_output_for_runtime_call(unlock, mem, TypeRawPtr::BOTTOM);32613262// Kill monitor from debug info3263map()->pop_monitor( );3264}32653266//-------------------------------get_layout_helper-----------------------------3267// If the given klass is a constant or known to be an array,3268// fetch the constant layout helper value into constant_value3269// and return (Node*)NULL. Otherwise, load the non-constant3270// layout helper value, and return the node which represents it.3271// This two-faced routine is useful because allocation sites3272// almost always feature constant types.3273Node* GraphKit::get_layout_helper(Node* klass_node, jint& constant_value) {3274const TypeKlassPtr* inst_klass = _gvn.type(klass_node)->isa_klassptr();3275if (!StressReflectiveCode && inst_klass != NULL) {3276ciKlass* klass = inst_klass->klass();3277bool xklass = inst_klass->klass_is_exact();3278if (xklass || klass->is_array_klass()) {3279jint lhelper = klass->layout_helper();3280if (lhelper != Klass::_lh_neutral_value) {3281constant_value = lhelper;3282return (Node*) NULL;3283}3284}3285}3286constant_value = Klass::_lh_neutral_value; // put in a known value3287Node* lhp = basic_plus_adr(klass_node, klass_node, in_bytes(Klass::layout_helper_offset()));3288return make_load(NULL, lhp, TypeInt::INT, T_INT, MemNode::unordered);3289}32903291// We just put in an allocate/initialize with a big raw-memory effect.3292// Hook selected additional alias categories on the initialization.3293static void hook_memory_on_init(GraphKit& kit, int alias_idx,3294MergeMemNode* init_in_merge,3295Node* init_out_raw) {3296DEBUG_ONLY(Node* init_in_raw = init_in_merge->base_memory());3297assert(init_in_merge->memory_at(alias_idx) == init_in_raw, "");32983299Node* prevmem = kit.memory(alias_idx);3300init_in_merge->set_memory_at(alias_idx, prevmem);3301kit.set_memory(init_out_raw, alias_idx);3302}33033304//---------------------------set_output_for_allocation-------------------------3305Node* GraphKit::set_output_for_allocation(AllocateNode* alloc,3306const TypeOopPtr* oop_type,3307bool deoptimize_on_exception) {3308int rawidx = Compile::AliasIdxRaw;3309alloc->set_req( TypeFunc::FramePtr, frameptr() );3310add_safepoint_edges(alloc);3311Node* allocx = _gvn.transform(alloc);3312set_control( _gvn.transform(new (C) ProjNode(allocx, TypeFunc::Control) ) );3313// create memory projection for i_o3314set_memory ( _gvn.transform( new (C) ProjNode(allocx, TypeFunc::Memory, true) ), rawidx );3315make_slow_call_ex(allocx, env()->Throwable_klass(), true, deoptimize_on_exception);33163317// create a memory projection as for the normal control path3318Node* malloc = _gvn.transform(new (C) ProjNode(allocx, TypeFunc::Memory));3319set_memory(malloc, rawidx);33203321// a normal slow-call doesn't change i_o, but an allocation does3322// we create a separate i_o projection for the normal control path3323set_i_o(_gvn.transform( new (C) ProjNode(allocx, TypeFunc::I_O, false) ) );3324Node* rawoop = _gvn.transform( new (C) ProjNode(allocx, TypeFunc::Parms) );33253326// put in an initialization barrier3327InitializeNode* init = insert_mem_bar_volatile(Op_Initialize, rawidx,3328rawoop)->as_Initialize();3329assert(alloc->initialization() == init, "2-way macro link must work");3330assert(init ->allocation() == alloc, "2-way macro link must work");3331{3332// Extract memory strands which may participate in the new object's3333// initialization, and source them from the new InitializeNode.3334// This will allow us to observe initializations when they occur,3335// and link them properly (as a group) to the InitializeNode.3336assert(init->in(InitializeNode::Memory) == malloc, "");3337MergeMemNode* minit_in = MergeMemNode::make(C, malloc);3338init->set_req(InitializeNode::Memory, minit_in);3339record_for_igvn(minit_in); // fold it up later, if possible3340Node* minit_out = memory(rawidx);3341assert(minit_out->is_Proj() && minit_out->in(0) == init, "");3342if (oop_type->isa_aryptr()) {3343const TypePtr* telemref = oop_type->add_offset(Type::OffsetBot);3344int elemidx = C->get_alias_index(telemref);3345hook_memory_on_init(*this, elemidx, minit_in, minit_out);3346} else if (oop_type->isa_instptr()) {3347ciInstanceKlass* ik = oop_type->klass()->as_instance_klass();3348for (int i = 0, len = ik->nof_nonstatic_fields(); i < len; i++) {3349ciField* field = ik->nonstatic_field_at(i);3350if (field->offset() >= TrackedInitializationLimit * HeapWordSize)3351continue; // do not bother to track really large numbers of fields3352// Find (or create) the alias category for this field:3353int fieldidx = C->alias_type(field)->index();3354hook_memory_on_init(*this, fieldidx, minit_in, minit_out);3355}3356}3357}33583359// Cast raw oop to the real thing...3360Node* javaoop = new (C) CheckCastPPNode(control(), rawoop, oop_type);3361javaoop = _gvn.transform(javaoop);3362C->set_recent_alloc(control(), javaoop);3363assert(just_allocated_object(control()) == javaoop, "just allocated");33643365#ifdef ASSERT3366{ // Verify that the AllocateNode::Ideal_allocation recognizers work:3367assert(AllocateNode::Ideal_allocation(rawoop, &_gvn) == alloc,3368"Ideal_allocation works");3369assert(AllocateNode::Ideal_allocation(javaoop, &_gvn) == alloc,3370"Ideal_allocation works");3371if (alloc->is_AllocateArray()) {3372assert(AllocateArrayNode::Ideal_array_allocation(rawoop, &_gvn) == alloc->as_AllocateArray(),3373"Ideal_allocation works");3374assert(AllocateArrayNode::Ideal_array_allocation(javaoop, &_gvn) == alloc->as_AllocateArray(),3375"Ideal_allocation works");3376} else {3377assert(alloc->in(AllocateNode::ALength)->is_top(), "no length, please");3378}3379}3380#endif //ASSERT33813382return javaoop;3383}33843385//---------------------------new_instance--------------------------------------3386// This routine takes a klass_node which may be constant (for a static type)3387// or may be non-constant (for reflective code). It will work equally well3388// for either, and the graph will fold nicely if the optimizer later reduces3389// the type to a constant.3390// The optional arguments are for specialized use by intrinsics:3391// - If 'extra_slow_test' if not null is an extra condition for the slow-path.3392// - If 'return_size_val', report the the total object size to the caller.3393// - deoptimize_on_exception controls how Java exceptions are handled (rethrow vs deoptimize)3394Node* GraphKit::new_instance(Node* klass_node,3395Node* extra_slow_test,3396Node* *return_size_val,3397bool deoptimize_on_exception) {3398// Compute size in doublewords3399// The size is always an integral number of doublewords, represented3400// as a positive bytewise size stored in the klass's layout_helper.3401// The layout_helper also encodes (in a low bit) the need for a slow path.3402jint layout_con = Klass::_lh_neutral_value;3403Node* layout_val = get_layout_helper(klass_node, layout_con);3404int layout_is_con = (layout_val == NULL);34053406if (extra_slow_test == NULL) extra_slow_test = intcon(0);3407// Generate the initial go-slow test. It's either ALWAYS (return a3408// Node for 1) or NEVER (return a NULL) or perhaps (in the reflective3409// case) a computed value derived from the layout_helper.3410Node* initial_slow_test = NULL;3411if (layout_is_con) {3412assert(!StressReflectiveCode, "stress mode does not use these paths");3413bool must_go_slow = Klass::layout_helper_needs_slow_path(layout_con);3414initial_slow_test = must_go_slow? intcon(1): extra_slow_test;34153416} else { // reflective case3417// This reflective path is used by Unsafe.allocateInstance.3418// (It may be stress-tested by specifying StressReflectiveCode.)3419// Basically, we want to get into the VM is there's an illegal argument.3420Node* bit = intcon(Klass::_lh_instance_slow_path_bit);3421initial_slow_test = _gvn.transform( new (C) AndINode(layout_val, bit) );3422if (extra_slow_test != intcon(0)) {3423initial_slow_test = _gvn.transform( new (C) OrINode(initial_slow_test, extra_slow_test) );3424}3425// (Macro-expander will further convert this to a Bool, if necessary.)3426}34273428// Find the size in bytes. This is easy; it's the layout_helper.3429// The size value must be valid even if the slow path is taken.3430Node* size = NULL;3431if (layout_is_con) {3432size = MakeConX(Klass::layout_helper_size_in_bytes(layout_con));3433} else { // reflective case3434// This reflective path is used by clone and Unsafe.allocateInstance.3435size = ConvI2X(layout_val);34363437// Clear the low bits to extract layout_helper_size_in_bytes:3438assert((int)Klass::_lh_instance_slow_path_bit < BytesPerLong, "clear bit");3439Node* mask = MakeConX(~ (intptr_t)right_n_bits(LogBytesPerLong));3440size = _gvn.transform( new (C) AndXNode(size, mask) );3441}3442if (return_size_val != NULL) {3443(*return_size_val) = size;3444}34453446// This is a precise notnull oop of the klass.3447// (Actually, it need not be precise if this is a reflective allocation.)3448// It's what we cast the result to.3449const TypeKlassPtr* tklass = _gvn.type(klass_node)->isa_klassptr();3450if (!tklass) tklass = TypeKlassPtr::OBJECT;3451const TypeOopPtr* oop_type = tklass->as_instance_type();34523453// Now generate allocation code34543455// The entire memory state is needed for slow path of the allocation3456// since GC and deoptimization can happened.3457Node *mem = reset_memory();3458set_all_memory(mem); // Create new memory state34593460AllocateNode* alloc3461= new (C) AllocateNode(C, AllocateNode::alloc_type(Type::TOP),3462control(), mem, i_o(),3463size, klass_node,3464initial_slow_test);34653466return set_output_for_allocation(alloc, oop_type, deoptimize_on_exception);3467}34683469//-------------------------------new_array-------------------------------------3470// helper for both newarray and anewarray3471// The 'length' parameter is (obviously) the length of the array.3472// See comments on new_instance for the meaning of the other arguments.3473Node* GraphKit::new_array(Node* klass_node, // array klass (maybe variable)3474Node* length, // number of array elements3475int nargs, // number of arguments to push back for uncommon trap3476Node* *return_size_val,3477bool deoptimize_on_exception) {3478jint layout_con = Klass::_lh_neutral_value;3479Node* layout_val = get_layout_helper(klass_node, layout_con);3480int layout_is_con = (layout_val == NULL);34813482if (!layout_is_con && !StressReflectiveCode &&3483!too_many_traps(Deoptimization::Reason_class_check)) {3484// This is a reflective array creation site.3485// Optimistically assume that it is a subtype of Object[],3486// so that we can fold up all the address arithmetic.3487layout_con = Klass::array_layout_helper(T_OBJECT);3488Node* cmp_lh = _gvn.transform( new(C) CmpINode(layout_val, intcon(layout_con)) );3489Node* bol_lh = _gvn.transform( new(C) BoolNode(cmp_lh, BoolTest::eq) );3490{ BuildCutout unless(this, bol_lh, PROB_MAX);3491inc_sp(nargs);3492uncommon_trap(Deoptimization::Reason_class_check,3493Deoptimization::Action_maybe_recompile);3494}3495layout_val = NULL;3496layout_is_con = true;3497}34983499// Generate the initial go-slow test. Make sure we do not overflow3500// if length is huge (near 2Gig) or negative! We do not need3501// exact double-words here, just a close approximation of needed3502// double-words. We can't add any offset or rounding bits, lest we3503// take a size -1 of bytes and make it positive. Use an unsigned3504// compare, so negative sizes look hugely positive.3505int fast_size_limit = FastAllocateSizeLimit;3506if (layout_is_con) {3507assert(!StressReflectiveCode, "stress mode does not use these paths");3508// Increase the size limit if we have exact knowledge of array type.3509int log2_esize = Klass::layout_helper_log2_element_size(layout_con);3510fast_size_limit <<= (LogBytesPerLong - log2_esize);3511}35123513Node* initial_slow_cmp = _gvn.transform( new (C) CmpUNode( length, intcon( fast_size_limit ) ) );3514Node* initial_slow_test = _gvn.transform( new (C) BoolNode( initial_slow_cmp, BoolTest::gt ) );35153516// --- Size Computation ---3517// array_size = round_to_heap(array_header + (length << elem_shift));3518// where round_to_heap(x) == round_to(x, MinObjAlignmentInBytes)3519// and round_to(x, y) == ((x + y-1) & ~(y-1))3520// The rounding mask is strength-reduced, if possible.3521int round_mask = MinObjAlignmentInBytes - 1;3522Node* header_size = NULL;3523int header_size_min = arrayOopDesc::base_offset_in_bytes(T_BYTE);3524// (T_BYTE has the weakest alignment and size restrictions...)3525if (layout_is_con) {3526int hsize = Klass::layout_helper_header_size(layout_con);3527int eshift = Klass::layout_helper_log2_element_size(layout_con);3528BasicType etype = Klass::layout_helper_element_type(layout_con);3529if ((round_mask & ~right_n_bits(eshift)) == 0)3530round_mask = 0; // strength-reduce it if it goes away completely3531assert((hsize & right_n_bits(eshift)) == 0, "hsize is pre-rounded");3532assert(header_size_min <= hsize, "generic minimum is smallest");3533header_size_min = hsize;3534header_size = intcon(hsize + round_mask);3535} else {3536Node* hss = intcon(Klass::_lh_header_size_shift);3537Node* hsm = intcon(Klass::_lh_header_size_mask);3538Node* hsize = _gvn.transform( new(C) URShiftINode(layout_val, hss) );3539hsize = _gvn.transform( new(C) AndINode(hsize, hsm) );3540Node* mask = intcon(round_mask);3541header_size = _gvn.transform( new(C) AddINode(hsize, mask) );3542}35433544Node* elem_shift = NULL;3545if (layout_is_con) {3546int eshift = Klass::layout_helper_log2_element_size(layout_con);3547if (eshift != 0)3548elem_shift = intcon(eshift);3549} else {3550// There is no need to mask or shift this value.3551// The semantics of LShiftINode include an implicit mask to 0x1F.3552assert(Klass::_lh_log2_element_size_shift == 0, "use shift in place");3553elem_shift = layout_val;3554}35553556// Transition to native address size for all offset calculations:3557Node* lengthx = ConvI2X(length);3558Node* headerx = ConvI2X(header_size);3559#ifdef _LP643560{ const TypeInt* tilen = _gvn.find_int_type(length);3561if (tilen != NULL && tilen->_lo < 0) {3562// Add a manual constraint to a positive range. Cf. array_element_address.3563jlong size_max = fast_size_limit;3564if (size_max > tilen->_hi) size_max = tilen->_hi;3565const TypeInt* tlcon = TypeInt::make(0, size_max, Type::WidenMin);35663567// Only do a narrow I2L conversion if the range check passed.3568IfNode* iff = new (C) IfNode(control(), initial_slow_test, PROB_MIN, COUNT_UNKNOWN);3569_gvn.transform(iff);3570RegionNode* region = new (C) RegionNode(3);3571_gvn.set_type(region, Type::CONTROL);3572lengthx = new (C) PhiNode(region, TypeLong::LONG);3573_gvn.set_type(lengthx, TypeLong::LONG);35743575// Range check passed. Use ConvI2L node with narrow type.3576Node* passed = IfFalse(iff);3577region->init_req(1, passed);3578// Make I2L conversion control dependent to prevent it from3579// floating above the range check during loop optimizations.3580lengthx->init_req(1, C->constrained_convI2L(&_gvn, length, tlcon, passed));35813582// Range check failed. Use ConvI2L with wide type because length may be invalid.3583region->init_req(2, IfTrue(iff));3584lengthx->init_req(2, ConvI2X(length));35853586set_control(region);3587record_for_igvn(region);3588record_for_igvn(lengthx);3589}3590}3591#endif35923593// Combine header size (plus rounding) and body size. Then round down.3594// This computation cannot overflow, because it is used only in two3595// places, one where the length is sharply limited, and the other3596// after a successful allocation.3597Node* abody = lengthx;3598if (elem_shift != NULL)3599abody = _gvn.transform( new(C) LShiftXNode(lengthx, elem_shift) );3600Node* size = _gvn.transform( new(C) AddXNode(headerx, abody) );3601if (round_mask != 0) {3602Node* mask = MakeConX(~round_mask);3603size = _gvn.transform( new(C) AndXNode(size, mask) );3604}3605// else if round_mask == 0, the size computation is self-rounding36063607if (return_size_val != NULL) {3608// This is the size3609(*return_size_val) = size;3610}36113612// Now generate allocation code36133614// The entire memory state is needed for slow path of the allocation3615// since GC and deoptimization can happened.3616Node *mem = reset_memory();3617set_all_memory(mem); // Create new memory state36183619if (initial_slow_test->is_Bool()) {3620// Hide it behind a CMoveI, or else PhaseIdealLoop::split_up will get sick.3621initial_slow_test = initial_slow_test->as_Bool()->as_int_value(&_gvn);3622}36233624// Create the AllocateArrayNode and its result projections3625AllocateArrayNode* alloc3626= new (C) AllocateArrayNode(C, AllocateArrayNode::alloc_type(TypeInt::INT),3627control(), mem, i_o(),3628size, klass_node,3629initial_slow_test,3630length);36313632// Cast to correct type. Note that the klass_node may be constant or not,3633// and in the latter case the actual array type will be inexact also.3634// (This happens via a non-constant argument to inline_native_newArray.)3635// In any case, the value of klass_node provides the desired array type.3636const TypeInt* length_type = _gvn.find_int_type(length);3637const TypeOopPtr* ary_type = _gvn.type(klass_node)->is_klassptr()->as_instance_type();3638if (ary_type->isa_aryptr() && length_type != NULL) {3639// Try to get a better type than POS for the size3640ary_type = ary_type->is_aryptr()->cast_to_size(length_type);3641}36423643Node* javaoop = set_output_for_allocation(alloc, ary_type, deoptimize_on_exception);36443645// Cast length on remaining path to be as narrow as possible3646if (map()->find_edge(length) >= 0) {3647Node* ccast = alloc->make_ideal_length(ary_type, &_gvn);3648if (ccast != length) {3649_gvn.set_type_bottom(ccast);3650record_for_igvn(ccast);3651replace_in_map(length, ccast);3652}3653}36543655return javaoop;3656}36573658// The following "Ideal_foo" functions are placed here because they recognize3659// the graph shapes created by the functions immediately above.36603661//---------------------------Ideal_allocation----------------------------------3662// Given an oop pointer or raw pointer, see if it feeds from an AllocateNode.3663AllocateNode* AllocateNode::Ideal_allocation(Node* ptr, PhaseTransform* phase) {3664if (ptr == NULL) { // reduce dumb test in callers3665return NULL;3666}3667if (ptr->is_CheckCastPP()) { // strip only one raw-to-oop cast3668ptr = ptr->in(1);3669if (ptr == NULL) return NULL;3670}3671// Return NULL for allocations with several casts:3672// j.l.reflect.Array.newInstance(jobject, jint)3673// Object.clone()3674// to keep more precise type from last cast.3675if (ptr->is_Proj()) {3676Node* allo = ptr->in(0);3677if (allo != NULL && allo->is_Allocate()) {3678return allo->as_Allocate();3679}3680}3681// Report failure to match.3682return NULL;3683}36843685// Fancy version which also strips off an offset (and reports it to caller).3686AllocateNode* AllocateNode::Ideal_allocation(Node* ptr, PhaseTransform* phase,3687intptr_t& offset) {3688Node* base = AddPNode::Ideal_base_and_offset(ptr, phase, offset);3689if (base == NULL) return NULL;3690return Ideal_allocation(base, phase);3691}36923693// Trace Initialize <- Proj[Parm] <- Allocate3694AllocateNode* InitializeNode::allocation() {3695Node* rawoop = in(InitializeNode::RawAddress);3696if (rawoop->is_Proj()) {3697Node* alloc = rawoop->in(0);3698if (alloc->is_Allocate()) {3699return alloc->as_Allocate();3700}3701}3702return NULL;3703}37043705// Trace Allocate -> Proj[Parm] -> Initialize3706InitializeNode* AllocateNode::initialization() {3707ProjNode* rawoop = proj_out(AllocateNode::RawAddress);3708if (rawoop == NULL) return NULL;3709for (DUIterator_Fast imax, i = rawoop->fast_outs(imax); i < imax; i++) {3710Node* init = rawoop->fast_out(i);3711if (init->is_Initialize()) {3712assert(init->as_Initialize()->allocation() == this, "2-way link");3713return init->as_Initialize();3714}3715}3716return NULL;3717}37183719//----------------------------- loop predicates ---------------------------37203721//------------------------------add_predicate_impl----------------------------3722void GraphKit::add_predicate_impl(Deoptimization::DeoptReason reason, int nargs) {3723// Too many traps seen?3724if (too_many_traps(reason)) {3725#ifdef ASSERT3726if (TraceLoopPredicate) {3727int tc = C->trap_count(reason);3728tty->print("too many traps=%s tcount=%d in ",3729Deoptimization::trap_reason_name(reason), tc);3730method()->print(); // which method has too many predicate traps3731tty->cr();3732}3733#endif3734// We cannot afford to take more traps here,3735// do not generate predicate.3736return;3737}37383739Node *cont = _gvn.intcon(1);3740Node* opq = _gvn.transform(new (C) Opaque1Node(C, cont));3741Node *bol = _gvn.transform(new (C) Conv2BNode(opq));3742IfNode* iff = create_and_map_if(control(), bol, PROB_MAX, COUNT_UNKNOWN);3743Node* iffalse = _gvn.transform(new (C) IfFalseNode(iff));3744C->add_predicate_opaq(opq);3745{3746PreserveJVMState pjvms(this);3747set_control(iffalse);3748inc_sp(nargs);3749uncommon_trap(reason, Deoptimization::Action_maybe_recompile);3750}3751Node* iftrue = _gvn.transform(new (C) IfTrueNode(iff));3752set_control(iftrue);3753}37543755//------------------------------add_predicate---------------------------------3756void GraphKit::add_predicate(int nargs) {3757if (UseLoopPredicate) {3758add_predicate_impl(Deoptimization::Reason_predicate, nargs);3759}3760// loop's limit check predicate should be near the loop.3761if (LoopLimitCheck) {3762add_predicate_impl(Deoptimization::Reason_loop_limit_check, nargs);3763}3764}37653766//----------------------------- store barriers ----------------------------3767#define __ ideal.37683769void GraphKit::sync_kit(IdealKit& ideal) {3770set_all_memory(__ merged_memory());3771set_i_o(__ i_o());3772set_control(__ ctrl());3773}37743775void GraphKit::final_sync(IdealKit& ideal) {3776// Final sync IdealKit and graphKit.3777sync_kit(ideal);3778}37793780// vanilla/CMS post barrier3781// Insert a write-barrier store. This is to let generational GC work; we have3782// to flag all oop-stores before the next GC point.3783void GraphKit::write_barrier_post(Node* oop_store,3784Node* obj,3785Node* adr,3786uint adr_idx,3787Node* val,3788bool use_precise) {3789// No store check needed if we're storing a NULL or an old object3790// (latter case is probably a string constant). The concurrent3791// mark sweep garbage collector, however, needs to have all nonNull3792// oop updates flagged via card-marks.3793if (val != NULL && val->is_Con()) {3794// must be either an oop or NULL3795const Type* t = val->bottom_type();3796if (t == TypePtr::NULL_PTR || t == Type::TOP)3797// stores of null never (?) need barriers3798return;3799}38003801if (use_ReduceInitialCardMarks()3802&& obj == just_allocated_object(control())) {3803// We can skip marks on a freshly-allocated object in Eden.3804// Keep this code in sync with new_store_pre_barrier() in runtime.cpp.3805// That routine informs GC to take appropriate compensating steps,3806// upon a slow-path allocation, so as to make this card-mark3807// elision safe.3808return;3809}38103811if (!use_precise) {3812// All card marks for a (non-array) instance are in one place:3813adr = obj;3814}3815// (Else it's an array (or unknown), and we want more precise card marks.)3816assert(adr != NULL, "");38173818IdealKit ideal(this, true);38193820// Convert the pointer to an int prior to doing math on it3821Node* cast = __ CastPX(__ ctrl(), adr);38223823// Divide by card size3824assert(Universe::heap()->barrier_set()->kind() == BarrierSet::CardTableModRef,3825"Only one we handle so far.");3826Node* card_offset = __ URShiftX( cast, __ ConI(CardTableModRefBS::card_shift) );38273828// Combine card table base and card offset3829Node* card_adr = __ AddP(__ top(), byte_map_base_node(), card_offset );38303831// Get the alias_index for raw card-mark memory3832int adr_type = Compile::AliasIdxRaw;3833Node* zero = __ ConI(0); // Dirty card value3834BasicType bt = T_BYTE;38353836if (UseCondCardMark) {3837// The classic GC reference write barrier is typically implemented3838// as a store into the global card mark table. Unfortunately3839// unconditional stores can result in false sharing and excessive3840// coherence traffic as well as false transactional aborts.3841// UseCondCardMark enables MP "polite" conditional card mark3842// stores. In theory we could relax the load from ctrl() to3843// no_ctrl, but that doesn't buy much latitude.3844Node* card_val = __ load( __ ctrl(), card_adr, TypeInt::BYTE, bt, adr_type);3845__ if_then(card_val, BoolTest::ne, zero);3846}38473848// Smash zero into card3849if( !UseConcMarkSweepGC ) {3850#if defined(AARCH64)3851__ store(__ ctrl(), card_adr, zero, bt, adr_type, MemNode::unordered);3852#else3853__ store(__ ctrl(), card_adr, zero, bt, adr_type, MemNode::release);3854#endif3855} else {3856// Specialized path for CM store barrier3857__ storeCM(__ ctrl(), card_adr, zero, oop_store, adr_idx, bt, adr_type);3858}38593860if (UseCondCardMark) {3861__ end_if();3862}38633864// Final sync IdealKit and GraphKit.3865final_sync(ideal);3866}38673868// G1 pre/post barriers3869void GraphKit::g1_write_barrier_pre(bool do_load,3870Node* obj,3871Node* adr,3872uint alias_idx,3873Node* val,3874const TypeOopPtr* val_type,3875Node* pre_val,3876BasicType bt) {38773878// Some sanity checks3879// Note: val is unused in this routine.38803881if (do_load) {3882// We need to generate the load of the previous value3883assert(obj != NULL, "must have a base");3884assert(adr != NULL, "where are loading from?");3885assert(pre_val == NULL, "loaded already?");3886assert(val_type != NULL, "need a type");3887} else {3888// In this case both val_type and alias_idx are unused.3889assert(pre_val != NULL, "must be loaded already");3890// Nothing to be done if pre_val is null.3891if (pre_val->bottom_type() == TypePtr::NULL_PTR) return;3892assert(pre_val->bottom_type()->basic_type() == T_OBJECT, "or we shouldn't be here");3893}3894assert(bt == T_OBJECT, "or we shouldn't be here");38953896IdealKit ideal(this, true);38973898Node* tls = __ thread(); // ThreadLocalStorage38993900Node* no_ctrl = NULL;3901Node* no_base = __ top();3902Node* zero = __ ConI(0);3903Node* zeroX = __ ConX(0);39043905float likely = PROB_LIKELY(0.999);3906float unlikely = PROB_UNLIKELY(0.999);39073908BasicType active_type = in_bytes(PtrQueue::byte_width_of_active()) == 4 ? T_INT : T_BYTE;3909assert(in_bytes(PtrQueue::byte_width_of_active()) == 4 || in_bytes(PtrQueue::byte_width_of_active()) == 1, "flag width");39103911// Offsets into the thread3912const int marking_offset = in_bytes(JavaThread::satb_mark_queue_offset() + // 6483913PtrQueue::byte_offset_of_active());3914const int index_offset = in_bytes(JavaThread::satb_mark_queue_offset() + // 6563915PtrQueue::byte_offset_of_index());3916const int buffer_offset = in_bytes(JavaThread::satb_mark_queue_offset() + // 6523917PtrQueue::byte_offset_of_buf());39183919// Now the actual pointers into the thread3920Node* marking_adr = __ AddP(no_base, tls, __ ConX(marking_offset));3921Node* buffer_adr = __ AddP(no_base, tls, __ ConX(buffer_offset));3922Node* index_adr = __ AddP(no_base, tls, __ ConX(index_offset));39233924// Now some of the values3925Node* marking = __ load(__ ctrl(), marking_adr, TypeInt::INT, active_type, Compile::AliasIdxRaw);39263927// if (!marking)3928__ if_then(marking, BoolTest::ne, zero, unlikely); {3929BasicType index_bt = TypeX_X->basic_type();3930assert(sizeof(size_t) == type2aelembytes(index_bt), "Loading G1 PtrQueue::_index with wrong size.");3931Node* index = __ load(__ ctrl(), index_adr, TypeX_X, index_bt, Compile::AliasIdxRaw);39323933if (do_load) {3934// load original value3935// alias_idx correct??3936pre_val = __ load(__ ctrl(), adr, val_type, bt, alias_idx);3937}39383939// if (pre_val != NULL)3940__ if_then(pre_val, BoolTest::ne, null()); {3941Node* buffer = __ load(__ ctrl(), buffer_adr, TypeRawPtr::NOTNULL, T_ADDRESS, Compile::AliasIdxRaw);39423943// is the queue for this thread full?3944__ if_then(index, BoolTest::ne, zeroX, likely); {39453946// decrement the index3947Node* next_index = _gvn.transform(new (C) SubXNode(index, __ ConX(sizeof(intptr_t))));39483949// Now get the buffer location we will log the previous value into and store it3950Node *log_addr = __ AddP(no_base, buffer, next_index);3951__ store(__ ctrl(), log_addr, pre_val, T_OBJECT, Compile::AliasIdxRaw, MemNode::unordered);3952// update the index3953__ store(__ ctrl(), index_adr, next_index, index_bt, Compile::AliasIdxRaw, MemNode::unordered);39543955} __ else_(); {39563957// logging buffer is full, call the runtime3958const TypeFunc *tf = OptoRuntime::g1_wb_pre_Type();3959__ make_leaf_call(tf, CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_pre), "g1_wb_pre", pre_val, tls);3960} __ end_if(); // (!index)3961} __ end_if(); // (pre_val != NULL)3962} __ end_if(); // (!marking)39633964// Final sync IdealKit and GraphKit.3965final_sync(ideal);3966}39673968//3969// Update the card table and add card address to the queue3970//3971void GraphKit::g1_mark_card(IdealKit& ideal,3972Node* card_adr,3973Node* oop_store,3974uint oop_alias_idx,3975Node* index,3976Node* index_adr,3977Node* buffer,3978const TypeFunc* tf) {39793980Node* zero = __ ConI(0);3981Node* zeroX = __ ConX(0);3982Node* no_base = __ top();3983BasicType card_bt = T_BYTE;3984// Smash zero into card. MUST BE ORDERED WRT TO STORE3985__ storeCM(__ ctrl(), card_adr, zero, oop_store, oop_alias_idx, card_bt, Compile::AliasIdxRaw);39863987// Now do the queue work3988__ if_then(index, BoolTest::ne, zeroX); {39893990Node* next_index = _gvn.transform(new (C) SubXNode(index, __ ConX(sizeof(intptr_t))));3991Node* log_addr = __ AddP(no_base, buffer, next_index);39923993// Order, see storeCM.3994__ store(__ ctrl(), log_addr, card_adr, T_ADDRESS, Compile::AliasIdxRaw, MemNode::unordered);3995__ store(__ ctrl(), index_adr, next_index, TypeX_X->basic_type(), Compile::AliasIdxRaw, MemNode::unordered);39963997} __ else_(); {3998__ make_leaf_call(tf, CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_post), "g1_wb_post", card_adr, __ thread());3999} __ end_if();40004001}40024003void GraphKit::g1_write_barrier_post(Node* oop_store,4004Node* obj,4005Node* adr,4006uint alias_idx,4007Node* val,4008BasicType bt,4009bool use_precise) {4010// If we are writing a NULL then we need no post barrier40114012if (val != NULL && val->is_Con() && val->bottom_type() == TypePtr::NULL_PTR) {4013// Must be NULL4014const Type* t = val->bottom_type();4015assert(t == Type::TOP || t == TypePtr::NULL_PTR, "must be NULL");4016// No post barrier if writing NULLx4017return;4018}40194020if (!use_precise) {4021// All card marks for a (non-array) instance are in one place:4022adr = obj;4023}4024// (Else it's an array (or unknown), and we want more precise card marks.)4025assert(adr != NULL, "");40264027IdealKit ideal(this, true);40284029Node* tls = __ thread(); // ThreadLocalStorage40304031Node* no_base = __ top();4032float likely = PROB_LIKELY(0.999);4033float unlikely = PROB_UNLIKELY(0.999);4034Node* young_card = __ ConI((jint)G1SATBCardTableModRefBS::g1_young_card_val());4035Node* dirty_card = __ ConI((jint)CardTableModRefBS::dirty_card_val());4036Node* zeroX = __ ConX(0);40374038// Get the alias_index for raw card-mark memory4039const TypePtr* card_type = TypeRawPtr::BOTTOM;40404041const TypeFunc *tf = OptoRuntime::g1_wb_post_Type();40424043// Offsets into the thread4044const int index_offset = in_bytes(JavaThread::dirty_card_queue_offset() +4045PtrQueue::byte_offset_of_index());4046const int buffer_offset = in_bytes(JavaThread::dirty_card_queue_offset() +4047PtrQueue::byte_offset_of_buf());40484049// Pointers into the thread40504051Node* buffer_adr = __ AddP(no_base, tls, __ ConX(buffer_offset));4052Node* index_adr = __ AddP(no_base, tls, __ ConX(index_offset));40534054// Now some values4055// Use ctrl to avoid hoisting these values past a safepoint, which could4056// potentially reset these fields in the JavaThread.4057Node* index = __ load(__ ctrl(), index_adr, TypeX_X, TypeX_X->basic_type(), Compile::AliasIdxRaw);4058Node* buffer = __ load(__ ctrl(), buffer_adr, TypeRawPtr::NOTNULL, T_ADDRESS, Compile::AliasIdxRaw);40594060// Convert the store obj pointer to an int prior to doing math on it4061// Must use ctrl to prevent "integerized oop" existing across safepoint4062Node* cast = __ CastPX(__ ctrl(), adr);40634064// Divide pointer by card size4065Node* card_offset = __ URShiftX( cast, __ ConI(CardTableModRefBS::card_shift) );40664067// Combine card table base and card offset4068Node* card_adr = __ AddP(no_base, byte_map_base_node(), card_offset );40694070// If we know the value being stored does it cross regions?40714072if (val != NULL) {4073// Does the store cause us to cross regions?40744075// Should be able to do an unsigned compare of region_size instead of4076// and extra shift. Do we have an unsigned compare??4077// Node* region_size = __ ConI(1 << HeapRegion::LogOfHRGrainBytes);4078Node* xor_res = __ URShiftX ( __ XorX( cast, __ CastPX(__ ctrl(), val)), __ ConI(HeapRegion::LogOfHRGrainBytes));40794080// if (xor_res == 0) same region so skip4081__ if_then(xor_res, BoolTest::ne, zeroX); {40824083// No barrier if we are storing a NULL4084__ if_then(val, BoolTest::ne, null(), unlikely); {40854086// Ok must mark the card if not already dirty40874088// load the original value of the card4089Node* card_val = __ load(__ ctrl(), card_adr, TypeInt::INT, T_BYTE, Compile::AliasIdxRaw);40904091__ if_then(card_val, BoolTest::ne, young_card); {4092sync_kit(ideal);4093// Use Op_MemBarVolatile to achieve the effect of a StoreLoad barrier.4094insert_mem_bar(Op_MemBarVolatile, oop_store);4095__ sync_kit(this);40964097Node* card_val_reload = __ load(__ ctrl(), card_adr, TypeInt::INT, T_BYTE, Compile::AliasIdxRaw);4098__ if_then(card_val_reload, BoolTest::ne, dirty_card); {4099g1_mark_card(ideal, card_adr, oop_store, alias_idx, index, index_adr, buffer, tf);4100} __ end_if();4101} __ end_if();4102} __ end_if();4103} __ end_if();4104} else {4105// Object.clone() instrinsic uses this path.4106g1_mark_card(ideal, card_adr, oop_store, alias_idx, index, index_adr, buffer, tf);4107}41084109// Final sync IdealKit and GraphKit.4110final_sync(ideal);4111}4112#undef __4113411441154116Node* GraphKit::load_String_offset(Node* ctrl, Node* str) {4117if (java_lang_String::has_offset_field()) {4118int offset_offset = java_lang_String::offset_offset_in_bytes();4119const TypeInstPtr* string_type = TypeInstPtr::make(TypePtr::NotNull, C->env()->String_klass(),4120false, NULL, 0);4121const TypePtr* offset_field_type = string_type->add_offset(offset_offset);4122int offset_field_idx = C->get_alias_index(offset_field_type);4123return make_load(ctrl,4124basic_plus_adr(str, str, offset_offset),4125TypeInt::INT, T_INT, offset_field_idx, MemNode::unordered);4126} else {4127return intcon(0);4128}4129}41304131Node* GraphKit::load_String_length(Node* ctrl, Node* str) {4132if (java_lang_String::has_count_field()) {4133int count_offset = java_lang_String::count_offset_in_bytes();4134const TypeInstPtr* string_type = TypeInstPtr::make(TypePtr::NotNull, C->env()->String_klass(),4135false, NULL, 0);4136const TypePtr* count_field_type = string_type->add_offset(count_offset);4137int count_field_idx = C->get_alias_index(count_field_type);4138return make_load(ctrl,4139basic_plus_adr(str, str, count_offset),4140TypeInt::INT, T_INT, count_field_idx, MemNode::unordered);4141} else {4142return load_array_length(load_String_value(ctrl, str));4143}4144}41454146Node* GraphKit::load_String_value(Node* ctrl, Node* str) {4147int value_offset = java_lang_String::value_offset_in_bytes();4148const TypeInstPtr* string_type = TypeInstPtr::make(TypePtr::NotNull, C->env()->String_klass(),4149false, NULL, 0);4150const TypePtr* value_field_type = string_type->add_offset(value_offset);4151const TypeAryPtr* value_type = TypeAryPtr::make(TypePtr::NotNull,4152TypeAry::make(TypeInt::CHAR,TypeInt::POS),4153ciTypeArrayKlass::make(T_CHAR), true, 0);4154int value_field_idx = C->get_alias_index(value_field_type);4155Node* load = make_load(ctrl, basic_plus_adr(str, str, value_offset),4156value_type, T_OBJECT, value_field_idx, MemNode::unordered);4157// String.value field is known to be @Stable.4158if (UseImplicitStableValues) {4159load = cast_array_to_stable(load, value_type);4160}4161return load;4162}41634164void GraphKit::store_String_offset(Node* ctrl, Node* str, Node* value) {4165int offset_offset = java_lang_String::offset_offset_in_bytes();4166const TypeInstPtr* string_type = TypeInstPtr::make(TypePtr::NotNull, C->env()->String_klass(),4167false, NULL, 0);4168const TypePtr* offset_field_type = string_type->add_offset(offset_offset);4169int offset_field_idx = C->get_alias_index(offset_field_type);4170store_to_memory(ctrl, basic_plus_adr(str, offset_offset),4171value, T_INT, offset_field_idx, MemNode::unordered);4172}41734174void GraphKit::store_String_value(Node* ctrl, Node* str, Node* value) {4175int value_offset = java_lang_String::value_offset_in_bytes();4176const TypeInstPtr* string_type = TypeInstPtr::make(TypePtr::NotNull, C->env()->String_klass(),4177false, NULL, 0);4178const TypePtr* value_field_type = string_type->add_offset(value_offset);41794180store_oop_to_object(ctrl, str, basic_plus_adr(str, value_offset), value_field_type,4181value, TypeAryPtr::CHARS, T_OBJECT, MemNode::unordered);4182}41834184void GraphKit::store_String_length(Node* ctrl, Node* str, Node* value) {4185int count_offset = java_lang_String::count_offset_in_bytes();4186const TypeInstPtr* string_type = TypeInstPtr::make(TypePtr::NotNull, C->env()->String_klass(),4187false, NULL, 0);4188const TypePtr* count_field_type = string_type->add_offset(count_offset);4189int count_field_idx = C->get_alias_index(count_field_type);4190store_to_memory(ctrl, basic_plus_adr(str, count_offset),4191value, T_INT, count_field_idx, MemNode::unordered);4192}41934194Node* GraphKit::cast_array_to_stable(Node* ary, const TypeAryPtr* ary_type) {4195// Reify the property as a CastPP node in Ideal graph to comply with monotonicity4196// assumption of CCP analysis.4197return _gvn.transform(new(C) CastPPNode(ary, ary_type->cast_to_stable(true)));4198}419942004201