Path: blob/master/src/hotspot/share/runtime/deoptimization.cpp
64440 views
/*1* Copyright (c) 1997, 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 "classfile/javaClasses.inline.hpp"27#include "classfile/symbolTable.hpp"28#include "classfile/systemDictionary.hpp"29#include "classfile/vmClasses.hpp"30#include "code/codeCache.hpp"31#include "code/debugInfoRec.hpp"32#include "code/nmethod.hpp"33#include "code/pcDesc.hpp"34#include "code/scopeDesc.hpp"35#include "compiler/compilationPolicy.hpp"36#include "gc/shared/collectedHeap.hpp"37#include "interpreter/bytecode.hpp"38#include "interpreter/interpreter.hpp"39#include "interpreter/oopMapCache.hpp"40#include "memory/allocation.inline.hpp"41#include "memory/oopFactory.hpp"42#include "memory/resourceArea.hpp"43#include "memory/universe.hpp"44#include "oops/constantPool.hpp"45#include "oops/method.hpp"46#include "oops/objArrayKlass.hpp"47#include "oops/objArrayOop.inline.hpp"48#include "oops/oop.inline.hpp"49#include "oops/fieldStreams.inline.hpp"50#include "oops/typeArrayOop.inline.hpp"51#include "oops/verifyOopClosure.hpp"52#include "prims/jvmtiDeferredUpdates.hpp"53#include "prims/jvmtiExport.hpp"54#include "prims/jvmtiThreadState.hpp"55#include "prims/vectorSupport.hpp"56#include "prims/methodHandles.hpp"57#include "runtime/atomic.hpp"58#include "runtime/biasedLocking.hpp"59#include "runtime/deoptimization.hpp"60#include "runtime/escapeBarrier.hpp"61#include "runtime/fieldDescriptor.hpp"62#include "runtime/fieldDescriptor.inline.hpp"63#include "runtime/frame.inline.hpp"64#include "runtime/handles.inline.hpp"65#include "runtime/interfaceSupport.inline.hpp"66#include "runtime/jniHandles.inline.hpp"67#include "runtime/keepStackGCProcessed.hpp"68#include "runtime/objectMonitor.inline.hpp"69#include "runtime/osThread.hpp"70#include "runtime/safepointVerifiers.hpp"71#include "runtime/sharedRuntime.hpp"72#include "runtime/signature.hpp"73#include "runtime/stackFrameStream.inline.hpp"74#include "runtime/stackWatermarkSet.hpp"75#include "runtime/stubRoutines.hpp"76#include "runtime/thread.hpp"77#include "runtime/threadSMR.hpp"78#include "runtime/threadWXSetters.inline.hpp"79#include "runtime/vframe.hpp"80#include "runtime/vframeArray.hpp"81#include "runtime/vframe_hp.hpp"82#include "runtime/vmOperations.hpp"83#include "utilities/events.hpp"84#include "utilities/macros.hpp"85#include "utilities/preserveException.hpp"86#include "utilities/xmlstream.hpp"87#if INCLUDE_JFR88#include "jfr/jfrEvents.hpp"89#include "jfr/metadata/jfrSerializer.hpp"90#endif9192bool DeoptimizationMarker::_is_active = false;9394Deoptimization::UnrollBlock::UnrollBlock(int size_of_deoptimized_frame,95int caller_adjustment,96int caller_actual_parameters,97int number_of_frames,98intptr_t* frame_sizes,99address* frame_pcs,100BasicType return_type,101int exec_mode) {102_size_of_deoptimized_frame = size_of_deoptimized_frame;103_caller_adjustment = caller_adjustment;104_caller_actual_parameters = caller_actual_parameters;105_number_of_frames = number_of_frames;106_frame_sizes = frame_sizes;107_frame_pcs = frame_pcs;108_register_block = NEW_C_HEAP_ARRAY(intptr_t, RegisterMap::reg_count * 2, mtCompiler);109_return_type = return_type;110_initial_info = 0;111// PD (x86 only)112_counter_temp = 0;113_unpack_kind = exec_mode;114_sender_sp_temp = 0;115116_total_frame_sizes = size_of_frames();117assert(exec_mode >= 0 && exec_mode < Unpack_LIMIT, "Unexpected exec_mode");118}119120121Deoptimization::UnrollBlock::~UnrollBlock() {122FREE_C_HEAP_ARRAY(intptr_t, _frame_sizes);123FREE_C_HEAP_ARRAY(intptr_t, _frame_pcs);124FREE_C_HEAP_ARRAY(intptr_t, _register_block);125}126127128intptr_t* Deoptimization::UnrollBlock::value_addr_at(int register_number) const {129assert(register_number < RegisterMap::reg_count, "checking register number");130return &_register_block[register_number * 2];131}132133134135int Deoptimization::UnrollBlock::size_of_frames() const {136// Acount first for the adjustment of the initial frame137int result = _caller_adjustment;138for (int index = 0; index < number_of_frames(); index++) {139result += frame_sizes()[index];140}141return result;142}143144145void Deoptimization::UnrollBlock::print() {146ttyLocker ttyl;147tty->print_cr("UnrollBlock");148tty->print_cr(" size_of_deoptimized_frame = %d", _size_of_deoptimized_frame);149tty->print( " frame_sizes: ");150for (int index = 0; index < number_of_frames(); index++) {151tty->print(INTX_FORMAT " ", frame_sizes()[index]);152}153tty->cr();154}155156157// In order to make fetch_unroll_info work properly with escape158// analysis, the method was changed from JRT_LEAF to JRT_BLOCK_ENTRY.159// The actual reallocation of previously eliminated objects occurs in realloc_objects,160// which is called from the method fetch_unroll_info_helper below.161JRT_BLOCK_ENTRY(Deoptimization::UnrollBlock*, Deoptimization::fetch_unroll_info(JavaThread* current, int exec_mode))162// fetch_unroll_info() is called at the beginning of the deoptimization163// handler. Note this fact before we start generating temporary frames164// that can confuse an asynchronous stack walker. This counter is165// decremented at the end of unpack_frames().166if (TraceDeoptimization) {167tty->print_cr("Deoptimizing thread " INTPTR_FORMAT, p2i(current));168}169current->inc_in_deopt_handler();170171if (exec_mode == Unpack_exception) {172// When we get here, a callee has thrown an exception into a deoptimized173// frame. That throw might have deferred stack watermark checking until174// after unwinding. So we deal with such deferred requests here.175StackWatermarkSet::after_unwind(current);176}177178return fetch_unroll_info_helper(current, exec_mode);179JRT_END180181#if COMPILER2_OR_JVMCI182static bool rematerialize_objects(JavaThread* thread, int exec_mode, CompiledMethod* compiled_method,183frame& deoptee, RegisterMap& map, GrowableArray<compiledVFrame*>* chunk,184bool& deoptimized_objects) {185bool realloc_failures = false;186assert (chunk->at(0)->scope() != NULL,"expect only compiled java frames");187188JavaThread* deoptee_thread = chunk->at(0)->thread();189assert(exec_mode == Deoptimization::Unpack_none || (deoptee_thread == thread),190"a frame can only be deoptimized by the owner thread");191192GrowableArray<ScopeValue*>* objects = chunk->at(0)->scope()->objects();193194// The flag return_oop() indicates call sites which return oop195// in compiled code. Such sites include java method calls,196// runtime calls (for example, used to allocate new objects/arrays197// on slow code path) and any other calls generated in compiled code.198// It is not guaranteed that we can get such information here only199// by analyzing bytecode in deoptimized frames. This is why this flag200// is set during method compilation (see Compile::Process_OopMap_Node()).201// If the previous frame was popped or if we are dispatching an exception,202// we don't have an oop result.203bool save_oop_result = chunk->at(0)->scope()->return_oop() && !thread->popframe_forcing_deopt_reexecution() && (exec_mode == Deoptimization::Unpack_deopt);204Handle return_value;205if (save_oop_result) {206// Reallocation may trigger GC. If deoptimization happened on return from207// call which returns oop we need to save it since it is not in oopmap.208oop result = deoptee.saved_oop_result(&map);209assert(oopDesc::is_oop_or_null(result), "must be oop");210return_value = Handle(thread, result);211assert(Universe::heap()->is_in_or_null(result), "must be heap pointer");212if (TraceDeoptimization) {213ttyLocker ttyl;214tty->print_cr("SAVED OOP RESULT " INTPTR_FORMAT " in thread " INTPTR_FORMAT, p2i(result), p2i(thread));215}216}217if (objects != NULL) {218if (exec_mode == Deoptimization::Unpack_none) {219assert(thread->thread_state() == _thread_in_vm, "assumption");220JavaThread* THREAD = thread; // For exception macros.221// Clear pending OOM if reallocation fails and return true indicating allocation failure222realloc_failures = Deoptimization::realloc_objects(thread, &deoptee, &map, objects, CHECK_AND_CLEAR_(true));223deoptimized_objects = true;224} else {225JavaThread* current = thread; // For JRT_BLOCK226JRT_BLOCK227realloc_failures = Deoptimization::realloc_objects(thread, &deoptee, &map, objects, THREAD);228JRT_END229}230bool skip_internal = (compiled_method != NULL) && !compiled_method->is_compiled_by_jvmci();231Deoptimization::reassign_fields(&deoptee, &map, objects, realloc_failures, skip_internal);232#ifndef PRODUCT233if (TraceDeoptimization) {234ttyLocker ttyl;235tty->print_cr("REALLOC OBJECTS in thread " INTPTR_FORMAT, p2i(deoptee_thread));236Deoptimization::print_objects(objects, realloc_failures);237}238#endif239}240if (save_oop_result) {241// Restore result.242deoptee.set_saved_oop_result(&map, return_value());243}244return realloc_failures;245}246247static void restore_eliminated_locks(JavaThread* thread, GrowableArray<compiledVFrame*>* chunk, bool realloc_failures,248frame& deoptee, int exec_mode, bool& deoptimized_objects) {249JavaThread* deoptee_thread = chunk->at(0)->thread();250assert(!EscapeBarrier::objs_are_deoptimized(deoptee_thread, deoptee.id()), "must relock just once");251assert(thread == Thread::current(), "should be");252HandleMark hm(thread);253#ifndef PRODUCT254bool first = true;255#endif256for (int i = 0; i < chunk->length(); i++) {257compiledVFrame* cvf = chunk->at(i);258assert (cvf->scope() != NULL,"expect only compiled java frames");259GrowableArray<MonitorInfo*>* monitors = cvf->monitors();260if (monitors->is_nonempty()) {261bool relocked = Deoptimization::relock_objects(thread, monitors, deoptee_thread, deoptee,262exec_mode, realloc_failures);263deoptimized_objects = deoptimized_objects || relocked;264#ifndef PRODUCT265if (PrintDeoptimizationDetails) {266ttyLocker ttyl;267for (int j = 0; j < monitors->length(); j++) {268MonitorInfo* mi = monitors->at(j);269if (mi->eliminated()) {270if (first) {271first = false;272tty->print_cr("RELOCK OBJECTS in thread " INTPTR_FORMAT, p2i(thread));273}274if (exec_mode == Deoptimization::Unpack_none) {275ObjectMonitor* monitor = deoptee_thread->current_waiting_monitor();276if (monitor != NULL && monitor->object() == mi->owner()) {277tty->print_cr(" object <" INTPTR_FORMAT "> DEFERRED relocking after wait", p2i(mi->owner()));278continue;279}280}281if (mi->owner_is_scalar_replaced()) {282Klass* k = java_lang_Class::as_Klass(mi->owner_klass());283tty->print_cr(" failed reallocation for klass %s", k->external_name());284} else {285tty->print_cr(" object <" INTPTR_FORMAT "> locked", p2i(mi->owner()));286}287}288}289}290#endif // !PRODUCT291}292}293}294295// Deoptimize objects, that is reallocate and relock them, just before they escape through JVMTI.296// The given vframes cover one physical frame.297bool Deoptimization::deoptimize_objects_internal(JavaThread* thread, GrowableArray<compiledVFrame*>* chunk,298bool& realloc_failures) {299frame deoptee = chunk->at(0)->fr();300JavaThread* deoptee_thread = chunk->at(0)->thread();301CompiledMethod* cm = deoptee.cb()->as_compiled_method_or_null();302RegisterMap map(chunk->at(0)->register_map());303bool deoptimized_objects = false;304305bool const jvmci_enabled = JVMCI_ONLY(UseJVMCICompiler) NOT_JVMCI(false);306307// Reallocate the non-escaping objects and restore their fields.308if (jvmci_enabled COMPILER2_PRESENT(|| (DoEscapeAnalysis && EliminateAllocations)309|| EliminateAutoBox || EnableVectorAggressiveReboxing)) {310realloc_failures = rematerialize_objects(thread, Unpack_none, cm, deoptee, map, chunk, deoptimized_objects);311}312313// Revoke biases of objects with eliminated locks in the given frame.314Deoptimization::revoke_for_object_deoptimization(deoptee_thread, deoptee, &map, thread);315316// MonitorInfo structures used in eliminate_locks are not GC safe.317NoSafepointVerifier no_safepoint;318319// Now relock objects if synchronization on them was eliminated.320if (jvmci_enabled COMPILER2_PRESENT(|| ((DoEscapeAnalysis || EliminateNestedLocks) && EliminateLocks))) {321restore_eliminated_locks(thread, chunk, realloc_failures, deoptee, Unpack_none, deoptimized_objects);322}323return deoptimized_objects;324}325#endif // COMPILER2_OR_JVMCI326327// This is factored, since it is both called from a JRT_LEAF (deoptimization) and a JRT_ENTRY (uncommon_trap)328Deoptimization::UnrollBlock* Deoptimization::fetch_unroll_info_helper(JavaThread* current, int exec_mode) {329// When we get here we are about to unwind the deoptee frame. In order to330// catch not yet safe to use frames, the following stack watermark barrier331// poll will make such frames safe to use.332StackWatermarkSet::before_unwind(current);333334// Note: there is a safepoint safety issue here. No matter whether we enter335// via vanilla deopt or uncommon trap we MUST NOT stop at a safepoint once336// the vframeArray is created.337//338339// Allocate our special deoptimization ResourceMark340DeoptResourceMark* dmark = new DeoptResourceMark(current);341assert(current->deopt_mark() == NULL, "Pending deopt!");342current->set_deopt_mark(dmark);343344frame stub_frame = current->last_frame(); // Makes stack walkable as side effect345RegisterMap map(current, true);346RegisterMap dummy_map(current, false);347// Now get the deoptee with a valid map348frame deoptee = stub_frame.sender(&map);349// Set the deoptee nmethod350assert(current->deopt_compiled_method() == NULL, "Pending deopt!");351CompiledMethod* cm = deoptee.cb()->as_compiled_method_or_null();352current->set_deopt_compiled_method(cm);353354if (VerifyStack) {355current->validate_frame_layout();356}357358// Create a growable array of VFrames where each VFrame represents an inlined359// Java frame. This storage is allocated with the usual system arena.360assert(deoptee.is_compiled_frame(), "Wrong frame type");361GrowableArray<compiledVFrame*>* chunk = new GrowableArray<compiledVFrame*>(10);362vframe* vf = vframe::new_vframe(&deoptee, &map, current);363while (!vf->is_top()) {364assert(vf->is_compiled_frame(), "Wrong frame type");365chunk->push(compiledVFrame::cast(vf));366vf = vf->sender();367}368assert(vf->is_compiled_frame(), "Wrong frame type");369chunk->push(compiledVFrame::cast(vf));370371bool realloc_failures = false;372373#if COMPILER2_OR_JVMCI374bool const jvmci_enabled = JVMCI_ONLY(EnableJVMCI) NOT_JVMCI(false);375376// Reallocate the non-escaping objects and restore their fields. Then377// relock objects if synchronization on them was eliminated.378if (jvmci_enabled COMPILER2_PRESENT( || (DoEscapeAnalysis && EliminateAllocations)379|| EliminateAutoBox || EnableVectorAggressiveReboxing )) {380bool unused;381realloc_failures = rematerialize_objects(current, exec_mode, cm, deoptee, map, chunk, unused);382}383#endif // COMPILER2_OR_JVMCI384385// Revoke biases, done with in java state.386// No safepoints allowed after this387revoke_from_deopt_handler(current, deoptee, &map);388389// Ensure that no safepoint is taken after pointers have been stored390// in fields of rematerialized objects. If a safepoint occurs from here on391// out the java state residing in the vframeArray will be missed.392// Locks may be rebaised in a safepoint.393NoSafepointVerifier no_safepoint;394395#if COMPILER2_OR_JVMCI396if ((jvmci_enabled COMPILER2_PRESENT( || ((DoEscapeAnalysis || EliminateNestedLocks) && EliminateLocks) ))397&& !EscapeBarrier::objs_are_deoptimized(current, deoptee.id())) {398bool unused;399restore_eliminated_locks(current, chunk, realloc_failures, deoptee, exec_mode, unused);400}401#endif // COMPILER2_OR_JVMCI402403ScopeDesc* trap_scope = chunk->at(0)->scope();404Handle exceptionObject;405if (trap_scope->rethrow_exception()) {406if (PrintDeoptimizationDetails) {407tty->print_cr("Exception to be rethrown in the interpreter for method %s::%s at bci %d", trap_scope->method()->method_holder()->name()->as_C_string(), trap_scope->method()->name()->as_C_string(), trap_scope->bci());408}409GrowableArray<ScopeValue*>* expressions = trap_scope->expressions();410guarantee(expressions != NULL && expressions->length() > 0, "must have exception to throw");411ScopeValue* topOfStack = expressions->top();412exceptionObject = StackValue::create_stack_value(&deoptee, &map, topOfStack)->get_obj();413guarantee(exceptionObject() != NULL, "exception oop can not be null");414}415416vframeArray* array = create_vframeArray(current, deoptee, &map, chunk, realloc_failures);417#if COMPILER2_OR_JVMCI418if (realloc_failures) {419pop_frames_failed_reallocs(current, array);420}421#endif422423assert(current->vframe_array_head() == NULL, "Pending deopt!");424current->set_vframe_array_head(array);425426// Now that the vframeArray has been created if we have any deferred local writes427// added by jvmti then we can free up that structure as the data is now in the428// vframeArray429430JvmtiDeferredUpdates::delete_updates_for_frame(current, array->original().id());431432// Compute the caller frame based on the sender sp of stub_frame and stored frame sizes info.433CodeBlob* cb = stub_frame.cb();434// Verify we have the right vframeArray435assert(cb->frame_size() >= 0, "Unexpected frame size");436intptr_t* unpack_sp = stub_frame.sp() + cb->frame_size();437438// If the deopt call site is a MethodHandle invoke call site we have439// to adjust the unpack_sp.440nmethod* deoptee_nm = deoptee.cb()->as_nmethod_or_null();441if (deoptee_nm != NULL && deoptee_nm->is_method_handle_return(deoptee.pc()))442unpack_sp = deoptee.unextended_sp();443444#ifdef ASSERT445assert(cb->is_deoptimization_stub() ||446cb->is_uncommon_trap_stub() ||447strcmp("Stub<DeoptimizationStub.deoptimizationHandler>", cb->name()) == 0 ||448strcmp("Stub<UncommonTrapStub.uncommonTrapHandler>", cb->name()) == 0,449"unexpected code blob: %s", cb->name());450#endif451452// This is a guarantee instead of an assert because if vframe doesn't match453// we will unpack the wrong deoptimized frame and wind up in strange places454// where it will be very difficult to figure out what went wrong. Better455// to die an early death here than some very obscure death later when the456// trail is cold.457// Note: on ia64 this guarantee can be fooled by frames with no memory stack458// in that it will fail to detect a problem when there is one. This needs459// more work in tiger timeframe.460guarantee(array->unextended_sp() == unpack_sp, "vframe_array_head must contain the vframeArray to unpack");461462int number_of_frames = array->frames();463464// Compute the vframes' sizes. Note that frame_sizes[] entries are ordered from outermost to innermost465// virtual activation, which is the reverse of the elements in the vframes array.466intptr_t* frame_sizes = NEW_C_HEAP_ARRAY(intptr_t, number_of_frames, mtCompiler);467// +1 because we always have an interpreter return address for the final slot.468address* frame_pcs = NEW_C_HEAP_ARRAY(address, number_of_frames + 1, mtCompiler);469int popframe_extra_args = 0;470// Create an interpreter return address for the stub to use as its return471// address so the skeletal frames are perfectly walkable472frame_pcs[number_of_frames] = Interpreter::deopt_entry(vtos, 0);473474// PopFrame requires that the preserved incoming arguments from the recently-popped topmost475// activation be put back on the expression stack of the caller for reexecution476if (JvmtiExport::can_pop_frame() && current->popframe_forcing_deopt_reexecution()) {477popframe_extra_args = in_words(current->popframe_preserved_args_size_in_words());478}479480// Find the current pc for sender of the deoptee. Since the sender may have been deoptimized481// itself since the deoptee vframeArray was created we must get a fresh value of the pc rather482// than simply use array->sender.pc(). This requires us to walk the current set of frames483//484frame deopt_sender = stub_frame.sender(&dummy_map); // First is the deoptee frame485deopt_sender = deopt_sender.sender(&dummy_map); // Now deoptee caller486487// It's possible that the number of parameters at the call site is488// different than number of arguments in the callee when method489// handles are used. If the caller is interpreted get the real490// value so that the proper amount of space can be added to it's491// frame.492bool caller_was_method_handle = false;493if (deopt_sender.is_interpreted_frame()) {494methodHandle method(current, deopt_sender.interpreter_frame_method());495Bytecode_invoke cur = Bytecode_invoke_check(method, deopt_sender.interpreter_frame_bci());496if (cur.is_invokedynamic() || cur.is_invokehandle()) {497// Method handle invokes may involve fairly arbitrary chains of498// calls so it's impossible to know how much actual space the499// caller has for locals.500caller_was_method_handle = true;501}502}503504//505// frame_sizes/frame_pcs[0] oldest frame (int or c2i)506// frame_sizes/frame_pcs[1] next oldest frame (int)507// frame_sizes/frame_pcs[n] youngest frame (int)508//509// Now a pc in frame_pcs is actually the return address to the frame's caller (a frame510// owns the space for the return address to it's caller). Confusing ain't it.511//512// The vframe array can address vframes with indices running from513// 0.._frames-1. Index 0 is the youngest frame and _frame - 1 is the oldest (root) frame.514// When we create the skeletal frames we need the oldest frame to be in the zero slot515// in the frame_sizes/frame_pcs so the assembly code can do a trivial walk.516// so things look a little strange in this loop.517//518int callee_parameters = 0;519int callee_locals = 0;520for (int index = 0; index < array->frames(); index++ ) {521// frame[number_of_frames - 1 ] = on_stack_size(youngest)522// frame[number_of_frames - 2 ] = on_stack_size(sender(youngest))523// frame[number_of_frames - 3 ] = on_stack_size(sender(sender(youngest)))524frame_sizes[number_of_frames - 1 - index] = BytesPerWord * array->element(index)->on_stack_size(callee_parameters,525callee_locals,526index == 0,527popframe_extra_args);528// This pc doesn't have to be perfect just good enough to identify the frame529// as interpreted so the skeleton frame will be walkable530// The correct pc will be set when the skeleton frame is completely filled out531// The final pc we store in the loop is wrong and will be overwritten below532frame_pcs[number_of_frames - 1 - index ] = Interpreter::deopt_entry(vtos, 0) - frame::pc_return_offset;533534callee_parameters = array->element(index)->method()->size_of_parameters();535callee_locals = array->element(index)->method()->max_locals();536popframe_extra_args = 0;537}538539// Compute whether the root vframe returns a float or double value.540BasicType return_type;541{542methodHandle method(current, array->element(0)->method());543Bytecode_invoke invoke = Bytecode_invoke_check(method, array->element(0)->bci());544return_type = invoke.is_valid() ? invoke.result_type() : T_ILLEGAL;545}546547// Compute information for handling adapters and adjusting the frame size of the caller.548int caller_adjustment = 0;549550// Compute the amount the oldest interpreter frame will have to adjust551// its caller's stack by. If the caller is a compiled frame then552// we pretend that the callee has no parameters so that the553// extension counts for the full amount of locals and not just554// locals-parms. This is because without a c2i adapter the parm555// area as created by the compiled frame will not be usable by556// the interpreter. (Depending on the calling convention there557// may not even be enough space).558559// QQQ I'd rather see this pushed down into last_frame_adjust560// and have it take the sender (aka caller).561562if (deopt_sender.is_compiled_frame() || caller_was_method_handle) {563caller_adjustment = last_frame_adjust(0, callee_locals);564} else if (callee_locals > callee_parameters) {565// The caller frame may need extending to accommodate566// non-parameter locals of the first unpacked interpreted frame.567// Compute that adjustment.568caller_adjustment = last_frame_adjust(callee_parameters, callee_locals);569}570571// If the sender is deoptimized the we must retrieve the address of the handler572// since the frame will "magically" show the original pc before the deopt573// and we'd undo the deopt.574575frame_pcs[0] = deopt_sender.raw_pc();576577assert(CodeCache::find_blob_unsafe(frame_pcs[0]) != NULL, "bad pc");578579#if INCLUDE_JVMCI580if (exceptionObject() != NULL) {581current->set_exception_oop(exceptionObject());582exec_mode = Unpack_exception;583}584#endif585586if (current->frames_to_pop_failed_realloc() > 0 && exec_mode != Unpack_uncommon_trap) {587assert(current->has_pending_exception(), "should have thrown OOME");588current->set_exception_oop(current->pending_exception());589current->clear_pending_exception();590exec_mode = Unpack_exception;591}592593#if INCLUDE_JVMCI594if (current->frames_to_pop_failed_realloc() > 0) {595current->set_pending_monitorenter(false);596}597#endif598599UnrollBlock* info = new UnrollBlock(array->frame_size() * BytesPerWord,600caller_adjustment * BytesPerWord,601caller_was_method_handle ? 0 : callee_parameters,602number_of_frames,603frame_sizes,604frame_pcs,605return_type,606exec_mode);607// On some platforms, we need a way to pass some platform dependent608// information to the unpacking code so the skeletal frames come out609// correct (initial fp value, unextended sp, ...)610info->set_initial_info((intptr_t) array->sender().initial_deoptimization_info());611612if (array->frames() > 1) {613if (VerifyStack && TraceDeoptimization) {614ttyLocker ttyl;615tty->print_cr("Deoptimizing method containing inlining");616}617}618619array->set_unroll_block(info);620return info;621}622623// Called to cleanup deoptimization data structures in normal case624// after unpacking to stack and when stack overflow error occurs625void Deoptimization::cleanup_deopt_info(JavaThread *thread,626vframeArray *array) {627628// Get array if coming from exception629if (array == NULL) {630array = thread->vframe_array_head();631}632thread->set_vframe_array_head(NULL);633634// Free the previous UnrollBlock635vframeArray* old_array = thread->vframe_array_last();636thread->set_vframe_array_last(array);637638if (old_array != NULL) {639UnrollBlock* old_info = old_array->unroll_block();640old_array->set_unroll_block(NULL);641delete old_info;642delete old_array;643}644645// Deallocate any resource creating in this routine and any ResourceObjs allocated646// inside the vframeArray (StackValueCollections)647648delete thread->deopt_mark();649thread->set_deopt_mark(NULL);650thread->set_deopt_compiled_method(NULL);651652653if (JvmtiExport::can_pop_frame()) {654// Regardless of whether we entered this routine with the pending655// popframe condition bit set, we should always clear it now656thread->clear_popframe_condition();657}658659// unpack_frames() is called at the end of the deoptimization handler660// and (in C2) at the end of the uncommon trap handler. Note this fact661// so that an asynchronous stack walker can work again. This counter is662// incremented at the beginning of fetch_unroll_info() and (in C2) at663// the beginning of uncommon_trap().664thread->dec_in_deopt_handler();665}666667// Moved from cpu directories because none of the cpus has callee save values.668// If a cpu implements callee save values, move this to deoptimization_<cpu>.cpp.669void Deoptimization::unwind_callee_save_values(frame* f, vframeArray* vframe_array) {670671// This code is sort of the equivalent of C2IAdapter::setup_stack_frame back in672// the days we had adapter frames. When we deoptimize a situation where a673// compiled caller calls a compiled caller will have registers it expects674// to survive the call to the callee. If we deoptimize the callee the only675// way we can restore these registers is to have the oldest interpreter676// frame that we create restore these values. That is what this routine677// will accomplish.678679// At the moment we have modified c2 to not have any callee save registers680// so this problem does not exist and this routine is just a place holder.681682assert(f->is_interpreted_frame(), "must be interpreted");683}684685#ifndef PRODUCT686static bool falls_through(Bytecodes::Code bc) {687switch (bc) {688// List may be incomplete. Here we really only care about bytecodes where compiled code689// can deoptimize.690case Bytecodes::_goto:691case Bytecodes::_goto_w:692case Bytecodes::_athrow:693return false;694default:695return true;696}697}698#endif699700// Return BasicType of value being returned701JRT_LEAF(BasicType, Deoptimization::unpack_frames(JavaThread* thread, int exec_mode))702703// We are already active in the special DeoptResourceMark any ResourceObj's we704// allocate will be freed at the end of the routine.705706// JRT_LEAF methods don't normally allocate handles and there is a707// NoHandleMark to enforce that. It is actually safe to use Handles708// in a JRT_LEAF method, and sometimes desirable, but to do so we709// must use ResetNoHandleMark to bypass the NoHandleMark, and710// then use a HandleMark to ensure any Handles we do create are711// cleaned up in this scope.712ResetNoHandleMark rnhm;713HandleMark hm(thread);714715frame stub_frame = thread->last_frame();716717// Since the frame to unpack is the top frame of this thread, the vframe_array_head718// must point to the vframeArray for the unpack frame.719vframeArray* array = thread->vframe_array_head();720721#ifndef PRODUCT722if (TraceDeoptimization) {723ttyLocker ttyl;724tty->print_cr("DEOPT UNPACKING thread " INTPTR_FORMAT " vframeArray " INTPTR_FORMAT " mode %d",725p2i(thread), p2i(array), exec_mode);726}727#endif728Events::log_deopt_message(thread, "DEOPT UNPACKING pc=" INTPTR_FORMAT " sp=" INTPTR_FORMAT " mode %d",729p2i(stub_frame.pc()), p2i(stub_frame.sp()), exec_mode);730731UnrollBlock* info = array->unroll_block();732733// We set the last_Java frame. But the stack isn't really parsable here. So we734// clear it to make sure JFR understands not to try and walk stacks from events735// in here.736intptr_t* sp = thread->frame_anchor()->last_Java_sp();737thread->frame_anchor()->set_last_Java_sp(NULL);738739// Unpack the interpreter frames and any adapter frame (c2 only) we might create.740array->unpack_to_stack(stub_frame, exec_mode, info->caller_actual_parameters());741742thread->frame_anchor()->set_last_Java_sp(sp);743744BasicType bt = info->return_type();745746// If we have an exception pending, claim that the return type is an oop747// so the deopt_blob does not overwrite the exception_oop.748749if (exec_mode == Unpack_exception)750bt = T_OBJECT;751752// Cleanup thread deopt data753cleanup_deopt_info(thread, array);754755#ifndef PRODUCT756if (VerifyStack) {757ResourceMark res_mark;758// Clear pending exception to not break verification code (restored afterwards)759PreserveExceptionMark pm(thread);760761thread->validate_frame_layout();762763// Verify that the just-unpacked frames match the interpreter's764// notions of expression stack and locals765vframeArray* cur_array = thread->vframe_array_last();766RegisterMap rm(thread, false);767rm.set_include_argument_oops(false);768bool is_top_frame = true;769int callee_size_of_parameters = 0;770int callee_max_locals = 0;771for (int i = 0; i < cur_array->frames(); i++) {772vframeArrayElement* el = cur_array->element(i);773frame* iframe = el->iframe();774guarantee(iframe->is_interpreted_frame(), "Wrong frame type");775776// Get the oop map for this bci777InterpreterOopMap mask;778int cur_invoke_parameter_size = 0;779bool try_next_mask = false;780int next_mask_expression_stack_size = -1;781int top_frame_expression_stack_adjustment = 0;782methodHandle mh(thread, iframe->interpreter_frame_method());783OopMapCache::compute_one_oop_map(mh, iframe->interpreter_frame_bci(), &mask);784BytecodeStream str(mh, iframe->interpreter_frame_bci());785int max_bci = mh->code_size();786// Get to the next bytecode if possible787assert(str.bci() < max_bci, "bci in interpreter frame out of bounds");788// Check to see if we can grab the number of outgoing arguments789// at an uncommon trap for an invoke (where the compiler790// generates debug info before the invoke has executed)791Bytecodes::Code cur_code = str.next();792Bytecodes::Code next_code = Bytecodes::_shouldnotreachhere;793if (Bytecodes::is_invoke(cur_code)) {794Bytecode_invoke invoke(mh, iframe->interpreter_frame_bci());795cur_invoke_parameter_size = invoke.size_of_parameters();796if (i != 0 && !invoke.is_invokedynamic() && MethodHandles::has_member_arg(invoke.klass(), invoke.name())) {797callee_size_of_parameters++;798}799}800if (str.bci() < max_bci) {801next_code = str.next();802if (next_code >= 0) {803// The interpreter oop map generator reports results before804// the current bytecode has executed except in the case of805// calls. It seems to be hard to tell whether the compiler806// has emitted debug information matching the "state before"807// a given bytecode or the state after, so we try both808if (!Bytecodes::is_invoke(cur_code) && falls_through(cur_code)) {809// Get expression stack size for the next bytecode810InterpreterOopMap next_mask;811OopMapCache::compute_one_oop_map(mh, str.bci(), &next_mask);812next_mask_expression_stack_size = next_mask.expression_stack_size();813if (Bytecodes::is_invoke(next_code)) {814Bytecode_invoke invoke(mh, str.bci());815next_mask_expression_stack_size += invoke.size_of_parameters();816}817// Need to subtract off the size of the result type of818// the bytecode because this is not described in the819// debug info but returned to the interpreter in the TOS820// caching register821BasicType bytecode_result_type = Bytecodes::result_type(cur_code);822if (bytecode_result_type != T_ILLEGAL) {823top_frame_expression_stack_adjustment = type2size[bytecode_result_type];824}825assert(top_frame_expression_stack_adjustment >= 0, "stack adjustment must be positive");826try_next_mask = true;827}828}829}830831// Verify stack depth and oops in frame832// This assertion may be dependent on the platform we're running on and may need modification (tested on x86 and sparc)833if (!(834/* SPARC */835(iframe->interpreter_frame_expression_stack_size() == mask.expression_stack_size() + callee_size_of_parameters) ||836/* x86 */837(iframe->interpreter_frame_expression_stack_size() == mask.expression_stack_size() + callee_max_locals) ||838(try_next_mask &&839(iframe->interpreter_frame_expression_stack_size() == (next_mask_expression_stack_size -840top_frame_expression_stack_adjustment))) ||841(is_top_frame && (exec_mode == Unpack_exception) && iframe->interpreter_frame_expression_stack_size() == 0) ||842(is_top_frame && (exec_mode == Unpack_uncommon_trap || exec_mode == Unpack_reexecute || el->should_reexecute()) &&843(iframe->interpreter_frame_expression_stack_size() == mask.expression_stack_size() + cur_invoke_parameter_size))844)) {845{846ttyLocker ttyl;847848// Print out some information that will help us debug the problem849tty->print_cr("Wrong number of expression stack elements during deoptimization");850tty->print_cr(" Error occurred while verifying frame %d (0..%d, 0 is topmost)", i, cur_array->frames() - 1);851tty->print_cr(" Current code %s", Bytecodes::name(cur_code));852if (try_next_mask) {853tty->print_cr(" Next code %s", Bytecodes::name(next_code));854}855tty->print_cr(" Fabricated interpreter frame had %d expression stack elements",856iframe->interpreter_frame_expression_stack_size());857tty->print_cr(" Interpreter oop map had %d expression stack elements", mask.expression_stack_size());858tty->print_cr(" try_next_mask = %d", try_next_mask);859tty->print_cr(" next_mask_expression_stack_size = %d", next_mask_expression_stack_size);860tty->print_cr(" callee_size_of_parameters = %d", callee_size_of_parameters);861tty->print_cr(" callee_max_locals = %d", callee_max_locals);862tty->print_cr(" top_frame_expression_stack_adjustment = %d", top_frame_expression_stack_adjustment);863tty->print_cr(" exec_mode = %d", exec_mode);864tty->print_cr(" cur_invoke_parameter_size = %d", cur_invoke_parameter_size);865tty->print_cr(" Thread = " INTPTR_FORMAT ", thread ID = %d", p2i(thread), thread->osthread()->thread_id());866tty->print_cr(" Interpreted frames:");867for (int k = 0; k < cur_array->frames(); k++) {868vframeArrayElement* el = cur_array->element(k);869tty->print_cr(" %s (bci %d)", el->method()->name_and_sig_as_C_string(), el->bci());870}871cur_array->print_on_2(tty);872} // release tty lock before calling guarantee873guarantee(false, "wrong number of expression stack elements during deopt");874}875VerifyOopClosure verify;876iframe->oops_interpreted_do(&verify, &rm, false);877callee_size_of_parameters = mh->size_of_parameters();878callee_max_locals = mh->max_locals();879is_top_frame = false;880}881}882#endif /* !PRODUCT */883884return bt;885JRT_END886887class DeoptimizeMarkedClosure : public HandshakeClosure {888public:889DeoptimizeMarkedClosure() : HandshakeClosure("Deoptimize") {}890void do_thread(Thread* thread) {891JavaThread* jt = thread->as_Java_thread();892jt->deoptimize_marked_methods();893}894};895896void Deoptimization::deoptimize_all_marked(nmethod* nmethod_only) {897ResourceMark rm;898DeoptimizationMarker dm;899900// Make the dependent methods not entrant901if (nmethod_only != NULL) {902nmethod_only->mark_for_deoptimization();903nmethod_only->make_not_entrant();904} else {905MutexLocker mu(SafepointSynchronize::is_at_safepoint() ? NULL : CodeCache_lock, Mutex::_no_safepoint_check_flag);906CodeCache::make_marked_nmethods_not_entrant();907}908909DeoptimizeMarkedClosure deopt;910if (SafepointSynchronize::is_at_safepoint()) {911Threads::java_threads_do(&deopt);912} else {913Handshake::execute(&deopt);914}915}916917Deoptimization::DeoptAction Deoptimization::_unloaded_action918= Deoptimization::Action_reinterpret;919920#if COMPILER2_OR_JVMCI921template<typename CacheType>922class BoxCacheBase : public CHeapObj<mtCompiler> {923protected:924static InstanceKlass* find_cache_klass(Symbol* klass_name) {925ResourceMark rm;926char* klass_name_str = klass_name->as_C_string();927InstanceKlass* ik = SystemDictionary::find_instance_klass(klass_name, Handle(), Handle());928guarantee(ik != NULL, "%s must be loaded", klass_name_str);929guarantee(ik->is_initialized(), "%s must be initialized", klass_name_str);930CacheType::compute_offsets(ik);931return ik;932}933};934935template<typename PrimitiveType, typename CacheType, typename BoxType> class BoxCache : public BoxCacheBase<CacheType> {936PrimitiveType _low;937PrimitiveType _high;938jobject _cache;939protected:940static BoxCache<PrimitiveType, CacheType, BoxType> *_singleton;941BoxCache(Thread* thread) {942InstanceKlass* ik = BoxCacheBase<CacheType>::find_cache_klass(CacheType::symbol());943objArrayOop cache = CacheType::cache(ik);944assert(cache->length() > 0, "Empty cache");945_low = BoxType::value(cache->obj_at(0));946_high = _low + cache->length() - 1;947_cache = JNIHandles::make_global(Handle(thread, cache));948}949~BoxCache() {950JNIHandles::destroy_global(_cache);951}952public:953static BoxCache<PrimitiveType, CacheType, BoxType>* singleton(Thread* thread) {954if (_singleton == NULL) {955BoxCache<PrimitiveType, CacheType, BoxType>* s = new BoxCache<PrimitiveType, CacheType, BoxType>(thread);956if (!Atomic::replace_if_null(&_singleton, s)) {957delete s;958}959}960return _singleton;961}962oop lookup(PrimitiveType value) {963if (_low <= value && value <= _high) {964int offset = value - _low;965return objArrayOop(JNIHandles::resolve_non_null(_cache))->obj_at(offset);966}967return NULL;968}969oop lookup_raw(intptr_t raw_value) {970// Have to cast to avoid little/big-endian problems.971if (sizeof(PrimitiveType) > sizeof(jint)) {972jlong value = (jlong)raw_value;973return lookup(value);974}975PrimitiveType value = (PrimitiveType)*((jint*)&raw_value);976return lookup(value);977}978};979980typedef BoxCache<jint, java_lang_Integer_IntegerCache, java_lang_Integer> IntegerBoxCache;981typedef BoxCache<jlong, java_lang_Long_LongCache, java_lang_Long> LongBoxCache;982typedef BoxCache<jchar, java_lang_Character_CharacterCache, java_lang_Character> CharacterBoxCache;983typedef BoxCache<jshort, java_lang_Short_ShortCache, java_lang_Short> ShortBoxCache;984typedef BoxCache<jbyte, java_lang_Byte_ByteCache, java_lang_Byte> ByteBoxCache;985986template<> BoxCache<jint, java_lang_Integer_IntegerCache, java_lang_Integer>* BoxCache<jint, java_lang_Integer_IntegerCache, java_lang_Integer>::_singleton = NULL;987template<> BoxCache<jlong, java_lang_Long_LongCache, java_lang_Long>* BoxCache<jlong, java_lang_Long_LongCache, java_lang_Long>::_singleton = NULL;988template<> BoxCache<jchar, java_lang_Character_CharacterCache, java_lang_Character>* BoxCache<jchar, java_lang_Character_CharacterCache, java_lang_Character>::_singleton = NULL;989template<> BoxCache<jshort, java_lang_Short_ShortCache, java_lang_Short>* BoxCache<jshort, java_lang_Short_ShortCache, java_lang_Short>::_singleton = NULL;990template<> BoxCache<jbyte, java_lang_Byte_ByteCache, java_lang_Byte>* BoxCache<jbyte, java_lang_Byte_ByteCache, java_lang_Byte>::_singleton = NULL;991992class BooleanBoxCache : public BoxCacheBase<java_lang_Boolean> {993jobject _true_cache;994jobject _false_cache;995protected:996static BooleanBoxCache *_singleton;997BooleanBoxCache(Thread *thread) {998InstanceKlass* ik = find_cache_klass(java_lang_Boolean::symbol());999_true_cache = JNIHandles::make_global(Handle(thread, java_lang_Boolean::get_TRUE(ik)));1000_false_cache = JNIHandles::make_global(Handle(thread, java_lang_Boolean::get_FALSE(ik)));1001}1002~BooleanBoxCache() {1003JNIHandles::destroy_global(_true_cache);1004JNIHandles::destroy_global(_false_cache);1005}1006public:1007static BooleanBoxCache* singleton(Thread* thread) {1008if (_singleton == NULL) {1009BooleanBoxCache* s = new BooleanBoxCache(thread);1010if (!Atomic::replace_if_null(&_singleton, s)) {1011delete s;1012}1013}1014return _singleton;1015}1016oop lookup_raw(intptr_t raw_value) {1017// Have to cast to avoid little/big-endian problems.1018jboolean value = (jboolean)*((jint*)&raw_value);1019return lookup(value);1020}1021oop lookup(jboolean value) {1022if (value != 0) {1023return JNIHandles::resolve_non_null(_true_cache);1024}1025return JNIHandles::resolve_non_null(_false_cache);1026}1027};10281029BooleanBoxCache* BooleanBoxCache::_singleton = NULL;10301031oop Deoptimization::get_cached_box(AutoBoxObjectValue* bv, frame* fr, RegisterMap* reg_map, TRAPS) {1032Klass* k = java_lang_Class::as_Klass(bv->klass()->as_ConstantOopReadValue()->value()());1033BasicType box_type = vmClasses::box_klass_type(k);1034if (box_type != T_OBJECT) {1035StackValue* value = StackValue::create_stack_value(fr, reg_map, bv->field_at(box_type == T_LONG ? 1 : 0));1036switch(box_type) {1037case T_INT: return IntegerBoxCache::singleton(THREAD)->lookup_raw(value->get_int());1038case T_CHAR: return CharacterBoxCache::singleton(THREAD)->lookup_raw(value->get_int());1039case T_SHORT: return ShortBoxCache::singleton(THREAD)->lookup_raw(value->get_int());1040case T_BYTE: return ByteBoxCache::singleton(THREAD)->lookup_raw(value->get_int());1041case T_BOOLEAN: return BooleanBoxCache::singleton(THREAD)->lookup_raw(value->get_int());1042case T_LONG: return LongBoxCache::singleton(THREAD)->lookup_raw(value->get_int());1043default:;1044}1045}1046return NULL;1047}10481049bool Deoptimization::realloc_objects(JavaThread* thread, frame* fr, RegisterMap* reg_map, GrowableArray<ScopeValue*>* objects, TRAPS) {1050Handle pending_exception(THREAD, thread->pending_exception());1051const char* exception_file = thread->exception_file();1052int exception_line = thread->exception_line();1053thread->clear_pending_exception();10541055bool failures = false;10561057for (int i = 0; i < objects->length(); i++) {1058assert(objects->at(i)->is_object(), "invalid debug information");1059ObjectValue* sv = (ObjectValue*) objects->at(i);10601061Klass* k = java_lang_Class::as_Klass(sv->klass()->as_ConstantOopReadValue()->value()());1062oop obj = NULL;10631064if (k->is_instance_klass()) {1065if (sv->is_auto_box()) {1066AutoBoxObjectValue* abv = (AutoBoxObjectValue*) sv;1067obj = get_cached_box(abv, fr, reg_map, THREAD);1068if (obj != NULL) {1069// Set the flag to indicate the box came from a cache, so that we can skip the field reassignment for it.1070abv->set_cached(true);1071}1072}10731074InstanceKlass* ik = InstanceKlass::cast(k);1075if (obj == NULL) {1076#ifdef COMPILER21077if (EnableVectorSupport && VectorSupport::is_vector(ik)) {1078obj = VectorSupport::allocate_vector(ik, fr, reg_map, sv, THREAD);1079} else {1080obj = ik->allocate_instance(THREAD);1081}1082#else1083obj = ik->allocate_instance(THREAD);1084#endif // COMPILER21085}1086} else if (k->is_typeArray_klass()) {1087TypeArrayKlass* ak = TypeArrayKlass::cast(k);1088assert(sv->field_size() % type2size[ak->element_type()] == 0, "non-integral array length");1089int len = sv->field_size() / type2size[ak->element_type()];1090obj = ak->allocate(len, THREAD);1091} else if (k->is_objArray_klass()) {1092ObjArrayKlass* ak = ObjArrayKlass::cast(k);1093obj = ak->allocate(sv->field_size(), THREAD);1094}10951096if (obj == NULL) {1097failures = true;1098}10991100assert(sv->value().is_null(), "redundant reallocation");1101assert(obj != NULL || HAS_PENDING_EXCEPTION, "allocation should succeed or we should get an exception");1102CLEAR_PENDING_EXCEPTION;1103sv->set_value(obj);1104}11051106if (failures) {1107THROW_OOP_(Universe::out_of_memory_error_realloc_objects(), failures);1108} else if (pending_exception.not_null()) {1109thread->set_pending_exception(pending_exception(), exception_file, exception_line);1110}11111112return failures;1113}11141115#if INCLUDE_JVMCI1116/**1117* For primitive types whose kind gets "erased" at runtime (shorts become stack ints),1118* we need to somehow be able to recover the actual kind to be able to write the correct1119* amount of bytes.1120* For that purpose, this method assumes that, for an entry spanning n bytes at index i,1121* the entries at index n + 1 to n + i are 'markers'.1122* For example, if we were writing a short at index 4 of a byte array of size 8, the1123* expected form of the array would be:1124*1125* {b0, b1, b2, b3, INT, marker, b6, b7}1126*1127* Thus, in order to get back the size of the entry, we simply need to count the number1128* of marked entries1129*1130* @param virtualArray the virtualized byte array1131* @param i index of the virtual entry we are recovering1132* @return The number of bytes the entry spans1133*/1134static int count_number_of_bytes_for_entry(ObjectValue *virtualArray, int i) {1135int index = i;1136while (++index < virtualArray->field_size() &&1137virtualArray->field_at(index)->is_marker()) {}1138return index - i;1139}11401141/**1142* If there was a guarantee for byte array to always start aligned to a long, we could1143* do a simple check on the parity of the index. Unfortunately, that is not always the1144* case. Thus, we check alignment of the actual address we are writing to.1145* In the unlikely case index 0 is 5-aligned for example, it would then be possible to1146* write a long to index 3.1147*/1148static jbyte* check_alignment_get_addr(typeArrayOop obj, int index, int expected_alignment) {1149jbyte* res = obj->byte_at_addr(index);1150assert((((intptr_t) res) % expected_alignment) == 0, "Non-aligned write");1151return res;1152}11531154static void byte_array_put(typeArrayOop obj, intptr_t val, int index, int byte_count) {1155switch (byte_count) {1156case 1:1157obj->byte_at_put(index, (jbyte) *((jint *) &val));1158break;1159case 2:1160*((jshort *) check_alignment_get_addr(obj, index, 2)) = (jshort) *((jint *) &val);1161break;1162case 4:1163*((jint *) check_alignment_get_addr(obj, index, 4)) = (jint) *((jint *) &val);1164break;1165case 8:1166*((jlong *) check_alignment_get_addr(obj, index, 8)) = (jlong) *((jlong *) &val);1167break;1168default:1169ShouldNotReachHere();1170}1171}1172#endif // INCLUDE_JVMCI117311741175// restore elements of an eliminated type array1176void Deoptimization::reassign_type_array_elements(frame* fr, RegisterMap* reg_map, ObjectValue* sv, typeArrayOop obj, BasicType type) {1177int index = 0;1178intptr_t val;11791180for (int i = 0; i < sv->field_size(); i++) {1181StackValue* value = StackValue::create_stack_value(fr, reg_map, sv->field_at(i));1182switch(type) {1183case T_LONG: case T_DOUBLE: {1184assert(value->type() == T_INT, "Agreement.");1185StackValue* low =1186StackValue::create_stack_value(fr, reg_map, sv->field_at(++i));1187#ifdef _LP641188jlong res = (jlong)low->get_int();1189#else1190jlong res = jlong_from((jint)value->get_int(), (jint)low->get_int());1191#endif1192obj->long_at_put(index, res);1193break;1194}11951196// Have to cast to INT (32 bits) pointer to avoid little/big-endian problem.1197case T_INT: case T_FLOAT: { // 4 bytes.1198assert(value->type() == T_INT, "Agreement.");1199bool big_value = false;1200if (i + 1 < sv->field_size() && type == T_INT) {1201if (sv->field_at(i)->is_location()) {1202Location::Type type = ((LocationValue*) sv->field_at(i))->location().type();1203if (type == Location::dbl || type == Location::lng) {1204big_value = true;1205}1206} else if (sv->field_at(i)->is_constant_int()) {1207ScopeValue* next_scope_field = sv->field_at(i + 1);1208if (next_scope_field->is_constant_long() || next_scope_field->is_constant_double()) {1209big_value = true;1210}1211}1212}12131214if (big_value) {1215StackValue* low = StackValue::create_stack_value(fr, reg_map, sv->field_at(++i));1216#ifdef _LP641217jlong res = (jlong)low->get_int();1218#else1219jlong res = jlong_from((jint)value->get_int(), (jint)low->get_int());1220#endif1221obj->int_at_put(index, (jint)*((jint*)&res));1222obj->int_at_put(++index, (jint)*(((jint*)&res) + 1));1223} else {1224val = value->get_int();1225obj->int_at_put(index, (jint)*((jint*)&val));1226}1227break;1228}12291230case T_SHORT:1231assert(value->type() == T_INT, "Agreement.");1232val = value->get_int();1233obj->short_at_put(index, (jshort)*((jint*)&val));1234break;12351236case T_CHAR:1237assert(value->type() == T_INT, "Agreement.");1238val = value->get_int();1239obj->char_at_put(index, (jchar)*((jint*)&val));1240break;12411242case T_BYTE: {1243assert(value->type() == T_INT, "Agreement.");1244// The value we get is erased as a regular int. We will need to find its actual byte count 'by hand'.1245val = value->get_int();1246#if INCLUDE_JVMCI1247int byte_count = count_number_of_bytes_for_entry(sv, i);1248byte_array_put(obj, val, index, byte_count);1249// According to byte_count contract, the values from i + 1 to i + byte_count are illegal values. Skip.1250i += byte_count - 1; // Balance the loop counter.1251index += byte_count;1252// index has been updated so continue at top of loop1253continue;1254#else1255obj->byte_at_put(index, (jbyte)*((jint*)&val));1256break;1257#endif // INCLUDE_JVMCI1258}12591260case T_BOOLEAN: {1261assert(value->type() == T_INT, "Agreement.");1262val = value->get_int();1263obj->bool_at_put(index, (jboolean)*((jint*)&val));1264break;1265}12661267default:1268ShouldNotReachHere();1269}1270index++;1271}1272}12731274// restore fields of an eliminated object array1275void Deoptimization::reassign_object_array_elements(frame* fr, RegisterMap* reg_map, ObjectValue* sv, objArrayOop obj) {1276for (int i = 0; i < sv->field_size(); i++) {1277StackValue* value = StackValue::create_stack_value(fr, reg_map, sv->field_at(i));1278assert(value->type() == T_OBJECT, "object element expected");1279obj->obj_at_put(i, value->get_obj()());1280}1281}12821283class ReassignedField {1284public:1285int _offset;1286BasicType _type;1287public:1288ReassignedField() {1289_offset = 0;1290_type = T_ILLEGAL;1291}1292};12931294int compare(ReassignedField* left, ReassignedField* right) {1295return left->_offset - right->_offset;1296}12971298// Restore fields of an eliminated instance object using the same field order1299// returned by HotSpotResolvedObjectTypeImpl.getInstanceFields(true)1300static int reassign_fields_by_klass(InstanceKlass* klass, frame* fr, RegisterMap* reg_map, ObjectValue* sv, int svIndex, oop obj, bool skip_internal) {1301GrowableArray<ReassignedField>* fields = new GrowableArray<ReassignedField>();1302InstanceKlass* ik = klass;1303while (ik != NULL) {1304for (AllFieldStream fs(ik); !fs.done(); fs.next()) {1305if (!fs.access_flags().is_static() && (!skip_internal || !fs.access_flags().is_internal())) {1306ReassignedField field;1307field._offset = fs.offset();1308field._type = Signature::basic_type(fs.signature());1309fields->append(field);1310}1311}1312ik = ik->superklass();1313}1314fields->sort(compare);1315for (int i = 0; i < fields->length(); i++) {1316intptr_t val;1317ScopeValue* scope_field = sv->field_at(svIndex);1318StackValue* value = StackValue::create_stack_value(fr, reg_map, scope_field);1319int offset = fields->at(i)._offset;1320BasicType type = fields->at(i)._type;1321switch (type) {1322case T_OBJECT: case T_ARRAY:1323assert(value->type() == T_OBJECT, "Agreement.");1324obj->obj_field_put(offset, value->get_obj()());1325break;13261327// Have to cast to INT (32 bits) pointer to avoid little/big-endian problem.1328case T_INT: case T_FLOAT: { // 4 bytes.1329assert(value->type() == T_INT, "Agreement.");1330bool big_value = false;1331if (i+1 < fields->length() && fields->at(i+1)._type == T_INT) {1332if (scope_field->is_location()) {1333Location::Type type = ((LocationValue*) scope_field)->location().type();1334if (type == Location::dbl || type == Location::lng) {1335big_value = true;1336}1337}1338if (scope_field->is_constant_int()) {1339ScopeValue* next_scope_field = sv->field_at(svIndex + 1);1340if (next_scope_field->is_constant_long() || next_scope_field->is_constant_double()) {1341big_value = true;1342}1343}1344}13451346if (big_value) {1347i++;1348assert(i < fields->length(), "second T_INT field needed");1349assert(fields->at(i)._type == T_INT, "T_INT field needed");1350} else {1351val = value->get_int();1352obj->int_field_put(offset, (jint)*((jint*)&val));1353break;1354}1355}1356/* no break */13571358case T_LONG: case T_DOUBLE: {1359assert(value->type() == T_INT, "Agreement.");1360StackValue* low = StackValue::create_stack_value(fr, reg_map, sv->field_at(++svIndex));1361#ifdef _LP641362jlong res = (jlong)low->get_int();1363#else1364jlong res = jlong_from((jint)value->get_int(), (jint)low->get_int());1365#endif1366obj->long_field_put(offset, res);1367break;1368}13691370case T_SHORT:1371assert(value->type() == T_INT, "Agreement.");1372val = value->get_int();1373obj->short_field_put(offset, (jshort)*((jint*)&val));1374break;13751376case T_CHAR:1377assert(value->type() == T_INT, "Agreement.");1378val = value->get_int();1379obj->char_field_put(offset, (jchar)*((jint*)&val));1380break;13811382case T_BYTE:1383assert(value->type() == T_INT, "Agreement.");1384val = value->get_int();1385obj->byte_field_put(offset, (jbyte)*((jint*)&val));1386break;13871388case T_BOOLEAN:1389assert(value->type() == T_INT, "Agreement.");1390val = value->get_int();1391obj->bool_field_put(offset, (jboolean)*((jint*)&val));1392break;13931394default:1395ShouldNotReachHere();1396}1397svIndex++;1398}1399return svIndex;1400}14011402// restore fields of all eliminated objects and arrays1403void Deoptimization::reassign_fields(frame* fr, RegisterMap* reg_map, GrowableArray<ScopeValue*>* objects, bool realloc_failures, bool skip_internal) {1404for (int i = 0; i < objects->length(); i++) {1405ObjectValue* sv = (ObjectValue*) objects->at(i);1406Klass* k = java_lang_Class::as_Klass(sv->klass()->as_ConstantOopReadValue()->value()());1407Handle obj = sv->value();1408assert(obj.not_null() || realloc_failures, "reallocation was missed");1409if (PrintDeoptimizationDetails) {1410tty->print_cr("reassign fields for object of type %s!", k->name()->as_C_string());1411}1412if (obj.is_null()) {1413continue;1414}14151416// Don't reassign fields of boxes that came from a cache. Caches may be in CDS.1417if (sv->is_auto_box() && ((AutoBoxObjectValue*) sv)->is_cached()) {1418continue;1419}1420#ifdef COMPILER21421if (EnableVectorSupport && VectorSupport::is_vector(k)) {1422assert(sv->field_size() == 1, "%s not a vector", k->name()->as_C_string());1423ScopeValue* payload = sv->field_at(0);1424if (payload->is_location() &&1425payload->as_LocationValue()->location().type() == Location::vector) {1426if (PrintDeoptimizationDetails) {1427tty->print_cr("skip field reassignment for this vector - it should be assigned already");1428if (Verbose) {1429Handle obj = sv->value();1430k->oop_print_on(obj(), tty);1431}1432}1433continue; // Such vector's value was already restored in VectorSupport::allocate_vector().1434}1435// Else fall-through to do assignment for scalar-replaced boxed vector representation1436// which could be restored after vector object allocation.1437}1438#endif1439if (k->is_instance_klass()) {1440InstanceKlass* ik = InstanceKlass::cast(k);1441reassign_fields_by_klass(ik, fr, reg_map, sv, 0, obj(), skip_internal);1442} else if (k->is_typeArray_klass()) {1443TypeArrayKlass* ak = TypeArrayKlass::cast(k);1444reassign_type_array_elements(fr, reg_map, sv, (typeArrayOop) obj(), ak->element_type());1445} else if (k->is_objArray_klass()) {1446reassign_object_array_elements(fr, reg_map, sv, (objArrayOop) obj());1447}1448}1449}145014511452// relock objects for which synchronization was eliminated1453bool Deoptimization::relock_objects(JavaThread* thread, GrowableArray<MonitorInfo*>* monitors,1454JavaThread* deoptee_thread, frame& fr, int exec_mode, bool realloc_failures) {1455bool relocked_objects = false;1456for (int i = 0; i < monitors->length(); i++) {1457MonitorInfo* mon_info = monitors->at(i);1458if (mon_info->eliminated()) {1459assert(!mon_info->owner_is_scalar_replaced() || realloc_failures, "reallocation was missed");1460relocked_objects = true;1461if (!mon_info->owner_is_scalar_replaced()) {1462Handle obj(thread, mon_info->owner());1463markWord mark = obj->mark();1464if (UseBiasedLocking && mark.has_bias_pattern()) {1465// New allocated objects may have the mark set to anonymously biased.1466// Also the deoptimized method may called methods with synchronization1467// where the thread-local object is bias locked to the current thread.1468assert(mark.is_biased_anonymously() ||1469mark.biased_locker() == deoptee_thread, "should be locked to current thread");1470// Reset mark word to unbiased prototype.1471markWord unbiased_prototype = markWord::prototype().set_age(mark.age());1472obj->set_mark(unbiased_prototype);1473} else if (exec_mode == Unpack_none) {1474if (mark.has_locker() && fr.sp() > (intptr_t*)mark.locker()) {1475// With exec_mode == Unpack_none obj may be thread local and locked in1476// a callee frame. In this case the bias was revoked before in revoke_for_object_deoptimization().1477// Make the lock in the callee a recursive lock and restore the displaced header.1478markWord dmw = mark.displaced_mark_helper();1479mark.locker()->set_displaced_header(markWord::encode((BasicLock*) NULL));1480obj->set_mark(dmw);1481}1482if (mark.has_monitor()) {1483// defer relocking if the deoptee thread is currently waiting for obj1484ObjectMonitor* waiting_monitor = deoptee_thread->current_waiting_monitor();1485if (waiting_monitor != NULL && waiting_monitor->object() == obj()) {1486assert(fr.is_deoptimized_frame(), "frame must be scheduled for deoptimization");1487mon_info->lock()->set_displaced_header(markWord::unused_mark());1488JvmtiDeferredUpdates::inc_relock_count_after_wait(deoptee_thread);1489continue;1490}1491}1492}1493BasicLock* lock = mon_info->lock();1494ObjectSynchronizer::enter(obj, lock, deoptee_thread);1495assert(mon_info->owner()->is_locked(), "object must be locked now");1496}1497}1498}1499return relocked_objects;1500}150115021503#ifndef PRODUCT1504// print information about reallocated objects1505void Deoptimization::print_objects(GrowableArray<ScopeValue*>* objects, bool realloc_failures) {1506fieldDescriptor fd;15071508for (int i = 0; i < objects->length(); i++) {1509ObjectValue* sv = (ObjectValue*) objects->at(i);1510Klass* k = java_lang_Class::as_Klass(sv->klass()->as_ConstantOopReadValue()->value()());1511Handle obj = sv->value();15121513tty->print(" object <" INTPTR_FORMAT "> of type ", p2i(sv->value()()));1514k->print_value();1515assert(obj.not_null() || realloc_failures, "reallocation was missed");1516if (obj.is_null()) {1517tty->print(" allocation failed");1518} else {1519tty->print(" allocated (%d bytes)", obj->size() * HeapWordSize);1520}1521tty->cr();15221523if (Verbose && !obj.is_null()) {1524k->oop_print_on(obj(), tty);1525}1526}1527}1528#endif1529#endif // COMPILER2_OR_JVMCI15301531vframeArray* Deoptimization::create_vframeArray(JavaThread* thread, frame fr, RegisterMap *reg_map, GrowableArray<compiledVFrame*>* chunk, bool realloc_failures) {1532Events::log_deopt_message(thread, "DEOPT PACKING pc=" INTPTR_FORMAT " sp=" INTPTR_FORMAT, p2i(fr.pc()), p2i(fr.sp()));15331534#ifndef PRODUCT1535if (PrintDeoptimizationDetails) {1536ttyLocker ttyl;1537tty->print("DEOPT PACKING thread " INTPTR_FORMAT " ", p2i(thread));1538fr.print_on(tty);1539tty->print_cr(" Virtual frames (innermost first):");1540for (int index = 0; index < chunk->length(); index++) {1541compiledVFrame* vf = chunk->at(index);1542tty->print(" %2d - ", index);1543vf->print_value();1544int bci = chunk->at(index)->raw_bci();1545const char* code_name;1546if (bci == SynchronizationEntryBCI) {1547code_name = "sync entry";1548} else {1549Bytecodes::Code code = vf->method()->code_at(bci);1550code_name = Bytecodes::name(code);1551}1552tty->print(" - %s", code_name);1553tty->print_cr(" @ bci %d ", bci);1554if (Verbose) {1555vf->print();1556tty->cr();1557}1558}1559}1560#endif15611562// Register map for next frame (used for stack crawl). We capture1563// the state of the deopt'ing frame's caller. Thus if we need to1564// stuff a C2I adapter we can properly fill in the callee-save1565// register locations.1566frame caller = fr.sender(reg_map);1567int frame_size = caller.sp() - fr.sp();15681569frame sender = caller;15701571// Since the Java thread being deoptimized will eventually adjust it's own stack,1572// the vframeArray containing the unpacking information is allocated in the C heap.1573// For Compiler1, the caller of the deoptimized frame is saved for use by unpack_frames().1574vframeArray* array = vframeArray::allocate(thread, frame_size, chunk, reg_map, sender, caller, fr, realloc_failures);15751576// Compare the vframeArray to the collected vframes1577assert(array->structural_compare(thread, chunk), "just checking");15781579#ifndef PRODUCT1580if (PrintDeoptimizationDetails) {1581ttyLocker ttyl;1582tty->print_cr(" Created vframeArray " INTPTR_FORMAT, p2i(array));1583}1584#endif // PRODUCT15851586return array;1587}15881589#if COMPILER2_OR_JVMCI1590void Deoptimization::pop_frames_failed_reallocs(JavaThread* thread, vframeArray* array) {1591// Reallocation of some scalar replaced objects failed. Record1592// that we need to pop all the interpreter frames for the1593// deoptimized compiled frame.1594assert(thread->frames_to_pop_failed_realloc() == 0, "missed frames to pop?");1595thread->set_frames_to_pop_failed_realloc(array->frames());1596// Unlock all monitors here otherwise the interpreter will see a1597// mix of locked and unlocked monitors (because of failed1598// reallocations of synchronized objects) and be confused.1599for (int i = 0; i < array->frames(); i++) {1600MonitorChunk* monitors = array->element(i)->monitors();1601if (monitors != NULL) {1602for (int j = 0; j < monitors->number_of_monitors(); j++) {1603BasicObjectLock* src = monitors->at(j);1604if (src->obj() != NULL) {1605ObjectSynchronizer::exit(src->obj(), src->lock(), thread);1606}1607}1608array->element(i)->free_monitors(thread);1609#ifdef ASSERT1610array->element(i)->set_removed_monitors();1611#endif1612}1613}1614}1615#endif16161617static void collect_monitors(compiledVFrame* cvf, GrowableArray<Handle>* objects_to_revoke,1618bool only_eliminated) {1619GrowableArray<MonitorInfo*>* monitors = cvf->monitors();1620Thread* thread = Thread::current();1621for (int i = 0; i < monitors->length(); i++) {1622MonitorInfo* mon_info = monitors->at(i);1623if (mon_info->eliminated() == only_eliminated &&1624!mon_info->owner_is_scalar_replaced() &&1625mon_info->owner() != NULL) {1626objects_to_revoke->append(Handle(thread, mon_info->owner()));1627}1628}1629}16301631static void get_monitors_from_stack(GrowableArray<Handle>* objects_to_revoke, JavaThread* thread,1632frame fr, RegisterMap* map, bool only_eliminated) {1633// Unfortunately we don't have a RegisterMap available in most of1634// the places we want to call this routine so we need to walk the1635// stack again to update the register map.1636if (map == NULL || !map->update_map()) {1637StackFrameStream sfs(thread, true /* update */, true /* process_frames */);1638bool found = false;1639while (!found && !sfs.is_done()) {1640frame* cur = sfs.current();1641sfs.next();1642found = cur->id() == fr.id();1643}1644assert(found, "frame to be deoptimized not found on target thread's stack");1645map = sfs.register_map();1646}16471648vframe* vf = vframe::new_vframe(&fr, map, thread);1649compiledVFrame* cvf = compiledVFrame::cast(vf);1650// Revoke monitors' biases in all scopes1651while (!cvf->is_top()) {1652collect_monitors(cvf, objects_to_revoke, only_eliminated);1653cvf = compiledVFrame::cast(cvf->sender());1654}1655collect_monitors(cvf, objects_to_revoke, only_eliminated);1656}16571658void Deoptimization::revoke_from_deopt_handler(JavaThread* thread, frame fr, RegisterMap* map) {1659if (!UseBiasedLocking) {1660return;1661}1662assert(thread == Thread::current(), "should be");1663ResourceMark rm(thread);1664HandleMark hm(thread);1665GrowableArray<Handle>* objects_to_revoke = new GrowableArray<Handle>();1666get_monitors_from_stack(objects_to_revoke, thread, fr, map, false);16671668int len = objects_to_revoke->length();1669for (int i = 0; i < len; i++) {1670oop obj = (objects_to_revoke->at(i))();1671BiasedLocking::revoke_own_lock(thread, objects_to_revoke->at(i));1672assert(!obj->mark().has_bias_pattern(), "biases should be revoked by now");1673}1674}16751676// Revoke the bias of objects with eliminated locking to prepare subsequent relocking.1677void Deoptimization::revoke_for_object_deoptimization(JavaThread* deoptee_thread, frame fr,1678RegisterMap* map, JavaThread* thread) {1679if (!UseBiasedLocking) {1680return;1681}1682GrowableArray<Handle>* objects_to_revoke = new GrowableArray<Handle>();1683assert(KeepStackGCProcessedMark::stack_is_kept_gc_processed(deoptee_thread), "must be");1684// Collect monitors but only those with eliminated locking.1685get_monitors_from_stack(objects_to_revoke, deoptee_thread, fr, map, true);16861687int len = objects_to_revoke->length();1688for (int i = 0; i < len; i++) {1689oop obj = (objects_to_revoke->at(i))();1690markWord mark = obj->mark();1691if (!mark.has_bias_pattern() ||1692mark.is_biased_anonymously() || // eliminated locking does not bias an object if it wasn't before1693!obj->klass()->prototype_header().has_bias_pattern() || // bulk revoke ignores eliminated monitors1694(obj->klass()->prototype_header().bias_epoch() != mark.bias_epoch())) { // bulk rebias ignores eliminated monitors1695// We reach here regularly if there's just eliminated locking on obj.1696// We must not call BiasedLocking::revoke_own_lock() in this case, as we1697// would hit assertions because it is a prerequisite that there has to be1698// non-eliminated locking on obj by deoptee_thread.1699// Luckily we don't have to revoke here because obj has to be a1700// non-escaping obj and can be relocked without revoking the bias. See1701// Deoptimization::relock_objects().1702continue;1703}1704BiasedLocking::revoke(thread, objects_to_revoke->at(i));1705assert(!objects_to_revoke->at(i)->mark().has_bias_pattern(), "biases should be revoked by now");1706}1707}17081709void Deoptimization::deoptimize_single_frame(JavaThread* thread, frame fr, Deoptimization::DeoptReason reason) {1710assert(fr.can_be_deoptimized(), "checking frame type");17111712gather_statistics(reason, Action_none, Bytecodes::_illegal);17131714if (LogCompilation && xtty != NULL) {1715CompiledMethod* cm = fr.cb()->as_compiled_method_or_null();1716assert(cm != NULL, "only compiled methods can deopt");17171718ttyLocker ttyl;1719xtty->begin_head("deoptimized thread='" UINTX_FORMAT "' reason='%s' pc='" INTPTR_FORMAT "'",(uintx)thread->osthread()->thread_id(), trap_reason_name(reason), p2i(fr.pc()));1720cm->log_identity(xtty);1721xtty->end_head();1722for (ScopeDesc* sd = cm->scope_desc_at(fr.pc()); ; sd = sd->sender()) {1723xtty->begin_elem("jvms bci='%d'", sd->bci());1724xtty->method(sd->method());1725xtty->end_elem();1726if (sd->is_top()) break;1727}1728xtty->tail("deoptimized");1729}17301731// Patch the compiled method so that when execution returns to it we will1732// deopt the execution state and return to the interpreter.1733fr.deoptimize(thread);1734}17351736void Deoptimization::deoptimize(JavaThread* thread, frame fr, DeoptReason reason) {1737// Deoptimize only if the frame comes from compile code.1738// Do not deoptimize the frame which is already patched1739// during the execution of the loops below.1740if (!fr.is_compiled_frame() || fr.is_deoptimized_frame()) {1741return;1742}1743ResourceMark rm;1744DeoptimizationMarker dm;1745deoptimize_single_frame(thread, fr, reason);1746}17471748#if INCLUDE_JVMCI1749address Deoptimization::deoptimize_for_missing_exception_handler(CompiledMethod* cm) {1750// there is no exception handler for this pc => deoptimize1751cm->make_not_entrant();17521753// Use Deoptimization::deoptimize for all of its side-effects:1754// gathering traps statistics, logging...1755// it also patches the return pc but we do not care about that1756// since we return a continuation to the deopt_blob below.1757JavaThread* thread = JavaThread::current();1758RegisterMap reg_map(thread, false);1759frame runtime_frame = thread->last_frame();1760frame caller_frame = runtime_frame.sender(®_map);1761assert(caller_frame.cb()->as_compiled_method_or_null() == cm, "expect top frame compiled method");1762vframe* vf = vframe::new_vframe(&caller_frame, ®_map, thread);1763compiledVFrame* cvf = compiledVFrame::cast(vf);1764ScopeDesc* imm_scope = cvf->scope();1765MethodData* imm_mdo = get_method_data(thread, methodHandle(thread, imm_scope->method()), true);1766if (imm_mdo != NULL) {1767ProfileData* pdata = imm_mdo->allocate_bci_to_data(imm_scope->bci(), NULL);1768if (pdata != NULL && pdata->is_BitData()) {1769BitData* bit_data = (BitData*) pdata;1770bit_data->set_exception_seen();1771}1772}17731774Deoptimization::deoptimize(thread, caller_frame, Deoptimization::Reason_not_compiled_exception_handler);17751776MethodData* trap_mdo = get_method_data(thread, methodHandle(thread, cm->method()), true);1777if (trap_mdo != NULL) {1778trap_mdo->inc_trap_count(Deoptimization::Reason_not_compiled_exception_handler);1779}17801781return SharedRuntime::deopt_blob()->unpack_with_exception_in_tls();1782}1783#endif17841785void Deoptimization::deoptimize_frame_internal(JavaThread* thread, intptr_t* id, DeoptReason reason) {1786assert(thread == Thread::current() ||1787thread->is_handshake_safe_for(Thread::current()) ||1788SafepointSynchronize::is_at_safepoint(),1789"can only deoptimize other thread at a safepoint/handshake");1790// Compute frame and register map based on thread and sp.1791RegisterMap reg_map(thread, false);1792frame fr = thread->last_frame();1793while (fr.id() != id) {1794fr = fr.sender(®_map);1795}1796deoptimize(thread, fr, reason);1797}179817991800void Deoptimization::deoptimize_frame(JavaThread* thread, intptr_t* id, DeoptReason reason) {1801Thread* current = Thread::current();1802if (thread == current || thread->is_handshake_safe_for(current)) {1803Deoptimization::deoptimize_frame_internal(thread, id, reason);1804} else {1805VM_DeoptimizeFrame deopt(thread, id, reason);1806VMThread::execute(&deopt);1807}1808}18091810void Deoptimization::deoptimize_frame(JavaThread* thread, intptr_t* id) {1811deoptimize_frame(thread, id, Reason_constraint);1812}18131814// JVMTI PopFrame support1815JRT_LEAF(void, Deoptimization::popframe_preserve_args(JavaThread* thread, int bytes_to_save, void* start_address))1816{1817thread->popframe_preserve_args(in_ByteSize(bytes_to_save), start_address);1818}1819JRT_END18201821MethodData*1822Deoptimization::get_method_data(JavaThread* thread, const methodHandle& m,1823bool create_if_missing) {1824JavaThread* THREAD = thread; // For exception macros.1825MethodData* mdo = m()->method_data();1826if (mdo == NULL && create_if_missing && !HAS_PENDING_EXCEPTION) {1827// Build an MDO. Ignore errors like OutOfMemory;1828// that simply means we won't have an MDO to update.1829Method::build_interpreter_method_data(m, THREAD);1830if (HAS_PENDING_EXCEPTION) {1831// Only metaspace OOM is expected. No Java code executed.1832assert((PENDING_EXCEPTION->is_a(vmClasses::OutOfMemoryError_klass())), "we expect only an OOM error here");1833CLEAR_PENDING_EXCEPTION;1834}1835mdo = m()->method_data();1836}1837return mdo;1838}18391840#if COMPILER2_OR_JVMCI1841void Deoptimization::load_class_by_index(const constantPoolHandle& constant_pool, int index, TRAPS) {1842// In case of an unresolved klass entry, load the class.1843// This path is exercised from case _ldc in Parse::do_one_bytecode,1844// and probably nowhere else.1845// Even that case would benefit from simply re-interpreting the1846// bytecode, without paying special attention to the class index.1847// So this whole "class index" feature should probably be removed.18481849if (constant_pool->tag_at(index).is_unresolved_klass()) {1850Klass* tk = constant_pool->klass_at(index, THREAD);1851if (HAS_PENDING_EXCEPTION) {1852// Exception happened during classloading. We ignore the exception here, since it1853// is going to be rethrown since the current activation is going to be deoptimized and1854// the interpreter will re-execute the bytecode.1855// Do not clear probable Async Exceptions.1856CLEAR_PENDING_NONASYNC_EXCEPTION;1857// Class loading called java code which may have caused a stack1858// overflow. If the exception was thrown right before the return1859// to the runtime the stack is no longer guarded. Reguard the1860// stack otherwise if we return to the uncommon trap blob and the1861// stack bang causes a stack overflow we crash.1862JavaThread* jt = THREAD;1863bool guard_pages_enabled = jt->stack_overflow_state()->reguard_stack_if_needed();1864assert(guard_pages_enabled, "stack banging in uncommon trap blob may cause crash");1865}1866return;1867}18681869assert(!constant_pool->tag_at(index).is_symbol(),1870"no symbolic names here, please");1871}18721873#if INCLUDE_JFR18741875class DeoptReasonSerializer : public JfrSerializer {1876public:1877void serialize(JfrCheckpointWriter& writer) {1878writer.write_count((u4)(Deoptimization::Reason_LIMIT + 1)); // + Reason::many (-1)1879for (int i = -1; i < Deoptimization::Reason_LIMIT; ++i) {1880writer.write_key((u8)i);1881writer.write(Deoptimization::trap_reason_name(i));1882}1883}1884};18851886class DeoptActionSerializer : public JfrSerializer {1887public:1888void serialize(JfrCheckpointWriter& writer) {1889static const u4 nof_actions = Deoptimization::Action_LIMIT;1890writer.write_count(nof_actions);1891for (u4 i = 0; i < Deoptimization::Action_LIMIT; ++i) {1892writer.write_key(i);1893writer.write(Deoptimization::trap_action_name((int)i));1894}1895}1896};18971898static void register_serializers() {1899static int critical_section = 0;1900if (1 == critical_section || Atomic::cmpxchg(&critical_section, 0, 1) == 1) {1901return;1902}1903JfrSerializer::register_serializer(TYPE_DEOPTIMIZATIONREASON, true, new DeoptReasonSerializer());1904JfrSerializer::register_serializer(TYPE_DEOPTIMIZATIONACTION, true, new DeoptActionSerializer());1905}19061907static void post_deoptimization_event(CompiledMethod* nm,1908const Method* method,1909int trap_bci,1910int instruction,1911Deoptimization::DeoptReason reason,1912Deoptimization::DeoptAction action) {1913assert(nm != NULL, "invariant");1914assert(method != NULL, "invariant");1915if (EventDeoptimization::is_enabled()) {1916static bool serializers_registered = false;1917if (!serializers_registered) {1918register_serializers();1919serializers_registered = true;1920}1921EventDeoptimization event;1922event.set_compileId(nm->compile_id());1923event.set_compiler(nm->compiler_type());1924event.set_method(method);1925event.set_lineNumber(method->line_number_from_bci(trap_bci));1926event.set_bci(trap_bci);1927event.set_instruction(instruction);1928event.set_reason(reason);1929event.set_action(action);1930event.commit();1931}1932}19331934#endif // INCLUDE_JFR19351936JRT_ENTRY(void, Deoptimization::uncommon_trap_inner(JavaThread* current, jint trap_request)) {1937HandleMark hm(current);19381939// uncommon_trap() is called at the beginning of the uncommon trap1940// handler. Note this fact before we start generating temporary frames1941// that can confuse an asynchronous stack walker. This counter is1942// decremented at the end of unpack_frames().1943current->inc_in_deopt_handler();19441945// We need to update the map if we have biased locking.1946#if INCLUDE_JVMCI1947// JVMCI might need to get an exception from the stack, which in turn requires the register map to be valid1948RegisterMap reg_map(current, true);1949#else1950RegisterMap reg_map(current, UseBiasedLocking);1951#endif1952frame stub_frame = current->last_frame();1953frame fr = stub_frame.sender(®_map);1954// Make sure the calling nmethod is not getting deoptimized and removed1955// before we are done with it.1956nmethodLocker nl(fr.pc());19571958// Log a message1959Events::log_deopt_message(current, "Uncommon trap: trap_request=" PTR32_FORMAT " fr.pc=" INTPTR_FORMAT " relative=" INTPTR_FORMAT,1960trap_request, p2i(fr.pc()), fr.pc() - fr.cb()->code_begin());19611962{1963ResourceMark rm;19641965DeoptReason reason = trap_request_reason(trap_request);1966DeoptAction action = trap_request_action(trap_request);1967#if INCLUDE_JVMCI1968int debug_id = trap_request_debug_id(trap_request);1969#endif1970jint unloaded_class_index = trap_request_index(trap_request); // CP idx or -119711972vframe* vf = vframe::new_vframe(&fr, ®_map, current);1973compiledVFrame* cvf = compiledVFrame::cast(vf);19741975CompiledMethod* nm = cvf->code();19761977ScopeDesc* trap_scope = cvf->scope();19781979bool is_receiver_constraint_failure = COMPILER2_PRESENT(VerifyReceiverTypes &&) (reason == Deoptimization::Reason_receiver_constraint);19801981if (TraceDeoptimization || is_receiver_constraint_failure) {1982ttyLocker ttyl;1983tty->print_cr(" bci=%d pc=" INTPTR_FORMAT ", relative_pc=" INTPTR_FORMAT ", method=%s" JVMCI_ONLY(", debug_id=%d"), trap_scope->bci(), p2i(fr.pc()), fr.pc() - nm->code_begin(), trap_scope->method()->name_and_sig_as_C_string()1984#if INCLUDE_JVMCI1985, debug_id1986#endif1987);1988}19891990methodHandle trap_method(current, trap_scope->method());1991int trap_bci = trap_scope->bci();1992#if INCLUDE_JVMCI1993jlong speculation = current->pending_failed_speculation();1994if (nm->is_compiled_by_jvmci()) {1995nm->as_nmethod()->update_speculation(current);1996} else {1997assert(speculation == 0, "There should not be a speculation for methods compiled by non-JVMCI compilers");1998}19992000if (trap_bci == SynchronizationEntryBCI) {2001trap_bci = 0;2002current->set_pending_monitorenter(true);2003}20042005if (reason == Deoptimization::Reason_transfer_to_interpreter) {2006current->set_pending_transfer_to_interpreter(true);2007}2008#endif20092010Bytecodes::Code trap_bc = trap_method->java_code_at(trap_bci);2011// Record this event in the histogram.2012gather_statistics(reason, action, trap_bc);20132014// Ensure that we can record deopt. history:2015// Need MDO to record RTM code generation state.2016bool create_if_missing = ProfileTraps || UseCodeAging RTM_OPT_ONLY( || UseRTMLocking );20172018methodHandle profiled_method;2019#if INCLUDE_JVMCI2020if (nm->is_compiled_by_jvmci()) {2021profiled_method = methodHandle(current, nm->method());2022} else {2023profiled_method = trap_method;2024}2025#else2026profiled_method = trap_method;2027#endif20282029MethodData* trap_mdo =2030get_method_data(current, profiled_method, create_if_missing);20312032JFR_ONLY(post_deoptimization_event(nm, trap_method(), trap_bci, trap_bc, reason, action);)20332034// Log a message2035Events::log_deopt_message(current, "Uncommon trap: reason=%s action=%s pc=" INTPTR_FORMAT " method=%s @ %d %s",2036trap_reason_name(reason), trap_action_name(action), p2i(fr.pc()),2037trap_method->name_and_sig_as_C_string(), trap_bci, nm->compiler_name());20382039// Print a bunch of diagnostics, if requested.2040if (TraceDeoptimization || LogCompilation || is_receiver_constraint_failure) {2041ResourceMark rm;2042ttyLocker ttyl;2043char buf[100];2044if (xtty != NULL) {2045xtty->begin_head("uncommon_trap thread='" UINTX_FORMAT "' %s",2046os::current_thread_id(),2047format_trap_request(buf, sizeof(buf), trap_request));2048#if INCLUDE_JVMCI2049if (speculation != 0) {2050xtty->print(" speculation='" JLONG_FORMAT "'", speculation);2051}2052#endif2053nm->log_identity(xtty);2054}2055Symbol* class_name = NULL;2056bool unresolved = false;2057if (unloaded_class_index >= 0) {2058constantPoolHandle constants (current, trap_method->constants());2059if (constants->tag_at(unloaded_class_index).is_unresolved_klass()) {2060class_name = constants->klass_name_at(unloaded_class_index);2061unresolved = true;2062if (xtty != NULL)2063xtty->print(" unresolved='1'");2064} else if (constants->tag_at(unloaded_class_index).is_symbol()) {2065class_name = constants->symbol_at(unloaded_class_index);2066}2067if (xtty != NULL)2068xtty->name(class_name);2069}2070if (xtty != NULL && trap_mdo != NULL && (int)reason < (int)MethodData::_trap_hist_limit) {2071// Dump the relevant MDO state.2072// This is the deopt count for the current reason, any previous2073// reasons or recompiles seen at this point.2074int dcnt = trap_mdo->trap_count(reason);2075if (dcnt != 0)2076xtty->print(" count='%d'", dcnt);2077ProfileData* pdata = trap_mdo->bci_to_data(trap_bci);2078int dos = (pdata == NULL)? 0: pdata->trap_state();2079if (dos != 0) {2080xtty->print(" state='%s'", format_trap_state(buf, sizeof(buf), dos));2081if (trap_state_is_recompiled(dos)) {2082int recnt2 = trap_mdo->overflow_recompile_count();2083if (recnt2 != 0)2084xtty->print(" recompiles2='%d'", recnt2);2085}2086}2087}2088if (xtty != NULL) {2089xtty->stamp();2090xtty->end_head();2091}2092if (TraceDeoptimization) { // make noise on the tty2093tty->print("Uncommon trap occurred in");2094nm->method()->print_short_name(tty);2095tty->print(" compiler=%s compile_id=%d", nm->compiler_name(), nm->compile_id());2096#if INCLUDE_JVMCI2097if (nm->is_nmethod()) {2098const char* installed_code_name = nm->as_nmethod()->jvmci_name();2099if (installed_code_name != NULL) {2100tty->print(" (JVMCI: installed code name=%s) ", installed_code_name);2101}2102}2103#endif2104tty->print(" (@" INTPTR_FORMAT ") thread=" UINTX_FORMAT " reason=%s action=%s unloaded_class_index=%d" JVMCI_ONLY(" debug_id=%d"),2105p2i(fr.pc()),2106os::current_thread_id(),2107trap_reason_name(reason),2108trap_action_name(action),2109unloaded_class_index2110#if INCLUDE_JVMCI2111, debug_id2112#endif2113);2114if (class_name != NULL) {2115tty->print(unresolved ? " unresolved class: " : " symbol: ");2116class_name->print_symbol_on(tty);2117}2118tty->cr();2119}2120if (xtty != NULL) {2121// Log the precise location of the trap.2122for (ScopeDesc* sd = trap_scope; ; sd = sd->sender()) {2123xtty->begin_elem("jvms bci='%d'", sd->bci());2124xtty->method(sd->method());2125xtty->end_elem();2126if (sd->is_top()) break;2127}2128xtty->tail("uncommon_trap");2129}2130}2131// (End diagnostic printout.)21322133if (is_receiver_constraint_failure) {2134fatal("missing receiver type check");2135}21362137// Load class if necessary2138if (unloaded_class_index >= 0) {2139constantPoolHandle constants(current, trap_method->constants());2140load_class_by_index(constants, unloaded_class_index, THREAD);2141}21422143// Flush the nmethod if necessary and desirable.2144//2145// We need to avoid situations where we are re-flushing the nmethod2146// because of a hot deoptimization site. Repeated flushes at the same2147// point need to be detected by the compiler and avoided. If the compiler2148// cannot avoid them (or has a bug and "refuses" to avoid them), this2149// module must take measures to avoid an infinite cycle of recompilation2150// and deoptimization. There are several such measures:2151//2152// 1. If a recompilation is ordered a second time at some site X2153// and for the same reason R, the action is adjusted to 'reinterpret',2154// to give the interpreter time to exercise the method more thoroughly.2155// If this happens, the method's overflow_recompile_count is incremented.2156//2157// 2. If the compiler fails to reduce the deoptimization rate, then2158// the method's overflow_recompile_count will begin to exceed the set2159// limit PerBytecodeRecompilationCutoff. If this happens, the action2160// is adjusted to 'make_not_compilable', and the method is abandoned2161// to the interpreter. This is a performance hit for hot methods,2162// but is better than a disastrous infinite cycle of recompilations.2163// (Actually, only the method containing the site X is abandoned.)2164//2165// 3. In parallel with the previous measures, if the total number of2166// recompilations of a method exceeds the much larger set limit2167// PerMethodRecompilationCutoff, the method is abandoned.2168// This should only happen if the method is very large and has2169// many "lukewarm" deoptimizations. The code which enforces this2170// limit is elsewhere (class nmethod, class Method).2171//2172// Note that the per-BCI 'is_recompiled' bit gives the compiler one chance2173// to recompile at each bytecode independently of the per-BCI cutoff.2174//2175// The decision to update code is up to the compiler, and is encoded2176// in the Action_xxx code. If the compiler requests Action_none2177// no trap state is changed, no compiled code is changed, and the2178// computation suffers along in the interpreter.2179//2180// The other action codes specify various tactics for decompilation2181// and recompilation. Action_maybe_recompile is the loosest, and2182// allows the compiled code to stay around until enough traps are seen,2183// and until the compiler gets around to recompiling the trapping method.2184//2185// The other actions cause immediate removal of the present code.21862187// Traps caused by injected profile shouldn't pollute trap counts.2188bool injected_profile_trap = trap_method->has_injected_profile() &&2189(reason == Reason_intrinsic || reason == Reason_unreached);21902191bool update_trap_state = (reason != Reason_tenured) && !injected_profile_trap;2192bool make_not_entrant = false;2193bool make_not_compilable = false;2194bool reprofile = false;2195switch (action) {2196case Action_none:2197// Keep the old code.2198update_trap_state = false;2199break;2200case Action_maybe_recompile:2201// Do not need to invalidate the present code, but we can2202// initiate another2203// Start compiler without (necessarily) invalidating the nmethod.2204// The system will tolerate the old code, but new code should be2205// generated when possible.2206break;2207case Action_reinterpret:2208// Go back into the interpreter for a while, and then consider2209// recompiling form scratch.2210make_not_entrant = true;2211// Reset invocation counter for outer most method.2212// This will allow the interpreter to exercise the bytecodes2213// for a while before recompiling.2214// By contrast, Action_make_not_entrant is immediate.2215//2216// Note that the compiler will track null_check, null_assert,2217// range_check, and class_check events and log them as if they2218// had been traps taken from compiled code. This will update2219// the MDO trap history so that the next compilation will2220// properly detect hot trap sites.2221reprofile = true;2222break;2223case Action_make_not_entrant:2224// Request immediate recompilation, and get rid of the old code.2225// Make them not entrant, so next time they are called they get2226// recompiled. Unloaded classes are loaded now so recompile before next2227// time they are called. Same for uninitialized. The interpreter will2228// link the missing class, if any.2229make_not_entrant = true;2230break;2231case Action_make_not_compilable:2232// Give up on compiling this method at all.2233make_not_entrant = true;2234make_not_compilable = true;2235break;2236default:2237ShouldNotReachHere();2238}22392240// Setting +ProfileTraps fixes the following, on all platforms:2241// 4852688: ProfileInterpreter is off by default for ia64. The result is2242// infinite heroic-opt-uncommon-trap/deopt/recompile cycles, since the2243// recompile relies on a MethodData* to record heroic opt failures.22442245// Whether the interpreter is producing MDO data or not, we also need2246// to use the MDO to detect hot deoptimization points and control2247// aggressive optimization.2248bool inc_recompile_count = false;2249ProfileData* pdata = NULL;2250if (ProfileTraps && CompilerConfig::is_c2_or_jvmci_compiler_enabled() && update_trap_state && trap_mdo != NULL) {2251assert(trap_mdo == get_method_data(current, profiled_method, false), "sanity");2252uint this_trap_count = 0;2253bool maybe_prior_trap = false;2254bool maybe_prior_recompile = false;2255pdata = query_update_method_data(trap_mdo, trap_bci, reason, true,2256#if INCLUDE_JVMCI2257nm->is_compiled_by_jvmci() && nm->is_osr_method(),2258#endif2259nm->method(),2260//outputs:2261this_trap_count,2262maybe_prior_trap,2263maybe_prior_recompile);2264// Because the interpreter also counts null, div0, range, and class2265// checks, these traps from compiled code are double-counted.2266// This is harmless; it just means that the PerXTrapLimit values2267// are in effect a little smaller than they look.22682269DeoptReason per_bc_reason = reason_recorded_per_bytecode_if_any(reason);2270if (per_bc_reason != Reason_none) {2271// Now take action based on the partially known per-BCI history.2272if (maybe_prior_trap2273&& this_trap_count >= (uint)PerBytecodeTrapLimit) {2274// If there are too many traps at this BCI, force a recompile.2275// This will allow the compiler to see the limit overflow, and2276// take corrective action, if possible. The compiler generally2277// does not use the exact PerBytecodeTrapLimit value, but instead2278// changes its tactics if it sees any traps at all. This provides2279// a little hysteresis, delaying a recompile until a trap happens2280// several times.2281//2282// Actually, since there is only one bit of counter per BCI,2283// the possible per-BCI counts are {0,1,(per-method count)}.2284// This produces accurate results if in fact there is only2285// one hot trap site, but begins to get fuzzy if there are2286// many sites. For example, if there are ten sites each2287// trapping two or more times, they each get the blame for2288// all of their traps.2289make_not_entrant = true;2290}22912292// Detect repeated recompilation at the same BCI, and enforce a limit.2293if (make_not_entrant && maybe_prior_recompile) {2294// More than one recompile at this point.2295inc_recompile_count = maybe_prior_trap;2296}2297} else {2298// For reasons which are not recorded per-bytecode, we simply2299// force recompiles unconditionally.2300// (Note that PerMethodRecompilationCutoff is enforced elsewhere.)2301make_not_entrant = true;2302}23032304// Go back to the compiler if there are too many traps in this method.2305if (this_trap_count >= per_method_trap_limit(reason)) {2306// If there are too many traps in this method, force a recompile.2307// This will allow the compiler to see the limit overflow, and2308// take corrective action, if possible.2309// (This condition is an unlikely backstop only, because the2310// PerBytecodeTrapLimit is more likely to take effect first,2311// if it is applicable.)2312make_not_entrant = true;2313}23142315// Here's more hysteresis: If there has been a recompile at2316// this trap point already, run the method in the interpreter2317// for a while to exercise it more thoroughly.2318if (make_not_entrant && maybe_prior_recompile && maybe_prior_trap) {2319reprofile = true;2320}2321}23222323// Take requested actions on the method:23242325// Recompile2326if (make_not_entrant) {2327if (!nm->make_not_entrant()) {2328return; // the call did not change nmethod's state2329}23302331if (pdata != NULL) {2332// Record the recompilation event, if any.2333int tstate0 = pdata->trap_state();2334int tstate1 = trap_state_set_recompiled(tstate0, true);2335if (tstate1 != tstate0)2336pdata->set_trap_state(tstate1);2337}23382339#if INCLUDE_RTM_OPT2340// Restart collecting RTM locking abort statistic if the method2341// is recompiled for a reason other than RTM state change.2342// Assume that in new recompiled code the statistic could be different,2343// for example, due to different inlining.2344if ((reason != Reason_rtm_state_change) && (trap_mdo != NULL) &&2345UseRTMDeopt && (nm->as_nmethod()->rtm_state() != ProfileRTM)) {2346trap_mdo->atomic_set_rtm_state(ProfileRTM);2347}2348#endif2349// For code aging we count traps separately here, using make_not_entrant()2350// as a guard against simultaneous deopts in multiple threads.2351if (reason == Reason_tenured && trap_mdo != NULL) {2352trap_mdo->inc_tenure_traps();2353}2354}23552356if (inc_recompile_count) {2357trap_mdo->inc_overflow_recompile_count();2358if ((uint)trap_mdo->overflow_recompile_count() >2359(uint)PerBytecodeRecompilationCutoff) {2360// Give up on the method containing the bad BCI.2361if (trap_method() == nm->method()) {2362make_not_compilable = true;2363} else {2364trap_method->set_not_compilable("overflow_recompile_count > PerBytecodeRecompilationCutoff", CompLevel_full_optimization);2365// But give grace to the enclosing nm->method().2366}2367}2368}23692370// Reprofile2371if (reprofile) {2372CompilationPolicy::reprofile(trap_scope, nm->is_osr_method());2373}23742375// Give up compiling2376if (make_not_compilable && !nm->method()->is_not_compilable(CompLevel_full_optimization)) {2377assert(make_not_entrant, "consistent");2378nm->method()->set_not_compilable("give up compiling", CompLevel_full_optimization);2379}23802381} // Free marked resources23822383}2384JRT_END23852386ProfileData*2387Deoptimization::query_update_method_data(MethodData* trap_mdo,2388int trap_bci,2389Deoptimization::DeoptReason reason,2390bool update_total_trap_count,2391#if INCLUDE_JVMCI2392bool is_osr,2393#endif2394Method* compiled_method,2395//outputs:2396uint& ret_this_trap_count,2397bool& ret_maybe_prior_trap,2398bool& ret_maybe_prior_recompile) {2399bool maybe_prior_trap = false;2400bool maybe_prior_recompile = false;2401uint this_trap_count = 0;2402if (update_total_trap_count) {2403uint idx = reason;2404#if INCLUDE_JVMCI2405if (is_osr) {2406// Upper half of history array used for traps in OSR compilations2407idx += Reason_TRAP_HISTORY_LENGTH;2408}2409#endif2410uint prior_trap_count = trap_mdo->trap_count(idx);2411this_trap_count = trap_mdo->inc_trap_count(idx);24122413// If the runtime cannot find a place to store trap history,2414// it is estimated based on the general condition of the method.2415// If the method has ever been recompiled, or has ever incurred2416// a trap with the present reason , then this BCI is assumed2417// (pessimistically) to be the culprit.2418maybe_prior_trap = (prior_trap_count != 0);2419maybe_prior_recompile = (trap_mdo->decompile_count() != 0);2420}2421ProfileData* pdata = NULL;242224232424// For reasons which are recorded per bytecode, we check per-BCI data.2425DeoptReason per_bc_reason = reason_recorded_per_bytecode_if_any(reason);2426assert(per_bc_reason != Reason_none || update_total_trap_count, "must be");2427if (per_bc_reason != Reason_none) {2428// Find the profile data for this BCI. If there isn't one,2429// try to allocate one from the MDO's set of spares.2430// This will let us detect a repeated trap at this point.2431pdata = trap_mdo->allocate_bci_to_data(trap_bci, reason_is_speculate(reason) ? compiled_method : NULL);24322433if (pdata != NULL) {2434if (reason_is_speculate(reason) && !pdata->is_SpeculativeTrapData()) {2435if (LogCompilation && xtty != NULL) {2436ttyLocker ttyl;2437// no more room for speculative traps in this MDO2438xtty->elem("speculative_traps_oom");2439}2440}2441// Query the trap state of this profile datum.2442int tstate0 = pdata->trap_state();2443if (!trap_state_has_reason(tstate0, per_bc_reason))2444maybe_prior_trap = false;2445if (!trap_state_is_recompiled(tstate0))2446maybe_prior_recompile = false;24472448// Update the trap state of this profile datum.2449int tstate1 = tstate0;2450// Record the reason.2451tstate1 = trap_state_add_reason(tstate1, per_bc_reason);2452// Store the updated state on the MDO, for next time.2453if (tstate1 != tstate0)2454pdata->set_trap_state(tstate1);2455} else {2456if (LogCompilation && xtty != NULL) {2457ttyLocker ttyl;2458// Missing MDP? Leave a small complaint in the log.2459xtty->elem("missing_mdp bci='%d'", trap_bci);2460}2461}2462}24632464// Return results:2465ret_this_trap_count = this_trap_count;2466ret_maybe_prior_trap = maybe_prior_trap;2467ret_maybe_prior_recompile = maybe_prior_recompile;2468return pdata;2469}24702471void2472Deoptimization::update_method_data_from_interpreter(MethodData* trap_mdo, int trap_bci, int reason) {2473ResourceMark rm;2474// Ignored outputs:2475uint ignore_this_trap_count;2476bool ignore_maybe_prior_trap;2477bool ignore_maybe_prior_recompile;2478assert(!reason_is_speculate(reason), "reason speculate only used by compiler");2479// JVMCI uses the total counts to determine if deoptimizations are happening too frequently -> do not adjust total counts2480bool update_total_counts = true JVMCI_ONLY( && !UseJVMCICompiler);2481query_update_method_data(trap_mdo, trap_bci,2482(DeoptReason)reason,2483update_total_counts,2484#if INCLUDE_JVMCI2485false,2486#endif2487NULL,2488ignore_this_trap_count,2489ignore_maybe_prior_trap,2490ignore_maybe_prior_recompile);2491}24922493Deoptimization::UnrollBlock* Deoptimization::uncommon_trap(JavaThread* current, jint trap_request, jint exec_mode) {2494// Enable WXWrite: current function is called from methods compiled by C2 directly2495MACOS_AARCH64_ONLY(ThreadWXEnable wx(WXWrite, current));24962497if (TraceDeoptimization) {2498tty->print("Uncommon trap ");2499}2500// Still in Java no safepoints2501{2502// This enters VM and may safepoint2503uncommon_trap_inner(current, trap_request);2504}2505HandleMark hm(current);2506return fetch_unroll_info_helper(current, exec_mode);2507}25082509// Local derived constants.2510// Further breakdown of DataLayout::trap_state, as promised by DataLayout.2511const int DS_REASON_MASK = ((uint)DataLayout::trap_mask) >> 1;2512const int DS_RECOMPILE_BIT = DataLayout::trap_mask - DS_REASON_MASK;25132514//---------------------------trap_state_reason---------------------------------2515Deoptimization::DeoptReason2516Deoptimization::trap_state_reason(int trap_state) {2517// This assert provides the link between the width of DataLayout::trap_bits2518// and the encoding of "recorded" reasons. It ensures there are enough2519// bits to store all needed reasons in the per-BCI MDO profile.2520assert(DS_REASON_MASK >= Reason_RECORDED_LIMIT, "enough bits");2521int recompile_bit = (trap_state & DS_RECOMPILE_BIT);2522trap_state -= recompile_bit;2523if (trap_state == DS_REASON_MASK) {2524return Reason_many;2525} else {2526assert((int)Reason_none == 0, "state=0 => Reason_none");2527return (DeoptReason)trap_state;2528}2529}2530//-------------------------trap_state_has_reason-------------------------------2531int Deoptimization::trap_state_has_reason(int trap_state, int reason) {2532assert(reason_is_recorded_per_bytecode((DeoptReason)reason), "valid reason");2533assert(DS_REASON_MASK >= Reason_RECORDED_LIMIT, "enough bits");2534int recompile_bit = (trap_state & DS_RECOMPILE_BIT);2535trap_state -= recompile_bit;2536if (trap_state == DS_REASON_MASK) {2537return -1; // true, unspecifically (bottom of state lattice)2538} else if (trap_state == reason) {2539return 1; // true, definitely2540} else if (trap_state == 0) {2541return 0; // false, definitely (top of state lattice)2542} else {2543return 0; // false, definitely2544}2545}2546//-------------------------trap_state_add_reason-------------------------------2547int Deoptimization::trap_state_add_reason(int trap_state, int reason) {2548assert(reason_is_recorded_per_bytecode((DeoptReason)reason) || reason == Reason_many, "valid reason");2549int recompile_bit = (trap_state & DS_RECOMPILE_BIT);2550trap_state -= recompile_bit;2551if (trap_state == DS_REASON_MASK) {2552return trap_state + recompile_bit; // already at state lattice bottom2553} else if (trap_state == reason) {2554return trap_state + recompile_bit; // the condition is already true2555} else if (trap_state == 0) {2556return reason + recompile_bit; // no condition has yet been true2557} else {2558return DS_REASON_MASK + recompile_bit; // fall to state lattice bottom2559}2560}2561//-----------------------trap_state_is_recompiled------------------------------2562bool Deoptimization::trap_state_is_recompiled(int trap_state) {2563return (trap_state & DS_RECOMPILE_BIT) != 0;2564}2565//-----------------------trap_state_set_recompiled-----------------------------2566int Deoptimization::trap_state_set_recompiled(int trap_state, bool z) {2567if (z) return trap_state | DS_RECOMPILE_BIT;2568else return trap_state & ~DS_RECOMPILE_BIT;2569}2570//---------------------------format_trap_state---------------------------------2571// This is used for debugging and diagnostics, including LogFile output.2572const char* Deoptimization::format_trap_state(char* buf, size_t buflen,2573int trap_state) {2574assert(buflen > 0, "sanity");2575DeoptReason reason = trap_state_reason(trap_state);2576bool recomp_flag = trap_state_is_recompiled(trap_state);2577// Re-encode the state from its decoded components.2578int decoded_state = 0;2579if (reason_is_recorded_per_bytecode(reason) || reason == Reason_many)2580decoded_state = trap_state_add_reason(decoded_state, reason);2581if (recomp_flag)2582decoded_state = trap_state_set_recompiled(decoded_state, recomp_flag);2583// If the state re-encodes properly, format it symbolically.2584// Because this routine is used for debugging and diagnostics,2585// be robust even if the state is a strange value.2586size_t len;2587if (decoded_state != trap_state) {2588// Random buggy state that doesn't decode??2589len = jio_snprintf(buf, buflen, "#%d", trap_state);2590} else {2591len = jio_snprintf(buf, buflen, "%s%s",2592trap_reason_name(reason),2593recomp_flag ? " recompiled" : "");2594}2595return buf;2596}259725982599//--------------------------------statics--------------------------------------2600const char* Deoptimization::_trap_reason_name[] = {2601// Note: Keep this in sync. with enum DeoptReason.2602"none",2603"null_check",2604"null_assert" JVMCI_ONLY("_or_unreached0"),2605"range_check",2606"class_check",2607"array_check",2608"intrinsic" JVMCI_ONLY("_or_type_checked_inlining"),2609"bimorphic" JVMCI_ONLY("_or_optimized_type_check"),2610"profile_predicate",2611"unloaded",2612"uninitialized",2613"initialized",2614"unreached",2615"unhandled",2616"constraint",2617"div0_check",2618"age",2619"predicate",2620"loop_limit_check",2621"speculate_class_check",2622"speculate_null_check",2623"speculate_null_assert",2624"rtm_state_change",2625"unstable_if",2626"unstable_fused_if",2627"receiver_constraint",2628#if INCLUDE_JVMCI2629"aliasing",2630"transfer_to_interpreter",2631"not_compiled_exception_handler",2632"unresolved",2633"jsr_mismatch",2634#endif2635"tenured"2636};2637const char* Deoptimization::_trap_action_name[] = {2638// Note: Keep this in sync. with enum DeoptAction.2639"none",2640"maybe_recompile",2641"reinterpret",2642"make_not_entrant",2643"make_not_compilable"2644};26452646const char* Deoptimization::trap_reason_name(int reason) {2647// Check that every reason has a name2648STATIC_ASSERT(sizeof(_trap_reason_name)/sizeof(const char*) == Reason_LIMIT);26492650if (reason == Reason_many) return "many";2651if ((uint)reason < Reason_LIMIT)2652return _trap_reason_name[reason];2653static char buf[20];2654sprintf(buf, "reason%d", reason);2655return buf;2656}2657const char* Deoptimization::trap_action_name(int action) {2658// Check that every action has a name2659STATIC_ASSERT(sizeof(_trap_action_name)/sizeof(const char*) == Action_LIMIT);26602661if ((uint)action < Action_LIMIT)2662return _trap_action_name[action];2663static char buf[20];2664sprintf(buf, "action%d", action);2665return buf;2666}26672668// This is used for debugging and diagnostics, including LogFile output.2669const char* Deoptimization::format_trap_request(char* buf, size_t buflen,2670int trap_request) {2671jint unloaded_class_index = trap_request_index(trap_request);2672const char* reason = trap_reason_name(trap_request_reason(trap_request));2673const char* action = trap_action_name(trap_request_action(trap_request));2674#if INCLUDE_JVMCI2675int debug_id = trap_request_debug_id(trap_request);2676#endif2677size_t len;2678if (unloaded_class_index < 0) {2679len = jio_snprintf(buf, buflen, "reason='%s' action='%s'" JVMCI_ONLY(" debug_id='%d'"),2680reason, action2681#if INCLUDE_JVMCI2682,debug_id2683#endif2684);2685} else {2686len = jio_snprintf(buf, buflen, "reason='%s' action='%s' index='%d'" JVMCI_ONLY(" debug_id='%d'"),2687reason, action, unloaded_class_index2688#if INCLUDE_JVMCI2689,debug_id2690#endif2691);2692}2693return buf;2694}26952696juint Deoptimization::_deoptimization_hist2697[Deoptimization::Reason_LIMIT]2698[1 + Deoptimization::Action_LIMIT]2699[Deoptimization::BC_CASE_LIMIT]2700= {0};27012702enum {2703LSB_BITS = 8,2704LSB_MASK = right_n_bits(LSB_BITS)2705};27062707void Deoptimization::gather_statistics(DeoptReason reason, DeoptAction action,2708Bytecodes::Code bc) {2709assert(reason >= 0 && reason < Reason_LIMIT, "oob");2710assert(action >= 0 && action < Action_LIMIT, "oob");2711_deoptimization_hist[Reason_none][0][0] += 1; // total2712_deoptimization_hist[reason][0][0] += 1; // per-reason total2713juint* cases = _deoptimization_hist[reason][1+action];2714juint* bc_counter_addr = NULL;2715juint bc_counter = 0;2716// Look for an unused counter, or an exact match to this BC.2717if (bc != Bytecodes::_illegal) {2718for (int bc_case = 0; bc_case < BC_CASE_LIMIT; bc_case++) {2719juint* counter_addr = &cases[bc_case];2720juint counter = *counter_addr;2721if ((counter == 0 && bc_counter_addr == NULL)2722|| (Bytecodes::Code)(counter & LSB_MASK) == bc) {2723// this counter is either free or is already devoted to this BC2724bc_counter_addr = counter_addr;2725bc_counter = counter | bc;2726}2727}2728}2729if (bc_counter_addr == NULL) {2730// Overflow, or no given bytecode.2731bc_counter_addr = &cases[BC_CASE_LIMIT-1];2732bc_counter = (*bc_counter_addr & ~LSB_MASK); // clear LSB2733}2734*bc_counter_addr = bc_counter + (1 << LSB_BITS);2735}27362737jint Deoptimization::total_deoptimization_count() {2738return _deoptimization_hist[Reason_none][0][0];2739}27402741void Deoptimization::print_statistics() {2742juint total = total_deoptimization_count();2743juint account = total;2744if (total != 0) {2745ttyLocker ttyl;2746if (xtty != NULL) xtty->head("statistics type='deoptimization'");2747tty->print_cr("Deoptimization traps recorded:");2748#define PRINT_STAT_LINE(name, r) \2749tty->print_cr(" %4d (%4.1f%%) %s", (int)(r), ((r) * 100.0) / total, name);2750PRINT_STAT_LINE("total", total);2751// For each non-zero entry in the histogram, print the reason,2752// the action, and (if specifically known) the type of bytecode.2753for (int reason = 0; reason < Reason_LIMIT; reason++) {2754for (int action = 0; action < Action_LIMIT; action++) {2755juint* cases = _deoptimization_hist[reason][1+action];2756for (int bc_case = 0; bc_case < BC_CASE_LIMIT; bc_case++) {2757juint counter = cases[bc_case];2758if (counter != 0) {2759char name[1*K];2760Bytecodes::Code bc = (Bytecodes::Code)(counter & LSB_MASK);2761if (bc_case == BC_CASE_LIMIT && (int)bc == 0)2762bc = Bytecodes::_illegal;2763sprintf(name, "%s/%s/%s",2764trap_reason_name(reason),2765trap_action_name(action),2766Bytecodes::is_defined(bc)? Bytecodes::name(bc): "other");2767juint r = counter >> LSB_BITS;2768tty->print_cr(" %40s: " UINT32_FORMAT " (%.1f%%)", name, r, (r * 100.0) / total);2769account -= r;2770}2771}2772}2773}2774if (account != 0) {2775PRINT_STAT_LINE("unaccounted", account);2776}2777#undef PRINT_STAT_LINE2778if (xtty != NULL) xtty->tail("statistics");2779}2780}27812782#else // COMPILER2_OR_JVMCI278327842785// Stubs for C1 only system.2786bool Deoptimization::trap_state_is_recompiled(int trap_state) {2787return false;2788}27892790const char* Deoptimization::trap_reason_name(int reason) {2791return "unknown";2792}27932794void Deoptimization::print_statistics() {2795// no output2796}27972798void2799Deoptimization::update_method_data_from_interpreter(MethodData* trap_mdo, int trap_bci, int reason) {2800// no udpate2801}28022803int Deoptimization::trap_state_has_reason(int trap_state, int reason) {2804return 0;2805}28062807void Deoptimization::gather_statistics(DeoptReason reason, DeoptAction action,2808Bytecodes::Code bc) {2809// no update2810}28112812const char* Deoptimization::format_trap_state(char* buf, size_t buflen,2813int trap_state) {2814jio_snprintf(buf, buflen, "#%d", trap_state);2815return buf;2816}28172818#endif // COMPILER2_OR_JVMCI281928202821