Path: blob/master/src/hotspot/share/ci/ciEnv.cpp
64441 views
/*1* Copyright (c) 1999, 2021, 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 "jvm.h"26#include "ci/ciConstant.hpp"27#include "ci/ciEnv.hpp"28#include "ci/ciField.hpp"29#include "ci/ciInstance.hpp"30#include "ci/ciInstanceKlass.hpp"31#include "ci/ciMethod.hpp"32#include "ci/ciNullObject.hpp"33#include "ci/ciReplay.hpp"34#include "ci/ciSymbols.hpp"35#include "ci/ciUtilities.inline.hpp"36#include "classfile/javaClasses.hpp"37#include "classfile/symbolTable.hpp"38#include "classfile/systemDictionary.hpp"39#include "classfile/vmClasses.hpp"40#include "classfile/vmSymbols.hpp"41#include "code/codeCache.hpp"42#include "code/scopeDesc.hpp"43#include "compiler/compilationPolicy.hpp"44#include "compiler/compileBroker.hpp"45#include "compiler/compilerEvent.hpp"46#include "compiler/compileLog.hpp"47#include "compiler/compileTask.hpp"48#include "compiler/disassembler.hpp"49#include "gc/shared/collectedHeap.inline.hpp"50#include "interpreter/linkResolver.hpp"51#include "jfr/jfrEvents.hpp"52#include "logging/log.hpp"53#include "memory/allocation.inline.hpp"54#include "memory/oopFactory.hpp"55#include "memory/resourceArea.hpp"56#include "memory/universe.hpp"57#include "oops/constantPool.inline.hpp"58#include "oops/cpCache.inline.hpp"59#include "oops/method.inline.hpp"60#include "oops/methodData.hpp"61#include "oops/objArrayKlass.hpp"62#include "oops/objArrayOop.inline.hpp"63#include "oops/oop.inline.hpp"64#include "prims/jvmtiExport.hpp"65#include "prims/methodHandles.hpp"66#include "runtime/handles.inline.hpp"67#include "runtime/init.hpp"68#include "runtime/reflection.hpp"69#include "runtime/jniHandles.inline.hpp"70#include "runtime/safepointVerifiers.hpp"71#include "runtime/sharedRuntime.hpp"72#include "runtime/thread.inline.hpp"73#include "utilities/dtrace.hpp"74#include "utilities/macros.hpp"75#ifdef COMPILER176#include "c1/c1_Runtime1.hpp"77#endif78#ifdef COMPILER279#include "opto/runtime.hpp"80#endif8182// ciEnv83//84// This class is the top level broker for requests from the compiler85// to the VM.8687ciObject* ciEnv::_null_object_instance;8889#define VM_CLASS_DEFN(name, ignore_s) ciInstanceKlass* ciEnv::_##name = NULL;90VM_CLASSES_DO(VM_CLASS_DEFN)91#undef VM_CLASS_DEFN9293ciSymbol* ciEnv::_unloaded_cisymbol = NULL;94ciInstanceKlass* ciEnv::_unloaded_ciinstance_klass = NULL;95ciObjArrayKlass* ciEnv::_unloaded_ciobjarrayklass = NULL;9697jobject ciEnv::_ArrayIndexOutOfBoundsException_handle = NULL;98jobject ciEnv::_ArrayStoreException_handle = NULL;99jobject ciEnv::_ClassCastException_handle = NULL;100101#ifndef PRODUCT102static bool firstEnv = true;103#endif /* PRODUCT */104105// ------------------------------------------------------------------106// ciEnv::ciEnv107ciEnv::ciEnv(CompileTask* task)108: _ciEnv_arena(mtCompiler) {109VM_ENTRY_MARK;110111// Set up ciEnv::current immediately, for the sake of ciObjectFactory, etc.112thread->set_env(this);113assert(ciEnv::current() == this, "sanity");114115_oop_recorder = NULL;116_debug_info = NULL;117_dependencies = NULL;118_failure_reason = NULL;119_inc_decompile_count_on_failure = true;120_compilable = MethodCompilable;121_break_at_compile = false;122_compiler_data = NULL;123#ifndef PRODUCT124assert(!firstEnv, "not initialized properly");125#endif /* !PRODUCT */126127_num_inlined_bytecodes = 0;128assert(task == NULL || thread->task() == task, "sanity");129if (task != NULL) {130task->mark_started(os::elapsed_counter());131}132_task = task;133_log = NULL;134135// Temporary buffer for creating symbols and such.136_name_buffer = NULL;137_name_buffer_len = 0;138139_arena = &_ciEnv_arena;140_factory = new (_arena) ciObjectFactory(_arena, 128);141142// Preload commonly referenced system ciObjects.143144// During VM initialization, these instances have not yet been created.145// Assertions ensure that these instances are not accessed before146// their initialization.147148assert(Universe::is_fully_initialized(), "should be complete");149150oop o = Universe::null_ptr_exception_instance();151assert(o != NULL, "should have been initialized");152_NullPointerException_instance = get_object(o)->as_instance();153o = Universe::arithmetic_exception_instance();154assert(o != NULL, "should have been initialized");155_ArithmeticException_instance = get_object(o)->as_instance();156157_ArrayIndexOutOfBoundsException_instance = NULL;158_ArrayStoreException_instance = NULL;159_ClassCastException_instance = NULL;160_the_null_string = NULL;161_the_min_jint_string = NULL;162163_jvmti_redefinition_count = 0;164_jvmti_can_hotswap_or_post_breakpoint = false;165_jvmti_can_access_local_variables = false;166_jvmti_can_post_on_exceptions = false;167_jvmti_can_pop_frame = false;168}169170ciEnv::ciEnv(Arena* arena) : _ciEnv_arena(mtCompiler) {171ASSERT_IN_VM;172173// Set up ciEnv::current immediately, for the sake of ciObjectFactory, etc.174CompilerThread* current_thread = CompilerThread::current();175assert(current_thread->env() == NULL, "must be");176current_thread->set_env(this);177assert(ciEnv::current() == this, "sanity");178179_oop_recorder = NULL;180_debug_info = NULL;181_dependencies = NULL;182_failure_reason = NULL;183_inc_decompile_count_on_failure = true;184_compilable = MethodCompilable_never;185_break_at_compile = false;186_compiler_data = NULL;187#ifndef PRODUCT188assert(firstEnv, "must be first");189firstEnv = false;190#endif /* !PRODUCT */191192_num_inlined_bytecodes = 0;193_task = NULL;194_log = NULL;195196// Temporary buffer for creating symbols and such.197_name_buffer = NULL;198_name_buffer_len = 0;199200_arena = arena;201_factory = new (_arena) ciObjectFactory(_arena, 128);202203// Preload commonly referenced system ciObjects.204205// During VM initialization, these instances have not yet been created.206// Assertions ensure that these instances are not accessed before207// their initialization.208209assert(Universe::is_fully_initialized(), "must be");210211_NullPointerException_instance = NULL;212_ArithmeticException_instance = NULL;213_ArrayIndexOutOfBoundsException_instance = NULL;214_ArrayStoreException_instance = NULL;215_ClassCastException_instance = NULL;216_the_null_string = NULL;217_the_min_jint_string = NULL;218219_jvmti_redefinition_count = 0;220_jvmti_can_hotswap_or_post_breakpoint = false;221_jvmti_can_access_local_variables = false;222_jvmti_can_post_on_exceptions = false;223_jvmti_can_pop_frame = false;224}225226ciEnv::~ciEnv() {227GUARDED_VM_ENTRY(228CompilerThread* current_thread = CompilerThread::current();229_factory->remove_symbols();230// Need safepoint to clear the env on the thread. RedefineClasses might231// be reading it.232current_thread->set_env(NULL);233)234}235236// ------------------------------------------------------------------237// Cache Jvmti state238bool ciEnv::cache_jvmti_state() {239VM_ENTRY_MARK;240// Get Jvmti capabilities under lock to get consistant values.241MutexLocker mu(JvmtiThreadState_lock);242_jvmti_redefinition_count = JvmtiExport::redefinition_count();243_jvmti_can_hotswap_or_post_breakpoint = JvmtiExport::can_hotswap_or_post_breakpoint();244_jvmti_can_access_local_variables = JvmtiExport::can_access_local_variables();245_jvmti_can_post_on_exceptions = JvmtiExport::can_post_on_exceptions();246_jvmti_can_pop_frame = JvmtiExport::can_pop_frame();247_jvmti_can_get_owned_monitor_info = JvmtiExport::can_get_owned_monitor_info();248_jvmti_can_walk_any_space = JvmtiExport::can_walk_any_space();249return _task != NULL && _task->method()->is_old();250}251252bool ciEnv::jvmti_state_changed() const {253// Some classes were redefined254if (_jvmti_redefinition_count != JvmtiExport::redefinition_count()) {255return true;256}257258if (!_jvmti_can_access_local_variables &&259JvmtiExport::can_access_local_variables()) {260return true;261}262if (!_jvmti_can_hotswap_or_post_breakpoint &&263JvmtiExport::can_hotswap_or_post_breakpoint()) {264return true;265}266if (!_jvmti_can_post_on_exceptions &&267JvmtiExport::can_post_on_exceptions()) {268return true;269}270if (!_jvmti_can_pop_frame &&271JvmtiExport::can_pop_frame()) {272return true;273}274if (!_jvmti_can_get_owned_monitor_info &&275JvmtiExport::can_get_owned_monitor_info()) {276return true;277}278if (!_jvmti_can_walk_any_space &&279JvmtiExport::can_walk_any_space()) {280return true;281}282283return false;284}285286// ------------------------------------------------------------------287// Cache DTrace flags288void ciEnv::cache_dtrace_flags() {289// Need lock?290_dtrace_extended_probes = ExtendedDTraceProbes;291if (_dtrace_extended_probes) {292_dtrace_method_probes = true;293_dtrace_alloc_probes = true;294} else {295_dtrace_method_probes = DTraceMethodProbes;296_dtrace_alloc_probes = DTraceAllocProbes;297}298}299300// ------------------------------------------------------------------301// helper for lazy exception creation302ciInstance* ciEnv::get_or_create_exception(jobject& handle, Symbol* name) {303VM_ENTRY_MARK;304if (handle == NULL) {305// Cf. universe.cpp, creation of Universe::_null_ptr_exception_instance.306InstanceKlass* ik = SystemDictionary::find_instance_klass(name, Handle(), Handle());307jobject objh = NULL;308if (ik != NULL) {309oop obj = ik->allocate_instance(THREAD);310if (!HAS_PENDING_EXCEPTION)311objh = JNIHandles::make_global(Handle(THREAD, obj));312}313if (HAS_PENDING_EXCEPTION) {314CLEAR_PENDING_EXCEPTION;315} else {316handle = objh;317}318}319oop obj = JNIHandles::resolve(handle);320return obj == NULL? NULL: get_object(obj)->as_instance();321}322323ciInstance* ciEnv::ArrayIndexOutOfBoundsException_instance() {324if (_ArrayIndexOutOfBoundsException_instance == NULL) {325_ArrayIndexOutOfBoundsException_instance326= get_or_create_exception(_ArrayIndexOutOfBoundsException_handle,327vmSymbols::java_lang_ArrayIndexOutOfBoundsException());328}329return _ArrayIndexOutOfBoundsException_instance;330}331ciInstance* ciEnv::ArrayStoreException_instance() {332if (_ArrayStoreException_instance == NULL) {333_ArrayStoreException_instance334= get_or_create_exception(_ArrayStoreException_handle,335vmSymbols::java_lang_ArrayStoreException());336}337return _ArrayStoreException_instance;338}339ciInstance* ciEnv::ClassCastException_instance() {340if (_ClassCastException_instance == NULL) {341_ClassCastException_instance342= get_or_create_exception(_ClassCastException_handle,343vmSymbols::java_lang_ClassCastException());344}345return _ClassCastException_instance;346}347348ciInstance* ciEnv::the_null_string() {349if (_the_null_string == NULL) {350VM_ENTRY_MARK;351_the_null_string = get_object(Universe::the_null_string())->as_instance();352}353return _the_null_string;354}355356ciInstance* ciEnv::the_min_jint_string() {357if (_the_min_jint_string == NULL) {358VM_ENTRY_MARK;359_the_min_jint_string = get_object(Universe::the_min_jint_string())->as_instance();360}361return _the_min_jint_string;362}363364// ------------------------------------------------------------------365// ciEnv::get_method_from_handle366ciMethod* ciEnv::get_method_from_handle(Method* method) {367VM_ENTRY_MARK;368return get_metadata(method)->as_method();369}370371// ------------------------------------------------------------------372// ciEnv::check_klass_accessiblity373//374// Note: the logic of this method should mirror the logic of375// ConstantPool::verify_constant_pool_resolve.376bool ciEnv::check_klass_accessibility(ciKlass* accessing_klass,377Klass* resolved_klass) {378if (accessing_klass == NULL || !accessing_klass->is_loaded()) {379return true;380}381if (accessing_klass->is_obj_array_klass()) {382accessing_klass = accessing_klass->as_obj_array_klass()->base_element_klass();383}384if (!accessing_klass->is_instance_klass()) {385return true;386}387388if (resolved_klass->is_objArray_klass()) {389// Find the element klass, if this is an array.390resolved_klass = ObjArrayKlass::cast(resolved_klass)->bottom_klass();391}392if (resolved_klass->is_instance_klass()) {393return (Reflection::verify_class_access(accessing_klass->get_Klass(),394InstanceKlass::cast(resolved_klass),395true) == Reflection::ACCESS_OK);396}397return true;398}399400// ------------------------------------------------------------------401// ciEnv::get_klass_by_name_impl402ciKlass* ciEnv::get_klass_by_name_impl(ciKlass* accessing_klass,403const constantPoolHandle& cpool,404ciSymbol* name,405bool require_local) {406ASSERT_IN_VM;407Thread* current = Thread::current();408409// Now we need to check the SystemDictionary410Symbol* sym = name->get_symbol();411if (Signature::has_envelope(sym)) {412// This is a name from a signature. Strip off the trimmings.413// Call recursive to keep scope of strippedsym.414TempNewSymbol strippedsym = Signature::strip_envelope(sym);415ciSymbol* strippedname = get_symbol(strippedsym);416return get_klass_by_name_impl(accessing_klass, cpool, strippedname, require_local);417}418419// Check for prior unloaded klass. The SystemDictionary's answers420// can vary over time but the compiler needs consistency.421ciKlass* unloaded_klass = check_get_unloaded_klass(accessing_klass, name);422if (unloaded_klass != NULL) {423if (require_local) return NULL;424return unloaded_klass;425}426427Handle loader;428Handle domain;429if (accessing_klass != NULL) {430loader = Handle(current, accessing_klass->loader());431domain = Handle(current, accessing_klass->protection_domain());432}433434Klass* found_klass;435{436ttyUnlocker ttyul; // release tty lock to avoid ordering problems437MutexLocker ml(current, Compile_lock);438Klass* kls;439if (!require_local) {440kls = SystemDictionary::find_constrained_instance_or_array_klass(current, sym, loader);441} else {442kls = SystemDictionary::find_instance_or_array_klass(sym, loader, domain);443}444found_klass = kls;445}446447// If we fail to find an array klass, look again for its element type.448// The element type may be available either locally or via constraints.449// In either case, if we can find the element type in the system dictionary,450// we must build an array type around it. The CI requires array klasses451// to be loaded if their element klasses are loaded, except when memory452// is exhausted.453if (Signature::is_array(sym) &&454(sym->char_at(1) == JVM_SIGNATURE_ARRAY || sym->char_at(1) == JVM_SIGNATURE_CLASS)) {455// We have an unloaded array.456// Build it on the fly if the element class exists.457SignatureStream ss(sym, false);458ss.skip_array_prefix(1);459// Get element ciKlass recursively.460ciKlass* elem_klass =461get_klass_by_name_impl(accessing_klass,462cpool,463get_symbol(ss.as_symbol()),464require_local);465if (elem_klass != NULL && elem_klass->is_loaded()) {466// Now make an array for it467return ciObjArrayKlass::make_impl(elem_klass);468}469}470471if (found_klass == NULL && !cpool.is_null() && cpool->has_preresolution()) {472// Look inside the constant pool for pre-resolved class entries.473for (int i = cpool->length() - 1; i >= 1; i--) {474if (cpool->tag_at(i).is_klass()) {475Klass* kls = cpool->resolved_klass_at(i);476if (kls->name() == sym) {477found_klass = kls;478break;479}480}481}482}483484if (found_klass != NULL) {485// Found it. Build a CI handle.486return get_klass(found_klass);487}488489if (require_local) return NULL;490491// Not yet loaded into the VM, or not governed by loader constraints.492// Make a CI representative for it.493return get_unloaded_klass(accessing_klass, name);494}495496// ------------------------------------------------------------------497// ciEnv::get_klass_by_name498ciKlass* ciEnv::get_klass_by_name(ciKlass* accessing_klass,499ciSymbol* klass_name,500bool require_local) {501GUARDED_VM_ENTRY(return get_klass_by_name_impl(accessing_klass,502constantPoolHandle(),503klass_name,504require_local);)505}506507// ------------------------------------------------------------------508// ciEnv::get_klass_by_index_impl509//510// Implementation of get_klass_by_index.511ciKlass* ciEnv::get_klass_by_index_impl(const constantPoolHandle& cpool,512int index,513bool& is_accessible,514ciInstanceKlass* accessor) {515Klass* klass = NULL;516Symbol* klass_name = NULL;517518if (cpool->tag_at(index).is_symbol()) {519klass_name = cpool->symbol_at(index);520} else {521// Check if it's resolved if it's not a symbol constant pool entry.522klass = ConstantPool::klass_at_if_loaded(cpool, index);523// Try to look it up by name.524if (klass == NULL) {525klass_name = cpool->klass_name_at(index);526}527}528529if (klass == NULL) {530// Not found in constant pool. Use the name to do the lookup.531ciKlass* k = get_klass_by_name_impl(accessor,532cpool,533get_symbol(klass_name),534false);535// Calculate accessibility the hard way.536if (!k->is_loaded()) {537is_accessible = false;538} else if (k->loader() != accessor->loader() &&539get_klass_by_name_impl(accessor, cpool, k->name(), true) == NULL) {540// Loaded only remotely. Not linked yet.541is_accessible = false;542} else {543// Linked locally, and we must also check public/private, etc.544is_accessible = check_klass_accessibility(accessor, k->get_Klass());545}546return k;547}548549// Check for prior unloaded klass. The SystemDictionary's answers550// can vary over time but the compiler needs consistency.551ciSymbol* name = get_symbol(klass->name());552ciKlass* unloaded_klass = check_get_unloaded_klass(accessor, name);553if (unloaded_klass != NULL) {554is_accessible = false;555return unloaded_klass;556}557558// It is known to be accessible, since it was found in the constant pool.559is_accessible = true;560return get_klass(klass);561}562563// ------------------------------------------------------------------564// ciEnv::get_klass_by_index565//566// Get a klass from the constant pool.567ciKlass* ciEnv::get_klass_by_index(const constantPoolHandle& cpool,568int index,569bool& is_accessible,570ciInstanceKlass* accessor) {571GUARDED_VM_ENTRY(return get_klass_by_index_impl(cpool, index, is_accessible, accessor);)572}573574// ------------------------------------------------------------------575// ciEnv::get_constant_by_index_impl576//577// Implementation of get_constant_by_index().578ciConstant ciEnv::get_constant_by_index_impl(const constantPoolHandle& cpool,579int pool_index, int cache_index,580ciInstanceKlass* accessor) {581int index = pool_index;582if (cache_index >= 0) {583assert(index < 0, "only one kind of index at a time");584index = cpool->object_to_cp_index(cache_index);585oop obj = cpool->resolved_references()->obj_at(cache_index);586if (obj != NULL) {587if (obj == Universe::the_null_sentinel()) {588return ciConstant(T_OBJECT, get_object(NULL));589}590BasicType bt = T_OBJECT;591if (cpool->tag_at(index).is_dynamic_constant()) {592bt = Signature::basic_type(cpool->uncached_signature_ref_at(index));593}594if (!is_reference_type(bt)) {595// we have to unbox the primitive value596if (!is_java_primitive(bt)) {597return ciConstant();598}599jvalue value;600BasicType bt2 = java_lang_boxing_object::get_value(obj, &value);601assert(bt2 == bt, "");602switch (bt2) {603case T_DOUBLE: return ciConstant(value.d);604case T_FLOAT: return ciConstant(value.f);605case T_LONG: return ciConstant(value.j);606case T_INT: return ciConstant(bt2, value.i);607case T_SHORT: return ciConstant(bt2, value.s);608case T_BYTE: return ciConstant(bt2, value.b);609case T_CHAR: return ciConstant(bt2, value.c);610case T_BOOLEAN: return ciConstant(bt2, value.z);611default: return ciConstant();612}613}614ciObject* ciobj = get_object(obj);615if (ciobj->is_array()) {616return ciConstant(T_ARRAY, ciobj);617} else {618assert(ciobj->is_instance(), "should be an instance");619return ciConstant(T_OBJECT, ciobj);620}621}622}623constantTag tag = cpool->tag_at(index);624if (tag.is_int()) {625return ciConstant(T_INT, (jint)cpool->int_at(index));626} else if (tag.is_long()) {627return ciConstant((jlong)cpool->long_at(index));628} else if (tag.is_float()) {629return ciConstant((jfloat)cpool->float_at(index));630} else if (tag.is_double()) {631return ciConstant((jdouble)cpool->double_at(index));632} else if (tag.is_string()) {633EXCEPTION_CONTEXT;634oop string = NULL;635assert(cache_index >= 0, "should have a cache index");636string = cpool->string_at(index, cache_index, THREAD);637if (HAS_PENDING_EXCEPTION) {638CLEAR_PENDING_EXCEPTION;639record_out_of_memory_failure();640return ciConstant();641}642ciObject* constant = get_object(string);643if (constant->is_array()) {644return ciConstant(T_ARRAY, constant);645} else {646assert (constant->is_instance(), "must be an instance, or not? ");647return ciConstant(T_OBJECT, constant);648}649} else if (tag.is_unresolved_klass_in_error()) {650return ciConstant(T_OBJECT, get_unloaded_klass_mirror(NULL));651} else if (tag.is_klass() || tag.is_unresolved_klass()) {652bool will_link;653ciKlass* klass = get_klass_by_index_impl(cpool, index, will_link, accessor);654assert (klass->is_instance_klass() || klass->is_array_klass(),655"must be an instance or array klass ");656ciInstance* mirror = (will_link ? klass->java_mirror() : get_unloaded_klass_mirror(klass));657return ciConstant(T_OBJECT, mirror);658} else if (tag.is_method_type() || tag.is_method_type_in_error()) {659// must execute Java code to link this CP entry into cache[i].f1660ciSymbol* signature = get_symbol(cpool->method_type_signature_at(index));661ciObject* ciobj = get_unloaded_method_type_constant(signature);662return ciConstant(T_OBJECT, ciobj);663} else if (tag.is_method_handle() || tag.is_method_handle_in_error()) {664// must execute Java code to link this CP entry into cache[i].f1665bool ignore_will_link;666int ref_kind = cpool->method_handle_ref_kind_at(index);667int callee_index = cpool->method_handle_klass_index_at(index);668ciKlass* callee = get_klass_by_index_impl(cpool, callee_index, ignore_will_link, accessor);669ciSymbol* name = get_symbol(cpool->method_handle_name_ref_at(index));670ciSymbol* signature = get_symbol(cpool->method_handle_signature_ref_at(index));671ciObject* ciobj = get_unloaded_method_handle_constant(callee, name, signature, ref_kind);672return ciConstant(T_OBJECT, ciobj);673} else if (tag.is_dynamic_constant() || tag.is_dynamic_constant_in_error()) {674return ciConstant(); // not supported675} else {676assert(false, "unknown tag: %d (%s)", tag.value(), tag.internal_name());677return ciConstant();678}679}680681// ------------------------------------------------------------------682// ciEnv::get_constant_by_index683//684// Pull a constant out of the constant pool. How appropriate.685//686// Implementation note: this query is currently in no way cached.687ciConstant ciEnv::get_constant_by_index(const constantPoolHandle& cpool,688int pool_index, int cache_index,689ciInstanceKlass* accessor) {690GUARDED_VM_ENTRY(return get_constant_by_index_impl(cpool, pool_index, cache_index, accessor);)691}692693// ------------------------------------------------------------------694// ciEnv::get_field_by_index_impl695//696// Implementation of get_field_by_index.697//698// Implementation note: the results of field lookups are cached699// in the accessor klass.700ciField* ciEnv::get_field_by_index_impl(ciInstanceKlass* accessor,701int index) {702ciConstantPoolCache* cache = accessor->field_cache();703if (cache == NULL) {704ciField* field = new (arena()) ciField(accessor, index);705return field;706} else {707ciField* field = (ciField*)cache->get(index);708if (field == NULL) {709field = new (arena()) ciField(accessor, index);710cache->insert(index, field);711}712return field;713}714}715716// ------------------------------------------------------------------717// ciEnv::get_field_by_index718//719// Get a field by index from a klass's constant pool.720ciField* ciEnv::get_field_by_index(ciInstanceKlass* accessor,721int index) {722GUARDED_VM_ENTRY(return get_field_by_index_impl(accessor, index);)723}724725// ------------------------------------------------------------------726// ciEnv::lookup_method727//728// Perform an appropriate method lookup based on accessor, holder,729// name, signature, and bytecode.730Method* ciEnv::lookup_method(ciInstanceKlass* accessor,731ciKlass* holder,732Symbol* name,733Symbol* sig,734Bytecodes::Code bc,735constantTag tag) {736InstanceKlass* accessor_klass = accessor->get_instanceKlass();737Klass* holder_klass = holder->get_Klass();738739// Accessibility checks are performed in ciEnv::get_method_by_index_impl.740assert(check_klass_accessibility(accessor, holder_klass), "holder not accessible");741742LinkInfo link_info(holder_klass, name, sig, accessor_klass,743LinkInfo::AccessCheck::required,744LinkInfo::LoaderConstraintCheck::required,745tag);746switch (bc) {747case Bytecodes::_invokestatic:748return LinkResolver::resolve_static_call_or_null(link_info);749case Bytecodes::_invokespecial:750return LinkResolver::resolve_special_call_or_null(link_info);751case Bytecodes::_invokeinterface:752return LinkResolver::linktime_resolve_interface_method_or_null(link_info);753case Bytecodes::_invokevirtual:754return LinkResolver::linktime_resolve_virtual_method_or_null(link_info);755default:756fatal("Unhandled bytecode: %s", Bytecodes::name(bc));757return NULL; // silence compiler warnings758}759}760761762// ------------------------------------------------------------------763// ciEnv::get_method_by_index_impl764ciMethod* ciEnv::get_method_by_index_impl(const constantPoolHandle& cpool,765int index, Bytecodes::Code bc,766ciInstanceKlass* accessor) {767assert(cpool.not_null(), "need constant pool");768assert(accessor != NULL, "need origin of access");769if (bc == Bytecodes::_invokedynamic) {770ConstantPoolCacheEntry* cpce = cpool->invokedynamic_cp_cache_entry_at(index);771bool is_resolved = !cpce->is_f1_null();772// FIXME: code generation could allow for null (unlinked) call site773// The call site could be made patchable as follows:774// Load the appendix argument from the constant pool.775// Test the appendix argument and jump to a known deopt routine if it is null.776// Jump through a patchable call site, which is initially a deopt routine.777// Patch the call site to the nmethod entry point of the static compiled lambda form.778// As with other two-component call sites, both values must be independently verified.779780if (is_resolved) {781// Get the invoker Method* from the constant pool.782// (The appendix argument, if any, will be noted in the method's signature.)783Method* adapter = cpce->f1_as_method();784return get_method(adapter);785}786787// Fake a method that is equivalent to a declared method.788ciInstanceKlass* holder = get_instance_klass(vmClasses::MethodHandle_klass());789ciSymbol* name = ciSymbols::invokeBasic_name();790ciSymbol* signature = get_symbol(cpool->signature_ref_at(index));791return get_unloaded_method(holder, name, signature, accessor);792} else {793const int holder_index = cpool->klass_ref_index_at(index);794bool holder_is_accessible;795ciKlass* holder = get_klass_by_index_impl(cpool, holder_index, holder_is_accessible, accessor);796797// Get the method's name and signature.798Symbol* name_sym = cpool->name_ref_at(index);799Symbol* sig_sym = cpool->signature_ref_at(index);800801if (cpool->has_preresolution()802|| ((holder == ciEnv::MethodHandle_klass() || holder == ciEnv::VarHandle_klass()) &&803MethodHandles::is_signature_polymorphic_name(holder->get_Klass(), name_sym))) {804// Short-circuit lookups for JSR 292-related call sites.805// That is, do not rely only on name-based lookups, because they may fail806// if the names are not resolvable in the boot class loader (7056328).807switch (bc) {808case Bytecodes::_invokevirtual:809case Bytecodes::_invokeinterface:810case Bytecodes::_invokespecial:811case Bytecodes::_invokestatic:812{813Method* m = ConstantPool::method_at_if_loaded(cpool, index);814if (m != NULL) {815return get_method(m);816}817}818break;819default:820break;821}822}823824if (holder_is_accessible) { // Our declared holder is loaded.825constantTag tag = cpool->tag_ref_at(index);826assert(accessor->get_instanceKlass() == cpool->pool_holder(), "not the pool holder?");827Method* m = lookup_method(accessor, holder, name_sym, sig_sym, bc, tag);828if (m != NULL &&829(bc == Bytecodes::_invokestatic830? m->method_holder()->is_not_initialized()831: !m->method_holder()->is_loaded())) {832m = NULL;833}834#ifdef ASSERT835if (m != NULL && ReplayCompiles && !ciReplay::is_loaded(m)) {836m = NULL;837}838#endif839if (m != NULL) {840// We found the method.841return get_method(m);842}843}844845// Either the declared holder was not loaded, or the method could846// not be found. Create a dummy ciMethod to represent the failed847// lookup.848ciSymbol* name = get_symbol(name_sym);849ciSymbol* signature = get_symbol(sig_sym);850return get_unloaded_method(holder, name, signature, accessor);851}852}853854855// ------------------------------------------------------------------856// ciEnv::get_instance_klass_for_declared_method_holder857ciInstanceKlass* ciEnv::get_instance_klass_for_declared_method_holder(ciKlass* method_holder) {858// For the case of <array>.clone(), the method holder can be a ciArrayKlass859// instead of a ciInstanceKlass. For that case simply pretend that the860// declared holder is Object.clone since that's where the call will bottom out.861// A more correct fix would trickle out through many interfaces in CI,862// requiring ciInstanceKlass* to become ciKlass* and many more places would863// require checks to make sure the expected type was found. Given that this864// only occurs for clone() the more extensive fix seems like overkill so865// instead we simply smear the array type into Object.866guarantee(method_holder != NULL, "no method holder");867if (method_holder->is_instance_klass()) {868return method_holder->as_instance_klass();869} else if (method_holder->is_array_klass()) {870return current()->Object_klass();871} else {872ShouldNotReachHere();873}874return NULL;875}876877878// ------------------------------------------------------------------879// ciEnv::get_method_by_index880ciMethod* ciEnv::get_method_by_index(const constantPoolHandle& cpool,881int index, Bytecodes::Code bc,882ciInstanceKlass* accessor) {883GUARDED_VM_ENTRY(return get_method_by_index_impl(cpool, index, bc, accessor);)884}885886887// ------------------------------------------------------------------888// ciEnv::name_buffer889char *ciEnv::name_buffer(int req_len) {890if (_name_buffer_len < req_len) {891if (_name_buffer == NULL) {892_name_buffer = (char*)arena()->Amalloc(sizeof(char)*req_len);893_name_buffer_len = req_len;894} else {895_name_buffer =896(char*)arena()->Arealloc(_name_buffer, _name_buffer_len, req_len);897_name_buffer_len = req_len;898}899}900return _name_buffer;901}902903// ------------------------------------------------------------------904// ciEnv::is_in_vm905bool ciEnv::is_in_vm() {906return JavaThread::current()->thread_state() == _thread_in_vm;907}908909// ------------------------------------------------------------------910// ciEnv::validate_compile_task_dependencies911//912// Check for changes during compilation (e.g. class loads, evolution,913// breakpoints, call site invalidation).914void ciEnv::validate_compile_task_dependencies(ciMethod* target) {915if (failing()) return; // no need for further checks916917Dependencies::DepType result = dependencies()->validate_dependencies(_task);918if (result != Dependencies::end_marker) {919if (result == Dependencies::call_site_target_value) {920_inc_decompile_count_on_failure = false;921record_failure("call site target change");922} else if (Dependencies::is_klass_type(result)) {923record_failure("concurrent class loading");924} else {925record_failure("invalid non-klass dependency");926}927}928}929930// ------------------------------------------------------------------931// ciEnv::register_method932void ciEnv::register_method(ciMethod* target,933int entry_bci,934CodeOffsets* offsets,935int orig_pc_offset,936CodeBuffer* code_buffer,937int frame_words,938OopMapSet* oop_map_set,939ExceptionHandlerTable* handler_table,940ImplicitExceptionTable* inc_table,941AbstractCompiler* compiler,942bool has_unsafe_access,943bool has_wide_vectors,944RTMState rtm_state,945const GrowableArrayView<RuntimeStub*>& native_invokers) {946VM_ENTRY_MARK;947nmethod* nm = NULL;948{949methodHandle method(THREAD, target->get_Method());950951// We require method counters to store some method state (max compilation levels) required by the compilation policy.952if (method->get_method_counters(THREAD) == NULL) {953record_failure("can't create method counters");954// All buffers in the CodeBuffer are allocated in the CodeCache.955// If the code buffer is created on each compile attempt956// as in C2, then it must be freed.957code_buffer->free_blob();958return;959}960961// To prevent compile queue updates.962MutexLocker locker(THREAD, MethodCompileQueue_lock);963964// Prevent SystemDictionary::add_to_hierarchy from running965// and invalidating our dependencies until we install this method.966// No safepoints are allowed. Otherwise, class redefinition can occur in between.967MutexLocker ml(Compile_lock);968NoSafepointVerifier nsv;969970// Change in Jvmti state may invalidate compilation.971if (!failing() && jvmti_state_changed()) {972record_failure("Jvmti state change invalidated dependencies");973}974975// Change in DTrace flags may invalidate compilation.976if (!failing() &&977( (!dtrace_extended_probes() && ExtendedDTraceProbes) ||978(!dtrace_method_probes() && DTraceMethodProbes) ||979(!dtrace_alloc_probes() && DTraceAllocProbes) )) {980record_failure("DTrace flags change invalidated dependencies");981}982983if (!failing() && target->needs_clinit_barrier() &&984target->holder()->is_in_error_state()) {985record_failure("method holder is in error state");986}987988if (!failing()) {989if (log() != NULL) {990// Log the dependencies which this compilation declares.991dependencies()->log_all_dependencies();992}993994// Encode the dependencies now, so we can check them right away.995dependencies()->encode_content_bytes();996997// Check for {class loads, evolution, breakpoints, ...} during compilation998validate_compile_task_dependencies(target);999}1000#if INCLUDE_RTM_OPT1001if (!failing() && (rtm_state != NoRTM) &&1002(method()->method_data() != NULL) &&1003(method()->method_data()->rtm_state() != rtm_state)) {1004// Preemptive decompile if rtm state was changed.1005record_failure("RTM state change invalidated rtm code");1006}1007#endif10081009if (failing()) {1010// While not a true deoptimization, it is a preemptive decompile.1011MethodData* mdo = method()->method_data();1012if (mdo != NULL && _inc_decompile_count_on_failure) {1013mdo->inc_decompile_count();1014}10151016// All buffers in the CodeBuffer are allocated in the CodeCache.1017// If the code buffer is created on each compile attempt1018// as in C2, then it must be freed.1019code_buffer->free_blob();1020return;1021}10221023assert(offsets->value(CodeOffsets::Deopt) != -1, "must have deopt entry");1024assert(offsets->value(CodeOffsets::Exceptions) != -1, "must have exception entry");10251026nm = nmethod::new_nmethod(method,1027compile_id(),1028entry_bci,1029offsets,1030orig_pc_offset,1031debug_info(), dependencies(), code_buffer,1032frame_words, oop_map_set,1033handler_table, inc_table,1034compiler, task()->comp_level(),1035native_invokers);10361037// Free codeBlobs1038code_buffer->free_blob();10391040if (nm != NULL) {1041nm->set_has_unsafe_access(has_unsafe_access);1042nm->set_has_wide_vectors(has_wide_vectors);1043#if INCLUDE_RTM_OPT1044nm->set_rtm_state(rtm_state);1045#endif10461047// Record successful registration.1048// (Put nm into the task handle *before* publishing to the Java heap.)1049if (task() != NULL) {1050task()->set_code(nm);1051}10521053if (entry_bci == InvocationEntryBci) {1054if (TieredCompilation) {1055// If there is an old version we're done with it1056CompiledMethod* old = method->code();1057if (TraceMethodReplacement && old != NULL) {1058ResourceMark rm;1059char *method_name = method->name_and_sig_as_C_string();1060tty->print_cr("Replacing method %s", method_name);1061}1062if (old != NULL) {1063old->make_not_used();1064}1065}10661067LogTarget(Info, nmethod, install) lt;1068if (lt.is_enabled()) {1069ResourceMark rm;1070char *method_name = method->name_and_sig_as_C_string();1071lt.print("Installing method (%d) %s ",1072task()->comp_level(), method_name);1073}1074// Allow the code to be executed1075MutexLocker ml(CompiledMethod_lock, Mutex::_no_safepoint_check_flag);1076if (nm->make_in_use()) {1077method->set_code(method, nm);1078}1079} else {1080LogTarget(Info, nmethod, install) lt;1081if (lt.is_enabled()) {1082ResourceMark rm;1083char *method_name = method->name_and_sig_as_C_string();1084lt.print("Installing osr method (%d) %s @ %d",1085task()->comp_level(), method_name, entry_bci);1086}1087MutexLocker ml(CompiledMethod_lock, Mutex::_no_safepoint_check_flag);1088if (nm->make_in_use()) {1089method->method_holder()->add_osr_nmethod(nm);1090}1091}1092}1093} // safepoints are allowed again10941095if (nm != NULL) {1096// JVMTI -- compiled method notification (must be done outside lock)1097nm->post_compiled_method_load_event();1098} else {1099// The CodeCache is full.1100record_failure("code cache is full");1101}1102}11031104// ------------------------------------------------------------------1105// ciEnv::comp_level1106int ciEnv::comp_level() {1107if (task() == NULL) return CompilationPolicy::highest_compile_level();1108return task()->comp_level();1109}11101111// ------------------------------------------------------------------1112// ciEnv::compile_id1113uint ciEnv::compile_id() {1114if (task() == NULL) return 0;1115return task()->compile_id();1116}11171118// ------------------------------------------------------------------1119// ciEnv::notice_inlined_method()1120void ciEnv::notice_inlined_method(ciMethod* method) {1121_num_inlined_bytecodes += method->code_size_for_inlining();1122}11231124// ------------------------------------------------------------------1125// ciEnv::num_inlined_bytecodes()1126int ciEnv::num_inlined_bytecodes() const {1127return _num_inlined_bytecodes;1128}11291130// ------------------------------------------------------------------1131// ciEnv::record_failure()1132void ciEnv::record_failure(const char* reason) {1133if (_failure_reason == NULL) {1134// Record the first failure reason.1135_failure_reason = reason;1136}1137}11381139void ciEnv::report_failure(const char* reason) {1140EventCompilationFailure event;1141if (event.should_commit()) {1142CompilerEvent::CompilationFailureEvent::post(event, compile_id(), reason);1143}1144}11451146// ------------------------------------------------------------------1147// ciEnv::record_method_not_compilable()1148void ciEnv::record_method_not_compilable(const char* reason, bool all_tiers) {1149int new_compilable =1150all_tiers ? MethodCompilable_never : MethodCompilable_not_at_tier ;11511152// Only note transitions to a worse state1153if (new_compilable > _compilable) {1154if (log() != NULL) {1155if (all_tiers) {1156log()->elem("method_not_compilable");1157} else {1158log()->elem("method_not_compilable_at_tier level='%d'",1159current()->task()->comp_level());1160}1161}1162_compilable = new_compilable;11631164// Reset failure reason; this one is more important.1165_failure_reason = NULL;1166record_failure(reason);1167}1168}11691170// ------------------------------------------------------------------1171// ciEnv::record_out_of_memory_failure()1172void ciEnv::record_out_of_memory_failure() {1173// If memory is low, we stop compiling methods.1174record_method_not_compilable("out of memory");1175}11761177ciInstance* ciEnv::unloaded_ciinstance() {1178GUARDED_VM_ENTRY(return _factory->get_unloaded_object_constant();)1179}11801181// ------------------------------------------------------------------1182// ciEnv::dump_replay_data*11831184// Don't change thread state and acquire any locks.1185// Safe to call from VM error reporter.11861187void ciEnv::dump_compile_data(outputStream* out) {1188CompileTask* task = this->task();1189if (task) {1190Method* method = task->method();1191int entry_bci = task->osr_bci();1192int comp_level = task->comp_level();1193out->print("compile %s %s %s %d %d",1194method->klass_name()->as_quoted_ascii(),1195method->name()->as_quoted_ascii(),1196method->signature()->as_quoted_ascii(),1197entry_bci, comp_level);1198if (compiler_data() != NULL) {1199if (is_c2_compile(comp_level)) {1200#ifdef COMPILER21201// Dump C2 inlining data.1202((Compile*)compiler_data())->dump_inline_data(out);1203#endif1204} else if (is_c1_compile(comp_level)) {1205#ifdef COMPILER11206// Dump C1 inlining data.1207((Compilation*)compiler_data())->dump_inline_data(out);1208#endif1209}1210}1211out->cr();1212}1213}12141215void ciEnv::dump_replay_data_unsafe(outputStream* out) {1216ResourceMark rm;1217#if INCLUDE_JVMTI1218out->print_cr("JvmtiExport can_access_local_variables %d", _jvmti_can_access_local_variables);1219out->print_cr("JvmtiExport can_hotswap_or_post_breakpoint %d", _jvmti_can_hotswap_or_post_breakpoint);1220out->print_cr("JvmtiExport can_post_on_exceptions %d", _jvmti_can_post_on_exceptions);1221#endif // INCLUDE_JVMTI12221223GrowableArray<ciMetadata*>* objects = _factory->get_ci_metadata();1224out->print_cr("# %d ciObject found", objects->length());1225for (int i = 0; i < objects->length(); i++) {1226objects->at(i)->dump_replay_data(out);1227}1228dump_compile_data(out);1229out->flush();1230}12311232void ciEnv::dump_replay_data(outputStream* out) {1233GUARDED_VM_ENTRY(1234MutexLocker ml(Compile_lock);1235dump_replay_data_unsafe(out);1236)1237}12381239void ciEnv::dump_replay_data(int compile_id) {1240static char buffer[O_BUFLEN];1241int ret = jio_snprintf(buffer, O_BUFLEN, "replay_pid%p_compid%d.log", os::current_process_id(), compile_id);1242if (ret > 0) {1243int fd = os::open(buffer, O_RDWR | O_CREAT | O_TRUNC, 0666);1244if (fd != -1) {1245FILE* replay_data_file = os::open(fd, "w");1246if (replay_data_file != NULL) {1247fileStream replay_data_stream(replay_data_file, /*need_close=*/true);1248dump_replay_data(&replay_data_stream);1249tty->print_cr("# Compiler replay data is saved as: %s", buffer);1250} else {1251tty->print_cr("# Can't open file to dump replay data.");1252}1253}1254}1255}12561257void ciEnv::dump_inline_data(int compile_id) {1258static char buffer[O_BUFLEN];1259int ret = jio_snprintf(buffer, O_BUFLEN, "inline_pid%p_compid%d.log", os::current_process_id(), compile_id);1260if (ret > 0) {1261int fd = os::open(buffer, O_RDWR | O_CREAT | O_TRUNC, 0666);1262if (fd != -1) {1263FILE* inline_data_file = os::open(fd, "w");1264if (inline_data_file != NULL) {1265fileStream replay_data_stream(inline_data_file, /*need_close=*/true);1266GUARDED_VM_ENTRY(1267MutexLocker ml(Compile_lock);1268dump_compile_data(&replay_data_stream);1269)1270replay_data_stream.flush();1271tty->print("# Compiler inline data is saved as: ");1272tty->print_cr("%s", buffer);1273} else {1274tty->print_cr("# Can't open file to dump inline data.");1275}1276}1277}1278}127912801281