Path: blob/master/src/hotspot/share/ci/ciEnv.cpp
40930 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}433434// setup up the proper type to return on OOM435ciKlass* fail_type;436if (sym->char_at(0) == JVM_SIGNATURE_ARRAY) {437fail_type = _unloaded_ciobjarrayklass;438} else {439fail_type = _unloaded_ciinstance_klass;440}441Klass* found_klass;442{443ttyUnlocker ttyul; // release tty lock to avoid ordering problems444MutexLocker ml(current, Compile_lock);445Klass* kls;446if (!require_local) {447kls = SystemDictionary::find_constrained_instance_or_array_klass(current, sym, loader);448} else {449kls = SystemDictionary::find_instance_or_array_klass(sym, loader, domain);450}451found_klass = kls;452}453454// If we fail to find an array klass, look again for its element type.455// The element type may be available either locally or via constraints.456// In either case, if we can find the element type in the system dictionary,457// we must build an array type around it. The CI requires array klasses458// to be loaded if their element klasses are loaded, except when memory459// is exhausted.460if (Signature::is_array(sym) &&461(sym->char_at(1) == JVM_SIGNATURE_ARRAY || sym->char_at(1) == JVM_SIGNATURE_CLASS)) {462// We have an unloaded array.463// Build it on the fly if the element class exists.464SignatureStream ss(sym, false);465ss.skip_array_prefix(1);466// Get element ciKlass recursively.467ciKlass* elem_klass =468get_klass_by_name_impl(accessing_klass,469cpool,470get_symbol(ss.as_symbol()),471require_local);472if (elem_klass != NULL && elem_klass->is_loaded()) {473// Now make an array for it474return ciObjArrayKlass::make_impl(elem_klass);475}476}477478if (found_klass == NULL && !cpool.is_null() && cpool->has_preresolution()) {479// Look inside the constant pool for pre-resolved class entries.480for (int i = cpool->length() - 1; i >= 1; i--) {481if (cpool->tag_at(i).is_klass()) {482Klass* kls = cpool->resolved_klass_at(i);483if (kls->name() == sym) {484found_klass = kls;485break;486}487}488}489}490491if (found_klass != NULL) {492// Found it. Build a CI handle.493return get_klass(found_klass);494}495496if (require_local) return NULL;497498// Not yet loaded into the VM, or not governed by loader constraints.499// Make a CI representative for it.500return get_unloaded_klass(accessing_klass, name);501}502503// ------------------------------------------------------------------504// ciEnv::get_klass_by_name505ciKlass* ciEnv::get_klass_by_name(ciKlass* accessing_klass,506ciSymbol* klass_name,507bool require_local) {508GUARDED_VM_ENTRY(return get_klass_by_name_impl(accessing_klass,509constantPoolHandle(),510klass_name,511require_local);)512}513514// ------------------------------------------------------------------515// ciEnv::get_klass_by_index_impl516//517// Implementation of get_klass_by_index.518ciKlass* ciEnv::get_klass_by_index_impl(const constantPoolHandle& cpool,519int index,520bool& is_accessible,521ciInstanceKlass* accessor) {522EXCEPTION_CONTEXT;523Klass* klass = NULL;524Symbol* klass_name = NULL;525526if (cpool->tag_at(index).is_symbol()) {527klass_name = cpool->symbol_at(index);528} else {529// Check if it's resolved if it's not a symbol constant pool entry.530klass = ConstantPool::klass_at_if_loaded(cpool, index);531// Try to look it up by name.532if (klass == NULL) {533klass_name = cpool->klass_name_at(index);534}535}536537if (klass == NULL) {538// Not found in constant pool. Use the name to do the lookup.539ciKlass* k = get_klass_by_name_impl(accessor,540cpool,541get_symbol(klass_name),542false);543// Calculate accessibility the hard way.544if (!k->is_loaded()) {545is_accessible = false;546} else if (k->loader() != accessor->loader() &&547get_klass_by_name_impl(accessor, cpool, k->name(), true) == NULL) {548// Loaded only remotely. Not linked yet.549is_accessible = false;550} else {551// Linked locally, and we must also check public/private, etc.552is_accessible = check_klass_accessibility(accessor, k->get_Klass());553}554return k;555}556557// Check for prior unloaded klass. The SystemDictionary's answers558// can vary over time but the compiler needs consistency.559ciSymbol* name = get_symbol(klass->name());560ciKlass* unloaded_klass = check_get_unloaded_klass(accessor, name);561if (unloaded_klass != NULL) {562is_accessible = false;563return unloaded_klass;564}565566// It is known to be accessible, since it was found in the constant pool.567is_accessible = true;568return get_klass(klass);569}570571// ------------------------------------------------------------------572// ciEnv::get_klass_by_index573//574// Get a klass from the constant pool.575ciKlass* ciEnv::get_klass_by_index(const constantPoolHandle& cpool,576int index,577bool& is_accessible,578ciInstanceKlass* accessor) {579GUARDED_VM_ENTRY(return get_klass_by_index_impl(cpool, index, is_accessible, accessor);)580}581582// ------------------------------------------------------------------583// ciEnv::get_constant_by_index_impl584//585// Implementation of get_constant_by_index().586ciConstant ciEnv::get_constant_by_index_impl(const constantPoolHandle& cpool,587int pool_index, int cache_index,588ciInstanceKlass* accessor) {589bool ignore_will_link;590EXCEPTION_CONTEXT;591int index = pool_index;592if (cache_index >= 0) {593assert(index < 0, "only one kind of index at a time");594index = cpool->object_to_cp_index(cache_index);595oop obj = cpool->resolved_references()->obj_at(cache_index);596if (obj != NULL) {597if (obj == Universe::the_null_sentinel()) {598return ciConstant(T_OBJECT, get_object(NULL));599}600BasicType bt = T_OBJECT;601if (cpool->tag_at(index).is_dynamic_constant())602bt = Signature::basic_type(cpool->uncached_signature_ref_at(index));603if (is_reference_type(bt)) {604} else {605// we have to unbox the primitive value606if (!is_java_primitive(bt)) return ciConstant();607jvalue value;608BasicType bt2 = java_lang_boxing_object::get_value(obj, &value);609assert(bt2 == bt, "");610switch (bt2) {611case T_DOUBLE: return ciConstant(value.d);612case T_FLOAT: return ciConstant(value.f);613case T_LONG: return ciConstant(value.j);614case T_INT: return ciConstant(bt2, value.i);615case T_SHORT: return ciConstant(bt2, value.s);616case T_BYTE: return ciConstant(bt2, value.b);617case T_CHAR: return ciConstant(bt2, value.c);618case T_BOOLEAN: return ciConstant(bt2, value.z);619default: return ciConstant();620}621}622ciObject* ciobj = get_object(obj);623if (ciobj->is_array()) {624return ciConstant(T_ARRAY, ciobj);625} else {626assert(ciobj->is_instance(), "should be an instance");627return ciConstant(T_OBJECT, ciobj);628}629}630}631constantTag tag = cpool->tag_at(index);632if (tag.is_int()) {633return ciConstant(T_INT, (jint)cpool->int_at(index));634} else if (tag.is_long()) {635return ciConstant((jlong)cpool->long_at(index));636} else if (tag.is_float()) {637return ciConstant((jfloat)cpool->float_at(index));638} else if (tag.is_double()) {639return ciConstant((jdouble)cpool->double_at(index));640} else if (tag.is_string()) {641oop string = NULL;642assert(cache_index >= 0, "should have a cache index");643string = cpool->string_at(index, cache_index, THREAD);644if (HAS_PENDING_EXCEPTION) {645CLEAR_PENDING_EXCEPTION;646record_out_of_memory_failure();647return ciConstant();648}649ciObject* constant = get_object(string);650if (constant->is_array()) {651return ciConstant(T_ARRAY, constant);652} else {653assert (constant->is_instance(), "must be an instance, or not? ");654return ciConstant(T_OBJECT, constant);655}656} else if (tag.is_unresolved_klass_in_error()) {657return ciConstant();658} else if (tag.is_klass() || tag.is_unresolved_klass()) {659// 4881222: allow ldc to take a class type660ciKlass* klass = get_klass_by_index_impl(cpool, index, ignore_will_link, accessor);661if (HAS_PENDING_EXCEPTION) {662CLEAR_PENDING_EXCEPTION;663record_out_of_memory_failure();664return ciConstant();665}666assert (klass->is_instance_klass() || klass->is_array_klass(),667"must be an instance or array klass ");668return ciConstant(T_OBJECT, klass->java_mirror());669} else if (tag.is_method_type()) {670// must execute Java code to link this CP entry into cache[i].f1671ciSymbol* signature = get_symbol(cpool->method_type_signature_at(index));672ciObject* ciobj = get_unloaded_method_type_constant(signature);673return ciConstant(T_OBJECT, ciobj);674} else if (tag.is_method_handle()) {675// must execute Java code to link this CP entry into cache[i].f1676int ref_kind = cpool->method_handle_ref_kind_at(index);677int callee_index = cpool->method_handle_klass_index_at(index);678ciKlass* callee = get_klass_by_index_impl(cpool, callee_index, ignore_will_link, accessor);679ciSymbol* name = get_symbol(cpool->method_handle_name_ref_at(index));680ciSymbol* signature = get_symbol(cpool->method_handle_signature_ref_at(index));681ciObject* ciobj = get_unloaded_method_handle_constant(callee, name, signature, ref_kind);682return ciConstant(T_OBJECT, ciobj);683} else if (tag.is_dynamic_constant()) {684return ciConstant();685} else {686ShouldNotReachHere();687return ciConstant();688}689}690691// ------------------------------------------------------------------692// ciEnv::get_constant_by_index693//694// Pull a constant out of the constant pool. How appropriate.695//696// Implementation note: this query is currently in no way cached.697ciConstant ciEnv::get_constant_by_index(const constantPoolHandle& cpool,698int pool_index, int cache_index,699ciInstanceKlass* accessor) {700GUARDED_VM_ENTRY(return get_constant_by_index_impl(cpool, pool_index, cache_index, accessor);)701}702703// ------------------------------------------------------------------704// ciEnv::get_field_by_index_impl705//706// Implementation of get_field_by_index.707//708// Implementation note: the results of field lookups are cached709// in the accessor klass.710ciField* ciEnv::get_field_by_index_impl(ciInstanceKlass* accessor,711int index) {712ciConstantPoolCache* cache = accessor->field_cache();713if (cache == NULL) {714ciField* field = new (arena()) ciField(accessor, index);715return field;716} else {717ciField* field = (ciField*)cache->get(index);718if (field == NULL) {719field = new (arena()) ciField(accessor, index);720cache->insert(index, field);721}722return field;723}724}725726// ------------------------------------------------------------------727// ciEnv::get_field_by_index728//729// Get a field by index from a klass's constant pool.730ciField* ciEnv::get_field_by_index(ciInstanceKlass* accessor,731int index) {732GUARDED_VM_ENTRY(return get_field_by_index_impl(accessor, index);)733}734735// ------------------------------------------------------------------736// ciEnv::lookup_method737//738// Perform an appropriate method lookup based on accessor, holder,739// name, signature, and bytecode.740Method* ciEnv::lookup_method(ciInstanceKlass* accessor,741ciKlass* holder,742Symbol* name,743Symbol* sig,744Bytecodes::Code bc,745constantTag tag) {746InstanceKlass* accessor_klass = accessor->get_instanceKlass();747Klass* holder_klass = holder->get_Klass();748749// Accessibility checks are performed in ciEnv::get_method_by_index_impl.750assert(check_klass_accessibility(accessor, holder_klass), "holder not accessible");751752LinkInfo link_info(holder_klass, name, sig, accessor_klass,753LinkInfo::AccessCheck::required,754LinkInfo::LoaderConstraintCheck::required,755tag);756switch (bc) {757case Bytecodes::_invokestatic:758return LinkResolver::resolve_static_call_or_null(link_info);759case Bytecodes::_invokespecial:760return LinkResolver::resolve_special_call_or_null(link_info);761case Bytecodes::_invokeinterface:762return LinkResolver::linktime_resolve_interface_method_or_null(link_info);763case Bytecodes::_invokevirtual:764return LinkResolver::linktime_resolve_virtual_method_or_null(link_info);765default:766fatal("Unhandled bytecode: %s", Bytecodes::name(bc));767return NULL; // silence compiler warnings768}769}770771772// ------------------------------------------------------------------773// ciEnv::get_method_by_index_impl774ciMethod* ciEnv::get_method_by_index_impl(const constantPoolHandle& cpool,775int index, Bytecodes::Code bc,776ciInstanceKlass* accessor) {777assert(cpool.not_null(), "need constant pool");778assert(accessor != NULL, "need origin of access");779if (bc == Bytecodes::_invokedynamic) {780ConstantPoolCacheEntry* cpce = cpool->invokedynamic_cp_cache_entry_at(index);781bool is_resolved = !cpce->is_f1_null();782// FIXME: code generation could allow for null (unlinked) call site783// The call site could be made patchable as follows:784// Load the appendix argument from the constant pool.785// Test the appendix argument and jump to a known deopt routine if it is null.786// Jump through a patchable call site, which is initially a deopt routine.787// Patch the call site to the nmethod entry point of the static compiled lambda form.788// As with other two-component call sites, both values must be independently verified.789790if (is_resolved) {791// Get the invoker Method* from the constant pool.792// (The appendix argument, if any, will be noted in the method's signature.)793Method* adapter = cpce->f1_as_method();794return get_method(adapter);795}796797// Fake a method that is equivalent to a declared method.798ciInstanceKlass* holder = get_instance_klass(vmClasses::MethodHandle_klass());799ciSymbol* name = ciSymbols::invokeBasic_name();800ciSymbol* signature = get_symbol(cpool->signature_ref_at(index));801return get_unloaded_method(holder, name, signature, accessor);802} else {803const int holder_index = cpool->klass_ref_index_at(index);804bool holder_is_accessible;805ciKlass* holder = get_klass_by_index_impl(cpool, holder_index, holder_is_accessible, accessor);806807// Get the method's name and signature.808Symbol* name_sym = cpool->name_ref_at(index);809Symbol* sig_sym = cpool->signature_ref_at(index);810811if (cpool->has_preresolution()812|| ((holder == ciEnv::MethodHandle_klass() || holder == ciEnv::VarHandle_klass()) &&813MethodHandles::is_signature_polymorphic_name(holder->get_Klass(), name_sym))) {814// Short-circuit lookups for JSR 292-related call sites.815// That is, do not rely only on name-based lookups, because they may fail816// if the names are not resolvable in the boot class loader (7056328).817switch (bc) {818case Bytecodes::_invokevirtual:819case Bytecodes::_invokeinterface:820case Bytecodes::_invokespecial:821case Bytecodes::_invokestatic:822{823Method* m = ConstantPool::method_at_if_loaded(cpool, index);824if (m != NULL) {825return get_method(m);826}827}828break;829default:830break;831}832}833834if (holder_is_accessible) { // Our declared holder is loaded.835constantTag tag = cpool->tag_ref_at(index);836assert(accessor->get_instanceKlass() == cpool->pool_holder(), "not the pool holder?");837Method* m = lookup_method(accessor, holder, name_sym, sig_sym, bc, tag);838if (m != NULL &&839(bc == Bytecodes::_invokestatic840? m->method_holder()->is_not_initialized()841: !m->method_holder()->is_loaded())) {842m = NULL;843}844#ifdef ASSERT845if (m != NULL && ReplayCompiles && !ciReplay::is_loaded(m)) {846m = NULL;847}848#endif849if (m != NULL) {850// We found the method.851return get_method(m);852}853}854855// Either the declared holder was not loaded, or the method could856// not be found. Create a dummy ciMethod to represent the failed857// lookup.858ciSymbol* name = get_symbol(name_sym);859ciSymbol* signature = get_symbol(sig_sym);860return get_unloaded_method(holder, name, signature, accessor);861}862}863864865// ------------------------------------------------------------------866// ciEnv::get_instance_klass_for_declared_method_holder867ciInstanceKlass* ciEnv::get_instance_klass_for_declared_method_holder(ciKlass* method_holder) {868// For the case of <array>.clone(), the method holder can be a ciArrayKlass869// instead of a ciInstanceKlass. For that case simply pretend that the870// declared holder is Object.clone since that's where the call will bottom out.871// A more correct fix would trickle out through many interfaces in CI,872// requiring ciInstanceKlass* to become ciKlass* and many more places would873// require checks to make sure the expected type was found. Given that this874// only occurs for clone() the more extensive fix seems like overkill so875// instead we simply smear the array type into Object.876guarantee(method_holder != NULL, "no method holder");877if (method_holder->is_instance_klass()) {878return method_holder->as_instance_klass();879} else if (method_holder->is_array_klass()) {880return current()->Object_klass();881} else {882ShouldNotReachHere();883}884return NULL;885}886887888// ------------------------------------------------------------------889// ciEnv::get_method_by_index890ciMethod* ciEnv::get_method_by_index(const constantPoolHandle& cpool,891int index, Bytecodes::Code bc,892ciInstanceKlass* accessor) {893GUARDED_VM_ENTRY(return get_method_by_index_impl(cpool, index, bc, accessor);)894}895896897// ------------------------------------------------------------------898// ciEnv::name_buffer899char *ciEnv::name_buffer(int req_len) {900if (_name_buffer_len < req_len) {901if (_name_buffer == NULL) {902_name_buffer = (char*)arena()->Amalloc(sizeof(char)*req_len);903_name_buffer_len = req_len;904} else {905_name_buffer =906(char*)arena()->Arealloc(_name_buffer, _name_buffer_len, req_len);907_name_buffer_len = req_len;908}909}910return _name_buffer;911}912913// ------------------------------------------------------------------914// ciEnv::is_in_vm915bool ciEnv::is_in_vm() {916return JavaThread::current()->thread_state() == _thread_in_vm;917}918919// ------------------------------------------------------------------920// ciEnv::validate_compile_task_dependencies921//922// Check for changes during compilation (e.g. class loads, evolution,923// breakpoints, call site invalidation).924void ciEnv::validate_compile_task_dependencies(ciMethod* target) {925if (failing()) return; // no need for further checks926927Dependencies::DepType result = dependencies()->validate_dependencies(_task);928if (result != Dependencies::end_marker) {929if (result == Dependencies::call_site_target_value) {930_inc_decompile_count_on_failure = false;931record_failure("call site target change");932} else if (Dependencies::is_klass_type(result)) {933record_failure("concurrent class loading");934} else {935record_failure("invalid non-klass dependency");936}937}938}939940// ------------------------------------------------------------------941// ciEnv::register_method942void ciEnv::register_method(ciMethod* target,943int entry_bci,944CodeOffsets* offsets,945int orig_pc_offset,946CodeBuffer* code_buffer,947int frame_words,948OopMapSet* oop_map_set,949ExceptionHandlerTable* handler_table,950ImplicitExceptionTable* inc_table,951AbstractCompiler* compiler,952bool has_unsafe_access,953bool has_wide_vectors,954RTMState rtm_state,955const GrowableArrayView<RuntimeStub*>& native_invokers) {956VM_ENTRY_MARK;957nmethod* nm = NULL;958{959methodHandle method(THREAD, target->get_Method());960961// We require method counters to store some method state (max compilation levels) required by the compilation policy.962if (method->get_method_counters(THREAD) == NULL) {963record_failure("can't create method counters");964// All buffers in the CodeBuffer are allocated in the CodeCache.965// If the code buffer is created on each compile attempt966// as in C2, then it must be freed.967code_buffer->free_blob();968return;969}970971// To prevent compile queue updates.972MutexLocker locker(THREAD, MethodCompileQueue_lock);973974// Prevent SystemDictionary::add_to_hierarchy from running975// and invalidating our dependencies until we install this method.976// No safepoints are allowed. Otherwise, class redefinition can occur in between.977MutexLocker ml(Compile_lock);978NoSafepointVerifier nsv;979980// Change in Jvmti state may invalidate compilation.981if (!failing() && jvmti_state_changed()) {982record_failure("Jvmti state change invalidated dependencies");983}984985// Change in DTrace flags may invalidate compilation.986if (!failing() &&987( (!dtrace_extended_probes() && ExtendedDTraceProbes) ||988(!dtrace_method_probes() && DTraceMethodProbes) ||989(!dtrace_alloc_probes() && DTraceAllocProbes) )) {990record_failure("DTrace flags change invalidated dependencies");991}992993if (!failing() && target->needs_clinit_barrier() &&994target->holder()->is_in_error_state()) {995record_failure("method holder is in error state");996}997998if (!failing()) {999if (log() != NULL) {1000// Log the dependencies which this compilation declares.1001dependencies()->log_all_dependencies();1002}10031004// Encode the dependencies now, so we can check them right away.1005dependencies()->encode_content_bytes();10061007// Check for {class loads, evolution, breakpoints, ...} during compilation1008validate_compile_task_dependencies(target);1009}1010#if INCLUDE_RTM_OPT1011if (!failing() && (rtm_state != NoRTM) &&1012(method()->method_data() != NULL) &&1013(method()->method_data()->rtm_state() != rtm_state)) {1014// Preemptive decompile if rtm state was changed.1015record_failure("RTM state change invalidated rtm code");1016}1017#endif10181019if (failing()) {1020// While not a true deoptimization, it is a preemptive decompile.1021MethodData* mdo = method()->method_data();1022if (mdo != NULL && _inc_decompile_count_on_failure) {1023mdo->inc_decompile_count();1024}10251026// All buffers in the CodeBuffer are allocated in the CodeCache.1027// If the code buffer is created on each compile attempt1028// as in C2, then it must be freed.1029code_buffer->free_blob();1030return;1031}10321033assert(offsets->value(CodeOffsets::Deopt) != -1, "must have deopt entry");1034assert(offsets->value(CodeOffsets::Exceptions) != -1, "must have exception entry");10351036nm = nmethod::new_nmethod(method,1037compile_id(),1038entry_bci,1039offsets,1040orig_pc_offset,1041debug_info(), dependencies(), code_buffer,1042frame_words, oop_map_set,1043handler_table, inc_table,1044compiler, task()->comp_level(),1045native_invokers);10461047// Free codeBlobs1048code_buffer->free_blob();10491050if (nm != NULL) {1051nm->set_has_unsafe_access(has_unsafe_access);1052nm->set_has_wide_vectors(has_wide_vectors);1053#if INCLUDE_RTM_OPT1054nm->set_rtm_state(rtm_state);1055#endif10561057// Record successful registration.1058// (Put nm into the task handle *before* publishing to the Java heap.)1059if (task() != NULL) {1060task()->set_code(nm);1061}10621063if (entry_bci == InvocationEntryBci) {1064if (TieredCompilation) {1065// If there is an old version we're done with it1066CompiledMethod* old = method->code();1067if (TraceMethodReplacement && old != NULL) {1068ResourceMark rm;1069char *method_name = method->name_and_sig_as_C_string();1070tty->print_cr("Replacing method %s", method_name);1071}1072if (old != NULL) {1073old->make_not_used();1074}1075}10761077LogTarget(Info, nmethod, install) lt;1078if (lt.is_enabled()) {1079ResourceMark rm;1080char *method_name = method->name_and_sig_as_C_string();1081lt.print("Installing method (%d) %s ",1082task()->comp_level(), method_name);1083}1084// Allow the code to be executed1085MutexLocker ml(CompiledMethod_lock, Mutex::_no_safepoint_check_flag);1086if (nm->make_in_use()) {1087method->set_code(method, nm);1088}1089} else {1090LogTarget(Info, nmethod, install) lt;1091if (lt.is_enabled()) {1092ResourceMark rm;1093char *method_name = method->name_and_sig_as_C_string();1094lt.print("Installing osr method (%d) %s @ %d",1095task()->comp_level(), method_name, entry_bci);1096}1097MutexLocker ml(CompiledMethod_lock, Mutex::_no_safepoint_check_flag);1098if (nm->make_in_use()) {1099method->method_holder()->add_osr_nmethod(nm);1100}1101}1102}1103} // safepoints are allowed again11041105if (nm != NULL) {1106// JVMTI -- compiled method notification (must be done outside lock)1107nm->post_compiled_method_load_event();1108} else {1109// The CodeCache is full.1110record_failure("code cache is full");1111}1112}11131114// ------------------------------------------------------------------1115// ciEnv::comp_level1116int ciEnv::comp_level() {1117if (task() == NULL) return CompilationPolicy::highest_compile_level();1118return task()->comp_level();1119}11201121// ------------------------------------------------------------------1122// ciEnv::compile_id1123uint ciEnv::compile_id() {1124if (task() == NULL) return 0;1125return task()->compile_id();1126}11271128// ------------------------------------------------------------------1129// ciEnv::notice_inlined_method()1130void ciEnv::notice_inlined_method(ciMethod* method) {1131_num_inlined_bytecodes += method->code_size_for_inlining();1132}11331134// ------------------------------------------------------------------1135// ciEnv::num_inlined_bytecodes()1136int ciEnv::num_inlined_bytecodes() const {1137return _num_inlined_bytecodes;1138}11391140// ------------------------------------------------------------------1141// ciEnv::record_failure()1142void ciEnv::record_failure(const char* reason) {1143if (_failure_reason == NULL) {1144// Record the first failure reason.1145_failure_reason = reason;1146}1147}11481149void ciEnv::report_failure(const char* reason) {1150EventCompilationFailure event;1151if (event.should_commit()) {1152CompilerEvent::CompilationFailureEvent::post(event, compile_id(), reason);1153}1154}11551156// ------------------------------------------------------------------1157// ciEnv::record_method_not_compilable()1158void ciEnv::record_method_not_compilable(const char* reason, bool all_tiers) {1159int new_compilable =1160all_tiers ? MethodCompilable_never : MethodCompilable_not_at_tier ;11611162// Only note transitions to a worse state1163if (new_compilable > _compilable) {1164if (log() != NULL) {1165if (all_tiers) {1166log()->elem("method_not_compilable");1167} else {1168log()->elem("method_not_compilable_at_tier level='%d'",1169current()->task()->comp_level());1170}1171}1172_compilable = new_compilable;11731174// Reset failure reason; this one is more important.1175_failure_reason = NULL;1176record_failure(reason);1177}1178}11791180// ------------------------------------------------------------------1181// ciEnv::record_out_of_memory_failure()1182void ciEnv::record_out_of_memory_failure() {1183// If memory is low, we stop compiling methods.1184record_method_not_compilable("out of memory");1185}11861187ciInstance* ciEnv::unloaded_ciinstance() {1188GUARDED_VM_ENTRY(return _factory->get_unloaded_object_constant();)1189}11901191// ------------------------------------------------------------------1192// ciEnv::dump_replay_data*11931194// Don't change thread state and acquire any locks.1195// Safe to call from VM error reporter.11961197void ciEnv::dump_compile_data(outputStream* out) {1198CompileTask* task = this->task();1199if (task) {1200Method* method = task->method();1201int entry_bci = task->osr_bci();1202int comp_level = task->comp_level();1203out->print("compile %s %s %s %d %d",1204method->klass_name()->as_quoted_ascii(),1205method->name()->as_quoted_ascii(),1206method->signature()->as_quoted_ascii(),1207entry_bci, comp_level);1208if (compiler_data() != NULL) {1209if (is_c2_compile(comp_level)) {1210#ifdef COMPILER21211// Dump C2 inlining data.1212((Compile*)compiler_data())->dump_inline_data(out);1213#endif1214} else if (is_c1_compile(comp_level)) {1215#ifdef COMPILER11216// Dump C1 inlining data.1217((Compilation*)compiler_data())->dump_inline_data(out);1218#endif1219}1220}1221out->cr();1222}1223}12241225void ciEnv::dump_replay_data_unsafe(outputStream* out) {1226ResourceMark rm;1227#if INCLUDE_JVMTI1228out->print_cr("JvmtiExport can_access_local_variables %d", _jvmti_can_access_local_variables);1229out->print_cr("JvmtiExport can_hotswap_or_post_breakpoint %d", _jvmti_can_hotswap_or_post_breakpoint);1230out->print_cr("JvmtiExport can_post_on_exceptions %d", _jvmti_can_post_on_exceptions);1231#endif // INCLUDE_JVMTI12321233GrowableArray<ciMetadata*>* objects = _factory->get_ci_metadata();1234out->print_cr("# %d ciObject found", objects->length());1235for (int i = 0; i < objects->length(); i++) {1236objects->at(i)->dump_replay_data(out);1237}1238dump_compile_data(out);1239out->flush();1240}12411242void ciEnv::dump_replay_data(outputStream* out) {1243GUARDED_VM_ENTRY(1244MutexLocker ml(Compile_lock);1245dump_replay_data_unsafe(out);1246)1247}12481249void ciEnv::dump_replay_data(int compile_id) {1250static char buffer[O_BUFLEN];1251int ret = jio_snprintf(buffer, O_BUFLEN, "replay_pid%p_compid%d.log", os::current_process_id(), compile_id);1252if (ret > 0) {1253int fd = os::open(buffer, O_RDWR | O_CREAT | O_TRUNC, 0666);1254if (fd != -1) {1255FILE* replay_data_file = os::open(fd, "w");1256if (replay_data_file != NULL) {1257fileStream replay_data_stream(replay_data_file, /*need_close=*/true);1258dump_replay_data(&replay_data_stream);1259tty->print_cr("# Compiler replay data is saved as: %s", buffer);1260} else {1261tty->print_cr("# Can't open file to dump replay data.");1262}1263}1264}1265}12661267void ciEnv::dump_inline_data(int compile_id) {1268static char buffer[O_BUFLEN];1269int ret = jio_snprintf(buffer, O_BUFLEN, "inline_pid%p_compid%d.log", os::current_process_id(), compile_id);1270if (ret > 0) {1271int fd = os::open(buffer, O_RDWR | O_CREAT | O_TRUNC, 0666);1272if (fd != -1) {1273FILE* inline_data_file = os::open(fd, "w");1274if (inline_data_file != NULL) {1275fileStream replay_data_stream(inline_data_file, /*need_close=*/true);1276GUARDED_VM_ENTRY(1277MutexLocker ml(Compile_lock);1278dump_compile_data(&replay_data_stream);1279)1280replay_data_stream.flush();1281tty->print("# Compiler inline data is saved as: ");1282tty->print_cr("%s", buffer);1283} else {1284tty->print_cr("# Can't open file to dump inline data.");1285}1286}1287}1288}128912901291